Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Tuesday, December 20, 2011

MongoDB vs Redis vs Cassandra for a fast-write, temporary row storage solution

This link is a topic in stackoverflow, which is talking about comparing well-known NoSQL write operation such as MongoDB, Redis, and Cassandra.

Here: http://stackoverflow.com/questions/3010224/mongodb-vs-redis-vs-cassandra-for-a-fast-write-temporary-row-storage-solution

When Does Amazon EC2 Reserved Instance Pricing Save Money

This blog will show some calculations to find the best usage point from the instance pricing.

HBase vs Cassandra: why they moved

This link is about the company which changed from HBase to Cassandra. He is working on a brand new product. He will explain why he don't use MySQL, and use NoSQL instead. But, before his team is going to use Cassandra, which is good at scalability and fault-tolelarance, they used HBase. Therefore, in this post he will tell why he changed from HBase to Cassandra.

Here: http://ria101.wordpress.com/2010/02/24/hbase-vs-cassandra-why-we-moved/

Java vs Python on Hadoop

Normally, in term of programming languages, the scripting languages are surely slower than Java , it mainly because Java has JVM to optimize running programs, also the code will be pre-complied before execution. But, scripting languages like Python usually use interpreter to compile and execute line by line. Still, Hadoop, which is written in Java also provide the universal interface for other languages by using streaming interface. Even, Java can run faster than Python but Python can develop programs faster. Compared to other scripting languages, Python is one of the faster ones after Java.

More details at: http://stackoverflow.com/questions/1482282/java-vs-python-on-hadoop.

Difference between Pig and Hive? Why have both?

There are some arguments in stackoverflow.

Thursday, December 1, 2011

Benchmark of Python WSGI Web Servers

Take a look this site, http://nichol.as/benchmark-of-python-web-servers. He tried his best to benchmark the different WSGI servers. He presented in graphs to make easy understanding.

Monday, November 28, 2011

Run internet required commands behind a proxy server in Linux

Most of the time I need to run a terminal behind a proxy server at my office to run a batch job, and I failed to run it because I don't know how to add proxy server in the terminal. But, now, I just found the command to add a proxy server in Linux. It's very simple just only one line :)

Open terminl and type this command
# Changing username, password, proxyname, and port to be yours.
export http_proxy="http://username:password@proxyname:port"
# After that you can test to run behind your proxy server
# , simply as following.
wget http://www.google.com
# If the connection is successful, then you will get the 
# file from this Google page.

To remove the proxy server from your network run the following command:
# Just delete a proxy sever variable using unset 
unset http_proxy
# Or set http_proxy to blank
export http_proxy=""

The example above is how bind a proxy server in HTTP protocol.
For the other protocols, e.g. FTP, ... so on. Try to find its variable for binding with a proxy server.
Another protocol that I know is FTP.
FTP => ftp_proxy
If you want to remove it, do the same as the example above.

Good luck ^^.

How to restart Linux network service

Sometime you may need to update your network immediately, e.g. DHCP and IP under a virtualization software, ... so on. The fastest way is to restart the network service.

You need to login as root user before using the following commands!!!

RedHat Linux command to reload or restart network:
# To restart Linux network service:
$ service network restart
or
$ /etc/init.d/network restart

# To start Linux network service:
$ service network start

# To stop Linux network service:
$ service network stop
Debian Linux command to reload or restart network:
# To restart Linux network service:
$ /etc/init.d/networking restart

# To start Linux network service:
$ /etc/init.d/networking start

# To stop Linux network service:
$ /etc/init.d/networking stop
Ubuntu Linux user use sudo command with above Debian Linux command:
# To restart Linux network service:
$ sudo /etc/init.d/networking restart

# To start Linux network service:
$ sudo /etc/init.d/networking start

# To stop Linux network service:
$ sudo /etc/init.d/networking stop

Credit: http://theos.in/desktop-linux/tip-that-matters/how-do-i-restart-linux-network-service/

Tuesday, November 22, 2011

Adding Facebook Like Button to your Blogger posts

According to Blogger default don't provide essential social plugins like "Like-Button" in a post. We, however, can includes it into each of your post easily as the following steps:
  1. You needs to create an App in Facebook at: https://developers.facebook.com.
  2. So, you will get the App API key.
  3. Go to https://developers.facebook.com/docs/reference/plugins/like/ page to customize your Like-Button as your preferred style. After finish, click at get code, then copy that code (HTML5) to somewhere. You will get 2 portions of code, first and second.
  4. Go to your Blogger template, select edit HTML manually then click at expand the widget because post customization is in the widget portion.
  5. Go deep to the above widget code zone (almost at the end), or if you can't find you can put it on the top, but this code will be loaded first before loading Blogger data.
  6. Paste your first half of Facebook code above widget code.
  7. Next, you need to find the template for each post, then append the second half to that template. For me, I want to append Like-Button  followed the default share buttons. So, I will search for "shareButtons". It may have many shareButtons words in your template, but to know the one you want is that it has a code to describe its components e.g. Twitter, Gmail, Facebook, Google+ buttons.
  8. Finally, append the second half of Facebook code here, but it need to change a "data-href" attribute to be "expr:href" as a Blogger data, and put its value equals to "data:post.url".
    For example: 
  9. <div class="fb-like" data-send="true" data-show-faces="true" data-width="450" expr:href="data:post.url"> </div>
  10. Done, save the your code and view your post!!!
