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
                break;

            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.
(function(){
   var body= document.getElementsByTagName('body')[0];
   var script1 = document.createElement('script');
   script1.type = 'text/javascript';
   script1.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
   var script2 = document.createElement('script');
   script2.type = 'text/javascript';
   script2.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js';
   body.appendChild(script1);
   
   var timer = setInterval(function(){
     if (typeof jQuery != 'undefined') { 
        body.appendChild(script2);
        clearTimeout(timer);
     }
   },10);
})()
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= 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; var script2 = document.createElement('script'); script2.type= 'text/javascript'; script2.src= 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js'; 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, 'https://api.parse.com/1/push');
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "channel": "","data": { "alert": "Red Sox win 7-0!" } }');
 
 curl_exec($ch);
 curl_close($ch);

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 = 'https://api.parse.com/1/push';
 $data = '{"channel":"","data":{ "alert":"Red Sox win 7-0!"}}';

 $opts = array('http' =>
  array(
   '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; 
}
</style>

<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.
   </div>  
</div>​

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

var item = Ext.select('.item div').first();
var divh = Ext.select('.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=Ext.select('.item div').first();
var divh=Ext.select('.item').first().getHeight();

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.

Tuesday, March 13, 2012

Technologic Advancements

While reading an article put out by the Church, I was confused why it took so long for these changes to take places. Thinking that it had come out recently, while it was talking about CADs and how much computers can save time, I stumbled across a reference to the Apple II. It was then I realized that the article was not recent, and checking yes it was written in 1984. Many of the systems described in the article are still being updated and worked on. Today it may feel like the Church is still behind where it could be in regards of technology. The reason why I feel this is that it takes awhile for technology to be implemented in a place where peoples' faith are concerned. It would get too impersonal if everything were automated and too much computerization can make a person less receptive to the spirit. The Church has done a marvelous job using the tools that have been given to the world. So much more now is available and so much more is possible that can be done now.