Javascript

Lempel–Ziv–Welch (LZW) Compression in JS

// Decode LZW-encoded string
function lzwDecode(s) {
        var dict = {};
        var data = (s + "").split("");
        var currChar = data[0];
        var oldPhrase = currChar;
        var out = [currChar];
        var code = 256;
        var phrase;
        for (var i = 1; i < data.length; i++) {
            var currCode = data[i].charCodeAt(0);
            if (currCode < 256) {
                phrase = data[i];
            }
            else {
                phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
            }
            out.push(phrase);
            currChar = phrase.charAt(0);
            dict = oldPhrase + currChar;
            code++;
            oldPhrase = phrase;
        }
        return out.join("");
}

// Compress a string with LZW
function lzwEncode(s) {
        var dict = {};
        var data = (s + "").split("");
        var out = [];
        var currChar;
        var phrase = data[0];
        var code = 256;
        var i, l;
        for (i = 1, l = data.length; i < l; i++) {
            currChar = data[i];
            if (dict[phrase + currChar] != null) {
                phrase += currChar;
            }
            else {
                out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
                dict[phrase + currChar] = code;
                code++;
                phrase = currChar;
            }
        }
        out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
        for (i = 0, l = out.length; i < l; i++) {
            out[i] = String.fromCharCode(out[i]);
        }
        return out.join("");
}
Image

JSON

JS Var to JSON & vice-versa

function getObj() {
  var arrA = [22,43], arrB = [];
  return {
   ar1:arrA, 
   ar2:arrB
  };
}
var arr = getObj().ar1;
console.log(arr);

var arr1 = [1,2];
var arr2 = [3,4];

var obj = {a:arr1,b:arr2};

console.log(JSON.stringify(obj)); // {"a":[1,2],"b":[3,4]}
console.log(JSON.stringify(arr2)); // [3,4]

// adding top node to existing obj
var withPref = {'pref' : obj}

console.log(JSON.stringify(withPref)); // {"pref": {"a":[1,2], "b":[3,4]} }

var arr = (obj.a).concat(obj.b);
console.log(arr); // plain js array: [1, 2, 3, 4]

var jane = {"person":[{"id":121},{"title":"Jane"}]};

All About JSON Manipulation

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
	<style>
	html,body {
		margin: 5px 0px 0px 5px;
		padding: 10px 0px 0px 0px;
	}
	span {
		border-radius: 3px;
		background: #220;
		color: #fff;
		padding: 10px;
	}
	</style>
  </head>

  <body>
    <div class="content"></div>
    <script src='jquery3.1.1.js'></script>

	<script type="text/javascript">
	$( "div.content" ).html("<span>Hello Again! I will exapnd</span>");
	$( "div.content span" ).append("&nbsp; > ABC" );
	
	var arry1 = [];
	var temp = {
		"gpc": [
          {
            "top": "Top1",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "jquery"},
              {"name": "json"}
            ]
          },
			    {
            "top": "Top2",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "ember"},
              {"name": "Top1"}
            ]
          }
		]
	};

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));    
        } else 
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(obj);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
            }
        }
    }
    return objects;
}

function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
			objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
			objects.push(i);
        }
    }
    return objects;
}


// then to get the JSON string
if(arry1.length === 0) {
  // console.log("empty arry");
} else {
  var strJSON = JSON.stringify({gpc: arry1});
  // console.log('New::: \n'+strJSON );
}

// console.log('Org::: \n'+JSON.stringify(temp));
var obj1 = getObjects(temp,'top','Top1');
var obj2 = getObjects(temp,'top','Top2');

var main = obj1.concat(obj2);

console.log(JSON.stringify(main));
	</script>
  </body>

</html>

adding a parent node

Stack Answer

Concat

Pen

See the Pen parse json by Hamzeen H (@hamzeen) on CodePen.

https://production-assets.codepen.io/assets/embed/ei.js

JSFiddle

http://jsfiddle.net/hamzeen/dw3q67md/

Back with Flock-The Social Web Browser

Guys Lonely Coder is back after a week of heavy work with a freaking project for Cutting Edge which is the most exiting event of IIT every year, Where the Final years of IIT enterprise their talent on stage to the public. And this is where all the work that they put over the years at IIT get exposed to the industry what we are really capable of being, students of University of Westminster. This time for this ever so  fascinating event, second years are also invited to take part due to lack of projects & gues what Lonely Coder grabbed it with both hands.

The project of us APES which stands for Automated Police Entry System. It’s  another entreating project I have come across after the long lasting nights working out on  Successlands another devastating project at Archmage which took me months to work on and believe me still it is incomplete. You can have a look at it via,

SuccessLands.com

Today I get a chance to explore a few breathtaking features of my new browser, should say a social web browser to be precise. Namely it’s Flock. Believe me this post is actually written & published right from the Flock browser how that sounds for a blogger… I’m sure already the guys must be pumped up to figure out how this actually works. It’s really easy as giving your particular blog’s username & password, don’t worry what ever the sort of blogger you are it supports all the famous blogs like blogger, wordpress in my case, xanga, LiveJournal, TypePad and many more.

