Git ask and answer

1.How to use git to checkout remote branch?

First you need to fetch those new remote branches by using:

1
git fetch origin
1
show and see all the branches:
1
git branch -v -a

Then checkout the branch you are interested in:

for example: a remote branch named test and you want to checkout this branch by using the name mybranch

1
git checkout -b mybranch origin/test

If your Git version >= 1.6.6 you can simply by running:

1
git checkout test

Relearn javascript : New Sight of Function

This post will not cover every part of javascript. what it going to include are something kind of ‘new’ to myself.

1.The method invocation pattern and function invocation pattern

When a function is invoked as a property of an object, we say it is invoked as a method. when a method is invoked, this refers to the current object.

for example:

1
2
3
4
5
6
7
8
var user = {
"username" : "bigruan",
"password" : "123456",
"sayHello" : function() {
return "Hello " + this.username;
}
}
console.log(user.sayHello()); //Hello bigruan

When a function is not the property of an object, it is invoked as a function.

for example:

1
2
3
4
var sayhello = function() {
console.log("hello");
}
sayhello();

However, when function was invoked like this, this will be bind to global object.

for example:

1
2
3
4
5
6
7
8
9
10
11
var user = {
"username" : "bigruan",
"password" : "123456",
"sayHello" : function() {
function say() {
return "Hello " + this.username;
}
return say();
}
}
console.log(user.sayHello()); //Hello undefined

the output could be undefined! how can we do with this situation?

the solution could be very easy:

1
2
3
4
5
6
7
8
9
10
11
12
var user = {
"username" : "bigruan",
"password" : "123456",
"sayHello" : function() {
var that = this; //one line hacker
function say() {
return "Hello " + that.username;
}
return say();
}
}
console.log(user.sayHello()); //Hello undefined

other invocation pattern like apply and new will not discussed.

2.Arguments

When a function is invoked, an array named arguments can be accessed in the function which contains all the parameters. Even the ones that are not showed in the function parameters.

1
2
3
4
5
6
7
8
9
10
function sum() {
var i,
sum = 0;
for(i=0; i<arguments.length; i++) {
sum += arguments[i];
}
return sum;
}

console.log(sum(1, 2, 3, 4, 5));

Relearn javascript : Basic Object Concepts

1.Define an Object

1
2
3
4
5
6
7
8
//define an empty object
var user = {}

//or with initial properties
var user = {
"userName" : "bigruan",
"passwd" : "123456"
}

It is not necessary to surround properties with quote if property name is a legal javascript name. For example: quotes are necessary for user-name but optinal for userName.

Legal javascript name: contains letters(upper case or lower case), digitals, _ and $ , but should not begin with digital

Object can nest:

1
2
3
4
5
6
7
8
9
var user = {
userName : "bigruan",
passwd : "123456",
car : {
brand : "Audi",
price : 1000
}
}
console.log(user.car.price); //1000

2.Object Property values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//access by [] or .
console.log(user["userName"]); //bigruan
console.log(user["car"]["price"]); //1000
console.log(user.userName); //bigruan
console.log(user.car.price); //1000

//if property not defined, the value will be undefined
console.log(user.child); // undefined
console.log(user["child"]); // undefined

//if trying to retrieve value from undefined, there will be a TypeError.
var childName = user.child.name; //TypeError
//A good practice to avoid this error
var childName = user.child && user.child.name;

Update property value. if property name was defined, value will be replaced by the new value. if there is no such property, a new property will be added to this Object.

1
2
user.userName = "yulong"; //value of userName is updated
user.child = {}; //new property child is added

Retrieve value by for in loop.

1
2
3
for(var key in user) {
console.log(user[key]);
}

3.Object passed by reference and can not be copied

1
2
3
4
5
var user2 = user;
user2.userName = "bigruan2";
console.log(user.userName);
// userName of user is bigruan2,
// because user and user2 are references to the same object

How to use git reset

Q1: How to undo git pull?

Actually git pull do two things, first run git fetch and then git merge.

If there are conflicts, merge will not be commit to local repo. So, just run the following command to reset your working directory and stating area.

1
git reset --hard

If there is not conflict, the merge will commit to the local repo, if you want to reset git pull immediatetly, run the following command to reset local repo, stating area and working directory to the previous commit.

1
git reset --hard HEAD^

Q2: How to undo git add?

1
git reset

or:

1
git reset HEAD

They are the same.

What this command do is to use local repo to replace stating area. All files that add to stating area will be affected.

What if just some specified files? Then you can run:

1
git reset -- filenmae

Q3: How to undo git commit if I am not satisfied with the comment?

1
git reset --soft HEAD^

By running reset with –soft the working directory and stating area will not change but the local repo will be reset to specified ref. for example here is HEAD^ which means the previous one commit.

image

Integrate django with apache2 via mod_wsgi

For django 1.6:

