Monday, April 30, 2012

php get file extention

I wish to get an extension of an image I am uploading but I just get an array back. Is there a way to just get the extension itself



     $userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(".", strtolower($_FILES['image']['name']));




Venn Diagram Drawing Algorithms

Someone was asked about overlapping subclusters in GraphViz and got the following response:




Sorry, no. General subgraphs can share nodes without implying subset
containment but not clusters. The problem is in the drawing.
If clusters can overlap arbitrarily, drawing them becomes the problem
of drawing Venn diagrams, for which there are no good algorithms.




What is a formal definition or example of the "problem of drawing Venn diagrams"?, and why is it (I assume NP-complete/hard) hard ? (Extra points: Sketch a reduction to a well-known NP-complete problem)





ICU's MessageFormat on iOS

It is my understanding that iOS uses ICU under the hood. I'd like to access the functionality of ICU's MessageFormat for strings involving numbers and plurals, for example,



There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.


Does iOS expose this capability? If so how do I use it? I thought I might be able to write



[NSString stringWithFormat: "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.", n];


or



[NSString stringWithFormat: "There {0,plural, =0{are no files}=1{is one file}other{are %ld files}}.", n];


But these formats (ICU4J and ICU, respectively) do not work.





Select statement for xdoc query

I am trying to add a sub category to Messages in my xml statement Is there a way I can do this GroupMessages -> Message -> GroupMessage :



        var groups = xDoc.Descendants("Group")
.Select(n => new
{
GroupName = n.Element("GroupName").Value,
GroupHeader = n.Element("GroupHeader").Value,
TimeCreated = DateTime.Parse(n.Element("TimeAdded").Value),
Tags = n.Element("Tags").Value,
Messages = n.Element("GroupMessages").Value
//line above
})
.ToList();


In my method GroupMessages contains both MessageID and GroupMessage and it is listing both in my datagrid within the one container. So I tryed this but it lists nothing:



 Messages = n.Descendants("GroupMessages").Select(nd => nd.Element("GroupMessage").Value)


My xml looks like this:



<Group>
<TimeAdded>2012-04-27T10:23:50.7153613+01:00</TimeAdded>
<GroupName>Group</GroupName>
<GroupHeader>Header</GroupHeader>
<GroupMessages>
<Message>
<MessageID>1</MessageID>
<GroupMessage>Message</GroupMessage>
<MessageGroup/>
</Message>
</GroupMessages>
</Group>


I have also tryed:



Messages = n.Descendants("GroupMessages").Select(nd => nd.Descendants("Message").Select(nde => nde.Element("GroupMessage").Value))


To no avail?





Ideal Skip list ? O(n) run-time?

I'm trying to find the best algorithm for



converting an "ordinary" linked list 
into an `ideal skip list`


.



Where the definition of an ideal skip list is that in the first level we'll have all
the elements , in the level above - half of them , the one after - quarter of them ... and so on .



I'm thinking about O(n) run-time where involving throwing a coin for each node in
the original linked-list , whether or not for a specific node , should I go up or not , and create another duplicate node for the current node upstairs ...
Eventually this algorithm would produce O(n) , is there any better algorithm ?



Regards





how to control a combo box by using another combo box swing

I have two combo box the items first one is (women and men).I want when user select women in first combo box the list of women's dress will appear in second combo box and when men is selected the list of men's dress will appear in second one.Can do this functionality by using JCombo box? if yes how can I do that give me example please.
any help will be appreciated.





Populate UITableView with custom objects?

I am unsuccessfully trying to populate a UITable from a NSMutableArray that contains a custom object.



My Student object



Student {
NSString name,
int age
}


In UITableView there is a method that displays the row's content:



cellForRowAtIndexPath
{
// there is more code here
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}


Should my Student class implement a method that returns a String representation of the object? And then how can I display the content of the NSMutableArray in the UITableView.



Any help will be appreciated.





Counting the number of DIVs placed into a DIV via drag and Drop

I have had a look about the site and found some code and tried it out but its not working in any shape or form.



I am wanting to count the number of DIVs thats placed into another DIV by the user dragging and dropping but only to count the 'correct' ones then if all the correct ones are in the DIV display an alert saying well done then rest the 'game'. Also need to show how many more is needed to go to 'win'.



This is what I have so far:



JS:



    $('.drop').each(function(){ 
var n = $(this).children('.draggable').length;
$(".count").text("There are " + n + " divs inside parent box detail.");
if(n == 2){
alert("You got them all right! :)");
}
});


HTML:



    <div class="foods">
<div class="draggable" id="draggable"><img src="images/fish.png" id="draggable"></div>

<div class="draggable" id="draggable"><img src="images/stone.png"></div>

<div class="wrong"><img src="images/tree.png"></div>
</div>

<div class="foods">
<div id="droppable" class="drop">
<p>Drop here</p>
</div>
</div>

<div class="foods">
<span class="count"></span>
</div>


JS Fiddle of the code: http://jsfiddle.net/JRLZK/



Thanks in advanced for any help!





malformed start tag error - Python, BeautifulSoup, and Sipie - Ubuntu 10.04

I just installed python, mplayer, beautifulsoup and sipie to run Sirius on my Ubuntu 10.04 machine. I followed some docs that seem straightforward, but am encountering some issues. I'm not that familiar with Python, so this may be out of my league.



I was able to get everything installed, but then running sipie gives this:



/usr/bin/Sipie/Sipie/Config.py:12: DeprecationWarning: the md5 module is deprecated; use hashlib instead import md5

Traceback (most recent call last):
File "/usr/bin/Sipie/sipie.py", line 22, in <module>
Sipie.cliPlayer()


File "/usr/bin/Sipie/Sipie/cliPlayer.py", line 74, in cliPlayer
completer = Completer(sipie.getStreams())


File "/usr/bin/Sipie/Sipie/Factory.py", line 374, in getStreams
streams = self.tryGetStreams()


File "/usr/bin/Sipie/Sipie/Factory.py", line 298, in tryGetStreams
soup = BeautifulSoup(data)


File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup-3.1.0.1-py2.6.egg/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)


File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup-3.1.0.1-py2.6.egg/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)


File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup-3.1.0.1-py2.6.egg/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)


File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)


File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)


File "/usr/lib/python2.6/HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)


File "/usr/lib/python2.6/HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")


File "/usr/lib/python2.6/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())


HTMLParser.HTMLParseError: malformed start tag, at line 100, column 3



I looked through these files and the line numbers, but since I am unfamiliar with Python, it doesn't make much sense. Any advice on what to do next?





Handling sessions with procedural PHP

I would like to dedicate this page to handling sessions using procedural php.



I'll begin with how I start most of my projects:



session_name('Easy_App');
session_start();

