January 2011

archive

extracting key value pairs of an array in javascript with jquery Jan
06
1
1

At times I feel spoiled using Python, especially when I try to do what seems to be a trivial operation to discover there's not already a construct to do it in whatever language I'm in at the time. One of these instances is when I try to loop over and extract key value pairs out of an array in Javascript. Being in the Python mode I'm usually hoping to find something like the following:

# python
for key, value in array:
    ....

The best I could come up with is to use the each() function from JQuery to loop over each element.

var example = {};

example['apple'] = 1;
example['orange'] = 2;

$.each(example, function(key, value) {
    console.log(key);
    console.log(value);
});

Or, for a non-jquery solution:

for(var key in example) {
    console.log(key);
    console.log(example[key]);
}

comments

how to stop / terminate / exit a python script Jan
03
1
1

I know this could be trivial to some of you, but it wasn't obvious to me which is why I'm posting. From time to time you might want to hard exit out of your python script. For me this came about when I was writing some system deploy and maintenance scripts. Just returning out of a function wasn't good enough because the rest of the script would keep on trucking. I needed to stop all execution of the script right there before it continued on and did irreversible damage to the system.

This can be done through the sys module.

import sys
sys.exit()

It's good to note that all this does is throws a SystemExit exception which can be caught like any other exception.

Alternatively you can use the os._exit() function which terminates at the C level and does not let the interpreter perform any of the normal tear-down procedures. It is not recommended to use os._exit() as sys.exit() should suffice for the vast majority of cases and is the recommended method.

comments