Like This Post!!!

Friday, November 18, 2011

Stanford Online Courses in Q1 2012

The following Stanford Online Classes will be opened in Q1 next year!!!
1. CS 101 by Nick Parlante
2. Natural Language Processing by Dan Jurafsky and Chris Manning
3. Software Engineering for SAAS by Armando Fox and David Patterson
4. Human-Computer Interfaces by Scott Klemmer
5. Game Theory by Matthew Jackson and Yoav Shoham
6. Probabilistic Graphical Models by Daphne Koller
7. Machine Learning by Andrew Ng (Same class as current ml-class.org)

Moreoever, Stanford Entrepreneurship Online Classes will be opened in Q1 next year too.

1. The Lean Launchpad - http://www.launchpad-class.org/
2. Technology Entrepreneurship - http://www.entrepreneur-class.org/

Don't wait until the last moment :)

Tuesday, November 1, 2011

The Lemur Project - SEO Tools

Lemur is an opensource toolkit for Information Retrieval and language modeling, It also provides API in C++, JAVA, C#, etc. I used it to check ranking among my website pages and competitor pages.
To use this tool, you have to download it first from http://www.lemurproject.org/.
Then, to allow Lemur indexing your pages you need to put Lemur' headers for all of your indexed pages as the following code:

<doc>
<docno>FULL PATH TO THIS FILE<⁄docno>
<dochdr><⁄dochdr>
.
.
.
YOUR HTML CONTENT
.
.
.
<⁄doc>

Next, let's see urllist.txt, you need to put all of full path of your indexed files one line per one file path.
C:\seo\competitors\aol\1.html
C:\seo\competitors\bbc\1.html
C:\seo\competitors\bbc\2.html
.
.
.

After that, edit queries.txt, insert keywords with one keyword per line.
carbon dioxide
cfc
fuel
.
.
.

Assume that my Lemur' folder is named seo. Do as follows:
1. Open a command window.
2. Go to seo directory by type in the following commnad.
cd C:\seo
3. To index the web pages (both competitors and cfs), type this
C:\seo\lemur\bin\BuildIndex.exe buildparam.txt
4. To run a query, type this
C:\seo\lemur\bin\RunQueriesHTML.exe queryparam.txt
5. Open the result file located in C:\seo\results.html with you web browser

Finally, you will see the result similar to the following picture:










Enjoy using it xD.

Thursday, October 27, 2011

Fate Unlimited Codes (PS2)

