Thursday, 17 December 2015

nginx: See Active connections / Connections Per Seconds

How do I monitor my nginx server status and connections requests per seconds under Linux or Unix like operating systems?

nginx server has a module called HttpStubStatusModule. This module provides the ability to get some status from nginx. You will get the following information:
  1. Number of all open connections.
  2. Stats about accepted connections.
  3. Connections per second and so on.

Configuration

Edit nginx.conf file:
# vi nginx.conf
Add or append the following in context location:
 
   location /nginx_status {
        # Turn on stats
        stub_status on;
        access_log   off;
        # only allow access from 192.168.1.5 #
        allow 192.168.1.5;
        deny all;
   }
 
Save and close the file. Reload nginx server:
# service nginx reload
OR
# nginx -s reload

Test it

Open a web-browser and type the following url:
http://your-domain-name-here/nginx_status
OR
http://ip.address.here/nginx_status
Sample outputs:
Fig.01: nginx Status Monitor with HttpStubStatusModule
Fig.01: nginx Status Monitor with HttpStubStatusModule

Where,
  1. 586 = Number of all open connections
  2. 9582571 = Accepted connections
  3. 9582571 = Handled connections
  4. 21897888 = Handles requests




Wednesday, 16 December 2015

RubyLex

@scanner = RubyLex.new
@scanner.exception_on_syntax_error = false
a = @scanner.set_prompt do; puts 1; end
=> #<Proc:0x007f845529df70@(pry):37>
a.call
1
=> nil
view raw gistfile1.txt hosted with ❤ by GitHub

Sunday, 13 December 2015

Thursday, 10 December 2015

Mac OS X tmux config Raw

### INSTALLATION NOTES ###
# 1. Install Homebrew (https://github.com/mxcl/homebrew)
# 2. brew install zsh
# 3. Install OhMyZsh (https://github.com/robbyrussell/oh-my-zsh)
# 4. brew install reattach-to-user-namespace --wrap-pbcopy-pbpaste && brew link reattach-to-user-namespace
# 5. Install iTerm2
# 6. In iTerm2 preferences for your profile set:
# Character Encoding: Unicode (UTF-8)
# Report Terminal Type: xterm-256color
# 7. Put itunesartist and itunestrack into PATH
#
#
# Usage:
# - Prefix is set to Ctrl-a (make sure you remapped Caps Lock to Ctrl)
# - All prefixed with Ctrl-a
# - Last used window: /
# - Last used pane: ;
# - Vertical split: v
# - Horizontal split: s
# - Previous window: [
# - Next window: ]
# - Choose session: Ctrl-s
# - Quick window: Ctrl-q
set-option -g default-command "reattach-to-user-namespace -l zsh"
### LOOK & FEEL ###
set -g default-terminal "xterm-256color"
# default statusbar colors
set-option -g status-bg colour235
set-option -g status-fg colour179
set-option -g status-attr default
# default window title colors
set-window-option -g window-status-fg colour244
set-window-option -g window-status-bg default
# active window title colors
set-window-option -g window-status-current-fg colour166
set-window-option -g window-status-current-bg default
set-window-option -g window-status-current-attr bright
# pane border
set-option -g pane-border-fg colour235
set-option -g pane-active-border-fg colour240
# pane number display
set-option -g display-panes-active-colour colour33
set-option -g display-panes-colour colour166
# clock
set-window-option -g clock-mode-colour colour64
# status bar right contents
set -g status-right-length 65
set -g status-right "#[fg=colour187][#(itunesartist) - #(itunestrack)] #[fg=default][%H:%M %e-%b-%Y]"
set -g status-interval 5
set-option -g mouse-select-pane on
set-option -g mouse-select-window on
set-option -g mode-mouse on
set-window-option -g utf8 on
set-option -g status-keys vi
set-option -g mode-keys vi
#no command delay
set -sg escape-time 0
#count windows and panes from 1
set -g base-index 1
setw -g pane-base-index 1
### KEYS ###
#using C-a as prefix
unbind C-b
set-option -g prefix C-a
bind C-a send-prefix
unbind /
bind / last-window
unbind %
bind s split-window -v
unbind '"'
bind v split-window -h
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
unbind {
bind { swap-pane -D
unbind }
bind } swap-pane -U
unbind r
bind r source-file ~/.tmux.conf; display "Reloaded"
bind Escape copy-mode
bind p paste-buffer
unbind [
bind [ previous-window
unbind ]
bind ] next-window
unbind o
bind o select-pane -t :.-
bind C-q command-prompt -I "htop" -p "Quick window command: " "new-window '%%'"
bind -t vi-copy 'v' begin-selection
bind -t vi-copy 'y' copy-selection
bind C-c run "tmux save-buffer - | pbcopy"
bind C-v run "tmux set-buffer \"$(pbpaste)\"; tmux paste-buffer"
bind C-s choose-session
view raw .tmux.conf hosted with ❤ by GitHub
#!/usr/bin/osascript
on run
set info to ""
tell application "System Events"
set num to count (every process whose name is "iTunes")
end tell
if num > 0 then
tell application "iTunes"
if player state is playing then
set info to artist of current track
end if
end tell
end if
return info
end run
view raw itunesartist hosted with ❤ by GitHub
#!/usr/bin/osascript
on run
set info to ""
tell application "System Events"
set num to count (every process whose name is "iTunes")
end tell
if num > 0 then
tell application "iTunes"
if player state is playing then
set info to name of current track
else
set info to "Not Playing."
end if
end tell
end if
return info
end run
view raw itunestrack hosted with ❤ by GitHub
https://gist.github.com/v-yarotsky/2157908

Sunday, 6 December 2015

The Recipe for the World's Largest Rails Monolith by Akira Matsuda

The Recipe for the World's Largest Rails Monolith


by Akira Matsuda



Kage (kah-geh) is a shadow proxy server to duplex HTTP requests

Kage (kah-geh) is a shadow proxy server to duplex HTTP requests


https://github.com/cookpad/kage

Kage (kah-geh) is an HTTP shadow proxy server that sits between clients and your server(s) to enable "shadow requests".
Kage can be used to duplex requests to the master (production) server and shadow servers that have newer code changes that are going to be deployed. By shadowing requests to the new code you can make sure there are no big/surprising changes in the response in terms of data, performance and database loads etc.
Kage is built with EventMachine and em-proxy and all shadow requests are done asynchronously, while responses from master are sent back to the client without blocking the network, so clients will never notice any delays even when shadow traffic is made.
You can customize the behavior of Kage with simple callbacks, when it chooses which backends to send shadow requests to (or not at all), appends or deletes HTTP headers per backend, and examines the complete HTTP response (including headers and body).

RRRSpec

RRRSpec enables you to run RSpec in a distributed manner.
This is developed for the purpose to obtain the fault-tolerance properties to process-failures, machine-failures, and unresponsivenss of processes in the automated testing process.
RRRSpec is used in production as a CI service, running 60+ RSpec processes concurrently, and it undergoes those failures, which include lots of rb_bugs, assertion errors, and segmentation faults.

https://github.com/cookpad/rrrspec

SwitchPoint

Switching database connection between readonly one and writable one.


https://github.com/eagletmt/switch_point


Suppose you have 4 databases: db-blog-master, db-blog-slave, db-comment-master and db-comment-slave. Article model and Category model are stored in db-blog-{master,slave} and Comment model is stored in db-comment-{master,slave}.

Quine Relay

This is a Ruby program that generates Scala program that generates Scheme program that generates ...(through 100 languages in total)... REXX program that generates the original Ruby code again.

https://github.com/mame/quine-relay

How Digital Disruption Is Redefining Industries


Digital Vortex
How Digital Disruption Is Redefining Industries

http://www.imd.org/uupload/IMD.WebSite/DBT/Digital_Vortex_06182015.pdf

Friday, 27 November 2015

Riemann monitors distributed systems.

Riemann streams are just functions which accept an event. Events are just structs with some common fields like :host and :service You can use dozens of built-in streams for filtering, altering, and combining events, or write your own.
Since Riemann's configuration is a Clojure program, its syntax is concise, regular, and extendable. Configuration-as-code minimizes boilerplate and gives you the flexibility to adapt to complex situations.

I wrote Riemann for operations staff trying to keep a large, dynamic infrastructure running with unreliable but fault-tolerant components. For engineers who need to understand the source of errors and performance bottlenecks in production. For everyone fed up with traditional approaches; who want something fast, expressive, and powerful.
See problems faster

Traditional monitoring systems run polling loops every five minutes, or roll up metrics on a minutely basis. In a Riemann infrastructure, clients (including stand-alone pollers) *push* their events to Riemann, which makes them visible within milliseconds. Low latencies let you see outages faster--and know the instant you've fixed the problem.
Throughput depends on what your streams *do* with events, but a stock Riemann config on commodity x86 hardware can handle *millions* of events per second at sub-ms latencies, with 99ths around 5ms. Riemann is fully parallel and leverages Clojure and JVM concurrency primitives throughout.



http://riemann.io/
Developer Environment:


Developers are all switching between tabs to view deployments, logs, commits etc!

My next project is to make a "Developers Physical Environment"


Using a Raspberry Pi connect multiple screens and display on each

  • 1. Server logs, 
  • 2. Git commits
  • 3.Newrelic performance 
  • 4. Deployemtn Logs

and more!
Next weekend project todo:

Sunday, 22 November 2015

AWS Architecture Center


The AWS Architecture Center is designed to provide you with the necessary guidance and application architecture best practices to build highly scalable and reliable applications in the AWS cloud.



https://aws.amazon.com/architecture/

nginx

test config
$ nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
It is also possible to enable the debugging for a particular IP address:
events {
debug_connection 127.0.0.1;
}
Print the nginx version.
$ nginx -v
nginx version: nginx/1.8.0
Print the nginx version, compiler version, and configure script parameters.
$ nginx -V
nginx version: nginx/1.8.0
built by clang 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
built with OpenSSL 1.0.2d 9 Jul 2015
TLS SNI support enabled
configure arguments: --prefix=/usr/local/Cellar/nginx/1.8.0 --with-http_ssl_module --with-pcre --with-ipv6 --sbin-path=/usr/local/Cellar/nginx/1.8.0/bin/nginx --with-cc-opt='-I/usr/local/Cellar/pcre/8.37/include -I/usr/local/Cellar/openssl/1.0.2d_1/include' --with-ld-opt='-L/usr/local/Cellar/pcre/8.37/lib -L/usr/local/Cellar/openssl/1.0.2d_1/lib' --conf-path=/usr/local/etc/nginx/nginx.conf --pid-path=/usr/local/var/run/nginx.pid --lock-path=/usr/local/var/run/nginx.lock --http-client-body-temp-path=/usr/local/var/run/nginx/client_body_temp --http-proxy-temp-path=/usr/local/var/run/nginx/proxy_temp --http-fastcgi-temp-path=/usr/local/var/run/nginx/fastcgi_temp --http-uwsgi-temp-path=/usr/local/var/run/nginx/uwsgi_temp --http-scgi-temp-path=/usr/local/var/run/nginx/scgi_temp --http-log-path=/usr/local/var/log/nginx/access.log --error-log-path=/usr/local/var/log/nginx/error.log --with-http_gzip_static_module
view raw gistfile1.txt hosted with ❤ by GitHub

