December 14, 2010

Winows vs. Linux

When you interact with Windows, your peers sitting near turn their heads from screen showing that they respect your privacy.

When you working with Linux your peers is all into console expecting you to share with them.


November 25, 2010

Garbage Collector

One existential part of Network Operation System (NOS) is [distributed] memory manager a.k.a. Garbage Collector. If we think about (G)lobality of GC , and continuations of task mapping to nodes, and also habits of NOS users we can expect that GC will can guided  by Celestial mechanics (Internet works this way).


Idea is to trigger Processor level GC by daylight line. 

Let first mark-and-sweep happened in Tokyo when Sun risen up. Guys coming to local Stock Exchange will push some analytic to NOS for processing. Then NOS will try to distribute algorithm to data locations in US and Russia where lots of idle nodes at night time.

Then it is Beijing turn to sweep their nodes and so on around.




November 17, 2010

GREP evolution

$ grep -r `some
^C
Why doesn't it find `some in files recursively?  Is it example of bad user inteface?

In fact it is not that ad-hock as it seems. One just need bit of UNIX cultural background to come to it logically.

Fact one is that grep is in fact  g/re/p (go with regexp and print) command in VI editor. It's command line version  have to be lifted over list of files and when mapped over directory tree have to use  "find . | xargs grep `some" instead. Eventually somebody made it script - rgrep.sh and other guy integrate it to grep as -r option.

find . -| xargs vi -e g/some/p 



November 8, 2010

Node.js - Node.os

Hi,


Node.js is just `processor and any `job can be `assigned to it. JavaScript is `system language for defining certain `computation and executing it as `job. Job 's has to be `synchronized over nodes to produce result of computation.

This is, basically, definition of NETWORKING OS, where:


  • Processor - node capable of executing Job.
  • Job - scheduled unit of computation.
  • System language - describes computation in terms of OS primitives, primitive computations and data-flows.
  • Synchronization - suppose tasks {A, B}, with I(nput) and O(utput). 


Possible synchronizations are:
1)
AO -> BI (A-Out implies B-Input) - This is PIPE like synchronization for sequence of tasks.

The OS primitive for it (see Algebra of Communicating Processes) is '.' - B.A - B after A.

Going further we can introduce `+' - choice and `|' - interleaving.

Execution of jobs in MapReduce process synchronized on inputs and intermediate outputs on node level and cluster level.

(AI -> BI -> ... -> ZI) - This synchronization characterize Map phase, which also taking on Reduce of outputs: (AO -> BO -> ... -> ZO).

Those definitions calls for POSIX like specification which may serve as solid base for 'Services (aka SaaS) design.


November 5, 2010

Continuous Integration UNIX way

Hi, there was a time I couldn't write SHELL scripts. For example, once I had to confirm 1000+ file deletion by pressing 'y'. Now I would do > yes | rm /1000/1/night/* ..., but then I used screwdriver, sticking it in between Y and H.



Personally, I can't imagine any development setup on UNIX without Emacs. Probably, VI would do but it's internal language far inferior to emacs-lisp.

So, here we go again - my desktop, that did not change for 3+ month...



It Emacs on the left and something what missing from Emacs functionality on the right (otherwise it wouldn't be there:)).

While developing significant piece of software we often feel insecure. It's especially true for dynamic languages which gives no guaranty of any kind about runtime (they are too rock-n-roll IMO, some type inference wouldn't harm).
To leverage this feeling we adding amount of bravado into SW life-circle with Maven, Hudson, Agile and Continuous Integration/Deployment. It helps, but seems like overkill for me and while this Zen can be practical in corporate aquarium (because they have office plankton there) it is not for individual projects (when no Zen/Lean master around). 

Here is my receipt for better sleep while still have fun with big amount of code. 

REM We would need nothing but linux-base to organize relevant TDD/CI environment for development with JavaScript.


For Integration Test I would recommend JsTestDriver from Google. It is quite sane piece of software with sound integration test-strategy.
We need to start server, register target browser's as test slave and trigger tests on repository when ready.

Those bits of manual labor can be automated with Bash script.

run_jsTestDrive.sh
# test-runner Continuous Integration style 

java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.2.jar --port 4224 --captureConsole &

PID=$!

trap "{ echo 'Exiting'; echo $PID;  kill $PID ; exit 0; }" SIGINT SIGTERM

sleep 3

while true;
do
      sleep 2

      java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.2.2.jar --tests all | \
      tee >({ \
      grep -q -s 'Total.*Fails: 0; Errors: 0'; \
     
      if [ $? -eq 0 ]; then \
          echo -e "\e[1;32m Tests successful - Fails: 0; Errors: 0  \e[0m"; \
      else \
          echo -e "\e[1;31m Tests failed. \e[0m"; \
      fi \
      })

      inotifywait -e modify *.js

done


It will start (and kill) server for us. It will look on disk for changing files and fire tests if any.

NB. It's very important that all your test have colored diagnostic. It doesn't meter what it says but it must be GREEN or RED for your peripheral vision to pick up it easily.

Tests failed. vs. Tests successful - Fails: 0; Errors: 0 

Also colors are big importance because TDD process based on REFACTOR-GREEN-COMMIT cycle, and 'green means tested.

There is some mambo-jumbo in the script which does coloring with terminal control sequences.

File changes picked up by kernel inode supervisor using user land utility $ inotifywait -e modify *.js



For Unitary Test I had to write small piece.

There about dozen well written xTest frameworks but I wanted to keep same test database for `unitary and for `integration. While we already fixed CI framework to js-test-driver, its TestCase format have to be reused with new unitary TestRunner.