Game Cover
Recently, I have watched Fate Stay Night and Fate Unlimited Blade Works for the fifth times. I also just found the game named Fate Unlimited Codes in PS2 (it is quite old game), and wanted to try it very much. It is a fighting game. In the game, you can select characters among masters and servants to play. There are some special secrets in this game such as Saber Lily costume, Zero Lancer, and Leysritt (Ilya's housekeeper).

Saber Lily














You can download this game here.
For how to play and secrets, take a look at here.
Mission mode information, go to this site.
Note that Ex attacks/specials can be used if the following conditions are passed:
1 - The Holy Grail Meter (the "chalice" under the timer) must be FULL
2 - Make sure you have 3 bars of Mana
3 - Deal damage to your opponent while the Holy Grail is full to get your life bar flashing
4 - Go into EX Mode/Overdrive/whatever you want to call it by pressing the three attack buttons together (and while you still have 3 bars full of Mana)
5 - Input the commands for the EX Attack.
6 - Make sure your attack actually HITS.
7 - Enjoy the EX Attack animation.
p.s. Go to practice mode to make you getting more ideas.


Special Box


Monday, October 17, 2011

Install Linux on Your Mac

Read this article: http://www.maclife.com/article/howtos/install_linux_your_mac.

How to speed up Visual Studio 2010

According to the current version of Visual Studio, that is 2010. We can't deny that this version of Visual Studio is running slower when compared to the previous version (2008). So, I found some blogs wrote about the solution to improve Visual Studio 2010 running performance. I followed his steps, I think it should work for everyone else. Enjoy coding time!


Later, it seems like the link I posted is not exist already. So, I would tell the steps from my memory 555.

1. Go to options and click at Environment then look at startup tab. Select show empty environment.

2. Go to main environment tab, in Visual experience, deselect automatically adjust visual experience based on client performance then select Use hardware graphics acceleration if available.


3. Go to IntelliTrace tab, deselect enable IntelliTrace.


4. Go to Buld and Run tab under Projects and Solutions, check at Only build startup projects and dependencies on Run


Finally, I hope that it can help your Visual Studio run faster a bit ^^".

Sunday, October 9, 2011

Remapping the keyboard layout in Windows 7

For some reasons, you may want to change to keyboard layout, such as playing games, changing mac keyboard layout to be more comfortable when using Windows. Try this program Sharpkeys at: http://www.randyrants.com/2006/07/sharpkeys_211.html.
There are also other programs that do the same purpose at: http://vlaurie.com/computers2/Articles/remap-keyboard.htm.

Thursday, October 6, 2011

Useful Resources for developing Python GUI Applications with Tkinter

How to force a thread to stop when the main program has been closed in Python

Last week, I had done with Tkinter GUI programming, and that program requires a lot of processing power to crawl and parse web pages. So, when I was running the program, it was hang. The solution is using multi-threading, but I found a next problem that threads were not killed when the main program was closed. To stop threads, we need to set daemon thread letting the threads die when the program is terminated.
Thread.setDaemon()

Compile Python apps to .exe with py2exe

Normally, to run Python applications, we need to have a Python Interpreter. However, it's not always end in this way. If you are using Windows-based Operating Systems, you can compile your Python program to an executable file, and let other Windows-based users to use it without any of Python interpreter installation. You can download the py2exe from http://www.py2exe.org/ according to your Python version.

Examples:    A console application
print 'Hello World!'
 To compile console applications, create a setup.py file and then write the following code:  
from distutils.core import setup
import py2exe
setup(console=['hello.py'])
Then, terminal access is required for compiling process. Write it as the following code:
python setup.py py2exe
Next, py2exe will try to generate the executable file for running that Python program on Windows.   A GUI application
from Tkinter import *
app = Tk()
app.mainloop()
 GUI applications need to modify console application setup code a bit as the following commands:
from distutils.core import setup
import py2exe
setup(windows=['ui.py'])
Then, use the same command that I already mentioned above. In addition, py2exe tutorial can be looked for more information at: http://www.py2exe.org/index.cgi/Tutorial

Saturday, October 1, 2011

How to print percent sign in Python

Hahaha! until now, I still don't know how to print percent sign in Python yet because I haven't needed to use it. The solution is in your printout string, you need to put '%%' (concatenate percent signs). Then, the output will show the percent sign.

print 'Your accuracy is 80%%.' # Your accuracy is 80%.

Friday, September 23, 2011

Lexalytics: Text Analytics Software

     Lexalytics, Inc. builds text analytics software, and also libraries as well to deal with the natural text from human. It provides the software that can be used to take competitive advantages in businesses such as social media monitoring, marketing intelligence, voice of customers, and enterprise searching. The most interesting thing for me is Tripadvisor is a one of Lexalytics partner, which this website is the world largest travel site, enabling travelers plan and have a perfect trip. Tripadvisor offers trusted advice from real travelers to make beginner travelers plan a suitable solution for themselves.
     In my B.Sc. project, I built a software that have tried to extract sentiment of travelers in positive and negative based on various traveling aspects such as appearance, atmosphere, cleanliness, value, and etc. The hardest things for me are entity mapping, set of vocabularies with feeling for each concerned aspect, error of data, and topic separation. Many things of Lexalytics made me feel curious , and I have tried to study about NLP more at http://www.lexalytics.com/sentiment-extraction-measuring-emotional-tone-text.
     Later, I will summarize important information and write down on this blog.

Monday, September 5, 2011

Wednesday, August 31, 2011

What IDE to use for Python?

See this topic, it may be helpful: http://stackoverflow.com/questions/81584/what-ide-to-use-for-python.
There also has a tool helping us to debug Python program in command shell called IPython. Currently, I don't know how to use it yet. If anyone knows how to use and how it can help us, please let me know ^^.

Rooting & Installing Recovery on X10 Official SE GB

Now, we can root Xperia X10 Ginger Bread (2.3.3). Take a look at: http://forum.xda-developers.com/showthread.php?t=1196808. I rooted it for installing the Cyanogen-Mod 7 ROM, need to be 2.3.3, because I am very frustrated with Sony Official  ROMs.

Thursday, August 25, 2011

Illustrated GOF Design Patterns in C#

  1. Illustrated GOF Design Patterns in C# Part I: Creational
  2. Illustrated GOF Design Patterns in C# Part II: Structural I 
  3. Illustrated GOF Design Patterns in C# Part III: Structural II 
  4. Illustrated GOF Design Patterns in C# Part IV: Behavioral I
  5. Illustrated GOF Design Patterns in C# Part V: Behavioral II 
  6. Illustrated GOF Design Patterns in C# Part VI: Behavioral III

Silverlight 4 – Datagrid (Sorting, Grouping, Filtering and Paging)

Take a look here: http://www.codeproject.com/Articles/83906/Silverlight-4-Datagrid-Sorting-Grouping-Filtering

Introduction to CLIPS

CLIPS is a type of computer language designed for writing applications called expert systems. An expert system is a program which is specifically intended to model human expertise or knowledge. In contrast, common programs such as payroll programs, word processors, spreadsheets, computer games, and so forth, are not intended to embody human expertise or knowledge. (One definition of an expert is someone more than 50 miles from home and carrying a briefcase.)

CLIPS is called an expert system tool because it is a complete environment for developing expert systems which includes features such as an integrated editor and a debugging tool. The word shell is reserved for that portion of CLIPS which performs inferences or reasoning. The CLIPS shell provides the basic elements of an expert system:
1. fact-list, and instance-list:  Global memory for data
2. knowledge-base:  Contains all the rules, the rule-base
3. inference engine:  Controls overall execution of rules


Be careful! CLIPS is case sensitive language.

The Beginning and End
We can start to program CLIPS by opening CLIPS prompt. You can exit CLIPS prompt by typing (exit).

Inserting a fact
We can put the data into fact-list using assert command.
Example: (assert (rainy)), (assert (weather rainy))

p.s. If you try to insert the same fact to your fact-list, CLIPS prompt will show message FALSE to notice that this fact was already in the fact-list.
p.s.2 However, (assert (duck)) and (assert (duck true)) don't have the same meaning in CLIPS (blue color means it can be any text).



Inserting multiple facts at the same time
You can also insert facts using one assert statement by typing (assert (fact1) (fact2) (fact3) ...).

To check the fact-list
After we assert the fact into the list, we can check it whether is in the list or not using facts command.
Example: (facts)

To clear the facts

Use clear command to remove all facts from memory. You can also use reset command to remove all facts, but reset command will not remove your rules and deffacts like clear command. clear command will clear everything to be the starting point.
Example: (clear), (reset)

Removing a fact

To remove the fact with index n in the fact-list, use retract command.
Example: (retract n) ; where n is a index number. (retract *) to remove all facts.


Watch that fact
CLIPS provides several commands to help you debug programs. One com­mand allows you to continuously watch facts being asserted and retracted. This is more convenient than having to type in a (facts) command over and over again and trying to figure out what's changed in the fact-list. To cancel watching facts is to type unwatch facts.
Example: (watch facts), (unwatch facts)
p.s. The right double arrow symbol, ==>, means that a fact is entering memory while the left double arrow indicates a fact is leaving memory.

You can watch  things as follows:

 (watch facts)
 (watch instances)        ; used with objects
 (watch slots)            ; used with objects
 (watch rules)
 (watch activations)
 (watch messages)         ; used with objects
 (watch message-handlers) ; used with objects
 (watch generic-functions)
 (watch methods)          ; used with objects
 (watch deffunctions)
 (watch compilations)     ; on by default
 (watch statistics)
 (watch globals)
 (watch focus)
 (watch all)              ; watch everything

Define your rule
You can define the rule in the common like IF ... THEN ..., in CLIPS, use defrule keyword to create the rule.
The general syntax of a rule is shown following.

(defrule rule_name "optional_comment"
   (pattern_1)            ; Left-Hand Side (LHS)
   (pattern_2)            ; of the rule consisting of elements
       .                  ; before the "=>"
       .
       .
   (pattern_N)                
=>
   (action_1)             ; Right-Hand Side (RHS)
   (action_2)             ; of the rule consisting of elements
       .                  ; after the "=>"
       .
   (action_M))            ; the last ")" balances the opening                               ; "(" to the left of "defrule". Be
                          ; sure all your parentheses balance                               ; or you will get error messages

Example:
LOGIC: IF weather is cloudy, THEN the rain will come.
CLIPS: (defrule rain
                    (weather is rain)
                    =>
                    (assert (rain will come))
              )

Removing your rules
CLIPS also allows you to eliminate rules selectively by using the undefrule, then followed by a rule name.
Example: (undefrule rule_name) ; where rule_name is a rule name that want to remove.
(undefrule *) to remove all rules.

To comment your code in CLIPS
You can put the comment into your code using semicolon (;), then followed by your comment.
Example: (assert (today is raining season))     ;  Hello, this is a raining season (comment code)

To see which rules are fired
CLIPS always executes the actions on the RHS of the highest priority rule on the agenda. This rule is then removed from the agenda and the actions of the new highest salience rule is executed. This process continues until there are no more activations or a command to stop is encountered.
You can check what's on the agenda with the agenda command.
Example: (agenda)

Running a program
To make a program run, just enter the run command. Type (run) and press the carriage return key.

Show the rules
Sometimes you may want to what is the content in your rule. So, you can use ppdefrule command to see it.
Example: (ppdefrule rule_name) ; where rule_name is your rule name that you defined.
But if you can't remember the name of your rule, you can use rules command to list all of your rule names.
Example: (rules)


Gimme Deffacts
As you work with CLIPS, you may become tired of typing in the same assertions from the top-level. If you are going to use the same assertions every time a pro­gram is run, you can first load assertions from a disk using a batch file. An alter­native way to enter facts is by using the define facts keyword, deffacts. For example,

CLIPS> (clear)
CLIPS> (unwatch facts)
CLIPS> (unwatch activations)
CLIPS> (deffacts walk "Some facts about walking" 
   (status walking)    ; fact to be asserted
   (walk-sign walk))   ; fact to be asserted
CLIPS> (reset)         ; causes facts from defacts to be asserted
CLIPS> (facts)
f-0     (initial-fact)
f-1     (status walking)
f-2     (walk-sign walk)
For a total of 3 facts.
CLIPS>

The required name of this deffacts statement, walk, follows the deffacts keyword. Following the name is an optional comment in double quotes. Like the optional comment of a rule, the (deffacts) comment will be retained with the (deffacts) after it's been loaded by CLIPS. After the name or comment are the facts that will be asserted in the fact-list. The facts in a deffacts statement are asserted using the CLIPS (reset) com­mand.
The (initial-fact) is put in automatically by a (reset). The fact-identifier of the initial-fact is always f-0. Even without any deffacts statements, a (reset) always will assert an (initial-fact).
The utility of (initial-fact) lies in starting the execution of a program. A CLIPS program will not start running unless there are rules whose LHS's are satisfied by facts. Rather than having to type in some fact to start things off, the (reset) command asserts it for you as well as asserting the facts in deffacts statements.
The (reset) has a further advantage compared to a (clear) command in that (reset) doesn't get rid of all the rules. The (reset) leaves your rules intact. Like (clear), it removes all activated rules from the agenda and also removes all old facts from the fact-list. Giving a (reset) command is a recommended way to start off program execution, especially if the program has been run before and the fact-list is cluttered with old facts.
In summary, the (reset) does three things for facts.
(1) It removes existing facts from the fact-list, which may remove activated rules from the agenda.
(2) It asserts (initial-fact).
(3) It asserts facts from existing (deffacts) statements.
Actually, the (reset) also does corresponding operations on objects. It deletes instances, creates initial-object, and asserts instances from definstances.

Remove deffacts
To remove deffacts, use undeffacts command, then followed by deffact name. Or use clear to remove everytihing (hahaha).
Example: (unndeffacts def_fact_name) ; where def_fact_name is your defined deffact. (undeffacts *) to remove all deffacts.

Matching a pattern
CLIPS has a  command called matches that can tell you which patterns in a rule match facts. Patterns which do not match pre­vent the rule from becoming activated. One common reason that a pattern won't match a fact results from misspelling an element in the pattern or in the asser­tion of the fact. 
Example: (matches rule_name) ; where rule_name is your rule name that you defined.

Print a result
You can print out information using the printout function. CLIPS also has a carriage return/linefeed keyword called crlf which is very useful in improving the appearance of output by formatting it on different lines. For a change, the crlf is not included in parentheses.
Example: (printout t "Hello" crlf)) => It will print "Hello", and the cursor will start at a new line.

