Build an Algorithm Processing Website

Why Care?

A friend of mine was interested in an idea for beating the casino at roulette.

His theory is that if he keeps playing either red or black, but adding to the bet, there is a mathematical certainty of winning at some point.

First spin, go red with $10.

Second spin, go red with $22.

Third spin, go red with $33.

Or something like that.

I told him I could write a program that would tell him the number of consecutive results from 50/50 roulette spins.

This is how we did it:

Tutorial For Launching Simple Algorithm Tools

Learning Algorithmic Technology

At this tutorial’s core, this is an HTML5 tutorial.

HTML5 incorporates HTML and JavaScript together. HTML5 incorporates CSS as well, but this tutorial doesn’t discuss that because design hasn’t been addressed here.

This tutorial takes the watcher on a journey of creating a simple web tool. In it we:

  • Start a project using command line interface (CLI) tools
  • Write the JavaScript algorithmic logic for the probability
  • Write the HTML5 user input form and clickable submit button
  • Link the JavaScript algorithm and the HTML5 input to work as a graphic user interface
  • Write clear directions for what the tool is used for
  • Initialize the project as a git project (version history software)
  • Sync our project with a GitHub repository
  • Publish the tool using GitHub pages

The tool is now available on the internet to whomever cares to view it. Click here to check it out:

www.ianrobinson.net/roulettespinner

If I were to answer my buddies specific question, this tool need more work. We would need to incorporate the increments of betting in order for us to get a specific plan to beat roulette…. but at the end of the day, this isn’t about beating the casinos. Even if we started beating casinos, the casinos would just kick us out.

The cool thing about this is that it helps us think algorithmically about complex issues. Using computers as tools, we can run massive tests in the blink of an eye. My computer only starts to have slow results (requiring 2-3 seconds) around 100 million spins. Imagine how long it would take to do 100 million spins in real life.

Algorithms are fun.

Fixing “Single arity template handlers are deprecated” error when upgrading from Rails 5.2 to Rails 6.0

DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> Coffee::Rails::TemplateHandler.call(template)
To:
  >> Coffee::Rails::TemplateHandler.call(template, source)
 (called from at /Users/MediocreManta/Desktop/freedom_podcasting/Rakefile:6)

This was an error I encountered while upgrading my application from Rails 5.2 to Rails 6.0. I found the fix on this Github page, but I thought I’d write it out here to make it a bit clearer for the young programmers out there.

To fix it, I upgraded the coffee-rails by doing the following:

  • Open Gemfile
  • Change gem 'coffee-rails', '~> 4.2'` to `gem 'coffee-rails', '~> 5.0.0'
  • Stop server in terminal by pressing ctrl + s
  • Running the command bundle
  • Restarting the server with rails s

Hope this helps!

I’ve added some language to the Rails documentation via this PR. Hopefully the powers that be accept the addition so future generations can skip having to look this up.

Comma Separated List of Array – Good idea for Ruby on Rails?

I feel like there should be a rails function for doing a comma separated list from an array. Here’s how to do it explicitly:

<% search_tags.each_with_index do |tag, index| %>
  <% if index < search_tags.size - 1 %>
    <%= "#{tag}, " %>
  <% else %>
    <%= "#{tag}" %>
  <% end %>
<% end %>

…maybe `render_comma_separated_list(array)` or something.

An example array would like this = [“one”, “two”, “three”]

render_comma_separated_list(array)

=> one, two, three

Does something like this exist already?

Is this worth the effort of making a PR to Ruby on Rails?

Radix Sort is Fun… but it’s Useless in JavaScript

I just spent an hour writing a Radix sort algorithm. It turns out that it is 25% the speed of the built in JavaScript `.sort()` function.

Apparently all this sorting has been figured out in the past. Strange that it’s part of learning to code these days…

const performance = require('perf_hooks').performance;


function getDigit(num, location) {
  let stringNum = num.toString();
  let resultNum = parseInt(stringNum[stringNum.length - 1 - location]);
  if (resultNum) {
    return resultNum;
  } else {
    return 0;
  }
}

function getDigitCount(num) {
  let digitCount =  Math.abs(num).toString().length;
  return digitCount;
}