Thursday, 19 November 2015

lodash

lodash v3.10.1


A JavaScript utility library delivering consistency, modularity, performance, & extras.



https://lodash.com/

ssh

ssh-agent -s #start the agent
eval `ssh-agent -s` #or this to start
ssh-add -K ~/.ssh/id_rsa #add
ssh-add -l #list identities
ssh -vT git@github.com
ssh-add -D #remove existing identities
ssh-agent #copy the lines & run them
ssh-add #uses the output from above
ssh-agent -k #kill the agent
ps -ef | grep ssh-agent
view raw gistfile1.txt hosted with ❤ by GitHub

Tuesday, 17 November 2015

ps tree OSX

brew install pstree
or Htop

assign value from irb to bash

#Bash:
function get_partner_token {
echo $(cd /Users/Ioannis/project/api && bundle exec pry -r ./app/setup -e "puts Partner.last.token; exit") | grep -oE '[^ ]+$'
}
Start rails server
LOCAL_PARTNER_TOKEN=$(get_partner_token) rails s

Friday, 13 November 2015

md file table of contents

I created two options to generate a toc for github-flavored-markdown:
DocToc Command Line Tool (source) requires node.js

Installation:
npm install -g doctoc
Usage:
doctoc . to add table of contents to all markdown files in the current and all sub directories.


http://stackoverflow.com/questions/9721944/automatic-toc-in-github-flavoured-markdown

Thursday, 12 November 2015

Inspect rack ENV Raw

class EnvInspector
def self.call(env)
[200, {}, env.inspect]
end
end
Rack::Server.start :app => EnvInspector
{
"SERVER_SOFTWARE"=>"thin 1.4.1 codename Chromeo",
"SERVER_NAME"=>"localhost",
"rack.input"=>#<StringIO:0x007fa1bce039f8>,
"rack.version"=>[1, 0],
"rack.errors"=>#<IO:<STDERR>>,
"rack.multithread"=>false,
"rack.multiprocess"=>false,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"GET",
"REQUEST_PATH"=>"/favicon.ico",
"PATH_INFO"=>"/favicon.ico",
"REQUEST_URI"=>"/favicon.ico",
"HTTP_VERSION"=>"HTTP/1.1",
"HTTP_HOST"=>"localhost:8080",
"HTTP_CONNECTION"=>"keep-alive",
"HTTP_ACCEPT"=>"*/*",
"HTTP_USER_AGENT"=>
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11",
"HTTP_ACCEPT_ENCODING"=>"gzip,deflate,sdch",
"HTTP_ACCEPT_LANGUAGE"=>"en-US,en;q=0.8",
"HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"HTTP_COOKIE"=> "_gauges_unique_year=1; _gauges_unique_month=1",
"GATEWAY_INTERFACE"=>"CGI/1.2",
"SERVER_PORT"=>"8080",
"QUERY_STRING"=>"",
"SERVER_PROTOCOL"=>"HTTP/1.1",
"rack.url_scheme"=>"http",
"SCRIPT_NAME"=>"",
"REMOTE_ADDR"=>"127.0.0.1",
"async.callback"=>#<Method: Thin::Connection#post_process>,
"async.close"=>#<EventMachine::DefaultDeferrable:0x007fa1bce35b88
}
view raw gistfile1.txt hosted with ❤ by GitHub

Monday, 2 November 2015

Detect file encoding to current dir .rb files

encodings = []
not_utf8 = []
Dir.glob(Dir.new(".").path + '/**/*.rb') do |file|
contents = File.read(file)
detection = CharlockHolmes::EncodingDetector.detect(contents)
encodings << detection[:encoding]
not_utf8 << {file: file, detection: detection} unless "UTF-8" == detection[:encoding]
end
pp encodings.uniq
pp not_utf8
view raw gistfile1.rb hosted with ❤ by GitHub

Wednesday, 21 October 2015

using ansible

Download and install VirtualBox
Download and install vagrant

$ vagrant init tower http://vms.ansible.com/ansible-tower-2.3.1-virtualbox.box
$ vagrant up
$ vagrant ssh


Read more : http://www.ansible.com/tower-trial

Ioannis@192 ~ $ vagrant init tower http://vms.ansible.com/ansible-tower-2.3.1-virtualbox.box
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on

`vagrantup.com` for more information on using Vagrant.



Ioannis@192 vagrant $ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'tower' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'tower' (v0) for provider: virtualbox
    default: Downloading: http://vms.ansible.com/ansible-tower-2.3.1-virtualbox.box
==> default: Successfully added box 'tower' (v0) for 'virtualbox'!
==> default: Importing base box 'tower'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1445436657938_42127
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: 
    default: Guest Additions Version: 4.3.26
    default: VirtualBox Version: 5.0
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...

    default: /vagrant => /Users/Ioannis/Development/vagrant




Ioannis@192 vagrant $ vagrant ssh
Last login: Mon Oct  5 22:04:50 2015 from 10.0.2.2

  Welcome to Ansible Tower!

  Log into the web interface here:

    https://10.42.0.42/

    Username: admin
    Password:  

  The documentation for Ansible Tower is available here:

    http://www.ansible.com/tower/

  For help, email support@ansible.com
-bash: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory

[vagrant@ansible-tower ~]$ 

Saturday, 10 October 2015

Το κομμάτι που λείπει συναντά το μεγάλο Ο

Η ιστορία μιλά για τη μοναξιά και την ανάγκη να ανήκεις. Την ανάγκη να βρεις αυτό που σε συμπληρώνει, ώστε να "κυλήσεις" στη ζωή μαζί του. Μιλά για την εναγώνια αναζήτηση αυτού του άλλου, που θα έρθει ως «από μηχανής θεός», να κλείσει το μέσα μας κενό, να δώσει νόημα στη ζωή μας. Αυτό το άλλο, που πιστεύουμε, ότι θα μας αναγνωρίσει και θα το αναγνωρίσουμε "μαγικά".

Στη διάρκεια αυτής της αναζήτησης θα κάνουμε πολλά: θα μασκαρευτούμε, θα τρομάξουμε, θα μπερδευτούμε, θα γελοιοποιηθούμε, θα ελπίσουμε... Και τελικά, κάποτε, θα βρούμε το ιδανικό μας άλλο, αυτό που μας χωρά και το χωράμε. Και ευτυχώς θα αρχίσουμε επιτέλους να «κυλάμε»...να ζούμε...Τι κρίμα μόνο, που κανείς δεν μας είπε και εμείς ποτέ δεν σκεφτήκαμε, ότι κυλώντας...αλλάζεις! Και έτσι αυτό που ξεκίνησε σαν απόλυτο ταίριασμα, στην πορεία αρχίζει να μας στενεύει και να το στενεύουμε...Και μετά τι....Μετά πάλι από την αρχή: προσμονή και μοναξιά... Μέχρι τη στιγμή που θα εμφανιστεί κάτι, κάποιος, που τίποτα δεν ζητά και τίποτα δεν του λείπει, (ένα Μεγάλο, ολοστρόγγυλο, πλήρες Ο), για να μας κάνει την απλή ερώτηση:

"Γιατί δεν κυλάς μόνο σου;"
"Μόνο μου; ένα Κομμάτι-που-λείπει (τριγωνικής μορφής) δεν μπορεί να κυλήσει μόνο του".
"Αλήθεια, προσπάθησες ποτέ;" ρώτησε το Μεγάλο Ο.
"Οι γωνίες μου είναι πολύ μυτερές" είπε το Κομμάτι-που-λείπει. "Δεν είμαι φτιαγμένο για να κυλάω μόνο μου!"
"Οι γωνίες και τα σχήματα αλλάζουν" είπε το Μεγάλο Ο...
"Αλλάζουν";

Σιωπή...Περισυλλογή...Απόπειρα....Προσπά­θεια....Κίνηση....Και επιτέλους αρχίζει το ταξίδι...η μεταμόρφωση...η ζωή...

"Το Κομμάτι που λείπει συναντά το Mεγάλο Ο", μιλά απλά και αληθινά για αυτό που όλοι ξέρουμε, αλλά ελάχιστοι κατανοούμε και ακόμα ελαχιστότεροι κάνουμε πράξη στη ζωή μας: η ολοκλήρωση και ευτυχία μας, είναι πρωτίστως μια προσωπική υπόθεση. Κανείς δεν μπορεί να μας την επιβάλει ή ακόμα και να μας τη χαρίσει «έξωθεν». Και ίσως δεν γίνεται αλλιώς: για να συν-υπάρξουμε κάποτε με κάποιον ή κάτι, πρέπει πρώτα να υπάρξουμε σαν αυτοκαθοριζόμενες οντότητες. Η συν-ύπαρξη χρειάζεται δυο...όχι δυο μισά, αλλά δυο ολόκληρα. Δυο Μεγάλα ολοστρόγγυλα Ο, που τίποτα δεν χρειάζονται και τίποτα δεν τους λείπει...Δύο ολόκληρα που συμπορεύονται από καθαρή αγάπη. Όχι από ανάγκη ούτε από συμφέρον. Δυο ολόκληρα που τα ενώνει η επιλογή. Όχι η ελπίδα, ούτε ο φόβος.... Αν έτσι αντικρίσουμε τη ζωή μας, ίσως πάψουμε να μεμψιμοιρούμε, να τα βάζουμε με τους άλλους, να είμαστε απαθής ή μοιρολάτρες. Αν δεν περιμένουμε την ευτυχία να μας χτυπήσει την πόρτα, αλλά τραβήξουμε εμείς κατά κει, αν μη τι άλλο, σίγουρα στο τέλος, όποιο κι αν είναι, θα έχουμε κάνει ένα πολύ ενδιαφέρον ταξίδι!

Thursday, 27 August 2015

Saturday, 4 July 2015

User TimeZones

#1 .ApplicationController
class ApplicationController < ActionController::Base
around_filter :set_time_zone
def set_time_zone(&block)
time_zone = current_user.shop.try(:timezone) || 'UTC'
Time.use_zone(time_zone, &block)
end
end
#2. Generate migration
class AddTimezoneToShops < ActiveRecord::Migration
def change
add_column :shops, :timezone, :string, :default => 'Europe/Athens'
end
end
#3. Set a form
<div class="form-group">
<%= f.label :timezone, :class => "col-lg-2 control-label" %>
<div class="col-lg-10">
<%= f.input :timezone, :collection => Timezone::Zone.names, :label => false ,:include_blank => false,
:class => "form-control" %>
</div>
</div>
view raw gistfile1.rb hosted with ❤ by GitHub

Thursday, 21 May 2015

YBoss generate Oauth url

