summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown84
-rw-r--r--c.html.markdown250
-rw-r--r--de-de/git-de.html.markdown374
-rw-r--r--de-de/python-de.html.markdown486
-rw-r--r--fr-fr/coffeescript-fr.html.markdown58
-rw-r--r--fr-fr/ruby-fr.html.markdown12
-rw-r--r--go.html.markdown354
-rw-r--r--groovy.html.markdown379
-rw-r--r--hu-hu/go.html.markdown305
-rw-r--r--ko-kr/java-kr.html.markdown10
-rw-r--r--objective-c.html.markdown2
-rw-r--r--pt-br/elisp-pt.html.markdown16
-rw-r--r--pt-br/ruby-pt.html.markdown8
-rw-r--r--ru-ru/clojure-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown18
-rw-r--r--ru-ru/python-ru.html.markdown8
-rw-r--r--ruby-ecosystem.html.markdown2
-rw-r--r--tr-tr/c-tr.html.markdown484
-rw-r--r--whip.html.markdown18
-rw-r--r--zh-cn/go-zh.html.markdown183
20 files changed, 2614 insertions, 439 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
new file mode 100644
index 00000000..8cf7be18
--- /dev/null
+++ b/bash.html.markdown
@@ -0,0 +1,84 @@
+---
+
+language: 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.
+Nearly all examples below can be a part of a shell script or executed directly in the shell.
+
+[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/sh
+# First line of the script is shebang which tells the system how to execute the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# As you already figured, comments start with #. Shebang is also a comment.
+
+# Simple hello world example:
+echo Hello, world!
+
+# Each command starts on a new line, or after semicolon:
+echo 'This is the first line'; echo 'This is the second line'
+
+# Declaring a variable looks like this:
+VARIABLE="Some string"
+
+# But not like this:
+VARIABLE = "Some string" # Bash will decide that VARIABLE is a command he must execute and give an error because it couldn't be found.
+
+# Using the variable:
+echo $VARIABLE
+echo "$VARIABLE"
+# When you use the variable itself — assign it, export it, or else — you write it's name without $. If you want to use variable's value, you should use $.
+
+# Reading a value from input:
+echo "What's your name?"
+read NAME # Note that we didn't need to declare new variable
+echo Hello, $NAME!
+
+# We have the usual if structure:
+if true
+then
+ echo "This is expected"
+else
+ echo "And this is not"
+fi
+
+# Expressions are denoted with the following format:
+echo $(( 10 + 5 ))
+
+# Unlike other programming languages, bash is a shell — so it works in a context of current directory.
+# You can list files and directories in the current directories with ls command:
+ls
+
+# These commands have options that control their execution:
+ls -l # Lists every file and directory on a separate line
+
+# Results of the previous command can be passed to the next command as input.
+# grep command filters the input with provided patterns. That's how we can list txt files in the current directory:
+ls -l | grep "\.txt"
+
+# Commands can be substitued within other commands using $( ):
+# The following command displays the number of files and directories in the current directory.
+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
+ #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."
+esac
+
+#For loops iterate for as many arguments given:
+#The contents of var $VARIABLE is printed three times.
+for $VARIABLE in x y z
+do
+ echo "$VARIABLE"
+done
+
+```
diff --git a/c.html.markdown b/c.html.markdown
index 00b13cb0..24a96463 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -1,11 +1,9 @@
---
-- name: c
-- category: language
-- language: c
-- filename: learnc.c
-- contributors:
- - [Adam Bard](http://adambard.com/)
- - [Árpád Goretity](http://twitter.com/H2CO3_iOS)
+language: c
+filename: learnc.c
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+ - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
---
@@ -27,17 +25,10 @@ Multi-line comments look like this. They work in C89 as well.
#include <stdio.h>
#include <string.h>
-// file names between <angle brackets> are headers from the C standard library.
-// They are searched for by the preprocessor in the system include paths
-// (usually /usr/lib on Unices, can be controlled with the -I<dir> option if you are using GCC or clang.)
+// (File names between <angle brackets> are headers from the C standard library.)
// For your own headers, use double quotes instead of angle brackets:
#include "my_header.h"
-// The C preprocessor introduces an almost fully-featured macro language. It's useful, but
-// it can be confusing (and what's even worse, it can be misused). Read the
-// Wikipedia article on the C preprocessor for further information:
-// http://en.wikipedia.org/wiki/C_preprocessor
-
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
void function_1();
@@ -50,132 +41,117 @@ int main() {
// %d is an integer, \n is a newline
printf("%d\n", 0); // => Prints 0
// All statements must end with a semicolon
-
+
///////////////////////////////////////
// Types
///////////////////////////////////////
-
- // You have to declare variables before using them. A variable declaration
- // requires you to specify its type; a variable's type determines its size
- // in bytes.
-
+
// ints are usually 4 bytes
int x_int = 0;
-
+
// shorts are usually 2 bytes
short x_short = 0;
-
+
// chars are guaranteed to be 1 byte
char x_char = 0;
char y_char = 'y'; // Char literals are quoted with ''
-
+
// longs are often 4 to 8 bytes; long longs are guaranteed to be at least
// 64 bits
long x_long = 0;
long long x_long_long = 0;
-
+
// floats are usually 32-bit floating point numbers
float x_float = 0.0;
-
+
// doubles are usually 64-bit floating-point numbers
double x_double = 0.0;
-
- // Integral types may be unsigned. This means they can't be negative, but
- // the maximum value of an unsigned variable is greater than the maximum
- // signed value of the same size.
- unsigned char ux_char;
+
+ // Integral types may be unsigned.
unsigned short ux_short;
unsigned int ux_int;
unsigned long long ux_long_long;
-
- // Other than char, which is always 1 byte (but not necessarily 8 bits!),
- // these types vary in size depending on your machine and compiler.
- // sizeof(T) gives you the size of a variable with type T in
- // bytes so you can express the size of these types in a portable way.
- // sizeof(obj) yields the size of an actual expression (variable, literal, etc.).
- // For example,
+
+ // sizeof(T) gives you the size of a variable with type T in bytes
+ // sizeof(obj) yields the size of the expression (variable, literal, etc.).
printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
-
-
- // It's worth noting that if the argument of the `sizeof` operator is not a type but an expression,
- // then its argument is not evaluated except VLAs (see below). Also, `sizeof()` is an operator, not a function,
- // furthermore, the value it yields is a compile-time constant (except when used on VLAs, again.)
+
+
+ // If the argument of the `sizeof` operator an expression, then its argument
+ // is not evaluated (except VLAs (see below)).
+ // The value it yields in this case is a compile-time constant.
int a = 1;
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
- // the above code prints "sizeof(a++) = 4 where a = 1" (on a usual 32-bit architecture)
-
+ // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
+
// Arrays must be initialized with a concrete size.
char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes
int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
// (assuming 4-byte words)
-
-
+
+
// You can initialize an array to 0 thusly:
char my_array[20] = {0};
-
+
// Indexing an array is like other languages -- or,
// rather, other languages are like C
my_array[0]; // => 0
-
+
// Arrays are mutable; it's just memory!
my_array[1] = 2;
printf("%d\n", my_array[1]); // => 2
-
- // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) can be declared as well.
- // The size of such an array need not be a compile time constant:
+
+ // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
+ // can be declared as well. The size of such an array need not be a compile
+ // time constant:
printf("Enter the array size: "); // ask the user for an array size
char buf[0x100];
fgets(buf, sizeof buf, stdin);
- size_t size = strtoul(buf, NULL, 10); // strtoul parses a string to an unsigned integer
+
+ // strtoul parses a string to an unsigned integer
+ size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
-
+
// A possible outcome of this program may be:
- Enter the array size: 10
- sizeof array = 40
-
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
// Strings are just arrays of chars terminated by a NUL (0x00) byte,
// represented in strings as the special character '\0'.
// (We don't have to include the NUL byte in string literals; the compiler
// inserts it at the end of the array for us.)
char a_string[20] = "This is a string";
printf("%s\n", a_string); // %s formats a string
-
- /*
- You may have noticed that a_string is only 16 chars long.
- Char #17 is the NUL byte.
- Chars #18, 19 and 20 are 0 as well - if an initializer list (in this case, the string literal)
- has less elements than the array it is initializing, then excess array elements are implicitly
- initialized to zero. This is why int ar[10] = { 0 } works as expected intuitively.
- */
-
+
printf("%d\n", a_string[16]); // => 0
-
- // So string literals are strings enclosed within double quotes, but if we have characters
- // between single quotes, that's a character literal.
+ // i.e., byte #17 is 0 (as are 18, 19, and 20)
+
+ // If we have characters between single quotes, that's a character literal.
// It's of type `int`, and *not* `char` (for historical reasons).
int cha = 'a'; // fine
- char chb = 'a'; // fine too (implicit conversion from int to char - truncation)
-
+ char chb = 'a'; // fine too (implicit conversion from int to char)
+
///////////////////////////////////////
// Operators
///////////////////////////////////////
-
+
int i1 = 1, i2 = 2; // Shorthand for multiple declaration
float f1 = 1.0, f2 = 2.0;
-
+
// Arithmetic is straightforward
i1 + i2; // => 3
i2 - i1; // => 1
i2 * i1; // => 2
i1 / i2; // => 0 (0.5, but truncated towards 0)
-
- f1 / f2; // => 0.5, plus or minus epsilon - floating-point numbers and calculations are not exact
-
+
+ f1 / f2; // => 0.5, plus or minus epsilon
+ // Floating-point numbers and calculations are not exact
+
// Modulo is there as well
11 % 3; // => 2
-
+
// Comparison operators are probably familiar, but
// there is no boolean type in c. We use ints instead.
// (Or _Bool or bool in C99.)
@@ -187,14 +163,14 @@ int main() {
3 < 2; // => 0
2 <= 2; // => 1
2 >= 2; // => 1
-
+
// C is not Python - comparisons don't chain.
int a = 1;
// WRONG:
int between_0_and_2 = 0 < a < 2;
// Correct:
int between_0_and_2 = 0 < a && a < 2;
-
+
// Logic works on ints
!3; // => 0 (Logical not)
!0; // => 1
@@ -202,7 +178,7 @@ int main() {
0 && 1; // => 0
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
-
+
// Bitwise operators!
~0x0F; // => 0xF0 (bitwise negation, "1's complement")
0x0F & 0xF0; // => 0x00 (bitwise AND)
@@ -210,17 +186,17 @@ int main() {
0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
0x01 << 1; // => 0x02 (bitwise left shift (by 1))
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
-
- // Be careful when shifting signed integers - the following are all undefined behavior:
+
+ // Be careful when shifting signed integers - the following are undefined:
// - shifting into the sign bit of a signed integer (int a = 1 << 32)
// - left-shifting a negative number (int a = -1 << 2)
- // - shifting by an offset which is more than or equal to the width of the type of the LHS:
+ // - shifting by an offset which is >= the width of the type of the LHS:
// int a = 1 << 32; // UB if int is 32 bits wide
-
+
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
-
+
if (0) {
printf("I am never run\n");
} else if (0) {
@@ -228,36 +204,38 @@ int main() {
} else {
printf("I print\n");
}
-
+
// While loops exist
int ii = 0;
while (ii < 10) {
- printf("%d, ", ii++); // ii++ increments ii in-place, after yielding its value ("postincrement").
+ printf("%d, ", ii++); // ii++ increments ii in-place
+ // after yielding its value ("postincrement").
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
+
printf("\n");
-
+
int kk = 0;
do {
printf("%d, ", kk);
- } while (++kk < 10); // ++kk increments kk in-place, and yields the already incremented value ("preincrement")
+ } while (++kk < 10); // ++kk increments kk in-place, and yields
+ // the already incremented value ("preincrement")
// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
+
printf("\n");
-
+
// For loops too
int jj;
for (jj=0; jj < 10; jj++) {
printf("%d, ", jj);
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
+
printf("\n");
-
+
// branching with multiple choices: switch()
switch (some_integral_expression) {
case 0: // labels need to be integral *constant* epxressions
do_stuff();
- break; // if you don't break, control flow falls over labels - you usually don't want that.
+ break; // if you don't break, control flow falls over labels
case 1:
do_something_else();
break;
@@ -267,73 +245,74 @@ int main() {
exit(-1);
break;
}
-
+
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
-
+
// Every value in C has a type, but you can cast one value into another type
// if you want (with some constraints).
-
+
int x_hex = 0x01; // You can assign vars with hex literals
-
+
// Casting between types will attempt to preserve their numeric values
printf("%d\n", x_hex); // => Prints 1
printf("%d\n", (short) x_hex); // => Prints 1
printf("%d\n", (char) x_hex); // => Prints 1
-
+
// Types will overflow without warning
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
- // printf("%d\n", (unsigned char) 257); would be undefined behavior - `char' is usually signed
- // on most modern systems, and signed integer overflow invokes UB.
- // Also, for determining the maximal value of a `char`, a `signed char` and an `unisigned char`,
+
+ // For determining the max value of a `char`, a `signed char` and an `unisigned char`,
// respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from <limits.h>
-
+
// Integral types can be cast to floating-point types, and vice-versa.
printf("%f\n", (float)100); // %f formats a float
printf("%lf\n", (double)100); // %lf formats a double
printf("%d\n", (char)100.0);
-
+
///////////////////////////////////////
// Pointers
///////////////////////////////////////
-
+
// A pointer is a variable declared to store a memory address. Its declaration will
// also tell you the type of data it points to. You can retrieve the memory address
// of your variables, then mess with them.
-
+
int x = 0;
printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable
// (%p formats an object pointer of type void *)
// => Prints some address in memory;
-
-
+
+
// Pointers start with * in their declaration
int *px, not_a_pointer; // px is a pointer to an int
px = &x; // Stores the address of x in px
printf("%p\n", (void *)px); // => Prints some address in memory
printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
// => Prints "8, 4" on a typical 64-bit system
-
+
// To retreive the value at the address a pointer is pointing to,
// put * in front to de-reference it.
- // Note: yes, it may be confusing that '*' is used for _both_ declaring a pointer and dereferencing it.
- printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of
-
+ // Note: yes, it may be confusing that '*' is used for _both_ declaring a
+ // pointer and dereferencing it.
+ printf("%d\n", *px); // => Prints 0, the value of x
+
// You can also change the value the pointer is pointing to.
// We'll have to wrap the de-reference in parenthesis because
// ++ has a higher precedence than *.
(*px)++; // Increment the value px is pointing to by 1
printf("%d\n", *px); // => Prints 1
printf("%d\n", x); // => Prints 1
-
- int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory
+
+ // Arrays are a good way to allocate a contiguous block of memory
+ int x_array[20];
int xx;
for (xx = 0; xx < 20; xx++) {
x_array[xx] = 20 - xx;
} // Initialize x_array to 20, 19, 18,... 2, 1
-
+
// Declare a pointer of type int and initialize it to point to x_array
int* x_ptr = x_array;
// x_ptr now points to the first element in the array (the integer 20).
@@ -342,50 +321,52 @@ int main() {
// it decays into (implicitly converted to) a pointer.
// Exceptions: when the array is the argument of the `&` (address-od) operator:
int arr[10];
- int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`! It's of type "pointer to array" (of ten `int`s).
+ int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`!
+ // It's of type "pointer to array" (of ten `int`s).
// or when the array is a string literal used for initializing a char array:
char arr[] = "foobarbazquirk";
// or when it's the argument of the `sizeof` or `alignof` operator:
int arr[10];
int *ptr = arr; // equivalent with int *ptr = &arr[0];
printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8"
-
+
// Pointers are incremented and decremented based on their type
// (this is called pointer arithmetic)
printf("%d\n", *(x_ptr + 1)); // => Prints 19
printf("%d\n", x_array[1]); // => Prints 19
-
+
// You can also dynamically allocate contiguous blocks of memory with the
// standard library function malloc, which takes one argument of type size_t
// representing the number of bytes to allocate (usually from the heap, although this
// may not be true on e. g. embedded systems - the C standard says nothing about it).
int *my_ptr = malloc(sizeof(*my_ptr) * 20);
for (xx = 0; xx < 20; xx++) {
- *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here, and it's also more readable
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
-
+
// Dereferencing memory that you haven't allocated gives
// "unpredictable results" - the program is said to invoke "undefined behavior"
printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash.
-
+
// When you're done with a malloc'd block of memory, you need to free it,
// or else no one else can use it until your program terminates
// (this is called a "memory leak"):
free(my_ptr);
-
+
// Strings are arrays of char, but they are usually represented as a
// pointer-to-char (which is a pointer to the first element of the array).
// It's good practice to use `const char *' when referring to a string literal,
// since string literals shall not be modified (i. e. "foo"[0] = 'a' is ILLEGAL.)
const char *my_str = "This is my very own string literal";
printf("%c\n", *my_str); // => 'T'
-
- // This is not the case if the string is an array (potentially initialized with a string literal)
+
+ // This is not the case if the string is an array
+ // (potentially initialized with a string literal)
// that resides in writable memory, as in:
char foo[] = "foo";
foo[0] = 'a'; // this is legal, foo now contains "aoo"
-
+
function_1();
} // end main function
@@ -435,17 +416,17 @@ printf("%s\n", c); // => ".tset a si sihT"
typedef int my_type;
my_type my_type_var = 0;
-// Structs are just collections of data, the members are allocated sequentially, in the order they are written:
+// Structs are just collections of data, the members are allocated sequentially,
+// in the order they are written:
struct rectangle {
int width;
int height;
};
-// it's generally not true that sizeof(struct rectangle) == sizeof(int) + sizeof(int) due to
-// potential padding between the structure members (this is for alignment reasons. Probably won't
-// happen if all members are of the same type, but watch out!
-// See http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
-// for further information.
+// It's not generally true that
+// sizeof(struct rectangle) == sizeof(int) + sizeof(int)
+// due to potential padding between the structure members (this is for alignment
+// reasons). [1]
void function_1()
{
@@ -473,7 +454,8 @@ int area(rect r)
return r.width * r.height;
}
-// if you have large structs, you can pass them "by pointer" to avoid copying the whole struct:
+// if you have large structs, you can pass them "by pointer" to avoid copying
+// the whole struct:
int area(const rect *r)
{
return r->width * r->height;
@@ -527,3 +509,5 @@ Readable code is better than clever code and fast code. For a good, sane coding
[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
Other than that, Google is your friend.
+
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
new file mode 100644
index 00000000..471c7641
--- /dev/null
+++ b/de-de/git-de.html.markdown
@@ -0,0 +1,374 @@
+---
+category: tool
+tool: git
+contributors:
+ - ["Jake Prather", "http:#github.com/JakeHP"]
+ - ["kultprok", "http://www.kulturproktologie.de"]
+filename: LearnGit.txt
+lang: de-de
+---
+
+Git ist eine verteilte Versions- und Quellcodeverwaltung.
+
+Es nimmt Schnappschüsse der Projekte, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können.
+
+Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* oder *Head* sind idiomatische Bestandteile im Umgang mit Git. Sie wurden nicht übersetzt.
+
+## Konzepte der Versionsverwaltung
+
+### Was ist Versionsverwaltung?
+
+Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit.
+
+### Zentrale im Vergleich mit verteilter Versionverwaltung
+
+* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien.
+* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID.
+* Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar.
+
+[Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
+
+### Warum Git?
+
+* Ist offline einsetzbar.
+* Einfache Kollaboration!
+* Branching ist einfach!
+* Merging ist einfach!
+* Git ist schnell.
+* Git ist flexibel.
+
+## Die Architektur von Git
+
+
+### Repository (Repo)
+
+Ein Satz von Dateien, Verzeichnisen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben.
+
+Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichnis.
+
+### .git-Verzeichnis (Teil des Repositorys)
+
+Das .git-Verzeichnis enth? alle Einstellung, Logs, Branches, den HEAD und mehr.
+[Ausführliche Übersicht](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Arbeitsverzeichnis (Teil des Repositorys)
+
+Dies sind die Verzeichnisse und Dateien in deinem Repository.
+
+### Index (Teil des .git-Verzeichnisses)
+
+Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht.
+
+### Commit
+
+Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht!
+
+### Branch
+
+Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf Stand gebracht und zeigt dann auf den neuen letzten Commit.
+
+### HEAD und head (Teil des .git-Verzeichnisses)
+
+HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt.
+
+### Konzeptionelle Hintergründe
+
+* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html)
+
+
+## Befehle
+
+
+### init
+
+Erstelle ein leeres Git-Repository. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt.
+
+```bash
+$ git init
+```
+
+### config
+
+Hiermit werden Einstellungen vorgenommen. Dies kann das Repository, das System selbst oder globale Einstellungen betreffen.
+
+```bash
+# Grundlegende Config-Variablen ausgeben und setzen
+$ git config --global user.email
+$ git config --global user.name
+
+$ git config --global user.email "MyEmail@Zoho.com"
+$ git config --global user.name "My Name"
+```
+
+[Mehr über git config](http://git-scm.com/docs/git-config)
+
+### help
+
+Schnellzugriff auf extrem detaillierte Anleitungen zu allen Befehlen. Oder als Erinnerung zu semantischen Eigenheiten.
+
+```bash
+# Übersicht gängiger Befehle
+$ git help
+
+# Übersicht aller verfügbaren Befehle
+$ git help -a
+
+# Befehlspezifische Hilfe - Bedienungsanleitung
+# git help <gesuchter_befehl>
+$ git help add
+$ git help commit
+$ git help init
+```
+
+### status
+
+Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-repository) und dem aktuellen HEAD an.
+
+
+```bash
+# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an
+$ git status
+
+# Anderes Wissenswertes über git status anzeigen
+$ git help status
+```
+
+### add
+
+Hinzufügen von Dateien zum Arbeitsverzeichnis/-repository. Wenn du neue Dateien nicht mit *git add* zum Arbeitsverzeichnis hinzufügst, werden sie nicht in den Commit aufgenommen!
+
+```bash
+# Fügt eine Datei deinem aktuellen Arbeitsverzeichnis hinzu
+$ git add HelloWorld.java
+
+# Fügt eine Datei aus einem verschachtelten Verzeichnis hinzu
+$ git add /path/to/file/HelloWorld.c
+
+# Reguläre Ausdrücke werden unterstützt!
+$ git add ./*.java
+```
+
+### branch
+
+Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen.
+
+```bash
+# Liste alle bestehenden Branches und Remotes auf
+$ git branch -a
+
+# Erstelle einen neuen Branch
+$ git branch myNewBranch
+
+# Lösche einen Branch
+$ git branch -d myBranch
+
+# Benenne einen Branch um
+# git branch -m <oldname> <newname>
+$ git branch -m myBranchName myNewBranchName
+
+# Ändere die Beschreibung eines Branchs
+$ git branch myBranchName --edit-description
+```
+
+### checkout
+
+Bringt alle Dateien im Arbeitsverzeichnis auf den Stand des Index oder des angegebenen Branches.
+
+```bash
+# Ein Repo auschecken - wenn nicht anders angegeben ist das der master
+$ git checkout
+# Einen bestimmten Branch auschecken
+$ git checkout branchName
+# Erstelle einen neuen Branch und wechsle zu ihm. Wie: "git branch <name>; git checkout <name>"
+$ git checkout -b newBranch
+```
+
+### clone
+
+Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen.
+
+```bash
+# Klone learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+```
+
+### commit
+
+Speichert die aktuellen Inhalte des Index in einen neuen *Commit*. Dieser Commit enthält alle Änderungen und eine vom Benutzer erstellte Beschreibung der Änderungen.
+
+```bash
+# Commit mit Beschreibung erstellen.
+$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+```
+
+### diff
+
+Zeigt die Unterschiede zwischen Dateien von Arbeitsverzeichnisse, dem Index und Commits an.
+
+```bash
+# Unterschiede zwischen deinem Arbeitsverzeichnis und dem Index anzeigen
+$ git diff
+
+# Unterschiede zwischen dem Index und dem aktuellsten Commit anzeigen
+$ git diff --cached
+
+# Unterschiede zwischen deinem Arbeitsverzeichnis und dem aktuellsten Commit anzeigen
+$ git diff HEAD
+```
+
+### grep
+
+Schnell ein Repository durchsuchen.
+
+Optionale Einstellungen:
+
+```bash
+# Vielen Dank an Travis Jeffery für die Hinweise.
+# Zeilennummerierung in grep-Suchergebnissen
+$ git config --global grep.lineNumber true
+
+# Suchergebnisse lesbarer gestalten, auch Gruppierungen sind möglich
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Suche nach "variableName" in allen java-Dateien
+$ git grep 'variableName' -- '*.java'
+
+# Suche nach eine Zeile, die "arrayListName" und "add" oder "remove" enthält
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Google ist dein Freund; für mehr Beispiele:
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Zeige Commits für das Repository an.
+
+```bash
+# Zeige alle Commits
+$ git log
+
+# Zeige die Anzahl n an Commits
+$ git log -n 10
+
+# Zeige nur Merges an
+$ git log --merges
+```
+
+### merge
+
+*Merge*, also verschmelze, alle Änderungen von externen Commits in den aktuellen Branch.
+
+```bash
+# Merge den angegebenen Branch in den aktuellen.
+$ git merge branchName
+
+# Erstelle immer einen Merge-Commit.
+$ git merge --no-ff branchName
+```
+
+### mv
+
+Eine Datei umbenennen oder verschieben.
+
+```bash
+# Umbenennen
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Verschieben
+$ git mv HelloWorld.c ./new/path/HelloWorld.c
+
+# Umbenennung oder Verschieben erzwingen
+# "existingFile" besteht schon im Verzeichnis, wird überschrieben mit "myFile"
+$ git mv -f myFile existingFile
+```
+
+### pull
+
+Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch.
+
+```bash
+# Update deines lokalen Repos, indem ein Merge der neuen Uderungen
+# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird.
+# git pull <remote> <branch>
+# git pull => impliziter Verweis auf origin und master
+$ git pull origin master
+
+# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase
+# des Branch-Commits im lokalen Repo durch. Wie: pull <remote> <branch>, git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+Führe einen Push, ein Hochladen, und einen Merge von Änderungen eines remote-Branch mit einem Branch aus.
+
+```bash
+# Führe Push und Merge von Änderungen des lokalen Repo zu einem
+# remote-Branch namens "origin" und dem "master"-Branch aus.
+# git push <remote> <branch>
+# git push => impliziter Verweis auf => git push origin master
+$ git push origin master
+```
+
+### rebase (mit Vorsicht einsetzen)
+
+Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden.
+
+```bash
+# Rebase "experimentBranch" in den "master"-Branch
+# git rebase <basisbranch> <themenbranch>
+$ git rebase master experimentBranch
+```
+
+[Weiterführende Informationen](http://git-scm.com/book/en/Git-Branching-Rebasing)
+
+### reset (mit Vorsicht einsetzen)
+
+Setze den aktuellen HEAD auf den angegebenen Zustand zurück. So können Merges, Pulls, Commits, Hinzufügungen und andere Änderungen rückgängig gemacht werden. Es ist ein hervorragender Befehl, aber auch sehr gefährlich, wenn du nicht weißt, was du tust.
+
+```bash
+# Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen (das Verzeichnis bleibt unberührt)
+$ git reset
+
+# Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis
+$ git reset --hard
+
+# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??)
+# Alle Uderungen bleiben im Verzeichnis erhalten
+$ git reset 31f2bb1
+
+# Bewegt die Spitze des Branches zurück zu dem angegebenen Commit
+# und gleicht die Arbeitsverzeichnisse ab (löscht nicht vom Commit erfasste Änderungen und alle Commits,
+# die dem angegebenen Commit folgen).
+$ git reset --hard 31f2bb1
+```
+
+### rm
+
+Das Gegenteil von *git add*. *git rm* löscht Dateien vom Arbeitsverzeichnis.
+
+```bash
+# Entferne HelloWorld.c
+$ git rm HelloWorld.c
+
+# Entferne eine Datei aus einem verschachtelten Verzeichnis
+$ git rm /pather/to/the/file/HelloWorld.c
+```
+
+## Weiterführende Informationen
+
+* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
+
+* [git-scm - Video Tutorials](http://git-scm.com/videos)
+
+* [git-scm - Documentation](http://git-scm.com/docs)
+
+* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
+
+* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
+* [GitGuys](http://www.gitguys.com/)
diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown
new file mode 100644
index 00000000..7462d5f6
--- /dev/null
+++ b/de-de/python-de.html.markdown
@@ -0,0 +1,486 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["kultprok", "http:/www.kulturproktologie.de"]
+filename: learnpython-de.py
+lang: de-de
+---
+
+Anmerkungen des ursprünglichen Autors:
+Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode.
+
+Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]
+
+Hinweis: Dieser Beitrag bezieht sich besonders auf Python 2.7, er sollte aber auf Python 2.x anwendbar sein. Haltet Ausschau nach einem Rundgang durch Python 3, der bald erscheinen soll.
+
+```python
+# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz)
+""" Mehrzeilige Strings werden mit
+ drei '-Zeichen geschrieben und werden
+ oft als Kommentare genutzt.
+"""
+
+####################################################
+## 1. Primitive Datentypen und Operatoren
+####################################################
+
+# Die Zahlen
+3 #=> 3
+
+# Mathematik funktioniert so, wie man das erwartet
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+
+# Division ist ein wenig kniffliger. Ganze Zahlen werden ohne Rest dividiert
+# und das Ergebnis wird automatisch abgerundet.
+5 / 2 #=> 2
+
+# Um das zu ändern, müssen wir Gleitkommazahlen einführen und benutzen
+2.0 # Das ist eine Gleitkommazahl
+11.0 / 4.0 #=> 2.75 Ahhh...schon besser
+
+# Rangfolge wird mit Klammern erzwungen
+(1 + 3) * 2 #=> 8
+
+# Boolesche Ausdrücke sind primitive Datentypen
+True
+False
+
+# Mit not wird negiert
+not True #=> False
+not False #=> True
+
+# Gleichheit ist ==
+1 == 1 #=> True
+2 == 1 #=> False
+
+# Ungleichheit ist !=
+1 != 1 #=> False
+2 != 1 #=> True
+
+# Ein paar weitere Vergleiche
+1 < 10 #=> True
+1 > 10 #=> False
+2 <= 2 #=> True
+2 >= 2 #=> True
+
+# Vergleiche können verknüpft werden!
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Strings werden mit " oder ' gebildet
+"Das ist ein String."
+'Das ist auch ein String.'
+
+# Strings können addiert werden!
+"Hello " + "world!" #=> "Hello world!"
+
+# Ein String kann wie eine Liste von Zeichen verwendet werden
+"Das ist ein String"[0] #=> 'D'
+
+# Mit % können Strings formatiert werden, etwa so:
+"%s können %s werden" % ("Strings", "interpoliert")
+
+# Ein modernerer Weg, um Strings zu formatieren, ist die format-Methode.
+# Diese Methode wird bevorzugt
+"{0} können {1} werden".format("Strings", "formatiert")
+# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen.
+"{name} will {food} essen".format(name="Bob", food="Lasagne")
+
+# None ist ein Objekt
+None #=> None
+
+# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen
+# Benutzt stattdessen `is`
+"etc" is None #=> False
+None is None #=> True
+
+# Der 'is'-Operator testet Objektidentität. Das ist nicht
+# sehr nützlich, wenn wir mit primitiven Datentypen arbeiten, aber
+# sehr nützlich bei Objekten.
+
+# None, 0, und leere Strings/Listen werden alle als False bewertet.
+# Alle anderen Werte sind True
+0 == False #=> True
+"" == False #=> True
+
+
+####################################################
+## 2. Variablen und Collections
+####################################################
+
+# Textausgabe ist sehr einfach
+print "Ich bin Python. Schön, dich kennenzulernen!"
+
+
+# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren.
+some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
+some_var #=> 5
+
+# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
+# Unter "Kontrollstruktur" kann noch mehr über
+# Ausnahmebehandlung erfahren werden.
+some_other_var # Löst einen NameError aus
+
+# if kann als Ausdruck verwendet werden
+"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
+
+# Listen speichern Sequenzen
+li = []
+# Wir können mit einer bereits gefüllten Liste anfangen
+other_li = [4, 5, 6]
+
+# append fügt Daten am Ende der Liste ein
+li.append(1) #li ist jetzt [1]
+li.append(2) #li ist jetzt [1, 2]
+li.append(4) #li ist jetzt [1, 2, 4]
+li.append(3) #li ist jetzt [1, 2, 4, 3]
+# Vom Ende der Liste mit pop entfernen
+li.pop() #=> 3 und li ist jetzt [1, 2, 4]
+# und dann wieder hinzufügen
+li.append(3) # li ist jetzt wieder [1, 2, 4, 3].
+
+# Greife auf Listen wie auf Arrays zu
+li[0] #=> 1
+# Das letzte Element ansehen
+li[-1] #=> 3
+
+# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError
+li[4] # Raises an IndexError
+
+# Wir können uns Ranges mit Slice-Syntax ansehen
+li[1:3] #=> [2, 4]
+# Den Anfang auslassen
+li[2:] #=> [4, 3]
+# Das Ende auslassen
+li[:3] #=> [1, 2, 4]
+
+# Ein bestimmtes Element mit del aus der Liste entfernen
+del li[2] # li ist jetzt [1, 2, 3]
+
+# Listen können addiert werden
+li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen
+
+# Listen mit extend verknüpfen
+li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6]
+
+# Mit in auf Existenz eines Elements prüfen
+1 in li #=> True
+
+# Die Länge der Liste mit len ermitteln
+len(li) #=> 6
+
+
+# Tupel sind wie Listen, nur unveränderlich.
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Löst einen TypeError aus
+
+# Wir können all diese Listen-Dinge auch mit Tupeln anstellen
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Wir können Tupel (oder Listen) in Variablen entpacken
+a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
+# Tuple werden standardmäßig erstellt, wenn wir uns die Klammern sparen
+d, e, f = 4, 5, 6
+# Es ist kinderleicht zwei Werte zu tauschen
+e, d = d, e # d is now 5 and e is now 4
+
+
+# Dictionarys (Wörterbucher) speichern Key-Value-Paare
+empty_dict = {}
+# Hier ein gefülltes Wörterbuch
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Wir können Einträge mit [] nachschlagen
+filled_dict["one"] #=> 1
+
+# So holen wir alle Keys (Schlüssel) als Liste
+filled_dict.keys() #=> ["three", "two", "one"]
+# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert.
+# Einzelne Resultate können anders angeordnet sein.
+
+# Alle Values (Werte) als Liste
+filled_dict.values() #=> [3, 2, 1]
+# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln.
+
+# Das Vorhandensein eines Schlüssels im Wörterbuch mit in prüfen
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus
+filled_dict["four"] # KeyError
+
+# Mit der get-Methode verhindern wir das
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen
+filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt
+filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5
+
+
+# Sets speichern Mengen
+empty_set = set()
+# Initialisieren wir ein Set mit ein paar Werten
+some_set = set([1,2,2,3,4]) # some_set ist jetzt set([1, 2, 3, 4])
+
+# Seit Python 2.7 kann {} benutzt werden, um ein Set zu erstellen
+filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+
+# Mehr Elemente hinzufügen
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# Schnittmengen werden mit & gebildet
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# Mengen werden mit | vereinigt
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# Die Differenz einer Menge mit - bilden
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Auf Vorhandensein von Elementen mit in prüfen
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Kontrollstruktur
+####################################################
+
+# Erstellen wir mal eine Variable
+some_var = 5
+
+# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig!
+# gibt "some_var ist kleiner als 10" aus
+if some_var > 10:
+ print "some_var ist viel größer als 10."
+elif some_var < 10: # Dieser elif-Absatz ist optional.
+ print "some_var ist kleiner als 10."
+else: # Das hier ist auch optional.
+ print "some_var ist tatsächlich 10."
+
+
+"""
+For-Schleifen iterieren über Listen
+Ausgabe:
+ hund ist ein Säugetier
+ katze ist ein Säugetier
+ maus ist ein Säugetier
+"""
+for animal in ["hund", "katze", "maus"]:
+ # Wir können Strings mit % formatieren
+ print "%s ist ein Säugetier" % animal
+
+"""
+`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder
+Ausgabe:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+While-Schleifen laufen, bis eine Bedingung erfüllt ist.
+Ausgabe:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Kurzform für x = x + 1
+
+# Ausnahmebehandlung mit einem try/except-Block
+
+# Funktioniert in Python 2.6 und höher:
+try:
+ # Mit raise wird ein Fehler ausgegeben
+ raise IndexError("Das hier ist ein Index-Fehler")
+except IndexError as e:
+ pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären.
+
+
+####################################################
+## 4. Funktionen
+####################################################
+
+# Mit def neue Funktionen erstellen
+def add(x, y):
+ print "x ist %s und y ist %s" % (x, y)
+ return x + y # Werte werden mit return zurückgegeben
+
+# Funktionen mit Parametern aufrufen
+add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück
+
+# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente
+add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden.
+
+# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) #=> (1,2,3)
+
+
+# Wir können auch Funktionen mit beliebiger Anzahl
+# Schlüsselwort-Argumenten definieren
+def keyword_args(**kwargs):
+ return kwargs
+
+# Rufen wir es mal auf, um zu sehen, was passiert
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# Wir können beides gleichzeitig machem, wenn wir wollen
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) Ausgabe:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen!
+# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4)
+all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4)
+all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4)
+
+# Python hat First-Class-Funktionen
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Es gibt auch anonyme Funktionen
+(lambda x: x > 2)(3) #=> True
+
+# Es gibt auch Funktionen höherer Ordnung als Built-Ins
+map(add_10, [1,2,3]) #=> [11, 12, 13]
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+
+# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen
+[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. Klassen
+####################################################
+
+# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten.
+class Human(object):
+
+ # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt
+ species = "H. sapiens"
+
+ # Ein simpler Konstruktor
+ def __init__(self, name):
+ # Wir weisen das Argument name dem name-Attribut der Instanz zu
+ self.name = name
+
+ # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument.
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Eine Klassenmethode wird von allen Instanzen geteilt.
+ # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Eine Instanz einer Klasse erstellen
+i = Human(name="Ian")
+print i.say("hi") # gibt "Ian: hi" aus
+
+j = Human("Joel")
+print j.say("hello") #gibt "Joel: hello" aus
+
+# Rufen wir mal unsere Klassenmethode auf
+i.get_species() #=> "H. sapiens"
+
+# Ändern wir mal das gemeinsame Attribut
+Human.species = "H. neanderthalensis"
+i.get_species() #=> "H. neanderthalensis"
+j.get_species() #=> "H. neanderthalensis"
+
+# Aufruf der statischen Methode
+Human.grunt() #=> "*grunt*"
+
+
+####################################################
+## 6. Module
+####################################################
+
+# Wir können Module importieren
+import math
+print math.sqrt(16) #=> 4
+
+# Wir können auch nur spezielle Funktionen eines Moduls importieren
+from math import ceil, floor
+print ceil(3.7) #=> 4.0
+print floor(3.7) #=> 3.0
+
+# Wir können auch alle Funktionen eines Moduls importieren
+# Warnung: Dies wird nicht empfohlen
+from math import *
+
+# Wir können Modulnamen abkürzen
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Module sind in Python nur gewöhnliche Dateien. Wir
+# können unsere eigenen schreiben und importieren. Der Name des
+# Moduls ist der Dateiname.
+
+# Wir können auch die Funktionen und Attribute eines
+# Moduls herausfinden.
+import math
+dir(math)
+
+
+```
+
+## Lust auf mehr?
+
+### Kostenlos online (Englisch)
+
+* [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/)
+
+### Totholz (Englisch)
+
+* [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/fr-fr/coffeescript-fr.html.markdown b/fr-fr/coffeescript-fr.html.markdown
new file mode 100644
index 00000000..c66b7be0
--- /dev/null
+++ b/fr-fr/coffeescript-fr.html.markdown
@@ -0,0 +1,58 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+translators:
+ - ["Geoffrey Roguelon", "https://github.com/GRoguelon"]
+lang: fr-fr
+filename: coffeescript-fr.coffee
+---
+
+``` coffeescript
+# CoffeeScript est un langage préprocesseur, il permet de générer du Javascript.
+# Il suit les tendances de certains langages récents.
+# Par exemple, les commentaires se définissent comme en Ruby ou en Python.
+
+###
+Ceci est un bloc de commentaires
+il est converti directement avec '/ *' et '* /'
+pour correspondre aux commentaires Javascript
+
+Vous devez comprendre la syntaxe du langage JavaScript pour continuer.
+###
+
+# Affectation :
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Structures de contrôle :
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Fonctions :
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+# Intervals :
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objets :
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+#}
+
+# Liste d'arguments variables :
+race = (winner, runners...) ->
+ print winner, runners
+
+# Existance :
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Lecture d'un tableau :
+cubes = (math.cube num for num in list) #=> ...
+```
diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown
index 5efb2f3c..3060bd75 100644
--- a/fr-fr/ruby-fr.html.markdown
+++ b/fr-fr/ruby-fr.html.markdown
@@ -166,7 +166,8 @@ hash['number'] #=> 5
# Recherchez une clé inexistante dans une Hash retourne nil :
hash['nothing here'] #=> nil
-# Depuis Ruby 1.9, Une syntaxe spécifique est apparue en utilisant les symboles comme clés :
+# Depuis Ruby 1.9, Une syntaxe spécifique est apparue
+# en utilisant les symboles comme clés :
new_hash = { defcon: 3, action: true}
@@ -198,10 +199,13 @@ end
# CEPENDANT, l'usage de la boucle for est très rare.
# À la place, utilisez la méthode "each"
# et passez lui un bloc de code.
-# Un bloc de code est un ensemble d'instructions que vous pouvez passer à une methode comme "each".
-# Les blocs sont similaires aux lambdas, les fonctions anonymes ou les closures dans d'autres langages.
+# Un bloc de code est un ensemble d'instructions
+# que vous pouvez passer à une methode comme "each".
+# Les blocs sont similaires aux lambdas, aux fonctions anonymes
+# ou encore aux closures dans d'autres langages.
#
-# La méthode "each" exécute le bloc de code pour chaque élément de l'intervalle d'éléments.
+# La méthode "each" exécute le bloc de code
+# pour chaque élément de l'intervalle d'éléments.
# Le bloc de code passe un paramètre compteur.
# Appelez la méthode "each" avec un bloc de code comme ceci :
diff --git a/go.html.markdown b/go.html.markdown
index e7b35926..4db76a49 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -18,7 +18,7 @@ help with large-scale programming.
Go comes with a great standard library and an enthusiastic community.
-```Go
+```go
// Single line comment
/* Multi-
line comment */
@@ -29,260 +29,260 @@ package main
// Import declaration declares library packages referenced in this file.
import (
- "fmt" // A package in the Go standard library
- "net/http" // Yes, a web server!
- "strconv" // String conversions
+ "fmt" // A package in the Go standard library
+ "net/http" // Yes, a web server!
+ "strconv" // String conversions
)
// A function definition. Main is special. It is the entry point for the
// executable program. Love it or hate it, Go uses brace brackets.
func main() {
- // Println outputs a line to stdout.
- // Qualify it with the package name, fmt.
- fmt.Println("Hello world!")
+ // Println outputs a line to stdout.
+ // Qualify it with the package name, fmt.
+ fmt.Println("Hello world!")
- // Call another function within this package.
- beyondHello()
+ // Call another function within this package.
+ beyondHello()
}
// Functions have parameters in parentheses.
// If there are no parameters, empty parens are still required.
func beyondHello() {
- var x int // Variable declaration. Variables must be declared before use.
- x = 3 // Variable assignment.
- // "Short" declarations use := to infer the type, declare, and assign.
- y := 4
- sum, prod := learnMultiple(x, y) // function returns two values
- fmt.Println("sum:", sum, "prod:", prod) // simple output
- learnTypes() // < y minutes, learn more!
+ var x int // Variable declaration. Variables must be declared before use.
+ x = 3 // Variable assignment.
+ // "Short" declarations use := to infer the type, declare, and assign.
+ y := 4
+ sum, prod := learnMultiple(x, y) // function returns two values
+ fmt.Println("sum:", sum, "prod:", prod) // simple output
+ learnTypes() // < y minutes, learn more!
}
// Functions can have parameters and (multiple!) return values.
func learnMultiple(x, y int) (sum, prod int) {
- return x + y, x * y // return two values
+ return x + y, x * y // return two values
}
// Some built-in types and literals.
func learnTypes() {
- // Short declaration usually gives you what you want.
- s := "Learn Go!" // string type
+ // Short declaration usually gives you what you want.
+ s := "Learn Go!" // string type
- s2 := `A "raw" string literal
+ s2 := `A "raw" string literal
can include line breaks.` // same string type
- // non-ASCII literal. Go source is UTF-8.
- g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point
+ // non-ASCII literal. Go source is UTF-8.
+ g := 'Σ' // rune type, an alias for uint32, holds a UTF-8 code point
- f := 3.14195 // float64, an IEEE-754 64-bit floating point number
- c := 3 + 4i // complex128, represented internally with two float64s
+ f := 3.14195 // float64, an IEEE-754 64-bit floating point number
+ c := 3 + 4i // complex128, represented internally with two float64s
- // Var syntax with an initializers.
- var u uint = 7 // unsigned, but implementation dependent size as with int
- var pi float32 = 22. / 7
+ // Var syntax with an initializers.
+ var u uint = 7 // unsigned, but implementation dependent size as with int
+ var pi float32 = 22. / 7
- // Conversion syntax with a short declaration.
- n := byte('\n') // byte is an alias for uint8
+ // Conversion syntax with a short declaration.
+ n := byte('\n') // byte is an alias for uint8
- // Arrays have size fixed at compile time.
- var a4 [4]int // an array of 4 ints, initialized to all 0
- a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown
+ // Arrays have size fixed at compile time.
+ var a4 [4]int // an array of 4 ints, initialized to all 0
+ a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown
- // Slices have dynamic size. Arrays and slices each have advantages
- // but use cases for slices are much more common.
- s3 := []int{4, 5, 9} // compare to a3. no ellipsis here
- s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0
- var d2 [][]float64 // declaration only, nothing allocated here
- bs := []byte("a slice") // type conversion syntax
+ // Slices have dynamic size. Arrays and slices each have advantages
+ // but use cases for slices are much more common.
+ s3 := []int{4, 5, 9} // compare to a3. no ellipsis here
+ s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0
+ var d2 [][]float64 // declaration only, nothing allocated here
+ bs := []byte("a slice") // type conversion syntax
- p, q := learnMemory() // declares p, q to be type pointer to int.
- fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
+ p, q := learnMemory() // declares p, q to be type pointer to int.
+ fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
- // Maps are a dynamically growable associative array type, like the
- // hash or dictionary types of some other languages.
- m := map[string]int{"three": 3, "four": 4}
- m["one"] = 1
+ // Maps are a dynamically growable associative array type, like the
+ // hash or dictionary types of some other languages.
+ m := map[string]int{"three": 3, "four": 4}
+ m["one"] = 1
- // Unused variables are an error in Go.
- // The underbar lets you "use" a variable but discard its value.
- _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
- // Output of course counts as using a variable.
- fmt.Println(s, c, a4, s3, d2, m)
+ // Unused variables are an error in Go.
+ // The underbar lets you "use" a variable but discard its value.
+ _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
+ // Output of course counts as using a variable.
+ fmt.Println(s, c, a4, s3, d2, m)
- learnFlowControl() // back in the flow
+ learnFlowControl() // back in the flow
}
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
func learnMemory() (p, q *int) {
- // Named return values p and q have type pointer to int.
- p = new(int) // built-in function new allocates memory.
- // The allocated int is initialized to 0, p is no longer nil.
- s := make([]int, 20) // allocate 20 ints as a single block of memory
- s[3] = 7 // assign one of them
- r := -2 // declare another local variable
- return &s[3], &r // & takes the address of an object.
+ // Named return values p and q have type pointer to int.
+ p = new(int) // built-in function new allocates memory.
+ // The allocated int is initialized to 0, p is no longer nil.
+ s := make([]int, 20) // allocate 20 ints as a single block of memory
+ s[3] = 7 // assign one of them
+ r := -2 // declare another local variable
+ return &s[3], &r // & takes the address of an object.
}
func expensiveComputation() int {
- return 1e6
+ return 1e6
}
func learnFlowControl() {
- // If statements require brace brackets, and do not require parens.
- if true {
- fmt.Println("told ya")
- }
- // Formatting is standardized by the command line command "go fmt."
- if false {
- // pout
- } else {
- // gloat
- }
- // Use switch in preference to chained if statements.
- x := 1
- switch x {
- case 0:
- case 1:
- // cases don't "fall through"
- case 2:
- // unreached
- }
- // Like if, for doesn't use parens either.
- for x := 0; x < 3; x++ { // ++ is a statement
- fmt.Println("iteration", x)
- }
- // x == 1 here.
-
- // For is the only loop statement in Go, but it has alternate forms.
- for { // infinite loop
- break // just kidding
- continue // unreached
- }
- // As with for, := in an if statement means to declare and assign y first,
- // then test y > x.
- if y := expensiveComputation(); y > x {
- x = y
- }
- // Function literals are closures.
- xBig := func() bool {
- return x > 100 // references x declared above switch statement.
- }
- fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x)
- x /= 1e5 // this makes it == 10
- fmt.Println("xBig:", xBig()) // false now
-
- // When you need it, you'll love it.
- goto love
+ // If statements require brace brackets, and do not require parens.
+ if true {
+ fmt.Println("told ya")
+ }
+ // Formatting is standardized by the command line command "go fmt."
+ if false {
+ // pout
+ } else {
+ // gloat
+ }
+ // Use switch in preference to chained if statements.
+ x := 1
+ switch x {
+ case 0:
+ case 1:
+ // cases don't "fall through"
+ case 2:
+ // unreached
+ }
+ // Like if, for doesn't use parens either.
+ for x := 0; x < 3; x++ { // ++ is a statement
+ fmt.Println("iteration", x)
+ }
+ // x == 1 here.
+
+ // For is the only loop statement in Go, but it has alternate forms.
+ for { // infinite loop
+ break // just kidding
+ continue // unreached
+ }
+ // As with for, := in an if statement means to declare and assign y first,
+ // then test y > x.
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
+ // Function literals are closures.
+ xBig := func() bool {
+ return x > 100 // references x declared above switch statement.
+ }
+ fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x)
+ x /= 1e5 // this makes it == 10
+ fmt.Println("xBig:", xBig()) // false now
+
+ // When you need it, you'll love it.
+ goto love
love:
- learnInterfaces() // Good stuff coming up!
+ learnInterfaces() // Good stuff coming up!
}
// Define Stringer as an interface type with one method, String.
type Stringer interface {
- String() string
+ String() string
}
// Define pair as a struct with two fields, ints named x and y.
type pair struct {
- x, y int
+ x, y int
}
// Define a method on type pair. Pair now implements Stringer.
func (p pair) String() string { // p is called the "receiver"
- // Sprintf is another public function in package fmt.
- // Dot syntax references fields of p.
- return fmt.Sprintf("(%d, %d)", p.x, p.y)
+ // Sprintf is another public function in package fmt.
+ // Dot syntax references fields of p.
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func learnInterfaces() {
- // Brace syntax is a "struct literal." It evaluates to an initialized
- // struct. The := syntax declares and initializes p to this struct.
- p := pair{3, 4}
- fmt.Println(p.String()) // call String method of p, of type pair.
- var i Stringer // declare i of interface type Stringer.
- i = p // valid because pair implements Stringer
- // Call String method of i, of type Stringer. Output same as above.
- fmt.Println(i.String())
-
- // Functions in the fmt package call the String method to ask an object
- // for a printable representation of itself.
- fmt.Println(p) // output same as above. Println calls String method.
- fmt.Println(i) // output same as above
-
- learnErrorHandling()
+ // Brace syntax is a "struct literal." It evaluates to an initialized
+ // struct. The := syntax declares and initializes p to this struct.
+ p := pair{3, 4}
+ fmt.Println(p.String()) // call String method of p, of type pair.
+ var i Stringer // declare i of interface type Stringer.
+ i = p // valid because pair implements Stringer
+ // Call String method of i, of type Stringer. Output same as above.
+ fmt.Println(i.String())
+
+ // Functions in the fmt package call the String method to ask an object
+ // for a printable representation of itself.
+ fmt.Println(p) // output same as above. Println calls String method.
+ fmt.Println(i) // output same as above
+
+ learnErrorHandling()
}
func learnErrorHandling() {
- // ", ok" idiom used to tell if something worked or not.
- m := map[int]string{3: "three", 4: "four"}
- if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
- fmt.Println("no one there")
- } else {
- fmt.Print(x) // x would be the value, if it were in the map.
- }
- // An error value communicates not just "ok" but more about the problem.
- if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
- // prints "strconv.ParseInt: parsing "non-int": invalid syntax"
- fmt.Println(err)
- }
- // We'll revisit interfaces a little later. Meanwhile,
- learnConcurrency()
+ // ", ok" idiom used to tell if something worked or not.
+ m := map[int]string{3: "three", 4: "four"}
+ if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
+ fmt.Println("no one there")
+ } else {
+ fmt.Print(x) // x would be the value, if it were in the map.
+ }
+ // An error value communicates not just "ok" but more about the problem.
+ if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
+ // prints "strconv.ParseInt: parsing "non-int": invalid syntax"
+ fmt.Println(err)
+ }
+ // We'll revisit interfaces a little later. Meanwhile,
+ learnConcurrency()
}
// c is a channel, a concurrency-safe communication object.
func inc(i int, c chan int) {
- c <- i + 1 // <- is the "send" operator when a channel appears on the left.
+ c <- i + 1 // <- is the "send" operator when a channel appears on the left.
}
// We'll use inc to increment some numbers concurrently.
func learnConcurrency() {
- // Same make function used earlier to make a slice. Make allocates and
- // initializes slices, maps, and channels.
- c := make(chan int)
- // Start three concurrent goroutines. Numbers will be incremented
- // concurrently, perhaps in parallel if the machine is capable and
- // properly configured. All three send to the same channel.
- go inc(0, c) // go is a statement that starts a new goroutine.
- go inc(10, c)
- go inc(-805, c)
- // Read three results from the channel and print them out.
- // There is no telling in what order the results will arrive!
- fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator.
-
- cs := make(chan string) // another channel, this one handles strings.
- cc := make(chan chan string) // a channel of channels.
- go func() { c <- 84 }() // start a new goroutine just to send a value
- go func() { cs <- "wordy" }() // again, for cs this time
- // Select has syntax like a switch statement but each case involves
- // a channel operation. It selects a case at random out of the cases
- // that are ready to communicate.
- select {
- case i := <-c: // the value received can be assigned to a variable
- fmt.Println("it's a", i)
- case <-cs: // or the value received can be discarded
- fmt.Println("it's a string")
- case <-cc: // empty channel, not ready for communication.
- fmt.Println("didn't happen.")
- }
- // At this point a value was taken from either c or cs. One of the two
- // goroutines started above has completed, the other will remain blocked.
-
- learnWebProgramming() // Go does it. You want to do it too.
+ // Same make function used earlier to make a slice. Make allocates and
+ // initializes slices, maps, and channels.
+ c := make(chan int)
+ // Start three concurrent goroutines. Numbers will be incremented
+ // concurrently, perhaps in parallel if the machine is capable and
+ // properly configured. All three send to the same channel.
+ go inc(0, c) // go is a statement that starts a new goroutine.
+ go inc(10, c)
+ go inc(-805, c)
+ // Read three results from the channel and print them out.
+ // There is no telling in what order the results will arrive!
+ fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator.
+
+ cs := make(chan string) // another channel, this one handles strings.
+ cc := make(chan chan string) // a channel of channels.
+ go func() { c <- 84 }() // start a new goroutine just to send a value
+ go func() { cs <- "wordy" }() // again, for cs this time
+ // Select has syntax like a switch statement but each case involves
+ // a channel operation. It selects a case at random out of the cases
+ // that are ready to communicate.
+ select {
+ case i := <-c: // the value received can be assigned to a variable
+ fmt.Println("it's a", i)
+ case <-cs: // or the value received can be discarded
+ fmt.Println("it's a string")
+ case <-cc: // empty channel, not ready for communication.
+ fmt.Println("didn't happen.")
+ }
+ // At this point a value was taken from either c or cs. One of the two
+ // goroutines started above has completed, the other will remain blocked.
+
+ learnWebProgramming() // Go does it. You want to do it too.
}
// A single function from package http starts a web server.
func learnWebProgramming() {
- // ListenAndServe first parameter is TCP address to listen at.
- // Second parameter is an interface, specifically http.Handler.
- err := http.ListenAndServe(":8080", pair{})
- fmt.Println(err) // don't ignore errors
+ // ListenAndServe first parameter is TCP address to listen at.
+ // Second parameter is an interface, specifically http.Handler.
+ err := http.ListenAndServe(":8080", pair{})
+ fmt.Println(err) // don't ignore errors
}
// Make pair an http.Handler by implementing its only method, ServeHTTP.
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Serve data with a method of http.ResponseWriter
- w.Write([]byte("You learned Go in Y minutes!"))
+ // Serve data with a method of http.ResponseWriter
+ w.Write([]byte("You learned Go in Y minutes!"))
}
```
diff --git a/groovy.html.markdown b/groovy.html.markdown
new file mode 100644
index 00000000..e4c2180b
--- /dev/null
+++ b/groovy.html.markdown
@@ -0,0 +1,379 @@
+---
+language: Groovy
+filename: learngroovy.groovy
+contributors:
+ - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
+filename: learngroovy.groovy
+---
+
+Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org)
+
+```cpp
+
+/*
+ Set yourself up:
+
+ 1) Install GVM - http://gvmtool.net/
+ 2) Install Groovy: gvm install groovy
+ 3) Start the groovy console by typing: groovyConsole
+
+*/
+
+// Single line comments start with two forward slashes
+/*
+Multi line comments look like this.
+*/
+
+// Hello World
+println "Hello world!"
+
+/*
+ Variables:
+
+ You can assign values to variables for later use
+*/
+
+def x = 1
+println x
+
+x = new java.util.Date()
+println x
+
+x = -3.1499392
+println x
+
+x = false
+println x
+
+x = "Groovy!"
+println x
+
+/*
+ Collections and maps
+*/
+//Creating an empty list
+def technologies = []
+
+//Add an element to the list
+technologies << "Groovy"
+technologies.add("Grails")
+technologies.addAll(["Gradle","Griffon"])
+
+//Remove an element from the list
+technologies.remove("Griffon")
+
+//Iterate over elements of a list
+technologies.each { println "Technology: $it"}
+technologies.eachWithIndex { it, i -> println "$i: $it"}
+
+//Evaluate if a list contains element(s) (boolean)
+technologies.contains('Groovy')
+technologies.containsAll(['Groovy','Grails'])
+
+//Sort a list
+technologies.sort()
+
+//Replace all elements in the list
+Collections.replaceAll(technologies, 'Gradle', 'gradle')
+
+//Shuffle a list
+Collections.shuffle(technologies, new Random())
+
+//Clear a list
+technologies.clear()
+
+//Creating an empty map
+def devMap = [:]
+
+//Add values
+devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
+devMap.put('lastName','Perez')
+
+//Iterate over elements of a map
+devMap.each { println "$it.key: $it.value" }
+devMap.eachWithIndex { it, i -> println "$i: $it"}
+
+//Evaluate if a map contains a key
+assert devMap.containsKey('name')
+
+//Evaluate if a map contains a value
+assert devMap.containsValue('Roberto')
+
+//Get the keys of a map
+println devMap.keySet()
+
+//Get the values of a map
+println devMap.values()
+
+/*
+ Groovy Beans
+
+ GroovyBeans are JavaBeans but using a much simpler syntax
+
+ When Groovy is compiled to bytecode, the following rules are used.
+
+ * If the name is declared with an access modifier (public, private or protected) then a field is generated.
+ * A name declared with no access modifier generates a private field with public getter and setter (i.e. a property).
+ * If a property is declared final the private field is created final and no setter is generated.
+ * You can declare a property and also declare your own getter or setter.
+ * You can declare a property and a field of the same name, the property will use that field then.
+ * If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected.
+ * If you access a property from within the class the property is defined in at compile time with implicit or explicit this (for example this.foo, or simply foo), Groovy will access the field directly instead of going though the getter and setter.
+ * If you access a property that does not exist using the explicit or implicit foo, then Groovy will access the property through the meta class, which may fail at runtime.
+
+*/
+
+class Foo {
+ // read only property
+ final String name = "Roberto"
+
+ // read only property with public getter and protected setter
+ String language
+ protected void setLanguage(String language) { this.language = language }
+
+ // dynamically typed property
+ def lastName
+}
+
+/*
+ Logical Branching and Looping
+*/
+
+//Groovy supports the usual if - else syntax
+def x = 3
+
+if(x==1) {
+ println "One"
+} else if(x==2) {
+ println "Two"
+} else {
+ println "X greater than Two"
+}
+
+//Groovy also supports the ternary operator:
+def y = 10
+def x = (y > 1) ? "worked" : "failed"
+assert x == "worked"
+
+//For loop
+//Iterate over a range
+def x = 0
+for (i in 0 .. 30) {
+ x += i
+}
+
+//Iterate over a list
+x = 0
+for( i in [5,3,2,1] ) {
+ x += i
+}
+
+//Iterate over an array
+array = (0..20).toArray()
+x = 0
+for (i in array) {
+ x += i
+}
+
+//Iterate over a map
+def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
+x = 0
+for ( e in map ) {
+ x += e.value
+}
+
+/*
+ Operators
+
+ Operator Overloading for a list of the common operators that Groovy supports: http://groovy.codehaus.org/Operator+Overloading
+
+ Helpful groovy operators
+*/
+//Spread operator: invoke an action on all items of an aggregate object.
+def technologies = ['Groovy','Grails','Gradle']
+technologies*.toUpperCase() //equivalent to: technologies.collect { it?.toUpperCase() }
+
+//Safe navigation operator: used to avoid a NullPointerException.
+def user = User.get(1)
+def username = user?.username
+
+
+/*
+ Closures
+ A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point.
+
+ More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition
+*/
+//Example:
+def clos = { println "Hello World!" }
+
+println "Executing the Closure:"
+clos()
+
+//Passing parameters to a closure
+def sum = { a, b -> println a+b }
+sum(2,4)
+
+//Closures may refer to variables not listed in their parameter list.
+def x = 5
+def multiplyBy = { num -> num * x }
+println multiplyBy(10)
+
+//If you have a Closure that takes a single argument, you may omit the parameter definition of the Closure
+def clos = { print it }
+clos( "hi" )
+
+/*
+ Groovy can memorize closure results:
+ More info at:
+ http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
+ http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
+ http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html
+*/
+def cl = {a, b ->
+ sleep(3000) // simulate some time consuming processing
+ a + b
+}
+
+mem = cl.memoize()
+
+def callClosure(a, b) {
+ def start = System.currentTimeMillis()
+ mem(a, b)
+ println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."
+}
+
+callClosure(1, 2)
+callClosure(1, 2)
+callClosure(2, 3)
+callClosure(2, 3)
+callClosure(3, 4)
+callClosure(3, 4)
+callClosure(1, 2)
+callClosure(2, 3)
+callClosure(3, 4)
+
+/*
+ Expando
+
+ The Expando class is a dynamic bean so we can add properties and we can add closures as methods to an instance of this class
+
+ Reference: http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
+*/
+ def user = new Expando(name:"Roberto")
+ assert 'Roberto' == user.name
+
+ user.lastName = 'Pérez'
+ assert 'Pérez' == user.lastName
+
+ user.showInfo = { out ->
+ out << "Name: $name"
+ out << ", Last name: $lastName"
+ }
+
+ def sw = new StringWriter()
+ println user.showInfo(sw)
+
+
+/*
+ Metaprogramming (MOP)
+*/
+
+//Using ExpandoMetaClass to add behaviour
+String.metaClass.testAdd = {
+ println "we added this"
+}
+
+String x = "test"
+x?.testAdd()
+
+//Intercepting method calls
+class Test implements GroovyInterceptable {
+ def sum(Integer x, Integer y) { x + y }
+
+ def invokeMethod(String name, args) {
+ System.out.println "Invoke method $name with args: $args"
+ }
+}
+
+def test = new Test()
+test?.sum(2,3)
+test?.multiply(2,3)
+
+//Groovy supports propertyMissing for dealing with property resolution attempts.
+class Foo {
+ def propertyMissing(String name) { name }
+}
+def f = new Foo()
+
+assertEquals "boo", f.boo
+
+/*
+ TypeChecked and CompileStatic
+ Groovy, by nature, is and will always be a dynamic language but it supports typechecked and compilestatic
+
+ More info: http://www.infoq.com/articles/new-groovy-20
+*/
+//TypeChecked
+import groovy.transform.TypeChecked
+
+void testMethod() {}
+
+@TypeChecked
+void test() {
+ testMeethod()
+
+ def name = "Roberto"
+
+ println naameee
+
+}
+
+//Another example:
+import groovy.transform.TypeChecked
+
+@TypeChecked
+Integer test() {
+ Integer num = "1"
+
+ Integer[] numbers = [1,2,3,4]
+
+ Date date = numbers[1]
+
+ return "Test"
+
+}
+
+//CompileStatic example:
+import groovy.transform.CompileStatic
+
+@CompileStatic
+int sum(int x, int y) {
+ x + y
+}
+
+assert sum(2,5) == 7
+
+
+```
+
+## Further resources
+
+[Groovy documentation](http://groovy.codehaus.org/Documentation)
+
+[Groovy web console](http://groovyconsole.appspot.com/)
+
+Join a [Groovy user group](http://groovy.codehaus.org/User+Groups)
+
+## Books
+
+* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook)
+
+* [Groovy in Action] (http://manning.com/koenig2/)
+
+* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do)
+
+
+
+
+
diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown
new file mode 100644
index 00000000..b3e8c1ca
--- /dev/null
+++ b/hu-hu/go.html.markdown
@@ -0,0 +1,305 @@
+---
+name: Go
+category: language
+language: Go
+filename: learngo.go
+contributors:
+ - ["Sonia Keys", "https://github.com/soniakeys"]
+translators:
+ - ["Szabó Krisztián", "https://github.com/thenonameguy/"]
+---
+
+A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született.
+A mai legújabb programozási trendeket elkerülve,
+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 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.
+
+```Go
+// Egy soros komment
+/* Több
+ soros komment */
+
+// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python csomagkezelésére
+// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz létre egy könyvtár helyett.
+package main
+
+// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a forrásfájlban
+import (
+ "fmt" // A Go alap könyvtárának része
+ "net/http" // Beépített webszerver!
+ "strconv" // Stringek átalakítására szolgáló csomag
+)
+
+// Funkció deklará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 csomag nevével
+ fmt.Println("Hello world!")
+
+ // Meghívunk egy másik funkciót ebből a csomagból
+ beyondHello()
+}
+
+// A függvények paraméterei zárójelek között vannak.
+// Ha nincsenek paraméterek, akkor is kötelező a zárójel-pár.
+func beyondHello() {
+ var x int // Változó deklaráció, használat előtt muszáj ezt megtenni.
+ x = 3 // Változó értékadás
+ // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, definiálja és értéket is ad a változónak
+ y := 4
+ sum, prod := learnMultiple(x, y) // a függvényeknek több visszatérési értéke is lehet
+ fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás
+ learnTypes()
+}
+
+// A funkcióknak elnevezett visszatérési értékük is lehet
+func learnMultiple(x, y int) (sum, prod int) {
+ return x + y, x * y // visszatérünk két értékkel
+ /*
+ sum = x + y
+ prod = x * y
+ return
+ Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor.
+ Üres return esetén, az elnevezett visszatérési változók
+ aktuális értékeikkel térnek vissza. */
+}
+
+// Beépített típusok
+func learnTypes() {
+ // Rövid deklará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
+ újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön típusa
+
+ // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok.
+ g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert tárol
+
+ 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
+
+ // Var szintaxis változó típus definiálással
+ var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az int-nél
+ var pi float32 = 22. / 7
+
+ // Rövid deklarásnál átalakítás is lehetséges
+ n := byte('\n') // byte típus, ami megegyezik az uint8-al
+
+ // A tömböknek fordítás-időben fixált méretük van
+ var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva
+ a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi értékekre
+
+ // 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.
+ 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
+
+ p, q := learnMemory() // deklarál két mutatót (p,q), két int-re
+ fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét.
+
+ // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít
+ // a hash és dictionary típusokra más nyelvekben.
+ m := map[string]int{"three": 3, "four": 4}
+ m["one"] = 1
+
+ // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban.
+ // Az aláhúzással "használod" a változókat, de eldobod az értéküket.
+ _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
+ // Kiíratás is természetesen használatnak minősül
+ fmt.Println(s, c, a4, s3, d2, m)
+
+ learnFlowControl()
+}
+
+// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne mutatók, de nincs mutató aritmetika.
+// Ez azt jelenti, hogy üres mutatóval még mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet.
+func learnMemory() (p, q *int) {
+ // Elnevezett visszatérési változóknak int-re mutató a típusa
+ p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát allokál, és visszaad rá egy mutatót.
+ // Az allokált int nullázva van, p többé nem üres mutató.
+ s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen.
+ s[3] = 7 // adjunk értéket az egyiknek
+ r := -2 // hozzánk létre egy lokális változót
+ return &s[3], &r // A & megadja a memóriacímét a változónak
+}
+
+func expensiveComputation() int {
+ return 1e6
+}
+
+func learnFlowControl() {
+ // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges.
+ if true {
+ fmt.Println("megmondtam")
+ }
+ // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" parancsa szabványosítja
+ if false {
+ // így lehet
+ } else {
+ // if/else-t csinálni
+ }
+ // Használjunk switchet a hosszabb elágazások alkalmazása helyett.
+ x := 1
+ switch x {
+ case 0:
+ case 1:
+ // Az "esetek" nem "esnek át", tehát
+ case 2:
+ // ez nem fog lefutni, nincs szükség break-ekre.
+ }
+ // A for ciklus sem használ zárójeleket
+ for x := 0; x < 3; x++ {
+ fmt.Println("iteráció", x)
+ }
+ // itt az x == 1.
+
+ // A for az egyetlen ciklus fajta a Go-ban, de több formája van.
+ for { // végtelen ciklus
+ 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.
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
+ // Függvényeket használhatjuk closure-ként is.
+ xBig := func() bool {
+ return x > 100 // a switch felett deklarált x-et használjuk itt
+ }
+ fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek)
+ x /= 1e5 // így most már x == 10
+ fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis
+
+ // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t.
+ goto love
+love:
+
+ learnInterfaces() // Itt kezdődnek az érdekes dolgok!
+}
+
+// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a String, ami visszatér egy stringgel.
+type Stringer interface {
+ String() string
+}
+
+// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, x és y.
+type pair struct {
+ x, y int
+}
+
+// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interf
+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
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
+}
+
+func learnInterfaces() {
+ // A kapcsos zárójellel jelezzük, hogy egyből inicializálni
+ // szeretnénk a struktúra változóit a sorrendnek megfelelően.
+ p := pair{3, 4}
+ fmt.Println(p.String()) // meghívjuk a p String metódusát.
+ var i Stringer // deklaráljuk i-t Stringer típusú interfésznek
+ i = p // lehetséges, mert a pair struktúra eleget tesz a Stringer interfésznek
+ // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb.
+ fmt.Println(i.String())
+
+ // Az fmt csomag funckciói automatikusan meghívják a String funkciót
+ // hogy megtudják egy objektum szöveges reprezentációját.
+ fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja a String metódust.
+ fmt.Println(i) // dettó
+
+ learnErrorHandling()
+}
+
+func learnErrorHandling() {
+ // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény.
+ m := map[int]string{3: "three", 4: "four"}
+ if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban.
+ fmt.Println("nincs meg")
+ } else {
+ fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban.
+ }
+ // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden "ok" volt-e
+ if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, úgy se lesz jó jelen esetben
+ // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax"
+ fmt.Println(err)
+ }
+ // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás!
+ learnConcurrency()
+}
+
+// c egy csatorna, egy konkurens-biztos kommunikációs objektum.
+func inc(i int, c chan int) {
+ c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így i+1-et küld be a csatornába
+}
+
+// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat
+func learnConcurrency() {
+ // Ugyan az a make funkció amivel korábban szeleteket hoztunk létre.
+ // Make allokál mapokat, szeleteket és csatornákat.
+ c := make(chan int)
+ // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek
+ // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig paralellizálva/egymás mellett.
+ // Mind a 3 ugyanabba a csatornába küldi az eredményeket.
+ go inc(0, c) // A go utasítás indít el goroutine-okat.
+ go inc(10, c)
+ go inc(-805, c)
+ // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre.
+ // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények!
+ fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a "<-" a beolvasó/kapó operátor
+
+ cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál
+ cc := make(chan chan string) // egy csatorna csatornával
+ go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért hogy küldjünk egy számot
+ go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet küldünk
+ // A select olyan mint a switch, csak feltételek helyett csatorna műveletek vannak.
+ // Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet kommunikáció.
+ select {
+ case i := <-c: // a megkapott értéket el lehet tárolni egy változóban
+ fmt.Println("ez egy", i)
+ case <-cs: // vagy el lehet dobni az értékét
+ fmt.Println("ez egy string volt")
+ case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni
+ fmt.Println("sose futok le :'( ")
+ }
+ // Ezen a ponton vagy c vagy a cs goroutineja lefutott.
+ // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik blokkolva vár.
+
+ learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni.
+}
+
+// Egy funkció a http csomagból elindít egy webszervert.
+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!
+}
+
+// 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
+ w.Write([]byte("Megtanultad a Go-t Y perc alatt!"))
+}
+```
+
+## További olvasmányok
+
+Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/).
+Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten és sok érdekességet olvashatsz.
+
+A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember.
+
+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!
+
diff --git a/ko-kr/java-kr.html.markdown b/ko-kr/java-kr.html.markdown
index dcca9b2e..371b4665 100644
--- a/ko-kr/java-kr.html.markdown
+++ b/ko-kr/java-kr.html.markdown
@@ -1,5 +1,6 @@
---
language: java
+filename: java-kr.java
category: language
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
@@ -26,7 +27,8 @@ import java.util.ArrayList;
// java.security 패키지 안에 있는 모든 클래스를 임포트합니다.
import java.security.*;
-// 각 .java 파일에는 공용(public) 클래스가 들어 있으며, 클래스의 이름은 파일명과 동일합니다.
+// 각 .java 파일에는 공용(public) 클래스가 들어 있으며, 클래스의 이름은
+// 파일명과 동일합니다.
public class LearnJava {
// 프로그램에는 반드시 진입점 역할을 하는 main 메서드가 하나 있어야 합니다.
@@ -253,8 +255,8 @@ public class LearnJava {
// String
// 형변환
- // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이 많을뿐더러
- // 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다.
+ // 자바 객채 또한 형변환할 수 있으며, 이와 관련해서 알아야 할 세부사항이
+ // 많을뿐더러 다소 중급 수준에 해당하는 개념들도 다뤄야 합니다.
// 이와 관련된 사항은 아래 링크를 참고하세요.
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
@@ -403,4 +405,4 @@ class PennyFarthing extends Bicycle {
* [제네릭(Generics)](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [자바 코딩 관례(Java Code Conventions)](http://www.oracle.com/technetwork/java/codeconv-138413.html) \ No newline at end of file
+* [자바 코딩 관례(Java Code Conventions)](http://www.oracle.com/technetwork/java/codeconv-138413.html)
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index b92e3218..9e9f43e7 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -90,7 +90,7 @@ int main (int argc, const char * argv[])
// Array object
NSArray *anArray = @[@1, @2, @3, @4];
NSNumber *thirdNumber = anArray[2];
- NSLog(@"Third number = %@", thirdObject); // Print "Third number = 3"
+ NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3"
// Dictionary object
NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown
index 9031cad9..fc2d1e40 100644
--- a/pt-br/elisp-pt.html.markdown
+++ b/pt-br/elisp-pt.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Bastien Guerry", "http://bzg.fr"]
translators:
- ["Lucas Tadeu Teixeira", "http://ltt.me"]
-lang: pt-br
+lang: pt-br
filename: learn-emacs-lisp-pt.el
---
@@ -30,9 +30,9 @@ filename: learn-emacs-lisp-pt.el
;; Realizar este tutorial não danificará seu computador, a menos
;; que você fique tão irritado a ponto de jogá-lo no chão. Neste caso,
;; me abstenho de qualquer responsabilidade. Divirta-se!
-
+
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
+;;
;; Abra o Emacs.
;;
;; Aperte a tecla `q' para ocultar a mensagem de boas vindas.
@@ -45,11 +45,11 @@ filename: learn-emacs-lisp-pt.el
;; O buffer de rascunho (i.e., "scratch") é o buffer padrão quando
;; o Emacs é aberto. Você nunca está editando arquivos: você está
;; editando buffers que você pode salvar em um arquivo.
-;;
+;;
;; "Lisp interaction" refere-se a um conjunto de comandos disponíveis aqui.
-;;
-;; O Emacs possui um conjunto de comandos embutidos (disponíveis em
-;; qualquer buffer) e vários subconjuntos de comandos disponíveis
+;;
+;; O Emacs possui um conjunto de comandos embutidos (disponíveis em
+;; qualquer buffer) e vários subconjuntos de comandos disponíveis
;; quando você ativa um modo específico. Aqui nós utilizamos
;; `lisp-interaction-mode', que possui comandos para interpretar e navegar
;; em código Elisp.
@@ -137,7 +137,7 @@ filename: learn-emacs-lisp-pt.el
;; => [a tela exibirá duas janelas e o cursor estará no buffer *test*]
;; Posicione o mouse sobre a janela superior e clique com o botão
-;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure
+;; esquerdo para voltar. Ou você pode utilizar `C-xo' (i.e. segure
;; ctrl-x e aperte o) para voltar para a outra janela, de forma interativa.
;; Você pode combinar várias "sexps" com `progn':
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index 8e8ce6a8..484bb0dd 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -1,5 +1,6 @@
---
language: ruby
+lang: br-pt
filename: learnruby.rb
contributors:
- ["Bruno Henrique - Garu", "http://garulab.com"]
@@ -98,9 +99,10 @@ caminho_para_a_raiz_do_projeto = '/bom/nome/'
caminho = '/nome/ruim/'
# Símbolos (são objetos)
-# Símbolos são imutáveis, são constantes reutilizáveis representadadas internamente por um
-# valor inteiro. Eles são frequentemente usados no lugar de strings para transmitir com eficiência os valores
-# específicos e significativos
+# Símbolos são imutáveis, são constantes reutilizáveis representadadas
+# internamente por um valor inteiro. Eles são frequentemente usados no
+# lugar de strings para transmitir com eficiência os valores específicos
+# e significativos
:pendente.class #=> Symbol
diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown
index 48c16192..e1d68e5a 100644
--- a/ru-ru/clojure-ru.html.markdown
+++ b/ru-ru/clojure-ru.html.markdown
@@ -4,7 +4,7 @@ filename: learnclojure-ru.clj
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Alexey Pirogov", "http://twitter.com/alex_pir"]
-
+lang: ru-ru
---
Clojure, это представитель семейства Lisp-подобных языков, разработанный
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 6c5720e3..9133ecca 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -88,7 +88,8 @@ $unescaped = 'This just contains a slash and a t: \t';
// Заключайте переменные в фигурные скобки если это необходимо
$money = "I have $${number} in the bank.";
-// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для неинтерполированного многострочного текста
+// Начиная с PHP 5.3, синтаксис nowdocs может использоваться для
+// неинтерполированного многострочного текста
$nowdoc = <<<'END'
Multi line
string
@@ -210,11 +211,13 @@ echo $integer + $integer; // => 2
$string = '1';
echo $string + $string; // => 2 (строка превращается в число)
-// Выводится 0 по той причине, что оператор + не может привести строку 'one' к числовому типу
+// Выводится 0 по той причине, что оператор + не может привести строку 'one' к
+// числовому типу
$string = 'one';
echo $string + $string; // => 0
-// Приведение типов (type casting) может быть использовано для преобразование переменной в другой тип
+// Приведение типов (type casting) может быть использовано для преобразование
+// переменной в другой тип
$boolean = (boolean) 1; // => true
$zero = 0;
@@ -429,10 +432,11 @@ return 'Anything you like.';
// Эти функции могут также возвращать значения.
$value = include 'my-include.php';
-// Имена файлов содержат их путь в файловой системе, или если передано просто имя файла,
-// PHP обращается к директиве include_path. Если файл не найден в include_path, предпринимается
-// попытка поиска в папке, где выполняется скрипт или в текущей рабочей директории.
-// Если не в одном из этих мест файл не найден - выдается ошибка
+// Имена файлов содержат их путь в файловой системе, или если передано просто
+// имя файла, PHP обращается к директиве include_path. Если файл не найден в
+// include_path, предпринимается попытка поиска в папке, где выполняется скрипт
+// или в текущей рабочей директории. Если не в одном из этих мест файл не
+// найден - выдается ошибка
/* */
/********************************
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 58b0adcc..9163c8aa 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -1,5 +1,6 @@
---
language: python
+lang: ru-ru
contributors:
- ["Yury Timofeev", "http://twitter.com/gagar1n"]
filename: learnpython-ru.py
@@ -219,7 +220,8 @@ filled_dict["four"] # KeyError
# Чтобы избежать этого, используйте метод get
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
-# Метод get также принимает аргумент default, значение которого будет возвращено при отсутствии указанного ключа
+# Метод get также принимает аргумент default, значение которого будет
+# возвращено при отсутствии указанного ключа
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
@@ -314,7 +316,9 @@ try:
# Для выбора ошибки используется raise
raise IndexError("Это IndexError")
except IndexError as e:
- pass # pass это просто отсутствие оператора. Обычно здесь происходит восстановление от ошибки.
+ # pass это просто отсутствие оператора. Обычно здесь происходит
+ # восстановление от ошибки.
+ pass
####################################################
diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown
index 54c1d178..c2a2087b 100644
--- a/ruby-ecosystem.html.markdown
+++ b/ruby-ecosystem.html.markdown
@@ -63,7 +63,7 @@ Very mature/compatible:
* MRI - Written in C, this is the reference implementation of ruby. By
definition it is 100% compatible (with itself). All other rubies
-maintain capatability with MRI (see RubySpec below).
+maintain compatibility with MRI (see [RubySpec](#rubyspec) below).
* JRuby - Written in Java and ruby, this robust implementation is quite fast.
Most importantly, JRuby's strength is JVM/Java interop, leveraging existing
JVM tools, projects, and languages.
diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown
new file mode 100644
index 00000000..50bca246
--- /dev/null
+++ b/tr-tr/c-tr.html.markdown
@@ -0,0 +1,484 @@
+---
+name: c
+category: language
+language: c
+filename: learnc-tr.c
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Haydar KULEKCI", "http://scanf.info/"]
+lang: tr-tr
+
+---
+/*
+C halen modern yüksek performans bilgisayarların dili.
+
+C bir çok programcının kullandığı en düşük seviye dillerdendir, ama
+salt hız ile daha fazlasını karşılar. C'nin bellek yönetiminden iyi
+anlarsanız sizi isteğiniz yere götürecektir.
+
+```c
+// Tek satır yorum // karakterleri ile başlar
+
+/*
+Çoklu satırlı yorumlar bu şekilde görünür.
+*/
+
+// C Standart kütüphanelerini uygulamanıza #include<ornek.h> ile
+// dahil edebilirsiniz.
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+// Kendi başlık(header) dosyalarınız dahil etmek için "çift tırnak"
+// kullanmalısınız.
+#include "my_header.h"
+
+// Fonksiyonlarınızı bir .h dosyasında ya da c dosyanızın üst tarafta
+// tanımlayın.
+
+void function_1();
+void function_2();
+
+// Programınızın giriş noktası main isimli bir fonksiyondur ve
+// integer değer döner
+int main() {
+
+ // çıktıları yazdırmak için printf kullanılır, "print formatted"
+ // %d bir sayı tipidir, \n yeni satır karakteridir
+ printf("%d\n", 0); // => 0 karakteri yazdırılır.
+ // Tüm ifadeler noktalı virgül ile bitmelidir.
+
+ ///////////////////////////////////////
+ // Tipler
+ ///////////////////////////////////////
+
+ // Değişkenleri kullanmadan önce tanımlamalısınız. Bir değişken tanımlarken
+ // tipini belirtmelisiniz; bu tip onun byte olarak boyutunu belirler.
+
+ // int değişken tipi 4 byte boyutundadır.
+ int x_int = 0;
+
+ // short değişken tipi genellikle 2 byte boyutundadır.
+ short x_short = 0;
+
+ // char tipi 1 byte boyutunu garanti eder.
+ char x_char = 0;
+ char y_char = 'y'; // Karakterler '' işaretleri arasına yazılır.
+
+ // long tipi 4-8 byte olur; long long tipi en azından 64 bit garantiler.
+ long x_long = 0;
+ long long x_long_long = 0;
+
+ // float tipi 32-bit kayan noktalı sayı boyutundadır.
+ float x_float = 0.0;
+
+ // double değişken tipi 64-bit kayan noktalı yazı tipindedir.
+ double x_double = 0.0;
+
+ // Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer
+ // olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum
+ // değeri işaretli bir sayının maksimum değeriden büyük olur.
+ unsigned char ux_char;
+ unsigned short ux_short;
+ unsigned int ux_int;
+ unsigned long long ux_long_long;
+
+ // Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler
+ // makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte
+ // cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir
+ // şekilde ifade edilebilir
+ // Örneğin,
+ printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words)
+
+ // If the argument of the `sizeof` operator an expression, then its argument
+ // is not evaluated (except VLAs (see below)).
+ // The value it yields in this case is a compile-time constant.
+ int a = 1;
+ 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)
+
+ // Diziler somut bir boyut ile oluşturulmalıdır.
+ char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar
+ int my_int_array[20]; // Bu dizi 4 * 20 = 80 byte alan kaplar
+ // (4-byte bir word varsayılır)
+
+ // Şu şekilde bir diziyi 0 ile oluşturabilirsiniz:
+ char my_array[20] = {0};
+
+ // Dizinin elemanlarını indexlemek diğer diller gibidir, veya
+ // diğer diller C gibi.
+ my_array[0]; // => 0
+
+ // Diziler değişebilirdir (mutable); O sadece memory!
+ my_array[1] = 2;
+ printf("%d\n", my_array[1]); // => 2
+
+ // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
+ // can be declared as well. The size of such an array need not be a compile
+ // time constant:
+ printf("Enter the array size: "); // ask the user for an array size
+ char buf[0x100];
+ fgets(buf, sizeof buf, stdin);
+
+ // strtoul parses a string to an unsigned integer
+ size_t size = strtoul(buf, NULL, 10);
+ int var_length_array[size]; // declare the VLA
+ printf("sizeof array = %zu\n", sizeof var_length_array);
+
+ // A possible outcome of this program may be:
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
+ // String'ler bir NUL (0x00) byte ile sonlandırılmış karakter dizileridir,
+ // bu string içerisinde özel bir karakter olan '\0' ile gösterilir.
+ // (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek
+ // yoktur; derleyici onu bizim için dizinin sonuna ekler.)
+ char a_string[20] = "This is a string";
+ printf("%s\n", a_string); // %s bir string formatıdır.
+
+ /*
+ a_string 16 karakter uzunluğundadır.
+ 17. karakter NUL karakteridir.
+ 18., 19. ve 20. karakterler tanımsızdır.(undefined)
+ */
+
+ printf("%d\n", a_string[16]); // => 0
+ // i.e., byte #17 is 0 (as are 18, 19, and 20)
+
+ // If we have characters between single quotes, that's a character literal.
+ // It's of type `int`, and *not* `char` (for historical reasons).
+ int cha = 'a'; // fine
+ char chb = 'a'; // fine too (implicit conversion from int to char)
+
+ ///////////////////////////////////////
+ // Operatörler
+ ///////////////////////////////////////
+
+ int i1 = 1, i2 = 2; // Çoklu tanımlama için kısayol.
+ float f1 = 1.0, f2 = 2.0;
+
+ // Aritmatik basittir.
+ i1 + i2; // => 3
+ i2 - i1; // => 1
+ i2 * i1; // => 2
+ i1 / i2; // => 0 (0.5'dir ama 0 a yuvarlanmıştır.)
+
+ f1 / f2; // => 0.5, artı veya eksi epsilon
+
+ // Modüler aritmetikte vardır.
+ 11 % 3; // => 2
+
+ // Karşılaştırma operatörleri muhtemelen tanıdıktır, ama
+ // C'de boolean tipi yoktur. Bunun yerine sayı(int) kullanırız.
+ // 0 false yerine ve diğer herşey true yerine geçmektedir.
+ // (Karşılaştırma operatörleri her zaman 0 veya 1 dönmektedir.)
+ 3 == 2; // => 0 (false)
+ 3 != 2; // => 1 (true)
+ 3 > 2; // => 1
+ 3 < 2; // => 0
+ 2 <= 2; // => 1
+ 2 >= 2; // => 1
+
+ // Sayılar üzerinde mantık işlemleri
+ !3; // => 0 (Logical not)
+ !0; // => 1
+ 1 && 1; // => 1 (Logical and)
+ 0 && 1; // => 0
+ 0 || 1; // => 1 (Logical or)
+ 0 || 0; // => 0
+
+ // Bit boyutunda işlem yapmak için operatörler
+ ~0x0F; // => 0xF0 (bitwise negation)
+ 0x0F & 0xF0; // => 0x00 (bitwise AND)
+ 0x0F | 0xF0; // => 0xFF (bitwise OR)
+ 0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
+ 0x01 << 1; // => 0x02 (bitwise left shift (by 1))
+ 0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
+
+ // Be careful when shifting signed integers - the following are undefined:
+ // - shifting into the sign bit of a signed integer (int a = 1 << 32)
+ // - left-shifting a negative number (int a = -1 << 2)
+ // - shifting by an offset which is >= the width of the type of the LHS:
+ // int a = 1 << 32; // UB if int is 32 bits wide
+
+ ///////////////////////////////////////
+ // Kontrol Yapıları
+ ///////////////////////////////////////
+
+ if (0) {
+ printf("I am never run\n");
+ } else if (0) {
+ printf("I am also never run\n");
+ } else {
+ printf("I print\n");
+ }
+
+ // While Döngüsü
+ int ii = 0;
+ while (ii < 10) {
+ printf("%d, ", ii++); // ii++, ii değişkenini değerini kullandıktan sonra artırır.
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ int kk = 0;
+ do {
+ printf("%d, ", kk);
+ } while (++kk < 10); // ++kk, kk değişkeninin değerini kullanmadan önce artırır.
+ // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // For Döngüsü
+ int jj;
+ for (jj=0; jj < 10; jj++) {
+ printf("%d, ", jj);
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ ///////////////////////////////////////
+ // Tip Dönüşümleri
+ ///////////////////////////////////////
+
+ // C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe
+ // dönüştürebilirsiniz.
+
+ int x_hex = 0x01; // Hex literatüründe değer atayabilirsiniz.
+
+ // Türler arasındaki dönüşümde kendi değerini korumak için çalışacaktır.
+ printf("%d\n", x_hex); // => Prints 1
+ printf("%d\n", (short) x_hex); // => Prints 1
+ printf("%d\n", (char) x_hex); // => Prints 1
+
+ // Tip hiçbir hata vermeden taşacaktır(overflow).
+ printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 eğer karakter 8 bit uzunluğunda ise)
+
+ // `char`, `signed char` ve `unsigned char` karakter tiplerinin maksimum uzunluğunu
+ // belirlemek için <limits.h> kütüphanesindeki CHAR_MAX, SCHAR_MAX ve UCHAR_MAX
+ // macrolarını kullanınız.
+
+ // Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi.
+ printf("%f\n", (float)100); // %f formats a float
+ printf("%lf\n", (double)100); // %lf formats a double
+ printf("%d\n", (char)100.0);
+
+ ///////////////////////////////////////
+ // İşaretçiler (Pointers)
+ ///////////////////////////////////////
+
+ // Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret
+ // edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini
+ // getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz.
+
+ int x = 0;
+ printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır.
+ // (%p işaretçilerin formatıdır)
+ // => Bazı bellek adresleri yazdırılacaktır.
+
+
+ // İşaretçiler tanımlanırken * ile başlar
+ int *px, not_a_pointer; // px sayı tipinde bir işaretçidir.
+ px = &x; // X değişkeninin bellek adresi px değişkeninde tutulmaktadır.
+ printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır.
+ printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer));
+ // => 64-bit sistemde "8, 4" yazdırılacaktır.
+
+ // İşaretçinin adres olarak gösterdiği yerdeki değeri almak için
+ // değişkenin önüne * işareti ekleyiniz.
+ printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir,
+ // çünkü px değişkeni x in adresini göstermektedir.
+
+ // Ayrıca siz işaretçinin gösterdiği yerin değerini
+ // değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz
+ // çünkü ++ işleminin önceliği * işleminden yüksektir.
+ (*px)++; // px'in işaret ettiği değeri 1 artır.
+ printf("%d\n", *px); // => 1 yazdırılır.
+ printf("%d\n", x); // => 1 yazdırılır.
+
+ int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını
+ // tahsis etmek için iyi bir yöntemdir.
+ int xx;
+ for (xx=0; xx<20; xx++) {
+ x_array[xx] = 20 - xx;
+ } // x_array dizisi 20, 19, 18,... 2, 1 değerleri ile oluşturuluyor.
+
+ // Bir sayı tipinde işaretçi tanımlanıyor ve x_array'i işaret ediyor.
+ int* x_ptr = x_array;
+ // x_ptr artık dizinin ilk elemanını işaret etmektedir (the integer 20).
+ // Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk
+ // elemanlarını gösteren birer işaretçidir.
+ // For example, when an array is passed to a function or is assigned to a pointer,
+ // it decays into (implicitly converted to) a pointer.
+ // Exceptions: when the array is the argument of the `&` (address-od) operator:
+ int arr[10];
+ int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`!
+ // It's of type "pointer to array" (of ten `int`s).
+ // or when the array is a string literal used for initializing a char array:
+ char arr[] = "foobarbazquirk";
+ // or when it's the argument of the `sizeof` or `alignof` operator:
+ int arr[10];
+ int *ptr = arr; // equivalent with int *ptr = &arr[0];
+ printf("%zu %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8"
+
+ // Diziler ilk elemanlarını gösteren birer işaretçidirler.
+ printf("%d\n", *(x_ptr)); // => 20 yazılacaktır.
+ printf("%d\n", x_array[0]); // => 20 yazılacaktır.
+
+ // İşaretçiler kendi tiplerinde artırılır ve azaltılır.
+ printf("%d\n", *(x_ptr + 1)); // => 19 yazılacaktır.
+ printf("%d\n", x_array[1]); // => 19 yazılacaktır.
+
+ // Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan
+ // malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon
+ // byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır.
+ int* my_ptr = (int*) malloc(sizeof(int) * 20);
+ for (xx=0; xx<20; xx++) {
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 'de aynı zamanda çalışabilir
+ } // Bellekte 20, 19, 18, 17... 2, 1 (as ints) şeklinde oluşturulmuş olacaktır.
+
+ // Eğer ayrımadığınız bir bellek adresini çağırırsanız
+ // öngörülmeyen bir değer dönecektir.
+ printf("%d\n", *(my_ptr + 21)); // => kim-bilir-ne-yazacak?
+
+ // Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde
+ // onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız
+ // kapatılana kadar belleğin o kısmını kimse kullanamaz.
+ free(my_ptr);
+
+ // Metin Dizileri(String) birer karakter dizisidir(char array), ama
+ // genelde karakter işaretçisi olarak kullanılır.
+ char* my_str = "This is my very own string";
+
+ printf("%c\n", *my_str); // => 'T'
+
+ function_1();
+} // main fonksiyon sonu
+
+///////////////////////////////////////
+// Fonksiyonlar
+///////////////////////////////////////
+
+// Fonksiyon tanımlama sözdizimi:
+// <return type> <fonksiyon adi>(<args>)
+
+int add_two_ints(int x1, int x2){
+ return x1 + x2; // bir değer geri döndürmek için return kullanılır.
+}
+
+/*
+Fonksiyonlar pass-by-value'dür, ama isterseniz işaretçi referanslarını
+kullanarak fonksiyona gönderilen parametrenin değerini değiştirebilirsiniz.
+
+Example: Bir metni tersine çevirme
+*/
+
+// Bir void konksiyonu hiç bir değer dönmez
+void str_reverse(char* str_in){
+ char tmp;
+ int ii=0, len = strlen(str_in); // Strlen C'nin standart kütüphanesinin bir fonksiyonu
+ for(ii=0; ii<len/2; ii++){
+ tmp = str_in[ii];
+ str_in[ii] = str_in[len - ii - 1]; // sondan ii'inci elemanı
+ str_in[len - ii - 1] = tmp;
+ }
+}
+
+/*
+char c[] = "This is a test.";
+str_reverse(c);
+printf("%s\n", c); // => ".tset a si sihT"
+*/
+
+///////////////////////////////////////
+// Kullanıcı Tanımlı Tipler ve Yapılar
+///////////////////////////////////////
+
+// Typedef'ler bir tip takma adı oluşturur.
+typedef int my_type;
+my_type my_type_var = 0;
+
+// Struct'lar bir veri koleksiyonudur.
+struct rectangle {
+ int width;
+ int height;
+};
+
+// It's not generally true that
+// sizeof(struct rectangle) == sizeof(int) + sizeof(int)
+// due to potential padding between the structure members (this is for alignment
+// reasons). [1]
+
+void function_1(){
+
+ struct rectangle my_rec;
+
+ // "." ile yapı üyelerine ulaşılabilir.
+ my_rec.width = 10;
+ my_rec.height = 20;
+
+ // Bir yapının adresini işaretçiye atayabilirsiniz.
+ struct rectangle* my_rec_ptr = &my_rec;
+
+ // İşaretçi üzerinden bir yapıya ulaşabilirsiniz.
+ (*my_rec_ptr).width = 30;
+
+ // ya da -> işareti ile yapının elemanlarına ulaşabilirsiniz.
+ my_rec_ptr->height = 10; // (*my_rec_ptr).height = 10; ile aynıdır.
+}
+
+// Kolaylık sağlamak için bir yapıya typedef tanımlayabilirsiniz.
+typedef struct rectangle rect;
+
+int area(rect r){
+ return r.width * r.height;
+}
+
+///////////////////////////////////////
+// Fonksiyon İşaretçiler
+///////////////////////////////////////
+
+/*
+Çalışma zamanında, fonksiyonların bilinen bir bellek adresleri vardır. Fonksiyon
+işaretçileri fonksiyonları direk olarak çağırmayı sağlayan veya geri bildirim(callback)
+için parametre gönderirken kullanılan başka birer işaretçidirler. Ama, syntax tanımı
+başlangıçta biraz karışık gelebilir.
+
+Örnek: bir işaretçiden str_reverse kullanımı
+*/
+void str_reverse_through_pointer(char * str_in) {
+ // f adında bir fonksiyon işaretçisi tanımlanır.
+ void (*f)(char *); // Signature should exactly match the target function.
+ f = &str_reverse; // Assign the address for the actual function (determined at runtime)
+ (*f)(str_in); // Just calling the function through the pointer
+ // f(str_in); // That's an alternative but equally valid syntax for calling it.
+}
+
+/*
+As long as function signatures match, you can assign any function to the same pointer.
+Function pointers are usually typedef'd for simplicity and readability, as follows:
+*/
+
+typedef void (*my_fnp_type)(char *);
+
+// Gerçek bir işaretçi tanımlandığı zaman ki kullanımı:
+// ...
+// my_fnp_type f;
+
+```
+
+## Daha Fazla Okuma Listesi
+
+[K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)'in bir kopyasını bulundurmak mükemmel olabilir
+
+Diğer bir iyi kaynak ise [Learn C the hard way](http://c.learncodethehardway.org/book/)
+
+It's very important to use proper spacing, indentation and to be consistent with your coding style in general.
+Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the
+[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
+
+Diğer taraftan google sizin için bir arkadaş olabilir.
+
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
diff --git a/whip.html.markdown b/whip.html.markdown
index b8852ecb..3429ec24 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -109,18 +109,18 @@ undefined ; user to indicate a value that hasn't been set
; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dicts'
; or Ruby 'hashes': an unordered collection of key-value pairs.
-{"key1":"value1" "key2":2 3:3}
+{"key1" "value1" "key2" 2 3 3}
; Keys are just values, either identifier, number, or string.
-(def my_dict {my_key:"my_value" "my other key":4})
-; But in Whip, dictionaries get parsed like: value, colon, value;
-; with whitespace between each. So that means
-{"key": "value"
+(def my_dict {my_key "my_value" "my other key" 4})
+; But in Whip, dictionaries get parsed like: value, whitespace, value;
+; with more whitespace between each. So that means
+{"key" "value"
"another key"
-: 1234
+1234
}
; is evaluated to the same as
-{"key":"value" "another key":1234}
+{"key" "value" "another key" 1234}
; Dictionary definitions can be accessed used the `at` function
; (like strings and lists.)
@@ -220,8 +220,8 @@ undefined ; user to indicate a value that hasn't been set
(max (1 2 3 4)) ; 4
; If value is in list or object
(elem 1 (1 2 3)) ; true
-(elem "foo" {"foo":"bar"}) ; true
-(elem "bar" {"foo":"bar"}) ; false
+(elem "foo" {"foo" "bar"}) ; true
+(elem "bar" {"foo" "bar"}) ; false
; Reverse list order
(reverse (1 2 3 4)) ; => (4 3 2 1)
; If value is even or odd
diff --git a/zh-cn/go-zh.html.markdown b/zh-cn/go-zh.html.markdown
index 25fd1f03..8f7cb2af 100644
--- a/zh-cn/go-zh.html.markdown
+++ b/zh-cn/go-zh.html.markdown
@@ -29,7 +29,8 @@ import (
"strconv" // 字符串转换
)
-//函数声明:Main是程序执行的入口。不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。
+// 函数声明:Main是程序执行的入口。
+// 不管你喜欢还是不喜欢,反正G就用了花括号来包住函数体。
func main() {
// 往标准输出打印一行。
// 用包名fmt限制打印函数。
@@ -65,10 +66,10 @@ func learnTypes() {
can include line breaks.` // 同样是String类型
// 非ascii字符。Go使用UTF-8编码。
- g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码
+ g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码
- f := 3.14195 // float64类型,IEEE-754 64位浮点数
- c := 3 + 4i // complex128类型,内部使用两个float64表示
+ f := 3.14195 // float64类型,IEEE-754 64位浮点数
+ c := 3 + 4i // complex128类型,内部使用两个float64表示
// Var变量可以直接初始化。
var u uint = 7 // unsigned 无符号变量,但是实现依赖int型变量的长度
@@ -99,9 +100,9 @@ can include line breaks.` // 同样是String类型
// 下划线 _ 可以使你“使用”一个变量,但是丢弃它的值。
_,_,_,_,_,_,_,_,_ = s2, g, f, u, pi, n, a3, s4, bs
// 输出变量
- fmt.Println(s, c, a4, s3, d2, m)
+ fmt.Println(s, c, a4, s3, d2, m)
- learnFlowControl() // 回到流程控制
+ learnFlowControl() // 回到流程控制
}
// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。
@@ -117,155 +118,159 @@ func learnMemory() (p, q *int) {
}
func expensiveComputation() int {
- return 1e6
+ return 1e6
}
func learnFlowControl() {
// If需要花括号,括号就免了
- if true {
- fmt.Println("told ya")
- }
- // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了,也不用容忍被人的代码风格。
- if false {
- // pout
- } else {
- // gloat
- }
+ if true {
+ fmt.Println("told ya")
+ }
+ // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了,
+ // 也不用容忍被人的代码风格。
+ if false {
+ // pout
+ } else {
+ // gloat
+ }
// 如果太多嵌套的if语句,推荐使用switch
- x := 1
- switch x {
- case 0:
- case 1:
+ x := 1
+ switch x {
+ case 0:
+ case 1:
// 隐式调用break语句,匹配上一个即停止
- case 2:
+ case 2:
// 不会运行
- }
+ }
// 和if一样,for也不用括号
- for x := 0; x < 3; x++ { // ++ 自增
- fmt.Println("iteration", x)
- }
+ for x := 0; x < 3; x++ { // ++ 自增
+ fmt.Println("iteration", x)
+ }
// x在这里还是1。为什么?
// for 是go里唯一的循环关键字,不过它有很多变种
- for { // 无限循环
- break // 骗你的
- continue // 不会运行的
- }
+ for { // 无限循环
+ break // 骗你的
+ continue // 不会运行的
+ }
// 和for一样,if中的:=先给y赋值,然后再和x作比较。
- if y := expensiveComputation(); y > x {
- x = y
- }
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
// 闭包函数
- xBig := func() bool {
- return x > 100 // x是上面声明的变量引用
- }
- fmt.Println("xBig:", xBig()) // true (上面把y赋给x了)
- x /= 1e5 // x变成10
- fmt.Println("xBig:", xBig()) // 现在是false
+ xBig := func() bool {
+ return x > 100 // x是上面声明的变量引用
+ }
+ fmt.Println("xBig:", xBig()) // true (上面把y赋给x了)
+ x /= 1e5 // x变成10
+ fmt.Println("xBig:", xBig()) // 现在是false
// 当你需要goto的时候,你会爱死它的!
- goto love
+ goto love
love:
- learnInterfaces() // 好东西来了!
+ learnInterfaces() // 好东西来了!
}
// 定义Stringer为一个接口类型,有一个方法String
type Stringer interface {
- String() string
+ String() string
}
// 定义pair为一个结构体,有x和y两个int型变量。
type pair struct {
- x, y int
+ x, y int
}
// 定义pair类型的方法,实现Stringer接口。
func (p pair) String() string { // p被叫做“接收器”
// Sprintf是fmt包中的另一个公有函数。
// 用 . 调用p中的元素。
- return fmt.Sprintf("(%d, %d)", p.x, p.y)
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func learnInterfaces() {
// 花括号用来定义结构体变量,:=在这里将一个结构体变量赋值给p。
- p := pair{3, 4}
- fmt.Println(p.String()) // 调用pair类型p的String方法
- var i Stringer // 声明i为Stringer接口类型
- i = p // 有效!因为p实现了Stringer接口(类似java中的塑型)
+ p := pair{3, 4}
+ fmt.Println(p.String()) // 调用pair类型p的String方法
+ var i Stringer // 声明i为Stringer接口类型
+ i = p // 有效!因为p实现了Stringer接口(类似java中的塑型)
// 调用i的String方法,输出和上面一样
- fmt.Println(i.String())
+ fmt.Println(i.String())
- // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。(类似java中的序列化)
- fmt.Println(p) // 输出和上面一样,自动调用String函数。
- fmt.Println(i) // 输出和上面一样。
+ // fmt包中的Println函数向对象要它们的string输出,实现了String方法就可以这样使用了。
+ // (类似java中的序列化)
+ fmt.Println(p) // 输出和上面一样,自动调用String函数。
+ fmt.Println(i) // 输出和上面一样。
- learnErrorHandling()
+ learnErrorHandling()
}
func learnErrorHandling() {
- // ", ok"用来判断有没有正常工作
- m := map[int]string{3: "three", 4: "four"}
- if x, ok := m[1]; !ok { // ok 为false,因为m中没有1
- fmt.Println("no one there")
- } else {
- fmt.Print(x) // 如果x在map中的话,x就是那个值喽。
- }
+ // ", ok"用来判断有没有正常工作
+ m := map[int]string{3: "three", 4: "four"}
+ if x, ok := m[1]; !ok { // ok 为false,因为m中没有1
+ fmt.Println("no one there")
+ } else {
+ fmt.Print(x) // 如果x在map中的话,x就是那个值喽。
+ }
// 错误可不只是ok,它还可以给出关于问题的更多细节。
- if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
- // 输出"strconv.ParseInt: parsing "non-int": invalid syntax"
- fmt.Println(err)
- }
+ if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
+ // 输出"strconv.ParseInt: parsing "non-int": invalid syntax"
+ fmt.Println(err)
+ }
// 待会再说接口吧。同时,
- learnConcurrency()
+ learnConcurrency()
}
// c是channel类型,一个并发安全的通信对象。
func inc(i int, c chan int) {
- c <- i + 1 // <-把右边的发送到左边的channel。
+ c <- i + 1 // <-把右边的发送到左边的channel。
}
// 我们将用inc函数来并发地增加一些数字。
func learnConcurrency() {
// 用make来声明一个slice,make会分配和初始化slice,map和channel。
- c := make(chan int)
- // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。三个都被发送到同一个channel。
- go inc(0, c) // go is a statement that starts a new goroutine.
- go inc(10, c)
- go inc(-805, c)
+ c := make(chan int)
+ // 用go关键字开始三个并发的goroutine,如果机器支持的话,还可能是并行执行。
+ // 三个都被发送到同一个channel。
+ go inc(0, c) // go is a statement that starts a new goroutine.
+ go inc(10, c)
+ go inc(-805, c)
// 从channel中独处结果并打印。
// 打印出什么东西是不可预知的。
- fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。
-
- cs := make(chan string) // 操作string的channel
- cc := make(chan chan string) // 操作channel的channel
- go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字
- go func() { cs <- "wordy" }() // 发送给cs
- // Select类似于switch,但是每个case包括一个channel操作。它随机选择一个准备好通讯的case。
- select {
- case i := <-c: // 从channel接收的值可以赋给其他变量
- fmt.Println("it's a", i)
- case <-cs: // 或者直接丢弃
- fmt.Println("it's a string")
- case <-cc: // 空的,还没作好通讯的准备
- fmt.Println("didn't happen.")
- }
+ fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是接收操作。
+
+ cs := make(chan string) // 操作string的channel
+ cc := make(chan chan string) // 操作channel的channel
+ go func() { c <- 84 }() // 开始一个goroutine来发送一个新的数字
+ go func() { cs <- "wordy" }() // 发送给cs
+ // Select类似于switch,但是每个case包括一个channel操作。
+ // 它随机选择一个准备好通讯的case。
+ select {
+ case i := <-c: // 从channel接收的值可以赋给其他变量
+ fmt.Println("it's a", i)
+ case <-cs: // 或者直接丢弃
+ fmt.Println("it's a string")
+ case <-cc: // 空的,还没作好通讯的准备
+ fmt.Println("didn't happen.")
+ }
// 上面c或者cs的值被取到,其中一个goroutine结束,另外一个保持阻塞。
- learnWebProgramming() // Go很适合web编程,我知道你也想学!
+ learnWebProgramming() // Go很适合web编程,我知道你也想学!
}
// http包中的一个简单的函数就可以开启web服务器。
func learnWebProgramming() {
// ListenAndServe第一个参数指定了监听端口,第二个参数是一个接口,特定是http.Handler。
- err := http.ListenAndServe(":8080", pair{})
- fmt.Println(err) // 不要无视错误。
+ err := http.ListenAndServe(":8080", pair{})
+ fmt.Println(err) // 不要无视错误。
}
// 使pair实现http.Handler接口的ServeHTTP方法。
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 使用http.ResponseWriter返回数据
- w.Write([]byte("You learned Go in Y minutes!"))
+ w.Write([]byte("You learned Go in Y minutes!"))
}
```