summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorMartin Schimandl <martin.schimandl@gmail.com>2015-10-24 07:28:36 +0200
committerMartin Schimandl <martin.schimandl@gmail.com>2015-10-24 07:28:36 +0200
commit28f71ffcccc6d69d4eb6fc2de0f384fe708362f5 (patch)
tree824a79dba743213cef1297a870c97c88e61b6c63
parent543f10b5626a600b27f5fb70212720a17a4f190e (diff)
parentab67a8f4c29309d7fd5e0b1bd3255fe695beb8cf (diff)
Merge remote-tracking branch 'adambard/master'
-rw-r--r--c.html.markdown34
-rw-r--r--coldfusion.html.markdown6
-rw-r--r--csharp.html.markdown29
-rw-r--r--de-de/bash-de.html.markdown223
-rw-r--r--de-de/git-de.html.markdown30
-rw-r--r--de-de/go-de.html.markdown3
-rw-r--r--es-es/ruby-es.html.markdown247
-rw-r--r--fr-fr/python-fr.html.markdown3
-rw-r--r--haskell.html.markdown8
-rw-r--r--id-id/xml-id.html.markdown2
-rw-r--r--java.html.markdown22
-rw-r--r--javascript.html.markdown67
-rw-r--r--json.html.markdown44
-rw-r--r--julia.html.markdown4
-rw-r--r--matlab.html.markdown7
-rw-r--r--ms-my/coffeescript-my.html.markdown105
-rw-r--r--objective-c.html.markdown10
-rw-r--r--php.html.markdown80
-rw-r--r--pt-br/matlab-pt.html.markdown540
-rw-r--r--python.html.markdown69
-rw-r--r--python3.html.markdown69
-rw-r--r--pythonstatcomp.html.markdown (renamed from pythonstatcomp.markdown.html)0
-rw-r--r--r.html.markdown107
-rw-r--r--ruby.html.markdown1
-rw-r--r--tmux.html.markdown2
-rw-r--r--whip.html.markdown9
-rw-r--r--xml.html.markdown7
27 files changed, 1574 insertions, 154 deletions
diff --git a/c.html.markdown b/c.html.markdown
index a8f71057..3d632eab 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -445,6 +445,17 @@ int main (int argc, char** argv)
for (xx = 0; xx < 20; xx++) {
*(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
+
+ // Note that there is no standard way to get the length of a
+ // dynamically allocated array in C. Because of this, if your arrays are
+ // going to be passed around your program a lot, you need another variable
+ // to keep track of the number of elements (size) of an array. See the
+ // functions section for more info.
+ int size = 10;
+ int *my_arr = malloc(sizeof(int) * size);
+ // Add an element to the array
+ my_arr = realloc(my_arr, ++size);
+ my_arr[10] = 5;
// Dereferencing memory that you haven't allocated gives
// "unpredictable results" - the program is said to invoke "undefined behavior"
@@ -530,6 +541,29 @@ swapTwoNumbers(&first, &second);
printf("first: %d\nsecond: %d\n", first, second);
// values will be swapped
*/
+
+/*
+With regards to arrays, they will always be passed to functions
+as pointers. Even if you statically allocate an array like `arr[10]`,
+it still gets passed as a pointer to the first element in any function calls.
+Again, there is no standard way to get the size of a dynamically allocated
+array in C.
+*/
+// Size must be passed!
+// Otherwise, this function has no way of knowing how big the array is.
+void printIntArray(int *arr, int size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ printf("arr[%d] is: %d\n", i, arr[i]);
+ }
+}
+/*
+int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+int size = 10;
+printIntArray(my_arr, size);
+// will print "arr[0] is: 1" etc
+*/
+
// if referring to external variables outside function, must use extern keyword.
int i = 0;
void testFunc() {
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index e2f0737d..70804a1e 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -1,14 +1,14 @@
---
-language: ColdFusion
+language: coldfusion
+filename: learncoldfusion.cfm
contributors:
- ["Wayne Boka", "http://wboka.github.io"]
-filename: LearnColdFusion.cfm
---
ColdFusion is a scripting language for web development.
[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
-```ColdFusion
+```html
<em>HTML tags have been provided for output readability</em>
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 31c0417e..dfdd98de 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -913,6 +913,35 @@ on a new line! ""Wow!"", the masses cried";
public DbSet<Bicycle> Bikes { get; set; }
}
+
+ // Classes can be split across multiple .cs files
+ // A1.cs
+ public partial class A
+ {
+ public static void A1()
+ {
+ Console.WriteLine("Method A1 in class A");
+ }
+ }
+
+ // A2.cs
+ public partial class A
+ {
+ public static void A2()
+ {
+ Console.WriteLine("Method A2 in class A");
+ }
+ }
+
+ // Program using the partial class "A"
+ public class Program
+ {
+ static void Main()
+ {
+ A.A1();
+ A.A2();
+ }
+ }
} // End Namespace
```
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index fb9cd9d4..541d28bb 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -28,18 +28,50 @@ echo Hello, world!
echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile'
# Variablen deklariert man so:
-VARIABLE="irgendein String"
+Variable="irgendein String"
# Aber nicht so:
-VARIABLE = "irgendein String"
-# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
+Variable = "irgendein String"
+# Bash wird 'Variable' für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
# weil es den Befehl nicht findet.
+# Und so auch nicht:
+Variable= 'Some string'
+# Bash wird 'Variable' wieder für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben,
+# Hier wird der Teil 'Variable=' als nur für diesen einen Befehl gültige Zuweisung an die Variable gesehen.
+
# Eine Variable wird so benutzt:
-echo $VARIABLE
-echo "$VARIABLE"
-# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –,
+echo $Variable
+echo "$Variable"
+echo ${Variable}
+# aber
+echo '$Variable'
+# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anderes –,
# dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen.
+# Beachte: ' (Hochkomma) verhindert das Interpretieren der Variablen
+
+# Ersetzen von Zeichenketten in Variablen
+echo ${Variable/irgendein/neuer}
+# Ersetzt das erste Vorkommen von "irgendein" durch "neuer"
+
+# Teil einer Zeichenkette
+Laenge=7
+echo ${Variable:0:Laenge}
+# Gibt nur die ersten 7 Zeichen zurück
+
+# Standardwert verwenden
+echo ${Foo:-"ErsatzWennLeerOderUngesetzt"}
+# Das funktioniert mit nicht gesetzten Variablen (Foo=) und leeren Zeichenketten (Foo="")
+# Die Zahl 0 (Foo=0) liefert 0.
+# Beachte: der wert der Variablen wird nicht geändert
+
+# Eingebaute Variable (BUILTINS):
+# Einige nützliche Beispiele
+echo "Rückgabewert des letzten Befehls: $?"
+echo "Die PID des skripts: $$"
+echo "Anzahl der Argumente beim Aufruf: $#"
+echo "Alle Argumente beim Aufruf: $@"
+echo "Die Argumente in einzelnen Variablen: $1 $2..."
# Einen Wert aus der Eingabe lesen:
echo "Wie heisst du?"
@@ -47,14 +79,30 @@ read NAME # Wir mussten nicht mal eine neue Variable deklarieren
echo Hello, $NAME!
# Wir haben die übliche if-Struktur:
-if true
+# 'man test' liefert weitere Informationen zu Bedingungen
+if [ "$NAME" -ne $USER ]
then
- echo "Wie erwartet"
+ echo "Dein Name ist nicht dein Login-Name"
else
- echo "Und dies nicht"
+ echo "Dein Name ist dein Login-Name"
+fi
+
+# Es gibt auch bedingte Ausführung
+echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschlägt"
+echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat"
+
+# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern:
+if [ $NAME == "Steve" ] && [ $Alter -eq 15 ]
+then
+ echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15."
+fi
+
+if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+then
+ echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'."
fi
-# Ausdrücke werden im folgenden Format festgehalten:
+# Ausdrücke haben folgendes Format:
echo $(( 10 + 5 ))
# Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen.
@@ -69,13 +117,60 @@ ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf
# txt-Dateien im aktuellen Verzeichnis auflisten:
ls -l | grep "\.txt"
-# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden:
+# Ein- und Ausgabe können umgeleitet werden (stdin, stdout, and stderr).
+# Von stdin lesen bis "EOF" allein in einer Zeile auftaucht
+# und die Datei hello.py mit den Zeilen zwischen den beiden "EOF"
+# überschreiben:
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ import print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("#stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Führe hello.py mit verschiedenen Umleitungen von
+# stdin, stdout und stderr aus:
+python hello.py < "input.in"
+python hello.py > "output.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# Die Fehlerausgabe würde die Datei "error.err" überschreiben (falls sie existiert)
+# verwende ">>" um stattdessen anzuhängen:
+python hello.py >> "output.out" 2>> "error.err"
+
+# Überschreibe output.out, hänge an error.err an und zähle die Zeilen beider Dateien:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Führe einen Befehl aus und gib dessen "file descriptor" (zB /dev/fd/123) aus
+# siehe: man fd
+echo <(echo "#helloworld")
+
+# Mehrere Arten, um output.out mit "#helloworld" zu überschreiben:
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Löschen der Hilfsdateien von oberhalb, mit Anzeige der Dateinamen
+# (mit '-i' für "interactive" erfolgt für jede Date eine Rückfrage)
+rm -v output.out error.err output-and-error.log
+
+# Die Ausgabe von Befehlen kann mit Hilfe von $( ) in anderen Befehlen verwendet weden:
# Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse
# im aktuellen Verzeichnis an.
echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse."
+# Dasselbe kann man mit "backticks" `` erreichen, aber diese können
+# nicht verschachtelt werden. $() ist die empfohlene Methode.
+echo "Dieser Ordner beinhaltet `ls | wc -l` Dateien und Verzeichnisse."
+
# Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält.
-case "$VARIABLE"
+case "$Variable"
in
# Liste der Fälle, die unterschieden werden sollen
0) echo "Hier ist eine Null."
@@ -83,10 +178,106 @@ in
*) echo "Das ist nicht Null."
esac
-# loops iterieren über die angegebene Zahl von Argumenten:
-# Der Inhalt von $VARIABLE wird dreimal ausgedruckt.
-for $VARIABLE in x y z
+# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten:
+# Der Inhalt von $Variable wird dreimal ausgedruckt.
+for $Variable in {1..3}
do
- echo "$VARIABLE"
+ echo "$Variable"
done
+
+# Oder verwende die "traditionelle 'for'-Schleife":
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Schleifen können auch mit Dateien arbeiten:
+# 'cat' zeigt zuerst file1 an und dann file2
+for Variable in file1 file2
+do
+ cat "$Variable"
+done
+
+# .. oder mit der Ausgabe eines Befehls:
+# Ausgabe des Inhalts jeder Datei, die von 'ls' aufgezählt wird
+for Output in $(ls)
+do
+ cat "$Output"
+done
+
+# while Schleife:
+while [ true ]
+do
+ echo "Schleifenkörper..."
+ break
+done
+
+# Funktionen definieren
+# Definition:
+function foo ()
+{
+ echo "Argumente funktionieren wie bei skripts: $@"
+ echo Und: $1 $2..."
+ echo "Dies ist eine Funktion"
+ return 0
+}
+
+# oder einfacher
+bar ()
+{
+ echo "Auch so kann man Funktionen deklarieren!"
+ return 0
+}
+
+# Aufruf der Funktion:
+foo "My name is" $Name
+
+# Was du noch lernen könntest:
+# Ausgabe der letzten 10 Zeilen von file.txt
+tail -n 10 file.txt
+# Ausgabe der ersten 10 Zeilen von file.txt
+head -n 10 file.txt
+# sortierte Ausgabe von file.txt
+sort file.txt
+# Mehrfachzeilen in sortierten Dateien unterdrücken
+# oder (mit -d) nur diese ausgeben
+uniq -d file.txt
+# Ausgabe nur der ersten Spalte (vor dem ersten ',')
+cut -d ',' -f 1 file.txt
+# ersetze in file.txt jedes vorkommende 'gut' durch 'super' (versteht regex)
+sed -i 's/gut/super/g' file.txt
+# Ausgabe nach stdout aller Zeilen von file.txt, die auf eine regex passen
+# Im Beispiel: Zeilen, die mit "foo" beginnen und mit "bar" enden
+grep "^foo.*bar$" file.txt
+# Mit der Option "-c" wird stattdessen die Anzahl der gefundenen Zeilen ausgegeben
+grep -c "^foo.*bar$" file.txt
+# verwende 'fgrep' oder 'grep -F' wenn du buchstäblich nach den Zeichen
+# suchen willst, ohne sie als regex zu interpretieren
+fgrep "^foo.*bar$" file.txt
+
+# Dokumentation über die in bash eingebauten Befehle
+# bekommst du mit dem eingebauten Befehl 'help'
+help
+help help
+help for
+help return
+help source
+help .
+
+# Das bash-Handbuch liest du mit 'man'
+apropos bash
+man 1 bash
+man bash
+
+# Dann gibt es noch das 'info' System (drücke ? um Hilfe angezeigt zu bekommen)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+# info Dokumentation über bash:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
```
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 43939129..dea329d5 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -18,12 +18,12 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit*
### Was ist Versionsverwaltung?
-Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit.
+Eine Versionsverwaltung 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.
+* Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien.
+* Verteilte Versionsverwaltung 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)
@@ -61,7 +61,7 @@ Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arb
### 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!
+Ein Commit ist ein Schnappschuss von Änderungen 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 Repositories gepusht werden. Oder nicht!
### Branch
@@ -69,7 +69,9 @@ Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den 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.
+HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD.
+
+Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Repository kann eine beliebige Zahl von *heads* enthalten.
### Konzeptionelle Hintergründe
@@ -127,7 +129,7 @@ Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-reposi
```bash
-# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an
+# Zeigt den Branch, nicht-verfolgte Dateien, Änderungen und andere Unterschiede an
$ git status
# Anderes Wissenswertes über git status anzeigen
@@ -151,7 +153,7 @@ $ git add ./*.java
### branch
-Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen.
+Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erzeugen oder löschen.
```bash
# Liste alle bestehenden Branches und Remotes auf
@@ -186,7 +188,7 @@ $ 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.
+Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für jedes geklonte Repository remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen.
```bash
# Klone learnxinyminutes-docs
@@ -288,16 +290,16 @@ $ git mv -f myFile existingFile
### pull
-Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch.
+Führe einen Pull (zieht alle Daten eines Repositories) aus und führt 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.
+# Update deines lokalen Repos, indem ein Merge der neuen Änderungen
+# von den remote-liegenden "origin"- und "master"-Branches durchgeführt 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
+# Führt einen Merge von Änderungen 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
```
@@ -337,8 +339,8 @@ $ 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
+# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unberührt)
+# Alle Änderungen bleiben im Verzeichnis erhalten
$ git reset 31f2bb1
# Bewegt die Spitze des Branches zurück zu dem angegebenen Commit
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index 765372e0..7e61bf81 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -3,6 +3,7 @@ language: Go
filename: learngo-de.go
contributors:
- ["Joseph Adams", "https://github.com/jcla1"]
+ - ["Dennis Keller", "https://github.com/denniskeller"]
lang: de-de
---
Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in
@@ -306,7 +307,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
## Weitere Resourcen
Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/).
-Dort können sie der Tutorial folgen, interaktiv Quelltext ausprobieren und viel
+Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel
Dokumentation lesen.
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
index 66a5d0fe..d8b67fe7 100644
--- a/es-es/ruby-es.html.markdown
+++ b/es-es/ruby-es.html.markdown
@@ -5,8 +5,18 @@ contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
- ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
translators:
- ["Camilo Garrido", "http://www.twitter.com/hirohope"]
+ - ["Erick Bernal", "http://www.twitter.com/billowkib"]
lang: es-es
---
@@ -33,6 +43,8 @@ Tu tampoco deberías
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
# La aritmética es sólo azúcar sintáctico
# para llamar un método de un objeto
@@ -55,8 +67,6 @@ false.class #=> FalseClass
# Desigualdad
1 != 1 #=> false
2 != 1 #=> true
-!true #=> false
-!false #=> true
# Además de 'false', 'nil' es otro valor falso
@@ -70,14 +80,29 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+# Operadores lógicos
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Existen versiones alternativas de los operadores lógicos con menor prioridad
+# Estos son usados como constructores controladores de flujo que encadenan
+# sentencias hasta que una de ellas retorne verdadero o falso
+
+# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero.
+has_algo() and has_otra_cosa()
+# `registra_error` solo se llama si `has_algo` falla
+has_algo() or registra_error()
+
+
# Los strings son objetos
'Soy un string'.class #=> String
"Soy un string también".class #=> String
-referente = "usar interpolacion de strings"
+referente = "usar interpolación de strings"
"Yo puedo #{referente} usando strings de comillas dobles"
-#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles"
+#=> "Yo puedo usar interpolación de strings usando strings de comillas dobles"
# Imprime a la salida estándar
@@ -119,15 +144,16 @@ status == :aprovado #=> false
# Arreglos
# Esto es un arreglo
-[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+arreglo = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arreglos pueden contener elementos de distintos tipos
-arreglo = [1, "hola", false] #=> => [1, "hola", false]
+[1, "hola", false] #=> => [1, "hola", false]
# Arreglos pueden ser indexados
# Desde el frente
arreglo[0] #=> 1
+arreglo.first #=> 1
arreglo[12] #=> nil
# Tal como la aritmética, el acceso como variable[índice]
@@ -138,15 +164,25 @@ arreglo.[] 12 #=> nil
# Desde el final
arreglo[-1] #=> 5
+arreglo.last #=> 5
+
+# Con un índice de inicio y longitud
+arreglo[2, 3] #=> [3, 4, 5]
-# Con un índice de inicio y final
-arreglo[2, 4] #=> [3, 4, 5]
+# Invertir un arreglo
+a = [1, 2, 3]
+a.reverse! #=> [3, 2, 1]
# O con rango
arreglo[1..3] #=> [2, 3, 4]
# Añade elementos a un arreglo así
arreglo << 6 #=> [1, 2, 3, 4, 5, 6]
+# O así
+arreglo.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+#Verifica si un elemento ya existe en ese arreglo
+arreglo.include?(1) #=> true
# Hashes son los diccionarios principales de Ruby con pares llave/valor.
# Hashes se denotan con llaves:
@@ -161,17 +197,16 @@ hash['numero'] #=> 5
# Preguntarle a un hash por una llave que no existe retorna 'nil':
hash['nada aqui'] #=> nil
-# Itera sobre un hash con el método 'each':
-hash.each do |k, v|
- puts "#{k} is #{v}"
-end
-
# Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave:
nuevo_hash = { defcon: 3, accion: true}
nuevo_hash.keys #=> [:defcon, :accion]
+# Verifica la existencia de llaves y valores en el hash
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
# Tip: Tanto los arreglos como los hashes son Enumerable (enumerables)
# Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más
@@ -194,9 +229,15 @@ end
#=> iteracion 4
#=> iteracion 5
-# Aunque
-# Nadie usa los ciclos `for`
-# Usa `each`, así:
+# SIN EMBARGO, nadie usa ciclos `for`
+# En su lugar debes usar el método "each" y pasarle un block (bloque).
+# Un bloque es un fragmento código que puedes pasar a métodos como `each`.
+# Es símilar a las funciones lambda, funciones anónimas o `closures` en otros
+# lenguajes de programación.
+#
+# El método `each` de un Range (rango) ejecuta el bloque una vez por cada elemento.
+# Al bloque se le pasa un contador como parametro.
+# Usar el método `each` con un bloque se ve así:
(1..5).each do |contador|
puts "iteracion #{contador}"
@@ -207,10 +248,27 @@ end
#=> iteracion 4
#=> iteracion 5
-counter = 1
-while counter <= 5 do
- puts "iteracion #{counter}"
- counter += 1
+# También puedes envolver el bloque entre llaves:
+(1..5).each { |counter| puts "iteración #{contador}" }
+
+#El contenido de las estructuras de datos en ruby puede ser iterado usando `each`.
+arreglo.each do |elemento|
+ puts "#{elemento} es parte del arreglo"
+end
+hash.each do |llave, valor|
+ puts "#{llave} es #{valor}"
+end
+
+# Si aún necesitas un índice puedes usar "each_with_index" y definir una variable
+# índice.
+arreglo.each_with_index do |element, index|
+ puts "#{element} tiene la posición #{index} en el arreglo"
+end
+
+contador = 1
+while contador <= 5 do
+ puts "iteracion #{contador}"
+ contador += 1
end
#=> iteracion 1
#=> iteracion 2
@@ -218,6 +276,19 @@ end
#=> iteracion 4
#=> iteracion 5
+# Hay una gran variedad de otras funciones iterativas útiles en Ruby,
+# por ejemplo `map`, `reduce`, `inject`, entre otras. Map, por ejemplo,
+# toma el arreglo sobre el cuál está iterando, le hace cambios
+# definidos en el bloque, y retorna un arreglo completamente nuevo.
+arreglo = [1,2,3,4,5]
+duplicado = array.map do |elemento|
+ elemento * 2
+end
+puts duplicado
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
nota = 'B'
case nota
@@ -234,6 +305,34 @@ when 'F'
else
puts "Sistema alternativo de notas, ¿eh?"
end
+#=> "Mejor suerte para la proxima"
+
+# Los casos también pueden usar rangos
+nota = 82
+
+case nota
+when 90..100
+ puts 'Excelente!'
+when 80..100
+ puts 'Buen trabajo'
+else
+ puts '¡Reprobaste!'
+end
+#=> "Buen trabajo"
+
+# Manejo de excepciones
+begin
+ # código que podría causar excepción
+ raise NoMemoryError, 'Se te acabó la memoria'
+rescue NoMemoryError => variable_de_excepcion
+ puts 'El error NoMemoryError ocurrió', variable_de_excepcion
+rescue RuntimeError => otra_variable_de_excepcion
+ puts 'El error RuntimeError ocurrió'
+else
+ puts 'Esto se ejecuta si ningun error ocurrió'
+ensure
+ puts 'Este código siempre se ejecuta, sin importar que'
+end
# Funciones
@@ -244,7 +343,7 @@ end
# Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción
doble(2) #=> 4
-# Paréntesis son opcionales cuando el resultado es ambiguo
+# Paréntesis son opcionales cuando el resultado no es ambiguo
doble 3 #=> 6
doble doble 3 #=> 12
@@ -259,7 +358,7 @@ suma 3, 4 #=> 7
suma suma(3,4), 5 #=> 12
# yield
-# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp
+# Todos los métodos tienen un parámetro bloque opcional e implícito
# puede llamarse con la palabra clave 'yield'
def alrededor
@@ -274,6 +373,17 @@ alrededor { puts 'hola mundo' }
# hola mundo
# }
+# Puedes pasar un bloque a una función
+# '&' representa una referencia a un bloque
+def visitantes(&bloque)
+ bloque.call
+end
+
+# Puedes pasar una lista de argumentos, que serán convertidos en un arreglo
+# Para eso sirve el operador ('*')
+def visitantes(*arreglo)
+ arreglo.each { |visitante| puts visitante }
+end
# Define una clase con la palabra clave 'class'
class Humano
@@ -299,16 +409,26 @@ class Humano
@nombre
end
+ # La funcionalidad anterior puede ser encapsulada usando el método attr_accessor
+ # de la siguiente manera
+
+ attr_accessor :name
+
+ # Los métodos de tipo getter y setter también se pueden crear de manera individual
+ # de la siguiente manera
+
+ attr_reader :name
+ attr_writer :name
+
# Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia.
# Sólo puede ser llamado en la clase, no por una instancia.
def self.decir(mensaje)
- puts "#{mensaje}"
+ puts mensaje
end
def especie
@@especie
end
-
end
@@ -328,6 +448,23 @@ dwight.nombre #=> "Dwight K. Schrute"
# Llama el método de clase
Humano.decir("Hi") #=> "Hi"
+# El alcance de las variables es definido por la manera en que las nombramos.
+# Las variables que inician con $ tienen un alcance global
+$var = "Soy una variable global"
+defined? $var #=> "global-variable"
+
+# Las variables que empiezan con @ tienen un alcance de instancia
+@var = "Soy una variable de instancia"
+defined? @var #=> "instance-variable"
+
+# Variables que empiezan con @@ tienen un alcance de clase
+@@var = "Soy una variable de clase"
+defined? @@var #=> "class variable"
+
+# Las variables que empiezan con letra mayuscula son constantes
+Var = "Soy una constante"
+defined? Var #=> "constant"
+
# Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia.
# Variables de clase son compartidas a través de la clase y todos sus descendientes.
@@ -371,7 +508,67 @@ end
class Doctor < Humano
end
-Human.bar # 0
+Humano.bar # 0
Doctor.bar # nil
+module ModuloEjemplo
+ def foo
+ 'foo'
+ end
+end
+
+# Al incluir un módulo sus métodos se comparten con las instancias de la clase
+# Al extender un módulo sus métodos se comparten con la clase misma
+
+class Persona
+ include ModuloEjemplo
+end
+
+class Libro
+ extend ModuloEjemplo
+end
+
+Persona.foo # => NoMethodError: undefined method `foo' for Persona:Class
+Persona.new.foo # => 'foo'
+Libro.foo # => 'foo'
+Libro.new.foo # => NoMethodError: undefined method `foo'
+
+# Las llamadas de retorno (callbacks) son ejecutadas cuando se incluye o
+# extiende un módulo
+module EjemploConcern
+ def self.incluido(base)
+ base.extend(MetodosClase)
+ base.send(:include, MetodosInstancia)
+ end
+
+ module MetodosClase
+ def bar
+ 'bar'
+ end
+ end
+
+ module MetodosInstancia
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Algo
+ include EjemploConcern
+end
+
+Algo.bar #=> 'bar'
+Algo.qux #=> NoMethodError: undefined method `qux'
+Algo.new.bar # => NoMethodError: undefined method `bar'
+Algo.new.qux # => 'qux'
```
+
+## Recursos adicionales
+- [Aprende Ruby Mediante Ejemplo con Ejercicios](http://www.learneroo.com/modules/61/nodes/338) - Una variante de
+esta referencia con ejercicios en navegador.
+- [Documentación Oficial](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby desde otros lenguajes](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programando Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una
+[edición antigua](http://ruby-doc.com/docs/ProgrammingRuby/) gratuita disponible en línea.
+- [Guía de estilo de Ruby](https://github.com/bbatsov/ruby-style-guide) - Guía de estilo creada por la comunidad.
diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown
index 3f6dcabb..d78291be 100644
--- a/fr-fr/python-fr.html.markdown
+++ b/fr-fr/python-fr.html.markdown
@@ -14,8 +14,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu
Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
-NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x
-Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/).
+N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/).
```python
# Une ligne simple de commentaire commence par un dièse
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 369b1b20..08611e63 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -195,11 +195,11 @@ foo 5 -- 15
-- function composition
-- the (.) function chains functions together.
-- For example, here foo is a function that takes a value. It adds 10 to it,
--- multiplies the result of that by 5, and then returns the final value.
-foo = (*5) . (+10)
+-- multiplies the result of that by 4, and then returns the final value.
+foo = (*4) . (+10)
--- (5 + 10) * 5 = 75
-foo 5 -- 75
+-- (5 + 10) * 4 = 60
+foo 5 -- 60
-- fixing precedence
-- Haskell has another operator called `$`. This operator applies a function
diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown
index c1e985aa..8b8d72ae 100644
--- a/id-id/xml-id.html.markdown
+++ b/id-id/xml-id.html.markdown
@@ -1,6 +1,6 @@
---
language: xml
-filename: learnxml.xml
+filename: learnxml-id.xml
contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
translators:
diff --git a/java.html.markdown b/java.html.markdown
index c2c1a18b..aae64ccf 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Simon Morgan", "http://sjm.io/"]
- ["Zachary Ferguson", "http://github.com/zfergus2"]
- ["Cameron Schermerhorn", "http://github.com/cschermerhorn"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
filename: LearnJava.java
---
@@ -137,7 +138,7 @@ public class LearnJava {
//
// BigDecimal allows the programmer complete control over decimal
// rounding. It is recommended to use BigDecimal with currency values
- // and where exact decimal percision is required.
+ // and where exact decimal precision is required.
//
// BigDecimal can be initialized with an int, long, double or String
// or by initializing the unscaled value (BigInteger) and scale (int).
@@ -184,8 +185,12 @@ public class LearnJava {
// LinkedLists - Implementation of doubly-linked list. All of the
// operations perform as could be expected for a
// doubly-linked list.
- // Maps - A set of objects that maps keys to values. A map cannot
- // contain duplicate keys; each key can map to at most one value.
+ // Maps - A set of objects that map keys to values. Map is
+ // an interface and therefore cannot be instantiated.
+ // The type of keys and values contained in a Map must
+ // be specified upon instantiation of the implementing
+ // class. Each key may map to only one corresponding value,
+ // and each key may appear only once (no duplicates).
// HashMaps - This class uses a hashtable to implement the Map
// interface. This allows the execution time of basic
// operations, such as get and insert element, to remain
@@ -445,6 +450,17 @@ class Bicycle {
protected int gear; // Protected: Accessible from the class and subclasses
String name; // default: Only accessible from within this package
+ static String className; // Static class variable
+
+ // Static block
+ // Java has no implementation of static constructors, but
+ // has a static block that can be used to initialize class variables
+ // (static variables).
+ // This block will be called when the class is loaded.
+ static {
+ className = "Bicycle";
+ }
+
// Constructors are a way of creating classes
// This is a constructor
public Bicycle() {
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 9c4f06fc..cce488e1 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -16,12 +16,8 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
becoming more and more popular.
-Feedback would be highly appreciated! You can reach me at
-[@adambrenecki](https://twitter.com/adambrenecki), or
-[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
-
```js
-// Comments are like C. Single-line comments start with two slashes,
+// Comments are like C's. Single-line comments start with two slashes,
/* and multiline comments start with slash-star
and end with star-slash */
@@ -149,6 +145,10 @@ someOtherVar = 10;
// Variables declared without being assigned to are set to undefined.
var someThirdVar; // = undefined
+// if you wan't to declare a couple of variables, then you could use a comma
+// separator
+var someFourthVar = 2, someFifthVar = 4;
+
// There's shorthand for performing math operations on variables:
someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
someVar *= 10; // now someVar is 100
@@ -287,12 +287,9 @@ myFunction("foo"); // = "FOO"
// Note that the value to be returned must start on the same line as the
// `return` keyword, otherwise you'll always return `undefined` due to
// automatic semicolon insertion. Watch out for this when using Allman style.
-function myFunction()
-{
+function myFunction(){
return // <- semicolon automatically inserted here
- {
- thisIsAn: 'object literal'
- }
+ {thisIsAn: 'object literal'}
}
myFunction(); // = undefined
@@ -306,6 +303,12 @@ setTimeout(myFunction, 5000);
// Note: setTimeout isn't part of the JS language, but is provided by browsers
// and Node.js.
+// Another function provided by browsers is setInterval
+function myFunction(){
+ // this code will be called every 5 seconds
+}
+setInterval(myFunction, 5000);
+
// Function objects don't even have to be declared with a name - you can write
// an anonymous function definition directly into the arguments of another.
setTimeout(function(){
@@ -527,28 +530,32 @@ if (Object.create === undefined){ // don't overwrite it if it exists
## Further Reading
-The [Mozilla Developer
-Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
-excellent documentation for JavaScript as it's used in browsers. Plus, it's a
-wiki, so as you learn more you can help others out by sharing your own
-knowledge.
+The [Mozilla Developer Network][1] provides excellent documentation for
+JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you
+can help others out by sharing your own knowledge.
+
+MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered
+here in more detail. This guide has quite deliberately only covered the
+JavaScript language itself; if you want to learn more about how to use
+JavaScript in web pages, start by learning about the [Document Object Model][3].
+
+[Learn Javascript by Example and with Challenges][4] is a variant of this
+reference with built-in challenges.
-MDN's [A re-introduction to
-JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-covers much of the concepts covered here in more detail. This guide has quite
-deliberately only covered the JavaScript language itself; if you want to learn
-more about how to use JavaScript in web pages, start by learning about the
-[Document Object
-Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
+[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts
+of the language.
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
+[JavaScript: The Definitive Guide][6] is a classic guide and reference book.
-[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
-guide of all the counter-intuitive parts of the language.
+In addition to direct contributors to this article, some content is adapted from
+Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
+Mozilla Developer Network.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
-In addition to direct contributors to this article, some content is adapted
-from Louie Dinh's Python tutorial on this site, and the [JS
-Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-on the Mozilla Developer Network.
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[5]: http://bonsaiden.github.io/JavaScript-Garden/
+[6]: http://www.amazon.com/gp/product/0596805527/
+[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
diff --git a/json.html.markdown b/json.html.markdown
index 060e9c3d..cde7bc40 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -5,22 +5,30 @@ contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["himanshu", "https://github.com/himanshu81494"]
+ - ["Michael Neth", "https://github.com/infernocloud"]
---
-As JSON is an extremely simple data-interchange format, this is most likely going
-to be the simplest Learn X in Y Minutes ever.
+As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever.
-JSON in its purest form has no actual comments, but most parsers will accept
-C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
-(i.e. a comma after the last element of an array or the after the last property of an object),
-but they should be avoided for better compatibility.
+JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
-Data types supported by JSON includes: numbers, string, boolean, array, object and null.
-Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
-JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json"
-Drawbacks of JSON include lack of type definition and some sort of DTD.
+A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null.
+
+Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
+
+File extension for JSON files is ".json" and the MIME type for JSON text is "application/json".
+
+Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data.
+
+More information can be found at http://www.json.org/
+
+JSON is built on two structures:
+* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
+* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
+
+An object with various name/value pairs.
```json
{
@@ -60,8 +68,18 @@ Drawbacks of JSON include lack of type definition and some sort of DTD.
"comment": "check this out!"
, "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
, "another comment": "how nice"
- },
-
- "that was short": "And, you're done. You now know everything JSON has to offer."
+ }
}
```
+
+A single array of values by itself is also valid JSON.
+
+```json
+[1, 2, 3, "text", true]
+```
+
+Objects can be a part of the array as well.
+
+```json
+[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}]
+```
diff --git a/julia.html.markdown b/julia.html.markdown
index c5089dc3..cba7cd45 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -117,11 +117,11 @@ catch e
println(e)
end
-# Variable names start with a letter.
+# Variable names start with a letter or underscore.
# After that, you can use letters, digits, underscores, and exclamation points.
SomeOtherVar123! = 6 # => 6
-# You can also use unicode characters
+# You can also use certain unicode characters
☃ = 8 # => 8
# These are especially handy for mathematical notation
2 * π # => 6.283185307179586
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 0cbc6f57..4d97834c 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -1,10 +1,11 @@
---
language: Matlab
+filename: learnmatlab.mat
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
- ["Colton Kohnke", "http://github.com/voltnor"]
-
+ - ["Claudson Martins", "http://github.com/claudsonm"]
---
MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
@@ -261,7 +262,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value
contour(A) % Contour plot of matrix
mesh(A) % Plot as a mesh surface
-h = figure % Create new figure object, with handle f
+h = figure % Create new figure object, with handle h
figure(h) % Makes the figure corresponding to handle h the current figure
close(h) % close figure with handle h
close all % close all open figure windows
@@ -329,7 +330,7 @@ double_input(6) % ans = 12
% anonymous function. Useful when quickly defining a function to pass to
% another function (eg. plot with fplot, evaluate an indefinite integral
% with quad, find roots with fzero, or find minimum with fminsearch).
-% Example that returns the square of it's input, assigned to to the handle sqr:
+% Example that returns the square of it's input, assigned to the handle sqr:
sqr = @(x) x.^2;
sqr(10) % ans = 100
doc function_handle % find out more
diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown
new file mode 100644
index 00000000..9820a561
--- /dev/null
+++ b/ms-my/coffeescript-my.html.markdown
@@ -0,0 +1,105 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+filename: coffeescript-ms.coffee
+translators:
+ - ["hack1m", "https://github.com/hack1m"]
+lang: ms-my
+---
+
+CoffeeScript adalah bahasa kecil yang menyusun/kompil satu-per-satu menjadi setara JavaScript, dan tidak ada interpretasi di runtime.
+Sebagai salah satu pengganti kepada JavaScript, CoffeeScript mencuba yang terbaik untuk output kod JavaScript yang mudah dibaca, cantik-dicetak dan berfungsi lancar, yang mana berfungsi baik pada setiap runtime JavaScript.
+
+Lihat juga [Laman sesawang CoffeeScript](http://coffeescript.org/), yang mana ada tutorial lengkap untuk CoffeeScript.
+
+```coffeescript
+# CoffeeScript adalah bahasa hipster.
+# Ia beredar mengikut trend kebanyakkan bahasa moden.
+# Jadi komen sama seperti Ruby dan Python, ia menggunakan simbol nombor.
+
+###
+Blok komen seperti ini, dan ia terjemah terus ke '/ *'s dan '* /'s
+untuk keputusan kod JavaScript.
+
+Sebelum meneruskan anda perlu faham kebanyakkan daripada
+JavaScript adalah semantik.
+###
+
+# Menetapkan:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Bersyarat:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Fungsi:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
+# Julat:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objek:
+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); }
+# };
+
+# Splats:
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
+
+# Kewujudan:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Pemahaman array:
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
+
+## Sumber tambahan
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index cf6bf780..f130ea0c 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -148,7 +148,13 @@ int main (int argc, const char * argv[])
[mutableDictionary setObject:@"value1" forKey:@"key1"];
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
-
+
+ // Change types from Mutable To Immutable
+ //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
+ NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
+ NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
+
+
// Set object
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
@@ -682,7 +688,7 @@ addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any pa
mutableVar = 32; // Assigning new value to __block variable.
return n + outsideVar; // Return statements are optional.
}
-int addUp = add(10 + 16); // Calls block code with arguments.
+int addUp = addUp(10 + 16); // Calls block code with arguments.
// Blocks are often used as arguments to functions to be called later, or for callbacks.
@implementation BlockExample : NSObject
diff --git a/php.html.markdown b/php.html.markdown
index 13cc83eb..0504ced2 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -104,7 +104,8 @@ END;
echo 'This string ' . 'is concatenated';
// Strings can be passed in as parameters to echo
-echo 'Multiple', 'Parameters', 'Valid';
+echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
+
/********************************
* Constants
@@ -117,8 +118,10 @@ echo 'Multiple', 'Parameters', 'Valid';
// followed by any number of letters, numbers, or underscores.
define("FOO", "something");
-// access to a constant is possible by direct using the choosen name
-echo 'This outputs '.FOO;
+// access to a constant is possible by calling the choosen name without a $
+echo FOO; // Returns 'something'
+echo 'This outputs '.FOO; // Returns 'This ouputs something'
+
/********************************
@@ -159,9 +162,9 @@ echo('Hello World!');
print('Hello World!'); // The same as echo
-// echo is actually a language construct, so you can drop the parentheses.
+// echo and print are language constructs too, so you can drop the parentheses
echo 'Hello World!';
-print 'Hello World!'; // So is print
+print 'Hello World!';
$paragraph = 'paragraph';
@@ -219,7 +222,11 @@ assert($a !== $d);
assert(1 === '1');
assert(1 !== '1');
-// spaceship operator since PHP 7
+// 'Spaceship' operator (since PHP 7)
+// Returns 0 if values on either side are equal
+// Returns 1 if value on the left is greater
+// Returns -1 if the value on the right is greater
+
$a = 100;
$b = 1000;
@@ -445,6 +452,16 @@ function parameters() {
parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World |
+// Since PHP 5.6 you can get a variable number of arguments
+function variable($word, ...$list) {
+ echo $word . " || ";
+ foreach ($list as $item) {
+ echo $item . ' | ';
+ }
+}
+
+variable("Separate", "Hello", "World") // Separate || Hello | World |
+
/********************************
* Includes
*/
@@ -712,6 +729,43 @@ use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
+
+/**********************
+* Late Static Binding
+*
+*/
+
+class ParentClass {
+ public static function who() {
+ echo "I'm a " . __CLASS__ . "\n";
+ }
+ public static function test() {
+ // self references the class the method is defined within
+ self::who();
+ // static references the class the method was invoked on
+ static::who();
+ }
+}
+
+ParentClass::test();
+/*
+I'm a ParentClass
+I'm a ParentClass
+*/
+
+class ChildClass extends ParentClass {
+ public static function who() {
+ echo "But I'm " . __CLASS__ . "\n";
+ }
+}
+
+ChildClass::test();
+/*
+I'm a ParentClass
+But I'm ChildClass
+*/
+
+
/**********************
* Error Handling
*
@@ -721,15 +775,15 @@ $cls = new SomeOtherNamespace\MyClass();
try {
// Do something
-} catch ( Exception $e) {
+} catch (Exception $e) {
// Handle exception
}
// When using try catch blocks in a namespaced enviroment use the following
-try {
+try {
// Do something
-} catch (\Exception $e) {
+} catch (\Exception $e) {
// Handle exception
}
@@ -738,13 +792,13 @@ try {
class MyException extends Exception {}
try {
-
- $condition = true;
-
+
+ $condition = true;
+
if ($condition) {
throw new MyException('Something just happend');
}
-
+
} catch (MyException $e) {
// Handle my exception
}
diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown
new file mode 100644
index 00000000..eb660d4c
--- /dev/null
+++ b/pt-br/matlab-pt.html.markdown
@@ -0,0 +1,540 @@
+---
+language: Matlab
+contributors:
+ - ["mendozao", "http://github.com/mendozao"]
+ - ["jamesscottbrown", "http://jamesscottbrown.com"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+translators:
+ - ["Claudson Martins", "https://github.com/claudsonm"]
+lang: pt-br
+filename: learnmatlab-pt.mat
+
+---
+
+MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática.
+
+Se você tem algum feedback, por favor fique a vontade para me contactar via
+[@the_ozzinator](https://twitter.com/the_ozzinator), ou
+[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
+
+```matlab
+% Comentários iniciam com um sinal de porcentagem
+
+%{
+Comentários de múltiplas linhas
+parecem
+com
+algo assim
+%}
+
+% Comandos podem ocupar várinhas linhas, usando '...':
+ a = 1 + 2 + ...
+ + 4
+
+% Comandos podem ser passados para o sistema operacional
+!ping google.com
+
+who % Exibe todas as variáveis na memória
+whos % Exibe todas as variáveis na memória, com seus tipos
+clear % Apaga todas as suas variáveis da memória
+clear('A') % Apaga uma variável em particular
+openvar('A') % Abre a variável no editor de variável
+
+clc % Apaga o conteúdo escrito na sua janela de comando
+diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto
+ctrl-c % Aborta a computação atual
+
+edit('minhafuncao.m') % Abre a função/script no editor
+type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando
+
+profile on % Ativa o perfil de código
+profile off % Desativa o perfil de código
+profile viewer % Visualiza os resultados na janela de Profiler
+
+help comando % Exibe a documentação do comando na janela de comando
+doc comando % Exibe a documentação do comando na janela de ajuda
+lookfor comando % Procura por comando na primeira linha comentada de todas as funções
+lookfor comando -all % Procura por comando em todas as funções
+
+
+% Formatação de saída
+format short % 4 casas decimais em um número flutuante
+format long % 15 casas decimais
+format bank % 2 dígitos após o ponto decimal - para cálculos financeiros
+fprintf('texto') % Imprime na tela "texto"
+disp('texto') % Imprime na tela "texto"
+
+% Variáveis & Expressões
+minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada
+minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando
+4 + 6 % Resposta = 10
+8 * minhaVariavel % Resposta = 32
+2 ^ 3 % Resposta = 8
+a = 2; b = 3;
+c = exp(a)*sin(pi/2) % c = 7.3891
+
+% A chamada de funções pode ser feita por uma das duas maneiras:
+% Sintaxe de função padrão:
+load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula
+% Sintaxe de comando:
+load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas
+% Observe a falta de aspas na forma de comando: entradas são sempre passadas
+% como texto literal - não pode passar valores de variáveis.
+% Além disso, não pode receber saída:
+[V,D] = eig(A); % Isto não tem um equivalente na forma de comando
+[~,D] = eig(A); % Se você só deseja D e não V
+
+
+
+% Operadores Lógicos e Relacionais
+1 > 5 % Resposta = 0
+10 >= 10 % Resposta = 1
+3 ~= 4 % Diferente de -> Resposta = 1
+3 == 3 % Igual a -> Resposta = 1
+3 > 1 && 4 > 1 % E -> Resposta = 1
+3 > 1 || 4 > 1 % OU -> Resposta = 1
+~1 % NOT -> Resposta = 0
+
+% Operadores Lógicos e Relacionais podem ser aplicados a matrizes
+A > 5
+% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada
+A( A > 5 )
+% Retorna um vetor com os elementos de A para os quais a condição é verdadeira
+
+% Cadeias de caracteres (Strings)
+a = 'MinhaString'
+length(a) % Resposta = 11
+a(2) % Resposta = i
+[a,a] % Resposta = MinhaStringMinhaString
+
+
+% Vetores de células
+a = {'um', 'dois', 'três'}
+a(1) % Resposta = 'um' - retorna uma célula
+char(a(1)) % Resposta = um - retorna uma string
+
+% Estruturas
+A.b = {'um','dois'};
+A.c = [1 2];
+A.d.e = false;
+
+% Vetores
+x = [4 32 53 7 1]
+x(2) % Resposta = 32, índices no Matlab começam por 1, não 0
+x(2:3) % Resposta = 32 53
+x(2:end) % Resposta = 32 53 7 1
+
+x = [4; 32; 53; 7; 1] % Vetor coluna
+
+x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+
+% Matrizes
+A = [1 2 3; 4 5 6; 7 8 9]
+% Linhas são separadas por um ponto e vírgula;
+% Elementos são separados com espaço ou vírgula
+% A =
+
+% 1 2 3
+% 4 5 6
+% 7 8 9
+
+A(2,3) % Resposta = 6, A(linha, coluna)
+A(6) % Resposta = 8
+% (implicitamente encadeia as colunas do vetor, e então as indexa)
+
+
+A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42
+% A =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+A(2:3,2:3) % Cria uma nova matriz a partir da antiga
+%Resposta =
+
+% 5 42
+% 8 9
+
+A(:,1) % Todas as linhas na coluna 1
+%Resposta =
+
+% 1
+% 4
+% 7
+
+A(1,:) % Todas as colunas na linha 1
+%Resposta =
+
+% 1 2 3
+
+[A ; A] % Concatenação de matrizes (verticalmente)
+%Resposta =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+% Isto é o mesmo de
+vertcat(A,A);
+
+
+[A , A] % Concatenação de matrizes (horizontalmente)
+
+%Resposta =
+
+% 1 2 3 1 2 3
+% 4 5 42 4 5 42
+% 7 8 9 7 8 9
+
+% Isto é o mesmo de
+horzcat(A,A);
+
+
+A(:, [3 1 2]) % Reorganiza as colunas da matriz original
+%Resposta =
+
+% 3 1 2
+% 42 4 5
+% 9 7 8
+
+size(A) % Resposta = 3 3
+
+A(1, :) =[] % Remove a primeira linha da matriz
+A(:, 1) =[] % Remove a primeira coluna da matriz
+
+transpose(A) % Transposta a matriz, que é o mesmo de:
+A one
+ctranspose(A) % Transposta a matriz
+% (a transposta, seguida pelo conjugado complexo de cada elemento)
+
+
+
+
+% Aritmética Elemento por Elemento vs. Aritmética com Matriz
+% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando
+% precedidos por um ponto, eles atuam em cada elemento. Por exemplo:
+A * B % Multiplicação de matrizes
+A .* B % Multiplica cada elemento em A por seu correspondente em B
+
+% Existem vários pares de funções nas quais uma atua sob cada elemento, e a
+% outra (cujo nome termina com m) age na matriz por completo.
+exp(A) % Exponencia cada elemento
+expm(A) % Calcula o exponencial da matriz
+sqrt(A) % Tira a raiz quadrada de cada elemento
+sqrtm(A) % Procura a matriz cujo quadrado é A
+
+
+% Gráficos
+x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1
+y = sin(x);
+plot(x,y)
+xlabel('eixo x')
+ylabel('eixo y')
+title('Gráfico de y = sin(x)')
+axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1
+
+plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico
+legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda
+
+% Método alternativo para traçar várias funções em um só gráfico:
+% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico
+% existente ao invés de o substituirem.
+plot(x, y)
+hold on
+plot(x, z)
+hold off
+
+loglog(x, y) % Plotar em escala loglog
+semilogx(x, y) % Um gráfico com eixo x logarítmico
+semilogy(x, y) % Um gráfico com eixo y logarítmico
+
+fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5
+
+grid on % Exibe as linhas de grade; Oculta com 'grid off'
+axis square % Torna quadrada a região dos eixos atuais
+axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções
+
+scatter(x, y); % Gráfico de dispersão ou bolha
+hist(x); % Histograma
+
+z = sin(x);
+plot3(x,y,z); % Plotar em espaço em 3D
+
+pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor
+contour(A) % Plotar de contorno da matriz
+mesh(A) % Plotar malha 3D
+
+h = figure % Cria uma nova figura objeto, com identificador h
+figure(h) % Cria uma nova janela de figura com h
+close(h) % Fecha a figura h
+close all % Fecha todas as janelas de figuras abertas
+close % Fecha a janela de figura atual
+
+shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário
+clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura
+
+% Propriedades podem ser definidas e alteradas através de um identificador.
+% Você pode salvar um identificador para uma figura ao criá-la.
+% A função gcf retorna o identificador da figura atual
+h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la
+set(h, 'Color', 'r')
+% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto
+set(h, 'LineStyle', '--')
+ % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha
+get(h, 'LineStyle')
+
+
+% A função gca retorna o identificador para os eixos da figura atual
+set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x
+
+% Para criar uma figura que contém vários gráficos use subplot, o qual divide
+% a janela de gráficos em m linhas e n colunas.
+subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3
+plot(x1); title('Primeiro Plot') % Plota algo nesta posição
+subplot(2,3,2); % Seleciona a segunda posição na grade
+plot(x2); title('Segundo Plot') % Plota algo ali
+
+
+% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual
+path % Exibe o caminho atual
+addpath /caminho/para/pasta % Adiciona o diretório ao caminho
+rmpath /caminho/para/pasta % Remove o diretório do caminho
+cd /caminho/para/mudar % Muda o diretório
+
+
+% Variáveis podem ser salvas em arquivos *.mat
+save('meuArquivo.mat') % Salva as variáveis do seu Workspace
+load('meuArquivo.mat') % Carrega as variáveis em seu Workspace
+
+% Arquivos M (M-files)
+% Um arquivo de script é um arquivo externo contendo uma sequência de instruções.
+% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos.
+% Possuem a extensão *.m
+
+% Arquivos M de Funções (M-file Functions)
+% Assim como scripts e têm a mesma extensão *.m
+% Mas podem aceitar argumentos de entrada e retornar uma saída.
+% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis).
+% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m)
+% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função
+function output = dobra_entrada(x)
+ %dobra_entrada(x) retorna duas vezes o valor de x
+ output = 2*x;
+end
+dobra_entrada(6) % Resposta = 12
+
+
+% Você também pode ter subfunções e funções aninhadas.
+% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados
+% por funções dentro do arquivo. Funções aninhadas são definidas dentro de
+% outras funções, e têm acesso a ambos workspaces.
+
+% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma
+% função anônima. Úteis para definir rapidamente uma função para passar a outra
+% função (ex. plotar com fplot, avaliar uma integral indefinida com quad,
+% procurar raízes com fzero, ou procurar mínimo com fminsearch).
+% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr:
+sqr = @(x) x.^2;
+sqr(10) % Resposta = 100
+doc function_handle % Saiba mais
+
+% Entrada do usuário
+a = input('Digite o valor: ')
+
+% Para a execução do arquivo e passa o controle para o teclado: o usuário pode
+% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair
+keyboard
+
+% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem)
+fopen(nomedoarquivo)
+
+% Saída
+disp(a) % Imprime o valor da variável a
+disp('Olá Mundo') % Imprime a string
+fprintf % Imprime na janela de comandos com mais controle
+
+% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática)
+if (a > 15)
+ disp('Maior que 15')
+elseif (a == 23)
+ disp('a é 23')
+else
+ disp('Nenhuma condição reconheceu')
+end
+
+% Estruturas de Repetição
+% Nota: fazer o loop sobre elementos de um vetor/matriz é lento!
+% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez.
+for k = 1:5
+ disp(k)
+end
+
+k = 0;
+while (k < 5)
+ k = k + 1;
+end
+
+% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo
+% passado desde que 'tic' foi chamado.
+tic
+A = rand(1000);
+A*A*A*A*A*A*A;
+toc
+
+% Conectando a uma base de dados MySQL
+dbname = 'nome_base_de_dados';
+username = 'root';
+password = 'root';
+driver = 'com.mysql.jdbc.Driver';
+dburl = ['jdbc:mysql://localhost:8889/' dbname];
+%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/
+javaclasspath('mysql-connector-java-5.1.xx-bin.jar');
+conn = database(dbname, username, password, driver, dburl);
+sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL
+a = fetch(conn, sql) %a will contain your data
+
+
+% Funções Matemáticas Comuns
+sin(x)
+cos(x)
+tan(x)
+asin(x)
+acos(x)
+atan(x)
+exp(x)
+sqrt(x)
+log(x)
+log10(x)
+abs(x)
+min(x)
+max(x)
+ceil(x)
+floor(x)
+round(x)
+rem(x)
+rand % Números pseudo-aleatórios uniformemente distribuídos
+randi % Inteiros pseudo-aleatórios uniformemente distribuídos
+randn % Números pseudo-aleatórios normalmente distribuídos
+
+% Constantes Comuns
+pi
+NaN
+inf
+
+% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados)
+% Os operadores \ e / são equivalentes às funções mldivide e mrdivide
+x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b.
+x=b/A % Resolve xA=b
+
+inv(A) % Calcula a matriz inversa
+pinv(A) % Calcula a pseudo-inversa
+
+% Funções Matriciais Comuns
+zeros(m,n) % Matriz de zeros m x n
+ones(m,n) % Matriz de 1's m x n
+diag(A) % Extrai os elementos diagonais da matriz A
+diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições
+eye(m,n) % Matriz identidade
+linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2
+inv(A) % Inverso da matriz A
+det(A) % Determinante da matriz A
+eig(A) % Valores e vetores próprios de A
+trace(A) % Traço da matriz - equivalente a sum(diag(A))
+isempty(A) % Testa se a matriz está vazia
+all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro
+any(A) % Testa se algum elemento é diferente de zero ou verdadeiro
+isequal(A, B) % Testa a igualdade de duas matrizes
+numel(A) % Número de elementos na matriz
+triu(x) % Retorna a parte triangular superior de x
+tril(x) % Retorna a parte triangular inferior de x
+cross(A,B) % Retorna o produto cruzado das matrizes A e B
+dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho)
+transpose(A) % Retorna a matriz transposta de A
+fliplr(A) % Inverte a matriz da esquerda para a direita
+flipud(A) % Inverte a matriz de cima para baixo
+
+% Fatorações de Matrizes
+% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação
+[L, U, P] = lu(A)
+% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores
+[P, D] = eig(A)
+% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente
+[U,S,V] = svd(X)
+
+% Funções Vetoriais Comuns
+max % Maior componente
+min % Menor componente
+length % Tamanho do vetor
+sort % Ordena em orcer ascendente
+sum % Soma de elementos
+prod % Produto de elementos
+mode % Valor modal
+median % Valor mediano
+mean % Valor médio
+std % Desvio padrão
+perms(x) % Lista todas as permutações de elementos de x
+
+
+% Classes
+% Matlab pode suportar programação orientada a objetos.
+% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m
+% Para começar, criamos uma simples classe que armazena posições de GPS
+% Início ClassePosicoesGPS.m
+classdef ClassePosicoesGPS % O nome da classe.
+ properties % As propriedades da classe comportam-se como estruturas
+ latitude
+ longitude
+ end
+ methods
+ % Este método que tem o mesmo nome da classe é o construtor.
+ function obj = ClassePosicoesGPS(lat, lon)
+ obj.latitude = lat;
+ obj.longitude = lon;
+ end
+
+ % Outras funções que usam os objetos de PosicoesGPS
+ function r = multiplicarLatPor(obj, n)
+ r = n*[obj.latitude];
+ end
+
+ % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar
+ % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira:
+ function r = plus(o1,o2)
+ r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ...
+ [o1.longitude]+[o2.longitude]);
+ end
+ end
+end
+% End ClassePosicoesGPS.m
+
+% Podemos criar um objeto da classe usando o construtor
+a = ClassePosicoesGPS(45.0, 45.0)
+
+% Propriedades da classe se comportam exatamente como estruturas Matlab
+a.latitude = 70.0
+a.longitude = 25.0
+
+% Métodos podem ser chamados da mesma forma que funções
+ans = multiplicarLatPor(a,3)
+
+% O método também pode ser chamado usando a notação de ponto. Neste caso,
+% o objeto não precisa ser passado para o método.
+ans = a.multiplicarLatPor(a,1/3)
+
+% Funções do Matlab podem ser sobrepostas para lidar com objetos.
+% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de
+% dois objetos PosicoesGPS.
+b = ClassePosicoesGPS(15.0, 32.0)
+c = a + b
+
+```
+
+## Mais sobre Matlab
+
+* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
+* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
+
diff --git a/python.html.markdown b/python.html.markdown
index b939ebbe..42a52bcf 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython.py
---
@@ -58,6 +59,12 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
+# Note that we can also import division module(Section 6 Modules)
+# to carry out normal division with just one '/'.
+from __future__ import division
+11/4 # => 2.75 ...normal division
+11//4 # => 2 ...floored division
+
# Modulo operation
7 % 3 # => 1
@@ -165,6 +172,7 @@ some_var # => 5
some_other_var # Raises a name error
# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# Lists store sequences
@@ -218,6 +226,17 @@ li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3, 4, 5, 6]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
+
+# Get the index of the first item found
+li.index(2) # => 3
+li.index(7) # Raises a ValueError as 7 is not in the list
+
# Check for existence in a list with "in"
1 in li # => True
@@ -309,6 +328,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
@@ -460,19 +488,19 @@ def pass_all_the_args(*args, **kwargs):
# Function Scope
x = 5
-def setX(num):
+def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print x # => 43
-def setGlobalX(num):
+def set_global_x(num):
global x
print x # => 5
x = num # global var x is now set to 6
print x # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python has first class functions
def create_adder(x):
@@ -516,6 +544,10 @@ class Human(object):
# Assign the argument to the instance's name attribute
self.name = name
+ # Initialize property
+ self.age = 0
+
+
# An instance method. All methods take "self" as the first argument
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
@@ -531,6 +563,23 @@ class Human(object):
def grunt():
return "*grunt*"
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
# Instantiate a class
i = Human(name="Ian")
@@ -550,6 +599,16 @@ j.get_species() # => "H. neanderthalensis"
# Call the static method
Human.grunt() # => "*grunt*"
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
####################################################
## 6. Modules
@@ -648,7 +707,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [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/)
+* [The Official Docs](http://docs.python.org/2/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
diff --git a/python3.html.markdown b/python3.html.markdown
index a1125c73..2398e7ac 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
- ["Zachary Ferguson", "http://github.com/zfergus2"]
+ - ["evuez", "http://github.com/evuez"]
filename: learnpython3.py
---
@@ -216,6 +217,17 @@ li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3] again
+
+# Get the index of the first item found
+li.index(2) # => 3
+li.index(4) # Raises a ValueError as 4 is not in the list
+
# You can add lists
# Note: values for li and for other_li are not modified.
li + other_li # => [1, 2, 3, 4, 5, 6]
@@ -249,6 +261,8 @@ tup[:2] # => (1, 2)
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+# You can also do extended unpacking
+a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
@@ -306,6 +320,11 @@ filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
+# From Python 3.5 you can also use the additional unpacking options
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
+
+
# Sets store ... well sets
empty_set = set()
@@ -332,6 +351,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
@@ -439,7 +467,7 @@ with open("myfile.txt") as f:
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
# We can loop over it.
for i in our_iterable:
@@ -528,19 +556,19 @@ x, y = swap(x, y) # => x = 2, y = 1
# Function Scope
x = 5
-def setX(num):
+def set_x(num):
# Local var x not the same as global variable x
x = num # => 43
print (x) # => 43
-def setGlobalX(num):
+def set_global_x(num):
global x
print (x) # => 5
x = num # global var x is now set to 6
print (x) # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
# Python has first class functions
@@ -589,6 +617,9 @@ class Human:
# Assign the argument to the instance's name attribute
self.name = name
+ # Initialize property
+ self.age = 0
+
# An instance method. All methods take "self" as the first argument
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
@@ -604,6 +635,23 @@ class Human:
def grunt():
return "*grunt*"
+ # A property is just like a getter.
+ # It turns the method age() into an read-only attribute
+ # of the same name.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
# Instantiate a class
i = Human(name="Ian")
@@ -623,6 +671,17 @@ j.get_species() # => "H. neanderthalensis"
# Call the static method
Human.grunt() # => "*grunt*"
+# Update the property
+i.age = 42
+
+# Get the property
+i.age # => 42
+
+# Delete the property
+del i.age
+i.age # => raises an AttributeError
+
+
####################################################
## 6. Modules
diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.html.markdown
index 78b62e33..78b62e33 100644
--- a/pythonstatcomp.markdown.html
+++ b/pythonstatcomp.html.markdown
diff --git a/r.html.markdown b/r.html.markdown
index 93751df5..8539b10e 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -3,6 +3,7 @@ language: R
contributors:
- ["e99n09", "http://github.com/e99n09"]
- ["isomorphismes", "http://twitter.com/isomorphisms"]
+ - ["kalinn", "http://github.com/kalinn"]
filename: learnr.r
---
@@ -15,7 +16,8 @@ R is a statistical computing language. It has lots of libraries for uploading an
# You can't make multi-line comments,
# but you can stack multiple comments like so.
-# in Windows or Mac, hit COMMAND-ENTER to execute a line
+# in Windows you can use CTRL-ENTER to execute a line.
+# on Mac it is COMMAND-ENTER
@@ -196,6 +198,14 @@ class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
c(1,2,3) + c(1,2,3) # 2 4 6
+# Since a single number is a vector of length one, scalars are applied
+# elementwise to vectors
+(4 * c(1,2,3) - 2) / 2 # 1 3 5
+# Except for scalars, use caution when performing arithmetic on vectors with
+# different lengths. Although it can be done,
+c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
+# Matching lengths is better practice and easier to read
+c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
# CHARACTERS
# There's no difference between strings and characters in R
@@ -234,6 +244,9 @@ class(NA) # "logical"
TRUE | FALSE # TRUE
# AND
TRUE & FALSE # FALSE
+# Applying | and & to vectors returns elementwise logic operations
+c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
+c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
@@ -664,15 +677,101 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
#########################
+# Statistical Analysis
+#########################
+
+# Linear regression!
+linearModel <- lm(price ~ time, data = list1)
+linearModel # outputs result of regression
+# =>
+# Call:
+# lm(formula = price ~ time, data = list1)
+#
+# Coefficients:
+# (Intercept) time
+# 0.1453 0.4943
+summary(linearModel) # more verbose output from the regression
+# =>
+# Call:
+# lm(formula = price ~ time, data = list1)
+#
+# Residuals:
+# Min 1Q Median 3Q Max
+# -8.3134 -3.0131 -0.3606 2.8016 10.3992
+#
+# Coefficients:
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.14527 1.50084 0.097 0.923
+# time 0.49435 0.06379 7.749 2.44e-09 ***
+# ---
+# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
+#
+# Residual standard error: 4.657 on 38 degrees of freedom
+# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
+# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
+coef(linearModel) # extract estimated parameters
+# =>
+# (Intercept) time
+# 0.1452662 0.4943490
+summary(linearModel)$coefficients # another way to extract results
+# =>
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
+# time 0.4943490 0.06379348 7.74920901 2.440008e-09
+summary(linearModel)$coefficients[,4] # the p-values
+# =>
+# (Intercept) time
+# 9.234021e-01 2.440008e-09
+
+# GENERAL LINEAR MODELS
+# Logistic regression
+set.seed(1)
+list1$success = rbinom(length(list1$time), 1, .5) # random binary
+glModel <- glm(success ~ time, data = list1,
+ family=binomial(link="logit"))
+glModel # outputs result of logistic regression
+# =>
+# Call: glm(formula = success ~ time,
+# family = binomial(link = "logit"), data = list1)
+#
+# Coefficients:
+# (Intercept) time
+# 0.17018 -0.01321
+#
+# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
+# Null Deviance: 55.35
+# Residual Deviance: 55.12 AIC: 59.12
+summary(glModel) # more verbose output from the regression
+# =>
+# Call:
+# glm(formula = success ~ time,
+# family = binomial(link = "logit"), data = list1)
+
+# Deviance Residuals:
+# Min 1Q Median 3Q Max
+# -1.245 -1.118 -1.035 1.202 1.327
+#
+# Coefficients:
+# Estimate Std. Error z value Pr(>|z|)
+# (Intercept) 0.17018 0.64621 0.263 0.792
+# time -0.01321 0.02757 -0.479 0.632
+#
+# (Dispersion parameter for binomial family taken to be 1)
+#
+# Null deviance: 55.352 on 39 degrees of freedom
+# Residual deviance: 55.121 on 38 degrees of freedom
+# AIC: 59.121
+#
+# Number of Fisher Scoring iterations: 3
+
+
+#########################
# Plots
#########################
# BUILT-IN PLOTTING FUNCTIONS
# Scatterplots!
plot(list1$time, list1$price, main = "fake data")
-# Regressions!
-linearModel <- lm(price ~ time, data = list1)
-linearModel # outputs result of regression
# Plot regression line on existing plot
abline(linearModel, col = "red")
# Get a variety of nice diagnostics
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 4e9f8aee..998b4bf7 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -41,6 +41,7 @@ You shouldn't either
35 / 5 #=> 7
2**5 #=> 32
5 % 3 #=> 2
+5 ^ 6 #=> 3
# Arithmetic is just syntactic sugar
# for calling a method on an object
diff --git a/tmux.html.markdown b/tmux.html.markdown
index 49d1bba6..868302a8 100644
--- a/tmux.html.markdown
+++ b/tmux.html.markdown
@@ -38,7 +38,7 @@ then later reattached.
lsp # List panes
-a # List all panes
-s # List all panes in session
- -t # List app panes in target
+ -t # List all panes in target
kill-window # Kill current window
-t "#" # Kill target window
diff --git a/whip.html.markdown b/whip.html.markdown
index 3faee98a..61c301a5 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -2,6 +2,7 @@
language: whip
contributors:
- ["Tenor Biel", "http://github.com/L8D"]
+ - ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
author: Tenor Biel
author_url: http://github.com/L8D
filename: whip.lisp
@@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value
undefined ; user to indicate a value that hasn't been set
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-; 2. Vairbles, Lists, and Dicts
+; 2. Variables, Lists, and Dicts
; Variables are declared with the `def` or `let` functions.
; Variables that haven't been set will be `undefined`.
(def some_var 5)
; `def` will keep the variable in the global context.
-; `let` will only have the variable inside its context, and has a wierder syntax.
+; `let` will only have the variable inside its context, and has a weirder syntax.
(let ((a_var 5)) (+ a_var 5)) ; => 10
(+ a_var 5) ; = undefined + 5 => undefined
@@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set
(my_function 10 10) ; = (+ (+ 10 10) 10) => 30
-; Obiously, all lambdas by definition are anonymous and
+; Obviously, all lambdas by definition are anonymous and
; technically always used anonymously. Redundancy.
((lambda (x) x) 10) ; => 10
@@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set
(slice (.. 1 5) 2) ; => (3 4 5)
(\ (.. 0 100) -5) ; => (96 97 98 99 100)
-; `append` or `<<` is self expanatory
+; `append` or `<<` is self explanatory
(append 4 (1 2 3)) ; => (1 2 3 4)
(<< "bar" ("foo")) ; => ("foo" "bar")
diff --git a/xml.html.markdown b/xml.html.markdown
index efc2340f..b95d6088 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -3,6 +3,7 @@ language: xml
filename: learnxml.xml
contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
---
XML is a markup language designed to store and transport data.
@@ -65,12 +66,12 @@ Unlike HTML, XML does not specify how to display or to format data, it just carr
* Well-Formated Document x Validation
-A XML document is well-formated if it is syntactically correct.
+An XML document is well-formatted if it is syntactically correct.
However, it is possible to inject more constraints in the document,
using document definitions, such as DTD and XML Schema.
-A XML document which follows a document definition is called valid,
-regarding that document.
+An XML document which follows a document definition is called valid,
+in regards to that document.
With this tool, you can check the XML data outside the application logic.