Monday, June 24, 2013

JavaScript Binary Insertion Sort

I ported over the binary insertion sort algorithm from this blog post to JavaScript. The two changes I made were that I used Math.floor to truncate the floats when division occurs and replaced memmove() with a for-loop from one of the previous implementations in the post.
function binaryInsertionSort (a)
    var i, m;
    var hi, lo, tmp;
    var n = a.length;

    for (i = 1; i < n; i++) {
        lo = 0, hi = i;
        m = Math.floor(i / 2);

        do {
            if (a[i] > a[m]) {
                lo = m + 1;
            } else if (a[i] < a[m]) {
                hi = m;
            } else

            m = Math.floor(lo + ((hi - lo) / 2));
        } while (lo < hi);
        if (m < i) {
            tmp = a[i];
            for (j = i - 1; j >= m; j--)
                a[j + 1] = a[j];
            a[m] = tmp;
    return a;

//outputs [11, 40, 42, 66, 73, 90]
binaryInsertionSort([66, 73, 42, 40, 90, 11]); 

Tuesday, June 18, 2013

Load jQuery and jQuery UI into any page

TL;DR You can copy the bookmarklet here. Just drag and drop onto your bookmark bar.

Sometimes I need to load jQuery and jQuery UI on some pages for testing or trying something out. I came up with a bookmarklet that loads the latest jQuery and jQuery UI libraries into the currently viewed page.
   var body= document.getElementsByTagName('body')[0];
   var script1 = document.createElement('script');
   script1.type = 'text/javascript';
   script1.src = '';
   var script2 = document.createElement('script');
   script2.type = 'text/javascript';
   script2.src = '';
   var timer = setInterval(function(){
     if (typeof jQuery != 'undefined') { 
A problem I ran into is that I couldn't just load jQuery UI into the page right after jQuery because it takes a bit of time for each script to download and jQuery UI is dependent on jQuery being loaded first. The solution I came up with is using a timer that checks every 10ms to see if jQuery has been loaded and then loading jQuery UI. Both are appended to the body (some pages don't have head tags) and the timer cleared to prevent the loop from continuing once the script is done. You could also extend this to add any Javascript you wanted to a page. Here is the code minified:
javascript: (function(){var body= document.getElementsByTagName('body')[0]; var script1 = document.createElement('script'); script1.type= 'text/javascript'; script1.src= ''; var script2 = document.createElement('script'); script2.type= 'text/javascript'; script2.src= ''; body.appendChild(script1); var timer = setInterval(function(){ if (typeof jQuery != 'undefined') { body.appendChild(script2); clearTimeout(timer); } },10);})()

Wednesday, April 11, 2012

Parse: Sending Push Notifications using PHP with/without cURL

I started using Parse to easily send push notifications to phones with my app. However I needed to use PHP to send the notifications and not from the command line as shown in their api.

I came up with the following using cURL:

 $ch = curl_init(); 

 $arr = array();
 array_push($arr, "X-Parse-Application-Id: YOUR_APPLICATION_ID");
 array_push($arr, "X-Parse-REST-API-Key: YOUR_REST_API_KEY");
 array_push($arr, "Content-Type: application/json");
 curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
 curl_setopt($ch, CURLOPT_URL, '');
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "channel": "","data": { "alert": "Red Sox win 7-0!" } }');

And if for some reason you don't want to use cURL, here is the code using the default stream_context_create and file_get_contents methods:

 $url = '';
 $data = '{"channel":"","data":{ "alert":"Red Sox win 7-0!"}}';

 $opts = array('http' =>
   'method'  => 'POST',
   'header'  => "X-Parse-Application-Id: YOUR_APPLICATION_ID\r\n
       X-Parse-REST-API-Key: YOUR_REST_API_KEY\r\n
       Content-Type: application/json\r\n
       Content-Length: " . strlen($data) . "\r\n",
   'content' => $data

 $context  = stream_context_create($opts); 
 $result = file_get_contents($url, false, $context);
 echo $result;

Tuesday, April 3, 2012

Virtual Nomads

Why do we play video games? We play video games for a social experience. Games can be after all part of the greate social network of the Internet. We play with others because it is more fun. Are social networks a bad things and can such social stimulation be addictive? Perhaps. Games start to become addictive when the player starts to feel compelled be there. The virtual world can be great and terrible. Not only is a product of our genius, but it costs virtually nothing to contribute too. It is something that we can get sucked into and lose our way. Most of us cannot do anything without our computers. The virtual world is has become our lives now. But we are humans, and no man is an island. We can't get all of our social fulfillment from video games. Eventually we feel that need and we come out into the light eventually. Do video games have lasting value? We play for many reasons: to relax, to create, to feel acomplished when we win, but mostly because we are bored. It is much easier to play a video game then it is to go out and make a new, real friend, or to learn a new skill. We lose ourselves if we lose the desire to innovate.

Monday, April 2, 2012

Multi-line overflow in Sencha Touch/ExtJS

Unfortunately CSS doesn't support multi-line overflow. I stumbled upon a stackoverflow question that addressed this. I applied this to work in Sencha Touch and ExtJS.

Try it yourself on jsfiddle:
ExtJS fiddle
Original jquery fiddle

With the following HTML:

<style type="text/css">
.item { 
   width: 300px; height: 120px; overflow: hidden;

.item div { 
  padding: 10px; margin: 0; 

<div class="category-item">
   <div class="list-item-title">Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan 
      orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed
      ipsum a lacus sodales eleifend. Vestibulum lorem felis, rhoncus elementum vestibulum eget, 
      dictum ut velit. Nullam venenatis, elit in suscipit imperdiet, orci purus posuere mauris, 
      quis adipiscing ipsum urna ac quam.

The javascript to add multi-line overflow in Sencha Touch is:

var item ='.item div').first();
var divh ='.item').first().getHeight();
while (item.getOuterHeight()>divh) {
   item.dom.innerText = item.dom.innerText.replace(/\W*\s(\S)*$/, '...');

ExtJS is the same with one line changed:

var'.item div').first();

while (item.getComputedHeight()>divh) { //this line changed
    item.dom.innerText = item.dom.innerText.replace(/\W*\s(\S)*$/, '...');

The above code with display the following:

Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Proin nisi ligula, dapibus a
volutpat sit amet, mattis et dui. Nunc
porttitor accumsan orci id luctus. Phasellus
ipsum metus, tincidunt non rhoncus id...

Thursday, March 22, 2012

Here Comes YouTube

In Shirky’s book "Here comes Everybody", the author discusses the possibility of something called “mass amateurization”. Any one can post anything to the internet using blog sites or other social networks. This includes uploading videos and images, as well as other content. The author describes that these tools don’t get socially interesting until they get technologically boring, and that sharing is enhanced through them. Shirky also states that society was transformed by tools such as the printing press but it is harder to prove that it was made better. it’s simple to say the internet is an interesting phenomenon. Recently I watched a YouTube video called The Machine is Us/ing Us. An Anthropologist from Kansas State University, Michael Wesch, created the video to show the future of Web 2.0. Over the course of the week it became viral. Because of this video, Wesch gave a presentation before the library of congress. Today Welsch and his students study the videos posted YouTube through Anthropology, or the effects of YouTube on society. Watching YouTube is practically a major now. We can see the effects that it has on society, the good and the bad. The web is an interesting place because it allows anyone to post anything, which changes how media is portrayed. But is this what the human race needs? Should people be allowed to post things without consequences? I believe that we should be responsible for our actions. I think that there has to be some way to genuinely authenticate a user before they upload anything so that they can be held morally responsible for what they upload.

Thursday, March 15, 2012

Tinkerers' Market

There has been a trend over the years that women have an aversion to the field of Computer Science. Women receive about half of undergraduate degrees in mathematics, physics and other science related fields but only about 20% in Computer Science. Researchers have determined that women are not drawn to to the study of computers because it is more of a tinkerers' field then an actual science. Early Software Engineers such as Steve Jobs and Bill Gates all got their start as tinkerers. Today Computer Science books give solutions but offer the student to try it on there own in a trial and error approach to solve the problem. Women have been driven out of computer science because there is not an agreed-upon body of knowledge that defines the field. 57% of men are drawn to Computer Science because of tinkering compared to the 16% of women. The study of computers should become a field of a science instead of a field of tinkerers.