function mostDigits(arr) {
  let maxDigits = -Infinity;
  for (var i = 0; i < arr.length; i += 1) {
    var digitCount = getDigitCount(arr[i])
    if (maxDigits < digitCount) {
      maxDigits = digitCount;
    }
  }
  return maxDigits;
}

function radixSort(list) {
  let numberOfDigitsTheLargestNumberHas = mostDigits(list);

  for (let i = 0; i < numberOfDigitsTheLargestNumberHas; i += 1) {
    let bucket = [[],[],[],[],[],[],[],[],[]];

    for (var j = 0; j < list.length; j += 1) {
      let number = list[j];
      bucket[getDigit(number, i)].push(number);
    }
    list = bucket.flat(2);
  }
  return list.flat();
}

function sum(a, b) {
  return a - b;
}

var ourBeautifulArray = [50000, 1200,1133, 44, 22, 1, 400000000];
var time1 = performance.now();
console.log(radixSort(ourBeautifulArray));
var time2 = performance.now();
console.log(`RadixSort took ${time2 - time1} to execute`);

var time3 = performance.now();
console.log(ourBeautifulArray.sort(sum));
var time4 = performance.now();
console.log(`Normal JS sort took ${time4 - time3} to execute`);

It’s possible that there is room for improvement in the way I’m executing this algorithm. Perhaps using .flat is causing this.

Either way, even if it’s not a useful thing to be able to do, I think it’s interesting. Once you figure out how it works, it’s neat because it sorts things in non-obvious ways.

I just wish it performed better. LoL

If you want to see the code I’m working with to deepen my knowledge of JavaScript, check out this repository.

Ruby vs. Python vs. JavaScript – What Programming Language To Learn First?

When I started programming, I struggled with deciding on a language. What programming language to learn first? How does one decide between Ruby, Python and/or JavaScript?

It’s an interesting question. I wish I could have seen the image below when I was trying to make sense of it:

FizzBuzz written in Python, Ruby and JavaScript

The three programs above all do the EXACT same thing. JavaScript on the left, Ruby in the middle and Python on the right.

All three print a count from one to fifteen. When the count is evenly divisible by 3 and 5, it prints ‘fizz_buzz’, when evenly divisible by 3 it prints ‘fizz’ and when evenly divisible by 5 it prints ‘buzz’. If none of those, it prints the number. You can see the count listed at the bottom of the image.

This is a classic computer programming exercise.

Aesthetics of Code

Whenever anyone shares their opinions on aesthetics, it’s important to remember that there are no right answers. Aesthetics are a matter of taste. So I’m just sharing my taste for code here.

The JavaScript file on the left requires considerably greater amount of keystrokes. It looks confusing. I see lots of opportunities to make mistakes.

Python is clearly the most concise. The Python code is three lines shorter than the other programs.

I like that Ruby doesn’t require semi-colons or colons. These symbols are annoying and require a close look. For me, it’s easy to mistake a semi-colon for a colon.

There is a question about how to write variables. One way is camel case (writingVariablesLikeThis), another option is to use underscore case (wirting_variables_like_this). Camel case is more concise, but I think it’s less aesthetically pleasing than the alternative.

In terms of aesthetics I can rank order the languages. Here they are from the prettiest to the ugliest (ugliest=JavaScript).

  1. Ruby
  2. Python
  3. JavaScript

Does that mean that I recommend learning Ruby as a first language?

Not really.

What Programming Language to Learn First?

Do this in order:

  1. HTML
  2. CSS
  3. JavaScript

JavaScript is the scripting language that you WILL learn if you care to write applications on the web.

All websites that have moving stuff use JavaScript.

Once you learn JavaScript, the other languages will be far easier to learn. I think switching from JavaScript to Ruby is actually interesting and fun.

If you come up learning Ruby, switching to JavaScript will seem like running with an irregularly sized weight chained to your hip.

Also, I’d suggest learning using Free Code Camp. I’m making a series of videos which I hope provide some special insights into the course work.

Enjoy!

Understanding Polymorphic Associations in Rails

When first trying to get an understanding of polymorphic associations in Rails, I was completely lost. At this point in my learning curve, polymorphic associations are a high-level concept in Rails which allows the programmer to reuse a single model to be useful for other models. It’s difficult to describe without an example. So… here we go.

