Inno Weekly #11

Web Development

Getting Started with Server-Side Rendering in Angular

By Kévin Barralon

This week we released a tutorial for developers using the Angular JavaScript framework to set them up with a pre-configured server-side rendering environment. This environment allows for the pre-rendering of an Angular site so that its contents can be made visible to robots (e.g. Google, Facebook, Twitter) and to improve the performance of Angular, as the state of the application is transferred from the server side to the client side.

As these features are new to the framework, the latest version of Angular (v5) is used for the tutorial. You can access the extensive version of this tutorial by reading the blog article: How to Create an Angular Application with Server-Side Rendering?

Bundle Your JavaScript Apps Using Parcel

By Jacob Cook

The JavaScript ecosystem is notorious for evolving very quickly. The modern JS application stack requires a variety of tooling mechanisms, including “bundlers”, which handle the generation and packaging of proper assets for the creation of a Web page. Up until now, two projects have reigned supreme in this space: Browserify and Webpack. They are not particularly known for their ease-of-use: for a preview, you only need to Google “Why is Webpack…” to get thousands of results like “Why is Webpack so slow?” or “Why is Webpack so complicated?”

It’s clear that the ecosystem needs some new utilities that can improve the startup process for cutting-edge JavaScript web applications. There is a new project on the scene called Parcel. This project aims to be an answer to many Webpack-related headaches. It does many things that Webpack does (code splitting, hot module replacement, code transpilation and transformation) with very little if any manual setup and no labyrinthine configuration files to write. It also uses a multicore compilation system, allowing CPU-hogging build operations to be spread across multiple workers and to better take advantage of those fancy processors we all use nowadays.

It remains to be seen if it will emerge as a solid competitor to Webpack, but if initial indications prove true, Parcel will be a huge boon to Web developers that want to get going with a modern project without having to run through their bottles of aspirin. Check out Parcel: https://parceljs.org/

Winter Break!

Thanks for following us for the past 11 editions. Our team wishes you a very happy and restful holiday season.

See you in January 2018!
Your Inno Weekly Team

How to Create an Angular Application with Server-Side Rendering?

Server-Side Rendering Management: An Angular’s Novelty Imposing a Challenge

Angular is a framework using the TypeScript Programming Language. Its 5th version (pentagonal-donut) was released in November 2017, containing new features and bugfixes. It is accompanied by the command line tool Angular CLI and new features such as a server-side rendering framework that has become very popular within the community of Angular users and developers.

However, one of the recurring problems that can be encountered when setting up a website with a modern library (e.g. Angular, React, Vue.js, etc.) is that, in general, web crawlers and robots will not be able to read that website! Therefore, if you want to share your article on Facebook, or simply be well referenced on search engines (i.e. SEO), this part may be complicated (although in the case of Google, it seems that their robots have recently learned to read pages generated by JavaScript).

The reason for this is simple: most robots do not know when your page will be entirely generated by JavaScript. Therefore, they will only be able to read a tiny part of your HTML – which is often a small ‘Loading …‘ message, and not very explicit! So, we are addressing this issue today in this post.

How To Create an Angular Application with Server-Side Rendering?

To overcome this problem we can use Angular CLI – the tool that helps to generate an Angular application from the command line. With its version 5 now available, it is now possible to manage a server state transfer to the client. For example, an application that makes a request to a REST API will not make the same request twice (i.e. on both server as well as client sides) while it can transfer the server-side result to the client. We will study these two cases successively in order to start an application with server-side rendering.

How to Initialize Your Angular Project?

Follow these steps in order to initialize your Angular project:

  • Start by installing the Angular CLI tool: npm i -g @angular/cli
  • Then, initialize the project: ng new ssr-app style = scss # Because it's better with SCSS.
  • Then, go to the directory of the generated application and launch the development server:
cd ssr-app
ng serve
  • Finally, visit http://localhost:4200/ and enjoy!

Now it’s time to configure the server-side rendering management.

How to Configure Server-Side Rendering?

Let’s start by installing the platform-server package: npm i -S @ angular / platform-server

In the file .angular-cli.json at the root of the project, you must add in the “apps” part, the following configuration:

{
   "name": "universal",
   "platform": "server",
   "root": "src",
   "outDir": "dist-server",
   "main": "main.server.ts",
   "tsconfig": "tsconfig.server.json",
   "environmentSource": "environments/environment.ts",
   "environments": {
      "dev": "environments/environment.ts",
      "prod": "environments/environment.prod.ts"
   }
}

In our src / app folder, we now need an app.server.module.ts file next to our app.module.ts file. This will be our entry point for our server-side application. Its content is:

import {NgModule} from '@angular/core';
import {ServerModule} from '@angular/platform-server';

import {AppModule} from './app.module';
import {AppComponent} from './app.component';

@NgModule({
   imports: [
      AppModule,
      ServerModule
   ],
   bootstrap: [AppComponent]
})
export class AppServerModule {
}

The file simply inherits modules from the app.module.ts file and adds the ServerModule module. As for the main.server.js file in the .angular-cli.json, we need to create it next to the main.ts file in the src / directory with the following content:

import {enableProdMode} from '@angular/core';
export {AppServerModule} from './app/app.server.module';

enableProdMode();

We also need to create a tsconfig.app.server.json file for TypeScript compilation next to tsconfig.app.json in the same directory:

