CSS

Live number in ruby

Live number in ruby


Live number is a number of the total sum for birthday year,months and days.
Below is the ruby implementation:

def live_number(birthday)
  reduce("#{birthday.year}#{birthday.month}#{birthday.day}")
end

def reduce(sum)
  add_sum = each_digits(sum).reduce(:+)
  add_sum >= 10 ? reduce(add_sum) : add_sum
end

def each_digits(num)
  num.to_s.split("").map{|c| c.to_i }
end


spec:

describe "live_number" do 

  before :each do 
    @birthdays = [Time.new(2001,3,5),
                  Time.new(1978,5,26),
                  Time.new(1962,10,1)]
    @birth = {:day => Time.new(1981,6,11), :ans => 9 }
  end

  it "return number of live by birthday" do 
    @birthdays.each do |day|
      live_number(day).should be_a_kind_of(Fixnum)
    end
  end

  it "return the correct number of live" do
    @birthdays.each do |day|
      live_number(day).should == 2
    end
  end

  it "return correct number with specific birthday" do 
    live_number(@birth[:day]).should == @birth[:ans]
  end
end

Ruby Warrior!!



Ruby Warrior is a game that teach you how to programming with Ruby, and also how to write AI script.


Install


gem install rubywarrior
rubywarrior


And you will have a player.rb script and README,


sample code for player.rb

def play_turn(warrior)
    if warrior.feel.empty?     
      warrior.attack!
    elsif warrior.health <= 5
      warrior.rest!
    else
      warrior.walk!
    end
  end

follow the instruction to implement player.rb, then run the rubywarrior to start fighting with your warrior!!

Termkit - Graphical Terminal

Termkit is an interesting project that focus on the improvement of terminal.

The UNIX terminal we use right now is established in the time of mainframe.

It is still powerful because it's simplicity and ability to script. The terminal output can be pipelined as input to other programs, and the command can be easily scripted and recognized by programs. Unlike GUI, it's hard to script the simple action like: click this red button and open this file. However, because the command is used by both human and machine. It is pretty unfriendly for beginner and unfriendly in terms of today's UI design. The target of termkit is adding a visual layer for terminal. like we can output the command in different color, the folder and files type with icon, autocomplete with commands and tooltip of command switches.

The structure is like this:

input => process => output for program
||
termkit => output for human

and termkit is using webkit for visual presentation, and node.js for glue the process with webkit.

Install:

install node.js , npm

npm install mime (for webkit to distinguish content type)

git clone https://github.com/unconed/TermKit.git --recursive

run the termkit demean

cd TermKit/Node; node nodekit.js

run client

cd Termkit/Build; unzip Termkit.zip; open Termkit.app


This project is still on an early stage. But it show an different aspect of GUI improvement. Like an different approach of sikuli.
https://github.com/unconed/TermKit

Introduction of SCSS and Compass

Recently, the CSS tool like SCSS,SASS and less have become more popular.
Those framework provide several extra functionality to CSS, also with build in compress option.
take SCSS as example:

install scss using ruby gem:


gem install sass
    sass style.scss style.css 
    sass [INPUT] [OUTPUT]

functions


1. Nesting class

#css{
     padding:5px;
     .tool{
          padding-top:10px;
     }
     //parent reference
     &:hover{
          background-color:#FFF;
     }
}


2.Variables
you can use dollar sign as variable mark in SCSS:
$mid-padding : 5px;

#css{
     padding : $mid-padding;
}

3. Mixins
Mixins means module inheritance in Ruby. It's just like inheritance from abstract class in SCSS. Use @ sign for declare maxin and include in css class.

@mixin block-base($margin){
     margin:$margin;
     padding:$padding;
}

#block{
     @include block-base(10px);
}

4. Inheritance
Also you can use @extend to inheritance from other CSS class.
.error{
     color:#F43;
}

.big-error{
     @extend .error
     font-size: 22px;
}

5. import
Import can let you include library and mixins into current css file, like compass will have lots of library to import.
@import "compass/css3/border-radius";
@import "compass/utilities/general/clearfix";

Compass


Compass is another framework that integrate SCSS and CSS grid framework like blueprint,
that provide you build in CSS layout, ie hack and other support. Compass is well integrated with rails.

using compass:

gem install compass
    compass init (under rails directory)

will create directory in app/stylesheets

