Changing default function-key behavior of apple keyboard under Linux

Be default function keys of apple keyboard serve as multimedia keys (media control, volume up/down) without fn key. But these F1,F2,… keys are more often used during coding/debugging rather than media control. To change them back to F1,F2.. see following post:

https://www.dalemacartney.com/2013/06/14/changing-the-default-function-key-behaviour-in-fedora/

 

Multi dimension array slicing in Python

Python has nice properties of slicing lists. See https://stackoverflow.com/questions/509211/pythons-slice-notation

But it won’t work on list of list. For example:

l = [[1,2,3],[4,5,6],[7,8,9]] and we would like to grab 1st and 3rd columns of l with following:

l[:][0,2]

it won’t work (TypeError: list indices must be integers, not tuple)

For some reason Python doesnt really support slicing on multi-dimensional list. You have to convert it to Numpy array to do so:

np.array(l)[:,[0,2]]

nice and easy. More see http://ilan.schnell-web.net/prog/slicing/

Immediately-Invoked Function Expression (IIFE)

Scope in Javascript is function-bound, meaning variables defined in a function are visible inside the same function, and each time a function is invoked it creates a new execution context. This is different from C which confines life span of variables inside a block. For following code:

var a = 1;

function f1() {
  var b = 2;
  console.log('inside f1 a:'+a);
}

function f2() {
  var c = 3;
  return function(d) {
    return d+c;
  }
}

{
var e = 5;
}

f1();

console.log(a);
console.log(b); //error
console.log(e);
console.log(f2()(4)); //closure

Only hidden variable to the global context is b. Since every C function is defined using block Javascript is more loose in the sense that blocks without function declaration doesn’t really do much.

Now move on to Immediately-Invoked Function Expression: the motive behind this is you want to execute a piece of code without contaminating the global context while being able to use many of the global variables. You do it by creating an anonymous function and immediately invoking it:

(function () {
 ...
})();

This is a very common pattern for Javascript and is seen everywhere, especially for locking in the value of
execution context. More reading can be found at http://benalman.com/news/2010/11/immediately-invoked-function-expression/

How fast node responds to concurrent http requests

Disclaimer: people have done this a million times but I just wanted to see it myself.

One of the merits of node.js that people keep talking about is it scales really well under the pressure when there’s a large number of users using the service at the same time. Let’s examine the validity of this witness today:

I’ve built a small website using Node.js + sqlite, with some in-house caching. For the testing request, there are 4 SQL Select requests. The database file is fairly light-weighted with less than 1 million records and the queried columns are indexed as well. But in theory all this shouldn’t matter as long as the same url has been visited, all those DB results are cached and no more DB access is needed.

I used ‘ab’ for concurrent tests and below is the result:

concurrency = 1 to 100

Image

 

#request from 100 to 1000

Image

 

Apparently node.js handles multiple requests pretty well until concurrency exceeds 15 for my hardware

Obtaining user’s zipcode with in browser

HTML5 offers the capability of obtaining browser’s physical location via it’s geolocation API:

https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation

The result consists of latitude and longitude. This is good, especially when you are making a Maps app. But sometimes the use case/database behind is organized by address/town/zipcode rather than geolocations, and we would like to convert the geo result to zipcode for example. We can achieve this by calling Google Maps API:

https://developers.google.com/maps/documentation/javascript/reference#Geocoder

What returns from this API call has an array of possibilities and usually the first one is good enough. Some sample code below:

function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(pos){
            var g = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);;
            g.geocode ({'location':latlng}, function(results, status) {
              if(status === google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                  for(var i=0; i<results[0].address_components.length; i++){
                      var types = results[0].address_components[i].types;
                      if(types[0]==='postal_code') {
                        var postalCode = results[0].address_components[i].long_name;
                        console.log(postalCode);
                      }
                  }
               }
              }
            });
          });
        } else {
          console.log("Geolocation is not supported by this browser.");
        }
      }

EMFILE error in node.js

This usually happens when we asynchronously operate on a large number of files in Node.js and due to the async nature of Node.js many files are open at the same time. See explanation at https://stackoverflow.com/questions/16200497/emfile-error-in-async-file-reading

Two solutions: 1) use sync version of readFile. so each file is closed before proceeding to next 2) use callback function for reading next file, something like


function readFile(files, i) {
  if(i>=files.length) return;
  fs.readFile(path+'/'+files[i], 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }
    parse(data, function(result){
      readFile(files,i+1);
    });
  });
}

fs.readdir(path, function(err, files) {
  readFile(files,0);
});