Author Archive

JavaScript’s Internal representation of Objects

Wednesday, April 15th, 2020

 

A simple diagram is probably the best way to give a quick overview of the object representation in Javascript.

Most objects contain all their properties in a single block of memory (“a”, and “b”). All blocks of memory have a pointer to a map, which describes their structure.
Named properties that don’t fit in an object are usually stored in an overflow array (“c”, and “d”).
Numbered properties are stored separately, usually in a contiguous array.

The JavaScript standard allows developers to define objects in a very flexible way, and it is hard to come up with an efficient representation that works for everything. An object is essentially a collection of properties: basically key-value pairs. You can access properties using two different kinds of expressions:

  • obj.prop
  • obj[“prop”]

According to the spec, property names are always strings. If you use a name which is not a string, it is implicitly converted to a string. This may be a little surprising: if you use a number as a property name, it gets converted to a string as well (at least according to the spec). Because of this, you can store values at negative or fractional array indices. So a JavaScript object is basically a map from strings to values.

 

Javascript as a Full Stack Language

Thursday, April 2nd, 2020

Javascript is a scripting language. JavaScript is interpreted and sometimes compiled at run time. It runs natively on your browser which makes it completely cross platform and hardware agnostic.

Javascript is the de facto language used to code the front end interface for web apps. There are many Javascript frameworks which do exactly that. Moreover JavaScript can also be run in a server environment using NodeJs.

JavaScript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. JavaScript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior.

Generally, JavaScript frameworks will do the heavy lifting when it comes to binding your data to your mark-up. You have a model of data, and you have some mark-up to which you’d like to bind it. You can achieve this in vanilla JavaScript yourself if you wish, but a framework such as Angular or React will cater for it most of the time.

With a framework, you’re just doing things faster. You can use all these battle-tested libraries. They’ve been checked for security, they’re in use on a thousand of different websites, they’ve been checked for performance, edge case bugs, so you don’t have to find those bugs over and over again because they’re already been found and fixed.

Another common application for JavaScript is as a (Web) server side scripting language. A JavaScript web server would expose host objects representing a HTTP request and response objects, which could then be manipulated by a JavaScript program to dynamically generate web pages. Node.js is a popular example of this.

Node.js is a platform built on Chrome’s JavaScript run time for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

In the database side of application development, Javascript also has an offering. Mongo DB has rapidly grown to become a popular database for web applications and is a perfect fit for Node.JS applications, letting you write Javascript for the client, backend and database layer. Its schemaless nature is a better match to our constantly evolving data structures in web applications, and the integrated support for location queries is a bonus that’s hard to ignore.

What is Full Stack Development ?

Sunday, March 29th, 2020

A software developer usually works on more than one platform or technologies in the organization he is working on. But those platforms or technologies usually fall under two categories.

The Front End and the Back End. Or Client Side and Server Side.

Front End Development
The front end is everything to do with what the user sees, including design of web pages, user interfaces and the entire user experience. Designing and maintaining the user experience is an important part of any software product, and it’s generally referred to as Front End Development.
Front End Technologies are HTML, CSS, Vue.JS, EmberJS, etc.

Back End Development
The back end, or the “server-side”, is basically how the software product works, updates, and changes. This refers to everything the user can’t see in their interface, like databases and servers.
Developing and maintaining the databases, servers and of course the actual business logic of the application is known as back end development.
Back End Technologies are much more varied. We have PHP, .NET, Java, Python, NodeJS and many more. It usually comes down to developer preference as all these tools are quite versatile.

In an application like Google Maps the Front End would be the actual application on your Android or iOS phone. The ability to scroll, pan across the loaded area of the maps, the option to search for locations and type in your destination are all to do with the front end. But once you’ve typed in your destination, the back end takes over. The data from the GPS module on your phone and your typed in destination are sent to Google’s servers. The back end receives this data. It determines your current location from the longitude and latitude values from your GPS. It determines the shortest route to your preferred destination. It also calculates all alternative routes and sends it back to your mobile phone. Then the front end takes the responsibility of displaying the optimal route along with alternatives in an easy to understand at a glance format.

Full Stack Development

Full stack developers have the ability to design complete web application and websites. They work on both the front end and the back end of their product of application. It naturally follows that they are well versed in technologies of both categories.

A technology stack is the set of technologies used to build an application. A technology stack usually comprises of a Server Platform, a Front End framework, a Back End language and a Database.