compass compile

can compile into public/stylesheets directory

more reference for compass library

Backbone.js - MVC framework for front-end javascript

What is Backbone.js?


Backbone is a framework for front-end JavaScript, unlike jQuery focus on easier DOM manipulation and event binding, backbone provide a structure for separating data model and DOM, just like a MVC framework separate model, view and controller. Make heavy JavaScript application easier to develop and maintain.

Why Backbone?


In jQuery, we will write a sequence of chain selector for assign data model to DOM element like:

var article = {
  author:"Joe",
  content: "testing"
};
$('#article').click(function(event){
  $(this).find('.content').text(article.content);
});
For backbone, it provide the Model class and View class, which is the main two element of backbone.
var Article = Backbone.Model;

var article = new Article({
  author:"Joe",
  content: "testing"
});

var ArticleView = Backbone.View.extend({
  el: $('#article'),
  initialize: function(){
    _.bindAll(this,'updateContent');
    this.model.bind('change',this.updateContent);
  },
  events: {
    "click .content" : "updateContent"
  },
  updateContent: function(){
    this.$('.content').text(this.model.get("content"));
  }
});

var articleView = new ArticleView({model:article});
OK, it's seen like a completely overwork, that's my first thought when I see a clientside MVC framework too, but we have to dig further to understand why people create it.

Event Binding


First, it separate the data model and view - which include event handle and DOM element, we can easily bind data model in view like:
this.model.bind('change',this.updateContent);
It means when the data model change, the view will be automatically updated to DOM element.

Also, backbone provide literal event binding:
events:{
  "click .content": "updateContent"
}
which bind the "click" event to ".content" class, trigger "updateContent" function in current view.
It's useful when binding multiple events.

Restful synchronization


Furthermore, the backbone provide a RESTful format API for synchronize data model with server.
every model class in backbone have a corresponding url for synchronize, and when the "model.save" or "model.fetch" method is called, the model will make an Ajax request to update data with server.
For example:
article.save({author:"John"});
will first find article.sync method, if undefined, call Backbone.sync.
The sync method will make an ajax request to server, and update model, trigger event and update to view.

the url of model is defined by RESTful API:

  • create -> POST /model
  • read -> GET /model[/id]
  • update -> PUT /model/id
  • delete -> DELETE /model/id

and we can also change it by overwrite url parameter

Dependency


backbone.js depend on underscore.js and jQuery/Zepto library, since it is only a 3.9k framework focus on the structure of JavaScript application.

Collection and Controller

backbone provide Collection, which is the collection of Backbone.Model,
the Controller in backbone is more like the route map in MVC framework, it provide clientside fragment url routing, eg. "/#article/12" match "article(id)". So the url can be recorded and bookmarked by browser.

Template

In Backbone, we can create template in view.
In that way we can add and remove multiple view and render with template.
The underscore.js provide template engine or we can use other engine too.

