Are you looking for my non-technical blog?

This is now my technical-only blog, my non-technical blog is here.
Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

30 September 2013

A Quick Intro. to NumPy

For me, NumPy is a Python list on steroids. You can use it to create multidimensional arrays and matrices.

The convention is to import it as follows:

import numpy as np

To create an array of numbers between 0 and 9, you could use the following command:

x = range(9)

To convert that list into a NumPy array, you can write:

x = np.array(range(9))

And to make you life easier, there is a shorthand for the above command:

x = np.arange(9)

So far, we have been creating one dimensional array. However, there are ways to reshape the arrays. The reshape() method when applied on an array, it returns a reshaped version of it without changing the original object. To reshape the original object itself, then use resize() instead.

y = x.reshape(2,5)

The above command create a 2-dimensional array of 2 rows and 5 columns. You can create a much dimensional arrays as you want. See the command below for a 3*4*5 array.

y = np.arange(3*4*5).reshape(3,4,5)

The mathematical operations '+', '-', '/' and '*' are applied elementwise.

x = np.arange(10)

# To multiply each element of x by 10
y = x + 10

# To multiply each element of x by itself
y = x + x

To do a Matrix Multiplication though:

# Create a 3 * 5 Matrix
A = np.arange(15).reshape(3,5)

# Create a 5 * 2 Matrix
B = np.arange(10).reshape(5,2)

# Dot product gives you a 3 * 2 Matrix
y = y = np.dot(A, B)

Just like lists, you can get parts of arrays

For original lists:

A = range(10)
A[2:5] # [2, 3, 4]

For NumPy Arrays

B =  arange(10)
B[2:5] # array([2, 3, 4])

However, you can set some elements of the array as follows

B[2:5] = 1337

But, you cannot do the same to lists.

A[2:5] = 1337 # TypeError: can only assign an iterable

For statisticians, there are also the following functions

x = np.arange(5) + 1
x.mean() # 3.0
x.max() # 5
x.min() # 1
x.std() # 1.414

You can also access elements of the array using start, stop and a step:

x = np.arange(10)
x[2:7:2] # array([2, 4, 6])

Or access specific elements, let's say elements 1, 5 and 6

x[[1,5,6]] # array([1, 5, 6])

Similar to reshape() and resize(), ravel() converts a multidimensional array into a one-dimensional array, while transpose() turns rows into columns and vice versa.

If you program in R, you will not miss their way of accessing elements of array that meet a certain condition.

x = np.arange(10)
x[x>4] # array([5, 6, 7, 8, 9])
x[x%2 == 1] # array([1, 3, 5, 7, 9])

If you are having an array of elements that are either True or False.

x = np.array([True, False, True, True])

x.all() # Only True if all elements are True
x.any() # Only True if any elements are True

Finally, there is a repeat() that repeats each element of the array n times

x = np.array([1, 2])
x.repeat(3) # array([1, 1, 1, 2, 2, 2])

That's all folks for today.
Check the following tutorial for more information.






24 December 2012

One line rsync tutorial

You might need to read rsync man page to understand all the options and bells and whistles of that software, but for me, all I need now is a one line tutorial:
rsync -rv src/ dst/

08 June 2012

Quick Intro to Ruby on Rails

There are a lot of tutorials and Getting Started guides, but I still need to write, not really a tutorial, but consider it as me taking notes of what I am learning so far, focusing mainly on Rails CLI.

Installing Rails:
$ gem install rails

