Things to do after installing Elementary OS 0.4.1 (Loki)

When you start out with elementary OS there are a couple of useful things that you should do to have a better experience working with your system.

General

“Software & Updates” for Additional Drivers

The easiest way to install the proprietary NVidia Drivers (in Ubuntu) is to go to System Settings > Additional Drivers and then simply select the driver.

This option is not available in Elementary. However, by installing the package software-properties-gtk you can get the program.

sudo apt install -y software-properties-gtk

Now by clicking on Applications on the top right, and then type “Software & Updates” you can access the Settings.

Easy way to add PPA

With the command line tool add-apt-repository you have a quick way to add additional PPA’s. To get this tool you need to install the package

sudo apt-get install software-properties-common

MS Fonts

sudo apt-get install ttf-mscorefonts-installer

Add a Minimize Button to Windows

Some of the Elementary Windows do not have an easy way to minimize the window. With Elementary Tweaks, you can add a button to the windows.

Officially the elementary team does not encourage users to use the tweaking tool. It exposes switches to functionality that could mess up your system – use the tool with caution.

sudo add-apt-repository ppa:philip.scott/elementary-tweaks
sudo apt install elementary-tweaks

Chromium Browser

sudo apt install chromium-browser
sudo apt remove epiphany-browser -y

Screenshot Tool

sudo apt remove screenshot-tool
sudo add-apt-repository ppa:shutter/ppa
sudo apt-get update
sudo apt-get install -y shutter

Video Lan

sudo apt install -y vlc
sudo apt remove audience -y

Web Development Tools

Visual Studio Code

curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
sudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'
sudo apt update
sudo apt install code

git

sudo apt install git

NodeJS

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

System Update

sudo apt-get update
sudo apt-get dist-upgrade

Remove Programs

sudo apt remove pantheon-mail -y
sudo apt remove maya-calendar -y
sudo apt autoremove

Other

Productivity

sudo apt install libreoffice
sudo apt install gimp inkscape shutter

Codecs

sudo apt-get install ubuntu-restricted-extras ffmpeg

Codewars: Sum Of Pairs

Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

Source: https://www.codewars.com/kata/sum-of-pairs

The initial problem does seem quite simple:

  1. Iterate over the array
  2. Check for every item if there is a corresponding pair
  3. Return the pair that has the lowest right index
var sum_pairs = function (arr, sum) {
    let pairs = []
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            if (arr[i] + arr[j] === sum && i != j && j > i) {
                results.push(j);
            }
        }
    }
    if (results.length) {
        let value = arr[Math.min(...results)];
        return [sum - value, value];
    } else {
        return undefined;
    }
}

All Tests pass. You think to yourself, well that was quite straightforward. No big deal. Let’s attempt the solution.

‘Attempt timed out’ solution must finish before 12s pass.

Then let’s optimize the algorithm. what all can we do?

  1. We can replace the second loop with the internal array.indexOf Function
  2. If we found a match we can stop looking for matches past the matches index
  3. We can avoid the pairs array, as we are only interested in a specific pair
var sum_pairs = function (arr, sum) {
    let rightIndex = arr.length;
    let match = false;
    for (let i = 0; i < rightIndex; i++) {
        let pairIndex = arr.indexOf(sum - arr[i]);

        if (pairIndex != -1 && pairIndex < rightIndex && pairIndex !== i) {
            rightIndex = pairIndex;
            match = true;
        }
    }
    if (match) {
        let value = arr[rightIndex];
        return [sum - value, value];
    }
    return undefined;
}

At this point, we only optimized for a couple of edge cases. We did not really reduce the complexity of the algorithm in the worst case every item in the array would need to be compared with every item in the array O(n*n). As even when we are using the internal functions we are still iterating over all items.

Next round of optimizations:

  • Instead of iterating and forgetting what we did let’s save our result.

Initially, I had a solution to map all values to an array and then iterate and find the pairs so it would have been O(2*n). But I had difficulties implementing that solution as the array of values could contain duplicates. Then I thought about it and said, hey if I simply compare the current value with the previous values then If I find a match, then I can stop and it would always be the right value. and as a bonus, the complexity is now 0(n), as if the pair is the last two elements of the array we would have needed to visit all elements before that.

