Wednesday, November 2, 2016

BitBucket Git checkout over SSH with multiple accounts

If you have multiple user accounts at BitBucket (e.g. personal and work), you may run into a problem. The first think you will notice that you could not use the same ssh key. Adding it to the second account will give you "the key is already used by someone else" error message. Now if you generate a new key and add it to your ssh-agent (via ssh-add), you will not be able to check out from one of your accounts.

The problem is caused by ButBucket identifying a user by first SSH key he or she supplies. There are several workarounds for this problem, but the one I prefer is to use ssh Host alias. In your ~/.ssh/config file add section like this:
Host bitbucket-cm
    User git
    IdentityFile ~/.ssh/id_rsa.1
    IdentitiesOnly yes
This would basically create a SSH host alias bitbucket-cm for associated with id_rsa.1 key. Now, instead of usual checkout URL, say, 
git clone 
git clone git@bitbucket-cm:org/repo.git

Wednesday, July 13, 2016

Pokemon Go circa 2012

Looking at current Pokemon Go success (It added whopping $9B to company's capitalization) I could not help help looking back at another project we did few years ago.

Back in 2012 we, at Codeminders, were working on Computer Vision algorithms for mobile phones. At some point we realized that there is a potential for a business there and developed a demo and even pitched to some angel investors. The investors told us that the gaming aspect is not interesting, and we should focus on some real-life problems like real estate, etc. Eventually we just published a technology demo in app store and let it go.

To demonstrate location-based augmented reality gaming we have chosen Pikachu avatar which you can place at random locations, where your friends can find it. The unique part was that it worked indoors, not relying on GPS alone.

Here is an image from our investor's pitch:

You can see our presentation here (I've removed some boring slides related to financials and planning). Also you can try yourself our demo (Android version, iOS version). In the demo we replaced Pikachu with Squirrel to avoid infringing on Nintendo's trademarks.

Saturday, February 6, 2016

State Monad in Coq Tutorial

In this post we will review usage of StateMonad in Coq using ExtLib on an adapted example from  a Haskell State Monad tutorial.

We will implement a simple game function which takes a string from dictionary {a,b,c} and produces a score number. The game could have two modes: on and off. It consumes an input string character by character and updates the mode and the score at each step. Initially the mode is off. The character 'c' toggles the on/off mode flag. In off mode, consuming characters does not affect the score. In on mode, each occurrence of the character 'a' increases the score by 1, and each occurrence of the character 'b' decreases it by 1. So for example, the input sequence "ab" will result in a score of 0, "ca" a score of 1, "cabca" also a 0, and "abcaaacbbcabbab" will result in a score of 2.

Let us look the implementation of this game in Coq using State Monad:

1 Require Import Coq.ZArith.ZArith_base Coq.Strings.String.
2 Require Import ExtLib.Data.Monads.StateMonad ExtLib.Structures.Monads.
4 Section StateGame.
5   Import MonadNotation.
6   Local Open Scope Z_scope.
7   Local Open Scope char_scope.
8   Local Open Scope monad_scope.
10   Definition GameValue : Type := Z.
11   Definition GameState : Type := (prod bool Z).
13   Variable m : Type → Type.
14   Context {Monad_m: Monad m}.
15   Context {State_m: MonadState GameState m}.
17   Fixpoint playGame (s: string): m GameValue :=
18     match s with
19     |  EmptyString =>
20        v <- get ;;
21          let '(on, score) := v in ret score
22     |  String x xs =>
23        v <- get ;;
24          let '(on, score) := v in
25          match x, on with
26          | "a", true =>  put (on, score + 1)
27          | "b", true => put (on, score - 1)
28          | "c", _ =>   put (negb on, score)
29          |  _, _  =>    put (on, score)
30          end ;; playGame xs
31     end.
33   Definition startState: GameState := (false, 0).
34 End StateGame.
36 Definition main : GameValue :=
37   (evalState  
38            (playGame (state GameState) "abcaaacbbcabbab") startState).

I will omit description of the Coq nuts and bolts of Require, Import, and Open Scope instructions in lines 1-8.

In lines 10 and 11, we declare type aliases for our game score value as a signed integer (Z), and game state as a product of the boolean game mode and and an integer game score.

Variable 'm' in line 13 identifies our Monad by it's type constructor. Line 14 states that 'm' must be an instance of type class Monad. If we look at ExtLib's definition of this type class we will see that it just postulates the presence of the standard Monad bind and return (called ret here) functions:

Class Monad (m : Type → Type) : Type := { 
    ret : ∀ {t}, t → m t ;
    bind : ∀ {t u}, m t → (t → m u) → m u

The next class, mentioned in line 15 brings additional get and put definitions, specific for State Monad:

Class MonadState (T : Type) (m : Type → Type) : Type := {
    get : m T ;
    put : T → m unit

The actual game function definition begins on line 17. It is a recursive function consuming an input string and returning a monadic value as a result. The string is an inductive type and we match its two constructors on lines 19 and 22, respectively. If the string is empty, we use syntax x <- c1 ;; c2 which is a Coq's rendering of well a known do-notation. Informally: we extract a score element from the current state tuple and return it as a monadic value using ret. While in Haskell, we can write a much terser expression (_, score) <- get, in Coq we have to use an intermediate value 'v' followed by destructive let, which unfortunately does not allow us to use a wildcard for the first element (mode), which we do not need anyway.

In the case of the second constructor on line 22 we again use do-notation and destructing let to break down the current state into on and score components and then analyze their combinations via match. Again, we use slightly different syntax from Haskell's version and, instead of matching on x with guards, we match on both x and on. Depending on their combination, we update the score and on/off flag according to our game rules using the state monad's put function. Then, we proceed with the next recursive iteration chained by c1 ;; c2 notation which is sometimes called then operator (>>) in Haskell, and used to to chain monadic computations where c2 does not depend on the outcome of c1. This could be expanded into our familiar do-notation of:  _ <- c1 ;; c2.

On line 33, we define our initial game state (game off, score=0) as startState.

On line 36, we define our 'main' function, which runs a game for a specific string and returns an integer score. It is a bit difficult to parse, so for clarity let us split it into several definitions, specifying return types and making all arguments explicit via '@':

Definition m : Type → Type := state GameState.
Definition pg :  state GameState GameValue := @playGame m _  _ "abcaaacbbcabbab".
Definition main : GameValue := @evalState GameState GameValue pg startState.

The first definition 'm' uses the state record type to create our State Monad's constructor. It is defined as:

state: Type → Type → Type
Record state (S t : Type) : Type := mkState { runState : S → t * S }

We partially specialize state with GameState, which gives us a new type constructor (Type → Type), which instantiates a type which holds a function with a type GameState -> t * GameState.

Th next definition 'pg' holds a monadic value returned as a result of running our game. You may notice that its type is state GameState GameValue which is the same as m GameValue, the type of  playGame. Please note that playGame was defined inside a section. Consequently, when seen outside one, it is additionally universally quantified with all section variables. In our case playGame now takes 4 arguments. The first is a type constructor for the monad, the second is the type class instance Monad m that carries the monad functions, the third is the type class instance MonadState GameState m that carries the monad state functions, and the fourth is the string input to the function. We explicitly provide 'm' but use wildcards for type class parameters, letting the type class resolution mechanism find instances for parameters marked as _ . Coq will look for a type class instance of Monad (state GameState) and MonadState (state GameState). Both of these are defined as Global Instances in the ExtLib.Data.Monads.StateMonad library so type class resolution finds the definitions. Thus, after class resolution, the 'pg' definition will expand to:

(@playGame (state GameState) (Monad_state GameState)
     (MonadState_state GameState) "abcaaacbbcabbab"

Finally in the 'main' definition, we use the evalState function to get our result. It is defined as:

Definition evalState {t} (c : state t) (s : S) : t :=
    fst (runState c s).

The semantics are pretty straightforward; we apply State Monad to the initial state (run state transition function), and project out the first element of the returned tuple (the score).

To test our implementation we can use Compute main instruction to get the expected result (2).

P.S. I would like to thank Gregory Malecha for the explanations, comments, and suggestions he provided.

Thursday, February 4, 2016

Auqamacs, Proof General and company-coq

If you are using Coq under Emacs, you are most likely using Proof General (note the new link, they moved to github recently). If you are not using excellent CompanyCoq extension to PG by Clément Pit--Claudel, you certainly should! (I was wondering for a while why it is named "company". The answer is that it is based on eponymous text completion framework for Emacs. The name stands for "complete anything".)

Aquamacs is a version of Emacs popular among MacOS X users. Unfortunately some key binding from company-coq do not work under it. Specifically control-mouse-1 which should show an overlay popup with information about a clicked symbol. There is a ticket open and there is a helpful discussion with developers but it looks like we could not make it work as on other platforms. There is a workaround described below, but I am not sure if it is going to make it to official release. If it does not or until it does here is what you can do. Add the following to your .emacs:

(add-hook 'coq-mode-hook
          (lambda ()
            (company-coq-initialize) ;; Load company-coq when opening Coq files
            (if (boundp 'aquamacs-version)
                  (define-key company-coq-map (kbd "<c-down-mouse-3>") #'company-coq-show-definition-overlay-under-pointer)
                  (define-key company-coq-map (kbd "<c-mouse-3>") #'company-coq-clear-definition-overlay)))))

The difference from other emacsen is that you need to use control-right-mouse-click. On MacBook's touchpad it means holding Control button while clicking on touchpad with two fingers. If you are using Apple Magic Mouse, click with one finger, but on the right side of the mouse. Finally if you are using 3-button USB mouse, you should click on right button, although I have not tested this.

Sunday, October 25, 2015

Augmented reality whiteboard

I often do remote video meetings which require writing and discussing math: formulae and plots. I've tested couple virtual whiteboard software applications but they are inconvenient and require using tablets of writing with your mouse. I ended up pointing my camera to a regular whiteboard during the meeting and photographing and emailing content as meeting minutes. Obviously there are more sophisticated solutions like these which cost thousands of dollars. The main problem with such solutions is that you have 2 whiteboards instead of one. Both parties do not draw on the same surface, but each draws on it's own. You could not correct or modify other person's writing. Even more expensive solutions like this, replace whiteboard with huge touchscreen TV solve this problem.

I thought that that this problem could be elegantly solved by augmented reality using Google or Oculus Rift VR glasses. Your correspondent's drawing is virtually projected on your whiteboard and yours is projected on his. While each whiteboard only has physical drawing from one of you, when you look at it through the glasses you see both whiteboard contents superimposed on top of each other. This should work with regular $40 whiteboard and crayons or even with a piece of paper. The solution is very portable. All you need is to carry your glasses and you can project a piece of paper from your hotel room.

Monday, September 21, 2015

ranting on Android Permissions

I have a bunch of applications installed on my Android phone. Most of them are frequently updated by developers. If the update does not require any new permissions it is installed automatically. So one could expect that after some time my app eco system will “settle” and most of the apps will be updated automatically. Unfortunately this is not what happening. Pretty much every other day I have to go into update manager and approve new updates granting additional permissions. 

From that one can conjecture that the apps tend to steadily expand their permissions “footprint”. I guess that makes sense, as new functionality require additional permissions. That would be OK, if Android permission system would not be fundamentally crippled. By that I mean their “all or nothing” permission model. User can either grant all the permissions an app requests or not to use this app at all. For example if some app requires access to my SMS messages for non-essential feature which I would never  use anyway, there is no way for me to refuse it to read my messages but still use the app. There are some indications that Android 6.0 “Marshmallow” will finally allow users to grant individual permissions to the app. Until then millions of users mindlessly keep pressing OK granting unnecessary permissions.

Sunday, July 12, 2015

Pebble Chaser watch face concept

Back in 2014 I wrote:

"When things get virtual we usually start by mimicking familiar physical world. We have mailbox, folder and envelope icons, "old phone" ringtones, and lot of other UI metaphors inspired by things now obsolete. Nothing wrong with that, as long as by doing this we do not limit our creativity. Take a look at this picture of Pebble watch:

In pebble argot this is called "watchface." This is a particularly popular one and there are dozens of variations of it in the Pebble store. The problem shown is that sometimes date "window" (at least this is what it is called on mechanical watches) is obstructed by watch hands and you could not tell the date. There is nothing you can do about it in old style mechanical watch, but on Pebble you can, for example, move the date window position around to make it always visible."

I was really missing this feature and finally took matters in my own hands and implemented this idea:

You can install it following this Pebble App Store Link. You are welcome to fork the github project and improve.