<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Garejoor</title>
	<atom:link href="http://garejoor.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://garejoor.com</link>
	<description>A Coders Handbook</description>
	<lastBuildDate>Sun, 19 Feb 2012 09:28:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Vim Quick Reference</title>
		<link>http://garejoor.com/2012/02/vim-quick-reference/</link>
		<comments>http://garejoor.com/2012/02/vim-quick-reference/#comments</comments>
		<pubDate>Sun, 19 Feb 2012 09:28:41 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1568</guid>
		<description><![CDATA[Changing Modes In Vim there are two modes. i : Change to INSERT mode ESC : Change to COMMAND MODE (non-insert mode) . : repeat last action Save and Close The following commands are executed from COMMAND MODE. :w : save the document, this will not close vim :q : quit :wq : save and quit Moving Cursors To move the cursor you can use the arrow keys, or alternatively &#8230; <a class="more_btn" href="http://garejoor.com/2012/02/vim-quick-reference/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<h2>Changing Modes</h2>
<p>In Vim there are two modes. </p>
<ul>
<li> <b> i </b> :  Change to INSERT mode </li>
<li> <b> ESC </b> : Change to COMMAND MODE (non-insert mode)</li>
<li> <b> . </b> : repeat last action </li>
</ul>
<p><BR/></p>
<h2>Save and Close</h2>
<p>The following commands are executed from COMMAND MODE.</p>
<ul>
<li> <b> :w </b>  : save the document, this will not close vim </li>
<li> <b> :q </b>  : quit</li>
<li> <b> :wq </b> : save and quit</li>
</ul>
<p><BR/></p>
<h2>Moving Cursors</h2>
<p>To move the cursor you can use the arrow keys, or alternatively the &#8216;h&#8217;,'j&#8217;,'k&#8217;,'l&#8217; keys. There are other options to move the cursor faster to other locations.</p>
<ul>
<li> <b> h </b> : left</li>
<li> <b> j </b> : down</li>
<li> <b> k </b> : up</li>
<li> <b> l </b> : right</li>
<li> <b> 0 (number zero) </b> : move to beginning of line</li>
<li> <b> $ (dollar sign) </b> : move to end of line </li>
<li> <b> w,b,e </b> : to move along words, for example: for(int i= 0; i < 10; i++) { will move from beginning of for to end of for, then to after parenthesis then to end of int ...
</li>
<li> <b> W,B,E </b> : to move along non-blanks, for example: for(int i= 0; i < 10; i++) { will move from beginning of for to end of int, then to after ; ... </li>
<li> <b> f + (character) </b> : moves to the first occurrence of the character on the line, must enter the character right after f
  </li>
</ul>
<p><BR/></p>
<h2>Basic Editing</h2>
<p>Editing, includes coping and pasting done in COMMAND MODE.</p>
<ul>
<li> <b> d + (followed by a a cursor motion) </b> : delete next item </li>
<li> <b> dd </b> : delete line </li>
<li> <b> y + (followed by a cursor motion) </b> : copy next item </li>
<li> <b> yy </b> : copy line </li>
<li> <b> p </b> : paste after </li>
<li> <b> P (capital p) </b> : paste before </li>
</ul>
<p><BR/></p>
<h2>Searching</h2>
<p>(done in command mode)</p>
<ul>
<li> <b> / + (followed by regex string) + (return) </b> : highlights all the findings </li>
<li> <b> ? + (followed by regex string) + (return) </b> : highlights but moves backward </li>
<li> <b> n </b> : moves the cursor to the next occurrence of the search entered using last two commands </li>
<li> <b> (move cursor under a word) + (ESC) + * </b> : searches for that string </li>
</ul>
<p><BR/></p>
<h2>Macros</h2>
<p><a href="http://www.thegeekstuff.com/2009/01/vi-and-vim-macro-tutorial-how-to-record-and-play/" title="Macro Tutorial" target="_blank">http://www.thegeekstuff.com/2009/01/vi-and-vim-macro-tutorial-how-to-record-and-play/</a></p>
<ul>
<li> <b> q + (followed by a character)  </b> :  start recording, the program is in RECORDING MODE </li>
<li> <b> q </b> : stops recording if in recording mode </li>
<li> <b> @ + (character defined for recording) </b> : plays the macro </li>
<li> <b> number + @ + (macro character defined) </b> : replays macro for &#8216;Number&#8217; of time </li>
</ul>
<p><BR/></p>
<h2> Resources </h2>
<p>http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html</p>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/02/vim-quick-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python: Quick Reference</title>
		<link>http://garejoor.com/2012/02/python-quick-reference/</link>
		<comments>http://garejoor.com/2012/02/python-quick-reference/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 22:44:05 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[reference]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1557</guid>
		<description><![CDATA[I forget almost everything I read, so I&#8217;ve compiled a list of topics with examples for a quick reminder. If you find find an error in the code, forgive me and please let me know. Print stuff on the screen String Manipulation User Input Program Arguments Read and Write to files Functions or Methods If Statement Loop List Tuples Dictionary Creating Modules Classes Inheritance Python in Linux Creating a GUI &#8230; <a class="more_btn" href="http://garejoor.com/2012/02/python-quick-reference/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<p>I forget almost everything I read, so I&#8217;ve compiled a list of topics with examples for a quick reminder. If you find find an error in the code, forgive me and please let me know.</p>
<table border="0">
<tr>
<td>
<ul>
<li><a href="#Print stuff on the screen">Print stuff on the screen</a>  </li>
<li><a href="#String Manipulation">String Manipulation</a>  </li>
<li><a href="#User Input">User Input</a>  </li>
<li><a href="#Program Arguments">Program Arguments</a>  </li>
<li><a href="#Read and Write to files">Read and Write to files</a>  </li>
<li><a href="#Functions or Methods">Functions or Methods</a>  </li>
<li><a href="#If Statement">If Statement</a>  </li>
<li><a href="#Loop">Loop</a>  </li>
<li><a href="#List">List</a>  </li>
</ul>
</td>
<td>
<ul>
<li><a href="#Tuples">Tuples<a>  </li>
<li><a href="#Dictionary">Dictionary</a>  </li>
<li><a href="#Creating Modules">Creating Modules</a>  </li>
<li><a href="#Classes">Classes</a>  </li>
<li><a href="#Inheritance">Inheritance</a>  </li>
<li><a href="#Python in Linux">Python in Linux</a>  </li>
<li><a href="#Creating a GUI application">Creating a GUI application</a>  </li>
<li><a href="#Making Python scripts executable">Making Python scripts executable</a>  </li>
<li><a href="#The standard library">The standard library</a>  </li>
</ul>
</td>
</tr>
</table>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Print stuff on the screen"></a></p>
<h2> Print stuff on the screen </h2>
<p>Printing content on the screen can be done using the print statement. Here are some examples:</p>
<pre class="brush: python; title: ; notranslate">

cars = 100
print &quot;There are&quot;, cars, &quot;cars available.&quot;
#output:
#There are 100 cars available.

t_name = &quot;Gary Joorian&quot;
t_age  = 25
print &quot;My name is %s and I'm %d year old.&quot; % (t_name, t_age)
#output:
#My name is Gary Joorian and I'm 25 year old.

print &quot;My name is %r and I'm %r year old.&quot; % (t_name, t_age)
#output:
#My name is Gary Joorian and I'm 25 year old.

word = &quot;This is the first line&quot; + &quot;\n&quot; + &quot;This is the second line&quot;
print word
#output:
#This is the first line
#This is the second line

print &quot;&quot;&quot;
with three double-quotes
we can write on a new line
and no need for a new line char
&quot;&quot;&quot;
#output:
#with three double-quotes
#we can write on a new line
#and no need for a new line char

fat_cat = &quot;&quot;&quot;
To Do list:
\t* eat
\t* sleep
&quot;&quot;&quot;
print fat_cat

#output:
#To Do list:
#	* eat
#	* sleep
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="String Manipulation"></a></p>
<h2>String Manipulation</h2>
<p>This will cover a very small subset of string manipulation. In python, a string is treated as a list of characters, so unlike Java or C#, it&#8217;s not an object type.</p>
<pre class="brush: python; title: ; notranslate">
word = &quot;name &quot; + &quot;and lastname&quot;
print word
#output:
#name and lastname

word = &quot;Honorific&quot; + &quot;        abilitudinitatibus&quot;.strip()
print word
#output:
#Honorificabilitudinitatibus

print word[6]
print word[17:21]
print word[:9]
print word[17:]
#output:
#f
#init
#Honorific
#initatibus
</pre>
<p>The last 4 lines of code illustrate that a string is essentially a list of characters. See the list section for more details.</p>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="User Input"></a></p>
<h2>User Input</h2>
<p>use raw_input() to get a user input from the keyboard. The user input is not the same as the program arguments which a person uses when executing the program.<br />
The user input is a string, which has to be converted to an integer if if required.</p>
<pre class="brush: python; title: ; notranslate">
x = int(raw_input(&quot;Please enter an integer: &quot;))
if x == 0:
     print 'zero'
elif x == 1:
     print 'One'
else:
     print 'None'
</pre>
<p>the raw_input allows the user to type in a string.</p>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Program Arguments"></a></p>
<h2>Program Arguments</h2>
<p>Program arguments are variables sent to the program when executing them form a console. For example, if we execute a program named myprogram.py like so:</p>
<pre class="brush: python; title: ; notranslate">
python myprogram.py 10 500 word
</pre>
<p>then 10, 500 and word are the first, second and third arguments sent to the program from the console. </p>
<pre class="brush: python; title: ; notranslate">
from sys import argv # we are loading the argv module

script, first, second, third = argv #unpacking the values

print &quot;The script is called:&quot;, script
print &quot;Your first variable is:&quot;, first
print &quot;Your second variable is:&quot;, second
print &quot;Your third variable is:&quot;, third
</pre>
<p>assume this is the content of a file named arguments.py:</p>
<pre class="brush: python; title: ; notranslate">
python arguments.py first 2nd 3rd
#output
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd
</pre>
<p>for more advanced argument parsing technique look up examples for &#8220;optparse&#8221;. It creates helper / usage screen and validates user entered arguments automatically with user friendly messages indicating if any error occurred.</p>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Read and Write to files"></a></p>
<h2>Read and Write to files</h2>
<p>to open a files use open(filepath) which returns a file object for that file. for example:</p>
<pre class="brush: python; title: ; notranslate">
from sys import argv

t_script, t_filename = argv
print &quot;file to open is %s&quot; % filename

t_file = open(t_filename) #open the file discriptor
t_fileCont = t_file.read() #will read all the content
print &quot;the file content:&quot;
print t_fileCont
</pre>
<p>To write to a file,</p>
<pre class="brush: python; title: ; notranslate">
from sys import argv

t_script, t_filename = argv
print &quot;file to write to is %s&quot; % filename

# use 'w' to open file for write
t_file = open(t_filename, 'w') #open the file discriptor
t_text = raw_input(&quot;Input text &gt; &quot;)
t_file.write(t_text) #will read all the content
t_file.close() #must close file after write or read
</pre>
<p>use &#8220;\n&#8221; to insert newlines.</p>
<p>Some of the functionality of the file object:</p>
<pre class="brush: python; title: ; notranslate">
t_filename = &quot;somefile.txt&quot;

# use 'w' to open file for write
t_file = open(t_filename, 'r') #open the file discriptor
t_file.readline();   #reads a whole line in the file
t_file.seek(0);   #moves the file cursor to the begging of the file
t_file.read();   #read all the content of the flie
t_file.close();  #must close file after write or read
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Functions or Methods"></a></p>
<h2> Functions or Methods </h2>
<p>In Python Methods are defined with the keyword &#8216;def&#8217;. </p>
<pre class="brush: python; title: ; notranslate">
#Function that takes a list as input and prints
#the size of that list and the items
def PrintSizeAndItems(in_list):
	print &quot;The size of a list is &quot; + str(len(in_list))
	for t_name in in_list:
		print t_name
</pre>
<p>You can call the function like so, </p>
<pre class="brush: python; title: ; notranslate">
_listOfNames = [&quot;Adam&quot;, &quot;Nazik&quot; ,&quot;Erik&quot;, &quot;Alex&quot;]
_listOfFoods = [&quot;Potato&quot;, &quot;Tomato&quot; ,&quot;Pizza&quot;]
PrintSizeAndItems(_listOfNames)
PrintSizeAndItems(_listOfFoods)
PrintSizeAndItems(&quot;&quot;)

#output
The size of a list is 4
Adam
Nazik
Erik
Alex
The size of a list is 3
Potato
Tomato
Pizza
The size of a list is 0
</pre>
<p>You can specify a default value for arguments. like so:</p>
<pre class="brush: python; title: ; notranslate">
def AskName(greet = 'Good Evening'):
	print greet
	_input = (raw_input(&quot;What is your name? &quot;))
	print 'Hello ', _input.strip()
AskName()
AskName(&quot;Yo!&quot;)
</pre>
<p>But if you have functions with more than one argument,<br />
it&#8217;s hard to keep track of which argument is what.<br />
in Objective-C (Apple) you type in the parameter name<br />
and then assign value to it so you wont get confused.<br />
You can do the same in Python, like so:</p>
<pre class="brush: python; title: ; notranslate">
def AskName(greet = 'Good Evening', hello = 'Hello'):
	print greet.strip()
	_input = (raw_input(&quot;What is your name? &quot;))
	print hello.strip() , &quot; &quot; , _input.strip()
AskName(greet = &quot;Hello Sir!&quot; , hello = &quot;Aloha&quot;)
AskName(greet = &quot; Hola!&quot; , hello = &quot;saludo&quot;)
</pre>
<p>You can pass in an arbitrary list of arguments to a function<br />
(using a C like pointer definition) like so:</p>
<pre class="brush: python; title: ; notranslate">
def PathCombine(*in_paths):
	t_fullPath = &quot;/&quot;
	for t_path in in_paths:
		t_fullPath += t_path + '/'
	return t_fullPath
print PathCombine(&quot;Home&quot;, &quot;user&quot;)
print PathCombine(&quot;var&quot;, &quot;lib&quot;, &quot;mysql&quot;)

#output
/Home/user/
/var/lib/mysql/
</pre>
<p>But if you pass in an argument list with keyword defined then<br />
that list is treated like a dictionary. (we will get to this)</p>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="If Statement"></a></p>
<h2>If Statement</h2>
<p>The If statement is the same in python as in any language but instead of else if it&#8217;s elif. A general syntax of the if statement is:</p>
<pre class="brush: python; title: ; notranslate">
if (condition):
    ....
elif (condition):
    ....
else:
    ....
</pre>
<p>where the three dots are regular statement. If you don&#8217;t what to use elif and instead another if statement of multiple condition cases, place a new line after the if executive statement and then the new if statement. For example:</p>
<pre class="brush: python; title: ; notranslate">
temperature = 50;
if(temperature &lt; 60)
    print &quot;Temperature is below 60&quot;

if(temperature &gt; 90)
    print &quot;it's really hot&quot;
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Loop"></a></p>
<h2>Loop</h2>
<pre class="brush: python; title: ; notranslate">
# Measure some strings:
a_word_list = ['cat', 'window', 'weird']
for x in a_word_list:
    print x, len(x)
#the output
cat 3
window 6
weird 5
</pre>
<p>You can place an else after a for loop, which will insure the execution of that code after the for loop has iterated through all the possible values:</p>
<pre class="brush: python; title: ; notranslate">
_input = int(raw_input(&quot;Please enter an integer: &quot;))
print _input
for a in range(0,100):
	if _input == a:
		print _input, ' is within 100'
		break
else:
	print 'input is NOT within 100 '
</pre>
<p>here is a sample run:</p>
<pre class="brush: bash; title: ; notranslate">
$ python lesson_2.py
Please enter an integer: 62
62
62  is within 100
$ python lesson_2.py
Please enter an integer: 301
301
input is NOT within 100
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="List"></a></p>
<h2>List</h2>
<p>Lets create a list of names and print each one:</p>
<pre class="brush: python; title: ; notranslate">
_listOfNames = [&quot;Adam&quot;, &quot;Nazik&quot; ,&quot;Erik&quot;, &quot;Alex&quot;]
print _listOfNames[0]
print _listOfNames[1]
print _listOfNames[2]
print _listOfNames[3]
#output
Adam
Nazik
Erik
Alex
</pre>
<p>much like strings, you can output a range of items using this pattern:</p>
<pre class="brush: python; title: ; notranslate">
print _listOfNames[1:2]
</pre>
<p>and you can make a deep copy of the list like so:</p>
<pre class="brush: python; title: ; notranslate">
copyOfNameList = _listOfNames[:]
</pre>
<p>** I dont know why it says shallow copy on the python website, I need to research more **</p>
<p>to be more elegant, we can traverse through this list using a for loop. So lets print the total number of names in the list and print each element.</p>
<pre class="brush: python; title: ; notranslate">
_listOfNames = [&quot;Adam&quot;, &quot;Nazik&quot; ,&quot;Erik&quot;, &quot;Alex&quot;]
#len(list) takes a list as an argument and return the number of items in it,
#str(integer) takes an integer as an argument and returns the string
print &quot;The size of a list is &quot; + str(len(_listOfNames))
#print each name in the list
for t_name in _listOfNames:
	print t_name
#output is
The size of a list is 4
Adam
Nazik
Erik
Alex
</pre>
<p>Here are some of the basic methods you can call on a list to modify the values (directly from python website):</p>
<pre class="brush: python; title: ; notranslate">
 a = [66.25, 333, 333, 1, 1234.5]
 print a.count(333), a.count(66.25), a.count('x')
2 1 0
 a.insert(2, -1)
 a.append(333)
 a
[66.25, 333, -1, 333, 1, 1234.5, 333]
 a.index(333)
1
 a.remove(333)
 a
[66.25, -1, 333, 1, 1234.5, 333]
 del a[0] #using index to remove the value
 a
[-1, 333, 1, 1234.5, 333]
 a.reverse()
 a
[333, 1234.5, 1, 333, -1]
 a.sort()
 a
[-1, 1, 333, 333, 1234.5]
</pre>
<p>more list functions:</p>
<pre class="brush: python; title: ; notranslate">
#stack implementation
 stack = []
 stack.append(34)
 stack.append(12)
 stack
[34, 12]
 stack.pop()
12
 stack.pop()
34
#queue implementation
 queue = []
 queue.append(&quot;1&quot;)
 queue.append(&quot;2&quot;)
 queue.append(&quot;3&quot;)
 queue.append(&quot;4&quot;)
 queue.popleft()
1
 queue.popleft()
2
</pre>
<p>It is also possible to create a list of lists. For example a 3&#215;3 matrix. Here is a sample:</p>
<pre class="brush: python; title: ; notranslate">
mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
...       ]
</pre>
<p>to sort a list, call the sorted function:<br />
sorted(a list of objects), which returns a the sorted version of a list</p>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Tuples"></a></p>
<h2>Tuples</h2>
<p>Lets add the associated age to the names we listed. To do this, we will use tuples. Tuples are same as a set, but instead of brackets use parenthesis.</p>
<pre class="brush: python; title: ; notranslate">
_listOfNames = ((&quot;Adam&quot;,46), (&quot;Nazik&quot;,42) ,(&quot;Erik&quot;,15), (&quot;Alex&quot;,18))
PrintSizeAndItems(_listOfNames)
</pre>
<p>but the output prints out in tuples:</p>
<pre class="brush: bash; title: ; notranslate">
The size of a list is 4
('Adam', 46)
('Nazik', 42)
('Erik', 15)
('Alex', 18)
</pre>
<p>lets create another function that pretty prints the names with the ages.</p>
<pre class="brush: python; title: ; notranslate">
#print name and age
def PrintNameAndAge(in_list):
	print &quot;The size of a list is &quot; + str(len(in_list))
	for t_item in in_list:
		print t_item[0] + &quot; is &quot; + str(t_item[1]) + &quot; years old.&quot;
_listOfNames = ((&quot;Adam&quot;,46), (&quot;Nazik&quot;,42) ,(&quot;Erik&quot;,15), (&quot;Alex&quot;,18))
PrintNameAndAge(_listOfNames)
</pre>
<p>IMPORTANT: to create a tuple container 0 item, create the item like so:</p>
<pre class="brush: python; title: ; notranslate">
_listOfFruits = ()
</pre>
<p>IMPORTANT: to create a tuple container 1 item, create the item like so:</p>
<pre class="brush: python; title: ; notranslate">
_listOfFruits = 'Banana', # ending comma
</pre>
<p>IMPORTANT: to create a tuple using the shorthand statement, create the item like so:</p>
<pre class="brush: python; title: ; notranslate">
_listOfFruits = 'Banana', 'apple', 11
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Dictionary"></a></p>
<h2>Dictionary</h2>
<p>Dictionary is a list (array) but instead of index value of integer, it&#8217;s a string. Here the index is referred to as Key. The Key can be any data type except list and mutable object.</p>
<p>to create an empty dictionary:</p>
<pre class="brush: python; title: ; notranslate">
 _fruitCost= {}
</pre>
<p>and to add values, you must specify a key followed by a &#8216;:&#8217; and the value:</p>
<pre class="brush: python; title: ; notranslate">
 _fruitCost= {'banana':7 , 'apple':0.8}
 _fruitCost['banana']
7
</pre>
<p>&#8220;The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.&#8221; (python.org)</p>
<p>you can use the sorted function like so:</p>
<pre class="brush: python; title: ; notranslate">
 basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
 for f in sorted(set(basket)):
        print f
</pre>
<p>To loop through a dictionary you can use iteritems() to get the key and the value, like so:</p>
<pre class="brush: python; title: ; notranslate">
 knights = {'gallahad': 'the pure', 'robin': 'the brave'}
 for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Creating Modules"></a></p>
<h2>Creating Modules</h2>
<p>Modules to python is what libraries are to C/++/Java/etc&#8230;<br />
here we have a few sample functions, that want to place them in a seperate file for<br />
a cleaner reusable code.</p>
<pre class="brush: python; title: ; notranslate">
#Function that takes a list as input and prints
#the size of that list along with the items
def PrintSizeAndItems(in_list):
	print &quot;The size of a list is &quot; + str(len(in_list));
	for t_name in in_list:
		print t_name

#Function that prompts the user for a yes or no response
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries &lt;= 0 :
            raise IOError('refusenik user')
        print complaint

_listOfNames = ((&quot;Adam&quot;,46), (&quot;Nazik&quot;,42) ,(&quot;Erik&quot;,15), (&quot;Alex&quot;,18))
ask_ok(&quot;Ok to print?&quot;);
PrintNameAndAge(_listOfNames)
</pre>
<p>lets split the our code and place our functions in a separate file. </p>
<p>So create a another file named lesson_1_functions.py and place all the function definitions in there. (the file is in the same directory of where the lesson_1.py file is). So we would have:</p>
<pre class="brush: python; title: ; notranslate">
#lesson_1_functions.py
#=====================

#Function that takes a list as input and prints
#the size of that list along with the items
def PrintSizeAndItems(in_list):
	print &quot;The size of a list is &quot; + str(len(in_list));
	for t_name in in_list:
		print t_name

#Function that prompts the user for a yes or no response
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries &lt;= 0 :
            raise IOError('refusenik user')
        print complaint
</pre>
<p>and, so to use these functions in a different file, you&#8217;d need to import the file, like so:</p>
<pre class="brush: python; title: ; notranslate">
#lesson_1.py
#===========

import lesson_1_functions

_listOfNames = ((&quot;Adom&quot;,46), (&quot;Nazik&quot;,42) ,(&quot;Erik&quot;,15), (&quot;Alex&quot;,18))
lesson_1_functions.ask_ok(&quot;Ok to print?&quot;);
lesson_1_functions.PrintSizeAndItems(_listOfNames)
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Classes"></a></p>
<h2>Classes</h2>
<p>Here is sample class structure:</p>
<pre class="brush: python; title: ; notranslate">
class Person:
     def __init__(self, Name, Lastname, Sex, Age = None):
          self.Name = Name
          self.Lastname = Lastname
          self.Age = Age
          self.Sex = Sex
</pre>
<p>Another example of a class, which is a calculator class</p>
<pre class="brush: python; title: ; notranslate">
class Calc:
    x,y = 0
    &quot;&quot;&quot;A Calculator class&quot;&quot;&quot;
    def add(self):
        return self.x + self.y
</pre>
<p>The function, which is not a constructor, has &#8216;self&#8217; for it&#8217;s first argument<br />
which is a convention when defining methods for classes in python.</p>
<p>and to use the class:</p>
<pre class="brush: python; title: ; notranslate">
t_basicCalc = Calc() #creates a new instance of the class
t_basicCalc.x = 4
t_basicCalc.y = 32
t_result = t_basicCalc.add();
print t_result; 		#prints 128
print t_basicCalc.__doc__ 	#returns &quot;A Calculator class&quot;
</pre>
<p>A note about class attributes &#8211; Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to.</p>
<p>def __init__, gets called when the object is instantiated. The self reference must be declared for every method but not needed to be passed when calling the method from an instance. An argument can have a default value if not specified by a user, in the Person class &#8216;Age&#8217; is set to None (which is a the same as a null).</p>
<p>To create a Person object, all you do is set the class name to followed by a parenthesis to a variable. </p>
<pre class="brush: python; title: ; notranslate">
t_someGirl = Person(&quot;Anna&quot;, &quot;Stone&quot; , 17, &quot;female&quot;);
</pre>
<p><i><br />
*****<br />
if you defined the Person class in a module named &#8220;lesson_1_functions.py&#8221;, then you can instantiate Person like so:</p>
<pre class="brush: python; title: ; notranslate">
t_someGirl = lesson_1_functions.Person(&quot;Anna&quot;, &quot;Stone&quot; , 17, &quot;female&quot;);
</pre>
<p>*****<br />
</i></p>
<p>and to access the variable all you can do is use the dot notation, like so:</p>
<pre class="brush: python; title: ; notranslate">
print t_someGirl.Name + &quot; , &quot; + t_someGirl.Lastname
</pre>
<p>which will print out: Anna , Stone</p>
<p>you can hold a collection of Person(s) like so:</p>
<pre class="brush: python; title: ; notranslate">
People = []
People.append(Person(&quot;Giffan&quot;, &quot;Pasoi&quot;, 42, &quot;male&quot;))
People.append(Person(&quot;Shean&quot;, &quot;Perihas&quot;, 31, &quot;male&quot;))

for t_person in People:
	print t_person.Name + &quot; , &quot; + t_person.Lastname
</pre>
<p>the variables in a class are called attributes. Attributes can be deleted, like so:</p>
<pre class="brush: python; title: ; notranslate">
t_person = Person(&quot;Tim&quot;,&quot;Stone&quot;,18,&quot;male&quot;)
del t_person.Name
</pre>
<p>If you have long names for methods in classes, you can set it to a<br />
variable and call it later.</p>
<pre class="brush: python; title: ; notranslate">
t_person = Person(&quot;Tim&quot;,&quot;Stone&quot;,18,&quot;male&quot;)
t_girl = Person(&quot;Brooke&quot;,&quot;Burke&quot;,30,&quot;female&quot;)

t_girlFriend = t_person.IsRelationshipAnOption
#it takes a Person object as an argument
t_girlFriend(t_girl)
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Inheritance"></a></p>
<h2>Inheritance</h2>
<p>Example of inheritance:</p>
<pre class="brush: python; title: ; notranslate">
class Base(object):
    def __init__(self, param):
        print &quot;Base:&quot;, param
    def method(self, param):
        print &quot;Base.method:&quot;, param

class Derived(Base):
    def __init__(self, param):
        super(Derived, self).__init__(param)
        print &quot;Derived:&quot;, param
    def method(self, param):
        Base.method(self, param)
        print &quot;Derived.method:&quot;, param

&gt;&gt;&gt; d = Derived(&quot;me&quot;)
Base: me
Derived: me
&gt;&gt;&gt; d.method(&quot;you&quot;)
Base.method: you
Derived.method: you
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Python in Linux"></a></p>
<h2>Python in Linux</h2>
<p>In a Linux system, by default python is installed in /usr/local/bin/python directory.<br />
To make a python script executable, set the permission mode to executable. </p>
<pre class="brush: bash; title: ; notranslate">
chmod +x python_script.py
</pre>
<p>to run it, call the script like so:</p>
<pre class="brush: bash; title: ; notranslate">
./python_script.py
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Creating a GUI application"></a></p>
<h2>Creating a GUI application</h2>
<p>TKinter is the de facto GUI library for Python. You need to install the module in order to use it.<br />
here is the code to install:</p>
<pre class="brush: bash; title: ; notranslate">
sudo apt-get install python-tk
</pre>
<p>here is a sample code:</p>
<pre class="brush: python; title: ; notranslate">
from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text=&quot;QUIT&quot;, fg=&quot;red&quot;, command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text=&quot;Hello&quot;, command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print &quot;hi there, everyone!&quot;

root = Tk()
app = App(root)

#run the main loop
root.mainloop()
</pre>
<p><BR/><br />
<BR/><br />
<BR/></p>
<p><a name="Making Python scripts executable"></a></p>
<h2> Making Python scripts executable </h2>
<p>the only way to execute python scripts is by typing python followed the name of the file. And, the other way is to include this line in the beginning of the python file:</p>
<pre class="brush: python; title: ; notranslate">
#! /usr/bin/env python
</pre>
<p> and then change the file privileges to executable: </p>
<pre class="brush: bash; title: ; notranslate">
$ chmod +x python_file_script.py
</pre>
<p>*for windows, double clicking the python.py file will execute the file as if it&#8217;s an executable.</p>
<p><BR /><br />
<BR /><br />
<BR /></p>
<p><a name="The standard library"></a></p>
<h2>The standard library</h2>
<h3> os: directory/file operation </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import os
&gt;&gt;&gt; os.getcwd()      # Return the current working directory
'C:\\Python26'
&gt;&gt;&gt; os.chdir('/server/accesslogs')   # Change current working directory
&gt;&gt;&gt; os.system('mkdir today')   # Run the command mkdir in the system shell
&gt;&gt;&gt; dir(os)
&lt;returns a list of all module functions&gt;
&gt;&gt;&gt; help(os)
&lt;returns an extensive manual page created from the module's docstrings&gt;
</pre>
<h3>shutil: file operation </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import shutil
&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
</pre>
<h3>glob: directory </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import glob
&gt;&gt;&gt; glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
</pre>
<h3> sys: input output </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import sys
&gt;&gt;&gt; print sys.argv
['demo.py', 'one', 'two', 'three']
&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
</pre>
<h3> re: regex </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import re
&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

#for simple ones use string operation
&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
'tea for two'
</pre>
<h3> math: math operations </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import math
&gt;&gt;&gt; math.cos(math.pi / 4.0)
0.70710678118654757
&gt;&gt;&gt; math.log(1024, 2)
10.0

&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
'apple'
&gt;&gt;&gt; random.sample(xrange(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
&gt;&gt;&gt; random.random()    # random float
0.17970987693706186
&gt;&gt;&gt; random.randrange(6)    # random integer chosen from range(6)
4
</pre>
<h3> urllib2: Internet Access </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import urllib2
&gt;&gt;&gt; for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...         print line

Nov. 25, 09:43:32 PM EST
</pre>
<h3> urllib2: Internet Access </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; import urllib2
&gt;&gt;&gt; for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...         print line

&lt;BR&gt;Nov. 25, 09:43:32 PM EST
</pre>
<h3> datetime: time </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; # dates are easily constructed and formatted
&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; now = date.today()
&gt;&gt;&gt; now
datetime.date(2003, 12, 2)
&gt;&gt;&gt; now.strftime(&quot;%m-%d-%y. %d %b %Y is a %A on the %d day of %B.&quot;)
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

&gt;&gt;&gt; # dates support calendar arithmetic
&gt;&gt;&gt; birthday = date(1964, 7, 31)
&gt;&gt;&gt; age = now - birthday
&gt;&gt;&gt; age.days
14368
</pre>
<h3> Performance </h3>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from timeit import Timer
&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
</pre>
<h3> Test Procedures </h3>
<p>We have a sample function named average. The test procedure will be included in the comment area (where the __doc__ variable will read the text). </p>
<pre class="brush: python; title: ; notranslate">
def average(values):
    &quot;&quot;&quot;Computes the arithmetic mean of a list of numbers.

    &gt;&gt;&gt; print average([20, 30, 70])
    40.0
    &gt;&gt;&gt; print average([33, 41, 97])
    57.0
    &gt;&gt;&gt; print average([31, 41, 97])
    57.0
    &quot;&quot;&quot;
    return sum(values, 0.0) / len(values)
</pre>
<p>To run the tests, you must import doctest and call the testmod function.</p>
<pre class="brush: python; title: ; notranslate">
import doctest
print doctest.testmod()   # automatically validate the embedded tests
**********************************************************************
File &quot;lesson_3.py&quot;, line 8, in __main__.average
Failed example:
    print average([31, 41, 97])
Expected:
    57.0
Got:
    56.3333333333
**********************************************************************
1 items had failures:
   1 of   3 in __main__.average
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=3)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/02/python-quick-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Git Basics: A Quick Reference</title>
		<link>http://garejoor.com/2012/01/git-basics-a-quick-reference/</link>
		<comments>http://garejoor.com/2012/01/git-basics-a-quick-reference/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 21:36:37 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[version control]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1487</guid>
		<description><![CDATA[This is a quick reference guide to Git basics. If your completely new to Git or version control, this is not the best reading to spend time on. I suggest progit.org or the quick reference guides from the official git website. Init To start tracking a directory: Add To start version-controlling specific files or a sub-set of files you need to add them to the staging area using the add &#8230; <a class="more_btn" href="http://garejoor.com/2012/01/git-basics-a-quick-reference/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<p>This is a quick reference guide to Git basics. If your completely new to Git or version control, this is not the best reading to spend time on. I suggest <a href="http://progit.org/book/">progit.org</a> or the quick reference guides from the <a href="http://git-scm.com/">official git website</a>.</p>
<h2>Init</h2>
<p>To start tracking a directory:</p>
<pre class="brush: bash; title: ; notranslate">
$ git init
</pre>
<h2>Add</h2>
<p>To start version-controlling specific files or a sub-set of files you need to add them to the staging area using the add command:</p>
<pre class="brush: bash; title: ; notranslate">
$ git add .
$ git commit -m 'first project commit'
</pre>
<p>The &#8216;.&#8217; will add all files in the directory to the staging area. Instead of the &#8216;.&#8217; which indicates all files in the directory you can write the full path to a file or a glob like pattern like *.c.</p>
<p><a href="http://garejoor.com/wp-content/uploads/2012/01/git_diagram.jpg"><img class="alignleft" title="git_diagram" src="http://garejoor.com/wp-content/uploads/2012/01/git_diagram.jpg" alt="" width="400" height="420" /></a><br />
But you don’t want to do that some of the time, especially when you have a binary or executable file in the folder. The binary files are called Untracked files. Each file in your working directory can be in one of two states: tracked or untracked. Tracked files are files that were in the last snapshot, meaning files that were first places in the staging area. They can be unmodified, modified, or staged. Untracked files are files that will not be version-ed by git.</p>
<p>If you have a class of files which you don’t want Git to automatically add or not show as being tracked when calling status Then you can add those files as rules of Exception Example of such files are log files, object files, and etc.<br />
You can add these class of files to a list of ignored files by typing the pattern in the .gitignore file:</p>
<pre class="brush: bash; title: ; notranslate">
$ cat .gitignore
(type the following lines inside the file)
*.[oa]     #for files ending with .o which are object files
*~         #for files that programs like Emacs create as a temporary cache
</pre>
<p>The .gitignore rules are:</p>
<ul>
<li>Blank lines or lines starting with # are ignored.</li>
<li>Standard <a href="http://www.jedit.org/users-guide/globs.html">glob </a>patterns work.</li>
<li>You can end patterns with a forward slash (/) to specify a directory.</li>
<li>You can negate a pattern by starting it with an exclamation point (!).</li>
</ul>
<h2>Commit</h2>
<p>To commit changes to the repository, you need to commit the changes made in the staging area:</p>
<pre class="brush: bash; title: ; notranslate">
$ git commit
</pre>
<p>If you edit the files after adding them (staging the files), then the modified version will not be in the staging area, but the original file that was added last time ,will be in the staging area. Basically the modified version will be in the working directory, and the last time added version will be in the staging area. So a call to commit will not save the current changes. But only after adding the modified file again it will get in the staging area and ready to be committed to the repository. </p>
<h2>Status</h2>
<p>To see the status of the directory:</p>
<pre class="brush: bash; title: ; notranslate">
$ git status (or followed by –s for short version)
</pre>
<p>Let’s run a sample example:</p>
<pre class="brush: bash; title: ; notranslate">
$ vim README
$ git status
# On branch master
# Untracked files:
#   (use &quot;git add ...&quot; to include in what will be committed)
#
#	README
nothing added to commit but untracked files present (use &quot;git add&quot; to track)

$ git add README

$ git status
# On branch master
# Changes to be committed:
#   (use &quot;git reset HEAD ...&quot; to unstage)
#
#	new file:   README
#
</pre>
<h2>Diff</h2>
<p>If a file is changed in the working directory but not staged, you can view the changes using diff:</p>
<pre class="brush: bash; title: ; notranslate">
$ git diff
</pre>
<p>and you&#8217;ll see the changes indicated with + sign, like so:</p>
<pre class="brush: bash; title: ; notranslate">
diff --git a/readme.txt b/readme.txt
index 436fb61..ef8358f 100644
--- a/readme.txt
+++ b/readme.txt
@@ -1,2 +1,9 @@
what is this project?
+It is a python project
+
</pre>
<p>to see changes made in the staging area but not committed use the cached option:</p>
<pre class="brush: bash; title: ; notranslate">
$ git diff --cached
</pre>
<h2>Clone</h2>
<p>To get a copy of a project and it’s repository you need to do a clone. This is how you checkout a project in git:</p>
<pre class="brush: bash; title: ; notranslate">
$ git clone [url] ? the url can be ssh/http/https/ftp/git….
</pre>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/01/git-basics-a-quick-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up Apache HTTP Server on CentOS</title>
		<link>http://garejoor.com/2012/01/setting-up-apache-http-server-on-centos/</link>
		<comments>http://garejoor.com/2012/01/setting-up-apache-http-server-on-centos/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 07:32:53 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[centOs]]></category>
		<category><![CDATA[httpd]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1404</guid>
		<description><![CDATA[Setting up HTTPD on CentOS By default the Apache web server is installed on CentOS but even if it is not, you can install it using the following command: to start the service, type the following entry: if you want to be able to access your pages externally, you need to open port 80 on the firewall. Open up the iptables file: and add the following line to the end &#8230; <a class="more_btn" href="http://garejoor.com/2012/01/setting-up-apache-http-server-on-centos/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<h2><strong>Setting up HTTPD on CentOS</strong></h2>
<p>By default the Apache web server is installed on CentOS but even if it is not, you can install it using the following command:</p>
<pre class="brush: bash; title: ; notranslate">
$ sudo yum install httpd
</pre>
<p>to start the service, type the following entry:</p>
<pre class="brush: bash; title: ; notranslate">
$ service httpd start
</pre>
<p>if you want to be able to access your pages externally, you need to open port 80 on the firewall. Open up the iptables file:</p>
<pre class="brush: bash; title: ; notranslate">
$ vim /etc/sysconfig/iptables
</pre>
<p>and add the following line to the end of the file right before COMMIT:</p>
<pre class="brush: bash; title: ; notranslate">
A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
</pre>
<p>save and exit, and then restart the firewall:</p>
<pre class="brush: bash; title: ; notranslate">
$ service iptables restart
</pre>
<p>The HTTP file location is in /var/www/<br />
The index.html page should be in </p>
<pre class="brush: plain; title: ; notranslate">
/var/www/html
</pre>
<p><BR /></p>
<h2><strong> References </strong></h2>
<p><a href="http://www.dedoimedo.com/computers/apache_book_part.html" title="Apache guide by Dedoimedo" target="_blank">Apache guide by Dedoimedo </a></p>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/01/setting-up-apache-http-server-on-centos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up Git on CentOS</title>
		<link>http://garejoor.com/2012/01/setting-up-git-on-centos/</link>
		<comments>http://garejoor.com/2012/01/setting-up-git-on-centos/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 06:52:52 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[centOs]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Git Server]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1444</guid>
		<description><![CDATA[Git is a new version control system created by Linus Torvalds. If your starting a project, it is a good idea to have a version control system setup before starting the project. There are alternatives to git but two of the most popular ones are SVN, CVS. The major difference between git and the rest is that git is distributed where svn or cvs are server-client based. Setup By default, &#8230; <a class="more_btn" href="http://garejoor.com/2012/01/setting-up-git-on-centos/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<p>Git is a new <a href="http://en.wikipedia.org/wiki/Revision_control">version control</a> system created by <a href="http://en.wikipedia.org/wiki/Linus_Torvalds">Linus Torvalds</a>. If your starting a project, it is a good idea to have a version control system setup before starting the project. There are alternatives to git but two of the most popular ones are <a href="http://en.wikipedia.org/wiki/Apache_Subversion">SVN</a>, <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System">CVS</a>. The major difference between git and the rest is that git is distributed where svn or cvs are server-client based.</p>
<p><BR /></p>
<h2><strong>Setup</strong></h2>
<p>By default, Git is installed on your CentOS, but even if it is not for some reason you can install it manually.<br />
<b><i>Note: all of the following commands require root privilege:</i></b></p>
<pre class="brush: bash; title: ; notranslate">
$ su root
</pre>
<p>execute the following command to install git:</p>
<pre class="brush: bash; title: ; notranslate">
$ yum install git
</pre>
<p>don&#8217;t worry if you don&#8217;t know whether or not Git is installed on your system, the above command will detect whether it is installed or not and will ignore the installation request.</p>
<p><BR /></p>
<h2><strong>Configuration</strong></h2>
<p>To setup Git on CentOS, first you need to setup a SSH server on CentOS. Click here to read &#8220;<a title="Setting up a SSH server on CentOS" href="http://garejoor.com/2012/01/setting-up-a-ssh-server-on-centos/" target="_blank">Setting up SSH on CentOS</a>&#8220;.</p>
<p>First, we will create a new user named Git on the Server system:</p>
<pre class="brush: bash; title: ; notranslate"> $ adduser git  </pre>
<p>To set or even change the password:</p>
<pre class="brush: bash; title: ; notranslate"> $ passwd git  </pre>
<p>A Git user will be created and the home directory of git will be created in </p>
<pre class="brush: bash; title: ; notranslate"> /home/git  </pre>
<p>The owner and the group owner of that folder must change so it belongs to the new user &#8216;git&#8217; &#8211;  we can change that via:</p>
<pre class="brush: bash; title: ; notranslate"> $ chown git:git /home/git  </pre>
<p>if you followed the steps from my last post on how to create SSH server on CentOS you must also add the &#8216;git&#8217; user to the SSH allowed list of SSH-ers configured in this file:</p>
<pre class="brush: plain; title: ; notranslate"> /etc/ssh/sshd_config </pre>
<p>Now lets create the project repository. We will login as git (exit root): </p>
<pre class="brush: bash; title: ; notranslate">
$ exit root
$ su git
</pre>
<p>and create the repo in the home directory:</p>
<pre class="brush: bash; title: ; notranslate">
$ cd ~
$ mkdir ProjectNameRepo.git
$ cd ProjectNameRepo.git
$ git init –bare
</pre>
<p>This folder will be the git repository on your server for this particular project. This is the folder where you will get copies from (called clone-ing) and committing new updates (called push-ing) from different users. </p>
<p><BR /></p>
<h2><strong>Using the System</strong></h2>
<p>From a different computer where you will use to code, create the project folder and create a readme file inside the folder, then initialize it using git:</p>
<pre class="brush: bash; title: ; notranslate">
$ mkdir ProjectName
$ cd ProjectName
$ touch readme.txt
$ git init
</pre>
<p>for more information on git commands see references at the bottom.<br />
stage the newly added files using git add:</p>
<pre class="brush: bash; title: ; notranslate"> $ git add . </pre>
<p>Now we must commit, but before that you must configure the user via git config. Your name and e-mail will be used in as part of the committing metadata.</p>
<pre class="brush: bash; title: ; notranslate">
$ git config --global user.name 'Your Name'
$ git config --global user.email you@somedomain.com
$ git commit -m 'My first commit! Matt Damooooon'
</pre>
<p>The changes have been snapshot-ed and will get transferred to the repo when pushed. Now, we need to define the repo server which is the CentOS PC we configured on the first part of this walkthrough. </p>
<pre class="brush: bash; title: ; notranslate">
$ git remote add origin ssh://git@server-address:port/~/ProjectNameRepo.git
</pre>
<p>And now we can push the code and push it later on when changes are made to the code:</p>
<pre class="brush: bash; title: ; notranslate"> $git push origin master </pre>
<p>To get a clone of the project on a different PC user the following command:</p>
<pre class="brush: bash; title: ; notranslate">
$ git clone ssh://git@server-name:port/~/ProjectName.git
</pre>
<p>and if you want to work on it from the local server, you can get a copy by specifing a different path when calling clone</p>
<pre class="brush: bash; title: ; notranslate">
$ git clone /home/got/ProjectName.git
</pre>
<p>In both cases, a copy of the repo will get copied to your current location under the directory name ProjectName without the .git extension.</p>
<h2><strong>References</strong></h2>
<p>A git reference based tutorial: http://gitref.org/creating/</p>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/01/setting-up-git-on-centos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up a SSH server on CentOS</title>
		<link>http://garejoor.com/2012/01/setting-up-a-ssh-server-on-centos/</link>
		<comments>http://garejoor.com/2012/01/setting-up-a-ssh-server-on-centos/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 18:17:09 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[centOs]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[ssh server]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1419</guid>
		<description><![CDATA[SSH allows users to connect to a remote linux/unix operating system and work on it as if they were actually physically near it. This allows you to work on your code/project from a remote location and not to worry about coping and pasting the changes made somewhere to another. Setup By default, SSH is installed on your CentOS, but even if it is not for some reason you can install &#8230; <a class="more_btn" href="http://garejoor.com/2012/01/setting-up-a-ssh-server-on-centos/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<p>SSH allows users to connect to a remote linux/unix operating system and work on it as if they were actually physically near it. This allows you to work on your code/project from a remote location and not to worry about coping and pasting the changes made somewhere to another. </p>
<p><BR /></p>
<h2><b>Setup</b></h2>
<p>By default, SSH is installed on your CentOS, but even if it is not for some reason you can install it manually.<br />
<b><i>Note: all of the following commands require root privilege:</i></b></p>
<pre class="brush: bash; title: ; notranslate">
$su root
</pre>
<p>The most widely used SSH implementation is openssh which can be installed using this command:</p>
<pre class="brush: bash; title: ; notranslate">
$ yum install openssh
</pre>
<p>don&#8217;t worry if you don&#8217;t know whether or not SSH is installed on your system, the above command will detect if ssh is installed and it will ignore the request.</p>
<p><BR /></p>
<h2><b>Configuration</b></h2>
<p>To change the SSH settings, open up the following file (/etc/ssh/sshd_config) using a text editor. The easiest way to do this is using vim/vi since root privilege are required for this operation.</p>
<pre class="brush: bash; title: ; notranslate">
$ vim /etc/ssh/sshd_config
</pre>
<p>The file contains setting variables along with values First, we need to disable root access. What this means is that when using ssh to login to the computer you or anyone else shouldn&#8217;t be able to do root@mycomputer. So edit the following entry:</p>
<pre class="brush: bash; title: ; notranslate">
PermitRootLogin no
</pre>
<p>If you have specific users who are going to use ssh to login, add AllowUsers followed by the usernames, for example:</p>
<pre class="brush: bash; title: ; notranslate">
AllowUsers alice bob
</pre>
<p>For security reasons, change the default port from 22 to something else that is not being used by another process (for example do not use port 80, or 3433). To change the default port edit the following entry:</p>
<pre class="brush: bash; title: ; notranslate">
Port 4322
</pre>
<p>We are done with the ssh config file, so save and close it.</p>
<p>Al the last entry we changed the default port from 22 to 4322. Doing this would also require you to modify the Operating system firewall to allow access to port 4322. The firewall setting file is located at (/etc/sysconfig/iptables), so open it up using a text editor.</p>
<pre class="brush: bash; title: ; notranslate">
$ vim /etc/sysconfig/iptables
</pre>
<p>by default, port 22 is open on the firewall and the entry in the file that configures this is:</p>
<pre class="brush: bash; title: ; notranslate">
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
</pre>
<p>so change the the number 22 to 4322 or any number you picked yourself.</p>
<pre class="brush: plain; title: ; notranslate">
-A INPUT -m state --state NEW -m tcp -p tcp --dport 4322 -j ACCEPT
</pre>
<p>Now save and close the file.</p>
<p>Since we modified the ssh server and the firewall settings, we need to restart the two services (or daemons).</p>
<pre class="brush: bash; title: ; notranslate">
$ service iptables restart
$ service sshd restart
</pre>
<p>if you have a router installed, read the rest of the steps.</p>
<p><BR /></p>
<h2><b>Router Firewall</b></h2>
<p>Your firewall is configured to ignore incoming packets. So we need to open up the new port 4322 and set it to route all the traffic to our PC using port forwarding.<br />
First lets get the ip of the computer.</p>
<pre class="brush: bash; title: ; notranslate">
$ ifconfig
</pre>
<p>usually the first paragraph that starts with eth0, is the NIC your looking for. The IP should start with 192.168.xxx.xxx, in my case it is 192.168.1.3</p>
<p>Second go to your router page and find port forwarding page. Set the start and end ports to 4322 and the destination IP to the IP we found from last step, in my case this is 192.168.1.3. The specific steps are dependent on your router manufacturer. </p>
<p><BR /></p>
<h2><b>Other Resources</b></h2>
<p>CentOS Wiki page for SSH: <a href="http://wiki.centos.org/HowTos/Network/SecuringSSH">http://wiki.centos.org/HowTos/Network/SecuringSSH</a></p>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2012/01/setting-up-a-ssh-server-on-centos/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python: Quick Start</title>
		<link>http://garejoor.com/2011/08/python-quick-start/</link>
		<comments>http://garejoor.com/2011/08/python-quick-start/#comments</comments>
		<pubDate>Tue, 02 Aug 2011 20:01:51 +0000</pubDate>
		<dc:creator>Garejoor</dc:creator>
				<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[quick start]]></category>

		<guid isPermaLink="false">http://garejoor.com/?p=1210</guid>
		<description><![CDATA[What is Python? Python is a programming language like C or C++ with several key differences. First of all, it&#8217;s not as fast as C or C++ since it&#8217;s a scripting language. This means the code wont compile to a native machine language (10010101), instead a run-time environment will handle the execution. Secondly, Python is a dynamic language, meaning each line of code that the computer reads will get executed &#8230; <a class="more_btn" href="http://garejoor.com/2011/08/python-quick-start/"> <img src="http://garejoor.com/wp-content/themes/Garejoor/images/more_btn.png"  alt="" /> </a>]]></description>
			<content:encoded><![CDATA[<h2>What is Python?</h2>
<p>Python is a programming language like C or C++ with several key differences. First of all, it&#8217;s not as fast as C or C++ since it&#8217;s a <a href="http://en.wikipedia.org/wiki/Scripting_language" target="_blank">scripting language</a>. This means the code wont <a href="http://en.wikipedia.org/wiki/Compiler" target="_blank">compile</a> to a native machine language (10010101), instead a run-time environment will handle the execution. Secondly, Python is a <a href="http://en.wikipedia.org/wiki/Dynamic_programming_language" target="_blank">dynamic language</a>, meaning each line of code that the computer reads will get executed at that instant. But, python code will run on any machine (windows, mac, linux) and it&#8217;s very easy to learn and code in python.</p>
<h2>Installing Python</h2>
<p>If you haven&#8217;t already installed Python, you can find tutorials on-line on how to install python for your platform (Mac OS, Windows, Ubuntu, Red hat). Since I&#8217;m using Ubuntu, I&#8217;ll explain the installation process which is one line of bash code. Open up the terminal and type the following command:</p>
<pre class="brush: bash; title: ; notranslate">
$ sudo apt-get install python
</pre>
<h2>Important Facts</h2>
<ul>
<li>Python has no curly braces ({}). Instead of Braces python uses indentation to relate which part of code belongs to another. I use tab for indentation but the official website says use &#8220;Use 4-space indentation, and no tabs&#8221;. However if you use a proper programming text editor it will indent automatically.</li>
<li>This is Pythons <a href="http://docs.python.org/tutorial/" target="_blank">official tutorials</a> page &#8211; this is where most of the material I present here is extracted from.</li>
<li>There are two ways to write code in Python. One is straight from the interpreter and the other is within a file. We&#8217;ll write everything in a file and execute the code from files. The file which includes the python code has the &#8220;.py&#8221; extension.</li>
</ul>
<h2>Sample Run</h2>
<p>Open up a terminal and create a directory where we can save all our exercise files there. Create a &#8220;lesson_1.py&#8221; file and write the following code in the file:</p>
<pre class="brush: python; title: ; notranslate">
#assign 1 to number1
number1 = 1;
#assign 2 to number2
number2 = 2;
#add the two variables and place the result into number3
number3 = number1 + number2;
#print the value to the output
print number3;
</pre>
<p>on the terminal, cd into the newly created directory. Type python followed by the location of the lession_1.py file:</p>
<pre class="brush: bash; title: ; notranslate">
$ python lesson.py
</pre>
<p>and you&#8217;ll see a number 3 displaying on the output screen. The <strong>lines that start with a # are comments</strong>, so you can write notes and comments and it won&#8217;t affect your program. There is no need to type semicolon after each line however, <strong>if your going to write more than two phrases in one sentence you must include a semicolon (;) after each line</strong>. Using semicolon the above code will look something like this:</p>
<pre class="brush: python; title: ; notranslate">
#all in one line
number1 = 1; number2 = 2; number3 = number1 + number2; print number3;
</pre>
<p>I mentioned above that you can execute your code straight from the interpreter. To do this, type python in the terminal:</p>
<pre class="brush: bash; title: ; notranslate">
garejoor@ubuntu:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
&gt;&gt;&gt;
</pre>
<p>now type in the same code we you wrote in the file above and press enter. You&#8217;ll see it will output the same result. To exit the interpreter type exit() and enter.</p>
]]></content:encoded>
			<wfw:commentRss>http://garejoor.com/2011/08/python-quick-start/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