var sum_pairs = function (arr, sum) {
    let viewedValues = []
    for (let i = 0; i & lt; arr.length; i++) {
        let currentValue = arr[i];
        let difference = sum - currentValue;
        if (viewedValues[difference]) {
            let result = [difference, currentValue];
            return result;
        }
        viewedValues[currentValue] = true;
    }
    return undefined;
}

comparing the first and the last solution there is a tradeoff between the two solutions.

  1. In the 0(n*n) solution it takes longer to get to the result. However, we do not need so much memory.
  2. With the O(n) solution, we get the result quicker, but we need a lot more memory.

The Joel Test

In essence, the test is a quick 12 yes/no Questions that allows you to quickly determine how good your development workflow really is. anything below 10 and you are usually in big trouble in the long term.

Now let’s go a little deeper into the questions and what you would need to do to fix these issues. At the end, I put a list of my revised questions.

1. Do you use source control?

Now in reality, if this question is answered with “No” you are royally screwed. If this is answered with no, then stop right now and take a look at git. Even when you are working on your own project that does not be synced with a remote repository you should use git. It is easy to set up and there are a lot of providers like GithubGitlabAtlassian Bitbucket if you need to sync it over multiple computers.

The bigger question that relates to this is: “Does every team member understand the Source Control workflow?” The most popular workflow is the GitFlow it is easy to understand and new team members can understand immediately what is going on.

Does your Source Control integrate directly into your build system?

2. Can you make a build in one step?

In most modern development projects this is not enough. If you are doing a Web Development Project, you can use tools like nodemon(Auto reload for NodeJS) or Hot Deployment (Auto reload for Java / Tomcat) to ensure that you constantly build your server. Similarly, you would use something like the webpack-dev server for the frontend.

What I am saying is, you are anyway constantly doing builds of your software. The bigger question is can you also deploy your build without effort? It does not have to be onto a production system, but it could be a testing-server or some other staging system. So when you have to deploy to production you can ensure that it is as hassle-free as possible?

3. Do you make daily builds?

The question should be “Do you deploy daily?” – Whatever you are creating needs to be seen by as many eyeballs as possible. So that the Feedback can get back and influence the development as early as possible. Also, the client should profit from improvements as fast as possible.

This, in turn, does not mean that you should skip testing or quality assurance. It only means that stuff that is production ready should be shipped as soon as possible.

4. Do you have a bug database?

Now bugs are bad, and you need to know about them as well as which features you want to create for your product. So the more pressing issue is how are you tracking all of the development efforts you are putting into the project.

Instead of a bug database, you should have an issue tracker like JIRAor the integrated bug tracker from Gitlab.

The other thing to consider is a dedicated website for “Help us improve our product..” or a publicly accessible “bug database” so everyone that is using your product can easily report issues they are having with it.

5. Do you fix bugs before writing new code?

Well nothing to add here, fix your product before shipping new features. This is more an issue of business intent vs development. Usually, Sales will pressure you to ship faster and will try to cut corners. However, this practice is very expensive in the long run, as customers expect high-quality software. By Apple advertising their products as “magic” the expectation of high-quality software is now the norm. Cutting corners and not fixing bugs is no longer an option. Customers that have the feeling the software is buggy will look for another piece of software that has a higher quality.

On top, of course, is that the longer the bug exists the more money it will cost to fix the bug. So there are enough incentives to first fix bugs and then move on to the new features.

6. Do you have an up-to-date schedule?

Programmers hate schedules. It does not matter if you are ‘agile’ you need to estimate the work you are doing and match it with reality. Only then you can ship things with confidence. Developers need to learn to make a schedule for themselves and not work 14 hours a day just because they did not finish.

But what about extra features? well yes that is called scope creep and yes that needs to be regularly discussed and the schedule adjusted accordingly.

7. Do you have a spec?

You need a spec to start any work. If it is not specified it is unclear what you should build.

That is not an excuse for not specifying exactly what you need at this moment.

8. Do programmers have quiet working conditions?

Now this one is critical for every developer. However ‘quiet’ refers more to that the developers are not constantly interrupted. Have rules like: google it for 5 min before asking a fellow developer. Interruptions of a programmer can cause delays of up to 30min per distraction. To have efficient developers do not interrupt them and let them listen to whatever music they want.

9. Do you use the best tools money can buy?

Every developer has his own personal preferences, allow them to use the tools that they want. Some of the most awesome tools available VSCode is a free tool. Other things like JIRA, and IntelliJ are well beloved and cost a monthly fee. This money is well spent if the developer is happy and gets support from an industry leading tool.

