Are you alive?

If you are actually living (not just surviving), you have probably experienced many disappointments in your journey. However, if your growth in life is following a linear function, then probably you are not alive or it’s better to say, you don’t want to. It is likely that you don’t do anything exciting in your life or you prefer to take a safe path and not taking any risks in your lifetime.

Imagine this chart:

Growth in life - linear

 

Above chart illustrates a boring life. Bullshit. It means you don’t enjoy your life and one day you will get bored of and you will regret the decisions you could have made but you didn’t. It doesn’t really matter if you are following a y = x, y = x/2 or y = 1. This is a boring life.

Whereas, consider this one:

Growth in life - better version

This one shows the growth of someone that wants to take a risk. Wants to experience new things and explore the world. If you ask yourself that you really like to take a risk and make a change in your life, the answer of your heart is “yes”. We, as humans, have something that no animal has. We are in charge of our lives and we have to accept dark moments to gain more.

I decided to write this post and share my opinions when I experienced a terrible situation a few days ago. This is what happened.

 

Shit happened

About 4 years ago, I decided to start my own software company and spend my time on what I wanted to. I did that and I spent a year to establish the company with my friends.

I was young and I didn’t know how important contract and legal work is. We started the company, I built the software but I didn’t have anything to prove that I own a part of the company (slow clap).

One of the guys designed a fake argument and as a result, they took my share of the company. And yes, they had access to the entire source code. I didn’t have any other choices but to start from scratch, again. I started interviewing with a few companies. It was unbelievable. I can’t explain how terrible that feeling was.

I spent a week at home to think and relax a bit. Then I said to myself, I have to start my own open-source project. I don’t remember how I came up with this decision but the result of that decision was Introjs.

 

Shit happened, again

A few days ago, I experienced one of my darkest moments in my life. I heard a disappointing news, and I had to accept that. There were no alternatives.

I signed a game changer contract but after a few weeks, the company forced me to terminate the contract, due to a ridiculous legal problem. The reason is not important though.

I spent a week, analysing my life, my goals and what I really wanted to do. I had two options. To keep thinking about the negative and dark parts of my life, and that event. Or, take advantage of what happened. I took the latter path.

 

What I’m going to do?

I decided to work harder. Prioritising tasks in my life and spending more time on the important ones. Reading more books and using my spare time better.

Just because that thing happened, it doesn’t mean I will use it as an excuse.

I made the decision to work on Juggernaut and start my dream project, Streamer.js. I will publish the updates soon.

 

Do what your heart asks

I wrote this blog post as a reminder for myself. Those things have happened to me and it is very likely to experience the same situation again in the future.

Everything that happens once can never happen twice. But everything that happens twice will surely happen a third time.

I wrote this post to have something to refer to and recharge my batteries.  Stay strong, keep going.

Don’t abuse language features

Recently we had a situation in a ES6 project. We were using some of new features ES6 in a wrong way. I’m writing this blog post to explain what was the issue and what is the solution to avoid these kind of problems it the future.

ES6 Promise

We designed a Message box class which accepts a title, text and buttons. Then, you can call open to display the message box. User can decide to click on Yes or No button (assume there is a Accept / Reject button on the message box).

That open function returns a Promise which fulfills the Promise if user clicked on Yes and rejects it if you click on No button. Therefore you can decide what to do with the Promise.

This is sample of that API:


let msg = Message({ 
	text: "Hello world", 
	title: "Are you sure?",
}).open(); //msg is a Promise now 

 

Now, to test and see if user clicked on Accept or Reject button, you can use then() or catch() of Promise object. But we didn’t use these functions. Instead, we use try...catch with async / await keywords.

Incorrect usage of Promise

Another way to handle Promise is to use async and await keywords, like so:

 


(async function () {
	try {
  	let res = await ReturnPromise();
    console.log("gotcha", res);
  } catch (e) {
	console.warn('opssss');
  }
}());

 

It would reach the catch block if user clicked on Reject and the try block if Accept (actually, it would execute anything after await keyword, otherwise, it throws an exception and hits the catch block).

Well, above usage is correct, too, but there are many problem with that approach:

1) Suppressing errors