if (!isset( $_SESSION['ip'] )){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

if (!isset( $_SESSION['created'] )){
$_SESSION['created'] = time();
}

if (!isset( $_SESSION['overall_views'] )){
$_SESSION['overall_views'] = 1;
}
else {
$_SESSION['overall_views']++;
}

if (!isset( $_SESSION['username'] )){
$_SESSION['username'] = "";
}

if (!isset( $_SESSION['logged_in'] )){
$_SESSION['logged_in'] = 0;
}

/*A quick method to keep pageviews to < 5 pages per 1 second per session*/
if (!isset($_SESSION['first_action'])){
$_SESSION['first_action'] = time();
}

$first_action = $_SESSION['first_action'];
if (!isset( $_SESSION['action'] )){
$_SESSION['action'] = 1;
}
else{
$_SESSION['action']++;
}

$action=$_SESSION['action'];
if ($action>=5){
unset($_SESSION['action']);
unset($_SESSION['first_action']);
if((time() - $first_action) <=1){
exit("Please Don't Hammer My Site ");
}
}


So We have a starting point:




  1. The Start of a session with a few regularly used parameters

  2. In the last few lines, prevention of hammering by casual users.



My question is this:



Where would you go from here? Improvements of the above code or a brief snippet of how you handle sessions using procedural php would be greatly appreciated.





dpi for downloadable images

its simple my doubt.
The app have 4 directories(ldpi, mdpi, hdpi, xhdpi) with same images but different dpi . For mdpi is 160dpi, the one im using atm.



What happens with the images i download from the web? i have a news reader and that means each new have one image at least. And i want to have a decent image for all the smartphones.



Do i need different type of images or just download the same for all?
Can i know which resolution is best for each particular smartphone?



I couldn't find the "official" way to handle this so i dont know if its important dpi for images that we plan to download.



Regards!





Algorithm Complexity Time

I am currently having trouble identifying and understanding the complexity time of the following algorithm.



Background: There is a list of files, each containing a list of candidate Ids. Both, number of files and number of candidates within them are not fixed.



How would you calculate the time complexity for an algorithm which is responsible for:
Reading each file and adding all the unique candidate Ids into a Hashset?



Thanks.





Python: How can add words to a list?

Okay, the Title is a bit vague, but what I'm trying to do is download data online, parse it and then put the parsed 'data' into an excel file.



I'm getting stuck in trying to put the data into a vector or list. Note that, the data can be either words or numbers. Also, I the length of the data is unknown. I tried the code below:



class MyHTMLParser(HTMLParser):
def handle_data(self, data):
d=[]
d=d.append(data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')

d

Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
d
NameError: name 'd' is not defined


I looked around the forum for an answer, but didn't seem to encounter anything. I am a beginner, so may I'm missing something basic? Thanks, for the help...





android xml loads fine in api 8 with WVGA, but crashes with api 14 with WXGA720 (tablet)

The program loads ok, and I can go through a couple screens, but when the main.xml tries to load, the program crashes only on api 14.



logcat output:



04-26 09:02:14.290: E/AndroidRuntime(566): FATAL EXCEPTION: main
04-26 09:02:14.290: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.surreall.yacht/com.surreall.yacht.yatzee}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread.access$600(ActivityThread.java:122)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.os.Handler.dispatchMessage(Handler.java:99)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.os.Looper.loop(Looper.java:137)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread.main(ActivityThread.java:4340)
04-26 09:02:14.290: E/AndroidRuntime(566): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 09:02:14.290: E/AndroidRuntime(566): at java.lang.reflect.Method.invoke(Method.java:511)
04-26 09:02:14.290: E/AndroidRuntime(566): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-26 09:02:14.290: E/AndroidRuntime(566): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-26 09:02:14.290: E/AndroidRuntime(566): at dalvik.system.NativeStart.main(Native Method)
04-26 09:02:14.290: E/AndroidRuntime(566): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.createView(LayoutInflater.java:606)
04-26 09:02:14.290: E/AndroidRuntime(566): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:653)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
04-26 09:02:14.290: E/AndroidRuntime(566): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.Activity.setContentView(Activity.java:1835)
04-26 09:02:14.290: E/AndroidRuntime(566): at com.surreall.yacht.yatzee.onCreate(yatzee.java:211)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.Activity.performCreate(Activity.java:4465)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
04-26 09:02:14.290: E/AndroidRuntime(566): ... 11 more
04-26 09:02:14.290: E/AndroidRuntime(566): Caused by: java.lang.reflect.InvocationTargetException
04-26 09:02:14.290: E/AndroidRuntime(566): at java.lang.reflect.Constructor.constructNative(Native Method)
04-26 09:02:14.290: E/AndroidRuntime(566): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.LayoutInflater.createView(LayoutInflater.java:586)
04-26 09:02:14.290: E/AndroidRuntime(566): ... 23 more
04-26 09:02:14.290: E/AndroidRuntime(566): Caused by: java.lang.OutOfMemoryError
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.Bitmap.nativeCreate(Native Method)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.Bitmap.createBitmap(Bitmap.java:605)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.Bitmap.createBitmap(Bitmap.java:551)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:437)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:524)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.content.res.Resources.loadDrawable(Resources.java:1937)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.View.<init>(View.java:2780)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.view.ViewGroup.<init>(ViewGroup.java:385)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.widget.LinearLayout.<init>(LinearLayout.java:174)
04-26 09:02:14.290: E/AndroidRuntime(566): at android.widget.LinearLayout.<init>(LinearLayout.java:170)
04-26 09:02:14.290: E/AndroidRuntime(566): ... 26 more


i can't post the contents of main.xml due to the 30k character question limit on stack overflow, and it is more than that. suggestions of where to start?





How to store the id from the one table to another in ruby on rails 2

Hello i'm trying to make a simple review function on ruby on rails. i have create a scaffold with the following attributes




event_id:integer name:string review_text:text no_starts:integer




Then i made this change on the show (view) of my event




:review, :action => :new, :id => @event.id %>


now i configured the routes fine and on the controller of the review i made this changes.
on the new i have added this




@review = Review.new(:event_id => params[:id])
and removed this
@review = Review.new




Then the page loads the event id it cites on the page but when i'm trying to save it is not stored. i thing the problem is when i move from the new method to create it doesnt transfer the id of the event thats why but i'm still what i'm doing wrong in the new?





update field values based on current field values content provider android

I cannot get to update the field values of a content provider as a function of current field values.
For a single column, I try to do



...
ContentValues values = new ContentValues();
values.put(TableInOut.INOUT, TableInOut.INOUT + " + 1"); (*)
int numRowsUpdated = getContentResolver().update(TableInOut.CONTENT_URI_PRESENCE, values, "time_details > lastSafeEpoch.toString()", null);
values.clear();
...


LogCat says that numRowsUpdated are the expected ones, but there is no update?!
Any ideas please?



(*)
No luck even with these



values.put(TableInOut.INOUT,  "88 + 1"); 
values.put(TableInOut.INOUT, "\"" +TableInOut.INOUT + "\"" + " + 1");


These work, but they do not use current values



values.put(TableInOut.INOUT,  77); 
values.put(TableInOut.INOUT, "77");




Change textblock from class#.cs windows phone

I want change text of textblock (or property of any object) by a class file. but when i call that class i just know name of object?



example:



<TextBlock VerticalAlignment="Top" HorizontalAlignment="Left" FontSize="25" Margin="25,220,0,0" Name="txbuser">Username :</TextBlock>


and i have file class.cs



how can i chan text obj when i just know Name obj is "txbuser"?
thanks all





mysql join query with sum retuns null

If article_payments table is null the query returns null. How shoul i set the query yo get recors if doesnt exist in SUM(payment_total) like 0.00 ?



SELECT article_name,user_real_name,user_name,SUM(`article_payment`) as holding,paid
FROM article_articles AS t1
JOIN article_users ON (t1.article_name=article_users.user_id)
JOIN (SELECT user_id,SUM(`payment_total`) as paid FROM article_payments GROUP BY user_id) AS t2 ON (t1.article_name=t2.user_id)
GROUP BY t2.user_id




how can I handle either-or with Rx?

I need to handle an either-or type situation with the Reactive-Extensions.



I have 2 events I'm receiving (A or B). When event A comes in followed by an event B within 2 seconds I want to generate a C. If an A is not followed by B then I'd like to generate a D.



Is there some way to express that with Rx??



Thanks





set values for 2nd selectbox from the selection of 1st selecbox

I have 2 select box as below. i want to make




  1. when user select A on 1st select box: only the value 100, 300 will appear on the 2nd select box

  2. when user select B on 1st select box: only the value 300, 900 will appear on the 2nd select box

  3. when user select C on 1st select box: only the value 100, 600, 900 will appear on the 2nd select box

  4. when user select D on 1st select box: only the value 100, 300, 900 will appear on the 2nd select box




    Select 1st
    A
    B
    C
    D


    Select 2nd
    100
    300
    600
    900






Tuesday, April 24, 2012

seperating strings by -

I have a string hai-welcome.



