Afshin Mehrabani

Programmer, open-source lover. Creator of IntroJS, PACKT publishing author and technical editor.

Read this first

Optimized solution to calculate first powers of 2

I experienced many programming contests and olympiads but this one was really different. In a programming contest on Hacker Rank, I faced with a challenging problem and it was the main reason I failed the test. That question made me nervous and stressful so I gave up. When I found the solution after the test, I laughed so loud.

The question is:

Calculate sum of first powers of 2 without using any built-in language API to calculate the power. Implement optimized solution.

Well, there are two factors. First, not using built-in functions like Math.pow and second implementing the optimized solution. So, of course a recursive function or for-loop is not the answer.

Answer

Use bitwise operations. How? Ok, let me show you a trick.

parseInt(10, '2') == Math.pow(2, 1); //2^1 = 2 parseInt(100, '2') == Math.pow(2, 2); //2^2 = 4 parseInt(1000, '2') == Math.pow(2, 3); //2^3 = 8 parseInt(10000,...

Continue reading →


MongoDB Aggregation

MongoDB has a aggregate operator that help programmers to define complex type of queries and combine operators such as group, match and find to build a complete result set.

Unfortunately, this operator doesn’t have enough tutorials and examples so I decided to explain it in better words.

Aggregate is a pipeline

First of all, you should know that aggregate is a pipeline of different operators. So, what does it mean?

The aggregate operator accepts an array of stages:

db.collection.aggregate( [ { <stage> }, ... ] ) 

