Category: code

Fixing Amazon’s Kindle Previewer in El Capitan

For some reason getting Amazon’s Kindle Previewer to work on El Capitan is not an easy task. There are a few resources online that pointed in the right direction but didn’t fully solve the problem for me. Here is what worked for me, extracted from the Amazon forums‎.

Amazon Kindle Previewer

1. Install X11 and Java for OSX

Downloads:

2. Open the Launcher shell script with a text editor

The Launcher file is located in /Applications/Kindle Previewer.app/Contents/MacOS/Launcher.

Go to Finder → Applications → Kindle Previewer.app, right click the file, Show package contents → Contents → MacOS → Launcher, right click the file, Open with → other, choose TextEdit or your favorite text editor.

3. Edit the Launcher file

First add the following line below #!/bin/sh:

export JAVA_HOME="/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home"

Then replace the two occurrences of java -d32 with ${JAVA_HOME}/bin/java -d32.

The new file should look like this:

#!/bin/sh
export JAVA_HOME="/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home"

dir=`dirname "$0"`
cd "$dir"
classpath=./:./lib/touchLibs/etc/fonts/fonts

for i in `ls ./lib`
do
    classpath=$classpath:./lib/$i
done

export DYLD_LIBRARY_PATH=.

# start the previewer
fileExtT=`echo $1 | awk -F. '{print $NF}'`
fileExt=`echo $fileExtT | tr '[:upper:]' '[:lower:]'`

if [ "$fileExt" == mobi -o "$fileExt" == azw3 -o "$fileExt" == epub -o "$fileExt" == opf -o  "$fileExt" == html -o  "$fileExt" == zip ]
then
    # opens only the first book in command line.  TODO: handle multiple books in command line
    ${JAVA_HOME}/bin/java -d32 -XstartOnFirstThread -Dfile.encoding=UTF-8 -cp "${classpath}" com.amazon.epub.reader.Main "$1"
    exit 1
else
    ${JAVA_HOME}/bin/java -d32 -XstartOnFirstThread -Dfile.encoding=UTF-8 -cp "${classpath}" com.amazon.epub.reader.Main
    exit 1
fi

4. Save the changes

You are done.

If you still run into issues it could be that a java process or a previous Kindle Previewer process is still running in the background and preventing the changes from taking effect. Kill the zombie processes (in the terminal or restarting your computer), and things should work now.

Good luck!

Top 10 Features of Swift Language Syntax for JavaScript Developers

Swift is Apple’s new language for Cocoa and Cocoa Touch, created as an evolution of Objective-C and intended for native OS X and iOS development.

Reading Swift’s new documentation I found a few of its features very interesting. Some of these new features are typical of other high performing languages such as C, Java, etc. Long time ago I used to code in C and C++ and now, years later, I still miss some of the more advanced language syntax in Javascript. Although some go as far as saying that “Swift is basically JavaScript on steroids”, the two have different goals (web vs. native).

Apple Swift Logo

#1. Constants

Such a simple thing and such a great help. I’ve always missed constants in JavaScript. A variable is declared with the keyword var a const with let.

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

Note: All the code samples have been extracted from the docs.

Read the official documentation about Constants

#2. Strong Type

Some people attribute some of the success of JavaScript to loose typing. Although it gives the language an incredible flexibility it also makes it harder to debug and more prone to runtime errors.

In Swift you can indicate the expected value type that a variable is to store as follows

var welcomeMessage: String

Swift is type safe, which means that it will always enforce the right type to be used in expressions. If the wrong type is passed in an assignment or feature call, compilation will fail.

Type declaration is not mandatory and so Swift uses type inference to determine the type of variables if not specified during creation. This is done by examining the values provided in code.

Read the official documentation about Type Safety and Type Inference

#3. Tuples

A tuple is a type that groups multiple values into a single compound value. It is a short way to express complex structures without defining an object.

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")

Very convenient as the return value of functions. (self link ####)

Read the official documentation about Tuples

#4. Range operator

The range operator is a shorthand way to define a range of values. It comes in two flavors closed and half-closed.

The closed range operator includes all the values in the expression. In the example below values 1, 2, 3, 4 and 5.

for index in 1...5 {
    println("(index) times 5 is (index * 5)")
}

The half-closed range omits the last value (very useful when iterating over arrays or lists).

let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..count {
    println("Person (i + 1) is called (names[i])")
}

Read the official documentation about the Range Operator

#5 The (supercharged) Switch Operator

Compared with JS, Swift’s switch operator is really powerful control flow operator. I’ve never been a fan of the switch command, but I could grow to like it in Switch.

Since Swift has tuples and ranges, the case expression of a switch command can be more elaborate and more useful. Swift also includes new concepts to control the flow such as the fallthrough keyword, value bindings and the where clause.

Range matching case: A case clause can match a range of values, not just a single value.

let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}
println("There are (naturalCount) (countedThings).")
// prints "There are millions and millions of stars in the Milky Way.”

