2017年11月30日 星期四

[ JavaScript Gossip ] JavaScript 核心 : 這些東西不簡單 (變數)

轉載自 這裡 
在程式語言的分類中,依所宣告的變數是否帶有型態,可區分為靜態(Static-type)語言動態(Dynamic-type)語言
Java、C/C++ 等皆為靜態語言,其宣告變數必然同時宣告變數之型態。以 Java 為例 : 
  1. int number = 10;  
  2. String id = "john";  
上例中,number 變數本身帶有 int 型態資訊,而 id 變數帶有 String 型態資訊,在指定時,變數型態資訊與值的型態資訊必須符合,否則會發生編譯失敗. 
JavaScript 則為動態語言,其變數本身使用者無需宣告型態,型態資訊僅在值或物件本身,變數只用來作為取得值或物件的參考。例如 : 
  1. var some = 10;  
  2. some = 'caterpillar';  
由於變數本身不帶型態資訊,同一個變數可以指定不同型態的值,實際操作時,是在執行時期才透過變數來參考至物件或值,才得知物件或值上有操作之方法. 靜態語言由於變數本身帶有型態資訊,好處就是編譯時期,可由編譯器確認變數與實際參考之值是否符合,可在編譯時期就檢查出許多型態指定不符的錯誤。相對地,動態語言就必須等到執行時期,才能發現所操作的對象並非預期型態之錯誤,這是靜態語言優點動態語言的地方. 
然而,靜態語言宣告變數時,必須同時宣告型態,因而容易造成語法上的冗長。例如在 Java 中,若要使用同一陣列儲存多種物件,則一個例子如下 : 
  1. Object[] objects = {"caterpillar"new Integer(100), new Date()};  
  2. String name = (String) objects[0];  
  3. Integer score = (Integer) objects[1];  
  4. Data time = (Date) objects[2];  
反觀 JavaScript 若要達到相同目的,所需的程式碼較為簡短。例如 : 
  1. var objects = ['caterpillar'100new Date()];  
  2. var name = objects[0];  
  3. var score = objects[1];  
  4. var time = objects[2];  
就程式撰寫速度上,動態語言著實有著比靜態語言快速的優點! 
再回頭看看 JavaScript 變數 宣告的討論。在 JavaScript 中要宣告變數,可以使用 var 來宣告。這是先前一直都有看到的,事實上,你也可以不用var宣告,直接指定某個名稱的值,該名稱會自動成為全域範圍,其實也就是在全域global物件上建立特性. 這很方便,也很危險,因為是在全域物件上建立特性。全域變數若在瀏覽器中,就是 window 物件,在 Rhino Shell 中,也可以在全域範圍中使用 this 來取得。例如 : 
> some = 10
10
> function test(some){ console.log('some=', some); console.log('this.some=',this.some);}
undefined
> test(20)
some= 20
this.some= 10
undefined


使用 var 所宣告的變數,作用範圍是在當時所在環境,不使用 var 直接指定值而建立的變數,則是全域物件上的一個特性,也就是俗稱的全域範圍。可以先以這樣的觀念理解,如果寫下 : 
some = 10;

執行時可先以直譯器會直接這麼作來理解 : 
this.some = 10;

如果你在全域使用 var 宣告變數,也相當於在全域物件上建立特性. 如果全域與區域中有同名的變數,則區域會暫時覆蓋全域. 你可以使用 delete 來刪除物件上的特性。由於未使用 var 宣告的變數,會是全域物件上的特性,就某些意義來說,對未使用 var 宣告的變數使用 delete,就相當於所謂刪除變數 : 
> a = 20
20
> if(delete a) console.log('Delete a success!')
Delete a success!

上例中, delete 會傳回 true 表示特性刪除成功,false 表示無法刪除。使用 var 宣告的變數就無法用 delete 刪除! 可觀察以下在函式中使用 var 與不使用 var 宣告的變數之差別: 
> function func() { var x = 10; y = 20; }
undefined
> func()
undefined
> x
ReferenceError: x is not defined
> y
20
> this.y
20