Each stage contains an operator such as $match, $limitor$project. After executing,aggregate` operator starts to perform each stage one by one. It’s important to know that each stage get the result set from the previous stage and the result set for the first stage is all records of the collection.

Following diagram illustrates a sample aggregate procedure (source:...

Continue reading →


Scheduled backup for MongoDB

MongoDB is one of NoSQL pioneers and it has a great community. Nowadays, most of startups prefer to use MongoDB as the main database because of its simplicity. Configuring scheduled backup for a database is really important to keep the last updated data somewhere and restore it in case of database crash.

In this post I want to introduce a simple open-source tool that I’ve recently published to setup a minimal scheduled backup for MongoDB.

Dependencies

I built this tool using Node.js so first of all you need to install http://nodejs.org/. I will publish a binary version for all platforms soon.

You need no more dependencies but official Node.js module. In the next step we will install them using npm.

Install

I named this tool mongodb-backup and you can clone the repository from Github:

https://github.com/afshinm/mongodb-backup

Then go to the folder of project and run following...

Continue reading →


Using `object` as the keys of another `object` in JavaScript

Sometimes you need to use objects for the keys of a dictionary (let’s say, another object).

Assume this code:

var keys = [{a: 1}, {a: 2}, {a: 3}]; var dic = {}; //add a new key to the dictionary dic[keys[0]] = 'boo'; dic[keys[1]] = 'foo'; 

Above code yields this result:

console.log(dic); //Object {[object Object]: "foo"} 

So the dictionary doesn’t have two items because object keys cannot be object. You can get the item with [object Object] string:

console.log(dic['[object Object]']); //returns `foo` 

Ok, wait. Then how we can set objects as the keys of a dictionary?

ECMAScript 6 - Map

Map feature in ES6 enables you to assign objects as the keys of a dictionary (or another object).

Here is the ES6 compatible of the previous example:

var keys = [{a: 1}, {a: 2}, {a: 3}]; var map = new Map(); //add a new key to the dictionary map.set(keys[0], 'boo'); map.set(keys[1], 'foo'); 

And the ...

Continue reading →


Block scope variable - ECMAScript 6

Since some of ECMAScript 6 features looks weird to old-fashioned JavaScripters, I’m going to write a series of blog posts to describe the main idea of some common ECMAScript 6 features.

In this posts I’d like to explain the usage of block scope variables. The keyword let enables you to create a block scope variable in ECMAScript 6:

let boo = 1; 

So, what’s the difference between var boo = 1; and let boo = 1;? Assume following example:

function sample() { if (true) { var boo = 1; } return boo; } console.log(sample()); //returns 1 

In the above old-fashioned code, boo variable is defined within the sample function scope so we have the value even outside of the if statement.

With let variable you can create a variable that is available within the if statement block:

function sample() { if (true) { let boo = 1; } return boo; //ReferenceError: boo is not defined } console.log(sample()); 
...

Continue reading →


Python: List and Tuple performance benchmark

Suppose you have two options to implement a solution using a programming language, what are important factors to select one of options? I do believe one of concerns for a programmer would be performance benchmark between those options.

In this short blog post I’d like to share my simple code and results for performance benchmark between Python list and tuple. Two features to create a list, but with this difference, that tuples are immutable and you can’t alter them after initializing.

Following code shows a simple usage of list and tuple to create a series of items:

# this is a list, you can alter it in next lines l = [1, 2, 3, 4, 5] # this is a tuple and it's immutable t = (1, 2, 3, 4, 5) 

Please note that you can store different data types as an item for both tuple and list.

My scenario to make a performance benchmark between list and tuple is retrieving 2,000,000 random items from...

Continue reading →


Using Redis as session store for ExpressJS + PassportJS settings

Since all other articles about using Redis as a session store for ExpressJS are out of date due to latest update of connect-redis, I’m going to write this short article to show how to use Redis as session store for ExpressJS.

In order to use Redis as session store for ExpressJS, first of all install connect-redis package using npm:

npm install connect-redis 

Then, add connect-redis to your dependencies and Following code shows the content of app.js file:

var express = require('express'); var RedisStore = require('connect-redis')(express.session); app.use(express.session({ store: new RedisStore({ host: '127.0.0.1', port: 6379 }), secret: 'hey you' })); 

If you’re using PassportJS for users authentication, you can simply add two following lines to your app.js file to enable PassportJS as well:

app.use(passport.initialize()); app.use(passport.session()); 

That’s it. Now you have...

Continue reading →


Why C# is not a good choice for web development?

C# is the main programming language in Iran. I’ve worked with several teams, various projects and developers with different development skills. Earlier I’ve worked with PHP.

There weren’t any motivations to migrate from PHP to C# but the company’s infrastructure. Most of web development companies in Iran work with C# and Microsoft technologies, and here is the reason, because they don’t want to learn more. Companies prefer to stay at the same level and do not pay for improving their developers skills!

If you ask them: “Why you are using C# for web development?” I bet they won’t give you acceptable answer.

I haven’t used C# for my own projects, and I won’t at all. It’s preferable to me to use NodeJS or Python, not only because of their popularity, but because they are scripting languages.

After spending ages with C#-based web apps I want to tell something horrible about this language...

Continue reading →


How to fix `setImmediate is not defined` error in NodeJs

The setImmediate function introduced in NodeJS v0.10.x to queue functions. It works like process.nextTick function but with a difference in functionality. Read JohnnyHK’s answer to figure out: http://stackoverflow.com/a/15349865/375966

Most of the time, by upgrading the NodeJS core to v0.10.x it can simply solve your problem.

tldr; Upgrade your NodeJS to v0.10.x.

Continue reading →


Become a CreateJS Ninja with “Getting Started with CreateJS” book

Nowadays using HTML5 technologies to develop web pages are become more commonplace and consequently HTML5-based libraries are become more popular. CreateJS is one of popular and successful libraries for creating rich HTML5-based web pages.

What is CreateJS?

A suite of Javascript libraries & tools for building rich, interactive experiences with HTML5.

CreateJS consist of four different libraries and each one is responsible for specific part of HTML5 technology.

  • EaselJS
  • TweenJS
  • PreloadJS
  • SoundJS

With combination of all parts you can develop a rich web application easily.

Getting Started with CreateJS

If you want to start learning CreateJS as fast as possible, “Getting Started with CreateJS” book with Packt Publishing is a good starting point. It’s a step-by-step tutorial for all CreateJS subsets. The book consists of many practical examples that help you to learn faster.

Getting Started with CreateJS - Cover.jpg

If...

Continue reading →