Monday, April 23, 2012

Perl, generating new data (new hash) using two different hash tables

I've bumped into a very complicated problem (in my perspective as a newbie) and I'm not sure how to solve it. I can think of the workflow but not the script.



I have file A that looks like the following: Teacher (tab) Student1(space)Student2(space)..



Fiona       Nicole Sherry 
James Alan Nicole
Michelle Crystal
Racheal Bobby Dan Nicole


They sometimes have numbers right next to their names when there are two of the same name (ex, John1, John2). Students may also overlap if they have more than two advisors..



File B is a file that has groups of teachers together. It looks similar but the values are comma-delimited.



Fiona       Racheal,Jack
Michelle Racheal
Racheal Fiona,Michelle
Jack Fiona


The trend in file B is that a key has multiple values and each value becomes a key as well to easily find who is grouped with who.



The output I would like is which students will be likely to receive similar education based on their teacher/groups.So I would like the script to do the following:




  1. Store file A into a hash and close

  2. Open file B, go through each teacher to see if they have students (some may not, the actual list is quite big..). So if I take the first teacher, Fiona, it will look in stored file A hash table to see if there is a Fiona. If there is, (in this case, Nicole and Sherry), pop them each as new keys to a new hash table.



    while (<Group>) {
    chomp;
    $data=$_;
    $data=~/^(\S+)\s+(.*)$/;
    $TeacherA=$1;
    $group=$2;

  3. Then, look at the group of teachers who are grouped with Fiona (Racheal, Jack). Take 1 person at a time (Racheal)



    if (defined??) {
    while ($list=~/(\w+)(.*)/) {
    $TeacherB=$1;
    $group=$2;

  4. Look at file A for Racheal's students.

  5. Fill them as values (comma-delimited) for student keys made from step 2.

  6. Print student-student and teacher-teacher group.



    Nicole  Bobby,Dan,Nicole    Fiona   Racheal
    Sherry Bobby,Dan,Nicole Fiona Racheal


    Since the next teacher in Fiona's group, Jack, didn't have any students, he would not be in this results. If he had, for example, David, the results would be:



    Nicole  Bobby,Dan,Nicole    Fiona   Racheal
    Sherry Bobby,Dan,Nicole Fiona Racheal
    Nicole David Fiona Jack
    Sherry David Fiona Jack



I'm so sorry for asking such a complicated and specific question. I hope other people who are doing something like this by any chance may benefit from the answers.
Thank you so much for your help and reply. You are my only source of help.





PHP Class Not Loading

I'm using WordPress and I'm trying to write a plugin that uses a file from another plugin. The URL to get the file is correct. I'm able to include the file when I'm calling a static function from the class, it is saying that the class is not loading.



//loading the file
$url=plugins_url().'/nextgen-gallery/admin/functions.php';
include $url;


The filename is functions.php and in it is a class defined nggAdmin



However, when i call the function nggAdmin::create_gallery();, i get the following error:



Fatal error: Class 'nggAdmin' not found in /var/www/html/wordpress/wp-content/plugins/Product/addProductForm.php on line 27




Bind only specific items to gridview from list

I have a list where one item have 4 different elements



Item



Id int
Name String
Value String
Enable bool


I want to Bind the List<item> to a gridview. Currently I am displaying all the items. But I want to display only the Name and Enable fields only.
What is the easy way of doing this? Without creating new list



Thanks





C++0x: Variadic templates

Can I use variadic templates without using the template parameters as function parameters?



When I use them, it compiles:



#include <iostream>
using namespace std;

template<class First>
void print(First first)
{
cout << 1 << endl;
}

template<class First, class ... Rest>
void print(First first, Rest ...rest)
{
cout << 1 << endl;
print<Rest...>(rest...);
}

int main()
{
print<int,int,int>(1,2,3);
}


But when I don't use them, it doesn't compile and complains about an ambiguity:



#include <iostream>
using namespace std;

template<class First>
void print()
{
cout << 1 << endl;
}

template<class First, class ... Rest>
void print()
{
cout << 1 << endl;
print<Rest...>();
}

int main()
{
print<int,int,int>();
}


Unfortunately the classes I want to give as template parameters are not instantiable (they have static functions that are called inside of the template function).
Is there a way to do this?





how to select option to submit different php page

drop down select "sales" go to sales.php, other options selected go to addFund.php...



<form name='searform' method='post' action='<?php echo $home;?>addFund.php'>
Search : <input type='text' id='sear' name='sear'> by
<select id='psel' name='psel' onchange='change()'>
<option value='email'>Email</option>
<option value='name'>Username</option>
<option value='domain'>Domain name</option>
<option value='sales'>Sales</option>
</select>
<input type='submit' name='sub' id='sub' value='Go' onclick='gopage()'>
<input type='submit' name='dir' id='dir' value='Direct'>
</form>


How to submit different pages





Cordova 1.6.1 setInfo error

I recently upgraded to cordova 1.6.1 but i can't get it to deploy on the simulator or the device itself. The debugger shows Error: executing module 'setInfo' are you sure you have loaded iOS version of cordova-1.6.1.js? Though i'm sure i already did. Any help?





Translating oracle right outer join to sql server

I'm fairly new to SQL and I'm trying to translate some oracle commands to sql server. The issue lies with converting the following right outer join:



where
SOURCE_FORMATS.LOC_SIMPLE_ENTITY_ID = FILEFORMAT_INTERNAL_SIGNATURES.LOC_FILEFORMAT_ID (+)


As far as I can understand in SQL this has to be represented in the "from" section to be something like:



from
SIMPLE_ENTITIES "SOURCE_FORMATS" RIGHT OUTER JOIN FILEFORMAT_INTERNAL_SIGNATURES
on SOURCE_FORMATS.LOC_SIMPLE_ENTITY_ID = FILEFORMAT_INTERNAL_SIGNATURES.LOC_FILEFORMAT_ID


Is this logic correct?





Maven assembly: copy from specific sub-folder of dependency

I'm using Maven assembly plugin to build a WAR of our product (previously done by Ant). As there're many leftovers of Apache Ant, there's one specific requirement that would make build process easier: copy specific sub-folder of dependency (e.g., jar or war resource) to a specific target sub-folder.



So far I learned that Assembly descriptors allow to specify <outputDirectory>, but is there's any chance to specify a <sourceDirectory>? E.g., I want to apply this rule for one single WAR or JAR type dependency.



Consider this example of assembly descriptor fragment (not 100% accurate):



    <dependencySet>
<unpack>true</unpack>
<scope>runtime</scope>
<useProjectArtifact>false</useProjectArtifact>
<includes>
<include>my-specific-dependency:war</include>
</includes>
<outputDirectory>WEB-INF/myresources</outputDirectory>
</dependencySet>


I want to say that I want to copy some folder from my-specific-dependency:war to WEB-INF/myresources.



EDIT NB: I'm aware that this is not a very correct requirement as we shouldn't know what's inside an artifact, the correct way would be declaring to extract the whole artifact to the target directory (neat declarative approach).





How can C++ compiler optimize incorrect hierarchical downcast to cause real undefined behavior

Consider the following example:



class Base {
public:
int data_;
};

class Derived : public Base {
public:
void fun() { ::std::cout << "Hi, I'm " << this << ::std::endl; }
};

int main() {
Base base;
Derived *derived = static_cast<Derived*>(&base);

derived->fun(); // Undefined behavior!

return 0;
}


Function call is obviously undefined behavior according to C++ standard. But on all available machines and compilers (VC2005/2008, gcc on RH Linux and SunOS) it works as expected (prints "Hi!"). Do anyone know configuration this code can work incorrectly on? Or may be, more complicated example with the same idea (note, that Derived shouldn't carry any additional data anyway)?



Thanks,
Mike.





MySQL group-by very slow

I have the folowwing SQL query



SELECT CustomerID FROM sales WHERE `Date` <= '2012-01-01' GROUP BY CustomerID


The query is executed over 11400000 rows and runs very slow. It takes over 3 minutes to execute. If I remove the group-by part, this runs below 1 second. Why is that?



MySQL Server version is '5.0.21-community-nt'





T-SQL: CTE with identity columns

I'm building a tree (bill of materials style), and transforming some data. Consider the following table:



BillOfMaterials




  • BomId

  • ParentId



Now I'm using a CTE to fill it up:



with BOM as 
(
select @@identity as BomId, null as ParentId <some other fields> from MyTable
union all
select @@identity as BomId,
parent.BomId as ParentId,
some other fields
from MyTable2
inner join BOM parent on blabla)

insert into MyTable3
select * from BOM


Problem is: the @@identity will only give me the identity of the last record inserted before the union.



What can I do to get the identity? I can modify Table3 but not Table1 or Table2



I know I can use a GUID, is that the only option?





How to close my popup and stay at same place on referring page?

I've got a popup and when I close it the page I should go back to scrolls up. How can I avoid having the referring page scroll all the way up when I close my popup? I'd like the referring page to stay where it's at.



My code to close the popup is



<a href="#" onclick="document.getElementById('popupD').style.display = 'none';"
" align="right">Close</a>



How can it be done in the way I want?



Any help is greatly appreciated.



Thanks





Implementing a Symfony2 single-sign-on

I have a basic understanding of the security concept in Symfony2. Now I'm trying to implement a single-sign-on feature for a multi-domain website.



The SSO concept itself is rather straightforward:




  • Domain A is the cookie domain; people can log in on this domain

  • When logging in on domain B, the user is redirected to domain A, where a One-time password is requested. The user needs a session on domain A to get this password.

  • After obtaining the OTP, the user is returned to domain B, which will match the OTP to the session on domain A.

  • If matched, a session will be created for domain B. The session will be validated against the session on domain A for each subsequent request from this point on.



Implementing the firewall/authentication for domain A can be done as you normally would. In my understanding, I need to:




  • Set up a firewall for domain B

  • Create a listener for this firewall, that somehow redirects the user to domain A (more specific: an uri that requests an OTP)

  • Create an authentication provider that handles a OTP and creates a session for domain B

  • Create another listener that checks the session validity against the session on domain A



However I could really use some tips on how to do this in a bundle. If anyone can help me out here, that'd be great.



Also, I'm not yet sure how to implement the OTP, or how to compare the two sessions, and make sure they both are valid. That will come later, I need to get this workflow working first.





Android Html.fromHtml() loses the HTML if it starts with <p> tag

i call a web service that returns some HTML which enclosed in an XML envelop... something like:



<xml version="1.0" cache="false">
<text color="white">
<p> Some text <br /> <p>
</text>
</xml>


I use XmlPullParser to parse this XML/HTML. To get the text in element, i do the following:



case XmlPullParser.START_TAG:

xmlNodeName = parser.getName();

if (xmlNodeName.equalsIgnoreCase("text")) {
String color = parser.getAttributeValue(null, "color");
String text = parser.nextText();

if (color.equalsIgnoreCase("white")) {

detail.setDetail(Html.fromHtml(text).toString());

}
}
break;


This works well and gets the text or html in element even if it contains some html tags.



Issue arises when the element's data starts with <p> tag as in above example. in this case the data is lost and text is empty.



How can i resolve this?



EDIT



Thanks to Nik & rajesh for pointing out that my service's response is actually not a valid XML & element not closed properly. But i have no control over the service so i cannot edit whats returned. I wonder if there is something like HTML Agility that can parse any type of malformed HTML or can at least get whats in html tags .. like inside <text> ... </text> in my case?? That would also be good.



OR anything else that i can use to parse what i get from the service will be good as long as its decently implementable.



Excuse me for my bad english





What is REST? Slightly confused

I was under the assumption that REST was a web service but it seems that I am incorrect in thinking this - so, what is REST?



I've read through Wikipedia but still cant quite wrap my head around it. Why to do many places refer to API's as REST API's?





how to get original image extension

Let's say i have an image abc.gif and i renamed it in to abc.jpg,



but both




*echo $_FILES['imageupload']['type'];*




and




*echo mime_content_type($_FILES['imageupload']['type']);*




output "image/jpg".



How could i get the original extension which is .gif not .jpg



Please help.





How to use resx with on variable test

I've been looking for a tuto to use resx but I only found some where the resx depends on the localization(and the language of the browser).



How can I tell my app to use a certain resx when a certain variable has a certain value.
For instance I'd like to use default.aspx.de.resx when xyz=1.



Thanx in advance





Convert string with expression to decimal

I have a table which has a column 'Faktor' (varchar(50)) which contains expressions like:



1/3
2*9/5
0.567
0.23


No, I am searching a way to execute a select like



select Faktor from Artikel


which should return a column of type decimal with the values



0.333333
3.6
0.567
0.23




subversion installed, cant connect to server

I am on ubuntu and i have installed svn and whatever else it requires to use it( at least thats what i think from the dozens of tutorials i looked into... )



so i have downloaded Versions subversion client app and when i tried to connect like



svn://user@domain.com



and type my password



i got an error



No repository found in 'svn://user@domain.com/'



i have create my repository called repo inside a folder called /svn but why it wont let me connect?





Add a new edge while keeping existing graph fixed

Consider the manually drawn red arrow in this graph:



enter image description here



I want to tell graphviz to draw an arrow like that, although the particular path is not important. The important thing is that the existing graph not change at all. Essentially, I want to instruct graphviz to




  1. Draw a certain graph

  2. Keeping that graph fixed, add a new edge to it



Is this possible?





View mercurial history with straightline development smashed

I'm interested in viewing the topology of my branches, ideally in a pretty way (a la graphlog). For example I want to see how many (open) branches there are, when they split, the last time they merged to and from each other, etc. I am not interested in all the merges between them, nor straight line development on each branch.



This is useful when looking at forks on bitbucket for example. Github's network graph helps, but often the branch structure is drowned out by straightline development and/or frequent merges.



I thought that perhaps I could use revsets like



hg glog --rev "head() or merge() or branch_points()"


but then glog shows all revisions in between, not to mention the fact that I couldn't figure out how to specify branch_points() i.e. revisions which have more than one child.



Is there an extentsion for mercurial (or another DVCS) which can approximate my desires? If not is there a better way to get this information?





Java mkdir -p equivalent

What's the java-esque way to create a director(ies), and don't complain if it exist?



Quoting the man for mkdir:



-p    Create intermediate directories as required... with this option 
specified, no error will be reported if a directory given as an
operand already exists.




Display and scroll over big layout

would be very grateful if anyone can advice how to solve the problem.



I got to draw a large and rather complicated structure (railway track layout). In order to have a smooth scrolling I wanted to draw the layout into a bitmap and then just to copy necessary part into the screen canvas in onDraw method.



The problem is that the layout is much larger than 2048x2048 (max allowed texture size on my Asus Prime) and I'm getting 'Bitmap too large to be uploaded into a texture'.
And this's even without zoom.



The layout is just a set of 2d geometrical primitives so maybe it's possible to work on geometrical rather than bitmap level, but how to implement smooth scroll and zoom then ?



What are common ways of solving this issue ?



Thanks in advance.





Stop form from submitting if select option is disabled

I'm not very good with forms and am having a great deal of difficulty with what should be a simple problem.



I have a form which contains the following:



        <select id="values" name="Choice">
<option value="choose">Please Choose...</option>
<option value="01">Value 1</option>
<option value="02">Value 2</option>
</select>


All I want to do is stop the form from submitting if neither value-01 or value-02 are selected but the disabled option doesn't work.



How can I achieve this?



UPDATE:



I'm already using javascript to check the form, but this does not seem to work.



function submitForm() {
if (formObj.Choice.value == '') {
alert("Please select a value");
return false;
}
return true;
}


UPDATE 2: In answer to @h4b0 question:



<input type="submit" value="Search" class="screen-reader-text button cf" name="SubmitButton" onclick="return submitForm();">




PHP refreshing a temporary form while a process is running

I have a simple E-mail done. I want this email form to run during a process. The user will submit a query. He will have to wait a short time to get the results. During this short time I want the screen to show my E mail form and constantly refresh every 5 seconds, when the process is finished and the results are ready I want the form to leave, and the script to continue to the results page created.



I was thinking javascript?


function timeRefresh(timeoutperiod){
setTimeout("location.reload(true);",timeoutPeriod);

Any suggestions Please?





jQuery UI: DatePicker, select only today's date through past

I'm using the datePicker in the jQuery UI core. I need a date picker that can only pick dates through the past all the way to today.



Is there an easy way to do this? -- Note I'm using the UI core, not the DatePicker Plugin.



My jQuery call:



$(function() {
$(".datepicker").datepicker();
});




Address memory of variable being output in java

This code below is meant to populate the combo box with available times according to the selected date.



However for some reason the combo box is storing the memory address of the data example:



Restaurant.Time@1a28362
Restaurant.Time@5fcf29
...


I know its getting the right times. But how do I actual print out the actual item?



TimeList times = dbConnector.selectTimes(lblDay.getText());//lblDay stores the date from the jCalendar button
cmbNewResTimes.removeAllItems();
for (int pos1 = 0; pos1 < times.size(); pos1++) {
cmbNewResTimes.addItem(times.getTimeAt(pos1).toString());
}




Javascript. Embed or link?

I'm starting to get into a lot more JavaScript thanks to a few UI frameworks such as KendoUI and Dojo/Dijit and I'm trying to integrate these with my custom MVC framework. However, all of their examples have the JavaScript embedded in <script></script> tags along with the HTML, which is fine and just means that the code gets dumped in my Views.



I was just wondering if there was some 'standard' or 'more acceptable' method of presenting custom JavaScript code in my projects. Is embedding the code in the HTML the best way to do it, or is it considered nicer to store the JavaScript in .js files and link to it from the HTML?





Regex to find first capital letter occurrence in a string

I want to find the index of first capital letter occurrence in a string.



E.g. -



String x = "soHaM";


Index should return 2 for this string. The regex should ignore all other capital letters after the first one is found. If there are no capital letters found then it should return 0. Please help.





Need to fill data sheet in excel via xsl for pivot report

Using XSLT I am able to create a XML Spread Sheet with xml raw data and the same can be viewed by MircoSoft excel or open office calc.



Here I need to do pivot report using a xml spread sheet data. Let us assume a work book contains two sheets



Sheet1 is "Data" Sheet,
Sheet2 is "PivotReport" sheet



Pivot Report sheet is predefined and Data sheet is dynamic. Using java I need to open data sheet fill data dynamically. I tried apache POI but its throwing Invocation target exception when accessing sheet.



Is there any other way to fill data sheet ? Thanks.