Hexa's Blog

Conkeror, Deleting all history instantly

02/05/2015 Conkeror

There is a small function you have to write to delete your history instantly. source

function history_clear () {
    var history = Cc["@mozilla.org/browser/nav-history-service;1"]
        .getService(Ci.nsIBrowserHistory);
    history.removeAllPages();
}
interactive("history-clear",
    "Clear the history.",
    history_clear);

JavaScript learning

30/04/2015 cheatsheet

1. Function and Variable

a. Declare function

var function_name = function(){
//Do something here
}

b. Declare variable

var variable_name = 123;

c. Reuse method

var function_namedA = function(){
    this.age = 123;
    Console.log(this.age);
}
var Bob = {
    age = 12;
}
Bob.function_namedA();
//The age of Bob changed from 12 to 123

#2. Object a. Make an object

// type 1
var object_name = {
	variable_name1 = 123;
    variable_name2 = 123;
}
// type 2
object  = new Object();
object.variable_name1 = 123;

b. Make constructor of an object

function Person(job, age){
    this.job = job;
    this.age = age;
}

c. Use constructor of an object

var Bob = new Person('engineer', 23);

d. Use variables of an object

//type 1
var a = object[var_name]
//type 2
var a = object.var_name

e. Private and public variables and function

  • private variables are declared with the var keyword inside the object, and can only be accessed by private functions and privileged methods.
  • private functions are declared inline inside the object’s constructor (or alternatively may be defined via var functionName=function(){...}) and may only be called by privileged methods (including the object’s constructor).
  • privileged methods are declared with this.methodName=function(){...} and may invoked by code external to the object.
  • public properties are declared with this.variableName and may be read/written from outside the object.
  • public methods are defined by Classname.prototype.methodName = function(){...} and may be called from outside the object.
  • prototype properties are defined by Classname.prototype.propertyName = someValue
  • static properties are defined by Classname.propertyName = someValue
var Person = function(job, age){
    //job and age are public variables
    this.job = job;
    this.age = age;
	//sex is private variable
	var sex = 'male';
	//printJob() is a public function
    this.printJob(){
	    Console.log(this.job);
	}
	//sayHello() is private function
	var sayHello = function(){
	    Console.log('Hello');
	}
}
Person.variable = 123; //variable is pointing to object named Person
Person.prototype.variable = 345; //variable is pointing to the function of object named Person

#3. Inheritance a.Inheritance object

var a = {a: 1};
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty);
// undefined, because d doesn't inherit from Object.prototype

#4. Notes

  • Keyword this, within a function, this refers to object which call the function.

Haivl mode for Conkeror

17/04/2015 Projects

This project is a project for hackday in Cogini company in 2014 1. Identify the page mode

define_keymaps_page_mode("haivl_mode",
       build_url_regexp($domain="haivainoi",
					    $allow_www = true,
					    $tlds = ["com", "tv"]),
       {normal: haivl_keymap},
       $display_name = "haivl");

2. Declare css selector, relative variables

var haivl = {};
haivl.selector = {};
haivl.selector.nav = ".top-menu.left>ul>li>a"
haivl.selector.seemore = ".button-readmore>a"
haivl.name = ["New", "Unread", "Vote","Video","Hot", "SeeMore"];

3. Declare function to make a click action to DOM node

haivl.doClick = function(I, index ){
  var document = I.buffer.document;
  var button_array = document.querySelectorAll(haivl.selector.nav);
  if(button_array[index] != null){
	dom_node_click(button_array[index]);
  }else {
 	I.minibuffer.message("Button: " + haivl.name[index] + " not found." + "length: "+ button_array.length);
  }
  I.minibuffer.message(I);
}
haivl.doClickSeeMore = function(I){
  var document = I.buffer.document;
  var button = document.querySelector(haivl.selector.seemore);

  if(button != null){
	dom_node_click(button);
  }else {
 	I.minibuffer.message("Button: " + haivl.name[5] + " not found.");
  }
}

4. Make those function become interactive

interactive("haivl-1","new feeds", function(I){
  haivl.doClick(I, 0);
});
interactive("haivl-2", "unread feeds",function(I){
  haivl.doClick(I,1);
});
interactive("haivl-3", "vote feeds", function(I){
  haivl.doClick(I,2);
});
interactive("haivl-4", "video feeds", function(I){
  haivl.doClick(I,3);
});
interactive("haivl-5", "hot feeds", function(I){
  haivl.doClick(I,4);
});
interactive("haivl-seemore", "see more feeds",function(I){
  haivl.doClickSeeMore(I);
})

5. Reference I must say thank to Tran Xuan Truong, Quan Bao Thien To. When I write this bunch of code I don’t know much about javascript. In addition, regarding Conkeror technical issues, I gained help from Tran Xuan Truong who is a master in Conkeror Web browser and he is one who has a big love in programming. Thank you, I will remember the hackday.