x 在函式中使用 var 宣告,所以在函式外不可見,但 y 並非使用 var 宣告,所以 y 是全域物件上的特性,在函式外依舊可見,俗稱全域範圍。 

如果你在全域使用 var 宣告變數,也相當於在全域物件上建立特性; 如果全域與區域中有同名的變數,則區域會暫時覆蓋全域. 例如: 
> var x = 10
undefined
> function func() { var x = 20; console.log(x); }
undefined
> func()
20 # 此時列印出來的是區域的 x
undefined
> console.log(x)
10


你可以重複使用 var 宣告變數,但不會覆蓋原有的指定值. 要注意的是,var宣告的變數是當時作用範圍中整個都是有作用的,並沒有所謂區塊範圍。例如 : 
> function func() { if(true) { var x = 10; } return x; }
undefined
> func()
10

var 宣告的變數是當時作用範圍中整個都是有作用的,這會產生令人驚奇的結果。例如下例不意外的,會產生直譯錯誤 
> function func() { print(m); }
undefined
> func()
ReferenceError: m is not defined

但下例中並不會直譯錯誤: 
> function func() { console.log(m); var m = 10; console.log(m); }
undefined
> func()
undefined
10
undefined

所 有 var 宣告的變數,在整個函式區塊中都是可見的,因而在上例中第一個 console.log(m) 時是可找到 m 特性,只不過 是 undefined 的值。 

如果你有興趣,範圍鏈(Scope chain) 會深入說明一件事,使用 var 所宣告的變數,會是當時執行環境(Execute context)中呼叫物件(call object)上的特性,也因此沒有所謂區塊範圍!

[ 文章收集 ] How To Install and Use PostgreSQL on CentOS 7

Source From Here 
Introduction 
Relational database management systems are a key component of many web sites and applications. They provide a structured way to store, organize, and access information. PostgreSQL, or Postgres, is a relational database management system that provides an implementation of the SQL querying language. It is a popular choice for many small and large projects and has the advantage of being standards-compliant and having many advanced features like reliable transactions and concurrency without read locks. 

In this guide, we will demonstrate how to install Postgres on CentOS 7 and go over some basic ways to use it. 

Installation 
CentOS's default repositories contain Postgres packages, so we can install them without a hassle using the yum package system. Below will install the postgresql-server package and the "contrib" package, that adds some additional utilities and functionality: 
# sudo yum install postgresql-server postgresql-contrib

Now that our software is installed, we have to perform a few steps before we can use it. First is to create a new PostgreSQL database cluster
# sudo postgresql-setup initdb

By default, PostgreSQL does not allow password authentication. We will change that by editing its host-based authentication (HBA) configuration. Open the HBA configuration with your favorite text editor. We will use vi
# sudo vi /var/lib/pgsql/data/pg_hba.conf

Find the lines that looks like this, near the bottom of the file: 
- pg_hba.conf excerpt (original) 
  1. ...  
  2. host    all             all             127.0.0.1/32            ident  
  3. host    all             all             ::1/128                 ident  
Then replace "ident" with "md5", so they look like this: 
- pg_hba.conf excerpt (updated) 
  1. ...  
  2. host    all             all             127.0.0.1/32            md5  
  3. host    all             all             ::1/128                 md5  
Save and exit. PostgreSQL is now configured to allow password authentication. Now start and enable PostgreSQL
# sudo systemctl start postgresql
# sudo systemctl enable postgresql

PostgreSQL is now ready to be used. We can go over how it works and how it may be different from similar database management systems you may have used. 

Using PostgreSQL Roles and Databases 
By default, Postgres uses a concept called "roles" to aid in authentication and authorization. These are, in some ways, similar to regular Unix-style accounts, but Postgres does not distinguish between users and groups and instead prefers the more flexible term "role". Upon installation Postgres is set up to use "ident" authentication, meaning that it associates Postgres roles with a matching Unix/Linux system account. If a Postgres role exists, it can be signed in by logging into the associated Linux system account. 