TestCase("js-test-unit", {
        
        setUp: function() {
            jstestunit.testCaseManager =
                new jstestunit.TestCaseManager();
            
            jstestunit.testCaseBuilder =
                new jstestunit.TestCaseBuilder(jstestunit.testCaseManager);
            
            jstestunit.testRunner =
                new jstestunit.TestRunner();
        },
        tearDown: function(){
            delete jstestunit.testCaseManager;
            delete jstestunit.testCaseBuilder;
            delete jstestunit.testRunner;
        },
        
        "test configuration exist": function(){
            
            assertEquals('object', typeof jstestunit.config);
            assertEquals('object', typeof jstestunit.testCaseManager);
            assertEquals('object', typeof jstestunit.testCaseBuilder);
            assertEquals('object', typeof jstestunit.testRunner);

        },
 });

Sources is in the repo on BitBucket: $ hg clone https://lib.aca55a@bitbucket.org/lib.aca55a/js-test-unit

This TestRunner is HTML infected and have to run directly inside Browser. To integrate it with Emacs we would need another module - MozRepl. This one is hooked directly in Gecko engine of FF and shows on localhost:4242. On Emacs side it is just sock to REPL.  From the MozRepl you can `BrowserReload() effectively re-executing all your tests.

Again we can automate stuff in emacs-lisp this time.

;; M-x moz-reload-mode 
(define-minor-mode moz-reload-mode
  "Moz Reload Minor Mode"
  nil " Reload" nil
  (if moz-reload-mode
      ;; Edit hook buffer-locally.
      (add-hook 'after-save-hook 'moz-reload nil t)
    (remove-hook 'after-save-hook 'moz-reload t)))

(defun moz-reload ()
    (moz-firefox-reload))

(defun moz-firefox-reload ()
  (comint-send-string (inferior-moz-process) "BrowserReload();"))


This setup did not add functionality. You REPL code normal way, occasionally saving files. But general feeling is like you hawing angel on right shoulder singing `Don't worry, be happy... .

Demon on left knows real state of affairs, and this what happens when you connection human to machine - you have to leverage fear.

1 Fr - define fear between zero and 1.0 software, when constant being-in-the-flow of 1 challenge applied to coding, produces a function of 1 hack, the programmer not being a seat of any interruptive force. 

Few tips in the end.

  • It is true that Emacs is best in the business but it is also true that it is hard to get on this 50+ year marked. I'm there today thanks to unknown-somebody who's config I `borrowed some years ago. Still use it - $ hg clone https://lib.aca55a@bitbucket.org/lib.aca55a/env . It is easy to discover key-binding in emacs-keys.el and module settings in emacs-packages.el for starter.
  • It is important to get right setup for you language. Examples of `right are:
  • There are integrated solution which easier to work with, but keep keep in mind that they raise fear to totally new level.
P.S. My testing harness runs outside of Emacs and when some error are in the report I have to communicate manually to editor. Still some automation goes in:
while read f; do emacsclient -n `echo $f|sed 's/\([^:]*\):\(.*\):.*/+\2 \1/'`; done


November 2, 2010

Inheritance models.

Hi, Here I keen to describe only practical models.


There is general properties of model which measures amount of information we can capture using this model.

Let say we describe some particular system using set of properties. Arrangements of properties constrained by inheritance model that we choose.

Models differ by redundancy it require (encapsulation vs. delegation) and reuse it provides (inheritance vs. inclusion).

Numerically we can capture redundancy by combinatory complexity but reuse can only feet in functor which doesn't have something like adjustency degree (? or does it).


Lets us look for model in the field of `modern` programming  languages.

Java diagonal inheritance model



There is two parallel hierarchies: one for interfaces and one for Implementation. Final class ready to produce system object (object which describe system we model) when it derived from proper implementation of interfaces exposed by our system.


Interfaces diagonal is redundant, it just a shadow of Implementation, has no properties and do nothing.
Implementation can be reused along Impl diagonal. Suppose we have 3 class diagonal and each class add one unique property. Model that can be build from it is power set of properties:

P {a, b, c} = {{}, {a}, {b}, {c}, {a,b}, {b,c}, {a,c}, {a,b,c}}

If no overwriting on parameters assumed, the only interesting model is complete diagonal - {a,b,c}.





C++ diamond inheritance model.


C++ employs virtual derivation schema when subtypes keeps parental properties or override them. This model can scale in any direction and is famous for its tendency for over-design.

Diamond models are domain specific and used mostly by frameworks.  No reuse achieved ever.

Previous (Diagonal) model scaling linearly from number of properties. But on diamond we can do permutations, so number of domain model described is factorial. 