Creating You Application (let's call it myblog)
$ rails new myblog
This will create a new folder with some stuff in there, i.e. your project folder.

To Run the Rails Server
$ rails server

What Are Rails Generators?
$ rails generate --help
Usage: rails generate GENERATOR [args] [options]


You can watch this Webcast about Rails3 Generators and then come back here l8r...

Types of Generators:

Rails:
  assets
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  resource
  scaffold
  scaffold_controller
  session_migration
  task
Coffee:
  coffee:assets
Jquery:
  jquery:install
Js:
  js:assets


Generating Controller:
$ rails generate controller --help
$ rails generate controller CreditCard open debit credit close

Description:
Stubs out a new controller and its views. Pass the controller name, either CamelCased or under_scored, and a list of views as arguments.

To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

Example:
`rails generate controller CreditCard open debit credit close`

Credit card controller with URLs like /credit_card/debit.
Controller: app/controllers/credit_card_controller.rb
Functional Test: test/functional/credit_card_controller_test.rb
Views: app/views/credit_card/debit.html.erb [...]
Helper: app/helpers/credit_card_helper.rb


Scaffold Generator
$ rails generate scaffold --help
Usage:
  rails generate scaffold NAME [field[:type][:index] field[:type][:index]] [optons]

Description: 

According to Wikipedia, Scaffolding is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used. The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a "scaffold" on which to build a more powerful application. [I.e. It creates tables, fields, and web forms to edit those tables, etc.]

Scaffolds an entire resource, from Model and Migration to Controller and Views, along with a full test suite. The resource is ready to use as a starting point for your RESTful, resource-oriented application.

Pass the name of the model (in singular form), either CamelCased or under_scored, as the first argument, and an optional list of attribute pairs.

Attributes are field arguments specifying the model's attributes. You can optionally pass the type and an index to each field. For instance: "title body:text tracking_id:integer:uniq" will generate a title field of  string type, a body with text type and a tracking_id as an integer with an  unique index. "index" could also be given instead of "uniq" if one desire  a non unique index.


Database
# Database configuration are stored in config/database.yml 
# To create the actual database, use the following commnad:
$ rake db:create

Gemfiles [In Application Home Directory]

Gemfile (and Gemfile.lock): These files allow you to specify what gem dependencies are needed for your Rails application.
$ bundle install  # Use this command to install newly added gems 

Some Ruby Tips
Since I don't speak ruby, here are some things I stumbled upon today
$myVar ==> Global Variable.
:myVar ==> I have no idea what's that, they call it Symbol, looks like constant string or something.


That's all folks for today.

17 February 2012

Notepad++ Sessions

I don't remember using an IDE for writing code ever. I am allergic to such stuff. I prefer a text editors and command line compilers or interpreters. Earlier when I used to write C/C++ code on Linux, I used to write the Make file myself, on Windows I only code in Python since it doesn't require the IDE fuss. I think one of the main reasons that backs me off of writing mobile applications is that IDE's, Simulators and stuff like that are required there, let alone my natural hatred for Java.

Anyway, I normally use Notepad++ as my text editor on Windows, and one of its cool features is that it remembers the files you had open in your last sessions and opens them the next time you use the program. Think of it that same way Firefox remembers the tabs you had open the previous time you used it. It's cool, it makes life easier when working on a project consisting of many files, instead of opening each one of them every time, yet sometimes you find yourself having zillions of open files from unrelated projects. So here is some other alternative.

Notepad++ Sessions


In Notepad++ you can save your current session into a file, hence you can have a session file for each project you are working on.


First of all, go to "Settings >> Preferences.." then un-check the "Remember current session ..." field and assign a file extension for your session files, I used ".npp" here, but you can invent any extension.


Now whenever you are on a project with many open files, go to "File >> Save Session" and save your session into a file with .npp as its extension, next time whenever you click on that file your previous session for that project will be open. Whenever you add or remove files to your project you can Save your session and overwrites your session file with those new updates.

03 January 2012

A Waitress & A Flask

Flask is a microframework for Python based on Werkzeug, Jinja2, and here is a simple Flask Hello World code:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run()

Waitress on the other hand is a pure-Python WSGI server, and here's normal usage of the server:

from waitress import serve
serve(wsgiapp, host='0.0.0.0', port=8080)

So, here is how I wrote code to run Flask from within a Waitress WSGI Server:

from flask import Flask
from waitress import serve

app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
#app.run()
serve(app)

Documentations:
http://flask.pocoo.org/docs/
https://github.com/Pylons/waitress/blob/master/docs/index.rst

29 December 2011

Quick jQuery Intro.

For the second time in two days, one of my friends asks me about jQuery. So, here is a quick introduction to it.Let's say we have the following HTML that contains a list of four items
<html>
<head>
<title>jQuery demo</title>
</head>
<body>
<ul>
<li class="news_line">Mr. One</li>
<li class="news_line">Mr. Two</li>
<li class="news_line">Mr. Three</li>
<li class="news_line">Mr. Four</li>
<ul>
</body>
</html>
Now we want to make it more interactive, so when the mouse hovers on any of the below items it turns red, and when it goes away it turns white again. Here comes the beauty of jQuery, you can give them all a CSS class "news_line", hence you write a function once and it is applicable to them all. So, first of all, you have to include the following script.

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
></script>
You put all your jQuery script between the following, this makes sure it's not executed until the page is loaded successfully
<script>
$(document).ready(function(){
... YOUR jQUERY SCRIPT HERE ...
});
</script>
We now are going to use the following function, which simply mean attach an event catcher to the items with class "news_line", and make the event trigger is 'mouseover', i.e. whenever the mouse hovers over it. We also have other events such as 'mouseout', etc.
$(".news_line").live('mouseover',function(){
... DO SOME STUFF HERE ...
});
One more thing to notice is "$(this)", the above command searches for all items with class "news_line", now when we use "$(this)", we are referring the the item we are dealing with now. And starting from that point we use another functions "css()" to change the object's background colour. You may in some other cases use stuff like "$(this).children().css()" to change the colour of all of the children of the matched items, or "$(this).parent().parent().hide();" to hide the parent of the parent of the item you are referring to, etc.So, finally here is the code we are talking about here.
<html>
<head>
<title>jQuery demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".news_line").live('mouseover',function(){
$(this).css("background-color","#ff0000");
});
$(".news_line").live('mouseout',function(){
$(this).css("background-color","#ffffff");
});
});
</script>
</head>
<body>
<ul>
<li class="news_line">Mr. One</li>
<li class="news_line">Mr. Two</li>
<li class="news_line">Mr. Three</li>
<li class="news_line">Mr. Four</li>
<ul>
</body>
</html>

Finally, here is a list of all jQuery functions, events, etc.
http://visualjquery.com/

10 March 2009

How to Create a New Place

In this video, I'll demonstrate adding a new place, in our example the new place is the Colosseum, in Rome, Italy.


Baralbait - Create New Place from Tarek Amr on Vimeo.

Please notice that you can always make use of other sites such as Wikimapia and Wikipedia to check the places' spelling, addresses, etc.

Also make sure to add as much info as you can about the place, and if it has different spellings try to write them all.

Finally, some places have branches all over the world, and some other places are not very well known and people may not know where there are from their name, so it's always better to write their names as follows, "McDonald's Westford" instead of just "McDonald's"