I have seen Java Developers that switch to IntelliJ that were then up to 20% more efficient as before. The program drastically improves code quality and speed in which you develop code. In addition, it has the feature “Inspect Code” that analyses the code for potential quality improvements etc.

10. Do you have testers?

testers should take a look at the software. This includes automated tests, Unit Tests etc. You need to have a Test suite set up to be sure that changes do not affect other parts of the software.

Human Testers should also take a look to ensure that even really unexpected situations do not make the program crash.

11. Do new candidates write code during their interview?

This is a very important thing. HR People have no clue about coding, they cannot evaluate if the developer is suitable and can be integrated into the current team. By enforcing that you need to code in the interview somebody from the dev team needs to be present. That means he also can evaluate the potential hire, plus the potential hire can show off that he has some skills.

This, however, is widely misinterpreted by companies. Some companies have an exam that is more like “find the missing ‘;'”, or other similar trivial mistakes that are found instantly by a compiler. Or in another case a company wanted me to complete a task that would require 2days of development effort.

The programming task should be something that is simple and relates to the position the developer is applying for and that can be done during the interview, so it must be short.

12. Do you do hallway usability testing?

“Eat your own dogfood”, people in your company should be able to use the product without any explanation of it. If your own employees cannot use the product or understand what is going on, how should they sell it to a customer? It builds confidence in the dev team that you are doing the right thing and that other people (non-developers) understand what is going on.

Only other Developers are interested in what awesome code you have written. Normal People only care about if they can use the program. Usability is key to any successful piece of software.

The Joel Test V2

  1. Do you use source control? (Does every team member understand the associated workflow?)
  2. Can you build and deploy in a single step?
  3. Do you deploy daily?
  4. Do you have a ticket system for features, bugs, maintenance?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule and devs schedule/estimate their work?
  7. Do you have a spec?
  8. Do programmers have a quiet / interruption-free working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have Quality Control (Automated Testing, Human Testing)?
  11. Do new candidates write code during their interview?
  12. Do you do usability testing?

Source: The Joel Test: 12 Steps to Better Code

Image: Designed by Freepik

Puppeteer.JS – Using Headless Chrome for Site Crawling

PuppeteerJS essentially allows you to automate Chrome. Headless Chrome allows you to run Chrome without actually rendering the webpage. Sounds silly, but has a lot of useful applications, you could for example simply write a test script that ensures that your website is still working correctly.

Installation

npm i puppeteer
# or
yarn add puppeteer

Usage

We are going to look at a quick example of how to Log In to a site and then do some operation.

Initialize Puppeteer

You need to run it in an async function, simply because you do not know how long it will take until chrome has started. so with

const pupeteer = require('puppeteer') const page; (async () => {
    // Init Pupeteer
    const browser = await pupeteer.launch({ headless: false });
    const page = await browser.newPage(); // New Page to be manipulated

    // Automation

    // Close Browser
    await browser.close();
})();

We start our browser. The flag headless is set to ‘true’ as default, however for debugging purposes, you should set it to ‘false’;

Login

To Login to the site we need three things:

  • The URL for the Login Page
  • CSS Selector for the Username Field
  • CSS Selector for the Password Field

To obtain the selectors you can use the Chrome DevTools (F12). Simply select the HTML Field and with Rightclick select Copy Selector.

async function  logIn(){
    let LOGIN_URL = 'https://example.com/login';
    await page.goto(LOGIN_URL);
    await page.focus('#username');
    await page.keyboard.type(USERNAME);
    await page.focus('#password');
    await page.keyboard.type(PASSWORD);
    await page.click('#form-submit');
    await page.waitForNavigation();
    console.log("LOGIN COMPLETE");
}

Now since you are logged in to the site, you can navigate to any site and fetch all the links.

async function analysePage(){
    let PAGE_URL = 'https://example.com/'
    await page.goto(PAGE_URL);
    let links = await page.evaluate(() => {
        return Array.from(document.querySelectorAll('a')).map((val) => val.href);
    });
    console.log(links);
}

Final Code

import pupeteer from 'puppeteer'; 
//Node Version < 9 
//const pupeteer = require('puppeteer')

const USERNAME = 'user';
const PASSWORD = 'user';

const page; 

