summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--README.markdown4
-rw-r--r--c.html.markdown1
-rw-r--r--common-lisp.html.markdown31
-rw-r--r--de-de/bash-de.html.markdown84
-rw-r--r--de-de/git-de.html.markdown2
-rw-r--r--haxe.html.markdown776
-rw-r--r--hu-hu/go.html.markdown22
-rw-r--r--javascript.html.markdown2
-rw-r--r--julia.html.markdown2
-rw-r--r--matlab.html.markdown260
-rw-r--r--perl.html.markdown149
-rw-r--r--php.html.markdown5
-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/php-tr.html.markdown682
-rw-r--r--tr-tr/python-tr.html.markdown502
17 files changed, 2822 insertions, 94 deletions
diff --git a/README.markdown b/README.markdown
index 701b12d7..fe72df6c 100644
--- a/README.markdown
+++ b/README.markdown
@@ -12,10 +12,6 @@ Make a new file, send a pull request, and if it passes muster I'll get it up pro
Remember to fill in the "contributors" fields so you get credited
properly!
-### Requests
-
-We've had a ton of interest, b
-
### Contributing
All contributions welcome, from the tiniest typo to a brand new article. Translations
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
new file mode 100644
index 00000000..f2a57511
--- /dev/null
+++ b/de-de/bash-de.html.markdown
@@ -0,0 +1,84 @@
+---
+language: bash
+contributors:
+ - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["kultprok", "http://www.kulturproktologie.de"]
+filename: LearnBash-de.bash
+lang: de-de
+---
+
+```bash
+#!/bin/sh
+# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie
+# wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang
+# Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar
+
+# Ein einfaches Beispiel mit hello world:
+echo Hello, world!
+
+# Jeder Befehl fängt auf einer neuen Zeile oder nach einem Semikolon an:
+echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile'
+
+# Variablen deklariert man so:
+VARIABLE="irgendein String"
+
+# Aber nicht so:
+VARIABLE = "irgendein String"
+# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
+# weil es den Befehl nicht findet.
+
+# Eine Variable wird so benutzt:
+echo $VARIABLE
+echo "$VARIABLE"
+# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –,
+# dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen.
+
+# Einen Wert aus der Eingabe lesen:
+echo "Wie heisst du?"
+read NAME # Wir mussten nicht mal eine neue Variable deklarieren
+echo Hello, $NAME!
+
+# Wir haben die übliche if-Struktur:
+if true
+then
+ echo "Wie erwartet"
+else
+ echo "Und dies nicht"
+fi
+
+# Ausdrücke werden im folgenden Format festgehalten:
+echo $(( 10 + 5 ))
+
+# Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen.
+# Du kannst alle Dateien und Verzeichnisse im aktiven Verzeichnis mit ls auflisten:
+ls
+
+# Diese Befehle haben Optionen, die ihre Ausführung beeinflussen:
+ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf
+
+# Ergebnisse eines vorangegangenen Befehls können an den nächsten Befehl als Input übergeben werden.
+# Der grep-Befehl filtert den Input nach dem vorgegebenen Muster. So können wir alle
+# txt-Dateien im aktuellen Verzeichnis auflisten:
+ls -l | grep "\.txt"
+
+# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden:
+# Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse
+# im aktuellen Verzeichnis an.
+echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse."
+
+# Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält.
+case "$VARIABLE"
+in
+ # Liste der Fälle, die unterschieden werden sollen
+ 0) echo "Hier ist eine Null."
+ 1) echo "Hier ist eine Eins."
+ *) echo "Das ist nicht Null."
+esac
+
+# loops iterieren über die angegebene Zahl von Argumenten:
+# Der Inhalt von $VARIABLE wird dreimal ausgedruckt.
+for $VARIABLE in x y z
+do
+ echo "$VARIABLE"
+done
+```
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 471c7641..88f4a643 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -4,7 +4,7 @@ tool: git
contributors:
- ["Jake Prather", "http:#github.com/JakeHP"]
- ["kultprok", "http://www.kulturproktologie.de"]
-filename: LearnGit.txt
+filename: LearnGit-de.txt
lang: de-de
---
diff --git a/haxe.html.markdown b/haxe.html.markdown
new file mode 100644
index 00000000..f4694fcb
--- /dev/null
+++ b/haxe.html.markdown
@@ -0,0 +1,776 @@
+---
+language: haxe
+filename: LearnHaxe3.hx
+contributors:
+ - ["Justin Donaldson", "https://github.com/jdonaldson/"]
+---
+
+Haxe is a web-oriented language that provides platform support for C++, C#,
+Swf/ActionScript, Javascript, Java, and Neko byte code (also written by the
+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
+/*
+ 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
+
+ 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.
+
+ */
+
+// Double slashes like this will give a single-line comment
+
+
+/*
+ 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.
+
+/*
+ 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 like a "mixin". More on 'using' later.
+ */
+using StringTools;
+
+/*
+ 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
+ a static main function, and specify the class in the compiler arguments.
+ In this case, we've specified the "LearnHaxe3" class in the compiler
+ arguments above.
+ */
+ static function main(){
+
+ /*
+ Trace is the default method of printing haxe expressions to the
+ screen. Different targets will have different methods of
+ accomplishing this. E.g., java, c++, c#, etc. will print to std
+ out. Javascript will print to console.log, and flash will print to
+ an embedded TextField. All traces come with a default newline.
+ Finally, It's possible to prevent traces from showing by using the
+ "--no-traces" argument on the compiler.
+ */
+ trace("Hello World, with trace()!");
+
+ /*
+ Trace can handle any type of value or object. It will try to print
+ 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);
+
+ /*
+ 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');
+
+
+ //////////////////////////////////////////////////////////////////
+ // Types & Variables
+ //////////////////////////////////////////////////////////////////
+ trace("***Types & Variables***");
+
+ /*
+ 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");
+
+
+ /*
+ Haxe is statically typed, so "an_integer" is declared to have an
+ "Int" type, and the rest of the expression assigns the value "1" to
+ it. It's not necessary to declare the type in many cases. Here,
+ 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");
+
+ // The $type() method prints the type that the compiler assigns:
+ $type(another_integer);
+
+ // You can also represent integers with hexadecimal:
+ var hex_integer = 0xffffff;
+
+ /*
+ Haxe uses platform precision for Int and Float sizes. It also
+ uses the platform behavior for overflow.
+ (Other numeric types and behavior are possible using special
+ libraries)
+ */
+
+ /*
+ In addition to simple values like Integers, Floats, and Booleans,
+ Haxe provides standard library implementations for common data
+ structures like strings, arrays, lists, and maps:
+ */
+
+ 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
+ parts or all of the string.
+ (See also the StringBuf class).
+ */
+ var a_sub_string = a_string.substr(0,4);
+ 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.
+ */
+ var a = new Array<String>(); // an array that contains Strings
+ a[0] = 'foo';
+ trace(a.length + " is the value for a.length");
+ a[9] = 'bar';
+ trace(a.length + " is the value for a.length (after modification)");
+ trace(a[3] + " is the value for a[3]"); //null
+
+ /*
+ Arrays are *generic*, so you can indicate which values they contain
+ with a type parameter:
+ */
+ var a2 = new Array<Int>(); // an array of Ints
+ var a3 = new Array<Array<String>>(); // an Array of Arrays (of Strings).
+
+ /*
+ Maps are simple key/value data structures. The key and the value
+ can be of any type.
+ */
+ var m = new Map<String, Int>(); // The keys are strings, the values are Ints.
+ m.set('foo', 4);
+ // You can also use array notation;
+ m['bar'] = 5;
+ trace(m.exists('bar') + " is the value for m.exists('bar')");
+ trace(m.get('bar') + " is the value for m.get('bar')");
+ trace(m['bar'] + " is the value for m['bar']");
+
+ var m2 = ['foo' => 4, 'baz' => 6]; // Alternative map syntax
+ trace(m2 + " is the value for m2");
+
+ /*
+ Remember, you can use type inference. The Haxe compiler will
+ decide the type of the variable the first time you pass an
+ argument that sets a type parameter.
+ */
+ var m3 = new Map();
+ m3.set(6, 'baz'); // m3 is now a Map<Int,String>
+ trace(m3 + " is the value for m3");
+
+ /*
+ Haxe has some more common datastructures in the haxe.ds module, such as
+ List, Stack, and BalancedTree
+ */
+
+
+ //////////////////////////////////////////////////////////////////
+ // Operators
+ //////////////////////////////////////////////////////////////////
+ trace("***OPERATORS***");
+
+ // basic arithmetic
+ trace((4 + 3) + " is the value for (4 + 3)");
+ trace((5 - 1) + " is the value for (5 - 1)");
+ trace((2 * 4) + " is the value for (2 * 4)");
+ trace((8 / 4) + " is the value for (8 / 3) (division always produces Floats)");
+ trace((12 % 4) + " is the value for (12 % 4)");
+
+
+ //basic comparison
+ trace((3 == 2) + " is the value for 3 == 2");
+ trace((3 != 2) + " is the value for 3 != 2");
+ trace((3 > 2) + " is the value for 3 > 2");
+ trace((3 < 2) + " is the value for 3 < 2");
+ trace((3 >= 2) + " is the value for 3 >= 2");
+ trace((3 <= 2) + " is the value for 3 <= 2");
+
+ // standard bitwise operators
+ /*
+ ~ Unary bitwise complement
+ << Signed left shift
+ >> Signed right shift
+ >>> Unsigned right shift
+ & Bitwise AND
+ ^ Bitwise exclusive OR
+ | Bitwise inclusive OR
+ */
+
+ //increments
+ var i = 0;
+ trace("Increments and decrements");
+ trace(i++); //i = 1. Post-Incrementation
+ trace(++i); //i = 2. Pre-Incrementation
+ trace(i--); //i = 1. Post-Decrementation
+ trace(--i); //i = 0. Pre-Decrementation
+
+ //////////////////////////////////////////////////////////////////
+ // Control Structures
+ //////////////////////////////////////////////////////////////////
+ trace("***CONTROL STRUCTURES***");
+
+ // if statements
+ var j = 10;
+ if (j == 10){
+ trace("this is printed");
+ } else if (j > 10){
+ trace("not greater than 10, so not printed");
+ } else {
+ 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
+ var k = 0;
+ while(k < 100){
+ // trace(counter); // will print out numbers 0-99
+ k++;
+ }
+
+ // do-while loop
+ var l = 0;
+ do{
+ trace("do statement always runs at least once");
+ } while (i > 0);
+
+ // for loop
+ /*
+ There is no c-style for loop in Haxe, because they are prone
+ to error, and not necessary. Instead, Haxe has a much simpler
+ and safer version that uses Iterators (more on those later).
+ */
+ var m = [1,2,3];
+ for (val in m){
+ trace(val + " is the value for val in the m array");
+ }
+
+ // Note that you can iterate on an index using a range
+ // (more on ranges later as well)
+ var n = ['foo', 'bar', 'baz'];
+ for (val in 0...n.length){
+ trace(val + " is the value for val (an index for m)");
+ }
+
+
+ trace("Array Comprehensions");
+
+ // Array comprehensions give you the ability to iterate over arrays
+ // while also creating filters and modifications.
+ var filtered_n = [for (val in n) if (val != "foo") val];
+ trace(filtered_n + " is the value for filtered_n");
+
+ var modified_n = [for (val in n) val += '!'];
+ trace(modified_n + " is the value for modified_n");
+
+ var filtered_and_modified_n = [for (val in n) if (val != "foo") val += "!"];
+ trace(filtered_and_modified_n + " is the value for filtered_and_modified_n");
+
+ //////////////////////////////////////////////////////////////////
+ // Switch Statements (Value Type)
+ //////////////////////////////////////////////////////////////////
+ trace("***SWITCH STATEMENTS (VALUE TYPES)***");
+
+ /*
+ Switch statements in Haxe are very powerful. In addition to working
+ on basic values like strings and ints, they can also work on the
+ 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 = "";
+ switch(my_dog_name){
+ 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.
+
+ trace("My dog's name is" + my_dog_name
+ + ", and his favorite thing is a: "
+ + favorite_thing);
+
+ //////////////////////////////////////////////////////////////////
+ // Expression Statements
+ //////////////////////////////////////////////////////////////////
+ trace("***EXPRESSION STATEMENTS***");
+
+ /*
+ Haxe control statements are very powerful because every statement
+ is also an expression, consider:
+ */
+
+ // if statements
+ var k = if (true){
+ 10;
+ } else {
+ 20;
+ }
+
+ trace("K equals ", k); // outputs 10
+
+ var other_favorite_thing = switch(my_dog_name) {
+ case "fido" : "teddy";
+ case "rex" : "stick";
+ case "spot" : "football";
+ default : "some unknown treat";
+ }
+
+ trace("My dog's name is" + my_dog_name
+ + ", and his other favorite thing is a: "
+ + other_favorite_thing);
+
+ //////////////////////////////////////////////////////////////////
+ // Converting Value Types
+ //////////////////////////////////////////////////////////////////
+ trace("***CONVERTING VALUE TYPES***");
+
+ // You can convert strings to ints fairly easily.
+
+ // string to integer
+ Std.parseInt("0"); // returns 0
+ Std.parseFloat("0.4"); // returns 0.4;
+
+ // integer to string
+ Std.string(0); // returns "0";
+ // concatenation with strings will auto-convert to string.
+ 0 + ""; // returns "0";
+ 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 foo_instance = new FooClass(3);
+
+ // read the public variable normally
+ trace(foo_instance.public_any + " is the value for foo_instance.public_any");
+
+ // we can read this variable
+ trace(foo_instance.public_read + " is the value for foo_instance.public_read");
+ // but not write it
+ // 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
+
+
+ /*
+ 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();
+
+ }
+
+}
+
+/*
+ This is the "child class" of the main LearnHaxe3 Class
+ */
+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
+ public var property (get, set): Int; // use this style to enable getters/setters
+
+ // private variables are not available outside the class.
+ // see @:allow for ways around this.
+ var _private:Int; // variables are private if they are not marked public
+
+ // a public constructor
+ public function new(arg:Int){
+ super(); // call the constructor of the parent object, since we extended BarClass
+
+ this.public_any= 0;
+ this._private = arg;
+
+ }
+
+ // getter for _private
+ function get_property() : Int {
+ return _private;
+ }
+
+ // setter for _private
+ function set_property(val:Int) : Int {
+ _private = val;
+ return val;
+ }
+
+ // special function that is called whenever an instance is cast to a string.
+ public function toString(){
+ return _private + " with toString() method!";
+ }
+
+ // this class needs to have this function defined, since it implements
+ // the BarInterface interface.
+ public function baseFunction(x: Int) : String{
+ // convert the int to string automatically
+ return x + " was passed into baseFunction!";
+ }
+}
+
+/*
+ A simple class to extend
+*/
+class BarClass {
+ var base_variable:Int;
+ public function new(){
+ base_variable = 4;
+ }
+ public static function acceptBarInstance(b:BarClass){
+ }
+}
+
+/*
+ A simple interface to implement
+*/
+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 460e23ec..69849858 100644
--- a/hu-hu/go.html.markdown
+++ b/hu-hu/go.html.markdown
@@ -14,7 +14,7 @@ praktikus megoldást nyújt a valós, üzleti problémákra.
C-szerű szintaktikával és statikus típuskezeléssel rendelkezik.
A fordító szempillantás alatt végez és egy gyorsan futó,statikus futtatható állományt hoz létre.
-A nyelv könnyen érthető, üzenet-alapú konkurenciát tesz lehetővé, így könnyen ki lehet használni
+A nyelv könnyen érthető, folyamatok közötti csatornákon áthaladó üzenetekkel kommunikáló konkurens programozást tesz lehetővé, így könnyen ki lehet használni
a mai számítógépek több magos processzorait, ez nagy rendszerek építéséhez ideális.
A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van.
@@ -77,7 +77,7 @@ func learnMultiple(x, y int) (sum, prod int) {
// Beépített típusok
func learnTypes() {
- // Rövid deklarás az esetek többségében elég lesz a változókhoz
+ // Rövid deklarálás az esetek többségében elég lesz a változókhoz
s := "Tanulj Go-t!" // string típus
s2 := `A "nyers" stringekben lehetnek
@@ -90,7 +90,7 @@ func learnTypes() {
f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites
// lebegőpontos szám
- c := 3 + 4i // complex128, belsőleg két float64-el tárolva
+ c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva
// Var szintaxis változó típus definiálással
var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az
@@ -107,7 +107,7 @@ func learnTypes() {
// Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg
// vannak az előnyeik de a szeleteket sokkal gyakrabban használjuk.
- s3 := []int{4, 5, 9} // vesd össze a3-al, nincsenek pontok.
+ s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok.
s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva
var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva
bs := []byte("a slice") // típus konverzió szintaxisa
@@ -179,9 +179,9 @@ func learnFlowControl() {
break // csak vicceltem
continue // soha nem fut le
}
- // Akárcsak a for-nál, az if-ben is lehet rövid deklarással egy lokális
- // változót létrehozni ami az blokk összes if/else-n keresztül érvényes
- // marad.
+
+ //Akárcsak a for-nál, az if-nél is lehet rövid deklarálással egy lokális változót létrehozni,
+ //ami a blokk összes if/else szerkezetén keresztül érvényes marad.
if y := expensiveComputation(); y > x {
x = y
}
@@ -212,8 +212,7 @@ type pair struct {
x, y int
}
-// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer
-// interf
+// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt.
func (p pair) String() string { // p lesz a "vevő"
// Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s
// megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit
@@ -312,13 +311,13 @@ func learnWebProgramming() {
// A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd.
// Második paramétere egy interfész, pontosabban a http.Handler interfész.
err := http.ListenAndServe(":8080", pair{})
- fmt.Println(err) // nem felejtük el kiírni az esetleges hibákat!
+ fmt.Println(err) // nem felejtjük el kiírni az esetleges hibákat!
}
// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az
// egyetlen metódusát a ServeHTTP-t.
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-el
+ // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel
w.Write([]byte("Megtanultad a Go-t Y perc alatt!"))
}
```
@@ -333,3 +332,4 @@ A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és
Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a standard könyvtárban a legjobb praktikákat kilesheted.
TIPP: a dokumentációban kattints egy funkció nevére és rögtön megmutatja a hozzá tartozó kódot!
+Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a [gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel.
diff --git a/javascript.html.markdown b/javascript.html.markdown
index fb79949e..1dd6e2be 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -342,7 +342,7 @@ myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43
// We mentioned that __proto__ was non-standard, and there's no standard way to
-// change the prototype of an existing object. However, there's two ways to
+// change the prototype of an existing object. However, there are two ways to
// create a new object with a given prototype.
// The first is Object.create, which is a recent addition to JS, and therefore
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/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
new file mode 100644
index 00000000..18339dde
--- /dev/null
+++ b/perl.html.markdown
@@ -0,0 +1,149 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+---
+
+Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
+
+Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
+
+```perl
+# Single line comments start with a hash.
+
+
+#### Perl variable types
+
+# Variables begin with the $ symbol.
+# A valid variable name starts with a letter or underscore,
+# followed by any number of letters, numbers, or underscores.
+
+### Perl has three main variable types: scalars, arrays, and hashes.
+
+## Scalars
+# A scalar represents a single value:
+my $animal = "camel";
+my $answer = 42;
+
+# Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required.
+
+## Arrays
+# An array represents a list of values:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+
+
+## Hashes
+# A hash represents a set of key/value pairs:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# You can use whitespace and the "=>" operator to lay them out more nicely:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+ );
+# Scalars, arrays and hashes are documented more fully in perldata. (perldoc perldata).
+
+# More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes.
+
+#### Conditional and looping constructs
+
+# Perl has most of the usual conditional and looping constructs.
+
+if ( $var ) {
+ ...
+} elsif ( $var eq 'bar' ) {
+ ...
+} else {
+ ...
+}
+
+unless ( condition ) {
+ ...
+ }
+# This is provided as a more readable version of "if (!condition)"
+
+# the Perlish post-condition way
+print "Yow!" if $zippy;
+print "We have no bananas" unless $bananas;
+
+# while
+ while ( condition ) {
+ ...
+ }
+
+
+# for and foreach
+for ($i = 0; $i <= $max; $i++) {
+ ...
+ }
+
+foreach (@array) {
+ print "This element is $_\n";
+ }
+
+
+#### Regular expressions
+
+# Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in perlrequick, perlretut, and elsewhere. However, in short:
+
+# Simple matching
+if (/foo/) { ... } # true if $_ contains "foo"
+if ($a =~ /foo/) { ... } # true if $a contains "foo"
+
+# Simple substitution
+
+$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
+
+Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself.
+
+perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
+
+#### Further Reading
+
+ - [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/php.html.markdown b/php.html.markdown
index 083574ee..1cc6d2c5 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -176,6 +176,11 @@ $y = 0;
echo $x; // => 2
echo $z; // => 0
+// Dumps type and value of variable to stdout
+var_dumb($z); // prints int(0)
+
+// Prints variable to stdout in human-readable format
+print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
/********************************
* Logic
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/php-tr.html.markdown b/tr-tr/php-tr.html.markdown
new file mode 100644
index 00000000..94bc31ff
--- /dev/null
+++ b/tr-tr/php-tr.html.markdown
@@ -0,0 +1,682 @@
+---
+language: php
+filename: learnphp-tr.php
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+translators:
+ - ["Haydar KULEKCI", "http://scanf.info/"]
+lang: tr-tr
+---
+
+PHP 5+ versiyonu için geçerlidir.
+
+```php
+<?php // PHP kodları <?php etiketleri içerisinde bulunmalıdır.
+
+// Eğer php dosyanız sadece PHP kodu içeriyorsa, php'nin kapatma
+// etiketini kapatmayabilirsiniz.
+
+// // işareti ile tek satırlık yorum satırı başlar.
+
+# # işareti de aynı görevi görür ancak // daha genel kullanımdadır.
+
+
+
+/*
+ Çoklu satır kodu bu şekilde yazıyoruz. slash yıldız ile başlar
+ ve yıldız slash ile biter.
+*/
+
+// "echo" ya da "print" metodları çıktı almak için kullanılır.
+print('Hello '); // Ekrana Yeni satır karakteri olmadan "Hello "
+ // yazdırılır.
+
+// () parantezler "echo" ve "print" metodları için isteğe bağlıdır.
+echo "World\n"; // Ekrana yeni satır karakteri olmadan "World"
+ // yazdırılır.
+// (Bütün ifadeler noktalı virgül ile bitmelidir.)
+
+// <?php tagı dışarısındaki herşey otomatik olarak yazdırılacaktır.
+?>
+Hello World Again!
+<?php
+
+
+/************************************
+* Tipler ve Değişkenler
+*************************************/
+
+// Değişkenler $ sembolü ile başlar.
+// Geçerli bir değişken bir harf veya alt çizgi ile başlar,
+// devamında da bir sayı, harf veya alt çizgi ile devam eder.
+
+// Mantıksal değerler
+// Boolean values are harf büyüklüğüne duyarsızdır.
+$boolean = true; // veya TRUE veya True
+$boolean = false; // veya FALSE veya False
+
+// Tam Sayılar
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (öneki 0 olan sekizlik(octal) bir sayıyı gösterir)
+$int4 = 0x0F; // => 15 (öneki 0x olanlar hex sayıları gösterir.)
+
+// Kayan Noktalı Sayılar
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// Aritmetik
+$sum = 1 + 1; // 2
+$difference = 2 - 1; // 1
+$product = 2 * 2; // 4
+$quotient = 2 / 1; // 2
+
+// Aritmetik Kısayolları
+$number = 0;
+$number += 1; // $number değişkeninin değerini 1 artırır.
+echo $number++; // 1 yazdırılır. (Yazdırıldıktan sonra artırılır.)
+echo ++$number; // 3 yazdırılır. (yazdırılmadan önce artırılır.)
+$number /= $float; // Bölünür ve bölüm $number değerine eşitlenir.
+
+// Karakter dizileri(strings) tek tırnak ile kullanılmalıdır.
+$sgl_quotes = '$String'; // => '$String'
+
+// Bir değişken içermediği sürece çift tırnak kullanmaktan kaçının
+$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+
+// Özel karakterler sadece çift tırnak ile kullanılabilir.
+$escaped = "This contains a \t tab character.";
+$unescaped = 'This just contains a slash and a t: \t';
+
+// Gerekirse bir değişkeni küme ayracı içine alın.
+$money = "I have $${number} in the bank.";
+
+// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
+$nowdoc = <<<'END'
+Multi line
+string
+END;
+
+// Heredocs will do string interpolation
+$heredoc = <<<END
+Multi line
+$sgl_quotes
+END;
+
+// . işareti ile karakter dizileri birbirine birleştirilebilir.
+echo 'This string ' . 'is concatenated';
+
+
+/********************************
+ * Sabitler
+ */
+
+// Bir sabit define() metodu kullanılarak tanımlanır.
+// ve çalışma zamanından hiçbir zaman değişmez!
+
+// geçerli bir sabit bir harf veya altçizgi ile başlar,
+// ve bir sayı, harf ya da altçizgi ile devam eder.
+define("FOO", "something");
+
+// sabite ulaşmak için direk olarak seçilen ismi kullanabilirsiniz.
+echo 'This outputs '.FOO;
+
+
+/********************************
+ * Diziler
+ */
+
+// PHP'de bütün diziler ilişikilendirilebilirdir. (hashmaps),
+// İlişkilendirilebilir(associative) diziler, hashmap olarak bilinir.
+
+// PHP'nin bütün versiyonları için çalışır
+$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
+
+// PHP 5.4 ile yeni bir söz dizimi kullanılmaya başlandı
+$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
+
+echo $associative['One']; // 1 yazdıracaktır.
+
+// Liste kullanımında index'ler tam sayıdır.
+$array = ['One', 'Two', 'Three'];
+echo $array[0]; // => "One"
+
+
+/********************************
+ * Çıktı
+ */
+
+echo('Hello World!');
+// Hello World! çıktısı stdout'a yazdırılır.
+// Eğer bir web browser ile çalışıyorsanır Stdout bir web sayfasıdır.
+
+print('Hello World!'); // echo ile aynıdır.
+
+// Aslında echo bir dil sabitidir, parantezleri kullanmayabilirsiniz.
+echo 'Hello World!';
+print 'Hello World!'; // Bu yazdırılacaktır.
+
+$paragraph = 'paragraph';
+
+echo 100; // Echo ile doğrudan sayısal değer kullanımı
+echo $paragraph; // veya değişken
+
+// PHP 5.4.0 veya daha üstü sürümlerde kısa açılış etiketi
+// konfigürasyonları yapıldı ise, kısa açılış etiketini kullanabilirsiniz.
+?>
+<p><?= $paragraph ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // Şu anda $x değişkeni $y ile aynı değere sahiptir.
+$z = &$y;
+// $z, $y'nin referansını içermektedir.
+// $z'nin değerinin değişmesi $y'nin değerinide değiştireceltir veya
+// tam tersi. Ancak $x özgün değeri olarak kalacaktır.
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+/********************************
+ * Mantık
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// Argüman doğru değilse bir hata fırlatılacaktır.
+
+// Bu karşılaştırmalar tipler aynı olmasa bile her zaman true olacaktır.
+assert($a == $b); // equality
+assert($c != $a); // inequality
+assert($c <> $a); // alternative inequality
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// Aşağıdakiler yanlızca değer ve tip aynı olduğunda true olacaktır.
+assert($c === $d);
+assert($a !== $d);
+assert(1 == '1');
+assert(1 !== '1');
+
+// Değişkenler kullanıma bağlı olarak farklı tiplere çevrilebilir.
+
+$integer = 1;
+echo $integer + $integer; // => 2
+
+$string = '1';
+echo $string + $string; // => 2 (Karakter dizisi tam sayıya çevrilmeye zorlanır)
+
+$string = 'one';
+echo $string + $string; // => 0
+// Çıktı 0 olacaktır, çünkü + operatörü karakter dizisi olan 'one' değerini
+// bir sayıya çeviremez.
+
+// Veri tipi çevirileri bir değişkeni farklı bir türde
+// düzenlemek için kullanılabilir.
+
+$boolean = (boolean) 1; // => true
+
+$zero = 0;
+$boolean = (boolean) $zero; // => false
+
+// Veri tiplerini çevirmek için bazı fonksiyonlar vardır.
+$integer = 5;
+$string = strval($integer);
+
+$var = null; // Null değeri.
+
+
+/********************************
+ * Kontrol Yapıları
+ */
+
+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';
+}
+
+// Üçlü operatör
+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';
+}
+
+
+
+// Bu alternatif sözdizimi template'ler için kullanışlıdır.
+?>
+
+<?php if ($x): ?>
+This is displayed if the test is truthy.
+<?php else: ?>
+This is displayed otherwise.
+<?php endif; ?>
+
+<?php
+
+// Use switch to save some logic.
+switch ($x) {
+ case '0':
+ print 'Switch does type coercion';
+ break; // Bir breake yazmalısınız ya da 'two' ve 'three'
+ // durumunuda kapsarsınız.
+ case 'two':
+ case 'three':
+ // $variable değişkeni 'two' ya da 'three' ise
+ break;
+ default:
+ // Varsayılan olarak bir şey yap
+}
+
+// While, do...while ve for döngüleri tanıdıktır.
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // "01234" yazdırılacaktır
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // "01234" yazdırılacaktır.
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // "0123456789" yazdırılacaktır.
+
+echo "\n";
+
+$wheels = ['bicycle' => 2, 'car' => 4];
+
+// Foreach döngüsü diziler üzerinde çalışır
+foreach ($wheels as $wheel_count) {
+ echo $wheel_count;
+} // "24" yazdırılacaktır.
+
+echo "\n";
+
+// Key-Value değerlere ulaşabilirsiniz.
+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 döngüsünden çıkar
+ }
+ echo $i++;
+} // Prints "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Aktif döngüyü atlar
+ }
+ echo $i;
+} // "0124" yazdırılacaktır.
+
+
+
+/********************************
+ * Fonksiyonlar
+ */
+
+// Bir fonksiyon tanımlamak için "function" kullanılır:
+function my_function () {
+ return 'Hello';
+}
+
+echo my_function(); // => "Hello"
+
+// Geçerli bir fonksiyon ismi bir harf veya altçizgi ile başlar ve
+// bir sayı, harf ya da alt çizgi ile devam eder.
+
+function add ($x, $y = 1) { // $y değeri isteğe bağlıdır ve
+ // varsayılan değeri 1'dir
+ $result = $x + $y;
+ return $result;
+}
+
+echo add(4); // => 5
+echo add(4, 2); // => 6
+
+// $result fonksiyon dışında ulaşılabilir değildir.
+// print $result; // Bir uyarı verecektir.
+
+// PHP 5.3'den beri bir anonymous fonksiyon tanımlayabilirsiniz;
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// Fonksiyonlar bir fonksiyon dönebilir.
+function bar ($x, $y) {
+ // Fonksiyona dışardan değişken gönderebilmek için 'use' komutunu kullanın.
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // "A - B - C" yazdırılacaktır.
+
+// Fonksiyonun ismini karakter dizinden çağırabilirsiniz.
+$function_name = 'add';
+echo $function_name(1, 2); // => 3
+// Programatik olarak fonksiyonları çalıştırmak için yararlı olabilir
+// veya, call_user_func(callable $callback [, $parameter [, ... ]]); kulanın.
+
+
+/********************************
+ * Includes
+ */
+
+<?php
+// PHP'de include edilecek dosyalar PHP açma etiketi ile başlamalı. (!)
+
+include 'my-file.php';
+// my-file.php dosyasındaki kodlar artık mevcut scope'da kullanılabilir.
+// Eğer dosya include edilemezse bir uyarı (örneğin: file not found)
+// fırlatılacaktır.
+
+include_once 'my-file.php';
+// Eğer bir dosya include edildi ise tekrar include edilmeyecektir.
+// Bu çoklu class tanımlama hatalarını önler.
+
+require 'my-file.php';
+require_once 'my-file.php';
+// Dosya include edilemediğinde fatal error veren require() bu konu
+// dışında include() ile aynıdır.
+
+// my-include.php dosyasının içeriği:
+<?php
+
+return 'Anything you like.';
+// Dosya sonu
+
+// Include'lar ver require'lar aynı zamanda bir return dönebilir.
+$value = include 'my-include.php';
+
+// Dosyalar verilen dosya yoluna göre include edilir veya, hiçbirşey
+// verilmezse include_path konfigürasyonuna göre include edecektir.
+// Eğer dosya include_path'da da bulunamazsa include hata vermeden
+// önce içinde bulunulan dizini kontrol ecektir.
+/* */
+
+
+/********************************
+ * Sınıflar
+ */
+
+// Sınıflar class kelimesi ile tanımlanır
+
+class MyClass
+{
+ const MY_CONST = 'value'; // Bir sabit
+
+ static $staticVar = 'static';
+
+ // Static değişkenler ve onların görünürlüğü
+ public static $publicStaticVar = 'publicStatic';
+ private static $privateStaticVar = 'privateStatic';
+ // Sadece bu sınıf içerisinde erişilebilir
+ protected static $protectedStaticVar = 'protectedStatic';
+ // Bu sınıf ve alt sınıflarından erişilebilir
+
+ // Özellikler görünürlüğü ile birlikte tanımlanmalıdır.
+ public $property = 'public';
+ public $instanceProp;
+ protected $prot = 'protected'; // Sınıf ve alt sınıflardan erişilebilir
+ private $priv = 'private'; // Sadece bu sınıftan erişilebilir
+
+ // __construct ile bir constructor oluşturulabilir.
+ public function __construct($instanceProp) {
+ // $this ile instance değişkenine erişilir.
+ $this->instanceProp = $instanceProp;
+ }
+
+ // Sınıfın içerisinde metodlar fonksiyonlar gibi tanımlanır.
+ public function myMethod()
+ {
+ print 'MyClass';
+ }
+
+ final function youCannotOverrideMe()
+ {
+ }
+
+ public static function myStaticMethod()
+ {
+ print 'I am static';
+ }
+}
+
+echo MyClass::MY_CONST; // 'value' şeklinde çıktı verir;
+echo MyClass::$staticVar; // 'static' şeklinde çıktı verir;
+MyClass::myStaticMethod(); // 'I am static' şeklinde çıktı verir;
+
+// Sınıfların new ile kullanımı
+$my_class = new MyClass('An instance property');
+// Eğer argüman göndermeyeceksek parantezler isteğe bağlıdır.
+
+// Sınıfın üyelerine erişim ->
+echo $my_class->property; // => "public"
+echo $my_class->instanceProp; // => "An instance property"
+$my_class->myMethod(); // => "MyClass"
+
+
+// "extends" ile sınıfı extend etmek
+class MyOtherClass extends MyClass
+{
+ function printProtectedProperty()
+ {
+ echo $this->prot;
+ }
+
+ // Bir methodu ezmek
+ function myMethod()
+ {
+ parent::myMethod();
+ print ' > MyOtherClass';
+ }
+}
+
+$my_other_class = new MyOtherClass('Instance prop');
+$my_other_class->printProtectedProperty(); // "protected" şeklinde çıktı verir.
+$my_other_class->myMethod(); // "MyClass > MyOtherClass" şeklinde çıktı verir
+
+final class YouCannotExtendMe
+{
+}
+
+// getter ve setter'ları oluşturmak için "magic method"ları kullanabilirsiniz.
+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() metodunu kullanacaktır.
+$x->property = 'Something'; // __set() metodunu kullanacaktır.
+
+// Sınıflar abstract olabilir(abstract kelimesini kullanarak) veya
+// interface'ler uygulanabilir (implements kelimesi kullanılarak).
+// Bir interface "interface" kelimesi kullanılarak oluşturulur.
+
+interface InterfaceOne
+{
+ public function doSomething();
+}
+
+interface InterfaceTwo
+{
+ public function doSomethingElse();
+}
+
+// interfaces can be extended
+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';
+ }
+}
+
+
+// Sınıflar birden fazla interface kullanabilir.
+class SomeOtherClass implements InterfaceOne, InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo 'doSomething';
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+
+
+/********************************
+ * Traits
+ */
+// Trait'ler PHP 5.4.0'dan beri kullanılabilir ve "trait" kullanılarak
+// tanımlanır.
+
+trait MyTrait
+{
+ public function myTraitMethod()
+ {
+ print 'I have MyTrait';
+ }
+}
+
+class MyTraitfulClass
+{
+ use MyTrait;
+}
+
+$cls = new MyTraitfulClass();
+$cls->myTraitMethod(); // "I have MyTrait" çıktısını verir.
+
+
+
+/********************************
+ * İsim Uzayları
+ */
+
+// Bu alan ayrılmıştır, çünkü isim uzayı tanımı bir dosyada en başta
+// yapılmalıdır. Bu örnekte böyle olmadığını varsayalım.
+
+<?php
+
+// Varsayılan olarak, sınıflar global isim uzayındadır, ve açıkça bir
+// ters slash ile çağrılabilir.
+
+$cls = new \MyClass();
+
+
+
+// Bir dosya için isim uzayı atama
+namespace My\Namespace;
+
+class MyClass
+{
+}
+
+// (diğer bir dosya)
+$cls = new My\Namespace\MyClass;
+
+//veya diğer bir isim uzayında.
+namespace My\Other\Namespace;
+
+use My\Namespace\MyClass;
+
+$cls = new MyClass();
+
+// veya isim uzayına bir takma isim koyabilirsiniz.
+
+namespace My\Other\Namespace;
+
+use My\Namespace as SomeOtherNamespace;
+
+$cls = new SomeOtherNamespace\MyClass();
+
+*/
+
+```
+
+## Daha fazla bilgi
+
+Referans ve topluluk yazıları için [official PHP documentation](http://www.php.net/manual/) adresini ziyaret edin.
+
+Gncel en yi örnekler için [PHP Usulüne Uygun](http://kulekci.net/php-the-right-way/) adresini ziyaret edin.
+
+Eğer bir paket yöneticisi olan dil kullandıysanız, [Composer](http://getcomposer.org/)'a bir göz atın.
+
+Genel standartlar için PHP Framework Interoperability Group'unun [PSR standards](https://github.com/php-fig/fig-standards) ziyaret edebilirsiniz.
+
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)