Tuples matching case: values can be tested against tuples

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    println("(0, 0) is at the origin")
case (_, 0):
    println("((somePoint.0), 0) is on the x-axis")
case (0, _):
    println("(0, (somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
    println("((somePoint.0), (somePoint.1)) is inside the box")
default:
    println("((somePoint.0), (somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box”

Read the official documentation about the Switch Operator

#6. (Advanced) Function syntax

The regular syntax of a function is Swift is slightly different from JavaScript in order to accommodate for the parameter and return type definition.

func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
}

CoffeeScript guys might like the use of the ->, and might find it more familiar than regular JS folks, specially when dealing with Swift’s closure syntax.

Besides the new syntax, the most powerful new features of functions in Swift are multiple return values, external parameter names & Variadic Parameters.

#6.1. Multiple Return Values

A function in swift can return a complex value as a tuple type.

func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
    var vowels = 0, consonants = 0, others = 0
    for character in string {
        switch String(character).lowercaseString {
        case "a", "e", "i", "o", "u":
            ++vowels
        case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
        "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
            ++consonants
        default:
            ++others
        }
    }
    return (vowels, consonants, others)
}

#6.2 External Parameter Names

Functions in Swift can expose the name of each parameter to use when calling the function. This helps readability by indicating the purpose of each argument and reduces errors.

func someFunction(externalParameterName localParameterName: Int) {
    // function body goes here, and can use localParameterName
    // to refer to the argument value for that parameter
}

#6.3 Variadic Parameters

A feature of crazy name (at least to my Spanish ears), used to indicate that a parameter can accept zero or more values of certain type.

func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)

Read the official documentation about Functions

#7 Enumeration type

It’s such as a small thing but, just like constants, it can make your code so much more clean, readable and less error prone.

enum Planet {
    case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

Read the official documentation about Enumerations

#8 Classes and structures (aka Object Oriented Programming)

Native support for classes.

class SomeClass {
    // class definition goes here
    var width = 0
}

OOP is simple but powerful and with classes come all sort of good things:

  • Inheritance
  • Getters and setters
  • Property Observers
  • Native self property
  • Type (aka static) methods
  • etc, etc

Read the official documentation about Classes and Structures

#9 Automatic Reference Counting (aka Smart memory management)

One of the great features of Swift that many developers of Objective-C are anticipating. Here’s the description directly from Apple’s documentation:

Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.

Read the official documentation about Automatic Reference Counting

#10 Generics

Not present in JavaScript but popular in C++. Generics are functions and complex types that don’t require an explicit specific type (Int, String, etc) but instead work with any type indicated at creation.

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

Mostly used for collection classes (Array and Dictionary types are actually generic collections in Swift).

Read the official documentation about Generics

In closing

Swift lies somewhere between Objective-C and JavaScript. Should be much easier to pick up for those JavaScript developers itching to learn development in the Apple ecosystem.

Maybe it’s time to try some native coding?

For more goodness on Swift & JS you can check out Swift for JavaScript developers.

Underscores in Apple’s Swift Numbers

I’m catching up with Apple’s new language Swift, and this declaration of numbers caught my attention: in order to help readability numerals can be written with underscores (eg: 12_345).

Apple Swift Logo

Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeroes and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal:

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Excerpt From: “The Swift Programming Language.”.

I also just learned that this feature is already present in some languages such as Perl, Ruby and Java but not in Javascript 🙁

I like the idea of not only creating new languages, but rethinking how we write code and how we can improve the coder experience (after UX, we now need a new field of CX).

Javascript Module Pattern: A Detailed Deconstruction

The term module is a convention used in Javascript to group code that’s conceptually coherent. The Module Pattern is a programming design pattern that uses modules as the basic construct for organizing code.

Javascript Module Pattern by omarrr

Wikipedia defines Modular Programming as follows

[…] a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

The basic module

The absolute most basic Javascript module is actually a Javascript object

var Module = {
    foo: 'hello world'
}

By itself this doesn’t seem like a very useful pattern but just by grouping under this object all variables needed we can get a great replacement for global variables

var Module = {
    foo: 'hello world',
    bar: 12345,
    baz: ["John", "Joe", "Josh"],
    qux: {x: 100, y: 300}
}

The Object-Module Pattern

Javascript object keys can hold functions also, which means that this simple module is a quick way to package our code consisting of both variables and functions.

var Module = {
    foo: 1,

    bar: function() {
        console.log(foo); // ReferenceError: foo is not defined
        console.log(this.foo); // 1
        console.log(Module.foo); //1
    }
};

Public access

Variables defined as in the example above are public and can be access directly

Module.foo = 3;
Module.bar();

Within the module’s bar the value of this equals Module, which means that the following two lines are equivalent when used inside bar

console.log(this.foo);
console.log(Module.foo);

Trying to access foo without the this qualifier or the namespace Module will throw a Reference error since there is no foo global variable defined.

Dynamic content

Modules allow for new variables to be added on the fly. This code is ok even if we’ve never declared the qux member before.

Module.qux = 2;

This simple module pattern is more a Javascript code grouping technique. It is the most basic example of Javascript namespacing and a good replacement for using any global variable. You should always be able to replace all your global variables and functions for this code:

var MyNamespace = {};

MyNamespace.qux = "my new namespaced var (aka global)"

Full Example

Here’s a complete example of this Module Type:

var Module = {
    foo: 1,

    bar: function() {
        console.log(this); // ok! (=Module)
        console.log(++this.foo); // ok!
        console.log(++Module.foo); // ok!
    }
};

// Public access
console.log(++Module.foo); // ok!
Module.bar();

// Allows for new variables to be added on the fly
Module.qux = 2;

The Functional-Module Pattern

The Functional-Module Pattern is very similar to the Object-Module described above, but instead of creating an object directly through the object notation, we create it as a result of executing a function.

Compare

var Module1 = {
    foo: 10,
    bar: function(){ alert("hi");}
}

with

var Module2 = (function(){
    return { 
        foo: 10,
        bar: function(){ alert("hi");}
    };
}());

both Module1 and Module2 define an identical object, but utilizing the second syntax we can take advantage of closures.

The Closure-Module Pattern

A Closure is a function, plus the environment (or scope) it was declared in. Only functions, created inside functions are closures, and they can make our objects a tad more powerful and a lot more secure by:

  • Data encapsulation: providing private member fields and methods
  • Persistence of local scope: allowing public and private methods access to a private scope unique to the Module at hand

Implementing Private Members

In the example below the variable _foo can be considered as a private member:

var Module = (function(){
    var _foo = 20;
    return { 
        bar: function(){ alert("hi");}
    };
}());

_foo is inaccessible to external code and so this code will return ‘undefined’

console.log(Module._foo); // undefined

(By the way, naming private variables starting with _ is a good common practice to easily differentiate between public and private variables and functions).

Taking advantage of the local scope

bar in the example above, however, is truly private and could be used with in the public (and private) functions declared inside Module. See the example below:

var Module = (function(){
    var _foo = 20;
    return { 
        bar: function(){ console.log(_foo);}
    };
}());

Calling the public method bar of Module will output the value of _foo, however trying to access the value directly from outside of Module will now work

Module.bar(); // 20
console.log(Module._foo); // undefined

We have effectively created a private variable that’s inaccessible to code outside of Module that can be used by internal functions for keeping the local state.

Closures are great when writing APIs and code to be used by other developers while keeping the integrity of the API itself.

Dynamic Members

The Module Pattern permits us to have, not only public and private members, but also dynamic variables and functions. Since the returned Module is a regular Javascript object we can extend it as we would normally do in Javascript

Module.qux = 20;
Module.qux = function(){ console.log(this.qux); };

The —so called— Constructor

So up until now I’ve used this format of the Module pattern:

var Module = (function(){
    var _foo = 0;

    return {
        bar: 1,
    }
}());

I personally find that using a more explicit format makes it more clear to read and understand. Here:

var Module = (function(){
    var _foo = 0;

    var self = {
        bar: 1,
    }

    return self;
}());

In this case it is clear that the value of Module is the object selfreturned by the function. This is informally called the constructor of the Module.

Even better, this exact same thing can be expressed as:

var Module = (function(){
    var _foo = 0;

    var self = {};

    self.bar = 1;

    return self;
}());

I like this last representation best since it consists mostly of regular Javascript functional expressions (vs. object notation).

Self-referencing

Using this —so called— constructor syntax gives us a way to reference the module itself from within the module’s private member functions. Without a variable self a private method would have no means to call a public variable or function.

Self-referencing varies depending on the scope of the caller and the callee. What this means is that in order to call a function of a module we must understand the scope of the function that’s calling and the function that’s being called, since there are rules for each.

Private access within a Module

Accessing private members can be done directly without any qualifier from private or public functions. Dynamic functions can’t access private members.

var Module = (function(){
    var _foo = 10;
    var _bar = function (){ console.log(_foo)};

    var self = {
        baz: function (){ console.log(_foo)};
    }

    return self;
}());

Public access within Module

Accessing public members from within private or public functions can be done using the self variable. Additionally public functions can also access public members via ‘this’ keyword.

var Module = (function(){
    var _foo = function (){ console.log(self.bar)};

    var self = {
        bar: 1,
        baz: function (){ console.log(self.bar)}; // this works
        qux: function (){ console.log(this.bar)}; // this works too
    }

    return self;
}());

Access from within dynamic members

Dynamic functions must always use the keyword this to access public and other dynamic members. This is one of the awesome things about Javascript closures. Since the dynamic functions were not in the same scope as the Module itself when created, they don’t have access to private methods (not even self). That means that developers can’t use dynamic members to get around the private scope limitations.

var Module = (function(){
    var _foo = 10;

    var self = {
        bar: 20,
    }

    return self;
}());

Module.qux = (function(){ 
    console.log(this._foo); // undefined
    console.log(this.bar); // 20
});

Summary

There are several ways to express the Module patter and all of them are equivalent. In any case taking advantage of closures will make modules that much more powerful.

Closure-based Pattern

This is the minimum expression of the Module Pattern. I personally like this syntax best, since I believe it offers best readability:

var m = (function(){
    var _foo = "I'm private";

    var self = {};

    self.bar = "I'm public";

    return self;
}());

A complete example: All put together

Here’s a complete example that shows public and private variables and functions.

var Module = (function(){
    // private variables
    var _v1 = 10;

    // private methods
    var _f1 = function(){ 
        console.log(_v1);
        console.log(self.v2);
        console.log(self.v3);
    };

    // constructor
    var self = {};

    // public variables
    self.v2 = 20;

    // public functions
    self.f2 = function(){
        console.log(_v1);
        console.log(self.v2);
        console.log(self.v3);
    };

    return self;
}());

// Dynamic Members
Module.v3 = 30;
Module.f3 = function(){ 
    console.log(this.v2); 
    console.log(this.v3); 
};

// Usage
console.log(Module.v2);
Module.f2();
console.log(Module.v3);
Module.f3();

References

5 Easy Steps to Archive a Github Repo on Bitbucket

So I love Github. I use it for personal projects and for work. I’m happy to pay for the service but I find myself constantly running out of space because of old private repos. Most of the time these finished (or abandoned) projects are not worth keeping around. Bitbucket offers free unlimited private repos, so using it for archiving projects seems like a great option.

Here’s the easy guide to archiving (or moving) a project from Github to Bitbucket.

Archive a Github Repo on Bitbucket by omarrr

1. Import the Github repository to Bitbucket

Probably the easiest part. Bitbucket has implemented a flawless Import your GitHub repositories feature. Authenticate with Github and you are done (Bitbucket will send out an email once the import is complete). If your project was private in Github it’ll still be private once it gets ported to Bitbucket.

2. Add the new Bitbucket remote on your local machine

This will allow you to use bitbucket as another remote should you want to continue doing development.

git remote add bitbucket <https://omarrr@bitbucket.org/omarrr/PROJECT>

Check your setup to make sure all is good.

git remote -v