require 'uri'
require 'cgi'
require 'openssl'
require 'base64'
module YBoss
class Oauth
attr_accessor :consumer_key, :consumer_secret, :token, :token_secret, :req_method,
:sig_method, :oauth_version, :callback_url, :params, :req_url, :base_str
def initialize
@consumer_key = '234234234--'
@consumer_secret = '167234234'
@token = ''
@token_secret = ''
@req_method = 'GET'
@sig_method = 'HMAC-SHA1'
@oauth_version = '1.0'
@callback_url = ''
end
# openssl::random_bytes returns non-word chars, which need to be removed. using alt method to get length
# ref http://snippets.dzone.com/posts/show/491
def nonce
Array.new( 5 ) { rand(256) }.pack('C*').unpack('H*').first
end
def percent_encode( string )
# ref http://snippets.dzone.com/posts/show/1260
return URI.escape(string,
Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")
).gsub('*', '%2A').gsub('\'','%27').gsub('(','%28').gsub(')','%29').gsub('!','%21')
end
# @ref http://oauth.net/core/1.0/#rfc.section.9.2
def signature
key = percent_encode( @consumer_secret ) + '&' + percent_encode( @token_secret )
# ref: http://blog.nathanielbibler.com/post/63031273/openssl-hmac-vs-ruby-hmac-benchmarks
digest = OpenSSL::Digest.new( 'sha1' )
hmac = OpenSSL::HMAC.digest( digest, key, @base_str )
# ref http://groups.google.com/group/oauth-ruby/browse_thread/thread/9110ed8c8f3cae81
Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
end
# sort (very important as it affects the signature), concat, and percent encode
# @ref http://oauth.net/core/1.0/#rfc.section.9.1.1
# @ref http://oauth.net/core/1.0/#9.2.1
# @ref http://oauth.net/core/1.0/#rfc.section.A.5.1
def query_string
pairs = []
@params.sort.each { | key, val |
pairs.push( "#{ percent_encode( key ) }=#{ percent_encode( val.to_s ) }" )
}
pairs.join '&'
end
# organize params & create signature
def sign( parsed_url )
@params = {
'oauth_consumer_key' => @consumer_key,
'oauth_nonce' => nonce,
'oauth_signature_method' => @sig_method,
'oauth_timestamp' => Time.now.to_i.to_s,
'oauth_version' => @oauth_version
}
# if url has query, merge key/values into params obj overwriting defaults
if parsed_url.query
CGI.parse( parsed_url.query ).each do |k,v|
if v.is_a?(Array) && v.count == 1
@params[k] = v.first
else
@params[k] = v
end
end
# @params.merge! CGI.parse( parsed_url.query )
end
# @ref http://oauth.net/core/1.0/#rfc.section.9.1.2
@req_url = parsed_url.scheme + '://' + parsed_url.host + parsed_url.path
# create base str. make it an object attr for ez debugging
# ref http://oauth.net/core/1.0/#anchor14
@base_str = [
@req_method,
percent_encode( req_url ),
# normalization is just x-www-form-urlencoded
percent_encode( query_string )
].join( '&' )
# add signature
@params[ 'oauth_signature' ] = signature
return self
end
end
end
oauth = YBoss::Oauth.new
yahoo_url = "https://yboss.yahooapis.com/ysearch/web,ads?"
params = {
"q" => "dvd",
"ads.url" => "webiste.com",
"ads.TYPE" => "ddc_id",
"ads.Partner" => "ddc_partner"
}.map{|k,v| "#{k}=#{v}&"}.join.chop!
# }.to_param
base = URI.parse(yahoo_url + params )
yahoo_url + oauth.sign(base).query_string
view raw gistfile1.rb hosted with ❤ by GitHub

Thursday, 14 May 2015

Config Heroku unicorn for WEB_CONCURRENCY

# Using
# ruby '2.1.3'
# 'rails', '4.1.8'
# 1. Test unicorn in background and check the RSS memory
heroku run bash
unicorn -c config/unicorn.rb & # Run unicorn in the background
ps euf # Read RSS value for each worker, in kb - ie: 116040 ~ 116mb
# USER PID %CPU %MEM VSZ RSS TTY STAT START TIME
# u41100 3 0.0 0.0 109116 2028 ? S 16:59 0:00
# u41100 4 0.0 0.0 109916 2760 ? R 16:59 0:00
# u41100 5 0.0 0.0 106504 1276 ? R+ 16:59 0:00
# each instance uses 200mb~
#2. Change the WEB_CONCURRENCY Based on dyno type
# example x1 (500mb RAM) change the worker_processes to 2
# worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2)
# heroku change log https://devcenter.heroku.com/changelog-items/618
view raw gistfile1.sh hosted with ❤ by GitHub

Wednesday, 6 May 2015

Tuesday, 28 April 2015

OWASP Zed Attack Proxy Project - OWASP

The new tool i found 
The Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications.



Sunday, 26 April 2015

ActiveRecord::ProtectedModel

require "active_record"
require 'active_record/errors'
module ActiveRecord
class ProtectedModelError < ActiveRecordError #:nodoc:
def initialize
super("Cannot delete record because its protected")
end
end
module ProtectedModel
extend ActiveSupport::Concern
protected
def delete(*args)
raise ProtectedModelError.new
end
def destroy_all(*args)
raise ProtectedModelError.new
end
def destroy(*args)
raise ProtectedModelError.new
end
module ClassMethods
def delete_all(*args)
raise ProtectedModelError.new
end
end
end
end
class Query < ActiveRecord::Base
include ActiveRecord::ProtectedModel if Rails.env.production?
end
view raw gistfile1.rb hosted with ❤ by GitHub

run_later



New Script:
# MIT License Copyright (c) 2015 Ioannis Kolovos
# See License
#
# RunLater is a gem for running commands later.
# It saves the commands in a yaml file (`~/.run_later/commands.yaml`) and executed it when you call `perform`
#
# Usage:
#
# $ run_later queue --commands='brew upgrade && brew install phantomjs'
#
# Later:
#
# $ run_later perform
#
# Methods:
#
# $ run_later queue params # Adding commands
# $ run_later clean # remove ~/.run_later
# $ run_later perform # executes the queue
# $ run_later list # view queue
#
# For more details use:
#
# $ run_later help
#
#
# Sourcing:
#
# When you running system commands with Ruby, is using `sh` so you have to load sources like `~/.profile` or `.~/.bash_profile`
# Default loaded are: ["~/.profile", "~/.bash_profile"]
#
#
# Options:
#
#
# --commands='brew upgrade && brew install phantomjs' # Commands to execute
# --preload=~/.bash_profile ~/.rvmrc # Source files to be loaded before execution (separated by space)
# # Default: ["~/.profile", "~/.bash_profile"]
# --sudo, --no-sudo # If commands require sudo
# --env=foo:bar joe:doe # System variables to be set before execution (key:value separated by space)
#
#
# Example:
# $ run_later --commands='brew upgrade && brew install phantomjs' --sudo --env=foo:bar joe:doe --preload=~/.bash_profile ~/.rvmrc
#
#
view raw gistfile1.rb hosted with ❤ by GitHub
TODO:
Delete task if is success


https://github.com/msroot/run_later

Thursday, 23 April 2015

Delete all Cloudinary

Cloudinary::Api.delete_all_resources
view raw gistfile1.rb hosted with ❤ by GitHub

Image upload preview

// Html5
document.querySelector('#dropzone').addEventListener('drop', function(e) {
var reader = new FileReader();
reader.onload = function(evt) {
document.querySelector('img').src = evt.target.result;
};
reader.readAsDataURL(e.dataTransfer.files[0]);
}, false);
view raw gistfile1.js hosted with ❤ by GitHub

commandline-api

// Copy in clipboard
// Copies a string representation of the specified object to the clipboard.
var this_is = function() { return "crazy"}
copy(this_is())
// now paste!
// #crazy
// Select all images in page
$$('img')
// opens the debuger
debug(this_is())
// When the function specified is called, the debugger will be invoked and will break inside the function on the Sources panel allowing you to be able to step through the code and debug it.
dir(object)
// Displays an object-style listing of all the properties of the specified object. This method is an alias for the Console API's console.dir() method.
inspect(object/function)
inspect(document.body)
// Opens and selects the specified element or object in the appropriate panel: either the Elements panel for DOM elements and the Profiles panel for JavaScript heap objects.
// The following example opens the first child element of document.body in the Elements panel:
getEventListeners(object)
// Returns the event listeners registered on the specified object. The return value is an object that contains an array for each registered event type ("click" or "keydown", for example). The members of each array are objects that describe the listener registered for each type. For example, the following lists all the event listeners registered on the document object.
getEventListeners(document);
// monitor(function)
// When the function specified is called, a message is logged to the console that indicates the function name along with the arguments that are passed to the function when it was called.
function sum(x, y) { return x + y;}monitor(sum);
monitorEvents(object[, events])
// When one of the specified events occurs on the specified object, the Event object is logged to the console. You can specify a single event to monitor, an array of events, or one of the generic events "types" that are mapped to a predefined collection of events. See examples below.
// The following monitors all resize events on the window object.
monitorEvents(window, "resize");
undebug(function)
// Stops the debugging of the specified function so that when the function is called the debugger will no longer be invoked.
undebug(getData);
// unmonitor(function)
// Stops the monitoring of the specified function. Used in concert with monitor(fn).
unmonitor(getData);
// unmonitorEvents(object[, events])
// Stops monitoring events for the specified object and events. For example, the following stops all event monitoring on the window object:
unmonitorEvents(window);
values(object)
// Returns an array containing the values of all properties belonging to the specified object.
values(object);
// https://developer.chrome.com/devtools/docs/commandline-api#0-4
view raw gistfile1.js hosted with ❤ by GitHub

Wednesday, 22 April 2015

onLine?

var statusElem = document.getElementById('status')
setInterval(function () {
statusElem.className = navigator.onLine ? 'online' : 'offline';
statusElem.innerHTML = navigator.onLine ? 'online' : 'offline';
}, 250);
// better way
var addEvent = (function() {
if (document.addEventListener) {
return function(el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function(el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function() {
return fn.call(el, window.event);
});
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
addEvent(window, 'online', function () {
document.getElementById('vialistener').innerHTML = 'Online';
});
addEvent(window, 'offline', function () {
document.getElementById('vialistener').innerHTML = 'Offline';
});
view raw gistfile1.js hosted with ❤ by GitHub

Fetch

fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
// Post
fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
})
.then(json)
.then(function (data) {
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});
view raw gistfile1.js hosted with ❤ by GitHub

Simple image preview for image file uploads

$(window).load(function(){
/* image preview */
$('#photo_image').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL($('#photo_image')[0].files[0]);
oFReader.onload = function (oFREvent) {
$('#preview').html('<img src="'+oFREvent.target.result+'">');
$('#preview img').css({"max-width":"900px"});
};
});
});
view raw gistfile1.js hosted with ❤ by GitHub

Object.observe()