{
   "extends": "./tsconfig.app.json",
   "compilerOptions": {
      "outDir": "../out-tsc/server",
      "module": "commonjs"
   },
   "exclude": [
      "test.ts",
      "**/*.spec.ts"
   ],
   "angularCompilerOptions": {
      "entryModule": "app/app.server.module#AppServerModule"
   }
}

In the src / app directory, we now need to modify the app.module.ts file by adding a method to our BrowserModule module:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule.withServerTransition({ appId: 'universal' })
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule {
}

We can now build our server side / client side application. To do so, add a line in the scripts of our package.json:

"scripts": {
   ...
   "universal": "ng build --prod && ng build --prod --app universal --output-hashing=none",
   ...
}

You may ask, what is this command for? It simply generates, on the one hand, a client-side build and, on the other hand, a server-side build (with reference to our app configured in the .angular-cli.json file). For the server side, we remove the creation of a hash on the file generated main.bundle.js for reference later.

If we run the npm run universal command, we get our two builds in two separate files, dist / and dist-server /.

From now on, we want to be able to launch our server. For now, the Angular Universal Package only supports Node.js and ASP.NET. We will write our server in Node.js.

We must first install the package @nguniversal/express-engine that will bootstrap our server Node.js with the Express framework. So just run the command npm i -S @nguniversal/express-engine.

We will then write a server.js file to the root of our project with this content:

require('zone.js/dist/zone-node');

const express = require('express');
const ngUniversal = require('@nguniversal/express-engine');

/**
* On charge le seul fichier de notre build côté serveur
*/
const bootstrap = require('./dist-server/main.bundle');

/**
* On crée motre instance Express
*/
const app = express();

app.get('/', (req, res) => res.render('index', {req, res}));

/**
* Obtient les fichiers statics provenant de la build dist/
*/
app.use(express.static(`${__dirname}/dist`));

/**
* Configuration de Express Engine
*/
app.engine('html', ngUniversal.ngExpressEngine({
   bootstrap: bootstrap.AppServerModuleNgFactory
}));
app.set('view engine', 'html');
app.set('views', 'dist');

/**
* Toutes les URLs renvoient à l'index.html du répertoire dist/
* Angular se charge se rediriger vers les bonnes routes
*/
app.get('*', (req, res) => res.render('index', {req, res}));

/**
* On lance notre serveur
*/
app.listen(3000, () => console.log(`Listening on http://localhost:3000`));

Time to celebrate! We have successfully configured our Angular application as well as our Node.js server.

Launch the server by typing ‘node server.js’ and go to the URL http://localhost:3000. Your page is server-side generated at launch, and then supported by the client-side build when loaded. If you disable JavaScript in your browser, your page is still generated because you have already properly configured it following these instructions.

How to Transfer the State of the Application?

Although our application works perfectly with this configuration, it is not completely optimal. If your application requires requests via a Rest API, for example, these will be done twice instead of once. Indeed, if the server is requested to make a request, the browser does not know it and will perform the same request a second time when the server side will take over.

For example, we can start by adding the HttpClientModule in our app.module.ts and our app.server.module.ts (the ideal would be to have a module file in common, but I leave you the freedom to do it!):

import {HttpClientModule} from '@angular/common/http';

@NgModule({
   ...
   imports: [
      ...
      HttpClientModule
   ],
   ...
})
export class AppModule {
}

Let’s go into our app.component.ts and delete the content we will replace with:

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
   image: any;

   constructor(private http: HttpClient) {
}

ngOnInit() {
   this.http.get('http://www.splashbase.co/api/v1/images/random')
      .subscribe(data => this.image = data);
    }
}

We will display a random image retrieved via a Rest API.

For rendering, let’s edit our app.component.html file that we will replace with this unique tag:

< img *ngIf="image" [src]="image.url" >

This image will be the result of our request to the API.

If we start a build with npm run universal and launch our server with ‘node server.js’, we have our page working correctly. The only downside is that the image appears a few milliseconds and is then replaced by another image. The reason is the same as before, a request is made server side, and another is made client side once the page loaded. The client-side query is therefore useless.

The idea here is to transfer the state of our request to the client side so as not to multiply unnecessary requests. To do so, we will import the ServerTransferStateModule in our app.server.module.ts and the BrowserTransferStateModule in our app.module.ts:

/* app.server.module.ts */
import {ServerTransferStateModule} from '@angular/platform-server';

@NgModule({
   imports: [
      ServerTransferStateModule /* Ici ! */
   ],
   bootstrap: [AppComponent],
})
export class AppServerModule {}

/* app.module.ts */
import {BrowserTransferStateModule} from '@angular/platform-browser'

@NgModule({
imports: [
   ...
   BrowserTransferStateModule /* Ici ! */
   ],
   bootstrap: [AppComponent],
})
export class AppServerModule {}

Once the configuration is done, we can go to our app.component.ts file in order to create a key before the declaration of our Class and to add TransferState in our constructor, such as the following:

import {makeStateKey, TransferState} from '@angular/platform-browser';

const IMAGE_KEY = makeStateKey('image');

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
   ...
   constructor(private http: HttpClient,
      private state: TransferState) {
   }
...
}

Then we modify our ngOnInit method in the following way:

ngOnInit() {
   const image: any = this.state.get(IMAGE_KEY, null);

   /**
   * Si l'image n'est pac contenue dans notre clef, on effectue la requête
   */
   if (!image) {
      this.http.get('http://www.splashbase.co/api/v1/images/random')
         .subscribe(data => {
            this.image = data;
            this.state.set(IMAGE_KEY, data as any);
          });
   }

   /**
   * Sinon, on récupère le contenu de notre clef
   */
   else {
      this.image = image;
   }
}