This is just another single amazing aspect of Flock. You got many more than this , to start  with one might wonder if it another version of firefox if you were firefox browser over the years. Yes it looks very similar to firefox and also uses the same technology for fast browsing.

Going through few of the other embarasing features of Flock,

  • Favorites management
  • Feed reader
  • Media minibar
  • Photo Uploader
  • Account Handling
  • Again Flock’s in-built Photo uploader also provides support to uploading media to most of your media sites which includes PICZO, Flickr, YOUTUBE & Photo Bucket. Never worry with signins just goto your browser and get access to most of your favourite sites. Nothing to type in your addressbar unless you wanna discover a new site.

    With all these wonderfull integerations it provides one with instantaneous access to most of their favourite sites. But then again security wise it’s really dangerous to leave your account informations in the browser so in that case Flock becomes an extremely confidential and a private browser.

    If you are interested in trying out Flock visit,
    Flock.com

    Blogged with Flock

    T20 World Cup -Where the Drama Begins

    Yesterday (2nd day of ICC twenty-twenty inaugural World Cup) Zimbabwe met The three times consecutive world cup winners Australia in another thrilling encounter.

    The minors(Zimbabwe) played good positive cricket wright from the beginning were paid of for their effort in the field and aussies were all over the place with Sky Scrapers most of them got caught in the deep. The drama continued and Aussies were restricted down to 138 for 9 wickets.

    Later in the evening Zimbabwe chased it down to welcome Aussies to ICC T20 WorldCup with a Shock Treatment.

    Earlier KIWI’s (New Zealand) marked their arrival to the WorldCup with a comprehensive win over Kenya.

    And Pakistan too marked their first victory in the T20 World Cup win with a much fought win over Scotland after they were restricted by the underdogs (Scotland) for a mere 171 for the loss of 9 wickets.

    Many Cricket Critics are still reluctant to express their view over this new innovation by the ICC and it will remain so up untill the end of this fascinating tournament as the Drama continues.

    Happy Blog Day

    Today, august 31st happens to be the third annual Blog Day, to join the celebrations all the bloggers are being asked to find five new blogs that you find interesting and notify them that you are recommending them in order to celebrate the event and also to give a brief description of those blogs in your blog.

    Blog Day 2007

    PC & Mobile Phone can they Co-Exist ?

    Whenever I receive a call or a text message on ma hand phone it seem to have disturb my PC’s both monitor and speaker a great deal. Hence this week I thought of going a bit into Physics.

    We all know that electric conductors when they are conducting electricity will have a magnetic effect on them, a good example is when you place a nail near an electric conductor(Say a Wire) while conduction will attract the nail towards it.

    Actually current is produced owing to the movment electrons (technically this is called a change in electric field), the direction of the induced current will always be in the opposing direction

    not stopping there the conductor will also producing a manetic field around it and electrons will be moving towards the north pole of the conductor. Now it is said to produce an Electro Magnetic Field (E-M). which is a combination of both electric and magnetic field at the same time. This energy is same as any other form of energy can do work. And the work dine is given by,

    ∆W=F∆S
    where W is notationed for Work, F for Force and S for displacement

    This is where we can apply Flemming’s left hand rule figure ouit the direction the Force produced during this event.

    Direction of induced Force

    All these research I carried out to figure out my particular problem which is also due electro-magnetic waves, it is called the Electro Magnetic Interference (EMI).

    Why monitor responds first?

    intersting part of my particular scenario is that I get a trigger in my monitor even before I hear the ring tone or my speaker gets disturbed.
    When I digg deap into this particular case what I find is very simple, it is because light waves are faster than sound waves.
    Acording to,
    v= fλ

    Where v represents velocity, f represents frequrncy, and λ for wave length.
    according to this relationship you can see that frequency(f) is inversely propotional to wavelenth(λ) as weell.
    hence smaller the wavelength, higher the frequency whilst the velocity remains constant.but,
    f=1/t

    this would suggest when higher the frequency lower the time it take s to travel. And that’s it. When you take the spectrum you will find that light wave’s wavelength is lower than sound waves. this the perfect reason for this matter. This is the reason that I could find for my monitor to respond first.

    Why Electro-Magnetic waves are so dominent?

    The other importatnt fact about Electromagnetic waves is that it is so quick to travel and they do not need any medium to travel they travel through vaccum as well, not like Sound waves or some other waves hence this is the way that rays from sun travel to earth in the space where there is no air.

    But after all these researches what Lonely Coder has to say is that there is no stable solution to overcome this senario. But stll I could findcarrying out some serious reaserches, hope they would be paid for their there effort.

    My mates go on paper this Sunday

    Yesterday I have missed a wonderfull opportunity when I went to fab to buy a cake for ma friend Anupiya (Sacramentum) who is getting his first salary today anyway since we got a free delivery from a cousine of his we bought it yesterday itself and sent it with her.

    When I returned to IIT Shariq came running at me asking to read next edition of Sunday Times, where his interview with his photo along together with many other friends at IIT is supposed to appear on the Education suppliment of this week’s Sunday Times. Well well we are all looking forward to it with great anticipation.

    Anyway I have missed yet another great oppertunity to get my photo published on paper. But Never the less hope l will be there next time.