diff options
| -rw-r--r-- | de-de/bash-de.html.markdown | 223 | ||||
| -rw-r--r-- | de-de/git-de.html.markdown | 30 | ||||
| -rw-r--r-- | de-de/go-de.html.markdown | 3 | ||||
| -rw-r--r-- | es-es/ruby-es.html.markdown | 247 | ||||
| -rw-r--r-- | fr-fr/python-fr.html.markdown | 3 | ||||
| -rw-r--r-- | haskell.html.markdown | 8 | ||||
| -rw-r--r-- | id-id/xml-id.html.markdown | 2 | ||||
| -rw-r--r-- | java.html.markdown | 11 | ||||
| -rw-r--r-- | javascript.html.markdown | 15 | ||||
| -rw-r--r-- | matlab.html.markdown | 7 | ||||
| -rw-r--r-- | ms-my/coffeescript-my.html.markdown | 105 | ||||
| -rw-r--r-- | php.html.markdown | 10 | ||||
| -rw-r--r-- | pt-br/matlab-pt.html.markdown | 540 | ||||
| -rw-r--r-- | python.html.markdown | 2 | ||||
| -rw-r--r-- | pythonstatcomp.html.markdown (renamed from pythonstatcomp.markdown.html) | 0 | ||||
| -rw-r--r-- | r.html.markdown | 104 | 
16 files changed, 1234 insertions, 76 deletions
| 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 38c9e490..aae64ccf 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -450,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 d408e885..c1c59de1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -21,7 +21,7 @@ Feedback would be highly appreciated! You can reach me at  [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 */ @@ -291,12 +291,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 @@ -310,6 +307,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(){ 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/php.html.markdown b/php.html.markdown index 403fc41d..0504ced2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -452,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   */ 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 675967f4..42a52bcf 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -707,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/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 8896c5b0..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  --- @@ -197,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 @@ -235,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: @@ -665,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 | 
