Monday, April 30, 2012

Selecting rows from numpy ndarray

I want to select only certain rows from a numpy array based on the value in the second column. For example, this test array has integers from 1 to 10 in second column.



>>> test = numpy.array([numpy.arange(100), numpy.random.randint(1, 11, 100)]).transpose()
>>> test[:10, :]
array([[ 0, 6],
[ 1, 7],
[ 2, 10],
[ 3, 4],
[ 4, 1],
[ 5, 10],
[ 6, 6],
[ 7, 4],
[ 8, 6],
[ 9, 7]])


If I wanted only rows where the second value is 4, it is easy.



>>> test[test[:, 1] == 4]
array([[ 3, 4],
[ 7, 4],
[16, 4],
...
[81, 4],
[83, 4],
[88, 4]])


But how do I achieve the same result when there is more than one wanted value. The wanted list can be of arbitrary length. For example, I may want all rows where the second column is either 2, 4 or 6.



>>> wanted = [2, 4, 6]


The only way I have come up with is to use list comprehension and then convert this back into an array and seems too convoluted, although it works.



>>> test[numpy.array([test[x, 1] in wanted for x in range(len(test))])]
array([[ 0, 6],
[ 3, 4],
[ 6, 6],
...
[90, 2],
[91, 6],
[92, 2]])


Is there a better way to do this in numpy itself that I am missing?





Use created attribute with javascript in select list

im trying to access an attribute that i created in a select list.



<script language="JavaScript">
function updateUrl()
{
var newUrl=document.getElementById('test').car;
alert(newUrl);
}
</script>

<input type="text" id="test" car="red" value="create Attribute test" size="40"/>
<input type="button" value="submit" onclick="updateUrl();">


it keep giving me undefined. how do i get the string red from attribute car?





Python Pyramid & Chameleon templating language escapes html

I can't make sense of chameleon's tags. I'm a django user, but decided to introduce my CompSci course mates and myself to Pyramid, since I though more lightweight = easier to learn.



At the moment the ${} tag is escaping any html tags I'm trying to output through it. In django there was some way to specify that a variable is "safe" and doesn't need to be escaped.



How can I do the same thing in Pyramid / Chameleon?





Game database structure

I'm working on a fantasy game and now I got to the part where I have to create the database structure for my spells. The problem is that I don't really have a good idea on how to create it... or should the effects of those spells not be stored in a database ?



Some of the effects would be to increase attack, pull an enemy, heal, teleport, hide, put a mine and so on... As you can see they are pretty different and I would like to make it extensible.



Thank you for your time guys ^^,





How to get the Eventbrite user's data using eventbrite class

How to get the Eventbrite user's data using eventbrite class.



Regards,
Mistry Sandip





NSUserDefaults vs. Core Data for application state

I have an existing large app using plists to store its data. I store application state indicating current item selected, current user, and various other current selections in user defaults. This worked fine when the data was in plists. Now I'm refactoring to use Core Data instead of plists. I want to store a reference to an object instance as the currently viewed object. I know sqlite and Core Data have an ID for this object in the database, but I'm not sure what to store in user defaults. Three options come to mind:




  1. Generate my own sequential ID, store that with the objects I want to remember as "current", store that ID in user defaults.

  2. Try to use NSManagedObjectID and store in user defaults. I "think" I can convert it to a string as follows. Does this work?



    NSString *stringID = [[[managedObject objectID] URIRepresentation] absoluteURL];


  3. I could create a current state entity in Core Data which is a singleton, only one row. This entity could have a to-one relationship to the current object I want to keep track of.




Suggestions appreciated for the approach with best design consideration.





How to determine the height of an InputBox?

I'm using the InputBox from the VB .dll. When I display it, I want to put it in a particular place relative to the controls it will have an impact on (out of their way). So I have this pseudocode for showing the InputBox ("selectionStart" is a Point assigned to on MouseDown):



int HeightOfInputBox = ? <- What is this value?
int XPos = selectionStart.X;
int YPos = selectionStart.Y - HeightOfInputBox;
Interaction.InputBox("Prompt", "Title", "DefaultResponse", XPos, YPos);


My question is: What is the height of an InputBox?





Video Streaming Application

A streaming application is requesting video clips with a playback rate of 100kbps from a regular streaming server. (a) How big (in bytes) must the client side buffer of the streaming application be in order to absorb network jitter up to 4 seconds? (b) Ignoring any connection delay, what is the minimum start-up latency a user of the streaming application has to expect and why?





How does listview differ from listactivity

I would like to know what is the diff b/w listview and listactivity. According to my understanding, if we have only listview in a screen then better to use listactivity correct?.
If we want to add either simple button at the bottom of list or include search on top of list, then we should use listview in layout file right?





Malloc on a Pointer Parameter Failing

I have the following lines of code:



struct c_obj_thing *object = NULL;
c_obj_initalizer(object);
// at this point, (object == NULL) is 'true'
printf("Value: %d\n", object->value); // this segfaults


Here is the definition for c_obj_initalizer:



int c_obj_initalizer(struct c_obj_thing *objParam) {
objParam = malloc(sizeof(struct c_obj_thing));
objParam->pointerThing = NULL;
objParam->value = 0;
return 0;
}


Why does the malloc in the c_obj_initalizer method not stay attached to the pointer passed as a parameter when the method returns? It seems like the call to the initalizer doesn't do anything. I realize that passing an actual c_obj_thing not as a pointer would mean that the changes made in the initalizer did not return, but I thought that dynamic memory perpetuated throughout the entire program.





How can I open a temporary buffer

For very long time I have done: C-x b and then some "unique" name like xbxb. So I use switch-to-buffer with a non-existent buffer. You can imagine what C-x C-b shows me: Lots of such names. xbxb, xbxbxxx .... It really gets annoying after some time (a week or so), since I discover that I have already used all good names.



Is there a more canonical way of opening a new buffer? If I want to run a shell a further time, I say C-u M-x shell. Something along that line would be ideal.





Parse a string by whitespace into a vector

Suppose I have a string of numbers



"1 2 3 4 5 6"


I want to split this string and place every number into a different slot in my vector. What is the best way to go about this





Replace sequence of characters in java

I am parsing a poorly structured rss feed, and some of the data that is being returned has <p>at in it. How can I replace all instance of <p>at with an empty space, using java?



I'm familiar with the .replace method for the String class, but I'm not sure how the regex expression would look. I tried inputString.replace("<p>at", "") but that didn't work.





adding a jquery plugin option