We then launch a build of our application as well as our server.

npm run universal
node server.js

Now, the content of the image is transferred from the server to the client and the request is made only once!

Conclusion

You are now well equipped with all you need to start an Angular application with server-side rendering configuration. As a precaution, you may now refrain from using all objects available in your browser unreservedly. For example, you may want to verify whether an object is client side or not. Consider the following example:

import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

   constructor(
      @Inject(PLATFORM_ID) private platformId: Object,
      @Inject(APP_ID) private appId: string) {
      if (isPlatformBrowser(platformId)) {
         console.log('Je suis appelé côté client !')
      }
    }

All these tips are meant to simplify your Angular developments with all the benefits of server-side rendering! Please stay tuned for more helpful tips…

Press Review Inno #10

Design

What Is Design System?

By Patrick Bracquart

For several years now, the complexity of the websites and applications has pushed us towards rethinking the concept of design, as well as the methodologies we use in the design process. This rethink is pushed by an ever-expanding field of necessary skills and positions in design such as web analyst, UI/UX designer, interaction designer, front-end developer and so forth. It is within this context that the idea of “design systems” has come forward.

A design system is the primary UI/UX reference of a project. It provides us with a guide that can serve as a support for the entire chain of production, no matter the subject matter (fashion, style, food, services, …), the terminal (laptop, mobile phone, smartwatch, …) or even the deliverable (websites, mobile applications, management interfaces, …).

More complete than a simple set of guidelines, this guide does not just describe the (atomic) design elements or the user interactions, it also lays out the development standards that should be followed, the accessibility standards to put in place, as well as iconography and video, to name a few. These guidelines and standards ensure that the entire Design Ecosystem remains perfectly coherent.

Mobile

How to Use Versatile Namespace in Swift?

By Thibault Wittemberg

In Swift, some APIs such as RxSwift use a technique that confines the code they are exposing in a dedicated namespace. This eases a lot the code reading and allows to extend this namespace to add your very own features.

In this post we will see that it is quite simple to create your own namespace and so generically that it allows an external contributor to extend it in an elegant way.

Press Review Inno #9

PyCon 2017 (Part 2!)

Talk: “Double Click: Continue Building Better CLIs”

Summarized by Kévin Barralon

This PyCon Canada talk was a presentation of Click, a Python package that allows you to create CLIs (Command-Line Interfaces) with only a few lines of code.

Click is simple and easy to use, in that the configuration of commands happens almost entirely using decorators around your Python functions. For example, here is a simple function that can be used to repeat the word you pass it as an argument:

# hello.py
import click<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>
@click.command()
@click.option('--count', default=1, type=int, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    for _ in range(count):
        click.echo(f'Hello {name}!') # Syntaxe de Python 3.6 !

if __name__ == '__main__':
    hello()

In just a few lines of code, you’ve created a command that can:

  • take an option --count with a default value of 1 and that is type-cast to an integer.
  • take an option --name which allows the user to state their name, thanks to the ‘prompt’ argument passed in the decorator

These values are passed directly as the count and name parameters of the decorated function.

To run this command in your terminal:

python3 test.py --count=3
Your name: Casimir 
Hello Casimir!
Hello Casimir!
Hello Casimir!

The other interesting (and practical!) point here is that if you pass the option --help when you call the command, you can see the docstring for your function, as well as information on each option that your comamnd supports thanks to the argument help passed in your decorators:

python3 hello.py --help

Usage: test.py [OPTIONS]

Simple program that greets NAME for a total of COUNT times.

Options:

Count INTEGER Number of greetings
Name TEXT The person to greet
Help Show this message and exit.

Rather than simply passing options to your command, you can also specify arguments. For example:

@click.command()
@click.argument('filename')
def touch(filename):
    click.echo(filename)

Then:

python3 touch.py foo.txt
foo.txt # Résultat

As you can see, the possibilities with Click are endless. Here are a few additional ones for fun:

  • Add the argument multiple=True in your decorator @click.option which will give you a tuple of all options passed to your command.
  • Add a callback as an argument to @click.option which will change the behaviour of your command (to define custom validation rules, for example).
  • Pass environment variables to your decorator (like so: envar="USERNAME").
    Define a limited or unlimited number of arguments that will return a tuple.
  • Add a File method as a type in your decorator (example: @click.argument('input', type=click.File('rb'))) which will automatically open a specified file and close it when necessary.

A list of all possibilities offered by this Python package is available in the documentation, which is indeed very well done.

Bonus!

The closing keynote on f-strings really seemed to motivate our team! Here’s an article by Maxime which adds to the one by Sébastien from last week:

What in the World Are F-Strings?

By Maxime Dupuis

The mechanism of Literal String Interpolation, known as f-strings, is a new arrival in the latest version of Python, 3.6. They are recognizable by the f (or F) at the beginning of a declaration of a string: f'My f-string!'. They are very similar in behaviour to template strings in JavaScript, which are defined using the ` character.

F-strings are useful because they can reference variables that will be automatically interpolated with the values of the local variables defined under the same name.

>>> age = 42
>>> first_name = 'Maxime'
>>> f"My name is {first_name} and I'm {age} years old"
"My name is Maxime and I'm 42 years old"
>>> # The use of an undefined variable will give us a NameError:
>>> f"{notdefined}"
Traceback (most recent call last):
  File "<stdin>;", line 1, in <module>
NameError: name 'notdefined' is not defined

They become very interesting when you consider their impact on performance. If we compare them to other ways to create strings in Python, we have the following:

python3.6 -m timeit -c 'age=42; first_name="Maxime"; f"My name is {first_name} and I'm {age} years old"'
10000000 loops, best of 3: 0.172 usec per loop
python3.6 -m timeit -c 'age=42; first_name="Maxime"; "My name is {first_name} and I'm {age} years old".format(first_name=first_name, age=age)'
1000000 loops, best of 3: 0.714 usec per loop
python3.6 -m timeit -c 'age=42; first_name="Maxime"; "My name is %s and I'm %s years old" % (prenom, age)'
1000000 loops, best of 3: 0.283 usec per loop
python3.6 -m timeit -c 'age=42; first_name="Maxime"; "My name is " + prenom + " and I'm " + str(age) + " years old"'
1000000 loops, best of 3: 0.449 usec per loop
python3.6 -m timeit -c 'from string import Template; age=42; first_name="Maxime"; Template("My name is $first_name and I'm $age years old").substitute(first_name=first_name, age=age)'
100000 loops, best of 3: 8.75 usec per loop

But it’s not only useful for its performance benefits. We can use f-strings to call functions, modify substrings, and many other things:

>>> total = 10.0
>>> taxes = 1.15
>>> f'Total: {total + taxes}'
'Total: 11.15'
>>> first_name = 'Maxime'
>>> f'My name is {first_name.upper()}'
'My name is MAXIME'

If f-strings interest you or you haven’t yet discovered all of the new things that Python 3.6 has to offer, check out the release notes.

Mobility

SwiftGen

By Thibault Wittemberg

When we develop an iOS app, we regularly need to access resources. The traditional way to use them in the code is to instantiate them with their identifiers (strings):

let avatar = UIImage(named: ‘darthVader’) // gets the ‘darthVader’ image from the assets folder
let name = NSLocalizedString (‘darthVader’, comment: ‘’) // gets the localized string with the key ‘darthVader’ from the Localizable.strings file

The same goes for fonts, storyboards and colors.
Swift is a strict language about type management and promotes the detection of errors at compile time rather than at run time.

That being said, what happens if one of the resources we want to instantiate is not found at run time? Since this instantiation is based on a string, it is subject to errors (typo errors). Therefore, we can use the SwiftGen tool which allows to secure this kind of manipulation:

  • It avoids typo errors
  • It allows auto completion
  • It ensures that the resources exist at compile time.

It operates as follows:

  • The “SwiftGen” executable is installed on the development workstation (either via Homebrew or via CocoaPods)
  • A custom build phase launches this executable for each compilation
  • SwiftGen scans the project’s resources and generates the Swift code representing them in a “type safe” manner

The resource identifiers will be transformed into enums that are much more secure and easy to use. Consider the following example:

let avatar = Asset.darthVader.image
let name = L10n.darthVader

It is even possible to customize the templates that will be used to generate the code if you want to apply a different coding style.

When combined with the “Reusable” framework (from the same author), we have tools that are almost mandatory (and we use them a lot at Savoir-faire Linux).

SwiftGen is made to be integrated with your continuous integration environment (the executable can be embedded in a CocoaPods dependency, it avoids installing it on the build machine). Read more on GitHub!

Contributions

New Release of num2words v0.5.6 with Support for New Languages!

By Ernesto Ortiz

It has been five months since the previous release of num2words v0.5.5, and these have been five really active months. A lot of new contributors have made some great improvements and have added support for new languages! Here are some of the latest changes, with “special thanks” to the contributors!

  • ‘Num2words’ has changed its coding conventions to follow PEP8. Code coverage has increased a lot, and we need your help to continue improving this, so check out the issues related to num2words
  • Now we can use other converters like to_currency, to_year, to_ordinal_num
  • Thanks to Tufan Kaynak for adding support for the Turkish localization
  • Thanks to Jesús Leganés-Combarro for adding support for Algerian French localization
  • Thanks to Armin Oliya for adding support for the Dutch localization
  • Thanks to Sergio Zholudov for adding support for the Ukrainian localization
  • Thanks to Blaž Bregar for adding support for the Slovenian localization
  • Thanks to Mārtiņš Šulcs for making a lot of improvements to the base code, to_currency functionalities and more!

Special thanks to everyone that has taken the time to report new issues, to make pull requests and to share their time and effort with this project!

You can check the new release at the following links:

Press Review Inno #8

Special Edition on PyConCa 2017

This week, we attended PyCon Canada which started on November 18 and lasted through 21. We are also proud and happy that we played a role in sponsoring this dynamic event. In this Special Edition of Press Review Inno, you find articles from our SFLers who actively participated in the event’s sessions.

PyCon 2017

Our Team Who Attended PyConCa 2017

 

Tutorial: Writing Tests that Write Themselves by David Kua

Summarized by Ernesto Rodriguez Ortiz

Stop worrying about corner cases and start loving the power property-based testing.

I just discovered the concept of property-based testing at PyCon Canada 2017, thanks to David Kua who prepared, showed and shared with us a great tutorial of property-based testing using the library Hypothesis. (Welcome to Hypothesis!)

In fact, the concept of property-based testing was popularized by the Haskell library Quickcheck. I am happy about my new discovery because I find myself too often thinking about corner cases in my tests, and now I don’t need to spend as much time considering this, as they will show up themselves with the help of Hypothesis.

So How Does This Work?

Hypothesis generates random data matching your specification and checks that your guarantee still holds up for each test case. Check out this really simple example:

# FILE NAME division.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# You wrote these two lines way too fast...
def division(x, y):
    return x / y
 
# Hypothesis will now show you your mistakes...
from hypothesis import given, settings
import hypothesis.strategies as st
 
@given(st.integers(), st.integers())
@settings(max_examples=1000)
def test_commutativity_pbt(x, y):
    assert division(x, y) * y == x

Then run:

pytest --hypothesis-show-statistics division.py

You should see how Hypothesis has found the corner case:

ZeroDivisionError: division by zero

This is powerful stuff, so go play a little with the awesome tutorial prepared by David Kua and check the documentation of Hypothesis.

Closing Keynote – Mariatta Wijaya

Summarized by Sébastien Blin

During the closing keynote, Mariatta Wijaya, a Python Core Developer, presented us Python 3.6 through the lens of a PEP (Python Enhancement Proposal) that has been released in this version: PEP 498: Literal String Interpolation.

Mariatta explained the history of this PEP, from its beginnings as a Python mailing list post since a few years ago. The new feature introduced in this PEP, colloquially called “f-strings”, allows for an improved experience in creating strings with variables in them, all the while improving performance and making for a more codebase than when the % operator or str.format functions are used.

>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f’He said his name is {name!r}.'
"He said his name is 'Fred'."

She then gave a brief overview of the other PEPs released with Python 3.6 (including PEP 628 which adds math.tau, which did not exist prior, and the value of which is 6.28). The complete list of PEPs in Python 3.6 is available at Python 3.6 Release Schedule.

In any case, Mariatta invites us to upgrade to Python 3.6 as soon as possible, as well as to contribute to the evolution of the programming language through the creation of new PEPs at this GitHub repo.

Contributions

GitHub Releases a Team-Based Discussion Feature

By Romain Bertozzi

To contribute to open source software means to share with others, so it only follows that the ability to effectively communicate is critical. GitHub announced a new feature on the 20th of November centered around team-based discussions.

The idea of this feature is to create a space for conversations within a project that might not be best placed under issues or pull requests. These issues and PRs will now be freed up and will be less of a magnet for long, irrelevant comment threads. In addition to this, these new discussions, public or private, will have dedicated URLs and will be able to be easily shared and cited on other sites.

Here at Savoir-faire Linux, we welcome this news enthusiastically. We believe that it will bring more clarity around the discussions related to the creation, management and direction of a project. The centralization and the ease-of-use of these discussions are benefits that will allow for more transparency and longevity of conversations. It remains to be seen how this functionality will be adopted by GitHub users, who already have many different options available to them that they may be more used to.

Press Review Inno #7


Mobility

 

Generic Protocols and Type Erasure in Swift

With Swift, you can define protocols by associating one or more generic types. These types are defined using the associatedtype” keyword. The name Generic Type” is a bit misused here. We should actually talk about a placeholder for a reserved type. Indeed, we will see that such protocols do not offer great flexibility of use when we consider them as generic.

Useful Information:

 

Web Development

Django 2.0 Release Candidate Now Available

By Kévin Barralon

The Django web framework just published the first release candidate of its upcoming 2.0 version. Django 2.0 is scheduled to be released on December 1st.

Don’t be fooled by the name – this new major release of Django will not bring any major significant changes to the framework. The changes in the latest version should be of the same scale as those found in past new releases.

Despite this, the most important change in the 2.0 release is its incompatibility with Python 2.7, the support for which is scheduled to last only until 2020. Django 2.0 will only support a minimum version of Python 3.4, and of course it is highly recommended to go directly to the most recent version of Python, which is presently 3.6.

URL Routing

In terms of new features, the new function django.urls.path() renders the URL routing syntax much simpler and easier to read. So, instead of having to write url(r'^articles/(?P[0-9]{4})/$', views.year_archive), you can write path('articles//', views.year_archive). This new syntax will also allow the view to receive the URL arguments with the proper type already defined (a whole number in the case of year above, instead of a string).

It is still not possible to add a constraint to the URL route directly (in this example, the fact that the year should only consist of four digits). The current function django.conf.urls.url() will be replaced by django.urls.re_path() which will keep the existing functionality of allowing regular expressions to be placed in the definition of the route.

The functiondjango.conf.urls.include() will also be directly available under django.urls. This will allow you to import your modules like from django.urls import include, path.

Other New Things

Helpful Links:

Deploying Entire Services with Docker Swarm and GitLab CI

by Jacob Cook

Here at Savoir-faire Linux, I work on the deployment infrastructure for many of our hosted services, and am constantly looking for ways to improve our DevOps practice. Currently the deployment pipeline is centered around the use of Ansible to manually provision a service inside a virtual machine and adjust as necessary. But in an effort to make builds and deployments faster and more stable for our developers, we are looking at new approaches, including the use of Docker builds pushed to a registry and subsequently deployed using a pipeline like GitLab CI.

One of the tools that can be used to deploy a micro-service architecture (created with docker-compose) is called Docker Swarm. Using a set of servers configured to act in a swarm, one can deploy a stack of containers in a simple pattern with only docker stack deploy. Docker will then automatically choose the appropriate servers in the swarm to deploy to, and handle networking between the services just as if you were using docker-compose on your local machine. Neat, huh?

The best part is that it plays nicely with our existing build system in GitLab CI. We can build, test, release and deploy across our infrastructure using GitLab CI and GitLab Container Registry. There are still pieces of the puzzle to work out but it represents a major leap forward in the simplification and stability of our DevOps practice.

Further Reading:

Press Review Inno #6

Design

Atomic Design

By Patrick Bracquart

Since the early days of the web, we talk about what goes into creating a Web “page”. This term shows how our vision of the web was informed since the 90s: it came from an architecture that was structured as a series of documents, like if they were printed pages of an encyclopedia.
However, for several years now, the multitude of available platforms in the Web ecosystem continues to grow and to become more complex. From the computer to the smartphone, and without forgetting the television or even smart watches, it has become clear that the concept behind the design and structure of Web pages is now obsolete.
There is a new methodology of design available that can take this into account. It is called Atomic Design, and the term was coined by Brad Frost. Thus, instead of thinking about content in the form of a page, each design element is created starting with its smallest component element (such as a call to action) and builds up to create something much bigger. We start from the atom to create the molecules, and these molecules come together in order to create a coherent and modular Web organism.

As each atom is placed individually in a library, Atomic Design saves a lot of time and makes for a more coherent and simplified end result.

Web Development

Makefiles, or How to Avoid Reinventing the Wheel

By Samuel Sirois

After having taken a break from frontend Web application development, I’ve recently jumped back into the field through two projects that I am working on. It represents a great opportunity to revisit my preconceived notions and old work habits, through a codebase that already exists and that is up-to-date with the latest stylish tools to use, ready after a simple git clone.

Wow, things do change quickly! (Even from the first line) From new versions of ECMAScript supported in modern Web clients – a panoply of pseudo-languages based on JavaScript – to the multitude of CSS pre-processors available… In addition to all these new automated build pipelines specifically created by and for JavaScript developers.

With all of these new shiny things, these automated build pipelines become essential to ensure that the minification, linking, compilation?!, of all of these files won’t cancel out the efficiency gains given by these tools which are now a necessity for the development of modern Web applications.

I still can’t keep myself from wondering if there hasn’t been a little bit of a lack of communication between those that have recently needed these complex tools in their projects (front-end developers) and those who have already faced these same requirements in the past and have discovered a solution (not the only one, mind you) to this problem, way back in the 70s!

I’ve never yet felt the need to use these new tools, as I already know Make, and having already been confronted with new, shiny, stylish solutions around the turn of the century, only to have taken some steps backward from something that already worked well. Indeed, I often insist on manually creating these Makefiles for projects I contribute to and I don’t hesitate to spend the time necessary to manage this tool.

Reinventing the wheel, i.e. to fall into the same traps and mistakes, or to really improve the situation? Here are a few interesting links to help you make your own opinions on the subject:

Contribution

From Contributions to Inno Hackfest

While evaluating the success of the afternoons we spend once per month on contributing to open source projects, we’ve decided to revise our formula a bit. Starting now, these afternoons will be held biweekly under the banner of “Hackfest”.

 Our First Few Hackfests

While working in small groups (and never alone), our SFLians have had the opportunity to learn about new technologies, to contribute to projects that they love or even to work on some new “side projects”.

In and amongst these contributions we find: initiations to the world of virtual reality (VR) through the creation of a dominos simulator using Unity and Oculus Rift; a workshop on blockchain technology and the connection with a concrete case study using the Ring software’s username database; the creation of a proof-of-concept client for a document-oriented database.

Upgrade Review

By Maxime Turcotte

The Drupal 8 migration report page, on which the modules that require migration are listed, was in sore need of a refresh in order to improve the user experience (UX). During our afternoon Hackfest, I wrote an initial patch that reuses certain design elements of the Drupal administration interface. Also, in adding just a few new descriptive icons, it is far easier to quickly find what requires our attention in this report.

 

Helpful Link:

Press Review Inno #5

Web Development

Node.js releases LTS of version 8.x

By Jacob Cook

The release schedule for Node.js provides for updates in long-term support (LTS) most every October, and this year will be no exception. Node.js offers developers a happy Halloween gift this year in transitioning its current version branch (8.x) to a stable LTS version. This means that features that have been at the cutting edge of development since early 2016 have finally been made available to users that require the stable and well-tested environment that an LTS version provides.
 

The new features in Node.js 8.x that have been eagerly awaited by developers include full support for async/await in Node.js core, updates to the V8 engine, an HTTP/2 implementation, a new version of NPM that allows for package version pinning with lockfiles, and much more.

Further reading :

Mobile

Firebase Dev Summit

The Firebase Dev Summit has just ended and several important announcements were made:
 
Following the purchase of Fabric by Google, Crashlytics will be integrated into the Firebase console. This new crash reporting system will benefit from access to other Firebase services, including Cloud Functions – which are the functions (lambdas) triggered when a Firebase internal trigger fires, or externally via a REST API call.

 

The added value of such an integration is in triggering a Cloud Function in response to some raised crashes. A crash in the main flow of the app could trigger an email to the entire team to speed up its resolution. A Cloud Function could also be used to create a task in a project management tool.
Google also announced that they are bringing machine learning to work with a new service, Predictions, which can categorize groups of users based on the way they use an application. Firebase can then present these groups with different offers or exclusive features to maintain their engagement.

 

Press Review Inno #4

Mobility

RxSwift 4.0.0 Final Version Released!

As mentioned in one of our last press reviews, we remain interested in and excited about new developments in the RxSwift project. The core developers pushing RxSwift forward have already released the fourth and most current version of it this past October 17 – i.e. RxSwift 4.0.0. You can find more information on its GitHub page here.

The version is available through various dependency management tools and GitHub. Just remember, the authors of RxSwift have always encouraged us to contribute to the project and, if you wish to do so, please follow these guidelines: About Contributing.

Android Studio v3.0

The new version of Android Studio is now available. Among the new features, we are most excited about: a new suite of tools allowing developers to profile their applications and more easily find performance issues, support for Kotlin, and a wide variety of new tools and assistants to make the use of Oreo APIs easier. 

If you are interested in learning more about the improvements and new features, please visit the
Android Developers Blog.


Netwoks and The Internet

The Internet, or How to Avoid Breaking What Is Working!

I try to avoid making the same old mistakes: i.e. breaking things that are already working or just avoid fighting against the tool itself  by regularly reminding myself of the Essence of the tools I use every day. 

Here are some articles that I find particularly pertinent regarding the “Essence” of the Internet, so that I can better avoid breaking things the next time I am asked to help put an existing Web application “in the cloud”!

Architecture and UI/UX Experiments at the DroidCon NYC 2017

Savoir-faire Linux’s Web & Mobile Development Team was at the DroidCon (@droidconNYC) in New  York on September 25th and 26th. DroidCon NYC is basically one of the biggest events on the planet fully dedicated to Android developers. During this two-day conference, more than 900 participants have been attending nearly 70 sessions on Android and its vibrant ecosystem. In this article, our team gives you an update on the presentations they have attended.


Sessions on Architecture

Model View Intent (MVI), Embracing Reactive UI’s

Our Web & Mobile Team! From the left to the right: Alexandre Lision, Hadrien De Sousa, and Thibault Wittemberg.

MVI is an application design pattern from the Cycle.js javascript library. It is based primarily on the concept of “Intents”, which represent the flow of user actions and the notion of “State”, which represents the immutable state of the application at a time T.

Intent streams are connected to the “State Reducers“. These reducers are simple functions whose purpose is to modify the state of the application step by step. The state is then displayed by the shape view of a “View State” (a pre-formatted state specifically for the view to display it).

This design pattern is therefore very much about functional reactive programming (or asynchronous dataflow programming). This is very close to Redux and highlights the interest of the immutability of the state (the mutability allows the sharing of reference on objects in memory, it is thus source of effects of uncontrolled edges) .

It also makes it possible to address the recurrent problem of managing the life cycle of the Activity / Fragment by introducing a cache of “State” on which the view will connect to each of its instantiations (in the case of a rotation for example) .

Reactive Clean Architecture

In this talk, the idea of “Clean Architecture” is based on a division of the application into 3 layers:

  • Presentation
  • Domain
  • Data

Reactive programming can help us in the communication between these layers that we present below.

Data layer

This layer exposes a “Repository” that provides public access to our data model and manages a “Reactive Store” that maintains the state of the application. Internally, this repository will rely on technical sub-layers such as network access, persistence and access to the file system.

Domain layer

This layer is based on a “Reactive Interactor” whose purpose is to manage user input. This Interactor subscribes to the “Reactive Store” in order to expose (by possibly filtering) the states intended for the upper layers (in particular the Presentation layer).

Presentation layer

This layer manages “ViewEntities” which represent the states of the application pre-formatted for the view. A “View Model” will be responsible for the mapping between the states from the “Reactive Store” (made available by the “Reactive Interactor”) and these “ViewEntities”.

In order to read more on this subject, you can consult the following article: Reactive Clean Architecture with Android Architecture Components

Opening Talk at .droidconNYC 2017

Advanced Networking with RX Java + Retrofit

While there are many useful example on how to use the “Retrofit” library, there is still need to better understand how it plays out in the context of complex cases such as the following:

  • Failure recovery,
  • The management of specific error codes,
  • Progress indicator display.

Here we provide you with some helpful tricks to address each of these cases.

The failure to recovery

  • Using the RxJava retryWhen operator.

Http errors

It may be interesting to apply the “share” operator on the observable Rx managing the requests (this makes it possible not to re-execute the request with each subscription). It is then possible to create as many subscriptions as there are error codes to manage, applying to each of its subscriptions a “filter” operator that will only pass the results with the error code to manage.

Progress indicator

The Rx stream managing the network request may someday set a “progress state” in the form of a “BehaviorSubject”. The Presenter (or ViewModel) can thus subscribe to the Observable resulting from this Subject and give rise to an update of the view.

An extra tip

It might be interesting to use RxLifeCycle combined with the MVP pattern to make it easier to manage rotations.

Kotlin

Full stack Kotlin

Kotlin is a well-known language to replace Java, especially as it proposes a more efficient syntax. Although associated with Android, it is also possible to use it in many other contexts such as: server application, native application, and Web application.

Back-end

Ktor is a library offered by Jetbrains (http://ktor.io). It allows to manage the Http layer and the WebSockets. It is therefore quite possible to develop a Rest API in Kotlin for example. Its operation is simple and passes by the instantiation of an embedded server (Jetty, Netty or Tomcat) then by the definition of routes. It is also quite possible to make him manage the static part of a website. Its main fault lies in its lack of documentation.

The following alternatives exist: Spring Boot / Javalin / Spark / Kara.

Front-end

It is also possible to write the front-end part (HTML and javascript) of a website in Kotlin with the help of the following APIs: kotlin.browser, kotlin.js, kotlinx.html. Please make sure to use the plugin “kotlin2js” instead of the plugin “kotlin”.

Native

Kotlin also allows you to write native code while having access to all the features of Kotlin 1.1.

We will be able, at the price of a compilation by type of platform, to run the same program on Mac OS, Linux, Android arm32/64, iOS and Windows. Of course, this does not concern user interfaces since each system has its particularities. In addition, one shall pay attention to correctly managing the memory in the manner of a C code. Furthermore, it is recommended to use the plugin “konan” instead of the plugin “kotlin”.

Build

Kobalt is a build system inspired by Gradle and Maven. It is written entirely in Kotlin and its compilation files are also valid Kotlin files, so it is possible to benefit from the code auto-completion features offered by IDEs. For more information, you can also access and read the Kobalt’s documentation –Kobalt: A modern, versatile build system.

Data Binding in a Kotlin World

Data binding as proposed by Google goes well with:

  • Dagger
  • RxJava
  • Kotlin
  • Architecture Components
  • Butterknife

It is, however, incompatible with:

  • Anko
  • Litho

It is possible to use an expression language directly in the XML layout (to do conditional processing, mathematical operators, etc.). This practice is not widespread since it breaks the principles of responsibility, namely write business code in the view part.


Sessions on the UI / UX Experience

View Performance Deep Dive

The Facebook teams have been trying to solve potential performance problems in rendering views, especially at the List view (ListViews, RecyclerViews …).

To do this, they made a 3-step comparison, measuring the rendering performance of the views with Google’s “Systrace” tool on a Nexus 5.

Step 1 : RecyclerView with ConstraintLayout

Each cell in the list is based on a layout type: “Constraint Layout“. The cells are relatively simple and contain only a text field, a button and an image. The performance analysis shows that the system omits some frames and therefore does not offer an optimal rendering.

Our feedback on the Constraint Layout in a recyclerView is brief; in fact, the wrap_content is sometimes misinterpreted on the height of ViewHolders which forces to use a fixed height.

Step 2: RecyclerView with Drawable

The idea here is not to build a view tree within a cell, but to draw it as a single Drawable.

The root view of the cell thus exposes its Canvas, on which we will come to draw our components. This technique requires a lot of code re-writing and does not take into account accessibility APIs or Touch events.

The measurement with Systrace shows us an obvious gain in rendering.

Step 3 : Litho

Litho is a library made available by Facebook. It relies on the declarative aspect of graphic components directly in the code, and not in XML layouts. Its primary goal is to reduce the rendering time of the view. For this, it is based on:

  • A finer division of the view tree (redraws only what is displayed),
  • An overall rendering of the view as a Drawable,
  • The rendering calculation in a “background thread”.

It also manages accessibility APIs and of course Touch events. Facebook is currently working on the integration of customs animations.

Facebook clearly shows us its intention to converge the concepts put forward in React.js with programming by Component and the use of Props and State. The internal Litho engine is responsible for mimicking the behavior of a virtual DOM. It is a competing vision of MVVM, MVP or MVI type modeling, where it will tend to use in addition to XML layouts a data binding (standard Binding of Android or RxBinding).

To obtain more information, you can read the Litho’s documentation — Litho: A declarative UI framework for Android.

Doze

Included from Android Marshmallow (API 26), Doze and App Standby are two components of energy saving. Doze is a system mode that restricts access to services, applications that use the CPU and the network extensively.

Since Android Oreo (API 26), these restrictions are even more severe and disable even implicit broadcasts (see, e.g. Implicit Broadcast Exceptions) and it is no longer possible to start a service in an application in the background.

To make it easier to migrate applications to include these new restrictions, Evernote has implemented the android-job library for creating deferred and background jobs.

The Resurgence of SQL

After a transition from mode and while many libraries of ORM can be abstracted, the SQL returns today with SQLDelight and Room.

Properly used, SQL allows you to execute the business directly in the database rather than in the code in order to gain performance.

SQLDelight

This library developed by Square generates Java models from SQL that allow to read and write in the database. SQL tables and declarations are written directly into .sq files interpreted by the library.

SQLDelight supports AutoValue but does not support Kotlin data class in its current version

Room

Room is a SQLite abstraction layer developed by Google for Android and is part of the Architecture Components such as LiveData and ViewModel.

This library generates SQL from Java using pre-processor annotation.

There are many examples of implementation of this library including Kotlin and there is more complete documentation for SQLDelight.

To obtain more information, you can consult the Documentation of Room here: Room Persistence Library

GraphQL on Android is here!

GraphQL

GraphQL is a query language for API development that aims to provide a complete description of the data that allows clients to query only what they need. GraphQL is developed by Facebook and is an answer to the problems encountered during the development of API Rest.

Apollo

Apollo-Android is a GraphQL client that generates Java templates from GraphQL queries written in a .graphql file. Generated classes are used to create network queries to the GraphQL API.

Apollo was written for the purpose of being fully compatible with the RxJava2 responsive programming library.

  • Apollo-Android is available on GitHub.

Upgrading to Moshi

Moshi is a parsing library of JSON to Java developed by Square who wants to be the successor of Gson considered inactive and heavy (1345 methods for Gson against 759 for Moshi).

The implementation of Moshi is relatively similar to that of Gson to facilitate the migration from one to the other. Some differences however:

  • Moshi has less default adapter for Java and Android platform types, forcing developers to write their own adapters,
  • For the sake of simplification, Moshi is less configurable (no naming strategy, versioning, etc.)
  • No JsonElement
  • Moshi uses the Okio bookseller for I/O and integrates perfectly with OKHttp

Moshi also supports Kotlin (moshi-kotlin) but is dependent in his current version of kotlin-reflect so size is very important for Android standards (11,500 methods).

  • Moshi is available on GitHub