Mixins model (includes: good C++, most of C#, Scala, all but bad JavaScript).

It's theoretical thus very orthogonal.

Prototype class
^
Component class (+) trait* 


Mixins is about sharing behavior between objects. There are anchors embedded into `Prototype class on which all traits agreed and synchronize. Anchor can be any kind ranging from enumeration to type constructors.   

This model is very powerful and can "bless" any class with additional behavior.

Comparative to previous discussed models  this one is real Functor. It works on constant property set (anchors). It creates new domain model by mixing traits.


October 27, 2010

Java_Script demons

Hi,
 I'm programmer and I'm writing JavaScript.
As any addicted person I have perfectly legal explanation for my behavior and here I'm going to show three things:

  • what motivate me doing this
  • why I think that it isn't addiction
  • how to quit

One

When I tried it first time it feel OK and looks harmless- just a toy, stripped down Java.
But it was naive - there always was monster inside. In fact two monsters and you already been warned about this by authorities such as Wikipedia.

The key design principles within JavaScript are taken from the Self and Scheme programming languages.[8]

Ha! It helps, if only you posses ability to read in between lines and see the future. I wasn't able then but I can help you now.

It is true, JavaScript is LISP and we all know how contagious LISP is. JavaScript hides it's true semantic behind M-expressions but you can convert any "HelloWorld.js" to "good-by-world-p" simple translating to S-expressions syntax and then you will see it true inner.

Second monster comes from Self and disgust in object. Many experienced folks lost there by creating loops with Object.prototype. They were thinking that JavaScript has class'es and that was their last mistake.

One and the only hero was Luca Cardelli, he saw it clearly, he fight it splitting object creature in pieces:

prototype class object
^
real class object
+
trait class object


Two

In the end of the day, I think that problem is more in writing but not JavaScript language. Ones you start programming it, it instantly become Zen. Programs creates programs, objects extended and contract in magical way, even functions not save in that world. It is meta programming and can not be controlled by human.

// Mix in composition helper
Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}
Object.extend(Array.prototype, Enumerable);

// curry
Function.prototype.curry = function(object) {
    var method = this,
        copy = Array.prototype.slice,
        args = copy.call(arguments, 1);
    return function() {
        var newArgs = copy.call(arguments);
        return method.apply(object == null ? this : object, args.concat(newArgs));
    };
};
Function.prototype.$ = Function.prototype.curry;
function hello(a, b, c) {
    repl.print("I am " + this + " and got: " +
          [a, b, c].join(", "));
};
var f = hello.$("foo", 1, 2);
f(4);

The consequence that you have to face is really horrible. You freezing in time, in space, and in mental state.

Three

The way out is to take control back before coding aimlessly. Learn discipline, limit yourself. You can start today: Learn You a Haskell for Great Good! or do some Scala if you weak.

October 24, 2010

GDC

It's good to have two pupil at home.

They explain me that
gdc(a,b) . lcm(a,b) = a . b

Equally nice to have i-net it explain that because
max(a,b) + min(a,b) = a + b

Can you see connection?

Trivial explanation is in fact that divisibility define lattice on R with meet given by gdc and join by lcm.

October 18, 2010

`three pieces of `four

Hi,

One morning Me, Iri and BGD were coming home after swimming. Cap of hot tee was long anticipated and we bought to it 3 peaces of `cremsnit (aka. Napoleon in U.S.).

Already far from backerei we realize - there 4 of us to share 3 peaces. How to share?

BGD suggest that we split each unit by 4, formally
Solution 1:
3u = 3 * 4 * u/4 = 4 * 3u/4  

I wanted extra unit for myself (irrational part of deal), than we can take module and split it even !
Solution 2:
|2u + i1u| = 1u + 2 * 2 * u/2 = 4 * u/2

Ups.. nobody liked my idea much.

Iri comes with another split where two pieces divided by half and one by four:
Solution 3:
2 * 2u/2 + 1 * 4u/4 = 4 * u/2 + 4 * u/4 = 4 * (u/2 + u/4) 

She argued that this fractal approach guaranty to work if we were N modulo 4:
N * (u/2 + u/4 + .. + u/N)

At the time of last solution we already finished tee.

I told kids folks tail about smart crow who helped divide cheese ball between two baby foxes. After initial split, ether fox wasn't happy with it piece so crow have to eat smaller one and start all over again. Eventually they reach atomic cheese unit. You can imagine how small it was but everybody left happy, including stomachached craw.

Kids agreed that crows solution was fare.
It makes me think about kind of education I provide to them.

October 2, 2010

Smell of Flower

Hi,


I'm programmer. It feels like being a Cylon most of the time and I'm not alone in this.

There is this program which freaks me out. It emulate sunrise and sunset by tuning color temperature on my monitors.

/home/../bin/xflux -l 45.0 -g 21.0 -k 3400

Being totally pro geek I giving you idea: install F.Lux and invite your girl for sunrise date in front of the monitor.

I'm looking forward for `X.Flower program appearing soon.

September 21, 2010

Raf's Problem

Another nice problem for testing your programming skills:

Given a String (x) containing only characters a-z, write a function (f)
that returns a base 10 integer, which converts the String as if it were
a base 26 numeral. Function f is bijective**.


Here are some example runs:


x      | f(x)
empty  | 0
a      | 1
b      | 2
z      | 26
aa     | 27
az     | 52
ba     | 53
bz     | 78
aaa    | 703
aaz    | 728
... 
aza    | 1353

Using your preferred programming language, implement function f.

* - it's known as Raf's problem and I saw it on Tony Morris `lambda blog
** - BUG: this function is injective since we can't use `spaces in number to string encoding ***
*** - we can make use of spaces if numeral separator is two-spaced but it is not what was asked - see example for encoding 26 and 27


Following is sample solutions done in Scala / Python / Haskell. Not sure about complexity level but it seems that python isn't shortest language anymore??

Haslell
str2num = foldl (\acc x -> acc * 26 + (ord x - (ord 'a') + 1)) 0

Scala
def str2num(str: String): Int = {
    val base = 26
    val offset = 'a'.toInt -1
    var res = 0
    for (c <- str) {
      val digit = if (c == ' ') 0 else (c.toInt - offset)
      res = res * base + digit
    }
    res
  }

  def num2str(n: Int): String = {
    val base = 26
    val offset = 'a'.toInt -1

    def aux(n: Int): List[Char] = (n / base, n % base) match {
      case (0, 0) => List(' ')
      case (0, r) => List((r + offset).toChar)
      case (q, 0) => 'z' :: aux(q-1)
      case (q, r) => (r + offset).toChar :: aux(q)
    }


    val res = aux(n).reverse.mkString
    if (res == " ") res else res.trim
  }

  test("Raf's Problem"){
    // x   | f(x)
    val tests = Map (
      " "   ->  0,
      "a"   ->  1,
      "b"   ->  2,
      "z"   ->  26,
      "aa"  ->  27,
      "az"  ->  52,
      "ba"  ->  53,
      "bz"  ->  78,
      "aaa" ->  703,
      "aaz" ->  728,
      "aza" ->  1353)
    for (t <- tests) {
      println(t._1 + " -> " + t._2 + " => <" + num2str(t._2) + ">")
      assert(str2num(t._1) == t._2)
      assert(t._1 == num2str(t._2))
    }
  }

Python
import string


def code(number):
    if number>0 and number<27:
        return chr(number+96)

def decode(s):
    if s in string.ascii_lowercase:
        return ord(s)-96


def coding(number):
    if number==0:
        return ""
    s=[]
    while number>0:
        x=number%26
        if x==0:
            x=26
            number=number-26
        y=code(x)    
        t=[y]+s
        s=t
        number=number/26

    return ''.join(s).split()[0]

def decoding(s):
    l=len(s)
    num=0
    for i in s:
        if not i==' ':
            c=decode(i)
            num=num*26+c
    return num



Super python
#!/usr/bin/python
 
from math import pow
from sys import argv

"""Details
16.09.2010
Given a String (x) containing only characters a-z, write a function (f) that returns a base 10 integer, which converts the String as if it were a base 26 numeral. Function f is bijective.

Nicu Marcu
*.*@*-*.com
"""

letters=map(chr, range(97,123))
 
def str2num(text):
 to_str2num=[]
 for l in text:
  index=1
  for ll in letters:
   if l == ll:
    to_str2num.append(index)
   index+=1
 index=0
 result=0
 for l in reversed(to_str2num):
  p = int(pow(26,index))
  result+=l*p
  index+=1
 
 return result
  

def num2str(nr):
 result=[]
 
 a = divmod(int(nr),26)
 rez = a[0]
 rest = a[1]
 
 if rez==0:
  result.append(rest)
  return result
 if rez==1 and rest==0:
  result.append(26)
  return result
 while(1):
  if rest==0:
   result.append(26)
   rez-=1
  else:
   result.append(rest)
  if rez==0:
   return result
  if rez<=26:
   result.append(rez)
   return result
   break
  else:
   a = divmod(rez,26)
   rez = a[0]
   rest = a[1]
 
def main():
 funct = argv[1]
 arg = argv[2]
 if funct=="str2num":
  print str2num(arg)
 if funct=="num2str":
  a = reversed(num2str(arg))
  world=""
  for i in a:
   world+=letters[i-1]
 
  print world
 return 1
main()

September 3, 2010

H2G2

Hi,





"In many of the more relaxed civilizations on the Outer Eastern Rim of the Galaxy, the Hitchhiker's Guide has already supplanted the great Encyclopaedia Galactica as the standard repository of all knowledge and wisdom, for though it has many omissions and contains much that is apocryphal, or at least wildly inaccurate, it scores over the older, more pedestrian work in two important respects.


"First, it is slightly cheaper; and secondly it has the words DON'T PANIC inscribed in large friendly letters on its cover.









UPDATE:
We make few coves for road safety...

Steam-punk version
Old t-shirt recycled

Autumn colors

Late Autumn collection

August 24, 2010

Etudes

Hi,

I'm going to write small number of websites in order to catchup with modern web.

Each will need subject and simple composition.

Borrowed from thecprogrammer.com
Etude One  Tic-tac-toe

- There is deck of empty cards on the page
- You can take one (dragging it from the deck) to invite play
- I can take another card from deck to invite play

Two one-handed cards invite each other, thus
game begins.

There is BOT which invites one-handed card on some timeout.

All cards are visible on the screen but they repelled by card you play towards margins.

August 15, 2010

scalac phases

Scala 2.8 compiler process sources trough 27 phases.

Compiler phases

# I'll illustrate `what's going on' in `bash code
scalac -Xshow-phases

The naming of those phases defined in man page. To get to the meaning we have to detour and become compiler hacker or rediscover stuff hands on style. I'm not that much into compiler internals yet and have to choose `discovery mode.

Collecting information

man scalac
Compilation Phases

initial    - initializing compiler
parse      - parse source files
namer      - create symbols
analyze    - name and type analysis
refcheck   - reference checking
uncurry    - uncurry function types and applications
transmatch   - translate match expressions
lambdalift   - lambda lifter
typesasvalues            - represent types as values
addaccessors             - add accessors for constructor arguments
explicitouterclasses     - make links from inner classes to enclosing one explicit
addconstructors          - add explicit constructor for each class
tailcall    - add tail-calls
wholeprog   - perform whole program analysis
addinterfaces            - add one interface per class
expandmixins             - expand mixins by code copying
boxing     - makes boxing explicit
erasure    - type eraser
icode      - generate icode
codegen    - enable code generation
terminal   - compilation terminated


Lets prepare stage. 

We use simple code with `case class and `for expression.

// Scala source: Frameworks.scala

object cph { 
  case class Person(name: String, mail: Boolean, children: Person*)
  //
  val bob = Person("Bob", true)
  val aida = Person("Aida", false)
  val cipi = Person("Cipi", true, bob, aida)
  val alina = Person("Alina", false, bob, aida)
  val all = List(bob, aida, cipi, alina)
  //  println(all)
  //
  val mochi = all filter (_.mail == false) 
flatMap (p => p.children map (c => (p, c)))
  //
  mochi foreach { 
    pair =>  
      val (p: Person, c: Person) = pair
      println(p.name + " > " + c.name)
  }
  //
  val motherOf = for (m <- all;
                      c <- m.children 
                      if m.mail == false) 
                 yield (m, c)
  //
  for ((m, c) <- motherOf)
    println (m.name + " - " + c.name)
}
(1) - Code formatting made ugly on purpose. I'm working with `emacs scala-mode with `sbt replacing `scala shell. Coding paralleled with 'sbt> ~compile', which means `compile whenever source files change. Going to REPL with 'sbt> console-project' I can use select paragraph M-h then sent it to interpreter with C-c-e. That's why scala blocks formatted as emacs paragraphs.


Generate reports for all phases.

$ scalac -Xshow-phases 2>&1 |while read f; do echo ">> $f";
> scalac -Xprint:$f Frameworks.scala 2>&1 > Frameworks.$f.scala;
> done

Analyze 

We need diff's from consecutive phase. Could be done nicely with change-set manager HG designed just for this.

scalac -Xshow-phases > scala.phases
for f in `cat scala.phases `; do echo ">> $f"; 
 cp  Frameworks.$f.scala Frameworks.scala; 
 hg ci -m"$f" Frameworks.scala; 
 done
 
hg log Frameworks.scala
changeset:   34:c03403f4f0c4
summary:     namer

changeset:   33:37ed3eeb753e
summary:     parser

changeset:   32:917dc0255899
summary:     add Framework.scala

hg diff -r33:34
diff -r 37ed3eeb753e -r c03403f4f0c4 ScalaLanguage/src/main/scala/Frameworks.scala
--- a/ScalaLanguage/src/main/scala/Frameworks.scala Sun Aug 15 13:03:51 2010 +0300
+++ b/ScalaLanguage/src/main/scala/Frameworks.scala Sun Aug 15 13:03:51 2010 +0300
@@ -1,6 +1,6 @@
-[[syntax trees at end of parser]]// Scala source: Frameworks.scala
+[[syntax trees at end of namer]]// Scala source: Frameworks.scala
 package  {
-  object cph extends scala.ScalaObject {
+  final object cph extends scala.ScalaObject {
     def () = {
       super.();
       ()


Visualizing 

It shouldn't be that much console stuff, but there is nice 'unix tradition to get you trough process even if don't have installed `kdiff3 or `hgview.

hgview on scalac phases



I was looking for translation of `for expression. Surprisingly, it done at the very beginning in `parse phase.

I followed remaining phases too.  It is quite entertaining to see code morphing from Sources to JVM.  It's also much more educative that simple `scalap  -verbose or even `jd.  However good showing off need special code snippets for which I'm going to look because it worse effort.

Naming phase.

Typer phase.

Specialize to ExplicitOuter.

August 11, 2010

Lifehack, Alarm invertion

Suppose there is strong reason for you to wake up at 7h00.
Default solution is to set alarm clock at appropriate time.


This hack use Inversion of Control (IoC) principle to achieve same effect when,
instead to wake up at 7h00 you go to sleep at 23h00. Following the idea alarm should be set to 23h00 (day before). After 8 hours of sleep you up.

Hack will probably fail first time when sleep debit is big, but in the long run this it's preferable to default solution.

Novelty of the approach can be contrasted in two positive intentions: 
The early bird catches the worm.
  and
It is better to oversleep than to undereat.




This hack isn't without BUG. It missing crucial part - Asynchronous Completion Token. When you wake up you need to recall context in which you set alarm and it is not implicitly true if reason to wake up every time different.

July 31, 2010

Desktop (at) Jul 31 2010

I organize my Desktop on III trends:
  • increasing comfort;
  • decreasing effort;
  • keeping productivity constant.

Currently I sit on two screens with same X11 but no Xinerama.
All stuff orchestrated by `Ion3 Window Manager.

It feels just right despite it's 5 dimensions which I thought would be to much to use subconsciously because of my 3D habits.

My front view has Screen1 ++ Screen2,
 Each screen has Windows on `X and Desktops on `Z,
  Windows divided into Frames (`X-horizontal or `Y-vertical),
 Frame has Tabs like in Firefox which slice `X ones more.

Screen 1 Screen 2

Left monitor smaller then right. I do reading from it.

Right is for work.

Desktops organized by themes on Screen1 (Office, RTFM's etc.) and tasks on Screen 2. Tasks have usually one or two application which need full screen (Eclipse, Remote Desktop to Windows machine or remote X Session) and some small frames with terminal app's and scripts.
Fulscreeners are collapsed initially  and only when I'm focusing on the task they goes big on `Z so I still have all stuff on 2D distance. Themes also adjusted to the task to extract me required info.



Before I used Window Managers with overlapped windows. Normally it consume 5-6 desktops times 2 monitors.
Now, just 5-6 on both monitors in any time. It's contra intuitive but tiling WM save 1.2 square meters of pixels for me.

I use mouse for editing and never for navigating because I have to move it and still not able to go directly trough all Ion's dimensions. I use teleport instead which doesn't have those limits then just tasting shortcuts in app's.

July 26, 2010

There no such think as lie

My point exactly is that there no deliberate untruth.
Fist account is logical equality of `rightful `true teller and `deluded `liar.
It can be checked by logical table and all YES/NO answers will be same.

Suppose real person. She is liar. Lie is recurring, also reflective process, from it comes self delusion. If we recall that this person liar it become indistinguishable from honest and sane one.

The only difference is inside.


Geeks jokes

trait Philosophical {
    def philosophize = println ("I consume memory, therefor I'm\nQED")  
} 


Atoms dialog:
- i lost my electron
- i you sure?
- yes, i'm positive!

Me - buying a Car

I don't hate cars but I love bicycles. Still time comes to buy one of those fridges on wheels with expectation of improving long distance mobility.

Data source for offers is local news-board. Datamining target is to filter ill intentioned sellers. Criteria 1 - get only new offers, 2 - check contact phone with Google for multiple cars in stock. Tools is 15-min script in Python which
$ crontab -e
# m h dom mon dow command
0 * * * * /home/$USER/golf.sh
.
and tail -F /tmp/new_golf.txt on results.

import sys
import datetime
import lxml.html

def readIds (name):
    xs = list ()
    file = open(name, "r")
    try:
        while 1:
            line = file.readline()
            if line == '':
                break
            xs.append(line.strip())
    finally:
        file.close()
    return xs

def writeIds (name, xs):
    file = open(name, "w")
    xsn = map(lambda (s): s + '\n', xs)
    try:
        file.writelines(xsn)
    finally:
        file.close()

def appendResult(name, xs):
    file = open(name, "a")
    xsn = map(lambda (s): s + '\n', xs)
    try:
        now = datetime.datetime.now()
        file.write(">> At " + str(now) + " added: " + str(len(xs)) + " new item\n")
        file.writelines(xsn)
    finally:
        file.close()
        
def parseCatalog(catalog, base_url, pages):
    xs = list ()
    for page in range(1, pages +2):
        linkTo = catalog % page

        links = lxml.html.parse(linkTo).xpath("//a[@class=\"resulttextlink noMargin\"]/@href")
        for link in links:
            if link.find(base_url) >= 0:
                Id = link[link.rfind('/', 0, link.rfind('/') -1) +1 : -5]
                xs.append(Id)

    return xs

CATALOG_URL = "http://www.publi24.ro/anunturi/auto-moto-velo/masini-second-hand/vw/golf-4/?pag=%d"
ANUNT_URL = "http://www.publi24.ro/anunturi/auto-moto-velo/masini-second-hand/vw/golf-4/anunt/"

def main ():
    upper = 2
    if len(sys.argv) >1:
        upper = int(sys.argv[1])

    cars_store_file = "/tmp/golf.txt"

    cars = readIds (cars_store_file)

    new_cars = parseCatalog(CATALOG_URL, ANUNT_URL, upper)
    
    lset = set (cars)
    rset = set (new_cars)    
    cars_diff = list(rset.difference(lset))
#     import pdb
#     pdb.set_trace()

    writeIds(cars_store_file, new_cars)

    new_urls = map(lambda s: ANUNT_URL + s + '.html', cars_diff)
    appendResult("/tmp/new_golf.txt", new_urls)
    
    

if __name__ == "__main__":
    main()




Simple enough and robust but wrong. For example next construct.

file = open(name, "r")
    try:
        while 1:
            line = file.readline()
            if line == '':
                break
            xs.append(line.strip())
    finally:
        file.close()

It is degenerated Python 3.0 resource management construct. It is RAII for GC runtimes sprinkling everywhere from VB to Ruby and C# two stage de-allocator.

with open(name, "r") as file:
           pass # here we do stuff
originally.

Some can argue that it is evolutionary result of new ideas implemented into language. But this semantic construct always been there. If natural language would need redesign every time new idea pushed out we would still be discussing advantages `wheel vs `backpacking instead Scala vs Python.

BTW, Scala has no problem with extension.

object _3 { 
  import java.io.File
  import java.io.PrintWriter
  //
  def withPrintWriter(file: File) (op: PrintWriter => Unit) { 
    val writer = new PrintWriter(file)
    try { 
      op (writer)
    } finally { 
      writer.close()
    }
  }
  //
  withPrintWriter (new File("/tmp/Date.txt")) { 
    writer =>
      writer.println (new java.util.Date)
  }
}

No need to wait. One can write new ideas fluently for other to understand and accept.

July 23, 2010

Scala is my language-of-the-year this season.

Already for a while, I'm teaching myself one programming-language-per-year.
It upgrade my coding abilities whilst keeping programming skills generic and language agnostic. Practically it means I'm rewriting lots of code snippets with familiar structure in different languages. Something like RosetaCode on syntactic level.

Last year I flushed my brain with Category Theory and Linear Logic. Reason for that upgrade was one silly question from headhunter, namely: "What do you call class with virtual function". (C++ interview).
His own answer was - `Polymorphic Class'. Ups... This `hangs me up just like F0 0F C7 C8  hangs Pentium MMX. Postfactum I meditated on subject a lot,  because it was traumatizing failing interview that miserable.
Clearly he meant `Subtyping polymorphism of C++ object's but I ruled that out on simplicity ground and begin looking for `higher-kinded (*->*) in type classes, then for `class's from Naive Sets and then back to nothing, Just Nothing...

Thanks to this unfortunate event I rethink my approach for `skills-upgrade in general:
`programming-language-per-year still good, valid and fun
`proficiency can be gained in 10 year (10,000 3000 hour when 4.5 per day 220 days per year)
`then you have to go to new LEVEL (still creator) or GAME OVER (manager)

What is Scala?
For me it is reification of computation via programing (By means of reification something that was previously implicit, unexpressed and possibly unexpressible is explicitly formulated and made available to conceptual (logical or computational) manipulation).

Why Scala?
Because I like to program things fluent style and the way I feel it right.

July 6, 2010

Get to the light..

.. make BOT happy.

One of my favorite educational games is Light-Bot.
Its target is to navigate psychotic robot to light ball, let him make lite. This act bring happiness to robot. This also complete the game.

Level 10 split humanoids in two groups - 60/40, where 40 will newer pas it.
Who does it - programmers. More precisely - `can be programmer under favorable circumstances.


Top 15 solutions presented in no order.


  • All 10 level in under 45 MIN
    
    


Sent: joi 8 noiembrie 2012 15:45 
Received: 11/08/2012 04:31 PM






  • lb-88.png
  • if __name__ == "__main__":
        f1()
    
  • lb-105.png
  • lb-111.png
  • :- use_module(library(clpfd)).
     
    puzzle(    [[ 151],
              [U1],[U2],
            [40],[U3],[U4],
          [U5],[U6],[U7],[U8],
        [ X],[11],[ Y],[ 4],[ Z]], X,Y,Z  ) :-
     151 #= U1 + U2, 40 #= U5 + U6,
     U1 #= 40 + U3, U2 #= U3 + U4,
     U3 #= U6 + U7, U4 #= U7 + U8,
     U5 #=  X + 11, U6 #= 11 +  Y,
     U7 #=  Y +  4, U8 #=  4 +  Z,
      Y #=  X +  Z,
     Vars = [U1,U2,U3,U4,U5,U6,U7,U8,X,Y,Z],
     Vars ins 0..sup, labeling([],Vars).
     
    % ?- puzzle(_,X,Y,Z).
    % X = 5,
    % Y = 13,
    % Z = 8 ;
    
  • lb-114.png
  • lb-116.png
  • 117, 117-1 are same as 116 but have hiden bug in them.. Because they 117 :_
  • lb-117-1.png
  • lb-117.png
  • [-]>,+[->,+]<[.<]
    
  • lb-119.png
  • lb-125.png
  • I think, I understand this one.
    qsort []     = []
    qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x]
    
  • lb-126.png
  • fib = 0 : 1 : zipWith (+) fib (tail fib)
    fib !! 4
    
  • lb-131.png
  • lb-136.png
  • Program will take all available memory no matter what. Seriously, trying to be everything is not a way to success.
  • lb-190.png
  • Two light bull solution

  • Total inline strategy



  • high kinetic energy 

  • real proof that non programmer can do it


  • Carpenter: there 17 symmetries in topology. He used 6.  


  • Easy Test



July 5, 2010

FooBuzz canonical answers

Most tasks have multiple solutions. Our life experience and aesthetic inclination forms partial map from `all solution space to personalized one.

By comparing `personal solution with `canonical, for a given problem, we can analyze what is our essence.

Many interview problem designed just for that purpose.

Problem One - `FooBuzz'.

You asked to enumerate numbers fro 1 to 100. It it is multiple of 3 then print `Foo. If multiple of 5 then print `Buzz. If multiple of both print `FooBuzz else print number.

Solution show the balance of mathematical awareness versus following programming standard.

Canonical solution for different type of languages (I skip most and ignore non-mainstream).

`C
int main ()
{
  
  for (int i = 0; i < 100; ++i) {
    bool flag = false;

    if (i % 3 == 0) {
      printf("Foo");
      flag = true;      
    }

    if (i % 5 == 0) {
      printf("Buzz");      
      flag = true;      
    }
    
    if (flag) {
      printf("\n");      
    } else {      
      printf("%d\n", i);      
    }    
  }
}

`Python
for i in range (1, 100):
    s = ""
    if i % 3 == 0: s+="Foo"
    if i % 5 == 0: s+="Buzz"
    if s == "": s += str(i)
    print s

`Scala
def FooBuzz {
    for (i <- 1 until 100) {
      val s = { if(i % 3 == 0) "Foo" else "" } + 
              { if(i % 5 == 0) "Buzz" else "" }
      println ( if(s.isEmpty)  i.toString else s )
    }
  } 

There is no extensive study of deviations for this solution only observations gathered from limited sources.

On math side main problem is failure to recognize instance of Monoids {nat, %} and {string, +} which naturally additive and don't need special treatment in code.

On coding side variety language specific problems. Only one was common -  putting conditional of multiple being equal 0 but not just `i % 3.


Our efficiency as designer proportional to degree of flexibility we can take without damaging our brain. This and similar test show us our limits.

June 24, 2010

Test results QuickCheck and RSpec

There are lame code-snippet in posts bellow:



  1. class Rational from Programming in Scala




  2. org.scalatest.Spec for Rational




  3. org.scalacheck a.k.a QuickCheck


They helped me to decide on my personal preference in testing style.

Conditionally on task at hand, but I'm inclined towards RSpec and QuickCheck tools.



While tossing code around my tests caught two not trivial BUGs.



BUG 1: Rational should normalize not only the quotient but also sign of nominator and denominator.


BUG 2: Scala library description of Ordering isn't accurate.

trait   Ordering[T] extends Comparator[T] with PartialOrdering[T]   
Theorem:
transitive: 
if 
   compare(x, y) == z 
   and compare(y, w) == v 
   and math.signum(z) >= 0 
   and math.signum(v) >= 0 
then 
   compare(x, w) == u 
   and math.signum(z + v) == math.signum(u), 

for any x, y, and w of type T and z, v, and u of type Int.



Both were detected by ScalaCheck tests.

So, it is 2:0 for QuickCheck against RSpec on foreign (Scala) field.

org.scalacheck a.k.a QuickCheck

Code from Rational spec use something which belong to different testing style:

package funobject
 it("should have a total order") { 
      import RationalOrderingCheck._

      check(propertyReflexive)  should be ('passed)
      check(propertySymmetry)   should be ('passed)
      check(propertyTransitive) should be ('passed)
    }

It is QuickCheck fixture.

"ScalaCheck is a powerful tool for automatic unit testing",
normal unit testing considered `manual and unreliable.

package funobject

import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.tools._

import org.scalacheck._
import org.scalacheck.Prop._
import org.scalacheck.Arbitrary.arbitrary


object ArbitraryRational { 

  import funobject._

  implicit def arbRational: Arbitrary[Rational]  = Arbitrary { 

    val genRational = for { 
      n <- Gen.choose(-5, 5)
      d <- Gen.choose(-6, 6) suchThat (_ != 0)
    } yield Rational(n, d)
    
    genRational
  }

}

object RationalOrderingCheck {  

  import ArbitraryRational._

  /** reflexive: compare(x, x) == 0, for any x of type T.
   */ 
  val propertyReflexive = forAll { 
    r: Rational =>  (r.compare(r) == 0)
  }  

  /** symmetry: compare(x, y) == z and compare(y, x) == w
   * then math.signum(z) == -math.signum(w),
   * for any x and y of type T and z and w of type Int.
   */ 
  val propertySymmetry = forAll { 
    (x: Rational, y:Rational) =>  { 
      val z = x.compare(y)
      val w = y.compare(x)
      math.signum(z) == -math.signum(w)
    }  
  }

  /** transitive: if compare(x, y) == z and compare(y, w) == v
   * and math.signum(z) >= 0 and math.signum(v) >= 0
   * then compare(x, w) == u and math.signum(z + v) == math.signum(u),
   * for any x, y, and w of type T and z, v, and u of type Int.
   */ 
  val propertyTransitive = forAll { 
    (x: Rational, y:Rational, w: Rational) =>  { 
      val z = x.compare(y)
      val v = y.compare(x)
      val u = x.compare(w)

      if (math.signum(z) > 0 &&
          math.signum(v) > 0) 
        math.signum(u) > 0
      else if (math.signum(z) < 0 &&
          math.signum(v) < 0) 
        math.signum(u) < 0
      else true
    }  
  }

}  




org.scalatest.Spec for Rational

A rational number is a number that can be expressed as a ratio d/n ....

package funobject

import org.scalacheck.Test.check
import org.scalacheck.ConsoleReporter.testReport

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.tools._
import funobject.Rational._
import funobject._

class RationalSpec extends Spec with ShouldMatchers { 
  // shorthand for Rational object
  val R = Rational 

  describe("A Rational Number") { 
    
    it("should throw IllegalArgumentException " +
       "if zero denuminator pased to ctor") { 
      evaluating { val e = R(1, 0) } should produce [IllegalArgumentException]      
    }

    it("should implement +, -, *, / and unary -") { 
      R(1,2) + R(2, 3) should have { 
        'nomer (7)
        'denom (6)
      }

      R(3,2) - R(1, 3) should have { 
        'nomer (7)
        'denom (6)
      }

      R(1, 3) * R(2, 5) should have { 
        'nomer (2)
        'denom (15)
      }

      R(1, 3) / R(2, 5) should have { 
        'nomer (5)
        'denom (6)
      }

      -R(1, 2) should have { 
        'nomer (-1)
        'denom (2)
      }
    }

    it("should have normal form") { 
      R(22, 42) should be === R(11, 21)
    }

    it("should support mixed ariphmetic" +
       " with implicit cast from integer") { 
      R(1,2) / 7 + (1 - R(2,3)) should be === R(-11, 42)
    }
    
    it("should have a total order") { 
      import RationalOrderingCheck._

      check(propertyReflexive)  should be ('passed)
      check(propertySymmetry)   should be ('passed)
      check(propertyTransitive) should be ('passed)
    }
  }
  
}


class Rational from Programming in Scala

A specification for class Rational from Programming in Scala

package funobject

/** Rational number is a number that can be expressed as ratio of n/d,
 * where n and d are integers, except that d can not be zero.
 */

class Rational(n: Int, d: Int) extends Ordered[Rational] {
  require(d != 0)

  private val g = gcd(n.abs, d.abs)
  val nomer = (if (d < 0) -n else n) / g
  val denom = d.abs / g

  def this(n: Int) = this(n, 1)


  def unary_- = new Rational(-nomer, denom)

  def + (that: Rational):Rational =
    new Rational (nomer * that.denom + that.nomer * denom,
                  denom * that.denom)
  def - (that: Rational):Rational =  -this + that

  def * (that: Rational):Rational =
    new Rational (nomer * that.nomer,
                  denom * that.denom)
  def / (that: Rational):Rational =
    new Rational (nomer * that.denom,
                  denom * that.nomer)

  override def equals (other: Any): Boolean = other match { 
    case that: Rational => this.nomer == that.nomer &&
                           this.denom == that.denom
    case _ => false

  }

  override def compare(that: Rational) = 
    this.nomer * that.denom - that.nomer * this.denom

  override def compareTo(that: Rational) = this.compare(that)

  override def <= (that: Rational): Boolean = compare(that) <= 0
  override def >= (that: Rational): Boolean = compare(that) >= 0
  override def <  (that: Rational): Boolean = compare(that) <  0
  override def >  (that: Rational): Boolean = compare(that) > 0


  override def toString = nomer + "/" + denom

  private def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)
}

object Rational {
  implicit def implicitRationalFromInt(i: Int): Rational = new Rational(i)
  def apply(n: Int, d: Int) = new Rational(n, d)
  def apply(n: Int) = new Rational(n)
}