2013年7月23日 星期二

bash_profile vs bashrc vs profile, environment variables

.bash_profile --> login shell

.bashrc --> non-login shell

login shell:
e.g. login via console, ssh

non-login shell:
e.g. new terminal windows in inside GNOME ( already logged in)
/bin/bash in terminal

When bash is invoked as an interactive login shell, or as a non-interac-
tive shell with the --login option, it first reads and executes commands
from the file /etc/profile, if that file exists. After reading that file,
it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that
order, and reads and executes commands from the first one that exists and
is readable. The --noprofile option may be used when the shell is started
to inhibit this behavior.

/etc/profile --> ~/.bash_profile > ~/.bash_login > ~/.profile

Environment Variable

/etc/environment - This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line. Specifically, this file stores the system-wide locale and path settings.


set -- show environment variables + shell variables

env -- show environment variables


2013年7月15日 星期一

CodeIgniter .htaccess mod_rewrite 404

CodeIgniter directory: /Document-root/[your-URL-path]
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /[your-URL-path]
RewriteCond $1 !^(index\.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)$ index.php/$1 [L]
                  `---!! No heading slash
</IfModule>

2013年7月12日 星期五

Javascript Prototype Chain / Inheritance

*Every Object has an internal link to another object called prototype
syntax constructs:
var o = {a: 1};
//o ---> Object.prototype ---> null

var a = ["yo", "whadup", "?"];
//a ---> Array.prototype ---> Object.prototype ---> null

function f(){
return 2;
}
//f ---> Function.prototype ---> Object.prototype ---> null

Constructor:
function Graph() {
this.vertexes = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v){
this.vertexes.push(v);
}
};
var g = new Graph();
//Graph ---> Graph.prototype ---> Object.prototype


Object.create
var a = {a: 1};
var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null
var d = Object.create(null);
// d ---> null

2013年7月7日 星期日

LINUX SYSTEM INITIALIZATION

DEBIAN

1.BIOS
   |--- POST (Power On Self Test)
    `--- Load initial code (bootloader code/kernel code...etc) form DISK
2.Bootloader (Bootstrap Loader)
    `--- load system kernel image and initrd image, hands over control
`-- Linux kernel             `---- initramfs
    * initrd : image of temporary root file system loaded into memory
               do hardware detection,module loading, mnt root file sys
3. initrd (mini-Debian System (Started by bootloader))
`----- /init is executed
4. Debian-System
|----- 0. /sbin/init (init(8)) is executed
| |--- parent of all processes
| `--- create process from script /etc/inittab
|----- 1. System goes into runlevel N(none) by following /etc/inittab
|----- 2. System goes into runlevel S for initialization
`----- 3. System goes into runlevel 2-5(multi-user))(determined by /etc/inittab)
`-- rc.local is executed at the end of each multiuser runlevel




A Bootable Linux Image

Load Sequence: Boot Loader->kernel->initrd->rootfs(the fs user will be working on)

2013年7月4日 星期四

BASIC APACHE

APACHE 2 ON **DEAIBN


#       /etc/apache2/
#       |-- apache2.conf
#       |       `--  ports.conf
#       |-- mods-enabled
#       |       |-- *.load
#       |       `-- *.conf
#       |-- conf.d
#       |       `-- *
#       `-- sites-enabled
#               `-- *