var model = {};
// Which we then observe
Object.observe(model, function(changes){
// This asynchronous callback runs
changes.forEach(function(change) {
// Letting us know what changed
console.log(change.type, change.name, change.oldValue);
});
});
Object {}
model.name = "yannos"
VM159:11 add name undefined
"yannos"
model.name = "yannis"
VM159:11 update name yannos
"yannis"
// If you don’t specify a list of accept types to O.o(), it defaults to the "intrinsic"
// object change types ("add", "update", "delete", "reconfigure", "preventExtensions"
// (for when an object becoming non-extensible isn’t observable)).
// Like earlier, a model can be a simple vanilla object
var model = {
name: 'yannis',
surname: 'kolovos'
};
// We then specify a callback for whenever mutations
// are made to the object
function observer(changes){
changes.forEach(function(change, i){
console.log(change);
})
};
// Which we then observe, specifying an array of change
// types we’re interested in
Object.observe(model, observer, ['delete']);
// without this third option, the change types provided
// default to intrinsic types
model.name = 'yannos';
// note that no changes were reported
VM562:4 "yannos"
delete model.name
VM562:4 Object {type: "delete", object: Object, name: "name", oldValue: "yannos"}
true
view raw gistfile1.js hosted with ❤ by GitHub

Monday, 20 April 2015

javascript console.table

console.table([{foo:"bar"}])
// prints table in console
alert(JSON.stringify(object, null, 4));
// alert object keys and values
view raw gistfile1.js hosted with ❤ by GitHub

Web Messaging or cross-document messaging

Web Messaging or cross-document messaging, is an API introduced in the WHATWG HTML5draft specification, allowing documents to communicate with one another across different origins, or source domains


Example[edit]

Consider we want document A located on example.net to communicate with document B located on example.com, which is contained within an iframe or popup window.[1] The JavaScript for document A will look as follows:
var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello B', 'http://example.com/');
The origin of our contentWindow object is passed to postMessage. It must match the origin of the document we wish to communicate with (in this case, document B). Otherwise, a security error will be thrown and the script will stop.[3] The JavaScript for document B will look as follows:
function receiver(event) {
 if (event.origin == 'http://example.net') {
  if (event.data == 'Hello B') {
   event.source.postMessage('Hello A, how are you?', event.origin);
  }
  else {
   alert(event.data);
  }
 }
}
window.addEventListener('message', receiver, false);
An event listener is set up to receive messages from document A. Using the origin property, it then checks that the domain of the sender is the expected domain. Document B then looks at the message, either displaying it to the user, or responding in turn with a message of its own for document A.[1]


http://en.wikipedia.org/wiki/Web_Messaging

rails validations validate html

# assume we have a :data attribute (an hstore hash) in our model that values have html
# data :hstore default({}), not null
validate :invalid_html?
def invalid_html?
self.data.each do |key, value|
doc = Nokogiri::HTML(value) {|config| config.strict }
if doc.errors.any?
errors.add(:base, "#{key}: #{doc.errors.join(", ")}")
end
end
end
# The problem is that Nokogiri its NOT very :strict
#2.1.3 :001 > Nokogiri::HTML("<a/><a/><a/>") {|config| config.strict }.errors.any?
# => false
2.1.3 :002 >
view raw gistfile1.rb hosted with ❤ by GitHub

Rails Route verification file

get '/7.IOOLFAIAt_Jju4.r2XtHjed2_MuF1jkA11S_HH.Q--.html', :to => proc { |env|
[ 200, {"Content-Type" => 'text/plain'}, ["works"] ]
}
view raw gistfile1.rb hosted with ❤ by GitHub

Sunday, 19 April 2015

.css to .scss and replace background image

change .css to .scss and replace background image

use image-url helper because we use cdn


Test it here: http://rubular.com/r/jp9hczSTHY
Find: url\((.*\.(jpg|JPG|gif|GIF|png|PNG))\)
Replace: image-url("$1")
view raw gistfile1.txt hosted with ❤ by GitHub

Sunday, 5 April 2015

Airbnb JavaScript Style Guide

https://github.com/airbnb/javascript/

![Gitter](https://badges.gitter.im/Join Chat.svg)

Airbnb JavaScript Style Guide() {

A mostly reasonable approach to JavaScript

Table of Contents

  1. Types
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Variables
  8. Hoisting
  9. Comparison Operators & Equality
  10. Blocks
  11. Comments
  12. Whitespace
  13. Commas
  14. Semicolons
  15. Type Casting & Coercion
  16. Naming Conventions
  17. Accessors
  18. Constructors
  19. Events
  20. Modules
  21. jQuery
  22. ECMAScript 5 Compatibility
  23. Testing
  24. Performance
  25. Resources
  26. In the Wild
  27. Translation
  28. The JavaScript Style Guide Guide
  29. Chat With Us About Javascript
  30. Contributors
  31. License

Types

  • Primitives: When you access a primitive type you work directly on its value.

    • string
    • number
    • boolean
    • null
    • undefined
    var foo = 1;
    var bar = foo;
    
    bar = 9;
    
    console.log(foo, bar); // => 1, 9
  • Complex: When you access a complex type you work on a reference to its value.

    • object
    • array
    • function
    var foo = [1, 2];
    var bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9

⬆ back to top

Objects

  • Use the literal syntax for object creation.

    // bad
    var item = new Object();
    
    // good
    var item = {};
  • Don't use reserved words as keys. It won't work in IE8. More info.

    // bad
    var superman = {
      default: { clark: 'kent' },
      private: true
    };
    
    // good
    var superman = {
      defaults: { clark: 'kent' },
      hidden: true
    };
  • Use readable synonyms in place of reserved words.

    // bad
    var superman = {
      class: 'alien'
    };
    
    // bad
    var superman = {
      klass: 'alien'
    };
    
    // good
    var superman = {
      type: 'alien'
    };

⬆ back to top

Arrays

  • Use the literal syntax for array creation.

    // bad
    var items = new Array();
    
    // good
    var items = [];
  • If you don't know array length use Array#push.

    var someStack = [];
    
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
  • When you need to copy an array use Array#slice. jsPerf

    var len = items.length;
    var itemsCopy = [];
    var i;
    
    // bad
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }
    
    // good
    itemsCopy = items.slice();
  • To convert an array-like object to an array, use Array#slice.

    function trigger() {
      var args = Array.prototype.slice.call(arguments);
      ...
    }

⬆ back to top

Strings

  • Use single quotes '' for strings.

    // bad
    var name = "Bob Parr";
    
    // good
    var name = 'Bob Parr';
    
    // bad
    var fullName = "Bob " + this.lastName;
    
    // good
    var fullName = 'Bob ' + this.lastName;
  • Strings longer than 80 characters should be written across multiple lines using string concatenation.

  • Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion.

    // bad
    var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    
    // bad
    var errorMessage = 'This is a super long error that was thrown because \
    of Batman. When you stop to think about how Batman had anything to do \
    with this, you would get nowhere \
    fast.';
    
    // good
    var errorMessage = 'This is a super long error that was thrown because ' +
      'of Batman. When you stop to think about how Batman had anything to do ' +
      'with this, you would get nowhere fast.';
  • When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.

    var items;
    var messages;
    var length;
    var i;
    
    messages = [{
      state: 'success',
      message: 'This one worked.'
    }, {
      state: 'success',
      message: 'This one worked as well.'
    }, {
      state: 'error',
      message: 'This one did not work.'
    }];
    
    length = messages.length;
    
    // bad
    function inbox(messages) {
      items = '<ul>';
    
      for (i = 0; i < length; i++) {
        items += '<li>' + messages[i].message + '</li>';
      }
    
      return items + '</ul>';
    }
    
    // good
    function inbox(messages) {
      items = [];
    
      for (i = 0; i < length; i++) {
        items[i] = '<li>' + messages[i].message + '</li>';
      }
    
      return '<ul>' + items.join('') + '</ul>';
    }

⬆ back to top

Functions

  • Function expressions:

    // anonymous function expression
    var anonymous = function() {
      return true;
    };
    
    // named function expression
    var named = function named() {
      return true;
    };
    
    // immediately-invoked function expression (IIFE)
    (function() {
      console.log('Welcome to the Internet. Please follow me.');
    })();
  • Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.

  • Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    var test;
    if (currentUser) {
      test = function test() {
        console.log('Yup.');
      };
    }
  • Never name a parameter arguments, this will take precedence over the arguments object that is given to every function scope.

    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }

⬆ back to top

Properties

  • Use dot notation when accessing properties.

    var luke = {
      jedi: true,
      age: 28
    };
    
    // bad
    var isJedi = luke['jedi'];
    
    // good
    var isJedi = luke.jedi;
  • Use subscript notation [] when accessing properties with a variable.

    var luke = {
      jedi: true,
      age: 28
    };
    
    function getProp(prop) {
      return luke[prop];
    }
    
    var isJedi = getProp('jedi');

⬆ back to top

Variables

  • Always use var to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.

    // bad
    superPower = new SuperPower();
    
    // good
    var superPower = new SuperPower();
  • Use one var declaration per variable. It's easier to add new variable declarations this way, and you never have to worry about swapping out a ; for a , or introducing punctuation-only diffs.

    // bad
    var items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    // (compare to above, and try to spot the mistake)
    var items = getItems(),
        goSportsTeam = true;
        dragonball = 'z';
    
    // good
    var items = getItems();
    var goSportsTeam = true;
    var dragonball = 'z';
  • Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.

    // bad
    var i, len, dragonball,
        items = getItems(),
        goSportsTeam = true;
    
    // bad
    var i;
    var items = getItems();
    var dragonball;
    var goSportsTeam = true;
    var len;
    
    // good
    var items = getItems();
    var goSportsTeam = true;
    var dragonball;
    var length;
    var i;
  • Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.

    // bad
    function() {
      test();
      console.log('doing stuff..');
    
      //..other stuff..
    
      var name = getName();
    
      if (name === 'test') {
        return false;
      }
    
      return name;
    }
    
    // good
    function() {
      var name = getName();
    
      test();
      console.log('doing stuff..');
    
      //..other stuff..
    
      if (name === 'test') {
        return false;
      }
    
      return name;
    }
    
    // bad
    function() {
      var name = getName();
    
      if (!arguments.length) {
        return false;
      }
    
      return true;
    }
    
    // good
    function() {
      if (!arguments.length) {
        return false;
      }
    
      var name = getName();
    
      return true;
    }

⬆ back to top

Hoisting

  • Variable declarations get hoisted to the top of their scope, their assignment does not.

    // we know this wouldn't work (assuming there
    // is no notDefined global variable)
    function example() {
      console.log(notDefined); // => throws a ReferenceError
    }
    
    // creating a variable declaration after you
    // reference the variable will work due to
    // variable hoisting. Note: the assignment
    // value of `true` is not hoisted.
    function example() {
      console.log(declaredButNotAssigned); // => undefined
      var declaredButNotAssigned = true;
    }
    
    // The interpreter is hoisting the variable
    // declaration to the top of the scope,
    // which means our example could be rewritten as:
    function example() {
      var declaredButNotAssigned;
      console.log(declaredButNotAssigned); // => undefined
      declaredButNotAssigned = true;
    }
  • Anonymous function expressions hoist their variable name, but not the function assignment.

    function example() {
      console.log(anonymous); // => undefined
    
      anonymous(); // => TypeError anonymous is not a function
    
      var anonymous = function() {
        console.log('anonymous function expression');
      };
    }
  • Named function expressions hoist the variable name, not the function name or the function body.

    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      superPower(); // => ReferenceError superPower is not defined
    
      var named = function superPower() {
        console.log('Flying');
      };
    }
    
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      }
    }
  • Function declarations hoist their name and the function body.

    function example() {
      superPower(); // => Flying
    
      function superPower() {
        console.log('Flying');
      }
    }
  • For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Comparison Operators & Equality

  • Use === and !== over == and !=.

  • Comparison operators are evaluated using coercion with the ToBoolean method and always follow these simple rules:

    • Objects evaluate to true
    • Undefined evaluates to false
    • Null evaluates to false
    • Booleans evaluate to the value of the boolean
    • Numbers evaluate to false if +0, -0, or NaN, otherwise true
    • Strings evaluate to false if an empty string '', otherwise true
    if ([0]) {
      // true
      // An array is an object, objects evaluate to true
    }
  • Use shortcuts.

    // bad
    if (name !== '') {
      // ...stuff...
    }
    
    // good
    if (name) {
      // ...stuff...
    }
    
    // bad
    if (collection.length > 0) {
      // ...stuff...
    }
    
    // good
    if (collection.length) {
      // ...stuff...
    }
  • For more information see Truth Equality and JavaScript by Angus Croll.