If you add anything to that try block, you would need to handle the errors on the catch block. If you don’t handle them in try catch block, it would suppress the errors and wouldn’t be able to understand what is going on in your application in case of any errors.

2) Catch block

You cannot remove the catch block. You should either leave it empty or add something between the catch block. Imagine your application with a milion of empty catch blocks:


(async function () {
	try {
  	let res = await ReturnPromise();
    console.log("gotcha", res);
  } catch (e) { } // <-- this is the empty block
}());

 

Also, sometimes you just need to handle the Accept case and there is no need to handle the catch or Reject case. Now, you can’t do anything but adding an empty catch block.

3) You are not handling an error!

You should use try catch when you want to handle an error and do something instead of letting the application to crash and exit the main. Is that case, we were not handling an error. Clicking on a Reject button is not an error.

 

Write maintainable code

Remember, you are writing codes and it should be readable and understandable for other contributors and if you use some sort of weird syntax in your program, it doesn’t prove anything about the level of your coding skills or how talented you are. A good code is boring to read.

OpenAI bot vs. Dendi – The International 2017 Dota2

Dendi is one of the most famous Dota2 players, because of his abilities in playing with Pudge. Last night, as a part of The International 2017, Dendi played with an OpenAI bot.

The funny part is, he lost the 1 vs. 1 two times and then he said, “I give up!”. Apparently, the bot was so accurate.

 

Blocking creeps

When it comes to blocking the creeps. the bot played much better than Dendi. This is the first game when the bot blocks creeps.

In the second game, there were two lines of creeps but the bot managed to block both lines very nicely.

 

First blood

In the second game, the bot drew first blood in a very complex situation. Under the tower with half hp.

And the nice part of this fight is, the bot used his 3rd skill (not first or second skill) to accurately hit the target.

 

Conclusion

This is so amazing that Dota2 introduces AI this year. Probably, something more important is going on behind the scene. We have to wait and see how AI and this relationship with OpenAI would affect the experience of Dota2 in the future.

This is the official blog post from OpenAI team that explain the process of training the bot and techniques that the bot can utilize to defeat the opponent: https://blog.openai.com/dota-2/

Character density using Haskell

In this short tutorial, I’m going to write a simple Haskell program to calculate the density of characters in a given text. For instance, in “hello” we have [('e',0.2),('h',0.2),('l',0.4),('o',0.2)].

The return format of our application would be a list of tuples

String -> [(Char, Float)]

To make the problem easier to solve, I’m going to break it into two programs. One that returns the number of repeats for each character and another program that converts that list to a percentage of repeats.

Count of repeats

freq_letter :: String -> [(Char, Int)]
freq_letter str = [ (x,c) | x <- ['a'..'z'], let c = (length.filter (==x)) str, c>0 ]

This program returns a list of tuples with the Char and Int. First item of tuple is the character in the given text and the second parameter, Int, is the count of repeats in the text. Executing this program will return:

*Main> freq_letter "hello"
[('e',1),('h',1),('l',2),('o',1)]

Percentage of repeats

freq_letter_pc :: String -> [(Char, Float)]
freq_letter_pc str = [ (char, fromIntegral(count) / fromIntegral(length str)) | x <- freq_letter (map toLower str), let (char,count) = x]

Second part of the application uses the previous program to get the list of repeats and then divide them by the length of the given text. This way we can calculate the density of characters in the text. Executing this program returns:

*Main> freq_letter_pc "hello"
[('e',0.2),('h',0.2),('l',0.4),('o',0.2)]

That's it.

Conclusion

In this tutorial, we have learnt how to calculate the density of characters using Haskell. Achieving this goal is much easier in Haskell because of list comprehension and higher order functions.

How to fix "Library not loaded: libmysqlclient.18.dylib" in Mac OS X

Well, sometimes a blog simple tip can save a day. That’s why I created this blog.

In this post, I’m going to show a simple way to fix Library not loaded: libmysqlclient.18.dylib error. It could happen when you upgrade your MySQL to the latest version (here it’s 5.7.10).

Just run following command:

sudo ln -s /usr/local/Cellar/mysql/5.7.10/lib/libmysqlclient.dylib /usr/local/lib/libmysqlclient.18.dylib

OR

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

