summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--README.markdown4
-rw-r--r--bash.html.markdown11
-rw-r--r--brainfuck.html.markdown79
-rw-r--r--c.html.markdown1
-rw-r--r--common-lisp.html.markdown31
-rw-r--r--de-de/bash-de.html.markdown92
-rw-r--r--de-de/git-de.html.markdown4
-rw-r--r--de-de/javascript-de.html.markdown449
-rw-r--r--es-es/clojure-es.html.markdown395
-rw-r--r--git.html.markdown3
-rw-r--r--haxe.html.markdown776
-rw-r--r--hu-hu/go.html.markdown24
-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.markdown19
-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--ruby.html.markdown18
-rw-r--r--tr-tr/php-tr.html.markdown682
-rw-r--r--tr-tr/python-tr.html.markdown502
-rw-r--r--zh-cn/go-zh.html.markdown8
24 files changed, 3796 insertions, 109 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/bash.html.markdown b/bash.html.markdown
index 7421f880..76c794c6 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -1,12 +1,10 @@
---
-
category: tool
tool: bash
contributors:
- ["Max Yankov", "https://github.com/golergka"]
- ["Darren Lin", "https://github.com/CogBear"]
filename: LearnBash.sh
-
---
Bash is a name of the unix shell, which was also distributed as the shell for the GNU operating system and as default shell on Linux and Mac OS X.
@@ -75,12 +73,11 @@ ls -l | grep "\.txt"
echo "There are $(ls | wc -l) items here."
# Bash uses a case statement that works similarily to switch in Java and C++:
-case "$VARIABLE"
-in
+case "$VARIABLE" in
#List patterns for the conditions you want to meet
- 0) echo "There is a zero."
- 1) echo "There is a one."
- *) echo "It is not null."
+ 0) echo "There is a zero.";;
+ 1) echo "There is a one.";;
+ *) echo "It is not null.";;
esac
#For loops iterate for as many arguments given:
diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown
new file mode 100644
index 00000000..2b7ce4db
--- /dev/null
+++ b/brainfuck.html.markdown
@@ -0,0 +1,79 @@
+---
+language: brainfuck
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io"]
+---
+
+Brainfuck is an extremely minimal programming language (just 8 commands) and
+is Turing complete.
+
+```
+Any character not "><+-.,[]" (excluding quotation marks) is ignored.
+
+Brainfuck is represented by an array with 30,000 cells initialized to zero
+and a data pointer pointing at the current cell.
+
+There are eight commands:
++ : Increments the value at the current cell by one.
+- : Decrements the value at the current cell by one.
+> : Moves the data pointer to the next cell (cell on the right).
+< : Moves the data pointer to the previous cell (cell on the left).
+. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
+, : Reads a single input character into the current cell.
+[ : If the value at the current cell is zero, skips to the corresponding ] .
+ Otherwise, move to the next instruction.
+] : If the value at the current cell is zero, move to the next instruction.
+ Otherwise, move backwards in the instructions to the corresponding [ .
+
+[ and ] form a while loop. Obviously, they must be balanced.
+
+Let's look at some basic Brainfuck programs.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+This program prints out the letter 'A'. First, it increments cell #1 to 6.
+Cell #1 will be used for looping. Then, it enters the loop ([) and moves
+to cell #2. It increments cell #2 10 times, moves back to cell #1, and
+decrements cell #1. This loop happens 6 times (it takes 6 decrements for
+cell #1 to reach 0, at which point it skips to the corresponding ] and
+continues on).
+
+At this point, we're on cell #1, which has a value of 0, while cell #2 has a
+value of 60. We move on cell #2, increment 5 times, for a value of 65, and then
+print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal.
+
+
+, [ > + < - ] > .
+
+This program reads a character from the user input, copies the character into
+another cell, and prints out the same character.
+
+, reads in a character from the user into cell #1. Then we start a loop. Move
+to cell #2, increment the value at cell #2, move back to cell #1, and decrement
+the value at cell #1. This continues on until cell #1 is 0, and cell #2 holds
+cell #1's old value. Because we're on cell #1 at the end of the loop, move to
+cell #2, and then print out the value in ASCII.
+
+Also keep in mind that the spaces are purely for readibility purposes. You
+could just as easily write it as
+
+,[>+<-]>.
+
+
+Try and figure out what this program does:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+This program takes two numbers for input, and multiplies them.
+
+The gist is it first reads in two inputs. Then it starts the outer loop,
+conditioned on cell #1. Then it moves to cell #2, and starts the inner
+loop conditioned on cell #2, incrementing cell #3. However, there comes a
+problem: at the end of the inner loop, cell #2 is zero. To solve this problem,
+we also increment cell #4, and then recopy cell #4 into cell #2.
+```
+
+And that's Brainfuck. Not that hard, eh? For fun, you can write your own
+Brainfuck programs, or you can write a Brainfuck interpreter in another
+language. The interpreter is fairly simple to implement, but if you're a
+masochist, trying writing a Brainfuck interpreter... in Brainfuck.
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..9e3d7bc8
--- /dev/null
+++ b/de-de/bash-de.html.markdown
@@ -0,0 +1,92 @@
+---
+category: tool
+tool: bash
+lang: de-de
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+translators:
+ - ["kultprok", "http://www.kulturproktologie.de"]
+filename: LearnBash-de.sh
+---
+
+Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde.
+Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden.
+
+[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/sh
+# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie
+# 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..10deefd5 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -2,9 +2,9 @@
category: tool
tool: git
contributors:
- - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"]
+translators:
- ["kultprok", "http://www.kulturproktologie.de"]
-filename: LearnGit.txt
lang: de-de
---
diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown
new file mode 100644
index 00000000..56a41af0
--- /dev/null
+++ b/de-de/javascript-de.html.markdown
@@ -0,0 +1,449 @@
+---
+language: JavaScript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["ggb", "http://www.ideen-und-soehne.de"]
+filename: learnjavascript.js
+lang: de-de
+---
+
+(Anmerkungen des Original-Autors:)
+JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzent zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java.
+
+Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, dass eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer.
+
+Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.id.au).
+
+```js
+// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei
+// Slashes
+/* während mehrzeilige Kommentare mit einem
+Slash und einem Stern anfangen und enden */
+
+// Statements können mit einem Semikolon beendet werden
+machWas();
+
+// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn
+// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen.
+machWas()
+
+// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist
+// es besser die Semikola immer zu setzen.
+
+///////////////////////////////////
+// 1. Nummern, Strings und Operationen
+
+// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double).
+3; // = 3
+1.5; // = 1.5
+
+// Alle grundlegenden arithmetischen Operationen arbeiten wie erwartet.
+1 + 1; // = 2
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Division funktioniert auch mit einem Ergebnis nach dem Komma.
+5 / 2; // = 2.5
+
+// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation
+// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit
+// Vorzeichen) umgewandelt.
+1 << 2; // = 4
+
+// Die Rangfolge der Operationen kann mit Klammern erzwungen werden.
+(1 + 3) * 2; // = 8
+
+// Es gibt drei spezielle, nicht-reale Nummern-Werte:
+Infinity; // Ergebnis von z. B. 1 / 0
+-Infinity; // Ergebnis von z. B. -1 / 0
+NaN; // Ergebnis von z. B. 0 / 0
+
+// Es gibt auch einen Boolean-Typ (für Wahrheitswerte).
+true;
+false;
+
+// Strings werden mit ' oder " erzeugt.
+'abc';
+"Hello, world";
+
+// Für die Negation wird das ! benutzt.
+!true; // = false
+!false; // = true
+
+// Gleichheit wird mit == geprüft.
+1 == 1; // = true
+2 == 1; // = false
+
+// Ungleichheit wird mit != überprüft.
+1 != 1; // = false
+2 != 1; // = true
+
+// Andere Vergleichsoperatoren sind
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Strings können mit + verbunden
+"Hello " + "world!"; // = "Hello world!"
+
+// und mit < und > verglichen werden.
+"a" < "b"; // = true
+
+// Für den Vergleich von Werten wird eine Typumwandlung erzwungen...
+"5" == 5; // = true
+
+// ...solange man nicht === verwendet.
+"5" === 5; // = false
+
+// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode
+// charAt zugegriffen werden
+"This is a string".charAt(0); // = "T"
+
+// Es gibt außerdem die Werte 'null' und 'undefined'
+null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen
+undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht
+ // verfügbar ist (obwohl genau genommen undefined selbst einen Wert
+ // darstellt)
+
+// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist
+// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0".
+
+///////////////////////////////////
+// 2. Variablen, Arrays und Objekte
+
+// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren
+// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer
+// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =.
+var einWert = 5;
+
+ // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler
+einAndererWert = 10;
+
+// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext,
+// in dem sie erzeugt wurde.
+
+// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den
+// Wert 'undefined'.
+var einDritterWert; // = undefined
+
+// Es existiert eine Kurzform, um mathematische Operationen mit Variablen
+// auszuführen:
+einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10
+einWert *= 10; // einWert ist nach dieser Operation 100
+
+// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren
+// oder zu subtrahieren
+einWert++; // nun ist einWert 101
+einWert--; // wieder 100
+
+// Arrays sind geordnete Listen von Werten irgendeines Typs
+var myArray = ["Hello", 45, true];
+
+// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index
+// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung
+// beginnt bei 0.
+myArray[1]; // = 45
+
+// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen
+// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare.
+var myObj = { key1: "Hello", key2: "World" };
+
+// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt,
+// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von
+// jedem Typ sein.
+var myObj = { myKey: "myValue", "my other key": 4 };
+
+// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen
+// werden,
+myObj["my other key"]; // = 4
+
+// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt
+// sich bei dem Schlüssel um einen validen Bezeichner.
+myObj.myKey; // = "myValue"
+
+// Objekte sind veränderlich, Werte können verändert und neue Schlüssel
+// hinzugefügt werden.
+myObj.myThirdKey = true;
+
+// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein
+// undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logik und Kontrollstrukturen
+
+// Die if-Struktur arbeitet, wie man es erwartet.
+var count = 1;
+if (count == 3){
+ // wird evaluiert, wenn count gleich 3 ist
+} else if (count == 4) {
+ // wird evaluiert, wenn count gleich 4 ist
+} else {
+ // wird evaluiert, wenn es weder 3 noch 4 ist
+}
+
+// Genauso 'while'.
+while (true) {
+ // Eine unendliche Schleife!
+}
+
+// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie
+// immer mindestens einmal ausgeführt werden.
+var input;
+do {
+ input = getInput();
+} while ( !isValid( input ) )
+
+// Die for-Schleife arbeitet genau wie in C und Java:
+// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird;
+// Iteration.
+for ( var i = 0; i < 5; i++ ) {
+ // wird 5-mal ausgeführt
+}
+
+// '&&' ist das logische und, '||' ist das logische oder
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+ // Die Größe des Hauses ist groß und die Farbe blau.
+}
+if (colour == "red" || colour == "blue"){
+ // Die Farbe ist entweder rot oder blau.
+}
+
+// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die
+// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist
+// nützlich, um einen Default-Wert zu setzen.
+var name = otherName || "default";
+
+///////////////////////////////////
+// 4. Funktionen, Geltungsbereich und Closures
+
+// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie
+// Variablen verwendet und als Parameter anderen Funktionen übergeben werden
+// - zum Beispiel, um einen 'event handler' zu 'beliefern'.
+function myFunction() {
+ // wird ausgeführt, nachdem 5 Sekunden vergangen sind
+}
+setTimeout(myFunction, 5000);
+
+// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen.
+// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument
+// einer anderen Funktion zu definieren.
+setTimeout(function() {
+ // wird ausgeführt, nachdem 5 Sekunden vergangen sind
+}, 5000);
+
+// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt:
+// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht.
+if(true) {
+ var i = 5;
+}
+i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die
+ // ihren Geltungsbereich nach Blöcken richtet
+
+// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme
+// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen
+// 'verschmutzt' wird.
+(function(){
+ var temporary = 5;
+ // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden,
+ // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist
+ // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js,
+ // kann das anders aussehen).
+ window.permanent = 10;
+})();
+temporary; // wirft einen ReferenceError
+permanent; // = 10
+
+// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird
+// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die
+// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann,
+// wenn die äußere Funktion beendet wurde.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds
+ // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein'
+ // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere
+ // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die
+ // Variable prompt.
+}
+sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der
+ // Nachricht "Hello, Adam!" öffnen.
+
+///////////////////////////////////
+// 5. Mehr über Objekte, Konstruktoren und Prototypen
+
+// Objekte können Funktionen enthalten.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie
+// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen
+// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht
+// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen
+// wird.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch
+// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem
+// Objekt nach dessen Definition zugewiesen wird.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird
+// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser
+// Art aufgerufen zu werden, werden Konstruktoren genannt.
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine
+// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert,
+// schaut der Interpreter in dessen Prototyp nach.
+
+// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den
+// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das
+// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil
+// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir
+// später.
+var myObj = {
+ myString: "Hello world!",
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Das funktioniert auch bei Funktionen.
+myObj.myFunc(); // = "hello world!"
+
+// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann
+// wird im Prototypen des Prototypen nachgesehen und so weiter.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz
+// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann
+// werden die Änderungen überall sichtbar.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es
+// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts
+// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem
+// gegebenen Prototypen erzeugt.
+
+// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des
+// JavaScript-Standards ist und daher noch nicht in allen Implementierungen
+// verfügbar.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun.
+// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es
+// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt
+// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es
+// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird.
+myConstructor.prototype = {
+ getMyNumber: function(){
+ return this.myNumber
+ }
+};
+var myNewObj2 = new myConstructor();
+myNewObj2.getMyNumber(); // = 5
+
+// Die eingebauten Typen, also strings und numbers, haben auch Konstruktoren,
+// die zu dem Typ äquivalente Wrapper-Objekte erzeugen.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Genau genommen: Sie sind nicht exakt äquivalent.
+typeof(myNumber); // = 'number'
+typeof(myNumberObj); // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
+}
+if (Number(0)){
+ // Dieser Teil des Codes wird ausgeführt, weil Number(0) zu wahr evaluiert.
+}
+
+// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen
+// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen
+// hinzuzufügen.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling'
+// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren
+// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in
+// älteren Umgebungen und Browsern verwendet werden können.
+
+// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in
+// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem
+// 'polyfill':
+if (Object.create === undefined){ // überschreib nichts, was eventuell bereits
+ // existiert
+ Object.create = function(proto){
+ // erstelle einen vorübergehenden Konstruktor mit dem richtigen
+ // Prototypen
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // verwende es dann, um ein neues Objekt mit einem passenden
+ // Prototypen zurückzugeben
+ return new Constructor();
+ }
+}
+```
+
+## Zur weiteren Lektüre (englisch)
+
+Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat.
+
+MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus.
+
+Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen.
+
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache.
+
+Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. \ No newline at end of file
diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown
new file mode 100644
index 00000000..7102b361
--- /dev/null
+++ b/es-es/clojure-es.html.markdown
@@ -0,0 +1,395 @@
+---
+language: clojure
+filename: learnclojure-es.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Antonio Hernández Blas", "https://twitter.com/nihilipster"]
+lang: es-es
+---
+
+Clojure es un lenguaje de la familia Lisp desarrollado para la Máquina Virtual
+de Java. Tiene un énfasis más fuerte en la [programación funcional](https://es.wikipedia.org/wiki/Programación_funcional) pura
+que Common Lisp, pero incluye varias facilidades de [SMT](https://es.wikipedia.org/wiki/Memoria_transacional) para manipular
+el estado según se presente.
+
+Esta combinación le permite manejar el procesamiento concurrente muy simple,
+y a menudo automáticamente.
+
+(Necesitas la versión de Clojure 1.2 o nueva)
+
+
+```clojure
+; Los comentatios inician con punto y coma.
+
+; Clojure es escrito en "forms" (patrones), los cuales son solo
+; listas de objectos dentro de paréntesis, separados por espacios en blanco.
+
+; El reader (lector) de Clojure asume que el primer objeto es una
+; función o una macro a llamar, y que el resto son argumentos.
+
+; La primera llamada en un archivo debe ser ns, para establecer el espacio de
+; nombre
+(ns learnclojure)
+
+; Más ejemplos básicos:
+
+; str creará una cadena de caracteres a partir de sus argumentos
+(str "Hello" " " "World") ; => "Hello World"
+
+; Las matemáticas son sencillas
+(+ 1 1) ; => 2
+(- 2 1) ; => 1
+(* 1 2) ; => 2
+(/ 2 1) ; => 2
+
+; La igualdad es =
+(= 1 1) ; => true
+(= 2 1) ; => false
+
+; Necesitas de la negación para la lógica, también
+(not true) ; => false
+
+; Los patrones anidados funcionan como lo esperas
+(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2
+
+; Tipos
+;;;;;;;;;;;;;
+
+; Clojure usa los tipos de objetos de Java para booleanos,cadenas de
+; caracteres y números.
+; Usa class para inspeccionarlos.
+(class 1); Los enteros literales son java.lang.Long por default
+(class 1.); Los flotantes literales son java.lang.Double
+(class ""); Las cadenas de caracteres van entre comillas dobles, y son
+; son java.lang.String
+(class false); Los Booleanos son java.lang.Boolean
+(class nil); El valor "null" es llamado nil
+
+; Si quieres crear una lista literal de datos, precede la con una comilla
+; simple para evitar su evaluación
+'(+ 1 2) ; => (+ 1 2)
+; (abreviatura de (quote (+ 1 2))
+
+; Puedes evaluar una lista precedida por comilla simple con eval
+(eval '(+ 1 2)) ; => 3
+
+; Colecciones & Secuencias
+;;;;;;;;;;;;;;;;;;;
+
+; Las Listas están basadas en listas enlazadas, mientras que los Vectores en
+; arreglos.
+; ¡Los Vectores y las Listas son clases de Java también!
+(class [1 2 3]); => clojure.lang.PersistentVector
+(class '(1 2 3)); => clojure.lang.PersistentList
+
+; Una lista podría ser escrita como (1 2 3), pero debemos precidirla con
+; comilla simple para evitar que el lector piense que es una función.
+; Además, (list 1 2 3) es lo mismo que '(1 2 3)
+
+; Las "Colecciones" son solo grupos de datos
+; Tanto las listas como los vectores son colecciones:
+(coll? '(1 2 3)) ; => true
+(coll? [1 2 3]) ; => true
+
+; Las "Secuencias" (seqs) son descripciones abstractas de listas de datos.
+; Solo las listas son seqs.
+(seq? '(1 2 3)) ; => true
+(seq? [1 2 3]) ; => false
+
+; Una seq solo necesita proporcionar una entrada cuando es accedida.
+; Así que, las seqs pueden ser perezosas -- pueden establecer series infinitas:
+(range 4) ; => (0 1 2 3)
+(range) ; => (0 1 2 3 4 ...) (una serie infinita)
+(take 4 (range)) ; (0 1 2 3)
+
+; Usa cons para agregar un elemento al inicio de una lista o vector
+(cons 4 [1 2 3]) ; => (4 1 2 3)
+(cons 4 '(1 2 3)) ; => (4 1 2 3)
+
+; conj agregará un elemento a una colección en la forma más eficiente.
+; Para listas, se agrega al inicio. Para vectores, al final.
+(conj [1 2 3] 4) ; => [1 2 3 4]
+(conj '(1 2 3) 4) ; => (4 1 2 3)
+
+; Usa concat para concatenar listas o vectores
+(concat [1 2] '(3 4)) ; => (1 2 3 4)
+
+; Usa filter, map para actuar sobre colecciones
+(map inc [1 2 3]) ; => (2 3 4)
+(filter even? [1 2 3]) ; => (2)
+
+; Usa reduce para reducirlos
+(reduce + [1 2 3 4])
+; = (+ (+ (+ 1 2) 3) 4)
+; => 10
+
+; reduce puede tomar un argumento como valor inicial también
+(reduce conj [] '(3 2 1))
+; = (conj (conj (conj [] 3) 2) 1)
+; => [3 2 1]
+
+; Funciones
+;;;;;;;;;;;;;;;;;;;;;
+
+; Usa fn para crear nuevas funciones. Una función siempre regresa
+; su última expresión
+(fn [] "Hello World") ; => fn
+
+; (Necesitas encerrarlo en paréntesis para llamarlo)
+((fn [] "Hello World")) ; => "Hello World"
+
+; Puedes crear una var (variable) usando def
+(def x 1)
+x ; => 1
+
+; Asigna una función a una var
+(def hello-world (fn [] "Hello World"))
+(hello-world) ; => "Hello World"
+
+; Puedes acortar este proceso al usar defn
+(defn hello-world [] "Hello World")
+
+; El [] es el vector de argumentos para la función.
+(defn hello [name]
+ (str "Hello " name))
+(hello "Steve") ; => "Hello Steve"
+
+; Puedes usar también esta abreviatura para crear funciones:
+(def hello2 #(str "Hello " %1))
+(hello2 "Fanny") ; => "Hello Fanny"
+
+; Puedes tener funciones multi-variadic (múltiple numero variable de
+; argumentos), también
+(defn hello3
+ ([] "Hello World")
+ ([name] (str "Hello " name)))
+(hello3 "Jake") ; => "Hello Jake"
+(hello3) ; => "Hello World"
+
+; Las funciones pueden colocar argumentos extras dentro de una seq por ti
+(defn count-args [& args]
+ (str "You passed " (count args) " args: " args))
+(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"
+
+; Puedes mezclar argumentos regulares y dentro de una seq
+(defn hello-count [name & args]
+ (str "Hello " name ", you passed " (count args) " extra args"))
+(hello-count "Finn" 1 2 3)
+; => "Hello Finn, you passed 3 extra args"
+
+
+; Mapas
+;;;;;;;;;;
+
+; Mapas de Hash y mapas de Arreglos comparten una interfaz. Los mapas de Hash
+; tienen búsquedas más rápidas pero no mantienen el orden de las llaves.
+(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap
+(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap
+
+; Los mapas de Arreglos serán convertidos en mapas de Hash en la mayoría de
+; operaciones si crecen lo suficiente, así que no necesitas preocuparte.
+
+; Los mapas pueden usar cualquier tipo para sus llaves, pero usualmente las
+; keywords (llaves) son mejor.
+; Las keywords son como cadenas de caracteres con algunas ventajas en eficiencia
+(class :a) ; => clojure.lang.Keyword
+
+(def stringmap {"a" 1, "b" 2, "c" 3})
+stringmap ; => {"a" 1, "b" 2, "c" 3}
+
+(def keymap {:a 1, :b 2, :c 3})
+keymap ; => {:a 1, :c 3, :b 2}
+
+; Por cierto, las comas son siempre tratadas como espacios en blanco y no hacen
+; nada.
+
+; Recupera un valor de un mapa tratando la como una función
+(stringmap "a") ; => 1
+(keymap :a) ; => 1
+
+; ¡Las keywords pueden ser usadas para recuperar su valor del mapa, también!
+(:b keymap) ; => 2
+
+; No intentes ésto con cadenas de caracteres.
+;("a" stringmap)
+; => Exception: java.lang.String cannot be cast to clojure.lang.IFn
+
+; Recuperando un valor no presente regresa nil
+(stringmap "d") ; => nil
+
+; Usa assoc para agregar nuevas llaves a los mapas de Hash
+(def newkeymap (assoc keymap :d 4))
+newkeymap ; => {:a 1, :b 2, :c 3, :d 4}
+
+; Pero recuerda, ¡los tipos de clojure son inmutables!
+keymap ; => {:a 1, :b 2, :c 3}
+
+; Usa dissoc para remover llaves
+(dissoc keymap :a :b) ; => {:c 3}
+
+; Conjuntos
+;;;;;;
+
+(class #{1 2 3}) ; => clojure.lang.PersistentHashSet
+(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3}
+
+; Agrega un miembro con conj
+(conj #{1 2 3} 4) ; => #{1 2 3 4}
+
+; Remueve uno con disj
+(disj #{1 2 3} 1) ; => #{2 3}
+
+; Comprueba la existencia tratando al conjunto como una función:
+(#{1 2 3} 1) ; => 1
+(#{1 2 3} 4) ; => nil
+
+; Hay más funciones en el espacio de nombre clojure.sets
+
+; Patrones útiles
+;;;;;;;;;;;;;;;;;
+
+; Las construcciones lógicas en clojure son macros, y tienen el mismo aspecto
+; que todo lo demás
+(if false "a" "b") ; => "b"
+(if false "a") ; => nil
+
+; Usa let para crear una binding (asociación) temporal
+(let [a 1 b 2]
+ (> a b)) ; => false
+
+; Agrupa expresiones con do
+(do
+ (print "Hello")
+ "World") ; => "World" (prints "Hello")
+
+; Las funciones tienen un do implicito
+(defn print-and-say-hello [name]
+ (print "Saying hello to " name)
+ (str "Hello " name))
+(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff")
+
+; De igual forma let
+(let [name "Urkel"]
+ (print "Saying hello to " name)
+ (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
+
+; Modulos
+;;;;;;;;;;;;;;;
+
+; Usa use para obtener todas las funciones del modulo
+(use 'clojure.set)
+
+; Ahora podemos usar operaciones de conjuntos
+(intersection #{1 2 3} #{2 3 4}) ; => #{2 3}
+(difference #{1 2 3} #{2 3 4}) ; => #{1}
+
+; Puedes escoger un subgrupo de funciones a importar, también
+(use '[clojure.set :only [intersection]])
+
+; Usa require para importar un modulo
+(require 'clojure.string)
+
+; Usa / para llamar funciones de un modulo
+; Aquí, el modulo es clojure.string y la función es blank?
+(clojure.string/blank? "") ; => true
+
+; Puedes asignarle una abreviatura a un modulo al importarlo
+(require '[clojure.string :as str])
+(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst."
+; (#"" es una expresión regular literal)
+
+; Puedes usar require (y use, pero no lo hagas) desde un espacio de nombre
+; usando :require,
+; No necesitas preceder con comilla simple tus módulos si lo haces de esta
+; forma.
+(ns test
+ (:require
+ [clojure.string :as str]
+ [clojure.set :as set]))
+
+; Java
+;;;;;;;;;;;;;;;;;
+
+; Java tiene una enorme y útil librería estándar, así que
+; querrás aprender como llegar a ella.
+
+; Usa import para cargar un modulo de java
+(import java.util.Date)
+
+; Puedes importar desde un ns también.
+(ns test
+ (:import java.util.Date
+ java.util.Calendar))
+
+; Usa el nombre de la clase con un "." al final para crear una nueva instancia
+(Date.) ; <un objeto Date>
+
+; Usa "." para llamar a métodos. O, usa el atajo ".método"
+(. (Date.) getTime) ; <un timestamp>
+(.getTime (Date.)) ; exactamente la misma cosa
+
+; Usa / para llamar métodos estáticos.
+(System/currentTimeMillis) ; <un timestamp> (System siempre está presente)
+
+; Usa doto para hacer frente al uso de clases (mutables) más tolerable
+(import java.util.Calendar)
+(doto (Calendar/getInstance)
+ (.set 2000 1 1 0 0 0)
+ .getTime) ; => A Date. set to 2000-01-01 00:00:00
+
+; STM
+;;;;;;;;;;;;;;;;;
+
+; Software Transactional Memory es un mecanismo que clojure usa para manejar
+; el estado persistente. Hay algunas cuantas construcciones en clojure que
+; usan esto.
+
+; Un atom es el más simple. Dale una valor inicial
+(def my-atom (atom {}))
+
+; Actualiza un atom con swap!
+; swap! toma una función y la llama con el valor actual del atom
+; como su primer argumento, y cualquier argumento restante como el segundo
+(swap! my-atom assoc :a 1) ; Establece my-atom al resultado de (assoc {} :a 1)
+(swap! my-atom assoc :b 2) ; Establece my-atom al resultado de (assoc {:a 1} :b 2)
+
+; Usa '@' para no referenciar al atom y obtener su valor
+my-atom ;=> Atom<#...> (Regresa el objeto Atom)
+@my-atom ; => {:a 1 :b 2}
+
+; Aquí está un simple contador usando un atom
+(def counter (atom 0))
+(defn inc-counter []
+ (swap! counter inc))
+
+(inc-counter)
+(inc-counter)
+(inc-counter)
+(inc-counter)
+(inc-counter)
+
+@counter ; => 5
+
+; Otros constructores STM son refs y agents.
+; Refs: http://clojure.org/refs
+; Agents: http://clojure.org/agents
+```
+
+### Lectura adicional
+
+Ésto queda lejos de ser exhaustivo, pero espero que sea suficiente para
+encaminarte.
+
+Clojure.org tiene muchos artículos:
+[http://clojure.org/](http://clojure.org/)
+
+Clojuredocs.org tiene documentación con ejemplos para la mayoría de
+funciones core:
+[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
+
+4Clojure es una grandiosa forma de fortalecer tus habilidades con clojure/FP:
+[http://www.4clojure.com/](http://www.4clojure.com/)
+
+Clojure-doc.org (sí, de verdad) tiene un número de artículos para empezar:
+[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/git.html.markdown b/git.html.markdown
index d8537300..abe8e3a7 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -2,9 +2,8 @@
category: tool
tool: git
contributors:
- - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"]
filename: LearnGit.txt
-
---
Git is a distributed version control and source code management system.
diff --git a/haxe.html.markdown b/haxe.html.markdown
new file mode 100644
index 00000000..eb39834e
--- /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.
+
+```csharp
+/*
+ Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org
+ This is an executable tutorial. You can compile and run it using the haxe
+ compiler, while in the same directory as LearnHaxe.hx:
+ $> haxe -main LearnHaxe3 -x out
+
+ 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..621ebdbf 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.
@@ -38,7 +38,7 @@ import (
"strconv" // Stringek átalakítására szolgáló csomag
)
-// Funkció deklarás, a main nevű funkció a program kezdőpontja.
+// Funkció deklarálás, a main nevű funkció a program kezdőpontja.
func main() {
// Println kiírja a beadott paramétereket a standard kimenetre.
// Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a
@@ -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..0caa07b6 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -59,6 +59,9 @@ $float = 1.234;
$float = 1.2e3;
$float = 7E-10;
+// Delete variable
+unset($int1)
+
// Arithmetic
$sum = 1 + 1; // 2
$difference = 2 - 1; // 1
@@ -136,6 +139,11 @@ echo $associative['One']; // prints 1
$array = ['One', 'Two', 'Three'];
echo $array[0]; // => "One"
+// Add an element to the end of an array
+$array[] = 'Four';
+
+// Remove element from array
+unset($array[3]);
/********************************
* Output
@@ -176,6 +184,11 @@ $y = 0;
echo $x; // => 2
echo $z; // => 0
+// Dumps type and value of variable to stdout
+var_dump($z); // prints int(0)
+
+// Prints variable to stdout in human-readable format
+print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
/********************************
* Logic
@@ -463,10 +476,16 @@ class MyClass
print 'MyClass';
}
+ //final keyword would make a function unoverridable
final function youCannotOverrideMe()
{
}
+/*
+Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.
+A property declared as static can not be accessed with an instantiated class object (though a static method can).
+*/
+
public static function myStaticMethod()
{
print 'I am static';
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/ruby.html.markdown b/ruby.html.markdown
index 3a233d98..80682682 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Luke Holder", "http://twitter.com/lukeholder"]
- ["Tristan Hume", "http://thume.ca/"]
- ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
---
```ruby
@@ -339,6 +340,23 @@ dwight.name #=> "Dwight K. Schrute"
# Call the class method
Human.say("Hi") #=> "Hi"
+# Variable's scopes are defined by the way we name them.
+# Variables that start with $ have global scope
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+
+# Variables that start with @ have instance scope
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+
+# Variables that start with @@ have class scope
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+
+# Variables that start with a capital letter are constants
+Var = "I'm a constant"
+defined? Var #=> "constant"
+
# Class also is object in ruby. So class can have instance variables.
# Class variable is shared among the class and all of its descendants.
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)
diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown
index 8f7cb2af..0af5bbe3 100644
--- a/zh-cn/go-zh.html.markdown
+++ b/zh-cn/go-zh.html.markdown
@@ -1,8 +1,8 @@
---
-名字:Go
-分类:编程语言
-文件名:learngo.go
-贡献者:
+language: Go
+lang: zh-cn
+filename: learngo.go
+contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["pantaovay", "https://github.com/pantaovay"]
---