I need to split the above string using - separator:



mySstring = "hai-welcome"
Seperate as:



firstString = "hai"
secondString = "welcome.





How is it possible that I can use LastPass from more than one computer?

Tell me if I'm wrong: LastPass can never see my passwords, because they are encrypted with a key that stays in my own computer?



Then how is it possible that I can use my passwords from another computer?



My only guess is that the key is the password I use to login to LastPass, or at least it is generated based on it, so it is related in some way. So when I login to LastPass from another computer, they key same key is created in that computer.





https using BasicHttpBinding and ignoring certificate errors

I am using BasicHttpBinding to connect a web service hosted on a secured (https) port. To get it working, I have changed the Security.Mode to TransportWithMessageCredential and Security.Message to BasicHttpMessageCredentialType.Cerificate. I am also calling



client.ClientCredentials.ClientCertificate.SetCertificate()


with localhost as the subject name.



The issue here is that for unit testing, I have an unsigned certificate from the web server and am supposed to ignore any certificate error thrown during the proxy creation; but I am unable to do so, because I keep getting an error telling me to "specify a certificate". Right now, I am clueless; I appreciate any help here.





Unique CPU ID on Windows via C++

Well I would like to get an unique CPU ID so I can get an UNIQUE identification for each machine.
I did check __cpuid() from windows.h library, but the problem is that the ID it gets, it's the ID of all types of CPU, if you have an I3 Core processor and I have an I3 core processor, it will give the same "Unique ID".



Here is what I came up with to make a CPU ID from the __cpuid() that returns the same information on processors of the same type:



std::string GetCPUID(){

int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0);
if (CPUInfo[0] < 4)
return ""; //Error on retrieving

stringstream st;
for(int i = 0; i <= 3; i++){
st << CPUInfo[i];
}

return st.str();

}


I also checked a program called "Hardware ID Extractor" that works fine, it actually returns a UNIQUE CPU ID as the GUI as I wanted, so they made available a DLL so we can extract the CPU ID it generated , I tried everything with the cleanest code with the DLL and following their example but it seems that it returns nothing when ran on Windows 7. a lot of other people were complaining about this on Windows 7 via the DLL, even though the GUI on windows 7 returns the correct CPU ID.



Showing my work in the Hardware ID Extractor,



Here is the site where I downloaded the DLL (Where I chose the link of C++, VB, .NET): http://www.soft.tahionic.com/download-hdd_id/free-download/free%20download.html



And here is the DLL itself to download: http://www.soft.tahionic.com/download-hdd_id/free-download/DLL%20compressed/HardwareIDExtractorC.dll



This is the code I got from Hardware ID Extractor (I'm using Visual Studio 2008):



#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;

int main (){

char* (__stdcall *GetIDESerialNumber)(BYTE);

HINSTANCE DllInst = NULL;
if (DllInst == NULL) DllInst = LoadLibrary("C:\\HardwareIDExtractorC.dll");
if (DllInst) {
GetIDESerialNumber = (char* (__stdcall*)(BYTE))GetProcAddress(DllInst, "GetIDESerialNumber");

//Now call the imported function
cout << "SN: " << GetIDESerialNumber(0); // 0 = first IDE hard drive in your system
}else{
printf("Not Loaded");
}

_getch();



return 0;
}


In the visual studio output it shows that the DLL was executed by saying:



'Test.exe': Loaded 'C:\HardwareIDExtractorC.dll', Binary was not built with debug information.


And the program output that I get is: Not loaded



Someone know what I can do to get a CPU ID Unique, like in the application Hardware ID Extractor? I need to get a CPU ID because if I get HDD information, the user may format their Hard Drive and the program will stop working, as I'm designing it to work only that specified computer.



I'm using Windows 7 32 bits Ultimate and Intel I3 Core Processor (if that helps in anyway).



I hope I was clear in my question.
Thanks in advance!





Send data to an android device through a text input form php

Here is the idea:



enter image description here



The user types in a command which it has to be send to an android device.



Then the android device runs the command and returns the result to the php page which displays the result in the page!



I have tried with sockets but with no luck(i wanted to keep a connection alive until the closure of the page).



I know how to run commands in my android device:



Runtime.getRuntime().exec( command,args);


And I also know how to send data to the php server:



HttpPost httppost = new HttpPost("http://192.168.10.21/epl371/index.php?"); 

etc...


The problem is that I want to send data to the android device first via the text box after pressing the submit button.



Is there a way to do this? Is HttpPost a wrong way to do this?



I have tried so many things like:



URL url = new URL(SERVER_URL);
URLConnection connection = url.openConnection();

etc..




Flex keyboard Event

I jus want to know, In Flex Datagrid If the pressed key is Enter, stop the propagation and dispatch a fake Tab Event.



Any suggesstion,
Thankxx





Base64 Encoding Images in CSS

I am writing a little project to parse a CSS file, and base64 encode all the background images.



While I am able to parse the CSS correctly, it seems that everytime I try to convert the image file into a base64Encoded string, the string returned is always exactly the same.



What am I doing wrong?



Here's the encoder. Please assume that all image paths are passing correctly to the method. In this instance, all images are fully qualified urls, so the first section of the method is what is doing the conversion.



Public Sub EncodeImage(ByVal _File As String)
If _File.StartsWith("http") OrElse _File.StartsWith("https") Then
Using _wc As New WebClient()
Common.SetAllowUnsafeHeaderParsing20()
_wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13")
_wc.DownloadFile(_File, "c:\temp.png")
Dim _d As Byte() = _wc.DownloadData(_File)
ImageStrings.Add(New ImageTyping() With {
.SourceFile = _File,
.Base64String = Convert.ToBase64String(_d)
})
_d = Nothing
End Using
Else
Using _fs As New FileStream(_File, IO.FileMode.Open)
Using _br As New BinaryReader(_fs)
Dim _i As Byte() = _br.ReadBytes(_fs.Length)
ImageStrings.Add(New ImageTyping() With {
.SourceFile = _File,
.Base64String = Convert.ToBase64String(_i)
})
_i = Nothing
_br.Close()
End Using
_fs.Close()
End Using
End If
End Sub


Each and every string returned from this is: iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAAGXcA1uAAAAKUlEQVRIx2P4//+/DwwzUJUzoiRGNYxqGNUwGDSMWjBqwagFoxbQAAMAfS9kqktT8qQAAAAASUVORK5CYII=





Bring a view back to other iphone

I want to place a view(firstView) back to another view(secondView). SecondView is basically a barchart using CGContext. I guess i can't use bringViewToFront there. So I need to place firstView back to secondView. Is there some default function to place a view back to some other view?



Thanks,

Nitish





Best way to go from tuple pairs of numbers to one tuple of all the individual numbers

How can i get this



nums = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]


to this?



[0, 1, 2, 3, 4, 5, 6, 7, 8]


I did:



>>> zip(*nums)[0]
(0, 1, 2, 3, 4, 5, 6, 7)


But it gives me everything except the last element and then i had to use some bad code to get it to the correct result so i was looking for an elegant solution.





Handling component links and retrieving the values from the fields of linked component in Dreamweaver TBB

I am working on Dreamweaver TBBs in SDL Tridion 2011 SP1.



I am unaware of handling component links in Dreamweaver TBBs.



Consider my Component name is "A" which has link to another component "B".



Component A source looks like this:



<Content xmlns="Some UUID">
<Name xlink:type="simple" xlink:href="tcm:184-1897"
xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="B"></Name>
</Content>


Component B source is:



<Content xmlns="Some other UUID">
<first>first field</first>
<second>second field</second>
</Content>


I want to write a DWT TBB which can access the fields in the linked component B from Component A.



I want to use RenderComponentField rendition method.



Do I need to add any extentions to it, will I be able apply SiteEdit on it.



Please share your views on it.



Thank you.





how to fix this issue with advanced search codeignitor