Declare variables
The name of a variable, or variable identifier, is always written by a question mark followed by a symbol that is the name of the variable. The general format is

?<variable-name>

For examples: ?noun, ?color, ?sensor, ?valve

To use variables, you can assert the variable as a fact. For example, enter

(defrule make-quack
   (duck-sound ?sound)
=>
   (assert (sound-is ?sound)))

Now, assert (duck-sound quack), then (run) program. You will get the fact (sound-is quack) that you input as ?sound variable. You also can keep an address of the fact into a variable using <- as a following example:

(defrule get-married
    ?duck <- (bachelor Dopey)
=>
   (printout t "Dopey is now happily married "  ?duck crlf)
   (retract  ?duck))

If you assert (bachelor Dopey), then (run) the program. Before the rule is fired, you have one fact (bachelor Dopey). After the rule is fired, that fact will be kept in ?duck variable. Then, you can retract to remove that fact using the variable name to tell CLIPS a fact-address

Use wildcard to say an anonymous field
Instead of binding a field value to a variable, the presence of a nonempty field can be detected alone using a wildcard. For example, suppose you're running a dating service for ducks, and a duckette asserts that she only dates ducks whose first name is Richard. Actually, two criteria are in this specification since there is an implication that the duck must have more than one name. So a plain (bachelor Richard) isn't adequate because there is only one name in the fact.
This type of situation, in which only part of the fact is specified, is very common and very important. To solve this problem, a wildcard can be used to fire the Richards.
The simplest form of wildcard is called a single-field wildcard and is shown by a question mark, "?". The "?" is also called a single-field constraint.

