CSS

[notes]Macvim settings

1.remove ^M (Ctrl-V Ctrl-M, dos newline symbol) when vimrc file is created in Windows:


search and replace in vim commandline by typing:

:%s/\r//g

to replace the ^M space

or using tr command to delete ^M char in file:

cat .vimrc | tr -d '\r' > .new_vimrc

2.open macvim from terminal:


add application path to .bash_profile

ex:
export PATH="$PATH:/Applications"

call mvim script from terminal to open macvim

3.remove toolbar and toolmenu:


set guioptions-=T
set guioptions-=m

4.sample .vimrc from vgod

https://github.com/vgod/vimrc/blob/master/vimrc

F2E Interview Questions

Here are some interview questions from a front-end engineering job, through I didn't get that position , these questions are pretty interesting and might help the others who want to get a Front-end job. So here are the questions:

1.Weird Width:

I create this <div/> to have my article inside. However, my nit picking product manager finds the width of this block is a little different between Internet Explorer 6 and Firefox. Can you help me to fix this weird bug?
In Internet Explorer, the width is 500px.
In Firefox 3, the width is 522px.
Can you help to correct my attached file so that the page is identical in different browsers? It would be great if you can tell me why so that I won't do that stupid thing again. And if you have spare time, please style the page for me since I am so lazy. ^^』』


Ans:

First of all, the problem of weird width is because older IE browser has different explanation in CSS box model.

The IE explained CSS width attribute as the width of content + padding + border. As the result, we get the width of 500px in IE browser that includes padding and border, in contrast of 522px in other modern browser.

Internet explorer 6+ has two mode of CSS interpretation:
Quirk mode – the interpretation of IE's own standard
standard-compliant mode – according the W3C standard (almost)
By define the <!DOCTYPE> tag we can switch the IE to standard-compliant mode. So here's the solution:
<!DOCTYPE>
By attach this before <html> tag, we can get correct width


2.Horizontal Toolbar

Product manager asks me to make a horizontal toolbar for our website.
Even if user scrolls, toolbar will always stay at the bottom of page. Another requirement is that all modern browsers are compatible with this new feature. (Internet Explorer 6 - 8, Firefox, Opera, Google Chrome, and Safari) After making a prototype I find it's really difficult. Please teach me how to do that.


Ans:

The CSS { position: fixed } attribute can build the toolbar in same position whenever scrolling. So the solution is:
#toolbar { position: fixed ; bottom:0; width:100%; }
Unfortunately, our old IE6 friend doesn't support it.
Again, search for some hack at web, we found 2 approaches:
1. JavaScript approach: which auto re-assigns position when event called.
2. CSS approach:
Using CSS expression or, Using wrapper
I use wrapper method because it's the simplest to me.



Normally, the { position:absolute } attribute will anchor the element according root element. Therefore we can set another element outside to be the root and have height equal to the screen. So the { position:absolute } attribute can place toolbar in right position. And by set the {overflow:hidden} attribute, we can hide the content outside the root element.
When assign css attribute, IE will active the element. So we can active the <html> element to be the wrapper, <body> to be the content,
CSS example:

#toolbar {position: fixed; bottom: 0; width: 100%;}
//css for ie6
* html{ overflow-y: hidden; } //hide the wrapper scroll
* html body{
  padding:0px;margin:0px; // reset
  overflow-y: auto; //set scroll
  height: 100%;
}
* html div#toolbar
{
  position: absolute;
  width:98%; //fix the problem that toolbar over scroll
}


Show me the Browser

Dear Candidate,
We front-end engineers are always busy at switching between browsers. Each engineer has three browsers installed on their notebook. They are Internet Explorer 6, Internet Explorer 7, and Firefox 3. It's really confusing to identify which browser is using. As an engineer with some repute, you want facilitate others by showing icon.

Ans:


1. we need to set CSS sprite for browser picture
I try to build CSS class with background-position attribute:
.firefox{ background-position:0 0 }
.ie7{ background-position:0 -75px }
.ie6{ background-position:0 -150px}
2. JavaScript to detect browser and parse userAgent string and replace picture for right browser.
using library from here: http://www.quirksmode.org/js/detect.html