Here are the most popular Full Stacks used:
MEAN Stack: MongoDB, Express, AngularJS and Node.js.
MERN Stack: MongoDB, Express, ReactJS and Node.js
Django Stack: Django, python and MySQL as Database.
Rails or Ruby on Rails: Uses Ruby, PHP and MySQL.
LAMP Stack: Linux, Apache, MySQL and PHP.

[Tutorial] Mouse Macro Maker using jnativehook

Saturday, March 24th, 2018

Clicking can be a mundane task. Especially when you have to do it repeatedly without much thinking. I’m sure a lot of you have felt this. Many applications exist which offer mouse macro capabilities, but what’s the fun in that ?
Lets make our own program which will simplify clicking chores.

Naturally, jnativehook and java.awt.Robot are all we need. Java’s Robot class can effectively move and click your mouse without human intervention and jnativehook allows you to listen to system wide mouse and keyboard calls.

Graphical User Interface :
A simplistic GUI built using Eclipse’s Window Builder plugin should serve us well.

A button to start/stop recording the macro, one to load and one to save the macro are all we need. An integer spinner to set the delay between playback clicks is an added functionality.

Structure of the Application :
To keep the end code as simple as possible we only use two Java classes here. A Recorder class will be our main class. It implements jnativehook to record mouse clicks and save it in an easily readable text format. A Player class will read the saved macro and execute it using Java’s Robot Class.

 

The project can be found at https://github.com/Vetox/MouseMacroMaker

[Tutorial] Insaniquarium Deluxe Rapid Clicker

Wednesday, November 29th, 2017

Insaniquarium Deluxe is a 2D arcade game released by Flying Bear Entertainment and PopCap Games in 2004. It received huge critical acclaim and positive reviews across the board. It was one of the defining games which rocketed PopCap games to fame before Plants vs Zombies. The player uses the mouse to feed fishes, collect coins and fight aliens. The game revolves around mashing your left mouse button for hours on end until you beat the level. And then you repeat the same process for the next level. This seems like something which can easily be helped.

jnativehook, a java library which acts as a global mouse and keyboard listener could easily reduce the number of clicks we need.

jnativehook allows us to detect keyboard key presses and java’s Robot class allows us to easily simulate mouse clicks. That’s all we need to make Insaniquarium less insane.

Lets code an application which will issue a mouse click at the position of the cursor whenever it detects a specific key being pressed, lets say “S”. If we hold down “S” our program should keep issuing left mouse clicks at the cursor. This rate of clicking will invariably be much faster than physically possible. Thereby making feeding fishes, collecting coins and fighting aliens much easier on us.
We’ll also add the “P” key as a way to exit the program.

Pre requisite :
Include jnativehook in the build path.

GUI :
The GUI is built using the Window Builder plugin for eclipse.

Once a keyboard hook is added, all thats left to do is to override the nativeKeyPressed method:

public void nativeKeyPressed(NativeKeyEvent e) {
if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals("S")) {
try {
Robot r = new Robot();

for (int t = 0; t < 1; t++) {
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
}

} catch (Exception e1) {
System.out.println(e1.toString());
}
}

if (NativeKeyEvent.getKeyText(e.getKeyCode()).equals(“P”)) {
try {
GlobalScreen.unregisterNativeHook();
System.exit(1);
} catch (Exception ex) {

}
}
}

When the “S” key is pressed down, it rapidly issues mouse click commands at the position of the cursor. Making it much easier to collect coins and feed fishes in Insaniquarium.

Source Code :
https://github.com/Vetox/RapidClicker

[Tutorial] jnativehook : Control native mouse and keyboard calls outside Java

Wednesday, November 29th, 2017

In programming a “hook” is a way for a programmer to access already existing code and modify it to his specification. A mouse hook in java is quite similar to a MouseListener, except while a MouseListener functions only within the swing or awt component it is bound to, a native mouse hook can intercept mouse calls from all over the system. This makes it immensely useful for various kinds of programs. Here, I’ll try to explain how the jnativehook library can be used to detect mouse and keyboard calls.

jnativehook is an opensource native hook library for Java. It functions as a Global Mouse and Keyboard Listener.

jnativehook can be downloaded from its official GitHub page here :
https://github.com/kwhat/jnativehook/releases
Extract and add jnativehook to your build path.