CLIPS> (clear)
CLIPS> (defrule dating-ducks
   (bachelor Dopey ?)
=>
   (printout t "Date Dopey" crlf))
CLIPS>
(deffacts duck
    (bachelor Dicky)
    (bachelor Dopey)
    (bachelor Dopey Mallard)
    (bachelor Dinky Dopey)
    (bachelor Dopey Dinky Mallard))
CLIPS> (reset)
CLIPS> (run)
Date Dopey

It will print Date Dopey because your fact contain Dopey Mallard that starting with Dopey as same as the pattern, then followed by any value of a single field.

If you allow multiple fields, you can use multifield wildcard.  This is a dollar sign followed by a question mark, "$?", and represents zero or more fields. Remember that each field is separated by space.

Wildcards have another important use because they can be attached to a symbolic field to create a variable such as ?x, $?x, ?name, or $?name. The variable can be a single‑field variable or a multifield variable depending on whether a "?" or "$?" is used on the LHS. Note that on the RHS only a ?x is used, where the "x" can be any variable name. You can think of the "$" as a function whose argument is a single-field wildcard or a single-field variable and returns a multifield wildcard or a multifield variable, respectively.

Additional Constraints
Not condition, in CLIPS, it is called a ~ constraint. Its symbol is the tilde "~". The ~ constraint acts on the one value that immediately follows it and will not allow that value.The first is called a ~ constraint. Its symbol is the tilde "~". The ~ constraint acts on the one value that immediately follows it and will not allow that value.

Example:
(defrule walk
   (light ~green)
=>
   (printout t "Don't walk" crlf))

Then you assert (light red) to a fact-list, it will print "Don't walk" because your fact is red, not green. This rule will be fired.

Or condition is the bar constraint, "|". The "|" connective constraint is used to allow any of a group of values to match.

Example:
(defrule cautious
      (light yellow|blinking-yellow)
      =>
      (printout t "Be cautious" crlf))

Then, you assert (light yellow) or (light blinking-yellow). This rule will be fired.

