Showing posts with label Web-Development. Show all posts
Showing posts with label Web-Development. Show all posts

2021-04-28

Programming Language Notes 2021 - multiplatform, GUIs

These are incomplete notes and thoughts on programming languages through lens of multiplatform support and coding GUI apps for platforms like Android, iOS, Mac, Windows, Linux, and web (front and back ends).

JavaScript

Lack type safety.

Java, Go, Python, Ruby, C++, C, Elixir

Not great for frontend web dev.

D

Not great for Android or iOS.   Can build web apps via compiling to WASM (pretty sure it's experimental), but lack mature frameworks for frontend web dev.  Not very popularly used, unfortunately.

TypeScript

It's JavaScript but with a brilliant aftermarket type system retrofit. If you must code JS, then TS is a fantastic upgrade.

For backend, there's faster languages (Java, Go).  For device native apps, other languages are maybe better suited (Swift, Kotlin, etc).  Great choice for web frontend.

For frontend web dev, used with React is popular.  There's React Native to build device native apps for Macs, Windows, Linux, Android, and iOS that uses platform native UI widgets (some haven't reached 1.0 yet though, if you're looking for maturity).  You'd still have to build 5 specialized UIs though (6 including web), and there are faster device native languages.

Kotlin

Compiles to JVM, JS, and native.  Kotlin Multiplatform Mobile (alpha) is great for write-once application logic for iOS / Android native apps, but the UI code must be specialized for each platform (could still be written in Kotlin though).

e.g. Use with Google Android's Jetpack Compose (beta) and Apple's Swift UI for native Android and iOS UI.

e.g. Use with Jetbrains' Compose for Desktop to build apps for Windows, Macs, and Linux --- but this  runs on JVM and renders using Skia, so it doesn't use platform native UI widgets (it draws it's own like a game does).  And it's in alpha.

Some say Jetpack Compose is Google Android team's answer to Google Ads team's Dart/Flutter.

Kotlin/JS means you can use with React for frontend web dev too.  Not sure of its maturity.  Kotlin is great for backend using Spring or Ktor.

PHP

Not great for device native apps

C#

Windows centric.  Blazor lets you do frontend web dev by compiling to WASM but it adds C#'s runtime to your web app to run in WASM as well (read: bigger, slower app).

Rust

Lower level, like C or C++.  Can build web apps via compiling to WASM, but without bringing a runtime along for the ride (check out Yew or Seed).  Can build backend stuff (check out Actix-web or Rocket), but frameworks aren't mature the way Django or RoR are.

Coding device native GUI apps is... not there yet.

Rust is getting a lot of traction for systems programming though (unlike D, unfortunately).

Dart

Basically exists for Flutter.  Flutter lets you build apps for Windows, Macs, Linux, iOS, Android, and the web.  On the web, it draws into a canvas.  On devices, it renders using Skia.  So it doesn't use platform native UI widgets anywhere, and draws it's own like a game does.  On the web, it's UI performance is a little janky.

Dart compiles to JS or runs on Dart VM.  Unlike the Kotlin stuff above, Flutter is production ready and being used by Google, notably by their Ads team (apparently some of the Kotlin stuff above are the Android team's answer to Flutter).

It's from Google, so who knows if they'll cancel it in 5 years time.

Other thoughts

Rendering to Skia like Compose for Desktop and Flutter is not great for accessibility, and their accessibility features are currently WIP.

React Native has edge cases for each platform so you'd still need to know each platform carefully.  Plus TypeScript / JavaScript bridging into native can have performance issues.

 Nothing's perfect.

That's all I've got time for today!

Missing: Scala, Clojure, Haskell, F#, Crystal, PureScript, Elm.

2020-03-25

One way to use SemVer for software versioning

Everyone has their own system for versioning in their software development process.

Semantic Versioning is very popular of course.  It basically takes the form of:

major.minor.patch-prerelease+build
  • Major for breaking changes.
  • Minor for backwards compatible feature additions.
  • Patch for bugfixes meant to be backwards compatible.
  • Pre-release tags for internal versioning, building up to a release.
  • Build for internal build numbers, useful if you build a lot.
There is a precedence order to SemVer numbers to essentially designate which version is "newer" in some sense.

Pre-release and Build tags do not participate in the precedence order.   So when specifying ranges of versions, those pre-release tags are kind of ignored in things like NPM contrary to precedence order as SemVer defines it --- reality is different than theory, right?

Pre-release tags are great for Designating development stages but when they are removed to do a non-pre-release release (e.g. a final release), it messes up the lexicographical ordering --- i.e. messes up the order in which they show up in my file browser. haha.

How I use SemVer

So I'm trying a SemVer compatible system that respects the 2nd and 3rd laws: "Don’t mess with math", and "Make friends with infinity.  In other words, don’t be afraid to increment".

The basic idea is: keep pre-releases to a patch level, release at the next patch level.

The rules are:
  1. Start at 0.1.0.
  2. Increment patch number to make a release
  3. Increment major, minor, or patch (whichever you're targeting for next) to make pre-releases
  4. Pre-releases are tagged a1, a2, ..., b1, b2, ..., rc1, rc2, etc.
  5. Use increasing build numbers if you need
  6. Use a "." then another build field if you must, like for adding a non-increasing alphanumeric build field (e.g. a SHA)

Example

So you'll get versions of WildApp like these, e.g.:
  • WildApp 0.1.0-a1
  • WildApp 0.1.0-a2
  • WildApp 0.1.0-b1
  • WildApp 0.1.0-b2
  • WildApp 0.1.0-b3
  • WildApp 0.1.0-rc1
  • WildApp 0.1.0-rc2
  • WildApp 0.1.1
  • WildApp 1.0.0-a1
  • WildApp 1.0.0-a2
  • WildApp 1.0.0-b1
  • WildApp 1.0.0-b2
  • WildApp 1.0.0-b3
  • WildApp 1.0.0-rc1
  • WildApp 1.0.0-rc2
  • WildApp 1.0.1
I'm going to give it a try at least.

2019-07-23

Create React Native App using TypeScript compiled with Babel


Here's every step to creating a React Native app, written in and type checked with TypeScript, but compiled with Babel 7.

You're assumed to have some proficiency with using the terminal.

Tools to Install on your PC

I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
  1. Install Homebrew.
    It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
  2. Install Node thru brew.
    Installing Node should include the NPM package manager with it, which is needed below.
  3. Some say to next install Yarn thru brew.
    Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
  4. Fix NPM if you installed Yarn.
    I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
  5. Install React Native CLI thru npm:npm install -g react-native-cli
    This is basically a template that creates a RN project for you to start from.
[1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

New Project with React Native

1. Create a React Native project:
$ react-native init CoolProject

1.5. Upgrade core-js:
I got an error like this:
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

You just need to upgrade core-js.  Go into your CoolProject folder and run:
npm install --save core-js@^3

2. cd CoolProject to go into the new project's root directory, then install Babel:
$ npm install --save-dev @babel/core @babel/cli
I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

3. Create a lib folder in the project root.
$ mkdir lib
The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

2019-03-20

How to migrate ReactXP App to make an Electron Desktop App

ReactXP comes with a few sample apps. The TodoList app is the most developed and closest to the structure of a production app written in TypeScript, but doesn't target Electron.  Here's how to migrate it to run on Electron so it could work as a desktop app.

I'm on a Mac, but Electron is cross platform with Windows and Linux so it should work there too.  ReactXP 1.6.x is current right now (hilariously, it upgraded from 1.5.x just as I was working on this and it introduced some new error so this migration is totally in beta).

Strategically, the idea is ReactXP can already directly target the web via React (in addition to native iOS, Android, and Windows via React Native).  So we just target the web with ReactXP, modify the web page loader to run in Electron, and modify some code so it doesn't assume it's running at the root of a web server.

Make TodoList into a web app. Run it on a local dev web server

First, use git to clone the ReactXP repository:

git clone https://github.com/microsoft/reactxp

In the reactxp/samples directory, you'll find the TodoList app. Open it:

cd reactxp/samples/TodoList/

Install Electron into it:

npm install --save-dev electron

Now we need a web page to load the app into Electron.  We'll use the default one from Electron quick start.  Just copy the main.js from electron-quick-start into the TodoList folder, and rename it to electron-main.js just for clarity.

2019-03-09

Maximally Cross Platform with React?

Once upon a time, going cross platform meant making an application that ran on both Macs and Windows, and maybe Linux/Unix if you're into that crowd.

Now everything is fragmented and compartmentalized.  Consider what "platforms" there are now for making apps:

  1. desktop web browsers --- i.e. Chrome, Firefox, Safari, vs Edge --- further divided by Macs, Windows, and Linux (at least for browsers that are cross platform, ha!)
     
  2. mobile web browsers --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
     
  3. Electron desktop apps --- i.e. Macs, Windows, vs Linux (built with web browser technology)
     
  4. native desktop apps --- i.e. Macs, Windows, vs Linux
     
  5. native mobile apps --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
Some of the above differences are a matter of building user interfaces sized for use on that display size, while other differences are a matter of framework (e.g. Cocoa vs Android SDK).

But at worse, that's still 26 different platforms to build for!  There are technologies that help bridge the divide, and one family of such tech is called React.

Here's a survey of some React based technologies and which platforms they work well for.


2019-03-06

Create React Native App using TypeScript with Babel and Expo

(updated 2019-07-23 for clarity)

Here's every step to creating a React Native app (with or without Expo), written in and type checked with TypeScript, but compiled with Babel 7.

You're assumed to have some proficiency with using the terminal.

Tools to Install on your PC

I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
  1. Install Homebrew.
    It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
  2. Install Node thru brew.
    Installing Node should include the NPM package manager with it, which is needed below.
  3. Some say to next install Yarn thru brew.
    Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
  4. Fix NPM if you installed Yarn.
    I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
  5. Install Expo thru npm:npm install -g expo-cli

    Expo is apparently kind of a mini-platform for running React Native apps, and makes it easy to test a React Native app on devices through its Expo app, or on Macs and PCs without resorting to an Android or iOS emulator (which is great, because those emulators are dreadfully slow in my experience).  Plus installing Expo should include React Native with it.
  6. Install React Native CLI thru npm:npm install -g react-native-cli
    This is basically a template that creates a RN project for you to start from.
[1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

New Project with React Native or Expo

1. Create a React Native project (possibly thru Expo):
$ expo init CoolProject
or alternatively without Expo:
$ react-native init CoolProject

1.5. Upgrade core-js:
I got an error like this:
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

You just need to upgrade core-js.  Go into your CoolProject folder and run:
npm install --save core-js@^3

2. cd CoolProject to go into the new project's root directory, then install Babel:
$ npm install --save-dev @babel/core @babel/cli
I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

3. Create a lib folder in the project root.
$ mkdir lib
The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

2016-12-03

Elixir and Phoenix on MacOS for the First Time: install to first project

Let's install Elixir and Phoenix on MacOS, and create our first web app project.

I looked through 3 separate web pages to figure it out (it was relatively easy), and thought it'd help to gather it into a single page of 10 steps.

What's Elixir?  Elixir is a programming language that superficially looks a little like Ruby, but more importantly is designed to be dynamic, functional, and capable of building concurrent, distributed, low-latency and fault-tolerant systems (perfect for the web!).

It does that by running on the Erlang VM (like a Java VM, not like a VirtualBox VM), and that also gives developers access to Erlang’s ecosystem (this reminds me of how Clojure runs on the JVM, providing access to Java's ecosystem).

What's Phoenix?   Phoenix is an Elixir framework implementing the server side of a web framework for modern web applications.  Like Ruby on Rails or Python's Django, but Phoenix is written in Elixir and derives benefits from that (in addition to whatever other advantages it may have as a framework - we're not comparing frameworks today).


(1) Install Homebrew

To begin, you need Homebrew installed on your MacOS.  Homebrew is a package management system that makes installing lots of developer software much easier on Macs.

Once installed, especially if it's been a while since you've last used Homebrew, make sure to update it (commands after "$" are to be typed in your terminal window):

$ brew update

Do a self diagnostic to make sure it's all okay, carefully read the instructions it provides:

$ brew doctor


(2) Install Elixir

Elixir requires Erlang to be installed.  Fortunately, the Homebrew package will automatically make sure of that.

2016-08-02

3 Steps to Free SSL for your domain's static website on AWS S3

Today, let's talk about upgrading your static web site --- served from your own domain --- so that it serves over HTTPS secure protocol.

Prerequisites
This post assumes you've got certain things already set up. If you don't, the rest of this post won't help you, sorry.

(1) You must already have a static web site served from Amazon Web Services (AWS) S3.

But really, if all you've got is just a static web site (no dynamic content, no server side scripts, no database, etc.), using S3 is pretty awesome.  It's fast, inexpensive, and pretty easy to set up --- a topic for another day perhaps.

(2) You must already have your own domain name set up for your web site, e.g. from Namecheap, and you're a little comfortable setting up custom "Advanced DNS" records like CNAME records, etc.  Again, if you don't, the following won't help you, sorry.

NameCheap's been pretty fantastic for domain name and DNS services for me.  Great service.

(3) You also must have email set up for your domain name.  Maybe you've got email set up with that domain name from your domain name registry (e.g. Namecheap).  Or maybe you've got it set up with a dedicated email hosting service, e.g. Fastmail.com, or Google Apps for Work.

Strategy
The general ideas are these:
  1. Get a free SSL / TLS certificate for your domain name from AWS Certificate Manager (ACM)
  2. Create an AWS Cloudfront Distribution to originate content from S3, to be served out on a Cloudfront address.
  3. Change your domain name's DNS CNAME record to point to that Cloudfront address.

2016-07-11

JavaScript OOP inheritance explained with diagrams


We're not talking about ES6 classes today.  Just ES5 JavaScript object-oriented programming.

## Prototypal inheritance

People say there's at least these **3 big features of OOP** that distinguishes OOP from other styles of programming:

1. Encapsulation
2. Polymorphism
3. Inheritance

We're going to focus on the last item today.

OOP in JavaScript isn't intrinsically class-based in the style of Java.  I assume you already know a thing or two about OOP in terms of Java or Python, or similar though.

Instead, **JavaScript OOP is prototype based**.

That means you'd just make an object `c` as you like it, no class definition required --- but if you must think in classes, imagine making a class `C` and using it to create exactly the one object `c`.

Then when you want another object `s` to inherit from object `c`, you'd just do it, *no class required* --- again if you must, imagine making a class `S` that inherits from `C`, and using `S` to create exactly the one object `s`.

Conceptually, it's simple, but trying to use it productively, with constructors and everything else, and it can get confusing.

Rather than learning how to do class-based OOP in JavaScript (for that, see MDN's [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) instead), let's try to really understand what JavaScript is doing --- from the bottom up.

## Diving in, bottom up

In JavaScript, everything are objects, even functions.

OK, some things are primitives... forget that, let's just see some code.

By the way, I'm running all the code in the Firefox Console.  Explanations and diagrams are interwoven into the code as comments.

## Cosmic Super Object
Let's start with the "cosmic super" object that all objects
usually inherit from, namely the object stored at 
`Object.prototype`.

```JavaScript
typeof(Object.prototype); // is an object

Object.prototype.prototype === undefined; // true
Object.prototype.__proto__ === null; // true
```

So `Object.prototype` doesn't have a `prototype`, and it doesn't
"`__proto__`-inherit" from anything.  The buck stops here.

In JavaScript, each object `o` has a `__proto__` property that
points to the object that `o` **prototypely-inherits** from
(as opposed to "inherit" in the class-based sense).

So from here on, if `s.__proto__ === k` then we say `s` **proto-inherits** from `k`.  I use the term "proto-inherit" to distinguish from the Java-style, class-based, concept of inheritance.

Yes, `__proto__` is deprecated, but it works (for now) and is easier to think with.


We're going to start diagram out the relationship
between the various objects we're exploring in JavaScript.

![Object.prototype UML-like diagram](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJZIMM9zCjENTA9a-3J3tm3NwQV-KrRXFQzB5zyxwDC7Q7qPSXXrXncOHmTktqCMqdcAsw6xRAMbrKfj2FGI56gDbAwoBmqe6-ovF_ZS1tprzxwaSeHfUnqfBQ7sOSXRXbrHCA89AGQFA/s1600/d1.txt.png)

As described before, if you must think in classes, then making an object
in JavaScript is like writing a class and instantiating exactly one object
from it, so we'll draw objects in the style of UML classes.

i.e.

![UML-like class diagram example schema](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjEss9UraMrJC7cwso34SN0A_SnETwAmxgnmLoYHQLanN68PI-Sd5Xr6KBPA1q-1HFp8H9dbkBgAUI7o6Expfhn5y4ePFGneu1sRJCoYwih4dP_NuyNeiGvysk2FqMc4lUszCaotE7dj4/s1600/d2.txt.png)


## Object function
But if `Object.prototype` is an object, what is `Object`?

```JavaScript
typeof(Object); // is a function.
```

Huh, but it had a `prototype` property before...
I guess functions are like objects and can have properties.

In fact, there is a circular relationship between
`Object` and `Object.prototype`:

```JavaScript
Object.prototype.constructor === Object; // true
```

Since functions can have properties, we'll draw them like objects
but tag them with "fn:"

![Circular relationship between fn Object and Object.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw2LI308pvxETX61mR7VYvqZH3mFJS71sn_ZLgoFPTygfm_jwi_LmzPXh-plk-1ZZVtPY18SIehfFFvLPtNoxFi2Ikfpuz6pET94i_1whyphenhyphenkjGLicaJFCLPw_YtxGg-BRImBw1aHKxdUak/s1600/d3.txt.png)

There's a general circular relationship between functions and prototype
objects as we'll soon see.


## Function function
Since `Object` is a function, what is `Function`?

```JavaScript
typeof(Function); // is also a function
```

Actually, `Function` is very much like `Object` with a
circular relationship:

```JavaScript
Function.prototype.constructor === Function; // true
```

But what is `Function.prototype`?

```JavaScript
typeof(Function.prototype); // is a function
```

So there's a general circular relationship between functions and prototype objects as well:

![Circular relationship between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuPF29bpW2vp-gRCzPr42gT1c4CLaGu6uJCdv_FjqK6nbOUC2JqeVCeU7pxNOiUr8NnFBNGtNuJ8C8yHXvM3JnvzIC8hHsPjjU1M77zAjvML5AehBC0IQnsq_tNkpwrf8yAo445j8rOgQ/s1600/d4.txt.png)


## How do Function and Object relate?
Well we already know `Object` and `Function` are both functions.
Now observe where they proto-inherit from:

```JavaScript
Object.__proto__ === Function.prototype; // true
Function.__proto__ === Function.prototype; // true
```

Wasn't `Function.prototype` a function as well? Yes and no...

```JavaScript
typeof(Function.prototype); // recall that's a function
Function.prototype.__proto__ === Object.prototype; // true
```

![Circular relationship between fn Object and Object.prototype, and between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJhd17gDojdt-labL0wFRS4dTscyh6miYnTm0Ah8QFjNVEXmX-sB6pR-s5D40GI461_K9LvvIfZLbvWWyZDagKJrEfXwgAICl60XxcNyfXuMQU3iBux1BmkV49shIPFfd2f32QByp1DB4/s1600/d5.txt.png)

So the buck stops at `Object.prototype`, and `Function.prototype` is
a function but proto-inherits from `Object.prototype`.

`Object` and `Function` are both more straightforward:
both are functions and proto-inherits from `Function.prototype`.


## Literal objects and functions
Consider the following literal object and function:

```JavaScript
var x = {};
typeof(x); // is an object

var f = function(){};
typeof(f); // is a function
```

So what do they proto-inherit from?

```JavaScript
x.__proto__ === Object.prototype; // true
f.__proto__ === Function.prototype; // true
```

...they proto-inherit not from `Object` or `Function`, but from
`Object.prototype` or `Function.prototype`.

Remember the general circular relationship between functions and 
prototype objects? Well `x` is an object, so I suspect we won't
find it related circularly with its prototype object (if it has one)...

```JavaScript
x.prototype === undefined; // true
```

But `f` is a function, so let's see if it has a circular relationship
with its prototype object...

```JavaScript
typeof(f.prototype); // is an object
f.prototype.__proto__ === Object.prototype; // true
f.prototype.prototype === undefined; // true
f.prototype.constructor === f; // true, truly circular!
```

Thus we see the following relationship `x`, `f`, and the existing circular relationships between `Object`, `Function`, and their prototypes:

![Relationship between Object, Function, their prototypes, and object x and function f](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOr45lN9l-LPz9AMjmRLVkvxpfMP54xceqL9mpX7iQwbF-K-haYIV9IZVl5gLH1SjTIr1_iFyhLa39IsuCj0bjOGSVNOa_5DGRf5pNso4fjARMw1TVSCBsHcZ-Q2H_xiggqf3r9fD6Tcw/s1600/d6.txt.png)


## Let's start writing some "classes"
The goal here is to end up with a "super class" called `SuperKlass`, which will have as a "subclass" the class `Klass`.

```JavaScript
var SuperKlass = function(){}; // a constructor for our super "class".
typeof(SuperKlass.prototype); // is an object.

SuperKlass.__proto__ === Function.prototype; // true
SuperKlass.prototype.__proto__ === Object.prototype; // true

SuperKlass.prototype.constructor === SuperKlass; // true
```

So merely writing a function creates a circular relationship between
a function and an object:

![Relationship between Function.prototype and SuperKlass, and Object.prototype and SuperKlass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgT-GnQ0tXAQtfJOJ02r0Frb7m4lDKOOERu4z07wB4yUbkKL_-yizcD7uQmiPA5tGKiiC6MqJyfn3RawR2hkcFBEgKBRO_PnnjsyGXTo2Orw9V8x3I9VB_ywZ18BRr05pBxX01uA3RmUA/s1600/d7.txt.png)

We'll abbreviate our diagram of the `Function.prototype` and
`Object.prototype` objects.


```JavaScript
var Klass = function(){}; // a constructor for another "class"
```

As with the `SuperKlass` case above, we get this circular relationship:

![Relationship between Function.prototype and Klass, and Object.prototype and Klass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaQWqkD5vVpxmcuwgb_doNxXVcMqTpgnXapMgzO_jGH23z9klsJGGJt1l2sbeJNSeA_SPuDf1BR-EOFuyaaUfcHdoVjatBa9J-8yA6IEiYOFdyWfm-NyF1_93Op3q_eOyQ0kWtkqejt0M/s1600/d8.txt.png)

`Klass` and `SuperKlass` don't look like classes, but they would if we started writing some methods for them.  But we'll hold of on that until we get some class-based inheritance going on first as those two are currently unrelated to each other.


## Proto-inherit our way to writing "subclasses"
The above don't look like classes yet, but they will once
we make `Klass` inherit from `SuperKlass`.

```JavaScript
var oldKlassProto = Klass.prototype; // for later testing

Klass.prototype = Object.create(SuperKlass.prototype);

Klass.prototype === oldKlassProto; // false. It's really a new object!

Klass.prototype.__proto__ === SuperKlass.prototype; // true
Klass.prototype.constructor === SuperKlass; // true
```

The `Object.create` line of code basically did the following:
create a new object `o` that proto-inherits
from `SuperKlass.prototype`, then set `o.constructor` to
the `constructor` of `SuperKlass.prototype`, which is of course
just `SuperKlass` because of the circular relationship we saw above!

Then we set `Klass.prototype` to `o` resulting in
this relationship:

![Relationship between Klass, Klass.prototype, SuperKlass, SuperKlass.prototype, and Object and Function prototypes, after using Object.create.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqAQynhPfRyI9oNlAydARZg9KKtMl8YHVsoShd7rg0xgmW-1BltlZFFlFd80PHe7MWcQzV6DcuT6RD_W_3UwANabRmeBX2clW-6MUeOc-GPi9Z5wGO2euu0F9ZuCV5a6-qMzhhR95aTMo/s1600/d9.txt.png)

Notice the `Klass.prototype.constructor` no longer points back to
`Klass`, breaking the circular relationship between constructor functions
and prototypes we kept seeing above.  Let's repair that...


```JavaScript
Klass.prototype.constructor = Klass;
```

![Relationship after repairing Klass.prototype.constructor to point to Klass](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwx_vHpDKSwHatiEbKbPKT2ZDJQfz640hWDn9YX1Yb5BndPDqGa2W958oH5CA4rbcoB6cOtzImFMChc704YmcaqqORmBPlnU6sK0EiRi0B00Mpjh36KjCcOdPywCZ2tM3RbzrfXdrftkQ/s1600/d10.txt.png)

Now `Klass` is a subclass inheriting from `SuperKlass` --- inheriting,
not proto-inheriting.


## Instance method for our Klass and some new objects
Let's dynamically create a `SuperKlass` instance method:

```JavaScript
SuperKlass.prototype.hi = function(){return "super!"};
```

Notice where the method is created in the diagram and how it relates to `SuperKlass`, and `Klass`:

![Relationship after dynamically patching in a "hi" method in SuperKlass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHAC3o2Katyy0MTOTeJXbp6JgtpON3wX3TJVYOc4MJ4Y3aEyau-7NghFiMpNy4nLQoPIXovxvPEZdBwsZUeJi8iW2fuhxduqNX4WFNa1msdLPVwMd3EgukzouQs4kCsphAW7RFHdeqZeM/s1600/d11.txt.png)

We keep making classes but never instance objects constructed
from those classes, so let's do that now:

```JavaScript
var sk = new SuperKlass();
var k = new Klass();

sk.prototype === undefined; // true
k.prototype === undefined; // true. They really are just objects

sk.__proto__ === SuperKlass.prototype; // true
k.__proto__ === Klass.prototype; // true
```

So `new F()` just makes a fresh object that proto-inherits from
`F.prototype`.  In fact, it also runs the `F()` constructor function
on that fresh object so to initialize it by doing whatever `F` does.

![Relationship between k and Klass, and sk and SuperKlass.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieQZxagZ6zrIBovw4Sg5SE99IrwehtpIKv-M9g4A8Yl4FNXmo3UJV-xRLtweAOCy42N0jgRDycjGULR8bv1G_aKc9EI_GFJcfj5WQPdwd7UnA0Y-_0sKy4TcZZ_u4iEGJzGq0Gzg5oyGM/s1600/d12.txt.png)

## Polymorphism
"Polymorphism" here just means, if an object `k` has it, use it,
otherwise repeat looking for it with the object that `k` 
proto-inherits from (done recursively, again and again...).

```JavaScript
sk.hi(); // "super!"
```
...note that `sk` itself doesn't have a method `hi()`,
but `sk.__proto__` (a.k.a. `SuperKlass.prototype`) has it!

```JavaScript
k.hi(); // "super!" - polymorphic call to inherited method
```

`k` itself doesn't have `hi()`, but in this case,
`k.__proto__` (a.k.a. `Klass.prototype`) doesn't have it either!
But `k.__proto__.__proto__`  (a.k.a. `SuperKlass.prototype`)
does have it!

In effect we've got, in Java terms, an instance method `hi()`
defined in the `SuperKlass` class, and `Klass` inherits it being
a subclass.  So `k` is like an instance of the class `Klass`,
and `sk` is like an instance of the class `SuperKlass`...
even though JavaScript has no native concept of class or
class-based inheritance (not until ES6 anyway).

Let's write more methods, this time dynamically adding the `hi` method to `Klass.prototype`:

```JavaScript
Klass.prototype.hi = function(){return "klass!"};
```

Notice how this `hi` method relates to the `Klass.prototype` object, "overriding" the one proto-inherited from `SuperKlass.prototype`:

![Relationship after dynamically patching in a "hi" method in Klass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiy61cgwO1v0tFIozlgQBaIW_ybFwdD-8kbDrerlsiCoTW5qgnyufyGaA7MMP2Cy6iWO6VthZlGtATpBe8dh1suG8jBsDf28I0lLnkyxb1f2YQnjbG9krKX8JrcvBQ2TscU21-bXugfpkg/s1600/d13.txt.png)

```JavaScript
sk.hi(); // "super!"
k.hi(); // "klass!" - polymorphic call to overriding method
```

...of course `k` itself doesn't have a method `hi()`,
but `k.__proto__` (a.k.a. `Klass.prototype`) this time does!

Although JavaScript has no native concept of class or class-based 
inheritance (not until ES6), it kind of half-heartedly does since
ES3 (JavaScript 1.4) via the `instanceof` operator which basically
just checks to see if a function's `prototype` is proto-inherited by,
or is proto-inherited proto-inherited by, or is proto-inherited 
proto-inherited proto-inherited by, ..., the given object.

```JavaScript
sk instanceof Klass; // false
sk instanceof SuperKlass; // true
```

The last line evaluates to `true` because `sk` proto-inherits from `SuperKlass.prototype`

```JavaScript
k instanceof Klass; // true
k instanceof SuperKlass; // also true!
```

The last line *also* evaluates to `true` because `k` proto-inherits proto-inherits `SuperKlass.prototype`

Just follow the proto-inheritance hierarchy!


## this and super
Let's write another subclass.

```JavaScript
var Klass2 = function(nm){
    // super(); in Java terms
    SuperKlass.call(this); // call superclass's constructor
                           // with `this` object
    this.name = nm;
};
Klass2.prototype = Object.create(SuperKlass.prototype);
Klass2.prototype.constructor = Klass2;

// Klass2 inherits from SuperKlass via usual proto-inheritance hierarchy:
Klass2.prototype.__proto__ === SuperKlass.prototype; // true


// make a `Klass2` instance
var k2 = new Klass2("Pat");
k2.hi(); // "super!" - polymorphic call to inherited method


// define a `Klass2` instance method
Klass2.prototype.hi = function(){return this.name};

sk.hi(); // "super!"
k.hi(); // "klass!"
k2.hi(); // "Pat"
```

More or less, `this` refers to the object the method is called on, but technically
it gets tricky as JavaScript's concept of a method is really in terms of functions
that are stored as properties on objects.  For details, see [MDN's JavaScript reference of this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).

Notice the dynamicism of JavaScript, where we added a new instance method to an existing class, and all existing instance objects of that class got to use the newly defined instance method.  No recompilation needed, unlike e.g. Java.

## References
It was noted that `__proto__` is deprecated.  It was a way of exposing to 
us the internal linkages between JavaScript's internal representation of 
objects.  The "proper" way now is through using the `getPrototypeOf` method.
See [MDN's reference on Object.prototype.\_\_proto\_\_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto).

A more in-depth explanation of JavaScript OOP can be found at MDN's 
reference on [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) or at [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript).

A hugely more in-depth explanation with beautiful diagrams is available at
[JavaScript: the core](http://dmitrysoshnikov.com/ecmascript/javascript-the-core).
Incidentally, had I found that article first, I might never have written
this one...

...because I wrote this to help myself understand JavaScript's prototypal OOP system
by drawing diagrams and playing around with JavaScript in the Firefox Console.
Conceptually, it was so simple, but then when you actually program with it,
or when you try to use it in a more class-based manner, it can get confusing.

All diagrams originally drawn with [ASCII Flow](http://asciiflow.com).  Diagrams turned into pretty PNG images using [Shaape](https://github.com/christiangoltz/shaape).

2012-08-27

OpenShift My Python Django Project

Red Hat's OpenShift platform-as-a-service is easy to set up and start using if you have a Python Django project (I haven't tried the other platforms supported, e.g. Java).  It's just 9 (longish) steps!

The django-example they offer gives a good idea of what the completed Django on OpenShift project should look like, but I thought I'd jot some notes down on how to get there from an existing Django project on Ubuntu Linux.

There are two main parts to this process, (A) OpenShift Tools Set-up, and (B) Set-up Python Django Project for OpenShift.


(A) OpenShift Tools Set-up
 
(0) Go to OpenShift and sign up for an account.

(1) Install the rhc client tool on your local computer.
 There's some instructions provided, but it boils down to running on your command line:

$ sudo apt-get install ruby-full rubygems git-core
$ sudo gem install rhc
$ rhc  #this should now run without errors

(2)  Setup your computer to connect to the OpenShift servers.
This should be easy. Just do on the command line: rhc setup and follow the on-screen instructions.

That should really be all it takes, but note that that will upload your default public encryption key for your computer to OpenShift, namely: ~/.ssh/id_rsa.pub so you should know the password to that key pair or else you won't be able to connect to OpenShift.

If you don't want to use your default key, or some other reason, you can always create a new public/private encryption key pair and upload that (just delete the default one from OpenShift, which you can do through their web interface or on the command line).  I'll describe that next.

2012-05-28

CSS Relative Positioning and Collapsing DIV

The HTML/CSS pattern of nesting a floating div element in a div element can cause the problem of collapsing the parent div element, and the child div doesn't position as expected (i.e., relative to the parent div).

Namely, this doesn't work as expected:
<div class="parent" style="margin: auto; width: 50%;">
  <div class="child" style="float: left; left: 1em; top: 1em; width: 50%;">
  Hi!
  </div>
</div>

First problem, the parent div collapses to zero height.  There are two solutions:

1) Apply the overflow: auto style to the parent div, but this can sometimes introduce scroll bars with the nested div moves "outside" the "normal" area of the parent div.

2) Add a "clearing" empty div element.  This is more predictable, I've found, but introduces a semantically meaningless element.  E.g.:
<div class="parent" style="margin: auto; width: 50%;">
  <div class="child" style="float: left; left: 1em; top: 1em; width: 50%;">
   Hi!
  </div>
  <div class="clearing" style="clear: both; height: 1px; overflow: none;">
  </div>
</div>
The extra styles besides clear: both in the clearing div is for compatibility with old Internet Explorer 6 browsers.

Second problem, the child div is floating left, but it doesn't get nudged down and to the right by 1em each way (via setting top and left).  The solution is to set the child to have the CSS style position: relative, namely as this:
<div class="parent" style="margin: auto; width: 50%;">
  <div class="child" style="position: relative; float: left; left: 1em; top: 1em; width: 50%;">
   Hi!
  </div>
  <div class="clearing" style="clear: both; height: 1px; overflow: none;">
  </div>
</div>

It's also possible to set the child div to have position: absolute (and not floated) but it will be placed absolutely relative to the window's upper-left corner.  To make it relative to the parent div, set the parent div to have position: relative as well, as follows:
<div class="parent" style="position: relative; margin: auto; width: 50%;">
  <div class="child" style="position: absolute; left: 1em; top: 1em; width: 50%;">
   Hi!
  </div>
  <div class="clearing" style="clear: both; height: 1px; overflow: none;">
  </div>
</div>

2012-01-01

Web Mobile App Development Tools and Libraries

Here's some tools and libraries that look interesting for web development, mobile App development, etc.

To begin, Firefox and Chrome, of course, are the browsers of choice for a web developer.

Tools for Firefox

Firefox has tons of tools for web developers! Take special note of:
  1. Firebug,
  2. Console²,
  3. DOM Inspector,
  4. FoxGuide,
  5. HTML Validator,
  6. JSView,
  7. LiveReload,
  8. PageSpeed,
  9. Phoenix,
  10. SQLite Manager,
  11. Web Developer.
  12. ColorZilla

If using Firebug, then also take special note of Acebug, FireRainbow.

Tools for Chrome

Chrome is younger and has less tools, but many web developers prefer Chrome over Firefox.  And there are definitely tools:
  1. Google Chrome Developer Tools
  2. Web Developer
  3. Firebug Lite
  4. Validity
  5. ColorZilla 
  6. Color Generator
  7. Eye Dropper

JavaScript Validator

When programming in JavaScript, you must use JSLint to validate that the JavaScript you wrote conforms to modern recommended idioms.

You can run JSLint on the command line locally if the JSLint program is set up correctly based on the JSLint source files. But then a JavaScript interpreter outside of the browser is required, such as node.js, Rhino, or spidermonkey.  Another, more convenient, possibility is to use the jslint4java wrapper program.


Libraries

dust.js has been selected by LinkedIn recently as their templating engine to unify the way web pages designed in HTML and CSS gets filled with data generated by other server based programs written in various languages including Java, Grails, and JRuby.  It is free and open source (looks like MIT license)

PhoneGap is a free and open source (Apache License) library for writing cross-mobile-platform HTML5 app to access technologies native to the mobile platform (vs. programs being stuck in the browser).

For building gesture/touch-enabled UI for cross-mobile-platform Apps, there is jQuery Mobile, which is a very young project still, and is free and open source: dual licensed under MIT and GPL2.  There is also Sencha Touch, a more mature library that is free and open source, cross-licensed under GPL3, a modified GPL3, a free (as in beer) commercial software license, and a paid commercial OEM license.

You might also need a library to add MVC or MVVM structure to your App.  For that, consider Backbone.js (MVC) or Knockout.js (MVVM).

For everything else, there's jQuery.

See also:
  1. Building Large-Scale jQuery Applications
  2. Tools For jQuery Application Architecture – The Printable Chart

2011-12-31

Resources for Learning Web Development (JavaScript, jQuery)

Assuming you have some working knowledge of HTML and CSS, then learning to program behaviours into web pages requires learning JavaScript, and here's resources I've looked into to help you learn JavaScript programming:

eBooks and paper Books
By "books", I mean "Bound Optimally Organized Knowledge". It's organized for structured learning and completeness.

Books I've looked into (literally) and would give at least a 4 out of 5 stars for:
Books that look promising based on the "cover" only:
  1. jQuery Fundamentals
  2. Web Development Recipes 
  3. Eloquent JavaScript: A Modern Introduction to Programming
  4. MDN: JavaScript Guide
Interactive Tutorials
Tutorials are organized for structured learning, often in a hands-on manner, but usually leaves gaps in knowledge.  Interactive tutorials have a turn-based prompting mechanics to it.

2011-12-30

Transferring a Canadian domain to Namecheap from Go Daddy for a Blogger custom domain

There's been a lot of recent news about Go Daddy's missteps in terms of the SOPA legislation in the USA.  I'm in Canada, but I can't help but also notice the Go Daddy business and political policies aren't terribly aligned with the business and political policies of my business practice.  Plus Go Daddy's services are focused on the up-sell than actually servicing my business needs, so I decided to transfer my domains from Go Daddy to Namecheap.

Here's the short of how I transferred the domain of this blog from Go Daddy to Namecheap, and how I had to reset things for Blogger custom domain to continue to work.

Note that doing this will cause a bit of down time for your domain name!