An example of a polymorphic association is as follows. Let’s say you’re building a sports history database. Baseball players and basketball players are both athletes, but you want to be able to keep the baseballers separate from the basketballers. One way to do that is to create an Athletes model.

The Athlete model would be a way to tie the sports together.

Coding The Polymorphic Association

This requires a migration where we connect the athletes with the sports they play:

rails g migration AddSportToAthlete sport_id:integer sport_type:string

First we set the polymorphic association model:

class Athlete < ApplicationRecord
  belongs_to :sport, polymorphic: true
end

Then we assign that association to the baseballers and the basketballers:

class Baseballer < ApplicationRecord
  has_many :athletes, as: :sport
end

class Basketballer < ApplicationRecord
  has_many :athletes, as: :sport
end

irb rbenv: pry: command not found – FIXED

$ irb
rbenv: pry: command not found

The `pry' command exists in these Ruby versions:
  2.3.1

I was having the issue in which I was attempting to test code using irb and the irb command wasn’t opening the Ruby REPL.

Apparently, pry was interrupting my usage of irb.

To fix it, I just updated pry:

gem install pry
irb rbenv: pry: command not found

Now it’s updated and working correctly. Here are my related software versions:

$ rails -v
Rails 5.2.1
$ pry -v
Pry version 0.11.3 on Ruby 2.5.1
$ irb -v
Pry version 0.11.3 on Ruby 2.5.1

Seeing a Rails App Develop From Looking at Git Changes

I’m deep diving into Ruby on Rails this week. One of the things I find interesting is how the scaffolding creates new parts of a Rails app. This is a helpful tool for understanding the stack so I’m stepping through it looking at the changes made which we can see better with git.

Below is a step by step view of the files created when developing a new Rails App. 

Stepping Through Rails and Watching Git Changes

rails new appName

  • git status => All code related to Ruby on Rails

appName => bundle update

  • git status => No changes

appName => bundle install

  • git status => No changes

appName => bin/rails generate controller name_of_controller

  • git status =>
    • app/assets/javascripts/ian.coffee
    • app/assets/stylesheets/ian.scss
    • app/controllers/ian_controller.rb
    • app/helpers/ian_helper.rb
    • test/controllers/ian_controller_test.rb

Note: git changes do NOT note that when generating a new controller, Rails also generates an empty views folder. This is an important thing to be aware of as your view templates will go here related to your new controller.

appName => bin/rails generate model name_of_model title:string body:text slug:string

  • git status =>
    • app/models/tree.rb
    • db/migrate/
    • test/fixtures/trees.yml
    • test/models/tree_test.rb

Creates the new files needed to maintain a model, it’s test data and test process.

appName => bin/rails db:migrate

  • git status =>
    • db/schema.rb

This process specifically reflects your new model’s functionality with the database.

The 12-Factor App – Notes and Reflections

What follows are my own notes and summations after reading what makes a 12 factor application. Reading this has been a great glimpse into why we do certain things.

I’m currently working with a friend (Ginger Nomad) on building a web app. He is the expert so I follow his lead even though it seems needlessly complex at times.

After reading this, I get it. Why obfuscate the config.js file and the .env files with these additional node modules? Because it’s smart. This document helped me get off the, “Why are we making this so complex”-train.

That’s the why. Here are my notes.

I. Codebase

A deployment is a running instance of an application. This of a deployment like a play. Trey and Matt wrote the Book of Mormon, but the Eugene O’Neill Theatre puts an instance of the play on when they perform it.

Each application should have a single codebase. If multiple apps make up a software project, that isn’t an app. It’s a distributed system made up of apps. Each app that makes up a distributed system should be a 12 factor app on it’s own.

II. Dependencies

A 12 factor app doesn’t depend on system-wide packages. When building a 12 factor app, I should be able to send a new developer the project and they should be able to run it with a working version of node and a simple npm install XXX command.

III. Config

12  factor apps should contain everything that is likely to vary between deploys in a single place. This is often the .env file for us NodeJS developers. This file will include things like:

  • Database Connection Keys – URI, Username, Password, etc.
  • External service credentials – API keys for example
  • Canonical values like hostname – We use path – npm

When we build NodeJS apps, we use the env – npm package to put all the config information in one place.

They warn against storing config variables as constants across the whole application. I’m unsure if this is for security reasons, or if it’s because they just want all the config variables in one place. When deploying multiple instances of an application, it makes sense to have all that data in one place for easy (or algorithmic) editing.

IV. Backing Services

There should be no distinction between local and third party services. To me, this means the app should be able to swap a local MongoDB with a database hosted on mLab, for example, without changing the codebase.

Other backing services could include Amazon S3, Google Maps, Twitter, and Postmark to name a few.

Why? Imagine you’re running an instance of your application and the server gets hit by a bus. That would cause the server to stop working and the database to explode into an inferno. How would you clean it up?

Well, because your backing services are all connected the same way, you would just adjust the config file and create a new instance of the database from backup. You could be back up and running in 10 minutes.

V. Build, Release, and Run

12 factor application development calls for separated build, release and run stages.

  • Build Stage – Where you transform a code repo into an executable bundle. This is where the server fetches dependencies and compiles the assets.
  • Release Stage – Combined build procedure with deploy’s config resulting in a release which can actually be run by humans.
  • Run Stage – Here you run the app by running it’s processes against a selected release. Otherwise put, you use it. Click away brave soldier!

VI. Process

The document calls for executing the app as one or more stateless processes. These processes should be stateless and share-nothing. All persistent data should be stored in a backing service like a database.

To be honest, I don’t entirely get this. I relate it to the way Redux adjusts state in single bursts, but I’m unsure if that is a worthwhile comparison (let me know in the comments below if you know more about this).

VII. Port Binding

12 factor apps should be self-contained and should not rely on runtime injections of a web-server into the execution environment.

I don’t know what self-contained means exactly. It’s possible that NodeJS was built to be self-contained so I’ve never experienced this problem. When building a Node application, one of the first steps is to set the port for the server to listen from.

VIII. Concurrency

Processes are first-class citizens.

In 12 factor apps, the processes share nothing and are horizontally portionable so adding concurrency is simple and reliable.

To me this is like… returning books at the library. The application is the library and it can put a box out to collect returned books. If the library has an especially busy day of book collection, they can just put out an additional box. That way the two boxes are accepting books at the same time, but they books aren’t getting mixed up or returned out of order….

Does that make sense? If you have something to add, please do so in the comments below.

IX. Disposability

Robustness in applications is maximized with graceful shutdowns and fast starts. Therefore, 12 factor apps should be able to be stopped and started at a moments notice.

SIGTERM is the signal from a process manager which should be able to shut down your application.

Idempotent – A property of an operation that means the operation can be applied multiple times without changing the result beyond the initial application.

In the article they mentioned a database technology called CouchDB. I’d like to return to it one day. I love the idea of idempotent operations.

X. Development and Production Parity

Development, staging and production should have similar execution environments. Also, they time distance between a developer making a change and the production side of the app seeing that change should be short.

No more working on code for six months and launching it once. Continuous development is an important characteristic for 12 factor apps.

XI. Logs

12 factor apps should treat logs as event streams. Therefore a 12 factor app should not be concerned with routing or storing it’s output stream.

XII. Administrative Processes

Administration processes should be one-off processes.

Administration code should also ship with the application code and run against a release using the same codebase and config process.

12 Factor App Checklist

  • Does your application require a single code base?
  • Are all required external dependencies loaded into the app? Can a new node developer run ‘npm install’ and get it working?
  • Are all your config variables and settings in a single file?
  • If you pushed your codebase to an open source repository like GitHub, would your config information be automatically hidden?
  • Does your codebase interact with backing services without editing the codebase?
  • Are your build, release and runs stages strictly separated?
  • Are your application’s processes stateless? Do they share nothing with other processes? Is your backing service stored in persistent backing services?
  • Does your app NOT require injections of a webserver?
  • Have you bound processes to a specific port?
  • Does your app NOT daemonize or write PID files?
  • Can your app be started and stopped at a moments notice without losing important data?
  • Are the development and production environments similar?
  • Does your app not care if it’s storing logging output streams?
  • Does your admin code ship with the application? Is the admin code connected to the release number, the codebase and the config file?

If you answered yes to tall the above questions, it seems you have a 12-factor app. Please let me know what it is in the comments below as I’d like to see what you’re working on.