WordPress Hybrid Client: v1.2.0 released

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

With WPHC you will be able to generate iOS and Android applications in a blink of an eye. Before anything you will need to install WP-API plugin which basically will turn your Website into a REST API.

Then you can refer to the documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

v1.2.0 ChangeLog

milestone

Sending push notifications to Android via Gulp

If you ever wondered how to test that your push notifications work on Android without setting up any server here is how to do.

Install

npm install gulp node-gcm

Get Api key, Sender ID and Device ID

In order to be able to send push notifications we need only need the Google Cloud Api key, and the device ID(s).

To get the Api key and the senderID you can register there: https://developers.google.com/mobile/add

As for the device ID it can be found once your device is registered.

If you are using this Cordova plugin https://github.com/phonegap-build/PushPlugin you can get it like this (note that the senderID is used here):

document.addEventListener("deviceready", function() {
    var pushNotification = window.plugins.pushNotification;
    pushNotification.register(
        successHandler,
        errorHandler, {
            "senderID": "replace_with_sender_id (12 digits number)",
            "ecb": "onNotification"
        });

    function onNotification(e) {
        switch (e.event) {
            case 'registered':
                if (e.regid.length > 0) {
                    // Your GCM push server needs to know the regID before it can push to this device
                    // here is where you might want to send it the regID for later use.
                    console.log('Device id', e.regid);
                }
                break;
        }
    }

    function successHandler() {}

    function errorHandler() {}
});

Script

Now that you have both Device ID and Api key let’s create a script that send push notifications.

gulp.task('push:android', function() {
    if (!gutil.env.apiKey || gutil.env.apiKey === true) {
        throw new Error('You must specify the android Api key, refer to the documentation');
    }
    if (!gutil.env.deviceId || gutil.env.deviceId === true) {
        throw new Error('You must specify the android ID, refer to the documentation');
    }

    console.log('apiKey', gutil.env.apiKey);
    console.log('deviceId', gutil.env.deviceId);

    var gcm = require('node-gcm')

    var message = new gcm.Message({
        collapseKey: 'demo',
        delayWhileIdle: true,
        timeToLive: 3,
        data: {
            key1: 'message1',
            key2: 'message2'
        }
    });

    var sender = new gcm.Sender(gutil.env.apiKey);

    sender.send(message, (gutil.env.deviceId instanceof Array) ? gutil.env.deviceId : [gutil.env.deviceId], 5, function(err, result) {
        if (err) {
            console.error('Failed, status code', err);
        } else {
            console.log('Success', result);
        }
    });
})

Run

You can run the script like like this on one or several devices:

# One device
gulp push:android --apiKey YOUR_API_KEY --deviceId YOUR_DEVICE_ID

# Two devices
gulp push:android --apiKey YOUR_API_KEY --deviceId YOUR_DEVICE_ID --deviceId YOUR_DEVICE_ID

If everything is fine you should have your push notifications working.

Commun error

If your api key and senderId are not ok you will get this error message:

Success { multicast_id: 7412383159195664000,
  success: 0,
  failure: 1,
  canonical_ids: 0,
  results: [ { error: 'MismatchSenderId' } ] }

If so regenerate a api key using this link https://github.com/phonegap-build/PushPlugin.

Toptal interview process explained

Introduction to toptal

Toptal is platform for Freelancers to meet clients from all over the world. It is similar to freelancer.com, elance.com or upwork.com but with a big difference, Toptal claims to have the best freelancers there are thanks to a high level interview process. Here is a video that will help you better understand Toptal.

It took me two months to go through all the interview steps to become a Toptal Engineer, part of the so called The Top 3%! Here is how things went:

Interview process

Language & Personality (26.4% pass)

The first step in the screening process is a comprehensive language, personality, and communication interview. Candidates must be able to read, write, and speak English extremely well.

You need to show them that you are invested and passionated about your work (maybe you have a blog or you commit on famous open source projects etc.). Find something that makes you an above average developer and start from there.

Be yourself, do not be stressed and everything will be alright.


Timed Algorithm Testing (7.4% pass)

This step checks for computer science fundamentals, problem solving ability, and intellect. I spent days going through old algorithm books and refreshing my memory about famous algorithms time complexity. If you do not have at least the background listed in this article: JavaScript background to have before any job interview with top companies do not even try.

You will have 90 minutes to solve three algorithms on https://codility.com/. To be honest you cannot do all of them in the given time, focus only on two but make them great! Obviously I cannot disclose the content of those tests but let just say that they were really different from each other and therefore required a large algorithm knowledge.

This is the most difficult part of the interview process. If you do not spend some time learning algorithm basics you will fail. My advice is to get back to your university books and train as much as you can. Open Codility and start coding! If you need a little help my solutions are available on this post: Codility efficient algorithm solutions in JavaScript


Technical Screenings (3.6% pass)

Each candidate is screened by at least two certified Toptal engineers. Each screener will provide specific live coding exercises that cover core topics within the candidate’s primary tech stack.

You will have the choice between a back end or a front end test. I obviously selected the front end test. You will have real life problems to solve using a specific technology. For me it was jQuery, and to be honest at the beginning I was a little bit skeptical on my ability to succeed as I did not used jQuery for a while but I sorted things out pretty easily.