First, install mod_wsgi

1
~$ sudo apt-get install libapache2-mod-wsgi

Config virtual Host for Apache:

1
2
~$ sudo touch /etc/apache2/sites-available/appname.example.com
~$ sudo vim /etc/apache2/sites-available/appname.example.com

Add these:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www/appname
ServerName appname.example.com

Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

AliasMatch ^/([^/]*\.css) /path/to/mysite.com/static/styles/$1

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Order deny,allow
Allow from all
</Directory>

<Directory /path/to/mysite.com/media>
Order deny,allow
Allow from all
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Order allow,deny
Allow from all
</Files>
</Directory>

ErrorLog ${APACHE_LOG_DIR}/appname.example.com-error.log
CustomLog ${APACHE_LOG_DIR}/appname.example.com-access.log combined

LogLevel warn
</VirtualHost>

Then enable this site:

1
2
~$ sudo a2ensite appname.example.com
~$ sudo /etc/init.d/apache2 restart

Add the django project path to System Path of Ubuntu.

1
2
3
4
5
6
7
import os,sys
#Add the path of django project to System Path
sys.path.append('/home/username/path/to/djangoproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Long press in javascript

Way to detect a long press event.

1
2
3
4
5
6
7
8
9
10
11
var pressTimer

$("a").mouseup(function(){
clearTimeout(pressTimer)
// Clear timeout
return false;
}).mousedown(function(){
// Set timeout
pressTimer = window.setTimeout(function() { ... your code ...},1000)
return false;
});

This can also be used in touch event.

Null and Undefined in javascript

1.Null and Undefined

In javascript an undefined variable is a variable that never been declared or never assigned a value.

1
2
var foo;
console.log(foo); // The output will be: undefined

If you assign foo = null. Then foo will be null which is a javascript object

1
2
3
4
5
var foo;
console.log(typeof foo); //output: undefined

foo = null;
console.log(typeof foo); //output: object

2.Confuse of working with “==” and “===”.

=== means strictly equal which will check both type and value.

Servral samples:

1
2
3
4
null === null            # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true

3.What is false in javascript?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if(!false) {
//definitely, false is false
}
if(!undefined) {
//undefined is false
}
if(!null) {
//null is false
}
if(!'') {
//empty string '' is false
}
if(!0) {
//numver 0 is false
}
if(!NaN) {
//numver NaN is false
}

Except these value, others could be regard as true.

ref: http://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and

JSON in Javascript

1.Create JSON

You can create it like this:

1
2
3
4
5
6
7
8
var foo = {
"name" : "Ruan",
"age" : 25,
"bar" : {
"name" : "Qiu",
"age" : 24
}
}

or like this:

1
2
3
4
5
6
7
8
9
var foo = {},
bar = {};
foo.name = "Ruan";
foo.age = 25;

bar.name = "Qiu";
bar.age = 24;

foo.bar = bar;

2.Access value in a JSON object

1
2
console.log(foo.name); //output: Ruan
console.log(foo.bar.name); //output: Qiu

or

1
2
console.log(foo["name"]);
console.log(foo["bar"]["name"]);

3.Get values by loop

1
2
3
for(var key in foo) {
console.log(foo[key]);
}

Someone may say that it is exactly javascript object, so what is the difference between json and javascript object?

JSON is:

  1. It is language agnostic data-interchange format.
  2. The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

ref:http://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object

For example, in JSON all keys must be quoted, while in object literals this is not necessary:

1
2
3
4
5
// JSON:
{ "foo": "bar" }

// Object literal:
var o = { foo: "bar" };

Javascript object can be convered to JSON format by JSON.stringify(obj) which keys/properties names will be quoted automatically. However, it is mandatory(good behavior) to use double quotes when define a JSON object.

4.Use native JSON

1
2
3
4
5
6
7
//Convert a JavaScript object into a JSON string
var jsonString = JSON.stringify(foo);
//output: {"name":"Ruan","age":25,"bar":{"name":"Qiu","age":24}}

//Convert a JSON string into a JavaScript object
var jsonObj = JSON.parse(jsonstring);
//result: a javascript object
  • NOTE: in JavaScript 1.8.5
  • Starting in JavaScript 1.8.5 (Firefox 4), JSON.parse() does not allow trailing commas
1
2
3
// both will throw a SyntaxError as of JavaScript 1.8.5
var jsObject = JSON.parse("[1, 2, 3, 4, ]");
var jsObject = JSON.parse("{ \"foo\" : 1, }");

Media queries in css

An easy way to make your website “responsive”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@media screen and (min-width:600px) {
nav {
float: left;
width: 25%;
}

section {
margin-left: 25%;
}

}
@media screen and (max-width:599px) {
nav li {
display: inline;
}

}

If screen width >= 600px, nav,section elements will display as this, and if screen width <= 599px, nav,section elements will display like that, quite easy!