window.onload = function(){
  // get the DOM object by ID
  var browserPic = document.getElementById("browsers");
  //detect browser and set correct class
  if(BrowserDetect.browser == "Firefox"){
    browserPic.className = "firefox";
  }
  if(BrowserDetect.browser == "Explorer"){
    if(BrowserDetect.version == "6")
      browserPic.className = "ie6";
    if(BrowserDetect.version == "7")
      browserPic.className = "ie7";
  }
};
(but it turn outs that using css hack * for ie6, _ for firefox is a far more simpler solution)

Scheme Note

Recently I am playing with some scheme code, here's some introduction and code snippet about it.

What is Scheme?

Scheme is a pure functional programming language that was developed by MIT media lab.
The design philosophy of scheme is, rather than provide more features, it's more important to provide elegant core functions, minimize the weak points and restriction of the languages.(which is: less is more)

A functional programming language, as the name, is a language that treat function as first level primitive. In functional language, you can pass and return function as variable, the program in functional language is constructed by multiple recursive function call.

for example, a for loop iterate a data array in structure language is like:

int[] a = [0,1,2,3,4]
for (int i = 0 ; i < 5 ; i++){
  print(a[i]);
}
// 01234
in scheme you have to define a for-each loop like this and pass the function:
(define each (lambda (list proc)
  (if (not (null? list))
      (begin
        (proc (car list)) ; car : get first element of list
        (each (cdr list) proc) ; cdr : get the rest of list except the first element
      )
)))