Mouse Hook :
To use a Mouse Hook in your program, have your class implement NativeMouseInputListener.
Methods to override :
public void nativeMouseClicked(NativeKeyEvent e);
public void nativeMousePressed(NativeKeyEvent e);
public void nativeMouseReleased(NativeKeyEvent e);
public void nativeMouseMoved(NativeKeyEvent e);
public void nativeMouseDragged(NativeKeyEvent e);

These methods are self explanatory. Put the code you want to run when your mouse is clicked, pressed, released, moved or dragged in these methods.

To register jnativehook and cause it to start listening to mouse events globally, enclose this line in a try catch block :
GlobalScreen.registerNativeHook();

To unregister it :
GlobalScreen.unregisterNativeHook();

For a program which detects and outputs which mouse actions have been performed :

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

public class GlobalMouseListenerExample implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
System.out.println("Mouse Clicked: " + e.getClickCount());
}

public void nativeMousePressed(NativeMouseEvent e) {
System.out.println("Mouse Pressed: " + e.getButton());
}

public void nativeMouseReleased(NativeMouseEvent e) {
System.out.println("Mouse Released: " + e.getButton());
}

public void nativeMouseMoved(NativeMouseEvent e) {
System.out.println("Mouse Moved: " + e.getX() + ", " + e.getY());
}

public void nativeMouseDragged(NativeMouseEvent e) {
System.out.println("Mouse Dragged: " + e.getX() + ", " + e.getY());
}

public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());

System.exit(1);
}

// Construct the example object.
GlobalMouseListenerExample example = new GlobalMouseListenerExample();

// Add the appropriate listeners.
GlobalScreen.addNativeMouseListener(example);
GlobalScreen.addNativeMouseMotionListener(example);
}
}

Similarly for a Keyboard Hook have your class implement NativeKeyListener.
Methods to override :

public void nativeKeyPressed(NativeKeyEvent e)
public void nativeKeyReleased(NativeKeyEvent e)
public void nativeKeyTyped(NativeKeyEvent e)

The method NativeKeyEvent.getKeyText(e.getKeyCode()) will return the key that was pressed. Where e is the NativeKeyEvent accepted by each of the overriden methods.


import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class GlobalKeyListenerExample implements NativeKeyListener {
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
GlobalScreen.unregisterNativeHook();
}
}

public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}

public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}

public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());

System.exit(1);
}

GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample());
}
}

Overriding the nativeKeyPressed() method like above will output the KeyText of every button pressed. It will also unregister the nativehook if the “ESC” key is pressed.

INOI 2012 Triathlon problem [EDITORIAL]

Tuesday, June 27th, 2017

This problem featured in the Indian National Olympiad on Informatics in 2012. This problem is supposed to be of intermediate difficulty.
https://www.codechef.com/IOIPRAC/problems/INOI1201

The problem asks you to find out what is the minimum time in which the contest can be completed if you get to choose the order in which the participants start and given the times they take to complete each of the three tasks. Keep in mind that each task can only be completed if the previous task is completed before it.

There are a few observations to be made before we start solving this problem.

First of all the second and third tasks can be merged into one as they will be performed concurrently and sequentially by all the participants as soon as they have finished their first task.
d[i] = b[i] + c[i]
Where b[i] and c[i] are the times taken to complete the second and third tasks.

Now secondly, we need to decide in which order the participants will start. Think of it two at a time. What decides Person A will go before Person B given both their timing for the tasks ?

Assume Person A goes first and calculate the maximum time it will take. Now calculate it when Person B goes first. After some tedious analysis. It turns out that the person with the larger d[i] should go first. intuitively, it can be said that he will take a longer time to complete the second task and hence has to start it earlier. To do that he has to go first.

Now all we have to do is sort based on d values and let the contest proceed in that order. Calculate the end time of the contest and output it.

Java Code :
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

StringTokenizer st;
int N = Integer.parseInt(br.readLine());
int tim = 0;
Point p[] = new Point[N];
int ar[] = new int[N];
for (int i = 0; i < N; i++) { p[i] = new Point(); st = new StringTokenizer(br.readLine()); p[i].x = Integer.parseInt(st.nextToken()); p[i].y = Integer.parseInt(st.nextToken()) + Integer.parseInt(st.nextToken()); } Arrays.sort(p, new Comparator(){
@Override
public int compare(Point p1, Point p2) {
return p2.y – p1.y;
}
});
for(int i = 0; i < N; i++){ tim += p[i].x; ar[i] = tim + p[i].y; } int m = 0; for(int x : ar){ m = (x > m) ? x : m;
}
System.out.println(m);

}

}