The installation procedure created a user account called postgres that is associated with the default Postgres role. In order to use Postgres, we'll need to log into that account. You can do that by typing: 
# sudo -i -u postgres

You will be asked for your normal user password and then will be given a shell prompt for the postgres user. You can get a Postgres prompt immediately by typing: 
# psql

You will be auto-logged in and will be able to interact with the database management system right away. However, we're going to explain a little bit about how to use other roles and databases so that you have some flexibility as to which user and database you wish to work with. Exit out of the PostgreSQL prompt by typing: 
postgres=# \q

You should now be back in the postgres user command prompt. 

Create a New Role 
From the postgres Linux account, you have the ability to log into the database system. However, we're also going to demonstrate how to create additional roles. The postgres Linux account, being associated with the Postgres administrative role, has access to some utilities to create users and databases. 

We can create a new role by typing
-bash-4.2$ createuser --interactive
Enter name of role to add: john
Shall the new role be a superuser? (y/n) y

This basically is an interactive shell script that calls the correct Postgres commands to create a user to your specifications. It will only ask you two questions: the name of the role and whether it should be a superuser. You can get more control by passing some additional flags. Check out the options by looking at the man page: 
-bash-4.2$ man createuser

Create a New Database 
The way that Postgres is set up by default (authenticating roles that are requested by matching system accounts) also comes with the assumption that a matching database will exist for the role to connect to. So if I have a user called test1, that role will attempt to connect to a database called test1 by default. 

You can create the appropriate database by simply calling this command as the postgres user: 
-bash-4.2$ createdb test1


Connect to Postgres with the New User 
Let's assume that you have a Linux system account called test1 (you can create one by typing: sudo adduser test1), and that you have created a Postgres role and database also called test1. You can change to the Linux system account by typing: 
# sudo -i -u test1

You can then connect to the test1 database as the test1 Postgres role by typing: 
# psql

This will log in automatically assuming that all of the components have been configured. 

If you want your user to connect to a different database, you can do so by specifying the database like this (make sure you use \q to be back to the command prompt): 
$ psql -d postgres
psql (9.2.23)
Type "help" for help.


postgres=#

You can get information about the Postgres user you're logged in as and the database you're currently connected to by typing: 
postgres=# \conninfo
You are connected to database "postgres" as user "test1" via socket in "/var/run/postgresql" at port "5432".

This can help remind you of your current settings if you are connecting to non-default databases or with non-default users. 

Create and Delete Tables 
Now that you know how to connect to the PostgreSQL database system, we will start to go over how to complete some basic tasks. First, let's create a table to store some data. Let's create a table that describes playground equipment. The basic syntax for this command is something like this: 
  1. CREATE TABLE table_name (  
  2.     column_name1 col_type (field_length) column_constraints,  
  3.     column_name2 col_type (field_length),  
  4.     column_name3 col_type (field_length)  
  5. );  
As you can see, we give the table a name, and then define the columns that we want, as well as the column type and the max length of the field data. We can also optionally add table constraints for each column. You can learn more about how to create and manage tables in Postgres here. 