i want to build advanced search script but i have this error with search_all function in the model



A PHP Error was encountered

Severity: 4096

Message: Object of class CI_DB_mysql_result could not be converted to string

Filename: models/search_model.php

Line Number: 129


i have four fildes
1- input text to write the book name
2- select box for the author
3- select box for the publisher
3-select box for the section



the model is



class search_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/* This function get all search in database sort by order asc.*/

function get_new_one($id)
{

$this->db->where('ne_id',$id);

$result=$this->db->get('d_search');

return $result->row();

}
//////////////frontend//////////////////////////////////////////////////////////

function show_new($id)
{

$result=$this->db->query("SELECT * , COUNT( d_comments_search.cn_new_id ) as count

FROM d_search

left JOIN d_comments_search ON d_search.ne_id = d_comments_search.cn_new_id and d_search.ne_hide='1'

inner join d_search_category on d_search_category.nc_id = d_search.ne_category_id and d_search_category.nc_hide= '1'

and d_search.ne_id= $id group by d_search.ne_id");

return $result->row() ;

}

function generate_results($keyword,$row=0){
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1' limit $row,20");
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1' limit $row,20");
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1' limit $row,20");
$results = array_merge($result1->result_array(),$result2->result_array(),$result3->result_array());

return $results;

}

// get total number of users
function getNumUsers($keyword)
{
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1'");
$result1 = $result1->num_rows();
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1'");
$result2 = $result2->num_rows();
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1'");
$result3 = $result3->num_rows();
return $result1 + $result2 + $result3;
}
//////////////////////////////////end paging///////////////////

function get_publishing()
{
$this->db->where('pub_state','1');
$result=$this->db->get('d_publishing')->result_array();
return $result;
}

function get_author()
{
$this->db->where('au_state','1');
$result=$this->db->get('d_author')->result_array();
return $result;
}

function get_section()
{
$this->db->where('sec_state','1');
$result=$this->db->get('d_section')->result_array();
return $result;
}

function search_name()
{
$bo_name=$_POST['bo_name'];
$this->db->order_by("bo_ord","asc");
$this->db->like('bo_name',$bo_name);
return $this->db->get('d_book')->result_array();

}


function search_all() {
$publish = $this->input->post('publish');
$author = $this->input->post('author');
$sec_name = $this->input->post('section');

$sql = $this->db->query("SELECT * FROM `d_book`");
$searches = array();
if ($publish != 'choose')
$searches[] = "`bo_pub_id` = '$publish'";
if ($author != 'choose')
$searches[] = "`bo_au_id` = '$author'";
if ($sec_name != 'choose')
$searches[] = "`bo_sec_id` = '$sec_name'";
if (count($searches) > 0) {
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';


}


}


this is controller



class Search extends front_end {
var $temp;

function __construct(){
parent::__construct();
$this->load->library('form_validation');
//echo $this->input->post("keyboard");

}

public function index()
{
$this->overview();
}

/**
* This function display all search
* @param integer $row
*/
public function overview($row=0)
{
$this->form_validation->set_rules('keyword', 'كلمة اÙ„بحØ«', 'trim|required|xss_clean|htmlspecialchars');
$this->form_validation->run();
$this->store_keyword();
//echo $this->session->flashdata('keyword');
if ($this->session->flashdata('keyword') != ''){
$keyword=$this->session->flashdata('keyword');
$this->generate_results($this->session->flashdata('keyword'),$row);
}else{
$this->generate_results($this->input->post("keyword"),$row);
}
//$this->session->set_flashdata('keyword', $this->input->post("keyword"));
$data = $this->temp;

//$this->session->keep_flashdata('keyword');
$this->view('search/site/results', $data);
}

/**
* This function generate result of search
* @param string $keyword
* @param integer $row
*/
public function generate_results($keyword,$row=0){
$this->load->model('search/search_model','search');
$this->load->library('pagination');
$config['base_url'] = base_url().'search/search/overview/';
$config['total_rows'] = $this->search->getNumUsers($keyword);
$config['per_page'] = '20';
$config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['page'] = $row;
$data['results'] = $this->search->generate_results($keyword,$row);
$data['total_rows'] = $this->search->getNumUsers($keyword);
$data['links']=$this->pagination->create_links();
$this->temp = $data;

}

/**
* This function display detail of new
* @param integer $id
*/
public function show($id)
{
$data['new']=$this->search->show_new($id);
$count=$data['new']->ne_count_visit;
$this->search->add_count($count,$id);
$data['comments']=$this->search->show_comments($id);
$this->view('site/new', $data);
}

/**
* This function store keyword to use in search
*/
private function store_keyword(){
if($this->input->post("keyword")){
$this->session->set_userdata('keyword', $this->input->post("keyword"));
}
}


public function search_form()
{
$this->load->model('search/search_model','search');
$data['publish']=$this->search->get_publishing();
$data['author']=$this->search->get_author();
$data['section']=$this->search->get_section();
$this->view('search/site/adv_search_form',$data);
}

public function search_adv()
{
$this->load->model('search/search_model','search');
$data['bo_name']=$this->input->post('bo_name');
$data['section']=$this->input->post('section');
$data['publish']=$this->input->post('publish');
$data['author']=$this->input->post('author');
$data['result1'] = '';
$data['result2'] = '';
$data['result3'] = '';
$data['result4'] = '';
if($data['bo_name'] == NULL and $data['section']== NULL and $data['publish']==NULL and $data['author']== NULL){
$this->search_form();
}else{
if(isset($data['bo_name']) and $data['bo_name']!= NULL)
{
$data['result1'] = $this->search->search_name();
}
if(isset($data['section']) and $data['section'] != NULL)
{
$data['result2']=$this->search->search_all();
}
if(isset($data['publish']) and $data['publish'] != NULL)
{
$data['result3']=$this->search->search_all();
}
if(isset($data['author']) and $data['author']!= NULL)
{
$data['result4']=$this->search->search_all();
}
$data['no_results'] = '';
if(! $data['result1'] && !$data['result2'] && !$data['result3'] && !$data['result4']){
$data['no_results'] = TRUE;
}else{
$data['no_results'] = FALSE;
}
$this->view('search/site/search_result',$data);
}
}
}

/* End of file dashboard.php */




Clipboard monitoring on Mac OS X | Java

I'm having troubles getting data from the system clipboard on Mac OS X.
What I'm trying to do is to listen to the system clipboard and print the content of the clipboard each time new [text based] information is put into it.



The problem: bellow code works perfectly fine on Windows 7 and openSuse Linux machines, however when I try running the same code on Mac OS X the program fails to print the new content of the clipboard until focus is given to the application. [Nothing is printed until I click on the application icon on the dock...]



My source code:



import java.awt.Toolkit;  
import java.awt.datatransfer.*;
import java.io.IOException;

public class ClipboardListener extends Thread implements ClipboardOwner {

Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

public void run(){
Transferable selection = systemClipboard.getContents(this);
gainOwnership(selection);
}

public void gainOwnership(Transferable t){
try {this.sleep(100);}
catch (InterruptedException e) {e.printStackTrace();}
systemClipboard.setContents(t, this);
}

public void lostOwnership(Clipboard clipboard, Transferable contents) {
try {System.out.println((String) clipboard.getData(DataFlavor.stringFlavor));}
catch (UnsupportedFlavorException e) {}
catch (IOException e) {}
gainOwnership(contents);
}
}





public class myApp {

public static void main(String[] args){
ClipboardListener listener = new ClipboardListener();
listener.start();
while(true){}}

}


What I'm missing/doing wrong?



[Update]
I found similar problem posted here: Java thread goes to sleep when not in focus on OSX
However using the command "java -jar myApp.jar &" didn't work as a workaround for me.





can i get to related textbox code in ollydbg?

how i can get to related text-box code in ollydbg?



example : i need text-box code in ollydbg but don't find this.
can this into the memory?
this program design by adobe director and need activation code, this code is unique and related to hardware id



thank you





Best pratices for Filtering CoreData records via UiControls

Im building an app where users will be able to filter through a set of photos based on 4 parameters:



param1 and param2 can be one of three possible values respectively. param3 and param4 can contain multiple 'tags' if you will that describe the photo. I have the ui setup where for param1/param2 a series of uiswitches represents each of the three chooses for each param. If you turn one value on, the other two will turn off. However all off should return all photos assuming no values for param3 or param4 are set



Params3/4 have UiButtons that can be made selected/normal. Any selected should be added to the filtering to narrow results.



I can't seem to figure out how I should write the filtering logic to be most effective. Essentially on any control change, I need to rewrite the predicate filter but I can't seem to wrap my head around how I can link the separate param filters together.



For param3/4 I'd also like to add a disabled state for uibuttons that have no records, or no records based on the currently selected buttons.



Can anyone help point me in the right direction?





Get and set value of TextField

I have this code for view:



App.TodoView = Em.View.extend({
labelView: Em.TextField.extend({

}),
createNew:function () {
console.log(this.labelView.get('value'));
}
});


and this template:



{{#view App.TodoView}}    
{{view labelView}}
{{#view Em.Button target="parentView" action="createNew"}}Add{{/view}}
{{/view}}


And I get the following error:



Uncaught TypeError: Object (subclass of Ember.TextField) has no method 'get'


I want to use insertNewLine method too, so I can set the value of the Em.TextField in template.





Parse and translate classic ASP & ASP.NET website

I have a site with a bunch of (pretty ugly) classic asp pages, as well as a number of ASP.NET web forms pages. I need to be able to set it up so the user can flip a switch and translate the whole site to French.



Unfortunately, the requesting client does not want us to use something simple like google translate, they want to be in control of the dictionary to prevent errors in grammar, etc. This means I have to overcome two problems.



First, I need to parse out all of the hard coded text on the website that would be visible to the client and put it into a spreadsheet so they can translate it to their liking and send it back. I was trying to use the Html Agility Pack to do this with the classic code, but was having trouble handling cases where there are server tags (which there are an obscene amount of).



Second, I need a solution that will use this dictionary to translate the text, in both classic and ASP.NET.



I'm thinking the dictionary will be in XML, and could do the translation on the client side, so it will not have to deal with the server tags issue and will work in both classic and .NET, but I'm completely open to suggestion. If anyone has any ideas or knows of any kind of solution that will help me with one or both of my problems, I'd greatly appreciate any help. Thanks





Repeating Button - If you keep it depressed, it keeps firing a function

I am not sure what to call this, all I can think of is a Repeater Button.



I want to press a button and it fires a function immediately once, eg MyZoom(InOrOut).



But if I keep the mouse button depressed it will keep firing that MyZoom(InOrOut) every one tenth of a second until I release the mouse button.



As you can probably guess from the function name, I will have 2 buttons, a zoom in and a zoom out. They will call MyZoom(-1) to make it smaller and MyZoom(1) to make it bigger.



<button onclick="MyZoom(-1);">Zoom Out</button>
<button onclick="MyZoom(1);">Zoom In</button>


How can I change this to include the repeating effect?





How to load php file through jQuery without advertising your technology

Nowadays, Developers and Professionals tend to use PHP templates because of two reasons. They are manageable and secondly, we don't need to advertise our technology as there are no question marks and .php extensions within the URL.



But how to make non-advertisement of your technology possible while sending a jQuery Ajax request to load a PHP file in a div. I mean we would, have to write $.get('phpfile.php') within the script and one can say that voa he is using PHP hmmmm.



Simply, I want to ask is there is any way of loading a PHP through request without advertising your technology as above told.



Some coding will be honored.





Issues about stepping through the code of a process on mac os x

In by debugger process, by using ptrace(PT_STEP,childPid,0,0), tell the OS to restart the child process, but stop it after it executes the next instruction.



But seems that the result is not right. Child process do not executes the next instruction,but in my debugger process, i called wait(&statue) after the call:ptrace(PT_STEP,childPid,0,0).



wait(&wait_status);
while (WIFSTOPPED(wait_status)) {
if (ptrace(PT_STEP, child, 0, 0) < 0) {
perror("ptrace");
return;
}
wait(&wait_status);
//Read the data using vm_read at address:0x10046 in process debugie's memory space,compare with the orig value.
//But, the new value is always same as the orig value!!!
}


In debugie process, i set: data= data*10; the data's address is 0x10046.
After several steps,the new value should be different from the orig value, i changed data's value several time in debugie process.



I test it on Mac os x, but it's a virtual machine(Virtual Box).





Java: Format double to String with K, M, B

999 to 999
1000 to 1k



1500000 to 1.5m



and so on, I would like to not lose any precision at all



Also, need to convert them back to their original value



1.5m to 1500000
etc



The highest it would go is 11 digits max



Thanks





Monday, April 23, 2012

C++ cli access Form variables from class

There is a form Form1 which contains int x; and a class MyClass with .h and .cpp files. How can I access the Form1 variable x from MyClass, without passing it using a method? I think something like Form1.x Maybe is it a bad style of programming?
I am just learning..





How do I get the host and port in a Rails applicaiton

Feel pretty dumb with this question.



In a Rails Model, I want to be able to find out the host and port. For example, if I am in a test environment it would return http://localhost:3000/ and if I was in production it would return something like http://my.application.com/?



Is this even possible?



Thanks!



jt





firefox position absolute inside a relative container issue

i am using table for displaying my dynamically generated data depend upon the user input the html structure is looks like below:



<table>
<tr>
<td>.....</td>
<td>.....</td>
<td style="position:relative;"> //like this i set for all td in table
<div style="position:absolute">//like this i set for all div in table
<contents>
</div>
</td>
<td>.....</td>
<td>.....</td>
</tr>
</table>


Here the div is goes to top corner of the body.all these above styles are applied throght the javascript and its working fine in chrome,IE,but not in FF like the image below



![enter image description here][1]


if we change the position of the div to absolute to relative it will align correctly but i am make a hover effect while the user hover the div's for that the positions are important and this issue happens only in firefox





facebook like button pop up - "post to facebook"

I implemented facebook like button.
First problem is following: when i click LIKE facebook button additional window pops up and and asks me if I want to post the article I read on facebook. What is bad about that is how this is presented. it seems that somehow it takes h1 tag that is "behind" it when it pops up. The content inside h1 tag is KATEGORIJE and that is displayed inside facebook pop up. I believe if you look at the picture it will be much more clearer http://tinypic.com/r/f58601/5



The second problem is that I defined facebook open graph meta tags but when I click I like the article I read in the pop up fb window I get: "you like 'ovdje ide naslov'"
i don't know from where I'm getting this. Can't find any line of code where I defined "ovdje ide naslov"





facebook like button pop up - "post to facebook"

I implemented facebook like button.
First problem is following: when i click LIKE facebook button additional window pops up and and asks me if I want to post the article I read on facebook. What is bad about that is how this is presented. it seems that somehow it takes h1 tag that is "behind" it when it pops up. The content inside h1 tag is KATEGORIJE and that is displayed inside facebook pop up. I believe if you look at the picture it will be much more clearer http://tinypic.com/r/f58601/5



The second problem is that I defined facebook open graph meta tags but when I click I like the article I read in the pop up fb window I get: "you like 'ovdje ide naslov'"
i don't know from where I'm getting this. Can't find any line of code where I defined "ovdje ide naslov"





android - fragments flow managing

I have a special flow of fragments in my app, so I need to be able to switch to any fragment, while keeping fragments in memory whenever possible (so if it's tight on memory, it's ok that the fragment will be released).



So far, I've succeeded doing a replace of the current fragment, but the thing is that the previous fragment is always being destroyed, so if I go back to it (using the action bar, for example), it's re-created and that takes some time.



The reason I use fragments instead of activities is the nice usage of the action bar, the ability to put multiple fragments inside the same container, the non-flexible activities-intents usage, etc...



The reason why I don't use the "Back" stack is that I wish to go to any fragment from any fragment, since the flow can change.



Here's a snippet of my code:



Fragment fragment=... ; //get the fragment from cache or create if not available yet...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainActivity_fragmentContainer, fragment).commit();


I have also tried to use ViewPager, but since I don't want to have the sliding effect (which allows you to slide to other fragments) and since one of the fragments already include a viewPager, it's an obstacle. Disabling the sliding effect on the main viewPager somehow disables it on the other one.



BTW, I'm using the android support library for the fragments and not the native API.



my question is:
how can i achieve full control of which fragment to go to , while maximizing speed and avoiding too much memory being used for fragments ?






EDIT:
for now , i use the next workaround :
for the onDestroyView , i take the parent of the created view and remove the created view from there .



for the onCreateView , if i already have the created view from before , i return it .



however , i think it's a very risky thing to do , since i'm not sure of how fragments managing work , so it might cause weird problems . plus ,i'm not sure what will happen if android decides that it has low memory - will it destroy unused fragments (which is good) or will it cause out-of-memory exceptions (which is bad) .





Simulating Google app engine maintenance period in development environment

During scheduled maintenance period outages, the high replication datastore will work normally, but memcache will not be available.



Is there a way this scenario can be simulated in local development environment?



More specifically, can we run dev_appserver.py with memcache disabled to test the maintenance period behavior?



As of now, I go to development console and flush out the memcache after every request, to get a rough idea of how the app behaves during server maintenance. I am hoping there must be some better way to test this scenario.





Simulating Google app engine maintenance period in development environment

During scheduled maintenance period outages, the high replication datastore will work normally, but memcache will not be available.



Is there a way this scenario can be simulated in local development environment?



More specifically, can we run dev_appserver.py with memcache disabled to test the maintenance period behavior?



As of now, I go to development console and flush out the memcache after every request, to get a rough idea of how the app behaves during server maintenance. I am hoping there must be some better way to test this scenario.





Learning Ruby, Looking for Possible Refactoring for If Statement

I've got a few ideas but wanted to get a few other options. Here is the ugly:



    def normal_balance
if type.to_s == 'Asset' or type.to_s == 'Expense'
if contra
"Credit"
else
"Debit"
end
else
if contra
"Debit"
else
"Credit"
end
end
end




android - fragments flow managing

I have a special flow of fragments in my app, so I need to be able to switch to any fragment, while keeping fragments in memory whenever possible (so if it's tight on memory, it's ok that the fragment will be released).



So far, I've succeeded doing a replace of the current fragment, but the thing is that the previous fragment is always being destroyed, so if I go back to it (using the action bar, for example), it's re-created and that takes some time.



The reason I use fragments instead of activities is the nice usage of the action bar, the ability to put multiple fragments inside the same container, the non-flexible activities-intents usage, etc...



The reason why I don't use the "Back" stack is that I wish to go to any fragment from any fragment, since the flow can change.



Here's a snippet of my code:



Fragment fragment=... ; //get the fragment from cache or create if not available yet...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainActivity_fragmentContainer, fragment).commit();


I have also tried to use ViewPager, but since I don't want to have the sliding effect (which allows you to slide to other fragments) and since one of the fragments already include a viewPager, it's an obstacle. Disabling the sliding effect on the main viewPager somehow disables it on the other one.



BTW, I'm using the android support library for the fragments and not the native API.



my question is:
how can i achieve full control of which fragment to go to , while maximizing speed and avoiding too much memory being used for fragments ?






EDIT:
for now , i use the next workaround :
for the onDestroyView , i take the parent of the created view and remove the created view from there .



for the onCreateView , if i already have the created view from before , i return it .



however , i think it's a very risky thing to do , since i'm not sure of how fragments managing work , so it might cause weird problems . plus ,i'm not sure what will happen if android decides that it has low memory - will it destroy unused fragments (which is good) or will it cause out-of-memory exceptions (which is bad) .





Learning Ruby, Looking for Possible Refactoring for If Statement

I've got a few ideas but wanted to get a few other options. Here is the ugly:



    def normal_balance
if type.to_s == 'Asset' or type.to_s == 'Expense'
if contra
"Credit"
else
"Debit"
end
else
if contra
"Debit"
else
"Credit"
end
end
end




Difficulty to transfer Entity instance from server to client

I have an Android client and a Google App Engine Servlet.

And I am transferring objects from client to server by serialization.

Serialization works fine for all the serialized Object in my project,

except to The Entity Object called Profile that I am saving in my JPA DB.

now when I am transferring Profile instance from client to server it works fine

but when I transfer from server to client i get the exception as written below.



I'll add that i don't have code duplication in my code.

Profile class is in Server Project, and Client project contains Server's path.



W/System.err(1104): java.io.InvalidClassException: javax.jdo.identity.LongIdentity; Incompatible class (SUID): javax.jdo.identity.LongIdentity: static final long serialVersionUID =2472141538875317527L; but expected javax.jdo.identity.LongIdentity: static final long serialVersionUID =2940818939440220368L; 


My Enity class is:



@Entity
public class Profile implements Serializable
{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int age;
private String email;
private boolean onlineStatus = false;

public Profile() {}

public Profile(int age,String email)
{
super();
this.age = age;
this.email = email;
}

public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}

public String getEmail()
{
return email;
}

public void setEmail(String email)
{
this.email = email;
}

public boolean isOnlineStatus()
{
return onlineStatus;
}

public void setOnlineStatus(boolean onlineStatus)
{
this.onlineStatus = onlineStatus;
}


full stack trace:



04-21 21:04:56.577: W/System.err(1104): at java.io.ObjectInputStream.verifyAndInit(ObjectInputStream.java:2697)
04-21 21:04:56.577: W/System.err(1104): at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1825)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:811)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2039)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNewArray(ObjectInputStream.java:1678)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:914)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readFieldValues(ObjectInputStream.java:1291)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:518)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1535)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1443)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2112)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNewArray(ObjectInputStream.java:1678)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:914)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readFieldValues(ObjectInputStream.java:1291)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:518)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1535)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1443)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2112)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.CustomHttpClient.readObject(CustomHttpClient.java:274)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.CustomHttpClient.executeHttpPost(CustomHttpClient.java:59)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.StreetMeetActivity.connectToServer(StreetMeetActivity.java:154)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.StreetMeetActivity.sendMessageToServer(StreetMeetActivity.java:141)
04-21 21:04:56.607: W/System.err(1104): at map.StreetMapActivity$1.run(StreetMapActivity.java:116)