OpenCV Experiment : Virtual On Screen Drums

Monday, June 12th, 2017

I was recently involved in a lot of Image Processing for a project at college and while I’m no longer interested in what I was working on, I still wanted to do something fun with whatever OpenCV and Image Processing Techniques I had learnt.

I imagined an “On Screen Drums Application” where we use a live video input to detect a “drumstick” we hold up and use to beat on a virtual drum causing it to reverberate depending on how hard we hit it.

Its not too complex and can quite easily be done with some simple OpenCV tricks in Java.

First we receive the video stream and process it frame by frame. We filter each frame for the specific color and shape of the marker on our “drumstick”. In my case, my drumstick is a bright orange ball stuck to a pencil. Once we’ve identified where the marker is, we compare its current position with its position in the previous frame to roughly calculate how fast it’s traveling.

We overlay an image of a drum on the video feed and when the marker touches the overlay, we use Java’s inbuilt MIDI synthesizers to generate drum noises depending on the speed at which the drum overlay was struck.

Identifying the marker :
We first convert the frame to HSV as that color palette is much easier to compute with, rather than RGB.

To identify the marker on the drumstick, start by filtering out its hsv value. A hsv range of (100, 100, 100) to (112, 255, 255) generally captures my marker alone and leaves out most other things.  Anything outside that threshold gets filtered out and that leaves us with just the marker. We run a couple of erode and dilate methods through the filtered image and that leaves us with a blob which is our marker in the frame. We also know the general size of the ball so getting the third moment of the blob would give its size. Checking if the moment is always larger than a fixed number would further eliminate mistakes.

Drawing the Drum overlay:
We use Java’s Graphics class to draw a drum overlay on the video feed. The overlay is an image of a drum cropped down to size and the rest of the screen filled with transparency. It’s saved in png format to preserve transparency.

Generating Drum Beats:
We initialize Java’s MIDI synthesizers and select the channel which sounds best. I liked channel 114 and that’s what I’ve used. I honestly can’t tell the difference between most channels, so it makes no difference to me. We check if the position of the marker intersects with the overlay on screen and if its velocity is greater than a suitable threshold. If so, then we tell Java to bang its virtual drums as hard as we virtually hit it.

The whole project is on my GitHub page at
https://github.com/Vetox/Virtual-On-Screen-Drum

Here are a few screenshots :
The marker on screen with the overlay

The same frame’s HSV image:

The same frame after filtering:

Save a life, wear your helmet !

Friday, May 12th, 2017

They say you never realize the value of something when you have it. You only realize its worth when you lose it. A helmet is an exception. Its worth its weight in gold no matter if its being used or not. I recently was involved in a motorcycle accident where my helmet possibly saved my life. I escaped with minor injuries but that would have been different had I not worn my helmet that day.

So, when buying my latest helmet after I lost my last one in the crash, I did extensive research. Here is what I’ve learned. Most of this applies to sports bikes. Scooters and cruisers generally have different requirements, but when it comes to safety, this information is mostly relevant.

Types of helmets from most to least protective :

Full Face :
This is the helmet I recommend under any circumstance. It provides maximum protection to your head and face. It will save your life under most situations and impart least impact to your head.

Modular Helmets :
These are a cross of the most protective Full Face and the least protective Half Face helmets. They are basically full faced but the chin bar can optionally be flipped up to make it a half face helmet.

Motocross Helmets :
These are helmets designed for motocross and off-road use. They have an angular shape and usually lack a visor. They are designed to be used with goggles. Usually they also have the same protective characteristics as Full face helmets but bear in mind that these were not designed for crashing on tarmac but on dirt rather.

Half Face Helmets :
This type of helmet covers the ears, cheeks, and back of the head, but the front of the face is exposed as a result of the lack of the chin bar. These aren’t very protective in nature as a lot of the impact is felt through your face, causing your face to take the brunt of the impact. Usually these can leave you with bad injuries on your face, but your brain would still be intact.

They say, wear a helmet.
But if you ask me, I’d say wear a FULL FACE helmet, ALWAYS !

Helmet buying guide (India)