(each '(0 1 2 3 4) write) ; pass the function "write" to execute on each element
; 01234

In functional language, a function is more like a logic unit, take inputs and return output, it's more close to the function in Mathematic. Therefore, a function will not have any side effects and dependencies, which make it very easy to test and reuse.
Another good part in functional language is lazy-evaluation. The function passed will only executed when it's needed to, for example, a program in structure programming like:

print(db.read());

Will call the read() function and save in memory before print, but in functional language, the function call is strict synchronization:

(print (read db ))

The read function will only perform when print function is going to print, and only read the data that is needed to print, if the print function abort, the read will not be executed. In this way, the function call can be integrated and optimized. Also, because the only things effect function output is the input, so we can easily save the results of function and reuse it. In Scheme, you can call the "delay" function to cache the results of function output: http://www.ibm.com/developerworks/linux/library/l-lazyprog.html

functional language is mainly used on science, math ,AI and financial area,

the functional language on the block included: scheme, haskell, f#, clojure and more.

more information about fp:
why fp matter
why fp matter matter

Getting Started


Racket is a good implementation and IDE for scheme, it's more friendly then MIT-Scheme, you can install it and choose the language as "R5RS" which is the newest version of scheme implementation.

snippets

get last element or list:
(define last (lambda (list) 
             (if (> (length list) 1) 
                 (rac(cdr list)) 
                 (car list) 
             )))
fibonacci:
(define fib (lambda (level)
            (if (< level 2) 
                 level
                 (+ (fib(- level 1)) (fib (- level 2)) ) 
            )))
; dynamic programming version
(define (fib-dym level) 
        (let fib ((base0 0) (base1 1) (n level))
        (if (< n 1)
            base0
            (fib base1 (+ base0 base1) (- n 1)))))
quick sort:
(define (partition pivot num-list)
  (if (null? num-list) '(()()) 
      (let ((split-of-rest (partition pivot (cdr num-list)))) ;split of rest is a 2 way list:((first...) ( second...))
        (if (< (car num-list) pivot)
            (list (cons (car num-list) (car split-of-rest)) ;put x into first list
                  (cadr split-of-rest))
            (list (car split-of-rest) ;put x into second list
                  (cons (car num-list)(car (cdr split-of-rest))))
            ))))

(define (quicksort num-list)
  (if (<= (length num-list) 1) num-list
      (let ((split (partition (car num-list) (cdr num-list))))
        (append (quicksort (car split)) ;smaller
                (list (car num-list))   ;pivot
                (quicksort (cadr split) ;larger
                           )))))

simple test function:

(define test (lambda (case expr ) 
                 (begin
                 (if (eqv? expr #t) 
                     (write (cons case "complete" ))
                     (write (cons case "failed" ))
                 ) (newline)
                 )))
;execute testCase:
(test "fib is fibonacci function:" (equal? (fib 8) 21) )

Bresenham's circle algorithm

Instruction


Bresenham's circle algorithm, also called midpoint circle algorithm, is an algorithm used to determine the points needed for drawing a circle.

The reason of using this algorithm is, when drawing circle, we need to calculate the floating point numbers of each coordinate points, which may be slow when processing multiple objects.

This method provides a simplified way to draw the circle by estimating the midpoint of arcs.


The Algorithm


for each point p(x,y)
we can take the next approximate points N(x,y+1) , NW(x-1,y+1) by estimating midpoint M(x-1/2,y+1)
that is: if the point M is in the circle, the point N is closer to the circle, therefore the N should be chooses for next point, otherwise, the NW point should be chooses.

so, we can calculate the distance from M to circumference by the formula:
Rd = r - Rm
if Rd < 0, M is outside the circle, if Rd > 0, M is inside the circle.
from x^2 + y^2 = r^2,
we can know that
Xm^2 + Ym^2 - Rm^2 = Xm^2 + Ym^2 - (r - Rd)^2 = 0
therefore, we can Defined D(M) = Xm^2 + Ym^2 - r^2 = Rd^2 - 2Rd = Rd(Rd -2)
because midpoint will be close to the circle, we can ignore the case when Rd > 2.
So if D(M) > 0,Rd < 0 ,M is outside the circle , NW should be chooses if D(M) < 0,Rd > 0 ,M is inside the circle , N should be chooses

We can get the algorithm as below in javascripts:

var drawCircle = function(ctx , x , y , r){
  var cx = r;
  var cy = 0;
  //init draw 4 points on top,right,left and bottom.    
  init(ctx,x,y,r);
  
  //we only need to calculate 1/8 of the arcs, 
  //that is when angle = 45degree, cx = xy 
  while(cx > cy){
    if(cx*cx + cy*cy -r*r > 0){ // D(M) , if D(M) > 0, NW(x-1,y+1) is chooses
      cx--;
    }
    cy++;

    //draw point and mirrow the points to other 7 places on circle
    mirrowing(ctx,x,y,cx,cy);
  }
}

Optimize

The algorithm is fast now and without any floating points,
but we can optimize more by simplify the calculation of D(M)

for each D(M) = D(x-1/2,y) = x^2 - x +1/4 + y^2 -r^2
the next D(Mnew) = D(x-1/2,y+1) = x^2 - x +1/4 + y^2 +2y +1 - r^2
so we can get the difference of each level of D(M), dy = 2y + 1
let D(Mnew) = D(M) + 2y + 1

also, don't forget when the D(M) > 0 , we should move x too,
so D(Mnew) = D(x-3/2,y+1) = x^2 - 3x +9/4 + y^2 +2y + 1
= D(M) -2x +2 +2y +1
so we can get the difference when x moved: dx = -2x +2

for the optimize above we can get the new algorithm:

var drawCircle = function(ctx, x, y, r){

  // d start from D(M) = r^2 - r^2 + r-1/4 = r- 1/4 , but we can ignore constant because r>1/4
  var d = r; 
  var dx = (-2) * r; //dx = -2x +2 , constant move to loop
  var dy = 0; //dy = 2y + 1 , constant move to loop

  var cx = r; //starting point:
  var cy = 0;
    
  init(ctx,x,y,r);

  while(cx > cy){
    if(d > 0){
      cx--;
      d += (-2)*cx + 2;
    }
    cy++;
    d += 2*cy + 1;

    mirrowing(ctx,x,y,cx,cy);
  }
}

you can watch the demo on javascript canvas here.(firefox and chrome/safari only)

ref:
Wiki
http://www.ecse.rpi.edu/