**Struture of config in Debian is different from other linux dist.
** apache2.conf is the main config file
it includes other files (mods-enabled/*, conf.d/*, sites-enabled,ports.conf)

** ports.conf
ports to listen to

Directives: Timeout, Keepalive,AccessFileName ........
Configuration Section Containers:
|
|---evaluted each request : <VirtualHost> <Directory>....
| |
| |--Filesystem cotainer:<Directory> <Files>.....
| |
| `--Webspace Container: <Location>......
|
`---evaluated at startup: <IfDefine> <IfModule> ....
Directives Scoping: Limit the scope of effect of  directives(w/SectionContainer)

.htaccess: Placed in DocumentDirectory, use directives to immediately affect access
Administrator can limit directives in .htaccess by AllowOverride Directive



Virtual Hosting


How apache selects virtual to respond to request
1. Find best matching <VirtualHost> based on IP addr
2. More than 1 match--> compare ServerName and ServerAlias
3. No match found --> handled by global server config


#sites-available/000-example
<VirtualHost *:80>
             `--- Placing IP rather than DN in this directive
        ServerName www.example.org  ß FQDN of server
        ServerAdmin webmaster@localhost  ß admin mail
        DirectoryIndex index.html index.cgi index.pl index.php index.xhtml
                                                                                        `--- index files to look for
        DocumentRoot /var/www           ß root directory of site
        Alias /mydoc /var/local/lib/mydata
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                                        `----Additional option for Directory
                AllowOverride None
                                        `----.htaccess (Only available under Directory)
                Order allow,deny
                allow from all
                                        |----.Search allow first, then deny, deny overwrites allow
                                        `----Rule not found --> deny
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/  <--CGI Scripts location
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                               |------ExecCGI à CGI script
                                      |------MultiViews HTTP1.1 content negotiation
                                       `------SymLinksIfOwnerMatch stricter symlink follow
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerName other.example.com  ßanother virtual host
    ServerAlias other.example.com *.other.example.com
                          `--another way is set ServerAlias
    DocumentRoot /www/otherdomain

</VirtualHost>


<VirtualHost _default_:80>  <--catching request not matching any vhost
    DocumentRoot /www/default

</VirtualHost>

Listen 8080   <--Listen directive should be placed here or in port.conf
Listen 9090
<VirtualHost *:8080 *:9090>  
    DocumentRoot /www/default


</VirtualHost>

UserDir Module
Mods-available/userdir.conf
<IfModule mod_userdir.c>
  UserDir public_html
  UserDir disabled root

  <Directory /home/*/public_html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
  </Directory>
</IfModule>

CGI Dynamic Content w/ PHP,Python,Perl
$apt-get install libapache2-mod-[php,perl,python]

.htaccess

*place directives
<Files ~ "^\.(htaccess|htpasswd)$">
deny from all
</Files>
Option +Indexes –FollowSymLinks
IndexOptions +FancyIndexing
IndexIgnore *.php *.exe

*Rewirte Request URL (Requires mod_rewrite and override allowed)
.htaccess

RewriteEngine on
RewriteBase /myApp         <---- base URL for per-directory rewrites

RewriteCond %{HTTP_HOST}   !^www\.example\.com [NC]
    `----only rewrite when HOST matches(NC flag = no case)
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{SERVER_PORT} !^80$

RewriteRule ^/?(.*)         http://www.example.com:%{SERVER_PORT}/$1 [L,R,NE]
    |---- $N (0 <= N <= 9) -> back references
    |---- (flag: L -> Stop the rewriting process immediately and don't apply any more rules)
    |---- (flag: R -> Forces an external redirect)
    `----( flag: NE: noescap -> especial characters, such as & and ?, for example, will be converted to their hexcode equivalent. Using the [NE] flag prevents that from happening.)

2013年7月3日 星期三

SQL

login
mysql -hlocalhost -u[username] -p[password]

SELECT DATABASE
use [database]


CREATING USERS/ GRANTING ACCESS TO DATABASE


Create new table:

CREATE table [table name](
id int NOT NULL PRIMARY KEY,
title varchar(255) UNIQUE
.
.
.

);


**NOT NULL
**PRIMARY KEY
**UNIQUE


Insert if not entry not existent or do nothing if entry is duplicate


INSERT INTO table(c1,c2)VALUES(v1,v2) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)


Search for duplicate:

SELECT address, count(id) as cnt FROM list
GROUP BY address HAVING cnt > 1


SELECT * FROM all_papers WHERE title IN(SELECT title FROM all_papers WHERE title NOT LIKE  '%unavailable%' GROUP BY (title) HAVING COUNT( title ) >1)

PHP with SQL
$USER = [username];
$PASS = [password];
try {
    $dsn = "mysql:dbname=$DBNAME;host=$HOST";
    $dbh = new PDO($dsn, $USER, $PASS);
    } 
    catch (PDOException $e) {
        print "Error!: " . $e->getMessage();
        die();
    }
    $TABLE = [tablename];
    $sql = "SELECT * FROM $TABLE";
    foreach (self::$dbh->query($sql) as $row) {
        .
        .
        .
    }

use addslashes to process string before INSERT