Right now, It’s April 14, 2015. I note this memory to remember a day of doing new things, learning new things and of course, because it’s a memorial hackday. Even though, currently, the haivl.com has been collapsed,but this project still work with haivainoi.com

Apache Web Server, Forbidden Error

17/04/2015 etc

Problem: Apache Web Server announces that Forbidden Error, given that developers configure Allow and Deny directory with no mistake Reason: A lack of Indexes for files in directory. Solution: Add option Indexes in directory tag <Directory>

Example: The following configuration causes forbidden error

<Directory "/home/pvt/apache2/htdocs">
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

The following configuration solve the problem

<Directory "/home/pvt/apache2/htdocs">
    Options Indexes FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Bootstrap fonts working with rails 4, asset pipeline

09/04/2015 Ruby on Rails 4

Problems: Cannot load the fonts of bootstrap Reason: In Rails, all assets are loaded from host:port/assets not host:port/fonts Solution: Replace the source url in @font-face, from ../fonts/ to /assets

Original version:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

Edited version:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('/assets/glyphicons-halflings-regular.eot');
  src: url('/assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('/assets/glyphicons-halflings-regular.woff') format('woff'), url('/assets/glyphicons-halflings-regular.ttf') format('truetype'), url('/assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

Music-api, a web-service to work with online music source

02/02/2015 Projects

Introduction

There is no need to descript more about the project, the main role of this project named music-api is to provide a web service for developers to exploit indirectly the song’s information coming from any online source such as ZingMp3, Nhaccuatui.

This project is an open source software, developers contribute and developer my project. This time, this is only two online source ZingMp3 and Nhaccuatui, however, the number source will be increased regarding developers’ demand.

The song information includes name, singers, lyrics, song's page and inparticular song's source for downloading.

Why does it work ?

Fundamentally, this service send a request to music oridinary servers, after receiving responses, it analyze the response (inspect elements selectively). After finished analysis, it send json object which inlcluding all song’s information. Currently, the web service is deployed at USA by heroku, Because of IP filter applying by VNG(ZingMp3), there are some songs which you cannot search. I have tested by using VPN locating in the USA, the result is limited.

Good news is that Nhaccuatui is very generous, they allow foreign IP to access all song, meanwhile, you can exploit from more songs.

How-to guide

Disable active record (nodatabase uses) in Rails 4

27/01/2015 Ruby on Rails 4

This article shows a quick tweak to unuse database gem, disable active record in Ruby on Rails 4.x

1. For new projects, run the following command to generate new project

rails new YourProject --skip-active-record

2. For existing projects

  • Edit file config/application.rb, remove require 'rails/all' and add:
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
  • Edit file /config/environment/development.rb, remove the following line:
config.active_record.migration_error = :page_load
  • Remove gem named sqlite3 in Gemfile
  • Delete or Comment (recommend) database.yml, db/schema.rb
  • Delete configuration in files in config/environments directory

Ruby - learning

06/01/2015 cheatsheet

#1. Variable in ruby class

  • Local variable: defined inside a method, the usage of local variable in only inside a method. Prefix of local variable is _ or [a-z].
  • Instance variable: instance variable is available accross methods and object, meanwhile, instance variable change from object to object. Prefix of instance variable is @. Instance variable is not shared among its descedants.
  • Class variable: it belongs to a class and is a characteristic of this class. Prefix is @@. Class variable is share among its descedants(childs).
  • Global variable: class varaible is not across class, however, global variable does. The prefix of global variable is $.
  • Constant variable: it’s similar to class variable but it’s constant. Constant varaibles should be in upper case for all letters.

#2. Commenting

  • Using =begin and =end
=begin
This is a multiline comment and con spwan as many lines as you
like. But =begin and =end should come in the first line only.
=end
  • Using #
 # This is a single line comment.

#3. Method

def method_name (arg = default_value,arg2 = default_value2 )
    expression
end

#4. Block

  • Block must be named after a name of a method (or a function), other while, it does not work. Usage: In a method, there might be an chunk of code which is used many time within the method, the point is that, this chunk of code is not worth making a new function or maybe programmers don’t want to make a function on that chunk (they cannot think a name for that).
def function_name
   puts "In a function"
   yield
   puts "Come back to function"
end

function_name{
   puts "In a block"
}
  • It’s also possible to insert parameters into a block. However, if a function has parameters, I don’t know but there is a error and cannot use block with function which have parameters.
def function_name
   yield a, b
end
function_name {
   |a,b|
   puts a+b
}

#5. Class

  • Class structure
 #making a class
class Box
end
  • Initial method
class Box
 #`@` is a declare of instance varaibles
    def initialize(w,h)
	    @width = w
		@height = h
    end
end
  • Getters and setters
class Box
    @@number_of_box = 0
    def initialize(w,h)
	    @width = w
		@height = h
    end
    # These are getters
    def printWidth
	    @width
	end
    def printHeight
	    @height
    end
    #These are setters
	def setWidth=(new_value)
	    @width = new_value
	end
	def setHeight=(new_value)
	    @height = new_value
    end
	#usage of @@class variables
    def printNumberOfBox
	    puts @@number_of_box
	end
end

#6. Access control: Public, Private, Protected

  • Public method: is called by anyone. By default, all methods excepting initialize method are public methods.
  • Private method: only class methods can access private methods
  • Protected method: is called by class method and its subclass method.
private :functionA, :functionB
protected :functionD, :functionD

#7.Inheritance, method overriding, operator overloading

  • ’<’ is used to indicate inheretent from class to class
class Box
end

class AutoBox < Box
end
  • Method overriding: change existing method (parent class) to new method (child class)
class Box
    def print
	    puts "base class"
    end
end

class AutoBox < Box
    def print
	    puts "child class"
    end
end
  • Method overloading: Unlike java, ruby is using dynamic typed language, as a results, it’s impossible to using overriding if depending on variable types. On the other hand, it uses number of parameters to differentiate methods.
def function_name(a,b) #there is no type declaring, compiler does not know
end                    #how to override

def function_name(a,b) #As a consequence, compiler uses number of parameters to
end                    #differentiate two methods

def function_name(a)
end

8. Loop

a. While loop

_counter = 0
while _counter < 5
  puts _counter
  _counter++
end

b. For loop

  # range is [0-5]
for counter in 0..5
  puts counter
end
  # range is [0-5)
for counter in 0...5
  puts counter
end

#9. Symbols a. What is this Symbols in ruby are immutable. Besides this point, it’s a string. It’s able to print put the value of a symbol in term of string or integer

:age #this is a symbol named age
puts :age # print out age's value in string
puts :age.object_id # print out age's object id

b. Implementation Automatic make new method based on the symbols

def make_me_a_setter(thename)
	eval <<-SETTERDONE
	def #{thename}(myarg)
		@#{thename} = myarg
	end
	SETTERDONE
end

class Example
	make_me_a_setter :symboll
	make_me_a_setter "stringg"

	def show_symboll
		puts @symboll
	end

	def show_stringg
		puts @stringg
	end
end

example = Example.new
example.symboll("ITS A SYMBOL")
example.stringg("ITS A STRING")
example.show_symboll
example.show_stringg
  # reference: http://www.troubleshooters.com/codecorn/ruby/symbols.htm

#10. Hash a. Declare a hash

  • Old hash
old_hash = {:var1 => "cat", :var2 => "dog"}
  • New hash
new_hash = {var1 : "cat", var2 : "dog"}

b. Access element

new_hash = {var1 : "cat", var2 : "dog"}
puts new_hash[:var1]
puts new_hash["var1"]

c. Documentation link

Python - learning

07/12/2014 cheatsheet

This is a remember note to learn python, more or less, it’s writen for me -the author to rememeber main issues of python.

1. Scope and Namespace

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

The output is:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Explaination:

  1. Local variable always is always used inside local scope. In the example, local variable spam has value is local spam, when do_local() invoked, spam only created inside a function, it has no use outside.
  2. Non local variable has been declared and it affect within scope_test and only within scope_test.
  3. Global variable only used in global scope.
  4. In Python, a function can exist inside a function, in the example above, do_local insides scope_test.
  5. Functions make its own scope.

##2. Class

class Dog:

    kind = 'canine'         # class variable shared by all instances
    def __init__(self, name):
        self.name = name    # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'

Notes:

  1. Class variables shared by all instances, kind is class variable.
  2. Instance variables shared by each instance,name is instance variable.
  3. Function can be define outside class.
# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1
    def g(self):
        return 'hello world'
    h = g

3. Inheritence

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

class DerivedClassName(modname.BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

Call baseclass method, base class must be in global scope:

BaseClassName.methodname(self, arguments)

Check instance type:

isinstance(obj, int) #check if `obj` is instance of `int`
issubclass(bool, int) #check if `bool` is subclass of `int`

Git - cheatsheet

05/12/2014 cheatsheet

1. Untrack an already check-in directory or file

git rm -r --cached folder_name

-r : recursive –cached: files or directories are only deleted on the git’s index, not on local storage.

2. See all submodules

cat .gitmodules

3. Add a submodule

git submodule add url_of_submodule

4. Initialize all submodules

git submodule init

5. Reset stage to the last commit

git reset --hard HEAD

6.Clone repository with a particular folder name

git clone git@github.com:whatever folder-name