The reason for that error is that your client (let’s say Python Django) is unable to find your libmysqlclient library. That way you can link that library again. everything else should work fine.

Source: New feed

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, '2') == Math.pow(2, 4); //2^4 = 16
//and so on

So, how to make 10, 100 or 1000? Using shift operations you can make it:

1 << 1 //2
1 << 2 //4
1 << 3 //8
1 << 4 //16

A short explanation of above source code is that the binary of 1 is 00000001 and when you use left shift operator, the result is 00000010, 00000100 and so on.

So the answer is to use a for-loop for N:

var sum = 0;
for (var i = 1;i <= n;i++) {
  sum += 1 << i;
}
console.log(sum);

 Can we make it better?

Yes. Here is the final hack.

The sum of first N powers of 2 is 2^(N + 1) - 2. For instance, n = 3:

(2 ^ (3 + 1)) - 2 = 16 - 2 = 2 + 4 + 8 = 14

And then, using bitwise operations we have:

console.log((2 << n) - 2);

Please note that the binary of 2 is 00000010.

Actually, this is the right answer.

Edit: You can find more interesting examples here: http://www.cs.utsa.edu/~wagner/knuth/fasc1a.pdf

Source: New feed

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: www.mongodb.org):

aggregation-pipeline.png

 Example

Let’s assume we have a users collection with following records:

[{
  _id: '55329ec72d3c018764000001',
  name: 'Steve',
  role: 'admin',
  age: 35
}, {
  _id: '55329ec72d3c018764000002',
  name: 'Guillermo',
  role: 'admin',
  age: 28
}, {
  _id: '55329ec72d3c018764000003',
  name: 'Roshan',
  role: 'user',
  age: 45
}]

 Example with two stages

Following aggregate operator has two stages, $sort and $limit:

User.aggregate([{
  $sort: { age: -1 }
}, {
  $limit: 2
}], function (err, records) { 
  //...
});

First of all, the aggregate operator executes the first stage. The result set for the first stage is the whole collection records. $sort operator sorts the users collection by age field. The result of the first stage is:

[{
  _id: '55329ec72d3c018764000003',
  name: 'Roshan',
  role: 'user',
  age: 45
}, {
  _id: '55329ec72d3c018764000001',
  name: 'Steve',
  role: 'admin',
  age: 35
}, {
  _id: '55329ec72d3c018764000002',
  name: 'Guillermo',
  role: 'admin',
  age: 28
}]

Then, the second stage gets the sorted array of users from previous stage and eliminates a record. Finally, the result of aggregate operator will be:

[{
  _id: '55329ec72d3c018764000003',
  name: 'Roshan',
  role: 'user',
  age: 45
}, {
  _id: '55329ec72d3c018764000001',
  name: 'Steve',
  role: 'admin',
  age: 35
}]

You can find more operators for aggregation stages here: http://docs.mongodb.org/manual/reference/operator/aggregation/

 Conclusion

Aggregate operator is a pipeline of stages. It accepts an array of stages and each stage has a operator. The first stage gets all records of the collection and after performing the operator, passes the result to the next stage.

Source: New feed

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 command:

npm install

This command installs all required dependencies including AWS sdk.

 Configuration

This tool has a simple config.js file that defines all dependencies to run the mongodump command and upload it to the Amazon S3 storages. Here you can find a list of all dependencies: https://github.com/afshinm/mongodb-backup#configjs

 Go go go

Final step is to run the script. You can run the cronjob using following command:

node index.js start

And if you want to run the script as a deamon, install forever using npm install forever and then run this command:

forever start index.js start

 Conclusion

This version of mongodb-backup works with Amazon S3 but I will publish another version soon that accepts FTP and SFTP to transfer backup files.

Source: New feed

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 map variable should be:

Map {Object {a: 1} => "boo", Object {a: 2} => "foo"}

Besides, you can get the item with get:

map.get(keys[0]); //returns `boo`

Or set a new value for one of items:

map.set([keys[0], 'new value');

Here you can read more about Map feature in ECMAScript 6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Source: New feed

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());

Awesome, isn’t it?

I will write more blog posts about ECMAScript 6 features soon.

Source: New feed

Source: New feed