⬆ back to top

Blocks

  • Use braces with all multi-line blocks.

    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
    
    // bad
    function() { return false; }
    
    // good
    function() {
      return false;
    }
  • If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace.

    // bad
    if (test) {
      thing1();
      thing2();
    }
    else {
      thing3();
    }
    
    // good
    if (test) {
      thing1();
      thing2();
    } else {
      thing3();
    }

⬆ back to top

Comments

  • Use /** ... */ for multiline comments. Include a description, specify types and values for all parameters and return values.

    // bad
    // make() returns a new element
    // based on the passed in tag name
    //
    // @param {String} tag
    // @return {Element} element
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed in tag name
     *
     * @param {String} tag
     * @return {Element} element
     */
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
  • Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.

    // bad
    var active = true;  // is current tab
    
    // good
    // is current tab
    var active = true;
    
    // bad
    function getType() {
      console.log('fetching type...');
      // set the default type to 'no type'
      var type = this._type || 'no type';
    
      return type;
    }
    
    // good
    function getType() {
      console.log('fetching type...');
    
      // set the default type to 'no type'
      var type = this._type || 'no type';
    
      return type;
    }
  • Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME -- need to figure this out or TODO -- need to implement.

  • Use // FIXME: to annotate problems.

    function Calculator() {
    
      // FIXME: shouldn't use a global here
      total = 0;
    
      return this;
    }
  • Use // TODO: to annotate solutions to problems.

    function Calculator() {
    
      // TODO: total should be configurable by an options param
      this.total = 0;
    
      return this;
    }