For our purposes, we're going to create a simple table like this: 
postgres=# CREATE TABLE playground (
postgres(# equip_id serial PRIMARY KEY,
postgres(# type varchar (50) NOT NULL,
postgres(# color varchar (25) NOT NULL,
postgres(# location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
postgres(# install_date date
postgres(# );

We have made a playground table that inventories the equipment that we have. This starts with an equipment ID, which is of the serial type. This data type is an auto-incrementing integer. We have given this column the constraint of primary key which means that the values must be unique and not null; For two of our columns, we have not given a field length. This is because some column types don't require a set length because the length is implied by the type. 

We then give columns for the equipment type and color, each of which cannot be empty. We then create a location column and create a constraint that requires the value to be one of eight possible values. The last column is a date column that records the date that we installed the equipment. We can see our new table by typing this: 
postgres=# \d
  1.                   List of relations  
  2. Schema |          Name           |   Type   | Owner  
  3. --------+-------------------------+----------+-------  
  4. public | playground              | table    | john  
  5. public | playground_equip_id_seq | sequence | john  
  6. (2 rows)  

As you can see, we have our playground table, but we also have something called playground_equip_id_seq that is of the type sequence. This is a representation of the "serial" type we gave our equip_id column. This keeps track of the next number in the sequence. If you want to see just the table, you can type: 
postgres=# \dt

Add, Query, and Delete Data in a Table 
Now that we have a table created, we can insert some data into it. Let's add a slide and a swing. We do this by calling the table we're wanting to add to, naming the columns and then providing data for each column. Our slide and swing could be added like this: 
postgres=# INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2014-04-28');
INSERT 0 1
postgres=# INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2010-08-16');
INSERT 0 1

You should notice a few things. First, keep in mind that the column names should not be quoted, but the column values that you're entering do need quotes. Another thing to keep in mind is that we do not enter a value for the equip_idcolumn. This is because this is auto-generated whenever a new row in the table is created. 

We can then get back the information we've added by typing: 
# SELECT * FROM playground;
  1. equip_id | type  | color  | location  | install_date  
  2. ----------+-------+--------+-----------+--------------  
  3.         1 | slide | blue   | south     | 2014-04-28  
  4.         2 | swing | yellow | northwest | 2010-08-16  
  5. (2 rows)  

Here, you can see that our equip_id has been filled in successfully and that all of our other data has been organized correctly. If our slide breaks and we remove it from the playground, we can also remove the row from our table by typing: 
postgres=# DELETE FROM playground WHERE type = 'slide';
DELETE 1

If we query our table again, we will see our slide is no longer a part of the table: 
postgres=# SELECT * FROM playground;
  1. equip_id | type  | color  | location  | install_date  
  2. ---------+-------+--------+-----------+--------------  
  3.        2 | swing | yellow | northwest | 2010-08-16  
  4. 1 row)  

How To Add and Delete Columns from a Table 
If we want to modify a table after it has been created to add an additional column, we can do that easily. We can add a column to show the last maintenance visit for each piece of equipment by typing: 
postgres=# ALTER TABLE playground ADD last_maint date;
ALTER TABLE

If you view your table information again, you will see the new column has been added (but no data has been entered): 
postgres=# SELECT * FROM playground;
  1. equip_id | type  | color  | location  | install_date | last_maint  
  2. ---------+-------+--------+-----------+--------------+------------  
  3.        2 | swing | yellow | northwest | 2010-08-16   |  
  4. 1 row)  

We can delete a column just as easily. If we find that our work crew uses a separate tool to keep track of maintenance history, we can get rid of the column here by typing: 
postgres=# ALTER TABLE playground DROP last_maint;
ALTER TABLE

How To Update Data in a Table 
We know how to add records to a table and how to delete them, but we haven't covered how to modify existing entries yet. 

You can update the values of an existing entry by querying for the record you want and setting the column to the value you wish to use. We can query for the "swing" record (this will match every swing in our table) and change its color to "red". This could be useful if we gave it a paint job: 
postgres=# UPDATE playground SET color = 'red' WHERE type = 'swing';
UPDATE 1

We can verify that the operation was successful by querying our data again: 
postgres=# SELECT * FROM playground;
  1. equip_id | type  | color | location  | install_date  
  2. ---------+-------+-------+-----------+--------------  
  3.        2 | swing | red   | northwest | 2010-08-16  
  4. 1 row)  

As you can see, our swing is now registered as being red. 

Conclusion 
You are now set up with PostgreSQL on your CentOS 7 server. However, there is still much more to learn with Postgres. Although many of them were written with Ubuntu in mind, these tutorials should be helpful in learning more about PostgreSQL: 
* A comparison of relational database management systems 
* Learn how to create and manage tables with Postgres 
* Get better at managing roles and permissions 
* Craft queries with Postgres with Select 
* Install phpPgAdmin to administer databases from a web interface on Ubuntu 
* Learn how to secure PostgreSQL on Ubuntu 
* Set up master-slave replication with Postgres on Ubuntu 
* Learn how to backup a Postgres database on Ubuntu

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...