Friday, July 24, 2015

Draw a plain text spiral in Scala

Here is the code:

import{File, PrintWriter}

object Element {
  private class ArrayElement(
                              val contents: Array[String]
                              ) extends Element
  private class LineElement(s: String) extends Element {
    val contents = Array(s)
  private class UniformElement(
                                ch: Char,
                                override val width: Int,
                                override val height: Int
                                ) extends Element {
    private val line = ch.toString * width
    def contents = Array.fill(height)(line)
  def elem(contents: Array[String]): Element = {
    new ArrayElement(contents)
  def elem(s: String): Element = {
    new ArrayElement(Array(s))
  def elem(chr: Char, width: Int, height: Int): Element = {
    new UniformElement(chr, width, height)

import Element.elem

abstract class Element {
  // contents to be implemented
  def contents: Array[String]

  def width: Int = contents(0).length

  def height: Int = contents.length

  def above(that: Element): Element = {
    val this1 = this widen that.width
    val that1 = that widen this.width
    elem(this1.contents ++ that1.contents)

  def beside(that: Element): Element = {
    val this1 = this heighten that.height
    val that1 = that heighten this.height
      for ((line1, line2) <- this1.contents zip that1.contents)
        yield line1 + line2

  def heighten(h: Int): Element = {
    if (h <= height) this
    else {
      val top = elem(' ', width, (h - height) / 2)
      val bottom = elem(' ', width, h - height - top.height)
      top above this above bottom

  def widen(w: Int): Element = {
    if (w <= width) this
    else {
      val left = elem(' ', (w - width) / 2, height)
      val right = elem(' ', w - width - left.width, height)
      left beside this beside right

  override def toString = contents mkString "\n"

object Spiral {
  val space = elem(" ")
  val corner = elem("+")
  def spiral(nEdges: Int, direction: Int): Element = {
    if(nEdges == 1) elem("+")
    else {
      val sp = spiral(nEdges - 1, (direction + 3) % 4) // or (direction - 1) % 4, but we don't want negative numbers
      def verticalBar = elem('|', 1, sp.height)
      def horizontalBar = elem('-', sp.width, 1)
      if(direction == 0)
        (corner beside horizontalBar) above (sp beside space)
      else if(direction == 1)
        (sp above space) beside (corner above verticalBar)
      else if(direction == 2)
        (space beside sp) above (horizontalBar beside corner)
        (verticalBar above corner) beside (space above sp)
  def draw(n: Int): Unit = {
    println(spiral(n, 0))

Test it:

| +--+ 
| |  | 
| ++ | 
|    | 

The crital part here is the recursive way of thinking:

I want to draw a 7-node spiral. What should I do if I already have a 6-node spiral?

Thursday, July 16, 2015

Things to do after a fresh Ubuntu install

Some libs that you need to install for R to work properly on a Ubuntu machine:

sudo apt-get install libcurl4-openssl-dev libxml2 

To keep R up-to-date, edit /etc/apt/sources.list and add the line:

deb vivid/

Change vivid to your Ubuntu version, of course. You can also use a different mirror site.

Set up Java:

sudo add-apt-repository ppa:webupd8team/java -y
sudo apt-get update
sudo apt-get install oracle-java8-installer
sudo apt-get install oracle-java8-set-default

Configure Java with R:

sudo R CMD javareconf

GPG guide from leiningen (but is generally applicable)

Using GPG

This is an introduction to setting up and using
GPG keys with
Leiningen to sign artifacts for publication to
Clojars and to encrypt repository credentials.

There are two versions of GPG available: v1.x and v2.x. For our
purposes, they are functionally equivalent. Package managers generally
install v2.x as gpg2, and v1.x as gpg. By default, Leiningen
expects the GPG command to be gpg. You’re welcome to use any version
you like, but this primer will only cover installing v1.x, and has
only been tested under v1.x.

What is it?

GPG (or Gnu Privacy Guard) is a set of tools
for cryptographic key creation/management and encryption/signing of
data. If you are unfamiliar with the concepts of public key
cryptography, this
Wikipedia entry
serves as a good introduction.

An important concept to understand in public key cryptography is that
you are really dealing with two keys (a keypair): one public, the
other private (or secret). The public key can be freely shared, and is
used by yourself and others to encrypt data that only you, as the
holder of the private key, can decrypt. It can also be used to verify
the signature of a file, confirming that the file was signed by the
holder of the private key, and the contents of the file have not been
altered since it was signed. **You should guard your private key
and passphrase closely, and share them with no one.**

Installing GPG


Debian based distributions

Apt uses GPG v1, so it should already be installed. If not:

apt-get install gnupg

Fedora based distributions

Fedora and friends may have GPG v2 installed by default, but GPG v1 is
available via:

yum install gnupg


There are several options here, depending on which package manager you
have installed (if any):

  1. via homebrew: brew install gnupg
  2. via macports: port install gnupg
  3. via a binary installer
    (this installs gpg2 as gpg)


GPG4Win provides a binary installer that
provides some possibly useful GUI tools in addition to providing the
gpg command.

Creating a keypair

Create a keypair with:

gpg --gen-key

This will prompt you for details about the keypair to be generated,
and store the resulting keypair in ~/.gnupg/.

The default key type (RSA and RSA) is fine for our purposes, as is the
default keysize (2048). We recommend a validity period of 2 years.

You’ll be prompted for a passphrase to protect your private key - it’s
important to use a strong one to help protect the integrity of your key.

Listing keys

GPG stores keys in a keystore located in ~/.gnupg/. This keystore
holds your keypair(s), along with any other public keys you have used.

To list all of the public keys in your keystore:

gpg --list-keys

This will include any public keys you have used, including keys from
others (if you’ve never used GPG before and just created your first
keypair, you should just see your own key).

The output of the --list-keys option will include the id of your
public key in the ‘pub’ line in the key listing (you’ll need that id
for other commands described here):

$ gpg --list-keys

pub   2048R/2ADFB13E 2013-03-16 [expires: 2014-03-16]
uid                  Bob Bobson <>
sub   2048R/8D2344D0 2013-03-16 [expires: 2014-03-16]

The --fingerprint option will act just like --list-keys, but will
include the fingerprint of each certificate in the output. You can
filter the output of the --fingerprint option by providing a key id
or any substring from the uid (this trick also works for the
--list-keys option):

$ gpg --fingerprint 2ADFB13E

pub   2048R/2ADFB13E 2013-03-16 [expires: 2014-03-16]
      Key fingerprint = 3367 5FD0 D67B 3218 5815  51A3 97D4 06D0 2ADF B13E
uid                  Bob Bobson <>
sub   2048R/8D2344D0 2013-03-16 [expires: 2014-03-16]

Publishing your public key

To make it easier for others that need your public key to find it,
you can publish it to a key server with:

gpg --send-keys 2ADFB13E # use your id instead

This pushes a copy of your public key to one of a cluster of free key
servers, and the key is propagated to all of the other servers in the
cluster in short order.

If your keypair is compromised, you can publish a revocation
certificate to the key server to let others know that your key can no
longer be trusted for any future signing or encryption. It’s a good
idea to generate a revocation certificate whenever you create a new
keypair, and store it in a safe place. As long as you have that
revocation certificate, you can revoke a keypair even if you no longer
have the private key. You can generate a revocation certificate with:

$ gpg --output 2ADFB13E-revoke.asc --gen-revoke 2ADFB13E

Be sure to protect your revocation certificate carefully - anyone who
gains access to it can use it to revoke your keypair. The GPG
maintainers recommend printing it out and storing the hardcopy in a
safe place.

To revoke your certificate when the time comes (not now!), do the

$ gpg --import 2ADFB13E-revoke.asc  # ONLY WHEN YOU NEED TO REVOKE
$ gpg --send-keys 2ADFB13E          # ONLY WHEN YOU NEED TO REVOKE

How Leiningen uses GPG

Leiningen uses GPG for three things: decrypting credential files,
signing release artifacts, and signing tags. We’ll focus on artifact
signing here; for information on credentials encryption/decryption,
see the
deploy guide. Once
you are configured to sign releases, signing tags should be

On some systems you will be prompted for your GPG passphrase when it
is needed if you haven’t entered it. If yours does not, you can
install Keychain, which provides
this functionality portably.

Signing a file

When you deploy a non-SNAPSHOT artifact via the deploy
task, Leiningen will attempt to create GPG signatures of the jar and
pom files. It does so by shelling out to gpg and using your default
private key to sign each artifact. This will create a signature file
for each artifact named by appending .asc to the artifact name.

Both signatures are then uploaded along with the artifacts. If you’re
deploying to Clojars, you’ll want to provide it with your public key
(see below) in order that the signatures can be verified.

To disable signing of releases, set :sign-releases to false in the
:repositories entry you are targeting. If you do this, everyone who
is depending on your library will not be able to confirm that the copy
they get has not been tampered with, so this is not recommended.

Overriding the gpg defaults

By default, Leiningen will try to call GPG as gpg, which assumes
that gpg is in your path, and your GPG binary is actually called
gpg. If either of those are false, you can override the command
Leiningen uses for GPG by setting the LEIN_GPG environment variable.

GPG by default will select the first private key it finds (which will
be the first key listed by gpg --list-secret-keys). If you have
multiple keys and want to sign with one other than first, or want to
use specific keys for a particular release repository, you can specify
which key to use either globally, per-project, or
per-deploy-repository. All three places use the same configuration
syntax, it’s all about where you put it. You can specify the key by id
or by the uid.

To set a key globally, add it to your user profile in

{:user {...
        :signing {:gpg-key "2ADFB13E"}}} ;; using the key id

To set a key for a particular project, add it to the project

(defproject ham-biscuit "0.1.0"
   :signing {:gpg-key ""} ;; using the key uid

To set a key for a particular deploy repository, add it to the
repository specification in your project definition:

(defproject ham-biscuit "0.1.0"
     [["releases" {:url ""
                   :signing {:gpg-key "2ADFB13E"}}]
     ["snapshots" ""]]


Clojars requires that artifacts be signed and verified before being
promoted to the
repository. In order to verify the signature, it needs a copy of your
public key. To view your public key, use gpg --export -a giving it
the key id. Example:

$ gpg --export -a 2ADFB13E
Version: GnuPG v1.4.11 (GNU/Linux)


Copy the entire output (including the BEGIN and END lines), and paste
it into the ‘PGP public key’ field of your Clojars profile.

lein deploy clojars vs. scp

Currently, publishing signatures to Clojars only works if you are
using lein deploy clojars. If you are using scp to deploy, you can
copy signatures along with the artifacts, but they will be



Unable to get GPG installed via Homebrew and OSX Keychain to work

Installing GPG from here instead:

GPG doesn’t ask for a passphrase

Make sure that you have “use-agent” option explicitly enabled in ~/.gnupg/gpg.conf. See gpg option list.

You can test the config with

gpg --quiet --batch --decrypt ~/.lein/credentials.clj.gpg

Leiningen should pick it up automatically when the command above works correctly.

GPG prompts for passphrase but does not work with Leiningen

gpg --quiet --batch --decrypt ~/.lein/credentials.clj.gpg

It’s hanging for a while after executing lein repl and then prints out these messages:

$ lein repl
Could not decrypt credentials from /Users/xxx/.lein/credentials.clj.gpg
pinentry-curses: no LC_CTYPE known - assuming UTF-8
pinentry-curses: no LC_CTYPE known - assuming UTF-8
pinentry-curses: no LC_CTYPE known - assuming UTF-8
pinentry-curses: no LC_CTYPE known - assuming UTF-8
pinentry-curses: no LC_CTYPE known - assuming UTF-8
gpg-agent[1009]: command get_passphrase failed: Invalid IPC response
gpg: problem with the agent: Invalid IPC response
gpg: decryption failed: No secret key

Leiningen can’t present enter-passphrase page of gpg. It’s an issue with Leiningen or gpg2 or gpg-agent or pinentry.

Use the GUI version of gpg, GPG Suite. Now when executing ‘lein repl’, it prompts for passphrase on the GUI instead.

Saturday, July 4, 2015

Thoughts on definition of e

From Stewart’s calculus textbook:

is the number such that

From there we can deduct another well-know fact:

If we let , then

when is large.

Inverse function and rotation matrix

To understand why graphs of inverse functions are symmetric about the line, try see this from a different point of view: symmetry about is equivalent to symmetry about the x-axis if you rotate the points by , right?

Let’s verify it. Given one arbitrary point in function (mapping) , then is in . Rotate both points by , we have:

Go ahead and see that and differ only in the sign of their x-coordinates!


Welcome to StackEdit!

Hey! I’m your first Markdown document in StackEdit1. Don’t delete me, I’m very helpful! I can be recovered anyway in the Utils tab of the Settings dialog.


StackEdit stores your documents in your browser, which means all your documents are automatically saved locally and are accessible offline!


  • StackEdit is accessible offline after the application has been loaded for the first time.
  • Your local documents are not shared between different browsers or computers.
  • Clearing your browser’s data may delete all your local documents! Make sure your documents are synchronized with Google Drive or Dropbox (check out the Synchronization section).

Create a document

The document panel is accessible using the button in the navigation bar. You can create a new document by clicking New document in the document panel.

Switch to another document

All your local documents are listed in the document panel. You can switch from one to another by clicking a document in the list or you can toggle documents using Ctrl+[ and Ctrl+].

Rename a document

You can rename the current document by clicking the document title in the navigation bar.

Delete a document

You can delete the current document by clicking Delete document in the document panel.

Export a document

You can save the current document to a file by clicking Export to disk from the menu panel.

Tip: Check out the Publish a document section for a description of the different output formats.


StackEdit can be combined with Google Drive and Dropbox to have your documents saved in the Cloud. The synchronization mechanism takes care of uploading your modifications or downloading the latest version of your documents.


  • Full access to Google Drive or Dropbox is required to be able to import any document in StackEdit. Permission restrictions can be configured in the settings.
  • Imported documents are downloaded in your browser and are not transmitted to a server.
  • If you experience problems saving your documents on Google Drive, check and optionally disable browser extensions, such as Disconnect.

Open a document

You can open a document from Google Drive or the Dropbox by opening the Synchronize sub-menu and by clicking Open from…. Once opened, any modification in your document will be automatically synchronized with the file in your Google Drive / Dropbox account.

Save a document

You can save any document by opening the Synchronize sub-menu and by clicking Save on…. Even if your document is already synchronized with Google Drive or Dropbox, you can export it to a another location. StackEdit can synchronize one document with multiple locations and accounts.

Synchronize a document

Once your document is linked to a Google Drive or a Dropbox file, StackEdit will periodically (every 3 minutes) synchronize it by downloading/uploading any modification. A merge will be performed if necessary and conflicts will be detected.

If you just have modified your document and you want to force the synchronization, click the button in the navigation bar.

Note: The button is disabled when you have no document to synchronize.

Manage document synchronization

Since one document can be synchronized with multiple locations, you can list and manage synchronized locations by clicking Manage synchronization in the Synchronize sub-menu. This will let you remove synchronization locations that are associated to your document.

Note: If you delete the file from Google Drive or from Dropbox, the document will no longer be synchronized with that location.


Once you are happy with your document, you can publish it on different websites directly from StackEdit. As for now, StackEdit can publish on Blogger, Dropbox, Gist, GitHub, Google Drive, Tumblr, WordPress and on any SSH server.

Publish a document

You can publish your document by opening the Publish sub-menu and by choosing a website. In the dialog box, you can choose the publication format:

  • Markdown, to publish the Markdown text on a website that can interpret it (GitHub for instance),
  • HTML, to publish the document converted into HTML (on a blog for example),
  • Template, to have a full control of the output.

Note: The default template is a simple webpage wrapping your document in HTML format. You can customize it in the Advanced tab of the Settings dialog.

Update a publication

After publishing, StackEdit will keep your document linked to that publication which makes it easy for you to update it. Once you have modified your document and you want to update your publication, click on the button in the navigation bar.

Note: The button is disabled when your document has not been published yet.

Manage document publication

Since one document can be published on multiple locations, you can list and manage publish locations by clicking Manage publication in the menu panel. This will let you remove publication locations that are associated to your document.

Note: If the file has been removed from the website or the blog, the document will no longer be published on that location.

Markdown Extra

StackEdit supports Markdown Extra, which extends Markdown syntax with some nice features.

Tip: You can disable any Markdown Extra feature in the Extensions tab of the Settings dialog.

Note: You can find more information about Markdown syntax here and Markdown Extra extension here.


Markdown Extra has a special syntax for tables:

Item Value
Computer $1600
Phone $12
Pipe $1

You can specify column alignment with one or two colons:

Item Value Qty
Computer $1600 5
Phone $12 12
Pipe $1 234

Definition Lists

Markdown Extra has a special syntax for definition lists too:

Term 1
Term 2
Definition A
Definition B
Term 3

Definition C

Definition D

part of definition D

Fenced code blocks

GitHub’s fenced code blocks are also supported with Highlight.js syntax highlighting:

// Foo
var bar = 0;

Tip: To use Prettify instead of Highlight.js, just configure the Markdown Extra extension in the Settings dialog.

Note: You can find more information:

  • about Prettify syntax highlighting here,
  • about Highlight.js syntax highlighting here.


You can create footnotes like this2.


SmartyPants converts ASCII punctuation characters into “smart” typographic punctuation HTML entities. For example:

Single backticks 'Isn't this fun?' ‘Isn’t this fun?’
Quotes "Isn't this fun?" “Isn’t this fun?”
Dashes -- is en-dash, --- is em-dash – is en-dash, — is em-dash

Table of contents

You can insert a table of contents using the marker [TOC]:


You can render LaTeX mathematical expressions using MathJax, as on

The Gamma function satisfying is via the Euler integral

Tip: To make sure mathematical expressions are rendered properly on your website, include MathJax into your template:

<script type="text/javascript" src=""></script>

Note: You can find more information about LaTeX mathematical expressions here.

UML diagrams

You can also render sequence diagrams like this:

Created with Raphaël 2.1.2AliceAliceBobBobHello Bob, how are you?Bob thinksI am good thanks!

And flow charts like this:

Created with Raphaël 2.1.2StartMy OperationYes or No?Endyesno

Note: You can find more information:

  • about Sequence diagrams syntax here,
  • about Flow charts syntax here.

Support StackEdit

  1. StackEdit is a full-featured, open-source Markdown editor based on PageDown, the Markdown library used by Stack Overflow and the other Stack Exchange sites.
  2. Here is the text of the footnote.