    bitbucket   https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    bitbucket   https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)
    origin  git@github.com:omarrr/PROJECT.git (fetch)
    origin  git@github.com:omarrr/PROJECT.git (push)

3. Setup the new origin repo

If you are going to delete the repo from Github and —potentially— start using Bitbuket instead, you’ll want to setup origin to point to the new Bitbucket remote instead of Github. We do this so that we can keep working with the new repo as if it was the old one by pushinng and pulling to Bitbucket as the default remote.

git remote rename origin github
git remote rename bitbucket origin

Again, check that everything is good

git remote -v

    github  git@github.com:omarrr/PROJECT.git (fetch)
    github  git@github.com:omarrr/PROJECT.git (push)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)

4. Done!

Since your project is safe in Bitbucket now, you can delete it from Github. You can see below how to.

4.1. Create a backup or clone (Optional)

Clone your repo to retrieve a copy of the full history of your project with all branches, tags, etc.

git clone <https://omarrr@bitbucket.org/omarrr/PROJECT>

Generate a ZIP

tar -cf <PROJECT>.ZIP <PROJECT/>

Delete the clone

rm -rf <PROJECT>

4.2 Delete the project from Github (Optional)

It’ll be a good idea to confirm that Bitbucket has been properly setup and/or create a clone of the repo (see above) before proceeding (just saying).

Go to the “Danger Zone™” in the project settings page on Github (eg: https://github.com/omarrr/PROJECT/settings) and click “Delete this Repository”.

Finally remove the remote from your local machine

git remote rm github

Once more, check that everything is good

git remote -v

    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (fetch)
    origin  https://omarrr@bitbucket.org/omarrr/PROJECT.git (push)    

5. Done!

No, really. We are done now.