CodeWars: Weekly Newsletter

8kyu – positiveSum

The first question is to sum up all the positive integers in an array. Basically two things need to be done:

  • Filter out Values that should not be added to the sum
  • Sum up every item in the array

Basically you can write the solution like this:

export function positiveSum(arr: number[]): number {
  return arr
          .filter(val => val > 0)
          .reduce((total, current) => total + current, 0)
}

It is important to note that the initial value of 0 must be set, as if you pass in an empty array it would return NaN

7kyu – next Prime

Basically you need to check every number if it isPrime. Then you need to select an algorithm that can check if it is a prime number.

In this case I just took the code from the npm package is-number-prime. Which is a brute force way of figuring out if the number is prime or not. (There is probably something more mathematically elegant out there)

function isNumberPrime(n) {
  if (n === 2 || n === 3){
    return true;
  }
  
  if (n < 2 || n % 1 || n % 2 === 0 || n % 3 === 0) {
    return false;
  }
  let foo = Math.floor(Math.sqrt(n));
  for (let i = 5; i <= foo; i += 6) {
    if (n % i === 0 || n % (i + 2) == 0) {
      return false;
    }
  }
  return true;
}

function nextPrime(n){
  while (true){
    n++;
    if (isNumberPrime(n)){
      return n;
    }
  }
}

CodeWars: Weekly Newsletter 02

8kyu – Logic Drills: Traffic light

You need a function to handle each change from green, to yellow, to red, and then to green again.

Based on how the question is formulated it is suggested that you should always return the next item in an array. If it is the last item it should return the first item.

/**
 * 
 * @param {'green'| 'yellow'| 'red'} current 
 * @returns {string}
 */
function updateLight(current) {
  let lights = ['green', 'yellow', 'red'];
  let nextIndex = (lights.indexOf(current) + 1) % lights.length;
  return lights[nextIndex];
}

However as alternative you also could say: We always already know the next state, we do not need to calculate the next state. For traffic lights this system also probably will never change. Thus you can use an object to save the next states.

/**
 * 
 * @param {'green'| 'yellow'| 'red'} current 
 * @returns {string}
 */
function updateLight2(current) {
    return {
    'green': 'red',
    'yellow': 'green',
    'red': 'yellow'
  }[current];
}

7kyu – Sum of numerous arguments

The idea of this problem is mostly to make aware of that you can pass in an arbitrary amount of arguments into a js function.

In ES5 you would be using the arguments object and iterate over the array. in ES6 however we can use the cleaner spread-syntax:

/**
 * 
 * @param {number[]} args 
 * @returns {number}
 */
function findSum(...args){
  if (args.find(val => val < 0)){
    return -1;
  } else {
    return [...arguments].reduce((total, current) => total + current);
  }
}

Dealing with the new Java Release Schedule

Oracle has just announced that the End of Support for Java 8 is going to be January 2019. This, in turn, means that every business using Java will need to upgrade for security reasons to the latest version of Java. The new release strategy says that newer versions have a 6-month support and then a new major version of Java is going to be released. In Addition, they are changing the Version naming scheme from SemVer to <year>.<month>Basically allowing Oracle to introduce breaking changes to Java every 6 months. As a business you basically are given the choice:

1. Upgrade Java every 6 Months

If we would go with the first option it already gets strange. At the moment assuming you are currently on Java 8 you would need to directly update to Java 10, as Java 9 Support already has ended. However, you still would first need to update to Java 9 just to see what all does not work anymore due to Java 9 major changes and then move to Java 10. But that is assuming that your 3rd Party libraries also already did the update to the new version. Then in September, you would upgrade to Java 11. A lot of people are going to say, well good then we just do not upgrade now and wait for September to do the upgrade. Yes, you can do that, but that does not really matter as in the following March you anyway would have to upgrade again. Your business needs a new strategy how to deal with the rapid version changes. That is now only supported for 6 months instead of the ~3+ years. Personally, I really like this, as most businesses have the strategy: “Version upgrade? only when hell freezes over” – that only costs money and has no immediate benefits.  Focusing on the short-term impact, neglecting the fact that continuous upgrades are cheaper in the long-term and contain less risk compared to the big bang upgrades. Source: Java Release Roadmap

2. Get Java Advanced licenses (Extended Support)

The alternative is to just get the Java Advanced license. I could not find any information on the Oracle site. Basically, you are paying around 500usd/core (Source), so depending on how many servers you are using you will have to pay a small fortune. At the same time, you are only sidestepping the upgrade issue as you anyway have to upgrade your system every 3 years at least once.

3. Use another Language

Depending on your codebase you may want to look into moving away from Java. If you are starting a project you may want to look into C#, Python or JavaScript (or any other language) Many Java projects are anyway already running for 15+ years and may need a technological overhaul. You could think about switching to micro-services and start replacing a service one by one with another technology. While there are many costs and risks involved switching technologies, *developer training, system stability, continuous support etc. etc.