And condition
is the & connective constraint. The symbol of the & connective constraint is the ampersand, "&". The & constraint forces connected constraints to match in union. However, if you use and condition, and you also want to print the value that you input, you can't use a variable to replace them. But you can do like a following example:
(defrule not-yellow-red
   (light ?color&~red&~yellow)
=>
   (printout t "Go, since light is " ?color crlf))
Then you assert (light blue), it will print blue instead.

Reading a user input
CLIPS can read the information that you type from the keyboard using the read function. The following example shows how (read) is used to input data. Note that no extra (crlf) is needed after the (read) to put the cursor on a new line. The (read) automatically resets the cursor to a new line.

Example:
(defrule read-input
   (initial-fact)
=>
   (printout t "Name a primary color" crlf)
   (assert (color (read))))

When you (run) the program. It will print "Name a primary color", then asks you to input the color. Next, it will keep your input from keyboard to be a new fact in the fact-list.

All of them are just basic usage of CLIPS. If you want to know more please visit at their official website: http://clipsrules.sourceforge.net/.
All of information is summarized from CLIPS official website documentation.

Monday, August 22, 2011

Arrays and pointers in C

This one makes me painful especially parsing more than 1 dimensional array into functions, but, right now, I just found the solution. Take a look here: http://www.ibiblio.org/pub/languages/fortran/append-c.html.

Thursday, August 18, 2011

How to use openssh (Thai)

Check out this link: http://www.oknation.net/blog/print.php?id=448209

Install GUI in Ubuntu Server

When you have installed a Ubuntu Server, you can access through bash only. Since I am not familiar with that, then I will try to install gnome interface on it to make it used easier.
The easiest way to install is to use apt-get install by type "sudo apt-get install ubuntu-desktop". Then, it will download all needed packages via the internet. After installation is finished, reboot the system. Finally, you will see GUI in your Ubuntu Server.

Other resource: http://www.ubuntugeek.com/install-gui-in-ubuntu-server.html

Wednesday, August 17, 2011

Learning how to read time

Hahaha, according to I'm not good at English. I need more practices :D. So, this time I found the website that contains the speakable application to teach me how to tell the time. It's very easy to follow. The link is here: http://www.timemonsters.com/.

There are 2 ways to read time. The first one is to read hours then minutes. Another is telling how long it past then hours for the first half , and telling the remaining minutes left then next hours for the latter half.

Examples:
4:00    ->    Four o' clock
4:05    ->    Four - oh - five, Five past four
4:15    ->    Four fifteen, A quarter past four
4.30    ->    Four thirty, Half past four
4.45    ->    Four forty-five, A quarter to five
4.50    ->    Four fifty, Ten to five

Saturday, July 30, 2011

DataContext vs ItemsSource (in Binding case)

Great article: DataContext vs ItemsSource (in Binding case)
The difference is that when using DataContext, it means that you bind the owner object of DataContext with the reference, which is DataContext pointed to. So, it some cases such as DataGrid or ListBox. We use ItemSource instead when we're talking about data in each row, not the DataGrid itself. On the other hand, we use DataContext to set binding from source ojbect to DataGrid directly.

Thursday, July 28, 2011

How to pass Dynamic Anonymous Object to ViewPage in Razor

Normally, you can't pass anonymous object as a model to ViewPage because it can only be accessed from within the assembly in which it’s declared. Since views get compiled separately, the dynamic binder complains that it can’t go over that assembly boundary. So, to solve this problem we have to create own ViewPage that use dynamic object as a Model, or create extension method to change its type to ExpandoObject.

Using ExpandoObject:
public static ExpandoObject ToExpando(this object anonymousObject)
{
    IDictionary anonymousDictionary =
    HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
    IDictionary expando = new ExpandoObject();
    foreach (var item in anonymousDictionary)
        expando.Add(item);
    return (ExpandoObject)expando;
}

Then, you can pass anonymous object through Model, and use it as dynamic object.
References: http://stackoverflow.com/questions/5120317/dynamic-anonymous-type-in-razor-causes-runtimebinderexception, http://blogs.msdn.com/b/davidebb/archive/2009/12/18/passing-anonymous-objects-to-mvc-views-and-accessing-them-using-dynamic.aspx

Wednesday, July 27, 2011

Comparison of NoSQL

Nowadays, there are many NoSQL tools or engines to use. Some people may not know which one should be used. Let's see the NoSQL comparison to know their strength and weakness here: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis. If you don't know what NoSQL is, take a look here: http://en.wikipedia.org/wiki/NoSQL.

Wednesday, June 22, 2011

Did you meant to say/did you mean to say

It must be "Did you mean to say" because meant is a past participle form of mean and did shows that this sentence is in the past.
Credit: http://www.englishforums.com/English/DidMeantMeanSay/ddkbn/post.htm

Sunday, June 19, 2011

Lets vs let's

To let means to "allow".

Let him in. = Allow him to come in.

The word "let's" means "let us"

The first comes with the pronoun "us".
The second does not come with the pronoun "us".


She lets [allows] him to paint. = She allows him to paint.

So the rule is that when you mean let us, or allow us, or permits us, you use let's.

The following examples do not have the plural pronoun [us] contraction so no apostrophy is used.

She lets me paint. = She allows me to paint.
She lets them paint. = She allows them to paint.
She lets him or her paint. She allows him or her to paint.

Credit: http://www.englishforums.com/English/LetsVsLets/gnbh/post.htm from 
Radrook