If you have the experience you claim to have, you should not have any difficulty with this step.


Test Projects (3.2% pass)

Ok now we are talking! If you arrive here, it means that you are pretty good at what you do but this step is somehow special. It tests your ability to commit to a project and your willingness to become a Toptal engineer! It is a great way to demonstrate technical competence, thoroughness, professionalism, and integrity.

I have heard there are several projects that you can end up with. One of them is a classic Todo list but the one I got was the creation of a Web page form that creates new users dynamically. I received around 20 wireframes that I had to bring to life in two weeks time using the technology that I wanted.

It had to be pixel perfect and fully functional. I am more of a mobile (cordova), single page application kind of guy so I actually learnt stuff doing this project. For example to help you doing pixel perfect pages you can use the Perfect pixel Chrome extension.

What I believe is that they are trying to give you a project that is a little bit far from your comfort zone to test your ability to learn/discover new stuff while delivering high quality projects.

I chose to use Webpack, Bootstrap 3 and jQuery and I spent around 20 hours to finish this project.

Once it is done you will review the project and the code with a recruiter and that’s it, the interview process is now over and if you are lucky enough you will be part of Toptal 🙂

Select only technologies that are mature enough, you do not want to waste time on bugs that are not part of your code.


Acknowledgment

I personally wanted to thank recruiters and engineers that I talked to. They are really professional and are here to help you succeed.

Conclusion

Overall this experience was really good to me, during the process I wrote greats articles JavaScript background to have before any job interview with top companies and Codility efficient algorithm solutions in JavaScript that really helped me reviewing my basics and taught me that in life nothing is impossible as long as your are brave enough.

In case your are interested in my profile: http://www.toptal.com/resume/julien-renaux

WordPress Hybrid Client: v1.1.0 released

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

With WPHC you will be able to generate iOS and Android applications in a blink of an eye. Before anything you will need to install WP-API plugin which basically will turn your Website into a REST API.

Then you can refer to the documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

v1.1.0 ChangeLog

milestone

[Chrome extension] The Great Suspender

Just wanted to share about a great tool I have just discovered:

“The Great Suspender” is a free and open-source Google Chrome extension for people who find that chrome is consuming too much system resource or suffer from frequent chrome crashing. Once installed and enabled, this extension will automatically suspend tabs that have not been used for a while, freeing up memory and cpu that the tab was consuming.

Available on GitHub and on Chrome store

JavaScript background to have before any job interview with top companies

Data types and data structures

In JavaScript, there are 6 primitive data types, a primitive (primitive value, primitive data type) is data that is not an object and has no methods.

Primitives

Boolean

In computer science, a boolean is a logical data type that can have only the values true or false.


Null

In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address.


Undefined

A primitive value automatically assigned to variables that have just been declared or to formal arguments for which there are no actual arguments.


Number

In JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754). In other programming languages different numeric types can exist, for examples: Integers, Floats, Doubles, or Bignums.


String

In any computer programming language, a string is a sequence of characters used to represent text.


Symbol (new in ECMAScript 6)

A Symbol is a unique and immutable primitive value and may be used as the key of an Object property.

const MY_KEY = Symbol();
let obj = {};
    
obj[MY_KEY] = 123;
console.log(obj[MY_KEY]); // 123

Object

Object refers to a data structure containing data and instructions for working with the data. Objects sometimes refer to real-world things like a user for instance:

var user = {
    "first_name" : "Julien",
    "last_name" : "Renaux"
}

console.log("My name is " + user["first_name"] + " " + user["last_name"]); // My name is Julien Renaux

Algorithm time complexity (Big O)

Complexity is express using big-O notation. For a problem of size N:

  • a constant-time method is “order 1”: O(1)
  • a linear-time method is “order N”: O(N)
  • a quadratic-time method is “order N squared”: O(N2)

big_o


For loop: O(N)

The loop executes N times, so the sequence of statements also executes N times. Since we assume the statements are O(1), the total time for the for loop is N * O(1), which is O(N) overall.

for (var i = 0; i < N.length; i++) {

}

Several For loops: O(max(N,M))

for (var i = 0; i < N.length; i++) {

}

for (var j = 0; j < M.length; j++) {

}

Nested For loops: O(N * M)

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. If N equal M then the complexity is O(N^2).

for (var i = 0; i < N.length; i++) {
    for (var j = 0; j < M.length; j++) {

    }
}

Sorting: O(N*log(N))

Typical serial sorting algorithms good behavior is O(N*log(N))

N.sort(function(a, b){
    return a - b;
})

Classic Algorithms

Algorithmic questions are a classic especially in Nord American companies. Facebook, Google, Twitter they all.

What interviewers seek is to see if you can logically resolve some of the basic problems known to computer science. The following algorithms will be as clear as they can be so you can understand the logic. It is not about algorithm elegance nor performance.


Binary search

Binary search is one of the fundamental algorithms in computer science. In its simplest form, binary search is used to quickly find a value in a sorted sequence. git bisect uses it to quickly find the commit that introduced a bug.