Difficulty to transfer Entity instance from server to client

I have an Android client and a Google App Engine Servlet.

And I am transferring objects from client to server by serialization.

Serialization works fine for all the serialized Object in my project,

except to The Entity Object called Profile that I am saving in my JPA DB.

now when I am transferring Profile instance from client to server it works fine

but when I transfer from server to client i get the exception as written below.



I'll add that i don't have code duplication in my code.

Profile class is in Server Project, and Client project contains Server's path.



W/System.err(1104): java.io.InvalidClassException: javax.jdo.identity.LongIdentity; Incompatible class (SUID): javax.jdo.identity.LongIdentity: static final long serialVersionUID =2472141538875317527L; but expected javax.jdo.identity.LongIdentity: static final long serialVersionUID =2940818939440220368L; 


My Enity class is:



@Entity
public class Profile implements Serializable
{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int age;
private String email;
private boolean onlineStatus = false;

public Profile() {}

public Profile(int age,String email)
{
super();
this.age = age;
this.email = email;
}

public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}

public String getEmail()
{
return email;
}

public void setEmail(String email)
{
this.email = email;
}

public boolean isOnlineStatus()
{
return onlineStatus;
}

public void setOnlineStatus(boolean onlineStatus)
{
this.onlineStatus = onlineStatus;
}