**[⬆ back to top](#table-of-contents)**


## Whitespace

- Use soft tabs set to 2 spaces.

  ```javascript
  // bad
  function() {
  ∙∙∙∙var name;
  }

  // bad
  function() {
  ∙var name;
  }

  // good
  function() {
  ∙∙var name;
  }
  ```

- Place 1 space before the leading brace.

  ```javascript
  // bad
  function test(){
    console.log('test');
  }

  // good
  function test() {
    console.log('test');
  }

  // bad
  dog.set('attr',{
    age: '1 year',
    breed: 'Bernese Mountain Dog'
  });

  // good
  dog.set('attr', {
    age: '1 year',
    breed: 'Bernese Mountain Dog'
  });
  ```

- Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space before the argument list in function calls and declarations.

  ```javascript
  // bad
  if(isJedi) {
    fight ();
  }

  // good
  if (isJedi) {
    fight();
  }

  // bad
  function fight () {
    console.log ('Swooosh!');
  }

  // good
  function fight() {
    console.log('Swooosh!');
  }
  ```

- Set off operators with spaces.

  ```javascript
  // bad
  var x=y+5;

  // good
  var x = y + 5;
  ```

- End files with a single newline character.

  ```javascript
  // bad
  (function(global) {
    // ...stuff...
  })(this);
  ```

  ```javascript
  // bad
  (function(global) {
    // ...stuff...
  })(this);↵
  ↵
  ```

  ```javascript
  // good
  (function(global) {
    // ...stuff...
  })(this);↵
  ```

- Use indentation when making long method chains. Use a leading dot, which
  emphasizes that the line is a method call, not a new statement.

  ```javascript
  // bad
  $('#items').find('.selected').highlight().end().find('.open').updateCount();

  // bad
  $('#items').
    find('selected').
      highlight().
      end().
    find('.open').
      updateCount();

  // good
  $('#items')
    .find('.selected')
      .highlight()
      .end()
    .find('.open')
      .updateCount();

  // bad
  var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
      .attr('width',  (radius + margin) * 2).append('svg:g')
      .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
      .call(tron.led);

  // good
  var leds = stage.selectAll('.led')
      .data(data)
    .enter().append('svg:svg')
      .class('led', true)
      .attr('width',  (radius + margin) * 2)
    .append('svg:g')
      .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
      .call(tron.led);
  ```

- Leave a blank line after blocks and before the next statement

  ```javascript
  // bad
  if (foo) {
    return bar;
  }
  return baz;

  // good
  if (foo) {
    return bar;
  }

  return baz;

  // bad
  var obj = {
    foo: function() {
    },
    bar: function() {
    }
  };
  return obj;

  // good
  var obj = {
    foo: function() {
    },

    bar: function() {
    }
  };

  return obj;
  ```


**[⬆ back to top](#table-of-contents)**

## Commas

- Leading commas: **Nope.**

  ```javascript
  // bad
  var story = [
      once
    , upon
    , aTime
  ];

  // good
  var story = [
    once,
    upon,
    aTime
  ];

  // bad
  var hero = {
      firstName: 'Bob'
    , lastName: 'Parr'
    , heroName: 'Mr. Incredible'
    , superPower: 'strength'
  };

  // good
  var hero = {
    firstName: 'Bob',
    lastName: 'Parr',
    heroName: 'Mr. Incredible',
    superPower: 'strength'
  };
  ```

- Additional trailing comma: **Nope.** This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 ([source](http://es5.github.io/#D)):

> Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.

  ```javascript
  // bad
  var hero = {
    firstName: 'Kevin',
    lastName: 'Flynn',
  };

  var heroes = [
    'Batman',
    'Superman',
  ];

  // good
  var hero = {
    firstName: 'Kevin',
    lastName: 'Flynn'
  };

  var heroes = [
    'Batman',
    'Superman'
  ];
  ```

**[⬆ back to top](#table-of-contents)**


## Semicolons

- **Yup.**

  ```javascript
  // bad
  (function() {
    var name = 'Skywalker'
    return name
  })()

  // good
  (function() {
    var name = 'Skywalker';
    return name;
  })();

  // good (guards against the function becoming an argument when two files with IIFEs are concatenated)
  ;(function() {
    var name = 'Skywalker';
    return name;
  })();
  ```

  [Read more](http://stackoverflow.com/a/7365214/1712802).

**[⬆ back to top](#table-of-contents)**


## Type Casting & Coercion

- Perform type coercion at the beginning of the statement.
- Strings:

  ```javascript
  //  => this.reviewScore = 9;

  // bad
  var totalScore = this.reviewScore + '';

  // good
  var totalScore = '' + this.reviewScore;

  // bad
  var totalScore = '' + this.reviewScore + ' total score';

  // good
  var totalScore = this.reviewScore + ' total score';
  ```

- Use `parseInt` for Numbers and always with a radix for type casting.

  ```javascript
  var inputValue = '4';

  // bad
  var val = new Number(inputValue);

  // bad
  var val = +inputValue;

  // bad
  var val = inputValue >> 0;

  // bad
  var val = parseInt(inputValue);

  // good
  var val = Number(inputValue);

  // good
  var val = parseInt(inputValue, 10);
  ```

- If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you're doing.

  ```javascript
  // good
  /**
   * parseInt was the reason my code was slow.
   * Bitshifting the String to coerce it to a
   * Number made it a lot faster.
   */
  var val = inputValue >> 0;
  ```

- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:

  ```javascript
  2147483647 >> 0 //=> 2147483647
  2147483648 >> 0 //=> -2147483648
  2147483649 >> 0 //=> -2147483647
  ```

- Booleans:

  ```javascript
  var age = 0;

  // bad
  var hasAge = new Boolean(age);

  // good
  var hasAge = Boolean(age);

  // good
  var hasAge = !!age;
  ```

**[⬆ back to top](#table-of-contents)**


## Naming Conventions

- Avoid single letter names. Be descriptive with your naming.

  ```javascript
  // bad
  function q() {
    // ...stuff...
  }

  // good
  function query() {
    // ..stuff..
  }
  ```

- Use camelCase when naming objects, functions, and instances.

  ```javascript
  // bad
  var OBJEcttsssss = {};
  var this_is_my_object = {};
  function c() {}
  var u = new user({
    name: 'Bob Parr'
  });

  // good
  var thisIsMyObject = {};
  function thisIsMyFunction() {}
  var user = new User({
    name: 'Bob Parr'
  });
  ```

- Use PascalCase when naming constructors or classes.

  ```javascript
  // bad
  function user(options) {
    this.name = options.name;
  }

  var bad = new user({
    name: 'nope'
  });

  // good
  function User(options) {
    this.name = options.name;
  }

  var good = new User({
    name: 'yup'
  });
  ```

- Use a leading underscore `_` when naming private properties.

  ```javascript
  // bad
  this.__firstName__ = 'Panda';
  this.firstName_ = 'Panda';

  // good
  this._firstName = 'Panda';
  ```

- When saving a reference to `this` use `_this`.

  ```javascript
  // bad
  function() {
    var self = this;
    return function() {
      console.log(self);
    };
  }

  // bad
  function() {
    var that = this;
    return function() {
      console.log(that);
    };
  }

  // good
  function() {
    var _this = this;
    return function() {
      console.log(_this);
    };
  }
  ```

- Name your functions. This is helpful for stack traces.

  ```javascript
  // bad
  var log = function(msg) {
    console.log(msg);
  };

  // good
  var log = function log(msg) {
    console.log(msg);
  };
  ```

- **Note:** IE8 and below exhibit some quirks with named function expressions.  See [http://kangax.github.io/nfe/](http://kangax.github.io/nfe/) for more info.

- If your file exports a single class, your filename should be exactly the name of the class.
  ```javascript
  // file contents
  class CheckBox {
    // ...
  }
  module.exports = CheckBox;

  // in some other file
  // bad
  var CheckBox = require('./checkBox');

  // bad
  var CheckBox = require('./check_box');

  // good
  var CheckBox = require('./CheckBox');
  ```

**[⬆ back to top](#table-of-contents)**


## Accessors

- Accessor functions for properties are not required.
- If you do make accessor functions use getVal() and setVal('hello').

  ```javascript
  // bad
  dragon.age();

  // good
  dragon.getAge();

  // bad
  dragon.age(25);

  // good
  dragon.setAge(25);
  ```

- If the property is a boolean, use isVal() or hasVal().

  ```javascript
  // bad
  if (!dragon.age()) {
    return false;
  }

  // good
  if (!dragon.hasAge()) {
    return false;
  }
  ```

- It's okay to create get() and set() functions, but be consistent.

  ```javascript
  function Jedi(options) {
    options || (options = {});
    var lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  Jedi.prototype.set = function(key, val) {
    this[key] = val;
  };

  Jedi.prototype.get = function(key) {
    return this[key];
  };
  ```

**[⬆ back to top](#table-of-contents)**


## Constructors

- Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!

  ```javascript
  function Jedi() {
    console.log('new jedi');
  }

  // bad
  Jedi.prototype = {
    fight: function fight() {
      console.log('fighting');
    },

    block: function block() {
      console.log('blocking');
    }
  };

  // good
  Jedi.prototype.fight = function fight() {
    console.log('fighting');
  };

  Jedi.prototype.block = function block() {
    console.log('blocking');
  };
  ```

- Methods can return `this` to help with method chaining.

  ```javascript
  // bad
  Jedi.prototype.jump = function() {
    this.jumping = true;
    return true;
  };

  Jedi.prototype.setHeight = function(height) {
    this.height = height;
  };

  var luke = new Jedi();
  luke.jump(); // => true
  luke.setHeight(20); // => undefined

  // good
  Jedi.prototype.jump = function() {
    this.jumping = true;
    return this;
  };

  Jedi.prototype.setHeight = function(height) {
    this.height = height;
    return this;
  };

  var luke = new Jedi();

  luke.jump()
    .setHeight(20);
  ```


- It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

  ```javascript
  function Jedi(options) {
    options || (options = {});
    this.name = options.name || 'no name';
  }

  Jedi.prototype.getName = function getName() {
    return this.name;
  };

  Jedi.prototype.toString = function toString() {
    return 'Jedi - ' + this.getName();
  };
  ```

**[⬆ back to top](#table-of-contents)**


## Events

- When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:

  ```js
  // bad
  $(this).trigger('listingUpdated', listing.id);

  ...

  $(this).on('listingUpdated', function(e, listingId) {
    // do something with listingId
  });
  ```

  prefer:

  ```js
  // good
  $(this).trigger('listingUpdated', { listingId : listing.id });

  ...

  $(this).on('listingUpdated', function(e, data) {
    // do something with data.listingId
  });
  ```

**[⬆ back to top](#table-of-contents)**


## Modules

- The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. [Explanation](https://github.com/airbnb/javascript/issues/44#issuecomment-13063933)
- The file should be named with camelCase, live in a folder with the same name, and match the name of the single export.
- Add a method called `noConflict()` that sets the exported module to the previous version and returns this one.
- Always declare `'use strict';` at the top of the module.

  ```javascript
  // fancyInput/fancyInput.js

  !function(global) {
    'use strict';

    var previousFancyInput = global.FancyInput;

    function FancyInput(options) {
      this.options = options || {};
    }

    FancyInput.noConflict = function noConflict() {
      global.FancyInput = previousFancyInput;
      return FancyInput;
    };

    global.FancyInput = FancyInput;
  }(this);
  ```

**[⬆ back to top](#table-of-contents)**


## jQuery

- Prefix jQuery object variables with a `$`.

  ```javascript
  // bad
  var sidebar = $('.sidebar');

  // good
  var $sidebar = $('.sidebar');
  ```

- Cache jQuery lookups.

  ```javascript
  // bad
  function setSidebar() {
    $('.sidebar').hide();

    // ...stuff...

    $('.sidebar').css({
      'background-color': 'pink'
    });
  }

  // good
  function setSidebar() {
    var $sidebar = $('.sidebar');
    $sidebar.hide();

    // ...stuff...

    $sidebar.css({
      'background-color': 'pink'
    });
  }
  ```

- For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
- Use `find` with scoped jQuery object queries.

  ```javascript
  // bad
  $('ul', '.sidebar').hide();

  // bad
  $('.sidebar').find('ul').hide();

  // good
  $('.sidebar ul').hide();

  // good
  $('.sidebar > ul').hide();

  // good
  $sidebar.find('ul').hide();
  ```

**[⬆ back to top](#table-of-contents)**


## ECMAScript 5 Compatibility

- Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/).

**[⬆ back to top](#table-of-contents)**


## Testing

- **Yup.**

  ```javascript
  function() {
    return true;
  }
  ```

**[⬆ back to top](#table-of-contents)**


## Performance

- [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/)
- [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)
- [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)
- [Bang Function](http://jsperf.com/bang-function)
- [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)
- [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)
- [Long String Concatenation](http://jsperf.com/ya-string-concat)
- Loading...

**[⬆ back to top](#table-of-contents)**


## Resources


**Read This**

- [Annotated ECMAScript 5.1](http://es5.github.com/)

**Tools**

- Code Style Linters
  + [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc)
  + [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json)

**Other Styleguides**

- [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
- [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
- [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)
- [JavaScript Standard Style](https://github.com/feross/standard)

**Other Styles**

- [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen
- [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
- [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
- [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman

**Further Reading**

- [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
- [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
- [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
- [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
- [Frontend Guidelines](https://github.com/bendc/frontend-guidelines) - Benjamin De Cock

**Books**

- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
- [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
- [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X)  - Ross Harmes and Dustin Diaz
- [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
- [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
- [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
- [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
- [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
- [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
- [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
- [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov
- [Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript](http://amzn.com/0321812182) - David Herman
- [Eloquent JavaScript](http://eloquentjavascript.net) - Marijn Haverbeke
- [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) - Kyle Simpson

**Blogs**

- [DailyJS](http://dailyjs.com/)
- [JavaScript Weekly](http://javascriptweekly.com/)
- [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)
- [Bocoup Weblog](http://weblog.bocoup.com/)
- [Adequately Good](http://www.adequatelygood.com/)
- [NCZOnline](http://www.nczonline.net/)
- [Perfection Kills](http://perfectionkills.com/)
- [Ben Alman](http://benalman.com/)
- [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
- [Dustin Diaz](http://dustindiaz.com/)
- [nettuts](http://net.tutsplus.com/?s=javascript)

**Podcasts**

- [JavaScript Jabber](http://devchat.tv/js-jabber/)


**[⬆ back to top](#table-of-contents)**

## In the Wild

This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list.

- **Aan Zee**: [AanZee/javascript](https://github.com/AanZee/javascript)
- **Adult Swim**: [adult-swim/javascript](https://github.com/adult-swim/javascript)
- **Airbnb**: [airbnb/javascript](https://github.com/airbnb/javascript)
- **American Insitutes for Research**: [AIRAST/javascript](https://github.com/AIRAST/javascript)
- **Apartmint**: [apartmint/javascript](https://github.com/apartmint/javascript)
- **Avalara**: [avalara/javascript](https://github.com/avalara/javascript)
- **Compass Learning**: [compasslearning/javascript-style-guide](https://github.com/compasslearning/javascript-style-guide)
- **DailyMotion**: [dailymotion/javascript](https://github.com/dailymotion/javascript)
- **Digitpaint** [digitpaint/javascript](https://github.com/digitpaint/javascript)
- **Evernote**: [evernote/javascript-style-guide](https://github.com/evernote/javascript-style-guide)
- **ExactTarget**: [ExactTarget/javascript](https://github.com/ExactTarget/javascript)
- **Gawker Media**: [gawkermedia/javascript](https://github.com/gawkermedia/javascript)
- **GeneralElectric**: [GeneralElectric/javascript](https://github.com/GeneralElectric/javascript)
- **GoodData**: [gooddata/gdc-js-style](https://github.com/gooddata/gdc-js-style)
- **Grooveshark**: [grooveshark/javascript](https://github.com/grooveshark/javascript)
- **How About We**: [howaboutwe/javascript](https://github.com/howaboutwe/javascript)
- **InfoJobs**: [InfoJobs/JavaScript-Style-Guide](https://github.com/InfoJobs/JavaScript-Style-Guide)
- **Intent Media**: [intentmedia/javascript](https://github.com/intentmedia/javascript)
- **Jam3**: [Jam3/Javascript-Code-Conventions](https://github.com/Jam3/Javascript-Code-Conventions)
- **Kinetica Solutions**: [kinetica/javascript](https://github.com/kinetica/javascript)
- **Mighty Spring**: [mightyspring/javascript](https://github.com/mightyspring/javascript)
- **MinnPost**: [MinnPost/javascript](https://github.com/MinnPost/javascript)
- **ModCloth**: [modcloth/javascript](https://github.com/modcloth/javascript)
- **Money Advice Service**: [moneyadviceservice/javascript](https://github.com/moneyadviceservice/javascript)
- **Muber**: [muber/javascript](https://github.com/muber/javascript)
- **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript)
- **National Park Service**: [nationalparkservice/javascript](https://github.com/nationalparkservice/javascript)
- **Nimbl3**: [nimbl3/javascript](https://github.com/nimbl3/javascript)
- **Nordic Venture Family**: [CodeDistillery/javascript](https://github.com/CodeDistillery/javascript)
- **Orion Health**: [orionhealth/javascript](https://github.com/orionhealth/javascript)
- **Peerby**: [Peerby/javascript](https://github.com/Peerby/javascript)
- **Razorfish**: [razorfish/javascript-style-guide](https://github.com/razorfish/javascript-style-guide)
- **reddit**: [reddit/styleguide/javascript](https://github.com/reddit/styleguide/tree/master/javascript)
- **REI**: [reidev/js-style-guide](https://github.com/reidev/js-style-guide)
- **Ripple**: [ripple/javascript-style-guide](https://github.com/ripple/javascript-style-guide)
- **SeekingAlpha**: [seekingalpha/javascript-style-guide](https://github.com/seekingalpha/javascript-style-guide)
- **Shutterfly**: [shutterfly/javascript](https://github.com/shutterfly/javascript)
- **StudentSphere**: [studentsphere/javascript](https://github.com/studentsphere/javascript)
- **Target**: [target/javascript](https://github.com/target/javascript)
- **TheLadders**: [TheLadders/javascript](https://github.com/TheLadders/javascript)
- **T4R Technology**: [T4R-Technology/javascript](https://github.com/T4R-Technology/javascript)
- **Userify**: [userify/javascript](https://github.com/userify/javascript)
- **VoxFeed**: [VoxFeed/javascript-style-guide](https://github.com/VoxFeed/javascript-style-guide)
- **Weggo**: [Weggo/javascript](https://github.com/Weggo/javascript)
- **Zillow**: [zillow/javascript](https://github.com/zillow/javascript)
- **ZocDoc**: [ZocDoc/javascript](https://github.com/ZocDoc/javascript)

## Translation

This style guide is also available in other languages:

- ![de](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png) **German**: [timofurrer/javascript-style-guide](https://github.com/timofurrer/javascript-style-guide)
- ![jp](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png) **Japanese**: [mitsuruog/javacript-style-guide](https://github.com/mitsuruog/javacript-style-guide)
- ![br](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png) **Brazilian Portuguese**: [armoucar/javascript-style-guide](https://github.com/armoucar/javascript-style-guide)
- ![tw](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png) **Chinese(Traditional)**: [jigsawye/javascript](https://github.com/jigsawye/javascript)
- ![cn](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png) **Chinese(Simplified)**: [adamlu/javascript-style-guide](https://github.com/adamlu/javascript-style-guide)
- ![es](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png) **Spanish**: [paolocarrasco/javascript-style-guide](https://github.com/paolocarrasco/javascript-style-guide)
- ![kr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png) **Korean**: [tipjs/javascript-style-guide](https://github.com/tipjs/javascript-style-guide)
- ![fr](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png) **French**: [nmussy/javascript-style-guide](https://github.com/nmussy/javascript-style-guide)
- ![ru](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png) **Russian**: [uprock/javascript](https://github.com/uprock/javascript)
- ![bg](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Bulgaria.png) **Bulgarian**: [borislavvv/javascript](https://github.com/borislavvv/javascript)
- ![ca](https://raw.githubusercontent.com/fpmweb/javascript-style-guide/master/img/catala.png) **Catalan**: [fpmweb/javascript-style-guide](https://github.com/fpmweb/javascript-style-guide)
- ![pl](https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Poland.png) **Polish**: [mjurczyk/javascript](https://github.com/mjurczyk/javascript)

## The JavaScript Style Guide Guide

- [Reference](https://github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)

## Chat With Us About JavaScript

- Find us on [gitter](https://gitter.im/airbnb/javascript).

## Contributors

- [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)


## License

(The MIT License)

Copyright (c) 2014 Airbnb

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

**[⬆ back to top](#table-of-contents)**

# };
view raw gistfile1.md hosted with ❤ by GitHub

Thursday, 2 April 2015

avoid lose data javascript

//from https://github.com/tolk/tolk/
$(function () {
$("#submit").bind("click", function () {
window.onbeforeunload = null;
});
// avoid lose data
$(".translations").bind("keydown", function () {
window.onbeforeunload = confirm;
});
$(".translations").bind("change", function () {
window.onbeforeunload = confirm;
});
function confirm() {
return "You are leaving this page with non-saved data. Are you sure you want to continue?";
}
});
view raw gistfile1.js hosted with ❤ by GitHub

i18n style hash

def convert_hash(hash, path = "")
hash.each_with_object({}) do |(k, v), ret|
key = path + k
if v.is_a? Hash
ret.merge! convert_hash(v, key + ".")
else
ret[key] = v
end
end
end
my_hash = {'a' =>
{'b' => 'a-b',
'c' => 'a-c',
'd' => {'e' => 'a-d-e'}
},
'f' => 'f'}
data = convert_hash(my_hash)
# => {"a.b"=>"a-b", "a.c"=>"a-c", "a.d.e"=>"a-d-e", "f"=>"f"}
data["a.b"]
# => "a-b"
view raw gistfile1.rb hosted with ❤ by GitHub

Wednesday, 1 April 2015

Import YAML translations to I18n::Backend::ActiveRecord::Translation

data = YAML::load(File.open("config/locales/en.yml"))
translations = {}
def process_hash(translations, current_key, hash)
hash.each do |new_key, value|
combined_key = [current_key, new_key].delete_if { |k| k == '' }.join(".")
if value.is_a?(Hash)
process_hash(translations, combined_key, value)
else
translations[combined_key] = value
end
end
end
process_hash(translations, '', data['en'])
translations.each do |k, v|
TRANSLATIONS_STORE.store_translations(:en, {
k => v
}, :escape => false)
end
view raw gistfile1.rb hosted with ❤ by GitHub

Monday, 30 March 2015

mock Thor's yes?

it "should import list" do
allow_any_instance_of(Thor::Actions).to receive(:yes?).and_return(true)
end
view raw gistfile1.rb hosted with ❤ by GitHub

Wednesday, 25 March 2015

Applied Philosophy, a.k.a. "Hacking"

Every system has two sets of rules: The rules as they are intended or commonly perceived, and the actual rules ("reality"). In most complex systems, the gap between these two sets of rules is huge.

Sometimes we catch a glimpse of the truth, and discover the actual rules of a system. Once the actual rules are known, it may be possible to perform "miracles" -- things which violate the perceived rules.

Hacking is most commonly associated with computers, and people who break into or otherwise subvert computer systems are often called hackers. Although this terminology is occasionally disputed, I think it is essentially correct -- these hackers are discovering the actual rules of the computer systems (e.g. buffer overflows), and using them to circumvent the intended rules of the system (typically access controls). The same is true of the hackers who break DRM or other systems of control.

Writing clever (or sometimes ugly) code is also described as hacking. In this case the hacker is violating the rules of how we expect software to be written. If there's a project that should take months to write, and someone manages to hack it out in a single evening, that's a small miracle, and a major hack. If the result is simple and beautiful because the hacker discovered a better solution, we may describe the hack as "elegant" or "brilliant". If the result is complex and hard to understand (perhaps it violates many layers of abstraction), then we will call it an "ugly hack". Ugly hacks aren't all bad though -- one of my favorite personal hacks was some messy code that demonstrated what would become AdSense (story here), and although the code was quickly discarded, it did it's job.

Hacking isn't limited to computers though. Wherever there are systems, there is the potential for hacking, and there are systems everywhere. Our entire reality is systems of systems, all the way down. This includes human relations (see The Game for an very amusing story of people hacking human attraction), health (Seth Roberts has some interesting ideas), sports (Tim Ferriss claims to have hacked the National Chinese Kickboxing championship), and finance ("too big to fail").

We're often told that there are no shortcuts to success -- that it's all a matter of hard work and doing what we're told. The hacking mindset takes there opposite approach: There are always shortcuts and loopholes. For this reason, hacking is sometimes perceived as cheating, or unfair, and it can be. Using social hacks to steal billions of dollars is wrong (see Madoff). On the other hand, automation seems like a great hack -- getting machines to do our work enabled a much higher standard of living, though as always, not everyone sees it that way (the Luddites weren't big fans).

Important new businesses are usually some kind of hack. The established businesses think they understand the system and have setup rules to guard their profits and prevent real competition. New businesses must find a gap in the rules -- something that the established powers either don't see, or don't perceive as important. That was certainly the case with Google: the existing search engines (which thought of themselves as portals) believed that search quality wasn't very important (regular people can't tell the difference), and that search wasn't very valuable anyway, since it sends people away from your site. Google's success came in large part from recognizing that others were wrong on both points.

In fact, the entire process of building a business and having other people and computers do the work for you is a big hack. Nobody ever created a billion dollars through direct physical labor -- it requires some major shortcuts to create that much wealth, and by definition those shortcuts were mostly invisible to others (though many will dispute it after the fact). Startup investing takes this hack to the next level by having other people do the work of building the business, though finding the right people and businesses is not easy.

Not everyone has the hacker mindset (society requires a variety of personalities), but wherever and whenever there were people, there was someone staring into the system, searching for the truth. Some of those people were content to simply find a truth, but others used their discoveries to hack the system, to transform the world. These are the people that created the governments, businesses, religions, and other machines that operate our society, and they necessarily did it by hacking the prior systems. (consider the challenge of establishing a successful new government or religion -- the incumbents won't give up easily)

To discover great hacks, we must always be searching for the true nature of our reality, while acknowledging that we do not currently possess the truth, and never will. Hacking is much bigger and more important than clever bits of code in a computer -- it's how we create the future.

Or at least that's how I see it. Maybe I'll change my mind later.

See also: "The Knack" (and the need to disassemble things)

Paul Buchheit

That's the vision of WebRTC.

Imagine a world where your phone, TV and computer could all communicate on a common platform. Imagine it was easy to add video chat and peer-to-peer data sharing to your web application. That's the vision of WebRTC.



http://www.html5rocks.com/en/tutorials/webrtc/basics/

method_missing to object

class Object
def method_missing(meth, *args, &block)
p meth
p args
super
end
end
view raw gistfile1.rb hosted with ❤ by GitHub

Tuesday, 24 March 2015

primer



The base coat of GitHub. Our internal CSS toolkit and guidelines. 

geolocation-api

// http://jonrohan.me/guide/javascript/geolocation-api/
function getLocation() {
2 if(navigator.geolocation) {
3 navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
4 } else {
5 noLocation();
6 }
7 }
8 function foundLocation(position) {
9 var lat = position.coords.latitude;
10 var long = position.coords.longitude;
11 $("#current-location").replaceWith('<a id="current-location" href="http://maps.google.com/?q=' + lat + ',' + long + '" target="_blank">' + lat + ', ' + long + '</a>');
12 }
13 function noLocation() {
14 $("#current-location").text('Could not find location');
15 }
16 $("#get-location").click(getLocation);
view raw gistfile1.js hosted with ❤ by GitHub

Monday, 23 March 2015

Load ActiveRecord Models

@active_record_models_loaded = false
def load_active_record_models
Dir.glob(Rails.root.to_s + '/app/models/*.rb').each { |file| require file }
@active_record_models_loaded = true
end
view raw gistfile1.rb hosted with ❤ by GitHub

Saturday, 21 March 2015

report.rb

# mysql-style output for an array of ActiveRecord objects
#
# Usage:
# report(records) # displays report with all fields
# report(records, :field1, :field2, ...) # displays report with given fields
#
# Example:
# >> report(records, :id, :amount, :created_at)
# +------+-----------+--------------------------------+
# | id | amount | created_at |
# +------+-----------+--------------------------------+
# | 8301 | $12.40 | Sat Feb 28 09:20:47 -0800 2009 |
# | 6060 | $39.62 | Sun Feb 15 14:45:38 -0800 2009 |
# | 6061 | $167.52 | Sun Feb 15 14:45:38 -0800 2009 |
# | 6067 | $12.00 | Sun Feb 15 14:45:40 -0800 2009 |
# | 6059 | $1,000.00 | Sun Feb 15 14:45:38 -0800 2009 |
# +------+-----------+--------------------------------+
# 5 rows in set
#
def report(items, *fields)
# find max length for each field; start with the field names themselves
fields = items.first.class.column_names unless fields.any?
max_len = Hash[*fields.map {|f| [f, f.to_s.length]}.flatten]
items.each do |item|
fields.each do |field|
len = item.read_attribute(field).to_s.length
max_len[field] = len if len > max_len[field]
end
end
border = '+-' + fields.map {|f| '-' * max_len[f] }.join('-+-') + '-+'
title_row = '| ' + fields.map {|f| sprintf("%-#{max_len[f]}s", f.to_s) }.join(' | ') + ' |'
puts border
puts title_row
puts border
items.each do |item|
row = '| ' + fields.map {|f| sprintf("%-#{max_len[f]}s", item.read_attribute(f)) }.join(' | ') + ' |'
puts row
end
puts border
puts "#{items.length} rows in set\n"
end
view raw report.rb hosted with ❤ by GitHub

Wednesday, 18 March 2015

Tunnelss a proxy from HTTPS to HTTP for POW

The Magic

Tunnelss is a mix between the tunnels gem and the powssl script.
  1. It builds a root-level certificate (a Certificate Authority) and registers it as a trusted root certificate (you will need to do it manually for Firefox).
  2. It generates a SSL certificate matching the Pow .dev domains.
  3. It runs an EventMachine server which acts as proxy from HTTPS to HTTP (just like tunnels), using the generated certificate so that your browser will not complain your SSL connection is not valid!

https://github.com/rchampourlier/tunnelss

Tunnelss


Installation

$ gem install tunnelss
If you're using rbenv:
$ rbenv rehash

Run

$ sudo tunnelss
Don't worry, the first time you launch it it will generate a certificate and ask for your permission to add it to trusted authorities (see The Magic above for more details).
If you are using rvm:
$ rvmsudo tunnelss








Visit https://myproject.dev :D



namespaced subdomain in rails

constraints :subdomain => 'manage' do
devise_for :admins, controllers: { sessions: 'admin/sessions'}, skip: :registrations
scope :module => 'admin', :as => 'admin' do
root to: 'dashboard#home'
end
end
view raw gistfile1.rb hosted with ❤ by GitHub

top level cookie in rails

cookies.permanent.signed[:beta_tester] = { value: "1", :domain => :all }
view raw gistfile1.rb hosted with ❤ by GitHub

Tuesday, 17 March 2015

validates_each

validates_each :date_expire, on: :create, if: ->(r) { r.is_company? } do |record, attr, value|
record.errors.add attr, 'must be in the future ' if value < Date.today
end
view raw gistfile1.rb hosted with ❤ by GitHub

Thursday, 12 March 2015

asset_host parallel cdn

#To really juice up the load times of your site, configure four subdomains for your assets,
#numbered from 0 to 3, e.g. #assets0.myapp.com to assets3.myapp.com, pointing at your asset CDN and set the following in your
#production configuration:
config.action_controller.asset_host = "assets%d.myapp.com"
#Rails will cycle through each of these subdomains when it generates asset links. Browsers are generally restricted to
#only two concurrent requests per host name, so having assets served from four allows the browser to make eight
#concurrent requests. Page load speeds will now be constrained only by the speed of your user’s connection.#
#If you user has a good connection then they will be able to download most of your assets in parallel.
#<script src="http://assets3.myapp.com/assets/application-79aae679bbfc378424584779fa84a6e8.js"></script>
#<script src="http://assets2.myapp.com/assets/application-79aae679bbfc378424584779fa84a6e8.css"></script>
view raw gistfile1.rb hosted with ❤ by GitHub

Amazon S3 CORS (Cross-Origin Resource Sharing) Serve Fonts

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://www.domain.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Content-*</AllowedHeader>
<AllowedHeader>Host</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>http://*.domain.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Content-*</AllowedHeader>
<AllowedHeader>Host</AllowedHeader>
</CORSRule>
</CORSConfiguration>
view raw gistfile1.xml hosted with ❤ by GitHub

Wednesday, 11 March 2015

Sync rails public folder aws s3 bucket rake task

require 'aws/s3'
require 'digest/md5'
require 'mime/types'
## These are some constants to keep track of my S3 credentials and
## bucket name. Nothing fancy here.
AWS_ACCESS_KEY_ID = ENV['S3_KEY']
AWS_SECRET_ACCESS_KEY = ENV['S3_SECRET']
AWS_BUCKET = ENV['S3_BUCKET']
## This defines the rake task `assets:deploy`.
namespace :assets do
desc "Deploy all assets in public/assets to S3/Cloudfront"
task :deploy, :env, :branch do |t, args|
## Use the `s3` gem to connect my bucket
puts "== Uploading assets to S3/Cloudfront"
AWS::S3::Base.establish_connection!(
:access_key_id => AWS_ACCESS_KEY_ID,
:secret_access_key => AWS_SECRET_ACCESS_KEY
)
service = AWS::S3::Service.new(
:access_key_id => AWS_ACCESS_KEY_ID,
:secret_access_key => AWS_SECRET_ACCESS_KEY)
bucket = AWS::S3::Bucket.find(AWS_BUCKET)
## Needed to show progress
STDOUT.sync = true
## Find all files (recursively) in ./public/assets and process them.
Dir.glob("public/assets/*").each do |file|
## Only upload files, we're not interested in directories
if File.file?(file)
## Slash 'public/' from the filename for use on S3
remote_file = file.gsub("public/", "")
## Try to find the remote_file, an error is thrown when no
## such file can be found, that's okay.
begin
obj = bucket[remote_file]
rescue
obj = nil
end
## If the object does not exist, or if the MD5 Hash / etag of the
## file has changed, upload it.
if !obj || (obj.etag != Digest::MD5.hexdigest(File.read(file)))
print "U"
## Simply create a new object, write the content and set the proper
## mime-type. `obj.save` will upload and store the file to S3.
AWS::S3::S3Object.store(remote_file, open(file), AWS_BUCKET)
else
print "."
end
end
end
STDOUT.sync = false # Done with progress output.
puts
puts "== Done syncing assets"
end
end
https://ariejan.net/2011/01/01/rake-task-to-sync-your-assets-to-amazon-s3cloudfront/

Monday, 2 March 2015

CSE341: Programming Languages, Winter 2013

http://courses.cs.washington.edu/courses/cse341/13wi/



CSE341: Programming Languages, Winter 2013



Course Information



Course Materials

Material in the future naturally subject to change in terms of coverage or schedule
  1. Unit 1: ML Functions, Tuples, Lists, and More    Reading Notes    Videos
  2.   L1. Jan 7-9: Course Mechanics, ML Variable Bindings   slides: pptx   pdf   pdf6up   code: sml
  3.   L2. Jan 9: Functions, Pairs, Lists   slides: pptx   pdf   pdf6up   code: sml
  4.   S1. Jan 10: Emacs, SML Mode, Shadowing, Error Messages   slides: pdf   pdf4up   code: errors.sml   solutions.sml
  5.   L3. Jan 11: Local Bindings, Options, Benefits of No Mutation   slides: pptx   pdf   pdf6up   code: sml
  6.  
  7. Unit 2: Datatypes, Pattern Matching, Tail Recursion, and More    Reading Notes    Videos
  8.   L4. Jan 14: Records, Datatypes, Case Expressions   slides: pptx   pdf   pdf6up   code: sml
  9.   L5. Jan 16: More Datatypes and Pattern Matching   slides: pptx   pdf   pdf6up   code: sml
  10.   S2. Jan 17: Type Synonyms, Polymorphism, & More   slides:   pptx   pdf   code:   synonyms.sml   generics.sml  equality.sml   fun_patterns.sml
  11.   L6. Jan 18: Nested Pattern-Matching, Exceptions, Tail Recursion   slides: pptx   pdf   pdf6up   code: sml 
    Tail recursion moved to Jan 23 after the Jan 21 holiday
  12.  
  13. Unit 3: First-Class Functions and Closures    Reading Notes    Videos
  14.   L7. Jan 23: First-Class Functions   slides: pptx   pdf   pdf6up   code: sml
  15.   S3. Jan 24: Standard-Library Docs, Unnecessary Function Wrapping, Map, & More   slides: pdf   pdf4up   code:sec3.sml   higher-order.sml
  16.   L8. Jan 25: Lexical Scope and Function Closures   slides: pptx   pdf   pdf6up   code: sml
  17.   L9. Jan 28: Function-Closure Idioms   slides: pptx   pdf   pdf6up   code: sml
  18.  
  19. Unit 4: ML Modules, Type Inference, Equivalence, & More    Reading Notes    Videos
  20.   L10. Jan 30: ML Modules   slides: pptx   pdf   pdf6up   code: sml
  21.   S4. Jan 31: Mutual Recursion, More Currying, More Modules   slides:   pptx   pdf   code:   all_pairs.sml   bank.sml  mutual_rec.sml
  22.   L11. Feb 1: Type Inference   slides: pptx   pdf   pdf6up   code: sml
  23.   L12. Feb 4: Equivalence   slides: pptx   pdf   pdf6up
  24.  
  25. Course-Motivation Interlude, Feb 4-6  slides  pdf  pdf6up   Videos
  26.  
  27. Unit 5: Racket, Delaying Evaluation, Memoization, Macros    Reading Notes    Videos
  28.   L13. Feb 6-11: Racket Introduction   slides: pptx   pdf   pdf6up   code: rkt
  29.   S5. Feb 7 <Midterm Review for Midterm on Feb 8>
  30.   L14. Feb 13: Thunks, Laziness, Streams, Memoization   slides: pptx   pdf   pdf6up   code: rkt
    Some of the material in L14 is covered in S6 instead
  31.   S6. Feb 14: More streams, memoization, etc.   slides: pdf   pdf6up   code: sec6.rkt   streams.rkt
  32.   L15. Feb 15: Macros   slides: pptx   pdf   pdf6up   code: rkt
  33.  
  34. Unit 6: Structs, Implementing Languages, Static vs. Dynamic Typing    Reading Notes    Videos
  35.   L16. Feb 15-20: Datatype-Style Programming With Lists or Structs   slides: pptx   pdf   pdf6up   code: rkt   sml
  36.   L17. Feb 20-22: Implementing Languages Including Closures   slides: pptx   pdf   pdf6up   code: rkt
    Some of the material in L17 is covered in S7 instead
  37.   S7. Legal ASTs, Macros as Functions, and More   slides: pdf
  38.   L18. Feb 22-25: Static vs. Dynamic Typing   slides: pptx   pdf   pdf6up   code: rkt   sml
  39.  
  40. Unit 7: Ruby, Object-Oriented Programming, Subclassing    Reading Notes    Videos
  41.   L19. Feb 27: Introduction to Ruby and OOP   slides: pptx   pdf   pdf6up   code: lec19_silly.rb   lec19_example.rb
  42.   S8. Ruby arrays, hashes, ranges, blocks, and more slides   (See also material posted with L20.)
    Some of the material in L20 is covered in S8 instead
  43.   L20. Mar 1-4: Arrays & Such, Blocks & Procs, Inheritance & Overriding   slides: pptx   pdf   pdf6up   code: rb
  44.   L21. Mar 4-6: Dynamic Dispatch Precisely, and Manually in Racket   slides: pptx   pdf   pdf6up   code: rb   sml   rkt
  45.  
  46. Unit 8: Program Decomposition, Mixins, Subtyping, and More    Reading Notes    Videos
  47.   L22. Mar 6-8: OOP vs. Functional Decomposition; Adding Operators & Variants; Double-Dispatch 
       slides: pptx   pdf   pdf6up   code stage A:   sml   rb   java   code stage B:   sml   rb   java   code stage C:   sml   rb   java
  48.   S9. Mar 7: Double-Dispatch, Expression Problem, Mixins, and Visitors   slides: pdf   pdf6up   code: janken.rb  janken.sml   helpers.sml   mixins.rb   visitor.rb   visitor.sml
  49.   L23. Mar 8: Multiple Inheritance, Mixins, Interfaces, Abstract Methods   slides: pptx   pdf   pdf6up   code: rb
  50.   L24. Mar 11-13: Subtyping   slides: pptx   pdf   pdf6up
  51.   L25. Mar 13: Subtyping for OOP; Comparing/Combining Generics and Subtyping   slides: pptx   pdf   pdf6up
  52.   S10. Mar 14: Review, Especially Subtyping   slides: pdf   counter-examples
  53.  
  54. L26. Mar 15: Course Victory Lap   slides: pptx   pdf   pdf6up