function binarySearch(haystack, needle) {
    var lo = 0,
        hi = haystack.length - 1,
        mid;
    while (lo <= hi) {
        mid = Math.floor((lo + hi) / 2);
        if (haystack[mid] < needle) {
            lo = mid + 1;
        } else if (haystack[mid] > needle) {
            hi = mid - 1;
        } else {
            return mid;
        }
    }
    return -1;
}
// Unsorted list
var list = [80, 9, 700, 40, 1, 5, 200];

// Now sorted
list.sort(function(a,b){
    return a - b;
});

// In which position is the number 200? Response: 5
binarySearch(list, 200);

Complexity: Since each comparison binary search uses halves the search space, we can assert and easily prove that binary search will never use more than O(log N) comparisons to find the target value.


Prime number

function isPrime(n){
  var divisor = 2;

  while (n > divisor){
    if(n % divisor == 0){
     return false; 
    }
    else
      divisor++;
  }
  return true;
}
// Response: true
isPrime(137);

// Response: false
isPrime(237);

Fibonacci

In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence: 0 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 …

It is defined by the recurrence relation: Fibonacci recurrence relation

Code Recursive

The below algorithm performs is elegant but not efficient when the sequence grows exponentially,
we get an inefficient solution.

function fibonacci(n){
    if(n < 2) return n;
    return fibonacci(n-1) + fibonacci (n-2);  
}
fibonacci(2); // Response: 1
fibonacci(3); // Response: 2
fibonacci(4); // Response: 3
fibonacci(5); // Response: 5

Complexity: O(2^n) Why?

Code dynamic programming

We can calculate the values F0, F1, . . . , Fn based on the previously calculated numbers (it is sufficient to remember only the last two values).

function fibonacci(n){
    var fiboSequence = [0, 1];
    
    if (n < 2) return n;
    
    for (var i = 2; i <=n; i++ ){
        fiboSequence[i] = fiboSequence[i-1] + fiboSequence[i-2];
    }
    
    return fiboSequence[n];
} 
fibonacci(2); // Response: 1
fibonacci(3); // Response: 2
fibonacci(4); // Response: 3
fibonacci(5); // Response: 5

Complexity: The time complexity of the above algorithm is O(n).


Going further

Once those basic algorithms in mind if you want to go further I suggest you test yourself using Codility’s great challenges.

Some of the solutions in JavaScript are available here: Codility efficient algorithm solutions in JavaScript


Design Patterns

Before an interview you need to know some of the most known design patterns and anti patterns. To do so I highly recommend reading Addy Osmani’s book “Learning JavaScript Design Patterns”. It is available for free http://addyosmani.com/resources/essentialjsdesignpatterns/book under http://creativecommons.org/licenses/by-nc-nd/3.0/.

Creational

Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.

Some of the patterns that fall under this category are: Constructor, Factory, Abstract, Prototype, Singleton and Builder.

Factory

The Factory pattern is another creational pattern concerned with the notion of creating objects. Where it differs from the other patterns in its category is that it doesn’t explicitly require us use a constructor. Instead, a Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to be created.

More info: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#factorypatternjavascript

// A constructor for defining new cars
function Car(options) {
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";

}

// A constructor for defining new trucks
function Truck(options) {
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
}