full stack trace:



04-21 21:04:56.577: W/System.err(1104): at java.io.ObjectInputStream.verifyAndInit(ObjectInputStream.java:2697)
04-21 21:04:56.577: W/System.err(1104): at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1825)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:811)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2039)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNewArray(ObjectInputStream.java:1678)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:914)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.592: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readFieldValues(ObjectInputStream.java:1291)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:518)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1535)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1443)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2112)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNewArray(ObjectInputStream.java:1678)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:914)
04-21 21:04:56.597: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readFieldValues(ObjectInputStream.java:1291)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:518)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObjectForClass(ObjectInputStream.java:1535)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readHierarchy(ObjectInputStream.java:1443)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:2112)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:916)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2262)
04-21 21:04:56.607: W/System.err(1104): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2217)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.CustomHttpClient.readObject(CustomHttpClient.java:274)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.CustomHttpClient.executeHttpPost(CustomHttpClient.java:59)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.StreetMeetActivity.connectToServer(StreetMeetActivity.java:154)
04-21 21:04:56.607: W/System.err(1104): at streetMeet.Client.StreetMeetActivity.sendMessageToServer(StreetMeetActivity.java:141)
04-21 21:04:56.607: W/System.err(1104): at map.StreetMapActivity$1.run(StreetMapActivity.java:116)