Conclusion

It really depends on your project and how your business deals with change how you ultimately deal with Release Schedule.  You definitely need a strategy how to approach this problem. The future of Java is unclear. Oracle is promising more rapid improvements of the language.  But there is the possibility that the changes are too drastic so that businesses will stop using the language. Either Java will continue to be one of the most used programming languages or fade into obscurity. The only thing that is certain is that the world of Java is going to be changing significantly in the next couple of years.

HTML: How to control the Form ‘autofill’-autocompetion

Image Designed by Freepik

The ‘autofill’ feature of browsers is a blessing and a curse. The feature enables the browser to reuse the data the user has previously entered in forms. The trouble starts when a form does not fulfill the standard. Then the feature sometimes fills in the wrong information into the fields.

Why does autofill fail?

The standard implemented a feature to group fields. This was created by adding optional ‘8characters at the start of the name’. A field like “first-name” could be interpreted as the group: “first” and autofill-field: ‘name’(=> last name). To correct this you would need to rename the field to ‘given-name‘ as this is defined in the standard. However, if you would test ‘first-name’ in the browser you will discover that autocomplete works without problems. That is because even though it is not in the standard certain aliases are detected correctly. Depending on how the browser interprets the form. If you are not using the standard you basically are telling the browser to guess what the field is and let the browser decide what to autofill.

The Standard Keywords

If you want a pleasant user experience for the visitors of your site then you should take the time to make sure that your form confirms to the standard keywords:

  • “name”
  • “honorific-prefix”
  • “given-name”
  • “additional-name”
  • “family-name”
  • “honorific-suffix”
  • “nickname”
  • “username”
  • “new-password”
  • “current-password”
  • “organization-title”
  • “organization”
  • “street-address”
  • “address-line1”
  • “address-line2”
  • “address-line3”
  • “address-level4”
  • “address-level3”
  • “address-level2”
  • “address-level1”
  • “country”
  • “country-name”
  • “postal-code”
  • “transaction-currency”
  • “transaction-amount”
  • “language”
  • “bday”
  • “bday-day”
  • “bday-month”
  • “bday-year”
  • “sex”
  • “url”
  • “photo”

For Credit Card Information:

  • “cc-name”
  • “cc-given-name”
  • “cc-additional-name”
  • “cc-family-name”
  • “cc-number”
  • “cc-exp”
  • “cc-exp-month”
  • “cc-exp-year”
  • “cc-csc”
  • “cc-type”

To use these keywords with attribute autocomplete. However if the field autocomplete is not set browsers will automatically check the attribute-name. In this example both fields would be detected by autofill as ‘name’:

    <form>
    <input name="field1" autocomplete="name" />
    <input name="name" />
    </form>

As a personal preference, I would not set the autocomplete-attribute and simply use the keywords in the field name. This immediately eliminates the need to think of a more suitable name. If you are dealing with a backend you cannot modify I would use the field autocomplete.

Groups

Sometimes you need some of these fields multiple times. Let’s say you need a shipping and a billing address.  Then you simply add a prefix to the attribute.

    <form>
      <input name="billing-street-address" />
      <input name="billing-country" />
      <input name="shipping-street-address" />
      <input name="shipping-country" />
    </form>

How to disable autofill?

In the rare case that you do not need this feature at all you probably would want to disable it. To do this you have again two options:

Disable globally

Simply add the attribute autocomplete="off to the form-element. You then can re-enable the autofill on an individual component by using autocomplete=on.

    <form autocomplete="off">
      <input 
        placeholder="disabled Autocomplete" 
      />
      <input 
        placeholder="enabled for only this input" 
        autocomplete="on" 
      />
    </form>

Disable Individual Input

You can disable the autofill feature for an individual component by adding autocomplete="new-password" (This is because Chrome ignores the ‘off’ value)

    <form>
      <input 
        placeholder="disabled only for this component"
        autocomplete="new-password" 
      />
    </form>

Sources:

ReactJS: Tech Demo – Learn Typing

In order to learn ReactJS, I decided to create a small useful tool to learn to type. I just recently had found the typing exercises I did when I was 10, so using that data as a basis I created a small react site. Demo: http://typing.nealbuerger.comSourceCode: https://github.com/borgfriend/Learn-Typing

Core Prototype

The prototype only took a look at how to create a single lesson. The lesson was hardcoded and simply took a look at how the lifecycle methods of ReactJs work.

Issue Keyevent Binding I discovered pretty soon that my typing lesson was a quite unusual case for the key event binding for React. I was creating a new type of input field that displayed the old text and change the display depending on the input of new text.

Solution: For my unique case, I added an additional event listener to the document using and passed the information into the react app.

Issue Design Since the goal was to look at various technologies I analyzed ant.designsemantic-ui, and material-ui.