Alright lets begin on which helmet to buy if you are in the market looking for one. It comes down on how much you are willing to sacrifice on safety for a lower price tag. Here are the best helmets in India at various price points.

Under 1000:
Lets not even go there. If you are desperate for a helmet under 1000, there isn’t one I can recommend without feeling guilty about it. So just pick up a random one from a vendor from the side street and be done with it. It doesn’t matter which one it is, chances are you’ll not be bothered to put it on anyway given you wont be bothered to spend a few bucks on a safety device which can potentially save your life. In short, spend more and then we can talk.

Under 2000:
Now, this is where the market opens up to the real headgear. Helmet in this range usually have only the most basic features. Not too ergonomic shells, non-existence of different sizes, and other problems can be felt. But, they do a pretty basic job of keeping you safe.
The Vega MotoCross Helmet comes at 2000 INR and is pretty popular. I know, its a motorcross helmet not designed for the road, but most people don’t care. The dual visor feature is a nice addition.

We also have the SteelBird Air series which again comes at around 2000 INR. These are proper full face helmets I’d recommend to anyone owning an entry level sportbike (Hint. R15s and CBR 150s).

Helmets under 2000 can usually be found with the ISI quality mark. Which is supposed to be OK, but I have a hard time trusting them. The DOT standards are much better and safer if you ask me.

Under 5000
Here is where the real helmets start showing up. We can expect internationally recognized brands and DOT certifications across the board. Wearing one of these will definitely boost your confidence when riding.

LS2 Tech Matt
A standard offering from LS2, comes with everything needed in a helmet you’d plan on using for a long time. Washable interior lining, a sturdy quick release catch, polycarbonate shell, air flow vents and of course DOT certification. Priced at 4500 INR, the only issue with LS2 is that since there are no authorized distributors of LS2 products in India, most of the pieces you’d find are fakes. Stay clear unless you are sure of its authenticity.

MT Axxis
A personal favorite of mine, this is the base model from MT. DOT certified, D Ring fasteners, washable lining, racing polycarbonate shell, aggressive styling and scratch resistant visors make for a great helmet for beginner and veteran bikers alike. Priced at 4570 INR, this is the absolute best in protection gear under 5000 INR as of now.

Safe Riding,
Karthikeyan M

My list of recommended Web Comics

Sunday, April 23rd, 2017

Who doesnt love comics. And who doesnt love the web ? See where Im going with this ?

And you get Web Comics. An amazing story full of with cliff hangers as you wait a whole week to read three panels and maybe months together to get a complete fulfilling scene play out. But, they do have their appeal. The variety of authors and their individualism in expression come together to ensure that however dark or cheerful you are, there is definitely a webcomic out there so tailored to you that youll feel as if you wrote it yourself.

Undead Ed :
UnDeadEdA completed story by Boredman a french cartoonist with a dark but equally quirky art style. Is a zombie also a ghoul ? Do vampires drink red wine or white wine ? The protagonist gets to find out.
Read for the funny story, well laid out art and also the very funny jokes.

unOrdinary :

A recently started toon which takes place in a normal school setting, complete with normal students who have superpowers. Very normal isn’t it ? The art is good but has nothing which stands out. None the less, the story is a must read. Youll feel compelled to read this week after week. John the new transfer student says he has no powers, and so is bullied by everyone else. But obviously he, being the protagonist has somewhat of a troubled past.

Live with Yourself! :

Have you wondered how/what youll be when you are 60. And also, we wonder about our baby days. We keep wondering about tomorrow as well. One person split into his baby-self, tomorrow-self and 60 year old-self become housemates as they wonder how they each return to their own timelines. Thats the premise of this comic obviously authored by Shen. Shenpai has a very striking art style which has become his trademark.

 

Tower of God :

I couldn’t find an image to describe TOG better so bear with this promo poster I had to dig up. A beautiful story with long chapters every week, lots of characters, cool powers, complex plot and even more complex plot tools. The premise may never fit in with reality, but the sheer weight of the story begins to grow on you. You’ll get confused with the names and the characters a lot and that might be a big issue had the story and its execution not been so top notch.

Questionable Content :

A long running comic by Jeph Jacques. He basically writes this for a living, you can see his art style improve vastly over the years, the character development is amazing, new faces come and go but they are always properly built up that you feel sad they are going. Must read, but just be prepared to be in for a lot of it.