Chris Ng

Senior Staff Software Engineer at LinkedIn | Ember Learning Core Team | Speaker

Page 5


Duplicate property names in object literals

This is a Sonar rule that makes sure the JSON structure has quality built-in.

Sample JSON:

var data = {
    "key": "value",
    "key": "value2", // not compliant
    key: "value3" // not compliant
}

In this case, data.key will be “value3” (taking the last instance).

JavaScript allows you to do this, it is valid javascript, but it only takes the last instance. This makes the code hard to debug and prone to bugs since a developer unfamiliar with the nls file or whatnot will assume the first Ctrl-F found item is the only instance.

View →


Push Notifications on Java EE 5

This is a way to have “server push” notifications to the client’s browser without having AsyncContext available.

With a distributed network system, you can’t just store notification messages into the cache and retrieve it quickly by polling the server from client.

The solution described uses Quartz Scheduler or something else to enable the Application Server to data synchronize with the database and store it in its cache (flow A, B, and C).

This way when the client polls the server (flow 0 and 1), it goes straight for the cache (flow 2) so it won’t use up the thread of the App Server since database functions take a long time (especially in large scale scenarios). The drawback to this is if this certain client has a message then it has to do a database delete record (flow 5) which takes a lot of time, comparatively to case when there are no records found. A way around this is to have...

Continue reading →


Configure Spring to turn Quartz scheduler on/off

This is a way to use Spring’s PropertyPlaceholderConfigurer to turn Quartz Scheduler on and off based on a properties file.

This way an application can be configurable using only the properties file exclusive of changing xml documents.

XML File:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:configuration/app.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

<!-- Scheduling START -->
<bean id="chrisJobDetailBean" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="sample.springquartz.chris.chrisJob" />
    <property name="jobDataAsMap">
        <map>
            <entry key="sampleBean" value-ref="sampleBean"/>
        </map>
...

Continue reading →


Making Sublime Text portable version have right-click>edit functionality

From mrchief, this solution lets you do right click on a file and do something like this >
SublimeText.png

Simply save the code below as a bat or even just run it off console with the proper path for you Sublime Text (or any reg entry to be honest)

@echo off
SET st2Path=C:\Program Files\Sublime Text 2.0.2\sublime_text.exe
 
rem add it for all file types
@reg add "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 2"         /t REG_SZ /v "" /d "Open with Sublime Text 2"   /f
@reg add "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 2"         /t REG_EXPAND_SZ /v "Icon" /d "%st2Path%,0" /f
@reg add "HKEY_CLASSES_ROOT\*\shell\Open with Sublime Text 2\command" /t REG_SZ /v "" /d "%st2Path% \"%%1\"" /f
 
rem add it for folders
@reg add "HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text 2"         /t REG_SZ /v "" /d "Open with Sublime Text 2"   /f
@reg add "HKEY_CLASSES_ROOT\Folder\shell\Open with
...

Continue reading →


Calling parent window from opened child popup window

This is a way to call the parent window from the popup it launched without adding hooks (just using the built in functionality).

From the parent window opening can be as simple as:

window.open('child.html');

From the child popup window to get a hook method “methodName” from the parent window:

window.opener.methodName();

From the child popup window to get a hook to the parent window elements:

window.opener.document.getElementById("sample").value;

View →


Dynamically adding images with only client side

This is a way to add images to say a carousel when you don’t know much about the number of images or where it is. Completely configurable.

Using the URL query string we can get the configurable options. This is a way to parse it using regex.

function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
                results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }

We basically call the function by calling “addImage(1)” with 1 being the start

function addImage(counter) {
            var src = getParameterByName('path') + counter +(getParameterByName('filetype')||'.png');
            var img = new Image();
            img.onload = function() {
                img.className =
...

Continue reading →


Clicking on background div only

This is a way to trigger a function when user clicked/touched the background div without hitting it’s child elements.

$('parentDiv').click(function(e) {
    var clicked = $(e.target);
    if(!clicked.hasClass('parentDivClass')) {
        // do function
    }
});

So the target of the event will be what was clicked. By using a jQuery selector we can do even more fine grain checking (especially useful for very complicated applications) before triggering the function.

View →


iOS hold and delete icons using HTML5

This is a way to mimic the iOS hold and deleting apps from the menu grid screen. In this case, it only shakes one of the icons when held-touched, but this can easily be mutuable to act exactly the same as the iOS scenario.

It also adds the img tag under the setTimeout method to provide the close button.

Used the willhelm-murdoch’s jQuery-Wiggle


function wiggle() {
    var timer;
    $('a.icon').bind('touchstart', function(e) {
        e.preventDefault();
        clearTimeout(this.timer);
        var p = $(this).parent(); // The container div
        this.timer = setTimeout(function(p) {
            p.prepend( img onclick="top.blockclose(this)" );
            p.wiggle('start');
        }, 1000, p);
    })
    .mouseup(function(e) {
        clearTimeout(this.timer);
    });
    
    $('bodywrap').click(function(e) {
        $('.wiggling')).wiggle('stop');
    });
}

Continue reading →


Array.prototype.forEach() in IE8

This is a way to work around the issue where a function in JavaScript (in this example forEach() in object Array) is not supported in IE8 or some other older browser.

ie8.PNG

To work around this, we can explore JavaScript’s dynamic feature of extending built in functions for in this case the object Array. We can add our own forEach() funtion on the Array object in our application.

Code:

if (typeof Array.prototype.forEach != 'function') {
    Array.prototype.forEach = function(callback){
      for (var i = 0; i < this.length; i++){
        callback.apply(this, [this[i], i, this]);
      }
    };
}

Continue reading →


JSON to CSV using JavaScript

This is a way to convert a JSON object to a CSV file using only JavaScript.

We download the CSV file using the DOM method and allow the entires of results to have different number of headers. We assume that while each result object can have different number of headers the entry with the most number of headers contain all the possible headers in the results array.

A follow up feature enchancement to do with this program is to store the headers in a map so we can fully support as many headers as possible.

Sample JSON:

{ "results": [
    {
        "id": "8675309",
        ...
    }
] }

Code:

function convert() {
    var json = $("_json").val();
    if(json == '')
        return;
    json = JSON.parse(json).results;
    // Find the largest element
    var largestEntry = 0;
    var header;
    for(var i=0; i<json.length; i++){
        if (!Object.keys) {
            Object.keys =
...

Continue reading →