Monday, September 30, 2013

Loop through nested objects with jQuery

Hey everyone I am trying t find the most dynamic way to loop through an array & return specific values return specific values… The json is deeply structured & may change, could there be a $.each() formula that can help?


var myobj = {    obj1: { key1: 'val1', key2: 'val2' },    obj2: { key1: '2val1',            key2: { nest1: 'val1', nest2: 'val2', nest3: 'val3' },            key3: { nest1: 'K3val1', nest2: 'K3val2',                  nest3: [                         { nest1: 'val1', nest2: 'val2', nest3: 'val3' },                          { nest1: 'val1', nest2: 'val2', nest3: 'val3' }                        ]                 }          },    obj3: { key1: 'dddddval1', key2: 'val2' }    }

now lets say i want to retrieve “K3val2” value yet instead of hardcoding it like so: myobj.obj2.key3.nest2 is there a dynamic way I do this with $.each() mybe?

You can simply nest calls to $.each:

Live Example | Live Source

// Loop the top level$.each(myobj, walker);function walker(key, value) {    // what you like with `key` & `value`    if (value !== null && typeof value === "object") {        // Recurse into children        $.each(value, walker);    }}

If you want to know how deep you are, you can do that too:

Live Example | Live Source

var path = "";// Loop the top level$.each(myobj, walker);function walker(key, value) {    var savepath = path;    path = path ? (path + "." + key) : key;    // what you like with `key` & `value`    if (value !== null && typeof value === "object") {        // Recurse into children        $.each(value, walker);    }    path = savepath;}

JFrame doesn't add TabbedPane

My JFrame is not adding the JTabbedPane & I don’t know if the crash is some sort of bug of my eclipse. There are no syntaxes errors or anything that seems to be to me wrong. Could anyone else try to run it & see if it works? The code is already ready to run. Thanks in advance