I'm using a jquery tabs plugin and am trying to add a delay to the slide effect where when you click a tab, it slides up, then a delay, then it slides down.



Currently the slide up/down is a function of the plugin, but I haven't been able to figure out how to add the delay option.



You can see the file here:



http://pastebin.com/kM5k9fDx



Just below the top you can see where I've added a "delayClose" option, but that's as far as I've got.



If anyone wouldn't mind taking a look, I'd appreciate it.





Setting up multilingual site with sitefinity in the form of mysite.com/us/home, mysite.com/fr/home

Trying to set up a multilingual site with sitefinity.



The structure is



mysite.com/us/ - all US content
mysite.com/fr/ - all French content


So, the home page for the US would be at



mysite.com/us/home


and the home page for France would be at



mysite.com/fr/home


How can I do that?



Site search should be limited to the currently selected locale (/fr/ or /us/ in this example).



What happens by default is that the US home page ends up in the root of the site, and the French under /fr/:



mysite.com/home     #US version, should appear under mysite.com/us/home
mysite.com/fr/home #French version




String Parsing a Time

I need to obtain a time in the format of "07:30 am" (not case-sensitive). I'm reading a file which has this in the format "07:30am". Eventually I will be constructing a DateTime from this, so I just need to get this back with a space before the am/pm part.



I can detect the occurrence of the a or p using this:



if(startString.IndexOfAny("ap".ToCharArray()) != -1)
{

}


What's the best ways to do this? I'm guessing I will end up with two strings that can be concatenated with a space? Can Split be used with the above snippet to achieve this?





regarding constructors

i was developing the below code....



class P {
//public P(){}
public P(int i) {

}
}

class D extends P {
public D(){ // default constructor must be defined in super class

}
}

public class agf {
public static void main(String[] args) {

}
}


Now in class p explicit parametrized constructor is defined and in class D default constructor is defined but it is still showing the compile time error ,please explain





Need help on reading emails with "mail" gem in ruby

I am doing automation using Watir that creates an email that I need to check. I was pointed at the email gem as being the easiest way to do this.



I added following code and am able to get first email from my inbox.



require 'mail' 
require 'openssl'

Mail.defaults do
retriever_method :pop3, :address => "email.someemail.com",
:port => 995,
:user_name => 'domain/username',
:password => 'pwd',
:enable_ssl => true
end

puts Mail.first


I am new to this forum and have following questions :




  1. How can I get all the unread emails? I tried Mail.all, Mail.first, Mail.last, but nothing returns unread email.


  2. How can I get all links that are present inside emails? Or mail message body from the specific email? I need to get the email body of first unread email.


  3. How can I get emails from a specific folder, if I have subfolders inside my inbox?






Normal distribution of random numbers hangs the program?

When I run this code is just hangs in for loop, can you explan why?



#include<iostream>
#include<random>
#include<ctime>

int main()
{
using std::cout;
using std::endl;
using std::cin;
using std::mt19937;
using std::minstd_rand;
using std::uniform_int;
using std::normal_distribution;

// engines
mt19937 rng;
minstd_rand gen;

// distributions
uniform_int<int> dist(0, 37);
normal_distribution<short> norm(4, 3);

// initializaiton
rng.seed(static_cast<unsigned int>(time(false)));
gen.seed(static_cast<unsigned short>(time(false)));



// generate numbers
for(int i = 0; i < 10; ++i)
std::cout << dist(rng) << " " << norm(gen) << endl; // This is as far as this code goes

cin.get();
return 0;
}




Creating an Android Service with Phonegap? (Have phonegap app run even when closed)

I have been working on an Android app using Phonegap and now would like to make it so when the app is closed it can still execute the java/js code in the app. So I understand I need to create a service. If I create a service plugin on phonegap can I still execute the javascript code or only the java?



Has anyone does something like this? I found this discussion but did not seem to work: http://groups.google.com/group/phonegap/browse_thread/thread/722b0e796baa7fc6
So that is all I have right now.



Before I turn to developing it native if I can't figure it out thought I would ask if anyone has done this before. I can't seem to find any of the phonegap plugins that do something similar.



EDIT: I have got an app that executes Java code as a service. However when it calls sendjavascript it does not work. So is there a way to have the javascript code running in the background as well when an app is closed with phonegap?



Thanks





Wednesday, April 25, 2012

How to get different random numbers?

I have a String array with many elements (as I haven't still finished the Application, I don't know exactly the number), maybe about 200. I would like to get 20 random elements of this array, but being certain that every random element occurs only once, like, I don't want to get in those 20 elements the 5th element (for example) twice. How can I do this?





Pruning a AbstractTableModel without getValueAt() complications

Is there a way to derive a pruned AbstractTableModel from a full AbstractTableModel without getValueAt() complications?



My full data (including userIds) is loaded into a JTable AbstractTableModel. However, for display purposes, I wish to derive a pruned AbstractTableModel of data associated with a particular userId.



I am beginning to think this is not possible because getValueAt intervenes and throws IndexOutOfBounds exceptions? These exceptions seem to occur becuase the pruned Data is not populated.



