summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown2
-rw-r--r--c.html.markdown1
-rw-r--r--common-lisp.html.markdown31
-rw-r--r--de-de/bash-de.html.markdown16
-rw-r--r--de-de/git-de.html.markdown4
-rw-r--r--git.html.markdown3
-rw-r--r--haxe.html.markdown428
-rw-r--r--hu-hu/go.html.markdown2
-rw-r--r--julia.html.markdown2
-rw-r--r--ko-kr/coffeescript-kr.html.markdown58
-rw-r--r--ko-kr/java-kr.html.markdown9
-rw-r--r--ko-kr/lua-kr.html.markdown2
-rw-r--r--ko-kr/php-kr.html.markdown662
-rw-r--r--matlab.html.markdown260
-rw-r--r--perl.html.markdown35
-rw-r--r--python.html.markdown34
-rw-r--r--ru-ru/erlang-ru.html.markdown255
-rw-r--r--ru-ru/python-ru.html.markdown105
-rw-r--r--tr-tr/python-tr.html.markdown502
-rw-r--r--zh-cn/go-zh.html.markdown8
20 files changed, 2260 insertions, 159 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index 7421f880..a0c43c12 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -1,12 +1,10 @@
---
-
category: tool
tool: bash
contributors:
- ["Max Yankov", "https://github.com/golergka"]
- ["Darren Lin", "https://github.com/CogBear"]
filename: LearnBash.sh
-
---
Bash is a name of the unix shell, which was also distributed as the shell for the GNU operating system and as default shell on Linux and Mac OS X.
diff --git a/c.html.markdown b/c.html.markdown
index 24a96463..3acf1a4d 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -81,6 +81,7 @@ int main() {
// is not evaluated (except VLAs (see below)).
// The value it yields in this case is a compile-time constant.
int a = 1;
+ // size_t is an unsiged integer type of at least 2 bytes used to represent the size of an object.
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
// prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index a917304c..bf4844f3 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -205,7 +205,7 @@ nil ; for false - and the empty list
;; Or use concatenate -
-(concatenate
+(concatenate 'list '(1 2) '(3 4))
;; Lists are a very central type, so there is a wide variety of functionality for
;; them, a few examples:
@@ -219,7 +219,7 @@ nil ; for false - and the empty list
;;; Vectors
-;; Vectors are fixed-length arrays
+;; Vector's literals are fixed-length arrays
#(1 2 3) ; => #(1 2 3)
;; Use concatenate to add vectors together
@@ -253,6 +253,23 @@ nil ; for false - and the empty list
; => 0
+;;; Adjustable vectors
+
+;; Adjustable vectors have the same printed representation
+;; as fixed-length vector's literals.
+
+(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
+ :adjustable t :fill-pointer t))
+
+*adjvec* ; => #(1 2 3)
+
+;; Adding new element:
+(vector-push-extend 4 *adjvec*) ; => 3
+
+*adjvec* ; => #(1 2 3 4)
+
+
+
;;; Naively, sets are just lists:
(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1)
@@ -279,10 +296,10 @@ nil ; for false - and the empty list
;; not.
;; Retrieving a non-present value returns nil
- (gethash *m* 'd) ;=> nil, nil
+ (gethash 'd *m*) ;=> nil, nil
;; You can provide a default value for missing keys
-(gethash *m* 'd :not-found) ; => :NOT-FOUND
+(gethash 'd *m* :not-found) ; => :NOT-FOUND
;; Let's handle the multiple return values here in code.
@@ -457,8 +474,8 @@ nil ; for false - and the empty list
:accessor velocity
:initarg :velocity)
(average-efficiency
- :accessor average-efficiency)
- :initarg :average-efficiency)
+ :accessor average-efficiency
+ :initarg :average-efficiency))
(:documentation "A human powered conveyance"))
;; defclass, followed by name, followed by the superclass list,
@@ -506,7 +523,7 @@ nil ; for false - and the empty list
; Direct superclasses: STANDARD-OBJECT
; Direct subclasses: UNICYCLE, BICYCLE, CANOE
; Not yet finalized.
-(defparameter *foo#\u03BBooo* nil) ; Direct slots:
+; Direct slots:
; VELOCITY
; Readers: VELOCITY
; Writers: (SETF VELOCITY)
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index f2a57511..9e3d7bc8 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -1,12 +1,20 @@
---
-language: bash
+category: tool
+tool: bash
+lang: de-de
contributors:
- - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+translators:
- ["kultprok", "http://www.kulturproktologie.de"]
-filename: LearnBash-de.bash
-lang: de-de
+filename: LearnBash-de.sh
---
+Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde.
+Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden.
+
+[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html)
+
```bash
#!/bin/sh
# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 88f4a643..10deefd5 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -2,9 +2,9 @@
category: tool
tool: git
contributors:
- - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"]
+translators:
- ["kultprok", "http://www.kulturproktologie.de"]
-filename: LearnGit-de.txt
lang: de-de
---
diff --git a/git.html.markdown b/git.html.markdown
index d8537300..abe8e3a7 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -2,9 +2,8 @@
category: tool
tool: git
contributors:
- - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"]
filename: LearnGit.txt
-
---
Git is a distributed version control and source code management system.
diff --git a/haxe.html.markdown b/haxe.html.markdown
index 90b2e250..eb39834e 100644
--- a/haxe.html.markdown
+++ b/haxe.html.markdown
@@ -11,45 +11,67 @@ Haxe author). Note that this guide is for Haxe version 3. Some of the guide
may be applicable to older versions, but it is recommended to use other
references.
-```haxe
+```csharp
/*
Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org
This is an executable tutorial. You can compile and run it using the haxe
compiler, while in the same directory as LearnHaxe.hx:
- haxe -main LearnHaxe3 -x out
- */
+ $> haxe -main LearnHaxe3 -x out
-// Let's start with comments... this is a single line comment
+ Look for the slash-star marks surrounding these paragraphs. We are inside
+ a "Multiline comment". We can leave some notes here that will get ignored
+ by the compiler.
+
+ Multiline comments are also used to generate javadoc-style documentation for
+ haxedoc. They will be used for haxedoc if they immediately precede a class,
+ class function, or class variable.
-/*
- And this is multiline. Multiline comments are also used to generate
- javadoc-style documentation for haxedoc. They will be used if they precede
- a class, class function, or class variable.
*/
+// Double slashes like this will give a single-line comment
+
+
/*
- A package declaration isn't necessary, but it's useful if you want to
- organize your code into modules later on. Also worth mentioning, all
- expressions in Haxe must end in a semicolon:
+ This is your first actual haxe code coming up, it's declaring an empty
+ package. A package isn't necessary, but it's useful if you want to create a
+ namespace for your code (e.g. org.module.ClassName).
*/
package; // empty package, no namespace.
-
-// if you import code from other files, it must be declared before the rest of
-// the code.
+/*
+ Packages define modules for your code. Each module (e.g. org.module) must
+ be lower case, and should exist as a folder structure containing the class.
+ Class (and type) names must be capitalized. E.g, the class "org.module.Foo"
+ should have the folder structure org/module/Foo.hx, as accessible from the
+ compiler's working directory or class path.
+
+ If you import code from other files, it must be declared before the rest of
+ the code. Haxe provides a lot of common default classes to get you started:
+ */
import haxe.ds.ArraySort;
// you can import many classes/modules at once with "*"
import haxe.ds.*;
-// you can also import classes in a special way, enabling them to extend the
-// functionality of other classes. More on this later.
+/*
+ You can also import classes in a special way, enabling them to extend the
+ functionality of other classes like a "mixin". More on 'using' later.
+ */
using StringTools;
-// Haxe files typically define classes, although they can also define other
-// types of code... more on that later.
+/*
+ Typedefs are like variables... for types. They must be declared before any
+ code. More on this later.
+ */
+typedef FooString = String;
+// Typedefs can also reference "structural" types, more on that later as well.
+typedef FooObject = { foo: String };
+/*
+ Here's the class definition. It's the main class for the file, since it has
+ the same name (LearnHaxe3).
+ */
class LearnHaxe3{
/*
If you want certain code to run automatically, you need to put it in
@@ -58,6 +80,7 @@ class LearnHaxe3{
arguments above.
*/
static function main(){
+
/*
Trace is the default method of printing haxe expressions to the
screen. Different targets will have different methods of
@@ -67,8 +90,6 @@ class LearnHaxe3{
Finally, It's possible to prevent traces from showing by using the
"--no-traces" argument on the compiler.
*/
-
-
trace("Hello World, with trace()!");
/*
@@ -76,16 +97,11 @@ class LearnHaxe3{
a representation of the expression as best it can. You can also
concatenate strings with the "+" operator:
*/
- trace(
- " Integer: " + 10 +
- " Float: " + 3.14 +
- " Boolean: " + true
- );
-
+ trace( " Integer: " + 10 + " Float: " + 3.14 + " Boolean: " + true);
/*
- Remember what I said about expressions needing semicolons? You
- can put more than one expression on a line if you want.
+ In Haxe, it's required to separate expressions in the same block with
+ semicolons. But, you can put two expressions on one line:
*/
trace('two expressions..'); trace('one line');
@@ -99,7 +115,6 @@ class LearnHaxe3{
You can save values and references to data structures using the
"var" keyword:
*/
-
var an_integer:Int = 1;
trace(an_integer + " is the value for an_integer");
@@ -111,7 +126,6 @@ class LearnHaxe3{
the haxe compiler is inferring that the type of another_integer
should be "Int".
*/
-
var another_integer = 2;
trace(another_integer + " is the value for another_integer");
@@ -137,8 +151,14 @@ class LearnHaxe3{
var a_string = "some" + 'string'; // strings can have double or single quotes
trace(a_string + " is the value for a_string");
+ /*
+ Strings can be "interpolated" by inserting variables into specific
+ positions. The string must be single quoted, and the variable must
+ be preceded with "$". Expressions can be enclosed in ${...}.
+ */
var x = 1;
var an_interpolated_string = 'the value of x is $x';
+ var another_interpolated_string = 'the value of x + 1 is ${x + 1}';
/*
Strings are immutable, instance methods will return a copy of
@@ -149,6 +169,12 @@ class LearnHaxe3{
trace(a_sub_string + " is the value for a_sub_string");
/*
+ Regexes are also supported, but there's not enough space to go into
+ much detail.
+ */
+ trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))");
+
+ /*
Arrays are zero-indexed, dynamic, and mutable. Missing values are
defined as null.
*/
@@ -191,7 +217,7 @@ class LearnHaxe3{
trace(m3 + " is the value for m3");
/*
- Haxe has many more common datastructures in the haxe.ds module, such as
+ Haxe has some more common datastructures in the haxe.ds module, such as
List, Stack, and BalancedTree
*/
@@ -199,7 +225,6 @@ class LearnHaxe3{
//////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////
-
trace("***OPERATORS***");
// basic arithmetic
@@ -218,7 +243,7 @@ class LearnHaxe3{
trace((3 >= 2) + " is the value for 3 >= 2");
trace((3 <= 2) + " is the value for 3 <= 2");
- //bitwise operators
+ // standard bitwise operators
/*
~ Unary bitwise complement
<< Signed left shift
@@ -252,6 +277,27 @@ class LearnHaxe3{
trace("also not printed.");
}
+ // there is also a "ternary" if:
+ (j == 10) ? trace("equals 10") : trace("not equals 10");
+
+ /*
+ Finally, there is another form of control structures that operates
+ at compile time: conditional compilation.
+ */
+#if neko
+ trace('hello from neko');
+#elseif js
+ trace('hello from js');
+#else
+ trace('hello from another platform!');
+#end
+ /*
+ The compiled code will change depending on the platform target.
+ Since we're compiling for neko (-x or -neko), we only get the neko
+ greeting.
+ */
+
+
trace("Looping and Iteration");
// while loop
@@ -310,13 +356,14 @@ class LearnHaxe3{
generalized algebraic data types in enums (more on enums later).
Here's some basic value examples for now:
*/
- var my_dog_name = 'fido';
- var favorite_thing = '';
+ var my_dog_name = "fido";
+ var favorite_thing = "";
switch(my_dog_name){
- case "fido" : favorite_thing = 'bone';
- case "rex" : favorite_thing = 'shoe';
- case "spot" : favorite_thing = 'tennis ball';
- case _ : favorite_thing = 'some unknown treat';
+ case "fido" : favorite_thing = "bone";
+ case "rex" : favorite_thing = "shoe";
+ case "spot" : favorite_thing = "tennis ball";
+ default : favorite_thing = "some unknown treat";
+ // case _ : "some unknown treat"; // same as default
}
// The "_" case above is a "wildcard" value
// that will match anything.
@@ -345,10 +392,10 @@ class LearnHaxe3{
trace("K equals ", k); // outputs 10
var other_favorite_thing = switch(my_dog_name) {
- case "fido" : 'teddy';
- case "rex" : 'stick';
- case "spot" : 'football';
- case _ : 'some unknown treat';
+ case "fido" : "teddy";
+ case "rex" : "stick";
+ case "spot" : "football";
+ default : "some unknown treat";
}
trace("My dog's name is" + my_dog_name
@@ -358,6 +405,7 @@ class LearnHaxe3{
//////////////////////////////////////////////////////////////////
// Converting Value Types
//////////////////////////////////////////////////////////////////
+ trace("***CONVERTING VALUE TYPES***");
// You can convert strings to ints fairly easily.
@@ -372,33 +420,93 @@ class LearnHaxe3{
true + ""; // returns "true";
// See documentation for parsing in Std for more details.
+
+ //////////////////////////////////////////////////////////////////
+ // Dealing with Types
+ //////////////////////////////////////////////////////////////////
+
+ /*
+
+ As mentioned before, Haxe is a statically typed language. All in
+ all, static typing is a wonderful thing. It enables
+ precise autocompletions, and can be used to thoroughly check the
+ correctness of a program. Plus, the Haxe compiler is super fast.
+
+ *HOWEVER*, there are times when you just wish the compiler would let
+ something slide, and not throw a type error in a given case.
+
+ To do this, Haxe has two separate keywords. The first is the
+ "Dynamic" type:
+ */
+ var dyn: Dynamic = "any type of variable, such as this string";
+
+ /*
+ All that you know for certain with a Dynamic variable is that the
+ compiler will no longer worry about what type it is. It is like a
+ wildcard variable: You can pass it instead of any variable type,
+ and you can assign any variable type you want.
+
+ The other more extreme option is the "untyped" keyword:
+ */
+
+ untyped {
+ var x:Int = 'foo'; // this can't be right!
+ var y:String = 4; // madness!
+ }
+
+ /*
+ The untyped keyword operates on entire *blocks* of code, skipping
+ any type checks that might be otherwise required. This keyword should
+ be used very sparingly, such as in limited conditionally-compiled
+ situations where type checking is a hinderance.
+
+ In general, skipping type checks is *not* recommended. Use the
+ enum, inheritance, or structural type models in order to help ensure
+ the correctness of your program. Only when you're certain that none
+ of the type models work should you resort to "Dynamic" or "untyped".
+ */
+
//////////////////////////////////////////////////////////////////
// Basic Object Oriented Programming
//////////////////////////////////////////////////////////////////
trace("***BASIC OBJECT ORIENTED PROGRAMMING***");
- // create an instance of FooClass. The classes for this are at the
- // end of the file.
- var instance = new FooClass(3);
+ /*
+ Create an instance of FooClass. The classes for this are at the
+ end of the file.
+ */
+ var foo_instance = new FooClass(3);
// read the public variable normally
- trace(instance.public_any + " is the value for instance.public_any");
+ trace(foo_instance.public_any + " is the value for foo_instance.public_any");
// we can read this variable
- trace(instance.public_read + " is the value for instance.public_read");
+ trace(foo_instance.public_read + " is the value for foo_instance.public_read");
// but not write it
- // instance.public_write = 4; // this will throw an error if uncommented:
- // trace(instance.public_write); // as will this.
+ // foo_instance.public_write = 4; // this will throw an error if uncommented:
+ // trace(foo_instance.public_write); // as will this.
+
+ trace(foo_instance + " is the value for foo_instance"); // calls the toString method
+ trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing
- trace(instance + " is the value for instance"); // calls the toString method
- trace(instance.toString() + " is the value for instance.toString()"); // same thing
+ /*
+ The foo_instance has the "FooClass" type, while acceptBarInstance
+ has the BarClass type. However, since FooClass extends BarClass, it
+ is accepted.
+ */
+ BarClass.acceptBarInstance(foo_instance);
+
+ /*
+ The classes below have some more advanced examples, the "example()"
+ method will just run them here.
+ */
+ SimpleEnumTest.example();
+ ComplexEnumTest.example();
+ TypedefsAndStructuralTypes.example();
+ UsingExample.example();
- // instance has the "FooClass" type, while acceptBaseFoo has the
- // BaseFooClass type. However, since FooClass extends BaseFooClass,
- // it is accepted.
- BaseFooClass.acceptBaseFoo(instance);
}
}
@@ -406,7 +514,7 @@ class LearnHaxe3{
/*
This is the "child class" of the main LearnHaxe3 Class
*/
-class FooClass extends BaseFooClass implements BaseFooInterface{
+class FooClass extends BarClass implements BarInterface{
public var public_any:Int; // public variables are accessible anywhere
public var public_read (default,null): Int; // use this style to only enable public read
public var public_write (null, default): Int; // or public write
@@ -418,7 +526,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{
// a public constructor
public function new(arg:Int){
- super(); // call the constructor of the parent object, since we extended BaseFooClass
+ super(); // call the constructor of the parent object, since we extended BarClass
this.public_any= 0;
this._private = arg;
@@ -442,7 +550,7 @@ class FooClass extends BaseFooClass implements BaseFooInterface{
}
// this class needs to have this function defined, since it implements
- // the BaseFooInterface interface.
+ // the BarInterface interface.
public function baseFunction(x: Int) : String{
// convert the int to string automatically
return x + " was passed into baseFunction!";
@@ -452,21 +560,217 @@ class FooClass extends BaseFooClass implements BaseFooInterface{
/*
A simple class to extend
*/
-class BaseFooClass {
+class BarClass {
var base_variable:Int;
public function new(){
base_variable = 4;
}
- public static function acceptBaseFoo(b:BaseFooClass){
+ public static function acceptBarInstance(b:BarClass){
}
}
/*
A simple interface to implement
*/
-interface BaseFooInterface{
+interface BarInterface{
public function baseFunction(x:Int):String;
}
+//////////////////////////////////////////////////////////////////
+// Enums and Switch Statements
+//////////////////////////////////////////////////////////////////
+
+/*
+ Enums in Haxe are very powerful. In their simplest form, enums
+ are a type with a limited number of states:
+ */
+
+enum SimpleEnum {
+ Foo;
+ Bar;
+ Baz;
+}
+
+// Here's a class that uses it:
+
+class SimpleEnumTest{
+ public static function example(){
+ var e_explicit:SimpleEnum = SimpleEnum.Foo; // you can specify the "full" name
+ var e = Foo; // but inference will work as well.
+ switch(e){
+ case Foo: trace("e was Foo");
+ case Bar: trace("e was Bar");
+ case Baz: trace("e was Baz"); // comment this line to throw an error.
+ }
+
+ /*
+ This doesn't seem so different from simple value switches on strings.
+ However, if we don't include *all* of the states, the compiler will
+ complain. You can try it by commenting out a line above.
+
+ You can also specify a default for enum switches as well:
+ */
+ switch(e){
+ case Foo: trace("e was Foo again");
+ default : trace("default works here too");
+ }
+ }
+}
+
+/*
+ Enums go much further than simple states, we can also enumerate
+ *constructors*, but we'll need a more complex enum example
+ */
+enum ComplexEnum{
+ IntEnum(i:Int);
+ MultiEnum(i:Int, j:String, k:Float);
+ SimpleEnumEnum(s:SimpleEnum);
+ ComplexEnumEnum(c:ComplexEnum);
+}
+// Note: The enum above can include *other* enums as well, including itself!
+
+class ComplexEnumTest{
+ public static function example(){
+ var e1:ComplexEnum = IntEnum(4); // specifying the enum parameter
+ /*
+ Now we can switch on the enum, as well as extract any parameters
+ it might of had.
+ */
+ switch(e1){
+ case IntEnum(x) : trace('$x was the parameter passed to e1');
+ default: trace("Shouldn't be printed");
+ }
+
+ // another parameter here that is itself an enum... an enum enum?
+ var e2 = SimpleEnumEnum(Foo);
+ switch(e2){
+ case SimpleEnumEnum(s): trace('$s was the parameter passed to e2');
+ default: trace("Shouldn't be printed");
+ }
+
+ // enums all the way down
+ var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3)));
+ switch(e3){
+ // You can look for certain nested enums by specifying them explicitly:
+ case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : {
+ trace('$i, $j, and $k were passed into this nested monster');
+ }
+ default: trace("Shouldn't be printed");
+ }
+ /*
+ Check out "generalized algebraic data types" (GADT) for more details
+ on why these are so great.
+ */
+ }
+}
+
+class TypedefsAndStructuralTypes {
+ public static function example(){
+ /*
+ Here we're going to use typedef types, instead of base types.
+ At the top we've declared the type "FooString" to mean a "String" type.
+ */
+ var t1:FooString = "some string";
+
+ /*
+ We can use typedefs for "structural types" as well. These types are
+ defined by their field structure, not by class inheritance. Here's
+ an anonymous object with a String field named "foo":
+ */
+
+ var anon_obj = { foo: 'hi' };
+
+ /*
+ The anon_obj variable doesn't have a type declared, and is an
+ anonymous object according to the compiler. However, remember back at
+ the top where we declared the FooObj typedef? Since anon_obj matches
+ that structure, we can use it anywhere that a "FooObject" type is
+ expected.
+ */
+
+ var f = function(fo:FooObject){
+ trace('$fo was passed in to this function');
+ }
+ f(anon_obj); // call the FooObject signature function with anon_obj.
+
+ /*
+ Note that typedefs can have optional fields as well, marked with "?"
+
+ typedef OptionalFooObj = {
+ ?optionalString: String,
+ requiredInt: Int
+ }
+ */
+
+ /*
+ Typedefs work well with conditional compilation. For instance,
+ we could have included this at the top of the file:
+
+#if( js )
+ typedef Surface = js.html.CanvasRenderingContext2D;
+#elseif( nme )
+ typedef Surface = nme.display.Graphics;
+#elseif( !flash9 )
+ typedef Surface = flash8.MovieClip;
+#elseif( java )
+ typedef Surface = java.awt.geom.GeneralPath;
+#end
+
+ That would give us a single "Surface" type to work with across
+ all of those platforms.
+ */
+ }
+}
+
+class UsingExample {
+ public static function example() {
+
+ /*
+ The "using" import keyword is a special type of class import that
+ alters the behavior of any static methods in the class.
+
+ In this file, we've applied "using" to "StringTools", which contains
+ a number of static methods for dealing with String types.
+ */
+ trace(StringTools.endsWith("foobar", "bar") + " should be true!");
+
+ /*
+ With a "using" import, the first argument type is extended with the
+ method. What does that mean? Well, since "endsWith" has a first
+ argument type of "String", that means all String types now have the
+ "endsWith" method:
+ */
+ trace("foobar".endsWith("bar") + " should be true!");
+
+ /*
+ This technique enables a good deal of expression for certain types,
+ while limiting the scope of modifications to a single file.
+
+ Note that the String instance is *not* modified in the run time.
+ The newly attached method is not really part of the attached
+ instance, and the compiler still generates code equivalent to a
+ static method.
+ */
+ }
+
+}
+
```
+We're still only scratching the surface here of what Haxe can do. For a formal
+overiew of all Haxe features, checkout the [online
+manual](http://haxe.org/manual), the [online api](http://api.haxe.org/), and
+"haxelib", the [haxe library repo] (http://lib.haxe.org/).
+
+For more advanced topics, consider checking out:
+
+* [Abstract types](http://haxe.org/manual/abstracts)
+* [Macros](http://haxe.org/manual/macros), and [Compiler Macros](http://haxe.org/manual/macros_compiler)
+* [Tips and Tricks](http://haxe.org/manual/tips_and_tricks)
+
+
+Finally, please join us on [the mailing list](https://groups.google.com/forum/#!forum/haxelang), on IRC [#haxe on
+freenode](http://webchat.freenode.net/), or on
+[Google+](https://plus.google.com/communities/103302587329918132234).
+
+
diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown
index 69849858..621ebdbf 100644
--- a/hu-hu/go.html.markdown
+++ b/hu-hu/go.html.markdown
@@ -38,7 +38,7 @@ import (
"strconv" // Stringek átalakítására szolgáló csomag
)
-// Funkció deklarás, a main nevű funkció a program kezdőpontja.
+// Funkció deklarálás, a main nevű funkció a program kezdőpontja.
func main() {
// Println kiírja a beadott paramétereket a standard kimenetre.
// Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a
diff --git a/julia.html.markdown b/julia.html.markdown
index 1023e303..cf3a464b 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -147,7 +147,7 @@ push!(a,3) #=> [1,2,4,3]
append!(a,b) #=> [1,2,4,3,4,5,6]
# Remove from the end with pop
-pop!(a) #=> 6 and b is now [4,5]
+pop!(b) #=> 6 and b is now [4,5]
# Let's put it back
push!(b,6) # b is now [4,5,6] again.
diff --git a/ko-kr/coffeescript-kr.html.markdown b/ko-kr/coffeescript-kr.html.markdown
new file mode 100644
index 00000000..7d00a0fe
--- /dev/null
+++ b/ko-kr/coffeescript-kr.html.markdown
@@ -0,0 +1,58 @@
+---
+language: coffeescript
+category: language
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+filename: coffeescript.coffee
+translators:
+ - ["wikibook", "http://wikibook.co.kr"]
+lang: ko-kr
+---
+
+``` coffeescript
+# 커피스크립트(CoffeeScript)는 최신 유행을 따르는 언어입니다.
+# 커피스크립트는 여러 현대 언어의 트렌드를 따르는데,
+# 그래서 주석을 작성할 때는 루비나 파이썬과 같이 해시를 씁니다.
+
+###
+블록 주석은 이처럼 작성하며, 자바스크립트 코드로 만들어지도록
+'/ *'와 '* /'로 직접적으로 변환됩니다.
+
+계속하기에 앞서 자바스크립트 시맨틱을 대부분 이해하고 있어야 합니다.
+###
+
+# 할당:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# 조건문:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# 함수:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+# 범위:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# 객체:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+#}
+
+# 가변 인자(splat):
+race = (winner, runners...) ->
+ print winner, runners
+
+# 존재 여부 확인:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# 배열 조건 제시법(comprehensions):
+cubes = (math.cube num for num in list) #=> ...
+```
diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown
index 371b4665..5dd5769a 100644
--- a/ko-kr/java-kr.html.markdown
+++ b/ko-kr/java-kr.html.markdown
@@ -169,7 +169,7 @@ public class LearnJava {
System.out.println(--i); //i = 0. 전치 감소 연산
///////////////////////////////////////
- // 에저 구조
+ // 제어 구조
///////////////////////////////////////
System.out.println("\n->Control Structures");
@@ -255,8 +255,13 @@ public class LearnJava {
// String
// 형변환
- // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이
+<<<<<<< HEAD
+ // 자바 객체 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러
+ // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다.
+=======
+ // 자바 객체 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이
// 많을뿐더러 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다.
+>>>>>>> f33dea8b83bf64ecde36337a5e02cae77f5210de
// 이와 관련된 사항은 아래 링크를 참고하세요.
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown
index 04d119c4..c40d9ab0 100644
--- a/ko-kr/lua-kr.html.markdown
+++ b/ko-kr/lua-kr.html.markdown
@@ -1,4 +1,4 @@
----
+---
language: lua
category: language
contributors:
diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown
new file mode 100644
index 00000000..2382a8fb
--- /dev/null
+++ b/ko-kr/php-kr.html.markdown
@@ -0,0 +1,662 @@
+---
+language: php
+category: language
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+filename: learnphp.php
+translators:
+ - ["wikibook", "http://wikibook.co.kr"]
+lang: ko-kr
+---
+
+이 문서에서는 PHP 5+를 설명합니다.
+
+
+```php
+<?php // PHP 코드는 반드시 <?php 태그로 감싸야 합니다.
+
+// php 파일에 PHP 코드만 들어 있다면 닫는 태그를 생략하는 것이 관례입니다.
+
+// 슬래시 두 개는 한 줄 주석을 의미합니다.
+
+# 해시(파운드 기호로도 알려진)도 같은 역할을 하지만 //이 더 일반적으로 쓰입니다.
+
+/*
+ 텍스트를 슬래시-별표와 별표-슬래시로 감싸면
+ 여러 줄 주석이 만들어집니다.
+*/
+
+// 출력결과를 표시하려면 "echo"나 "print"를 사용합니다.
+print('Hello '); // 줄바꿈 없이 "Hello "를 출력합니다.
+
+// ()는 print와 echo를 사용할 때 선택적으로 사용할 수 있습니다.
+echo "World\n"; // "World"를 출력한 후 줄바꿈합니다.
+// (모든 구문은 반드시 세미콜론으로 끝나야 합니다.)
+
+// <?php 태그 밖의 내용은 모두 자동으로 출력됩니다.
+?>
+Hello World Again!
+<?php
+
+
+/************************************
+ * 타입과 변수
+ */
+
+// 변수명은 $ 기호로 시작합니다.
+// 유효한 변수명은 문자나 밑줄(_)로 시작하고,
+// 이어서 임의 개수의 숫자나 문자, 밑줄이 옵니다.
+
+// 불린값은 대소문자를 구분합니다.
+$boolean = true; // 또는 TRUE나 True
+$boolean = false; // 또는 FALSE나 False
+
+// Integer
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (a leading 0 denotes an octal number)
+$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal)
+
+// Float (doubles로도 알려짐)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// 산술 연산
+$sum = 1 + 1; // 2
+$difference = 2 - 1; // 1
+$product = 2 * 2; // 4
+$quotient = 2 / 1; // 2
+
+// 축약형 산술 연산
+$number = 0;
+$number += 1; // $number를 1만큼 증가
+echo $number++; // 1을 출력(평가 후 증가)
+echo ++$number; // 3 (평가 전 증가)
+$number /= $float; // 나눗셈 후 몫을 $number에 할당
+
+// 문자열은 작은따옴표로 감싸야 합니다.
+$sgl_quotes = '$String'; // => '$String'
+
+// 다른 변수를 포함할 때를 제외하면 큰따옴표 사용을 자제합니다.
+$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+
+// 특수 문자는 큰따옴표에서만 이스케이프됩니다.
+$escaped = "This contains a \t tab character.";
+$unescaped = 'This just contains a slash and a t: \t';
+
+// 필요할 경우 변수를 중괄호로 감쌉니다.
+$money = "I have $${number} in the bank.";
+
+// PHP 5.3부터는 여러 줄 문자열을 생성하는 데 나우닥(nowdoc)을 사용할 수 있습니다.
+$nowdoc = <<<'END'
+Multi line
+string
+END;
+
+// 히어닥(heredoc)에서는 문자열 치환을 지원합니다.
+$heredoc = <<<END
+Multi line
+$sgl_quotes
+END;
+
+// 문자열을 연결할 때는 .을 이용합니다.
+echo 'This string ' . 'is concatenated';
+
+
+/********************************
+ * 상수
+ */
+
+// 상수는 define()을 이용해 정의되며,
+// 런타임 동안 절대 변경될 수 없습니다!
+
+// 유효한 상수명은 문자나 밑줄로 시작하고,
+// 이어서 임의 개수의 숫자나 문자, 밑줄이 옵니다.
+define("FOO", "something");
+
+// 상수명을 이용해 직접 상수에 접근할 수 있습니다.
+echo 'This outputs '.FOO;
+
+
+/********************************
+ * 배열
+ */
+
+// PHP의 모든 배열은 연관 배열(associative array, 해시맵)입니다.
+
+// 일부 언어에서 해시맵으로도 알려진 연관 배열은
+
+// 모든 PHP 버전에서 동작합니다.
+$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
+
+// PHP 5.4에서는 새로운 문법이 도입됐습니다.
+$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
+
+echo $associative['One']; // 1을 출력
+
+// 리스트 리터럴은 암시적으로 정수형 키를 할당합니다.
+$array = ['One', 'Two', 'Three'];
+echo $array[0]; // => "One"
+
+
+/********************************
+ * 출력
+ */
+
+echo('Hello World!');
+// 표준출력(stdout)에 Hello World!를 출력합니다.
+// 브라우저에서 실행할 경우 표준출력은 웹 페이지입니다.
+
+print('Hello World!'); // echo과 동일
+
+// echo는 실제로 언어 구성물에 해당하므로, 괄호를 생략할 수 있습니다.
+echo 'Hello World!';
+print 'Hello World!'; // 똑같이 출력됩니다.
+
+$paragraph = 'paragraph';
+
+echo 100; // 스칼라 변수는 곧바로 출력합니다.
+echo $paragraph; // 또는 변수의 값을 출력합니다.
+
+// 축약형 여는 태그를 설정하거나 PHP 버전이 5.4.0 이상이면
+// 축약된 echo 문법을 사용할 수 있습니다.
+?>
+<p><?= $paragraph ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // 이제 $x의 값은 $y의 값과 같습니다.
+$z = &$y;
+// $z는 이제 $y에 대한 참조를 담고 있습니다. $z의 값을 변경하면
+// $y의 값도 함께 변경되며, 그 반대도 마찬가지입니다.
+// $x는 $y의 원래 값을 그대로 유지합니다.
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+
+/********************************
+ * 로직
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// assert는 인자가 참이 아닌 경우 경고를 출력합니다.
+
+// 다음과 같은 비교는 항상 참이며, 타입이 같지 않더라도 마찬가지입니다.
+assert($a == $b); // 동일성 검사
+assert($c != $a); // 불일치성 검사
+assert($c <> $a); // 또 다른 불일치성 검사
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// 다음과 같은 코드는 값과 타입이 모두 일치하는 경우에만 참입니다.
+assert($c === $d);
+assert($a !== $d);
+assert(1 == '1');
+assert(1 !== '1');
+
+// 변수는 어떻게 사용하느냐 따라 다른 타입으로 변환될 수 있습니다.
+
+$integer = 1;
+echo $integer + $integer; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (문자열이 강제로 정수로 변환됩니다)
+
+$string = 'one';
+echo $string + $string; // => 0
+// + 연산자는 'one'이라는 문자열을 숫자로 형변환할 수 없기 때문에 0이 출력됩니다.
+
+// 한 변수를 다른 타입으로 처리하는 데 형변환을 사용할 수 있습니다.
+
+$boolean = (boolean) 1; // => true
+
+$zero = 0;
+$boolean = (boolean) $zero; // => false
+
+// 대다수의 타입을 형변환하는 데 사용하는 전용 함수도 있습니다.
+$integer = 5;
+$string = strval($integer);
+
+$var = null; // 널 타입
+
+
+/********************************
+ * 제어 구조
+ */
+
+if (true) {
+ print 'I get printed';
+}
+
+if (false) {
+ print 'I don\'t';
+} else {
+ print 'I get printed';
+}
+
+if (false) {
+ print 'Does not get printed';
+} elseif(true) {
+ print 'Does';
+}
+
+// 사항 연산자
+print (false ? 'Does not get printed' : 'Does');
+
+$x = 0;
+if ($x === '0') {
+ print 'Does not print';
+} elseif($x == '1') {
+ print 'Does not print';
+} else {
+ print 'Does print';
+}
+
+
+
+// 다음과 같은 문법은 템플릿에 유용합니다.
+?>
+
+<?php if ($x): ?>
+This is displayed if the test is truthy.
+<?php else: ?>
+This is displayed otherwise.
+<?php endif; ?>
+
+<?php
+
+// 특정 로직을 표현할 때는 switch를 사용합니다.
+switch ($x) {
+ case '0':
+ print 'Switch does type coercion';
+ break; // break을 반드시 포함해야 하며, break를 생략하면
+ // 'two'와 'three' 케이스로 넘어갑니다.
+ case 'two':
+ case 'three':
+ // 변수가 'two'나 'three'인 경우에 실행될 코드를 작성합니다.
+ break;
+ default:
+ // 기본값으로 실행될 코드를 작성
+}
+
+// while과 do...while, for 문이 아마 더 친숙할 것입니다.
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // "01234"를 출력
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // "01234"를 출력
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // "0123456789"를 출력
+
+echo "\n";
+
+$wheels = ['bicycle' => 2, 'car' => 4];
+
+// foreach 문은 배영를 순회할 수 있습니다.
+foreach ($wheels as $wheel_count) {
+ echo $wheel_count;
+} // "24"를 출력
+
+echo "\n";
+
+// 키와 값을 동시에 순회할 수 있습니다.
+foreach ($wheels as $vehicle => $wheel_count) {
+ echo "A $vehicle has $wheel_count wheels";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // while 문을 빠져나옴
+ }
+ echo $i++;
+} // "012"를 출력
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // 이번 순회를 생략
+ }
+ echo $i;
+} // "0124"를 출력
+
+
+/********************************
+ * 함수
+ */
+
+// "function"으로 함수를 정의합니다.
+function my_function () {
+ return 'Hello';
+}
+
+echo my_function(); // => "Hello"
+
+// 유효한 함수명은 문자나 밑줄로 시작하고, 이어서
+// 임의 개수의 문자나 숫자, 밑줄이 옵니다.
+
+function add ($x, $y = 1) { // $y는 선택사항이고 기본값은 1입니다.
+ $result = $x + $y;
+ return $result;
+}
+
+echo add(4); // => 5
+echo add(4, 2); // => 6
+
+// 함수 밖에서는 $result에 접근할 수 없습니다.
+// print $result; // 이 코드를 실행하면 경고가 출력됩니다.
+
+// PHP 5.3부터는 익명 함수를 선언할 수 있습니다.
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// 함수에서는 함수를 반환할 수 있습니다.
+function bar ($x, $y) {
+ // 'use'를 이용해 바깥 함수의 변수를 전달합니다.
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // "A - B - C"를 출력
+
+// 문자열을 이용해 이름이 지정된 함수를 호출할 수 있습니다.
+$function_name = 'add';
+echo $function_name(1, 2); // => 3
+// 프로그램 방식으로 어느 함수를 실행할지 결정할 때 유용합니다.
+// 아니면 call_user_func(callable $callback [, $parameter [, ... ]]);를 사용해도 됩니다.
+
+/********************************
+ * 인클루드
+ */
+
+<?php
+// 인클루드된 파일 내의 PHP 코드도 반드시 PHP 여는 태그로 시작해야 합니다.
+
+include 'my-file.php';
+// my-file.php 안의 코드는 이제 현재 유효범위에서 이용할 수 있습니다.
+// 파일을 인클루드할 수 없으면(예: 파일을 찾을 수 없음) 경고가 출력됩니다.
+
+include_once 'my-file.php';
+// my-file.php 안의 코드가 다른 곳에 인클루드됐다면 다시 인클루드되지는 않습니다.
+// 따라서 클래스 선언이 여러 번 되어 발생하는 문제가 일어나지 않습니다.
+
+require 'my-file.php';
+require_once 'my-file.php';
+// require()는 include()와 같지만 파일을 인클루드할 수 없을 경우
+// 치명적인 오류가 발생한다는 점이 다릅니다.
+
+// my-include.php의 내용
+<?php
+
+return 'Anything you like.';
+// 파일의 끝
+
+// include와 require는 값을 반환할 수도 있습니다.
+$value = include 'my-include.php';
+
+// 파일은 지정된 파일 경로를 토대로 인클루드되거나, 혹은 아무것도 명시하지 않은 경우
+// include_path라는 설정 지시지를 따릅니다. include_path에서 파일을 발견할 수 없으면
+// include는 마지막으로 실패하기 전에 호출 스크립트 자체의 디렉터리와 현재 작업 디렉터리를 확인합니다.
+/* */
+
+/********************************
+ * 클래스
+ */
+
+// 클래스는 class라는 키워드로 정의합니다.
+
+class MyClass
+{
+ const MY_CONST = 'value'; // 상수
+
+ static $staticVar = 'static';
+
+ // 프로퍼티에는 반드시 가시성을 선언해야 합니다.
+ public $property = 'public';
+ public $instanceProp;
+ protected $prot = 'protected'; // 이 클래스와 하위 클래스에서 접근할 수 있음
+ private $priv = 'private'; // 이 클래스 내에서만 접근 가능
+
+ // __construct로 생성자를 만듭니다.
+ public function __construct($instanceProp) {
+ // $this로 인스턴스 변수에 접근합니다.
+ $this->instanceProp = $instanceProp;
+ }
+
+ // 메서드는 클래스 안의 함수로서 선언됩니다.
+ public function myMethod()
+ {
+ print 'MyClass';
+ }
+
+ final function youCannotOverrideMe()
+ {
+ }
+
+ public static function myStaticMethod()
+ {
+ print 'I am static';
+ }
+}
+
+echo MyClass::MY_CONST; // 'value' 출력
+echo MyClass::$staticVar; // 'static' 출력
+MyClass::myStaticMethod(); // 'I am static' 출력
+
+// new를 사용해 클래스를 인스턴스화합니다.
+$my_class = new MyClass('An instance property');
+// 인자를 전달하지 않을 경우 괄호를 생략할 수 있습니다.
+
+// ->를 이용해 클래스 멤버에 접근합니다
+echo $my_class->property; // => "public"
+echo $my_class->instanceProp; // => "An instance property"
+$my_class->myMethod(); // => "MyClass"
+
+
+// "extends"를 이용해 클래스를 확장합니다.
+class MyOtherClass extends MyClass
+{
+ function printProtectedProperty()
+ {
+ echo $this->prot;
+ }
+
+ // 메서드 재정의
+ function myMethod()
+ {
+ parent::myMethod();
+ print ' > MyOtherClass';
+ }
+}
+
+$my_other_class = new MyOtherClass('Instance prop');
+$my_other_class->printProtectedProperty(); // => "protected" 출력
+$my_other_class->myMethod(); // "MyClass > MyOtherClass" 출력
+
+final class YouCannotExtendMe
+{
+}
+
+// "마법 메서드(magic method)"로 설정자 메서드와 접근자 메서드를 만들 수 있습니다.
+class MyMapClass
+{
+ private $property;
+
+ public function __get($key)
+ {
+ return $this->$key;
+ }
+
+ public function __set($key, $value)
+ {
+ $this->$key = $value;
+ }
+}
+
+$x = new MyMapClass();
+echo $x->property; // __get() 메서드를 사용
+$x->property = 'Something'; // __set() 메서드를 사용
+
+// 클래스는 추상화하거나(abstract 키워드를 사용해)
+// 인터페이스를 구현할 수 있습니다(implments 키워드를 사용해).
+// 인터페이스는 interface 키워드로 선언합니다.
+
+interface InterfaceOne
+{
+ public function doSomething();
+}
+
+interface InterfaceTwo
+{
+ public function doSomethingElse();
+}
+
+// 인터페이스는 확장할 수 있습니다.
+interface InterfaceThree extends InterfaceTwo
+{
+ public function doAnotherContract();
+}
+
+abstract class MyAbstractClass implements InterfaceOne
+{
+ public $x = 'doSomething';
+}
+
+class MyConcreteClass extends MyAbstractClass implements InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo $x;
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+
+// 클래스에서는 하나 이상의 인터페이스를 구현할 수 있습니다.
+class SomeOtherClass implements InterfaceOne, InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo 'doSomething';
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+
+/********************************
+ * 특성
+ */
+
+// 특성(trait)은 PHP 5.4.0부터 사용 가능하며, "trait"으로 선언합니다.
+
+trait MyTrait
+{
+ public function myTraitMethod()
+ {
+ print 'I have MyTrait';
+ }
+}
+
+class MyTraitfulClass
+{
+ use MyTrait;
+}
+
+$cls = new MyTraitfulClass();
+$cls->myTraitMethod(); // "I have MyTrait"을 출력
+
+
+/********************************
+ * 네임스페이스
+ */
+
+// 이 부분은 별도의 영역인데, 파일에서 처음으로 나타나는 문장은
+// 네임스페이스 선언이어야 하기 때문입니다. 여기서는 그런 경우가 아니라고 가정합니다.
+
+<?php
+
+// 기본적으로 클래스는 전역 네임스페이스에 존재하며,
+// 백슬래시를 이용해 명시적으로 호출할 수 있습니다.
+
+$cls = new \MyClass();
+
+
+
+// 파일에 대한 네임스페이스를 설정합니다.
+namespace My\Namespace;
+
+class MyClass
+{
+}
+
+// (다른 파일에 들어 있는 코드)
+$cls = new My\Namespace\MyClass;
+
+// 또는 다른 네임스페이스 내에서 접근하는 경우
+namespace My\Other\Namespace;
+
+use My\Namespace\MyClass;
+
+$cls = new MyClass();
+
+// 혹은 네임스페이스에 별칭을 붙일 수도 있습니다.
+
+namespace My\Other\Namespace;
+
+use My\Namespace as SomeOtherNamespace;
+
+$cls = new SomeOtherNamespace\MyClass();
+
+*/
+
+```
+
+## 더 자세한 정보
+
+레퍼런스와 커뮤니티 관련 내용은 [공식 PHP 문서](http://www.php.net/manual/)를 참고하세요.
+
+최신 모범 사례에 관심이 있다면 [PHP The Right Way](http://www.phptherightway.com/)를 참고하세요.
+
+PHP를 익히기 전에 다른 훌륭한 패키지 관리자를 지원하는 언어를 사용해본 적이 있다면 [컴포저(Composer)](http://getcomposer.org/)를 확인해 보세요.
+
+공통 표준이 궁금하다면 PHP 프레임워크 상호운용성 그룹의 [PSR 표준](https://github.com/php-fig/fig-standards)을 참고하세요.
diff --git a/matlab.html.markdown b/matlab.html.markdown
new file mode 100644
index 00000000..507e9c85
--- /dev/null
+++ b/matlab.html.markdown
@@ -0,0 +1,260 @@
+---
+language: Matlab
+contributors:
+ - ["mendozao", "http://github.com/mendozao"]
+---
+
+Matlab stands for Matrix Laboratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
+
+If you have any feedback please feel free to reach me at
+[@the_ozzinator](https://twitter.com/the_ozzinator), or
+[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
+
+```Matlab
+
+
+
+% Comments start with a percent sign.
+
+%{ Multi line comments look
+something
+like
+this %}
+
+clear % Erases all your variables from memory
+clc % Erases the writing on your Command Window
+who % Displays all variables in memory
+diary % History of session
+ctrl-c % Abort current computation
+
+help command % Displays documentation for command in Command Window
+lookfor command % Searches for a given command
+
+
+% Output formatting
+format short % 4 decimals in a floating number
+format long % 15 decimals
+fprintf
+
+% Variables & Expressions
+myVariable = 4 % Notice Workspace pane shows newly created variable
+myVariable = 4; % Semi colon suppresses output to the Command Window
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+a = 2; b = 3;
+c = exp(a)*sin(pi/2) % c = 7.3891
+
+% Logicals
+1 > 5 % ans = 0
+10 >= 10 % ans = 1
+3 ~= 4 % Not equal to -> ans = 1
+3 == 3 % equal to -> ans = 1
+3 > 1 && 4 > 1 % AND -> ans = 1
+3 > 1 || 4 > 1 % OR -> ans = 1
+~1 % NOT -> ans = 0
+
+% Strings
+a = 'MyString'
+length(a) % ans = 8
+a(2) % ans = y
+[a,a] % ans = MyStringMyString
+
+
+% Cells
+a = {'one', 'two', 'three'}
+a(1) % ans = 'one' - returns a cell
+char(a(1)) % ans = one - returns a string
+
+
+% Vectors
+x = [4 32 53 7 1]
+x(2) % ans = 32, indices in Matlab start 1, not 0
+x(2:3) % ans = 32 53
+x(2:end) % ans = 32 53 7 1
+
+x = [4; 32; 53; 7; 1] % Column vector
+
+x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+
+% Matrices
+A = [1 2 3; 4 5 6; 7 8 9]
+% Rows are seperated with a semi colon, each element is seperated with space or comma
+% A =
+
+% 1 2 3
+% 4 5 6
+% 7 8 9
+
+A(2,3) % ans = 6, A(row, column)
+A(2,3) = 42 % Update row 2 col 3 with 42
+% A =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+A(2:3,2:3) % Creates a new matrix from the old one
+%ans =
+
+% 5 42
+% 8 9
+
+A(:,1) % All rows in column 1
+%ans =
+
+% 1
+% 4
+% 7
+
+A(1,:) % All columns in row 1
+%ans =
+
+% 1 2 3
+
+A(:, [3 1 2]) %Rearrange the columns of original matrix
+%ans =
+
+% 3 1 2
+% 42 4 5
+% 9 7 8
+
+A(1, :) =[] %Delete the first row of the matrix
+
+size(A) % ans = 3 3
+
+A' % Transpose the matrix
+
+[A ; A] % Concatenation of matrices
+%ans =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+
+%Element by Element Arithmetic VS Matrix Arithmetic
+A * B % Matrix multiplication
+A .* B % Multiple each element in A by its corresponding element in B
+
+
+%Plotting
+x = 0:.10:2*pi % Creates a vector that starts at 0 and ends at 2*pi with increments of .1
+y = sin(x)
+plot(x,y)
+xlabel('x axis')
+ylabel('y axis')
+title('Plot of y = sin(x)')
+axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1
+plot(x,y1,’-’,x,y2,’--’,x,y3,’:’) % For multiple functions on one plot
+
+
+% .mat files
+% Save the variables in your Workspace
+
+%M-file Scripts
+%A script file is an external file that contains a sequence of statements.
+%Better than typing your code in the Command Window
+%Have .m extensions
+
+
+%M-file Functions
+%Programs that accept inputs and return an output
+%Have .m extensions
+% double_input.m - naming your ,m file the same as you call it in the file is required
+function output = double_input(x)
+ %double_input(x) returns twice the value of x
+ output = 2*x;
+end
+double_input(6) % ans = 12
+
+%User input
+a = input('Enter the value: ')
+
+%Reading in data
+fopen(filename)
+
+%Output
+disp(a) % Print out the value of variable a
+disp('Hello World') % Print out a string
+fprintf % More control display to Command Window
+
+%Conditional statements
+if a > 15
+ disp('Greater than 15')
+elseif a == 23
+ disp('a is 23')
+else
+ disp('neither condition met')
+end
+
+%Looping
+for k = 1:5
+ disp(k)
+end
+
+k = 0;
+while (k < 5)
+ k = k + 1;
+end
+
+
+%Connecting to a MySQL Database
+dbname = 'database_name';
+username = 'root';
+password = 'root';
+driver = 'com.mysql.jdbc.Driver';
+dburl = ['jdbc:mysql://localhost:8889/' dbname];
+javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
+conn = database(dbname, username, password, driver, dburl);
+sql = ['SELECT * from table_name where id = 22'] %Example sql statement
+a = fetch(conn, sql) %a will contain your data
+
+
+% Common math functions
+sin(x)
+cos(x)
+tan(x)
+asin(x)
+acos(x)
+atan(x)
+exp(x)
+sqrt(x)
+log(x)
+log10(x)
+abs(x)
+min(x)
+max(x)
+ceil(x)
+floor(x)
+round(x)
+rem(x)
+rand
+randi
+
+% Common constants
+pi
+NaN
+inf
+
+% Common matrix functions
+zeros(m,n) % m x n matrix of 0's
+ones(m,n) % m x n matrix of 1's
+diag(A) % Extracts the diagonal elements of a matrix
+eye(m,n) % Indentity matrix
+inv(A) % Inverse of matrix A
+det(A) % Determinant of A
+eig(A) %Eigenvalues and eigenvectors of A
+isempty(A) % Tests if array is empty
+isequal(A, B) %Tests equality of two arrays
+numel(A) %Number of elements in matrix
+
+
+
+```
+
+## More on Matlab
+
+* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
diff --git a/perl.html.markdown b/perl.html.markdown
index 024bd851..18339dde 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -104,6 +104,35 @@ $a =~ s/foo/bar/; # replaces foo with bar in $a
$a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a
+#### Files and I/O
+
+# You can open a file for input or output using the "open()" function.
+
+open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
+open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
+open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
+
+# You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line from
+# the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list:
+
+my $line = <$in>;
+my @lines = <$in>;
+
+#### Writing subroutines
+
+# Writing subroutines is easy:
+
+sub logger {
+ my $logmessage = shift;
+ open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
+ print $logfile $logmessage;
+}
+
+# Now we can use the subroutine just as any other built-in function:
+
+logger("We have a logger subroutine!");
+
+
```
#### Using Perl modules
@@ -114,5 +143,7 @@ perlfaq contains questions and answers related to many common tasks, and often p
#### Further Reading
-[Learn at www.perl.com](http://www.perl.org/learn.html)
- and perldoc perlintro
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn at www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - and perl built-in : `perldoc perlintro`
diff --git a/python.html.markdown b/python.html.markdown
index f0b74d08..bad9a360 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -93,8 +93,8 @@ not False #=> True
# None is an object
None #=> None
-# Don't use the equality `==` symbol to compare objects to None
-# Use `is` instead
+# Don't use the equality "==" symbol to compare objects to None
+# Use "is" instead
"etc" is None #=> False
None is None #=> True
@@ -158,19 +158,19 @@ li[2:] #=> [4, 3]
# Omit the end
li[:3] #=> [1, 2, 4]
-# Remove arbitrary elements from a list with del
+# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
# You can add lists
li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone
-# Concatenate lists with extend
+# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
-# Check for existence in a list with in
+# Check for existence in a list with "in"
1 in li #=> True
-# Examine the length with len
+# Examine the length with "len()"
len(li) #=> 6
@@ -201,37 +201,37 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Look up values with []
filled_dict["one"] #=> 1
-# Get all keys as a list
+# Get all keys as a list with "keys()"
filled_dict.keys() #=> ["three", "two", "one"]
# Note - Dictionary key ordering is not guaranteed.
# Your results might not match this exactly.
-# Get all values as a list
+# Get all values as a list with "values()"
filled_dict.values() #=> [3, 2, 1]
# Note - Same as above regarding key ordering.
-# Check for existence of keys in a dictionary with in
+# Check for existence of keys in a dictionary with "in"
"one" in filled_dict #=> True
1 in filled_dict #=> False
# Looking up a non-existing key is a KeyError
filled_dict["four"] # KeyError
-# Use get method to avoid the KeyError
+# Use "get()" method to avoid the KeyError
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
-# Setdefault method is a safe way to add new key-value pair into dictionary
+# "setdefault()" method is a safe way to add new key-value pair into dictionary
filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5
# Sets store ... well sets
empty_set = set()
-# Initialize a set with a bunch of values
+# Initialize a "set()" with a bunch of values
some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])
# Since Python 2.7, {} can be used to declare a set
@@ -284,7 +284,7 @@ for animal in ["dog", "cat", "mouse"]:
print "%s is a mammal" % animal
"""
-`range(number)` returns a list of numbers
+"range(number)" returns a list of numbers
from zero to the given number
prints:
0
@@ -312,7 +312,7 @@ while x < 4:
# Works on Python 2.6 and up:
try:
- # Use raise to raise an error
+ # Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
@@ -322,7 +322,7 @@ except IndexError as e:
## 4. Functions
####################################################
-# Use def to create new functions
+# Use "def" to create new functions
def add(x, y):
print "x is %s and y is %s" % (x, y)
return x + y # Return values with a return statement
@@ -359,7 +359,7 @@ all_the_args(1, 2, a=3, b=4) prints:
{"a": 3, "b": 4}
"""
-# When calling functions, you can do the opposite of varargs/kwargs!
+# When calling functions, you can do the opposite of args/kwargs!
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
@@ -402,7 +402,7 @@ class Human(object):
# Assign the argument to the instance's name attribute
self.name = name
- # An instance method. All methods take self as the first argument
+ # An instance method. All methods take "self" as the first argument
def say(self, msg):
return "%s: %s" % (self.name, msg)
diff --git a/ru-ru/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown
new file mode 100644
index 00000000..88d07c09
--- /dev/null
+++ b/ru-ru/erlang-ru.html.markdown
@@ -0,0 +1,255 @@
+---
+language: erlang
+contributors:
+ - ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
+ - ["Nikita Kalashnikov", "https://root.yuuzukiyo.net/"]
+filename: learnerlang-ru.erl
+lang: ru-ru
+---
+
+```erlang
+% Символ процента предваряет однострочный комментарий.
+
+%% Два символа процента обычно используются для комментариев к функциям.
+
+%%% Три символа процента используются для комментариев к модулям.
+
+% Пунктуационные знаки, используемые в Erlang:
+% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и
+% образцах.
+% Точка (`.`) (с пробелом после них) разделяет функции и выражения в
+% оболочке.
+% Точка с запятой (`;`) разделяет выражения в следующих контекстах:
+% формулы функций, выражения `case`, `if`, `try..catch` и `receive`.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 1. Переменные и сопоставление с образцом.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+Num = 42. % Все названия переменных начинаются с большой буквы.
+
+% Erlang использует единичное присваивание переменным. Если вы попытаетесь
+% присвоить другое значение переменной `Num`, вы получите ошибку.
+Num = 43. % ** exception error: no match of right hand side value 43
+
+% В большинстве языков `=` обозначает операцию присвоения. В отличие от них, в
+% Erlang `=` — операция сопоставления с образцом. `Lhs = Rhs` на самом
+% деле подразумевает «вычисли правую часть выражения (Rhs) и затем сопоставь
+% результат с образцом слева (Lhs)».
+Num = 7 * 6.
+
+% Числа с плавающей точкой.
+Pi = 3.14159.
+
+% Атомы используются для представления различных нечисловых констант. Названия
+% атомов начинаются с буквы в нижнем регистре, за которой могут следовать другие
+% буквы английского алфавита, цифры, символ подчёркивания (`_`) или «собака»
+% (`@`).
+Hello = hello.
+OtherNode = example@node.
+
+% Если в имени атома нужно использовать другие символы, кроме допустимых,
+% имя атома необходимо взять в одинарные кавычки (`'`).
+AtomWithSpace = 'some atom with space'.
+
+% Кортежы подобны структурам в языке C.
+Point = {point, 10, 45}.
+
+% Если нужно извлечь определённые данные из кортежа, используется оператор
+% сопоставления с образцом — `=`.
+{point, X, Y} = Point. % X = 10, Y = 45
+
+% Символ `_` может использоваться как «заполнитель» для переменных, значения
+% которых в текущем выражении нас не интересуют. Он называется анонимной
+% переменной. В отличие от остальных переменных, множественные использования
+% `_` в одном образце не требуют, чтобы все значения, присваевыемые этой
+% переменной, были идентичными.
+Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.
+{_, {_, {_, Who}, _}, _} = Person. % Who = joe
+
+% Список создаётся путём заключения его элементов в квадратные скобки и
+% разделения их запятыми. Отдельные элементы списка могут быть любого типа.
+% Первый элемент списка называется головой списка. Список, получающийся в
+% результате отделения головы, называется хвостом списка.
+ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}].
+
+% Если `T` — список, то `[H|T]` — тоже список, где `H` является головой, а `T` —
+% хвостом. Вертикальная черта (`|`) разделяет голову и хвост списка.
+% `[]` — пустой список.
+% Мы можем извлекать элементы из списка с помощью сопоставления с образцом.
+% Если у нас есть непустой список `L`, тогда выражение `[X|Y] = L`, где `X` и
+% `Y` — свободные (не связанные с другими значениям) переменные, извлечёт голову
+% списка в `X` и его хвост в `Y`.
+[FirstThing|OtherThingsToBuy] = ThingsToBuy.
+% FirstThing = {apples, 10}
+% OtherThingsToBuy = {pears, 6}, {milk, 3}
+
+% В Erlang нет строк как отдельного типа. Все используемые в программах строки
+% являются обычным списком целых чисел. Строковые значения всегда должны быть в
+% двойных кавычках (`"`).
+Name = "Hello".
+[72, 101, 108, 108, 111] = "Hello".
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 2. Последовательное программирование.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Модуль — основная единица кода в Erlang. В них пишутся и сохраняются все
+% функции. Модули хранятся в файлах с расширением `.erl`.
+% Модули должны быть скомпилированы перед тем, как использовать код из них.
+% Скомпилированный файл модуля имеет разрешение `.beam`.
+-module(geometry).
+-export([area/1]). % список функций, экспортируемых из модуля.
+
+% Функция `area` состоит из двух формул (clauses). Формулы отделяются друг от
+% друга точкой с запятой, после последнего определения должна стоять точка с
+% пробелом после неё.
+% Каждое определение имеет заголовок и тело. Заголовок состоит из названия
+% функции и образца (в скобках); тело состоит из последовательных выражений,
+% вычисляемых, когда аргументы функции совпадают с образцом в заголовке.
+% Сопоставление с образцами в заголовках происходит в том порядке, в котором
+% они перечислены в определении функции.
+area({rectangle, Width, Ht}) -> Width * Ht;
+area({circle, R}) -> 3.14159 * R * R.
+
+% Компиляция файла с исходным кодом geometry.erl.
+c(geometry). % {ok,geometry}
+
+% Необходимо указывать имя модуля вместе с именем функции для определения, какую
+% именно фукнцию мы хотим вызвать.
+geometry:area({rectangle, 10, 5}). % 50
+geometry:area({circle, 1.4}). % 6.15752
+
+% В Erlang две функции с разной арностью (числом аргументов) в пределах одного
+% модуля представляются как две разные функции.
+-module(lib_misc).
+-export([sum/1]). % экспорт функции `sum` с арностью 1, принимающую один аргумент.
+sum(L) -> sum(L, 0).
+sum([], N) -> N;
+sum([H|T], N) -> sum(T, H+N).
+
+% Fun'ы — анонимные функции, называемые так по причине отсутствия имени. Зато
+% их можно присваивать переменным.
+Double = fun(X) -> 2*X end. % `Double` указывает на анонимную функцию с идентификатором: #Fun<erl_eval.6.17052888>
+Double(2). % 4
+
+% Функции могут принимать fun'ы как параметры и возвращать их в качестве
+% результата вычислений.
+Mult = fun(Times) -> ( fun(X) -> X * Times end ) end.
+Triple = Mult(3).
+Triple(5). % 15
+
+% Выделения списоков (list comprehensions) — выражения, создающие списки без
+% применения анонимных функций, фильтров или map'ов.
+% Запись `[F(X) || X <- L]` значит «список `F(X)`, где `X` последовательно
+% выбирается из списка `L`».
+L = [1,2,3,4,5].
+[2*X || X <- L]. % [2,4,6,8,10]
+% В выделениях списков могут быть генераторы и фильтры для отделения подмножеств
+% генерируемых значений.
+EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]
+
+% Охранные выражения используются для простых проверок переменных в образцах,
+% что значительно расширяет возможности сопоставления. Они могут использоваться
+% в заголовках определений функций, предварённые ключевым словом `when`, а также
+% в условных конструкциях.
+max(X, Y) when X > Y -> X;
+max(X, Y) -> Y.
+
+% Охранные выражения можно группировать, разделяя запятой.
+% Последовательность `GuardExpr1, GuardExpr2, ..., GuardExprN` является истинной
+% только в том случае, когда все выражения, которые она содержат, являются
+% истинными.
+is_cat(A) when is_atom(A), A =:= cat -> true;
+is_cat(A) -> false.
+is_dog(A) when is_atom(A), A =:= dog -> true;
+is_dog(A) -> false.
+
+% Последовательность охранных выражений, разделённых точками с запятой, является
+% истинной в том случае, если хотя бы одно выражение из списка `G1; G2; ...; Gn`
+% является истинным.
+is_pet(A) when is_dog(A); is_cat(A) -> true;
+is_pet(A) -> false.
+
+% Записи предоставляют возможность именования определённых элементов в кортежах.
+% Определения записей могут быть включены в исходный код модулей Erlang или же
+% в заголовочные файлы с расширением `.hrl`.
+-record(todo, {
+ status = reminder, % Значение по умолчанию.
+ who = joe,
+ text
+}).
+
+% Для чтения определений записей из файлов в оболочке можно использовать команду
+% `rr`.
+rr("records.hrl"). % [todo]
+
+% Создание и изменение записей.
+X = #todo{}.
+% #todo{status = reminder, who = joe, text = undefined}
+X1 = #todo{status = urgent, text = "Fix errata in book"}.
+% #todo{status = urgent, who = joe, text = "Fix errata in book"}
+X2 = X1#todo{status = done}.
+% #todo{status = done,who = joe,text = "Fix errata in book"}
+
+% Условное выражение `case`.
+% Функция `filter` возвращет список всех элементов `X` из списка `L`, для
+% которых выражение `P(X)` является истинным.
+filter(P, [H|T]) ->
+ case P(H) of
+ true -> [H|filter(P, T)];
+ false -> filter(P, T)
+ end;
+filter(P, []) -> [].
+filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4]
+
+% Условное выражение `if`.
+max(X, Y) ->
+ if
+ X > Y -> X;
+ X < Y -> Y;
+ true -> nil;
+ end.
+
+% Внимание: в выражении `if` должно быть как минимум одно охранное выраженние,
+% вычисляющееся в true, иначе возникнет исключение.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 3. Обработка исключений.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Исключения возникают в случае внутренних ошибок системы или вызываются
+% непосредственно из кода программы с помощью вызовов `throw(Exception)`,
+% `exit(Exception)` или `erlang:error(Exception)`.
+generate_exception(1) -> a;
+generate_exception(2) -> throw(a);
+generate_exception(3) -> exit(a);
+generate_exception(4) -> {'EXIT', a};
+generate_exception(5) -> erlang:error(a).
+
+% В Erlang есть два способа обработки исключений. Первый заключается в
+% использовании выражения `try..catch` в функции, в которой возможен выброс
+% исключения.
+catcher(N) ->
+ try generate_exception(N) of
+ Val -> {N, normal, Val}
+ catch
+ throw:X -> {N, caught, thrown, X};
+ exit:X -> {N, caught, exited, X};
+ error:X -> {N, caught, error, X}
+ end.
+
+% Второй способ заключается в использовании `catch`. Во время поимки исключения
+% оно преобразуется в кортеж с информацией об ошибке.
+catcher(N) -> catch generate_exception(N).
+
+```
+
+## Ссылки:
+
+* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/)
+* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang)
+* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/)
+* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml)
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 9163c8aa..3f457bdc 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -6,12 +6,12 @@ contributors:
filename: learnpython-ru.py
---
-Язык Python был создан Гвидо ван Россумом в ранние 90-е. Сегодня это один из самых популярных
-языков. Я влюбился в него благодаря его понятному и доходчивому синтаксису - это почти что исполняемый псевдокод.
+Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из самых популярных
+языков. Я люблю его за его понятный и доходчивый синтаксис - это почти что исполняемый псевдокод.
-Обратная связь будет высоко оценена! Вы можете связаться со мной: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service]
+С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service]
-Замечание: Эта статья относится к Python 2.7, но должна быть применима к Python 2.x. Скоро ожидается версия и для Python 3!
+Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x. Скоро будет версия и для Python 3!
```python
# Однострочные комментарии начинаются с hash-символа.
@@ -21,25 +21,25 @@ filename: learnpython-ru.py
"""
####################################################
-## 1. Примитивные типы данных и операторв
+## 1. Примитивные типы данных и операторов
####################################################
# У вас есть числа
3 #=> 3
-# Математика работает так, как вы и думаете
+# Математика работает вполне ожидаемо
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
-# Деление немного сложнее. Это деление целых чисел и результат
-# автоматически округляется в меньшую сторону.
+# А вот деление немного сложнее. В этом случае происходит деление
+№ целых чисел и результат автоматически округляется в меньшую сторону.
5 / 2 #=> 2
# Чтобы научиться делить, сначала нужно немного узнать о дробных числах.
-2.0 # Это дробное число.
-11.0 / 4.0 #=> 2.75 вооот... гораздо лучше
+2.0 # Это дробное число
+11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше
# Приоритет операций указывается скобками
(1 + 3) * 2 #=> 8
@@ -60,7 +60,7 @@ not False #=> True
1 != 1 #=> False
2 != 1 #=> True
-# Больше сравнений
+# Еще немного сравнений
1 < 10 #=> True
1 > 10 #=> False
2 <= 2 #=> True
@@ -70,36 +70,36 @@ not False #=> True
1 < 2 < 3 #=> True
2 < 3 < 2 #=> False
-# Строки создаются при символом " или '
+# Строки определяются символом " или '
"Это строка."
'Это тоже строка.'
-# Строки тоже могут складываться!
+# И строки тоже могут складываться!
"Привет " + "мир!" #=> "Привет мир!"
-# Со строкой можно работать как со списком символов
+# Со строкой можно работать, как со списком символов
"Это строка"[0] #=> 'Э'
-# % используется для форматирования строк, например:
+# Символ % используется для форматирования строк, например:
"%s могут быть %s" % ("строки", "интерполированы")
# Новый метод форматирования строк - использование метода format.
# Это предпочитаемый способ.
"{0} могут быть {1}".format("строки", "форматированы")
-# Вы можете использовать ключевые слова, если не хотите считать.
+# Если вы не хотите считать, можете использовать ключевые слова.
"{name} хочет есть {food}".format(name="Боб", food="лазанью")
# None является объектом
None #=> None
-# Не используйте оператор равенства `==` для сравнения
-# объектов с None. Используйте для этого `is`
+# Не используйте оператор равенства '=='' для сравнения
+# объектов с None. Используйте для этого 'is'
"etc" is None #=> False
None is None #=> True
# Оператор 'is' проверяет идентичность объектов. Он не
# очень полезен при работе с примитивными типами, но
-# очень полезен при работе с объектами.
+# зато просто незаменим при работе с объектами.
# None, 0, и пустые строки/списки равны False.
# Все остальные значения равны True
@@ -111,15 +111,15 @@ None is None #=> True
## 2. Переменные и коллекции
####################################################
-# Печать довольно проста
+# Печатать довольно просто
print "Я Python. Приятно познакомиться!"
-# Необязательно объявлять переменные перед присваиванием им значения.
+# Необязательно объявлять переменные перед их инициализацией.
some_var = 5 # По соглашению используется нижний_регистр_с_подчеркиваниями
some_var #=> 5
-# При попытке доступа к переменной, которой не было ранее присвоено значение,
+# При попытке доступа к неинициализированной переменной,
# выбрасывается исключение.
# См. раздел "Поток управления" для информации об исключениях.
some_other_var # Выбрасывает ошибку именования
@@ -133,25 +133,25 @@ li = []
other_li = [4, 5, 6]
# Объекты добавляются в конец списка методом append
-li.append(1) #li содержит [1]
-li.append(2) #li содержит [1, 2]
-li.append(4) #li содержит [1, 2, 4]
-li.append(3) #li содержит [1, 2, 4, 3]
-# Удаляются с конца методом pop
-li.pop() #=> 3 и li содержит [1, 2, 4]
-# Положим его обратно
-li.append(3) # li содержит [1, 2, 4, 3] опять.
+li.append(1) # [1]
+li.append(2) # [1, 2]
+li.append(4) # [1, 2, 4]
+li.append(3) # [1, 2, 4, 3]
+# И удаляются с конца методом pop
+li.pop() #=> возвращает 3 и li становится равен [1, 2, 4]
+# Положим элемент обратно
+li.append(3) # [1, 2, 4, 3].
# Обращайтесь со списком, как с обычным массивом
li[0] #=> 1
-# Посмотрим на последний элемент
+# Обратимся к последнему элементу
li[-1] #=> 3
-# Попытка выйти за границы массива приводит к IndexError
+# Попытка выйти за границы массива приведет к IndexError
li[4] # Выдает IndexError
# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax)
-# (Для тех из вас, кто любит математику, это замкнуто/открытый интервал.)
+# (Для тех, кто любит математику, это называется замкнуто/открытый интервал.)
li[1:3] #=> [2, 4]
# Опускаем начало
li[2:] #=> [4, 3]
@@ -159,38 +159,38 @@ li[2:] #=> [4, 3]
li[:3] #=> [1, 2, 4]
# Удаляем произвольные элементы из списка оператором del
-del li[2] # li содержит [1, 2, 3]
+del li[2] # [1, 2, 3]
# Вы можете складывать списки
-li + other_li #=> [1, 2, 3, 4, 5, 6] - ЗАмечание: li и other_li остаются нетронутыми
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Замечание: li и other_li остаются нетронутыми
# Конкатенировать списки можно методом extend
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
-# Проверять элемент на вхождение на список оператором in
+# Проверить элемент на вхождение в список можно оператором in
1 in li #=> True
-# Длина списка вычисляется при помощи len
+# Длина списка вычисляется функцией len
len(li) #=> 6
-# Кортежи - это как списки, только неизменяемые
+# Кортежи - это такие списки, только неизменяемые
tup = (1, 2, 3)
tup[0] #=> 1
tup[0] = 3 # Выдает TypeError
-# Все те же штуки можно делать и с кортежами
+# Все то же самое можно делать и с кортежами
len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
2 in tup #=> True
# Вы можете распаковывать кортежи (или списки) в переменные
-a, b, c = (1, 2, 3) # a теперь равно 1, b равно 2 и c равно 3
+a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3
# Кортежи создаются по умолчанию, если опущены скобки
d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
-e, d = d, e # d теперь равно 5 and e равно 4
+e, d = d, e # теперь d == 5, а e == 4
# Словари содержат ассоциативные массивы
@@ -208,7 +208,7 @@ filled_dict.keys() #=> ["three", "two", "one"]
# Можно получить и все значения в виде списка
filled_dict.values() #=> [3, 2, 1]
-# Замечание - то же самое, что и выше, насчет порядка ключей
+# То же самое замечание насчет порядка ключей справедливо и здесь
# При помощи оператора in можно проверять ключи на вхождение в словарь
"one" in filled_dict #=> True
@@ -260,7 +260,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
## 3. Поток управления
####################################################
-# Давайте заведем переменную
+# Для начала заведем переменную
some_var = 5
# Так выглядит выражение if. Отступы в python очень важны!
@@ -274,8 +274,9 @@ else: # Это тоже необязательно.
"""
-Циклы For проходят по циклам
-результат:
+Циклы For проходят по спискам
+
+Результат:
собака это млекопитающее
кошка это млекопитающее
мышь это млекопитающее
@@ -287,7 +288,7 @@ for animal in ["собака", "кошка", "мышь"]:
"""
`range(number)` возвращает список чисел
от нуля до заданного числа
-результат:
+Результат:
0
1
2
@@ -298,7 +299,7 @@ for i in range(4):
"""
Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
-результат:
+Результат:
0
1
2
@@ -422,10 +423,10 @@ class Human(object):
# Инстанцирование класса
i = Human(name="Иван")
-print i.say("привет") # выводит "Иван: привет"
+print i.say("привет") # "Иван: привет"
j = Human("Петр")
-print j.say("Привет") #выводит "Петр: привет"
+print j.say("Привет") # "Петр: привет"
# Вызов метода класса
i.get_species() #=> "H. sapiens"
@@ -453,7 +454,7 @@ print ceil(3.7) #=> 4.0
print floor(3.7) #=> 3.0
# Можете импортировать все функции модуля.
-# Предупреждение: не рекомендуется
+# (Хотя это и не рекомендуется)
from math import *
# Можете сокращать имена модулей
@@ -472,7 +473,7 @@ dir(math)
```
-## Хочется большего?
+## Хотите еще?
### Бесплатные онлайн-материалы
@@ -482,7 +483,7 @@ dir(math)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
-### Готовьте деньги
+### Платные
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
diff --git a/tr-tr/python-tr.html.markdown b/tr-tr/python-tr.html.markdown
new file mode 100644
index 00000000..01285080
--- /dev/null
+++ b/tr-tr/python-tr.html.markdown
@@ -0,0 +1,502 @@
+---
+language: python
+filename: learnpython-tr.py
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+translators:
+ - ["Haydar KULEKCI", "http://scanf.info/"]
+lang: tr-tr
+---
+Python Guido Van Rossum tarafından 90'ların başında yaratılmıştır. Şu anda
+varolanlar arasında en iyi dillerden birisidir. Ben (Louie Dinh) Python
+dilinin syntax'ının belirginliğine aşığım. O basit olarak çalıştırılabilir
+pseudocode'dur.
+
+Geri bildirimlerden son derece mutluluk duyarım! Bana [@louiedinh](http://twitter.com/louiedinh)
+adresinden ya da louiedinh [at] [google's email service] adresinden ulaşabilirsiniz.
+
+Çeviri için geri bildirimleri de [@kulekci](http://twitter.com/kulekci)
+adresine yapabilirsiniz.
+
+Not: Bu yazıdaki özellikler Python 2.7 için geçerlidir, ama Python 2.x için de
+uygulanabilir. Python 3 için başka bir zaman tekrar bakınız.
+
+
+```python
+# Tek satır yorum hash işareti ile başlar.
+""" Çoklu satır diziler üç tane çift tırnak
+ arasında yazılır. Ve yorum olarak da
+ kullanılabilir
+"""
+
+
+####################################################
+## 1. İlkel Veri Tipleri ve Operatörler
+####################################################
+
+# Sayılar
+3 #=> 3
+
+# Matematik beklediğiniz gibi
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# Bölünme biraz ilginç. EĞer tam sayılar üzerinde bölünme işlemi yapıyorsanız
+# sonuç otomatik olarak kırpılır.
+5 / 2 #=> 2
+
+# Bölünme işlemini düzenlemek için kayan noktalı sayıları bilmeniz gerekir.
+2.0 # Bu bir kayan noktalı sayı
+11.0 / 4.0 #=> 2.75 ahhh...daha iyi
+
+# İşlem önceliğini parantezler ile sağlayabilirsiniz.
+(1 + 3) * 2 #=> 8
+
+# Boolean değerleri bilindiği gibi
+True
+False
+
+# not ile nagatif(mantıksal) değerini alma
+not True #=> False
+not False #=> True
+
+# Eşitlik ==
+1 == 1 #=> True
+2 == 1 #=> False
+
+# Eşitsizlik !=
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Daha fazla karşılaştırma
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# Karşılaştırma zincirleme yapılabilir!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Karakter dizisi " veya ' ile oluşturulabilir
+"This is a string."
+'This is also a string.'
+
+# Karakter dizileri birbirleri ile eklenebilir
+"Hello " + "world!" #=> "Hello world!"
+
+# A string can be treated like a list of characters
+# Bir string'e karakter listesi gibi davranabilirsiniz.
+"This is a string"[0] #=> 'T'
+
+# % karakter dizisini(string) formatlamak için kullanılır, bunun gibi:
+"%s can be %s" % ("strings", "interpolated")
+
+# String'leri formatlamanın yeni bir yöntem ise format metodudur.
+# Bu metod tercih edilen yöntemdir.
+"{0} can be {1}".format("strings", "formatted")
+# Eğer saymak istemiyorsanız anahtar kelime kullanabilirsiniz.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# None bir objedir
+None #=> None
+
+# "==" eşitliğini non objesi ile karşılaştırmak için kullanmayın.
+# Onun yerine "is" kullanın.
+"etc" is None #=> False
+None is None #=> True
+
+# 'is' operatörü obje kimliği için test etmektedir. Bu ilkel değerler
+# için kullanışlı değildir, ama objeleri karşılaştırmak için kullanışlıdır.
+
+# None, 0 ve boş string/list'ler False olarak değerlendirilir.
+# Tüm eşitlikler True döner
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Değişkenler ve Kolleksiyonlar
+####################################################
+
+# Ekrana yazdırma oldukça kolaydır.
+print "I'm Python. Nice to meet you!"
+
+
+# Değişkenlere bir değer atamadan önce tanımlamaya gerek yoktur.
+some_var = 5 # Değişken isimlerinde gelenek küçük karakter ve alt çizgi
+ # kullanmaktır.
+some_var #=> 5
+
+# Daha önceden tanımlanmamış ya da assign edilmemeiş bir değişkene erişmeye
+# çalıştığınızda bir hata fırlatılacaktır. Hata ayıklama hakkında daha fazla
+# bilgi için kontrol akışı kısmına göz atınız.
+some_other_var # isim hatası fırlatılır
+
+# isterseniz "if"i bir ifade gibi kullanabilirsiniz.
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Listeler
+li = []
+# Önceden değerleri tanımlanmış listeler
+other_li = [4, 5, 6]
+
+# Bir listenin sonuna birşeyler eklemek
+li.append(1) #li şu anda [1]
+li.append(2) #li şu anda [1, 2]
+li.append(4) #li şu anda [1, 2, 4]
+li.append(3) #li şu anda [1, 2, 4, 3]
+# pop ile sondan birşeyler silmek
+li.pop() #=> 3 and li is now [1, 2, 4]
+# Tekrar sonuna eklemek
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# Dizi gibi listenin elemanlarına erişmek
+li[0] #=> 1
+# Son elemanın değerine ulaşmak
+li[-1] #=> 3
+
+# Listede bulunmayan bir index'teki elemana erişirken "IndexError" hatası
+# fırlatılır
+li[4] # IndexError fırlatılır
+
+# slice syntax'ı ile belli aralıktakı değerlere bakabilirsiniz.
+# (Açık ve kapalı aralıklıdır.)
+li[1:3] #=> [2, 4]
+# Başlangıcı ihmal etme
+li[2:] #=> [4, 3]
+# Sonu ihmal etme
+li[:3] #=> [1, 2, 4]
+
+# "del" ile istenilen bir elemanı listeden silmek
+del li[2] # li is now [1, 2, 3]
+
+# Listeleri birbiri ile birleştirebilirsiniz.
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Not: li ve other_li yanlız bırakılır
+
+# extend ile listeleri birleştirmek
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# bir değerin liste içerisinde varlığını "in" ile kontrol etmek
+1 in li #=> True
+
+# "len" ile listenin uzunluğunu bulmak
+len(li) #=> 6
+
+# Tüpler listeler gibidir sadece değişmezler(immutable)
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # TypeError fırlatılır.
+
+# Litelerde yapılanların hepsini tüplerde de yapılabilir
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Tüplerin(veya listelerin) içerisindeki değerleri değişkenelere
+# atanabilir
+a, b, c = (1, 2, 3) # a şu anda 1, b şu anda 2 ve c şu anda 3
+# Eğer parantez kullanmaz iseniz tüpler varsayılan olarak oluşturulur
+d, e, f = 4, 5, 6
+# şimdi iki değeri değiş tokuş etmek çok kolaydır.
+e, d = d, e # d şimdi 5 ve e şimdi 4
+
+
+# Sözlükler (Dictionaries) key-value saklanır.
+empty_dict = {}
+# Sözlüklere önceden değer atama örneği
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Değere ulaşmak için [] kullanılır
+filled_dict["one"] #=> 1
+
+# Tüm anahtarlara(key) "keys()" metodu ile ulaşılır
+filled_dict.keys() #=> ["three", "two", "one"]
+# Not - Sözlüklerin anahtarlarının sıralı geleceği garanti değildir
+# Sonuçlarınız değer listesini aldığınızda tamamen eşleşmeyebilir
+
+# Tüm değerleri almak için "values()" kullanabilirsiniz.
+filled_dict.values() #=> [3, 2, 1]
+# Not - Sıralama ile ilgili anahtarlar ile aynı durum geçerlidir.
+
+# Bir anahtarın sözlükte oluş olmadığını "in" ile kontrol edilebilir
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Olmayan bir anahtar çağrıldığında KeyError fırlatılır.
+filled_dict["four"] # KeyError
+
+# "get()" metodu KeyError fırlatılmasını önler
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# get() metodu eğer anahtar mevcut değilse varsayılan bir değer atama
+# imknaı sağlar.
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# "setdefault()" metodu sözlüğe yeni bir key-value eşleşmesi eklemenin
+# güvenli bir yoludur.
+filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5
+filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5
+
+
+# Sets store ... well sets
+empty_set = set()
+# Bir demek değer ile bir "set" oluşturmak
+some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])
+
+# Python 2.7'den beri {}'ler bir "set" tanımlaman için kullanılabilir
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Bir set'e daha fazla eleman eklemek
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# "&" işareti ile iki set'in kesişimlerini alınabilir
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# | işareti ile
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# "-" işareti ile iki set'in farkları alınabilir
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# "in" ile değerin set içerisinde olup olmadığını kontrol edebilirsiniz
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Akış Denetimi
+####################################################
+
+# Bir değişken oluşturmak
+some_var = 5
+
+# Buradaki bir if ifadesi. Girintiler(Intentation) Python'da önemlidir!
+# "some_var is smaller than 10" yazdırılır.
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # elif ifadesi isteğe bağlıdır
+ print "some_var is smaller than 10."
+else: # Bu da isteğe bağlıdır.
+ print "some_var is indeed 10."
+
+
+"""
+For döngüleri listeler üzerinde iterasyon yapar
+Ekrana yazdırılan:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # Biçimlendirmeleri string'e katmak için % kullanabilirsiniz
+ print "%s is a mammal" % animal
+
+"""
+"range(number)" ifadesi sıfırdan verilen sayıya kadar bir sayı listesi döner
+Ekrana yazdırılan:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+While döngüsü koşul sağlanmayana kadar devam eder
+Ekrana yazdırılan:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Shorthand for x = x + 1
+
+# try/except bloğu ile hatalar ayıklanabilir
+
+# Python 2.6 ve üstü için çalışacaktır:
+try:
+ # "raise" bir hata fırlatmak için kullanılabilir
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # Pass is just a no-op. Usually you would do recovery here.
+
+
+####################################################
+## 4. Fonksiyonlar
+####################################################
+
+
+# Yeni bir fonksiyon oluşturmak için "def" kullanılır
+def add(x, y):
+ print "x is %s and y is %s" % (x, y)
+ return x + y # Return values with a return statement
+
+# Fonksiyonu parametre ile çağırmak
+add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11
+
+# Diğer bir yol fonksiyonları anahtar argümanları ile çağırmak
+add(y=6, x=5) # Anahtar argümanlarının sırası farklı da olabilir
+
+# Değişken sayıda parametresi olan bir fonksiyon tanımlayabilirsiniz
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+# Değişken sayıda anahtar argümanlı parametre alan fonksiyonlar da
+# tanımlayabilirsiniz.
+def keyword_args(**kwargs):
+ return kwargs
+
+# Şu şekilde kullanılacaktır
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# Eğer isterseniz ikisini aynı anda da yapabilirsiniz
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Fonksiyonu çağırırken, args/kwargs'ın tam tersini de yapabilirsiniz!
+# Tüpü yaymak için * ve kwargs'ı yaymak için ** kullanın.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # foo(1, 2, 3, 4) ile eşit
+all_the_args(**kwargs) # foo(a=3, b=4) ile eşit
+all_the_args(*args, **kwargs) # foo(1, 2, 3, 4, a=3, b=4) ile eşit
+
+# Python first-class fonksiyonlara sahiptir
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Anonymous fonksiyonlar da vardır
+(lambda x: x > 2)(3) #=> True
+
+# Dahili yüksek seviye fonksiyonlar vardır
+map(add_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+
+# Map etme(maps) ve filtreleme(filtres) için liste kullanabiliriz.
+[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
+
+
+####################################################
+## 5. Sınıflar
+####################################################
+
+# We subclass from object to get a class.
+class Human(object):
+
+ # Bir sınıf özelliği. Bu sınıfın tüm "instance"larına paylaşılmıştır.
+ species = "H. sapiens"
+
+ # Basic initializer
+ def __init__(self, name):
+ # Metoda gelen argümanın değerini sınıfın elemanı olan "name"
+ # değişkenine atama
+ self.name = name
+
+ # Bir instance metodu. Tüm metodlar ilk argüman olarak "self"
+ # parametresini alır
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Bir sınıf metodu tüm "instance"lar arasında paylaşılır
+ # İlk argüman olarak sınıfı çağırarak çağrılırlar
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Bir statik metod bir sınıf ya da instance referansı olmadan çağrılır
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Bir sınıf örneği oluşturmak
+i = Human(name="Ian")
+print i.say("hi") # "Ian: hi" çıktısı verir
+
+j = Human("Joel")
+print j.say("hello") # "Joel: hello" çıktısı verir
+
+# Sınıf metodunu çağıralım
+i.get_species() #=> "H. sapiens"
+
+# Paylaşılan sınıf özellik değiştirelim.
+Human.species = "H. neanderthalensis"
+i.get_species() #=> "H. neanderthalensis"
+j.get_species() #=> "H. neanderthalensis"
+
+# Statik metodu çağırma
+Human.grunt() #=> "*grunt*"
+
+
+####################################################
+## 6. Modüller
+####################################################
+
+# Modülleri sayfaya dahil edebilirsiniz
+import math
+print math.sqrt(16) #=> 4
+
+# Modül içerisinden spesifik bir fonksiyonu getirebilirsiniz
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Modüldeki tüm fonksiyonları dahil edebilirsiniz
+# Uyarı: bu önerilmez
+from math import *
+
+# Modülün adını kısaltabilirsiniz
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Python modülleri sıradan python dosyalarıdır. Kendinize bir modül
+# yazabilirsiniz, ve dahil edebilirsiniz. Modülün adı ile dosya adı
+# aynı olmalıdır.
+
+# Modüllerde tanımlanmış fonksiyon ve metodları öğrenebilirsiniz.
+import math
+dir(math)
+
+
+
+```
+
+## Daha fazlası için hazır mısınız?
+
+### Ücretsiz Dökümanlar
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+
+### Dead Tree
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown
index 8f7cb2af..0af5bbe3 100644
--- a/zh-cn/go-zh.html.markdown
+++ b/zh-cn/go-zh.html.markdown
@@ -1,8 +1,8 @@
---
-名字:Go
-分类:编程语言
-文件名:learngo.go
-贡献者:
+language: Go
+lang: zh-cn
+filename: learngo.go
+contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["pantaovay", "https://github.com/pantaovay"]
---