Solution Each of the GUI-Frameworks has their pros and cons. It was a difficult choice, in the end, I created the app using material-ui simply because I liked how it looked. Diving deeper into it how it deals with styles (while incredibly flexible) I would need to get a little more familiar with it. For the next project, I will probably try out something else.

Functional Prototype

To make the app a little more useful, I converted all lessons into a single JSON file. I considered to create a server with a database, but as I only had around 20 lessons and the resulting JSON file was 67kb I decided to simply include the entire JSON file. With more lessons, I needed a lesson overview page and routing. I added react-router and used it with the tools it initially provided. Using react-router can be a little awkward at first. But as soon as you get the hang of it it is a powerful tool.

Improved Functional Prototype

Problem Slow Display of Characters For short lessons react worked great. However, if the lesson had more than ~500 characters the react became extremely sluggish, with even longer texts it took ages only to type a single character. React was re-rendering all components on every keypress.

Solution Basically, the problem was caused by inefficient state management and updating techniques. I added in mobx to deal with all the states and rewrote the core prototype to take advantage of the mobx observers. An additional benefit was to use mobx-react-router which can create a routingStore and lets you avoid the withRouter()stuff.

Current Version

For the last iteration of the project, I refactored the entire code to be more readable and maintainable in the future. For now, I stopped working on this project. It should be only a quick tech demo to show how React code should look like.

Image: Green Typewriter Designed by Freepik

How to publish on Github Pages with create-react-app and react-router

Now I will be assuming a couple of things:

  • You have a GitHub account and you created a repository for your app.
  • You created a react app either with npx create-react-app <appName> or npx create-react-app <appName> --scripts-version=react-scripts-ts
  • Then let’s get started.

Add gh-pages

Run npm i -D gh-pages\

Configure your package.json

First, you need to tell the react app where it will be hosted. You need to add to your package.json the attribute ‘homepage’:

    { ...
    "homepage": "https://<UserName>.github.io/<RepositoryName>/"
    }

Additionally, you need to adjust the scripts attribute.

    "scripts": {
    ...
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
    },

Now you can run npm deploy and it will automatically create a branch, build the app and deploy it into your repository. It will even configure your github repository that the branch gh-pages will be now hosted.  So you can simply navigate to  https://<UserName>.github.io/<RepositoryName>/ and see the result. # Configure React-Router Before we can publish we probably have to change a couple of things in the configuration of the react-router.

  1. We need to set the basename. The basename ensures that all links of the Router are relative to this basename. To configure the basename you can use the variable process.env.PUBLIC_URL this ensures that you only need to configure the url via the package.json.
  2. We need to ensure that we are using aHashRouter instead of the typical BrowserRouter . The difference is that the hashRouter adds a ‘#’ into the url and upon a refresh of the page you will not see a 404 Github Error

Your index.js should look something like this:

    import * as React from 'react';
    import * as ReactDOM from 'react-dom';
    import { Router } from 'react-router';
    import createHashHistory from 'history/createHashHistory';
    
    const hashHistory = createHashHistory({ basename: process.env.PUBLIC_URL });
    
    ReactDOM.render(
        <Router history={hashHistory}>
          <App />
        </Router>,
      document.getElementById('root') as HTMLElement
    );

Deploy

Now can simply run `npm deploy` and your site should be published on https://<UserName>.github.io/<RepositoryName>/

Note: Since the build is published on a separate branch, your main repository may contain different src than what is published. So you still need to ensure that you commit your changes to your repository.

CodeWars: 7kyu – The Highest Profit wins

I am exercising to get back into Python. Even though the solution to this exercise is quite straightforward, you could tweak the code a little bit so that it runs a little faster.

Basically, with min() and max(), the list would need to be iterated over 2 times. You could rewrite the code so that you only iterate once over the array. Overall I choose to stick with my initial solution as it is better readable, thus making it easier to maintain in the long run.

def min_max(lst):
    '''
    Exercise: https://www.codewars.com/kata/the-highest-profit-wins/train/python
    Example:
        min_max([1, 2, 3, 4, 5]) => [1, 5]
    Args:
        lst: A list of numbers
    
    Returns:
        A list with two entries of the min and the max value of the list
    '''
    return [min(lst), max(lst)]

CodeWars: 6kyu – Counting Bits

You got numbers, you want to know how many bits are flipped to a 1

Sourcehttps://www.codewars.com/kata/bit-counting/train/python

Approach:

Well, first we need to convert our number from an integer to a binary number.

There are two ways to do this:

Variant 1: String Formatting

"{:b}.format(number)"

Variant 2: Build In a binary converter “bin(number)”

Then well now we just have to count the occurrences of ones.

def count_bits:
   return bin(number).count(str(1))

Note: It is important to count the instances of ones as strings of “1” instead of integers of 1. This is the case because we converted the int to a string and are now looking for strings instead of numbers.

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.