public class PrunedUserIdTableModel extends AbstractTableModel {

TableModel fullModel;
List columnIdentifiers;
List tempDatum;
List tempData; // holds tempDatums
int rowCount; // reports pruned rowCount through getRowCount() method
List prunedData; // intended to hold data of matched userId rows

public PrunedUserIdTableModel(JTable fullTable, String userId) {
fullModel = fullTable.getModel();
columnIdentifiers = new ArrayList();
tempDatum = new ArrayList();
tempData = new ArrayList();
rowCount = 0;

List<Integer> userCount = new ArrayList<>();

// Load columnIdentifiers from fullModel; omitted here

// Go through fullModel searching for rows with matching userIds

for (int i = 0; i < fullModel.getRowCount(); i++) {
for (int k = 0; k < fullModel.getColumnCount(); k++) {
tempDatum.add(fullModel.getValueAt(i,k);
if ((fullModel.getValueAt(i,k).equals(userId)) {
// Matching userId found; record relevant row
userCount.add(g);
}
}
tempData.add(tempDatum);
tempDatum.clear();
}

// Now populate prunedData
for (int j = 0; j < userCount.size(); j++) {
prunedData.add(tempData.get(userCount.get(j)));
rowCount=rowCount+1;
}

fireTableChanged(null);
}
@Override
public int getRowCount() {
return rowCount;
}
@Override
public int getColumnCount() {
return fullModel.getColumnCount();
}
@Override
public int getValueAt(int rowIndex, int columnIndex) {
// THROWS INDEX OUT OF BOUNDS EXCEPTION: Index 0; size 0
List rowList = (List)prunedData.get(rowIndex);
return rowList.get(columnIndex);
}
}




CSS3 transitions want to add a colour and fade it away

I want to make a DIV background (which doesn't have a background color) flash red then ease out to blank again. now I have used JS to add a new CLASS (which adds the red) to the DIV in question and CSS3 to add an easing to the background color. but it eases it IN, what I want is it to go RED then ease out. I guess I could do this by using JS to add multiple CLasss after a delay. but can CSS3 be used to do this entirely?



cheers





Dom parsing in android

i have parsed xml using dom parser,but when the xml element contains no value it throws null pointer Exception.how to check this?...
here my code



NodeList TrackName1 = fstElmnt2.getElementsByTagName("Artist_Name");    


Element TrackElement1 = (Element) TrackName1.item(0);

TrackName1 = TrackElement1.getChildNodes();
result=result+((Node) TrackName1.item(0)).getNodeValue()

String Artistname=((Node)TrackName1.item(0)).getNodeValue();



}




Combotree in javascript (jquery)

I'm looking for a component which enable display tree in combo (select).
Something like that: http://www.jeasyui.com/demo/index.php



But this component doesn't allow import JSON directly, only from file.



It works in that way:



$('#cc').combotree({  
url:'tree_data.json'
});


I need (pseudocode):



$('#cc').combotree({  
data:'[{"id":1,"text":"City","children":[{"id":11,"text":"Wyoming","children":[{"id":111,"text":"Albin"}]}]}]'
});


Or (pseudocode):



$('#cc').combotree({  
data:'<?php $json_string; ?>'
});


Is it possible? Or maybe do you know any components which enable to do that?



Regards,
Chris





Frame with 50 png in iPhone

I have a ViewController with 16 buttons. Each button loads a popover that show 50 frames renders in moving.



What is the best form to do it?



I know that imageWithName is bad because it load all images in cache, and for this reason im doing it with:



myAnimatedView.animationImages=[NSArray arrayWithObjects:
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@0000",nombrePieza]ofType:@"png"]],
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@0001",nombrePieza]ofType:@"png"]],
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@0002",nombrePieza]ofType:@"png"]],
...
...
... [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@0050",nombrePieza]ofType:@"png"]],nil];


But when i load about 10 times the popover with differents frames, i have a leak of memory only on my device, but not in the simulator.



For this reason, i want know which is the best form to do it?



With a video? or with CAAnimation?



Thanks for help.





How to hide the code of firefox extension

I made an IE toolbar by BHO with C#. And now I want to make a firefox version.
I planned to use xul but it will show the source code to the user.
Seems DLL is not a good way in firefox.



I tried some toolbar like yahoo, google which will not create files in extension folder.
How can I make something like that?





Android SAX parsing retrieval very slow

In my app i have some 50 to 100 data to be parsed...also some images within 2 MB size...All these are to be retrieved to a single activity and are sorted and displayed there...



But its taking about 2 minutes...thats too much.



What to do for reducing the parse time?



Or am i wrong using SAX parsing???Suggestions please....



SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

/** Send URL to parse XML Tags */
URL sourceUrl = new URL(url);

/** Create handler to handle XML Tags ( extends DefaultHandler ) */
XmlHandler xmlHandler4Profile = new XmlHandler();
xr.setContentHandler(xmlHandler4Profile);
xr.parse(new InputSource(sourceUrl.openStream()));

}




How to add g729 codec plug-in in JMF 2.1.1e

I have a g729 codec package, but I couldn't able to add it in JMF.
How can I make a JMF codec plugin, so that I can transmit audio in
g729 format.



In a straight forward way, how to enable JMF to support additional
codec plugin.



I searched through, but couldn't find any straight forward answer.





Spring Security Implementation in Legacy Application

Let say i have a screen name ITEM thats performs different actions
Save,Updata, Delete



i have given a user ADMIN with a role of ADMIN
and the ADMIN role can only perform SAVE and UPDATE operations on this screen
how to customize this using spring security



Mehtod Level Security checks only on roles but not one step further
but that must pe possible with spring security
as i have currently not so much knowledge of this therefore i am asking this
from spring experts



thanks





Conditional Coloring of Datatable in PF or var vs binding tags in a datatable

I have a datatable and a collector. Each row in the datatable has a button and this button adds the corresponding row to the collector. I want to add conditional coloring to this datatable. Condition is whether the selected rows are in the collector or not.



<p:dataTable rowStyleClass="#{backingBean.selectedMemberList.contains(aMember) ? 'passive' : 'active'}" style="width: 100%;" id="dTable" var="aMember" value="#{backingBean.memberList}">
<p:column>
...
</p:column>

<p:column>
<p:commandButton id="btn_add" value="Add" update=":mf:op" process=":mf:op_uk">
<p:collector value="#{aMember}" addTo="#{backingBean.selectedMemberList}" />
</p:commandButton>
</p:column>


backing bean:



List<Member> selectedMemberList;
List<Member> memberList;

//getter and setter methods


Above code does passive style class but does not add active style. I thought it is maybe because I can not pass var (which is request scoped) to backing bean.. So I tried binding the value to a backing bean value:



<p:dataTable binding="#{backingBean.anotherMember}" rowStyleClass="#{backingBean.selectedMemberList.contains(aMember) ? 'passive' : 'active'}" style="width: 100%;" id="dTable" var="aMember" value="#{backingBean.memberList}">


backingBean:



private Member anotherMember;
//getter and setter methods


but it did not work either. Does anyone have any recommendation about this issue?



PrimeFaces ver 2.2.1



EDIT:
css contains these fields:



.active{    
background-image: none !important;
}

.passive{
background-color:gainsboro !important;
background-image: none !important;
}




How to use a Custom Controller in a JSF Application

I have an existing Java EE based web Application having JSP as a view component and a Servlet as a controller (name: Control1), which has the entire application logic.



The requirement is to use JSF 2.0 Facelets as UI Components. The Facelets have been written.



Now the problem is navigation. Since it is an existing application there is a huge amount of code and logic inside the controller Control1, which I have to reuse without evaluating the design trade-off.



Please suggest when I submit the form in my newly written xhtml pages how the request can be forwarded to my controller Control1, with the HTTP request object and parameters from the Faces Servlet.





C# - Can't get column types from MySQL

Here's some code:



OdbcConnection connection = new OdbcConnection(@"DRIVER={MySQL ODBC 5.1 Driver};SERVER=" + ip + ";DATABASE=db_name;USER=user;PASSWORD=" + dbPw + ";");
connection.Open();

string queryString = query;
OdbcCommand command = new OdbcCommand(queryString);

command.Connection = connection;
OdbcDataReader myReader = command.ExecuteReader();
int fieldsN = myReader.FieldCount;

StringBuilder sb = new StringBuilder();

while (myReader.Read())
{
for (int i = 0; i < fieldsN; i++ )
{
sb.Append(myReader.GetString(i) + " ");
}
sb.Append(", ");
}

connection.Close();

//Console.WriteLine(sb.ToString());


This code works fine with queries like "SELECT * FROM some_table" or "SELECT (something, something_else) FROM some_table."



However it fails when I use "SHOW COLUMNS FROM some_table."



Here's the error I get:




Unable to cast object of type 'System.DBNull' to type 'System.String'.




This error happens somewhere in the myReader.GetString() line.



I've tried creating an if statement that checks if myReader.GetString(i) is System.DBNull to no avail. Whatever I do it always errors out. I don't understand what is going on.



Thanks for any help!





PHP: how to create a search form that will link to my search script

I have a PHP search script which I've altered slightly and works well for me. But there is one part Im not sure how to do, and that is linking the script up to a search form, that a user can complete.



The script is below, and it searches a text file for key words. Currently the "key word" is entered directly into the script. But that is no good for someone visiting my site - so I wanted to create a search form. But not sure if I should use POST or GET or something else. And I dont know how I should link the code up from the form, to the script below. I've searched for quite a bit of time to find this, but cant see anything that covers it, and my attempts at getting it to link up arent going well. If anyone could help it would be most appreciated.



(original code borrowed from Lekensteyn - http://stackoverflow.com/a/3686246/1322744 (thanks))



<?php
$file = 'users.txt';
$searchfor = 'entersearchterm';

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:<br />";
echo implode("<br />", $matches[0]);
}
else{
echo "No matches found";
fclose ($file);
}
?>




generate next color randomly if the color is still available

I m working on an app for android and I'm struggling at some points. One of them would be to chose the next color (out of four) but keeping in mind, that the color chosen, could be empty already, in this case the next of the four colors shall be chosen



I have two ways of doing it, but one of them is way too much code and the other one is causing a crash (I guess that happens because it can end up in an endless loop)



Thanks in advance



public void nextColor(Canvas canvas) {
Random rnd = new Random(System.currentTimeMillis());
int theNextColor = rnd.nextInt(4);
switch (theNextColor) {
case 0:
if (!blue.isEmpty()) {
currentPaint = paintBlue;
} else
nextColor(canvas);

case 1:
if (!grey.isEmpty()) {
currentPaint = paintGray;
} else
nextColor(canvas);
case 2:
if (!gold.isEmpty()) {
currentPaint = paintGold;
} else
nextColor(canvas);
case 3:
if (!red.isEmpty()) {
currentPaint = paintRed;
} else
nextColor(canvas);
}




scala map / type instantiation

can someone explain the best way to get around the following,
rather curious type error. Suppose I create a list of tuples like so:



scala> val ys = List((1,2), (3,4), (5,6))
ys: List[(Int, Int)] = List((1,2), (3,4), (5,6))


Now, if I want to map this to a List(Int)



scala> ys.map((a: Int, b: Int) => a + b)
<console>:9: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => ?
ys.map((a: Int, b: Int) => a + b)
^


Any clues? I know I can use the for comprehension



scala> for ((a, b) <- ys) yield a + b
res1: List[Int] = List(3, 7, 11)


But it feels wrong to bust out a comprehension in this setting. Thanks!





Show specific page when opening Account window

Following on from my previous Dynamics CRM question (Show popup/alert if account has related entity records)



In the OnLoad event of the Account form, I want to set the window to open with a specific sub-navigation item loaded into the right-hand frame.



For example, by default, when you open the Account window, it loads the account details. Listed on the left are various related items. I have a custom related entity called Alert. If a specific criteria is met in my javascript, I want the Alert entity view to be loaded into the right-hand view instead of the Account details.



Is this possible?





How Can I Change the Icon for an Existing Shortcut in shell script

I have installed my flash application using packagemaker installer. I have created short cut to desktop using shell Script. Now i want to change the default short cut Icon. Please tell me shell script to change the short cut icon.



MAC OS 10.7.2





Codeigniter Profiler with method execution count, times etc

Is there any CI library that I can use for profiling, finding bottlenecks, seeing unnecessary execution times etc in my local php environment using beside the CI's default profiler?



I'm going to use it remotely and my host doesn't have any debug extensions installed, and I don't want to ask them to install, and if there's any PHP solution of it, it'll be nice.





Execute Immediate Alter User Bind Variable

The following procedure:



create or replace
PROCEDURE ChangePassword
(
p_Name VARCHAR2,
p_Password VARCHAR2
)
AS
EXECUTE IMMEDIATE 'ALTER USER :a IDENTIFIED BY :b' USING p_Name, p_Password;
END;


compiles successfuly, but when executed:



exec ChangePassword('TestUser', 'newPassword');


results in error:



01935. 00000 -  "missing user or role name"
*Cause: A user or role name was expected.
*Action: Specify a user or role name.


Why?





Compatibility assistance issue in window 7

After creating an installer whenever I am running my application (from installer) , I am getting program compatibility assistant message. To fix this issue I have added the below code in my manifest file. but still I am getting the same issue . I am facing this issues in 2 of my applications one is in vs2010 and other is in VS2005. Below code fixes the issue in VS2010 application. But for the other application , still the issue is present.



  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.

<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

Specifying requestedExecutionLevel node will disable file and registry virtualization.
If you want to utilize File and Registry Virtualization for backward
compatibility then delete the requestedExecutionLevel node.
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>








  <!-- If your application is designed to work with Windows 7, uncomment the following supportedOS node-->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>

</application>




can any one help me in resolving the above mentioned problem



Regards,



Vidya





ASP.NET MVC Ajax Form: Is enctype correct? Why doesn't file get uploaded?

In the case that the user doesn't have Javascript activated, in order to draw a form, I begin this way:



<% using (Html.BeginForm("Create", "Language", FormMethod.Post,
new {enctype="multipart/form-data"}))
{ %>


If the user has Javascript activated, the following code is used:



<% using (Ajax.BeginForm("Create", "Language",
new AjaxOptions { UpdateTargetId = "CommonArea" },
new { enctype = "multipart/form-data" }))
{ %>


The problem is this:



In the first case, I can get the file uploaded using the following instruction in the business layer:



// Get the uploaded file
HttpPostedFile Flag = HttpContext.Current.Request.Files["Flag"];


In the second case, this instruction doesn't work. How do I know upload that file using the Ajax.BeginForm? Is the code right? Can anyone more experience advise about using jQuery plug-in to upload file before the form submission?



Thank you





Repackaging the .jar file

I need to add some jars from JRE7 library to my Android project. But for example rt.jar is in conflict with android.jar from Adroid 2.2 SDK, so I get this error:



Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.


I know there have been several threads about it and things like JarJar, OneJar or FatJar might be good for me. But I don't know how to make any of them work and documentation doesn't really make it clear (for me). I guess they use Ant commands, but I have always used Eclipse built-in builder and now I have no idea how to use neither Ant nor any of mentioned above.



So my question is: how can I repack this rt.jar so I could compile it in my Android project?



Thank you!





How to check whether the port 80 is available using a batch file in windows xp

I'm writing a batch file to automatically checks the port 80 availability and give an error message if it is using by another program. But I'm not sure how to check the port 80 availability in a batch file.



I found following command to check that with terminal.



 netstat -o -n -a | findstr 0.0:80


But I need to check it with a batch file like follows



if (!//port 80 is available) {
// Give an error message
} else {
// Continue with the rest
}


Can someone please help me on this.





Google Contacts API asp.net settings and authorization token

Is there any good example that shows how to fill the application settings creating the settings for request?



this is code from google



using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
// ...
RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>");
// Add authorization token.
//
// ...
ContactsRequest cr = new ContactsRequest(settings);


Do I have to specify the token that I get from oAuth request, and no more?



The value for YOUR_APPLICATION_NAME could be any string value?





jQuery input updates all IDs, rather than just the one required

The issue I'm having is fairly hard for me to explain, but I have replicated it in a jsFiddle http://jsfiddle.net/6ms4T/1/



What I am trying to achieve is by updating the 'Quantity' text box, I want to display the value elsewhere (the line below which I'll refer to as the 'Cost line').



Basically, updating the first input box (qty_item_1) is updating all the (quant_) IDs in the 'Cost line', rather than just the one related to that product.



function recalc(){

$("[id^=quant_]").text($("input[id^=qty_item_]").val());


etc...



Full code is here: http://jsfiddle.net/6ms4T/1/



Any help would be appreciated.





How to start selenium server with log4j

I want to start selenium server with log4j so that all server related logs go there. I'm starting the server with ANT using the following ANT target



<target name="startserver" depends="setClassPath">
<java jar="${test.home}/lib/selenium-server-standalone-2.20.0.jar" fork="true">
<arg line="-Djava.util.logging.config.file=log4j.properties"/>
<arg line="-firefoxProfileTemplate 'D:\selenium.default'"/>
<arg line="-browserSideLog"/>
</java>
</target>


My log4j.properties is as below:



log4j.rootLogger=INFO, R, stdout

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=./logs/sellog.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n


But I'm not getting any server logs after I start the server from the target.



Also, I have a selenium test where I'm throwing the log into log4j as below:



private LogManager lm;
private Logger logger = lm.getLogger(this.getClass().getName());
logger.info("Selenium Client started...");


I'm getting application logs in log4j log.



What I want is to have all the logs (selenium server log + app log) in log4j log.



Any help is greatly appreciated.





nested ul menu - pass variables between windows?

I have a simple ul menu with nested ul menus here



http://www.ttmt.org.uk/forum/reload/



When the page loads the nested menus are hidden.



When the parent links are clicked I want them the nested ul to slidedown
and show the menu.



The first link 'One' is connected to another page, when it's clicked I want it's nested
menu to appear when the new page loads.



I'm thinking the only way to do this is pass a variable to the new page so it's knows which nested menu to open.



Is this the bested way to do this or is there a better way.



How can I pass a variable to the new page to open the nested menu.



    <!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.4.1/build/cssreset/cssreset-min.css">

<style type="text/css">
#nav{
margin:50px;
width:200px;
}
#nav li a{
background:#aaa;
display:block;
padding:5px;
margin:0 0 2px 0;
text-decoration:none;
}
#nav ul li a{
background:red;
color:white;
display:block;
padding:5px;
margin:0 0 2px 5px;
}
h1{
margin:50px;
font:bold 1.5em sans-serif;
}
</style>

</head>

<body>

<h1>Home</h1>

<ul id="nav">
<li><a href="one.html">One</a>
<ul class="children">
<li><a href="one.html">One/One</a></li>
<li><a href="#">One/Two</a></li>
<li><a href="#">One/Three</a></li>
</ul>
</li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a>
<ul class="children">
<li><a href="#">Three/One</a></li>
<li><a href="#">Three/Two</a></li>
</ul>
</li>
</ul>

<script type="text/javascript">

$('#nav li ul').slideUp();

$('#nav > li > a').click(function(){

if ($(this).attr('class') != 'active'){
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});

</script>

</body>

</html>




How to fetch/optimize huge volume for PAGINATION of data through Hibernet Java Struts

Current Problem: We are currently trying to fetch over 500k (Five hundred thousand) records from the database and then I have to show 50 records per page on a JSP (using struts 2). Problem is it takes time loading long time or even some time it does not. Once it is loaded we are able to navigate smoothly.



Solution Needed: Like to load limited records as per the pagination defined records, for eg: each page upto 100 records.Has anyone implemented similar functionality in struts or similar framework? also i dont want to get all records at once. please guide me how to implement?





Open only single instance of view

From my ShellViewModel I have below command binding to open another window "Remote View"



public ICommand RemoteViewCommand
{
get { return new RelayCommand(RemoteViewExecute, CanRemoteViewExecute); }
}

private void RemoteViewExecute()
{
if (!CanRemoteViewExecute())
{
return;
}

//call restore view
//new ShellRemoteView().Show();

ShellRemoteView shellRemoteView = Application._Container.Resolve<ShellRemoteView>();
shellRemoteView.DataContext = Application._Container.Resolve<ShellRemoteViewModel>();
shellRemoteView.Show();
}


ie Every time I click button on shellView -> it opens as much instances of remote view.
How can I achieve only single instance of RemoteView to be opened/activate each time.
Any help would be really appreciated





Tuesday, April 24, 2012

Wicket AbstractAjaxTimerBehavior and performance

I'm using AbstractAjaxWicketBehavior in my Wicket application and it seems to have a descending performance over time when more AJAX calls appear. When a page is refreshed without AJAX, the performance is fine again. I would like to know if this is a normal thing or can be a memory leak of some kind present? I can't simply attach the code as it's spread over more classes and it would require too much effort to understand, but in short I want to do this:




  1. create and start the timer

  2. repeat some code 10x

  3. stop the timer

  4. set some values to attributes

  5. ajax refresh (causes show/hide of some components)



and do the same again (hypotetically infinite times).



Every repetition of this flow is slower even though I use constant updating interval of 100ms.



As the timer is a behavior and does not allow to be restarted or reused, it is created every time as a new instance and attached to the Form component.



The timer looks like this:



static int count = 0
new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) {
// do some code
count++
if(count == 10) {
stop();
// do some code
}
}


This behavior is attached to a Form inside a Panel and upon a click on an AjaxLink the Form is refreshed (added to AjaxRequestTarget). Every time I remove the old timer from the Form component before adding the new behavior.



Everything works fine, but every repetition of this procedure runs slower (The first one is perfect, the second one is also around 100ms, but then it gets slower (after 10 or 15 repetitions, the refresh interval is about 1 second) and all other AJAX calls in the app also go significantly slower), so I suspect there is a memory leak... any obvious reasons? Or any ways how to make a wicket timer better for my purpose? Any advice appreciated. Thanks.





jQuery: $(element).text() doesn't work

Why isn't this working? I've searched Stackoverflow and jQuery API and it should work. Instead I get an empty string :(



function a(){
var div=document.createElement("div");
div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';

var parent_div=document.getElementById('dinamicni_div');
parent_div.appendChild(div);
}

function showMyText(link){
var txt=$(link).text();
alert(txt);
}




Transition between 2 movies using a MPMoviePlayerController

I'm trying to make a smooth cross fade between 2 movies in my iPad App. On a button tap the visuals randomize & the movie which is playing fades to the next movie.



Since 2 movies cannot be played simultaneously (from the docs) a straight-forward cross-fade isn't possible. To get around this I use a still image of the initial frame of the new movie (which is to be faded in). I used two players to handle the interchange of movies.



The original movie is paused, Then I transition to the image. Now I add my 2nd movie (with alpha = 0.0) & then transition so that its alpha = 1. I then play the new movie. This all works ok except for a noticeable darkening as the new movie transitions in over the image.



I tested it without the still image & the darkening doesn't seem to occur during said transition.



My code for the switch is below (first half of the if-statement). It looks pretty strange ,looking over it, but it's the method that brought me closest to what I needed.



Maybe there's a better way to go about this task? Thanks in advance :)



- (void) switchMovie;
{

NSURL *movieImageUrl = [movieImageUrlArray objectAtIndex:index];
NSData *data = [NSData dataWithContentsOfURL:movieImageUrl];
UIImage *movieImage = [[UIImage alloc] initWithData:data];
UIImageView *image = [[UIImageView alloc] initWithImage:movieImage];

image.alpha = 0.0f;
[self addSubview:image];

if (moviePlayer1Playing) {

moviePlayer1Playing = NO;
moviePlayer2Playing = NO;

[moviePlayer1 pause]; //pausing later in the method caused a crash, stopping causes a crash.

[UIView animateWithDuration:1.0
delay:0.0
options:UIViewAnimationCurveEaseIn
animations:^{

image.alpha = 1.0f; //fade in still of first frame of new movie

} completion:^(BOOL finished) {

[moviePlayer1 release]; //release original movie.

moviePlayer2 = [[MPMoviePlayerController alloc] initWithContentURL:[movieUrlArray objectAtIndex:index]];

moviePlayer2.shouldAutoplay = NO;
[moviePlayer2 prepareToPlay];
[moviePlayer2 setControlStyle:MPMovieControlStyleNone];
moviePlayer2.scalingMode = MPMovieScalingModeAspectFill;
[moviePlayer2.view setFrame:CGRectMake(0, 0, 1024 , 768)];
moviePlayer2.view.backgroundColor = [UIColor clearColor];
moviePlayer2.view.alpha = 0.0;
[self addSubview:moviePlayer2.view];

[UIView animateWithDuration: 3.0
delay: 0.0
options: UIViewAnimationCurveLinear
animations:^(void){

moviePlayer2.view.alpha = 1.0f;
//During this transition the view goes dark half-way through, before lightening again.

} completion:^ (BOOL finished) {

[moviePlayer2 play];
moviePlayer2Playing = YES;
moviePlayer1Playing = NO;


}];

}];


}




Detecting button clicks within a for loop in an Android app

I'm having a little bit of trouble. There are 12 buttons, and 10 questions in my android app. If I ran a for loop for all of the questions is there a way that I can check if a button is pushed and if it's the answer to the current question? Then it would move on to the next question, and do the same until the loop ended. I don't know exactly how to word it, but I hope you can figure out what I mean.





Disabling button from another class

I know this question has been asked before or similar questions asked but none of the solutions has yet fixed my problem.



I have a winform that has a button named hitButton. All I need to do is to disable this button from another class (i.e. not the form class).



My form class is:



public partial class BlackJackTable : Form
{
}


My separate class is:



class GameWon
{
}


I have tried exposing a public method in BlackJackTable like this:



public void DisableButtons()
{
hitButton.Enabled = false;
}


and accessing from GameWon constructor (it doesn't seem to matter where in the class I access it from though) like this:



public BlackJackTable blackJackTable = new BlackJackTable();

public GameWon()
{
blackJackTable.DisableButtons();
}


I have tried using a variable in GameWon:



public Button hit;


and assigning from blackJackTable:



GameWon gameWon = new GameWon();

public void Assign()
{
gameWon.hit = this.hitButton; // or just = hitButton;
}


and disabling from GameWon:



hit.Enabled = false;


I have tried a couple of other things but none of them work. I'm guessing I'm missing something obvious as none of the methods I've tried have worked.



Any thoughts appreciated!



Update



I have managed to do the latter method with textboxes and pictureboxes, what's the difference with a button?





Populate a ListView with an AsyncTask failing to populate

Trying to get this working... it loads up fine, even tells the application that it completed getting all the data. It does not populate the listview though.



The data response inside show_list: [A, B, C, D]



public class MainActivity extends ActionBarActivity {
private static final String DEBUG_TAG = "MainActivity";
private boolean mAlternateTitle = false;
List<Show> mShowList;
AlertDialog mAlertDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadTitles();
}

private void loadTitles() {
ShowsList show_list = new ShowsList();
show_list.execute();
}

private class ShowsList extends AsyncTask<Void, Void, List<Show>> {
@Override
protected void onPreExecute() {
mAlertDialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_action_refresh).setTitle(R.string.fetching_new).show();
}

@Override
protected List<Show> doInBackground(Void... voids) {
try {
mShowList = Show.getShows();
return mShowList;
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this.getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
return null;
}
}

@Override
protected void onPostExecute(final List<Show> show_list) {
final String DEBUG_TAG = "MainActivity$ShowList$onPostExecute";
/*ListView lv = (ListView) findViewById(R.id.list);
ArrayAdapter<Show> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, async_show_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
*/
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}

try {
ListView lv = (ListView) findViewById(R.id.list);
ShowsAdapter adapter = new ShowsAdapter(MainActivity.this, android.R.layout.simple_list_item_1, show_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
Log.d(DEBUG_TAG, adapter.toString());
adapter.notifyDataSetChanged();
//adapter.add(show_list[0]);
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
}
}
}

private class ListClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Show show = mShowList.get(i);
Toast.makeText(MainActivity.this, "Clicked on a list item: " + show.title, Toast.LENGTH_LONG).show();
}
}

private class ShowsAdapter extends ArrayAdapter<Show> {
public ShowsAdapter(Context context, int textViewResourceId, List<Show> shows) {
super(context, textViewResourceId, shows);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
Show show = this.getItem(position);

if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row_show, parent, false);
}

((TextView) convertView.findViewById(R.id.show_title)).setText(show.title);
//((TextView) convertView.findViewById(R.id.episode_number)).setText(episode.getGrayLine());

return convertView;
}
}




Random image in a .php file

Im trying to make a random image display with php. Now im not talking about something that echos "image", I need something that when I view the .png file I will see a random image everytime. I wasnt sure what to search for so Im gonna ask it here. I saw someone do it before, where they 'tricked' the browser into thinking it was a .png file, when it was just some php using something to pick a random image and set it as the file.





BackboneJS root level views

If you have some root level HTML that is present on "almost" every screen, where/how would you organize this?



I'm using backbone-boilerplate and requirejs. One of the root level views is a global navigation element that can be invoked from the bottom of the screen at any time.



This is organized in a module that has a model (for visibility, the selected state, the log of clicks, etc). The app is stored in:



ClientName.app = _.extend( { rootViews: {} }, Backbone.Views);


Then in my routers initialize method, i have:



ClientName.app.rootViews.globalNav = new GlobalNav.Views.BottomView({ model: new GlobalNav.Models.Bottom()});


It works fine, but as the functionality is growing, the routers initialize method is getting out of hand with similar root views, sub routers, etc. Am I totally missing something?



What would you recommend?





Why doesn't this rememberUser() function work?

I have written a function to remember the user that has just logged in. It looks to me that it should work, but no Idea why it doesn't work. The problem is that the cookie doesn't get made when I look into my browser's stored cookies.



This is the function I'm talking about:



function rememberUser($id) {

$mysqli = new mysqli('bla', 'blabla', 'blablablaa', 'blaaaaa');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$remember = md5(uniqid(mt_rand(),true));
$stmt = $mysqli->prepare("UPDATE USERS SET USER_REMEMBER_KEY = ? WHERE USER_ID = ?");
$stmt->bind_param('si', $remember, $id);
$stmt->execute();
setcookie("remember", $remember, time()+60*60*24*30, "/", "www.someSite.com", false, true);
}


I should mention that the query works fine and USER_REMEMBER_KEY is stored fine in the DB. So the problem is really the cookie, I think.



Does anyone see the problem here? Thanks in advance.



UPDATE: I'm using Google Chrome BETA version 19.xx





alternative to Uniformjs for styling select and check boxes?

Uniformjs seems to be unmaintained now (last commit 2 years ago). Is there another solid javascript library that allows you to style select, radio and check boxes?





Object Assignment vs Object Creation

I have always found it hard to decide when I should create a single object and pass it to every object that needs it, or create a new object for every object which needs that item.



Some cases are so obvious, like entity objects which are readonly after allocation and instantiation. You can pass the same object anywhere and not worry about another object modifying it, which ruins the other objects holding a reference to it.



My problem mainly lies with objects that represent themselves to the user. Objects like CCSprite in cocos2d, NSMenuItem in Cocoa (AppKit) and other objects with visual representation..









Examples:



In cocoa, i know that I have to create an NSMenu for each NSPopUpButton, so that the selection for a specific button does not affect the rest. But, what about the NSMenuItems contained within? Can I create a single set and pass them to all the menus? What are your grounds, or how did you come to such a conclusion?



Other example:



In cocos2d, and almost all GUI based applications, you can pass to a button two images/sprites/...etc. such that one is for the normal state, and the other is for the selected (highlighted, pressed, clicked) state. Can I pass the same image/sprite/...etc. to both, making them point to the same object?



I hope this is not an implementation related issue (that it ultimately depends on the implementation) , since I face it in a lot of my programming projects, in cocoa, cocos2d, Java ... etc.



PS: I need help with choosing the proper tags





Ohm, find all records from array of ids

I am looking for a way to find all Ohm affiliated objects with one query, by feeding it an array of attributes that are indexed. In Mongoid, this is done with something like:



Foo.any_in(:some_id => [list_of_ids])


ActiveRecord has the find_all family of methods.



I essentially want to be able to pull N records from the data store without calling find() 30 times individually.





How to display only one data at a time in an online quiz

I've previously made a text file and turned it into multidimensional array to display as the questions for my quiz.



Note: I am unable to insert images therefore I cannot provide any example so I'll try to be as descriptive as I can.



I'm trying to display only one question at a time, every time a user clicks on my quiz.



This is my code so far. The main.php page:



<h2>ONLINE QUIZ</h2>
<ul>
<li><a href='question.php'>Take quiz</a></li>
<li><a href='module.php'>Admin Module</a></li>
</ul>
<?php

$file = fopen('data.txt', 'r');

$array = array();
while ($line = fgetcsv($file)) {
$array[] = $line;
}

fclose($file);

session_start();
$_SESSION["questions_array"]=$array;

?>


And the question.php page:



<?php

session_start();
$array=$_SESSION["questions_array"];

foreach ($array as $q => $data) {
echo '<p>'.array_shift($data).'</p>';
foreach ($data as $a => $answer) {
echo
' <input type="radio" name="question-'.$q.'" id="question-'.$q.'"'.
' value="'.$a.'"/>'.
' <label for="question-'.$q.'">'.$answer.'</label>'.
'<br>';
}

}

?>


When the Take quiz link is clicked, the user is taken to the question page where only one question is shown. The user then picks an answer and hits submit. This submit button will take the user to the result page where they can then hit continue.



The Continue link will redirect them back to the question page where the next question is displayed.



From stuff that I've done before, I am attempting to use the isset() function to make this happen. However, the problem is that I'm not sure how exactly to write my isset().



I've found this snippet from this site, I'm not sure if it's useful, but:



if (!isset($_SESSION['FirstVisit'])) {

//show site for the first time part
$_SESSION['FirstVisit] = 1;
header("Location: http://example.com/index.php");

// Don't forget to add http colon slash slash www dot before!

} else { Show normal site }


But once again I found myself blank. How exactly do I use the isset() to display only one question?





Can I get the table, column and type information from a model?

I'm using ruby and activerecord to get information about a mysql table.



I was hoping I could get this information directly from my model class, is this possible?



Say I have my model:



class Product < ActiveRecord::Base
end


Is it now possible for me to get information regarding:



1. mysql table
2. columns
3. column types


Or do I have to look somewhere deeper into the ActiveRecord module to get this?





CUDA: bad performance with shared memory and no parallelism

I'm trying to exploit shared memory in this kernel function, but the performance are not as good as I was expecting. This function is called many times in my application (about 1000 times or more), so I was thinking to exploit shared memory to avoid the memory latency. But something is wrong apparently because my application became really slow since i'm using shared memory.

This is the kernel:



__global__ void AndBitwiseOperation(int* _memory_device, int b1_size, int* b1_memory, int* b2_memory){
int j = 0;

// index GPU - Transaction-wise
unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int tid = threadIdx.x;

// shared variable
extern __shared__ int shared_memory_data[];
extern __shared__ int shared_b1_data[];
extern __shared__ int shared_b2_data[];

// copy from global memory into shared memory and sync threads
shared_b1_data[tid] = b1_memory[tid];
shared_b2_data[tid] = b2_memory[tid];
__syncthreads();

// AND each int bitwise
for(j = 0; j < b1_size; j++)
shared_memory_data[tid] = (shared_b1_data[tid] & shared_b2_data[tid]);

// write result for this block to global memory
_memory_device[i] = shared_memory_data[i];
}


The shared variables are declared extern because I don't know the size of b1 and b2 since they depend from the number of customer that I can only know at runtime (but both have the same size all the times).

This is how I call the kernel:



void Bitmap::And(const Bitmap &b1, const Bitmap &b2)
{

int* _memory_device;
int* b1_memory;
int* b2_memory;

int b1_size = b1.getIntSize();

// allocate memory on GPU
(cudaMalloc((void **)&b1_memory, _memSizeInt * SIZE_UINT));
(cudaMalloc((void **)&b2_memory, _memSizeInt * SIZE_UINT));
(cudaMalloc((void **)&_memory_device, _memSizeInt * SIZE_UINT));

// copy values on GPU
(cudaMemcpy(b1_memory, b1._memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));
(cudaMemcpy(b2_memory, b2._memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));
(cudaMemcpy(_memory_device, _memory, _memSizeInt * SIZE_UINT, cudaMemcpyHostToDevice ));

dim3 dimBlock(1, 1);
dim3 dimGrid(1, 1);

AndBitwiseOperation<<<dimGrid, dimBlock>>>(_memory_device, b1_size, b1_memory, b2_memory);

// return values
(cudaMemcpy(_memory, _memory_device, _memSizeInt * SIZE_UINT, cudaMemcpyDeviceToHost ));

// Free Memory
(cudaFree(b1_memory));
(cudaFree(b2_memory));
(cudaFree(_memory_device));
}


b1 and b2 are bitmaps with 4 bits for each element. The number of elements depend from the number of customers. Also, I have problem with the kernel's parameters, because if I add some blocks or threads, the AndBitwiseOperation() is not giving me the correct result. With just 1 block and 1 thread per block the result is correct but the kernel is not in parallel.

Every advice is welcomed :)

Thank you





Posting data to a HTTPS page

If I have a page outside of my site, and it posts to an HTTPS page on my site (SSL is setup), will the server and client exchange keys before the data is posted and then encrypt the data, or will the data be posted in plain text from the client to the server, then be given the key to encrypt?



Thank you,





Trying to bind the height/width of a grid to a ViewModel

So I have a grid inside a viewbox. Now the grid scales with the viewbox fine. However, I need to know the height and width of the grid in my ViewModel. However it doesn't seem to ever set the Height to anything?



<Viewbox VerticalAlignment="Top" Margin="5,20,5,0">
<Border BorderThickness="6" BorderBrush="Black" CornerRadius="2">

<Grid MinHeight="300" MinWidth="400" Height="{Binding Height, Mode=TwoWay}" Width="{Binding Width, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" >
<ItemsControl ItemsSource="{Binding Viewers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Grid>
</Border>
</Viewbox>


And in my ViewModel:



    private int _height;
public int Height
{
get
{
return _height;
}

set
{
_height = value;
OnPropertyChanged("Height");
}
}

private int _width;
public int Width
{
get
{
return _width;
}

set
{
_width = value;
OnPropertyChanged("Width");
}
}


Any ideas?





Triangle partitioning

This was a problem in the 2010 Pacific ACM-ICPC contest. The gist of it is trying to find a way to partition a set of points inside a triangle into three subtriangles such that each partition contains exactly a third of the points.



Input:




  • Coordinates of a bounding triangle: (v1x,v1y),(v2x,v2y),(v3x,v3y)

  • A number 3n < 30000 representing the number of points lying inside the triangle

  • Coordinates of the 3n points: (x_i,y_i) for i=1...3n



Output:




  • A point (sx,sy) that splits the triangle into 3 subtriangles such that each subtriangle contains exactly n points.



The way the splitting point splits the bounding triangle into subtriangles is as follows: Draw a line from the splitting point to each of the three vertices. This will divide the triangle into 3 subtriangles.



We are guaranteed that such a point exists. Any such point will suffice (the answer is not necessarily unique).



Here is an example of the problem for n=2 (6 points). We are given the coordinates of each of the colored points and the coordinates of each vertex of the large triangle. The splitting point is circled in gray.



enter image description here



Can someone suggest an algorithm faster than O(n^2)?





jquery output id display as [object object]

var str = prompt("What is your name?");
var str1=$(str).html('<b>'+str+'</b>');
alert(str1);


By above code I'm getting [object object] as output ,. please help





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