Saturday, May 28, 2011

Fetch Web Pages in Python using urllib2

urllib2 is an extensible library for opening URLs. Mostly, we will use fetch data from URLs via HTTP. We can use it to access normal Website, HTTP Authentication, Web Proxy, and etc. urllib2 is included in python standard library.

Example:

import urllib2
# Normal usage
f = urllib2.urlopen('http://wwww.google.com')
print f.read()

# Use under Proxy
auth_handler = urllib2.ProxyBasicAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm())
auth_handler.add_password(realm=None,uri='proxy-name',user='username',passwd='password')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
f = urllib2.urlopen('http://wwww.bing.com')
print f.read()

In the example, It use GET to fetch data. If you want to change it to POST, you have to put data attribute in the method.

The basic usage is "urllib2.urlopen(url[, data][, timeout])".

More details at: http://docs.python.org/library/urllib2.html

Sunday, May 22, 2011

So You Think You Can Dance Online

So You Think You Can Dance is an American Dance reality show. It is broadcast on the Fox Channel. It's marvelous. I began to watch it since March via AXN Channel during vacation. Each competitor has a high standard in dancing, so it make me feel excited when I'm watching it.

Watch at: http://www.sidereel.com/So_You_Think_You_Can_Dance

Or you may download it directly using KeepVid, or Keep-Tube without any limitation from MegaUploadVideo. Enjoy watching ><!

Wednesday, May 18, 2011

The differences between get and post method in HTTP

Sometimes, I confuse which method should be used in HTTP. Now, I have found the answer from http://wiki.answers.com.

The answer is here:
GET Method:
  1. All the name value pairs are submitted as a query string in URL.
  2. It's not secured as it is visible in plain text format in the Lacation bar of the web browser.
  3. As the data transfers through address bar (URL) there are some restrictions in using space, some characters like ampersand (&) etc in the GET method of posting data. We have to take special care for encoding data if such special characters are present.
  4. Length of the string is restricted.
  5. If method is not mentioned in the Form tag, this is the default method used.
  6. If get method is used and if the page is refreshed it would not prompt before the request is submitted again.
  7. One can store the name value pairs as bookmark and directly be used while sharing with others - example search results.
  8. Data is always submitted in the form of text
  9. If the response of the page is always same for the posted query then use GET example database searches
POST Method:
  1. All the name value pairs are submitted in the Message Body of the request.
  2. Length of the string (amount of data submitted) is not restricted.
  3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser.
  4. If post method is used and if the page is refreshed it would prompt before the request is resubmitted.
  5. If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
  6. Data is submitted in the form as specified in enctype attribute of form tag and thus files can be used in FileUpload input box.

Read more: http://wiki.answers.com/Q/What_is_the_difference_between_get_and_post_method_in_HTTP

Thursday, May 5, 2011

As follow VS As following

http://www.andrewbiggs.com/smf/index.php?topic=76.0
These two words usually make me feel confused how to use them all the time - -*.

Free ASP.NET MVC “NerdDinner” Tutorial

 Here, you will know a lot of basic things for ASP.NET MVC framework as following topics:

Interesting Silverlight blog posts

7 Simple Steps to Connect SQL Server using WCF from SilverLight
WCF Basics - Data Contracts
Silverlight: How to Send Message to Desktop Application
Silverlight: How to Receive Messages from Desktop Application
RIATasks: A Simple Silverlight CRUD Example (using View Model)
A Sample Silverlight 4 Application Using MEF, MVVM, and WCF RIA Services
Silverlight Elevated Permissions
Full-Screen Support

Friday, April 29, 2011

Using Fences to organize your desktop shortcuts

Recently, I had a problem with the shortcuts on the desktop. I usually connect my laptop to an external monitor, so the resolution usually changes. The problem was that my shortcuts arrangement also changed! Now, I have a solution you can use Fences to organize your shortcuts, and it can remember the shortcuts arrangement.

Download at: http://download.cnet.com/Fences/3000-2072_4-10909535.html

The Fences Example

Monday, April 25, 2011

Cut Automator script for Mac with Automator

One thing that caused a lot of problems for me in Mac is there is no "cut" short key like "ctrl+x" in Windows. I had to dragged items, sometimes it's hard to do like that. So far, I tried to develop "Cut Script" with Automator. It can be used by using right clicking to the item, then select the path to move.

You can create it as following steps:
1. Open Automator from your Application.
2. Service receives selected change to "files or folders" and in to "Finder".
3. Drag "Get Selected Finder Items" to the Automator space.
4. Drag "Set Value of Variable", and change its name to "item".
5. Drag "Apple Script".
Step 3-5
6. Drag "Ask for Finder Items", and change type(Type:) to "Folders".
7. Drag "Set Value of Variable", and change its name to "path".
8. Drag "Apple Script".

Step 6-8
9. Drag "Get Value of Variable", and change its name to "item".
10. Drag "Move Finder Items", and change to(To:) to "path".

Step 9-10
Download

In addition, you can also download it, and then place it into your profile service folder (~/Users/[User]/Library/Services/).
Now, you can move your file faster with easy steps. Don't have to drag anymore!

Saturday, April 2, 2011

How to install Python Imaging Library (PIL)