C++ cli access Form variables from class

There is a form Form1 which contains int x; and a class MyClass with .h and .cpp files. How can I access the Form1 variable x from MyClass, without passing it using a method? I think something like Form1.x Maybe is it a bad style of programming?
I am just learning..





How to Clone a child of an abstract class in WP7 XNA

I'm working on a game for WP7 with XNA. Here is my structure:



public abstract class enemy
{}


Child elements:



public class genericEnemy : enemy{}
...
public class snake : enemy {}


etc...



In WP7, a lot of things have been moved around and/or removed (especially with Serialization) it seems. Despite much searching, I haven't been able to find a solution. I'm trying to duplicate the child elements.



For example: On loading a level, I pass an array of three different enemies into the loading phase. During loading, I need to duplicate each of those enemies so that 20 of each are flying around doing their own thing during gameplay.



All the solutions I've seen refer to things that are not present in the WP7 library.





How can I achieve this background scroll effect?

I really like the way each background section overlaps each other which scrolling down. I have seen it done a lot:
here is the link : http://www.soleilnoir.net/believein/



Any ideas how to achieve the similar effect?



Thanks





How to Clone a child of an abstract class in WP7 XNA

I'm working on a game for WP7 with XNA. Here is my structure:



public abstract class enemy
{}


Child elements:



public class genericEnemy : enemy{}
...
public class snake : enemy {}


etc...



In WP7, a lot of things have been moved around and/or removed (especially with Serialization) it seems. Despite much searching, I haven't been able to find a solution. I'm trying to duplicate the child elements.



For example: On loading a level, I pass an array of three different enemies into the loading phase. During loading, I need to duplicate each of those enemies so that 20 of each are flying around doing their own thing during gameplay.



All the solutions I've seen refer to things that are not present in the WP7 library.





How can I achieve this background scroll effect?

I really like the way each background section overlaps each other which scrolling down. I have seen it done a lot:
here is the link : http://www.soleilnoir.net/believein/



Any ideas how to achieve the similar effect?



Thanks





Pass a gridview column value to a session using javascript

I have a gridview that contains a list of products. What i am trying to do is using the ItemTemplate is pass the ProductID of the selected item using an Onclick event to a session so i can then lookup that session on another page to avoid having the ProductID shown in the URL.



    <asp:GridView ID="GVProducts" runat="server" 
onselectedindexchanged="GVProducts_SelectedIndexChanged">
<Columns>
<asp:ImageField DataImageUrlField="FileName"
DataImageUrlFormatString="Images/{0}" HeaderText="Image">
<ControlStyle Height="80px" Width="80px" />
</asp:ImageField>
<asp:TemplateField HeaderText="Title" SortExpression="ProductID" >
<ItemTemplate>
<a onclick="javascript:function setSessionVariable(<%#Eval("ProductID")%>)" href="ProductDetail.aspx"><%#Eval("Title")%></a>
</ItemTemplate></asp:TemplateField>

</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>


Hopefully it is something simple as i am just starting out with javascript but i cant seem to get it to pass to the session.



Thanks





Pass a gridview column value to a session using javascript

I have a gridview that contains a list of products. What i am trying to do is using the ItemTemplate is pass the ProductID of the selected item using an Onclick event to a session so i can then lookup that session on another page to avoid having the ProductID shown in the URL.



    <asp:GridView ID="GVProducts" runat="server" 
onselectedindexchanged="GVProducts_SelectedIndexChanged">
<Columns>
<asp:ImageField DataImageUrlField="FileName"
DataImageUrlFormatString="Images/{0}" HeaderText="Image">
<ControlStyle Height="80px" Width="80px" />
</asp:ImageField>
<asp:TemplateField HeaderText="Title" SortExpression="ProductID" >
<ItemTemplate>
<a onclick="javascript:function setSessionVariable(<%#Eval("ProductID")%>)" href="ProductDetail.aspx"><%#Eval("Title")%></a>
</ItemTemplate></asp:TemplateField>

</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>


Hopefully it is something simple as i am just starting out with javascript but i cant seem to get it to pass to the session.



Thanks





It isn't a JSONObject. It isn't a JSONArray. What is it?

I have not been working with JSON very long. I have the following response and I'm struggling to understand how to call the details of the "Topic". I thought it was a JSONObject, but Android's logcat is telling me JSONObject["Topic"] not found.



[{"Id":1,"TopicId":1,"UserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Topic":{"Id":1,"AdminUserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Title":"Test Topic 1","AccessType":"public"}}]


Any help is greatly appreciated.





It isn't a JSONObject. It isn't a JSONArray. What is it?

I have not been working with JSON very long. I have the following response and I'm struggling to understand how to call the details of the "Topic". I thought it was a JSONObject, but Android's logcat is telling me JSONObject["Topic"] not found.



[{"Id":1,"TopicId":1,"UserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Topic":{"Id":1,"AdminUserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Title":"Test Topic 1","AccessType":"public"}}]


Any help is greatly appreciated.





DataGridViewRow to DataRow - object reference not set to an instance

What I'm doing (or trying to do) is getting a row from DataGridView and convert it to DataRow, so I can put that DataRow into DataTable. So I searched for examples on the Web,
and people claimed they work just fine, but my doesn't.
This is my code:



DataGridViewRowCollection rows = myDataGridView.Rows;
foreach (DataGridViewRow row in rows)
{
/*(1)*/ DataRow myRow = (row.DataBoundItem as DataRowView).Row;
myDataTable.Rows.Add(myRow);
}


but I get "Object reference not set to an instance of an object." on line (1).





find page number of a string in pdf file in c#

I am developing a pdf reader. i want to find any string in pdf and to know the corresponding page number. I am using iTextSharp.



Thanks in advance





Webcam frame from Aforge always gray image

I am using Aforge .NET framework to get a webcam in my app but I always get an all gray image frame.



            this.videoSource = new VideoCaptureDevice(this.Moniker);
this.videoSource.DesiredFrameSize = GetHighestResolution(this.videoSource.VideoCapabilities);
this.videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
this.videoSource.Start();


The vent handler:



    private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
this.outputBox.Image = (Bitmap)eventArgs.Frame.Clone();
}


This should do the trick. DesiredFrameSize is set to the highest value the cam can support.



Any hints why the image is always gray? Even when writing it do disk...





find page number of a string in pdf file in c#

I am developing a pdf reader. i want to find any string in pdf and to know the corresponding page number. I am using iTextSharp.



Thanks in advance





Webcam frame from Aforge always gray image