public class MainScreen extends JFrame implements ActionListener {    JMenuBar bar;    JMenu file, register;    JMenuItem close, search;    ImageIcon logo= new ImageIcon("rsc/img/sh-logo.jpg");    ImageIcon worldIcon= new ImageIcon("rsc/img/world-icon.png");    JLabel lbImage1;    JTabbedPane tabbedPane = new JTabbedPane();    JPanel entrance = new JPanel();    public MainScreen()    {        JFrame mainFrame = new JFrame();        lbImage1= new JLabel(logo, JLabel.CENTER);        entrance.add(lbImage1);        tabbedPane.addTab("SHST", worldIcon, entrance);        mainFrame.add( tabbedPane, BorderLayout.CENTER);        bar= new JMenuBar();        file= new JMenu("File");        register= new JMenu("Search");        close= new JMenuItem("Close");        close.addActionListener(this);        search= new JMenuItem("Request Query");        search.addActionListener(this);        //Keyboard Shortcut        register.setMnemonic(KeyEvent.VK_S);        file.setMnemonic(KeyEvent.VK_F);        search.setMnemonic(KeyEvent.VK_R);        //mainFrame Setup        bar.add(file);        bar.add(register);        file.add(close);        register.add(search);        mainFrame.add(bar);        mainFrame.setExtendedState(getExtendedState() | mainFrame.MAXIMIZED_BOTH); // Maximized Window or setSize(getMaximumSize());        mainFrame.setTitle("SHST");        mainFrame.setJMenuBar(bar);        mainFrame.setDefaultCloseOperation(0);        mainFrame.setVisible(true);            WindowListener J=new WindowAdapter(){            public void windowClosing(WindowEvent e){            System.exit(0);            }        };         addWindowListener(J);}public void actionPerformed(ActionEvent e){        if(e.getSource()==close){            System.exit(0);        }        }public static void main (String[] args){        MainScreen m= new MainScreen();    }}

You’ve added JMenuBar in Content pane. It is not required.

remove this line in your code mainFrame.add(bar); & mainFrame.setJMenuBar(bar); is already added.

Sunday, September 29, 2013

adding element with a specific style using appenchild method

this is my code :


it doesn’t work !
but when i write only this :


it works, so why i can’t add the div element with a specific style ?
what’ wrong with my work .. thanks in advantage
i want to add a div element with a specific style just from the URL implantation on chrome using :

javascript://all of my code goes here

so it must be short


This will return “someCssStyle” which will be given as argument to (a=document).getElementsByTagName(‘body’)[0].appendChild( function. So the div is never added. Can you see the problem here ?

You have to create the div, style it & then add it to the body. Like this

var div = document.createElement("div"); = "someCssStyle";document.body.appendChild(div);

Saturday, September 28, 2013

Dojo, setAttribute with Internet Explorer

I’m working on a web application that I didn’t make myself & it has been done using Dojo & specially Dijit.
The part which I’m struggling with is approximately a form that gets changed depending on radio buttons.
Therefore, I’m using dijit.byId('id').setAttribute('disabled',true); to disabled a field & this works on FF yet not with IE8. Although, it works yet not directly when I check the radio button, I have to do one more action (like clicking in a random area on the page) & the action is applied. I tried with stuff like: document.getElementById('id').disabled=true; yet it doesn’t work correctly either.

Would you please have any suggestion?
Thank you.

Dojo Widgets have a convention to set attributes using the set method.


This convention will call the _setDisabledAttr method on the widget which will take care of making itself disabled.

opencv - how to save Mat image in filestorage

I want to save a floating point one-channel image & I don’t want to convert it. So I decided to use filestorage class to save it yet I couldn’t quite obtain how to do it from the documentation. And what I tried didn’t work. Can anybody assist me with this?

// Write:FileStorage fs("img.xml", FileStorage::WRITE);Mat img;fs << img;// Read:FileStorage fs("img.xml", FileStorage::READ);Mat img;fs >> img;

Writing to file

cv::FileStorage storage("test.yml", cv::FileStorage::WRITE);storage << "img" << img;storage.release();

Reading from file

cv::FileStorage storage("test.yml", cv::FileStorage::READ);storage["img"] >> img;storage.release();

Friday, September 27, 2013

Python requests hook returns a value to cause exception

The Documentation for python requests module says for hooks that “If the callback function returns a value, it is assumed that it is to replace the data that was passed in. If the function doesn’t return anything, nothing else is effected”

Now i am trying to return a value(int in my case) from my hook function & it throws an exception. This will be valid in all the cases when the return value is an object that DOESNOT have the raw() method defined for it.

Here is some code

def hook(resp,**kwargs):    print resp.url    return 1def main()    s = requests.Session()    s.hooks = {"response":hook}    r = s.get("http://localhost/index.html")

And here is the exception:

http://localhost/index.htmlTraceback (most recent call last): File "/home/talha/ws/", line 85, in <module>   main() File "/home/talha/ws/", line 72, in main   r = s.get("http://localhost/index.html") File "/usr/lib/python2.7/site-packages/requests/", line 347, in get   return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/site-packages/requests/", line 335, in request   resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/site-packages/requests/", line 446, in send   extract_cookies_to_jar(self.cookies, request, r.raw) AttributeError: 'int' object has no attribute 'raw'

The code in @line 446 is trying to extract cookies after the dispatch_hook..From source

    # Response manipulation hooks    r = dispatch_hook('response', hooks, r, **kwargs)    # Persist cookies    extract_cookies_to_jar(self.cookies, request, r.raw)

Either the documentation needs to alter or the handling needs to be re-worked. What is the best way to handle this ?


Based on the comments I tried to return the base response object. Turns out it cannot be used in that manner moreover since some of its fields are initialized to None.

Newer code:

def hook(resp, **kwargs):    obj = requests.Response()    return obj

Exception thrown now:

Traceback (most recent call last):File "/home/talha/ws/", line 88, in <module>   main()File "/home/talha/ws/", line 75, in main   r = s.get("http://localhost/index.html")File "/usr/lib/python2.7/site-packages/requests/", line 347, in get   return self.request('GET', url, **kwargs)File "/usr/lib/python2.7/site-packages/requests/", line 335, in request   resp = self.send(prep, **send_kwargs)File "/usr/lib/python2.7/site-packages/requests/", line 446, in send   extract_cookies_to_jar(self.cookies, request, r.raw)File "/usr/lib/python2.7/site-packages/requests/", line 108, in extract_cookies_to_jar    res = MockResponse(response._original_response.msg)AttributeError: 'NoneType' object has no attribute '_original_response'

What seems is that i will have to implement a full pseudo response?

If the callback function returns a value, it is assumed that it is to replace the data that was passed in. If the function doesn’t return anything, nothing else is effected.

This means that whatever you return is expected to take the place of the response object you were passed.

Nothing in the documentation states that you can return just anything. What did you expect to happen instead?

If you wanted to return a response that has different data, return something that acts like a response still. This means that either you need to subclass the requests response object, or implement something that provides the same API:

from requests.moduls import Responseclass MyIntResponse(Response):    def __init__(self, integer):        super(MyIntResponse, self).__init__()        self._content_consumed = True        self._content = integerdef hook(resp,**kwargs):    print resp.url    newresp = MyIntResponse(1)    newresp.raw = resp.raw  # copy across original HTTP response object

You may want to copy over some of the other attributes from the original response; check the documentation on what attributes Response objects have.

what is white color in GetPixel() method? [on hold]

as you can see from topic I just have a very simple question:

what is the RBG value of white color in GetPixel() method?
is it 255 255 255?
or 0 0 0?


White = 255 255 255

Black = 0 0 0

There’s an effortless code to check it

  Byte r = Color.White.R; // r = 255  Byte g = Color.White.G; // g = 255  Byte b = Color.White.B; // b = 255

What is the difference when assigning a bash variable value with this syntax?

Sorry if this is something really simple or has already been asked, yet due to the nature of the question I cannot think of any search terms to put on search engines.

Lately I have seen some bash scripts that they assign variable values like this:

$ MY_BASH_VAR=${MY_BASH_VAR:-myvalue}$ echo "$MY_BASH_VAR"myvalue

What is the difference from the most usual way of assigning a value like this:

MY_BASH_VAR=myvalue$ echo "$MY_BASH_VAR"myvalue

You can look at

${parameter:-word}  Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

This provides a default value : MY_BASH_VAR keeps its value if defined otherwise, it takes the default “myvalue”

bruce@lorien:~$ A=42bruce@lorien:~$ A=${A:-5}bruce@lorien:~$ echo $A42

htaccess mod Rewrite Rule - optional parameters

I want to rewrite the below:

  1. http://www.mywebsite/address/12345/ to http://www.mywebsite/address/?param1=12345
  2. http://www.mywebsite/address/12345/12 to http://www.mywebsite/address/?param1=12345&param2=12
  3. http://www.mywebsite/address/12345/?{otherparam}=1 to http://www.mywebsite/address/?param1=12345&{otherparam}=1

Below is what I have in the .htaccess file. I have the first two working fine yet am struggling with the 3rd. I need the third to pass param1 & moreover pass other optional parameters. Can anyone assist?

RewriteRule ^address/([^/.]+)/?$ address/?param1=$1  [NC]RewriteRule ^address/([^/]+)/([^/.]+)/?$ address/?param1=$1&param2=$2  [NC]

You’re looking for the QSA flag, which appends any existing query string to the newly constructed one in the rule’s target:

RewriteRule ^address/([^/.]+)/?$ address/?param1=$1  [NC,QSA,L]RewriteRule ^address/([^/]+)/([^/.]+)/?$ address/?param1=$1&param2=$2  [NC,QSA,L]

SQL Server date formatting from string

We’ve recently migrated our database to a different server & since this I think the date format querying has changed somehow.

Previously we could use the following..


However now we have to use..


Can someone tell me what I need to alter to obtain back to the previous version?

Try this one –



Read current settings:



Set Option                 Value-------------------------- -----------------...language                   us_englishdateformat                 ymd...

Get image code from url with Javascript

I\’m creating image uploader for my website. I figured out how to upload image from computer & wrote the whole processing script; Now I need to add an option to upload an image from web. My script works fine after the image is converted into 64 bit format:


Looks like it is impossible to do anything helpful with image before it is on my server, so I have this script which creates a temporary copy of the image on my host:

$content = file_get_contents(\"\");file_put_contents(\"image.png\",$content);

So, what I need to do is to take a link \”image.png\” in JavaScript & transform it to 64 bit format to apply further actions in JavaScript. I can\’t find a solution anywhere, can someone help?

Please take a look at this thread, where a complete solution to convert an image to base64 is provided. This requires HTML5 tho, so your client needs a relatively up-to-date browser.

There seems tho to be some issues between the browsers, since they process image data differentely. If you want 100% the same Base64 encoding as your PHP-script, I suggest you simply make an AJAX-call to the script, which processes the image. Then it returns the Base64 string.

javascript regex validate years in range

I have input field for year & I need a regex for validation it.
I have such code: ^([12]d)?(dd)$.
But I want allow to validate only years in certain range (1990-2010, for example). How can I do it?

Edit. range must be 1950-2050

Try this:

1990 – 2010:


1950 – 2050:


Other examples:

1945 – 2013:


1812 – 3048:


Basically, you need to split your range into effortless “regexable” chunks:

1812-3048: 1812-1819 + 1820-1899 + 1900-1999 + 2000-2999 + 3000-3039 + 3040-3048    regex: 181[2-9]    18[2-9]d   19dd      2d{3}      30[0-3]d   304[0-8]

Update method in Python dictionary

I was trying to update values in my dictionary, I came across 2 ways to do so:

product.update(map(key, value))product.update(key, value)

What is the difference between them?

The difference is that the second method does not work:

>>> {}.update(1, 2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: update expected at most 1 arguments, received 2

dict.update() expects to find a iterable of key-value pairs, keyword arguments, or another dictionary:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

map() is a built-in method that produces a sequence by applying the elements of the second (and subsequent) arguments to the first argument, which must be a callable. Unless your key object is a callable & the value object is a sequence, your first method will fail too.

Demo of a working map() application:

>>> def key(v):...     return (v, v)... >>> value = range(3)>>> map(key, value)[(0, 0), (1, 1), (2, 2)]>>> product = {}>>> product.update(map(key, value))>>> product{0: 0, 1: 1, 2: 2}

Here map() just produces key-value pairs, which satisfies the dict.update() expectations.

Use Aggregate Function in UNION ALL result set

How can I use aggregate Functions in UNION ALL Resultset



Result Set Would Be

    A  B--------------    1  2    3  4    4  5    6  7

When I tried to obtain MAX(A) it returns 3. I want 6.

When I tried to obtain MAX(B) it returns 4. I want 7.

Other than Max(), Can I obtain another aggregate function which user defined?

For example:


Try this way:

select max(A)from(      SELECT A,B FROM MyTable      UNION ALL      SELECT B,C FROM MYAnotherTable    ) Tab

If the column A is varchar (You said that in the comment below) try this way:

select max(A)from(      SELECT cast(A as int) as A,B FROM MyTable      UNION ALL      SELECT B,C FROM MYAnotherTable    ) Tab

With TOP 1

select max(A)from(      SELECT top 1 cast(A as int) as A,B FROM MyTable      UNION ALL      SELECT B,C FROM MYAnotherTable    ) Tab

Adding char to string in C++

I work with Eclipse & Arduino.

I want to add a char to a string. I tried to use append,insert ( yet these can not be resolved)
I tried to use += yet when i print the string it always have one char.Basically i deletes the string & writes only the new char i want to add in.
I tried moreover concat & it does the same thing.Also strcat gives me headache with the operands cause it needs a const char pointer & i want to add a char that changes.

while (theSettings.available()) {character =;if(character == '/')         {    // Comment - ignore this line    while(character != '\n'){        character =;    }} else if(isalnum(character)){  // Add a character to the description    Serial.println(character);    description +=character;    //description.concat(character);    Serial.println(description);}

It sounds like what you want (for convenience) is the String object class available with the Arduino library.

Thursday, September 26, 2013

WordPress mobile theme: WPTouch


Remember: this is a PLUGIN, not a theme.
Install: put extracted wptouch-pro-3 folder under plugins folder.