summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitattributes2
-rw-r--r--bash.html.markdown11
-rw-r--r--bg-bg/perl-bg.html.markdown7
-rw-r--r--c++.html.markdown2
-rw-r--r--cobol.html.markdown317
-rw-r--r--dart.html.markdown8
-rw-r--r--de-de/clojure-macros-de.html.markdown161
-rw-r--r--de-de/elm-de.html.markdown376
-rw-r--r--de-de/perl-de.html.markdown4
-rw-r--r--de-de/processing-de.html.markdown498
-rw-r--r--de-de/pug-de.html.markdown208
-rw-r--r--de-de/ruby-de.html.markdown782
-rw-r--r--el-gr/vim-gr.html.markdown267
-rw-r--r--elixir.html.markdown3
-rw-r--r--es-es/perl-es.html.markdown16
-rw-r--r--es-es/raku-es.html.markdown (renamed from es-es/perl6-es.html.markdown)508
-rw-r--r--fr-fr/crystal-fr.html.markdown2
-rw-r--r--fr-fr/elisp-fr.html.markdown10
-rw-r--r--fr-fr/fsharp-fr.html.markdown3
-rw-r--r--fr-fr/perl-fr.html.markdown4
-rw-r--r--fsharp.html.markdown4
-rw-r--r--git.html.markdown4
-rw-r--r--groovy.html.markdown2
-rw-r--r--it-it/sql-it.html.markdown112
-rw-r--r--it-it/zfs-it.html.markdown361
-rw-r--r--janet.html.markdown328
-rw-r--r--jsonnet.html.markdown139
-rw-r--r--ko-kr/vim-kr.html.markdown56
-rw-r--r--lbstanza.html.markdown282
-rw-r--r--ldpl.html.markdown13
-rw-r--r--matlab.html.markdown2
-rw-r--r--mips.html.markdown2
-rw-r--r--moonscript.html.markdown2
-rw-r--r--nim.html.markdown2
-rw-r--r--nix.html.markdown2
-rw-r--r--nl-nl/json-nl.html.markdown13
-rw-r--r--opencv.html.markdown22
-rw-r--r--p5.html.markdown2
-rw-r--r--perl.html.markdown4
-rw-r--r--php.html.markdown8
-rw-r--r--pl-pl/perl-pl.html.markdown4
-rw-r--r--powershell.html.markdown34
-rw-r--r--pt-br/perl-pt.html.markdown4
-rw-r--r--pt-br/sass-pt.html.markdown67
-rw-r--r--python.html.markdown22
-rw-r--r--qsharp.html.markdown204
-rw-r--r--raku-pod.html.markdown (renamed from perl6-pod.html.markdown)90
-rw-r--r--raku.html.markdown113
-rw-r--r--raylib.html.markdown146
-rw-r--r--red.html.markdown2
-rw-r--r--rst.html.markdown6
-rw-r--r--ru-ru/pascal-ru.html.markdown217
-rw-r--r--ru-ru/perl-ru.html.markdown30
-rw-r--r--ru-ru/python-ru.html.markdown2
-rw-r--r--ru-ru/ruby-ru.html.markdown2
-rw-r--r--ruby.html.markdown18
-rw-r--r--scala.html.markdown5
-rw-r--r--set-theory.html.markdown132
-rw-r--r--smalltalk.html.markdown2
-rw-r--r--typescript.html.markdown6
-rw-r--r--vim.html.markdown4
-rw-r--r--zh-cn/c-cn.html.markdown2
-rw-r--r--zh-cn/make-cn.html.markdown8
-rw-r--r--zh-cn/opencv-cn.html.markdown145
-rw-r--r--zh-cn/perl-cn.html.markdown4
-rw-r--r--zh-cn/python-cn.html.markdown6
-rw-r--r--zh-cn/pythonlegacy-cn.html.markdown2
-rw-r--r--zh-cn/yaml-cn.html.markdown55
68 files changed, 4815 insertions, 1066 deletions
diff --git a/.gitattributes b/.gitattributes
index 183b7cdb..96d2bb5a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -61,5 +61,5 @@ paren*.html.markdown linguist-language=lisp
pcre*.html.markdown linguist-language=Perl
perl.html.markdown linguist-language=Perl
perl-*.html.markdown linguist-language=Perl
-perl6*.html.markdown linguist-language=Perl6
+raku*.html.markdown linguist-language=Perl6
ruby*.html.markdown linguist-language=Ruby
diff --git a/bash.html.markdown b/bash.html.markdown
index 856db706..7ca4285b 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -23,7 +23,7 @@ translators:
---
Bash is a name of the unix shell, which was also distributed as the shell
-for the GNU operating system and as default shell on Linux and Mac OS X.
+for the GNU operating system and as the default shell on most Linux distros.
Nearly all examples below can be a part of a shell script
or executed directly in the shell.
@@ -88,6 +88,11 @@ echo ${Variable: -5} # => tring
# String length
echo ${#Variable} # => 11
+# Indirect expansion
+OtherVariable="Variable"
+echo ${!OtherVariable} # => Some String
+# This will expand the value of OtherVariable
+
# Default value for variable
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# => DefaultValueIfFooIsMissingOrEmpty
@@ -225,7 +230,9 @@ cat file.txt
# We can also read the file using `cat`:
Contents=$(cat file.txt)
-echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character
+# "\n" prints a new line character
+# "-e" to interpret the newline escape characters as escape characters
+echo -e "START OF FILE\n$Contents\nEND OF FILE"
# => START OF FILE
# => [contents of file.txt]
# => END OF FILE
diff --git a/bg-bg/perl-bg.html.markdown b/bg-bg/perl-bg.html.markdown
index 2ae7a8fd..e6da8965 100644
--- a/bg-bg/perl-bg.html.markdown
+++ b/bg-bg/perl-bg.html.markdown
@@ -11,10 +11,10 @@ translators:
lang: bg-bg
---
-Perl 5 е изключително мощен език за програмиране с широка област на приложение
+Perl е изключително мощен език за програмиране с широка област на приложение
и над 25 годишна история.
-Perl 5 работи на повече от 100 операционни системи от мини до супер-компютри и е
+Perl работи на повече от 100 операционни системи от мини до супер-компютри и е
подходящ както за бърза разработка на скриптове така и за огромни приложения.
```perl
@@ -281,7 +281,7 @@ sub increment {
1;
-# Методите могат да се извикват на клас или на обект като се използва оператора
+# Методите могат да се извикват на клас или на обект като се използва оператора
# стрелка (->).
use MyCounter;
@@ -323,4 +323,3 @@ sub increment {
- [Learn at www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- и идващото с perl: `perldoc perlintro`
-
diff --git a/c++.html.markdown b/c++.html.markdown
index f3dc8e20..59aad210 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -202,7 +202,7 @@ int main()
cout << "Your favorite number is " << myInt << "\n";
// prints "Your favorite number is <myInt>"
- cerr << "Used for error messages";
+ cerr << "Used for error messages";
}
//////////
diff --git a/cobol.html.markdown b/cobol.html.markdown
index 4452bd95..7d94d8c9 100644
--- a/cobol.html.markdown
+++ b/cobol.html.markdown
@@ -8,178 +8,187 @@ COBOL is a business-oriented language revised multiple times since its original
organizations.
```cobol
- *COBOL. Coding like it's 1985.
+ *COBOL. Coding like it's 1985.
*Compiles with GnuCOBOL in OpenCobolIDE 4.7.6.
*COBOL has significant differences between legacy (COBOL-85)
*and modern (COBOL-2002 and COBOL-2014) versions.
*Legacy versions require columns 1-6 to be blank (they are used
*to store the index number of the punched card..)
- *A * in column 7 means a comment.
+ *A '*' in column 7 means a comment.
*In legacy COBOL, a comment can only be a full line.
*Modern COBOL doesn't require fixed columns and uses *> for
*a comment, which can appear in the middle of a line.
*Legacy COBOL also imposes a limit on maximum line length.
*Keywords have to be in capitals in legacy COBOL,
*but are case insensitive in modern.
-
- *First, we must give our program ID.
+ *Although modern COBOL allows you to use mixed-case characters
+ *it is still common to use all caps when writing COBOL code.
+ *This is what most professional COBOL developers do.
+ *COBOL statements end with a period.
+
+ *COBOL code is broken up into 4 divisions.
+ *Those divisions, in order, are:
+ *IDENTIFICATION DIVSION.
+ *ENVIRONMENT DIVISION.
+ *DATA DIVISION.
+ *PROCEDURE DIVISION.
+
+ *First, we must give our program an ID.
*Identification division can include other values too,
- *but they are comments only. Program-id is mandatory.
- identification division.
- program-id. learn.
+ *but they are comments only. Program-id is the only one that is mandatory.
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARN.
+ AUTHOR. JOHN DOE.
+ DATE-WRITTEN. 05/02/2020.
*Let's declare some variables.
- data division.
- working-storage section.
-
- *Variables are specified by a "picture" - how they should be
- *displayed, and variable type is inferred from this.
- *The "01" value is the level number which is used for building
- *data structures.
- 01 myname picture xxxxxxxxxx. *> A 10 character string.
- 01 age picture 999. *> A number up to 3 digits.
- 01 valx picture 999. *> Another number up to 3 digits.
- 01 inyear picture s9(7). *> S makes number signed.
+ *We do this in the WORKING-STORAGE section within the DATA DIVISION.
+ *Each data item (aka variable) with start with a level number,
+ *then the name of the item, followed by a picture clause
+ *describing the type of data that the variable will contain.
+ *Almost every COBOL programmer will abbreviate PICTURE as PIC.
+ *A is for alphabetic, X is for alphanumeric, and 9 is for numeric.
+
+ *example:
+ 01 MYNAME PIC xxxxxxxxxx. *> A 10 character string.
+
+ *But counting all those x's can lead to errors,
+ *so the above code can, and should
+ *be re-written as:
+ 01 MYNAME PIC X(10).
+
+ *Here are some more examples:
+ 01 AGE PIC 9(3). *> A number up to 3 digits.
+ 01 LAST_NAME PIC X(10). *> A string up to 10 characters.
+
+ *In COBOL, multiple spaces are the same as a single space, so it is common
+ *to use multiple spaces to line up your code so that it is easier for other
+ *coders to read.
+ 01 inyear picture s9(7). *> S makes number signed.
*> Brackets indicate 7 repeats of 9,
*> ie a 6 digit number (not an array).
- *Now let's write some code.
- procedure division.
-
- main-procedure.
- *> COBOL is the language that uses DISPLAY instead of PRINT.
- *> Note: no full stops after commands. Only after the LAST
- *> command.
- display "Hello. What's your name?"
-
- *> Let's input a string.
- *> If input too long, later characters are trimmed.
- accept myname
- display "Hello " myname *> We can display several things.
- display "How old are you?"
-
- *> Let's input a number.
- *> If input too long, EARLIER characters are trimmed.
- accept age
-
- display age *> Left-padded to three chracaters with zeroes,
- *> because of the defined PICTURE for age.
-
- *> We have two ways of doing a FOR loop.
- *> Old style way: doesn't give an index.
- perform age times
- display "*" with no advancing *> Ie, no newline at end
- end-perform
- display "." *> Output buffer isn't flushed until newline.
-
- *> New style way: with an index.
- perform varying valx from 1 by 1 until valx > age
- display valx "-" with no advancing
- end-perform
- display "."
-
- *> If tests are still good old if tests.
- if myname = "Bob" then
- display "I don't like Bob."
- else
- display "I don't know you."
- end-if
-
- *> There are two ways of doing subprograms and calling
- *> them.
- *> The simplest way: a paragraph.
- perform subparagraph
-
- *> The complex way, with parameters and stuff.
- call "eratosthenes" using age returning valx
-
- display "There were " valx " primes."
-
- stop run.
-
- subparagraph. *> Marks the top of an internal subprogram.
- *> Shares variable score with its caller.
-
- *> Read year from system timer.
- *> Remember the whole "year 2000 crisis"? The yyyyddd
- *> option was added in response to that.
- accept inyear from day yyyyddd.
-
- *> We can do math step-by-step like this...
- divide 1000 into inyear.
- subtract age from inyear.
-
- display "You were born in " inyear "."
-
- *> Or we can just use expressions.
- compute inyear = 1970 - inyear.
-
- if inyear >= 0 then
- display "When you were " inyear ", " with no advancing
- else
- display inyear " years before you were born, " with no
- advancing
- end-if
-
- display "COBOL was the most popular language in the world."
- . *> You can put the final . on a new line if it's clearer.
-
-
- *If we want to use a subprogram, we use literally a subprogram.
- *This is the entire program layout, repeated for the
- *eratosthenes subroutine.
- identification division.
- program-id. eratosthenes.
-
- data division.
- working-storage section.
- *Declare an array.
- *We can declare a variable to use as an index for it at the
- *same time.
- 01 sieve pic 9 occurs 999 times indexed by sa, sb.
- *> Standard cobol doesn't have a boolean type.
- 01 pstart pic 999.
- 01 counter pic 999.
-
- *Our parameters have to be declared in the linkage section.
- *Their pictures must match the values they're called with.
- linkage section.
- 01 maxvalue picture 999.
-
- *"using" declares our actual parameter variables.
- *"returning" declares the variable value returned at end.
- procedure division using maxvalue returning counter.
- main-procedure.
-
- display "Here are all the primes up to " maxvalue "."
-
- perform varying sa from 1 by 1 until sa > maxvalue
- move 1 to sieve (sa)
- end-perform
-
- perform varying sa from 2 by 1 until sa > maxvalue
- if sieve(sa) = 1 then
- compute pstart = sa + sa
- perform varying sb from pstart by sa until sb >
- maxvalue
- move 0 to sieve(sb)
- end-perform
- end-if
- end-perform
-
- initialise counter *> To zero by default for a number.
-
- perform varying sa from 2 by 1 until sa > maxvalue
- if sieve(sa) = 1 THEN
- display sa
- add 1 to counter
- end-if
- end-perform.
-
- end program eratosthenes.
-
- end program learn.
+ *Now let's write some code. Here is a simple, Hello World program.
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLO.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 THE-MESSAGE PIC X(20).
+ PROCEDURE DIVSION.
+ DISPLAY "STARTING PROGRAM".
+ MOVE "HELLO WORLD" TO THE-MESSAGE.
+ DISPLAY THE-MESSAGE.
+ STOP RUN.
+
+ *The above code will output:
+ *STARTING PROGRAM
+ *HELLO WORLD
+
+
+
+ ********COBOL can perform math***************
+ ADD 1 TO AGE GIVING NEW-AGE.
+ SUBTRACT 1 FROM COUNT.
+ DIVIDE VAR-1 INTO VAR-2 GIVING VAR-3.
+ COMPUTE TOTAL-COUNT = COUNT1 PLUS COUNT2.
+
+
+ *********PERFORM********************
+ *The PERFORM keyword allows you to jump to another specified section of the code,
+ *and then to return to the next executable
+ *statement once the specified section of code is completed.
+ *You must write the full word, PERFORM, you cannot abbreviate it.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLOCOBOL.
+
+ PROCEDURE DIVISION.
+ FIRST-PARA.
+ DISPLAY 'THIS IS IN FIRST-PARA'.
+ PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perfrom 3rd & 4th
+ *> then after performing third and fourth,
+ *> return here and continue the program until STOP RUN.
+
+ SECOND-PARA.
+ DISPLAY 'THIS IS IN SECOND-PARA'.
+ STOP RUN.
+
+ THIRD-PARA.
+ DISPLAY 'THIS IS IN THIRD-PARA'.
+
+ FOURTH-PARA.
+ DISPLAY 'THIS IS IN FOURTH-PARA'.
+
+
+ *When you compile and execute the above program, it produces the following result:
+ THIS IS IN FIRST-PARA
+ THIS IS IN THIRD-PARA
+ THIS IS IN FOURTH-PARA
+ THIS IS IN SECOND-PARA
+
+
+ **********Combining variables together using STRING ***********
+
+ *Now it is time to learn about two related COBOL verbs: string and unstring.
+
+ *The string verb is used to concatenate, or put together, two or more stings.
+ *Unstring is used, not surprisingly, to separate a
+ *string into two or more smaller strings.
+ *It is important that you remember to use ‘delimited by’ when you
+ *are using string or unstring in your program.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARNING.
+ ENVIRONMENT DIVISION.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 FULL-NAME PIC X(20).
+ 01 FIRST-NAME PIC X(13) VALUE "BOB GIBBERISH".
+ 01 LAST-NAME PIC X(5) VALUE "COBB".
+ PROCEDURE DIVISION.
+ STRING FIRST-NAME DELIMITED BY SPACE
+ " "
+ LAST-NAME DELIMITED BY SIZE
+ INTO FULL-NAME
+ END-STRING.
+ DISPLAY "THE FULL NAME IS: "FULL-NAME.
+ STOP RUN.
+
+
+ *The above code will output:
+ THE FULL NAME IS: BOB COBB
+
+
+ *Let’s examine it to see why.
+
+ *First, we declared all of our variables, including the one that we are creating
+ *by the string command, in the DATA DIVISION.
+
+ *The action takes place down in the PROCEDURE DIVISION.
+ *We start with the STRING keyword and end with END-STRING. In between we
+ *list what we want to combine together into the larger, master variable.
+ *Here, we are combining FIRST-NAME, a space, and LAST-NAME.
+
+ *The DELIMITED BY phrase that follows FIRST-NAME and
+ *LAST-NAME tells the program how much of each variable we want to capture.
+ *DELIMITED BY SPACE tells the program to start at the beginning,
+ *and capture the variable until it runs into a space.
+ *DELIMITED BY SIZE tells the program to capture the full size of the variable.
+ *Since we have DELIMITED BY SPACE after FIRST-NAME, the GIBBERISH part is ignored.
+
+ *To make this clearer, change line 10 in the above code to:
+
+ STRING FIRST-NAME DELIMITED BY SIZE
+
+ *and then re-run the program. This time the output is:
+
+ THE FULL NAME IS: BOB GIBBERISH COBB
+
+
+
+
+
```
diff --git a/dart.html.markdown b/dart.html.markdown
index 2672dc6a..b215474a 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -6,7 +6,7 @@ contributors:
- ["Vince Ramces Oliveros", "https://github.com/ram231"]
---
-**Dart** is a single threaded, general puprose programming languages.
+**Dart** is a single threaded, general purpose programming language.
It borrows a lot from other mainstream languages.
It supports Streams, Futures(known as Promises in JavaScript), Generics, First-class functions(closures) and static type checking.
Dart can run in any platform such as Web, CLI, Desktop, Mobile and IoT devices.
@@ -198,7 +198,7 @@ class GenericExample<T>{
/// or outside of class have to be constant. Strings and numbers are constant
/// by default. But arrays and maps are not. They can be made constant by
/// declaring them "const". Kind of similar to Javascript's Object.freeze()
-const example8List = ["Example8 const array"],
+const example8List = ["Example8 const array"];
const example8Map = {"someKey": "Example8 const map"};
/// Declare List or Maps as Objects.
List<String> explicitList = new List<String>();
@@ -206,7 +206,6 @@ const example8Map = {"someKey": "Example8 const map"};
explicitList.add("SomeArray");
example8() {
- print(example8Array[0]);
print(example8Map["someKey"]);
print(explicitList[0]);
}
@@ -224,7 +223,7 @@ var newExplicitLists = explicitList.toList() // Converts Iterable<E> to List<E>
/// supported features, starting with forEach,map and where.
var example9Array = const ["a", "b"];
example9() {
- for (final i = 0; i < example9Array.length; i++) {
+ for (int i = 0; i < example9Array.length; i++) {
print("Example9 for loop '${example9Array[i]}'");
}
var i = 0;
@@ -694,7 +693,6 @@ example33() {
/// Dart has also added feature such as Null aware operators
var isBool = true;
var hasString = isBool ?? "default String";
-var hasValue ??= "default Value";
/// Programs have only one entry point in the main function.
/// Nothing is expected to be executed on the outer scope before a program
diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown
new file mode 100644
index 00000000..088a29a8
--- /dev/null
+++ b/de-de/clojure-macros-de.html.markdown
@@ -0,0 +1,161 @@
+---
+language: "clojure macros"
+filename: learnclojuremacros-de.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Wie mit allen Lisps besitzt auch Clojure die inhärente [Homoikonizität](https://en.wikipedia.org/wiki/Homoiconic),
+die dir den vollen Zugang der Sprache gibt, um
+ Code-Generierungsroutinen zu schreiben. Diese werden "Macros" genannt.
+Macros geben dir eine leistungsarke Möglichkeit, die Sprache
+an deine Bedürfnisse anzupassen.
+
+Sei aber vorsichtig, es wird als schlechter Stil angesehen, wenn du
+ein Macro schreibst, obwohl eine Funktion genausogut funktionieren würde.
+Verwende nur dann ein Macro, wenn du Kontrolle darüber brauchst, wann oder ob Argumente in einer Form evaluiert werden.
+
+Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Clojure in Y Minutes](/docs/clojure/) verstehst.
+
+```clojure
+;; Definiere ein Macro mit defmacro. Dein Macro sollte eine Liste zurückgeben,
+;; die als Clojure Code evaluiert werden kann.
+;;
+;; Dieses Macro ist das Gleiche, als ob du (reverse "Hallo Welt") geschrieben
+;; hättest
+(defmacro my-first-macro []
+ (list reverse "Hallo Welt"))
+
+;; Inspiziere das Ergebnis eines Macros mit macroexpand oder macroexpand-1.
+;;
+;; Beachte, dass der Aufruf zitiert sein muss.
+(macroexpand '(my-first-macro))
+;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hallo Welt")
+
+;; Du kannst das Ergebnis von macroexpand direkt auswerten.
+(eval (macroexpand '(my-first-macro)))
+; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Aber du solltest diese prägnante und funktionsähnliche Syntax verwenden:
+(my-first-macro) ; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Du kannst es dir leichter machen, indem du die Zitiersyntax verwendest
+;; um Listen in ihren Makros zu erstellen:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hallo Welt"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hallo Welt")
+;; Beachte, dass reverse nicht mehr ein Funktionsobjekt ist, sondern ein Symbol
+
+;; Macros können Argumente haben.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Aber wenn du versuchst das mit einer zitierten Liste zu machen wirst du
+;; einen Fehler bekommen, weil das Argument auch zitiert sein wird.
+;; Um dies zu umgehen, bietet Clojure einee Art und Weise Macros zu zitieren: `
+;; In ` kannst du ~ verwenden um in den äußeren Bereich zu kommen.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Du kannst die normalen destruktuierungs Argumente verwenden. Expandiere
+;; Listenvariablen mit ~@.
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Erinnere dich an das do!
+
+(macroexpand '(unless true (reverse "Hallo Welt")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hallo Welt")))
+
+;; (unless) evaluiert und gibt body zurück, wenn das erste Argument falsch ist.
+;; Andernfalls gibt es nil zurück
+
+(unless true "Hallo") ; -> nil
+(unless false "Hallo") ; -> "Hallo"
+
+;; Die Verwendung Macros ohne Sorgfalt kann viel Böses auslösen, indem es
+;; deine Variablen überschreibt
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;; Um das zu verhindern kannst du gensym verwenden um einen eindeutigen
+;; Identifikator zu bekommen
+(gensym 'x) ; -> x1281 (oder etwas Ähnliches)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Du kannst # innerhalb von ` verwenden um für jedes Symbol automatisch
+;; ein gensym zu erstellen
+(defmacro define-x-hygienically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygienically) ; -> (2)
+(list x) ; -> (4)
+
+;; Es ist üblich, Hilfsfunktionen mit Macros zu verwenden. Lass uns einige
+;; erstellen, die uns helfen , eine (dumme) arithmetische Syntax
+;; zu unterstützen
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Bekomme die Argumente [x (+ y)], gebe (+ x y) zurück"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Wir können es sofort testen, ohne ein Macro zu erstellen
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Allerdings, brauchen wir ein Macro, wenn wir es zur Kompilierungszeit
+; ausführen wollen
+(defmacro inline-2 [form]
+ (inline-2-helper form))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (eigentlich, 3N, da die Zahl zu einem rationalen Bruch mit / umgewandelt wird)
+```
+
+### Weiterführende Literatur
+
+[Macros schreiben](http://www.braveclojure.com/writing-macros/)
+
+[Offiziele Docs](http://clojure.org/macros)
+
+[Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/)
diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown
new file mode 100644
index 00000000..08832327
--- /dev/null
+++ b/de-de/elm-de.html.markdown
@@ -0,0 +1,376 @@
+---
+language: Elm
+filename: learnelm.elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+translators:
+ - ["waynee95", "https://waynee95.me"]
+lang: de-de
+---
+
+Elm ist eine pure funktionale Programmiersprache. Mit Elm werden GUIs
+(grafische Benutzeroberfläche) für Webanwendungen erstellt. Durch die statische
+Typisierung kann Elm viele Fehler schon bei der Kompilierung abfangen. Ein
+Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen.
+
+```haskell
+-- Einzeilige Kommentare beginnen mit 2 Bindestrichen.
+{- So wird ein mehrzeiliger Kommentar angelegt.
+{- Diese können auch verschachtelt werden. -}
+-}
+
+{-- Die Grundlagen --}
+
+-- Arithmetik
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Zahlen ohne Punkt sind entweder vom Typ Int oder Float.
+33 / 2 -- 16.5 mit Division von Gleitkommazahlen
+33 // 2 -- 16 mit ganzzahliger Division
+
+-- Exponenten
+5 ^ 2 -- 25
+
+-- Boolsche Werte
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings (Zeichenketten) und Zeichen
+"Das hier ist ein String."
+'a' -- Zeichen
+
+-- Strings können konkateniert werden.
+"Hello " ++ "world!" -- "Hello world!"
+
+{-- Listen und Tupel --}
+
+-- Jedes Element einer Liste muss vom gleichen Typ sein. Listen sind homogen.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- Das zweite Beispiel kann man auch mit Hilfe der "range" Funktion schreiben.
+List.range 1 5
+
+-- Listen werden genauso wie Strings konkateniert.
+List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True
+
+-- Mit dem "cons" Operator lässt sich ein Element an den Anfang einer Liste anfügen.
+0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5]
+
+-- Die Funktionen "head" und "tail" haben als Rückgabewert den "Maybe" Typ.
+-- Dadurch wird die Fehlerbehandlung von fehlenden Elementen explizit, weil
+-- man immer mit jedem möglichen Fall umgehen muss.
+List.head (List.range 1 5) -- Just 1
+List.tail (List.range 1 5) -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.funktionsName bedeutet, dass diese Funktion aus dem "List"-Modul stammt.
+
+-- Tupel sind heterogen, jedes Element kann von einem anderen Typ sein.
+-- Jedoch haben Tupel eine feste Länge.
+("elm", 42)
+
+-- Das Zugreifen auf Elemente eines Tupels geschieht mittels den Funktionen
+-- "first" und "second".
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
+
+-- Das leere Tupel, genannt "Unit", wird manchmal als Platzhalter verwendet.
+-- Es ist das einzige Element vom Typ "Unit".
+()
+
+{-- Kontrollfluss --}
+
+-- Eine If-Bedingung hat immer einen Else-Zweig und beide Zweige müssen den
+-- gleichen Typ haben.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- If-Bedingungen können verkettet werden.
+if n < 0 then
+ "n is negative"
+else if n > 0 then
+ "n is positive"
+else
+ "n is zero"
+
+-- Mit dem Mustervergleich (pattern matching) kann man bestimmte Fälle direkt
+-- behandeln.
+case aList of
+ [] -> "matches the empty list"
+ [x]-> "matches a list of exactly one item, " ++ toString x
+ x::xs -> "matches a list of at least one item whose head is " ++ toString x
+-- Mustervergleich geht immer von oben nach unten. Würde man [x] als letztes
+-- platzieren, dann würde dieser Fall niemals getroffen werden, weil x:xs diesen
+-- Fall schon mit einschließt (xs ist in dem Fall die leere Liste).
+
+-- Mustervergleich an einem Maybe Typ.
+case List.head aList of
+ Just x -> "The head is " ++ toString x
+ Nothing -> "The list was empty."
+
+{-- Funktionen --}
+
+-- Die Syntax für Funktionen in Elm ist minimal. Hier werden Leerzeichen anstelle
+-- von runden oder geschweiften Klammern verwendet. Außerdem gibt es kein "return"
+-- Keyword.
+
+-- Eine Funktion wird durch ihren Namen, einer Liste von Parametern gefolgt von
+-- einem Gleichheitszeichen und dem Funktionskörper angegeben.
+multiply a b =
+ a * b
+
+-- Beim Aufruf der Funktion (auch Applikation genannt) werden die Argumente ohne
+-- Komma übergeben.
+multiply 7 6 -- 42
+
+-- Partielle Applikation einer Funktion (Aufrufen einer Funktion mit fehlenden
+-- Argumenten). Hierbei entsteht eine neue Funktion, der wir einen Namen geben.
+double =
+ multiply 2
+
+-- Konstanten sind Funktionen ohne Parameter.
+answer =
+ 42
+
+-- Funktionen, die Funktionen als Parameter haben, nennt man Funktionen höherer
+-- Ordnung. In funktionalen Programmiersprachen werden Funktionen als "first-class"
+-- behandelt. Man kann sie als Argument übergeben, als Rückgabewert einer Funktion
+-- zurückgeben oder einer Variable zuweisen.
+List.map double (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Funktionen können auch als anonyme Funktion (Lambda-Funktionen) übergeben werden.
+-- Diese werden mit einem Blackslash eingeleitet, gefolgt von allen Argumenten.
+-- Die Funktion "\a -> a * 2" beschreibt die Funktion f(x) = x * 2.
+List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Mustervergleich kann auch in der Funktionsdefinition verwendet werden.
+-- In diesem Fall hat die Funktion ein Tupel als Parameter. (Beachte: Hier
+-- werden die Werte des Tupels direkt ausgepackt. Dadurch kann man auf die
+-- Verwendung von "first" und "second" verzichten.)
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Mustervergleich auf Records macht man mit geschweiften Klammern.
+-- Bezeichner (lokale Variablen) werden mittels dem "let" Keyword angelegt.
+-- (Mehr zu Records weiter unten!)
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Rekursive Funktion
+fib n =
+ if n < 2 then
+ 1
+ else
+ fib (n - 1) + fib (n - 2)
+
+List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
+
+-- Noch eine rekursive Funktion (Nur ein Beispiel, verwende stattdessen immer
+-- List.length!)
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Funktionsapplikation hat die höchste Präzedenz, sie binden stärker als Operatoren.
+-- Klammern bietet die Möglichkeit der Bevorrangung.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen.
+-- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben.
+-- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese
+-- beiden Werte dann addiert.
+
+{-- Typen und Typ Annotationen --}
+
+-- Durch Typinferenz kann der Compiler jeden Typ genau bestimmen. Man kann diese
+-- aber auch manuell selber angeben (guter Stil!).
+-- Typen beginnen immer mit eine Großbuchstaben. Dabei liest man "x : Typ" als
+-- "x" ist vom Typ "Typ".
+-- Hier ein paar übliche Typen:
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Funktionen haben ebenfalls einen Typ. Dabei ist der ganz rechte Typ der
+-- Rückgabetyp der Funktion und alle anderen sind die Typen der Parameter.
+not : Bool -> Bool
+round : Float -> Int
+
+-- Es ist guter Stil immer den Typ anzugeben, da diese eine Form von Dokumentation
+-- sind. Außerdem kann so der Compiler genauere Fehlermeldungen geben.
+double : Int -> Int
+double x = x * 2
+
+-- Funktionen als Parameter werden durch Klammern angegeben. Die folgende Funktion
+-- ist nicht auf einen Typ festgelegt, sondern enthält Typvariablen (beginnend
+-- mit Kleinbuchstaben). Die konkreten Typen werden erst bei Anwendung der
+-- Funktion festgelegt. "List a" bedeutet, dass es sich um eine Liste mit
+-- Elementen vom Typ "a" handelt.
+List.map : (a -> b) -> List a -> List b
+
+-- Es gibt drei spezielle kleingeschriebene Typen: "number", "comparable" und
+-- "appendable".
+add : number -> number -> number
+add x y = x + y -- funktioniert mit Ints und Floats.
+
+max :: comparable -> comparable -> comparable
+max a b = if a > b then a else b -- funktioniert mit Typen, die vergleichbar sind.
+
+append :: appendable -> appendable -> appendable
+append xs ys = xs ++ ys -- funktioniert mit Typen, die konkatenierbar sind.
+
+append "hello" "world" -- "helloworld"
+append [1,1,2] [3,5,8] -- [1,1,2,3,5,8]
+
+{-- Eigene Datentypen erstellen --}
+
+-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat.
+-- Dabei spielt die Reihenfolge keine Rolle.
+{ x = 3, y = 7 }
+
+-- Um auf Werte eines Records zuzugreifen, benutzt man einen Punkt gefolgt
+-- von dem Namen des Feldes.
+{ x = 3, y = 7 }.x -- 3
+
+-- Oder mit einer Zugriffsfunktion, welche aus einem Punkt und dem Feldnamen besteht.
+.y { x = 3, y = 7 } -- 7
+
+-- Wert eines Feldes ändern. (Achtung: Das Feld muss aber vorher schon vorhanden sein!)
+{ person |
+ name = "George" }
+
+-- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes.
+{ particle |
+ position = particle.position + particle.velocity,
+ velocity = particle.velocity + particle.acceleration }
+
+-- Du kannst ein Record auch als Typ Annotation verwenden.
+-- (Beachte: Ein Record Typ benutzt einen Doppelpunkt und ein Record Wert benutzt
+-- ein Gleichheitszeichen!)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- Durch das "type" Keyword kann man einem existierenden Typen einen Namen geben.
+type alias Point3D =
+ { x : Float, y : Float, z : Float }
+
+-- Der Name kann dann als Konstruktor verwendet werden.
+otherOrigin : Point3D
+otherOrigin =
+ Point3D 0 0 0
+
+-- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist!
+origin == otherOrigin -- True
+
+-- Neben den Records gibt es auch noch so genannte Summentypen.
+-- Ein Summentyp hat mehrere Konstruktoren.
+type Direction =
+ North | South | East | West
+
+-- Ein Konstruktor kann außerdem noch andere Typen enthalten. Rekursion ist
+-- auch möglich.
+type IntTree =
+ Leaf | Node Int IntTree IntTree
+
+-- Diese können auch als Typ Annotation verwendet werden.
+root : IntTree
+root =
+ Node 7 Leaf Leaf
+
+-- Außerdem können auch Typvariablen verwendet werden in einem Konstruktor.
+type Tree a =
+ Leaf | Node a (Tree a) (Tree a)
+
+-- Beim Mustervergleich kann man auf die verschiedenen Konstruktoren matchen.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+{-- Module und Imports --}
+
+-- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt.
+-- Für große Projekte können auch eigene Module erstellt werden.
+
+-- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich
+-- automatisch im Modul "Main".
+module Name where
+
+-- Ohne genaue Angabe von Exports wird alles exportiert. Es können aber alle
+-- Exporte explizit angegeben werden.
+module Name (MyType, myValue) where
+
+-- Importiert das Modul "Dict". Jetzt kann man Funktionen mittels "Dict.insert"
+-- aufrufen.
+import Dict
+
+-- Importiert das "Dict" Modul und den "Dict" Typ. Dadurch muss man nicht "Dict.Dict"
+-- verwenden. Man kann trotzdem noch Funktionen des Moduls aufrufen, wie "Dict.insert".
+import Dict exposing (Dict)
+
+-- Abkürzung für den Modulnamen. Aufrufen der Funktionen mittels "C.funktionsName".
+import Graphics.Collage as C
+
+{-- Kommandozeilen Programme --}
+
+-- Eine Elm-Datei kompilieren.
+$ elm make MyFile.elm
+
+-- Beim ersten Aufruf wird Elm die "core" Bibliotheken installieren und eine
+-- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes
+-- speichert.
+
+-- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt.
+$ elm reactor
+
+-- Starte das REPL (read-eval-print-loop).
+$ elm repl
+
+-- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert.
+-- Installieren einer neuen Bibliothek.
+$ elm package install elm-lang/html
+-- Diese wird der elm-package.json Datei hinzugefügt.
+
+-- Zeigt alle Veränderungen zwischen zwei bestimmten Versionen an.
+$ elm package diff elm-lang/html 1.1.0 2.0.0
+-- Der Paketmanager von Elm erzwingt "semantic versioning"!
+```
+
+Elm ist eine besonders kleine Programmiersprache. Jetzt hast du genug Wissen an
+deiner Seite, um dich in fast jedem Elm Code zurecht zu finden.
+
+Noch ein paar weitere hilfreiche Ressourcen (in Englisch):
+
+- Die [Elm Homepage](http://elm-lang.org/). Dort findest du:
+
+ - [Anleitung zur Installierung von Elm](http://elm-lang.org/install)
+ - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax)
+ - Viele hilfreiche [Beispiele](http://elm-lang.org/examples)
+
+- Dokumentation der [Elm Kernbibliotheken](http://package.elm-lang.org/packages/elm-lang/core/latest/). Insbesondere:
+
+ - [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics) (standardmäßig importiert)
+ - [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) sowie [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) (benutzt für Fehlerbehandlung)
+ - Datenstrukturen, wie [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), und [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ - JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) und [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+- [Die Elm Architektur](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture).
+
+- Die [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss).
diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown
index fd8fb3c4..13c00b01 100644
--- a/de-de/perl-de.html.markdown
+++ b/de-de/perl-de.html.markdown
@@ -8,9 +8,9 @@ translators:
lang: de-de
---
-Perl 5 ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
+Perl ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
-Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl 5 ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
+Perl läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
```perl
# Einzeilige Kommentare beginnen mit dem # Symbol.
diff --git a/de-de/processing-de.html.markdown b/de-de/processing-de.html.markdown
new file mode 100644
index 00000000..42ae2233
--- /dev/null
+++ b/de-de/processing-de.html.markdown
@@ -0,0 +1,498 @@
+---
+language: processing
+filename: learnprocessing.pde
+contributors:
+ - ["Phone Thant Ko", "http://github.com/phonethantko"]
+ - ["Divay Prakash", "https://github.com/divayprakash"]
+translators:
+ - ["caminsha", "https://github.com/caminsha"]
+filename: processing-de.md
+lang: de-de
+---
+
+## Einführung
+
+Processing ist eine Programmiersprache, welche es ermöglicht, digitale Kunst
+und multimediale Inhalte zu erstellen. Mit Processing können Personen ohne
+Programmiererfahrung die Grundlagen der Computerprogrammierung in einem
+visuellen Kontext erlernen.
+
+Obwohl Processing von Java beeinflusst wurde und auf Java basiert, ist die Syntax
+sowohl von Java als auch Javascript beeinflusst worden. Weitere Informationen
+sind [hier](https://processing.org/reference/) zu finden.
+
+Die Programmiersprache wird statisch programmiert und kommt mit einer eigenen
+offiziellen IDE, damit die Programme kompiliert und ausgeführt werden können.
+
+```
+/* ------------
+ Mehrzeilige Kommentare werden so gemacht
+*/
+
+// Einzeilige Kommentare funktionieren so //
+
+/*
+ Da Processing von Java abstammt, ist die Syntax für Kommentare gleich
+ wie bei Java (wie du vielleicht oben bemerkt hast)!
+ Mehrzeilige Kommentare werden wie hier umschloßen.
+*/
+
+/* -------------------------------------------------
+ Schreiben und Ausführen von Processing Programmen
+ -------------------------------------------------
+*/
+
+// In Processing ist der Startpunkt eines Programms die Funktion `setup()`
+// mit dem Rückgabetyp `void`.
+// Beachte: Die Syntax ist derjenigen von C++ ziemlich ähnlich.
+void setup() {
+ // Dies gibt beim Ausführen "Hallo Welt!" auf der Konsole aus.
+ println("Hallo Welt!"); // eine weitere Sprache mit einem Semikolon am Ende.
+}
+
+// Normalerweise wird der Code für statische Elemente innerhalb der Methode
+// `setup()` geschrieben, da diese lediglich einmal ausgeführt wird.
+// Dies kann zum Beispiel das Setzen der Hintergrundfarbe oder das Bestimmen
+// der Canvas-Größe sein.
+background(color); // Setze die Hintergrundfarbe
+size(width, height, [renderer]); // bestimme die Canvasgröße mit dem optionalen
+ // Parameter `renderer`.
+// Du wirst innerhalb dieses Dokuments noch weitere Parameter sehen.
+
+// Wenn du möchstest, dass Code unendlich oft ausgeführt wird, so muss dieser
+// Code innerhalb der `draw()`-Methode stehen.
+// `draw()` muss existieren, wenn du möchtest, dass das Programm durchgehend
+// läuft. Die `draw()`-Methode darf nur einmal vorkommen.
+
+int i = 0;
+void draw() {
+ // Dieser Codeblock wird ausgeführt bis er gestoppt wird.
+ print(i);
+ i++; // Inkrement-Operator
+}
+
+// Da wir nun wissen, wie man ein funktionierendes Skript erstellen kann und wie
+// dieses ausgeführt wird, fahren wir mit den unterschiedlichen Datentypen und
+// Collections weiter, welche in Processing unterstützt werden.
+
+/* -------------------------------------------------
+ Datentypen und Collections
+ -------------------------------------------------
+*/
+
+// Gemäß den Angaben in der Processingreferenz, unterstützt Processing die
+// folgenden acht primitiven Datentypen:
+boolean booleanValue = true; // Boolean
+byte byteValueOfA = 23; // Byte
+char charValueOfA = 'A'; // Char (einzelnes Zeichen)
+color colorValueOfWhiteM = color(255, 255, 255); // Farben (angegeben durch die
+ // `color()`-Methode)
+color colorValueOfWhiteH = #FFFFFF; // Farbe (angegeben mit der Hexadezimal-
+ // schreibweise.)
+int intValue = 5; // Integer (ganze Zahl)
+long longValue = 2147483648L; // "L" wird hinzugefügt, um es als `long` zu
+ // markieren.
+float floatValue = 1.12345; // Float (32-Bit Gleitkommazahl)
+double doubleValue = 1.12345D // Double (64-Bit Gleitkommazahl)
+
+//BEACHTE!
+// Auch wenn es die Datentypen "long" und "double" gibt und auch funktionieren,
+// verwenden Processing-Funktionen diese Datentypen nicht. Das bedeutet, dass
+// diese zu "int" resp. "float" konvertiert werden müssen.
+// Dies geschieht, indem man `(int)` oder `(float)` vor die Variable schreibt,
+// bevor diese einer Funktion übergeben werden.
+
+// Es gibt eine ganze Reiher zusammengesetzter Datentypen, welche in Processing
+// gebraucht werden können. Um Zeit zu sparen, gehen wir in diesem Tutorial
+// lediglich die wichtigsten durch.
+
+// String
+// Während der Datentyp `char` einfache Anzührungszeichen (' ') braucht, haben
+// Strings doppelte Anführungszeichen (" ").
+String sampleString = "Hallo, Processing!";
+// Strings können auch durch ein Array von `char`s erstellt werden.
+// Wir werden Arrays gleich anschauen.
+char source = {'H', 'A', 'L', 'L', 'O'};
+String stringFromSource = new String(source); // HALLO
+// Wie auch in Java können in Processing Strings auch zusammengefügt werden
+// mit dem +-Operator.
+print("Hallo " + "Welt!"); // => Hallo Welt!
+
+
+// Arrays
+// In Processing können Arrays jeden Datentypen beinhalten, sogar Objekte.
+// Da Arrays ähnlich wie Objekte sind, müssen diese mit dem Schlüsselwort `new`
+// erstellt werden.
+int[] intArray = new int[5];
+int[] intArrayWithValues = {1, 2, 3} // Arrays können auch mit Daten gefüllt
+ // werden.
+// ArrayList
+// Die Funktionen einer ArrayList sind ähnlich wie die eines Arrays und können
+// auch jegliche Datentypen beinhalten. Der einzige Unterschied zwischen Arrays
+// und `ArrayList`s ist, dass eine `ArrayList` die Größe dynamisch anpassen kann,
+// da es eine Implementierung des "List" Interface in Java ist.
+ArrayList<Integer> intArrayList = new ArrayList<Integer>();
+
+// Objekte
+// Da Processing auf Java basiert, unterstützt Processing die Objektorientierte
+// Programmierung. Dies bedeutet, dass du grundsätzlich jegliche Datentypen
+// selber erstellen kannst und diese nach deinen Bedürfnissen manipulieren kannst.
+// Selbstverständlich muss eine Klasse definiert werden bevor du ein Objekt
+// davon instanzieren kannst.
+// Format: ClassName InstanceName
+SomeRandomClass myObject // hier musst du das Objekt später instazieren
+// Hier wird das Objekt direkt instanziert:
+SomeRandomClass myObjectInstantiated = new SomeRandomClass();
+
+// Processing hat noch weitere Collections (wie zum Beispiel Dictionaries und
+// Listen). Aus Einfachheitsgründen wird dies in diesem Tutorial weggelassen.
+
+/* -------------------------------------------------
+ Mathematik
+ -------------------------------------------------
+*/
+
+// Arithmetik
+1 + 1 // => 2
+2 -1 // => 1
+2 * 3 // => 6
+3 / 2 // => 1
+3.0 / 2 // => 1.5
+3.0 % 2 // => 1.0 (Modulo)
+
+// Processing beinhaltet auch einige Funktionen, welche mathematische
+// Operationen vereinfachen
+float f = sq(3); // Quadrat => f = 9.0
+float p = pow(3, 3); // Potenz => p = 27.0
+int a = abs(-13); // Absolute Zahl => a = 13
+int r1 = round(3.1); // Runden => r1 = 3
+int r2 = round(3.7); // Runden => r2 = 4
+int sr = sqrt(25); // Quadratwurzel => sr = 5.0
+
+// Vektoren
+// Processing bietet eine einfache Möglichkeit an, mit Vektoren zu arbeiten mit
+// der Klasse PVector. Die Klasse kann zwei- und dreidimensionale Vektoren
+// darstellen und bietet Methoden an, welche nützlich sein können für Matrizen-
+// Operationen. Weitere Informationen findest du hier:
+// (https://processing.org/reference/PVector.html)
+
+// Trigonometrie
+// Processing unterstützt auch trigonometrische Operationen mit Hilfe dieser
+// Funktionen: `sin()`, `cos()`, `tan()`, `asin()`, `atan()`. Für die einfache
+// Konvertierung gibt es außerdem noch die Funktionen `degrees()` und `radians()`.
+// Die trigonometrischen Funktionen rechnen mit dem Winkelmaß Radian, wodurch
+// die Gradzahlen zuerst konvertiert werden müssen.
+float one = sin(PI/2); // => one = 1.0
+// Wie du vielleicht bemerkt hast, existieren einige Konstanten für trigo-
+// metrische Operationen; `PI`, `HALF_PI`, `QUARTER_PI` und so weiter ...
+
+/* -------------------------------------------------
+ Kontrollstrukturen
+ -------------------------------------------------
+*/
+
+// Bedingte Anweisungen
+// Bedinge Anweisungen werden gleich wie in Java geschrieben.
+if (author.getAppearence().equals("hot")) {
+ print("Narzissmus vom Feinsten!")
+} else {
+ // Du kannst hier weitere Bedingungen prüfen.
+ print("Irgendetwas ist falsch hier!");
+}
+// Für die `if`-Anweisungen gibt es auch eine Kurzschreibweise
+// Dies sind sogenannte ternäre Operatoren.
+int i = 3;
+String value = (i > 5) ? "Groß" : "Klein"; // => "Klein"
+
+// Die Switch-Case-Anweisung kann verwendet werden, um mehrere Bedingungen
+// zu prüfen.
+// Wichtig ist, dass nach jeder Bedingung ein `break`-Statement verwendet wird,
+// sonst werden alle folgenden ausgeführt und es wird nicht mehr überprüft, ob
+// die Bedingung wahr ist.
+int value = 2;
+switch(value) {
+ case 0:
+ print("Auf keinen Fall!"); // Dies wird nicht ausgeführt.
+ break; // Geht zum nächsten Statement und prüft dieses
+ case 1:
+ print("Wir kommen näher..."); // Auch dies wird nicht ausgeführt
+ break;
+ case 2:
+ print("Bravo!"); // Dies wird ausgeführt.
+ break;
+ default:
+ print("Nicht gefunden."); // Diese Zeile wird ausgeführt, wenn keine
+ // der anderen Operatoren wahr sind.
+ break;
+}
+
+// Wiederholungen
+// For-Schleifen - Auch hier ist die Syntax wieder gleich wie in Java
+for(int i = 0; i < 5; i++) {
+ print(i); // Gibt die Zahlen 0 bis 4 aus.
+}
+
+// While-Statements
+int j = 3;
+while(j > 0) {
+ print(j);
+ j--; // Dies ist wichtig, dass der Code nicht unendlich lange läuft.
+}
+
+// `loop()` | `noloop()` | `redraw()` | `exit()`
+// Dies sind spezifische Funktionen, welche in Processing verwendet werden
+// können, um den Programmablauf zu steuern.
+loop(); // erlaubt es der `draw()`-Methode immer zu laufen, während
+noloop(); // dies nur für einmal erlaubt.
+redraw(); // führt die `draw()`-Methode noch einmal aus.
+exit(); // Diese Methode stoppt das Programm. Dies kann nützlich sein, wenn die
+ // Methode `draw()` immer läuft.
+```
+
+## Mit Processing zeichnen
+
+Da du nun die Grundsätze der Programmiersprache verstanden hast, schauen wir
+uns nun das Beste an Processing an - Das Zeichnen!
+
+```
+
+/* -------------------------------------------------
+ Figuren
+ -------------------------------------------------
+*/
+
+// 2D-Figuren
+
+// Punkte
+point(x,y); // im zweidimensionalen Raum
+point(x, y, z); // im dreidimensionalen Raum
+// Diese Befehle zeichnen einen Punkt an der Koordinate.
+
+// Linien
+line(x1, y1, x2, y2); // im zweidimensionalen Raum
+// Dies zeichnet eine Linie, welche durch die zwei Punkte (x1, y1) und (x2, y2)
+// definiert wird.
+line(x1, y1, z1, x2, y2, z2); // im dreidimensionalen Raum
+// Analog wird hier eine Linie gezeichnet mit drei Punkten
+
+// Dreieck
+triangle(x1, y1, x2, y2, x3, y3);
+// Zeichnet ein Dreieck, welches als Eckpunkte die drei Koordinaten hat.
+
+// Rechteck
+rect(a, b, c, d, [r]); // Mit dem optionalen Parameter kann der Winkel aller
+ // vier Ecken definiert werden
+rect(a, b, c, d, [tl, tr, br, bl]); // Mit weiteren optionalen Parametern kann
+ // jeder Winkel des Rechtecks definiert werden.
+// Dies zeichnet ein Quadrat mit der Koordinate {a, b} als linke obere Ecke
+// die Parameter c und d sind für die Breite und Höhe.
+
+// Vierecke
+quad(x, y, x2, y2, x3, y3, x4, y4);
+// Dies zeichnet ein Viereck, welches die einzelnen Koordinaten als Eckpunkte hat.
+
+// Ellipse
+ellipse(x, y, width, height);
+// Zeichnet eine Ellipse beim Punkt {x. y}. Die Breite und die Höhe werden durch
+// die Parameter width und height definiert.
+
+// Arc
+arc(x, y, width, height, start, stop, [mode]);
+// Die ersten vier Parameter sollten selbsterklärend sein.
+// start und end definieren die Winkel, bei welchen `arc` starten resp. enden
+// (in Radians)
+// Der optionale Parameter `mode` definiert, ob der Kreisbogen gefüllt wird
+// oder nicht.
+// Die möglichen Optionen für `mode` sind: PIE, CHORD und OPEN.
+
+// Kurven
+// Processing bietet zwei mögliche Kurven an, welche verwendet werden können.
+// Da es hier darum geht, dass es möglichst simpel ist, werden hier keine
+// weiteren Details genannt. Wenn du Kurven in deinem Programm verwenden möchtest,
+// sind die folgenden Links empfehlenswert:
+// https://processing.org/reference/curve_.html
+// https://processing.org/reference/bezier_.html
+
+
+// 3D-Figuren
+
+// Der dreidimensionale Raum kann aktiviert werden, indem man den Renderer-
+// Parameter in der Methode `size()` zu "P3D" setzt.
+size(width, height, P3D);
+// Im dreidimensionalen Raum müssen die Koordinaten übersetzt werden, damit
+// diese korrekt gerendert werden.
+
+// Box
+box(size); // Würfel mit der Seitenlänge `size`
+box(w, h, d); // Quader definiert durch Breite, Höhe und Tiefe
+
+// Kugel
+sphere(radius); // Die Größe wird definiert durch den Parameter `radius`
+// Der Mechanismus hinter dem Rendern von Kugeln wurde durch mosaikartige
+// Dreiecke implementiert.
+// Mit der folgenden Funktion ist es möglich, zu bestimmen wie detailliert die
+// Kugel gerendert wird.
+// spereDetail(res);
+// Weitere Informationen sind hier zu finden: (https://processing.org/reference/sphereDetail_.html)
+
+// Unregelmäßige Figuren
+// Was ist, wenn du etwas zeichnen möchtest, was nicht durch Processing-Funktionen
+// abgedeckt ist?
+// Es ist möglich, die Funktionen `beginShape()`, `endShape()` und `vertex(x,y)
+// zu verwenden.
+// Weitere Informationen findest du hier: (https://processing.org/reference/beginShape_.html)
+// Du kannst selber gemachte Formen auch verwenden mit der PShape-Klasse.
+// Informationen zu PShape gibt es hier: (https://processing.org/reference/PShape.html)
+
+/* -------------------------------------------------
+ Transformationen
+ -------------------------------------------------
+*/
+
+// Tranformationen sind nützlich, um ständig zu wissen, wo die Koordinaten und
+// die Ecken einer Form sind, welche du gezeichnet hast. Grundsätzlich sind dies
+// Matrizenoperationen. `pushMatrix()`, `popMatrix()` und `translate()`.
+pushMatrix(); // Speichert das aktuelle Koordinatensystem auf dem Stack
+ // alle Transformationen werden hier angewendet.
+popMatrix(); // Stellt das gespeicherte Koordinatensystem wieder her.
+// Wenn du diese Funktionen verwendest, kann das Koordinatensystem gespeichert
+// und visualisiert werden, ohne dass es Konflikte gibt.
+
+// Translate
+translate(x,y); // Setzt den Ursprung zu diesem Punkt.
+translate(x, y, z); // Pendant zu der oberen Funktion im dreidimensionalen Raum
+
+// Rotationen
+rotate(angle); // Rotiere, um den Betrag, welcher spezifiert wurde.
+// Es gibt drei Pendants im dreidimensionalen Raum.
+// Namentlich sind dies: `rotateX(angle)`, `rotateY(angle)` und `rotateZ(angle)`
+
+// Skalierung
+scale(s); // Skaliert das Koordinatensystem (entweder erweitern oder verkleinern)
+
+/* -------------------------------------------------
+ Styling und Texturen
+ -------------------------------------------------
+*/
+
+// Farben
+// Wie ich zuvor schon erklärt habe, kann die Hintergrundfarbe mit der Funktion
+// `background()` definiert werden. Außerdem ist es möglich, dass man zuerst
+// eine Farbe definiert und diese erst danach der Funktion übergeben wird.
+color c = color(255, 255, 255); // WEISS!
+// Standardmäßig verwendet Processing das RGB-Farbschema, aber dies kann
+// zu HSB konfiguriert werden, indem die Funktion `colorMode()` verwendet wird.
+// Weitere Informationen findest du hier: (https://processing.org/reference/colorMode_.html)
+background(c); // Ab jetzt ist der Hintergrund in weiß.
+// Du kannst die Funktion `fill()` verwenden, um die Farbe auszuwählen, mit
+// welcher die Formen ausgefüllt werden.
+// Dies muss konfiguriert werden bevor Formen und Figuren gezeichnet werden.
+fill(color(0, 0, 0));
+// Wenn du nur die Farbe der Umrandungen definieren möchtest, kannst du die
+// Funktion `stroke()` verwenden.
+stroke(255, 255, 0, 200); // Linienfarbe wird zu gelb mit einer höheren
+ // Transparenz geändert.
+
+// Bilder
+// Processing kann Bilder rendern und diese unterschiedlich verwenden. Die
+// meisten Bilder sind im Datentyp `PImage` gespeichert.
+filter(shader); // Processing unterstützt mehrere Filter-Funktionen, damit
+ // Bilder verändert werden können.
+texture(image); // PImage kann als Argument, weiteren Funktionen übergeben
+ // werden, um die Figuren zu "Text" zu machen.
+```
+
+Wenn du weitere Dinge mit Processing kennenlernen willst, dann gibt es unzählige
+Dinge, welche du mit Processing machen kannst. Das Rendern von Modellen,
+Schattierungen und viele mehr. Für ein kurzes Tutorial bietet Processing zu viel,
+daher verweise ich dich, falls du interessiert bist, auf die offizielle
+Dokumentaion.
+
+```
+// Bevor wir weiterfahren, werde ich einige Aspekte zum Importieren von
+// Bibliotheken und Paketen sagen, damit du Processing erweitern kannst..
+
+/* -------------------------------------------------
+ Import
+ -------------------------------------------------
+*/
+
+// Die Macht von Processing kann besser veranschaulicht werden, wenn wir
+// Bibliotheken und Pakete importieren.
+// Die Import-Anweisung kann wie unten geschrieben zu Beginn des Quelltextes
+// geschrieben werden.
+import processing.something.*;
+```
+
+## Beispielprogramm
+
+Lass uns ein Beispiel von openprocessing.org ansehen, welches verdeutlicht,
+was man in Processing mit nur wenigen Zeilen Code machen kann.
+
+Kopiere den nachfolgenden Code in deine Processing IDE.
+
+```
+// Disclaimer: Ich habe das Porgramm nicht selbst geschriben. Diese Skizze
+// stammt aus openprocessing, allerdings soll dieses Programm zeigen, wie wenig
+// Zeilen Code notwendig sind, um etwas Cooles zu machen.
+// Abgerufen von: (https://www.openprocessing.org/sketch/559769)
+
+float theta;
+float a;
+float col;
+float num;
+
+void setup() {
+ size(600,600);
+}
+
+void draw() {
+ background(#F2F2F2);
+ translate(width/2, height/2);
+ theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6);
+
+ float num=6;
+ for (int i=0; i<num; i++) {
+ a =350;
+ rotate(TWO_PI/num);
+ branch(a);
+ }
+}
+
+void branch(float len) {
+ col=map(len, 0, 90, 150, 255);
+ fill(col, 0, 74);
+ stroke (col, 0, 74);
+ line(0, 0, 0, -len);
+ ellipse(0, -len, 3, 3);
+ len*=0.7;
+
+ if (len>30) {
+ pushMatrix();
+ translate(0, -30);
+ rotate(theta);
+ branch(len);
+ popMatrix();
+
+ pushMatrix();
+ translate(0, -30);
+ rotate(-theta);
+ branch(len);
+ popMatrix();
+ }
+}
+```
+
+Processing ist einfach zu erlernen und ist vorallem nützlich, um Multimedia-
+Inhalte (auch in 3D) zu erstellen ohne viel Code zu schreiben. Es ist so einfach
+gehalten, dass man den Code durchlesen kann und man versteht den Programmablauf
+bereits.
+
+Wenn du externe Bibliotheken, Pakete oder eigene Klassen einbindest, kann ein
+Programm, welches mit Processing geschrieben wurde, durchaus auch kompliziert
+werden.
+
+## Einige nützliche Links
+
+- [Processing Webseite](http://processing.org)
+- [Processing Sketches](http://openprocessing.org)
diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown
new file mode 100644
index 00000000..c86494ce
--- /dev/null
+++ b/de-de/pug-de.html.markdown
@@ -0,0 +1,208 @@
+---
+language: Pug
+contributors:
+ - ["Michael Warner", "https://github.com/MichaelJGW"]
+filename: lernepug-de.pug
+translators:
+ - ["denniskeller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+## Erste Schritte mit Pug
+
+Pug ist eine kleine Sprache, die zu HTML kompiliert. Sie hat eine
+saubere Syntax mit zusätzlichen Funktionen wie if Anweisungen und Schleifen.
+Sie kann auch als serverseitige Templatingsprache für Serversprachen
+wie NodeJS verwendet werden.
+
+### Die Sprache
+```pug
+
+//- Einzeilenkommentar
+
+//- Mehrzeiliger
+ Kommentar
+
+//- ---TAGS---
+//- Grundlagen
+div
+//- <div></div>
+h1
+//- <h1></h1>
+mein-benutzerdefiniertesTag
+//- <mein-benutzerdefiniertesTag></mein-benutzerdefiniertesTag>
+
+//- Geschwister
+div
+div
+//- <div></div>
+ <div></div>
+
+//- Kind
+div
+ div
+//- <div>
+ <div></div>
+ </div>
+
+//- Text
+h1 Hallo Welt
+//- <h1>Hallo Welt</h1>
+
+//- Multizeilentext
+div.
+ Hallo
+ Welt
+//- <div>
+ Hallo
+ Welt
+ </div>
+
+//- ---ATTRIBUTE---
+div(class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled)
+//- <div class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled></div>
+
+//- Kurzhand
+span.meine-klasse
+//- <span class="meine-klasse"></span>
+.meine-klasse
+//- <div class="meine-klasse"></div>
+div#meine-id
+//- <div id="meine-id"></div>
+div#meine-id.meine-klasse
+//- <div class="meine-klasse" id="meine-id"></div>
+
+
+//- ---JS---
+- const sprache = "pug";
+
+//- Multizeilen JS
+-
+ const srache = "pug";
+ const cool = true;
+
+//- JS Klassen
+- const meineKlasse = ['class1', 'class2', 'class3']
+div(class=meineKlasse)
+//- <div class="class1 class2 class3"></div>
+
+//- JS Stil
+- const meineStile = {'color':'white', 'background-color':'blue'}
+div(styles=meineStile)
+//- <div styles="{&quot;color&quot;:&quot;white&quot;,&quot;background-color&quot;:&quot;blue&quot;}"></div>
+
+//- JS Attributte
+- const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"}
+img&attributes(meineAttribute)
+//- <img src="foto.png" alt="meine Bilder">
+- let deaktiviert = false
+input(type="text" disabled=deaktiviert)
+//- <input type="text">
+- deaktiviert = true
+input(type="text" disabled=deaktiviert)
+//- <input type="text" disabled>
+
+//- JS Templating
+- const name = "Bob";
+h1 Hi #{name}
+h1= name
+//- <h1>Hi Bob</h1>
+//- <h1>Bob</h1>
+
+//- ---Schleifen---
+
+//- 'each' und 'for' machen das Selbe. Wir werden nur 'each' verwenden.
+
+each value, i in [1,2,3]
+ p=value
+//-
+ <p>1</p>
+ <p>2</p>
+ <p>3</p>
+
+each value, index in [1,2,3]
+ p=value + '-' + index
+//-
+ <p>1-0</p>
+ <p>2-1</p>
+ <p>3-2</p>
+
+each value in []
+ p=value
+//-
+
+each value in []
+ p=value
+else
+ p Keine Werte sind hier
+
+//- <p>Keine Werte sind hier</p>
+
+//- ---BEDINGUNGEN---
+
+- const zahl = 5
+if zahl < 5
+ p zahl ist kleiner als 5
+else if zahl > 5
+ p zahl ist größer als 5
+else
+ p zahl ist 5
+//- <p>zahl ist 5</p>
+
+- const bestellungsStatus = "Ausstehend";
+case bestellungsStatus
+ when "Ausstehend"
+ p.warn Deine Bestellung steht noch aus
+ when "Abgeschlossen"
+ p.success Bestellung ist abgeschlossen.
+ when -1
+ p.error Ein Fehler ist aufgetreten
+ default
+ p kein Bestellprotokoll gefunden
+//- <p class="warn">Deine Bestellung steht noch aus</p>
+
+//- --INCLUDE--
+//- File path -> "includes/nav.png"
+h1 Firmenname
+nav
+ a(href="index.html") Home
+ a(href="about.html") Über uns
+
+//- Dateipfad -> "index.png"
+html
+ body
+ include includes/nav.pug
+//-
+ <html>
+ <body>
+ <h1>Firmenname</h1>
+ <nav><a href="index.html">Home</a><a href="about.html">Über uns</a></nav>
+ </body>
+ </html>
+
+//- Importiere JS und CSS
+script
+ include scripts/index.js
+style
+ include styles/theme.css
+
+//- ---MIXIN---
+mixin basic()
+ div Hallo
++basic("Bob")
+//- <div>Hallo</div>
+
+mixin comment(name, kommentar)
+ div
+ span.comment-name= name
+ div.comment-text= kommentar
++comment("Bob", "Das ist super")
+//- <div>Hallo</div>
+
+```
+
+
+### Zusätzliche Ressourcen
+- [The Site](https://pugjs.org/)
+- [The Docs](https://pugjs.org/api/getting-started.html)
+- [Github Repo](https://github.com/pugjs/pug)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index e14603cd..8025a8c0 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -1,5 +1,6 @@
---
language: ruby
+filename: ruby-de.rb
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
@@ -11,602 +12,677 @@ contributors:
- ["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"]
+ - ["Jake Faris", "https://github.com/farisj"]
+ - ["Corey Ward", "https://github.com/coreyward"]
+ - ["Jannik Siebert", "https://github.com/janniks"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
- ["Dennis Keller", "https://github.com/denniskeller"]
-filename: ruby-de.rb
+ - ["Paul Götze", "https://gitub.com/paulgoetze"]
lang: de-de
---
-# Dies ist ein Kommentar
+```ruby
+# Das ist ein Kommentar
=begin
-Dies sind multi-line
-Kommentare. Niemand benutzt
-die wirklich.
+Das ist ein mehrzeiliger Kommentar.
+Die Anfangszeile muss mit "=begin" beginnen
+und die Endzeile muss mit "=end" beginnen.
+
+Alternativ kannst du jede Zeile in einem
+mehrzeiligen Kommentar mit dem # Zeichen beginnen.
=end
-# Objekte - Alles ist ein Objekt
+# In Ruby ist (fast) alles ein Objekt.
+# Das schließt Zahlen ein...
+3.class #=> Integer
-## Zahlen sind Objekte
-```
-3.class #=> Fixnum
-3.to_s #=> "3"
-```
+# ...und Zeichenketten (Strings)...
+"Hallo".class #=> String
-### Simple Arithmetik
-```
+# ...und sogar Methoden!
+"Hallo".method(:class).class #=> Method
+
+# Simple Arithmetik
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
-2**5 #=> 32
-```
+2 ** 5 #=> 32
+5 % 3 #=> 2
-// Arithmetik ist aber eigentlich nur syntaktischer Zucker
-// um eine Methode eines Objekt aufzurufen
-```
+# Bitweise Operatoren
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Arithmetik ist aber eigentlich nur syntaktischer Zucker
+# um eine Methode eines Objekts aufzurufen
1.+(3) #=> 4
10.* 5 #=> 50
-```
+100.methods.include?(:/) #=> true
-## Special values sind Objekte
-```
-nil # Nothing to see here
-true # truth
-false # falsehood
+## Spezielle Werte sind Objekte
+nil # Equivalent zu null in anderen Sprachen
+true # Wahrheitswert
+false # Falschheitswert
nil.class #=> NilClass
true.class #=> TrueClass
false.class #=> FalseClass
-```
-## Objektvergleiche
-### Gleicheit
-```
+# Gleicheit
1 == 1 #=> true
2 == 1 #=> false
-```
-### Ungleichheit
-```
+
+# Ungleichheit
1 != 1 #=> false
2 != 1 #=> true
-```
-### Neben false selbst, nil ist ein anderer 'falsey' Wert
-```
-!nil #=> true
-!false #=> true
-!0 #=> false
-```
-### Weitere Vergleiche
-```
+
+# Neben false selbst, ist nil der einzige andere
+# zu Falsch evaluierende Wert
+
+!!nil #=> false
+!!false #=> false
+!!0 #=> true
+!!"" #=> true
+
+# Weitere Vergleiche
1 < 10 #=> true
1 > 10 #=> false
2 <= 2 #=> true
2 >= 2 #=> true
-```
+
+# Kombinierter Vergleichsoperator (gibt `1` zurück wenn das erste Argument
+# größer ist, und `-1`, wenn das zweite Argument größer ist, sonst `0`)
+1 <=> 10 #=> -1 (1 < 10)
+10 <=> 1 #=> 1 (10 > 1)
+1 <=> 1 #=> 0 (1 == 1)
+
### Logische Operatoren
-```
true && false #=> false
true || false #=> true
-!true #=> false
-```
-Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
-Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um
-verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
-liefert.
+# Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
+# Wertigkeit. Diese werden meistens zur Flusskontrolle eingesetzt, um
+# verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
+# liefert.
-#### and
-##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
+# `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
do_something() and do_something_else()
-
-#### or
-#####`log_error` wird nur ausgewertet wenn `do_something` false ist.
+# `log_error` wird nur ausgewertet wenn `do_something` false ist.
do_something() or log_error()
-## Strings sind Objekte
-```
-'I am a string'.class #=> String
-"I am a string too".class #=> String
+# String Interpolation
+placeholder = 'Ruby'
+"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungszeichen füllen."
+#=> "Ich kann in Ruby Platzhalter mit doppelten Anführungszeichen füllen."
-platzhalter = 'Ruby'
-"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen."
-```
-Einfache Anführungszeichen sollten bevorzugt werden.
-Doppelte Anführungszeichen führen interne Berechnungen durch.
+# Du kannst Strings mit `+` verbinden, nicht jedoch mit anderen Typen
+'hallo ' + 'Welt' #=> "hallo Welt"
+'Hallo ' + 3 #=> TypeError: no implicit conversion of Integer into String
+'hallo ' + 3.to_s #=> "hallo 3"
+"hallo #{3}" #=> "hallo 3"
+
+# ...oder Strings mit Operatoren kombinieren
+'hallo ' * 3 #=> "hallo hallo hallo "
+
+# ...oder Strings an andere Strings anhängen
+'hallo' << ' Welt' #=> "hallo Welt"
+
+# Du kannst Text mit einer neuen Zeile am Ende ausgeben
+puts "Ich gebe Text aus!"
+#=> Ich gebe Text aus!
+#=> nil
+
+# ...oder Text ohne einen Zeilenumbruch ausgeben
+print "Ich gebe Text aus!"
+#=> "Ich gebe Text aus!" => nil
-### Strings können verbunden werden, aber nicht mit Zahlen
-```
-'hello ' + 'world' #=> "hello world"
-'hello ' + 3 #=> TypeError: can't convert Fixnum into String
-```
-#### Zahl muss in String konvertiert werden
-```
-'hello ' + 3.to_s #=> "hello 3"
-```
-### Text ausgeben
-```
-puts "I'm printing!"
-```
# Variablen
-## Zuweisungen
-### Diese Zuweisung gibt den zugeordneten Wert zurück
-```
x = 25 #=> 25
x #=> 25
-```
-### Damit funktionieren auch mehrfache Zuweisungen
-```
+
+# Beachte, dass Zuweisungen den zugewiesenen Wert zurückgeben.
+# D.h. du kannst mehrfache Zuweisungen machen.
+
x = y = 10 #=> 10
x #=> 10
y #=> 10
-```
-## Benennung
-### Konvention ist snake_case
-```
+
+# Nutze snake_case für Variablennamen.
snake_case = true
-```
-### Benutze verständliche Variablennamen
-```
-path_to_project_root = '/good/name/'
-path = '/bad/name/'
-```
-# Symbols (sind auch Objekte)
-Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
-als integer repräsentiert werden. Sie werden häufig anstelle von Strings
-verwendet, um sinnvoll Werte zu übermitteln.
-Symbols werden mit dem Doppelpunkt gekennzeichnet.
-```
+# Nutze verständliche Variablennamen.
+path_to_project_root = '/guter/Name/'
+m = '/schlechter/Name/'
+
+
+# Symbole sind unveränderliche, wiederverwendbare Konstanten, welche intern
+# als Integer repräsentiert werden. Sie werden häufig anstelle von Strings
+# verwendet, um semantisch sinnvoll Werte zu übermitteln.
+# Symbols werden mit dem Doppelpunkt gekennzeichnet.
+
:pending.class #=> Symbol
+
status = :pending
+
status == :pending #=> true
+
status == 'pending' #=> false
+
status == :approved #=> false
-```
+
+# Strings können in Symbole konvertiert werden und umgekehrt.
+status.to_s #=> "pending"
+"argon".to_sym #=> :argon
+
# Arrays
-## Ein Array anlegen
-```
+# Das ist ein Array.
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
-```
-## Array können verschiedene Typen beinhalten
-```
+# Array können verschiedene Typen beinhalten
[1, 'hello', false] #=> [1, "hello", false]
-```
-## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf
-## [0] eigentlich die Methode [] des Array Objekts aufgerufen.
-```
-array.[] 0 #=> 1
-array.[] 12 #=> nil
-```
+## Arrays könnenindiziert werden.
-## Arrays können von vorne indiziert werden
-```
+# Von vorne...
array[0] #=> 1
+array.first #=> 1
array[12] #=> nil
-```
-## Arrays können von hinten indiziert werden
-```
+# ...oder von hinten...
array[-1] #=> 5
-```
+array.last #=> 5
-## Arrays können mit Start Index und Länge indiziert werden
-```
+# ...oder mit einem Startindex und einer Länge...
array[2, 3] #=> [3, 4, 5]
-```
-## Arrays können mit einer Range indiziert werden
-```
+# ...oder mit einem Range...
array[1..3] #=> [2, 3, 4]
-```
-## Einen Wert hinzufügen
-```
+# Du kanns ein Array umkehren.
+# Gib ein neues Array mit umgkehrten Werten zurück
+[1,2,3].reverse #=> [3,2,1]
+
+# Kehre ein Array an Ort und Stelle um, um die Variable mit den
+# umgekehrten Werten zu aktualisieren.
+a = [1,2,3]
+a.reverse! #=> a==[3,2,1] wegen des Aufrufs von reverse mit Ausrufezeichens ('!')
+
+# Wie bei der Arithmetik, ist Zugriff mit [index] nur
+# syntaktischer Zucker für den Aufruf der `[]` Methode auf dem Objekt.
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Du kannst Werte zu einem Array hinzufügen...
array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Oder so
array.push(6) #=> [1, 2, 3, 4, 5, 6]
-```
-## Testen, ob ein Element schon vorhanden ist
-```
+# ...und testen ob ein Element schon vorhanden ist
array.include?(1) #=> true
-```
-# Hashes
-Hashes sind das Hauptfeature um Key/Values zu speichern
+# Hashes sind Rubys Hauptdatenstruktur for Schlüssel/Wert Paare.
+# Hashes werden durch geschweifte Klammern gekennzeichnet.
+hash = { 'Farbe' => 'grün', 'Nummer' => 5 }
-## Ein Hash anlegen
-```
-hash = { 'color' => 'green', 'number' => 5 }
-hash.keys #=> ['color', 'number']
-```
+hash.keys #=> ['farbe', 'nummer']
-## Wert per key herausfinden
-```
-hash['color'] #=> 'green'
-hash['number'] #=> 5
-hash['nothing here'] #=> nil
-// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
-```
+# Hashes can be quickly looked up by key.
+hash['Farbe'] #=> "grün"
+hash['Nummer'] #=> 5
-## Symbols können auch keys sein
-```
-new_hash = { defcon: 3, action: true }
-new_hash.keys #=> [:defcon, :action]
-```
+# Abfragen eines nicht vorhandenen Schlüssels, gibt nil zurück.
+hash['nicht vorhanden'] #=> nil
-## Testen ob ein Key oder ein Value existiert
-```
-new_hash.has_key?(:defcon) #=> true
-new_hash.has_value?(3) #=> true
-```
+# Wenn du Symbole als Schlüssel in einem Hash verwendest, kannst du
+# eine alternative Syntax verwenden.
+hash = { :defcon => 3, :action => true }
+hash.keys #=> [:defcon, :action]
-### Tipp: Arrays und Hashes sind Enumerable
-### Und haben gemeinsame, hilfreiche Methoden wie:
-### each, map, count, and more
+hash = { defcon: 3, action: true }
+hash.keys #=> [:defcon, :action]
+
+# Testen ob ein Schlüssel oder Wert im Hash existiert
+hash.key?(:defcon) #=> true
+hash.value?(3) #=> true
+
+# Tipp: Arrays und Hashes sind Enumerables!
+# Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere.
# Kontrolstrukturen
-## if
-```
+
+# Bedingungen
if true
- 'if statement'
+ 'wenn Bedingung'
elsif false
- 'else if, optional'
+ 'sonst wenn, optional'
else
- 'else, also optional'
+ 'sonst, auch optional'
end
-```
-## for - Allerdings werden for Schleifen nicht oft vewendet.
-```
-for counter in 1..5
- puts "iteration #{counter}"
-end
-```
-## Stattdessen: "each" Methode und einen Bloch übergeben
-Ein Block ist ein Codeteil, den man einer Methode übergeben kann
-Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
-Programmiersprachen.
-```
+# Wenn eine Kontrollstruktur keinen Code-Block, sondern einen einzigen
+# Ausdruck ausführt, dann kannst du die nachgestellte if-Notation verwenden
+warnings = ['Nachname fehlt', 'Adresse zu kurz']
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) if !warnings.empty?
+
+# Formuliere die Bedingung um, wenn sich `unless` besser liest als `if`
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) unless warnings.empty?
+
+# Schleifen
+# Traditionell ist das Benutzen von `for` Schleifen in Ruby eher unüblich.
+# Stattdessen werden diese mit Hilfe von Enumerables implementiert, was mit
+# dem Aufrufen von `each` einhergeht.
(1..5).each do |counter|
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
+end
+
+# Was in etwa das selbe ist wie Folgendes (selten in Ruby zu sehen).
+for counter in 1..5
+ puts "Iteration #{counter}"
end
-```
-Die each Methode einer Range führt den Block für jedes Element der Range aus.
+# Das `do |variable| ... end` Konstrukt wird `block` genannt.
+# Blocks sind vergleichbar mit Lambdas, anonymen Funktionen
+# oder Closures in anderen Programmiersprachen.
+# Sie können als Objekte übergeben, aufgerufen oder als Methoden
+# zugewiesen werden.
-Dem Block wird ein "counter" parameter übergeben.
+# Die `each` Methode eines Ranges führt den Block einmal für jedes
+# Element des Ranges aus.
+# Dem Block wird eine counter Variable als Parameter übergeben.
-### Den Block kann man auch in geschweiften Klammern schreiben
-```
-(1..5).each { |counter| puts "iteration #{counter}" }
-```
+# Du kannst einen Block auch mit geschweiften Klammern schreiben.
+(1..5).each { |counter| puts "Iteration #{counter}" }
-### Each kann auch über den Inhalt von Datenstrukturen iterieren
-```
+# Each kann auch über den Inhalt von Datenstrukturen iterieren.
array.each do |element|
- puts "#{element} is part of the array"
+ puts "#{element} is Teil des Arrays"
end
+
hash.each do |key, value|
- puts "#{key} is #{value}"
+ puts "#{key} ist #{value}"
+end
+
+# Um auf den Laufindex zuzugreifen kannst du `each_with_index` verwenden
+# und eine index Variable definieren.
+array.each_with_index do |element, index|
+ puts "#{element} ist Nummer #{index} im Array"
end
counter = 1
while counter <= 5 do
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
counter += 1
end
-```
+#=> Iteration 1
+#=> Iteration 2
+#=> Iteration 3
+#=> Iteration 4
+#=> Iteration 5
+
+# Es gibt einige andere hilfreiche Schleifenfunktionen in Ruby.
+# Wie etwa 'map', 'reduce', 'inject' und viele andere mehr.
+# Map zum Beispiel iteriert über das Array, führt für jedes Element
+# die Anweisungen aus,
+# die im Block definiert sind und gibt ein völlig neues Array zurück.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
-## case
-```
+# Case Konstruct
grade = 'B'
case grade
when 'A'
- puts 'Way to go kiddo'
+ puts 'So wird’s gemacht'
when 'B'
- puts 'Better luck next time'
+ puts 'Viel Glück beim nächsten Mal'
when 'C'
- puts 'You can do better'
+ puts 'Das kannst du besser'
when 'D'
- puts 'Scraping through'
+ puts 'Gerade so durch'
when 'F'
- puts 'You failed!'
+ puts 'Durchgefallen!'
else
- puts 'Alternative grading system, eh?'
+ puts 'Anderes Bewertungssystem, was?'
end
-=> "Better luck next time"
-```
+#=> "Viel Glück beim nächsten Mal"
-### Case können auch ranges
-```
+# Case kann auch Ranges benutzen
grade = 82
case grade
when 90..100
- puts 'Hooray!'
+ puts 'Hurra!'
when 80...90
- puts 'OK job'
+ puts 'OK gemacht'
else
- puts 'You failed!'
+ puts 'Durchgefallen!'
end
-=> "OK job"
-```
+#=> "OK gemacht"
-# Exception handling:
-```
+# Fehlerbehandlung
begin
- # code here that might raise an exception
- raise NoMemoryError, 'You ran out of memory.'
+ # Code der einen Fehler wirft...
+ raise NoMemoryError, 'Dein Speicher ist voll.'
rescue NoMemoryError => exception_variable
- puts 'NoMemoryError was raised', exception_variable
+ puts 'NoMemoryError ist aufgetreten', exception_variable
rescue RuntimeError => other_exception_variable
- puts 'RuntimeError was raised now'
+ puts 'RuntimeError ist aufgetreten'
else
- puts 'This runs if no exceptions were thrown at all'
+ puts 'Das wird ausgeführt, wenn keine Fehler geworfen wurden'
ensure
- puts 'This code always runs no matter what'
+ puts 'Dieser Code wird immer ausgeführt, egal was vorher passiert'
end
-```
-# Funktionen
-```
+
+# Methoden
+
def double(x)
x * 2
end
-```
-## Funktionen (und Blocks)
-## geben implizit den Wert des letzten Statements zurück
-```
+
+# Methoden (und Blocks) geben implizit den Wert des letzten Anweisung zurück.
double(2) #=> 4
-```
-### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
-```
+# Klammern sind optional wenn die Anweisung dadurch nicht mehrdeutig wird.
double 3 #=> 6
+
double double 3 #=> 12
+
def sum(x, y)
x + y
end
-```
-### Methoden Parameter werden per Komma getrennt
-```
+# Die Argumente einer Methode werden durch ein Komma getrennt.
sum 3, 4 #=> 7
+
sum sum(3, 4), 5 #=> 12
-```
-## yield
-### Alle Methoden haben einen impliziten, optionalen block Parameter
-### Dieser wird mit dem Schlüsselword "yield" aufgerufen
-```
+# yield
+# Alle Methoden haben implizit einen optionalen block Parameter.
+# Dieser kann durch das Schlüsselwort 'yield' ausgeführt werden.
def surround
puts '{'
yield
puts '}'
end
-surround { puts 'hello world' }
-```
-## Einen Block kann man auch einer Methoden übergeben
-### "&" kennzeichnet die Referenz zum übergebenen Block
-```
+surround { puts 'hallo Welt' }
+
+#=> {
+#=> hallo Welt
+#=> }
+
+# Blocks können in ein 'Proc' Objekt umgewandelt werden.
+# Dieses ist eine Art Container um den Block und erlaubt ihn an eine
+# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht
+# einzubinden oder ihn andersweitig zu verändern.
+# Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form
+# eines letzten '&block' Parameters, der den Block – wenn es einen gibt –
+# entgegen nimmt und ihn in ein 'Proc' umwandelt. Die Benennung '&block' ist
+# hier nur eine Konvention; es würde genauso mit '&pineapple' funktionieren.
def guests(&block)
- block.call 'some_argument'
+ block.class #=> Proc
+ block.call(4)
end
-```
-### Eine Liste von Parametern kann man auch übergeben,
-### Diese wird in ein Array konvertiert
-### "*" kennzeichnet dies.
-```
+# Die 'call' Methode eines Proc ist ganz ähnlich zum Aufruf von 'yield', wenn
+# ein Block vorhanden ist. Die Argumente, die 'call' übergeben werden, werden
+# als Argumente and den Block weitergereicht.
+
+guests { |n| "Du hast #{n} Gäste." }
+# => "Du hast 4 Gäste."
+
+# Du kannst eine Liste von Argumenten übergeben, die dann in ein Array
+# umgewandelt werden. Dafür gibt es den splat-Operator (`*`).
def guests(*array)
array.each { |guest| puts guest }
end
-```
+
+# Destrukturierung
+
+# Ruby destrukturiert Arrays automatisch beim Zuweisen mehrerer Variablen.
+a, b, c = [1, 2, 3]
+a #=> 1
+b #=> 2
+c #=> 3
+
+# In manchen Fällen will man den splat-Operator (`*`) verwenden um ein Array in
+# eine Liste zu destrukturieren.
+ranked_competitors = ["John", "Sally", "Dingus", "Moe", "Marcy"]
+
+def best(first, second, third)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+end
+
+best *ranked_competitors.first(3) #=> Gewinner sind John, Sally and Dingus.
+
+# Der splat-Operator kann auch in Parametern verwendet werden.
+def best(first, second, third, *others)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+ puts "Es gab #{others.count} andere Teilnehmer."
+end
+
+best *ranked_competitors
+#=> Gewinner sind John, Sally und Dingus.
+#=> Es gab 2 andere Teilnehmer.
+
+# Per Konvention enden alle Methoden, die einen Wahrheitswert zurück geben, mit einem
+# Fragezeichen.
+5.even? #=> false
+5.odd? #=> true
+
+# Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode
+# per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu
+# verändern.
+# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und
+# eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt.
+company_name = "Dunder Mifflin"
+company_name.upcase #=> "DUNDER MIFFLIN"
+company_name #=> "Dunder Mifflin"
+# Diesmal verändern wir company_name direkt.
+company_name.upcase! #=> "DUNDER MIFFLIN"
+company_name #=> "DUNDER MIFFLIN"
+
# Klassen
-## Werden mit dem class Schlüsselwort definiert
-```
+
+# Du kannst eine Klasse mit dem Schlüsselwort 'class' definieren.
class Human
-```
-### Konstruktor bzw. Initializer
-```
+ # Eine Klassenvariable. Sie wird von allen Instanzen einer Klasse geteilt.
+ @@species = 'H. sapiens'
+
+ # Konstruktor bzw. Initializer
def initialize(name, age = 0)
- # Assign the argument to the "name" instance variable for the instance
+ # Weise das Argument der Instanzvariable 'name' zu.
@name = name
- # If no age given, we will fall back to the default in the arguments list.
+ # Wenn kein 'age' angegeben wurde wird der Standartwert aus der Argumentenlist verwendet.
@age = age
end
-```
-### setter Methode
-```
+ # Setter Methode
def name=(name)
@name = name
end
-```
-### getter Methode
-```
+
+ # Getter Methode
def name
@name
end
-```
-#### getter können mit der attr_accessor Methode vereinfacht definiert werden
-```
+ # Getter & Setter können auch kürzer mit der attr_accessor Methode erstellt werden.
attr_accessor :name
- # Getter/setter methods can also be created individually like this
+
+ # Getter & Setter Methoden können auch einzeln erstellt werden.
attr_reader :name
attr_writer :name
- # A class method uses self to distinguish from instance methods.
- # It can only be called on the class, not an instance.
+
+ # Eine Klassenmethode unterscheidet sich durch ein 'self' von einer
+ # Instanzmethode.
+ # Sie kann nur auf der Klasse und nicht auf einer Instanz der Klasse
+ # aufgerufen werden.
def self.say(msg)
puts msg
end
+
def species
@@species
end
end
-```
-## Eine Klasse instanziieren
-```
+# Instanziieren einer Klasse
jim = Human.new('Jim Halpert')
dwight = Human.new('Dwight K. Schrute')
-```
-## Methodenaufrufe
-```
+# Du kannst die Methoden des erstellten Objekts aufrufen.
jim.species #=> "H. sapiens"
jim.name #=> "Jim Halpert"
jim.name = "Jim Halpert II" #=> "Jim Halpert II"
jim.name #=> "Jim Halpert II"
dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
-```
-## Eine Klassenmethode aufrufen
-```
+# Aufrufen einer Klassenmethode
Human.say('Hi') #=> "Hi"
-```
-## Variable Gültigkeit
-### Variablen die mit "$" starten, gelten global
-```
-$var = "I'm a global var"
+# Der Gültigkeitsbereich einer Variablen wird durch ihren Namen definiert.
+# Variablen, die mit $ beginnen sind global gültig.
+$var = "Ich bin eine globale Variable"
defined? $var #=> "global-variable"
-```
-### Variablen die mit "@" starten, gelten für die Instanz
-```
-@var = "I'm an instance var"
+# Variablen, die mit @ beginnen, sind innerhalb einer Instanz gültig.
+@var = "Ich bin eine Instanzvariable"
defined? @var #=> "instance-variable"
-```
-### Variablen die mit "@@" starten, gelten für die Klasse
-```
-@@var = "I'm a class var"
+# Variablen, die mit @@ beginnen, sind für die Klasse gültig.
+@@var = "Ich bin eine Klassenvariable"
defined? @@var #=> "class variable"
-```
-### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten
-```
-Var = "I'm a constant"
+# Variablen, die mit einem Großbuchstaben beginnen, sind Konstanten
+Var = "Ich bin eine Konstante"
defined? Var #=> "constant"
-```
-## Class ist auch ein Objekt
-### Hat also auch Instanzvariablen
-### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt.
+# Class ist in Ruby auch ein Objekt. Deshalb kann eine Klasse Instanzvariablen
+# haben. Eine Klassenvariable wird zwischen der Klasse und all ihren
+# Ableitungen geteilt.
-### Basis Klasse
-```
+# Basis Klasse
class Human
@@foo = 0
+
def self.foo
@@foo
end
+
def self.foo=(value)
@@foo = value
end
end
-```
-### Abgeleitete Klasse
-```
+# Abgeleitete Klasse
class Worker < Human
end
-Human.foo # 0
-Worker.foo # 0
-Human.foo = 2 # 2
-Worker.foo # 2
-```
-### Eine Klasseninstanzvariable wird nicht geteilt
-```
+Human.foo #=> 0
+Worker.foo #=> 0
+
+Human.foo = 2
+Worker.foo #=> 2
+
+# Ableitungen einer Klasse haben keinen Zugriff auf eine Eine Klassen-Instanzvariable.
class Human
@bar = 0
+
def self.bar
@bar
end
+
def self.bar=(value)
@bar = value
end
end
-```
-```
+
class Doctor < Human
end
-```
-```
-Human.bar # 0
-Doctor.bar # nil
-```
-```
+
+Human.bar #=> 0
+Doctor.bar #=> nil
+
module ModuleExample
def foo
'foo'
end
end
-```
-### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden
-### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden
-```
+
+# Ein Einbinden (include) eines Moduls bindet seine Methoden an die Instanzen
+# der Klasse.
+# Ein Erweitern (extend) eines Moduls bindet seine Methoden an die Klasse
+# selbst.
class Person
include ModuleExample
end
-```
-```
+
class Book
extend ModuleExample
end
-```
-```
-Person.foo # => NoMethodError: undefined method `foo' for Person:Class
-Person.new.foo # => 'foo'
-Book.foo # => 'foo'
-Book.new.foo # => NoMethodError: undefined method `foo'
-```
-### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird
-```
- module ConcernExample
- def self.included(base)
- base.extend(ClassMethods)
- base.send(:include, InstanceMethods)
- end
- module ClassMethods
- def bar
- 'bar'
- end
- end
- module InstanceMethods
- def qux
- 'qux'
- end
+
+Person.foo #=> NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo #=> "foo"
+Book.foo #=> "foo"
+Book.new.foo #=> NoMethodError: undefined method `foo'
+
+
+# Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird.
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
end
end
- class Something
- include ConcernExample
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
end
-```
-```
-Something.bar # => 'bar'
-Something.qux # => NoMethodError: undefined method `qux'
-Something.new.bar # => NoMethodError: undefined method `bar'
-Something.new.qux # => 'qux'
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar #=> "bar"
+Something.qux #=> NoMethodError: undefined method `qux'
+Something.new.bar #=> NoMethodError: undefined method `bar'
+Something.new.qux #=> "qux"
```
-## Weiterführende Hinweise
+## Weitere Links
-//EN
+_(z.T. auf Englisch)_
-- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
-- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Offizielle Ruby Website](https://www.ruby-lang.org/de/)
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Eine Variante dieses Dokuments mit in-Browser Challenges.
+- [RubyMonk](https://rubymonk.com/) - Lerne Ruby mit einer Reihe interaktiver Tutorials.
+- [Offizielle Dokumentation](http://ruby-doc.org/core)
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
-- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
-- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide.
+- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown
new file mode 100644
index 00000000..679a5488
--- /dev/null
+++ b/el-gr/vim-gr.html.markdown
@@ -0,0 +1,267 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+filename: LearnVim.txt
+lang: el-gr
+---
+
+
+[Vim](http://www.vim.org)
+To (Vi IMproved) είναι ένας κλώνος του δημοφιλούς vi editor για Unix.
+Είναι ένας text editor σχεδιασμένος για ταχύτητα και αυξημένη παραγωγικότητα,
+και υπάρχει σχεδόν σε όλα τα Unix-based συστήματα. Έχει διάφορα keybindings
+(συντομεύσεις πλήκτρων) για να πλοηγούμαστε γρήγορα σε συγκεκριμένα σημεία ενός αρχείου,
+καθώς και για γρήγορη επεξεργασία.
+
+## Τα βασικά της πλοήγησης στον Vim
+
+```
+ vim <filename> # Άνοιξε το <filename> στον vim
+ :help <topic> # Άνοιξε το built-in βοήθημα για το <topic> αν υπάρχει
+ :q # Βγες από τον vim
+ :w # Αποθήκευσε το τρέχον αρχείο
+ :wq # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ ZZ # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ :q! # Βγες χωρίς αποθήκευση
+ # ! *αναγκάζει* το :q να εκτελεστεί, γι αυτό βγαίνει χωρίς saving
+ :x # Ίδιο με το wq αλλά πιο σύντομο
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # Μετακινήσου κατά ένα χαρακτήρα αριστερά
+ j # Μετακινήσου μια γραμμή κάτω
+ k # Μετακινήσου μια γραμμή πάνω
+ l # Μετακινήσου μια γραμμή δεξιά
+
+ Ctrl+B # Πήγαινε μία οθόνη πίσω
+ Ctrl+F # Πήγαινε μία οθόνη μπροστά
+ Ctrl+U # Πήγαινε μισή οθόνη πίσω
+ Ctrl+D # Πήγαινε μισή οθόνη μπροστά
+
+ # Μετακινήσεις στην ίδια γραμμή
+
+ 0 # Πήγαινε στην αρχή της γραμμής
+ $ # Πήγαινε στο τέλος της γραμμής
+ ^ # Πήγαινε στον πρώτο μη κενό χαρακτήρα της γραμμής
+
+ # Αναζήτηση στο κείμενο
+
+ /word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης μετά τον cursor
+ ?word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης πριν τον cursor
+ n # Μετακινεί τον cursor στην επόμενη εμφάνιση της λέξης
+ N # Μετακινεί τον cursor στην προηγούμενη εμφάνιση της λέξης
+
+ :%s/foo/bar/g # άλλαξε το 'foo' σε 'bar' σε κάθε γραμμή του αρχείου
+ :s/foo/bar/g # άλλαξε το 'foo' σε 'bar' στην τρέχουσα γραμμή
+
+ # Άλματα σε χαρακτήρες
+
+ f<character> # Άλμα μπροστά και προσγείωση στο επόμενο <character>
+ t<character> # Άλμα μπροστά και προσγείωση αμέσως πριν το προηγούμενο <character>
+
+ # Για παράδειγμα,
+ f< # Άλμα μπροστά και προσγείωση σε <
+ t< # Άλμα μπροστά και προσγείωση αμέσως πριν <
+
+ # Μετακινήσεις κατά λέξεις
+
+ w # Πήγαινε μια λέξη μπροστά
+ b # Πήγαινε μια λέξη πίσω
+ e # Πήγαινε στο τέλος της λέξης στην οποία είσαι
+
+ # Άλλοι χαρακτήρες για να τριγυρνάμε
+
+ gg # Πήγαινε στην αρχή του αρχείου
+ G # Πήγαινε στο τέλος του αρχείου
+ :NUM # Πήγαινε στη γραμμή με αριθμό NUM (οποιοσδήποτε αριθμός)
+ H # Πήγαινε στην κορυφή της σελίδας
+ M # Πήγαινε στην μέση της σελίδας
+ L # Πήγαινε στο κάτω άκρο της σελίδας
+```
+
+## Help docs:
+Το Vim έχει built-in help documentation που μπορείς να δεις με `:help <topic>`.
+Για παράδειγμα το `:help navigation` θα σου εμφανίσει documentation σχετικό με
+το πως να πλοηγείσαι στο αρχείο!
+
+To `:help` μπορεί να χρησιμοποιηθεί και χωρίς option. Αυτό θα εμφανίσει το default
+help dialog που σκοπεύει να κάνει το vim πιο προσιτό σε αρχάριους!
+
+## Modes:
+
+O Vim στηρίζεται στο concept των **modes**.
+
+- Command Mode - ο vim εκκινεί σε αυτό mode, χρησιμοποιείται για πλοήγηση και εντολές
+- Insert Mode - χρησιμοποιείται για να κάνουμε αλλαγές στα αρχεία
+- Visual Mode - χρησιμοποιείται για να υπογραμμίζουμε κείμενα και να κάνουμε διάφορα σε αυτά
+- Ex Mode - χρησιμοποιείται για να πάμε στο κάτω μέρος με το ':' που δίνουμε εντολές
+
+```
+ i # Βάζει το vim σε insert mode, πριν τη θέση cursor
+ a # Βάζει το vim σε insert mode, μετά τη θέση cursor
+ v # βάζει τον vim σε visual mode
+ : # Βάζει τον vim σε ex mode
+ <esc> # φεύγει από όποιο mode είμαστε και πάει σε command mode
+
+ # Αντιγραφή-Επικόληση κειμένου
+
+ y # Yank (κάνε copy) ό,τι είναι επιλεγμένο
+ yy # Yank την γραμμή στην οποία είσαι
+ d # διάγραψε ό,τι είναι επιλεγμένο
+ dd # Διάγραψε τη γραμμή στην οποία είσαι
+ p # Κάνε Paste το αντεγραμένο κείμενο μετά την θέση του cursor
+ P # Κάνε Paste το αντεγραμένο κείμενο πριν την θέση του cursor
+ x # Διάγραψε τον χαρακτήρα που είναι κάτω από τον cursor
+```
+
+## Η 'γραμματική' του Vim
+
+Μπορείς να σκεφτείς τον Vim ως ένα σύνολο εντολών
+σε μορφή 'Verb-Modifier-Noun', όπου
+
+- Verb - η ενέργεια που θες να κάνεις
+- Modifier - πώς κάνεις την ενέργεια
+- Noun - το αντικείμενο που δέχεται την ενέργεια
+
+Μερικά παραδείγματα ''Ρημάτων', 'Modifiers' και 'Ουσιαστικών':
+
+```
+ # 'Ρήματα'
+
+ d # Διάγραψε
+ c # Άλλαξε
+ y # Yank (αντίγραψε)
+ v # Επίλεξε οπτικά
+
+ # 'Modifiers'
+
+ i # Μέσα
+ a # Γύρω
+ NUM # Αριθμός (NUM = οποιοσδήποτε αριθμός)
+ f # Ψάξε κάτι και πήγαινε εκεί που βρίσκεται
+ t # Ψάξε κάτι και πήγαινε πριν από εκεί που βρίσκεται
+ / # Βρες κάποιο string μετά από τον cursor
+ ? # Βρες κάποιο string πριν τον cursor
+
+ # 'Ουσιαστικά'
+
+ w # Λέξη
+ s # Πρόταση
+ p # Παράγραφος
+ b # Block
+
+ # Δείγματα 'προτάσεων' ή εντολών
+
+ d2w # Διάγραψε 2 λέξεις
+ cis # Άλλαξε μέσα στην πρώταση
+ yip # Αντίγραψε την παράγραφο στην οποία βρίσκεσαι
+ ct< # Άλλαξε σε <
+ # Άλλαξε το κείμενο από το οποίο είσαι πριν το επόμενο bracketChange the text from where you are to the next open bracket
+ d$ # Διάγραψε μέχρι το τέλος της γραμμής
+```
+
+## Μερικά shortcuts και κόλπα
+
+ <!--TODO: Βάλτε κι άλλα!-->
+```
+ > # Στοίχισε προς τα δεξιά την επιλογή σου κατά ένα block
+ < # Στοίχισε προς τα αριστερά την επιλογή σου κατά ένα block
+ :earlier 15m # Κάνε το αρχείο όπως ήταν πριν 15 λεπτά
+ :later 15m # Ακύρωση για την παραπάνω εντολή
+ ddp # Αντάλλαξε τις θέσεις διαδοχικών γραμμών
+ . # Επανάλαβε την προηγούμενη ενέργεια
+ :w !sudo tee % # Σώσε το τρέχον αρχείο ως root
+ :set syntax=c # Κάνε syntax highlighting για τη γλώσσα c
+ :sort # Ταξινόμησε όλες τις γραμμές
+ :sort! # Ταξινόμησε ανάποδα όλες τις γραμμές (αύξουσα σειρά)
+ :sort u # Ταξινόμησε όλες τις γραμμές και διάγραψε τις διπλές γραμμές
+ ~ # Άλλαξε τα κεφαλαία σε μικρά στο επιλεγμένο κείμενο
+ u # Το επιλεγμένο κείμενο να γίνει πεζά γράμματα
+ U # Το επιλεγμένο κείμενο να γίνει κεφαλαία γράμματα
+
+ # Fold text
+ zf # Διπλώνει (συμπιέζει τις γραμμές σε μία) το επιλεγμένο κείμενο
+ zo # Ξεδιπλώνει το επιλεγμένο fold
+ zc # Κλείνει το επιλεγμένο fold
+ zR # Ανοίγει όλα τα folds
+ zM # Κλείνει όλα τα folds
+```
+
+## Macros
+
+Τα macros βασικά είναι καταγραφή ενεργειών.
+Όταν ξεικάς να καταγράφεις ένα macro καταγράφονται **όλες** οι ενέργεις και οι
+εντολές που χρησιμοποιείς, μέχρι να σταματήσεις την καταγραφή. Όταν καλείς ένα macro,
+εκτελείται πάλι η ίδια σειρά από ενέργειες και εντολές στο επιλεγμένο κείμενο.
+
+```
+ qa # Ξεκίνα να καταγράφεις ένα macro που θα ονομαστεί 'a'
+ q # Σταμάτα την καταγραφή
+ @a # Τρέξε το macro
+```
+
+### Configuring ~/.vimrc
+
+Το αρχείο .vimrc μπορεί να χρησιμοποιηθεί για να κάνεις configure το Vim στο startup.
+
+Εδώ βλέπουμε δείγμα ενός ~/.vimrc file:
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" Determines filetype from name to allow intelligent auto-indenting, etc.
+filetype indent plugin on
+
+" Enable syntax highlighting
+syntax on
+
+" Better command-line completion
+set wildmenu
+
+" Use case insensitive search except when using capital letters
+set ignorecase
+set smartcase
+
+" When opening a new line and no file-specific indenting is enabled,
+" keep same indent as the line you're currently on
+set autoindent
+
+" Display line numbers on the left
+set number
+
+" Indentation options, change according to personal preference
+
+" Number of visual spaces per TAB
+set tabstop=4
+
+" Number of spaces in TAB when editing
+set softtabstop=4
+
+" Number of spaces indented when reindent operations (>> and <<) are used
+set shiftwidth=4
+
+" Convert TABs to spaces
+set expandtab
+
+" Enable intelligent tabbing and spacing for indentation and alignment
+set smarttab
+```
+
+### Αναφορές
+
+[Vim | Home](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 0b717ca6..8b80c582 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -439,7 +439,7 @@ self() #=> #PID<0.27.0>
# Create an agent with `Agent.start_link`, passing in a function
# The initial state of the agent will be whatever that function returns
-{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
+{:ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
# `Agent.get` takes an agent name and a `fn` that gets passed the current state
# Whatever that `fn` returns is what you'll get back
@@ -457,3 +457,4 @@ Agent.update(my_agent, fn colors -> ["blue" | colors] end)
* [Elixir Cheat Sheet](https://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
* ["Learn You Some Erlang for Great Good!"](https://learnyousomeerlang.com/) by Fred Hebert
* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong
+* [Introduction to Elixir](https://learn-elixir.com/)
diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown
index 644182ff..76e9b6e6 100644
--- a/es-es/perl-es.html.markdown
+++ b/es-es/perl-es.html.markdown
@@ -11,9 +11,9 @@ translators:
lang: es-es
---
-Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
+Perl es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
-Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
+Perl corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
```perl
# Comentarios de una sola línea con un carácter hash
@@ -31,7 +31,7 @@ Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores cen
my $animal = "camello";
my $respuesta = 42;
-# Los valores escalares pueden ser cadenas de caracteres, números enteros o
+# Los valores escalares pueden ser cadenas de caracteres, números enteros o
# de punto flotante; Perl automáticamente los convertirá como sea requerido
## Arreglos
@@ -52,7 +52,7 @@ my %color_fruta = (
# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata)
-# Los tipos de datos más complejos se pueden construir utilizando
+# Los tipos de datos más complejos se pueden construir utilizando
# referencias, las cuales le permiten construir listas y hashes dentro
# de listas y hashes
@@ -61,7 +61,7 @@ my %color_fruta = (
# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
if ( $var ) {
...;
-} elsif ( $var eq 'bar' ) {
+} elsif ( $var eq 'bar' ) {
...;
} else {
...;
@@ -98,7 +98,7 @@ foreach (@array) {
#### Expresiones regulares
-# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
+# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
# Sin embargo, resumiendo:
@@ -113,7 +113,7 @@ $a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en
#### Archivos y E/S
-# Puede abrir un archivo para obtener datos o escribirlos utilizando la
+# Puede abrir un archivo para obtener datos o escribirlos utilizando la
# función "open()"
open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!";
@@ -122,7 +122,7 @@ open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!";
# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>".
# En contexto escalar, leer una sola línea desde el gestor de archivo, y
-# en contexto de lista, leer el archivo completo en donde asigna
+# en contexto de lista, leer el archivo completo en donde asigna
# cada línea a un elemento de la lista
my $linea = <$entrada>;
diff --git a/es-es/perl6-es.html.markdown b/es-es/raku-es.html.markdown
index bf3ae65e..e916d0fd 100644
--- a/es-es/perl6-es.html.markdown
+++ b/es-es/raku-es.html.markdown
@@ -1,8 +1,8 @@
---
name: perl6
category: language
-language: perl6
-filename: perl6-es.p6
+language: Raku
+filename: learnraku-es.raku
contributors:
- ["vendethiel", "http://github.com/vendethiel"]
- ["Samantha McVey", "https://cry.nu"]
@@ -11,10 +11,10 @@ translators:
lang: es-es
---
-Perl 6 es un lenguaje de programación altamente capaz y con características
+Raku es un lenguaje de programación altamente capaz y con características
abundantes para hacerlo el lenguage ideal por los próximos 100 años.
-El compilador primario de Perl 6 se llama [Rakudo](http://rakudo.org), el cual
+El compilador primario de Raku se llama [Rakudo](http://rakudo.org), el cual
se ejecuta en JVM y en [MoarVM](http://moarvm.com).
Meta-nota: dos signos de números (##) son usados para indicar párrafos,
@@ -26,7 +26,7 @@ mientras que un solo signo de número (#) indica notas.
# Un comentario de una sola línea comienza con un signo de número
#`(
- Comentarios multilíneas usan #` y signos de encerradura tales
+ Comentarios multilíneas usan #` y signos de encerradura tales
como (), [], {}, 「」, etc.
)
```
@@ -34,28 +34,28 @@ mientras que un solo signo de número (#) indica notas.
## Variables
```perl6
-## En Perl 6, se declara una variable lexical usando `my`
+## En Raku, se declara una variable lexical usando `my`
my $variable;
-## Perl 6 tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
+## Raku tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
```
### Escalares
```perl6
-# Un escalar representa un solo valor. Variables escalares comienzan
+# Un escalar representa un solo valor. Variables escalares comienzan
# con un `$`
my $str = 'Cadena';
-# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
+# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
# luego):
my $str2 = "Cadena";
## Los nombres de variables pueden contener pero no terminar con comillas
-## simples y guiones. Sin embargo, pueden contener
+## simples y guiones. Sin embargo, pueden contener
## (y terminar con) guiones bajos (_):
my $nombre'de-variable_ = 5; # Esto funciona!
-my $booleano = True; # `True` y `False` son valores booleanos en Perl 6.
+my $booleano = True; # `True` y `False` son valores booleanos en Raku.
my $inverso = !$booleano; # Puedes invertir un booleano con el operador prefijo `!`
my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
# convierte su operador en un Bool
@@ -70,7 +70,7 @@ my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
my @array = 'a', 'b', 'c';
# equivalente a:
my @letras = <a b c>; # array de palabras, delimitado por espacios.
- # Similar al qw de perl5, o el %w de Ruby.
+ # Similar al qw de perl, o el %w de Ruby.
my @array = 1, 2, 3;
say @array[2]; # Los índices de un array empiezan por el 0 -- Este es
@@ -83,7 +83,7 @@ say "Interpola todos los elementos de un array usando [] : @array[]";
@array[0, 1] = 5, 6; # Asigna varios valores
my @llaves = 0, 2;
-@array[@llaves] = @letras; # Asignación usando un array que contiene valores
+@array[@llaves] = @letras; # Asignación usando un array que contiene valores
# índices
say @array; #=> a 6 b
```
@@ -93,19 +93,19 @@ say @array; #=> a 6 b
```perl6
## Un hash contiene parejas de llaves y valores.
## Puedes construir un objeto Pair usando la sintaxis `LLave => Valor`.
-## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
+## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
## sin ningún orden.
## Ten en cuenta que las llaves son "aplanadas" en contexto de hash, y
## cualquier llave duplicada es deduplicada.
my %hash = 1 => 2,
3 => 4;
-my %hash = foo => "bar", # las llaves reciben sus comillas
+my %hash = foo => "bar", # las llaves reciben sus comillas
# automáticamente.
"some other" => "value", # las comas colgantes estań bien.
;
## Aunque los hashes son almacenados internamente de forma diferente a los
-## arrays, Perl 6 te permite crear un hash usando un array
+## arrays, Raku te permite crear un hash usando un array
## con un número par de elementos fácilmente.
my %hash = <llave1 valor1 llave2 valor2>;
@@ -122,7 +122,7 @@ my %hash = :w(1), # equivalente a `w => 1`
say %hash{'llave1'}; # Puedes usar {} para obtener el valor de una llave
say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
- # (`{llave1}` no funciona, debido a que Perl 6 no tiene
+ # (`{llave1}` no funciona, debido a que Raku no tiene
# palabras desnudas (barewords en inglés))
```
@@ -133,7 +133,7 @@ say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
## creadas con la palabra clave `sub`.
sub di-hola { say "¡Hola, mundo!" }
-## Puedes proveer argumentos (tipados). Si especificado,
+## Puedes proveer argumentos (tipados). Si especificado,
## el tipo será chequeado al tiempo de compilación si es posible.
## De lo contrario, al tiempo de ejecución.
sub di-hola-a(Str $nombre) {
@@ -165,7 +165,7 @@ say return-for; # imprime Nil
## Una subrutina puede tener argumentos opcionales:
sub con-opcional($arg?) { # el signo "?" marca el argumento opcional
- say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
+ say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
un argumento, o returnaré mi argumento";
$arg;
}
@@ -173,7 +173,7 @@ con-opcional; # devuelve Any
con-opcional(); # devuelve Any
con-opcional(1); # devuelve 1
-## También puedes proveer un argumento por defecto para
+## También puedes proveer un argumento por defecto para
## cuando los argumentos no son proveídos:
sub hola-a($nombre = "Mundo") {
say "¡Hola, $nombre!";
@@ -190,10 +190,10 @@ sub con-nombre($arg-normal, :$nombrado) {
}
con-nombre(1, nombrado => 6); #=> 7
## Sin embargo, debes tener algo en cuenta aquí:
-## Si pones comillas alrededor de tu llave, Perl 6 no será capaz de verla
+## Si pones comillas alrededor de tu llave, Raku no será capaz de verla
## al tiempo de compilación, y entonces tendrás un solo objeto Pair como
-## un argumento posicional, lo que significa que el siguiente ejemplo
-## falla:
+## un argumento posicional, lo que significa que el siguiente ejemplo
+## falla:
con-nombre(1, 'nombrado' => 6);
con-nombre(2, :nombrado(5)); #=> 7
@@ -205,7 +205,7 @@ sub con-nombre-mandatorio(:$str!) {
}
con-nombre-mandatorio(str => "Mi texto"); #=> Mi texto!
con-nombre-mandatorio; # error al tiempo de ejecución:
- # "Required named parameter not passed"
+ # "Required named parameter not passed"
# ("Parámetro nombrado requerido no proveído")
con-nombre-mandatorio(3);# error al tiempo de ejecución:
# "Too many positional parameters passed"
@@ -226,7 +226,7 @@ sub nombrado-definido(:$def = 5) {
nombrado-definido; #=> 5
nombrado-definido(def => 15); #=> 15
-## Dado que puedes omitir los paréntesis para invocar una función sin
+## Dado que puedes omitir los paréntesis para invocar una función sin
## argumentos, necesitas usar "&" en el nombre para almacenar la función
## `di-hola` en una variable.
my &s = &di-hola;
@@ -240,8 +240,8 @@ sub muchos($principal, *@resto) { #`*@` (slurpy) consumirá lo restante
say @resto.join(' / ') ~ "!";
}
say muchos('Feliz', 'Cumpleaño', 'Cumpleaño'); #=> Feliz / Cumpleaño!
- # Nota que el asterisco (*) no
- # consumió el parámetro frontal.
+ # Nota que el asterisco (*) no
+ # consumió el parámetro frontal.
## Puedes invocar un función con un array usando el
## operador "aplanador de lista de argumento" `|`
@@ -256,12 +256,12 @@ concat3(|@array); #=> a, b, c
## Contenedores
```perl6
-## En Perl 6, valores son actualmente almacenados en "contenedores".
-## El operador de asignación le pregunta al contenedor en su izquierda
+## En Raku, valores son actualmente almacenados en "contenedores".
+## El operador de asignación le pregunta al contenedor en su izquierda
## almacenar el valor a su derecha. Cuando se pasan alrededor, contenedores
## son marcados como inmutables. Esto significa que, en una función, tu
## tendrás un error si tratas de mutar uno de tus argumentos.
-## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
+## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
## mutable usando `is rw`:
sub mutar($n is rw) {
$n++;
@@ -276,7 +276,7 @@ mutar $m; # ¡$n es ahora 43!
## dado que no contenedor ha sido pasado y números enteros son inmutables
## por naturaleza:
-mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
+mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
# pero recibió un valor Int
## Si en cambio quieres una copia, debes usar `is copy`.
@@ -286,7 +286,7 @@ mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
my $x = 42;
sub x-almacena() is rw { $x }
x-almacena() = 52; # En este caso, los paréntesis son mandatorios
- # (porque de otra forma, Perl 6 piensa que la función
+ # (porque de otra forma, Raku piensa que la función
# `x-almacena` es un identificador).
say $x; #=> 52
```
@@ -297,9 +297,9 @@ say $x; #=> 52
```perl6
## - `if`
## Antes de hablar acerca de `if`, necesitamos saber cuales valores son
-## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
-## (o "Falsy") -- representa False (falso). Solo estos valores son
-## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
+## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
+## (o "Falsy") -- representa False (falso). Solo estos valores son
+## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
## por supuesto False. Todos los valores son Truthy.
if True {
say "¡Es verdadero!";
@@ -316,8 +316,8 @@ unless False {
## También puedes usar sus versiones sufijos seguidas por la palabra clave:
say "Un poco verdadero" if True;
-## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
-## devuelve $valor-si-verdadera si la condición es verdadera y
+## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
+## devuelve $valor-si-verdadera si la condición es verdadera y
## $valor-si-falsa si es falsa.
## my $resultado = $valor condición ?? $valor-si-verdadera !! $valor-si-falsa;
@@ -338,21 +338,21 @@ say $edad > 18 ?? "Eres un adulto" !! "Eres menor de 18";
##
## `given` simplemente pone su argumento en `$_` (como un bloque lo haría),
## y `when` lo compara usando el operador de "coincidencia inteligente" (`~~`).
-##
-## Dado que otras construcciones de Perl 6 usan esta variable (por ejemplo,
+##
+## Dado que otras construcciones de Raku usan esta variable (por ejemplo,
## el bucle `for`, bloques, etc), esto se significa que el poderoso `when` no
-## solo se aplica con un `given`, sino que se puede usar en cualquier
+## solo se aplica con un `given`, sino que se puede usar en cualquier
## lugar donde exista una variable `$_`.
given "foo bar" {
say $_; #=> foo bar
- when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
+ when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
# solo ten presente que `when` la usa.
# Esto es equivalente a `if $_ ~~ /foo/`.
say "¡Yay!";
}
when $_.chars > 50 { # coincidencia inteligente con cualquier cosa True es True,
- # i.e. (`$a ~~ True`)
+ # i.e. (`$a ~~ True`)
# por lo tanto puedes también poner condiciones "normales".
# Este `when` es equivalente a este `if`:
# if $_ ~~ ($_.chars > 50) {...}
@@ -373,12 +373,12 @@ given "foo bar" {
## pero también puede ser un bucle for al estilo de C:
loop {
say "¡Este es un bucle infinito!";
- last; # last interrumpe el bucle, como la palabra clave `break`
+ last; # last interrumpe el bucle, como la palabra clave `break`
# en otros lenguajes.
}
loop (my $i = 0; $i < 5; $i++) {
- next if $i == 3; # `next` salta a la siguiente iteración, al igual
+ next if $i == 3; # `next` salta a la siguiente iteración, al igual
# que `continue` en otros lenguajes. Ten en cuenta que
# también puedes usar la condicionales postfix (sufijas)
# bucles, etc.
@@ -391,29 +391,29 @@ for @array -> $variable {
}
## Como vimos con `given`, la variable de una "iteración actual" por defecto
-## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
+## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
## normalmente lo harías con `given`.
for @array {
say "he conseguido a $_";
.say; # Esto es también permitido.
- # Una invocación con punto (dot call) sin "tópico" (recibidor) es
- # enviada a `$_` por defecto.
+ # Una invocación con punto (dot call) sin "tópico" (recibidor) es
+ # enviada a `$_` por defecto.
$_.say; # lo mismo de arriba, lo cual es equivalente.
}
for @array {
# Puedes...
- next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
+ next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
# lenguages parecido a C)
- redo if $_ == 4; # Re-hacer la iteración, manteniendo la
+ redo if $_ == 4; # Re-hacer la iteración, manteniendo la
# misma variable tópica (`$_`)
- last if $_ == 5; # Salir fuera del bucle (como `break`
+ last if $_ == 5; # Salir fuera del bucle (como `break`
# en lenguages parecido a C)
}
-## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
-## Es solo una manera de expresar un bloque en Perl 6.
+## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
+## Es solo una manera de expresar un bloque en Raku.
if computación-larga() -> $resultado {
say "El resultado es $resultado";
}
@@ -423,7 +423,7 @@ if computación-larga() -> $resultado {
```perl6
## Dados que los lenguajes de la familia Perl son lenguages basados
-## mayormente en operadores, los operadores de Perl 6 son actualmente
+## mayormente en operadores, los operadores de Raku son actualmente
## subrutinas un poco cómicas en las categorías sintácticas. Por ejemplo,
## infix:<+> (adición) o prefix:<!> (bool not).
@@ -455,7 +455,7 @@ if computación-larga() -> $resultado {
(1, 2) eqv (1, 3);
## - Operador de coincidencia inteligente (smart matching): `~~`
-## Asocia (aliasing en inglés) el lado izquierda a la variable $_
+## Asocia (aliasing en inglés) el lado izquierda a la variable $_
## y después evalúa el lado derecho.
## Aquí algunas comparaciones semánticas comunes:
@@ -464,8 +464,8 @@ if computación-larga() -> $resultado {
'Foo' ~~ 'Foo'; # True si las cadenas de texto son iguales.
12.5 ~~ 12.50; # True si los números son iguales.
-## Regex - Para la comparación de una expresión regular en contra
-## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
+## Regex - Para la comparación de una expresión regular en contra
+## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
## como True si el regex coincide con el patrón.
my $obj = 'abc' ~~ /a/;
@@ -475,12 +475,12 @@ say $obj.WHAT; # (Match)
## Hashes
'llave' ~~ %hash; # True si la llave existe en el hash
-## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
+## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
## superclases y roles)
1 ~~ Int; # True (1 es un número entero)
-## Coincidencia inteligente contra un booleano siempre devuelve ese
+## Coincidencia inteligente contra un booleano siempre devuelve ese
## booleano (y lanzará una advertencia).
1 ~~ True; # True
@@ -502,13 +502,13 @@ False ~~ True; # True
## Esto también funciona como un atajo para `0..^N`:
^10; # significa 0..^10
-## Esto también nos permite demostrar que Perl 6 tiene arrays
+## Esto también nos permite demostrar que Raku tiene arrays
## ociosos/infinitos, usando la Whatever Star:
my @array = 1..*; # 1 al Infinito! `1..Inf` es lo mismo.
say @array[^10]; # puedes pasar arrays como subíndices y devolverá
# un array de resultados. Esto imprimirá
# "1 2 3 4 5 6 7 8 9 10" (y no se quedaré sin memoria!)
-## Nota: Al leer una lista infinita, Perl 6 "cosificará" los elementos que
+## Nota: Al leer una lista infinita, Raku "cosificará" los elementos que
## necesita y los mantendrá en la memoria. Ellos no serán calculados más de
## una vez. Tampoco calculará más elementos de los que necesita.
@@ -517,14 +517,14 @@ say @array[^10]; # puedes pasar arrays como subíndices y devolverá
say join(' ', @array[15..*]); #=> 15 16 17 18 19
## lo que es equivalente a:
say join(' ', @array[-> $n { 15..$n }]);
-## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
+## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
## provocará un array infinito (tu programa nunca terminará)
## Puedes usar eso en los lugares que esperaría, como durante la asignación
## a un array
my @números = ^20;
-## Aquí los números son incrementados por "6"; más acerca del
+## Aquí los números son incrementados por "6"; más acerca del
## operador `...` adelante.
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@números[5..*] = 3, 9 ... *; # aunque la secuencia es infinita,
@@ -546,7 +546,7 @@ $a && $b && $c; # Devuelve 0, el primer valor que es False
$b || $a; # 1
## Y porque tu lo querrás, también tienes operadores de asignación
-## compuestos:
+## compuestos:
$a *= 2; # multiplica y asigna. Equivalente a $a = $a * 2;
$b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
@array .= sort; # invoca el método `sort` y asigna el resultado devuelto.
@@ -555,8 +555,8 @@ $b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
## ¡Más sobre subrutinas!
```perl6
-## Como dijimos anteriormente, Perl 6 tiene subrutinas realmente poderosas.
-## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
+## Como dijimos anteriormente, Raku tiene subrutinas realmente poderosas.
+## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
## lenguaje :-).
```
@@ -602,14 +602,14 @@ sub fst(*@ [$fst]) { # o simplemente: `sub fst($fst) { ... }`
fst(1); #=> 1
fst(1, 2); # errores con "Too many positional parameters passed"
-## También puedes desestructurar hashes (y clases, las cuales
-## veremos adelante). La sintaxis es básicamente
+## También puedes desestructurar hashes (y clases, las cuales
+## veremos adelante). La sintaxis es básicamente
## `%nombre-del-hash (:llave($variable-para-almacenar))`.
## El hash puede permanecer anónimos si solo necesitas los valores extraídos.
sub llave-de(% (:azul($val1), :red($val2))) {
say "Valores: $val1, $val2.";
}
-## Después invócala con un hash: (necesitas mantener las llaves
+## Después invócala con un hash: (necesitas mantener las llaves
## de los parejas de llave y valor para ser un hash)
llave-de({azul => 'blue', rojo => "red"});
#llave-de(%hash); # lo mismo (para un `%hash` equivalente)
@@ -621,11 +621,11 @@ sub siguiente-indice($n) {
}
my $nuevo-n= siguiente-indice(3); # $nuevo-n es ahora 4
-## Este es cierto para todo, excepto para las construcciones de bucles
+## Este es cierto para todo, excepto para las construcciones de bucles
## (debido a razones de rendimiento): Hay una razón de construir una lista
## si la vamos a desechar todos los resultados.
## Si todavías quieres construir una, puedes usar la sentencia prefijo `do`:
-## (o el prefijo `gather`, el cual veremos luego)
+## (o el prefijo `gather`, el cual veremos luego)
sub lista-de($n) {
do for ^$n { # nota el uso del operador de rango `^` (`0..^N`)
$_ # iteración de bucle actual
@@ -639,19 +639,19 @@ my @list3 = lista-de(3); #=> (0, 1, 2)
```perl6
## Puedes crear una lambda con `-> {}` ("bloque puntiagudo") o `{}` ("bloque")
my &lambda = -> $argumento { "El argumento pasado a esta lambda es $argumento" }
-## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
+## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
## tomar argumentos, y la segunda puede ser malinterpretada como un hash
## por el parseador.
## Podemos, por ejemplo, agregar 3 a cada valor de un array usando map:
my @arraymas3 = map({ $_ + 3 }, @array); # $_ es el argumento implícito
-## Una subrutina (`sub {}`) tiene semánticas diferentes a un
-## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
+## Una subrutina (`sub {}`) tiene semánticas diferentes a un
+## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
## (aunque puede tener argumentos), lo que significa que si quieres devolver
## algo desde un bloque, vas a returnar desde la función parental. Compara:
sub is-in(@array, $elem) {
- # esto `devolverá` desde la subrutina `is-in`
+ # esto `devolverá` desde la subrutina `is-in`
# Una vez que la condición evalúa a True, el bucle terminará
map({ return True if $_ == $elem }, @array);
}
@@ -685,7 +685,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (aquí con `sub`)
### Acerca de tipos...
```perl6
-## Perl 6 es gradualmente tipado. Esto quiere decir que tu especifica el
+## Raku es gradualmente tipado. Esto quiere decir que tu especifica el
## tipo de tus variables/argumentos/devoluciones (return), o puedes omitirlos
## y serán "Any" por defecto.
## Obviamente tienes acceso a algunas tipos básicos, como Int y Str.
@@ -703,7 +703,7 @@ subset EnteroGrande of Int where * > 500;
### Despacho Múltiple (Multiple Dispatch)
```perl6
-## Perl 6 puede decidir que variante de una subrutina invocar basado en el
+## Raku puede decidir que variante de una subrutina invocar basado en el
## tipo de los argumento, o precondiciones arbitrarias, como con un tipo o
## un `where`:
@@ -740,9 +740,9 @@ multi sin_ti-o-contigo {
}
## Esto es muy útil para muchos propósitos, como subrutinas `MAIN` (de las
## cuales hablaremos luego), y hasta el mismo lenguaje la está usando
-## en muchos lugares.
+## en muchos lugares.
##
-## - `is`, por ejemplo, es actualmente un `multi sub` llamado
+## - `is`, por ejemplo, es actualmente un `multi sub` llamado
## `trait_mod:<is>`.
## - `is rw`, es simplemente un despacho a una función con esta signatura:
## sub trait_mod:<is>(Routine $r, :$rw!) {}
@@ -754,7 +754,7 @@ multi sin_ti-o-contigo {
## Ámbito (Scoping)
```perl6
-## En Perl 6, a diferencia de otros lenguajes de scripting, (tales como
+## En Raku, a diferencia de otros lenguajes de scripting, (tales como
## (Python, Ruby, PHP), debes declarar tus variables antes de usarlas. El
## declarador `my`, del cual aprendiste anteriormente, usa "ámbito léxical".
## Hay otros declaradores (`our`, `state`, ..., ) los cuales veremos luego.
@@ -770,7 +770,7 @@ sub externo {
}
outer()(); #=> 'Foo Bar'
-## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
+## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
## fueron capturados. Pero si intentaramos usar `$bar` fuera de `foo`,
## la variable estaría indefinida (y obtendrías un error al tiempo de
## compilación).
@@ -779,12 +779,12 @@ outer()(); #=> 'Foo Bar'
## Twigils
```perl6
-## Hay muchos `twigils` especiales (sigilos compuestos) en Perl 6.
-## Los twigils definen el ámbito de las variables.
+## Hay muchos `twigils` especiales (sigilos compuestos) en Raku.
+## Los twigils definen el ámbito de las variables.
## Los twigils * y ? funcionan con variables regulares:
## * Variable dinámica
## ? Variable al tiempo de compilación
-## Los twigils ! y . son usados con los objetos de Perl 6:
+## Los twigils ! y . son usados con los objetos de Raku:
## ! Atributo (miembro de la clase)
## . Método (no una variable realmente)
@@ -820,20 +820,20 @@ di_ambito(); #=> 1 100 Cambiamos el valor de $*ambito_din_2 en invoca_a_di_ambit
```perl6
## Para invocar a un método en un objeto, agrega un punto seguido por el
-## nombre del objeto:
+## nombre del objeto:
## => $object.method
## Las classes son declaradas usando la palabra clave `class`. Los atributos
## son declarados con la palabra clave `has`, y los métodos con `method`.
## Cada atributo que es privado usa el twigil `!`. Por ejemplo: `$!attr`.
-## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
+## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
## mutables con `is rw`).
-## La manera más fácil de recordar el twigil `$.` is comparándolo
+## La manera más fácil de recordar el twigil `$.` is comparándolo
## con como los métodos son llamados.
-## El modelo de objeto de Perl 6 ("SixModel") es muy flexible, y te permite
+## El modelo de objeto de Raku ("SixModel") es muy flexible, y te permite
## agregar métodos dinámicamente, cambiar la semántica, etc ...
-## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
-## https://docs.perl6.org/language/objects.html).
+## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
+## https://docs.raku.org/language/objects.html).
class Clase-Atrib {
has $.atrib; # `$.atrib` es inmutable.
@@ -858,7 +858,7 @@ class Clase-Atrib {
};
## Crear una nueva instancia de Clase-Atrib con $.atrib asignado con 5:
-## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
+## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
## esto adelante).
my $class-obj = Clase-Atrib.new(atrib => 5);
say $class-obj.devolver-valor; #=> 5
@@ -870,12 +870,12 @@ $class-obj.otro-atrib = 10; # En cambio, esto funciona porque el atributo
### Herencia de Objeto
```perl6
-## Perl 6 también tiene herencia (junto a herencia múltiple)
+## Raku también tiene herencia (junto a herencia múltiple)
## Mientras los métodos declarados con `method` son heredados, aquellos
## declarados con `submethod` no lo son.
## Submétodos son útiles para la construcción y destrucción de tareas,
## tales como BUILD, o métodos que deben ser anulados por subtipos.
-## Aprenderemos acerca de BUILD más adelante.
+## Aprenderemos acerca de BUILD más adelante.
class Padre {
has $.edad;
@@ -890,7 +890,7 @@ class Padre {
# Herencia usa la palabra clave `is`
class Niño is Padre {
method hablar { say "Goo goo ga ga" }
- # Este método opaca el método `hablar` de Padre.
+ # Este método opaca el método `hablar` de Padre.
# Este niño no ha aprendido a hablar todavía.
}
my Padre $Richard .= new(edad => 40, nombre => 'Richard');
@@ -899,19 +899,19 @@ $Richard.hablar; #=> "Hola, mi nombre es Richard"
## $Richard es capaz de acceder el submétodo; él sabe como decir su nombre.
my Niño $Madison .= new(edad => 1, nombre => 'Madison');
-$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
+$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
# en la clase Niño.
# $Madison.color-favorito # no funciona porque no es heredado
## Cuando se usa `my T $var` (donde `T` es el nombre de la clase), `$var`
## inicia con `T` en si misma, por lo tanto puedes invocar `new` en `$var`.
-## (`.=` es sólo la invocación por punto y el operador de asignación:
+## (`.=` es sólo la invocación por punto y el operador de asignación:
## `$a .= b` es lo mismo que `$a = $a.b`)
## Por ejemplo, la instancia $Richard pudo también haber sido declarada así:
## my $Richard = Padre.new(edad => 40, nombre => 'Richard');
-## También observa que `BUILD` (el método invocado dentro de `new`)
-## asignará propiedades de la clase padre, por lo que puedes pasar
+## También observa que `BUILD` (el método invocado dentro de `new`)
+## asignará propiedades de la clase padre, por lo que puedes pasar
## `val => 5`.
```
@@ -932,7 +932,7 @@ class Item does PrintableVal {
has $.val;
## Cuando se utiliza `does`, un `rol` se mezcla en al clase literalmente:
- ## los métodos y atributos se ponen juntos, lo que significa que una clase
+ ## los métodos y atributos se ponen juntos, lo que significa que una clase
## puede acceder los métodos y atributos privados de su rol (pero no lo inverso!):
method access {
say $!counter++;
@@ -945,17 +945,17 @@ class Item does PrintableVal {
## de su clase hijo/a, pero es un error sin un rol lo hace)
## NOTA: Puedes usar un rol como una clase (con `is ROLE`). En este caso,
- ## métodos serán opacados, dado que el compilador considerará `ROLE`
- ## como una clase.
+ ## métodos serán opacados, dado que el compilador considerará `ROLE`
+ ## como una clase.
}
```
## Excepciones
```perl6
-## Excepciones están construidas al tope de las clases, en el paquete
+## Excepciones están construidas al tope de las clases, en el paquete
## `X` (como `X::IO`).
-## En Perl 6, excepciones son lanzadas automáticamente.
+## En Raku, excepciones son lanzadas automáticamente.
open 'foo'; #=> Failed to open file foo: no such file or directory
## También imprimirá la línea donde el error fue lanzado y otra información
## concerniente al error.
@@ -966,16 +966,16 @@ die 'Error!'; #=> Error!
## O más explícitamente:
die X::AdHoc.new(payload => 'Error!');
-## En Perl 6, `orelse` es similar al operador `or`, excepto que solamente
+## En Raku, `orelse` es similar al operador `or`, excepto que solamente
## coincide con variables indefinidas, en cambio de cualquier cosa
## que evalúa a falso.
-## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
+## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
## `Int`, `Str` y otros tipos que no han sido inicializados a ningún valor
## todavía.
## Puedes chequear si algo está definido o no usando el método defined:
my $no-inicializada;
say $no-inicializada.defined; #=> False
-## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
+## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
## fallo en $_
## Esto evitará que sea automáticamente manejado e imprima una marejada de
## mensajes de errores en la pantalla.
@@ -986,7 +986,7 @@ open 'foo' orelse say "Algo pasó {.exception}";
open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
#=> Failed to open file foo: no such file or directory
## Ambos ejemplos anteriores funcionan pero en caso de que consigamos un
-## objeto desde el lado izquierdo que no es un fallo, probablemente
+## objeto desde el lado izquierdo que no es un fallo, probablemente
## obtendremos una advertencia. Más abajo vemos como usar `try` y `CATCH`
## para ser más expecíficos con las excepciones que capturamos.
```
@@ -994,8 +994,8 @@ open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
### Usando `try` y `CATCH`
```perl6
-## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
-## interrumpir el resto del programa. `try` asignará la última excepción
+## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
+## interrumpir el resto del programa. `try` asignará la última excepción
## a la variable especial `$!`.
## Nota: Esto no tiene ninguna relación con las variables $!.
@@ -1003,12 +1003,12 @@ try open 'foo';
say "Bueno, lo intenté! $!" if defined $!; #=> Bueno, lo intenté! Failed to open file
#foo: no such file or directory
## Ahora, ¿qué debemos hacer si queremos más control sobre la excepción?
-## A diferencia de otros lenguajes, en Perl 6 se pone el bloque `CATCH`
+## A diferencia de otros lenguajes, en Raku se pone el bloque `CATCH`
## *dentro* del bloque a intentar (`try`). Similarmente como $_ fue asignada
## cuando 'disarmamos' la excepción con `orelse`, también usamos $_ en el
## bloque CATCH.
## Nota: ($! es solo asignada *después* del bloque `try`)
-## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
+## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
## cualquier excepción (`CATCH { default {} }`).
try { my $a = (0 %% 0); CATCH { say "Algo pasó: $_" } }
@@ -1022,9 +1022,9 @@ try {
when X::AdHoc { say "Error: $_" }
#=>Error: Failed to open file /dir/foo: no such file or directory
- ## Cualquier otra excepción será levantada de nuevo, dado que no
+ ## Cualquier otra excepción será levantada de nuevo, dado que no
## tenemos un `default`.
- ## Básicamente, si un `when`
+ ## Básicamente, si un `when`
## Basically, if a `when` matches (or there's a `default`) marks the
## exception as
## "handled" so that it doesn't get re-thrown from the `CATCH`.
@@ -1032,14 +1032,14 @@ try {
}
}
-## En Perl 6, excepciones poseen ciertas sutilezas. Algunas
-## subrutinas en Perl 6 devuelven un `Failure`, el cual es un tipo de
+## En Raku, excepciones poseen ciertas sutilezas. Algunas
+## subrutinas en Raku devuelven un `Failure`, el cual es un tipo de
## "excepción no levantada". Ellas no son levantadas hasta que tu intentas
-## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
+## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
## ellas - entonces, son manejadas.
## (el método `.handled` es `rw`, por lo que puedes marcarlo como `False`
## por ti mismo)
-## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
+## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
## `use fatal` estás siendo utilizado, `fail` levantará una excepión (como
## `die`).
fail "foo"; # No estamos intentando acceder el valor, por lo tanto no problema.
@@ -1053,27 +1053,27 @@ try {
## También hay otro tipo de excepción: Excepciones de control.
## Esas son excepciones "buenas", las cuales suceden cuando cambias el flujo
## de tu programa, usando operadores como `return`, `next` or `last`.
-## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
+## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
```
## Paquetes
```perl6
-## Paquetes son una manera de reusar código. Paquetes son como
-## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
+## Paquetes son una manera de reusar código. Paquetes son como
+## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
## modelo seis (`module`, `role`, `class`, `grammar`, `subset` y `enum`)
-## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
+## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
## denominador)
-## Los paquetes son importantes - especialmente dado que Perl es bien
+## Los paquetes son importantes - especialmente dado que Perl es bien
## reconocido por CPAN, the Comprehensive Perl Archive Nertwork.
## Puedes usar un módulo (traer sus declaraciones al ámbito) con `use`
use JSON::Tiny; # si intalaste Rakudo* o Panda, tendrás este módulo
say from-json('[1]').perl; #=> [1]
-## A diferencia de Perl 5, no deberías declarar paquetes usando
+## A diferencia de Perl, no deberías declarar paquetes usando
## la palabra clave `package`. En vez, usa `class Nombre::Paquete::Aquí;`
-## para declarar una clase, o si solamente quieres exportar
+## para declarar una clase, o si solamente quieres exportar
## variables/subrutinas, puedes usar `module`.
module Hello::World { # forma de llaves
@@ -1083,11 +1083,11 @@ module Hello::World { # forma de llaves
}
unit module Parse::Text; # forma de ámbito de archivo
-grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
+grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
# en el cual puedes usar `use`
} # Aprenderás más acerca de gramáticas en la sección de regex
-## Como se dijo anteriormente, cualquier parte del modelo seis es también un
+## Como se dijo anteriormente, cualquier parte del modelo seis es también un
## paquete. Dado que `JSON::Tiny` usa su propia clase `JSON::Tiny::Actions`,
## tu puedes usarla de la manera siguiente:
my $acciones = JSON::Tiny::Actions.new;
@@ -1098,13 +1098,13 @@ my $acciones = JSON::Tiny::Actions.new;
## Declaradores
```perl6
-## En Perl 6, tu obtienes diferentes comportamientos basado en como declaras
+## En Raku, tu obtienes diferentes comportamientos basado en como declaras
## una variable.
## Ya has visto `my` y `has`, ahora exploraremos el resto.
## * las declaraciones `our` ocurren al tiempo `INIT` (ve "Phasers" más abajo)
## Es como `my`, pero también crea una variable paquete.
-## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
+## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
## `our` por defecto)
module Var::Incrementar {
our $nuestra-var = 1; # Nota: No puedes colocar una restricción de tipo
@@ -1132,7 +1132,7 @@ Var::Incrementar::Inc; #=> 3 # Nota como el valor de $nuestra-var fue
Var::Incrementar::no-disponible; #=> Could not find symbol '&no-disponible'
## * `constant` (ocurre al tiempo `BEGIN`)
-## Puedes usar la palabra clave `constant` para declarar una
+## Puedes usar la palabra clave `constant` para declarar una
## variable/símbolo al tiempo de compilación:
constant Pi = 3.14;
constant $var = 1;
@@ -1151,11 +1151,11 @@ sub aleatorio-fijo {
aleatorio-fijo for ^10; # imprimirá el mismo número 10 veces
## Nota, sin embargo, que ellas existen separadamente en diferentes contextos.
-## Si declaras una función con un `state` dentro de un bucle, recreará la
+## Si declaras una función con un `state` dentro de un bucle, recreará la
## variable por cada iteración del bucle. Observa:
for ^5 -> $a {
sub foo {
- state $valor = rand; # Esto imprimirá un valor diferente
+ state $valor = rand; # Esto imprimirá un valor diferente
# por cada valor de `$a`
}
for ^5 -> $b {
@@ -1165,11 +1165,11 @@ for ^5 -> $a {
}
```
-## Phasers
+## Phasers
```perl6
-## Un phaser en Perl 6 es un bloque que ocurre a determinados puntos de tiempo
-## en tu programa. Se les llama phaser porque marca un cambio en la fase de
+## Un phaser en Raku es un bloque que ocurre a determinados puntos de tiempo
+## en tu programa. Se les llama phaser porque marca un cambio en la fase de
## de tu programa. Por ejemplo, cuando el programa es compilado, un bucle
## for se ejecuta, dejas un bloque, o una excepción se levanta.
## (¡`CATCH` es actualmente un phaser!)
@@ -1191,13 +1191,13 @@ END { say "Se ejecuta al tiempo de ejecución, " ~
"tan tarde como sea posible, una sola vez" }
## * Phasers de bloques
-ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
+ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
"se repite en bloques de bucle" }
-LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
+LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
"cuando una excepción ocurre. Se repite en bloques de bucle"}
PRE {
- say "Impone una precondición a cada entrada de un bloque, " ~
+ say "Impone una precondición a cada entrada de un bloque, " ~
"antes que ENTER (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada.";
@@ -1209,7 +1209,7 @@ for 0..2 {
}
POST {
- say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
+ say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
"después de LEAVE (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada, como con PRE.";
@@ -1250,14 +1250,14 @@ sub do-db-stuff {
## Prefijos de sentencias
```perl6
-## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
+## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
## comportamiento del siguiente código.
## Debido a que son ejecutados en línea con el código ejecutable, ellos
## se escriben en letras minúsculas. (`try` and `start` están teoréticamente
## en esa lista, pero serán explicados en otra parte)
## Nota: Ningunos de estos (excepto `start`) necesitan las llaves `{` y `}`.
-## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
+## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
## término.
## Normalmente no puedes usar una sentencia como un valor (o término):
##
@@ -1289,7 +1289,7 @@ say join ',', gather if False {
## - `eager` - Evalúa una sentencia ávidamente (forza contexto ávido)
## No intentes esto en casa:
##
-## eager 1..*; # esto probablemente se colgará por un momento
+## eager 1..*; # esto probablemente se colgará por un momento
## # (y podría fallar...).
##
## Pero considera lo siguiente:
@@ -1302,13 +1302,13 @@ constant tres-veces = eager gather for ^3 { say take $_ }; #=> 0 1 2
## Iterables
```perl6
-## En Perl 6, los iterables son objetos que pueden ser iterados similar
-## a la construcción `for`.
+## En Raku, los iterables son objetos que pueden ser iterados similar
+## a la construcción `for`.
## `flat`, aplana iterables:
say (1, 10, (20, 10) ); #=> (1 10 (20 10)) Nota como la agrupación se mantiene
say (1, 10, (20, 10) ).flat; #=> (1 10 20 10) Ahora el iterable es plano
-## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
+## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
## (forza contexto perezoso)
my @lazy-array = (1..100).lazy;
say @lazy-array.is-lazy; #=> True # Chequea por "pereza" con el método `is-lazy`.
@@ -1333,7 +1333,7 @@ quietly { warn 'Esto es una advertencia!' }; #=> No salida
## ¡Todo el mundo ama los operadores! Tengamos más de ellos.
## La lista de precedencia puede ser encontrada aquí:
-## https://docs.perl6.org/language/operators#Operator_Precedence
+## https://docs.raku.org/language/operators#Operator_Precedence
## Pero primero, necesitamos un poco de explicación acerca
## de la asociatividad:
@@ -1356,7 +1356,7 @@ $a ! $b ! $c; # con asociatividad de lista `!`, esto es `infix:<>`
## Okay, has leído todo esto y me imagino que debería mostrarte
## algo interesante.
## Te mostraré un pequeño secreto (o algo no tan secreto):
-## En Perl 6, todos los operadores son actualmente solo subrutinas.
+## En Raku, todos los operadores son actualmente solo subrutinas.
## Puedes declarar un operador como declaras una subrutina:
sub prefix:<ganar>($ganador) { # se refiere a las categorías de los operadores
@@ -1374,14 +1374,14 @@ sub postfix:<!>(Int $n) {
}
say 5!; #=> 120
# Operadores sufijos (postfix) van *directamente* después del témino.
- # No espacios en blanco. Puedes usar paréntesis para disambiguar,
+ # No espacios en blanco. Puedes usar paréntesis para disambiguar,
# i.e. `(5!)!`
sub infix:<veces>(Int $n, Block $r) { # infijo va en el medio
for ^$n {
$r(); # Necesitas los paréntesis explícitos para invocar la función
- # almacenada en la variable `$r`. De lo contrario, te estaría
+ # almacenada en la variable `$r`. De lo contrario, te estaría
# refiriendo a la variable (no a la función), como con `&r`.
}
}
@@ -1399,33 +1399,33 @@ say [5]; #=> 3125
# un circunfijo va alrededor. De nuevo, no espacios en blanco.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
- ## un pos-circunfijo es
+ ## un pos-circunfijo es
## "después de un término y alrededor de algo"
$s.substr($idx, 1);
}
say "abc"{1}; #=> b
# depués del término `"abc"`, y alrededor del índice (1)
-## Esto es de gran valor -- porque todo en Perl 6 usa esto.
+## Esto es de gran valor -- porque todo en Raku usa esto.
## Por ejemplo, para eliminar una llave de un hash, tu usas el adverbio
## `:delete` (un simple argumento con nombre debajo):
%h{$llave}:delete;
## es equivalente a:
-postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
+postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
# operadores de esta forma)
-## ¡*Todos* usan los mismos bloques básicos!
+## ¡*Todos* usan los mismos bloques básicos!
## Categorías sintácticas (prefix, infix, ...), argumentos nombrados
## (adverbios), ... - usados para construir el lenguaje - están al alcance
## de tus manos y disponibles para ti.
-## (obviamente, no se te recomienda que hagas un operador de *cualquier
+## (obviamente, no se te recomienda que hagas un operador de *cualquier
## cosa* -- Un gran poder conlleva una gran responsabilidad.)
```
### Meta-operadores!
```perl6
-## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
-## en el agujero del conejo, y probablemente no querrás regresar a
+## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
+## en el agujero del conejo, y probablemente no querrás regresar a
## otros lenguajes después de leer esto.
## (Me imagino que ya no quieres a este punto).
## Meta-operadores, como su nombre lo sugiere, son operadores *compuestos*.
@@ -1434,14 +1434,14 @@ postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
## * El meta-operador reduce (reducir)
## Es un meta-operador prefijo que toman una función binaria y
## una o varias listas. Sino se pasa ningún argumento,
-## returna un "valor por defecto" para este operador
+## returna un "valor por defecto" para este operador
## (un valor sin significado) o `Any` si no hay ningún valor.
##
-## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
+## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
## aplica la función binaria al último resultado (o al primer elemento de
## la lista y el elemento que ha sido removido).
##
-## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
+## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
## i.e.:
say [+] 1, 2, 3; #=> 6
## es equivalente a `(1+2)+3`
@@ -1461,20 +1461,20 @@ say [+] (); #=> 0
# valores sin significado, dado que N*1=N y N+0=N.
say [//]; #=> (Any)
# No hay valor por defecto para `//`.
-## También puedes invocarlo con una función de tu creación usando
+## También puedes invocarlo con una función de tu creación usando
## los dobles corchetes:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * El meta-operador zip
-## Este es un meta-operador infijo que también puede ser usado como un
+## Este es un meta-operador infijo que también puede ser usado como un
## operador "normal". Toma una función binaria opcional (por defecto, solo
-## crear un par), y remueve un valor de cada array e invoca su función
+## crear un par), y remueve un valor de cada array e invoca su función
## binaria hasta que no tenga más elementos disponibles. Al final, returna
## un array con todos estos nuevos elementos.
-(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
+(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
# crea un array.
-1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
+1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
## Dado que `Z` tiene asociatividad de lista (ve la lista más arriba),
## puedes usarlo en más de una lista
@@ -1487,13 +1487,13 @@ say [[&add]] 1, 2, 3; #=> 6
## Y para terminar la lista de operadores:
## * El operador secuencia
-## El operador secuencia es uno de la más poderosas características de
-## Perl 6: Está compuesto, en la izquierda, de la lista que quieres que
-## Perl 6 use para deducir (y podría incluir una clausura), y en la derecha,
-## un valor o el predicado que dice cuando parar (o Whatever para una
+## El operador secuencia es uno de la más poderosas características de
+## Raku: Está compuesto, en la izquierda, de la lista que quieres que
+## Raku use para deducir (y podría incluir una clausura), y en la derecha,
+## un valor o el predicado que dice cuando parar (o Whatever para una
## lista infinita perezosa).
my @list = 1, 2, 3 ... 10; # deducción básica
-#my @list = 1, 3, 6 ... 10; # esto muere porque Perl 6 no puede deducir el final
+#my @list = 1, 3, 6 ... 10; # esto muere porque Raku no puede deducir el final
my @list = 1, 2, 3 ...^ 10; # como con rangos, puedes excluir el último elemento
# (la iteración cuando el predicado iguala).
my @list = 1, 3, 9 ... * > 30; # puedes usar un predicado
@@ -1505,8 +1505,8 @@ my @fib = 1, 1, *+* ... *; # lista infinita perezosa de la serie fibonacci,
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalene a lo de arriba)
my @fib = 1, 1, { $^a + $^b } ... *; #(... también equivalene a lo de arriba)
## $a and $b siempre tomarán el valor anterior, queriendo decir que
-## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
-## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
+## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
+## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
## etc.
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
@@ -1519,29 +1519,29 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
## Expresiones Regulares
```perl6
-## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
-## sabes algo acerca de Perl 6, podemos comenzar. Primeramente, tendrás
-## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
+## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
+## sabes algo acerca de Raku, podemos comenzar. Primeramente, tendrás
+## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
## (expresiones regulares compatible de perl).
##
## IMPORTANTE: No salte esto porque ya sabes acerca de PCRE. Son totalmente
-## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
+## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
## algunas veces la semántica cambia (`|`). Asegúrate de leer esto
## cuidadosamente porque podrías trospezarte sino lo haces.
##
-## Perl 6 tiene muchas características relacionadas con RegExps. Después de
+## Raku tiene muchas características relacionadas con RegExps. Después de
## todo, Rakudo se parsea a si mismo. Primero vamos a estudiar la sintaxis
## por si misma, después hablaremos acerca de gramáticas (parecido a PEG),
-## las diferencias entre los declaradores `token`, `regex`, y `rule` y
+## las diferencias entre los declaradores `token`, `regex`, y `rule` y
## mucho más.
-## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
+## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
## mofificador `:P5` (Sin embargo, no lo discutiremos en este tutorial).
##
-## En esencia, Perl 6 implementa PEG ("Parsing Expression Grammars")
+## En esencia, Raku implementa PEG ("Parsing Expression Grammars")
## ("Parseado de Expresiones de Gramáticas") nativamente. El orden jerárquico
-## para los parseos ambiguos es determinado por un examen multi-nivel de
+## para los parseos ambiguos es determinado por un examen multi-nivel de
## desempate:
-## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
+## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
## (por 2 o más posiciones)
## - El prefijo literal más largo. `food\w*` le gana a `foo\w*` (por 1)
## - Declaración desde la gramática más derivada a la menos derivada
@@ -1550,48 +1550,48 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
say so 'a' ~~ /a/; #=> True
say so 'a' ~~ / a /; #=> True # ¡Más legible con los espacios!
-## Nota al lector (del traductor):
+## Nota al lector (del traductor):
## Como pudiste haber notado, he decidido traducir "match" y sus diferentes
-## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
+## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
## un regex (o regexp) coincide con cierto texto, me refiero a que el regex
## describe cierto patrón dentro del texto. Por ejemplo, el regex "cencia"
-## coincide con el texto "reminiscencia", lo que significa que dentro del
+## coincide con el texto "reminiscencia", lo que significa que dentro del
## texto aparece ese patrón de caracteres (una `c`, seguida de una `e`,
-## (seguida de una `n`, etc.)
+## (seguida de una `n`, etc.)
-## En todos nuestros ejemplos, vamos a usar el operador de
-## "coincidencia inteligente" contra una expresión regular ("regexp" or
+## En todos nuestros ejemplos, vamos a usar el operador de
+## "coincidencia inteligente" contra una expresión regular ("regexp" or
## "regex" de aquí en adelante). Estamos convirtiendo el resultado usando `so`,
## pero en efecto, está devolviendo un objeto Match. Ellos saben como responder
-## a la indexación de lista, indexación de hash, y devolver la cadena de
+## a la indexación de lista, indexación de hash, y devolver la cadena de
## texto coincidente.
-## Los resultados de la coincidencia están disponible como `$/` (en
+## Los resultados de la coincidencia están disponible como `$/` (en
## ámbito implícito lexical). También puedes usar las variables de captura
## las cuales comienzan con 0:
## `$0`, `$1', `$2`...
##
-## Nota que `~~` no hace un chequeo de inicio/final (es decir,
+## Nota que `~~` no hace un chequeo de inicio/final (es decir,
## el regexp puede coincider con solo un carácter de la cadena de texto).
## Explicaremos luego como hacerlo.
-## En Perl 6, puedes tener un carácter alfanumérico como un literal,
+## En Raku, puedes tener un carácter alfanumérico como un literal,
## todo lo demás debe escaparse usando una barra invertida o comillas.
-say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
+say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
say so 'a|b' ~~ / a \| b /; # `True`. Otra forma de escaparlo
-## El espacio en blanco actualmente no se significa nada en un regexp,
+## El espacio en blanco actualmente no se significa nada en un regexp,
## a menos que uses el adverbio `:s` (`:sigspace`, espacio significante).
say so 'a b c' ~~ / a b c /; #=> `False`. Espacio no significa nada aquí.
say so 'a b c' ~~ /:s a b c /; #=> `True`. Agregamos el modificador `:s` aquí.
-## Si usamos solo un espacio entre cadenas de texto en un regexp, Perl 6
+## Si usamos solo un espacio entre cadenas de texto en un regexp, Raku
## nos advertirá:
say so 'a b c' ~~ / a b c /; #=> 'False' # Espacio no significa nada aquí.
## Por favor usa comillas o el modificador :s (:sigspace) para suprimir
-## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
-## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
+## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
+## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
## dos espacios entre las cadenas de texto o usa el adverbio `:s`.
-## Como vimos anteriormente, podemos incorporar `:s` dentro de los
+## Como vimos anteriormente, podemos incorporar `:s` dentro de los
## delimitadores de barras. También podemos ponerlos fuera de ellos si
## especificamos `m` for `match` (coincidencia):
say so 'a b c' ~~ m:s/a b c/; #=> `True`
@@ -1603,7 +1603,7 @@ say so 'abc' ~~ m[a b c]; #=> `True`
## minúsculas y mayúsculas:
say so 'ABC' ~~ m:i{a b c}; #=> `True`
-## Sin embargo, es importante para como los modificadores son aplicados
+## Sin embargo, es importante para como los modificadores son aplicados
## (lo cual verás más abajo)...
## Cuantificando - `?`, `+`, `*` y `**`.
@@ -1612,7 +1612,7 @@ so 'ac' ~~ / a b c /; # `False`
so 'ac' ~~ / a b? c /; # `True`, la "b" coincidió (apareció) 0 veces.
so 'abc' ~~ / a b? c /; # `True`, la "b" coincidió 1 vez.
-## ... Como debes saber, espacio en blancos son importante porque
+## ... Como debes saber, espacio en blancos son importante porque
## determinan en que parte del regexp es el objetivo del modificador:
so 'def' ~~ / a b c? /; # `False`. Solamente la `c` es opcional
so 'def' ~~ / a b? c /; # `False`. Espacio en blanco no es significante
@@ -1642,7 +1642,7 @@ so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (rangos infinitos no son un problem
## - `<[]>` - Clases de carácteres
## Las clases de carácteres son equivalentes a las clases `[]` de PCRE,
-## pero usan una sintaxis de Perl 6:
+## pero usan una sintaxis de Raku:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
## Puedes usar rangos:
@@ -1663,7 +1663,7 @@ so 'foo' ~~ / <-[ f o ]> + /; # False
## ... y componerlos:
so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (cualquier letra excepto f y o)
so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letra excepto f and o)
-so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
+so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
# parte de la izquierda)
```
@@ -1671,7 +1671,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
```perl6
## Grupo: Puedes agrupar partes de tu regexp con `[]`.
-## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
+## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
so 'abc' ~~ / a [ b ] c /; # `True`. El agrupamiento no hace casi nada
so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## La línea anterior returna `True`.
@@ -1680,15 +1680,15 @@ so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## Pero esto no va demasiado lejos, porque no podemos actualmente obtener
## devuelta el patrón que coincidió.
-## Captura: Podemos actualmente *capturar* los resultados del regexp,
+## Captura: Podemos actualmente *capturar* los resultados del regexp,
## usando paréntesis.
so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (usando `so`
# aquí, `$/` más abajo)
-## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
+## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
### nuestra objeto `Match` está disponible en la variable `$/`:
-say $/; # Imprimirá algo extraño (explicaremos luego) o
- # "Nil" si nada coincidió
+say $/; # Imprimirá algo extraño (explicaremos luego) o
+ # "Nil" si nada coincidió
## Como dijimos anteriormente, un objeto Match tiene indexación de array:
say $/[0]; #=> 「ABC」 「ABC」
@@ -1696,15 +1696,15 @@ say $/[0]; #=> 「ABC」 「ABC」
# Aquí, tenemos un array de ellos.
say $0; # Lo mismo que lo anterior.
-## Nuestra captura es `$0` porque es la primera y única captura en el
-## regexp. Podrías estarte preguntando porque un array y la respuesta es
+## Nuestra captura es `$0` porque es la primera y única captura en el
+## regexp. Podrías estarte preguntando porque un array y la respuesta es
## simple: Algunas capturas (indezadas usando `$0`, `$/[0]` o una nombrada)
## será un array si y solo si puedes tener más de un elemento.
## (Así que, con `*`, `+` y `**` (cualquiera los operandos), pero no con `?`).
## Usemos algunos ejemplos para ver como funciona:
## Nota: Pusimos A B C entre comillas para demostrar que el espacio en blanco
-## entre ellos no es significante. Si queremos que el espacio en blanco
+## entre ellos no es significante. Si queremos que el espacio en blanco
## *sea* significante, podemos utilizar el modificador `:sigspace`.
so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # `True`
say $/[0]; #=> 「ABC」
@@ -1718,22 +1718,22 @@ say $0.WHAT; #=> (Array)
# Un cuantificador específico siempre capturará un Array,
# puede ser un rango o un valor específico (hasta 1).
-## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
-## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
+## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
+## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
## para este código:
'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /;
say $/[0].Str; #=> hello~
say $/[0][0].Str; #=> ~
-## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
-## texto, números enteros o arrays sino que solo contiene objetos Match.
-## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
-## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
+## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
+## texto, números enteros o arrays sino que solo contiene objetos Match.
+## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
+## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
## para accesar un array.
say $/[0].list.perl; #=> (Match.new(...),).list
# Podemos ver que es una lista de objetos Match.
- # Estos contienen un montón de información: dónde la
- # coincidencia comenzó o terminó, el "ast"
+ # Estos contienen un montón de información: dónde la
+ # coincidencia comenzó o terminó, el "ast"
# (chequea las acciones más abajo), etc.
# Verás capturas nombradas más abajo con las gramáticas.
@@ -1743,9 +1743,9 @@ so 'abc' ~~ / a [ b | y ] c /; # `True`. o "b" o "y".
so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## La diferencia entre este `|` y el otro al que estás acustombrado es LTM.
-## LTM significa "Longest Token Matching", traducido libremente como
+## LTM significa "Longest Token Matching", traducido libremente como
## "Coincidencia de Token Más Larga". Esto significa que el motor ("engine")
-## siempre intentará coindidir tanto como sea posible en la cadena de texto.
+## siempre intentará coindidir tanto como sea posible en la cadena de texto.
## Básicamente, intentará el patrón más largo que concuerde con el regexp.
'foo' ~~ / fo | foo /; # `foo` porque es más largo.
## Para decidir cual parte es la "más larga", primero separa el regex en
@@ -1759,19 +1759,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## anteriores, aserciones de código, y otras cosas que tradicionalmente no pueden
## ser representadas por regexes normales.
##
-## Entonces, todas las alternativas se intentan al mismo tiempo, y la
+## Entonces, todas las alternativas se intentan al mismo tiempo, y la
## más larga gana.
## Ejemplos:
## DECLARATIVO | PROCEDIMENTAL
/ 'foo' \d+ [ <subrule1> || <subrule2> ] /;
## DECLARATIVO (grupos anidados no son un problema)
/ \s* [ \w & b ] [ c | d ] /;
-## Sin embargo, las clausuras y la recursión (de regexes nombrados)
+## Sin embargo, las clausuras y la recursión (de regexes nombrados)
## son procedimentales.
## ... Hay más reglas complicadas, como la especifidad (los literales ganan
## son las clases de caracteres)
+
-## Nota: la primera coincidencia `or` todavía existen, pero ahora se
+## Nota: la primera coincidencia `or` todavía existen, pero ahora se
## deletrea `||`
'foo' ~~ / fo || foo /; # `fo` ahora.
```
@@ -1779,19 +1779,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## Extra: la subrutina MAIN
```perl6
-## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Perl 6
-## directamente. Es realmente poderosa porque Perl 6 actualmente parsea
-## los argumentos y los pasas a la subrutina. También maneja argumentos
+## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Raku
+## directamente. Es realmente poderosa porque Raku actualmente parsea
+## los argumentos y los pasas a la subrutina. También maneja argumentos
## nombrados (`--foo`) y hasta autogenerará un `--help`.
sub MAIN($nombre) { say "¡Hola, $nombre!" }
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl <nombre>
-## Y dado que una subrutina regular en Perl 6, puedes tener múltiples
+## Y dado que una subrutina regular en Raku, puedes tener múltiples
## despachos:
-## (usando un "Bool" por un argumento nombrado para que podamos hacer
+## (usando un "Bool" por un argumento nombrado para que podamos hacer
## `--replace` a cambio de `--replace=1`)
subset File of Str where *.IO.d; # convierte a un objeto IO para chequear si
# un archivo existe
@@ -1800,7 +1800,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl [--replace] add <key> <value>
## t.pl remove <key>
@@ -1814,7 +1814,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
### Lista de cosas
```perl6
-## Consideramos que por ahora ya sabes lo básico de Perl 6.
+## Consideramos que por ahora ya sabes lo básico de Raku.
## Esta sección es solo para listar algunas operaciones comunes
## las cuales no están en la "parte principal" del tutorial.
@@ -1825,13 +1825,13 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## (los cuales representan los números -1, 0 o +1).
1 <=> 4; # comparación de orden para caracteres numéricos
'a' leg 'b'; # comparación de orden para cadenas de texto
-$obj eqv $obj2; # comparación de orden usando la semántica eqv
+$obj eqv $obj2; # comparación de orden usando la semántica eqv
## * Ordenación genérica
3 before 4; # True
'b' after 'a'; # True
-## * Operador (por defecto) de circuito corto
+## * Operador (por defecto) de circuito corto
## Al igual que `or` y `||`, pero devuelve el primer valor *defined*
## (definido):
say Any // Nil // 0 // 5; #=> 0
@@ -1843,9 +1843,9 @@ say True ^^ False; #=> True
## * Flip Flop
## Los operadores flip flop (`ff` y `fff`, equivalente a `..`/`...` en P5)
## son operadores que toman dos predicados para evalualarlos:
-## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
+## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
## son `True` hasta que su lado derecho devuelve `True`.
-## Como los rangos, tu puedes excluir la iteración cuando se convierte en
+## Como los rangos, tu puedes excluir la iteración cuando se convierte en
## `True`/`False` usando `^` en cualquier lado.
## Comencemos con un ejemplo:
for <well met young hero we shall meet later> {
@@ -1861,25 +1861,25 @@ for <well met young hero we shall meet later> {
}
## Esto imprimirá "young hero we shall meet" (exluyendo "met"):
## el flip-flop comenzará devolviendo `True` cuando primero encuentra "met"
-## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
+## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
## hasta que ve "meet", lo cual es cuando comenzará devolviendo `False`.
## La diferencia entre `ff` (al estilo de awk) y `fff` (al estilo de sed)
-## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
+## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
## a `True`, y puede returnar a `False` inmediamente (*excepto* que será
-## `True` por la iteración con la cual coincidió). Por lo contrario,
-## `fff` esperará por la próxima iteración para intentar su lado
+## `True` por la iteración con la cual coincidió). Por lo contrario,
+## `fff` esperará por la próxima iteración para intentar su lado
## derecho, una vez que su lado izquierdo ha cambiado:
.say if 'B' ff 'B' for <A B C B A>; #=> B B
# porque el lado derecho se puso a prueba
# directamente (y returnó `True`).
# Las "B"s se imprimen dadó que coincidió
- # en ese momento (returnó a `False`
+ # en ese momento (returnó a `False`
# inmediatamente).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
# El lado derecho no se puso a prueba
# hasta que `$_` se convirtió en "C"
- # (y por lo tanto no coincidió
+ # (y por lo tanto no coincidió
# inmediamente).
## Un flip-flop puede cambiar estado cuantas veces se necesite:
@@ -1901,35 +1901,35 @@ for (1, 3, 60, 3, 40, 60) { # Nota: los paréntesis son superfluos aquí
## que no pasará la primera vez:
for <a b c> {
.say if * ^ff *; # el flip-flop es `True` y nunca returna a `False`,
- # pero el `^` lo hace *que no se ejecute* en la
+ # pero el `^` lo hace *que no se ejecute* en la
# primera iteración
#=> b c
}
-## - `===` es la identidad de valor y usa `.WHICH`
+## - `===` es la identidad de valor y usa `.WHICH`
## en los objetos para compararlos.
-## - `=:=` es la identidad de contenedor y usa `VAR()`
+## - `=:=` es la identidad de contenedor y usa `VAR()`
## en los objetos para compararlos.
```
Si quieres ir más allá de lo que se muestra aquí, puedes:
- - Leer la [documentación de Perl 6](https://docs.perl6.org/). Esto es un recurso
- grandioso acerca de Perl 6. Si estás buscando por algo en particular, usa la
+ - Leer la [documentación de Raku](https://docs.raku.org/). Esto es un recurso
+ grandioso acerca de Raku. Si estás buscando por algo en particular, usa la
barra de búsquedas. Esto te dará un menú de todas las páginas concernientes
a tu término de búsqueda (¡Es mucho mejor que usar Google para encontrar
- documentos acerca de Perl 6!)
- - Leer el [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). Este es
- un gran recurso de fragmentos de código de Perl 6 y explicaciones. Si la documentación
+ documentos acerca de Raku!)
+ - Leer el [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). Este es
+ un gran recurso de fragmentos de código de Raku y explicaciones. Si la documentación
no describe algo lo suficientemente bien, puedes encontrar información más detallada
aquí. Esta información puede ser un poquito más antigua pero hay muchos ejemplos y
- explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
- el lenguaje fue declarado estable y Perl 6.c fue lanzado.
- - Unirte a `#perl6` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
- - Chequear la [fuente de las funciones y clases de Perl 6
- ](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo está principalmente
- escrito en Perl 6 (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
- subconjunto de Perl 6 que es más fácil de implementar y optimizar).
- - Leer [documentos acerca del diseño del lenguaje](http://design.perl6.org).
+ explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
+ el lenguaje fue declarado estable y Raku.c fue lanzado.
+ - Unirte a `#raku` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
+ - Chequear la [fuente de las funciones y clases de Raku
+ ](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo está principalmente
+ escrito en Raku (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
+ subconjunto de Raku que es más fácil de implementar y optimizar).
+ - Leer [documentos acerca del diseño del lenguaje](http://design.raku.org).
Estos explican P6 desde la perspectiva de un implementador, lo cual es bastante
interesante.
diff --git a/fr-fr/crystal-fr.html.markdown b/fr-fr/crystal-fr.html.markdown
index 2bb17fc5..02ab3b2b 100644
--- a/fr-fr/crystal-fr.html.markdown
+++ b/fr-fr/crystal-fr.html.markdown
@@ -350,7 +350,7 @@ sum 3, 4 #=> 7
sum sum(3, 4), 5 #=> 12
# yield
-# Toutes les méthodes on un paramètre optionel et implicite de type bloc
+# Toutes les méthodes ont un paramètre optionel et implicite de type bloc
# il peut être appelé avec le mot clé 'yield'
def surround
puts '{'
diff --git a/fr-fr/elisp-fr.html.markdown b/fr-fr/elisp-fr.html.markdown
index 2e0a9408..f9bf589c 100644
--- a/fr-fr/elisp-fr.html.markdown
+++ b/fr-fr/elisp-fr.html.markdown
@@ -328,9 +328,9 @@ lang: fr-fr
(other-window 1))
;; Cette fonction introduit `re-search-forward' : au lieu de chercher
-;; la chaîne "Bonjour", nous cherchons un "pattern" en utilisant une
-;; "expression régulière" (le préfixe "re-" signifie "regular
-;; expression").
+;; la chaîne "Bonjour", nous cherchons un motif ("pattern" en anglais)
+;; en utilisant une "expression régulière" (le préfixe "re-" signifie
+;; "regular expression").
;; L'expression régulière est "Bonjour \\(.+\\)!" et se lit :
;; la chaîne "Bonjour ", et
@@ -343,7 +343,7 @@ lang: fr-fr
(boldify-names)
-;; `add-text-properties' ajoute des propriétés textuelles telle que
+;; `add-text-properties' ajoute des propriétés textuelles telles que
;; des "faces" (une "face" définit la fonte, la couleur, la taille et
;; d'autres propriétés du texte.)
@@ -361,7 +361,7 @@ lang: fr-fr
;; Pour lire en ligne une introduction à Emacs Lisp :
;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
-;; Merci à ces personnes pour leurs retours et suggetions :
+;; Merci à ces personnes pour leurs retours et suggestions :
;; - Wes Hardaker
;; - notbob
;; - Kevin Montuori
diff --git a/fr-fr/fsharp-fr.html.markdown b/fr-fr/fsharp-fr.html.markdown
index 3fd41676..dda9945f 100644
--- a/fr-fr/fsharp-fr.html.markdown
+++ b/fr-fr/fsharp-fr.html.markdown
@@ -140,7 +140,8 @@ module FunctionExamples =
let a = add 1 2
printfn "1+2 = %i" a
- // partial application to "bake in" parameters (?)
+ // application partielle des paramètres (curryfication ou "currying" en anglais)
+ // add42 est une nouvelle fonction qui ne prend plus qu'un paramètre
let add42 = add 42
let b = add42 1
printfn "42+1 = %i" b
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
index e737b7aa..e073bcf5 100644
--- a/fr-fr/perl-fr.html.markdown
+++ b/fr-fr/perl-fr.html.markdown
@@ -10,9 +10,9 @@ translators:
- ["Matteo Taroli", "http://www.matteotaroli.be"]
lang: fr-fr
---
-Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+Perl est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
-Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+Perl fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
```perl
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 064a9fdd..c140d6b1 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -633,6 +633,6 @@ module NetCompatibilityExamples =
## More Information
-For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
+For more demonstrations of F#, go to my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
-Read more about F# at [fsharp.org](http://fsharp.org/).
+Read more about F# at [fsharp.org](http://fsharp.org/) and [dotnet's F# page](https://dotnet.microsoft.com/languages/fsharp).
diff --git a/git.html.markdown b/git.html.markdown
index aa96c90a..a40ef01b 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -82,12 +82,12 @@ pushed to other repositories, or not!
### Branch
A branch is essentially a pointer to the last commit you made. As you go on
-committing, this pointer will automatically update to point the latest commit.
+committing, this pointer will automatically update to point to the latest commit.
### Tag
A tag is a mark on specific point in history. Typically people use this
-functionality to mark release points (v1.0, and so on)
+functionality to mark release points (v1.0, and so on).
### HEAD and head (component of .git dir)
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 89ca973a..0d589c10 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -184,7 +184,7 @@ class Foo {
Methods with optional parameters
*/
-// A mthod can have default values for parameters
+// A method can have default values for parameters
def say(msg = 'Hello', name = 'world') {
"$msg $name!"
}
diff --git a/it-it/sql-it.html.markdown b/it-it/sql-it.html.markdown
new file mode 100644
index 00000000..7db2eec1
--- /dev/null
+++ b/it-it/sql-it.html.markdown
@@ -0,0 +1,112 @@
+---
+language: SQL
+filename: learnsql-it.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["Christian Grasso", "https://grasso.io"]
+lang: it-it
+---
+
+Structured Query Language (SQL) è un linguaggio standard ISO per la creazione e la gestione
+di database organizzati in un insieme di tabelle. Le diverse implementazioni aggiungono
+spesso le proprie estensioni al linguaggio base ([confronto tra le diverse implementazioni](http://troels.arvin.dk/db/rdbms/))
+
+Le diverse implementazioni forniscono inoltre un prompt per inserire in modo interattivo i comandi
+o eseguire il contenuto di uno script.
+
+I comandi di seguito lavorano sul [database di esempio MySQL](https://dev.mysql.com/doc/employee/en/)
+disponibile su [GitHub](https://github.com/datacharmer/test_db). I file .sql contengono liste di comandi
+simili a quelli mostrati di seguito, che creano e riempiono delle tabelle con dati di un'azienda fittizia.
+Il comando per eseguire questi script può variare in base all'implementazione in uso.
+
+
+```sql
+-- I commenti iniziano con due trattini. Ogni comando va terminato con il punto e virgola
+
+-- SQL è case-insensitive per quanto riguarda i comandi; in genere si
+-- preferisce scriverli in maiuscolo per distinguerli dai nomi di
+-- database, tabelle e colonne
+
+-- Crea ed elimina un database. I nomi di database e tabelle sono case-sensitive
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- Lista dei database disponibili
+SHOW DATABASES;
+
+-- Attiva uno specifico database
+USE employees;
+
+-- Seleziona tutte le righe e le colonne dalla tabella departments
+SELECT * FROM departments;
+
+-- Seleziona tutte le righe della tabella departments,
+-- ma solo le colonne dept_no e dept_name.
+-- È possibile suddividere i comandi su più righe.
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- Seleziona solo le prime 5 righe della tabella departments.
+SELECT * FROM departments LIMIT 5;
+
+-- Ottiene la colonna dept_name della tabella departments
+-- solo per le righe il cui valore di dept_name contiene 'en'.
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- Ottiene tutte le colonne della tabella departments
+-- solo per le righe che hanno un dept_name formato da una 'S'
+-- seguita esattamente da altri 4 caratteri
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- Seleziona i valori di title dalla tabella titles eliminando i duplicati
+SELECT DISTINCT title FROM titles;
+
+-- Come sopra, ma i valori sono ordinati alfabeticamente
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- Mostra il numero di righe della tabella departments
+SELECT COUNT(*) FROM departments;
+
+-- Mostra il numero di righe della tabella departments
+-- il cui valore di dept_name contiene 'en'.
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+-- Un JOIN tra più tabelle: la tabella titles contiene gli
+-- incarichi lavorativi associati ad un certo numero di impiegato.
+-- Con il JOIN utilizziamo il numero di impiegato per ottenere
+-- le informazioni ad esso associate nella tabella employees.
+-- (Inoltre selezioniamo solo le prime 10 righe)
+
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- Mostra tutte le tabelle di tutti i database.
+-- Spesso le implementazioni forniscono degli shortcut per questo comando
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- Crea una tabella tablename1, con due colonne, per il database in uso.
+-- Per le colonne specifichiamo il tipo di dato (stringa di max 20 caratteri)
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- Inserisce una riga nella tabella tablename1. I valori devono essere
+-- appropriati per la definizione della tabella
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+-- In tablename1, modifica il valore di fname a 'John'
+-- in tutte le righe che hanno come lname 'Mutt'.
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+-- Elimina tutte le righe di tablename1
+-- il cui lname inizia per 'M'.
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- Elimina tutte le righe della tabella tablename1
+DELETE FROM tablename1;
+
+-- Elimina la tabella tablename1
+DROP TABLE tablename1;
+```
diff --git a/it-it/zfs-it.html.markdown b/it-it/zfs-it.html.markdown
new file mode 100644
index 00000000..c1307e67
--- /dev/null
+++ b/it-it/zfs-it.html.markdown
@@ -0,0 +1,361 @@
+---
+category: tool
+tool: zfs
+contributors:
+ - ["sarlalian", "http://github.com/sarlalian"]
+translators:
+ - ["Christian Grasso","https://grasso.io"]
+filename: LearnZfs-it.txt
+lang: it-it
+---
+
+
+[ZFS](http://open-zfs.org/wiki/Main_Page) è un sistema di storage che combina file system
+tradizionali e volume manager in un unico strumento. ZFS utilizza della terminologia
+specifica, diversa da quella usata da altri sistemi di storage, ma le sue funzioni lo
+rendono un ottimo tool per gli amministratori di sistema.
+
+
+## Concetti base di ZFS
+
+### Virtual Device
+
+Un VDEV è simile a un dispositivo gestito da una scheda RAID. Esistono diversi tipi di
+VDEV che offrono diversi vantaggi, tra cui ridondanza e velocità. In generale,
+i VDEV offrono una maggiore affidabilità rispetto alle schede RAID. Si sconsiglia di
+utilizzare ZFS insieme a RAID, poichè ZFS è fatto per gestire direttamente i dischi fisici.
+
+Tipi di VDEV:
+
+* stripe (disco singolo, senza ridondanza)
+* mirror (mirror su più dischi)
+* raidz
+ * raidz1 (parity a 1 disco, simile a RAID 5)
+ * raidz2 (parity a 2 dischi, simile a RAID 6)
+ * raidz3 (parity a 3 dischi)
+* disk
+* file (non consigliato in production poichè aggiunge un ulteriore filesystem)
+
+I dati vengono distribuiti tra tutti i VDEV presenti nella Storage Pool, per cui un maggior
+numero di VDEV aumenta le operazioni al secondo (IOPS).
+
+### Storage Pool
+
+Le Storage Pool di ZFS sono un'astrazione del livello inferiore (VDEV) e consentono di
+separare il filesystem visibile agli utenti dal layout reale dei dischi.
+
+### Dataset
+
+I dataset sono simili ai filesystem tradizionali, ma con molte più funzioni che rendono
+vantaggioso l'utilizzo di ZFS. I dataset supportano il [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write)
+gli snapshot, la gestione delle quota, compressione e deduplicazione.
+
+
+### Limiti
+
+Una directory può contenere fino a 2^48 file, ognuno dei quali di 16 exabyte.
+Una storage pool può contenere fino a 256 zettabyte (2^78), e può essere distribuita
+tra 2^64 dispositivi. Un singolo host può avere fino a 2^64 storage pool.
+
+
+## Comandi
+
+### Storage Pool
+
+Azioni:
+
+* List (lista delle pool)
+* Status (stato)
+* Destroy (rimozione)
+* Get/Set (lettura/modifica proprietà)
+
+Lista delle zpool
+
+```bash
+# Crea una zpool raidz
+$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+
+# Lista delle zpool
+$ zpool list
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+
+# Informazioni dettagliate su una zpool
+$ zpool list -v zroot
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75%
+```
+
+Stato delle zpool
+
+```bash
+# Informazioni sullo stato delle zpool
+$ zpool status
+ pool: zroot
+ state: ONLINE
+ scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+
+# "Scrubbing" (correzione degli errori)
+$ zpool scrub zroot
+$ zpool status -v zroot
+ pool: zroot
+ state: ONLINE
+ scan: scrub in progress since Thu Oct 15 16:59:14 2015
+ 39.1M scanned out of 106G at 1.45M/s, 20h47m to go
+ 0 repaired, 0.04% done
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+```
+
+Proprietà delle zpool
+
+```bash
+
+# Proprietà di una zpool (gestite dal sistema o dall'utente)
+$ zpool get all zroot
+NAME PROPERTY VALUE SOURCE
+zroot size 141G -
+zroot capacity 75% -
+zroot altroot - default
+zroot health ONLINE -
+...
+
+# Modifica di una proprietà
+$ zpool set comment="Dati" zroot
+$ zpool get comment
+NAME PROPERTY VALUE SOURCE
+tank comment - default
+zroot comment Dati local
+```
+
+Rimozione di una zpool
+
+```bash
+$ zpool destroy test
+```
+
+
+### Dataset
+
+Azioni:
+
+* Create
+* List
+* Rename
+* Delete
+* Get/Set (proprietà)
+
+Creazione dataset
+
+```bash
+# Crea un dataset
+$ zfs create tank/root/data
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+
+# Crea un sottodataset
+$ zfs create tank/root/data/stuff
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+
+
+# Crea un volume
+$ zfs create -V zroot/win_vm
+$ zfs list zroot/win_vm
+NAME USED AVAIL REFER MOUNTPOINT
+tank/win_vm 4.13G 17.9G 64K -
+```
+
+Lista dei dataset
+
+```bash
+# Lista dei dataset
+$ zfs list
+NAME USED AVAIL REFER MOUNTPOINT
+zroot 106G 30.8G 144K none
+zroot/ROOT 18.5G 30.8G 144K none
+zroot/ROOT/10.1 8K 30.8G 9.63G /
+zroot/ROOT/default 18.5G 30.8G 11.2G /
+zroot/backup 5.23G 30.8G 144K none
+zroot/home 288K 30.8G 144K none
+...
+
+# Informazioni su un dataset
+$ zfs list zroot/home
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home 288K 30.8G 144K none
+
+# Lista degli snapshot
+$ zfs list -t snapshot
+zroot@daily-2015-10-15 0 - 144K -
+zroot/ROOT@daily-2015-10-15 0 - 144K -
+zroot/ROOT/default@daily-2015-10-15 0 - 24.2G -
+zroot/tmp@daily-2015-10-15 124K - 708M -
+zroot/usr@daily-2015-10-15 0 - 144K -
+zroot/home@daily-2015-10-15 0 - 11.9G -
+zroot/var@daily-2015-10-15 704K - 1.42G -
+zroot/var/log@daily-2015-10-15 192K - 828K -
+zroot/var/tmp@daily-2015-10-15 0 - 152K -
+```
+
+Rinominare un dataset
+
+```bash
+$ zfs rename tank/root/home tank/root/old_home
+$ zfs rename tank/root/new_home tank/root/home
+```
+
+Eliminare un dataset
+
+```bash
+# I dataset non possono essere eliminati se hanno degli snapshot
+$ zfs destroy tank/root/home
+```
+
+Lettura/modifica proprietà
+
+```bash
+# Tutte le proprietà di un dataset
+$ zfs get all zroot/usr/home │157 # Create Volume
+NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm
+zroot/home type filesystem - │159 $ zfs list zroot/win_vm
+zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT
+zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K -
+zroot/home available 94.1G - │162 ```
+zroot/home referenced 11.9G - │163
+zroot/home mounted yes -
+...
+
+# Proprietà specifica
+$ zfs get compression zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home compression off default
+
+# Modifica di una proprietà
+$ zfs set compression=gzip-9 mypool/lamb
+
+# Specifiche proprietà per tutti i dataset
+$ zfs list -o name,quota,reservation
+NAME QUOTA RESERV
+zroot none none
+zroot/ROOT none none
+zroot/ROOT/default none none
+zroot/tmp none none
+zroot/usr none none
+zroot/home none none
+zroot/var none none
+...
+```
+
+
+### Snapshot
+
+Gli snapshot sono una delle funzioni più importanti di ZFS:
+
+* Lo spazio occupato è la differenza tra il filesystem e l'ultimo snapshot
+* Il tempo di creazione è di pochi secondi
+* Possono essere ripristinati alla velocità di scrittura del disco
+* Possono essere automatizzati molto semplicemente
+
+Azioni:
+
+* Create
+* Delete
+* Rename
+* Access
+* Send / Receive
+* Clone
+
+
+Creazione di uno snapshot
+
+```bash
+# Crea uno snapshot di un singolo dataset
+zfs snapshot tank/home/sarlalian@now
+
+# Crea uno snapshot di un dataset e dei suoi sottodataset
+$ zfs snapshot -r tank/home@now
+$ zfs list -t snapshot
+NAME USED AVAIL REFER MOUNTPOINT
+tank/home@now 0 - 26K -
+tank/home/sarlalian@now 0 - 259M -
+tank/home/alice@now 0 - 156M -
+tank/home/bob@now 0 - 156M -
+...
+```
+
+Eliminazione di uno snapshot
+
+```bash
+# Elimina uno snapshot
+$ zfs destroy tank/home/sarlalian@now
+
+# Elimina uno snapshot ricorsivamente
+$ zfs destroy -r tank/home/sarlalian@now
+
+```
+
+Rinominare uno snapshot
+
+```bash
+$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today
+$ zfs rename tank/home/sarlalian@now today
+
+$ zfs rename -r tank/home@now @yesterday
+```
+
+Accedere ad uno snapshot
+
+```bash
+# Utilizzare il comando cd come per una directory
+$ cd /home/.zfs/snapshot/
+```
+
+Invio e ricezione
+
+```bash
+# Backup di uno snapshot su un file
+$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz
+
+# Invia uno snapshot ad un altro dataset
+$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian
+
+# Invia uno snapshot ad un host remoto
+$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian'
+
+# Invia l'intero dataset e i suoi snapshot ad un host remoto
+$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home'
+```
+
+Clonare gli snapshot
+
+```bash
+# Clona uno snapshot
+$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new
+
+# Rende il clone indipendente dallo snapshot originale
+$ zfs promote tank/home/sarlalian_new
+```
+
+### Letture aggiuntive (in inglese)
+
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html)
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html)
+* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning)
+* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide)
diff --git a/janet.html.markdown b/janet.html.markdown
new file mode 100644
index 00000000..ec53b018
--- /dev/null
+++ b/janet.html.markdown
@@ -0,0 +1,328 @@
+---
+language: Janet
+filename: learnJanet.janet
+contributors:
+ - ["John Gabriele", "http://www.unexpected-vortices.com/"]
+---
+
+[Janet](https://janet-lang.org/) is a Lisp-like (Clojure-like),
+lexically-scoped, dynamically-typed, garbage-collected, C-based, high-level
+language. The entire language (core library, interpreter, compiler, assembler,
+PEG) is about 300-500 kB and should run on many constrained systems.
+
+I encourage you to try out the code snippets below in the Janet
+repl (either by [installing Janet](https://janet-lang.org/docs/index.html),
+or else by using the repl embedded in the Janet homepage).
+
+As we only have a scant *y* minutes, we'll survey the basics here and
+leave the remaining details for the manual. So please, keep your arms and
+legs inside the vehicle at all times, and on with the scenic tour!
+
+```janet
+# A comment.
+
+# Some literal values.
+true
+false
+nil
+
+# Typical style for symbols (identifiers-for / names-of things).
+do-stuff
+pants-on-fire!
+foo->bar # Evidently for converting foos to bars.
+fully-charged?
+_ # Usually used as a dummy variable.
+
+# Keywords are like symbols that start with a colon, are treated like
+# constants, and are typically used as map keys or pieces of syntax in
+# macros.
+:a
+:some-val
+
+# Numbers #####################################################################
+5
+1e3 # => 1000
+1_000 # => 1000
+2e-03 # => 0.002
+0xff # => 255
+
+# You can specify a radix (base) like so:
+16rff # => 255 (same as 0xff)
+2r1101 # => 13
+
+# Some numbers in the math library:
+math/pi # => 3.14159
+math/e # => 2.71828
+
+# Strings #####################################################################
+"hello"
+"hey\tthere" # contains a tab
+
+# For multi-line strings, use one or more backticks. No escapes allowed.
+``a long
+multi-line
+string`` # => "a long\nmulti-line\nstring"
+
+# Strings and data structures in Janet come in two varieties: mutable and
+# immutable. The literal for the mutable variety is written with a `@` in
+# front of it.
+
+# A mutable string (aka "buffer").
+@"this"
+@`a multi-line
+one here`
+
+(string "con" "cat" "enate") # => "concatenate"
+
+# To get a substring:
+(string/slice "abcdefgh" 2 5) # => "cde"
+# To find a substring:
+(string/find "de" "abcdefgh") # => 3
+
+# See the string library for more (splitting, replacement, etc.)
+
+# Arrays and Tuples ###########################################################
+# Arrays are mutable, tuples are immutable.
+
+# Arrays (mutable)
+@(4 5 6)
+@[4 5 6]
+
+# Tuples (immutable)
+# Note that an open paren usually indicates a function call, so if you want a
+# literal tuple with parens, you need to "quote" it (with a starting single
+# quote mark).
+'(4 5 6)
+[4 5 6] # ... or just use square brackets.
+
+# Tables and Structs (AKA: "maps", "hashmaps", "dictionaries")
+@{:a 1 :b 2 :c 3} # table (mutable)
+{:a 1 :b 2 :c 3} # struct (immutable)
+
+# More about how to work with arrays/tuples and tables/structs below.
+
+# Bindings ####################################################################
+# ... or "Name Some Things!" (that is, bind a value to a symbol)
+(def x 4.7) # Define a constant, `x`.
+x # => 4.7
+(quote x) # => x (the symbol x)
+'x # => x (the symbol x (shorthand))
+(print x) # prints 4.7
+
+# Since we used `def`, can't change to what `x` refers:
+(set x 5.6) # Error, `x` is a constant.
+
+(var y 10)
+(set y 12) # Works, since `y` was made var.
+
+# Note that bindings are local to the scope they're called in. `let`
+# creates a local scope and makes some bindings all in one shot:
+(let [a 2
+ b 3]
+ (print "Hello from inside this local scope.")
+ (* a b)) # => 6
+
+# Destructuring is supported, both for arrays/tuples ...
+(def a ["foos" "bars" "moos"])
+(let [[s1 _ s2] a]
+ (print s1 s2)) # foosmoos
+
+# ... and for tables/structs.
+(def t {:a "ayy" :b "bee" :c "sea"})
+(let [{:a a :b b} t]
+ (print a b)) # ayybee
+
+# You can even destructure right in a `def`:
+(def [aa1 aa2] a)
+aa1 # => foos
+aa2 # => bars
+
+(def {:c body-of-water :b insect-friend} t)
+body-of-water # => sea
+insect-friend # => bee
+
+# Note that keywords evaluate to themselves, whereas symbols evaluate
+# to whatever value they're bound to (unless you quote them).
+
+# Operators ###################################################################
+# Janet supports the usual ensemble of operators.
+# +, -, *, /, and so on. Note:
+(/ 5 3) # => 1.66667
+(% 5 3) # => 2 (remainder)
+(- 5) # => -5 (or you can just write `-5`)
+
+(++ i) # increments
+(-- i) # decrements
+(+= i 3) # add 3 to `i`
+(*= i 3) # triple `i`
+# ... and so on for the other operations on numbers.
+
+# Comparison
+# = < > not= <= >=
+(< 2 7 12) # => true
+
+# Functions ###################################################################
+# Call them:
+(- 5 3) # => 2 (Yes, operators and functions work the same.)
+(math/sin (/ math/pi 2)) # => 1
+(range 5) # => @[0 1 2 3 4]
+
+# Create them:
+(defn mult-by-2
+ ``First line of docstring.
+
+ Some more of the docstring.
+
+ Possibly more!``
+ [x]
+ (print "Hi.")
+ (print "Will compute using: " x)
+ (* 2 x))
+
+(print (mult-by-2 6)) # => 12 (after printing "Hi" and so forth)
+
+# If you have a function named "main" in your file, `janet` will automatically
+# call it for you when you run the file.
+
+# Interactively read a function's docs from within the repl:
+(doc mult-by-2)
+
+# Note, functions have to be defined before they can be used in a function,
+# so if you design top-down, you'll need to write your functions from the
+# bottom of the file up.
+
+# You can make anonymous functions as well:
+(fn [x] (+ x x))
+(fn my-func [x] (+ x x)) # This one's less anonymous.
+
+# Use `do` to make some side-effecting calls and then evaluate to
+# the last form in the `do`:
+(def n (do
+ (print "hi")
+ (do-some-side-effecting 42)
+ 3))
+n # => 3
+
+# You might say that function bodies provide an "implicit do".
+
+# Operations on data structures ###############################################
+# (Making all these mutable so we can ... mutate them.)
+(def s @"Hello, World!")
+(def a @[:a :b :c :d :e])
+(def t @{:a 1 :b 2})
+
+(length s) # => 13
+(length a) # => 5
+(length t) # => 2
+
+# Getting values:
+(s 7) # => 87 (which is the code point for "W")
+(a 1) # => :b
+(t :a) # => 1
+(keys t) # => @[:a :b]
+(values t) # => @[1 2]
+
+# Changing values (for mutable data structures):
+(put s 2 87) # @"HeWlo, World!"
+(put a 2 :x) # @[:a :b :x :d :e]
+(put t :b 42) # @{:a 1 :b 42}
+
+# Adding & removing values (again, for mutable data structures):
+(buffer/push-string s "??") # @"HeWlo, World!??"
+(array/push a :f) # @[:a :b :x :d :e :f]
+(array/pop a) # => :f, and it's also removed from `a`.
+(put t :x 88) # @{:a 1 :b 42 :x 88}
+
+# See the manual for a wide variety of functions for working with
+# buffers/strings, arrays/tuples, and tables/struct.
+
+# Flow control ################################################################
+(if some-condition
+ 42
+ 38)
+
+# Only `nil` and `false` are falsey. Everything else is truthy.
+
+(if got-it?
+ 71) # No false-branch value. Returns `nil` if `got-it?` is falsey.
+
+(var i 10)
+(while (pos? i)
+ (print "... " i)
+ (-- i))
+# Now `i` is 0.
+
+# `case` compares the dispatch value to each of the options.
+(var x 2)
+(case x
+ 1 "won"
+ 2 "too"
+ 3 "tree"
+ "unknown") # => "too"
+
+# `cond` evaluates conditions until it gets a `true`.
+(set x 8)
+(cond
+ (= x 1) "won"
+ (= x 2) "too"
+ (< x 10) "tree"
+ "oof!") # => "tree"
+
+(when (avoided-wipeout?)
+ (do-side-effecty-thing 88)
+ (smell-the-roses)
+ (paint-fencepost-error))
+
+# Pattern matching.
+# `match` is like a high-powered switch expression. If you switch on a data
+# structure, it can look inside to try and match on its contents. For example,
+# matching on a table or struct:
+(def t {:a 1 :b 2 :c 3})
+(match t
+ {:yar v} (print "matches key :yar! " v)
+ {:moo v} (print "matches key :moo! " v)
+ {:c v} (print "matches key :c! " v)
+ _ (print "no match")) # => prints "matches key :c! 3"
+
+# Iterating ###################################################################
+# Iterate over an integer range:
+(for i 0 5
+ (print i)) # prints 0, 1, 2, 3, 4
+
+# There's also the more general `loop`:
+(loop [i :range [0 10] :when (even? i)]
+ (print i))
+
+# Loop over an array/tuple:
+(def words ["foo" "bar" "baz"])
+(each word words
+ (print word))
+
+# Loop over a table/struct:
+(def t {:a 1 :b 2})
+(eachp [k v] t # Loop over each pair in `t`.
+ (print k " --> " v))
+
+# Can also use `eachk` to loop over keys in a table or struct.
+
+# Functional programming ######################################################
+# You'll find many familiar old friends here.
+(filter even?
+ (map (fn [x]
+ (* x x))
+ (range 10))) # => @[0 4 16 36 64]
+
+(reduce + 0 (range 5)) # => 10
+
+# ...and lots more (see the API docs).
+
+# Errata ######################################################################
+(type a) # => the type of `a` (as a keyword)
+(describe a) # => a human-readable description of `a`
+(string/format "%j" a) # => Janet values, nicely-formatted
+```
+
+This tour didn't cover a number of other features such as modules, fibers,
+PEGs, macros, etc., but should give you a taste of what Janet is like. See
+the [Janet manual](https://janet-lang.org/docs/index.html) and the [Janet API
+docs](https://janet-lang.org/api/index.html) for more info.
diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown
new file mode 100644
index 00000000..9fe4edbe
--- /dev/null
+++ b/jsonnet.html.markdown
@@ -0,0 +1,139 @@
+---
+language: jsonnet
+filename: learnjsonnet.jsonnet
+contributors:
+ - ["Huan Wang", "https://github.com/fredwangwang"]
+---
+
+Jsonnet is a powerful templating language for JSON. Any valid JSON
+document is a valid Jsonnet object. For an interactive demo/tutorial,
+click [here](https://jsonnet.org/learning/tutorial.html)
+
+```python
+// single line comment
+
+/*
+ multiline comment
+*/
+
+# as well as python style comment
+
+# define a variable.
+# Variables have no effect in the generated JSON without being used.
+local num1 = 1;
+local num2 = 1 + 1;
+local num3 = 5 - 2;
+local num4 = 9 % 5;
+local num5 = 10 / 2.0;
+# jsonnet is a lazy language, if a variable is not used, it is not evaluated.
+local num_runtime_error = 1 / 0;
+
+# fields are valid identifiers without quotes
+local obj1 = { a: 'letter a', B: 'letter B' };
+
+local arr1 = ['a', 'b', 'c'];
+
+# string literals use " or '.
+local str1 = 'a' + 'B';
+# multiline text literal in between |||
+# Each line must start with a white space.
+local str_multiline = |||
+ this is a
+ multiline string
+|||;
+# Python-compatible string formatting is available via %
+# When combined with ||| this can be used for templating text files.
+local str_templating = |||
+ %(f1)0.3f
+||| % { f1: 1.2345678 };
+assert str_templating == '1.235\n';
+
+# if b then e else e. The else branch is optional and defaults to null
+local var1 = if 3 < 2 then "YES";
+assert var1 == null;
+
+local obj2 = {
+ # variable defined inside the object ends with ','
+ local var_in_obj = 0,
+
+ local vowels = ['a', 'e', 'i', 'o', 'u'],
+ local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+
+ # [num] to look up an array element
+ first_vowel: vowels[0],
+ # can also slice the array like in Python
+ even_numbers: numbers[1::2],
+
+ # python-style list and object comprehensions are also supported
+ double_numbers: [x * 2 for x in numbers],
+ even_numbers_map: {
+ # [ ] syntax in field name is to compute the field name dynamically
+ [x + '_is_even']: true for x in numbers if x % 2 == 0
+ },
+
+ nested: {
+ nested_field1: 'some-value',
+ # self refers to the current object
+ # ["field-name"] or .field-name can be used to look up a field
+ nested_field2: self.nested_field1,
+ nested_field3: self.nested_field1,
+ # $ refers to outer-most object
+ nested_field4: $.first_vowel,
+
+ assert self.nested_field1 == self.nested_field2,
+ assert self.nested_field1 == self.nested_field3,
+ },
+
+ special_field: 'EVERYTHING FEELS BAD',
+};
+
+local obj3 = {
+ local var_in_obj = 1.234,
+ local var_in_obj2 = { a: { b: 'c' } },
+
+ concat_array: [1, 2, 3] + [4],
+ # strings can be concat with +,
+ # which implicitly converts one operand to string if needed.
+ concat_string: '123' + 4,
+
+ # == tests deep equality
+ equals: { a: { b: 'c', d: {} } } == var_in_obj2,
+
+ special_field: 'this feels good',
+};
+
+# objects can be merged with + where the right-hand side wins field conflicts
+local obj4 = obj2 + obj3;
+assert obj4.special_field == 'this feels good';
+
+# define a function
+# functions have positional parameters, named parameters, and default arguments
+local my_function(x, y, z=1) = x + y - z;
+local num6 = my_function(7, 8, 9);
+local num7 = my_function(8, z=10, y=9);
+local num8 = my_function(4, 5);
+# inline anonymous function
+local num9 = (function(x) x * x)(3);
+
+local obj5 = {
+ # define a method
+ # fields defined with :: are hidden, which does not apper in generated JSON
+ # function cannot be serialized so need to be hidden
+ # if the object is used in the generated JSON.
+ is_odd(x):: x % 2 == 1,
+};
+assert obj5 == {};
+
+# a jsonnet doucment have to evaluate to something
+# be it an object, list, number or just string literal
+"FIN"
+
+```
+
+## Further Reading
+There are a few but important concepts that are not touched in this exmaple, including:
+
+- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config)
+- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports)
+- In depth example of OOP aspect of Jsonnet: [Object-Orientation](https://jsonnet.org/learning/tutorial.html#Object-Orientation)
+- Useful standard library: [Stdlib](https://jsonnet.org/ref/stdlib.html)
diff --git a/ko-kr/vim-kr.html.markdown b/ko-kr/vim-kr.html.markdown
index cd0fa236..76063143 100644
--- a/ko-kr/vim-kr.html.markdown
+++ b/ko-kr/vim-kr.html.markdown
@@ -5,12 +5,13 @@ contributors:
- ["RadhikaG", "https://github.com/RadhikaG"]
translators:
- ["Wooseop Kim", "https://github.com/linterpreteur"]
+ - ["Yeongjae Jang", "https://github.com/Liberatedwinner"]
filename: LearnVim-kr.txt
lang: ko-kr
---
[Vim](http://www.vim.org)
-(Vi IMproved)은 유닉스의 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
+(Vi IMproved)은 유닉스에서 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
설계된 텍스트 에디터로, 대부분의 유닉스 기반 시스템에 내장되어 있습니다. 다양한 단축 키를 통해
파일 안에서 빠르게 이동하고 편집할 수 있습니다.
@@ -18,19 +19,21 @@ lang: ko-kr
```
vim <filename> # vim으로 <filename> 열기
+ :help <topic> # (존재하는 경우에) <topic>에 대한, 내장된 도움말 문서 열기
:q # vim 종료
:w # 현재 파일 저장
:wq # 파일 저장 후 종료
+ ZZ # 파일 저장 후 종료
:q! # 저장하지 않고 종료
# ! *강제로* :q를 실행하여, 저장 없이 종료
- :x # 파일 저장 후 종료 (짧은 :wq)
+ :x # 파일 저장 후 종료 (:wq의 축약)
u # 동작 취소
CTRL+R # 되돌리기
h # 한 글자 왼쪽으로 이동
- j # 아래로 한 줄 이동
- k # 위로 한 줄 이동
+ j # 한 줄 아래로 이동
+ k # 한 줄 위로 이동
l # 한 글자 오른쪽으로 이동
# 줄 안에서의 이동
@@ -38,6 +41,11 @@ lang: ko-kr
0 # 줄 시작으로 이동
$ # 줄 끝으로 이동
^ # 줄의 공백이 아닌 첫 문자로 이동
+
+ Ctrl+B # 한 화면 뒤로 이동
+ Ctrl+F # 한 화면 앞으로 이동
+ Ctrl+D # 반 화면 앞으로 이동
+ Ctrl+U # 반 화면 뒤로 이동
# 텍스트 검색
@@ -48,6 +56,8 @@ lang: ko-kr
:%s/foo/bar/g # 파일 모든 줄에 있는 'foo'를 'bar'로 치환
:s/foo/bar/g # 현재 줄에 있는 'foo'를 'bar'로 치환
+ :%s/foo/bar/gc # 사용자에게 확인을 요구하는, 모든 줄에 있는 'foo'를 'bar'로 치환
+ :%s/\n/\r/g # 한 종류의 개행 문자에서 다른 종류의 것으로 치환 (\n에서 \r로)
# 문자로 이동
@@ -74,14 +84,22 @@ lang: ko-kr
L # 화면 바닥으로 이동
```
+## 도움말 문서
+
+Vim은 `:help <topic>` 명령을 통해 접근할 수 있는 도움말 문서를 내장하고 있습니다.
+예를 들어, `:help navigation` 은 당신의 작업 공간을 탐색하는 방법에 대한 문서를 표시합니다!
+
+`:help`는 옵션 없이도 사용할 수 있습니다. 이는 기본 도움말 대화 상자를 표시합니다.
+이 대화 상자는 Vim을 시작하는 것이 보다 용이하도록 도와줍니다.
+
## 모드
Vim은 **모드**의 개념에 기초를 두고 있습니다.
-명령어 모드 - vim을 시작하면 처음에 이 모드입니다. 이동과 명령어 입력에 사용합니다.
-삽입 모드 - 파일을 수정합니다.
-비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
-실행 모드 - ':' 이후 명령어를 입력합니다.
+- 명령어 모드 - vim은 이 모드로 시작됩니다. 이동과 명령어 입력에 사용합니다.
+- 삽입 모드 - 파일을 수정합니다.
+- 비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
+- 실행 모드 - ':' 이후 명령어를 입력합니다.
```
i # 커서 위치 앞에서 삽입 모드로 변경
@@ -97,11 +115,11 @@ Vim은 **모드**의 개념에 기초를 두고 있습니다.
d # 선택한 객체 삭제
dd # 현재 줄 삭제
p # 커서 위치 뒤에 복사한 텍스트 붙여넣기
- P # 커서 위치 뒤에 복사한 텍스트 붙여넣기
+ P # 커서 위치 앞에 복사한 텍스트 붙여넣기
x # 현재 커서 위치의 문자 삭제
```
-## vim의 문법
+## vim의 '문법'
Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니다.
@@ -134,7 +152,7 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
w # 단어를
s # 문장을
p # 문단을
- b # 블락을
+ b # 블록을
# 예시 '문장' (명령어)
@@ -157,6 +175,22 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
ddp # 이어지는 줄과 위치 맞바꾸기 (dd 후 p)
. # 이전 동작 반복
:w !sudo tee % # 현재 파일을 루트 권한으로 저장
+ :set syntax=c # 문법 강조를 'C'의 것으로 설정
+ :sort # 모든 줄을 정렬
+ :sort! # 모든 줄을 역순으로 정렬
+ :sort u # 모든 줄을 정렬하고, 중복되는 것을 삭제
+ ~ # 선택된 텍스트의 대/소문자 토글
+ u # 선택된 텍스트를 소문자로 바꾸기
+ U # 선택된 텍스트를 대문자로 바꾸기
+
+ # 텍스트 폴딩
+ zf # 선택된 텍스트 위치에서 폴딩 만들기
+ zo # 현재 폴딩 펴기
+ zc # 현재 폴딩 접기
+ zR # 모든 폴딩 펴기
+ zM # 모든 폴딩 접기
+ zi # 폴딩 접기/펴기 토글
+ zd # 접은 폴딩 삭제
```
## 매크로
diff --git a/lbstanza.html.markdown b/lbstanza.html.markdown
new file mode 100644
index 00000000..19dc7db7
--- /dev/null
+++ b/lbstanza.html.markdown
@@ -0,0 +1,282 @@
+---
+language: LB Stanza
+filename: learn-stanza.stanza
+contributors:
+ - ["Mike Hilgendorf", "https://github.com/m-hilgendorf"]
+---
+
+LB Stanza (or Stanza for short) is a new optionally-typed general purpose programming language from the University of California, Berkeley. Stanza was designed to help programmers tackle the complexity of architecting large programs and significantly increase the productivity of application programmers across the entire software development life cycle.
+
+
+```stanza
+; this is a comment
+;<A>
+This is a block comment
+ ;<B>
+ block comments can be nested with optional tags.
+ ;<B>
+;<A>
+defpackage learn-stanza-in-y:
+ import core
+ import collections
+
+;==============================================================================
+; The basics, things you'd find in most programming languages
+;==============================================================================
+
+
+; Variables can be mutable (var) or immutable (val)
+val immutable = "this string can't be changed"
+var mutable = "this one can be"
+mutable = "like this"
+
+; The basic data types (annotations are optional)
+val an-int: Int = 12345
+val a-long: Long = 12345L
+val a-float: Float = 1.2345f
+val a-double: Double = 3.14159
+val a-string: String = "this is a string"
+val a-multiline-string = \<tag>
+ this is a "raw" string literal
+\<tag>
+
+; Print a formatted string with println and "..." % [...]
+println("this is a formatted string %_ %_" % [mutable, immutable])
+
+; Stanza is optionally typed, and has a ? (any) type.
+var anything:? = 0
+anything = 3.14159
+anything = "a string"
+
+; Stanza has basic collections like Tuples, Arrays, Vectors and HashTables
+val tuple: Tuple<?> = [mutable, immutable]
+
+val array = Array<?>(3)
+array[0] = "string"
+array[1] = 1
+array[2] = 1.23455
+; array[3] = "out-of-bounds" ; arrays are bounds-checked
+
+val vector = Vector<?>()
+vector[0] = "string"
+vector[1] = 1
+vector[2] = 3.14159
+
+val hash-table = HashTable<String, ?>()
+hash-table["0"] = 0
+hash-table["1"] = 1
+hash-table["2"] = 1
+
+
+;==============================================================================
+; Functions
+;==============================================================================
+; Functions are declared with the `defn` keyword
+defn my-function (arg:?) : ; note the space between identifier and arg list
+ println("called my-function with %_" % [arg])
+
+my-function("arg") ; note the lack of a space to call the function
+
+; Functions can be declared inside another function and capture variables from
+; the surrounding environment.
+defn outer (arg):
+ defn inner ():
+ println("outer had arg: %_" % [arg])
+ inner()
+
+outer("something")
+
+; functions are "first-class" in stanza, meaning you can assign variables
+; to functions and pass functions as arguments to other functions.
+val a-function = outer
+defn do-n-times (arg, func, n:Int):
+ for i in 0 to n do :
+ func(arg)
+do-n-times("argument", a-function, 3)
+
+; sometimes you want to define a function inline, or use an anonymous function.
+; for this you can use the syntax:
+; fn (args):
+; ...
+do-n-times("hello", fn (arg): println(arg), 2)
+
+; there is a shorthand for writing anonymous functions
+do-n-times("hello", { println(_) }, 2)
+
+; the short hand works for multiple arguments as well.
+val multi-lambda = { println(_ + 2 * _) }
+multi-lambda(1, 2)
+
+;==============================================================================
+; User defined types
+;==============================================================================
+; Structs are declared with the `defstruct` keyword
+defstruct MyStruct:
+ field
+
+; constructors are derived automatically
+val my-struct = MyStruct("field:value")
+
+; fields are accessed using function-call syntax
+println(field(my-struct))
+
+; Stanza supports subtyping with a "multimethod" system based on method
+; overloading.
+deftype MyType
+defmulti a-method (m:MyType)
+
+defstruct Foo <: MyType
+defstruct Bar <: MyType
+defmethod a-method (a-foo: Foo):
+ println("called a-method on a Foo")
+
+defmethod a-method (a-foo: Bar):
+ println("called a-method on a Bar")
+
+;==============================================================================
+; The Type System
+;==============================================================================
+; True and Falseare types with a single value.
+val a-true: True = true
+val a-false: False = false
+
+; You can declare a union type, or a value that is one of a set of types
+val a-boolean: True|False = true
+val another-boolean: True|False = false
+
+; You can pattern match on types
+match(a-boolean):
+ (t:True): println("is true")
+ (f:False): println("is false")
+
+; You can match against a single possible type
+match(a-boolean:True):
+ println("is still true")
+else:
+ println("is not true")
+
+; You can compose program logic around the type of a variable
+if anything is Float :
+ println("anything is a float")
+else if anything is-not String :
+ println("anything is not an int")
+else :
+ println("I don't know what anything is")
+
+;==============================================================================
+; Control Flow
+;==============================================================================
+; stanza has the standard basic control flow
+val condition = [false, false]
+if condition[0] :
+ ; do something
+ false
+else if condition[1] :
+ ; do another thing
+ false
+else :
+ ; whatever else
+ false
+
+; there is also a switch statement, which can be used to pattern match
+; on values (as opposed to types)
+switch(anything):
+ "this": false
+ "that": false
+ "the-other-thing": false
+ else: false
+
+; for and while loops are supported
+while condition[0]:
+ println("do stuff")
+
+for i in 0 to 10 do:
+ vector[i] = i
+
+; stanza also supports named labels which can functin as break or return
+; statements
+defn another-fn ():
+ label<False> return:
+ label<False> break:
+ while true:
+ if condition[0] is False:
+ break(false)
+ return(false)
+
+; For a comprehensive guide on Stanza's advanced control flow, check out
+; this page: http://lbstanza.org/chapter9.html from Stanza-by-Example
+
+;==============================================================================
+; Sequences
+;==============================================================================
+; for "loops" are sugar for a more powerful syntax.
+val xs = [1, 2, 3]
+val ys = ['a', 'b', 'c']
+val zs = ["foo", "bar", "baz"]
+
+for (x in xs, y in ys, z in zs) do :
+ println("x:%_, y:%_, z:%_" % [x, y, z])
+
+
+;xs, ys, and zs are all "Seqable" meaing they are Seq types (sequences).
+; the `do` identifier is a special function that just applies the body of
+; the for loop to each element of the sequence.
+;
+; A common sequence task is concatenating sequences. This is accomplished
+; using the `seq-cat` function. This is analogous to "flattening" iterateors
+val concat = to-tuple $
+ for sequence in [xs, ys, zs] seq-cat:
+ sequence
+
+; we can also use a variation to interleave the elements of multiple sequences
+val interleaved = to-tuple $
+ for (x in xs, y in ys, z in zs) seq-cat :
+ [x, y, z]
+
+println("[%,] [%,]" % [concat, interleaved])
+
+; Another common task is mapping a sequence to another, for example multiplying
+; all the elements of a list of numbers by a constant. To do this we use `seq`.
+var numbers = [1.0, 2.0, 3.0, 4.0]
+numbers = to-tuple $
+ for n in numbers seq :
+ 2.0 * n
+println("%," % [numbers])
+
+if find({_ == 2.0}, numbers) is-not False :
+ println("found it!")
+
+; or maybe we just want to know if there's something in a sequence
+var is-there =
+ for n in numbers any? :
+ n == 2.0
+
+; since this is "syntactic sugar" we can write it explicitly using an
+; anonymous function
+is-there = any?({_ == 2.0}, numbers)
+
+; a detailed reference of the sequence library and various adaptors can
+; be found here: http://lbstanza.org/reference.html#anchor439
+
+
+=========================================================================
+; Documentation
+;=========================================================================
+;
+; Top level statements can be prefixed with the "doc" field which takes
+; a string value and is used to autogenerate documentation for the package.
+doc: \<doc>
+ # Document Strings
+
+ ```stanza
+ val you-can = "include code snippets, too"
+ ```
+
+ To render documentation as markdown (compatible with mdbook)
+
+ ```bash
+ stanza doc source.stanza -o docs
+ ```
+\<doc>
+defn docfn () : false
+``` \ No newline at end of file
diff --git a/ldpl.html.markdown b/ldpl.html.markdown
index cc95f5fb..86603d94 100644
--- a/ldpl.html.markdown
+++ b/ldpl.html.markdown
@@ -165,19 +165,6 @@ display myNumber crlf
exit
```
-## Topics Not Covered
-
- * [Command line arguments](https://docs.ldpl-lang.org/variables-in-ldpl/command-line-arguments)
- * [Error variables](https://docs.ldpl-lang.org/variables-in-ldpl/errorcode-and-errortext)
- * [Import other files](https://docs.ldpl-lang.org/structure-of-ldpl-source-code/importing-other-sources)
- * [Identifier naming schemes](https://docs.ldpl-lang.org/naming-rules)
- * [Text Statements](https://docs.ldpl-lang.org/text-statements/join-and-in)
- * [List Statements](https://docs.ldpl-lang.org/list-statements/push-to)
- * [Map Statements](https://docs.ldpl-lang.org/vector-statements/clear)
- * [File loading / writing](https://docs.ldpl-lang.org/i-o-statements/load-file-in)
- * [Executing commands](https://docs.ldpl-lang.org/i-o-statements/execute)
- * [Extending LDPL with C++](https://docs.ldpl-lang.org/extensions/c++-extensions)
-
## Further Reading
* [LDPL Docs](https://docs.ldpl-lang.org)
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 5790bcc6..4ca31857 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -234,7 +234,7 @@ A' % Concise version of complex transpose
% On their own, the arithmetic operators act on whole matrices. When preceded
% by a period, they act on each element instead. For example:
A * B % Matrix multiplication
-A .* B % Multiple each element in A by its corresponding element in B
+A .* B % Multiply each element in A by its corresponding element in B
% There are several pairs of functions, where one acts on each element, and
% the other (whose name ends in m) acts on the whole matrix.
diff --git a/mips.html.markdown b/mips.html.markdown
index 7f759bec..33d4f87c 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -209,7 +209,7 @@ gateways and routers.
## LOOPS ##
_loops:
# The basic structure of loops is having an exit condition and a jump
- instruction to continue its execution
+ # instruction to continue its execution
li $t0, 0
while:
bgt $t0, 10, end_while # While $t0 is less than 10,
diff --git a/moonscript.html.markdown b/moonscript.html.markdown
index 941578e7..193d7f97 100644
--- a/moonscript.html.markdown
+++ b/moonscript.html.markdown
@@ -192,7 +192,7 @@ items = {1, 2, 3, 4}
doubled = [item * 2 for item in *items]
-- Uses `when` to determine if a value should be included.
-slice = [item for item in *items when i > 1 and i < 3]
+slice = [item for item in *items when item > 1 and item < 3]
-- `for` clauses inside of list comprehensions can be chained.
diff --git a/nim.html.markdown b/nim.html.markdown
index 1e17d8f0..9730e579 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -28,7 +28,7 @@ Or for unparsable, broken code
var # Declare (and assign) variables,
letter: char = 'n' # with or without type annotations
lang = "N" & "im"
- nLength : int = len(lang)
+ nLength: int = len(lang)
boat: float
truth: bool = false
diff --git a/nix.html.markdown b/nix.html.markdown
index 5941f0e6..dde5dbec 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -279,7 +279,7 @@ with builtins; [
#=> 7
# This first line of tutorial starts with "with builtins;"
- # because builtins is a set the contains all of the built-in
+ # because builtins is a set that contains all of the built-in
# functions (length, head, tail, filter, etc.). This saves
# us from having to write, for example, "builtins.length"
# instead of just "length".
diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown
index 906112ff..d243802d 100644
--- a/nl-nl/json-nl.html.markdown
+++ b/nl-nl/json-nl.html.markdown
@@ -5,26 +5,27 @@ contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["himanshu", "https://github.com/himanshu81494"]
+ - ["Maarten Jacobs", "https://github.com/maartenJacobs"]
translators:
- ["Niels van Velzen", "https://nielsvanvelzen.me"]
lang: nl-nl
---
-Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste
+Gezien JSON een zeer eenvouding formaat heeft zal dit één van de simpelste
Learn X in Y Minutes ooit zijn.
-JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de
+JSON heeft volgens de specificaties geen commentaar. Ondanks dat hebben de
meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.
Sommige parsers staan zelfs trailing komma's toe.
-(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object).
-Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken.
+(Een komma na het laatste element in een array of achter de laatste eigenschap van een object).
+Het is wel beter om dit soort dingen te vermijden omdat het niet in elke parser zal werken.
In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.
Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.
Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
-De extensie voor JSON bestanden is ".json". De MIME type is "application/json"
-Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD.
+De extensie voor JSON bestanden is ".json". De MIME type is "application/json".
+Enkele nadelen van JSON zijn het gebrek aan type definities en een manier van DTD.
```json
{
diff --git a/opencv.html.markdown b/opencv.html.markdown
index f8763b35..d1f7ec51 100644
--- a/opencv.html.markdown
+++ b/opencv.html.markdown
@@ -14,9 +14,9 @@ Opencv currently supports wide variety of languages like, C++, Python, Java etc
#### Installation
Please refer to these articles for installation of OpenCV on your computer.
-* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]()
-* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]()
-* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]()
+* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows)
+* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a](https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a)
+* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv](https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv)
### Here we will be focusing on python implementation of OpenCV
@@ -133,12 +133,12 @@ cv2.destroyAllWindows()
### Further Reading:
-* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]()
-* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]()
-* An up-to-date language reference can be found at [https://opencv.org]()
-* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV]()
+* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades](https://github.com/opencv/opencv/blob/master/data/haarcascades)
+* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html](https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html)
+* An up-to-date language reference can be found at [https://opencv.org](https://opencv.org)
+* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV)
* Good OpenCv Tutorials
- * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]()
- * [https://realpython.com/python-opencv-color-spaces]()
- * [https://pyimagesearch.com]()
- * [https://www.learnopencv.com]()
+ * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html)
+ * [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces)
+ * [https://pyimagesearch.com](https://pyimagesearch.com)
+ * [https://www.learnopencv.com](https://www.learnopencv.com)
diff --git a/p5.html.markdown b/p5.html.markdown
index be22d3e5..f6084b98 100644
--- a/p5.html.markdown
+++ b/p5.html.markdown
@@ -7,7 +7,7 @@ contributors:
filename: p5.js
---
-p5.js is a JavaScript library that starts with the original goal of [Processing](http://processing.org"), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
+p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.
```js
diff --git a/perl.html.markdown b/perl.html.markdown
index 08001ab0..8811dd08 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -8,9 +8,9 @@ contributors:
- ["Dan Book", "http://github.com/Grinnz"]
---
-Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
+Perl is a highly capable, feature-rich programming language with over 25 years of development.
-Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
+Perl runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
```perl
# Single line comments start with a number sign.
diff --git a/php.html.markdown b/php.html.markdown
index d4103e97..57ba29c4 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -34,6 +34,7 @@ echo "World\n"; // Prints "World" with a line break
?>
Hello World Again!
<?php
+// That is because historically PHP started as a Template engine
/************************************
@@ -41,12 +42,15 @@ Hello World Again!
*/
// Variables begin with the $ symbol.
-// A valid variable name starts with a letter or underscore,
+// A valid variable name starts with a letter or an underscore,
// followed by any number of letters, numbers, or underscores.
+// You don't have to (and cannot) declare variables.
+// Once you assign a value, PHP will create the variable with the right type.
+
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
-$boolean = false; // or FALSE or False
+$boolean = FALSE; // or false or False
// Integers
$int1 = 12; // => 12
diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown
index 3e27cc4f..43d68b05 100644
--- a/pl-pl/perl-pl.html.markdown
+++ b/pl-pl/perl-pl.html.markdown
@@ -12,10 +12,10 @@ lang: pl-pl
---
-Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
+Perl jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
z ponad 25 latami nieustannego rozwoju.
-Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w
+Perl używany jest na ponad 100 różnych platformach (od przenośnych do w
pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak
i projektów deweloperskich prowadzonych na szeroką skalę.
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 5d74024d..6efd984c 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -55,6 +55,11 @@ The tutorial starts here:
```powershell
# As you already figured, comments start with #
+<#
+ Multi-line comments
+ like so
+#>
+
# Simple hello world example:
echo Hello world!
# echo is an alias for Write-Output (=cmdlet)
@@ -68,6 +73,8 @@ $aString="Some string"
# Or like this:
$aNumber = 5 -as [double]
$aList = 1,2,3,4,5
+# Reverse an array *Note this is a mutation on the existing array
+[array]::Reverse($aList)
$anEmptyList = @()
$aString = $aList -join '--' # yes, -split exists also
$aHashtable = @{name1='val1'; name2='val2'}
@@ -100,6 +107,10 @@ echo "Bound arguments in a function, script or code block: $PSBoundParameters"
echo "Unbound arguments: $($Args -join ', ')."
# More builtins: `help about_Automatic_Variables`
+# Find the datatype of variables or properties you're working with
+$true.GetType()
+$aHashtable.name2.GetType()
+
# Inline another file (dot operator)
. .\otherScriptName.ps1
@@ -184,7 +195,7 @@ Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
# Use % as a shorthand for ForEach-Object
-(a,b,c) | ForEach-Object `
+('a','b','c') | ForEach-Object `
-Begin { "Starting"; $counter = 0 } `
-Process { "Processing $_"; $counter++ } `
-End { "Finishing: $counter" }
@@ -198,12 +209,13 @@ ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
### Functions
# The [string] attribute is optional.
-function foo([string]$name) {
+# Function names should follow Verb-Noun convention
+function Get-Foo([string]$name) {
echo "Hey $name, have a function"
}
# Calling your function
-foo "Say my name"
+Get-Foo "Say my name"
# Functions with named parameters, parameter attributes, parsable documentation
<#
@@ -283,7 +295,22 @@ Pop-Location # change back to previous working directory
# Unblock a directory after download
Get-ChildItem -Recurse | Unblock-File
+# You can also pass arguments to a Function with a hash table
+# This is called Splatting
+# Normal Command
+Export-Csv -InputObject $csv -Path 'c:\mypath' -Encoding UTF8 -NoTypeInformation
+# With Splatting
+$csvArguments = @{
+ InputObject = $csv
+ Path = 'c:\mypath'
+ Encoding = 'UTF8'
+ NoTypeInformation = $true
+}
+Export-Csv @csvArguments
+
# Open Windows Explorer in working directory
+Invoke-Item .
+# Or the alias
ii .
# Any key to exit
@@ -318,6 +345,7 @@ Interesting Projects
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
+* [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac
* [PSake](https://github.com/psake/psake) Build automation tool
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown
index 217861f9..55a10626 100644
--- a/pt-br/perl-pt.html.markdown
+++ b/pt-br/perl-pt.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: pt-br
---
-Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
+Perl é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
-Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
+Perl roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
```perl
# Comentários de uma linha começam com um sinal de número.
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
index 3d91f1ca..28df3c59 100644
--- a/pt-br/sass-pt.html.markdown
+++ b/pt-br/sass-pt.html.markdown
@@ -56,19 +56,19 @@ body {
}
-/ * Este é muito mais fácil de manter do que ter de mudar a cor
-cada vez que aparece em toda a sua folha de estilo. * /
+/* Este é muito mais fácil de manter do que ter de mudar a cor
+cada vez que aparece em toda a sua folha de estilo. */
-/*Mixins
+/* Mixins
==============================*/
-/* Se você achar que você está escrevendo o mesmo código para mais de um
-elemento, você pode querer armazenar esse código em um mixin.
+/* Se você achar que está escrevendo o mesmo código para mais de um
+elemento, você pode armazenar esse código em um mixin.
Use a diretiva '@mixin', além de um nome para o seu mixin. */
@@ -87,7 +87,7 @@ div {
background-color: $primary-color;
}
-/* Apoś compilar ficaria assim: */
+/* Após compilar ficaria assim: */
div {
display: block;
margin-left: auto;
@@ -128,7 +128,7 @@ div {
-/*Funções
+/* Funções
==============================*/
@@ -138,6 +138,7 @@ div {
/* Funções pode ser chamado usando seu nome e passando o
    argumentos necessários */
+
body {
width: round(10.25px);
}
@@ -156,14 +157,14 @@ body {
background-color: rgba(0, 0, 0, 0.75);
}
-/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
-   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
-   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
-   lógica que pode ser usado em todo o seu código Sass. Os exemplos
-   seção Operadores Math 'são candidatos ideais para se tornar um reutilizável
-   função. */
+/* Você também pode definir suas próprias funções. As funções são muito semelhantes
+ aos mixins. Ao tentar escolher entre uma função ou um mixin, lembre
+ que mixins são os melhores para gerar CSS enquanto as funções são melhores para
+ lógica que pode ser usado em todo o seu código Sass. Os exemplos na
+ seção "Operações Math" são candidatos ideais para se tornar um função
+ reutilizável. */
-/* Esta função terá um tamanho de destino eo tamanho do pai e calcular
+/* Esta função terá um tamanho de destino e o tamanho do pai (parent), calcular
   e voltar a percentagem */
@function calculate-percentage($target-size, $parent-size) {
@@ -220,21 +221,21 @@ $main-content: calculate-percentage(600px, 960px);
border-color: #22df56;
}
-/* Ampliando uma declaração CSS é preferível a criação de um mixin
-   por causa da maneira agrupa as classes que todos compartilham
+/* Ao ampliar uma declaração CSS é preferível a criação de um mixin,
+   por causa da maneira em que agrupa as classes com todos que compartilham
   o mesmo estilo base. Se isso for feito com um mixin, a largura,
   altura, e a borda seria duplicado para cada instrução que
   o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será
-   adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */
+   adicionado inchaço desnecessário para os arquivos criados pelo compilador Sass. */
-/*Assentamento
+/* Assentamento
==============================*/
-/ * Sass permite seletores ninhos dentro seletores * /
+/* Sass permite seletores ninhos dentro seletores */
ul {
list-style-type: none;
@@ -245,7 +246,7 @@ ul {
}
}
-/* '&' será substituído pelo selector pai. */
+/* '&' será substituído pelo selector pai (parent). */
/* Você também pode aninhar pseudo-classes. */
/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável.
Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação.
@@ -290,7 +291,7 @@ ul li a {
-/*Parciais e Importações
+/* Parciais e Importações
==============================*/
@@ -313,7 +314,7 @@ ol {
/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
   Isso difere da declaração CSS @import tradicional, que faz
   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
-   importadas arquivo e combina com o código compilado. */
+   arquivo importados e combina com o código compilado. */
@import 'reset';
@@ -322,7 +323,7 @@ body {
font-family: Helvetica, Arial, Sans-serif;
}
-/* Compiles to: */
+/* Compila para: */
html, body, ul, ol {
margin: 0;
@@ -336,14 +337,14 @@ body {
-/*Placeholder Selectors
+/* Placeholder Selectors
==============================*/
-/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
-   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
-   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
-   de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * /
+/* Os Placeholders são úteis na criação de uma declaração CSS para ampliar. Se você
+   deseja criar uma instrução CSS que foi usado exclusivamente com @extend,
+   você pode fazer isso usando um Placeholder. Placeholder começar com um '%' em vez
+   de '.' ou '#'. Placeholder não aparece no CSS compilado. */
%content-window {
font-size: 14px;
@@ -372,14 +373,14 @@ body {
-/*Operações Math
-============================== * /
+/* Operações Math
+============================== */
/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
-   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
-   de usar valores que você já calculados pela mão. Abaixo está um exemplo
-   de uma criação de um projeto simples de duas colunas. * /
+   ser úteis para calcular os valores diretamente no seu arquivos Sass em vez
+ de usar valores que você já calculados manualmente. O exemplo abaixo é
+ de um projeto simples de duas colunas. */
$content-area: 960px;
$main-content: 600px;
diff --git a/python.html.markdown b/python.html.markdown
index 56cb9aac..27b2b22a 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -132,7 +132,7 @@ b == a # => True, a's and b's objects are equal
"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
-"This is a string"[0] # => 'T'
+"Hello world!"[0] # => 'H'
# You can find the length of a string
len("This is a string") # => 16
@@ -186,7 +186,7 @@ some_unknown_var # Raises a NameError
# if can be used as an expression
# Equivalent of C's '?:' ternary operator
-"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+"yay!" if 0 > 1 else "nay!" # => "nay!"
# Lists store sequences
li = []
@@ -772,11 +772,11 @@ if __name__ == '__main__':
# Call the static method
print(Human.grunt()) # => "*grunt*"
-
- # Cannot call static method with instance of object
+
+ # Cannot call static method with instance of object
# because i.grunt() will automatically put "self" (the object i) as an argument
print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
+
# Update the property for this instance
i.age = 42
# Get the property
@@ -792,7 +792,7 @@ if __name__ == '__main__':
####################################################
# Inheritance allows new child classes to be defined that inherit methods and
-# variables from their parent class.
+# variables from their parent class.
# Using the Human class defined above as the base or parent class, we can
# define a child class, Superhero, which inherits the class variables like
@@ -926,7 +926,7 @@ class Batman(Superhero, Bat):
# So instead we explicitly call __init__ for all ancestors.
# The use of *args and **kwargs allows for a clean way to pass arguments,
# with each parent "peeling a layer of the onion".
- Superhero.__init__(self, 'anonymous', movie=True,
+ Superhero.__init__(self, 'anonymous', movie=True,
superpowers=['Wealthy'], *args, **kwargs)
Bat.__init__(self, *args, can_fly=False, **kwargs)
# override the value for the name attribute
@@ -941,9 +941,9 @@ if __name__ == '__main__':
# Get the Method Resolution search Order used by both getattr() and super().
# This attribute is dynamic and can be updated
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
# => <class 'bat.Bat'>, <class 'object'>)
# Calls parent method but uses its own class attribute
@@ -1040,3 +1040,5 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
diff --git a/qsharp.html.markdown b/qsharp.html.markdown
new file mode 100644
index 00000000..b256043c
--- /dev/null
+++ b/qsharp.html.markdown
@@ -0,0 +1,204 @@
+---
+language: Q#
+contributors:
+ - ["Vincent van Wingerden", "https://github.com/vivanwin"]
+ - ["Mariia Mykhailova", "https://github.com/tcNickolas"]
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
+filename: LearnQSharp.qs
+---
+
+Q# is a high-level domain-specific language which enables developers to write quantum algorithms. Q# programs can be executed on a quantum simulator running on a classical computer and (in future) on quantum computers.
+
+```C#
+// Single-line comments start with //
+
+
+/////////////////////////////////////
+// 1. Quantum data types and operators
+
+// The most important part of quantum programs is qubits.
+// In Q# type Qubit represents the qubits which can be used.
+// This will allocate an array of two new qubits as the variable qs.
+using (qs = Qubit[2]) {
+
+ // The qubits have internal state that you cannot access to read or modify directly.
+ // You can inspect the current state of your quantum program
+ // if you're running it on a classical simulator.
+ // Note that this will not work on actual quantum hardware!
+ DumpMachine();
+
+ // If you want to change the state of a qubit
+ // you have to do this by applying quantum gates to the qubit.
+ H(q[0]); // This changes the state of the first qubit
+ // from |0⟩ (the initial state of allocated qubits)
+ // to (|0⟩ + |1⟩) / sqrt(2).
+ // q[1] = |1⟩; - this does NOT work, you have to manipulate a qubit by using gates.
+
+ // You can apply multi-qubit gates to several qubits.
+ CNOT(qs[0], qs[1]);
+
+ // You can also apply a controlled version of a gate:
+ // a gate that is applied if all control qubits are in |1⟩ state.
+ // The first argument is an array of control qubits,
+ // the second argument is the target qubit.
+ Controlled Y([qs[0]], qs[1]);
+
+ // If you want to apply an anti-controlled gate
+ // (a gate that is applied if all control qubits are in |0⟩ state),
+ // you can use a library function.
+ ApplyControlledOnInt(0, X, [qs[0]], qs[1]);
+
+ // To read the information from the quantum system, you use measurements.
+ // Measurements return a value of Result data type: Zero or One.
+ // You can print measurement results as a classical value.
+ Message($"Measured {M(qs[0])}, {M(qs[1])}");
+}
+
+
+/////////////////////////////////////
+// 2. Classical data types and operators
+
+// Numbers in Q# can be stored in Int, BigInt or Double.
+let i = 1; // This defines an Int variable i equal to 1
+let bi = 1L; // This defines a BigInt variable bi equal to 1
+let d = 1.0; // This defines a Double variable d equal to 1
+
+// Arithmetic is done as expected, as long as the types are the same
+let n = 2 * 10; // = 20
+// Q# does not have implicit type cast,
+// so to perform arithmetic on values of different types,
+// you need to cast type explicitly
+let nd = IntAsDouble(2) * 1.0; // = 20.0
+
+// Boolean type is called Bool
+let trueBool = true;
+let falseBool = false;
+
+// Logic operators work as expected
+let andBool = true and false;
+let orBool = true or false;
+let notBool = not false;
+
+// Strings
+let str = "Hello World!";
+
+// Equality is ==
+let x = 10 == 15; // is false
+
+// Range is a sequence of integers and can be defined like: start..step..stop
+let xi = 1..2..7; // Gives the sequence 1,3,5,7
+
+// Assigning new value to a variable:
+// by default all Q# variables are immutable;
+// if the variable was defined using let, you cannot reassign its value.
+
+// When you want to make a variable mutable, you have to declare it as such,
+// and use the set word to update value
+mutable xii = true;
+set xii = false;
+
+// You can create an array for any data type like this
+let xiii = new Double[10];
+
+// Getting an element from an array
+let xiv = xiii[8];
+
+// Assigning a new value to an array element
+mutable xv = new Double[10];
+set xv w/= 5 <- 1;
+
+
+/////////////////////////////////////
+// 3. Control flow
+
+// If structures work a little different than most languages
+if (a == 1) {
+ // ...
+} elif (a == 2) {
+ // ...
+} else {
+ // ...
+}
+
+// Foreach loops can be used to iterate over an array
+for (qubit in qubits) {
+ X(qubit);
+}
+
+// Regular for loops can be used to iterate over a range of numbers
+for (index in 0 .. Length(qubits) - 1) {
+ X(qubits[index]);
+}
+
+// While loops are restricted for use in classical context only
+mutable index = 0;
+while (index < 10) {
+ set index += 1;
+}
+
+// Quantum equivalent of a while loop is a repeat-until-success loop.
+// Because of the probabilistic nature of quantum computing sometimes
+// you want to repeat a certain sequence of operations
+// until a specific condition is achieved; you can use this loop to express this.
+repeat {
+ // Your operation here
+}
+until (success criteria) // This could be a measurement to check if the state is reached
+fixup {
+ // Resetting to the initial conditions, if required
+}
+
+
+/////////////////////////////////////
+// 4. Putting it all together
+
+// Q# code is written in operations and functions
+operation ApplyXGate(source : Qubit) : Unit {
+ X(source);
+}
+
+// If the operation implements a unitary transformation, you can define
+// adjoint and controlled variants of it.
+// The easiest way to do that is to add "is Adj + Ctl" after Unit.
+// This will tell the compiler to generate the variants automatically.
+operation ApplyXGateCA (source : Qubit) : Unit is Adj + Ctl {
+ X(source);
+}
+
+// Now you can call Adjoint ApplyXGateCA and Controlled ApplyXGateCA.
+
+
+// To run Q# code, you can put @EntryPoint() before the operation you want to run first
+@EntryPoint()
+operation XGateDemo() : Unit {
+ using (q = Qubit()) {
+ ApplyXGate(q);
+ }
+}
+
+// Here is a simple example: a quantum random number generator.
+// We will generate a classical array of random bits using quantum code.
+@EntryPoint()
+operation QRNGDemo() : Unit {
+ mutable bits = new Int[5]; // Array we'll use to store bits
+ using (q = Qubit()) { // Allocate a qubit
+ for (i in 0 .. 4) { // Generate each bit independently
+ H(q); // Hadamard gate sets equal superposition
+ let result = M(q); // Measure qubit gets 0|1 with 50/50 prob
+ let bit = result == Zero ? 0 | 1; // Convert measurement result to integer
+ set bits w/= i <- bit; // Write generated bit to an array
+ }
+ }
+ Message($"{bits}"); // Print the result
+}
+```
+
+
+## Further Reading
+
+The [Quantum Katas][1] offer great self-paced tutorials and programming exercises to learn quantum computing and Q#.
+
+[Q# Documentation][2] is official Q# documentation, including language reference and user guides.
+
+[1]: https://github.com/microsoft/QuantumKatas
+[2]: https://docs.microsoft.com/quantum/
diff --git a/perl6-pod.html.markdown b/raku-pod.html.markdown
index 80a501b8..7e9b6fc3 100644
--- a/perl6-pod.html.markdown
+++ b/raku-pod.html.markdown
@@ -5,9 +5,9 @@ contributors:
filename: learnpod.pod6
---
-Pod is an easy-to-use and purely descriptive mark-up language,
+Pod is an easy-to-use and purely descriptive mark-up language,
with no presentational components. Besides its use for documenting
-Raku Perl 6 programs and modules, Pod can be utilized to write language
+Raku programs and modules, Pod can be utilized to write language
documentation, blogs, and other types of document composition as well.
Pod documents can be easily converted to HTML and many other formats
@@ -49,12 +49,12 @@ generate documentation.
```
=begin pod
-A very simple Raku Perl 6 Pod document. All the other directives go here!
+A very simple Raku Pod document. All the other directives go here!
=end pod
```
-Pod documents usually coexist with Raku Perl 6 code. If by themselves,
+Pod documents usually coexist with Raku code. If by themselves,
Pod files often have the `.pod6` suffix. Moving forward, it's assumed that
the constructs being discussed are surrounded by the `=begin pod ... =end pod`
directives.
@@ -65,7 +65,7 @@ directives.
Text can be easily styled as bold, italic, underlined or verbatim (for code
formatting) using the following formatting codes: `B<>`, `I<>`, `U<>`
-and `C<>`.
+and `C<>`.
```
B<This text is in Bold.>
@@ -83,7 +83,7 @@ just a single capital letter followed immediately by a set of single or double
angle brackets. The Unicode variant («») of the angle brackets can also be
used.
-### Headings
+### Headings
Headings are created by using the `=headN` directive where `N` is the
heading level.
@@ -145,7 +145,7 @@ Unordered lists can be created using the `=item` directive.
```
Sublists are achieved with items at each level specified using the `=item1`,
-`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
+`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
defaults to `=item1`.
```
@@ -157,7 +157,7 @@ defaults to `=item1`.
=item1 Item four
```
-Definition lists that define terms or commands use the `=defn` directive.
+Definition lists that define terms or commands use the `=defn` directive.
This is equivalent to the `<dl>` element in HTML.
```
@@ -186,13 +186,13 @@ As shown in the [Basic Text Formatting](#basic-text-formatting) section,
inline code can be created using the `C<>` code.
```
-In Raku Perl 6, there are several functions/methods to output text. Some of them
+In Raku, there are several functions/methods to output text. Some of them
are C<print>, C<put> and C<say>.
```
### Comments
-Although Pod blocks are ignored by the Raku Perl 6 compiler, everything
+Although Pod blocks are ignored by the Rakudo Raku compiler, everything
indentified as a Pod block will be read and interpreted by Pod renderers. In
order to prevent Pod blocks from being rendered by any renderer, use the
`=comment` directive.
@@ -206,21 +206,21 @@ order to prevent Pod blocks from being rendered by any renderer, use the
To create inline comments, use the `Z<>` code.
```
-Pod is awesome Z<Of course it is!>. And Raku Perl 6 too!
+Pod is awesome Z<Of course it is!>. And Raku too!
```
-Given that the Perl interpreter never executes embedded Pod blocks,
+Given that the Raku interpreter never executes embedded Pod blocks,
comment blocks can also be used as an alternative form of nestable block
-comments in Raku Perl 6.
+comments.
### Links
Creating links in Pod is quite easy and is done by enclosing them in
a `L<>` code. The general format is `L<Label|Url>` with `Label`
-being optional.
+being optional.
```
-Raku Perl 6 homepage is L<https://perl6.org>.
+Raku homepage is L<https://raku.org>.
L<Click me!|http://link.org/>.
```
@@ -242,7 +242,7 @@ The Pod specifications are not completely handled properly yet and this
includes the handling of table. For simplicity's sake, only one way of
constructing tables is shown here. To learn about good practices and see
examples of both good and bad tables, please visit
-<https://docs.perl6.org/language/tables>.
+<https://docs.raku.org/language/tables>.
```
=begin table
@@ -287,7 +287,7 @@ For example:
Delimited blocks are bounded by `=begin` and `=end` markers, both of which are
followed by a valid Pod identifier, which is the `typename` of the block.
-The general syntax is
+The general syntax is
```
=begin BLOCK_TYPE
@@ -304,7 +304,7 @@ Top level heading
```
This type of blocks is useful for creating headings, list items, code blocks,
-etc. with multiple paragraphs. For example,
+etc. with multiple paragraphs. For example,
* a multiline item of a list
@@ -345,7 +345,7 @@ say pow(6); #=> 36
Paragraph blocks are introduced by a `=for` marker and terminated by
the next Pod directive or the first blank line (which is not considered to
be part of the block's contents). The `=for` marker is followed by the
-`typename` of the block. The general syntax is
+`typename` of the block. The general syntax is
```
=for BLOCK_TYPE
@@ -360,10 +360,10 @@ Top level heading
```
## Configuration Data
-
+
Except for abbreviated blocks, both delimited blocks and paragraph
blocks can be supplied with configuration information about their
-contents right after the `typename` of the block. Thus the following
+contents right after the `typename` of the block. Thus the following
are more general syntaxes for these blocks:
* Delimited blocks
@@ -384,16 +384,16 @@ BLOCK DATA
```
The configuration information is provided in a format akin to the
-["colon pair"](https://docs.perl6.org/language/glossary#index-entry-Colon_Pair)
-syntax in Raku Perl 6. The following table is a simplified version of the
-different ways in which configuration info can be supplied. Please go to
-<https://docs.perl6.org/language/pod#Configuration_information> for a more
+["colon pair"](https://docs.raku.org/language/glossary#index-entry-Colon_Pair)
+syntax in Raku. The following table is a simplified version of the
+different ways in which configuration info can be supplied. Please go to
+<https://docs.raku.org/language/pod#Configuration_information> for a more
thorough treatment of the subject.
| Value | Specify with... | Example |
| :-------- | :------ | :------ |
-| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Perl6') |
-| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'perl6.org'} |
+| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Raku') |
+| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'raku.org'} |
| Boolean | :key/:key(True) | :skip-test(True) |
| Boolean | :!key/:key(False) | :!skip-test |
| String | :key('string') | :nonexec-reason('SyntaxError') |
@@ -450,7 +450,7 @@ we get the following output:
</pre>
This is highly dependent on the format output. For example, while this works
-when Pod is converted to HTML, it might not be preserved when converted
+when Pod is converted to HTML, it might not be preserved when converted
to Markdown.
### Block Pre-configuration
@@ -549,48 +549,48 @@ a Pod document, enclose them in a `E<>` code.
For example:
```
-Raku Perl 6 makes considerable use of the E<171> and E<187> characters.
-Raku Perl 6 makes considerable use of the E<laquo> and E<raquo> characters.
+Raku makes considerable use of the E<171> and E<187> characters.
+Raku makes considerable use of the E<laquo> and E<raquo> characters.
```
is rendered as:
-Raku Perl 6 makes considerable use of the « and » characters.
-Raku Perl 6 makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
## Rendering Pod
-To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
-have the Raku Perl 6 compiler installed. In addition, you must install
+To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
+have the Rakudo Raku compiler installed. In addition, you must install
a module (e.g., `Pod::To::Markdown`, `Pod::To::HTML`, `Pod::To::Text`, etc.)
that generates your desired output from Pod.
-For instructions about installing Raku Perl 6,
-[look here](https://perl6.org/downloads/).
+For instructions about installing Rakudo for running raku programs,
+[look here](https://raku.org/downloads/).
Run the following command to generate a certain output:
```
-perl6 --doc=TARGET input.pod6 > output.html
+raku --doc=TARGET input.pod6 > output.html
```
with `TARGET` being `Markdown`, `HTML`, `Text`, etc. Thus to generate
Markdown from Pod, run this:
```
-perl6 --doc=Markdown input.pod6 > output.html
+raku --doc=Markdown input.pod6 > output.html
```
## Accessing Pod
-In order to access Pod documentation from within a Raku Perl 6 program,
+In order to access Pod documentation from within a Raku program,
it is required to use the special `=` twigil (e.g., `$=pod`, `$=SYNOPSIS`,etc).
-The `$=` construct provides the introspection over the Pod structure,
+The `$=` construct provides the introspection over the Pod structure,
producing a `Pod::Block` tree root from which it is possible to access
the whole structure of the Pod document.
-If we place the following piece of Raku Perl 6 code and the Pod documentation
+If we place the following piece of Raku code and the Pod documentation
in the section [Semantic blocks](#semantic-blocks) in the same file:
```
@@ -615,8 +615,8 @@ AUTHOR
DESCRIPTION
```
-## Additional Information
+## Additional Information
-* <https://docs.perl6.org/language/pod> for the Pod documentation.
-* <https://docs.perl6.org/language/tables> for advices about Pod tables.
-* <https://design.perl6.org/S26.html> for the Pod specification.
+* <https://docs.raku.org/language/pod> for the Pod documentation.
+* <https://docs.raku.org/language/tables> for advices about Pod tables.
+* <https://design.raku.org/S26.html> for the Pod specification.
diff --git a/raku.html.markdown b/raku.html.markdown
index 2460ac7e..16035615 100644
--- a/raku.html.markdown
+++ b/raku.html.markdown
@@ -15,7 +15,7 @@ the JVM and the [MoarVM](http://moarvm.com).
Meta-note:
-* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
+* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
comments (more below about them) are used whenever it's convenient.
* `# OUTPUT:` is used to represent the output of a command to any standard
stream. If the output has a newline, it's represented by the `␤` symbol.
@@ -23,7 +23,7 @@ Meta-note:
* `#=>` represents the value of an expression, return value of a sub, etc.
In some cases, the value is accompanied by a comment.
* Backticks are used to distinguish and highlight the language constructs
- from the text.
+ from the text.
```perl6
####################################################
@@ -95,7 +95,7 @@ my @array = 'a', 'b', 'c';
# equivalent to:
my @letters = <a b c>;
# In the previous statement, we use the quote-words (`<>`) term for array
-# of words, delimited by space. Similar to perl5's qw, or Ruby's %w.
+# of words, delimited by space. Similar to perl's qw, or Ruby's %w.
@array = 1, 2, 4;
@@ -152,7 +152,7 @@ though.
=end comment
say %hash{'n'}; # OUTPUT: «2␤», gets value associated to key 'n'
say %hash<is-even>; # OUTPUT: «True␤», gets value associated to key 'is-even'
-
+
####################################################
# 2. Subroutines
####################################################
@@ -265,9 +265,9 @@ takes-a-bool('config', :bool); # OUTPUT: «config takes True␤»
takes-a-bool('config', :!bool); # OUTPUT: «config takes False␤»
=begin comment
-Since paranthesis can be omitted when calling a subroutine, you need to use
-`&` in order to distinguish between a call to a sub with no arguments and
-the code object.
+Since parenthesis can be omitted when calling a subroutine, you need to use
+`&` in order to distinguish between a call to a sub with no arguments and
+the code object.
For instance, in this example we must use `&` to store the sub `say-hello`
(i.e., the sub's code object) in a variable, not a subroutine call.
@@ -276,7 +276,7 @@ my &s = &say-hello;
my &other-s = sub { say "Anonymous function!" }
=begin comment
-A sub can have a "slurpy" parameter, or what one'd call a
+A sub can have a "slurpy" parameter, or what one'd call a
"doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
functions. For this, you must use `*@` (slurpy) which will "take everything
else". You can have as many parameters *before* a slurpy one, but not *after*.
@@ -298,7 +298,7 @@ arguments (or Iterable ones).
=end comment
sub b(**@arr) { @arr.perl.say };
b(['a', 'b', 'c']); # OUTPUT: «[["a", "b", "c"],]»
-b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
+b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
=begin comment
@@ -508,7 +508,7 @@ given "foo bar" {
# can also be a C-style `for` loop:
loop {
say "This is an infinite loop !";
- last;
+ last;
}
# In the previous example, `last` breaks out of the loop very much
# like the `break` keyword in other languages.
@@ -614,8 +614,8 @@ say Int === Int; # OUTPUT: «True␤»
# Here are some common comparison semantics:
# String or numeric equality
-say 'Foo' ~~ 'Foo'; # OUTPU: «True␤», if strings are equal.
-say 12.5 ~~ 12.50; # OUTPU: «True␤», if numbers are equal.
+say 'Foo' ~~ 'Foo'; # OUTPUT: «True␤», if strings are equal.
+say 12.5 ~~ 12.50; # OUTPUT: «True␤», if numbers are equal.
# Regex - For matching a regular expression against the left side.
# Returns a `Match` object, which evaluates as True if regexp matches.
@@ -624,7 +624,7 @@ say $obj; # OUTPUT: «「a」␤»
say $obj.WHAT; # OUTPUT: «(Match)␤»
# Hashes
-say 'key' ~~ %hash; # OUTPUT:«True␤», if key exists in hash.
+say 'key' ~~ %hash; # OUTPUT: «True␤», if key exists in hash.
# Type - Checks if left side "is of type" (can check superclasses and roles).
say 1 ~~ Int; # OUTPUT: «True␤»
@@ -652,7 +652,7 @@ say 'a' le 'b'; # OUTPUT: «True␤»
# 5.2 Range constructor
#
-say 3 .. 7; # OUTPUT: «3..7␤», both included.
+say 3 .. 7; # OUTPUT: «3..7␤», both included.
say 3 ..^ 7; # OUTPUT: «3..^7␤», exclude right endpoint.
say 3 ^.. 7; # OUTPUT: «3^..7␤», exclude left endpoint.
say 3 ^..^ 7; # OUTPUT: «3^..^7␤», exclude both endpoints.
@@ -665,7 +665,7 @@ say 3.5 ~~ 3 ^.. 7; # OUTPUT: «True␤»,
# This is because the range `3 ^.. 7` only excludes anything strictly
# equal to 3. Hence, it contains decimals greater than 3. This could
-# mathematically be described as 3.5 ∈ (3,7] or in set notation,
+# mathematically be described as 3.5 ∈ (3,7] or in set notation,
# 3.5 ∈ { x | 3 < x ≤ 7 }.
say 3 ^.. 7 ~~ 4 .. 7; # OUTPUT: «False␤»
@@ -800,7 +800,7 @@ fst(1); # OUTPUT: «1␤»
=begin comment
You can also destructure hashes (and classes, which you'll learn about later).
-The syntax is basically the same as
+The syntax is basically the same as
`%hash-name (:key($variable-to-store-value-in))`.
The hash can stay anonymous if you only need the values you extracted.
@@ -842,7 +842,7 @@ my @list3 = list-of(3); #=> (0, 1, 2)
# 6.2 Lambdas (or anonymous subroutines)
#
-# You can create a lambda by using a pointy block (`-> {}`), a
+# You can create a lambda by using a pointy block (`-> {}`), a
# block (`{}`) or creating a `sub` without a name.
my &lambda1 = -> $argument {
@@ -858,18 +858,18 @@ my &lambda3 = sub ($argument) {
}
=begin comment
-Both pointy blocks and blocks are pretty much the same thing, except that
+Both pointy blocks and blocks are pretty much the same thing, except that
the former can take arguments, and that the latter can be mistaken as
-a hash by the parser. That being said, blocks can declare what's known
+a hash by the parser. That being said, blocks can declare what's known
as placeholders parameters through the twigils `$^` (for positional
-parameters) and `$:` (for named parameters). More on them latern on.
+parameters) and `$:` (for named parameters). More on them later on.
=end comment
my &mult = { $^numbers * $:times }
say mult 4, :times(6); #=> «24␤»
# Both pointy blocks and blocks are quite versatile when working with functions
-# that accepts other functions such as `map`, `grep`, etc. For example,
+# that accepts other functions such as `map`, `grep`, etc. For example,
# we add 3 to each value of an array using the `map` function with a lambda:
my @nums = 1..4;
my @res1 = map -> $v { $v + 3 }, @nums; # pointy block, explicit parameter
@@ -1088,7 +1088,7 @@ sub call_say_dyn {
# $*dyn_scoped 1 and 2 will be looked for in the call.
say_dyn(); # OUTPUT: «25 100␤»
-
+
# The call to `say_dyn` uses the value of $*dyn_scoped_1 from inside
# this sub's lexical scope even though the blocks aren't nested (they're
# call-nested).
@@ -1162,7 +1162,7 @@ class Human {
};
# Create a new instance of Human class.
-# NOTE: Only attributes declared with the `.` twigil can be set via the
+# NOTE: Only attributes declared with the `.` twigil can be set via the
# default constructor (more later on). This constructor only accepts named
# arguments.
my $person1 = Human.new(
@@ -1317,7 +1317,7 @@ method on the `$_` variable to access the exception
open 'foo' orelse say "Something happened {.exception}";
# This also works:
-open 'foo' orelse say "Something happened $_";
+open 'foo' orelse say "Something happened $_";
# OUTPUT: «Something happened Failed to open file foo: no such file or directory␤»
=begin comment
@@ -1431,15 +1431,15 @@ use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; # OUTPUT: «[1]␤»
=begin comment
-You should not declare packages using the `package` keyword (unlike Perl 5).
+You should not declare packages using the `package` keyword (unlike Perl).
Instead, use `class Package::Name::Here;` to declare a class, or if you only
want to export variables/subs, you can use `module` instead.
=end comment
# If `Hello` doesn't exist yet, it'll just be a "stub", that can be redeclared
-# as something else later.
+# as something else later.
module Hello::World { # bracketed form
- # declarations here
+ # declarations here
}
# The file-scoped form which extends until the end of the file. For
@@ -1520,7 +1520,7 @@ fixed-rand for ^10; # will print the same number 10 times
for ^5 -> $a {
sub foo {
# This will be a different value for every value of `$a`
- state $val = rand;
+ state $val = rand;
}
for ^5 -> $b {
# This will print the same value 5 times, but only 5. Next iteration
@@ -1558,9 +1558,9 @@ END { say "Runs at run time, as late as possible, only once" }
#
# 14.3 Block phasers
#
-ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" }
+ENTER { say "[*] Runs every time you enter a block, repeats on loop blocks" }
LEAVE {
- say "Runs everytime you leave a block, even when an exception
+ say "Runs every time you leave a block, even when an exception
happened. Repeats on loop blocks."
}
@@ -1610,7 +1610,7 @@ for ^5 {
#
# 14.6 Role/class phasers
#
-COMPOSE {
+COMPOSE {
say "When a role is composed into a class. /!\ NOT YET IMPLEMENTED"
}
@@ -1619,9 +1619,9 @@ say "This code took " ~ (time - CHECK time) ~ "s to compile";
# ... or clever organization:
class DB {
- method start-transaction { say "Starting transation!" }
- method commit { say "Commiting transaction..." }
- method rollback { say "Something went wrong. Rollingback!" }
+ method start-transaction { say "Starting transaction!" }
+ method commit { say "Committing transaction..." }
+ method rollback { say "Something went wrong. Rolling back!" }
}
sub do-db-stuff {
@@ -1647,7 +1647,7 @@ braces `{` and `}`.
=end comment
#
-# 15.1 `do` - It runs a block or a statement as a term.
+# 15.1 `do` - It runs a block or a statement as a term.
#
# Normally you cannot use a statement as a value (or "term"). `do` helps
@@ -1805,7 +1805,7 @@ sub postfix:<!>( Int $n ) {
}
say 5!; # OUTPUT: «120␤»
-# Postfix operators ('after') have to come *directly* after the term.
+# Postfix operators ('after') have to come *directly* after the term.
# No whitespace. You can use parentheses to disambiguate, i.e. `(5!)!`
sub infix:<times>( Int $n, Block $r ) { # infix ('between')
@@ -1898,7 +1898,7 @@ say [+] (); # OUTPUT: «0␤», empty sum
say [//]; # OUTPUT: «(Any)␤»
# There's no "default value" for `//`.
-# You can also use it with a function you made up,
+# You can also use it with a function you made up,
# You can also surround using double brackets:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; # OUTPUT: «6␤»
@@ -2078,19 +2078,19 @@ say so 'abc' ~~ / a b+ c /; # OUTPUT: «True␤», one is enough
say so 'abbbbc' ~~ / a b+ c /; # OUTPUT: «True␤», matched 4 "b"s
# `*` - zero or more matches
-say so 'ac' ~~ / a b* c /; # OUTPU: «True␤», they're all optional
-say so 'abc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'abbbbc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'aec' ~~ / a b* c /; # OUTPU: «False␤», "b"(s) are optional, not replaceable.
+say so 'ac' ~~ / a b* c /; # OUTPUT: «True␤», they're all optional
+say so 'abc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'aec' ~~ / a b* c /; # OUTPUT: «False␤», "b"(s) are optional, not replaceable.
# `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand why exponentation is used
# for quantity.
-say so 'abc' ~~ / a b**1 c /; # OUTPU: «True␤», exactly one time
-say so 'abc' ~~ / a b**1..3 c /; # OUTPU: «True␤», one to three times
-say so 'abbbc' ~~ / a b**1..3 c /; # OUTPU: «True␤»
-say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPU: «Fals␤», too much
-say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPU: «True␤», infinite ranges are ok
+say so 'abc' ~~ / a b**1 c /; # OUTPUT: «True␤», exactly one time
+say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «True␤», one to three times
+say so 'abbbc' ~~ / a b**1..3 c /; # OUTPUT: «True␤»
+say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPUT: «Fals␤», too much
+say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPUT: «True␤», infinite ranges are ok
#
# 18.2 `<[]>` - Character classes
@@ -2150,7 +2150,7 @@ say so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # OUTPUT: «True␤
say $/; # Will either print the matched object or `Nil` if nothing matched.
# As we also said before, it has array indexing:
-say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
+say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
# The corner brackets (「..」) represent (and are) `Match` objects. In the
# previous example, we have an array of them.
@@ -2202,8 +2202,8 @@ say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list␤»
# Alternation - the `or` of regexes
# WARNING: They are DIFFERENT from PCRE regexps.
-say so 'abc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Either "b" or "y".
-say so 'ayc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Obviously enough...
+say so 'abc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Either "b" or "y".
+say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Obviously enough...
# The difference between this `|` and the one you're used to is
# LTM ("Longest Token Matching") strategy. This means that the engine will
@@ -2218,7 +2218,7 @@ To decide which part is the "longest", it first splits the regex in two parts:
yet introduced), literals, characters classes and quantifiers.
* The "procedural part" includes everything else: back-references,
- code assertions, and other things that can't traditionnaly be represented
+ code assertions, and other things that can't traditionally be represented
by normal regexps.
Then, all the alternatives are tried at once, and the longest wins.
@@ -2268,7 +2268,7 @@ while its absence falseness). For example:
# convert to IO object to check the file exists
subset File of Str where *.IO.d;
-
+
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
@@ -2358,7 +2358,7 @@ side, once its left side changed:
# In this case the right-hand-side wasn't tested until `$_` became "C"
# (and thus did not match instantly).
-.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
+.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
# A flip-flop can change state as many times as needed:
for <test start print it stop not printing start print again stop not anymore> {
@@ -2392,21 +2392,20 @@ resource on Raku. If you are looking for something, use the search bar.
This will give you a dropdown menu of all the pages referencing your search
term (Much better than using Google to find Raku documents!).
-- Read the [Raku Advent Calendar](http://perl6advent.wordpress.com/). This
+- Read the [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). This
is a great source of Raku snippets and explanations. If the docs don't
describe something well enough, you may find more detailed information here.
This information may be a bit older but there are many great examples and
explanations. Posts stopped at the end of 2015 when the language was declared
-stable and Raku 6.c was released.
+stable and `Raku v6.c` was released.
-- Come along on `#raku` at `irc.freenode.net`. The folks here are
+- Come along on `#raku` at [`irc.freenode.net`](https://webchat.freenode.net/?channels=#raku). The folks here are
always helpful.
- Check the [source of Raku's functions and
-classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is
+classes](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo is
mainly written in Raku (with a lot of NQP, "Not Quite Perl", a Raku subset
easier to implement and optimize).
- Read [the language design documents](https://design.raku.org/). They explain
Raku from an implementor point-of-view, but it's still very interesting.
-
diff --git a/raylib.html.markdown b/raylib.html.markdown
new file mode 100644
index 00000000..0afc6e03
--- /dev/null
+++ b/raylib.html.markdown
@@ -0,0 +1,146 @@
+---
+category: tool
+tool: raylib
+filename: learnraylib.c
+contributors:
+ - ["Nikolas Wipper", "https://notnik.cc"]
+---
+
+**raylib** is a cross-platform easy-to-use graphics library, built around
+OpenGL 1.1, 2.1, 3.3 and OpenGL ES 2.0. Even though it is written in C
+it has bindings to over 50 different languages. This tutorial will use C,
+more specifically C99.
+
+```c
+#include <raylib.h>
+
+int main(void)
+{
+ const int screenWidth = 800;
+ const int screenHeight = 450;
+
+ // Before initialising raylib we can set configuration flags
+ SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
+
+ // raylib doesn't require us to store any instance structures
+ // At the moment raylib can handle only one window at a time
+ InitWindow(screenWidth, screenHeight, "MyWindow");
+
+ // Set our game to run at 60 frames-per-second
+ SetTargetFPS(60);
+
+ // Set a key that closes the window
+ // Could be 0 for no key
+ SetExitKey(KEY_DELETE);
+
+ // raylib defines two types of cameras: Camera3D and Camera2D
+ // Camera is a typedef for Camera3D
+ Camera camera = {
+ .position = {0.0f, 0.0f, 0.0f},
+ .target = {0.0f, 0.0f, 1.0f},
+ .up = {0.0f, 1.0f, 0.0f},
+ .fovy = 70.0f,
+ .type = CAMERA_PERSPECTIVE
+ };
+
+ // raylib supports loading of models, animations, images and sounds
+ // from various different file formats
+ Model myModel = LoadModel("my_model.obj");
+ Font someFont = LoadFont("some_font.ttf");
+
+ // Creates a 100x100 render texture
+ RenderTexture renderTexture = LoadRenderTexture(100, 100);
+
+ // WindowShouldClose checks if the user is closing the window
+ // This might happen using a shortcut, window controls
+ // or the key we set earlier
+ while (!WindowShouldClose())
+ {
+
+ // BeginDrawing needs to be called before any draw call
+ BeginDrawing();
+ {
+
+ // Sets the background to a certain color
+ ClearBackground(BLACK);
+
+ if (IsKeyDown(KEY_SPACE))
+ DrawCircle(400, 400, 30, GREEN);
+
+ // Simple draw text
+ DrawText("Congrats! You created your first window!",
+ 190, // x
+ 200, // y
+ 20, // font size
+ LIGHTGRAY
+ );
+
+ // For most functions there are several versions
+ // These are usually postfixed with Ex, Pro, V
+ // or sometimes Rec, Wires (only for 3D), Lines (only for 2D)
+ DrawTextEx(someFont,
+ "Text in another font",
+ (Vector2) {10, 10},
+ 20, // font size
+ 2, // spacing
+ LIGHTGRAY);
+
+ // Required for drawing 3D, has 2D equivalent
+ BeginMode3D(camera);
+ {
+
+ DrawCube((Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, 1.0f, 1.0f, RED);
+
+ // White tint when drawing will keep the original color
+ DrawModel(myModel, (Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, //Scale
+ WHITE);
+
+ }
+ // End 3D mode so we can draw normally again
+ EndMode3D();
+
+ // Start drawing onto render texture
+ BeginTextureMode(renderTexture);
+ {
+
+ // It behaves the same as if we just called `BeginDrawing()`
+
+ ClearBackground(RAYWHITE);
+
+ BeginMode3D(camera);
+ {
+
+ DrawGrid(10, // Slices
+ 1.0f // Spacing
+ );
+
+ }
+ EndMode3D();
+
+ }
+ EndTextureMode();
+
+ // render textures have a Texture2D field
+ DrawTexture(renderTexture.texture, 40, 378, BLUE);
+
+ }
+ EndDrawing();
+ }
+
+ // Unloading loaded objects
+ UnloadFont(someFont);
+ UnloadModel(myModel);
+
+ // Close window and OpenGL context
+ CloseWindow();
+
+ return 0;
+}
+
+```
+
+## Further reading
+raylib has some [great examples](https://www.raylib.com/examples.html)
+If you don't like C check out the [raylib bindings](https://github.com/raysan5/raylib/blob/master/BINDINGS.md) \ No newline at end of file
diff --git a/red.html.markdown b/red.html.markdown
index 74538bd7..34c4bcd9 100644
--- a/red.html.markdown
+++ b/red.html.markdown
@@ -216,7 +216,7 @@ The Red/System language specification can be found [here](http://static.red-lang
To learn more about Rebol and Red join the [chat on Gitter](https://gitter.im/red/red). And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM).
-Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/red).
+Browse or ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/red).
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
diff --git a/rst.html.markdown b/rst.html.markdown
index 2423622e..bdc73c7a 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -49,9 +49,11 @@ Subtitles with dashes
You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``.
+Special characters can be escaped using a backslash, e.g. \\ or \*.
+
Lists are similar to Markdown, but a little more involved.
-Remember to line up list symbols (like - or *) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
+Remember to line up list symbols (like - or \*) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
- First item
- Second item
@@ -86,7 +88,7 @@ There are multiple ways to make links:
- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)
- By making a more Markdown-like link: `Github <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _Github: https://github.com/
```
diff --git a/ru-ru/pascal-ru.html.markdown b/ru-ru/pascal-ru.html.markdown
new file mode 100644
index 00000000..5ea856bc
--- /dev/null
+++ b/ru-ru/pascal-ru.html.markdown
@@ -0,0 +1,217 @@
+---
+language: Pascal
+filename: learnpascal-ru.pas
+contributors:
+ - ["Ganesha Danu", "http://github.com/blinfoldking"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["Anton 'Dart' Nikolaev", "https://github.com/dartfnm"]
+lang: ru-ru
+---
+
+
+>Pascal - это процедурный язык программирования, который Никлаус Вирт разработал в 1968–69 годах и опубликовал в 1970 году как небольшой эффективный язык, предназначенный для поощрения хороших методов программирования с использованием структурированного программирования и структурирования данных. Он назван в честь французского математика, философа и физика Блеза Паскаля.
+>
+>source : [wikipedia](https://ru.wikipedia.org/wiki/Паскаль_(язык_программирования)))
+
+
+
+Для компиляции и запуска программы на языке Паскаль вы можете использовать бесплатный компилятор FreePascal. [Скачать здесь](https://www.freepascal.org/)
+
+Либо современный бесплатный компилятор Паскаля нового поколения под платформу .Net [PascalABC.NET](http://pascalabc.net)
+
+```pascal
+// это комментарий
+{
+ а вот это:
+ - комментарий на несколько строк
+}
+
+//объявляем имя программы
+program learn_pascal; //<-- не забываем ставить точку с запятой (;)
+
+const
+ {
+ это секция в которой вы должны объявлять константы
+ }
+type
+ {
+ здесь вы можете объявлять собственные типы данных
+ }
+var
+ {
+ секция для объявления переменных
+ }
+
+begin //начало основной программы
+ {
+ тело вашей программы
+ }
+end. // В конце основной программы обязательно должна стоять точка "."
+```
+
+```pascal
+//объявление переменных
+//вы можете сделать так
+var a:integer;
+var b:integer;
+//или так
+var
+ a : integer;
+ b : integer;
+//или даже так
+var a,b : integer;
+```
+
+```pascal
+program Learn_More;
+
+// Познакомимся с типами данных и с их операциями
+const
+ PI = 3.141592654;
+ GNU = 'GNU''s Not Unix';
+ // имена константам принято давать ЗАГЛАВНЫМИ_БУКВАМИ (в верхнем регистре)
+ // их значения фиксированны т.е никогда не меняются во время выполнения программы
+ // содержат любой стандартный тип данных (integer, real, boolean, char, string)
+
+type
+ ch_array : array [0..255] of char;
+ // массивы - это составной тип данных
+ // мы указываем индекс первого и последнего элемента массива ([0..255])
+ // здесь мы объявили новый тип данных содержащий 255 символов 'char'
+ // (по сути, это просто строка - string[256])
+
+ md_array : array of array of integer;
+ // массив в массиве - по сути является двумерным массивом
+ // можно задать массив нулевой (0) длины, а потом динамически расширить его
+ // это двумерный массив целых чисел
+
+//Объявление переменных
+var
+ int, c, d : integer;
+ // три переменные, которые содержат целые числа
+ // Тип "integer" это 16-битное число в диапазоне [-32,768..32,767]
+ r : real;
+ // переменная типа "real" принимает вещественные (дробные) значения
+ // в диапазоне [3.4E-38..3.4E38]
+ bool : boolean;
+ // переменная логического типа, принимающая булевы-значения: True/False (Правда/Ложь)
+ ch : char;
+ // эта переменная содержит значение кода одного символа
+ // тип 'char' это 8-битное число (1 байт), так что никакого Юникода
+ str : string;
+ // это переменная составного типа, являющееся строкой
+ // по сути, строка это массив в 255 символов длиною, по умолчанию
+
+ s : string[50];
+ // эта строка может содержать максимум 50 символов
+ // вы можете сами указать длину строки, чтобы минимизировать использование памяти
+ my_str: ch_array;
+ // вы можете объявлять переменные собственных типов
+ my_2d : md_array;
+ // динамически расширяемые массивы требуют указания длины перед их использованием.
+
+ // дополнительные целочисленные типы данных
+ b : byte; // диапазон [0..255]
+ shi : shortint; // диапазон [-128..127]
+ smi : smallint; // диапазон [-32,768..32,767] (стандартный Integer)
+ w : word; // диапазон [0..65,535]
+ li : longint; // диапазон [-2,147,483,648..2,147,483,647]
+ lw : longword; // диапазон [0..4,294,967,295]
+ c : cardinal; // тоже что и longword
+ i64 : int64; // диапазон [-9223372036854775808..9223372036854775807]
+ qw : qword; // диапазон [0..18,446,744,073,709,551,615]
+
+ // дополнительные вещественные типы данных (дробные)
+ rr : real; // диапазон зависит от платформы (т.е. 8-бит, 16-бит и т.д.)
+ rs : single; // диапазон [1.5E-45..3.4E38]
+ rd : double; // диапазон [5.0E-324 .. 1.7E308]
+ re : extended; // диапазон [1.9E-4932..1.1E4932]
+ rc : comp; // диапазон [-2E64+1 .. 2E63-1]
+
+Begin
+ int := 1; // так мы присваиваем значение переменной
+ r := 3.14;
+ ch := 'a';
+ str := 'apple';
+ bool := true;
+ // Паскаль не чувствителен к регистру
+
+ // арифметические операции
+ int := 1 + 1; // int = 2; заменяет предыдущее значение
+ int := int + 1; // int = 2 + 1 = 3;
+ int := 4 div 2; //int = 2; 'div' операция деления, с отбрасыванием дробной части
+ int := 3 div 2; //int = 1;
+ int := 1 div 2; //int = 0;
+
+ bool := true or false; // bool = true
+ bool := false and true; // bool = false
+ bool := true xor true; // bool = false
+
+ r := 3 / 2; // деления вещественных чисел с дробной частью
+ r := int; // вещественной переменной можно присвоить целочисленное значение, но не наоборот
+
+ my_str[0] := 'a'; // для доступа к элементу массива нужно указать его индекс в квадратных скобках ([0])
+
+ c := str[1]; // первая буква во всех Строках находится по индексу [1]
+ str := 'hello' + 'world'; //объединяем 2 строки в одну
+
+ SetLength(my_2d,10,10); // инициализируем динамически расширяемый массив
+ // задаём размер 2х-мерного массива 10×10
+
+ // первый элемент массива лежит в индексе [0], последний [длина_массива-1]
+ for c := 0 to 9 do
+ for d := 0 to 9 do // переменные для счетчиков циклов должны быть объявлены
+ my_2d[c,d] := c * d;
+ // обращаться к многомерным массивам нужно с помощью одного набора скобок
+
+End.
+```
+
+```pascal
+program Functional_Programming;
+
+Var
+ i, dummy : integer;
+
+function factorial_recursion(const a: integer) : integer;
+{ Функция расчёта Факториала целочисленного параметра 'a', рекурсивно. Возвращает целое значение }
+
+// Мы можем объявлять локальные переменные внутри своей функции:
+// Var
+// local_a : integer;
+
+Begin
+ If a >= 1 Then
+ factorial_recursion := a * factorial_recursion(a-1)
+ // возвращаем результат, присваивая найденное значение переменной с тем же именем, как у функции
+ Else
+ factorial_recursion := 1;
+End; // Для завершения функции, используется символ ";" после оператора "End;"
+
+
+
+procedure get_integer( var i : integer; dummy : integer );
+{ Эта процедура ждёт от пользователя ввода целого числа и возвращает его значение через параметр i.
+ Если параметр функции начинается с 'var', это означает, что его значение было передано, по ссылке, то есть, оно может использоваться не только как входное значение, но и для возвращения дополнительных результатов работы функции.
+ Параметры функции (без 'var'), (такие как "dummy" (пустышка)), передаются по значению, и по сути являются - локальными переменными, таким образом изменения, внесенные внутри функции/процедуры, не влияют на значение переменной за её пределами.
+}
+Begin // начало процедуры
+ write('Введите целое число: ');
+ readln(i); // число, введённое пользователем, сохранится в переменной i
+ // и её значение будет доступно вызывающей подпрограмме
+
+ dummy := 4; // значение 'dummy' не будет влиять на значения переменной вне процедуры
+End; // конец процедуры
+
+Begin // главный блок программы
+ dummy := 3;
+ get_integer(i, dummy); // вызываем процедуру получения числа от пользователя
+ writeln(i, '! = ', factorial_recursion(i)); // ввыводим значение факториала от i
+
+ writeln('dummy = ', dummy);
+ // всегда выводит "3", поскольку фиктивная переменная не изменяется.
+End. // конец программы
+
+```
+
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
index a907ba41..a9bb683b 100644
--- a/ru-ru/perl-ru.html.markdown
+++ b/ru-ru/perl-ru.html.markdown
@@ -9,12 +9,12 @@ translators:
lang: ru-ru
---
-Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
-Особенно хорош для обработки разнообразных текстовых данных.
+Perl -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
-Perl 5 работает более чем на 100 платформах, от портативных устройств
-до мейнфреймов, и подходит как для быстрого прототипирования,
-так и для крупных проектов.
+Perl работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
```perl
# Комментарии начинаются с символа решетки.
@@ -23,8 +23,8 @@ Perl 5 работает более чем на 100 платформах, от п
#### Типы переменных в Perl
# Скалярные переменные начинаются с знака доллара $.
-# Имя переменной состоит из букв, цифр и знаков подчеркивания,
-# начиная с буквы или подчеркивания.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
### В Perl три основных типа переменных: скаляры, массивы, хеши.
@@ -55,7 +55,7 @@ my %fruit_color = (
banana => "yellow",
);
-# Важно: вставка и поиск в хеше выполняются за константное время,
+# Важно: вставка и поиск в хеше выполняются за константное время,
# независимо от его размера.
# Скаляры, массивы и хеши подробно описаны в разделе perldata
@@ -81,7 +81,7 @@ unless ( condition ) {
}
# Это более читаемый вариант для "if (!condition)"
-# Специфические Perl-овые пост-условия:
+# Специфические Perl-овые пост-условия:
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
@@ -129,7 +129,7 @@ open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Читать из файлового дескриптора можно с помощью оператора "<>".
-# В скалярном контексте он читает одну строку из файла, в списковом --
+# В скалярном контексте он читает одну строку из файла, в списковом --
# читает сразу весь файл, сохраняя по одной строке в элементе массива:
my $line = <$in>;
@@ -152,13 +152,13 @@ logger("We have a logger subroutine!");
#### Perl-модули
-Perl-овые модули предоставляют широкий набор функциональности,
-так что вы можете не изобретать заново велосипеды, а просто скачать
-нужный модуль с CPAN (http://www.cpan.org/).
-Некоторое количество самых полезных модулей включено в стандартную
+Perl-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
поставку Perl.
-Раздел документации perlfaq содержит вопросы и ответы о многих частых
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
задачах, и часто предлагает подходящие CPAN-модули.
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index b2c00baf..9133549d 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -380,7 +380,7 @@ else: # Необязательное выражение. Должно след
# Объект, который возвратила функция range(), итерируемый.
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable
+print(our_iterable) #=> dict_keys(['one', 'two', 'three']). Это объект, реализующий интерфейс iterable
# Мы можем проходить по нему циклом.
for i in our_iterable:
diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown
index b1fd04e1..8b263be6 100644
--- a/ru-ru/ruby-ru.html.markdown
+++ b/ru-ru/ruby-ru.html.markdown
@@ -480,7 +480,7 @@ class Human
@name
end
- # Тоже самое можно определить с помощью att_accessor
+ # Тоже самое можно определить с помощью attr_accessor
attr_accessor :name
# Также можно создать методы только для записи или чтения
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 376f4a47..4b96b71c 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -181,6 +181,9 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can contain different types of items.
[1, 'hello', false] #=> [1, "hello", false]
+# You might prefer %w instead of quotes
+%w[foo bar baz] #=> ["foo", "bar", "baz"]
+
# Arrays can be indexed.
# From the front...
array[0] #=> 1
@@ -324,6 +327,11 @@ puts doubled
puts array
#=> [1,2,3,4,5]
+# another useful syntax is .map(&:method)
+a = ["FOO", "BAR", "BAZ"]
+a.map { |s| s.downcase } #=> ["foo", "bar", "baz"]
+a.map(&:downcase) #=> ["foo", "bar", "baz"]
+
# Case construct
grade = 'B'
@@ -430,6 +438,16 @@ def guests(*array)
array.each { |guest| puts guest }
end
+# There is also the shorthand block syntax. It's most useful when you need
+# to call a simple method on all array items.
+upcased = ['Watch', 'these', 'words', 'get', 'upcased'].map(&:upcase)
+puts upcased
+#=> ["WATCH", "THESE", "WORDS", "GET", "UPCASED"]
+
+sum = [1, 2, 3, 4, 5].reduce(&:+)
+puts sum
+#=> 15
+
# Destructuring
# Ruby will automatically destructure arrays on assignment to multiple variables.
diff --git a/scala.html.markdown b/scala.html.markdown
index c7a8842e..08fd37e4 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -252,7 +252,7 @@ weirdSum(2, 4) // => 16
// The return keyword exists in Scala, but it only returns from the inner-most
// def that surrounds it.
// WARNING: Using return in Scala is error-prone and should be avoided.
-// It has no effect on anonymous functions. For example:
+// It has no effect on anonymous functions. For example here you may expect foo(7) should return 17 but it returns 7:
def foo(x: Int): Int = {
val anonFunc: Int => Int = { z =>
if (z > 5)
@@ -260,9 +260,10 @@ def foo(x: Int): Int = {
else
z + 2 // This line is the return value of anonFunc
}
- anonFunc(x) // This line is the return value of foo
+ anonFunc(x) + 10 // This line is the return value of foo
}
+foo(7) // => 7
/////////////////////////////////////////////////
// 3. Flow Control
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
new file mode 100644
index 00000000..6fb657ed
--- /dev/null
+++ b/set-theory.html.markdown
@@ -0,0 +1,132 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+contributors:
+---
+Set theory is a branch of mathematics that studies sets, their operations, and their properties.
+
+* A set is a collection of disjoint items.
+
+## Basic symbols
+
+### Operators
+* the union operator, `∪`, pronounced "cup", means "or";
+* the intersection operator, `∩`, pronounced "cap", means "and";
+* the exclusion operator, `\`, means "without";
+* the compliment operator, `'`, means "the inverse of";
+* the cross operator, `×`, means "the Cartesian product of".
+
+### Qualifiers
+* the colon qualifier, `:`, means "such that";
+* the membership qualifier, `∈`, means "belongs to";
+* the subset qualifier, `⊆`, means "is a subset of";
+* the proper subset qualifier, `⊂`, means "is a subset of but is not equal to".
+
+### Canonical sets
+* `∅`, the empty set, i.e. the set containing no items;
+* `ℕ`, the set of all natural numbers;
+* `ℤ`, the set of all integers;
+* `ℚ`, the set of all rational numbers;
+* `ℝ`, the set of all real numbers.
+
+There are a few caveats to mention regarding the canonical sets:
+1. Even though the empty set contains no items, the empty set is a subset of itself (and indeed every other set);
+2. Mathematicians generally do not universally agree on whether zero is a natural number, and textbooks will typically explicitly state whether or not the author considers zero to be a natural number.
+
+
+### Cardinality
+
+The cardinality, or size, of a set is determined by the number of items in the set. The cardinality operator is given by a double pipe, `|...|`.
+
+For example, if `S = { 1, 2, 4 }`, then `|S| = 3`.
+
+### The Empty Set
+* The empty set can be constructed in set builder notation using impossible conditions, e.g. `∅ = { x : x =/= x }`, or `∅ = { x : x ∈ N, x < 0 }`;
+* the empty set is always unique (i.e. there is one and only one empty set);
+* the empty set is a subset of all sets;
+* the cardinality of the empty set is 1, i.e. `|∅| = 1`.
+
+## Representing sets
+
+### Literal Sets
+
+A set can be constructed literally by supplying a complete list of objects contained in the set. For example, `S = { a, b, c, d }`.
+
+Long lists may be shortened with ellipses as long as the context is clear. For example, `E = { 2, 4, 6, 8, ... }` is clearly the set of all even numbers, containing an infinite number of objects, even though we've only explicitly written four of them.
+
+### Set Builder
+
+Set builder notation is a more descriptive way of constructing a set. It relies on a _subject_ and a _predicate_ such that `S = { subject : predicate }`. For example,
+
+```
+A = { x : x is a vowel } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+Sometimes the predicate may "leak" into the subject, e.g.
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## Relations
+
+### Membership
+
+* If the value `a` is contained in the set `A`, then we say `a` belongs to `A` and represent this symbolically as `a ∈ A`.
+* If the value `a` is not contained in the set `A`, then we say `a` does not belong to `A` and represent this symbolically as `a ∉ A`.
+
+### Equality
+
+* If two sets contain the same items then we say the sets are equal, e.g. `A = B`.
+* Order does not matter when determining set equality, e.g. `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
+* Sets are disjoint, meaning elements cannot be repeated, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
+* Two sets `A` and `B` are equal if and only if `A ⊂ B` and `B ⊂ A`.
+
+## Special Sets
+
+### The Power Set
+* Let `A` be any set. The set that contains all possible subsets of `A` is called a "power set" and is written as `P(A)`. If the set `A` contains `n` elements, then `P(A)` contains `2^N` elements.
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## Set operations among two sets
+### Union
+Given two sets `A` and `B`, the union of the two sets are the items that appear in either `A` or `B`, written as `A ∪ B`.
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### Intersection
+Given two sets `A` and `B`, the intersection of the two sets are the items that appear in both `A` and `B`, written as `A ∩ B`.
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### Difference
+Given two sets `A` and `B`, the set difference of `A` with `B` is every item in `A` that does not belong to `B`.
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### Symmetrical difference
+Given two sets `A` and `B`, the symmetrical difference is all items among `A` and `B` that doesn't appear in their intersections.
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Cartesian product
+Given two sets `A` and `B`, the cartesian product between `A` and `B` consists of a set containing all combinations of items of `A` and `B`.
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index d6d369cc..58dccae4 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -388,7 +388,7 @@ y := $A max: $B.
```smalltalk
| b x y |
x := #Hello. "symbol assignment"
-y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
+y := #Symbol, #Concatenation. "symbol concatenation (result is string)"
b := x isEmpty. "test if symbol is empty"
y := x size. "string size"
y := x at: 2. "char at location"
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 640be0cd..f7a41ce1 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -114,7 +114,7 @@ class Point {
}
// Functions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
// Static members
static origin = new Point(0, 0);
@@ -137,9 +137,9 @@ class Point3D extends Point {
}
// Overwrite
- dist() {
+ dist(): number {
let d = super.dist();
- return Math.sqrt(d() * d() + this.z * this.z);
+ return Math.sqrt(d * d + this.z * this.z);
}
}
diff --git a/vim.html.markdown b/vim.html.markdown
index 65efc25c..55649cb2 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -13,6 +13,9 @@ editor designed for speed and increased productivity, and is ubiquitous in most
unix-based systems. It has numerous keybindings for speedy navigation to
specific points in the file, and for fast editing.
+`vimtutor` is a an excellent application that teaches you how to use `Vim`. It comes with the vim package during installation. You should be able to just run "vimtutor" on the command line to open this tutor. It will guide you through all the major features in `vim`.
+
+
## Basics of navigating Vim
```
@@ -182,6 +185,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
~ # Toggle letter case of selected text
u # Selected text to lower case
U # Selected text to upper case
+ J # Join the current line with the next line
# Fold text
zf # Create fold from selected text
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 8eecc56e..7286fa9f 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -128,7 +128,7 @@ printf("Enter the array size: "); // 询问用户数组长度
char buf[0x100];
fgets(buf, sizeof buf, stdin);
-// stroul 将字符串解析为无符号整数
+// strtoul 将字符串解析为无符号整数
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // 声明VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
diff --git a/zh-cn/make-cn.html.markdown b/zh-cn/make-cn.html.markdown
index 76dde941..641714ef 100644
--- a/zh-cn/make-cn.html.markdown
+++ b/zh-cn/make-cn.html.markdown
@@ -23,7 +23,7 @@ Makefile 用于定义如何创建目标文件, 比如如何从源码到可执行
```make
# 这行表示注释
-# 文件名一定要交 Makefile, 大小写区分, 使用 `make <target>` 生成 target
+# 文件名一定要叫 Makefile, 大小写区分, 使用 `make <target>` 生成 target
# 如果想要取别的名字, 可以用 `make -f "filename" <target>`.
# 重要的事情 - 只认识 TAB, 空格是不认的, 但是在 GNU Make 3.82 之后, 可以通过
@@ -87,7 +87,7 @@ ex0.txt ex1.txt: maker
maker:
touch ex0.txt ex1.txt
-# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显示的指明哪些 targets 是 phony
+# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显式地指明哪些 targets 是 phony
.PHONY: all maker process
# This is a special target. There are several others.
@@ -116,7 +116,7 @@ process: ex1.txt file0.txt
# 模式匹配
#-----------------------------------------------------------------------
-# 可以让 make 知道如何转换某些文件到别格式
+# 可以让 make 知道如何转换某些文件到其他格式
# 比如 从 svg 到 png
%.png: %.svg
inkscape --export-png $^
@@ -149,7 +149,7 @@ echo:
@echo $(name)
@echo ${name2}
@echo $name # 这个会被蠢蠢的解析成 $(n)ame.
- @echo \"$(name3)\" # 为声明的变量或扩展成空字符串.
+ @echo \"$(name3)\" # 未声明的变量会被处理成空字符串.
@echo $(name4)
@echo $(name5)
# 你可以通过4种方式设置变量.
diff --git a/zh-cn/opencv-cn.html.markdown b/zh-cn/opencv-cn.html.markdown
new file mode 100644
index 00000000..06b997d5
--- /dev/null
+++ b/zh-cn/opencv-cn.html.markdown
@@ -0,0 +1,145 @@
+---
+category: tool
+tool: OpenCV
+filename: learnopencv.py
+contributors:
+ - ["Yogesh Ojha", "http://github.com/yogeshojha"]
+translators:
+ - ["GengchenXU", "https://github.com/GengchenXU"]
+lang: zh-cn
+---
+### Opencv
+
+Opencv(开源计算机视觉)是一个编程功能库,主要面向实时计算机视觉。最初由英特尔开发,后来由Willow Garage,然后Itseez(后来被英特尔收购)支持。Opencv 目前支持多种语言,如C++、Python、Java 等
+
+#### 安装
+有关在计算机上安装 OpenCV,请参阅这些文章。
+
+* Windows 安装说明: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]()
+* Mac 安装说明 (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]()
+* Linux 安装说明 (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]()
+
+### 在这里,我们将专注于 OpenCV 的 python 实现
+
+```python
+# OpenCV读取图片
+import cv2
+img = cv2.imread('cat.jpg')
+
+# 显示图片
+# imshow() 函数被用来显示图片
+cv2.imshow('Image',img)
+# 第一个参数是窗口的标题,第二个参数是image
+# 如果你得到错误,对象类型为None,你的图像路径可能是错误的。请重新检查图像包
+cv2.waitKey(0)
+# waitKey() 是一个键盘绑定函数,参数以毫秒为单位。对于GUI事件,必须使用waitKey()函数。
+
+# 保存图片
+cv2.imwrite('catgray.png',img)
+# 第一个参数是文件名,第二个参数是图像
+
+# 转换图像灰度
+gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+
+# 从摄像头捕捉视频
+cap = cv2.VideoCapture(0)
+#0 是你的相机,如果你有多台相机,你需要输入他们的id
+while(True):
+ # 一帧一帧地获取
+ _, frame = cap.read()
+ cv2.imshow('Frame',frame)
+ # 当用户按下q ->退出
+ if cv2.waitKey(1) & 0xFF == ord('q'):
+ break
+# 相机必须释放
+cap.release()
+
+# 在文件中播放视频
+cap = cv2.VideoCapture('movie.mp4')
+while(cap.isOpened()):
+ _, frame = cap.read()
+ # 灰度播放视频
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+ cv2.imshow('frame',gray)
+ if cv2.waitKey(1) & 0xFF == ord('q'):
+ break
+cap.release()
+
+# 在OpenCV中画线
+# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)(注 color颜色rgb参数 thickness粗细)
+cv2.line(img,(0,0),(511,511),(255,0,0),5)
+
+# 画矩形
+# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)
+# 粗细= -1用于填充矩形
+cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
+
+# 画圆
+cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness)
+cv2.circle(img,(200,90), 100, (0,0,255), -1)
+
+# 画椭圆
+cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
+
+# 在图像上增加文字
+cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
+
+# 合成图像
+img1 = cv2.imread('cat.png')
+img2 = cv2.imread('openCV.jpg')
+dst = cv2.addWeighted(img1,0.5,img2,0.5,0)
+
+# 阈值图像
+# 二进制阈值
+_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
+# Adaptive Thresholding
+adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
+
+# 模糊的形象
+# 高斯模糊
+blur = cv2.GaussianBlur(img,(5,5),0)
+# 模糊中值
+medianBlur = cv2.medianBlur(img,5)
+
+# Canny 边缘检测
+img = cv2.imread('cat.jpg',0)
+edges = cv2.Canny(img,100,200)
+
+# 用Haar Cascades进行人脸检测
+# 下载 Haar Cascades 在 https://github.com/opencv/opencv/blob/master/data/haarcascades/
+import cv2
+import numpy as np
+face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
+eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
+
+img = cv2.imread('human.jpg')
+gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+
+aces = face_cascade.detectMultiScale(gray, 1.3, 5)
+for (x,y,w,h) in faces:
+ cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
+ roi_gray = gray[y:y+h, x:x+w]
+ roi_color = img[y:y+h, x:x+w]
+ eyes = eye_cascade.detectMultiScale(roi_gray)
+ for (ex,ey,ew,eh) in eyes:
+ cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
+
+cv2.imshow('img',img)
+cv2.waitKey(0)
+
+cv2.destroyAllWindows()
+# destroyAllWindows() destroys all windows.
+# 如果您希望销毁特定窗口,请传递您创建的窗口的确切名称。
+```
+
+### 进一步阅读:
+
+* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]()
+* OpenCV 绘图函数 [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]()
+* 最新的语言参考 [https://opencv.org]()
+* 更多的资源 [https://en.wikipedia.org/wiki/OpenCV]()
+* 优秀的的 OpenCV 教程
+ * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]()
+ * [https://realpython.com/python-opencv-color-spaces]()
+ * [https://pyimagesearch.com]()
+ * [https://www.learnopencv.com]()
diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown
index 5b0d6179..4421da6e 100644
--- a/zh-cn/perl-cn.html.markdown
+++ b/zh-cn/perl-cn.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: zh-cn
---
-Perl 5是一个功能强大、特性齐全的编程语言,有25年的历史。
+Perl 是一个功能强大、特性齐全的编程语言,有25年的历史。
-Perl 5可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
+Perl 可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
```perl
# 单行注释以#号开头
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index da13275b..6c5556fc 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -436,9 +436,9 @@ all_the_args(1, 2, a=3, b=4) prints:
# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
-all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
-all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # 相当于 all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # 相当于 all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)
# 函数作用域
diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown
index 756081d6..f8aa2332 100644
--- a/zh-cn/pythonlegacy-cn.html.markdown
+++ b/zh-cn/pythonlegacy-cn.html.markdown
@@ -163,7 +163,7 @@ li[:3] # => [1, 2, 4]
del li[2] # li 现在是 [1, 2, 3]
# 合并列表
-li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表
+li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会改变这两个列表
# 通过拼接来合并列表
li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6]
diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown
index 7b6ff305..cfa22dfb 100644
--- a/zh-cn/yaml-cn.html.markdown
+++ b/zh-cn/yaml-cn.html.markdown
@@ -5,27 +5,27 @@ contributors:
translators:
- ["Zach Zhang", "https://github.com/checkcheckzz"]
- ["Jiang Haiyun", "https://github.com/haiiiiiyun"]
+ - ["Wen Sun", "https://github.com/HermitSun"]
filename: learnyaml-cn.yaml
lang: zh-cn
---
-YAML 是一个数据序列化语言,被设计成人类直接可写可读的。
+YAML 是一种数据序列化语言,旨在让人类直接可写可读。
-它是 JSON 的严格超集,增加了语法显著换行符和缩进,就像 Python。但和 Python 不一样,
-YAML 根本不容许文字制表符。
+它是 JSON 的严格超集,增加了*在语法上有意义的*(syntactically significant)换行符和缩进,就像 Python 一样。但和 Python 的不同之处在于,YAML 不允许使用*文字制表符*(literal tab characters)来表示缩进。
```yaml
--- # 文档开头
-# YAML 中的注解看起来像这样。
+# YAML 中的注释看起来像这样。
################
# 标量类型 #
################
-# 我们的根对象 (它们在整个文件里延续) 将会是一个映射,
-# 它等价于在别的语言里的一个字典,哈希表或对象。
+# 我们的根对象 (贯穿整个文档的始终) 是一个映射(map),
+# 它等价于其它语言中的一个字典(dictionary),哈希表(hash)或对象(object)。
key: value
another_key: Another value goes here.
a_number_value: 100
@@ -35,16 +35,16 @@ scientific_notation: 1e+12
boolean: true
null_value: null
key with spaces: value
-# 注意,字符串不必被括在引号中,但也可以被括起来。
+# 注意,字符串可以不括在引号里。当然,也可以括在引号里。
however: 'A string, enclosed in quotes.'
'Keys can be quoted too.': "Useful if you want to put a ':' in your key."
single quotes: 'have ''one'' escape pattern'
double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more."
-# UTF-8/16/32 字符需要被转义(encoded)
+# UTF-8/16/32字符需要指明编码(通过\u)。
Superscript two: \u00B2
-# 多行字符串既可以写成像一个'文字块'(使用 |),
-# 或像一个'折叠块'(使用 '>')。
+# 多行字符串既可以写成一个'字面量块'(使用 '|'),
+# 也可以写成一个'折叠块'(使用 '>')。
literal_block: |
This entire block of text will be the value of the 'literal_block' key,
with line breaks being preserved.
@@ -67,7 +67,7 @@ folded_style: >
# 集合类型 #
####################
-# 嵌套是通过缩进完成的。推荐使用 2 个空格的缩进(但非必须)
+# 嵌套是通过缩进完成的。推荐使用 2 个空格的缩进(但非必须)。
a_nested_map:
key: value
another_key: Another Value
@@ -77,22 +77,22 @@ a_nested_map:
# 映射的键不必是字符串。
0.25: a float key
-# 键也可以是复合型的,比如多行对象
-# 我们用 ? 后跟一个空格来表示一个复合键的开始。
+# 键也可以是复合(complex)的,比如多行对象
+# 我们用 '?' 后跟一个空格来表示一个复合键的开始。
? |
This is a key
that has multiple lines
: and this is its value
# YAML 也允许使用复杂键语法表示序列间的映射关系。
-# 但有些语言的解析器可能会不支持。
+# 但有些解析器可能会不支持。
# 一个例子:
? - Manchester United
- Real Madrid
: [ 2001-01-01, 2002-02-02 ]
-# 序列 (等价于列表或数组) 看起来像这样:
-# 注意 '-' 算作缩进
+# 序列 (sequences,等价于列表 list 或数组 array ) 看起来像这样:
+# 注意 '-' 也算缩进:
a_sequence:
- Item 1
- Item 2
@@ -115,7 +115,7 @@ and quotes are optional: {key: [3, 2, 1, takeoff]}
# 其余的 YAML 特性 #
#######################
-# YAML 还有一个方便的特性叫 '锚',它能让你很容易在文档中进行文本复用。
+# YAML 还有一个方便的特性叫“锚”(anchors)。你可以使用它在文档中轻松地完成文本复用。
# 如下两个键会有相同的值:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
@@ -124,8 +124,8 @@ other_anchor: *anchor_name
base: &base
name: Everyone has same name
-# The regexp << is called Merge Key Language-Independent Type.
-# 它表明指定映射的所有键值会插入到当前的映射中。
+# '<<'称为语言无关的合并键类型(Merge Key Language-Independent Type).
+# 它表明一个或多个指定映射中的所有键值会插入到当前的映射中。
foo: &foo
<<: *base
@@ -137,22 +137,22 @@ bar: &bar
# foo 和 bar 将都含有 name: Everyone has same name
-# YAML 还有标签,你可以用它显式地声明类型。
+# YAML 还有标签(tags),你可以用它显式地声明类型。
explicit_string: !!str 0.5
-# 一些解析器实现特定语言的标签,就像这个针对 Python 的复数类型。
+# 一些解析器实现了特定语言的标签,就像这个针对Python的复数类型的标签。
python_complex_number: !!python/complex 1+2j
-# 我们也可以在 YAML 的复合键中使用特定语言的标签
+# 我们也可以在 YAML 的复合键中使用特定语言的标签:
? !!python/tuple [5, 7]
: Fifty Seven
-# 将会是 Python 中的 {(5, 7): 'Fifty Seven'}
+# 将会是 Python 中的 {(5, 7): 'Fifty Seven'}
####################
# 其余的 YAML 类型 #
####################
-# 除了字符串和数字,YAML 还能理解其它标量。
-# ISO 格式的日期和日期时间文本也可以被解析。
+# 除了字符串和数字,YAML 还支持其它标量。
+# ISO 格式的日期和时间字面量也可以被解析。
datetime: 2001-12-15T02:59:43.1Z
datetime_with_spaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
@@ -165,14 +165,14 @@ gif_file: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML 还有一个集合类型,它看起来像这样:
+# YAML 还有一个集合(set)类型,它看起来像这样:
set:
? item1
? item2
? item3
or: {item1, item2, item3}
-# 集合只是值为 null 的映射;上面的集合等价于:
+# 集合只是值均为 null 的映射;上面的集合等价于:
set2:
item1: null
item2: null
@@ -184,4 +184,5 @@ set2:
### 更多资源
+ [YAML official website](http://yaml.org/)
++ [Online YAML Converter](http://yamlonline.com)
+ [Online YAML Validator](http://codebeautify.org/yaml-validator)