I am using Aforge .NET framework to get a webcam in my app but I always get an all gray image frame.



            this.videoSource = new VideoCaptureDevice(this.Moniker);
this.videoSource.DesiredFrameSize = GetHighestResolution(this.videoSource.VideoCapabilities);
this.videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
this.videoSource.Start();


The vent handler:



    private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
this.outputBox.Image = (Bitmap)eventArgs.Frame.Clone();
}


This should do the trick. DesiredFrameSize is set to the highest value the cam can support.



Any hints why the image is always gray? Even when writing it do disk...





jQuery - changed element won't clone

I have changed the html text of an element, in this case #main_cluster_id_reach_12



$("#main_cluster_id_reach_12").html( '400' ).effect("highlight", {color: '#2a6500'}, 60000 * 5);


That works fine but when I try to clone the container that is holding it(#applications), it doesn't contain the updated html of #main_cluster_id_reach_12 but rather the original text that loaded with the page. Here is how I am cloning it:



var $applications = $('#applications');
var $data = $applications.clone();


What am I doing wrong?



edit: Here is the js and html. I am using jquery 1.7.2



What i am trying to do is update the reach of a group of clusters on a 10 second interval via ajax and then resorting the li items with quicksand ordered by their reach. The updating occurs without problem but quicksand clones the original list, not the updated list. This morning i've been playing with some logging and it appears the cloning is happening before the ajax update completes.



// quicksand sorting plugin
(function($) {
$.fn.sorted = function(customOptions) {
var options = {
reversed: true,
by: function(a) { return a.text(); }
};
$.extend(options, customOptions);
$data = $(this);
arr = $data.get();
arr.sort(function(a, b) {
var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
} else {
return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
}
});
return $(arr);
};
})(jQuery);


$(document).ready(function(){
//loop through all reaches to update
setInterval(function() {
//reach
$("[id^='main_cluster_id_reach_']").each(function(){

//Check for reach updates

//get cluster id first
var cluster_id = parseInt(this.id.replace("main_cluster_id_reach_", ""));

//get cluster reach
$.post("./lib/ajax/meme_cluster_update.php", { cluster_id: cluster_id },
function(data) {

//get reach - new
var new_reach = 0;

new_reach = parseInt(data.ItemReach, 10);

//get reach - old
var reach = $("#main_cluster_id_reach_" + cluster_id).html();

// Format as American input
reach = parseInt(reach.replace(/[^\d\.\-\ ]/g, ''));

//compare new vs old and change cell view
compareReach(cluster_id, reach, new_reach);

}, "json");
});

// get the first collection
var $applications = $('#applications');

// clone applications to get a second collection
var $data = $applications.clone();

var $filteredData = $data.find('li[data-type=app]');

var $sortedData = $filteredData.sorted({
by: function (v) {
return parseFloat($(v).find('span[data-type=size]').text());
}
});

// finally, call quicksand
$applications.quicksand($sortedData, {
duration: 800,
easing: 'easeInOutQuad'
});
}, 10000);

//compare the reaches to update accordingly
function compareReach(cluster_id, reach, new_reach) {
//determine what color to change cells
if(new_reach > reach) {
$(".main_cluster_id_reach_" + cluster_id).html( new_reach ).effect("highlight", {color: '#2a6500'}, 60000 * 5);
}
else if(new_reach < reach) {
$(".main_cluster_id_reach_" + cluster_id).html( new_reach ).effect("highlight", {color: '#990004'}, 60000 * 5);
}
}


html



 <div class="span-24" id='demo'>
<ul id="applications" class="image-grid">
<li data-id="id-210639" data-type="app" class='cluster'>
<div class='cluster_byline'>@awkwardisco</div>
<div class="cluster_padding">
<span class='cluster_headline'>Avengers on Thursday!!!</span>
<br>
<div class="cluster_stats">
<div class="span-2 reach">
<strong>REACH</strong>
<span class="main_cluster_id_reach_210639" data-type="size">26777</span>
</div>
<div class="span-2 retweets">
<strong>RETWEETS</strong>
</div>
<div class="span-2 velocity">
<strong>VELOCITY</strong>
</div>
<div class="span-8 LAST">
<strong>LINKS</strong>
</div>
</div>
</div>
</li>
</ul>
</div>




jQuery - changed element won't clone

I have changed the html text of an element, in this case #main_cluster_id_reach_12



$("#main_cluster_id_reach_12").html( '400' ).effect("highlight", {color: '#2a6500'}, 60000 * 5);


That works fine but when I try to clone the container that is holding it(#applications), it doesn't contain the updated html of #main_cluster_id_reach_12 but rather the original text that loaded with the page. Here is how I am cloning it:



var $applications = $('#applications');
var $data = $applications.clone();


What am I doing wrong?



edit: Here is the js and html. I am using jquery 1.7.2



What i am trying to do is update the reach of a group of clusters on a 10 second interval via ajax and then resorting the li items with quicksand ordered by their reach. The updating occurs without problem but quicksand clones the original list, not the updated list. This morning i've been playing with some logging and it appears the cloning is happening before the ajax update completes.



// quicksand sorting plugin
(function($) {
$.fn.sorted = function(customOptions) {
var options = {
reversed: true,
by: function(a) { return a.text(); }
};
$.extend(options, customOptions);
$data = $(this);
arr = $data.get();
arr.sort(function(a, b) {
var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
} else {
return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
}
});
return $(arr);
};
})(jQuery);


$(document).ready(function(){
//loop through all reaches to update
setInterval(function() {
//reach
$("[id^='main_cluster_id_reach_']").each(function(){

//Check for reach updates

//get cluster id first
var cluster_id = parseInt(this.id.replace("main_cluster_id_reach_", ""));

//get cluster reach
$.post("./lib/ajax/meme_cluster_update.php", { cluster_id: cluster_id },
function(data) {

//get reach - new
var new_reach = 0;

new_reach = parseInt(data.ItemReach, 10);

//get reach - old
var reach = $("#main_cluster_id_reach_" + cluster_id).html();

// Format as American input
reach = parseInt(reach.replace(/[^\d\.\-\ ]/g, ''));

//compare new vs old and change cell view
compareReach(cluster_id, reach, new_reach);

}, "json");
});

// get the first collection
var $applications = $('#applications');

// clone applications to get a second collection
var $data = $applications.clone();

var $filteredData = $data.find('li[data-type=app]');

var $sortedData = $filteredData.sorted({
by: function (v) {
return parseFloat($(v).find('span[data-type=size]').text());
}
});

// finally, call quicksand
$applications.quicksand($sortedData, {
duration: 800,
easing: 'easeInOutQuad'
});
}, 10000);

//compare the reaches to update accordingly
function compareReach(cluster_id, reach, new_reach) {
//determine what color to change cells
if(new_reach > reach) {
$(".main_cluster_id_reach_" + cluster_id).html( new_reach ).effect("highlight", {color: '#2a6500'}, 60000 * 5);
}
else if(new_reach < reach) {
$(".main_cluster_id_reach_" + cluster_id).html( new_reach ).effect("highlight", {color: '#990004'}, 60000 * 5);
}
}


html



 <div class="span-24" id='demo'>
<ul id="applications" class="image-grid">
<li data-id="id-210639" data-type="app" class='cluster'>
<div class='cluster_byline'>@awkwardisco</div>
<div class="cluster_padding">
<span class='cluster_headline'>Avengers on Thursday!!!</span>
<br>
<div class="cluster_stats">
<div class="span-2 reach">
<strong>REACH</strong>
<span class="main_cluster_id_reach_210639" data-type="size">26777</span>
</div>
<div class="span-2 retweets">
<strong>RETWEETS</strong>
</div>
<div class="span-2 velocity">
<strong>VELOCITY</strong>
</div>
<div class="span-8 LAST">
<strong>LINKS</strong>
</div>
</div>
</div>
</li>
</ul>
</div>