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?

Example:

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) {    // ...do 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;    // ...do 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 :

(a=document).getElementsByTagName(‘body’)[0].appendChild(a.createElement(‘div’).style.cssText="someCssStyle");

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

(a=document).getElementsByTagName(‘body’)[0].appendChild(a.createElement(‘div’));

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

a.createElement(‘div’).style.cssText=”someCssStyle”

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");div.style.cssText = "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.

dijit.byId('id').set('disabled',true);

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

http://dojotoolkit.org/reference-guide/1.7/dijit/_WidgetBase.html#attributes

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

The code in sessions.py @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 ?

[update]

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/test.py", line 88, in <module>   main()File "/home/talha/ws/test.py", line 75, in main   r = s.get("http://localhost/index.html")File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 347, in get   return self.request('GET', url, **kwargs)File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 335, in request   resp = self.send(prep, **send_kwargs)File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 446, in send   extract_cookies_to_jar(self.cookies, request, r.raw)File "/usr/lib/python2.7/site-packages/requests/cookies.py", 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?

TNX

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