// Define a skeleton vehicle factory
function VehicleFactory() {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function(options) {

    switch (options.vehicleType) {
        case "car":
            this.vehicleClass = Car;
            break;
        case "truck":
            this.vehicleClass = Truck;
            break;
            //defaults to VehicleFactory.prototype.vehicleClass (Car)
    }

    return new this.vehicleClass(options);
};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle({
    vehicleType: "car",
    color: "yellow",
    doors: 6
});

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log(car instanceof Car);

Prototype

We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects. The prototype object itself is effectively used as a blueprint for each object the constructor creates. If the prototype of the constructor function used contains a property called name for example (as per the code sample lower down), then each object created by that same constructor will also have this same property.

More info: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#prototypepatternjavascript

var myCar = {

    name: "Ford Escort",

    drive: function() {
        console.log("Weeee. I'm driving!");
    },

    panic: function() {
        console.log("Wait. How do you stop this thing?");
    }

};

// Use Object.create to instantiate a new car
var yourCar = Object.create(myCar);

// Now we can see that one is a prototype of the other
console.log(yourCar.name);

Singleton

The Singleton pattern is thus known because it restricts instantiation of a class to a single object. Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn’t exist. In the event of an instance already existing, it simply returns a reference to that object.

More info: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

var mySingleton = (function() {
    // Instance stores a reference to the Singleton
    var instance;

    function init() {
        // Private methods and variables
        function privateMethod() {
            console.log("I am private");
        }

        var privateVariable = "Im also private";

        var privateRandomNumber = Math.random();

        return {
            // Public methods and variables
            publicMethod: function() {
                console.log("The public can see me!");
            },
            publicProperty: "I am also public",
            getRandomNumber: function() {
                return privateRandomNumber;
            }
        };
    };
    return {
        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function() {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log(singleA === singleB); // true

Structural

Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

Patterns that fall under this category include: Decorator, Facade, Flyweight, Adapter and Proxy.

Decorator

Decorators are a structural design pattern that aim to promote code re-use. Similar to Mixins, they can be considered another viable alternative to object sub-classing.

Classically, Decorators offered the ability to add behaviour to existing classes in a system dynamically.

More info: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#decoratorpatternjavascript

function Vehicle(vehicleType) {
    this.vehicleType = vehicleType || "car";
    this.model = "default";
    this.license = "00000-000";
}

// Lets create a new instance of vehicle, to be decorated
var truck = new Vehicle("truck");

// New functionality we're decorating vehicle with
truck.setModel = function(modelName) {
    this.model = modelName;
};

truck.setColor = function(color) {
    this.color = color;
};

// Test the value setters and value assignment works correctly
truck.setModel("CAT");
truck.setColor("blue");

console.log(truck);

// Outputs:
// vehicle:truck, model:CAT, color: blue

// Demonstrate "vehicle" is still unaltered
var secondInstance = new Vehicle("car");
console.log(secondInstance);

Behavior

Behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Some behavioral patterns include: Iterator, Mediator, Observer and Visitor.

Iterator

The Iterator is a design pattern where iterators (objects that allow us to traverse through all the elements of a collection) access the elements of an aggregate object sequentially without needing to expose its underlying form.

Iterators encapsulate the internal structure of how that particular iteration occurs. In the case of jQuery’s jQuery.fn.each() iterator, we are actually able to use the underlying code behind jQuery.each() to iterate through a collection, without needing to see or understand the code working behind the scenes providing this capability.

More info: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#iteratorpatternjquery

$.each(["john", "dave", "rick", "julien"], function(index, value) {
    console.log(index + ": " + value);
});

Here we can see the code for jQuery.fn.each():

// Execute a callback for every element in the matched set.
each: function(callback, args) {
    return jQuery.each(this, callback, args);
}

Followed by a simplified version of the code behind jQuery.each()

each: function(object, callback, args) {
    var name, i = 0,
        length = object.length,
        isObj = length === undefined || jQuery.isFunction(object);

    if (isObj) {
        for (name in object) {
            if (callback.call(object[name], name, object[name]) === false) {
                break;
            }
        }
    } else {
        for (; i < length;) {
            if (callback.call(object[i], i, object[i++]) === false) {
                break;
            }
        }
    }
    return object;
};

Sources

WordPress Hybrid Client: Create free iOS/Android mobile applications for WordPress

After more than 100 commits, I am happy to announce the release of my latest Open Source project WordPress Hybrid Client available on GitHub.

With WPHC you will be able to generate iOS and Android applications in a blink of an eye. Before anything you will need to install WP-API plugin which basically will turn your Website into a REST API.

Then you can refer to the documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

I first created this project for my blog app that is now available on Android and iOS (approval still pending). Go check it out, it speaks for itself!

As it is an Open Source project, any help is welcome, I have created issues and milestones to help people get a clear understanding on where the project is heading.

If you have any questions please ask on the comments.

Creating an application with AngularJS 1.4, ECMAScript 6, Material Design and Webpack

AngularJS 1.4 has now been released.

It introduces a new Router, a translation system similar to angular-translate created by Pascal Precht, some performance enhancement and a better Webpack, Browserify support (CommonJS) without any “hacks”. You can for example directly import AngularJS like this

import 'angular/angular.js';

instead of this

require('expose?angular!exports?window.angular!angular/angular.js')

Demo

Source available on Github : https://github.com/shprink/angular1.4-ES6-material-webpack-boilerplate


Basic Needs

Dependencies (package.json)

For this tutorial we will need AngularJS, Angular Material, the UI router (The new router is not ready for production yet) and a icon library.

"dependencies": {
    "angular": "~1.4.0",
    "angular-animate": "~1.4.0",
    "angular-aria": "~1.4.0",
    "angular-material": "^0.10.1",
    "angular-ui-router": "^0.2.14",
    "font-awesome": "^4.3.0"
}

Webpack

If you need an explanation on what is Webpack for, I suggest you go check out a previous post of mine: http://julienrenaux.fr/2015/03/30/introduction-to-webpack-with-practical-examples/

We will need the following Webpack loaders to be able to compile ECMAScript 6 code and to process CSS, HTML files.

"devDependencies": {
    "babel-loader": "^5.0.0",
    "css-loader": "^0.12.0",
    "file-loader": "^0.8.1",
    "html-loader": "^0.3.0",
    "html-webpack-plugin": "^1.3.0",
    "style-loader": "^0.12.1"
}

The webpack.config.js cannot be easier:

module.exports = {
    entry: './lib/index.js',
    output: {
        path: './www',
        filename: 'bundle-[hash:6].js'
    },
    module: {
        loaders: [{
            test: /.html$/,
            loader: 'file?name=templates/[name]-[hash:6].html'
        }, {
            test: /.css$/,
            loader: "style!css"
        }, {
            test: /.js$/,
            exclude: /(node_modules)/,
            loader: "ng-annotate?add=true!babel"
        }, {
            test: [/fontawesome-webfont.svg/, /fontawesome-webfont.eot/],
            loader: 'file?name=fonts/[name].[ext]'
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './lib/index.html'
        })
    ]
};

Entry point (lib/index.js)

The following entry point gathers all our application basic needs: Angular, Material Design, the router and the icons. Here we use import which is the ECMAScript 6 way to require CommonJS modules, inject angularMaterial and angularUIRouter as our module dependencies and to finish we export our module as default (You can export several modules within a single file, default is the export you will get if you do not specify a specific import).

// Import angular
import 'angular/angular.js';
// Material design css
import 'angular-material/angular-material.css';
// Icons
import 'font-awesome/css/font-awesome.css';
// Materail Design lib
import angularMaterial from 'angular-material';
// Router
import angularUIRouter from 'angular-ui-router';

// Create our demo module
let demoModule = angular.module('demo', [
    angularMaterial,
    angularUIRouter
])

export default demoModule;

Index.html

The index.html needs two things. A way to bootstrap the application (here ng-app="demo") and a way to include the JavaScript file generated by Webpack (here src="{%=o.htmlWebpackPlugin.assets[chunk]%}").

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    </head>
    <body ng-strict-di ng-app="demo">
        {% for (var chunk in o.htmlWebpackPlugin.assets) { %}
        <script src="{%=o.htmlWebpackPlugin.assets[chunk]%}"></script>
        {% } %}
    </body>
</html>

Now you should have your demo module running. To make sure it works add the following lines to your entry point:

demoModule.run(($log) => {
    $log.info('demo running');
})

and check the console!


Going further

Create your own module

Now that our application is running let’s create a home module with ES6!

// Create a new module
let homeModule = angular.module('demo.home', []);
// Named export is needed to inject modules directly as Angular dependencies
export default homeModule = homeModule.name

Then we can import it the same way as other modules:

import home from './home/home.module.js';

// Create our demo module
let demoModule = angular.module('demo', [
    angularMaterial,
    angularUIRouter,
    home
])

Now let’s create a controller function './home.controller' that will be imported by our new module:

export default function($scope) {
    'ngInject';
}

'ngInject'; is an annotation of ng-annotate that allow us to use AngularJS in strict mode. If you want to know more about Ng-annotate here is an explanation: http://julienrenaux.fr/2015/01/18/angularjs-1-x-open-source-projects-to-follow-in-2015/#Ng-Annotate

We can then import the function that way:

let homeModule = angular.module('demo.home', []);

import HomeController from './home.controller';

homeModule.controller('HomeController', HomeController);

export default homeModule = homeModule.name

Full demo

A working example is available on Github, feel free to fork: https://github.com/shprink/angular1.4-ES6-material-webpack-boilerplate

Install

git clone git@github.com:shprink/angular1.4-ES6-material-webpack-boilerplate.git
cd angular1.4-ES6-material-webpack-boilerplate.git
npm install

Dev (liverelaod server)

npm run-script devserver

Build

npm run-script build

Codility efficient algorithm solutions in JavaScript

This post aim is to provide Codility algorithm solutions in JavaScript as there are so many of then available out there. I am not pretending to have the best algorithm possible but at least the following answers scored 100% on Codility test result.

After reading the task description a wise thing to do is to check the expected worst case time complexity. It gives you a hint on how to apprehend the solution. For instance if the worst case time complexity is O(N), you would probably need to use a for loop, if it is O(N*M) a nested for loop might be necessary etc.

big_o

This post in on going, I am adding new solutions often.

Lesson 1: Time Complexity

FrogJmp

Difficulty: PAINLESS

Count minimal number of jumps from position X to Y.

https://codility.com/demo/take-sample-test/frog_jmp

Expected time complexity: worst-case is O(1)

function solution(X, Y, D) {
    return Math.ceil((Y - X)/ D);
}

PermMissingElem

Difficulty: PAINLESS

Find the missing element in a given permutation.

https://codility.com/demo/take-sample-test/perm_missing_elem

Expected time complexity: worst-case is O(N)

function solution(A) {
    var length = A.length;
    var sum = ((length + 1) /2) * (length + 2);
    var sumMinusMissing = 0;
    for (i = 0; i < length; i++) { 
        sumMinusMissing += A[i];
    }
    return sum - sumMinusMissing;
}

TapeEquilibrium

Difficulty: PAINLESSS

Minimize the value |(A[0] + … + A[P-1]) – (A[P] + … + A[N-1])|

https://codility.com/demo/take-sample-test/tape_equilibrium

Expected time complexity: worst-case is O(N)

function solution(A) {
    var sumAfter = sumBefore = 0;
    var minDiff = Number.POSITIVE_INFINITY;
    
    A.forEach(function(value){
        sumAfter += value;
    });
    
    for (var i = 1; i < A.length; i++){
        sumBefore += A[i -1];
        sumAfter = sumAfter - A[i -1];
        minDiffTemp = Math.abs(sumBefore - sumAfter);
        if (minDiffTemp < minDiff){
            minDiff = minDiffTemp;
        }
    }
    return minDiff;
}

Lesson 2: Counting Elements

MaxCounters

Difficulty: RESPECTETABLE

Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.

https://codility.com/demo/take-sample-test/max_counters

Expected time complexity: worst-case is O(N+M)

function solution(N, A) {
    var counters = [], 
    size = N, 
    max = 0,
    forValue = 0,
    counter = 0,
    lastUpdate = 0;
    // init zeros
    for (var i = 0; i < N; i++){
        counters[i] = 0;
    }
    
    for (var i = 0; i < A.length; i++){
        if (A[i] <= N){
            position = A[i] -1;
            if (counters[position] < lastUpdate){
                counters[position] = lastUpdate + 1;
            } else {
                counters[position] = counters[position]+1;
            }
            if (counters[position] > max) {
                max = counters[position];
            }
        } else {
            lastUpdate = max;
        }
    }
    
    for (var i = 0; i < N; i++){
        if (counters[i] < lastUpdate)
            counters[i] = lastUpdate;
    }
    
    return counters;
}

MissingInteger

Difficulty: RESPECTETABLE

Find the minimal positive integer not occurring in a given sequence.

https://codility.com/demo/take-sample-test/missing_integer

Expected time complexity: worst-case is O(N)

function solution(A) {
    var onlyPositiveInt = [];
    for (var i =0; i < A.length; i++){
        if (A[i] > 0 ){
            onlyPositiveInt[A[i]] = true;
        }
    }
    for (i = 1; i <= onlyPositiveInt.length; i++){
        if (!onlyPositiveInt[i]){
            return i;
        }
    }
    return 1;
}

Lesson 3: Prefix Sums

In computer science, the prefix sum, scan, or cumulative sum of a sequence of numbers x0, x1, x2, … is a second sequence of numbers y0, y1, y2, …, the sums of prefixes (running totals) of the input sequence

http://en.wikipedia.org/wiki/Prefix_sum

Material https://codility.com/media/train/3-PrefixSums.pdf

PassingCars

Difficulty: PAINLESS

Count the number of passing cars on the road.

https://codility.com/demo/take-sample-test/passing_cars

Expected time complexity: worst-case is O(N)

function solution(A) {
    var ones = 0, passing = 0;
    for(var i=A.length-1; i>=0; i--) {
	    if (A[i] === 0){
	        passing += ones;
	        if (passing > 1000000000){
	            return -1;
	        }
	    } else {
	       ones ++;
	    }
    }
    return passing;
}

CountDiv

Difficulty: RESPECTETABLE

Compute number of integers divisible by k in range [a..b].

https://codility.com/demo/take-sample-test/count_div

For this one your coding skills won’t help. It is a pure math problem.

Expected time complexity: worst-case is O(1)

function solution(A, B, K) {
    if (A % K === 0)
        return Math.floor((B - A) / K + 1);
    return Math.floor((B - (A - (A % K) )) / K)
}

MinAvgTwoSlice

Difficulty: RESPECTETABLE

Find the minimal average of any slice containing at least two elements.

https://codility.com/demo/take-sample-test/min_avg_two_slice

Expected time complexity: worst-case is O(N)

Still searching for this one. If you have a 100% solution please share 🙂

GenomicRangeQuery

Difficulty: RESPECTETABLE

Find the minimal nucleotide from a range of sequence DNA.

https://codility.com/demo/take-sample-test/genomic_range_query

Expected time complexity: worst-case is O(N+M)

function solution(S, P, Q) {
    var positionOne,
    positionTwo,
    factorPerType = {
        "A":1,
        "C":2,
        "G":3,
        "T":4
    },
    prefix = [[0,0,0,0]],
    Plen = P.length,
    Slen = S.length,
    result =[],
    counterType = [0,0,0,0];

    for(var i = 0; i<Slen; i++) {
        counterType = counterType.concat(); // local copy
        counterType[factorPerType[S[i]] -1]++;
        prefix.push(counterType);
    }
    
    for(i=0; i<Plen; i++) {
	    positionOne = P[i] + 1;
	    positionTwo = Q[i]+ 1;

	    var finalCount =0;
	    for (j = 0; j < 4; j++){
	        finalCount = prefix[positionTwo][j] - prefix[positionOne -1][j];
	        if (finalCount > 0){
	            result.push(j + 1);
	            break;
	        }
	    }
    }
 
    return result;
}

Lesson 4: Sorting

MaxProductOfThree

Difficulty: PAINLESS

Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).

https://codility.com/demo/take-sample-test/max_product_of_three

Expected time complexity: worst-case is O(N*log(N))

function solution(A) {
    var N = A.length;

    // Sort ascending
    A.sort(function(a, b){
        return a - b;
    });
    // the max product of three elements is the product of the last three
    // elements in the sorted array or the product of the first two elements
    // and the last element if the first two elements are negatives.    
    return Math.max(A[0] * A[1] * A[N-1], A[N-3] * A[N-2] * A[N-1]);
}

Distinct

Difficulty: PAINLESS

Compute number of distinct values in an array.

https://codility.com/demo/take-sample-test/distinct

Expected time complexity: worst-case is O(N*log(N))

function solution(A) {
    var leng = A.length, counter = 0;

    // Sort ascending
    A.sort(function(a, b){
        return a - b;    
    });
    
    for (var i=1; i <= leng; i++){
        if (A[i] != A[i - 1]){
            counter++;   
        }
    }
    
    return counter;
}

Triangle

Difficulty: PAINLESS

Determine whether a triangle can be built from a given set of edges.

https://codility.com/demo/take-sample-test/triangle

Expected time complexity: worst-case is O(N*log(N))

function solution(A) {
    var len = A.length;
    
    // Sort descending
    A.sort(function(a, b){
        return b - a; 
    });
    
    for(var i=0; i<len - 2; i++) {
        var P = i, Q= i+1, R= i+2;
        var condition1 = A[P] + A[Q] > A[R];
        var condition2 = A[Q] + A[R] > A[P];
        var condition3 = A[R] + A[P] > A[Q];
        if (condition1 && condition2 && condition3){
            return 1;
        }
    }
    return 0;
}

NumberOfDiscIntersections

Difficulty: RESPECTETABLE

Compute intersections between sequence of discs.

https://codility.com/demo/take-sample-test/number_of_disc_intersections/

Expected worst-case time complexity is O(N*log(N));

function solution(A) {
    var len =  A.length,
    tupples = [],
    count =0;
    
    for (var i=0; i < len; i++){
        tupples.push([i - A[i], i + A[i]]);  
    }
    
    // [[5,5], [0,4], [-4, 6]] => [[-4, 6], [0,4], [5,5]]
    tupples.sort(function(a,b){
        return a[0] - b[0];
    });

    for (var j=0; j < len; j++){
        var tupple = tupples[j];
        for (var k=j+1; k < len; k++){
            var comparisonTupple = tupples[k];
            if (comparisonTupple[0] <= tupple[1]){
                count++;
                if (count >10000000){
                    return -1;    
                }
            } else {
                break;    
            }
        } 
    }
    return count;
}

Lesson 5: Stacks and Queues

Brackets

Difficulty: PAINLESS

Determine whether given string of parentheses is properly nested.

https://codility.com/demo/take-sample-test/brackets/

Expected worst-case time complexity is O(N)

function solution(S) {
    var len = S.length;
    
    if (!len){
        return 1;
    }
    
    var stack = [],
    matches = {
        "{" : "}",  
        "(" : ")", 
        "[" : "]"   
    };
    
    for (i=0; i < len; i++){
        var currentCharacter = S[i];
        if (matches[currentCharacter]){
            stack.push(currentCharacter);
        } else {
            if (!stack.length){
                return 0;
            }   
            var previousCharacter = stack.pop();
            if (matches[previousCharacter] !== currentCharacter){
                return 0;
            }   
        }   
    }        
    
    return (stack.length)? 0 : 1;
}

Nesting

Difficulty: PAINLESS

Determine whether given string of parentheses is properly nested.

https://codility.com/demo/take-sample-test/nesting/

Expected worst-case time complexity is O(N)

function solution(S) {
    var len = S.length;
    
    if (!len){
        return 1;
    }
    
    var stack = [],
    matches = {
        "(" : ")" 
    };
    
    for (i=0; i < len; i++){
        var currentCharacter = S[i];
        if (matches[currentCharacter]){
            stack.push(currentCharacter);
        } else {
            if (!stack.length){
                return 0;
            }   
            var previousCharacter = stack.pop();
            if (matches[previousCharacter] !== currentCharacter){
                return 0;
            }   
        }   
    }        
    
    return (stack.length)? 0 : 1;
}

Fish

Difficulty: PAINLESS

N voracious fish are moving along a river. Calculate how many fish are alive.

https://codility.com/demo/take-sample-test/fish/

Expected worst-case time complexity is O(N)

function solution(A, B) {
    var len = A.length,
    count = parseInt(len),
    stackDownstreamFishes = [];
    
    for (var i = 0; i < len; i++){
        var direction = B[i] ? 'downstream' : 'upstream';
        if (direction === 'downstream'){
            stackDownstreamFishes.push(A[i]);    
        } else {            
            // Going backward through all downstream fishes
            for(var j= stackDownstreamFishes.length-1; j>=0; j--) {
                var lastDownstreamFishSize = stackDownstreamFishes[j];
                if (lastDownstreamFishSize > A[i]){
                    count--;
                    break;
                } else if (lastDownstreamFishSize < A[i]){
                    count--;
                    stackDownstreamFishes.pop();
                }
            }
        }
    }
    return count;
}

StoneWall

Difficulty: PAINLESS

Cover “Manhattan skyline” using the minimum number of rectangles.

https://codility.com/demo/take-sample-test/stone_wall/

Expected worst-case time complexity is O(N)

function solution(H) {
    var len = H.length,
        stack = [H[0]],
        result = 1;
    if (!len) {
        return 0;
    }
    for (var i = 1; i < len; i++) {
        var currentHeight = H[i];
        while (stack.length && stack[stack.length - 1] >= currentHeight) {
            if (currentHeight == stack[stack.length - 1]) {
                result--;
            }
            stack.pop();
        }
        stack.push(currentHeight);
        result++;
    }
    return result;
}

I started with a backward for loop:

for (var j = stack.length - 1; j >= 0; j--) {
    if (stack[j] < currentHeight) {
        break;
    }
    if (stack[j] == currentHeight) {
        result--;
    }
    stack.pop();
}

But a while loop is faster: https://jsperf.com/compare-while-loop-vs-for-loop/4


Lesson 6: Leader

Material https://codility.com/media/train/6-Leader.pdf

EquiLeader

Difficulty: PAINLESS

Find the index S such that the leaders of the sequences A[0], A[1], …, A[S] and A[S + 1], A[S + 2], …, A[N – 1] are the same.

https://codility.com/demo/take-sample-test/equi_leader/

Expected worst-case time complexity is O(N)

function solution(A) {
    var len = A.length,
        i = 0,
        j = 0,
        k = 0,
        size = 0,
        indexCount = 0,
        candidateCount = 0,
        leader,
        leaderCount = 0,
        candidate = null;

    // First find the leader within A
    for (; i < len; i++) {
        if (size === 0) {
            size++;
            candidate = A[i];
        } else {
            (candidate === A[i]) ? size++ : size--;
        }
    }

    for (; j < len; j++) {
        if (A[j] === candidate) {
            candidateCount++;
        }
    }

    if (candidateCount <= len / 2) { // Our candidate failed 🙁
        return 0;
    } else { // we have a winner!
        leader = candidate;
        leaderCount = candidateCount;
    }

    var leaderLeftCount = 0;
    for (; k < len - 1; k++) {
        var lenLeft = (k + 1);
        var lenRight = len - lenLeft;
        if (A[k] === leader) {
            leaderCount--;
            leaderLeftCount++;
        }
        if (leaderLeftCount > (lenLeft / 2) && leaderCount > (lenRight / 2)) {
            indexCount++;
        }
    }
    return indexCount;
}

Dominator

Difficulty: PAINLESS

Find an index of an array such that its value occurs at more than half of indices in the array.

https://codility.com/demo/take-sample-test/dominator/

Expected worst-case time complexity is O(N)

function solution(A) {
    var len = A.length,
    i = 0,
    j = 0,
    leaderCount = 0,
    latestIndex = -1,
    size = 0,
    candidate = null,
    value = null;
    
    for (; i < len; i++){
        if (size === 0){
            size++;
            value = A[i];
        } else {
            value !== A[i] ?  size-- : size++;
        }
    }
    
    candidate = value;
    for (; j < len; j++){
        if (candidate === A[j]){
            leaderCount++;
        }
        if (leaderCount > len / 2){
            latestIndex = j;
            break;
        }
    }
    return latestIndex;
}

## Lesson 7: Maximum slice problem

Material

### MaxProfit

Difficulty: PAINLESS

Given a log of stock prices compute the maximum possible earning.

Expected worst-case time complexity is O(N)

At first I could not find a better solution the following:

function solution(A) {
    var len = A.length,
    i= len-1,
    max = 0;
    
    for(; i>=0; i--) {
    	var stockShare = A[i];
    	for(j = i-1; j>=0; j--) {
    	   var diff = stockShare - A[j];
    	   if (diff > max){
    	       max = diff;
    	   }
    	}
    }
    return max;
}

The time complexity is quadratic O(N^2) which is terrible.

Then I spent a little more time thinking about it and I ended up writing the following which has the correct time complexity: O(N).


Changing apache2 document root in ubuntu 14.x

Having the default Apache document root to /etc/www can be sometimes annoying because of permissions. I strongly recommend to use a folder into your home folder.

For the sake of this post, I will use the folder Sites (that I created under my personal folder /home/shprink/Sites/).

PS: The Apache version used for this post is: 2.4.10 (Ubuntu), you can see yours using apache2 -v command.

Changing apache2 document root

The default document root is set in the 000-default.conf file that is under /etc/apache2/sites-available folder.

$ cd /etc/apache2/sites-available
$ sudo nano 000-default.conf

While the file is opened change DocumentRoot /var/www/ with your new folder e.g DocumentRoot /home/shprink/Sites/

Set the right Apache configuration

The configuration of the /etc/www folder is under /etc/apache2/apache2.conf. Edit this file to add the configuration of your new document root.

$ sudo nano /etc/apache2/apache2.conf

Copy the following:

<Directory /var/www/>
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
</Directory>

and change the directory path:

<Directory /home/shprink/Sites/>
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
</Directory>

Restart Apache

$ sudo service apache2 restart

Set the right permission

All of your document root parent folders must be executable by everyone. To know if it is the case you can use the utility namei that list the permissions along each component of the path:

$ namei -m /home/shprink/Sites/
f: /home/shprink/Sites/
 drwxr-xr-x /
 drwxr-xr-x home
 drwx------ shprink
 drwx------ Sites

Here as you can see that shprink and Sites permissions are not set properly.

Open http://localhost/ in your browser, you should get the following message:

Forbidden
You don’t have permission to access / on this server.

Open the apache error log to see the exact error code e.g AH00035. It might help you to get more information.

$ sudo tail -f /var/log/apache2/error.log
[Mon Apr 06 09:04:26.518260 2015] [core:error] [pid 22139] (13)Permission denied: [client 127.0.0.1:45121] AH00035: access to / denied (filesystem path '/home/shprink/Sites') because search permissions are missing on a component of the path

To fix the permission problem for good, using chmod +755 should be enough.

$ chmod +755 /home/shprink/
$ chmod +755 /home/shprink/Sites/

Re run namei to make sure everything is ok.

$ namei -m ~/Sites/
f: /home/shprink/Sites/
 drwxr-xr-x /
 drwxr-xr-x home
 drwxr-xr-x shprink
 drwxr-xr-x Sites

Now opening http://localhost/ should work as expected. If you are having trouble please leave a comment.