(async () => {
    // Init Pupeteer
    const browser = await pupeteer.launch({ headless: true});
    const page = await browser.newPage();

    // Automation
    logIn(page);
    analysePage(page);

    // Close Browser
    await browser.close();
})();

async function logIn(){
    let LOGIN_URL = 'https://example.com/login';
    await page.goto(LOGIN_URL);
    await page.focus('#username');
    await page.keyboard.type(USERNAME);
    await page.focus('#password');
    await page.keyboard.type(PASSWORD);
    await page.click('#form-submit');
    await page.waitForNavigation();
    console.log("LOGIN COMPLETE");
}

async function analysePage(){
    let PAGE_URL = 'https://example.com/'
    await page.goto(PAGE_URL);
    let links = await page.evaluate(() => {
        return Array.from(document.querySelectorAll('a')).map((val) => val.href);
    });
    console.log(links);
}

Image: Designed by Freepik

VSCode: Launch create-react-app and Chrome with launch.json

Developing React (with create-react-app) and Visual Studio Code you usually press ESC-` and then npm start. The script from create-react-app then automatically starts a Browser. That you then close. then reopen by pressing F5 to start Chrome in debug mode.

Let’s make these steps a little quicker.

Create a Task for npm start

Press Ctrl-Shift- and Select “Tasks: Configure Default Test Task” This will create a tasks.json file.

In the tasks.json file you need to add a couple of values:

  • isBackground: true – launch.json will not wait until the task completes
  • problemMatcher Needs to be defined to figure out when the task has completed its initialization phase and it is safe to continue with the next task
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "start",
            "group": {
                "kind": "test",
                "isDefault": true
            },
            "isBackground": true,                       //This prevents the launch.json to wait for the completion of the task
            "problemMatcher": {
                "owner": "custom",                      //This is not needed but, required by the problemMatcher Object
                "pattern": {
                    "regexp": "^$"                      //This is not needed but, required by the problemMatcher Object
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "Compiling...",    //Signals the begin of the Task
                    "endsPattern": "Compiled .*"        //Signals that now the initialization of the task is complete
                }
            },
            "identifier": "Start Server"
        }
    ]
}

Configure create-react-app

To prevent launching the browser you need to add in your .env-file following line:

BROWSER=none

More Info:

Configure the Launch.json file

Press F5 and select Chrome and a launch.json file will be created.

  • Change the port to 3000 (create-react-app default)
  • Add a preLaunchTask to start the task we defined earlier
{
    "version": "0.2.0",
    "configurations": \[ 
        {
            "name": "Chrome",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:3000",         //Change to the create-react-app default 3000
            "webRoot": "${workspaceRoot}/src",
            "preLaunchTask": "npm: start"           //Add prelaunch Task npm: start (defined in tasks.json)
        }
    \]
}

Start Working

Tadaa, now you press F5 and can start debugging directly in vscode. The background task will continue running even when you stop debugging.

Stop Working

You need to terminate the task via ctrl-shift-p > terminate Task. (Or you just close vscode)

DEV281x: Introduction to ReactJS

I took a quick look at Microsoft Introduction to ReactJS, not to actually learn React, but to evaluate how good the materials are for a beginner to learn React.

tl;dr Avoid the assessment. Maybe use create-react-app instead of codepen. Covers the basics quite well.

Lesson 01 | JSX and React Components

Instead of using “create-react-app” as a starting point, the course tells you to go to codepen to check out react.

I guess that makes it a little more focused on the React concepts and less focused on all the surrounding technologies that are needed in a production environment.

After that, it covers the basics of ReactJS, and JSX.

If you are a beginner you probably want to check out create-react-app.

Lesson 02 | State, Life Cycle and Event Handlers

I think the chapter covers the basics quite well. Nothing really to add here.

Lesson 03 | Lists and Forms

I think it is very nice that they cover the basics of handling multiple Form Elements with a generic handler.

handleChange(event){
  this.setState({[event.target.name]: event.target.value});
}

Assessment

The Assessment is quite theoretical and asks rather complicated questions. These questions are especially hard if you have already worked with React as you would never even try to build something in that way.

As a beginner, I would completely skip the assessment. It does not help your understanding of React. It actually also confronts you with bad practices, while inferring that this would be the way how you would actually do things

Conclusion

If you use create-react-app with vscode I think you would have a much better starting experience. The course is great to get started with ReactJS if you avoid the assessments and rather just experiment with your own code base.

Sources:

ImageDesigned by Freepik

DEV275x – Writing Professional Code

The course DEV275x Writing Professional Code is a very short introduction to best practices when it comes to writing code. As usual, this is only my notes I took during the course, you defiantly should check out the course for yourself at https://courses.edx.org/courses/course-v1:Microsoft+DEV275x+2T2017/course/

Module 1: Elements of Professional Code

Source Control with Git

Source Control is one of the most important aspects of programming.

  • Backup of your Source Code
  • Ability to compare with changes done in the past
  • Restore previous versions if something goes wrong with the new version
  • Easy collaboration with other people

There are many different Software packages that enable Source Control. Currently, the two most popular systems are Git (70% of Programmers) followed by SVN (10% of Programmers) (Survey of 30k Developers)

The core difference between the two is, that for SVN you need to set up a dedicated Source Control Server, and all changes are tracked there. With Git it is distributed, so you can use it locally and if you choose in combination with a server.

Especially Code Editors like Visual Studio Code have Git directly integrated making it really easy to set up and use Git.

Programs:

Cloud Providers

Workflows

Markdown

Markdown is really great because you can learn it really fast, and even if you do not convert Markdown into a HTML site or PDF the text is still formatted quite neatly and readable.

Like Git you find support for Markdown files in common editors like Visual Studio Code / Atom. And of course, in blogging software like WordPress have plugins that enable Markdown for the Posts.

Module 2: Communicate with Code

Now, this chapter was rather interesting, it focused on how those smaller things like code conventions actually help to improve the codebase. While the presenter did not use automated tools to improve the code readability it was nice to see that it is a very important aspect of coding to get the really basic elements correct.

Consistency and Naming

The code should be formatted always in the same matter. It improves the readability and removes all personal style from the code enabling all developers to immediately take ownership of the code instead of saying well that is the style of developer A, he should fix it.

Naming is important and greatly improves the readability of the code it does not help to say var c = 0, it is much better to say var beanCounter= 0. You do not write code for the computer but actually for other human beings. The compiler will then convert it into machine code, but you will probably not have to debug that.

Refactor Duplicate Code

A great problem is when the code base has a lot of duplicate code. As soon as that happens and some minor change changes the way how you do things, then you would have to go back and change all the different places where that piece of code is used.

Refactoring early reduces the risk that the next developer says, well, I will just do that with copy and paste.

Simplify

This one is rather difficult, but by keeping the code and the structures simple and readable has a much higher benefit in the maintainability of the code than some complex structure that executes a micron second faster. Of course, that depends on the program you are writing.

As a rule of thumb, functions should be rather short, not hundreds of lines long. (Too short is also bad.) If you needed to add complexity then you also should document why you are adding it and what is the best approach to understand that complex structure.

Module 3: Code Confidently With Unit Tests

Well writing Unit Tests and overall having Tests for your code, allows you to a) know the use cases of your code and b) allows you to see when you change something what else may have been broken while you were developing a new feature.

Sources:

ImageDesigned by Freepik

package.json: Updating Fixed Versions with npm-check

One of the common problems when running a larger project is that you need to use fixed versions in your package.json file. But at the same time you need to regularly update your packages. The most elegant way is using npm-check. The small tool allows you to select which packages should get an update and update accordingly.

Installation

npm i -g npm-check

Usage

To update the packages in your project you now simply run npm-check -u. If you want to ensure that you are installing the exact package run it with the additional optional flag -E to ensure exact-versions.

npm-check -u -E

With Space you select the packages and with Enter you install the package.

Sources:

ImageDesigned by Freepik

Elementary: Changing the Layout of the Window Controls

While Elementary focuses a lot on UI and is beautiful to use. It is totally mind-boggling that they decided to remove the minimize button.

By changing the value for “gsettings set org.pantheon.desktop.gala.appearance button-layout” you can adjust the button layout to your preference. The value would be in the format of [leftElements] : [ rightElements ]

So the default Elementary setting would be:

gsettings set org.pantheon.desktop.gala.appearance button-layout close:maximize

While the Windows Layout would be

gsettings set org.pantheon.desktop.gala.appearance button-layout :minimize,maximize,close

Sadly the official Elementary Apps do not support this setting, so a program like VSCode would have its Icons on the correct side, while the Pantheon-files still has the same button Layout as before. But well it is a good start.