In view:
render:function(){
    var template = "
<%=content %>
"; $(this.el).html( this.template(this.model.toJSON()) ); return this; }

Conclusion


JavaScript MVC framework is good for rich client application and also can keep your javascript cleaner.
But whether to use it depend on how much script in your application, for small page, the MVC is total overhead, but it is good for large scale page like Mail or Desktop like application.

More

Backbone
Sample todo application
Annotated source

[Note] Start first instance on Amazon Web Service EC2

How-to guide by Amazon
http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/

Amazon have become the largest cloud service company that provide compute instance and stroage
in their data center, that we can rent those computing resource as instances.

What's EC2?
Elastic Compute Cloud, the amazon computing service, we can rent an instance and run service on it as a virtual machine.

Amazon also have other service like S3 - simple storage service , is a storage service that you can upload file and let other people download. S3 provide auto bitTorrent support for big files.

Start an Instance

Login Amazon Aws console , choose EC2 tag, press "launch instance button"

1. Choose Instance Type: AMI(amazon machine image)
Default has Amazon custom Linux, Suse Linux and Windows Server 2003, both 32bit and 64bit.
There's also community AMI you can choose (which have CentOS and Ubuntu)

Read ubuntu document to find official AMI for ubuntu: https://help.ubuntu.com/community/EC2StartersGuide

ami-06ad526f for free micro instance supported Ubuntu 11.04 , check the Star mark for free support or not.
The root device ebs means the data will be saved in ebs service by default, which will not disappear after shutdown,

2. Select number of instance, instance type (related to money, micro is free)

3. Advance Instance Option: kernel, ramdisk id, monitoring, import user data shutdown behavior
you can import your userdata as text or file, that's useful when setting up multiple instances, you don't have to set user separately.

4.key-value tag to administrate multiple instances, and help to manage
ex: Owner = Jimmy
Admin = Jimmy
Service = Redmine
Stack = Development

5.choose key-pair to login with ssh , pem format (see below for how to login)

6.choose security group
Decided which incoming network traffic should be delivered to your instance
- access web traffic on port 80
- Its like the firewall setting, need to add every open port for usage (black-listed)
- SSH:22, windows RDP(Remote Desktop Protocol)
- source : 0.0.0.0/0 means no restriction on ip/submask
- 192.168.2.0/24 means restriction on 192.168.2 sub-area

How to login?


pem: public key of a specific certificate. Apache use this kind of certificate.
In apache installs, this frequently resides in /etc/ssl/servercerts.
it is also called X.509 Certificates

terminal:
# ssh -i ~/.ssh/XXX.pem root@ec2-##-##-##-##.compute-1.amazonaws.com

connection in windows using Putty:
generate private key from .pem file using puttygen,
choose Load => XXX.pem
then save private key XXX.ppk


Connection with putty under windows
choose connection => auth => load private key


More on aws:

EC2 command line tool: using command line to manage EC2 Instance
need to apply X.509 keypair for Amazon EC2 AMI Tools,
Amazon Web Services > Your Account > Security Credentials > X.509 Certificate

Watchr : simple continuous testing tool

Watchr is a pretty cool and simple tool for saving developer's time.

According to the preject description, watchr is:
Agile development tool that monitors a directory tree, and triggers a user defined action whenever an observed file is modified. Its most typical use is continuous testing, and as such it is a more flexible alternative to autotest.

But moreover, Watchr can be used on every simple task that need to execute a file, like markdown generate, coffee script compile, and the syntax is so simple to add those task in watchr script.

The syntax is like:

watch 'regular expression' { |matched_file| action_for matched_file }

#listen to all file and print filename when it modified
watch('.*') {|match| puts match[1]}

#listen to ruby file and run test
watch('lib/(.*)\.rb') {|match| system("ruby test/test_#{match[1]}.rb") }

#match[0] is full filename, match[1] is filename without extname.

running under command:
watchr script_name

Continous Testing


Continous Testing is a concept born from MIT Program Analysis Group,
It improve the Test Driven Development, which is auto run the corresponding test
in TDD right after the code saved. In this way, the test time lag will be reduced to zero,
and programer won't need to run the test to know the program is work or not. Makes testing become natural behavior in development.

Refers


ihower's rails3 watchr script template
Doc generate template from watchr project itself (dog fooding)

mini BDD Framework in CoffeeScript

Rails 3.1 is default supporting Coffee-Script,

This might be controversial, but basically I think it is a right move,
since rails development philosophy is always simplify developer's life.
And coffee script sure is.


compare the following code with javascript and coffee script:
describe('spec in javascript', function(){
  it('should return true in javascript',function(){
    return 1===1;
  });
});

//in coffee script
describe 'spec in coffeescript', ->
  it 'should return true in coffeescript',->
    1 is 1

You can see how the syntax has been simplified and easy to read.

Inspired by A unit test framework in 44 lines of ruby, I want to write a test framework in coffeescript to show the good of it.

Here's the work:
dsl =
  tests : {}
  it : (description,test) ->
    @tests[description] = test
  parse:(block)->
    block.call(dsl)
    @tests

class Executor
  constructor: (@description,@tests) ->
  tests : {}
  success : 0
  fail : 0
  count : 0
  run:()->
    console.log(@description + " ::")
    @execute desc,test for desc,test of @tests
    console.log("Executed #{@count} tests: #{@success} success, #{@fail} fail")

  execute : (desc,test) ->
    test_result = test()
    if test_result is yes than @success += 1 else @fail += 1
    @count += 1
    console.log(" --"+ desc + " is "+ test_result)

exports.describe = (description,block) ->
  executor = new Executor(description,dsl.parse(block))
  executor.run()

with the following testcase

spec = require './nspec'

spec.describe 'hello coffee test', ->

  @it 'should be true', ->
    1 is 1

  @it 'should fail', ->
    1 is 2

Basically the describe function contains all tests in callback,
and will parse all the testcase by
block.call(dsl)
which inject the dsl functions as the "this" object in block, and the "it" syntax will collect the test functions to a map object.
afterward, Executor will execute all tests and print out results.

During the implementation, I can't find the way to remove that nasty @ before test function 'it'
without declaring global. I am still working on it, there's a solution that you can execute test
by calling node.js child_process "coffee spec.coffee"(from coffee-spec), but that will be too complex for this. Jasmine didn't have this problem, let me know if anyone got the answer, or I will figure it out later :p.

Foursquare API with oauth2 gem

The oauth things is pretty complex, here is some notes that may avoid you fall into the same pitfall as me.

You can read the whole spec here.

But basically, it provide a interface let website can access the user's data in other website.
User will first be redirect to that website, click confirm, and redirected back to the callback page.

In the back end, the process of server is:
1.Send request to target website for token, with the server's client_id & secret_id
2.Redirect user to authorize page with token (and callback url)
3.After user confirm, user will be redirect to the callback page with a access_token
4.Save the access_token, and free to call target server for user data.

However, using gem to manage those things seen like a smart way, but still, it may not work correctly because of some error:

#pitfall 1

Check the api is using oauth or oauth2,
which is different when choosing the oauth gem.

#pitfall 2

check the oauth_path, access_token_path is correct
the default setting of gem may not work with the api you choose.

#pitfall 3

check the api address,
in foursquare, the authorize url is : https://foursquare.com/oauth2/authorize
however, the api is not under the same subdomain, is under https://api.foursquare.com/

make sure those setting is correct, and you will feel the sweet of oauth!

here's the code with sinatra:

require 'sinatra'
require 'oauth2'

get '/auth' do
  redirect to(client.web_server.authorize_url(:redirect_uri =>
                                              "http://myhost/callback"))
end

get '/callback' do
  #make sure the access token is named "code"
  access_token = client.web_server.get_access_token(params[:code],
                                      :redirect_uri => "http://myhost/callback")
  access_token.get('https://api.foursquare.com/v2/users/self')
  # save your access token in session or db...
end

def client
  client ||= OAuth2::Client.new(
  YOUR_CLIENT_ID,YOUR_SECRET_ID,
  :site => 'https://foursquare.com',
  :authorize_path => '/oauth2/authorize',
  :access_token_path => '/oauth2/access_token')
end

HTML5 push state

Recently I was trying to make a slide pages effect, and I realize there are some obstacle to let the browser work properly on next/back page. because you can only change the #hash value of url but the real url without redirect, the old ajax problem.

But wait a minute, is the github use the ajax page slide effect and work perfectly? After a peek on the source, I found they are using the html5 pushstate api on webkit and ff4, which can let you change the url without actually redirect the page.

sample:
$(function(){
  //check if the browser support it.
  $.get('/new_page',function(data){
    if(history.pushState){
      //push the url to the browser history, with state object and title.
      history.pushState({isAjax:true},"push the state"), 'new_page');
    }
    //update the data...
  });
  //popstate event will triggered whenever the url changed
  //but the page won't reload if url is pushed into history
  //so you have to update page yourself or reload it.
  $(window).bind("popstate",function(e){
    if (e.state.isAjax) {
      //make the ajax call for update page
    }
  });
});

try it yourself by typing
history.pushState({},"test","/test:);
in your browser console, and you'll see the effect.

reference: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

[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/

[Style Guide]Google Javascript Style Guide的結語

BE CONSISTENT.

If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too.

"如果妳在修改程式碼, 花幾分鐘看一下其他程式碼並了解它的風格.
如果他們在算數運算子周圍用了空格,妳也該用,如果他們用橫線圍住註解,妳也該用橫線圍注你的注解"

The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you're saying rather than on how you're saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Avoid this.

"這個guideline的重點是提供一份共同的字彙庫,讓每個人能專注在妳說什麼而不是妳怎麼說的.我們提出了一份共通的style規則讓大家能了解程式碼的規則,但是小部分的風格也很重要,如果妳的程式碼和周圍的檔案看起來完全不同,這會讓看的人失去了他們閱讀程式碼的節奏感,要盡量避免"