Python Imaging Library is a library for doing image processing tasks just as its name. In Windows you can install it easily by downloading PIL windows installer, but in Linux and Mac are more harder. You have to compile and install it from a source package. PIL also need other libraries in order to install it completely as followings: JPG, Freetype, LittleCMS 1.19 NOT 2.0+.

In Linux, you may install those libraries via your command line. For example, sudo apt-get install (Ubuntu). Then, install PIL.

However, in Mac, you have to install Xcode and X11 to make your Mac can use "./configure" and "make" command. After that, installing MacPorts or Fink which allow you to get those required libraries and download them via command line (use "port install" or "fink install" respectively). Finally, install PIL after installing dependent libraries.


You can download PIL from here (all platforms): from http://www.pythonware.com/products/pil/

To install PIL from source package do steps follows:
1. Change current directory of your terminal under PIL source folder.
2. Type "sudo python setup.py build_ext i".
3. Run the test "python selftest.py".
4. If everything is fine, then install it by typing  "sudo python setup.py install".

Then, you should run PIL example code to make sure installation is complete. If not or in the case that you already installed PIL, you need to delete its package from site-package in python library. Then, you have to extract PIL source package from zip file again (do not use older extracted folder because it won't work for sure). Build it again, then install.

p.s. Required libraries: libjpeg, freetype, lcms

Friday, March 25, 2011

How to create table of contents in Blogger

Check out this link http://www.mybloggertricks.com/2010/12/how-to-create-table-of-contents-for.html

REST vs SOAP Web Services

Check out this link REST vs SOAP Web Services.
For Web Service Architecture is at W3C.

How to use JSON in python

JSON stands for JavaScript Object Notation. It is a light-weight text format that usually used it for data interchange (alternative choice to XML based). We can use it in  RESTful services.
to
Now, it just a example how encrypt and decrypt JSON in Python. The most important in JSON is the property key must be string only.

The followings are available data type in JSON:

# Python can use json from standard library
import json
# Create object in python
ob = {'name':'Json','email':['x@a.com','x@b.com']}
# Convert python object into json string format
jstring = json.dumps(ob)
print jstring
# Load python object from json string
jobject = json.loads(jstring)
print jobject

Wednesday, March 23, 2011

How to move file in Python shell

In the previous post, I introduced about change current directory in Python shell. Now, it's about move file in the shell by using "shutil.move(src, dst)" (shell util).
For example:
# Move text.txt from src to dst
shutil.move('/src/text.txt','/dst')
More detail at: http://docs.python.org/library/shutil.html

Tuesday, March 22, 2011

How to read line from an input file without \n

In python, when you read each line from a file, the line string will contain \n at the end of line (1 character).
So, you have to remove it manually unlike Java you can read line in Scanner class.
f = open(...)               # Open file

f.readline().rstrip('\n')   # Remove last character
or
f.readline()[:-1]           # Remove last character

Monday, March 21, 2011

How to change current directory in Python shell

Basically, you can't use os.system('cd ...') directly. But you can use os.chdir('path') instead.
For example:
os.chdir('..')    # Move up
os.chdir('./')    # Current dir
os.chdir('path')  # Go to folder name 'path'
More detail at: http://docs.python.org/library/os.html

Problem Solving using creative thinking

There are 3 general steps:
1. Target the goal: you must have the concrete and attainable target in order to asking questions that straight to the point.
2. Find the ways to solve the problem: think, think, and think. Don't think about possibility and reality yet.
3. Analysis and select good ideas: adjust ideas, re-think, possibility, logicality, or blend ideas together.
But ideas are not creative if not better, can't solve a problem, and not attainable.
Ref: Creative Thinking - Dr.Kriengsak Chareonwongsak
Web: http://www.kriengsak.com/

Sunday, March 20, 2011

How to show hidden files in Mac

It's very easy by do as following:
1. Open "Terminal"
2. type "defaults write com.apple.finder AppleShowAllFies TRUE"
3. Then type "killall Finder" to restart Finder

Note: If you want to change back to hidden files, just change TRUE into FALSE

Wednesday, March 16, 2011

How to calculate precision and recall

Basically, we can calculate precision and recall easily. For example, we have total 1000 cases. We know that there are 100 cases which are positive. Then, you want system to predict the positive. For example, you get 200 positive cases in testing and then you record the ids of our predictions. After that, sum up how many times to get right and wrong. There are 4 ways to determine right of wrong:

1. True Negative (TN): case negative and system can predict as negative.
2. False Negative (FN): case positive but system predicted as negative.
3. False Positive (FP): case negative but system predicted as positive.
4. True Positive (TP): case positive and system can predict as positive.

Then, we found that got 80 true positives of 200 cases. Total cases (N) = 1000
TP = 80
FN = 20 -> (100-80)
FP = 120 -> (200-80)
TN = 780 -> ((1000-100)-(200-80)) -> (900-120)
Note that: TP + FN + FP + TN = N,
TP + FN = Number of positive labels,
TN + FP = Number of negative labels

Finally, we can do calculation.
Accuracy = (TP + TN) / N = (80 + 780) / 1000 = 0.86 => 86%
Recall = TP / (TP + FN) = 80 / (80 + 20) = 0.8 => 80%
Precision = TP / (TP + FP) = 80 / (80 + 120) = 0.4 => 40%