summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--CHICKEN.html.markdown4
-rw-r--r--CONTRIBUTING.markdown7
-rw-r--r--awk.html.markdown4
-rw-r--r--bash.html.markdown89
-rw-r--r--c.html.markdown12
-rw-r--r--ca-es/asciidoc-ca.html.markdown134
-rw-r--r--ca-es/groovy-ca.html.markdown4
-rw-r--r--chapel.html.markdown30
-rw-r--r--clojure-macros.html.markdown2
-rw-r--r--crystal.html.markdown3
-rw-r--r--cs-cz/elm.html.markdown4
-rw-r--r--csharp.html.markdown209
-rw-r--r--de-de/LOLCODE-de.html.markdown188
-rw-r--r--de-de/dynamic-programming-de.html.markdown77
-rw-r--r--de-de/edn-de.html.markdown112
-rw-r--r--de-de/git-de.html.markdown6
-rw-r--r--de-de/html-de.html.markdown4
-rw-r--r--de-de/nix-de.html.markdown358
-rw-r--r--de-de/pyqt-de.html.markdown89
-rw-r--r--de-de/qt-de.html.markdown175
-rw-r--r--de-de/swift-de.html.markdown32
-rw-r--r--dynamic-programming.html.markdown2
-rw-r--r--edn.html.markdown32
-rw-r--r--elm.html.markdown4
-rw-r--r--es-es/groovy-es.html.markdown4
-rw-r--r--es-es/learnsmallbasic-es.html.markdown132
-rw-r--r--es-es/swift-es.html.markdown30
-rw-r--r--forth.html.markdown2
-rw-r--r--fr-fr/crystal-fr.html.markdown1
-rw-r--r--fr-fr/d-fr.html.markdown (renamed from fr-fr/d.html.markdown)0
-rw-r--r--fr-fr/haskell-fr.html.markdown (renamed from fr-fr/haskell.html.markdown)0
-rw-r--r--fr-fr/java-fr.html.markdown939
-rw-r--r--fr-fr/markdown-fr.html.markdown (renamed from fr-fr/markdown.html.markdown)0
-rw-r--r--fr-fr/php-fr.html.markdown (renamed from fr-fr/php.html.markdown)84
-rw-r--r--fr-fr/scala-fr.html.markdown (renamed from fr-fr/scala.html.markdown)0
-rw-r--r--fr-fr/vim-fr.html.markdown (renamed from fr-fr/vim.html.markdown)0
-rw-r--r--git.html.markdown4
-rw-r--r--go.html.markdown2
-rw-r--r--groovy.html.markdown4
-rw-r--r--haml.html.markdown52
-rw-r--r--haxe.html.markdown4
-rw-r--r--html.html.markdown2
-rw-r--r--hu-hu/python-hu.html.markdown816
-rw-r--r--id-id/bf-id.html.markdown86
-rw-r--r--id-id/hq9+-id.html.markdown45
-rw-r--r--id-id/rst-id.html.markdown122
-rw-r--r--it-it/go-it.html.markdown44
-rw-r--r--it-it/html-it.html.markdown121
-rw-r--r--it-it/markdown.html.markdown194
-rw-r--r--it-it/matlab-it.html.markdown2
-rw-r--r--it-it/rst-it.html.markdown111
-rw-r--r--java.html.markdown55
-rw-r--r--javascript.html.markdown47
-rw-r--r--lambda-calculus.html.markdown121
-rw-r--r--latex.html.markdown2
-rw-r--r--nim.html.markdown23
-rw-r--r--nix.html.markdown6
-rw-r--r--perl6.html.markdown1274
-rw-r--r--prolog.html.markdown16
-rw-r--r--pt-br/amd-pt.html.markdown (renamed from pt-br/amd.html.markdown)2
-rw-r--r--pt-br/asciidoc-pt.html.markdown2
-rw-r--r--pt-br/asymptotic-notation-pt.html.markdown2
-rw-r--r--pt-br/asymptoticnotation-pt.html.markdown161
-rw-r--r--pt-br/awk-pt.html.markdown376
-rw-r--r--pt-br/bf-pt.html.markdown (renamed from pt-br/bf.html.markdown)0
-rw-r--r--pt-br/c++-pt.html.markdown12
-rw-r--r--pt-br/c-pt.html.markdown4
-rw-r--r--pt-br/csharp-pt.html.markdown (renamed from pt-br/csharp.html.markdown)36
-rw-r--r--pt-br/css-pt.html.markdown2
-rw-r--r--pt-br/dynamic-programming-pt.html.markdown10
-rw-r--r--pt-br/elixir-pt.html.markdown (renamed from pt-br/elixir.html.markdown)0
-rw-r--r--pt-br/elm-pt.html.markdown4
-rw-r--r--pt-br/groovy-pt.html.markdown4
-rw-r--r--pt-br/java-pt.html.markdown2
-rw-r--r--pt-br/javascript-pt.html.markdown2
-rw-r--r--pt-br/json-pt.html.markdown2
-rw-r--r--pt-br/latex-pt.html.markdown291
-rw-r--r--pt-br/perl-pt.html.markdown6
-rw-r--r--pt-br/pyqt-pt.html.markdown92
-rw-r--r--pt-br/qt-pt.html.markdown174
-rw-r--r--pt-br/rust-pt.html.markdown (renamed from rust-pt.html.markdown)0
-rw-r--r--pt-br/swift-pt.html.markdown10
-rw-r--r--pt-br/visualbasic-pt.html.markdown12
-rw-r--r--pt-br/whip-pt.html.markdown247
-rw-r--r--pt-pt/bf-pt.html.markdown (renamed from pt-pt/bf.html.markdown)0
-rw-r--r--pt-pt/swift-pt.html.markdown (renamed from pt-pt/swift.html.markdown)32
-rw-r--r--python.html.markdown6
-rw-r--r--python3.html.markdown136
-rw-r--r--pythonstatcomp.html.markdown7
-rw-r--r--r.html.markdown3
-rw-r--r--ru-ru/haml-ru.html.markdown233
-rw-r--r--ru-ru/php-ru.html.markdown2
-rw-r--r--ru-ru/python3-ru.html.markdown3
-rw-r--r--ru-ru/ruby-ru.html.markdown5
-rw-r--r--ru-ru/swift-ru.html.markdown38
-rw-r--r--sk-sk/bash-sk.html.markdown (renamed from sk-sk/bash.html.markdown)0
-rw-r--r--sk-sk/coffeescript-sk.html.markdown (renamed from sk-sk/coffeescript.html.markdown)0
-rw-r--r--sk-sk/elixir-sk.html.markdown (renamed from sk-sk/elixir.html.markdown)0
-rw-r--r--sk-sk/git-sk.html.markdown (renamed from sk-sk/git.html.markdown)0
-rw-r--r--sk-sk/json-sk.html.markdown (renamed from sk-sk/json.html.markdown)0
-rw-r--r--sk-sk/latex-sk.html.markdown.tex (renamed from sk-sk/latex.html.markdown.tex)0
-rw-r--r--sk-sk/ruby-sk.html.markdown (renamed from sk-sk/ruby.html.markdown)0
-rw-r--r--smalltalk.html.markdown4
-rw-r--r--solidity.html.markdown207
-rw-r--r--swift.html.markdown38
-rw-r--r--tr-tr/swift-tr.html.markdown32
-rw-r--r--typescript.html.markdown4
-rw-r--r--uk-ua/javascript-ua.html.markdown2
-rw-r--r--vi-vn/less-vi.html.markdown395
-rw-r--r--vi-vn/markdown-vi.html.markdown325
-rw-r--r--vi-vn/sass-vi.html.markdown590
-rw-r--r--vi-vn/typescript-vi.html.markdown193
-rw-r--r--vim.html.markdown42
-rw-r--r--whip.html.markdown2
-rw-r--r--yaml.html.markdown81
-rw-r--r--zfs.html.markdown2
-rw-r--r--zh-cn/go-cn.html.markdown1
-rw-r--r--zh-cn/groovy-cn.html.markdown4
-rw-r--r--zh-cn/javascript-cn.html.markdown7
-rw-r--r--zh-cn/kotlin-cn.html.markdown33
-rw-r--r--zh-cn/swift-cn.html.markdown30
121 files changed, 8412 insertions, 1424 deletions
diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown
index 7fb0270b..bb2f91f0 100644
--- a/CHICKEN.html.markdown
+++ b/CHICKEN.html.markdown
@@ -8,7 +8,7 @@ contributors:
CHICKEN is an implementation of Scheme programming language that can
compile Scheme programs to C code as well as interpret them. CHICKEN
-supports RSR5 and RSR7 (work in progress) standards and many extensions.
+supports R5RS and R7RS (work in progress) standards and many extensions.
```scheme
@@ -510,7 +510,7 @@ sqr ;; => #<procedure (sqr x)>
```
## Further Reading
* [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual).
-* [RSR5 standards](http://www.schemers.org/Documents/Standards/R5RS)
+* [R5RS standards](http://www.schemers.org/Documents/Standards/R5RS)
## Extra Info
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
index 5fa1d03d..455c3256 100644
--- a/CONTRIBUTING.markdown
+++ b/CONTRIBUTING.markdown
@@ -71,3 +71,10 @@ contributors:
lang: ep-ep
---
```
+
+### Should I add myself as a Contributor?
+
+If you want to add yourself to contributors, keep in mind that contributors get
+equal billing, and the first contributor usually wrote the whole article. Please
+use your judgement when deciding if your contribution constitutes a substantial
+addition or not.
diff --git a/awk.html.markdown b/awk.html.markdown
index 0e27528d..e3ea6318 100644
--- a/awk.html.markdown
+++ b/awk.html.markdown
@@ -38,7 +38,7 @@ BEGIN {
a = count + 1
b = count - 1
c = count * 1
- d = count / 1
+ d = count / 1 # integer division
e = count % 1 # modulus
f = count ^ 1 # exponentiation
@@ -143,7 +143,7 @@ BEGIN {
}
# Here's how you define a function
-function arithmetic_functions(a, b, c, localvar) {
+function arithmetic_functions(a, b, c, d) {
# Probably the most annoying part of AWK is that there are no local
# variables. Everything is global. For short scripts, this is fine, even
diff --git a/bash.html.markdown b/bash.html.markdown
index 14366e4c..0c097c27 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -15,6 +15,7 @@ contributors:
- ["Leo Rudberg", "https://github.com/LOZORD"]
- ["Betsy Lorton", "https://github.com/schbetsy"]
- ["John Detter", "https://github.com/jdetter"]
+ - ["Harry Mumford-Turner", "https://github.com/harrymt"]
filename: LearnBash.sh
---
@@ -30,59 +31,62 @@ Nearly all examples below can be a part of a shell script or executed directly i
# As you already figured, comments start with #. Shebang is also a comment.
# Simple hello world example:
-echo Hello world!
+echo Hello world! # => Hello world!
# Each command starts on a new line, or after semicolon:
echo 'This is the first line'; echo 'This is the second line'
+# => This is the first line
+# => This is the second line
# Declaring a variable looks like this:
Variable="Some string"
# But not like this:
-Variable = "Some string"
+Variable = "Some string" # => returns error "Variable: command not found"
# Bash will decide that Variable is a command it must execute and give an error
# because it can't be found.
# Or like this:
-Variable= 'Some string'
+Variable= 'Some string' # => returns error: "Some string: command not found"
# Bash will decide that 'Some string' is a command it must execute and give an
# error because it can't be found. (In this case the 'Variable=' part is seen
# as a variable assignment valid only for the scope of the 'Some string'
# command.)
# Using the variable:
-echo $Variable
-echo "$Variable"
-echo '$Variable'
+echo $Variable # => Some string
+echo "$Variable" # => Some string
+echo '$Variable' # => $Variable
# When you use the variable itself — assign it, export it, or else — you write
# its name without $. If you want to use the variable's value, you should use $.
# Note that ' (single quote) won't expand the variables!
# Parameter expansion ${ }:
-echo ${Variable}
+echo ${Variable} # => Some string
# This is a simple usage of parameter expansion
# Parameter Expansion gets a value from a variable. It "expands" or prints the value
# During the expansion time the value or parameter are able to be modified
# Below are other modifications that add onto this expansion
# String substitution in variables
-echo ${Variable/Some/A}
+echo ${Variable/Some/A} # => A string
# This will substitute the first occurrence of "Some" with "A"
# Substring from a variable
Length=7
-echo ${Variable:0:Length}
+echo ${Variable:0:Length} # => Some st
# This will return only the first 7 characters of the value
# Default value for variable
-echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
+echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
+# => DefaultValueIfFooIsMissingOrEmpty
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.
# Brace Expansion { }
# Used to generate arbitrary strings
-echo {1..10}
-echo {a..z}
+echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
+echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z
# This will output the range from the start value to the end value
# Builtin variables:
@@ -121,6 +125,7 @@ then
else
echo "Your name is your username"
fi
+# True if the value of $Name is not equal to the current user's login username
# NOTE: if $Name is empty, bash sees the above condition as:
if [ != $USER ]
@@ -133,7 +138,11 @@ if [ "" != $USER ] ...
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
+# => Always executed
echo "Always executed" && echo "Only executed if first command does NOT fail"
+# => Always executed
+# => Only executed if first command does NOT fail
+
# To use && and || with if statements, you need multiple pairs of square brackets:
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
@@ -147,12 +156,12 @@ then
fi
# Expressions are denoted with the following format:
-echo $(( 10 + 5 ))
+echo $(( 10 + 5 )) # => 15
# Unlike other programming languages, bash is a shell so it works in the context
# of a current directory. You can list files and directories in the current
# directory with the ls command:
-ls
+ls # Lists the files and subdirectories contained in the current directory
# These commands have options that control their execution:
ls -l # Lists every file and directory on a separate line
@@ -169,7 +178,10 @@ cat file.txt
# We can also read the file using `cat`:
Contents=$(cat file.txt)
-echo "START OF FILE\n$Contents\nEND OF FILE"
+echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character
+# => START OF FILE
+# => [contents of file.txt]
+# => END OF FILE
# Use `cp` to copy files or directories from one place to another.
# `cp` creates NEW versions of the sources,
@@ -203,6 +215,8 @@ pwd # still in first directory
mkdir myNewDir
# The `-p` flag causes new intermediate directories to be created as necessary.
mkdir -p myNewDir/with/intermediate/directories
+# if the intermediate directories didn't already exist, running the above
+# command without the `-p` flag would return an error
# You can redirect command input and output (stdin, stdout, and stderr).
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
@@ -217,12 +231,13 @@ for line in sys.stdin:
print(line, file=sys.stdout)
EOF
-# Run hello.py with various stdin, stdout, and stderr redirections:
-python hello.py < "input.in"
-python hello.py > "output.out"
-python hello.py 2> "error.err"
-python hello.py > "output-and-error.log" 2>&1
-python hello.py > /dev/null 2>&1
+# Run the hello.py Python script with various stdin, stdout, and
+# stderr redirections:
+python hello.py < "input.in" # pass input.in as input to the script
+python hello.py > "output.out" # redirect output from the script to output.out
+python hello.py 2> "error.err" # redirect error output to error.err
+python hello.py > "output-and-error.log" 2>&1 # redirect both output and errors to output-and-error.log
+python hello.py > /dev/null 2>&1 # redirect all output and errors to the black hole, /dev/null, i.e., no output
# The output error will overwrite the file if it exists,
# if you want to append instead, use ">>":
python hello.py >> "output.out" 2>> "error.err"
@@ -269,12 +284,19 @@ for Variable in {1..3}
do
echo "$Variable"
done
+# => 1
+# => 2
+# => 3
+
# Or write it the "traditional for loop" way:
for ((a=1; a <= 3; a++))
do
echo $a
done
+# => 1
+# => 2
+# => 3
# They can also be used to act on files..
# This will run the command 'cat' on file1 and file2
@@ -296,6 +318,7 @@ do
echo "loop body here..."
break
done
+# => loop body here...
# You can also define functions
# Definition:
@@ -306,6 +329,11 @@ function foo ()
echo "This is a function"
return 0
}
+# Call the function `foo` with two arguments, arg1 and arg2:
+foo arg1 arg2
+# => Arguments work just like script arguments: arg1 arg2
+# => And: arg1 arg2...
+# => This is a function
# or simply
bar ()
@@ -313,6 +341,8 @@ bar ()
echo "Another way to declare functions!"
return 0
}
+# Call the function `bar` with no arguments:
+bar # => Another way to declare functions!
# Calling your function
foo "My name is" $Name
@@ -320,25 +350,35 @@ foo "My name is" $Name
# There are a lot of useful commands you should learn:
# prints last 10 lines of file.txt
tail -n 10 file.txt
+
# prints first 10 lines of file.txt
head -n 10 file.txt
+
# sort file.txt's lines
sort file.txt
+
# report or omit repeated lines, with -d it reports them
uniq -d file.txt
+
# prints only the first column before the ',' character
cut -d ',' -f 1 file.txt
-# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible)
+
+# replaces every occurrence of 'okay' with 'great' in file.txt
+# (regex compatible)
sed -i 's/okay/great/g' file.txt
+
# print to stdout all lines of file.txt which match some regex
# The example prints lines which begin with "foo" and end in "bar"
grep "^foo.*bar$" file.txt
+
# pass the option "-c" to instead print the number of lines matching the regex
grep -c "^foo.*bar$" file.txt
+
# Other useful options are:
grep -r "^foo.*bar$" someDir/ # recursively `grep`
grep -n "^foo.*bar$" file.txt # give line numbers
grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files
+
# perform the same initial search, but filter out the lines containing "baz"
grep "^foo.*bar$" file.txt | grep -v "baz"
@@ -346,8 +386,9 @@ grep "^foo.*bar$" file.txt | grep -v "baz"
# and not the regex, use fgrep (or grep -F)
fgrep "foobar" file.txt
-# trap command allows you to execute a command when a signal is received by your script.
-# Here trap command will execute rm if any one of the three listed signals is received.
+# The trap command allows you to execute a command whenever your script
+# receives a signal. Here, trap will execute `rm` if it receives any of the
+# three listed signals.
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
# `sudo` is used to perform commands as the superuser
diff --git a/c.html.markdown b/c.html.markdown
index 1ff8658c..0c6df413 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Marco Scannadinari", "https://marcoms.github.io"]
- ["Zachary Ferguson", "https://github.io/zfergus2"]
- ["himanshu", "https://github.com/himanshu81494"]
+ - ["Joshua Li", "https://github.com/JoshuaRLi"]
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -19,11 +20,12 @@ memory management and C will take you as far as you need to go.
> **About compiler flags**
>
> By default, gcc and clang are pretty quiet about compilation warnings and
-> errors, which can be very useful information. Using some
-> stricter compiler flags is recommended. Here is an example you can
-> tweak to your liking:
+> errors, which can be very useful information. Explicitly using stricter
+> compiler flags is recommended. Here are some recommended defaults:
>
-> `-Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11`
+> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic`
+>
+> For information on what these flags do as well as other flags, consult the man page for your C compiler (e.g. `man 1 gcc`) or just search online.
```c
// Single-line comments start with // - only available in C99 and later.
@@ -348,7 +350,7 @@ int main (int argc, char** argv)
printf("Error occurred at i = %d & j = %d.\n", i, j);
/*
https://ideone.com/GuPhd6
- this will print out "Error occurred at i = 52 & j = 99."
+ this will print out "Error occurred at i = 51 & j = 99."
*/
///////////////////////////////////////
diff --git a/ca-es/asciidoc-ca.html.markdown b/ca-es/asciidoc-ca.html.markdown
new file mode 100644
index 00000000..a88aba52
--- /dev/null
+++ b/ca-es/asciidoc-ca.html.markdown
@@ -0,0 +1,134 @@
+---
+language: asciidoc
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+translators:
+ - ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
+lang: ca-es
+filename: asciidoc-ca.md
+---
+
+AsciiDoc és un llenguatge de marques similar a Markdown i que pot ser usat per qualsevol ús, des de llibres fins a blogs.
+Creat al 2002 per Stuart Rackham, és un llenguatge simple però permet un gran nivell de personalització.
+
+Capçalera de document
+
+La capçalera és opcional i no pot contenir línies buides. Ha d'estar separada del contingut per com a mínim una línia en blanc.
+
+Només títol
+
+```
+= Títol del document
+
+Primer contingut del document.
+```
+
+Títol i autor
+
+```
+= Títol del document
+Nom Cognom(s) <nom.cognom@learnxinyminutes.com>
+
+Inici d'aquest document.
+```
+
+Múltiples autors
+
+```
+= Títol del document
+John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
+
+Inici d'un document amb múltiples autors.
+```
+
+Línia de versió (requereix línia d'autor)
+
+```
+= Títol del document V1
+Potato Man <chip@crunchy.com>
+v1.0, 2016-01-13
+
+Aquest article sobre patates fregides serà genial.
+```
+
+Paràgraf
+
+```
+No necessites res especial per un paràgraf.
+
+Insereix una línia buida entre cada paràgraf per separar-los.
+
+Per inserir un salt de línia, afegeix només un +
+i ja ho tens!
+```
+
+Donant format al text
+
+```
+_guió baix per cursiva_
+*asteriscs per negreta*
+*_combina'ls i veuràs_*
+`usa cometes invertides per monospace`
+`*combina per negreta monospace*`
+```
+
+Títols de secció
+
+```
+= Nivell 0 (usa'l només pel títol del document)
+
+== Nivell 1 <h2>
+
+=== Nivell 2 <h3>
+
+==== Nivell 3 <h4>
+
+===== Nivell 4 <h5>
+```
+
+Llistes
+
+Per crear una llista sense ordre usa asteriscs.
+
+```
+* foo
+* bar
+* baz
+```
+
+Per crear una llista numerada usa punts.
+
+```
+. element 1
+. element 2
+. element 3
+```
+
+Pots crear fins a 5 subnivells de llista afegint asteriscs o punts.
+
+```
+* foo 1
+** foo 2
+*** foo 3
+**** foo 4
+***** foo 5
+
+. foo 1
+.. foo 2
+... foo 3
+.... foo 4
+..... foo 5
+```
+
+## Referències
+
+Existeixen dues eines per processar documentació en AsciiDoc:
+
+1. [AsciiDoc](http://asciidoc.org/): implementació original per Python, disponible a las principals distribucions Linux. Versió estable actualment en mode manteniment.
+2. [Asciidoctor](http://asciidoctor.org/): implementació alternativa per Ruby, usable també des de Java i JavaScript. Implementació completa en evolució, té com a objectiu ampliar AsciiDoc amb noves funcionalitats i conversors de sortida.
+
+Els següents enllaços pertanyen a `Asciidoctor` (documentació en anglès):
+
+* [Comparació de sintaxi Markdown - AsciiDoc](http://asciidoctor.org/docs/user-manual/#comparison-by-example): comparativa d'elements comuns entre Markdown i AsciiDoc.
+* [Primeres pases](http://asciidoctor.org/docs/#get-started-with-asciidoctor): manuals d'instal·lació i inici per convertir documents simples.
+* [Manual d'usuari d'Asciidoctor](http://asciidoctor.org/docs/user-manual/): referència completa en un únic document, conté exemples, guies d'eines, etc.
diff --git a/ca-es/groovy-ca.html.markdown b/ca-es/groovy-ca.html.markdown
index 57674970..f0a9adbe 100644
--- a/ca-es/groovy-ca.html.markdown
+++ b/ca-es/groovy-ca.html.markdown
@@ -233,10 +233,12 @@ for (i in array) {
//Itera per un mapa
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
-x = 0
+x = ""
for ( e in map ) {
x += e.value
+ x += " "
}
+assert x.equals("Roberto Grails Groovy ")
/*
Operadors
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 96ddc69d..9190f462 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -2,11 +2,11 @@
language: chapel
filename: learnchapel.chpl
contributors:
- - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"]
- - ["Ben Harshbarger", "http://github.com/benharsh/"]
+ - ["Ian J. Bertolacci", "https://www.cs.arizona.edu/~ianbertolacci/"]
+ - ["Ben Harshbarger", "https://github.com/benharsh/"]
---
-You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com).
+You can read all about Chapel at [Cray's official Chapel website](https://chapel-lang.org).
In short, Chapel is an open-source, high-productivity, parallel-programming
language in development at Cray Inc., and is designed to run on multi-core PCs
as well as multi-kilocore supercomputers.
@@ -188,7 +188,7 @@ if 10 < 100 then
if -1 < 1 then
writeln("Continuing to believe reality");
else
- writeln("Send mathematician, something's wrong");
+ writeln("Send mathematician, something is wrong");
// You can use parentheses if you prefer.
if (10 > 100) {
@@ -213,7 +213,7 @@ if a % 3 == 0 {
var maximum = if thisInt < thatInt then thatInt else thisInt;
// select statements are much like switch statements in other languages.
-// However, select statements don't cascade like in C or Java.
+// However, select statements do not cascade like in C or Java.
var inputOption = "anOption";
select inputOption {
when "anOption" do writeln("Chose 'anOption'");
@@ -223,7 +223,7 @@ select inputOption {
}
otherwise {
writeln("Any other Input");
- writeln("the otherwise case doesn't need a do if the body is one line");
+ writeln("the otherwise case does not need a do if the body is one line");
}
}
@@ -282,7 +282,7 @@ var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10
var reverse2to10by2 = 2..10 by -2; // 10, 8, 6, 4, 2
var trapRange = 10..1 by -1; // Do not be fooled, this is still an empty range
-writeln("Size of range '", trapRange, "' = ", trapRange.length);
+writeln("Size of range ", trapRange, " = ", trapRange.length);
// Note: range(boundedType= ...) and range(stridable= ...) are only
// necessary if we explicitly type the variable.
@@ -425,7 +425,7 @@ var thisPlusThat = thisArray + thatArray;
writeln(thisPlusThat);
// Moving on, arrays and loops can also be expressions, where the loop
-// body's expression is the result of each iteration.
+// body expression is the result of each iteration.
var arrayFromLoop = for i in 1..10 do i;
writeln(arrayFromLoop);
@@ -1124,16 +1124,16 @@ This tutorial is for people who want to learn the ropes of chapel without
having to hear about what fiber mixture the ropes are, or how they were
braided, or how the braid configurations differ between one another. It won't
teach you how to develop amazingly performant code, and it's not exhaustive.
-Refer to the [language specification](http://chapel.cray.com/language.html) and
-the [module documentation](http://chapel.cray.com/docs/latest/) for more
+Refer to the [language specification](https://chapel-lang.org/docs/latest/language/spec.html) and
+the [module documentation](https://chapel-lang.org/docs/latest/) for more
details.
-Occasionally check back here and on the [Chapel site](http://chapel.cray.com)
+Occasionally check back here and on the [Chapel site](https://chapel-lang.org)
to see if more topics have been added or more tutorials created.
### What this tutorial is lacking:
- * Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html)
+ * Exposition of the [standard modules](https://chapel-lang.org/docs/latest/modules/standard.html)
* Multiple Locales (distributed memory system)
* Records
* Parallel iterators
@@ -1141,7 +1141,7 @@ to see if more topics have been added or more tutorials created.
Your input, questions, and discoveries are important to the developers!
-----------------------------------------------------------------------
-The Chapel language is still in-development (version 1.15.0), so there are
+The Chapel language is still in-development (version 1.16.0), so there are
occasional hiccups with performance and language features. The more information
you give the Chapel development team about issues you encounter or features you
would like to see, the better the language becomes. Feel free to email the team
@@ -1158,8 +1158,8 @@ Chapel can be built and installed on your average 'nix machine (and cygwin).
[Download the latest release version](https://github.com/chapel-lang/chapel/releases/)
and it's as easy as
- 1. `tar -xvf chapel-1.15.0.tar.gz`
- 2. `cd chapel-1.15.0`
+ 1. `tar -xvf chapel-1.16.0.tar.gz`
+ 2. `cd chapel-1.16.0`
3. `source util/setchplenv.bash # or .sh or .csh or .fish`
4. `make`
5. `make check # optional`
diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown
index 89066faf..3864f676 100644
--- a/clojure-macros.html.markdown
+++ b/clojure-macros.html.markdown
@@ -131,7 +131,7 @@ You'll want to be familiar with Clojure. Make sure you understand everything in
; However, we'll need to make it a macro if we want it to be run at compile time
(defmacro inline-2 [form]
- (inline-2-helper form)))
+ (inline-2-helper form))
(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
diff --git a/crystal.html.markdown b/crystal.html.markdown
index 15cbc0b1..8210b443 100644
--- a/crystal.html.markdown
+++ b/crystal.html.markdown
@@ -301,7 +301,6 @@ end
(1..3).each do |index|
puts "Index: #{index}"
end
-# Index: 0
# Index: 1
# Index: 2
# Index: 3
@@ -422,7 +421,7 @@ class Human
@name
end
- # The above functionality can be encapsulated using the attr_accessor method as follows
+ # The above functionality can be encapsulated using the propery method as follows
property :name
# Getter/setter methods can also be created individually like this
diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown
index f19f9e8b..42ec89e5 100644
--- a/cs-cz/elm.html.markdown
+++ b/cs-cz/elm.html.markdown
@@ -75,8 +75,8 @@ List.head [] -- Nothing
-- K získání hodnot z dvojice použijte funkce first a second.
-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
-- Je to jediná hodnota svého typu, který se také nazývá "Unit".
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 963f38f4..f27adf18 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -132,6 +132,12 @@ namespace Learning.CSharp
DateTime fooDate = DateTime.Now;
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
+ // Verbatim String
+ // You can use the @ symbol before a string literal to escape all characters in the string
+ string path = "C:\\Users\\User\\Desktop";
+ string verbatimPath = @"C:\Users\User\Desktop";
+ Console.WriteLine(path == verbatimPath); // => true
+
// You can split a string over two lines with the @ symbol. To escape " use ""
string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";
@@ -634,6 +640,54 @@ on a new line! ""Wow!"", the masses cried";
}
}
+
+ // DELEGATES AND EVENTS
+ public class DelegateTest
+ {
+ public static int count = 0;
+ public static int Increment()
+ {
+ // increment count then return it
+ return ++count;
+ }
+
+ // A delegate is a reference to a method
+ // To reference the Increment method,
+ // first declare a delegate with the same signature
+ // ie. takes no arguments and returns an int
+ public delegate int IncrementDelegate();
+
+ // An event can also be used to trigger delegates
+ // Create an event with the delegate type
+ public static event IncrementDelegate MyEvent;
+
+ static void Main(string[] args)
+ {
+ // Refer to the Increment method by instantiating the delegate
+ // and passing the method itself in as an argument
+ IncrementDelegate inc = new IncrementDelegate(Increment);
+ Console.WriteLine(inc()); // => 1
+
+ // Delegates can be composed with the + operator
+ IncrementDelegate composedInc = inc;
+ composedInc += inc;
+ composedInc += inc;
+
+ // composedInc will run Increment 3 times
+ Console.WriteLine(composedInc()); // => 4
+
+
+ // Subscribe to the event with the delegate
+ MyEvent += new IncrementDelegate(Increment);
+ MyEvent += new IncrementDelegate(Increment);
+
+ // Trigger the event
+ // ie. run all delegates subscribed to this event
+ Console.WriteLine(MyEvent()); // => 6
+ }
+ }
+
+
// Class Declaration Syntax:
// <public/private/protected/internal> class <class name>{
// //data fields, constructors, functions all inside.
@@ -949,6 +1003,7 @@ on a new line! ""Wow!"", the masses cried";
// String interpolation by prefixing the string with $
// and wrapping the expression you want to interpolate with { braces }
+ // You can also combine both interpolated and verbatim strings with $@
public class Rectangle
{
public int Length { get; set; }
@@ -961,6 +1016,9 @@ on a new line! ""Wow!"", the masses cried";
{
Rectangle rect = new Rectangle { Length = 5, Width = 3 };
Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");
+
+ string username = "User";
+ Console.WriteLine($@"C:\Users\{username}\Desktop");
}
}
@@ -1096,25 +1154,144 @@ namespace Learning.More.CSharp
}
}
+//New C# 7 Feature
+//Install Microsoft.Net.Compilers Latest from Nuget
+//Install System.ValueTuple Latest from Nuget
using System;
namespace Csharp7
{
- //New C# 7 Feature
- //Install Microsoft.Net.Compilers Latest from Nuget
- //Install System.ValueTuple Latest from Nuget
- class Program
- {
- static void Main(string[] args)
- {
- //Type 1 Declaration
- (string FirstName, string LastName) names1 = ("Peter", "Parker");
- Console.WriteLine(names1.FirstName);
-
- //Type 2 Declaration
- var names2 = (First:"Peter", Last:"Parker");
- Console.WriteLine(names2.Last);
- }
- }
+ // TUPLES, DECONSTRUCTION AND DISCARDS
+ class TuplesTest
+ {
+ public (string, string) GetName()
+ {
+ // Fields in tuples are by default named Item1, Item2...
+ var names1 = ("Peter", "Parker");
+ Console.WriteLine(names1.Item2); // => Parker
+
+ // Fields can instead be explicitly named
+ // Type 1 Declaration
+ (string FirstName, string LastName) names2 = ("Peter", "Parker");
+
+ // Type 2 Declaration
+ var names3 = (First:"Peter", Last:"Parker");
+
+ Console.WriteLine(names2.FirstName); // => Peter
+ Console.WriteLine(names3.Last); // => Parker
+
+ return names3;
+ }
+
+ public string GetLastName() {
+ var fullName = GetName();
+
+ // Tuples can be deconstructed
+ (string firstName, string lastName) = fullName;
+
+ // Fields in a deconstructed tuple can be discarded by using _
+ var (_, last) = fullName;
+ return last;
+ }
+
+ // Any type can be deconstructed in the same way by
+ // specifying a Deconstruct method
+ public int randomNumber = 4;
+ public int anotherRandomNumber = 10;
+
+ public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
+ {
+ randomNumber = this.randomNumber;
+ anotherRandomNumber = this.anotherRandomNumber;
+ }
+
+ static void Main(string[] args)
+ {
+ var tt = new TuplesTest();
+ (int num1, int num2) = tt;
+ Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10
+
+ Console.WriteLine(tt.GetLastName());
+ }
+ }
+
+ // PATTERN MATCHING
+ class PatternMatchingTest
+ {
+ public static (string, int)? CreateLogMessage(object data)
+ {
+ switch(data)
+ {
+ // Additional filtering using when
+ case System.Net.Http.HttpRequestException h when h.Message.Contains("404"):
+ return (h.Message, 404);
+ case System.Net.Http.HttpRequestException h when h.Message.Contains("400"):
+ return (h.Message, 400);
+ case Exception e:
+ return (e.Message, 500);
+ case string s:
+ return (s, s.Contains("Error") ? 500 : 200);
+ case null:
+ return null;
+ default:
+ return (data.ToString(), 500);
+ }
+ }
+ }
+
+ // REFERENCE LOCALS
+ // Allow you to return a reference to an object instead of just its value
+ class RefLocalsTest
+ {
+ // note ref in return
+ public static ref string FindItem(string[] arr, string el)
+ {
+ for(int i=0; i<arr.Length; i++)
+ {
+ if(arr[i] == el) {
+ // return the reference
+ return ref arr[i];
+ }
+ }
+ throw new Exception("Item not found");
+ }
+
+ public static void SomeMethod()
+ {
+ string[] arr = {"this", "is", "an", "array"};
+
+ // note refs everywhere
+ ref string item = ref FindItem(arr, "array");
+ item = "apple";
+ Console.WriteLine(arr[3]); // => apple
+ }
+ }
+
+ // LOCAL FUNCTIONS
+ class LocalFunctionTest
+ {
+ private static int _id = 0;
+ public int id;
+ public LocalFunctionTest()
+ {
+ id = generateId();
+
+ // This local function can only be accessed in this scope
+ int generateId()
+ {
+ return _id++;
+ }
+ }
+
+ public static void AnotherMethod()
+ {
+ var lf1 = new LocalFunctionTest();
+ var lf2 = new LocalFunctionTest();
+ Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1
+
+ int id = generateId();
+ // error CS0103: The name 'generateId' does not exist in the current context
+ }
+ }
}
```
diff --git a/de-de/LOLCODE-de.html.markdown b/de-de/LOLCODE-de.html.markdown
new file mode 100644
index 00000000..155c5657
--- /dev/null
+++ b/de-de/LOLCODE-de.html.markdown
@@ -0,0 +1,188 @@
+---
+language: LOLCODE
+filename: learnLOLCODE.lol
+contributors:
+ - ["abactel", "https://github.com/abactel"]
+translators:
+ - ["Henrik Jürges", "http://github.com/santifa"]
+lang: de-de
+---
+
+LOLCODE ist eine esoterische Programmiersprache die die Sprache der [lolcats](https://upload.wikimedia.org/wikipedia/commons/a/ab/Lolcat_in_folder.jpg?1493656347257) nachahmt.
+
+```
+BTW Das ist ein Kommentar
+BTW Das Programm muss mit `HAI <language version>` beginnen und mit `KTHXBYE` enden.
+
+HAI 1.3
+CAN HAS STDIO? BTW Standard Header importieren
+
+OBTW
+ ==========================================================================
+ ============================== Grundlegendes =============================
+ ==========================================================================
+TLDR
+
+BTW Texte anzeigen:
+VISIBLE "HELLO WORLD"
+
+BTW Variablen deklarieren:
+I HAS A MESSAGE ITZ "CATZ ARE GOOD"
+VISIBLE MESSAGE
+
+OBTW
+ Variablen sind dynamisch typisiert und der Typ muss nicht explizit
+ angegeben werden. Die möglichen Typen sind:
+TLDR
+
+I HAS A STRING ITZ "DOGZ ARE GOOOD" BTW Typ ist YARN
+I HAS A INTEGER ITZ 42 BTW Typ ist NUMBR
+I HAS A FLOAT ITZ 3.1415 BTW Typ ist NUMBAR
+I HAS A BOOLEAN ITZ WIN BTW Typ ist TROOF
+I HAS A UNTYPED BTW Typ ist NOOB
+
+BTW Eingaben von Nutzern:
+I HAS A AGE
+GIMMEH AGE
+BTW Die Variable wird als YARN gespeichert und kann in eine
+BTW NUMBR konvertiert werden:
+AGE IS NOW A NUMBR
+
+OBTW
+ ==========================================================================
+ ================================== MATHE =================================
+ ==========================================================================
+TLDR
+
+BTW LOLCODE benutzt polnische Notation für Mathe.
+
+BTW grundlegende mathematische Notationen:
+
+SUM OF 21 AN 33 BTW 21 + 33
+DIFF OF 90 AN 10 BTW 90 - 10
+PRODUKT OF 12 AN 13 BTW 12 * 13
+QUOSHUNT OF 32 AN 43 BTW 32 / 43
+MOD OF 43 AN 64 BTW 43 modulo 64
+BIGGR OF 23 AN 53 BTW max(23, 53)
+SMALLR OF 53 AN 45 BTW min(53, 45)
+
+BTW binäre Notation:
+
+BOTH OF WIN AN WIN BTW und: WIN if x=WIN, y=WIN
+EITHER OF FAIL AN WIN BTW oder: FAIL if x=FAIL, y=FAIL
+WON OF WIN AN FAIL BTW exklusives oder: FAIL if x=y
+NOT FAIL BTW unäre Negation: WIN if x=FAIL
+ALL OF WIN AN WIN MKAY BTW beliebige Stelligkeit bei AND
+ANY OF WIN AN FAIL MKAY BTW beliebige Stelligkeit bei OR
+
+BTW Vergleiche:
+
+BOTH SAEM "CAT" AN "DOG" BTW WIN wenn x == y
+DIFFRINT 732 AN 184 BTW WIN wenn x != y
+BOTH SAEM 12 AN BIGGR OF 12 AN 4 BTW x >= y
+BOTH SAEM 43 AN SMALLR OF 43 AN 56 BTW x <= y
+DIFFRINT 64 AN SMALLR OF 64 AN 2 BTW x > y
+DIFFRINT 75 AN BIGGR OF 75 AN 643 BTW x < y
+
+OBTW
+ ==========================================================================
+ ============================= Flusskontrolle =============================
+ ==========================================================================
+TLDR
+
+BTW If/then Statement:
+I HAS A ANIMAL
+GIMMEH ANIMAL
+BOTH SAEM ANIMAL AN "CAT", O RLY?
+ YA RLY
+ VISIBLE "YOU HAV A CAT"
+ MEBBE BOTH SAEM ANIMAL AN "MAUS"
+ VISIBLE "NOM NOM NOM. I EATED IT."
+ NO WAI
+ VISIBLE "AHHH IS A WOOF WOOF"
+OIC
+
+BTW Case Statement:
+I HAS A COLOR
+GIMMEH COLOR
+COLOR, WTF?
+ OMG "R"
+ VISIBLE "RED FISH"
+ GTFO
+ OMG "Y"
+ VISIBLE "YELLOW FISH"
+ BTW Weil hier kein `GTFO` ist wird auch das nächste Statement überprüft
+ OMG "G"
+ OMG "B"
+ VISIBLE "FISH HAS A FLAVOR"
+ GTFO
+ OMGWTF
+ VISIBLE "FISH IS TRANSPARENT OHNO WAT"
+OIC
+
+BTW For Schleife:
+I HAS A TEMPERATURE
+GIMMEH TEMPERATURE
+TEMPERATURE IS NOW A NUMBR
+IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN TEMPERATURE
+ VISIBLE ITERATOR
+IM OUTTA YR LOOP
+
+BTW While Schleife:
+IM IN YR LOOP NERFIN YR ITERATOR WILE DIFFRINT ITERATOR AN -10
+ VISIBLE ITERATOR
+IM OUTTA YR LOOP
+
+OBTW
+ =========================================================================
+ ================================ Strings ================================
+ =========================================================================
+TLDR
+
+BTW Zeilenumbrüche:
+VISIBLE "FIRST LINE :) SECOND LINE"
+
+BTW Tabulatoren:
+VISIBLE ":>SPACES ARE SUPERIOR"
+
+BTW Bell (macht beep):
+VISIBLE "NXT CUSTOMER PLS :o"
+
+BTW Anführungszeichen in Strings:
+VISIBLE "HE SAID :"I LIKE CAKE:""
+
+BTW Doppelpunkte in Strings :
+VISIBLE "WHERE I LIVE:: CYBERSPACE"
+
+OBTW
+ =========================================================================
+ =============================== Funktionen ==============================
+ =========================================================================
+TLDR
+
+BTW Definieren einer neuen Funktion:
+HOW IZ I SELECTMOVE YR MOVE BTW `MOVE` ist ein Argument
+ BOTH SAEM MOVE AN "ROCK", O RLY?
+ YA RLY
+ VISIBLE "YOU HAV A ROCK"
+ NO WAI
+ VISIBLE "OH NO IS A SNIP-SNIP"
+ OIC
+ GTFO BTW Gibt NOOB zurück
+IF U SAY SO
+
+BTW Eine Funktion deklarieren und einen Wert zurückgeben:
+HOW IZ I IZYELLOW
+ FOUND YR "YELLOW"
+IF U SAY SO
+
+BTW Eine Funktion aufrufen:
+I IZ IZYELLOW MKAY
+
+KTHXBYE
+```
+
+## Weiterführende Informationen:
+
+- [LCI compiler](https://github.com/justinmeza/lci)
+- [Official spec](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md)
diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown
new file mode 100644
index 00000000..801d2514
--- /dev/null
+++ b/de-de/dynamic-programming-de.html.markdown
@@ -0,0 +1,77 @@
+---
+category: Algorithms & Data Structures
+name: Dynamic Programming
+contributors:
+ - ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
+translators:
+ - ["Henrik Jürges", "http://github.com/santifa"]
+lang: de-de
+---
+
+# Dynamische Programmierung
+
+## Einführung
+Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung
+einer bestimmten Klasse von Problemen verwendet wird.
+Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe
+gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu
+vermeiden, das gleiche Problem noch einmal zu lösen.
+
+Denken Sie immer daran!
+"Diejenigen, die sich nicht an die Vergangenheit erinnern können,
+sind dazu verdammt, sie zu wiederholen."
+
+## Wege zur Lösung solcher Probleme
+
+1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen.
+Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die
+gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und
+speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr
+intuitiv. Er wird als Memoization bezeichnet.
+
+2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher
+Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der
+Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird
+sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden.
+Dies wird als Dynamische Programmierung bezeichnet.
+
+## Ein Beispiel für Dynamische Programmierung
+
+Das Problem mit der längsten ansteigenden Subsequenz besteht darin,
+die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden.
+Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`,
+müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j<i`
+in der Teilmenge `aj<ai` gilt.
+Zuerst müssen wir bei jedem Index i den Wert der längsten Subsequenzen (LSi)
+finden, wobei das letzte Element der Sequenz ai ist. Dann wäre die größte LSi
+die längste Subsequenz in der gegebenen Sequenz. Am Anfang wird der LSi mit
+eins belegt, da ai ein Element der Sequenz (Letztes Element) ist.
+Dann ist für alle `j` mit `j<i` und `aj<ai`, so dass wir den größten LSj finden
+und zum LSi hinzufügen. Der Algorithmus hat eine Laufzeit von *O(n2)*.
+
+Pseudocode zur Bestimmung der Länge der am längsten ansteigenden Subsequenz:
+Die Komplexität des Algorithmus könnte durch eine bessere Datenstruktur anstelle
+von Arrays reduziert werden. Das Speichern von Vorgänger-Array's und Variablen
+wie `largest_sequences_so_far` und dessen Index würde eine Menge Zeit sparen.
+
+Ein ähnliches Konzept könnte auch bei der Suche nach dem längsten Weg
+in gerichteten azyklischen Graphen angewandt werden.
+```python
+for i=0 to n-1
+ LS[i]=1
+ for j=0 to i-1
+ if (a[i] > a[j] and LS[i]<LS[j])
+ LS[i] = LS[j]+1
+for i=0 to n-1
+ if (largest < LS[i])
+```
+
+### Einige bekannte DP Probleme
+
+- Floyd Warshall Algorithm - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code)
+- Integer Knapsack Problem - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem)
+- Longest Common Subsequence - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence)
+
+## Online Ressourcen
+
+* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)
diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown
new file mode 100644
index 00000000..2434d1bd
--- /dev/null
+++ b/de-de/edn-de.html.markdown
@@ -0,0 +1,112 @@
+---
+language: edn
+filename: learnedn-de.edn
+contributors:
+ - ["Jason Yeo", "https://github.com/jsyeo"]
+ - ["Jonathan D Johnston", "https://github.com/jdjohnston"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Extensible Data Notation (EDN) ist ein Format für serialisierte Daten.
+
+EDN ist ein Subset der von Clojure verwendeten Syntax. Das Lesen von Daten, die durch EDN definiert werden, ist
+sicherer als das, was durch die vollständige Clojure-Syntax definiert wird, insbesondere von nicht
+vertrauenswürdigen Quellen. EDN ist beschränkt auf Daten, kein Code. Es ist ähnlich in seinen Zielen zu JSON.
+Obwohl es mehr in Clojure verwendet wird, gibt es verschiedene Implementationen von EDN in vielen
+verschiedenen anderen Sprachen.
+
+Der Hauptvorteil von EDN im Gegensatz zu JSON und YAML ist, dass es erweiterbar ist.
+Wir werden später sehen wie es erweitert werden kann.
+
+```clojure
+; Kommentare starten mit einem Semikolon.
+; Alles nach dem Semikolon wird ignoriert.
+
+;;;;;;;;;;;;;;;;;;;
+;;; Basistypen ;;;
+;;;;;;;;;;;;;;;;;;;
+
+nil ; auch bekannt in anderen Sprachen als null
+
+; Booleans
+true
+false
+
+; Strings werden in Gänsefüßchen eingeschlossen.
+"hungarian breakfast"
+"farmer's cheesy omelette"
+
+; Charaktere werden einem Backslash vorangestellt
+\g \r \a \c \e
+
+; Schlüsselwörter beginnen mit einem Doppelpunkt. Sie verhalten sich wie Enums.
+; Ähnlich, wie Symbole in Ruby.
+:eggs
+:cheese
+:olives
+
+; Symbole werden verwendet um Identifier zu repräsentieren. Sie beginnen mit einem #.
+; Du kannst einen Namespace für Symbole nutzen, wenn du / verwendest. Egal was / vorangestellt wird
+; ist der Namespace dieses Namens.
+#spoon
+#kitchen/spoon ; nicht das selbe, wie #spoon
+#kitchen/fork
+#github/fork ; damit kannst du nicht essen
+
+; Integers und Floats
+42
+3.14159
+
+; Listen sind Sequenzen von Werten
+(:bun :beef-patty 9 "yum!")
+
+; Vektoren erlauben zufälligen Zugriff
+[:gelato 1 2 -2]
+
+; Maps sind assoziative Datenstrukturen, die einen Schlüssel mit einem Wert verbinden.
+{:eggs 2
+ :lemon-juice 3.5
+ :butter 1}
+
+; Du bist nicht beschränkt ausschließlich Schlüsselwörter als Schlüssel zu verwenden.
+{[1 2 3 4] "tell the people what she wore",
+ [5 6 7 8] "the more you see the more you hate"}
+
+; Du kannst Kommas für eine bessere Lesbarkeit verwenden. Sie werden wie Leerraum behandelt.
+; Sets sind Sammlungen, die eindeutige Elemente enthalten.
+#{:a :b 88 "huat"}
+
+;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; markierte Elemente ;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;
+
+; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden.
+
+#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
+
+; Lass mich das mit einem Clojure Beispiel erklären.
+; Angenommen ich möchte dieses Stück EDM in einen MenuItem record umwandeln.
+(defrecord MenuItem [name rating])
+
+; Um EDN in clojure Werte umzuwandeln, muss ich den eingebauten EDN Leser
+; edn/read-string verwenden
+
+(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
+; -> {:eggs 2 :butter 1 :flour 5}
+
+; Definiere die Leserfunktion, um markierte Elemente zu transformieren
+; und übergebe eine Map, die Tags den Lesefunktionen als edn / read-string zuweisen
+
+(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
+ "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
+; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
+
+```
+
+# Referenzen
+
+- [EDN spec](https://github.com/edn-format/edn)
+- [Implementationen](https://github.com/edn-format/edn/wiki/Implementations)
+- [makierte Elemente](http://www.compoundtheory.com/clojure-edn-walkthrough/)
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 61f7bb67..a0ed120f 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -205,6 +205,12 @@ Speichert die aktuellen Inhalte des Index in einen neuen *Commit*. Dieser Commit
```bash
# Commit mit Beschreibung erstellen.
$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+
+# Alle veränderten oder gelöschten Dateien außer neue Dateien werden gestaged und dann wird ein Commit erstellt.
+$ git commit -a -m "Modified foo.php and removed bar.php"
+
+# Ändert den letzten Commit (der letzte Commit wird mit einem neuen Commit ersetzt)
+$ git commit --amend -m "Correct message"
```
### diff
diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown
index 2ee18129..0bf58f9c 100644
--- a/de-de/html-de.html.markdown
+++ b/de-de/html-de.html.markdown
@@ -9,7 +9,7 @@ lang: de-de
---
HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache).
-Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben..
+Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben.
Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien.
Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags.
Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt.
@@ -111,7 +111,7 @@ Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben
## Verwendung
-HTML Dateien enden mit `.html`.
+HTML Dateien enden mit `.html` oder mit `.htm`. Der Mime Typ ist meist `text/html`.
## Um mehr zu lernen
diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown
new file mode 100644
index 00000000..79b60d20
--- /dev/null
+++ b/de-de/nix-de.html.markdown
@@ -0,0 +1,358 @@
+---
+language: nix
+filename: learnnix-de.nix
+contributors:
+ - ["Chris Martin", "http://chris-martin.org/"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Nix ist eine simple funktionale Programmiersprache, die für den
+[Nix package manager](https://nixos.org/nix/) und
+[NixOS](https://nixos.org/) entwickelt wurde.
+
+Du kannst Nix Ausdrücke evaluieren mithilfe von
+[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate)
+oder [`nix-repl`](https://github.com/edolstra/nix-repl).
+
+```
+with builtins; [
+
+ # Kommentare
+ #=========================================
+
+ # Inline Kommentare sehen so aus.
+
+ /* Multizeilen Kommentare
+ sehen so aus. */
+
+
+ # Booleans
+ #=========================================
+
+ (true && false) # Und
+ #=> false
+
+ (true || false) # Oder
+ #=> true
+
+ (if 3 < 4 then "a" else "b") # Bedingungen
+ #=> "a"
+
+
+ # Integers
+ #=========================================
+
+ # Integers sind die einzigen numerischen Typen.
+
+ 1 0 42 (-3) # Einige integers
+
+ (4 + 6 + 12 - 2) # Addition
+ #=> 20
+
+ (7 / 2) # Division
+ #=> 3
+
+
+ # Strings
+ #=========================================
+
+ "String Literale sind in Anführungszeichen."
+
+ "
+ String Literale können mehrere
+ Zeilen umspannen.
+ "
+
+ ''
+ Dies wird als Literal mit eingerückten String bezeichnet.
+ Es entfernt intelligent führende Leerzeichen.
+ ''
+
+ ''
+ a
+ b
+ ''
+ #=> "a\n b"
+
+ ("ab" + "cd") # String Konkatenation
+ #=> "abcd"
+
+ # Mit Antiquotation kannst du Werte in Strings einbetten.
+ ("Dein Homeverzeichnis ist ${getEnv "HOME"}")
+ #=> "Dein Homeverzeichnis ist /home/alice"
+
+
+ # Paths
+ #=========================================
+
+ # Nix besitzt einen primitiven Datentyp für Pfade
+ /tmp/tutorials/learn.nix
+
+ # Ein relativer Pfad wird beim Parsing zu einem absoluten Pfad aufgelöst,
+ # relativ zu der Datei in der es auftritt.
+ tutorials/learn.nix
+ #=> /the-base-path/tutorials/learn.nix
+
+ # Ein Pfad muss mindestens einen Schrägstrich enthalten. Ein Pfad für eine
+ # Datei im selben Verzeichnis benötigt ein ./ Präfix.
+ ./learn.nix
+ #=> /the-base-path/learn.nix
+
+ # Der / Operator muss von Leerraum umgeben sein wenn du dividieren möchtest.
+ 7/2 # Das ist ein Pfadliteral
+ (7 / 2) # Das ist ein Integerliteral
+
+
+ # Importe
+ #=========================================
+
+ # Eine nix Datei besitzt einen einzelnen top-level Ausdruck mit keinen freien Variablen.
+ # Ein Import-Ausdruck wird zum Wert der Datei, die importiert wird, ausgewertet.
+ (import /tmp/foo.nix)
+
+ # Importe können ebenso mit Strings spezifiziert werden.
+ (import "/tmp/foo.nix")
+
+ # Import Pfade müssen absolut sein. Pfadliterale
+ # sind automatisch aufgelöst, das ist ein Ordnung.
+ (import ./foo.nix)
+
+ # Jedoch passiert dies nicht mit Strings.
+ (import "./foo.nix")
+ #=> error: string ‘foo.nix’ doesn't represent an absolute path
+
+
+ # Let
+ #=========================================
+
+ # `let` Blöcke erlauben es uns Werte zu Variablen zu binden.
+ (let x = "a"; in
+ x + x + x)
+ #=> "aaa"
+
+ # Bindungen können auf sich gegenseitig verweisen. Die Reihenfolge spielt
+ # keine Rolle.
+ (let y = x + "b";
+ x = "a"; in
+ y + "c")
+ #=> "abc"
+
+ # Innere Bindungen überschatten Äußere.
+ (let a = 1; in
+ let a = 2; in
+ a)
+ #=> 2
+
+
+ # Funktionen
+ #=========================================
+
+ (n: n + 1) # Funktion, die 1 addiert
+
+ ((n: n + 1) 5) # Dieselbe Funktion angewendet auf 5.
+ #=> 6
+
+ # Es gibt keine spezielle Syntax für benannte Funktionen, aber sie
+ # können mit `let` Blöcken, wie jeder andere Wert auch, gebunden werden.
+ (let succ = (n: n + 1); in succ 5)
+ #=> 6
+
+ # Eine Funktion hat genau ein Argument.
+ # Mehrere Argumente können erreicht werden mithilfe von Currying.
+ ((x: y: x + "-" + y) "a" "b")
+ #=> "a-b"
+
+ # Benannte Funktionsargumente gibt es auch. Diese werden wir einführen, nachdem wir uns Sets
+ # angeschaut haben.
+
+ # Listen
+ #=========================================
+
+ # Listen werden durch eckige Klammern gekennzeichnet.
+
+ (length [1 2 3 "x"])
+ #=> 4
+
+ ([1 2 3] ++ [4 5])
+ #=> [1 2 3 4 5]
+
+ (concatLists [[1 2] [3 4] [5]])
+ #=> [1 2 3 4 5]
+
+ (head [1 2 3])
+ #=> 1
+ (tail [1 2 3])
+ #=> [2 3]
+
+ (elemAt ["a" "b" "c" "d"] 2)
+ #=> "c"
+
+ (elem 2 [1 2 3])
+ #=> true
+ (elem 5 [1 2 3])
+ #=> false
+
+ (filter (n: n < 3) [1 2 3 4])
+ #=> [ 1 2 ]
+
+
+ # Sets
+ #=========================================
+
+ # Ein "Set" ist eine ungeordnete Zuordnung mit Stringschlüsseln.
+ { foo = [1 2]; bar = "x"; }
+
+ # Der . Operator nimmt einen Wert aus dem Set.
+ { a = 1; b = 2; }.a
+ #=> 1
+
+ # Der ? Operator testet, ob der Schlüssel in dem Set vorhanden ist.
+ ({ a = 1; b = 2; } ? a)
+ #=> true
+ ({ a = 1; b = 2; } ? c)
+ #=> false
+
+ # Der // Operator mergt zwei Sets.
+ ({ a = 1; } // { b = 2; })
+ #=> { a = 1; b = 2; }
+
+ # Werte auf der rechten Seite überschreiben die Werte auf der linken Seite.
+ ({ a = 1; b = 2; } // { a = 3; c = 4; })
+ #=> { a = 3; b = 2; c = 4; }
+
+ # Das Schlüsselwort rec bezeichenet ein "rekursives Set", in dem sich Attribute
+ # aufeinander beziehen können.
+ (let a = 1; in { a = 2; b = a; }.b)
+ #=> 1
+ (let a = 1; in rec { a = 2; b = a; }.b)
+ #=> 2
+
+ # Verschachtelte Sets können stückweise definiert werden.
+ {
+ a.b = 1;
+ a.c.d = 2;
+ a.c.e = 3;
+ }.a.c
+ #=> { d = 2; e = 3; }
+
+ # Die Nachkommen eines Attributs können in diesem Feld nicht zugeordnet werden, wenn
+ # das Attribut selbst nicht zugewiesen wurde.
+ {
+ a = { b = 1; };
+ a.c = 2;
+ }
+ #=> error: attribute ‘a’ already defined
+
+
+ # With
+ #=========================================
+
+ # Der Körper eines Sets Blocks wird mit der Zuordnung eines Satzes an die Variablen gebunden.
+ (with { a = 1; b = 2; };
+ a + b)
+ # => 3
+
+ # Innere Bindungen überschatten äußere Bindungen.
+ (with { a = 1; b = 2; };
+ (with { a = 5; };
+ a + b))
+ #=> 7
+
+ # Die erste Linie diese Tutorials startet mit "with builtins;",
+ # weil builtins ein Set mit allen eingebauten
+ # Funktionen (length, head, tail, filter, etc.) umfasst.
+ # Das erspart uns beispielsweise "builtins.length" zu schreiben,
+ # anstatt nur "length".
+
+
+ # Set patterns
+ #=========================================
+
+ # Sets sind nützlich, wenn du mehrere Werte einer Funktion
+ # übergeben musst.
+ (args: args.x + "-" + args.y) { x = "a"; y = "b"; }
+ #=> "a-b"
+
+ # Dies kann mit Hilfe von Set patterns deutlicher geschrieben werden.
+ ({x, y}: x + "-" + y) { x = "a"; y = "b"; }
+ #=> "a-b"
+
+ # Standardmäßig schlägt das Muster bei Sets mit zusätzlichen Schlüsseln fehl.
+ ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; }
+ #=> error: anonymous function called with unexpected argument ‘z’
+
+ # Durch Hinzufügen von ", ..." können zusätzliche Schlüssel ignoriert werden.
+ ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; }
+ #=> "a-b"
+
+
+ # Errors
+ #=========================================
+
+ # `throw` bewirkt, dass die Auswertung mit einer Fehlermeldung abgebrochen wird.
+ (2 + (throw "foo"))
+ #=> error: foo
+
+ # `tryEval` fängt geworfene Fehler.
+ (tryEval 42)
+ #=> { success = true; value = 42; }
+ (tryEval (2 + (throw "foo")))
+ #=> { success = false; value = false; }
+
+ # `abort` ist ähnlich wie throw, aber es ist fatal. Es kann nicht gefangen werden.
+ (tryEval (abort "foo"))
+ #=> error: evaluation aborted with the following error message: ‘foo’
+
+ # `assert` evaluiert zu dem gegebenen Wert, wenn die Bedingung wahr ist, sonst
+ # löst es eine abfangbare Exception aus.
+ (assert 1 < 2; 42)
+ #=> 42
+ (assert 1 > 2; 42)
+ #=> error: assertion failed at (string):1:1
+ (tryEval (assert 1 > 2; 42))
+ #=> { success = false; value = false; }
+
+
+ # Impurity
+ #=========================================
+
+ # Da die Wiederholbarkeit von Builds für den Nix Packetmanager entscheidend ist,
+ # werden in der Nix Sprache reine funktionale Elemente betont. Es gibt aber ein paar
+ # unreine Elemente.
+ # Du kannst auf Umgebungsvariablen verweisen.
+ (getEnv "HOME")
+ #=> "/home/alice"
+
+ # Die trace Funktion wird zum Debugging verwendet. Sie gibt das erste Argument zu stderr aus
+ # und evaluiert das zweite Argument.
+ (trace 1 2)
+ #=> trace: 1
+ #=> 2
+
+ # Du kannst Dateien in den Nix Store schreiben. Obwohl unrein, kannst du dir relativ sicher sein,
+ # dass es sicher ist, da der Dateiname aus dem Hash des Inhalts abgeleitet wird.
+ # Du kannst Dateien von überall lesen. In diesem Beispiel schreiben wir Dateien in den Store
+ # und lesen wieder davon.
+ (let filename = toFile "foo.txt" "hello!"; in
+ [filename (builtins.readFile filename)])
+ #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ]
+
+ # Außerdem können wir Dateien in den Nix Store herunterladen.
+ (fetchurl "https://example.com/package-1.2.3.tgz")
+ #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz"
+
+]
+```
+
+### Weitere Ressourcen
+
+* [Nix Manual - Nix expression language]
+ (https://nixos.org/nix/manual/#ch-expression-language)
+
+* [James Fisher - Nix by example - Part 1: The Nix expression language]
+ (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
+
+* [Susan Potter - Nix Cookbook - Nix By Example]
+ (http://funops.co/nix-cookbook/nix-by-example/)
diff --git a/de-de/pyqt-de.html.markdown b/de-de/pyqt-de.html.markdown
new file mode 100644
index 00000000..93ee20d4
--- /dev/null
+++ b/de-de/pyqt-de.html.markdown
@@ -0,0 +1,89 @@
+---
+category: tool
+tool: PyQT
+filename: learnpyqt-de.py
+contributors:
+ - ["Nathan Hughes", "https://github.com/sirsharpest"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+**Qt** ist eine weit bekanntes Framework mit den man plattformunabhängige Programme schreiben kann,
+die auf verschiedenen Sotfware und Hardware Plattformen laufen mit kleinen oder keinen Änderungen im Code.
+Dabei besitzen sie trozdem die Power und Geschwindigkeit von nativen Anwendungen.
+**Qt** wurde ursprünglich in *C++** geschrieben.
+
+Das ist eine Adaption von dem C++ Intro für QT von [Aleksey Kholovchuk](https://github.com/vortexxx192),
+manche der Codebeispiele sollte in der selben Funktionalität resultieren.
+Diese Version wurde in pyqt erstellt.
+
+```python
+import sys
+from PyQt4 import QtGui
+
+def window():
+ # Erschafft ein Anwendungsobjekt.
+ app = QtGui.QApplication(sys.argv)
+ # Erschafft ein Widget, auf dem unser Label platziert wird.
+ w = QtGui.QWidget()
+ # Fügt ein Label zu dem Widget hinzu.
+ b = QtGui.QLabel(w)
+ # Setzt einen Text für das Label.
+ b.setText("Hello World!")
+ # Setzt die Größe und die Platzierungsinfomationen.
+ w.setGeometry(100, 100, 200, 50)
+ b.move(50, 20)
+ # Setzt unserem Fenster einen schönen Titel.
+ w.setWindowTitle("PyQt")
+ # Lässt alles anzeigen.
+ w.show()
+ # Führe alles aus, nachdem wir alles aufgebaut haben.
+ sys.exit(app.exec_())
+
+if __name__ == '__main__':
+ window()
+
+```
+
+Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können,
+müssen wir anfangen zusätzliche Elemente zu bauen.
+Hier zeigen wir wie man eine Dialog Popup Box einführt.
+Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen.
+
+```Python
+import sys
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+
+
+def window():
+ app = QApplication(sys.argv)
+ w = QWidget()
+ # Erschafft einen Knopf und fügt das Widget w hinzu
+ b = QPushButton(w)
+ b.setText("drücke mich")
+ b.move(50, 50)
+ # Wenn b gedrückt wird, wird diese Funktion aufgerufen.
+ # Bemerke das Fehlen von () bei dem Funktionsaufruf.
+ b.clicked.connect(showdialog)
+ w.setWindowTitle("PyQt Dialog")
+ w.show()
+ sys.exit(app.exec_())
+
+# Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen.
+# Der Knopf wartet bis er geklickt wird und beendet das Programm
+def showdialog():
+ d = QDialog()
+ b1 = QPushButton("ok", d)
+ b1.move(50, 50)
+ d.setWindowTitle("Dialog")
+ # Diese Modalität sagt dem Popup, dass es den Parent blocken soll, solange es aktiv ist.
+ d.setWindowModality(Qt.ApplicationModal)
+ # Beim klicken möchte ich, dass der gesamte Prozess beendet wird.
+ b1.clicked.connect(sys.exit)
+ d.exec_()
+
+if __name__ == '__main__':
+ window()
+```
diff --git a/de-de/qt-de.html.markdown b/de-de/qt-de.html.markdown
new file mode 100644
index 00000000..480030fe
--- /dev/null
+++ b/de-de/qt-de.html.markdown
@@ -0,0 +1,175 @@
+---
+category: tool
+tool: Qt Framework
+language: c++
+filename: learnqt-de.cpp
+contributors:
+ - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+**Qt** ist ein weithin bekanntes Framework zum Entwickeln von cross-platform Software,
+die auf verschiedenen Hard- und Softwareplatformen mit wenig oder keinen Veränderungen im Code läuft.
+Dabei besitzt man die Power und Geschiwindigkeit von nativen Anwendungen.
+Obwohl **Qt** ursprünglich in *C++* geschrieben wurde,
+gibt es verschiedene Ports für andere Sprachen: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
+
+**Qt** eignet sich hervorragend zum Erstellen von Anwendungen mit grafischer Benutzeroberfläche (GUI).
+Dieses Tutorial zeigt, wie man das in *C++* macht.
+
+```c++
+/*
+ * Lass uns klassisch starten
+ */
+
+// Alle Header vom Qt Framework starten mit dem Großbuchstaben 'Q'.
+#include <QApplication>
+#include <QLineEdit>
+
+int main(int argc, char *argv[]) {
+ // Erstellt ein Objekt um applikationsweit die Resourcen zu managen.
+ QApplication app(argc, argv);
+
+ // Erstellt ein Line edit Widget und zeigt es auf dem Bildschirm
+ QLineEdit lineEdit("Hello world!");
+ lineEdit.show();
+
+ // Startet die Event Loop der Anwendung.
+ return app.exec();
+}
+```
+
+Die GUI bezogene Teile von **Qt** bestehen aus *Widgets* und den *Verbindungen*
+dazwischen.
+
+[Lies mehr über Widgets](http://doc.qt.io/qt-5/qtwidgets-index.html)
+
+```c++
+/*
+ * Lass uns Label und einen Button machen.
+ * Ein Label soll auftauchen, wenn der Button gedrückt wird.
+ *
+ * Der Qt Code spricht für sich selbst.
+ */
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QLabel>
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ // Füge ein vertikales Layout hinzu
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ QLabel textLabel("Danke für das Knopf drücken");
+ layout.addWidget(&textLabel);
+ textLabel.hide();
+
+ QPushButton button("Drück mich");
+ layout.addWidget(&button);
+
+ // Zeigt verstecktes Label, wenn der Button gedrückt wird.
+ QObject::connect(&button, &QPushButton::pressed,
+ &textLabel, &QLabel::show);
+
+ return app.exec();
+}
+```
+
+Beachte den *QObject::connect* Teil. Diese Methode wird verwendet,
+um *Signale* eines Objekts mit den *Slots* eines Objektes zu verbinden.
+
+**Signale** werden ausgegeben, wenn bestimmte Dinge mit Objekten passieren.
+Beispielsweise wird das *pressed* Signal ausgegeben,
+wenn der Benutzer auf das QPushButton Objekt drückt.
+
+**Slots** sind Aktionen, die als Reaktion auf empfangene Signale ausgeführt werden können.
+
+[Lies mehr über Slots und Signale](http://doc.qt.io/qt-5/signalsandslots.html)
+
+
+Als Nächstes lernen wir, dass wir nicht nur Standard Widgets verwenden können,
+sondern auch ihr Verhalten mithilfe von Vererbung verändern können.
+Lass uns einen Button erschaffen, der zählt, wie häufig er gedrückt wird.
+Dafür definieren wir unsere eigene Klasse *CounterLabel*.
+Diese muss wegen der speziellen Qt Architektur in einer seperaten Datei deklariert werden.
+
+```c++
+// counterlabel.hpp
+
+#ifndef COUNTERLABEL
+#define COUNTERLABEL
+
+#include <QLabel>
+
+class CounterLabel : public QLabel {
+ Q_OBJECT // Qt definiertes Makro, welches in jedem modifizierten Widget vorhanden sein muss.
+
+public:
+ CounterLabel() : counter(0) {
+ setText("Zähler wurde noch nicht erhöht."); // Methode von QLabel
+ }
+
+public slots:
+ // Aktion, die ausgeführt wird, wenn der Button gedrückt wird.
+ void increaseCounter() {
+ setText(QString("Zähler Wert: %1").arg(QString::number(++counter)));
+ }
+
+private:
+ int counter;
+};
+
+#endif // Zähllabel
+```
+
+```c++
+// main.cpp
+// Fast das Gleiche, wie das vorherige Beispiel
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QString>
+#include "counterlabel.hpp"
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ CounterLabel counterLabel;
+ layout.addWidget(&counterLabel);
+
+ QPushButton button("Drück mich nochmal.");
+ layout.addWidget(&button);
+ QObject::connect(&button, &QPushButton::pressed,
+ &counterLabel, &CounterLabel::increaseCounter);
+
+ return app.exec();
+}
+```
+
+Das wars! Natürlich ist das Qt Framework erheblich größer, als der der Teil der in diesem Tutorial behandelt wurde.
+Das heißt, es gibt viel zu lesen und zu üben.
+
+## Further reading
+
+- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
+- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
+
+Viel Erfolg und viel Spaß!
diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown
index b58a72d3..08f72a35 100644
--- a/de-de/swift-de.html.markdown
+++ b/de-de/swift-de.html.markdown
@@ -440,13 +440,13 @@ if let circle = myEmptyCircle {
// Wie Klassen auch können sie Methoden haben
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
@@ -455,35 +455,35 @@ enum Suit {
// Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ
// genannt werden, wenn die Variable explizit deklariert wurde
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte"
enum BookName: String {
- case John = "John"
- case Luke = "Luke"
+ case john = "John"
+ case luke = "Luke"
}
-print("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.john.rawValue)")
// Enum mit assoziierten Werten
enum Furniture {
// mit Int assoziiert
- case Desk(height: Int)
+ case desk(height: Int)
// mit String und Int assoziiert
- case Chair(String, Int)
-
+ case chair(String, Int)
+
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Desk with \(height) cm"
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
-var chair = Furniture.Chair("Foo", 40)
+var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown
index 7df367e7..4db8e92e 100644
--- a/dynamic-programming.html.markdown
+++ b/dynamic-programming.html.markdown
@@ -26,7 +26,7 @@ The Longest Increasing Subsequence problem is to find the longest increasing sub
First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all `j` such that `j<i` and `aj<ai`, we find Largest LSj and add it to LSi. Then algorithm take *O(n2)* time.
Pseudo-code for finding the length of the longest increasing subsequence:
-This algorithms complexity could be reduced by using better data structure rather than array. Storing predecessor array and variable like largest_sequences_so_far and its index would save a lot time.
+This algorithms complexity could be reduced by using better data structure rather than array. Storing predecessor array and variable like `largest_sequences_so_far` and its index would save a lot time.
Similar concept could be applied in finding longest path in Directed acyclic graph.
diff --git a/edn.html.markdown b/edn.html.markdown
index 04346eb8..f47853f0 100644
--- a/edn.html.markdown
+++ b/edn.html.markdown
@@ -44,13 +44,13 @@ false
:cheese
:olives
-; Symbols are used to represent identifiers. They start with #.
+; Symbols are used to represent identifiers.
; You can namespace symbols by using /. Whatever precedes / is
-; the namespace of the name.
-#spoon
-#kitchen/spoon ; not the same as #spoon
-#kitchen/fork
-#github/fork ; you can't eat with this
+; the namespace of the symbol.
+spoon
+kitchen/spoon ; not the same as spoon
+kitchen/fork
+github/fork ; you can't eat with this
; Integers and floats
42
@@ -84,22 +84,26 @@ false
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
-; Let me explain this with a clojure example. Suppose I want to transform that
+; Let me explain this with a Clojure example. Suppose I want to transform that
; piece of EDN into a MenuItem record.
(defrecord MenuItem [name rating])
-; To transform EDN to clojure values, I will need to use the built in EDN
-; reader, edn/read-string
+; defrecord defined, among other things, map->MenuItem which will take a map
+; of field names (as keywords) to values and generate a user.MenuItem record
-(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
+; To transform EDN to Clojure values, I will need to use the built-in EDN
+; reader, clojure.edn/read-string
+
+(clojure.edn/read-string "{:eggs 2 :butter 1 :flour 5}")
; -> {:eggs 2 :butter 1 :flour 5}
-; To transform tagged elements, define the reader function and pass a map
-; that maps tags to reader functions to edn/read-string like so
+; To transform tagged elements, pass to clojure.edn/read-string an option map
+; with a :readers map that maps tag symbols to data-reader functions, like so
-(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
- "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
+(clojure.edn/read-string
+ {:readers {'MyYelpClone/MenuItem map->MenuItem}}
+ "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
```
diff --git a/elm.html.markdown b/elm.html.markdown
index 23ae9eeb..ad80adc9 100644
--- a/elm.html.markdown
+++ b/elm.html.markdown
@@ -72,8 +72,8 @@ List.head [] -- Nothing
-- Access the elements of a pair with the first and second functions.
-- (This is a shortcut; we'll come to the "real way" in a bit.)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- The empty tuple, or "unit", is sometimes used as a placeholder.
-- It is the only value of its type, also called "Unit".
diff --git a/es-es/groovy-es.html.markdown b/es-es/groovy-es.html.markdown
index 799fc609..262d5e6a 100644
--- a/es-es/groovy-es.html.markdown
+++ b/es-es/groovy-es.html.markdown
@@ -232,10 +232,12 @@ for (i in array) {
// Iterando sobre un mapa
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
-x = 0
+x = ""
for ( e in map ) {
x += e.value
+ x += " "
}
+assert x.equals("Roberto Grails Groovy ")
/*
Operadores
diff --git a/es-es/learnsmallbasic-es.html.markdown b/es-es/learnsmallbasic-es.html.markdown
new file mode 100644
index 00000000..21208792
--- /dev/null
+++ b/es-es/learnsmallbasic-es.html.markdown
@@ -0,0 +1,132 @@
+---
+language: SmallBASIC
+filename: learnsmallbasic-es.bas
+contributors:
+ - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"]
+translators:
+ - ["José Juan Hernández García", "http://jjuanhdez.es"]
+lang: es-es
+---
+
+## Acerca de
+
+SmallBASIC es un intérprete del lenguaje BASIC rápido y fácil de aprender, ideal para cálculos cotidianos, scripts y prototipos. SmallBASIC incluye funciones trigonométricas, matrices y álgebra, un IDE integrado, una potente librería de cadenas de texto, comandos de sistema, sonido y gráficos, junto con una sintaxis de programación estructurada.
+
+## Desarrollo
+
+SmallBASIC fue desarrollado originalmente por Nicholas Christopoulos a finales de 1999 para el Palm Pilot. El desarrollo del proyecto ha sido continuado por Chris Warren-Smith desde el año 2005.
+Versiones de SmallBASIC se han hecho para una serie dispositivos de mano antiguos, incluyendo Franklin eBookman y el Nokia 770. También se han publicado varias versiones de escritorio basadas en una variedad de kits de herramientas GUI, algunas de las cuales han desaparecido. Las plataformas actualmente soportadas son Linux y Windows basadas en SDL2 y Android basadas en NDK. También está disponible una versión de línea de comandos de escritorio, aunque no suele publicarse en formato binario.
+Alrededor de 2008 una gran corporación lanzó un entorno de programación BASIC con un nombre de similar. SmallBASIC no está relacionado con este otro proyecto.
+
+```SmallBASIC
+REM Esto es un comentario
+' y esto tambien es un comentario
+
+REM Imprimir texto
+PRINT "hola"
+? "? es la abreviatura de PRINT"
+
+REM Estructuras de control
+FOR index = 0 TO 10 STEP 2
+ ? "Este es el numero de linea "; index
+NEXT
+J = 0
+REPEAT
+ J++
+UNTIL J = 10
+WHILE J > 0
+ J--
+WEND
+
+REM Estructura Select Case
+SELECT CASE "Cool"
+ CASE "null", 1, 2, 3, 4, 5, 6, 7, 8, "Cool", "blah"
+ CASE "No Cool"
+ PRINT "Fallo epico"
+ CASE ELSE
+ PRINT "Fallo"
+END SELECT
+
+REM Captura de errores con TRY/CATCH
+TRY
+ fn = Freefile
+ OPEN filename FOR INPUT As #fn
+CATCH err
+ PRINT "No se pudo abrir"
+END TRY
+
+REM Procedimientos y funciones definidas por el usuario
+FUNC add2(x, y)
+ ' variables pueden declararse como locales en el ambito de una SUB o FUNC
+ LOCAL k
+ k = "k dejara de existir cuando retorne FUNC"
+ add2 = x + y
+END
+PRINT add2(5, 5)
+
+SUB print_it(it)
+ PRINT it
+END
+print_it "IT...."
+
+REM Visualizacion de lineas y pixeles
+At 0, ymax / 2 + txth ("Q")
+COLOR 1: ? "sin(x)":
+COLOR 8: ? "cos(x)":
+COLOR 12: ? "tan(x)"
+LINE 0, ymax / 2, xmax, ymax / 2
+FOR i = 0 TO xmax
+ PSET i, ymax / 2 - SIN(i * 2 * pi / ymax) * ymax / 4 COLOR 1
+ PSET i, ymax / 2 - COS(i * 2 * pi / ymax) * ymax / 4 COLOR 8
+ PSET i, ymax / 2 - TAN(i * 2 * pi / ymax) * ymax / 4 COLOR 12
+NEXT
+SHOWPAGE
+
+REM SmallBASIC es ideal para experimentar con fractales y otros efectos interesantes
+DELAY 3000
+RANDOMIZE
+ff = 440.03
+FOR j = 0 TO 20
+ r = RND * 1000 % 255
+ b = RND * 1000 % 255
+ g = RND * 1000 % 255
+ c = RGB(r, b, g)
+ ff += 9.444
+ FOR i = 0 TO 25000
+ ff += ff
+ x = MIN(xmax, -x + COS(f * i))
+ y = MIN(ymax, -y + SIN(f * i))
+ PSET x, y COLOR c
+ IF (i % 1000 == 0) THEN
+ SHOWPAGE
+ fi
+ NEXT
+NEXT j
+
+REM Para historiadores de computadoras, SmallBASIC puede ejecutar programas
+REM encontrados en los primeros libros de computacion y revistas, por ejemplo:
+10 LET A = 9
+20 LET B = 7
+30 PRINT A * B
+40 PRINT A / B
+
+REM SmallBASIC también tiene soporte para algunos conceptos modernos como JSON
+aa = ARRAY("{\"cat\":{\"name\":\"harry\"},\"pet\":\"true\"}")
+IF (ismap(aa) == false) THEN
+ THROW "no es un mapa"
+END IF
+PRINT aa
+
+PAUSE
+
+```
+## Artículos
+
+* [Primeros pasos](http://smallbasic.sourceforge.net/?q=node/1573)
+* [Bienvenido a SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838)
+
+## GitHub
+
+* [Código fuente](https://github.com/smallbasic/SmallBASIC)
+* [Reference snapshot](http://smallbasic.github.io/)
+
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
index 8f63517a..22e3c532 100644
--- a/es-es/swift-es.html.markdown
+++ b/es-es/swift-es.html.markdown
@@ -446,48 +446,48 @@ if let circle = myEmptyCircle {
// Al igual que las clases, pueden contener métodos
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
// Los valores de enum permite la sintaxis corta, sin necesidad de poner
// el tipo del enum cuando la variable es declarada de manera explícita
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// Enums de tipo no-entero requiere asignaciones de valores crudas directas
enum BookName: String {
- case John = "John"
- case Luke = "Luke"
+ case john = "John"
+ case luke = "Luke"
}
-print("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.john.rawValue)")
// Enum con valores asociados
enum Furniture {
// Asociación con Int
- case Desk(height: Int)
+ case desk(height: Int)
// Asociación con String e Int
- case Chair(String, Int)
+ case chair(String, Int)
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Desk with \(height) cm"
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
-var chair = Furniture.Chair("Foo", 40)
+var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
diff --git a/forth.html.markdown b/forth.html.markdown
index 09f3beb0..ff094017 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -59,7 +59,7 @@ Forth, but most of what is written here should work elsewhere.
\ ---------------------- More Advanced Stack Manipulation ----------------------
-1 2 3 4 tuck \ duplicate the top item into the second slot: 1 2 4 3 4 ok
+1 2 3 4 tuck \ duplicate the top item below the second slot: 1 2 4 3 4 ok
1 2 3 4 over \ duplicate the second item to the top: 1 2 3 4 3 ok
1 2 3 4 2 roll \ *move* the item at that position to the top: 1 3 4 2 ok
1 2 3 4 2 pick \ *duplicate* the item at that position to the top: 1 2 3 4 2 ok
diff --git a/fr-fr/crystal-fr.html.markdown b/fr-fr/crystal-fr.html.markdown
index 2c4e3dad..2bb17fc5 100644
--- a/fr-fr/crystal-fr.html.markdown
+++ b/fr-fr/crystal-fr.html.markdown
@@ -305,7 +305,6 @@ end
(1..3).each do |index|
puts "Index: #{index}"
end
-# Index: 0
# Index: 1
# Index: 2
# Index: 3
diff --git a/fr-fr/d.html.markdown b/fr-fr/d-fr.html.markdown
index 8d98f9dc..8d98f9dc 100644
--- a/fr-fr/d.html.markdown
+++ b/fr-fr/d-fr.html.markdown
diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell-fr.html.markdown
index a34dc098..a34dc098 100644
--- a/fr-fr/haskell.html.markdown
+++ b/fr-fr/haskell-fr.html.markdown
diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown
new file mode 100644
index 00000000..d0f91611
--- /dev/null
+++ b/fr-fr/java-fr.html.markdown
@@ -0,0 +1,939 @@
+---
+language: java
+contributors:
+ - ["Jake Prather", "https://github.com/JakeHP"]
+ - ["Jakukyo Friel", "https://weakish.github.io"]
+ - ["Madison Dickson", "https://github.com/mix3d"]
+ - ["Simon Morgan", "https://sjm.io/"]
+ - ["Zachary Ferguson", "https://github.com/zfergus2"]
+ - ["Cameron Schermerhorn", "https://github.com/cschermerhorn"]
+ - ["Rachel Stiyer", "https://github.com/rstiyer"]
+ - ["Michael Dähnert", "https://github.com/JaXt0r"]
+ - ["Rob Rose", "https://github.com/RobRoseKnows"]
+ - ["Sean Nam", "https://github.com/seannam"]
+filename: JavaFr.java
+translators:
+ - ['Mathieu Gemard', 'https://github.com/mgemard']
+lang: fr-fr
+---
+Java est un langage orienté objet, concurrent et très facilement portable. Java
+est inspiré du C++ mais ne reprend pas tous les concepts comme par exemple les
+pointeurs et en ajoute de nouveaux comme les interfaces.
+[En savoir plus.](https://fr.wikipedia.org/wiki/Java_(langage))
+
+```java
+// Les commentaires sur une seule ligne commencent par //
+
+/*
+Les commentaires sur plusieurs lignes ressemblent à ceci.
+*/
+
+/**
+ * Les commentaires de la JavaDoc ressemblent à ceci. Ils sont utilisés pour
+ * décrire la classe et ses différents attributs.
+ * Attributs principaux:
+ *
+ * @author Nom (et information de contact comme l'email) de(s) auteur(s).
+ * @version Version actuelle du programme.
+ * @since Date à laquelle cette partie du programme a été ajouté.
+ * @param Décrit les différents paramètres pour d'une méthode.
+ * @return Décrit le retour de la méthode.
+ * @deprecated Indique si le code est déprécié ou ne doit plus être utilisé.
+ * @see Lien vers une autre partie de la documentation.
+*/
+
+// Importe la classe ArrayList qui se trouve dans le package java.util
+import java.util.ArrayList;
+// Importe toutes les classes qui se trouvent dans le package java.security
+import java.security.*;
+
+// Chaque fichier .java doit contenir une classe public portant le même nom que
+le fichier.
+public class JavaFr {
+
+ // Pour exécuter un programme Java, celui-ci doit posséder une méthode main
+ // qui fournir un point d'entrée.
+ public static void main(String[] args) {
+
+ ///////////////////////////////////////
+ // Entrée/Sortie
+ ///////////////////////////////////////
+
+ /*
+ * Sortie
+ */
+
+ // Utilisez System.out.println() pour afficher un texte dans la console.
+ System.out.println("Hello World!");
+ System.out.println(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Pour afficher sans retour à la ligne, on utilise System.out.print().
+ System.out.print("Hello ");
+ System.out.print("World");
+
+ // Utilisez System.out.printf() pour formatter les données à afficher.
+ System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
+
+ /*
+ * Entrée
+ */
+
+ // Utilisez Scanner pour lire l'entrée
+ // Nécessite: import java.util.Scanner;
+ Scanner scanner = new Scanner(System.in);
+
+ // Lire une chaîne de caractères
+ String name = scanner.next();
+
+ // Lire un byte
+ byte numByte = scanner.nextByte();
+
+ // Lire un entier
+ int numInt = scanner.nextInt();
+
+ // Lire une entrée de type long
+ float numFloat = scanner.nextFloat();
+
+ // Lire une entrée de type double
+ double numDouble = scanner.nextDouble();
+
+ // Lire une entrée de type boolean
+ boolean bool = scanner.nextBoolean();
+
+ ///////////////////////////////////////
+ // Variables
+ ///////////////////////////////////////
+
+ /*
+ * Déclaration de variable
+ */
+ // Déclarez une variable avec la forme <type> <name>
+ int fooInt;
+ // Declarez plusieurs variables du même type <type> <name1>, <name2>,
+ // <name3>
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Initialisation de variable
+ */
+
+ // Initialisez une variable sous la forme <type> <name> = <val>
+ int barInt = 1;
+ // Initialisez plusieurs variables du même type et avec la même valeur
+ // sous la forme
+ // <type> <name1>, <name2>, <name3>
+ // <name1> = <name2> = <name3> = <val>
+ int barInt1, barInt2, barInt3;
+ barInt1 = barInt2 = barInt3 = 1;
+
+ /*
+ * Types de variable
+ */
+ // byte - Entier signé utilisant la notation en complément à deux sur
+ // 8 bits
+ // (-128 <= byte <= 127)
+ byte fooByte = 100;
+
+ // Si vous voulez interpréter un byte en entier non-signé, cette simple
+ // opération peut vous aider
+ int unsignedIntLessThan256 = 0xff & fooByte;
+ // cela contraste avec une conversion qui peut être négative.
+ int signedInt = (int) fooByte;
+
+ // short - Entier signé utilisant la notation en complément à deux sur
+ // 16 bits
+ // (-32,768 <= short <= 32,767)
+ short fooShort = 10000;
+
+ // int - Entier signé utilisant la notation en complément à deux sur
+ // 32 bits
+ // (-2,147,483,648 <= int <= 2,147,483,647)
+ int bazInt = 1;
+
+ // long - Entier signé utilisant la notation en complément à deux sur
+ // 64 bits
+ // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ long fooLong = 100000L;
+ // L est utilisé pour indiquer que la variable est de type long;
+ // le nombre serait traité comme un int sans le L
+
+ // Note: byte, short, int et long sont signés. Ils peuvent avoir des
+ // valeurs positives et négatives.
+ // Il n'existe pas de variantes non-signées.
+ // char, toutefois, est non-signé sur 16 bits
+
+ // float - nombre à virgule flottante selon la norme IEEE 754 utilisant
+ // le format simple précision sur 32 bits
+ // 2^-149 <= float <= (2-2^-23) * 2^127
+ float fooFloat = 234.5f;
+ // f ou F sont utilisés pour indiquer que la variable est de type float;
+ // autrement elle serait traitée comme un double.
+
+ // double - nombre à virgule flottante selon la norme IEEE 754 utilisant
+ // le format double précision sur 64 bits
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
+ double fooDouble = 123.4;
+
+ // boolean - vrai & faux
+ boolean fooBoolean = true;
+ boolean barBoolean = false;
+
+ // char - un caractère Unicode sur 16 bits
+ char fooChar = 'A';
+
+ // les variables final ne peuvent pas être réassignés à un autre objet,
+ final int HOURS_I_WORK_PER_WEEK = 9001;
+ // mais ils peuvent être initialisés plus tard.
+ final double E;
+ E = 2.71828;
+
+ // BigInteger - entier immuable de taille arbitraire
+ //
+ // BigInteger est un type de donné qui autorise les développeurs à
+ // manipuler des entiers au delà de 64 bits. Les entiers sont stockés
+ // dans un tableau de bytes et sont manipulés grâce à des functions
+ // de la classe BigIntger
+ //
+ // BigInteger peut être initialiser en utilisant un tableau de bytes ou
+ // une chaîne de caractère.
+ BigInteger fooBigInteger = new BigInteger(fooByteArray);
+
+ // BigDecimal - entier immuable et positif de taille arbitraire
+ //
+ // BigDecimal comprend deux parties: une entier de taille arbitraire
+ // (BigInteger) et un entier de 32 bits représantant la position de la
+ // virgule.
+ //
+ // BigDecimal donne aux développeurs un contrôle total pour l'arrondie
+ // à la décimale. Il est recommandé de l'utiliser pour les valeurs
+ // monétaires et pour les cas où la value exacte de l'arondie à la
+ // décimale est requis.
+ //
+ // BigInteger peut être initialiser en utilisant un int, long, double ou
+ // String.
+ // On peut également utiliser un BigInteger et un int pour la
+ // position de la virgule.
+ BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
+
+ // Sachez que la création d'un BigDecimal avec un float ou
+ // un double prendra en compte l'inexactitude des représention en float
+ // ou double.
+ // Préférez String pour une représention exacte.
+ BigDecimal tenCents = new BigDecimal("0.1");
+
+ // String - Chaîne de caractères
+ String fooString = "My String Is Here!";
+
+ // \n est un caractère d'échappement qui indique une nouvelle ligne
+ String barString = "Printing on a new line?\nNo Problem!";
+ // \t est un caractère d'échappement qui indique une tabulation
+ String bazString = "Do you want to add a tab?\tNo Problem!";
+ System.out.println(fooString);
+ System.out.println(barString);
+ System.out.println(bazString);
+
+ // Construction de chaînes de caractères
+ // #1 - avec l'opérateur +
+ // C'est la manière la plus simple et optimisé par le compilateur
+ String plusConcatenated = "Strings can " + "be concatenated " + "via + operator.";
+ System.out.println(plusConcatenated);
+ // Affiche: Strings can be concatenated via + operator.
+
+ // #2 - avec StringBuilder
+ // Cette méthode ne nécessite pas d'objet String intermédiaire. Elle
+ // stocke juste les différentes chaînes de caractères et les assemble
+ // lorsque la méthode toString() est appelée.
+ // Attention: Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé
+ // entre les threads). Une alternative
+ // (avec un impact sur les performances) thread-safe est d'utiliser la
+ // classe StringBuffer.
+ StringBuilder builderConcatenated = new StringBuilder();
+ builderConcatenated.append("You ");
+ builderConcatenated.append("can use ");
+ builderConcatenated.append("the StringBuilder class.");
+ System.out.println(builderConcatenated.toString()); // only now is the string built
+ // Affiche: You can use the StringBuilder class.
+
+ // StringBuffer est efficace quand la chaîne de caractères n'est pas
+ // utilisée avec la fin de sa construction.
+ StringBuilder stringBuilder = new StringBuilder();
+ String inefficientString = "";
+ for (int i = 0 ; i < 10; i++) {
+ stringBuilder.append(i).append(" ");
+ inefficientString += i + " ";
+ }
+ System.out.println(inefficientString);
+ System.out.println(stringBuilder.toString());
+ // inefficientString est moins performant car une chaîne de caractères
+ // est créée à chaque itération de la boucle.
+ // Les concaténations avec + sont compilés en un StringBuilder et
+ // toString().
+ // Evitez les concaténations de string dans les boucles.
+
+ // #3 - avec la méthode format() de la classe String.
+ // Une autre alternative. Rapide et lisible.
+ String.format("%s may prefer %s.", "Or you", "String.format()");
+ // Affiche: Or you may prefer String.format().
+
+ // Tableau
+ // La taille du tableau doit être précisée à l'instantiation
+ // Les formats suivant sont possibles pour déclarer un tableau
+ // <datatype>[] <var name> = new <datatype>[<array size>];
+ // <datatype> <var name>[] = new <datatype>[<array size>];
+ int[] intArray = new int[10];
+ String[] stringArray = new String[1];
+ boolean boolArray[] = new boolean[100];
+
+ // Une autre manière de déclarer et initialiser un tableau
+ int[] y = {9000, 1000, 1337};
+ String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
+ boolean bools[] = {true, false, false};
+
+ // Accéder à un élément
+ System.out.println("intArray @ 0: " + intArray[0]);
+
+ // Les tableaus commencent à 0 et sont muables
+ intArray[1] = 1;
+ System.out.println("intArray @ 1: " + intArray[1]); // => 1
+
+ // Les autres types de donnés utiles sont
+ // ArrayList - Identique aux tableaux mais avec plus de fonctionnalités
+ // et de taille muable.
+ // LinkedList - Implémentation de listes doublement chaînées. Toutes Les
+ // opérations éffectuées le sont comme attendue pour une
+ // liste doublement chaînée.
+ // Map - Une collection d'objets qui fait correspondre une valeur à une
+ // clé. Map est une interface et ne peut pas être instantiée. Le
+ // type des clés et des valeurs doit être précisés à
+ // l'instantiation. Chaque clé doit correspondre à une seule
+ // valeur et chaque clé doit être unique (pas de clés dupliquées).
+ // HashMap - Cette classe utilise une table de hachage pour implémenter
+ // l'interface Map. Cela garantie que le temps d'exécution des
+ // opérations basiques, comme get (récuper une valeur) et
+ // insert (insérer une valeur), reste constant quelque soit la
+ // la taille.
+ // TreeMap - Cette classe utilise une structure en arbre et est
+ // ordonnée. Elle implémente un arbre bicolore (ou arbre rouge
+ // et noir) et ordonne les éléments en se basant sur la clé ou
+ // en utilisant un comparateur fournit à la création.
+
+ ///////////////////////////////////////
+ // Opérateurs
+ ///////////////////////////////////////
+ System.out.println("\n->Operators");
+
+ int i1 = 1, i2 = 2; // Raccourcis pour des déclarations multiples
+
+ // L'arithmétique
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
+ System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
+
+ // Le modulo
+ System.out.println("11%3 = "+(11 % 3)); // => 2
+
+ // Opérateurs de comparaison
+ System.out.println("3 == 2? " + (3 == 2)); // => faux
+ System.out.println("3 != 2? " + (3 != 2)); // => vrai
+ System.out.println("3 > 2? " + (3 > 2)); // => vrai
+ System.out.println("3 < 2? " + (3 < 2)); // => faux
+ System.out.println("2 <= 2? " + (2 <= 2)); // => vrai
+ System.out.println("2 >= 2? " + (2 >= 2)); // => vrai
+
+ // Opérateurs boolean
+ System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
+ System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
+ System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
+
+ // Opérateurs sur les bits
+ /*
+ ~ Complément à un
+ << Décalage des bits vers la gauche
+ >> Décalage des bits vers la droite, le signe est conservé
+ >>> Décalage des bits vers la droite, zéro est utilisé pour les bits
+ les plus à gauche
+ & Opérateur ET
+ ^ Opérateur OU exlusif
+ | Opérateur OU inclusif
+ */
+
+ // Opérateurs d'incrémentation
+ int i = 0;
+ System.out.println("\n->Inc/Dec-rementation");
+ // Les opérateurs ++ et -- incrémentent et décrémentent respectivement
+ // de 1.
+ // S'ils sont placés avant la variable, ils incrémentent la variable puis
+ // retournent la valeur. Placés après la varible, ils retournent la variable
+ // puis l'incrémentent.
+ System.out.println(i++); // i = 1, affiche 0 (pré-incrément)
+ System.out.println(++i); // i = 2, affiche 2 (post-incrément)
+ System.out.println(i--); // i = 1, affiche 2 (post-incrément)
+ System.out.println(--i); // i = 0, affiche 0 (pré-incrément)
+
+ ///////////////////////////////////////
+ // Structures de contôles
+ ///////////////////////////////////////
+ System.out.println("\n->Control Structures");
+
+ // Les instructions conditionnelle sont identiques aux langage C
+ int j = 10;
+ if (j == 10) {
+ System.out.println("I get printed");
+ } else if (j > 10) {
+ System.out.println("I don't");
+ } else {
+ System.out.println("I also don't");
+ }
+
+ // Bouble while
+ int fooWhile = 0;
+ while(fooWhile < 100) {
+ System.out.println(fooWhile);
+ // Incrémente le compteur
+ // Itéré 100 fois, fooWhile 0,1,2...99
+ fooWhile++;
+ }
+ System.out.println("fooWhile Value: " + fooWhile);
+
+ // Boucle do-while
+ int fooDoWhile = 0;
+ do {
+ System.out.println(fooDoWhile);
+ // Incrémente le compteur
+ // Itéré 99 fois, fooDoWhile 0->99
+ fooDoWhile++;
+ } while(fooDoWhile < 100);
+ System.out.println("fooDoWhile Value: " + fooDoWhile);
+
+ // Boucle for
+ // De la forme for(<start_statement>; <conditional>; <step>)
+ for (int fooFor = 0; fooFor < 10; fooFor++) {
+ System.out.println(fooFor);
+ // Itéré 10 fois, fooFor 0->9
+ }
+ System.out.println("fooFor Value: " + fooFor);
+
+ // Fin d'une boucle for avec un label
+ outer:
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (i == 5 && j ==5) {
+ break outer;
+ // termine l'itération de la boucle englobante avec le label outer
+ }
+ }
+ }
+
+ // Boucle for-each
+ // La boucle for est également capable d'itérer aussi bien sur un
+ // tableau que sur des objets qui implémentent l'interface Iterable.
+ int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
+ // De la forme: for (<object> : <iterable>)
+ // Lu comme: "Pour chaque élément du tableau"
+ // note: le type doit correspondre à celui de l'objet itérable
+ for (int bar : fooList) {
+ System.out.println(bar);
+ //Itère 9 fois et affiche les chiffres de 1 à 9
+ }
+
+ // Le switch-case
+ // Un switch fonctionne avec les données de type byte, short, char et
+ // int.
+ // On peut également utiliser le type Enum, la classe String et les
+ // classes spéciales qui englobent les types primitifs (Character, Byte,
+ // Short et Integer).
+ // Depuis Java 7, on peut utiliser le type String.
+ int month = 3;
+ String monthString;
+ switch (month) {
+ case 1: monthString = "January";
+ break;
+ case 2: monthString = "February";
+ break;
+ case 3: monthString = "March";
+ break;
+ default: monthString = "Some other month";
+ break;
+ }
+ System.out.println("Switch Case Result: " + monthString);
+
+ // try-with-resources (Java 7+)
+ // Le mécanisme de gestion des erreurs try-catch-finally peut être
+ // utilisé mais depuis Java 7 il est également possible d'utiliser
+ // try-with-ressources.
+ // try-with-resources simplifie try-catch-finally en fermant
+ // automatiquement les ressources
+
+ // Pour utiliser un try-with-resources, il suffit d'inclure l'instance
+ // d'une classe qui implémente l'interface java.lang.AutoCloseable
+ try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
+ // Ici, vous pouvez essayer de faire quelque chose qui lance une
+ // exception.
+ System.out.println(br.readLine());
+ // Avec Java 7, la ressource sera toujours fermé, même si elle lance
+ // une exception.
+ } catch (Exception ex) {
+ // La ressource sera fermé avant que le catch s'exécute.
+ System.out.println("readLine() failed.");
+ }
+ // Il n'y a pas besoin de finally dans ce cas, l'objet BufferedReader
+ // sera déjà fermé. Cela peut être utile dans certains cas spécifiques
+ // où le code contenu dans finally ne serait pas exécuté.
+ // Consulter la documention Oracle pour en savoir plus (en anglais) :
+ // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
+
+
+ // Expression ternaire
+ // Vous pouvez utiliser l'opérateur ternaire '?' pour faire un
+ // assignement rapide avec une condition logique.
+ // Il faut lire "Si la (condition) est vraie alors utiliser la
+ // <première valeur> sinon utilisez la <deuxième valeur>".
+ int foo = 5;
+ String bar = (foo < 10) ? "A" : "B";
+ System.out.println("bar : " + bar); // Affiche "bar : A", car la condition est vraie
+ // Ou alors plus simplement
+ System.out.println("bar : " + (foo < 10 ? "A" : "B")); // Affiche également "bar : A"
+
+ ////////////////////////////////////////
+ // Conversion de type
+ ////////////////////////////////////////
+
+ // Autoboxing
+
+ // Convertir un objet String en un objet Integer
+ Integer.parseInt("123"); // retourne un le type primitif int de 123
+
+ // Convert Integer To String
+ Integer.toString(123); // retourne un object String correspondant à"123"
+
+ // Pour les autres conversions, référer vous aux classes suivantes:
+ // Double
+ // Long
+ // String
+
+ ///////////////////////////////////////
+ // Classes et fonctions
+ ///////////////////////////////////////
+
+ System.out.println("\n->Classes & Functions");
+
+ // (voir plus loin pour la définition de la classe Bicycle)
+
+ // Utilisez new pour instancier une classe
+ Bicycle trek = new Bicycle();
+
+ // Pour appeler une méthode de l'objet
+ trek.speedUp(3); // !! Il est conseillé de passer par une méthode pour
+ // changer la valeur d'une variable.
+ trek.setCadence(100);
+
+ // toString retourne une représentation de l'objet en chaîne de caractères.
+ System.out.println("trek info: " + trek.toString());
+
+ // Initialisation avec double accolades
+ // Le langage Java ne permet pas de créer des collections statiques d'une
+ // manière simple. Généralement, on utilise la forme suivante:
+ private static final Set<String> COUNTRIES = new HashSet<String>();
+ static {
+ COUNTRIES.add("DENMARK");
+ COUNTRIES.add("SWEDEN");
+ COUNTRIES.add("FINLAND");
+ }
+
+ // Mais on peut le faire d'une manière plus habile, dite initialisation
+ // avec double semi-colonnes
+ private static final Set<String> COUNTRIES = new HashSet<String>() {{
+ add("DENMARK");
+ add("SWEDEN");
+ add("FINLAND");
+ }}
+
+ // La première semi-colonne crée une classe anonyme et la deuxième est
+ // un bloc d'initialisation du bloc. Ce dernier est appelé lorsque Copyright (c)
+ // classe anonyme est crée. Cela ne fonctionne pas uniquement pour les
+ // collections mais également pour toutes les classes n'étant pas
+ // déclarées comme final.
+
+ } // Fin de la méthode main
+} // Fin de la class JavaFr
+
+// Vous pouvez inclure des classes qui ne sont pas publics dans un fichier Java.
+// Cependant, il est préférable de séparer les
+// classes dans des fichiers différents.
+
+// Syntaxe de déclaration des classes:
+// <public/private/protected> class <Nom de la classe> {
+// // Les attributs, les constructeurs et les méthodes de la classe vont ici.
+// // Les functions de classes sont appelées méthode.
+// }
+
+class Bicycle {
+
+ // Attributs et variables de la classe Bicycle
+ public int cadence; // Public: Peut être accesible depuis n'importe où
+ private int speed; // Private: Accisible depuis la classe
+ protected int gear; // Protected: Accisible depuis la classe et ses sous-
+ // classes
+ String name; // default: Uniquement accesible depuis ce package
+ static String className; // Variable de classe static
+
+ // Bloc static
+ // Java n'a pas d'implémentation pour les constructeurs statiques mais
+ // possède le bloc static qui peut être utilisé pour initialiser les
+ // variables de classe.
+ // Ce bloc sera appelé lorsque la classe sera chargée.
+ static {
+ className = "Bicycle";
+ }
+
+ // Les constructeurs sont un moyen de créer les classe
+ // Ceci est le constructeur de la classe Bicycle
+ public Bicycle() {
+ // Vous pouvez aussie appeler un autre constructeur. Par exemple en
+ // appelant le constructeur de la classe mère (voir héritage):
+ // this(1, 50, 5, "Bontrager");
+ gear = 1;
+ cadence = 50;
+ speed = 5;
+ name = "Bontrager";
+ }
+ // Le constructeur peut prendre plusieurs arguments
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ String name) {
+ this.gear = startGear;
+ this.cadence = startCadence;
+ this.speed = startSpeed;
+ this.name = name;
+ }
+
+ // Syntaxe d'une méthode :
+ // <public/private/protected> <type de retour> <nom de la fonction>(
+ // <arguments>)
+
+ // Les classes Java possèdent souvent des accesseurs (getters) et mutateurs
+ // (setters) pour leurs attributs.
+
+ public int getCadence() {
+ return cadence;
+ }
+
+ // Les méthodes void ne retourne aucune valeur
+ public void setCadence(int newValue) {
+ cadence = newValue;
+ }
+ public void setGear(int newValue) {
+ gear = newValue;
+ }
+ public void speedUp(int increment) {
+ speed += increment;
+ }
+ public void slowDown(int decrement) {
+ speed -= decrement;
+ }
+ public void setName(String newName) {
+ name = newName;
+ }
+ public String getName() {
+ return name;
+ }
+
+ // Méthode pour afficher la valeur des attributs de l'objet. @Override est
+ // une annotation (voir plus loin).
+ @Override //On dit ici qu'on remplace la méthode de la classe Objet.
+ public String toString() {
+ return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
+ " name: " + name;
+ }
+} // Fin de la classe Bicycle
+
+// PennyFarthing est une sous-classe de Bicycle
+class PennyFarthing extends Bicycle {
+ // (Les Penny Farthings sont des bicyclette avec une grande roue avant.
+ // Il n'y a pas de roue libre, le cycliste est obligé de pédaler en
+ // permanence.)
+
+ public PennyFarthing(int startCadence, int startSpeed) {
+ // Appelez le constructeur parent avec la méthode super()
+ super(startCadence, startSpeed, 0, "PennyFarthing");
+ }
+
+ // Ici nous modifions la méthode setGear() de la classe mère. Il faut donc
+ // utiliser l'annotation @Overide. Pour en savoir plus sur les annotations,
+ // consulter la documention officiel (en anglais) :
+ // out: http://docs.oracle.com/javase/tutorial/java/annotations/
+ @Override
+ public void setGear(int gear) {
+ this.gear = 0;
+ }
+}
+
+// Polymorphisme (cast d'objets)
+// Comme la classe PennyFarthing héritent de la classe Bicycle, on peut dire
+// qu'un PennyFarthing est un Bicycle (un vélo en anglais) et écrire :
+// Bicycle bicycle = new PennyFarthing();
+// Le polymorphisme est la capacité d'un objet de se faire passer pour un autre.
+// Vous pouvez consulter la documentation Oracle pour plus de détails et
+// concepts (en anglais) :
+// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
+// Interfaces
+// Déclaration d'une interface
+// <niveau d'accès> interface <nom de l'interface> extends <nom de l'interface
+// mère> {
+// // Constantes
+// // Délaration des méthodes
+// }
+
+// Exemple - Toute nourriture peut être mangée et digégée différemment
+// L'interface Edible (traduction : comestible) décrit l'action de manger
+public interface Edible {
+ public void eat(); // Toute classe qui implémente cette interface doit
+ // implémenter cette méthode
+}
+
+// L'interface Digestible décrit l'action de digérer
+public interface Digestible {
+ public void digest();
+ // Depuis Java 8, les interfaces peuvent avoir des méthodes par défaut.
+ public void defaultMethod() {
+ System.out.println("Hi from default method ...");
+ }
+}
+
+// On peut maintenant créer une classe qui implémente chacune de ces interfaces.
+public class Fruit implements Edible, Digestible {
+ @Override
+ public void eat() {
+ // ...
+ }
+
+ @Override
+ public void digest() {
+ // ...
+ }
+}
+
+// En Java, on peut hériter uniquement d'une classe mais on peut implémenter
+// plusieurs interfaces:
+public class ExampleClass extends ExampleClassParent implements InterfaceOne,
+ InterfaceTwo {
+ @Override
+ public void InterfaceOneMethod() {
+ }
+
+ @Override
+ public void InterfaceTwoMethod() {
+ }
+
+}
+
+// Classes abstraites
+
+// Syntaxe de déclaration:
+// <niveau d'accès> abstract class <nom de la classe abstraite> extends <nom de la
+// classe mère abstraite> {
+// // Constantes et variables
+// // Méthodes
+// }
+
+// Une classe abstraite contient au moins une méthode abstraite qui doit être
+// définee dans la classe fille. Comme les interfaces, les classes abstraites ne
+// peuvent pas être instanciées mais doivent être étendues avec les méthodes
+// abstraites implémentées. À la différence des interfaces, une classe abstraite
+// peut contenir des méthodes abstraites ou non-abstraites. Les méthodes dans une
+// interfaces ne peuvent pas être implémentées à l'exception des méthodes static.
+// Les variables d'une classe abstraite sont déclarées comme final par défaut à
+// l'opposé des interfaces. Finalement les classes abstraites peuvent avoir une
+// méthode main.
+public abstract class Animal
+{
+ public abstract void makeSound();
+
+ // Les méthodes peuvent avoir une implémentation dans une classe abstraite.
+ public void eat()
+ {
+ System.out.println("I am an animal and I am Eating.");
+ // Note: On peut accéder à une variable privée ici.
+ age = 30;
+ }
+
+ // On n'a pas besoin d'initialiser les variables dans les classe abstraites.
+ // Cependant, dans une interfaces, les variables sont implicitement
+ // déclarées comme final et doivent donc être initialisées.
+ private int age;
+
+ public void printAge()
+ {
+ System.out.println(age);
+ }
+
+ // Les classes abstraites peuvent avoir une fonction main.
+ public static void main(String[] args)
+ {
+ System.out.println("I am abstract");
+ }
+}
+
+class Dog extends Animal
+{
+ // On doit également utiliser l'annotation @Override lors de la surchage de
+ // la méthode abstraite d'une classe abstraite.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Bark");
+ // age = 30; ==> ERREUR! age est privé et n'est pas accesible.
+ }
+
+ // NOTE: Vous obtiendrez une erreur si vous utilisé l'annotation @Override
+ // ici car Java n'autorise pas la surcharge de méthodes statiques. Ce qui ce
+ // passe est appelé "method hiding". Si vous voulez en savoir plus,
+ // consultez cette discussion (en anglais) :
+ // http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Dog pluto = new Dog();
+ pluto.makeSound();
+ pluto.eat();
+ pluto.printAge();
+ }
+}
+
+// Classes finales
+
+// Syntaxe de déclaration
+// <niveau d'accès> final <nom de la classe final> {
+// // Constantes et variables
+// // Méthodes déclarations
+// }
+
+// Les classe déclarées comme final ne peuvent pas avoir de classe fille. Elles
+// peuvent être considérées comme l'opposé des classes abstraites.
+public final class SaberToothedCat extends Animal
+{
+ // On doit également utiliser l'annotation @Override lors de la surchage de
+ // la méthode abstraite d'une classe abstraite.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Méthodes final
+public abstract class Mammal()
+{
+ // Syntaxe:
+ // <niveau d'accès> final <type de retour> <nom de la fonction>(<arguments>)
+
+ // Les méthodes déclarées comme final ne peuvent pas être surchargées par
+ // une classe fille et en sont donc l'implémentation finale.
+ public final boolean isWarmBlooded()
+ {
+ return true;
+ }
+}
+
+// Enumérations
+//
+// Le type enum est un type de donnée spécial qui permet à une variable de ne
+// prendre que certaines valeurs prédéfinies. La variable doit être égales à une
+// des valeurs pédéfinies pour celle-ci. En Java, les variables constantes sont
+// notées en majuscules.
+// On définie un type enum en utilisant le mot clé enum. Par exemple pour les
+// jours de l'année:
+public enum Day {
+ SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
+ THURSDAY, FRIDAY, SATURDAY
+}
+
+// On l'utilise ainsi:
+public class EnumTest {
+ // On utilise notre énumération
+ Day day;
+
+ public EnumTest(Day day) {
+ this.day = day;
+ }
+
+ public void tellItLikeItIs() {
+ switch (day) {
+ case MONDAY:
+ System.out.println("Mondays are bad.");
+ break;
+ case FRIDAY:
+ System.out.println("Fridays are better.");
+ break;
+ case SATURDAY:
+ case SUNDAY:
+ System.out.println("Weekends are best.");
+ break;
+ default:
+ System.out.println("Midweek days are so-so.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTest firstDay = new EnumTest(Day.MONDAY);
+ firstDay.tellItLikeItIs(); // => affiche "Mondays are bad"
+ EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
+ thirdDay.tellItLikeItIs(); // => affiche "Midweek days are so-so"
+ }
+}
+
+// Le type enum permet de faire bien plus que ce qui est montré ici. Il ne se
+// limite pas à une liste de constante mais peut inclure des champs et méthodes.
+// Vous pouvez en savoir plus ici (en anglais):
+//https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
+```
+
+## Pour aller plus loin (en anglais)
+
+Les liens ci-dessous sont données si vous souhaitez approfondir sur le sujet,
+n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
+
+**Guides officiels d'Oracle**:
+
+* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html)
+
+* [Java Access level modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Abstraction](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [Generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
+
+* Nouvelles fonctionnalités Java 8:
+ * [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)
+ * [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html)
+
+**Pratiquer en ligne et tutoriels**
+
+* [Learneroo.com - Learn Java](http://www.learneroo.com)
+
+* [Codingbat.com](http://codingbat.com/java)
+
+**Livres**:
+
+* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
+
+* [Thinking in Java](http://www.mindview.net/Books/TIJ/)
+
+* [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
+
+* [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300)
diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown-fr.html.markdown
index 2e4e8461..2e4e8461 100644
--- a/fr-fr/markdown.html.markdown
+++ b/fr-fr/markdown-fr.html.markdown
diff --git a/fr-fr/php.html.markdown b/fr-fr/php-fr.html.markdown
index 823630bd..45a02d75 100644
--- a/fr-fr/php.html.markdown
+++ b/fr-fr/php-fr.html.markdown
@@ -6,10 +6,11 @@ contributors:
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["Pascal Boutin", "http://pboutin.net/"]
+ - ["Julien M'Poy", "https://github.com/groovytron"]
lang: fr-fr
---
-This document describes PHP 5+.
+Ce document décrit PHP 5+.
```php
// Le code PHP doit être placé à l'intérieur de balises '<?php'
@@ -48,7 +49,7 @@ Hello World Again!
// Un nom de variable valide commence par une lettre ou un souligné,
// suivi de n'importe quelle lettre, nombre ou de soulignés.
-// Les valeurs booléenes ne sont pas sensibles à la casse
+// Les valeurs booléennes ne sont pas sensibles à la casse
$boolean = true; // ou TRUE ou True
$boolean = false; // ou FALSE ou False
@@ -84,30 +85,30 @@ $number /= $float; // Divise et assigne le quotient à $number
$sgl_quotes = '$String'; // => '$String'
// Évitez les guillemets sauf pour inclure le contenu d'une autre variable
-$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+$dbl_quotes = "Ceci est une $sgl_quotes."; // => 'Ceci est une $String.'
// Les caractères spéciaux sont seulement échappés avec des guillemets
-$escaped = "This contains a \t tab character.";
-$unescaped = 'This just contains a slash and a t: \t';
+$escaped = "Ceci contient \t une tabulation.";
+$unescaped = 'Ceci contient juste un slash et un t: \t';
// En cas de besoin, placez la variable dans des accolades
-$money = "I have $${number} in the bank.";
+$money = "J'ai $${number} sur mon compte en banque.";
// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes
// multi-lignes non-interprétées
$nowdoc = <<<'END'
-Multi line
-string
+String
+mutli-lignes
END;
// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées
$heredoc = <<<END
-Multi line
$sgl_quotes
+multi-lignes
END;
// La concaténation de chaînes se fait avec un .
-echo 'This string ' . 'is concatenated';
+echo 'Cette string ' . 'est concatenée'; // => 'Cette string est concaténée'
/********************************
@@ -122,7 +123,7 @@ echo 'This string ' . 'is concatenated';
define("FOO", "something");
// on peut accéder à une constante en utilisant directement son nom
-echo 'This outputs '.FOO;
+echo 'Ceci affiche ' . FOO;
/********************************
@@ -149,6 +150,14 @@ $array[] = 'Four';
// Retrait d'un élément du tableau
unset($array[3]);
+// Depuis PHP 7, il est possible de déclarer des tableaux constants en
+// utilisant 'define'.
+define('ANIMAUX', [
+ 'chien',
+ 'chat',
+ 'oiseau',
+]);
+
/********************************
* Affichage
*/
@@ -159,11 +168,13 @@ echo('Hello World!');
print('Hello World!'); // Pareil à "écho"
-// Pour écho, vous n'avez pas besoin des parenthèses
+// 'echo' et 'print' sont des language constructs.
+// Il n'ont pas besoin de parenthèses car ils sont traités comme
+// des opérateurs unaires.
echo 'Hello World!';
-print 'Hello World!'; // Pour print non plus
+print 'Hello World!';
-$paragraph = 'paragraph';
+$paragraph = 'paragraphe';
echo 100; // Affichez un scalaire directement
echo $paragraph; // ou des variables
@@ -202,7 +213,8 @@ $b = '0';
$c = '1';
$d = '1';
-// assert affiche un avertissement dans son argument n'est pas vrai
+// assert affiche un avertissement quand l'expression booléenne passée
+// en argument n'est pas vraie.
// Ces comparaisons vont toujours être vraies, même si leurs
// types ne sont pas les mêmes.
@@ -315,7 +327,7 @@ if ($x === '0') {
switch ($x) {
case '0':
print 'Les switch font du transtypage implicite';
- break; // Il est important de déclaré un 'break', sinon les cas
+ break; // Il est important de déclarer un 'break', sinon les cas
// 'two' et 'three' seront évalués
case 'two':
case 'three':
@@ -390,9 +402,10 @@ function my_function () {
echo my_function(); // => "Hello"
-// Les noms de fonction débutent par le symbole $
-// Un nom de variable valide commence par une lettre ou un souligné,
+// Un nom de fonction valide commence par une lettre ou un souligné,
// suivi de n'importe quelle lettre, nombre ou de soulignés.
+// Les noms des arguments d'une fonction doivent respecter le même format que
+// celui des variables.
function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1
$result = $x + $y;
@@ -519,7 +532,7 @@ class MyClass
public static function myStaticMethod()
{
- print 'I am static';
+ print 'Je suis static';
}
}
@@ -527,7 +540,7 @@ class MyClass
echo MyClass::MY_CONST; // Outputs 'value';
echo MyClass::$staticVar; // Retourne 'static';
-MyClass::myStaticMethod(); // Retourne 'I am static';
+MyClass::myStaticMethod(); // Retourne 'Je suis static';
// On peut instancier une classe en utilisant le mot clé 'new'
$my_class = new MyClass('An instance property');
@@ -584,7 +597,7 @@ echo $x->property; // Va utiliser la méthode __get()
$x->property = 'Something'; // Va utiliser la méthode __set()
// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou
-// elle peuvent implémenter une interface (en utilisant le mot clé 'implement').
+// elle peuvent implémenter une interface (en utilisant le mot clé 'implements').
// Une interface peut être déclarée avec le mot clé 'interface'
@@ -637,6 +650,35 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo
}
}
+// Il est possible de déclarer des classes internes anonymes depuis PHP 7
+
+interface Logger {
+ public function log(string $msg);
+}
+
+class Application {
+ private $logger;
+
+ public function getLogger(): Logger {
+ return $this->logger;
+ }
+
+ public function setLogger(Logger $logger) {
+ $this->logger = $logger;
+ }
+}
+
+$app = new Application;
+
+$app->setLogger(new class implements Logger {
+ public function log(string $msg) {
+ echo $msg;
+ }
+});
+
+var_dump($app->getLogger()); // => 'object(class@anonymous)#2 (0) {}'
+
+
/********************************
* Espaces de noms (namespaces)
*/
diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala-fr.html.markdown
index c6a61745..c6a61745 100644
--- a/fr-fr/scala.html.markdown
+++ b/fr-fr/scala-fr.html.markdown
diff --git a/fr-fr/vim.html.markdown b/fr-fr/vim-fr.html.markdown
index b2f1d24d..b2f1d24d 100644
--- a/fr-fr/vim.html.markdown
+++ b/fr-fr/vim-fr.html.markdown
diff --git a/git.html.markdown b/git.html.markdown
index 088c109f..582f8863 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -292,6 +292,10 @@ contains the changes made and a message created by the user.
# commit with a message
$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+# signed commit with a message (user.signingkey must have been set
+# with your GPG key e.g. git config --global user.signingkey 5173AAD5)
+$ git commit -S -m "signed commit message"
+
# automatically stage modified or deleted files, except new files, and then commit
$ git commit -a -m "Modified foo.php and removed bar.php"
diff --git a/go.html.markdown b/go.html.markdown
index e5263cf6..47d9c234 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -180,7 +180,7 @@ func learnFlowControl() {
if true {
fmt.Println("told ya")
}
- // Formatting is standardized by the command line command "go fmt."
+ // Formatting is standardized by the command line command "go fmt".
if false {
// Pout.
} else {
diff --git a/groovy.html.markdown b/groovy.html.markdown
index a3a45757..efbb2b32 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -230,10 +230,12 @@ for (i in array) {
//Iterate over a map
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
-x = 0
+x = ""
for ( e in map ) {
x += e.value
+ x += " "
}
+assert x.equals("Roberto Grails Groovy ")
/*
Operators
diff --git a/haml.html.markdown b/haml.html.markdown
index 5dd4cb6d..bb8bdc54 100644
--- a/haml.html.markdown
+++ b/haml.html.markdown
@@ -3,6 +3,7 @@ language: haml
filename: learnhaml.haml
contributors:
- ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Vasiliy Petrov", "https://github.com/Saugardas"]
---
Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup.
@@ -11,7 +12,9 @@ It aims to reduce repetition in your markup by closing tags for you based on the
You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html.
+```shell
$ haml input_file.haml output_file.html
+```
```haml
@@ -55,8 +58,17 @@ $ haml input_file.haml output_file.html
</header>
</body>
-/ The div tag is the default element, so they can be written simply like this
-.foo
+/
+ The div tag is the default element, so it can be omitted.
+ You can define only class/id using . or #
+ For example
+
+%div.my_class
+ %div#my_id
+
+/ Can be written
+.my_class
+ #my_id
/ To add content to a tag, add the text directly after the declaration
%h1 Headline copy
@@ -97,6 +109,15 @@ $ haml input_file.haml output_file.html
/ To write data-attributes, use the :data key with its value as another hash
%div{:data => {:attribute => 'foo'}}
+/ For Ruby version 1.9 or higher you can use Ruby's new hash syntax
+%div{ data: { attribute: 'foo' } }
+
+/ Also you can use HTML-style attribute syntax.
+%a(href='#' title='bar')
+
+/ And both syntaxes together
+%a(href='#'){ title: @my_class.title }
+
/ -------------------------------------------
/ Inserting Ruby
@@ -120,7 +141,7 @@ $ haml input_file.haml output_file.html
- books.shuffle.each_with_index do |book, index|
%h1= book
- if book do
+ - if book do
%p This is a book
/ Adding ordered / unordered list
@@ -166,12 +187,33 @@ $ haml input_file.haml output_file.html
/ -------------------------------------------
/
- Use the colon to define Haml filters, one example of a filter you can
- use is :javascript, which can be used for writing inline js
+ Filters pass the block to another filtering program and return the result in Haml
+ To use a filter, type a colon and the name of the filter
+
+/ Markdown filter
+:markdown
+ # Header
+ Text **inside** the *block*
+
+/ The code above is compiled into
+<h1>Header</h1>
+
+<p>Text <strong>inside</strong> the <em>block</em></p>
+
+/ Javascript filter
:javascript
console.log('This is inline <script>');
+/ is compiled into
+<script>
+ console.log('This is inline <script>');
+</script>
+
+/
+ There are many types of filters (:markdown, :javascript, :coffee, :css, :ruby and so on)
+ Also you can define your own filters using Haml::Filters
+
```
## Additional resources
diff --git a/haxe.html.markdown b/haxe.html.markdown
index e811031e..df2a1e78 100644
--- a/haxe.html.markdown
+++ b/haxe.html.markdown
@@ -770,8 +770,8 @@ class UsingExample {
```
We're still only scratching the surface here of what Haxe can do. For a formal
-overiew of all Haxe features, checkout the [online
-manual](http://haxe.org/manual), the [online api](http://api.haxe.org/), and
+overview of all Haxe features, checkout the [online
+manual](http://haxe.org/manual), the [online API](http://api.haxe.org/), and
"haxelib", the [haxe library repo] (http://lib.haxe.org/).
For more advanced topics, consider checking out:
diff --git a/html.html.markdown b/html.html.markdown
index 3c855b5c..6516e5dd 100644
--- a/html.html.markdown
+++ b/html.html.markdown
@@ -111,7 +111,7 @@ This article is concerned principally with HTML syntax and some useful tips.
## Usage
-HTML is written in files ending with `.html`.
+HTML is written in files ending with `.html` or `.htm`. The mime type is `text/html`.
## To Learn More
diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/python-hu.html.markdown
new file mode 100644
index 00000000..9b55f8e2
--- /dev/null
+++ b/hu-hu/python-hu.html.markdown
@@ -0,0 +1,816 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "https://aminb.org"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+ - ["asyne", "https://github.com/justblah"]
+ - ["habi", "http://github.com/habi"]
+translators:
+ - ["Tamás Diószegi", "https://github.com/ditam"]
+filename: learnpython-hu.py
+lang: hu-hu
+---
+
+A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az
+egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem
+bele. Tulajdonképpen futtatható pszeudokód.
+
+Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
+vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
+
+Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
+általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
+támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
+ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/)
+ajánlott.
+
+Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x
+verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával.
+A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami
+Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott.
+
+```python
+
+# Az egysoros kommentek kettőskereszttel kezdődnek
+
+""" Többsoros stringeket három darab " közé
+ fogva lehet írni, ezeket gyakran használják
+ több soros kommentként.
+"""
+
+####################################################
+# 1. Egyszerű adattípusok és operátorok
+####################################################
+
+# Használhatsz számokat
+3 # => 3
+
+# Az alapműveletek meglepetésektől mentesek
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része
+# lesz az eredmény
+5 / 2 # => 2
+
+# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk
+2.0 # Ez egy float
+11.0 / 4.0 # => 2.75 áh... máris jobb
+
+# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # floatok esetén is
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Ha importáljuk a division modult (ld. 6. Modulok rész),
+# akkor a '/' jellel pontos osztást tudunk végezni.
+from __future__ import division
+
+11 / 4 # => 2.75 ...sima osztás
+11 // 4 # => 2 ...egész osztás
+
+# Modulo művelet
+7 % 3 # => 1
+
+# Hatványozás (x az y. hatványra)
+2 ** 4 # => 16
+
+# A precedencia zárójelekkel befolyásolható
+(1 + 3) * 2 # => 8
+
+# Logikai operátorok
+# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes
+True and False # => False
+False or True # => True
+
+# A logikai operátorok egészeken is használhatóak
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
+
+# Negálni a not kulcsszóval lehet
+not True # => False
+not False # => True
+
+# Egyenlőségvizsgálat ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Egyenlőtlenség !=
+1 != 1 # => False
+2 != 1 # => True
+
+# További összehasonlítások
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Az összehasonlítások láncolhatóak!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# Stringeket " vagy ' jelek közt lehet megadni
+"Ez egy string."
+'Ez egy másik string.'
+
+# A stringek összeadhatóak!
+"Hello " + "world!" # => "Hello world!"
+# '+' jel nélkül is összeadhatóak
+"Hello " "world!" # => "Hello world!"
+
+# ... illetve szorozhatóak
+"Hello" * 3 # => "HelloHelloHello"
+
+# Kezelhető karakterek indexelhető listájaként
+"This is a string"[0] # => 'T'
+
+# A string hosszát a len függvény adja meg
+len("This is a string") # => 16
+
+# String formázáshoz a % jel használható
+# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog
+# kerülni, de azért jó tudni, hogyan működik.
+x = 'alma'
+y = 'citrom'
+z = "A kosárban levő elemek: %s és %s" % (x, y)
+
+# A string formázás újabb módja a format metódus használatával történik.
+# Jelenleg ez a javasolt megoldás.
+"{} egy {} szöveg".format("Ez", "helytartó")
+"A {0} pedig {1}".format("string", "formázható")
+# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók.
+"{name} kedvence a {food}".format(name="Bob", food="lasagna")
+
+# None egy objektum
+None # => None
+
+# A None-nal való összehasonlításhoz ne használd a "==" jelet,
+# használd az "is" kulcsszót helyette
+"etc" is None # => False
+None is None # => True
+
+# Az 'is' operátor objektum egyezést vizsgál.
+# Primitív típusok esetén ez nem túl hasznos,
+# objektumok esetén azonban annál inkább.
+
+# Bármilyen objektum használható logikai kontextusban.
+# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek):
+# - None
+# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j)
+# - üres sorozatok (pl. '', (), [])
+# - üres konténerek (pl., {}, set())
+# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint,
+# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki)
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+# 2. Változók és kollekciók
+####################################################
+
+# Létezik egy print utasítás
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# Így lehet egyszerűen bemenetet kérni a konzolról:
+input_string_var = raw_input(
+ "Enter some data: ") # Visszatér a megadott stringgel
+input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként
+# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni
+# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve
+
+# A változókat nem szükséges a használat előtt deklarálni
+some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas
+some_var # => 5
+
+# Érték nélküli változóra hivatkozás hibát dob.
+# Lásd a Control Flow szekciót a kivételkezelésről.
+some_other_var # name error hibát dob
+
+# az if használható kifejezésként
+# a C nyelv '?:' ternáris operátorával egyenértékűen
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# A listákban sorozatok tárolhatóak
+li = []
+# Már inicializáláskor megadhatóak elemek
+other_li = [4, 5, 6]
+
+# A lista végére az append metódus rak új elemet
+li.append(1) # li jelenleg [1]
+li.append(2) # li jelenleg [1, 2]
+li.append(4) # li jelenleg [1, 2, 4]
+li.append(3) # li jelenleg [1, 2, 4, 3]
+# A végéről a pop metódus távolít el elemet
+li.pop() # => 3 és li jelenleg [1, 2, 4]
+# Rakjuk vissza
+li.append(3) # li jelenleg [1, 2, 4, 3], újra.
+
+# A lista elemeket tömb indexeléssel lehet hivatkozni
+li[0] # => 1
+# A már inicializált értékekhez a = jellel lehet új értéket rendelni
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # csak visszaállítjuk az eredeti értékére
+# Így is lehet az utolsó elemre hivatkozni
+li[-1] # => 3
+
+# A túlindexelés eredménye IndexError
+li[4] # IndexError hibát dob
+
+# A lista részeit a slice szintaxissal lehet kimetszeni
+# (Matekosoknak ez egy zárt/nyitott intervallum.)
+li[1:3] # => [2, 4]
+# A lista eleje kihagyható így
+li[2:] # => [4, 3]
+# Kihagyható a vége
+li[:3] # => [1, 2, 4]
+# Minden második elem kiválasztása
+li[::2] # =>[1, 4]
+# A lista egy másolata, fordított sorrendben
+li[::-1] # => [3, 4, 2, 1]
+# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek
+# li[start:end:step]
+
+# Listaelemek a "del" paranccsal törölhetőek
+del li[2] # li jelenleg [1, 2, 3]
+
+# A listák összeadhatóak
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# Megjegyzés: az eredeti li és other_li értékei változatlanok
+
+# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal
+li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6]
+
+# Egy elem első előfordulásának eltávolítása
+li.remove(2) # li jelenleg [1, 3, 4, 5, 6]
+li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában
+
+# Elemek beszúrhatóak tetszőleges helyre
+li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét
+
+# Egy elem első előfordulási helye
+li.index(2) # => 1
+li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában
+
+# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető
+1 in li # => True
+
+# A lista hossza a "len()" függvénnyel
+len(li) # => 6
+
+# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # TypeError hibát dob
+
+# Az összes lista-műveletet ezeken is használható
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Az N-esek (és listák) kicsomagolhatóak külön változókba
+a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3
+d, e, f = 4, 5, 6 # a zárójel elhagyható
+# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik
+g = 4, 5, 6 # => (4, 5, 6)
+# Nézd, milyen egyszerű két értéket megcserélni
+e, d = d, e # d most már 5 és az e 4
+
+# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók
+empty_dict = {}
+# Ez pedig rögtön értékekkel van inicializálva
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Egy dictionary értékei [] jelek közt indexelhetőek
+filled_dict["one"] # => 1
+
+# A "keys()" metódus visszatér a kulcsok listájával
+filled_dict.keys() # => ["three", "two", "one"]
+# Megjegyzés: egy dictionary párjainak sorrendje nem garantált
+# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket.
+
+# Az értékek listája a "values()" metódussal kérhető le
+filled_dict.values() # => [3, 2, 1]
+# ld. a fenti megjegyzést az elemek sorrendjéről.
+
+# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal
+filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
+
+# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# Nem létező kulcs hivatkozása KeyError hibát dob
+filled_dict["four"] # KeyError
+
+# A "get()" metódus használatával elkerülhető a KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# Megjegyzés: ettől még filled_dict.get("four") => None
+# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben)
+
+# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek:
+filled_dict["four"] = 4 # ez után filled_dict["four"] => 4
+
+# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva
+filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re
+filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5
+
+# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat
+empty_set = set()
+# Inicializáljuk ezt a halmazt néhány elemmel
+some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4])
+
+# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet
+another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4])
+
+# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Új halmaz-elemek hozzáadása
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# Halmaz metszés a & operátorral
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Halmaz unió | operátorral
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Halmaz különbség -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Szimmetrikus differencia ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit
+{1, 2} >= {1, 2, 3} # => False
+
+# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak
+{1, 2} <= {1, 2, 3} # => True
+
+# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+# 3. Control Flow
+####################################################
+
+# Legyen egy változónk
+some_var = 5
+
+# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben!
+# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél"
+if some_var > 10:
+ print "some_var nagyobb, mint 10."
+elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben.
+ print "some_var kisebb 10-nél"
+else: # Ez sem kötelező.
+ print "some_var kereken 10."
+
+"""
+For ciklusokkal végigiterálhatunk listákon
+a kimenet:
+ A(z) kutya emlős
+ A(z) macska emlős
+ A(z) egér emlős
+"""
+for animal in ["kutya", "macska", "egér"]:
+ # A {0} kifejezéssel formázzuk a stringet, ld. korábban.
+ print "A(z) {0} emlős".format(animal)
+
+"""
+"range(number)" visszatér számok listájával 0-től number-ig
+a kimenet:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" visszatér a lower és upper közti számok listájával
+a kimenet:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+A while ciklus a feltétel hamissá válásáig fut.
+a kimenet:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # Rövidítés az x = x + 1 kifejezésre
+
+# A kivételek try/except blokkokkal kezelhetőek
+
+# Python 2.6-tól felfele:
+try:
+ # A "raise" szóval lehet hibát dobni
+ raise IndexError("Ez egy index error")
+except IndexError as e:
+ pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat.
+except (TypeError, NameError):
+ pass # Ha szükséges, egyszerre több hiba típus is kezelhető
+else: # Az except blokk után opcionálisan megadható
+ print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák
+finally: # Mindenképpen lefut
+ print "Itt felszabadíthatjuk az erőforrásokat például"
+
+# Az erőforrások felszabadításához try/finally helyett a with használható
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+
+####################################################
+# 4. Függvények
+####################################################
+
+# A "def" szóval hozhatunk létre új függvényt
+def add(x, y):
+ print "x is {0} and y is {1}".format(x, y)
+ return x + y # A return szóval tudunk értékeket visszaadni
+
+
+# Így hívunk függvényt paraméterekkel
+add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11
+
+# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt
+add(y=6, x=5) # Ez esetben a sorrendjük nem számít
+
+
+# Változó számú paramétert fogadó függvény így definiálható.
+# A * használatával a paramétereket egy N-esként kapjuk meg.
+def varargs(*args):
+ return args
+
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# Változó számú nevesített paramétert fogadó függvény is megadható,
+# a ** használatával a paramétereket egy dictionary-ként kapjuk meg
+def keyword_args(**kwargs):
+ return kwargs
+
+
+# Nézzük meg, mi történik
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# A két módszer egyszerre is használható
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+
+
+"""
+all_the_args(1, 2, a=3, b=4) kimenete:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Függvények hívásakor a fenti args és kwargs módszerek inverze használható
+# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4)
+all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4)
+all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4)
+
+
+# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek,
+# a * illetve ** operátorokkal kifejtve
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+
+# Függvény scope
+x = 5
+
+
+def set_x(num):
+ # A lokális x változó nem ugyanaz, mint a globális x
+ x = num # => 43
+ print x # => 43
+
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # a globális x-et 6-ra állítjuk
+ print x # => 6
+
+
+set_x(43)
+set_global_x(6)
+
+
+# A pythonban a függvény elsőrendű (ún. "first class") típus
+def create_adder(x):
+ def adder(y):
+ return x + y
+
+ return adder
+
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Névtelen függvények is definiálhatóak
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# Léteznek beépített magasabb rendű függvények
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+# halmaz és dictionary képzők is léteznek
+{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
+{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+# 5. Osztályok
+####################################################
+
+# Az object osztály egy alosztályát képezzük
+class Human(object):
+ # Osztály szintű mező: az osztály összes példányában azonos
+ species = "H. sapiens"
+
+ # Ez a függvény meghívódik az osztály példányosításakor.
+ # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python
+ # előre definiált, a nyelv által belsőleg használt, de a felhasználó által
+ # is látható objektumok és mezők neveire.
+ # Ne vezessünk be új, ilyen elnevezési sémát használó neveket!
+ def __init__(self, name):
+ # A paramétert értékül adjuk a példány name attribútumának
+ self.name = name
+
+ # Inicializálunk egy mezőt
+ self.age = 0
+
+ # Példány metódus. Minden metódus első paramétere a "self", a példány maga
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # Egy osztálymetódus az osztály összes példány közt meg van osztva.
+ # Hívásukkor az első paraméter mindig a hívó osztály.
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Egy statikus metódus osztály és példányreferencia nélkül hívódik
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # Egy property jelölésű függvény olyan, mint egy getter.
+ # Használatával az age mező egy csak-olvasható attribútummá válik.
+ @property
+ def age(self):
+ return self._age
+
+ # Így lehet settert megadni egy mezőhöz
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # Így lehet egy mező törlését engedélyezni
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# Példányosítsuk az osztályt
+i = Human(name="Ian")
+print i.say("hi") # kimenet: "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # kimenet: "Joel: hello"
+
+# Hívjuk az osztály metódusunkat
+i.get_species() # => "H. sapiens"
+
+# Változtassuk meg az osztály szintű attribútumot
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Hívjuk meg a statikus metódust
+Human.grunt() # => "*grunt*"
+
+# Adjunk új értéket a mezőnek
+i.age = 42
+
+# Kérjük le a mező értékét
+i.age # => 42
+
+# Töröljük a mezőt
+del i.age
+i.age # => AttributeError hibát dob
+
+####################################################
+# 6. Modulok
+####################################################
+
+# Modulokat így lehet importálni
+import math
+
+print math.sqrt(16) # => 4
+
+# Lehetséges csak bizonyos függvényeket importálni egy modulból
+from math import ceil, floor
+
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# Egy modul összes függvénye is importálható
+# Vigyázat: ez nem ajánlott.
+from math import *
+
+# A modulok nevei lerövidíthetőek
+import math as m
+
+math.sqrt(16) == m.sqrt(16) # => True
+# Meggyőződhetünk róla, hogy a függvények valóban azonosak
+from math import sqrt
+
+math.sqrt == m.sqrt == sqrt # => True
+
+# A Python modulok egyszerű fájlok.
+# Írhatsz sajátot és importálhatod is.
+# A modul neve azonos a tartalmazó fájl nevével.
+
+# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul.
+import math
+
+dir(math)
+
+
+# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos
+# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett.
+# A lokális mappa prioritást élvez a beépített könyvtárak felett.
+
+
+####################################################
+# 7. Haladóknak
+####################################################
+
+# Generátorok
+# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket.
+
+# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit,
+# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat!
+def double_numbers(iterable):
+ double_arr = []
+ for i in iterable:
+ double_arr.append(i + i)
+ return double_arr
+
+
+# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk
+# ezt a nagy listát a ciklus vezérléséhez.
+for value in double_numbers(range(1000000)): # `test_non_generator`
+ print value
+ if value > 5:
+ break
+
+
+# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet,
+# amikor azt kérik tőle
+def double_numbers_generator(iterable):
+ for i in iterable:
+ yield i + i
+
+
+# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt.
+# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak
+# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!).
+for value in double_numbers_generator(xrange(1000000)): # `test_generator`
+ print value
+ if value > 5:
+ break
+
+# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén
+# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a
+# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range`
+# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük
+# - esetünkben a ciklus következő iterációjakor
+
+# A lista képzéshez hasonlóan generátor képzőket is használhatunk
+# ("generator comprehensions").
+values = (-x for x in [1, 2, 3, 4, 5])
+for x in values:
+ print(x) # kimenet: -1 -2 -3 -4 -5
+
+# Egy generátor összes generált elemét listaként is elkérhetjük:
+values = (-x for x in [1, 2, 3, 4, 5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+# Dekorátorok
+# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény.
+# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény
+# kimenetébe beszúrja az 'Apple' elemet.
+def add_apples(func):
+ def get_fruits():
+ fruits = func()
+ fruits.append('Apple')
+ return fruits
+ return get_fruits
+
+@add_apples
+def get_fruits():
+ return ['Banana', 'Mango', 'Orange']
+
+# A kimenet tartalmazza az 'Apple' elemet:
+# Banana, Mango, Orange, Apple
+print ', '.join(get_fruits())
+
+# Ebben a példában a beg dekorátorral látjuk el a say függvényt.
+# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor
+# megváltoztatja az eredmény mondatot.
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print say() # Can you buy me a beer?
+print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
+```
+
+## Még több érdekel?
+
+### Ingyenes online tartalmak
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [LearnPython](http://www.learnpython.org/)
+* [Fullstack Python](https://www.fullstackpython.com/)
+
+### Könyvek
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/id-id/bf-id.html.markdown b/id-id/bf-id.html.markdown
new file mode 100644
index 00000000..9901290b
--- /dev/null
+++ b/id-id/bf-id.html.markdown
@@ -0,0 +1,86 @@
+---
+language: "Brainfuck"
+filename: brainfuck-id.bf
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Muhammad Rifqi Fatchurrahman", "http://muhrifqii.github.io/"]
+lang: id-id
+---
+
+Brainfuck (tidak dalam huruf kapital kecuali pada awal kalimat) adalah sebuah
+bahasa pemrograman Turing-complete yang sangat minim yang hanya memiliki 8 perintah.
+
+Anda bisa mencoba brainfuck pada browser dengan menggunakan [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
+```bf
+Karakter apapun selain "><+-.,[]" (tanda kutip tidak termasuk) diabaikan.
+
+Brainfuck direpresentasikan dengan sebuah array yang memiliki 30,000 cell yang
+diinisialisasi dengan nol dan pointer data yang menunjuk ke current cell.
+
+Terdapat delapan perintah:
++ : Menaikkan nilai pada current cell sebesar satu.
+- : Menurunkan nilai pada current cell sebesar satu.
+> : Menggeser pointer data ke cell selanjutnya (cell sebelah kanan).
+< : Menggeser pointer data ke cell sebelumnya (cell sebelah kiri).
+. : Mencetak nilai ASCII pada current cell (misal 65 = 'A').
+, : Membaca sebuah karakter masukan tunggal ke dalam current cell.
+[ : Jika nilai pada current cell bernilai nol, lewati hingga mencapai ] yang sesuai.
+ Jika tidak, pindah ke instruksi berikutnya.
+] : Jika nilai pada current cell bernilai nol, pindah ke instruksi berikutnya.
+ Jika tidak, mundur pada instruksi hingga mencapai [ yang sesuai.
+
+[ dan ] membentuk sebuah rekursi while. Tentu saja mereka harus seimbang.
+
+Mari kita lihat beberapa program brainfuck dasar.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Program ini mencetak huruf 'A'. Mula-mula, cell #1 dinaikkan ke 6.
+Cell #1 akan digunakan untuk rekursi. Lalu, masuk ke rekursi ([) dan pindah
+ke cell #2. Cell #2 dinaikkan 10 kali, mundur ke cell #1, dan menurunkan
+cell #1. Rekursi ini berlangsung 6 kali (melakukan 6 penurunan nilai untuk
+cell #1 hingga mencapai 0, di titik mana dia melewati hingga mencapai ] dan
+terus berlanjut).
+
+Pada titik ini, kita berada pada cell #1, yang memiliki nilai 0, sedangkan cell #2
+memiliki sebuah nilai 60. Kita berpindah ke cell #2, menaikkan nilai 5 kali, memunculkan
+nilai 65, lalu cetak nilai pada cell #2. 65 adalah 'A' pada ASCII, jadi 'A'
+dicetak ke terminal.
+
+, [ > + < - ] > .
+
+Program ini membaca sebuah karakter dari masukan user dan menyalin karakternya ke
+cell #1. Setelah itu rekursi dimulai. Geser ke cell #2, menaikkan nilai pada cell #2,
+mundur ke cell #1, dan menurunkan nilai pada cell #1. Hal ini berlanjut sampai cell #1
+bernilai 0, dan cell #2 menyimpan nilai lama dari cell #1. Karena kita berada di cell #1
+saat ujung rekursi, geser ke cell #2, lalu cetak nilai dalam bentuk ASCII.
+
+Perlu diingat bahwa spasi itu murni untuk memudahkan membaca. Anda bisa
+menuliskannya dengan mudah seperti:
+
+,[>+<-]>.
+
+Coba dan cari tahu apa yang program ini lakukan:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Program ini menerima dua buah angka sebagai input, lalu mengalikannya.
+
+Intinya adalah membaca dua masukan. Lalu mulai pada rekursi terluar yang
+kondisinya pada cell #1. Lalu pindah ke cell #2, dan mulai rekursi terdalam
+yang kondisinya ada pada cell #2, menaikkan nilai pada cell #3. Namun,
+ada suatu masalah: Pada akhir dari rekursi terdalam, cell #2 bernilai nol.
+Pada kasus tersebut, rekursi terdalam tidak dapat bekerja lagi mulai setelah ini.
+Untuk menyelesaikan masalah tersebut, kita juga menaikkan cell #4, dan menyalin
+ulang cell #4 ke cell #2. Maka cell #3 adalah hasilnya.
+```
+
+Dan itulah brainfuck. Tidak terlalu sulit kan? Hanya untuk iseng-iseng, anda
+bisa menuliskan porgram brainfuck anda sendiri, atau anda bisa menuliskan interpreter
+brainfuck pada bahasa lain. Interpreternya tidak begitu sulit untuk diimplementasikan,
+tapi jika anda seorang masokis, cobalah menulis sebuah interpreter brainfuck... dalam
+brainfuck.
+
diff --git a/id-id/hq9+-id.html.markdown b/id-id/hq9+-id.html.markdown
new file mode 100644
index 00000000..46abcf42
--- /dev/null
+++ b/id-id/hq9+-id.html.markdown
@@ -0,0 +1,45 @@
+---
+language: HQ9+
+filename: hq9+-id.html
+contributors:
+ - ["Alexey Nazaroff", "https://github.com/rogaven"]
+translators:
+ - ["Haydar Ali Ismail", "http://github.com/haydarai"]
+lang: id-id
+---
+
+HQ9+ adalah bahasa pemrograman gurauan yang dibuat oleh Cliff Biffle. Bahasa
+ini hanya memiliki empat perintah dan tidak memenuhi Turing-complete.
+
+```
+Hanya ada 4 perintah, masing-masing direpresentasikan oleh karakter berikut
+H: mencetak "Hello, world!"
+Q: mencetak kode sumber dari program ini (Quine)
+9: mencetak lirik dari lagu "99 Bottles of Beer"
++: menambah nilai satu ke akumulator (nilai dari akumulator tidak dapat
+ diakses)
+Karakter lain akan dihiraukan.
+
+Ok. Mari kita menulis beberapa program:
+ HQ9
+
+Hasil:
+ Hello world!
+ HQ9
+
+HQ9+ sangat sederhana, tetapi membuat anda bisa melakukan hal yang sangat sulit
+dilakukan di bahasa lain. Sebagai contoh, berikut sebuah program yang
+menciptakan tiga salinan dirinya sendiri ke layar:
+ QQQ
+
+Ini menghasilakn:
+ QQQ
+ QQQ
+ QQQ
+```
+
+Dan itu semuanya. Ada banyak interpreters untuk HQ9+. Kamu bisa menemukannya di
+bawah
+
++ [Salah satu interpreter online](https://almnet.de/esolang/hq9plus.php)
++ [Website resmi HQ9+](http://cliffle.com/esoterica/hq9plus.html)
diff --git a/id-id/rst-id.html.markdown b/id-id/rst-id.html.markdown
new file mode 100644
index 00000000..06d80089
--- /dev/null
+++ b/id-id/rst-id.html.markdown
@@ -0,0 +1,122 @@
+---
+language: restructured text (RST)
+filename: rst-id.html
+contributors:
+ - ["DamienVGN", "https://github.com/martin-damien"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+translators:
+ - ["Haydar Ali Ismail", "https://github.com/haydarai"]
+lang: id-id
+---
+
+RST adalah sebual format file yang dibuat oleh komunitas Python untuk menulis
+dokumentasi (dan menjadi bagian dari Docutils).
+
+File-file RST adalah sebuah file-file teks simpel dengan sintaks yang ringan
+(dibandingkan dengan HTML).
+
+
+## Pemasangan
+
+Untuk menggunakan RST, anda harus memasang [Python](http://www.python.org) dan
+paket `docutils` terlebih dahulu.
+
+`docutils` bisa dipasang menggunakan command berikut:
+
+```bash
+$ easy_install docutils
+```
+
+Jika sistem anda sudah mempunyai `pip`, anda bisa menggunakannya juga:
+
+```bash
+$ pip install docutils
+```
+
+
+## Sintaks file
+
+Sebuah contoh sederhana dari sintaks file:
+
+```
+.. Baris yang dimulai dengan dua titik adalah perintah spesial. Tetapi jika
+perintah tidak ditemukan, maka baris tersebut akan dianggap sebagai komentar
+
+===============================================================================
+Judul utama ditulis menggunakan rentetan tanda sama dengan di atas dan bawahnya
+===============================================================================
+
+Ingat bahwa jumlah tanda sama dengan harus sama panjangnya dengan total
+karakter judul
+
+Judul juga digarisbawahi dengan tanda sama dengan juga
+======================================================
+
+Sub-judul dengan menggunakan dash
+---------------------------------
+
+Dan sub-sub-judul dengan menggunakan tilde
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Anda bisa menulis teks dalam *italik* atau *tebal*, anda bisa "menandai" teks
+sebagai kode dengan menggunakan backquote ganda ``: ``print()``.
+
+Membuat daftar semudah seperti dalam Markdown:
+
+- Barang pertama
+- Barang kedua
+ - Sub barang
+
+atau
+
+* Barang pertama
+* Barang kedua
+ * Sub barang
+
+Tabel sangat mudah untuk ditulis:
+
+=========== ========
+Negara Ibu Kota
+=========== ========
+Prancis Paris
+Jepang Tokyo
+=========== ========
+
+Tabel yang lebih kompleks bisa dibuat dengan mudah (kolom tergabung atau/dan
+baris) tetapi saya menyarankan anda untuk membaca dokumentasi lengkap tentang
+ini :)
+
+Ada berbagai macam cara untuk membuat tautan:
+
+- Dengan menambahkan garis bawah setelah sebuah huruf : Github_ dan dengan
+menambahkan URL target setelah teks (cara ini mempunyai kelebihan dengan tidak
+memasukkan URL yang tidak penting ke dalam teks yang bisa dibaca).
+- Dengan mengetik URL lengkap yang dapat dipahami : https://github.com (akan
+otomatis diubah menjadi sebuah link)
+- Dengan membuat link seperti di Markdown: `Github <https://github.com/>`_ .
+
+.. _Github https://github.com/
+
+```
+
+
+## Bagaimana Cara Menggunakannya
+
+RST hadir dengan docutils di mana anda mempunyai `rst2html`, sebagai contoh:
+
+```bash
+$ rst2html fileku.rst hasil.html
+```
+
+*Catatan : Di beberapa sistem, perintah tersebut bisa menjadi rst2html.py*
+
+Tetapi ada beberapa aplikasi kompleks yang menggunakan format RST:
+
+- [Pelican](http://blog.getpelican.com/), Generator web statik
+- [Sphinx](http://sphinx-doc.org/), Generator dokumnetasi
+- dan masih banyak lainnya
+
+
+## Bacaan
+
+- [Referensi singkat resmi](http://docutils.sourceforge.net/docs/user/rst/quickref.html)
diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown
index e005f2dc..e49ccd79 100644
--- a/it-it/go-it.html.markdown
+++ b/it-it/go-it.html.markdown
@@ -26,14 +26,14 @@ Aggiunge la concorrenza in maniera diretta e semplice da capire, per far
forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili
per la programmazione in larga scala.
-Go comes with a great standard library and an enthusiastic community.
+Go include un'ottima libreria standard e ha una community entusiasta.
```go
// Commento su riga singola
/* Commento
su riga multipla */
-// In cima a ogni file è necessario specificare il package.
+// In cima ad ogni file è necessario specificare il package.
// Main è un package speciale che identifica un eseguibile anziché una libreria.
package main
@@ -65,19 +65,19 @@ func oltreIlCiaoMondo() {
x = 3 // Assegnazione di una variabile.
// E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente.
y := 4
- // Una funzione che ritorna due valori.
- somma, prod := imparaMoltepliciValoriDiRitorno(x, y)
+ // Una funzione che restituisce due valori.
+ somma, prod := imparaMoltepliciValoriRestituiti(x, y)
fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output.
imparaTipi() // < y minuti, devi imparare ancora!
}
/* <- commento su righe multiple
-Le funzioni possono avere parametri e ritornare (molteplici!) valori.
-Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati.
+Le funzioni possono avere parametri e restituire (molteplici!) valori.
+In questo esempio, x e y sono gli argomenti, mentre somma e prod sono i valori restituiti.
Da notare il fatto che x e somma vengono dichiarati come interi.
*/
-func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) {
- return x + y, x * y // Ritorna due valori.
+func imparaMoltepliciValoriRestituiti(x, y int) (somma, prod int) {
+ return x + y, x * y // Restituisce due valori.
}
// Ecco alcuni tipi presenti in Go
@@ -86,7 +86,7 @@ func imparaTipi() {
str := "Impara il Go!" // Tipo stringa.
s2 := `Una stringa letterale
-puo' includere andata a capo.` // Sempre di tipo stringa.
+può includere andata a capo.` // Sempre di tipo stringa.
// Stringa letterale non ASCII. I sorgenti Go sono in UTF-8.
g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode.
@@ -144,20 +144,20 @@ puo' includere andata a capo.` // Sempre di tipo stringa.
imparaControlloDiFlusso() // Torniamo in carreggiata.
}
-// In Go è possibile associare dei nomi ai valori di ritorno di una funzione.
-// Assegnare un nome al tipo di dato ritornato permette di fare return in vari
+// In Go è possibile associare dei nomi ai valori restituiti da una funzione.
+// Assegnare un nome al tipo di dato restituito permette di fare return in vari
// punti all'interno del corpo della funzione, ma anche di usare return senza
-// specificare in modo esplicito che cosa ritornare.
-func imparaValoriDiRitornoConNome(x, y int) (z int) {
+// specificare in modo esplicito che cosa restituire.
+func imparaValoriRestituitiConNome(x, y int) (z int) {
z = x * y
return // z è implicito, perchè compare nella definizione di funzione.
}
// Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei
-// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente
-// incrementare un puntatore.
+// puntatori. Puoi commettere errori a causa di puntatori nulli, ma non puoi
+// incrementare un puntatore direttamente.
func imparaLaMemoria() (p, q *int) {
- // I valori di ritorno (con nome) p e q sono puntatori a int.
+ // I valori restituiti (con nome) p e q sono puntatori a int.
p = new(int) // La funzione new si occupa di allocare memoria.
// L'int allocato viene inizializzato a 0, dunque p non è più nil.
s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria.
@@ -207,14 +207,14 @@ func imparaControlloDiFlusso() {
}
// x == 42 qua.
- // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme.
+ // Il for è l'unica istruzione per i loop in Go, ma ha varie forme.
for { // Ciclo infinito.
break // Scherzavo.
continue // Non si arriva qua.
}
- // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale.
- // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa).
+ // Puoi usare range per iterare lungo un vettore, slice, stringa, mappa o canale.
+ // range restituisce uno (per i canali) o due valori (vettore, slice, stringa, mappa).
for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} {
// per ogni coppia dentro la mappa, stampa chiave e valore
fmt.Printf("chiave=%s, valore=%d\n", chiave, valore)
@@ -236,7 +236,7 @@ func imparaControlloDiFlusso() {
// Inoltre le funzioni letterali possono essere definite e chiamate
// inline, col ruolo di parametri di funzione, a patto che:
// a) la funzione letterale venga chiamata subito (),
- // b) il valore ritornato è in accordo con il tipo dell'argomento.
+ // b) il valore restituito è in accordo con il tipo dell'argomento.
fmt.Println("Somma e raddoppia due numeri: ",
func(a, b int) int {
return (a + b) * 2
@@ -247,7 +247,7 @@ func imparaControlloDiFlusso() {
goto amore
amore:
- imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente!
+ imparaFabbricaDiFunzioni() // Una funzione che restituisce un'altra funzione è divertente!
imparaDefer() // Un tour veloce di una parola chiave importante.
imparaInterfacce() // Arriva la roba buona!
}
@@ -271,7 +271,7 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string {
func imparaDefer() (ok bool) {
// Le istruzioni dette "deferred" (rinviate) sono eseguite
- // appena prima che la funzione ritorni.
+ // appena prima che la funzione abbia termine.
defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).")
defer fmt.Println("\nQuesta riga viene stampata per prima perché")
// defer viene usato di solito per chiudere un file, così la funzione che
diff --git a/it-it/html-it.html.markdown b/it-it/html-it.html.markdown
new file mode 100644
index 00000000..471019a1
--- /dev/null
+++ b/it-it/html-it.html.markdown
@@ -0,0 +1,121 @@
+---
+language: html
+filename: learnhtml-it.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+translators:
+ - ["Ale46", "http://github.com/Ale46/"]
+lang: it-it
+---
+
+HTML sta per HyperText Markup Language (linguaggio a marcatori per ipertesti).
+È un linguaggio che consente di scrivere pagine web per il world wide web.
+È un linguaggio di markup, che permette di scrivere pagine web usando del codice che indica come il testo ed i dati devono essere mostrati.
+Infatti, i files html sono semplici file di testo.
+Cos'è il markup? È un metodo per organizzare i dati della pagina circondandoli con tag di apertura e tag di chiusura.
+Questo markup serve a dare significato al testo che racchiude.
+Come altri linguaggi di programmazione, HTML ha molte versioni. Qui discuteremo di HTML5.
+
+**NOTA :** Puoi testare i differenti tags ed elementi man mano che prosegui nel tutorial in un sito come [codepen](http://codepen.io/pen/) per vedere i loro effetti, capire come lavorano e familiarizzare con il linguaggio.
+Questo articolo riguarda principalmente la sintassi HTML ed alcuni suggerimenti utili.
+
+
+```html
+<!-- I commenti sono racchiusi come in questa riga! -->
+
+<!-- #################### I Tags #################### -->
+
+<!-- Ecco un esempio di file HTML che andremo ad analizzare. -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Il mio sito</title>
+ </head>
+ <body>
+ <h1>Ciao, mondo!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Vieni a vedere ciò che mostra</a>
+ <p>Questo è un paragrafo.</p>
+ <p>Questo è un altro paragrafo.</p>
+ <ul>
+ <li>Questo è un elemento di un elenco non numerato (elenco puntato)</li>
+ <li>Questo è un altro elemento</li>
+ <li>E questo è l'ultimo elemento dell'elenco</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Un file HTML inizia sempre indicando al browser che la pagina è HTML. -->
+<!doctype html>
+
+<!-- Dopo questo, inizia aprendo un tag <html>. -->
+<html>
+
+<!-- che sarà chiuso alla fine del file con </html>. -->
+</html>
+
+<!-- Nulla dovrebbe apparire dopo questo tag finale. -->
+
+<!-- All'interno (tra i tag di apertura e chiusura <html> </html>) troviamo: -->
+
+<!-- Un'intestazione definita da <head> (deve essere chiusa con </head>). -->
+<!-- L'intestazione contiene alcune descrizioni e informazioni aggiuntive non visualizzate; questi sono i metadati. -->
+
+<head>
+ <title>Il mio sito</title> <!-- Il tag <title> indica al browser il titolo da mostrare nella barra del titolo della finestra del browser e nel nome della scheda. -->
+</head>
+
+<!-- Dopo la sezione <head>, troviamo il tag - <body> -->
+<!-- Fino a questo punto, niente di ciò che abbiamo descritto verrà visualizzato nella finestra del browser. -->
+<!-- Dobbiamo riempire il corpo con il contenuto da visualizzare. -->
+
+<body>
+ <h1>Ciao, mondo!</h1> <!-- Il tag h1 crea un titolo. -->
+ <!-- Ci sono anche sottotitoli a <h1> dal più importante (h2) al più preciso (h6). -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Vieni a vedere ciò che mostra</a> <!-- un collegamento ipertestuale all'URL fornito dall'attributo href="" -->
+ <p>Questo è un paragrafo.</p> <!-- Il tag <p> ci permette di includere del testo nella pagina html. -->
+ <p>Questo è un altro paragrafo.</p>
+ <ul> <!-- Il tag <ul> crea un elenco puntato. -->
+ <!-- Per avere un elenco numerato, invece, usiamo <ol> che restituisce 1. per il primo elemento, 2. per il secondo, etc. -->
+ <li>Questo è un elemento in un elenco non elencato (elenco puntato)</li>
+ <li>Questo è un altro elemento</li>
+ <li>E questo è l'ultimo elemento dell'elenco</li>
+ </ul>
+</body>
+
+<!-- E questo è tutto, creare un file HTML può essere molto semplice. -->
+
+<!-- Ma è possibile aggiungere molti altri tipi di tag HTML. -->
+
+<!-- Per inserire un'immagine. -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- La fonte dell'immagine viene indicata usando l'attributo src="" -->
+<!-- La fonte può essere un URL o persino un percorso di un file sul tuo computer. -->
+
+<!-- È anche possibile creare una tabella. -->
+
+<table> <!-- Apriamo un elemento <table>. -->
+ <tr> <!-- <tr> ci permette di creare una riga. -->
+ <th>Prima intestazione</th> <!-- <th> ci permette di dare un titolo ad una colonna della tabella. -->
+ <th>Seconda intestazione</th>
+ </tr>
+ <tr>
+ <td>prima riga, prima colonna</td> <!-- <td> ci permette di creare una cella della tabella. -->
+ <td>prima riga, seconda colonna</td>
+ </tr>
+ <tr>
+ <td>seconda riga, prima colonna</td>
+ <td>seconda riga, seconda colonna</td>
+ </tr>
+</table>
+
+```
+
+## Uso
+
+HTML è scritto in files che finiscono con `.html`.
+
+## Per saperne di più
+
+* [wikipedia](https://it.wikipedia.org/wiki/HTML)
+* [HTML tutorial](https://developer.mozilla.org/it/docs/Web/HTML)
+* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown
index b006dbb4..44801747 100644
--- a/it-it/markdown.html.markdown
+++ b/it-it/markdown.html.markdown
@@ -2,41 +2,65 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
translators:
- ["Jacopo Andrea Giola", "http://geekpanda.net"]
+ - ["Ale46", "https://github.com/Ale46"]
filename: markdown-it.md
lang: it-it
---
Markdown è stato creato da John Gruber nel 2004. Il suo scopo è quello di essere una sintassi facile da leggere e scrivere, e che può essere convertita in HTML (ad oggi anche in molti altri formati).
-Mandate tutto il feedback che volete! / Sentitevi liberi di forkare o di mandare pull request!
+Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida cercherà di chiarire quali caratteristiche esistono a livello globale o quando sono disponibili solo per un determinato parser.
+- [Elementi HTML](#elementi-html)
+- [Titoli](#titoli)
+- [Stili di testo semplici](#stili-di-testo-semplici)
+- [Paragrafi](#paragrafi)
+- [Liste](#liste)
+- [Estratti di codice](#estratti-di-codice)
+- [Linea orizzontale](#linea-orizzontale)
+- [Links](#links)
+- [Immagini](#immagini)
+- [Miscellanea](#miscellanea)
+
+## Elementi HTML
+Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido.
```markdown
-<!-- Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido. Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti, e questi non saranno modificati dal parser di Markdown. State attenti però, se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi all'interno del contenuto dell'elemento. -->
+<!-- Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti,
+e questi non saranno modificati dal parser di Markdown. State attenti però,
+se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi
+all'interno del contenuto dell'elemento. -->
+```
+
+## Titoli
-<!-- L'implementazione di Markdown inoltre cambia da parser a parser. In questa guida cercheremo di indicare quando una feature è universale e quando sono specifiche ad un certo parser. -->
+Potete creare gli elementi HTML da `<h1>` a `<h6>` facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento
-<!-- Titoli -->
-<!-- Potete creare gli elementi HTML da <h1> ad <h6> facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento -->
+```markdown
# Questo è un <h1>
## Questo è un <h2>
### Questo è un <h3>
#### Questo è un <h4>
##### Questo è un <h5>
###### Questo è un <h6>
+```
+Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2
-<!-- Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2 -->
+```markdown
Questo è un h1
==============
Questo è un h2
--------------
+```
-<!-- Stili di testo semplici -->
-<!-- Il testo può essere stilizzato in corsivo o grassetto usando markdown -->
+## Stili di testo semplici
+Il testo può essere stilizzato in corsivo o grassetto usando markdown
+```markdown
*Questo testo è in corsivo.*
_Come pure questo._
@@ -46,30 +70,38 @@ __Come pure questo.__
***Questo testo è stilizzato in entrabmi i modi.***
**_Come questo!_**
*__E questo!__*
+```
-<!-- In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su
-Github, è presente anche lo stile barrato -->
+In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato:
+```markdown
~~Questo testo è barrato.~~
+```
+## Paragrafi
-<!-- I paragrafi sono uno o più linee di testo addiacenti separate da una o più righe vuote. -->
+```markdown
+I paragrafi sono una o più linee di testo adiacenti separate da una o più righe vuote.
-Qeusto è un paragrafo. Sto scrivendo in un paragrafo, non è divertente?
+Questo è un paragrafo. Sto scrivendo in un paragrafo, non è divertente?
Ora sono nel paragrafo 2.
Anche questa linea è nel paragrafo 2!
Qui siamo nel paragrafo 3!
+```
-<!-- Se volete inserire l'elemento HTML <br />, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo. -->
+Se volete inserire l'elemento HTML `<br />`, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo.
+```markdown
Questa frase finisce con due spazi (evidenziatemi per vederli).
C'è un <br /> sopra di me!
+```
-<!-- Le citazioni sono semplici da inserire, basta usare il carattere >. -->
+Le citazioni sono semplici da inserire, basta usare il carattere >.
+```markdown
> Questa è una citazione. Potete
> mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente.
> Non c'è alcuna differenza, basta che iniziate ogni riga con `>`.
@@ -78,9 +110,12 @@ C'è un <br /> sopra di me!
>> di indentazione!
> Quanto è comodo?
-<!-- Liste -->
-<!-- Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini -->
+```
+
+## Liste
+Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini
+```markdown
* Oggetto
* Oggetto
* Altro oggetto
@@ -96,149 +131,180 @@ oppure
- Oggetto
- Oggetto
- Un ultimo oggetto
+```
-<!-- Le liste ordinate invece, sono inserite con un numero seguito da un punto. -->
+Le liste ordinate invece, sono inserite con un numero seguito da un punto.
+```markdown
1. Primo oggetto
2. Secondo oggetto
3. Terzo oggetto
+```
-<!-- Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea. -->
+Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea.
+```markdown
1. Primo oggetto
1. Secondo oggetto
1. Terzo oggetto
-<!-- (Questa lista verrà visualizzata esattamente come quella dell'esempio prima) -->
+```
+(Questa lista verrà visualizzata esattamente come quella dell'esempio prima)
-<!-- Potete inserire anche sotto liste -->
+Potete inserire anche sotto liste
+```markdown
1. Primo oggetto
2. Secondo oggetto
3. Terzo oggetto
* Sotto-oggetto
* Sotto-oggetto
4. Quarto oggetto
+```
-<!-- Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML. -->
+Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML.
+```markdown
I box senza la 'x' sono checkbox HTML ancora da completare.
- [ ] Primo task da completare.
- [ ] Secondo task che deve essere completato.
Il box subito sotto è una checkbox HTML spuntata.
- [x] Questo task è stato completato.
+```
+## Estratti di codice
-<!-- Estratti di codice -->
-<!-- Potete inserire un estratto di codice (che utilizza l'elemento <code>) indentando una linea con quattro spazi oppure con un carattere tab -->
+Potete inserire un estratto di codice (che utilizza l'elemento `<code>`) indentando una linea con quattro spazi oppure con un carattere tab.
+```markdown
Questa è una linea di codice
Come questa
+```
-<!-- Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice -->
+Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Codice inline può essere inserito usando il carattere backtick ` -->
+Codice inline può essere inserito usando il carattere backtick `
+```markdown
Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`!
+```
-<!-- In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice -->
-
-\`\`\`ruby <!-- In realtà dovete rimuovere i backslash, usate solo ```ruby ! -->
+In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
def foobar
puts "Hello world!"
end
-\`\`\` <!-- Anche qui, niente backslash, solamente ``` -->
+&#x60;&#x60;&#x60;</code></pre>
+Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali
-<!-- Se usate questa sintassi, il testo non richiederà di essere indentanto, inoltre Github userà la syntax highlighting del linguaggio specificato dopo i ``` iniziali -->
-
-<!-- Linea orizzontale (<hr />) -->
-<!-- Le linee orizzontali sono inserite facilemtne usanto tre o più asterischi o trattini senza spazi consecutivi e senza spazi. -->
+## Linea orizzontale
+Le linee orizzontali (`<hr/>`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi.
+```markdown
***
---
- - -
****************
+```
-<!-- Link -->
-<!-- Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde () -->
+## Links
+Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde ()
+```markdown
[Cliccami!](http://test.com/)
+```
-<!-- Potete inoltre aggiungere al link un titolo mettendolo fra doppie apici dopo il link -->
+Potete inoltre aggiungere al link un titolo mettendolo fra doppi apici dopo il link
+```markdown
[Cliccami!](http://test.com/ "Link a Test.com")
+```
-<!-- La sintassi funziona anche i path relativi. -->
+La sintassi funziona anche con i path relativi.
+```markdown
[Vai a musica](/music/).
+```
-<!-- Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo -->
-
+Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo.
+```markdown
[Apri questo link][link1] per più informazioni!
[Guarda anche questo link][foobar] se ti va.
[link1]: http://test.com/ "Bello!"
[foobar]: http://foobar.biz/ "Va bene!"
+```
+l titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco.
-<!-- Il titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco. -->
-
-<!-- Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id -->
-
+Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id.
+```markdown
[Questo][] è un link.
[Questo]: http://thisisalink.com/
+```
+Ma non è comunemente usato.
-<!-- Ma non è comunemente usato. -->
-
-<!-- Immagini -->
-<!-- Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! -->
+## Immagini
+Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre!
+```markdown
![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale")
+```
-<!-- E la modalità a riferimento funziona esattamente come ci si aspetta -->
+E la modalità a riferimento funziona esattamente come ci si aspetta
+```markdown
![Questo è il testo alternativo.][myimage]
[myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui"
+```
+## Miscellanea
+### Auto link
-<!-- Miscellanea -->
-<!-- Auto link -->
-
+```markdown
<http://testwebsite.com/> è equivalente ad
[http://testwebsite.com/](http://testwebsite.com/)
+```
+### Auto link per le email
-<!-- Auto link per le email -->
-
+```markdown
<foo@bar.com>
+```
+### Caratteri di escaping
-<!-- Caratteri di escaping -->
-
+```markdown
Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*.
+```
-<!-- Combinazioni di tasti -->
-<!-- In Github Flavored Markdown, potete utilizzare il tag <kbd> per raffigurare i tasti della tastiera -->
+### Combinazioni di tasti
+In Github Flavored Markdown, potete utilizzare il tag `<kbd>` per raffigurare i tasti della tastiera.
+```markdown
Il tuo computer è crashato? Prova a premere
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Canc</kbd>
+```
-<!-- Tabelle -->
-<!-- Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: -->
+### Tabelle
+Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue:
+```markdown
| Col1 | Col2 | Col3 |
| :------------------- | :------: | -----------------: |
| Allineato a sinistra | Centrato | Allineato a destra |
| blah | blah | blah |
+```
+oppure, per lo stesso risultato
-<!-- oppure, per lo stesso risultato -->
-
+```markdown
Col 1 | Col2 | Col3
:-- | :-: | --:
È una cosa orrenda | fatela | finire in fretta
-
-<!-- Finito! -->
-
```
+---
Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown
index aeb42658..8d6d4385 100644
--- a/it-it/matlab-it.html.markdown
+++ b/it-it/matlab-it.html.markdown
@@ -217,7 +217,7 @@ A .* B % Moltiplica ogni elemento di A per il corrispondente elemento di B
% l'altra (il cui nome termina con m) agisce sull'intera matrice.
exp(A) % Calcola l'esponenziale di ogni elemento
expm(A) % Calcola la matrice esponenziale
-sqrt(A) % Calcola la radice quadrata di ogni elementotake the square root of each element
+sqrt(A) % Calcola la radice quadrata di ogni elemento
sqrtm(A) % Trova la matrice di cui A nè è la matrice quadrata
diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown
new file mode 100644
index 00000000..a834e899
--- /dev/null
+++ b/it-it/rst-it.html.markdown
@@ -0,0 +1,111 @@
+---
+language: restructured text (RST)
+filename: restructuredtext-it.rst
+contributors:
+ - ["DamienVGN", "https://github.com/martin-damien"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+translators:
+ - ["Ale46", "https://github.com/Ale46"]
+ - ["Chris54721", "https://chris54721.net"]
+lang: it-it
+---
+
+RST (Restructured Text) è un formato di file inizialmente creato dalla comunità Python
+per la documentazione (per questo motivo appartiene a Docutils).
+
+I file RST sono semplici file di testo con una sintassi leggera (in confronto all'HTML).
+
+## Installazione
+
+Per usare Restructured Text, sarà necessario installare [Python](http://www.python.org) ed il pacchetto `docutils`.
+
+`docutils` può essere installato da riga di comando:
+
+```bash
+$ easy_install docutils
+```
+
+Oppure, se hai `pip` installato sul tuo sistema:
+
+```bash
+$ pip install docutils
+```
+
+
+## Sintassi del file
+
+Ecco un semplice esempio della sintassi RST:
+
+```
+.. Le righe che iniziano con due punti sono comandi speciali. Ma se non è possibile trovare alcun comando, la riga viene considerata come un commento
+
+===============================================================================
+I titoli principali sono scritti utilizzando caratteri di uguale, sopra e sotto
+===============================================================================
+
+Si noti che devono esserci tanti caratteri di uguale quanti caratteri del titolo.
+
+Anche i titoli normali usano caratteri di uguale, ma solo sotto
+===============================================================
+
+I sottotitoli usano i trattini
+------------------------------
+
+E i sotto-sottotitoli le tildi
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Puoi inserire il testo in *corsivo* o in **grassetto**, puoi "contrassegnare" il testo come codice con un doppio apice ``: `` print () ``.
+
+Le liste sono semplici come in Markdown:
+
+- primo articolo
+- Secondo elemento
+     - Sottoelemento
+
+oppure
+
+* Primo elemento
+* Secondo elemento
+     * Sottoelemento
+
+Le tabelle sono molto semplici da inserire:
+
+=========== ========
+Stato Capitale
+=========== ========
+Francia Parigi
+Giappone Tokio
+=========== ========
+
+Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o righe unite) ma ti suggerisco di leggere la documentazione completa per questo :)
+
+Esistono diversi modi per creare collegamenti:
+
+- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile).
+- Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento)
+- Utilizzando una sintassi simile a Markdown: `Github <https://github.com/>`_ .
+
+.. _Github https://github.com/
+
+```
+
+## Come usarlo
+
+RST viene fornito con docutils, che dispone di `rst2html`, per esempio:
+
+```bash
+$ rst2html miofile.rst output.html
+```
+
+*Nota : In alcuni sistemi il comando potrebbe essere rst2html.py*
+
+Ma ci sono applicazioni più complesse che utilizzano il formato RST:
+
+- [Pelican](http://blog.getpelican.com/), un generatore di siti statici
+- [Sphinx](http://sphinx-doc.org/), un generatore di documentazione
+- e molti altri
+
+
+## Letture
+
+- [Riferimento ufficiale rapido](http://docutils.sourceforge.net/docs/user/rst/quickref.html)
diff --git a/java.html.markdown b/java.html.markdown
index fa1ff3d1..ab2be4a2 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -44,8 +44,6 @@ import java.util.ArrayList;
// Import all classes inside of java.security package
import java.security.*;
-// Each .java file contains one outer-level public class, with the same name
-// as the file.
public class LearnJava {
// In order to run a java program, it must have a main method as an entry
@@ -173,7 +171,7 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // final variables can't be reassigned to another object,
+ // final variables can't be reassigned,
final int HOURS_I_WORK_PER_WEEK = 9001;
// but they can be initialized later.
final double E;
@@ -280,7 +278,7 @@ public class LearnJava {
// LinkedLists - Implementation of doubly-linked list. All of the
// operations perform as could be expected for a
// doubly-linked list.
- // Maps - A set of objects that map keys to values. Map is
+ // Maps - A mapping of key Objects to value Objects. Map is
// an interface and therefore cannot be instantiated.
// The type of keys and values contained in a Map must
// be specified upon instantiation of the implementing
@@ -289,10 +287,16 @@ public class LearnJava {
// HashMaps - This class uses a hashtable to implement the Map
// interface. This allows the execution time of basic
// operations, such as get and insert element, to remain
- // constant even for large sets.
- // TreeMap - This class is a sorted tree structure. It implements a red
- // black tree and sorts the entries based on the key value or
- // the comparator provided while creating the object
+ // constant-amortized even for large sets.
+ // TreeMap - A Map that is sorted by its keys. Each modification
+ // maintains the sorting defined by either a Comparator
+ // supplied at instantiation, or comparisons of each Object
+ // if they implement the Comparable interface.
+ // Failure of keys to implement Comparable combined with failure to
+ // supply a Comparator will throw ClassCastExceptions.
+ // Insertion and removal operations take O(log(n)) time
+ // so avoid using this data structure unless you are taking
+ // advantage of the sorting.
///////////////////////////////////////
// Operators
@@ -306,7 +310,7 @@ public class LearnJava {
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
- System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
+ System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -418,6 +422,8 @@ public class LearnJava {
// String class, and a few special classes that wrap primitive types:
// Character, Byte, Short, and Integer.
// Starting in Java 7 and above, we can also use the String type.
+ // Note: Do remember that, not adding "break" at end any particular case ends up in
+ // executing the very next case(given it satisfies the condition provided) as well.
int month = 3;
String monthString;
switch (month) {
@@ -660,7 +666,7 @@ public interface Edible {
public interface Digestible {
public void digest();
// Since Java 8, interfaces can have default method.
- public void defaultMethod() {
+ public default void defaultMethod() {
System.out.println("Hi from default method ...");
}
}
@@ -701,15 +707,21 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// // Method declarations
// }
-// Marking a class as abstract means that it contains at least one abstract
-// method that must be defined in a child class. Similar to interfaces, abstract
-// classes cannot be instantiated, but instead must be extended and the abstract
-// methods defined. Different from interfaces, abstract classes can contain a
-// mixture of concrete and abstract methods. Methods in an interface cannot
-// have a body, unless the method is static, and variables are final by default,
-// unlike an abstract class. Also abstract classes CAN have the "main" method.
+// Abstract Classes cannot be instantiated.
+// Abstract classes may define abstract methods.
+// Abstract methods have no body and are marked abstract
+// Non-abstract child classes must @Override all abstract methods
+// from their super-classes.
+// Abstract classes can be useful when combining repetitive logic
+// with customised behavior, but as Abstract classes require
+// inheritance, they violate "Composition over inheritance"
+// so consider other approaches using composition.
+// https://en.wikipedia.org/wiki/Composition_over_inheritance
+
public abstract class Animal
{
+ private int age;
+
public abstract void makeSound();
// Method can have a body
@@ -720,17 +732,12 @@ public abstract class Animal
age = 30;
}
- // No need to initialize, however in an interface
- // a variable is implicitly final and hence has
- // to be initialized.
- private int age;
-
public void printAge()
{
System.out.println(age);
}
- // Abstract classes can have main function.
+ // Abstract classes can have main method.
public static void main(String[] args)
{
System.out.println("I am abstract");
@@ -886,6 +893,8 @@ The links provided here below are just to get an understanding of the topic, fee
* [Codingbat.com](http://codingbat.com/java)
+* [Codewars - Java Katas](https://www.codewars.com/?language=java)
+
**Books**:
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 85c8a52d..e7066291 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -103,7 +103,7 @@ false;
// ... which works with more than just strings
"1, 2, " + 3; // = "1, 2, 3"
-"Hello " + ["world", "!"] // = "Hello world,!"
+"Hello " + ["world", "!"]; // = "Hello world,!"
// and are compared with < and >
"a" < "b"; // = true
@@ -180,6 +180,24 @@ myArray.length; // = 4
// Add/Modify at specific index
myArray[3] = "Hello";
+// Add and remove element from front or back end of an array
+myArray.unshift(3); // Add as the first element
+someVar = myArray.shift(); // Remove first element and return it
+myArray.push(3); // Add as the last element
+someVar = myArray.pop(); // Remove last element and return it
+
+// Join all elements of an array with semicolon
+var myArray0 = [32,false,"js",12,56,90];
+myArray0.join(";") // = "32;false;js;12;56;90"
+
+// Get subarray of elements from index 1 (include) to 4 (exclude)
+myArray0.slice(1,4); // = [false,"js",12]
+
+// Remove 4 elements starting from index 2, and insert there strings
+// "hi","wr" and "ld"; return removed subarray
+myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90]
+// myArray0 === [32,false,"hi","wr","ld"]
+
// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
// languages: an unordered collection of key-value pairs.
var myObj = {key1: "Hello", key2: "World"};
@@ -222,7 +240,7 @@ while (true){
var input;
do {
input = getInput();
-} while (!isValid(input))
+} while (!isValid(input));
// The `for` loop is the same as C and Java:
// initialization; continue condition; iteration.
@@ -293,7 +311,7 @@ myFunction("foo"); // = "FOO"
// automatic semicolon insertion. Watch out for this when using Allman style.
function myFunction(){
return // <- semicolon automatically inserted here
- {thisIsAn: 'object literal'}
+ {thisIsAn: 'object literal'};
}
myFunction(); // = undefined
@@ -388,7 +406,7 @@ myFunc(); // = undefined
// through `this`, even if it wasn't attached when it was defined.
var myOtherFunc = function(){
return this.myString.toUpperCase();
-}
+};
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"
@@ -397,7 +415,7 @@ myObj.myOtherFunc(); // = "HELLO WORLD!"
var anotherFunc = function(s){
return this.myString + s;
-}
+};
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
// The `apply` function is nearly identical, but takes an array for an argument
@@ -420,7 +438,7 @@ boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
// `bind` can also be used to partially apply (curry) a function.
-var product = function(a, b){ return a * b; }
+var product = function(a, b){ return a * b; };
var doubler = product.bind(this, 2);
doubler(8); // = 16
@@ -430,11 +448,11 @@ doubler(8); // = 16
var MyConstructor = function(){
this.myNumber = 5;
-}
+};
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
-// Unlike most other popular object-oriented languages, JavaScript has no
+// Unlike most other popular object-oriented languages, JavaScript has no
// concept of 'instances' created from 'class' blueprints; instead, JavaScript
// combines instantiation and inheritance into a single concept: a 'prototype'.
@@ -451,7 +469,7 @@ var myObj = {
var myPrototype = {
meaningOfLife: 42,
myFunc: function(){
- return this.myString.toLowerCase()
+ return this.myString.toLowerCase();
}
};
@@ -515,7 +533,7 @@ MyConstructor.prototype = {
};
var myNewObj2 = new MyConstructor();
myNewObj2.getMyNumber(); // = 5
-myNewObj2.myNumber = 6
+myNewObj2.myNumber = 6;
myNewObj2.getMyNumber(); // = 6
// Built-in types like strings and numbers also have constructors that create
@@ -540,7 +558,7 @@ if (new Number(0)){
// you can actually add functionality to a string, for instance.
String.prototype.firstCharacter = function(){
return this.charAt(0);
-}
+};
"abc".firstCharacter(); // = "a"
// This fact is often used in "polyfilling", which is implementing newer
@@ -556,7 +574,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists
Constructor.prototype = proto;
// then use it to create a new, appropriately-prototyped object
return new Constructor();
- }
+ };
}
```
@@ -589,6 +607,10 @@ some of the more complicated examples.
[Javascript: The Right Way][10] is a guide intended to introduce new developers
to JavaScript and help experienced developers learn more about its best practices.
+[Javascript:Info][11] is a modern javascript tutorial covering the basics (core language and working with a browser)
+as well as advanced topics with concise explanations.
+
+
In addition to direct contributors to this article, some content is adapted from
Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
Mozilla Developer Network.
@@ -604,3 +626,4 @@ Mozilla Developer Network.
[8]: http://eloquentjavascript.net/
[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
[10]: http://jstherightway.org/
+[11]: https://javascript.info/
diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown
new file mode 100644
index 00000000..6103c015
--- /dev/null
+++ b/lambda-calculus.html.markdown
@@ -0,0 +1,121 @@
+---
+category: Algorithms & Data Structures
+name: Lambda Calculus
+contributors:
+ - ["Max Sun", "http://github.com/maxsun"]
+---
+
+# Lambda Calculus
+
+Lambda calculus (λ-calculus), originally created by
+[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church),
+is the world's smallest programming language.
+Despite not having numbers, strings, booleans, or any non-function datatype,
+lambda calculus can be used to represent any Turing Machine!
+
+Lambda calculus is composed of 3 elements: **variables**, **functions**, and
+**applications**.
+
+
+| Name | Syntax | Example | Explanation |
+|-------------|------------------------------------|-----------|-----------------------------------------------|
+| Variable | `<name>` | `x` | a variable named "x" |
+| Function | `λ<parameters>.<body>` | `λx.x` | a function with parameter "x" and body "x" |
+| Application | `<function><variable or function>` | `(λx.x)a` | calling the function "λx.x" with argument "a" |
+
+The most basic function is the identity function: `λx.x` which is equivalent to
+`f(x) = x`. The first "x" is the function's argument, and the second is the
+body of the function.
+
+## Free vs. Bound Variables:
+
+- In the function `λx.x`, "x" is called a bound variable because it is both in
+the body of the function and a parameter.
+- In `λx.y`, "y" is called a free variable because it is never declared before hand.
+
+## Evaluation:
+
+Evaluation is done via
+[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction),
+which is essentially lexically-scoped substitution.
+
+When evaluating the
+expression `(λx.x)a`, we replace all occurences of "x" in the function's body
+with "a".
+
+- `(λx.x)a` evaluates to: `a`
+- `(λx.y)a` evaluates to: `y`
+
+You can even create higher-order functions:
+
+- `(λx.(λy.x))a` evaluates to: `λy.a`
+
+Although lambda calculus traditionally supports only single parameter
+functions, we can create multi-parameter functions using a technique called
+[currying](https://en.wikipedia.org/wiki/Currying).
+
+- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = x(y(z))`
+
+Sometimes `λxy.<body>` is used interchangeably with: `λx.λy.<body>`
+
+----
+
+It's important to recognize that traditional **lambda calculus doesn't have
+numbers, characters, or any non-function datatype!**
+
+## Boolean Logic:
+
+There is no "True" or "False" in lambda calculus. There isn't even a 1 or 0.
+
+Instead:
+
+`T` is represented by: `λx.λy.x`
+
+`F` is represented by: `λx.λy.y`
+
+First, we can define an "if" function `λbtf` that
+returns `t` if `b` is True and `f` if `b` is False
+
+`IF` is equivalent to: `λb.λt.λf.b t f`
+
+Using `IF`, we can define the basic boolean logic operators:
+
+`a AND b` is equivalent to: `λab.IF a b F`
+
+`a OR b` is equivalent to: `λab.IF a T b`
+
+`a NOT b` is equivalent to: `λa.IF a F T`
+
+*Note: `IF a b c` is essentially saying: `IF(a(b(c)))`*
+
+## Numbers:
+
+Although there are no numbers in lambda calculus, we can encode numbers using
+[Church numerals](https://en.wikipedia.org/wiki/Church_encoding).
+
+For any number n: <code>n = λf.f<sup>n</sup></code> so:
+
+`0 = λf.λx.x`
+
+`1 = λf.λx.f x`
+
+`2 = λf.λx.f(f x)`
+
+`3 = λf.λx.f(f(f x))`
+
+To increment a Church numeral,
+we use the successor function `S(n) = n + 1` which is:
+
+`S = λn.λf.λx.f((n f) x)`
+
+Using successor, we can define add:
+
+`ADD = λab.(a S)n`
+
+**Challenge:** try defining your own multiplication function!
+
+## For more advanced reading:
+
+1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf)
+2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html)
+3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file
diff --git a/latex.html.markdown b/latex.html.markdown
index a3866892..c9b1d8fb 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -255,7 +255,7 @@ There exists two main types of links: visible URL \\
% You can not add extra-spaces or special symbols into shadowing text since it
% will cause mistakes during the compilation
-This package also produces list of tumbnails in the output pdf document and
+This package also produces list of thumbnails in the output pdf document and
active links in the table of contents.
\section{End}
diff --git a/nim.html.markdown b/nim.html.markdown
index 07674532..30dfa94f 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -12,6 +12,25 @@ that gives the programmer power without compromises on runtime efficiency.
Nim is efficient, expressive, and elegant.
```nim
+# Single-line comments start with a #
+
+#[
+ Multi-line comments begin with a #[
+ ... and end with ]#
+
+They don't care about indentation
+
+ #[
+ and they can be nested
+ ]#
+
+]#
+
+discard """
+This can also work as a multiline comment.
+Or for unparsable, broken code
+"""
+
var # Declare (and assign) variables,
letter: char = 'n' # with or without type annotations
lang = "N" & "im"
@@ -35,10 +54,6 @@ when compileBadCode: # `when` is a compile time `if`
discard 1 > 2 # Note: The compiler will complain if the result of an expression
# is unused. `discard` bypasses this.
-discard """
-This can work as a multiline comment.
-Or for unparsable, broken code
-"""
#
# Data Structures
diff --git a/nix.html.markdown b/nix.html.markdown
index ef59a135..ba122a46 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -208,6 +208,12 @@ with builtins; [
{ a = 1; b = 2; }.a
#=> 1
+ # The ? operator tests whether a key is present in a set.
+ ({ a = 1; b = 2; } ? a)
+ #=> true
+ ({ a = 1; b = 2; } ? c)
+ #=> false
+
# The // operator merges two sets.
({ a = 1; } // { b = 2; })
#=> { a = 1; b = 2; }
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 364711af..04f9c6e3 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -13,8 +13,8 @@ least the next hundred years.
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
the JVM and [the MoarVM](http://moarvm.com).
-Meta-note : the triple pound signs are here to denote headlines,
-double paragraphs, and single notes.
+Meta-note : double pound signs (##) are used to indicate paragraphs, while
+single pound signs (#) indicate notes.
`#=>` represents the output of a command.
@@ -30,9 +30,9 @@ double paragraphs, and single notes.
## Variables
```perl6
-# In Perl 6, you declare a lexical variable using `my`
+## In Perl 6, you declare a lexical variable using `my`
my $variable;
-# Perl 6 has 4 kinds of variables:
+## Perl 6 has 3 basic types of variables: scalars, arrays, and hashes.
```
### Scalars
@@ -44,9 +44,9 @@ my $str = 'String';
# double quotes allow for interpolation (which we'll see later):
my $str2 = "String";
-# Variable names can contain but not end with simple quotes and dashes,
-# and can contain (and end with) underscores :
-# my $weird'variable-name_ = 5; # works !
+## Variable names can contain but not end with simple quotes and dashes,
+## and can contain (and end with) underscores :
+my $weird'variable-name_ = 5; # works !
my $bool = True; # `True` and `False` are Perl 6's boolean values.
my $inverse = !$bool; # You can invert a bool with the prefix `!` operator
@@ -57,13 +57,13 @@ my $forced-bool = so $str; # And you can use the prefix `so` operator
### Arrays and Lists
```perl6
-# Arrays represent multiple values. Their name start with `@`.
-# Lists are similar but are an immutable type
+## Arrays represent multiple values. Their name start with `@`.
+## Lists are similar but are an immutable type.
my @array = 'a', 'b', 'c';
# equivalent to :
my @letters = <a b c>; # array of words, delimited by space.
- # Similar to perl5's qw, or Ruby's %w.
+ # Similar to perl5's qw, or Ruby's %w.
my @array = 1, 2, 3;
say @array[2]; # Array indices start at 0 -- This is the third element
@@ -82,24 +82,25 @@ say @array; #=> a 6 b
### Hashes, or key-value Pairs.
```perl6
-# Hashes are pairs of keys and values.
-# You can construct a Pair object using the syntax `Key => Value`.
-# Hash tables are very fast for lookup, and are stored unordered.
-# Keep in mind that keys get "flattened" in hash context, and any duplicated
-# keys are deduplicated.
+## Hashes are pairs of keys and values.
+## You can construct a Pair object using the syntax `Key => Value`.
+## Hash tables are very fast for lookup, and are stored unordered.
+## Keep in mind that keys get "flattened" in hash context, and any duplicated
+## keys are deduplicated.
my %hash = 1 => 2,
3 => 4;
my %hash = foo => "bar", # keys get auto-quoted
"some other" => "value", # trailing commas are okay
;
-# Even though hashes are internally stored differently than arrays,
-# Perl 6 allows you to easily create a hash from an even numbered array:
+
+## Even though hashes are internally stored differently than arrays,
+## Perl 6 allows you to easily create a hash from an even numbered array:
my %hash = <key1 value1 key2 value2>;
my %hash = key1 => 'value1', key2 => 'value2'; # same result as above
-# You can also use the "colon pair" syntax:
-# (especially handy for named parameters that you'll see later)
+## You can also use the "colon pair" syntax:
+## (especially handy for named parameters that you'll see later)
my %hash = :w(1), # equivalent to `w => 1`
# this is useful for the `True` shortcut:
:truey, # equivalent to `:truey(True)`, or `truey => True`
@@ -115,18 +116,18 @@ say %hash<key2>; # If it's a string, you can actually use <>
## Subs
```perl6
-# subroutines or functions as most other languages call them are
-# created with the `sub` keyword.
+## Subroutines, or functions as most other languages call them, are
+## created with the `sub` keyword.
sub say-hello { say "Hello, world" }
-# You can provide (typed) arguments.
-# If specified, the type will be checked at compile-time if possible,
-# otherwise at runtime.
+## You can provide (typed) arguments.
+## If specified, the type will be checked at compile-time if possible,
+## otherwise at runtime.
sub say-hello-to(Str $name) {
say "Hello, $name !";
}
-# A sub returns the last value of the block.
+## A sub returns the last value of the block.
sub return-value {
5;
}
@@ -135,7 +136,7 @@ sub return-empty {
}
say return-empty; # prints Nil
-# Some control flow structures produce a value, like if:
+## Some control flow structures produce a value, like if:
sub return-if {
if True {
"Truthy";
@@ -143,13 +144,12 @@ sub return-if {
}
say return-if; # prints Truthy
-# Some don't, like for:
+## Some don't, like for:
sub return-for {
for 1, 2, 3 { }
}
say return-for; # prints Nil
-
## A sub can have optional arguments:
sub with-optional($arg?) { # the "?" marks the argument optional
say "I might return `(Any)` (Perl's 'null'-like value) if I don't have
@@ -170,20 +170,20 @@ hello-to('You'); #=> Hello, You !
## You can also, by using a syntax akin to the one of hashes
## (yay unified syntax !), pass *named* arguments to a `sub`.
-# They're optional, and will default to "Any".
+## They're optional, and will default to "Any".
sub with-named($normal-arg, :$named) {
say $normal-arg + $named;
}
with-named(1, named => 6); #=> 7
-# There's one gotcha to be aware of, here:
-# If you quote your key, Perl 6 won't be able to see it at compile time,
-# and you'll have a single Pair object as a positional parameter,
-# which means this fails:
+## There's one gotcha to be aware of, here:
+## If you quote your key, Perl 6 won't be able to see it at compile time,
+## and you'll have a single Pair object as a positional parameter,
+## which means this fails:
with-named(1, 'named' => 6);
with-named(2, :named(5)); #=> 7
-# To make a named argument mandatory, you can use `?`'s inverse, `!`
+## To make a named argument mandatory, you can use `?`'s inverse, `!`
sub with-mandatory-named(:$str!) {
say "$str !";
}
@@ -195,7 +195,7 @@ with-mandatory-named(3);# run time error:"Too many positional parameters passed"
sub takes-a-bool($name, :$bool) {
say "$name takes $bool";
}
-# ... you can use the same "short boolean" hash syntax:
+## ... you can use the same "short boolean" hash syntax:
takes-a-bool('config', :bool); # config takes True
takes-a-bool('config', :!bool); # config takes False
@@ -206,15 +206,15 @@ sub named-def(:$def = 5) {
named-def; #=> 5
named-def(def => 15); #=> 15
-# Since you can omit parenthesis to call a function with no arguments,
-# you need "&" in the name to store `say-hello` in a variable.
+## Since you can omit parenthesis to call a function with no arguments,
+## you need "&" in the name to store `say-hello` in a variable.
my &s = &say-hello;
my &other-s = sub { say "Anonymous function !" }
-# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many"
+## A sub can have a "slurpy" parameter, or "doesn't-matter-how-many"
sub as-many($head, *@rest) { #`*@` (slurpy) will "take everything else"
-# Note: you can have parameters *before* a slurpy one (like here),
-# but not *after*.
+## Note: you can have parameters *before* a slurpy one (like here),
+## but not *after*.
say @rest.join(' / ') ~ " !";
}
say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday !
@@ -222,8 +222,8 @@ say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday !
# consume the parameter before.
## You can call a function with an array using the
-# "argument list flattening" operator `|`
-# (it's not actually the only role of this operator, but it's one of them)
+## "argument list flattening" operator `|`
+## (it's not actually the only role of this operator, but it's one of them)
sub concat3($a, $b, $c) {
say "$a, $b, $c";
}
@@ -234,12 +234,12 @@ concat3(|@array); #=> a, b, c
## Containers
```perl6
-# In Perl 6, values are actually stored in "containers".
-# The assignment operator asks the container on the left to store the value on
-# its right. When passed around, containers are marked as immutable.
-# Which means that, in a function, you'll get an error if you try to
-# mutate one of your arguments.
-# If you really need to, you can ask for a mutable container using `is rw`:
+## In Perl 6, values are actually stored in "containers".
+## The assignment operator asks the container on the left to store the value on
+## its right. When passed around, containers are marked as immutable.
+## Which means that, in a function, you'll get an error if you try to
+## mutate one of your arguments.
+## If you really need to, you can ask for a mutable container using `is rw`:
sub mutate($n is rw) {
$n++;
say "\$n is now $n !";
@@ -248,15 +248,15 @@ sub mutate($n is rw) {
my $m = 42;
mutate $m; # $n is now 43 !
-# This works because we are passing the container $m to mutate. If we try
-# to just pass a number instead of passing a variable it won't work because
-# there is no container being passed and integers are immutable by themselves:
+## This works because we are passing the container $m to mutate. If we try
+## to just pass a number instead of passing a variable it won't work because
+## there is no container being passed and integers are immutable by themselves:
mutate 42; # Parameter '$n' expected a writable container, but got Int value
-# If what you want a copy instead, use `is copy`.
+## If what you want a copy instead, use `is copy`.
-# A sub itself returns a container, which means it can be marked as rw:
+## A sub itself returns a container, which means it can be marked as rw:
my $x = 42;
sub x-store() is rw { $x }
x-store() = 52; # in this case, the parentheses are mandatory
@@ -268,12 +268,12 @@ say $x; #=> 52
### Conditionals
```perl6
-# - `if`
-# Before talking about `if`, we need to know which values are "Truthy"
-# (represent True), and which are "Falsey" (or "Falsy") -- represent False.
-# Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or `Int`)
-# and of course False itself.
-# Every other value is Truthy.
+## - `if`
+## Before talking about `if`, we need to know which values are "Truthy"
+## (represent True), and which are "Falsey" (or "Falsy") -- represent False.
+## Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or
+## `Int`) and of course False itself.
+## Every other value is Truthy.
if True {
say "It's true !";
}
@@ -282,17 +282,17 @@ unless False {
say "It's not false !";
}
-# As you can see, you don't need parentheses around conditions.
-# However, you do need the brackets around the "body" block:
+## As you can see, you don't need parentheses around conditions.
+## However, you do need the brackets around the "body" block:
# if (true) say; # This doesn't work !
-# You can also use their postfix versions, with the keyword after:
+## You can also use their postfix versions, with the keyword after:
say "Quite truthy" if True;
-# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
-# returns $value-if-true if the condition is true and $value-if-false
-# if it is false.
-# my $result = $value condition ?? $value-if-true !! $value-if-false;
+## - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
+## returns $value-if-true if the condition is true and $value-if-false
+## if it is false.
+## my $result = $value condition ?? $value-if-true !! $value-if-false;
my $age = 30;
say $age > 18 ?? "You are an adult" !! "You are under 18";
@@ -301,18 +301,18 @@ say $age > 18 ?? "You are an adult" !! "You are under 18";
### given/when, or switch
```perl6
-# - `given`-`when` looks like other languages' `switch`, but is much more
-# powerful thanks to smart matching and Perl 6's "topic variable", $_.
-#
-# This variable contains the default argument of a block,
-# a loop's current iteration (unless explicitly named), etc.
-#
-# `given` simply puts its argument into `$_` (like a block would do),
-# and `when` compares it using the "smart matching" (`~~`) operator.
-#
-# Since other Perl 6 constructs use this variable (as said before, like `for`,
-# blocks, etc), this means the powerful `when` is not only applicable along with
-# a `given`, but instead anywhere a `$_` exists.
+## - `given`-`when` looks like other languages' `switch`, but is much more
+## powerful thanks to smart matching and Perl 6's "topic variable", $_.
+##
+## This variable contains the default argument of a block,
+## a loop's current iteration (unless explicitly named), etc.
+##
+## `given` simply puts its argument into `$_` (like a block would do),
+## and `when` compares it using the "smart matching" (`~~`) operator.
+##
+## Since other Perl 6 constructs use this variable (as said before, like `for`,
+## blocks, etc), this means the powerful `when` is not only applicable along
+## with a `given`, but instead anywhere a `$_` exists.
given "foo bar" {
say $_; #=> foo bar
@@ -338,8 +338,8 @@ given "foo bar" {
### Looping constructs
```perl6
-# - `loop` is an infinite loop if you don't pass it arguments,
-# but can also be a C-style `for` loop:
+## - `loop` is an infinite loop if you don't pass it arguments,
+## but can also be a C-style `for` loop:
loop {
say "This is an infinite loop !";
last; # last breaks out of the loop, like the `break` keyword in other
@@ -353,13 +353,13 @@ loop (my $i = 0; $i < 5; $i++) {
say "This is a C-style for loop !";
}
-# - `for` - Passes through an array
+## - `for` - Passes through an array
for @array -> $variable {
say "I've got $variable !";
}
-# As we saw with given, for's default "current iteration" variable is `$_`.
-# That means you can use `when` in a `for` just like you were in a `given`.
+## As we saw with given, for's default "current iteration" variable is `$_`.
+## That means you can use `when` in a `for` just like you were in a `given`.
for @array {
say "I've got $_";
@@ -370,13 +370,13 @@ for @array {
for @array {
# You can...
- next if $_ == 3; # Skip to the next iteration (`continue` in C-like languages).
- redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`).
- last if $_ == 5; # Or break out of a loop (like `break` in C-like languages).
+ next if $_ == 3; # Skip to the next iteration (`continue` in C-like languages)
+ redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`)
+ last if $_ == 5; # Or break out of a loop (like `break` in C-like languages)
}
-# The "pointy block" syntax isn't specific to for.
-# It's just a way to express a block in Perl6.
+## The "pointy block" syntax isn't specific to for.
+## It's just a way to express a block in Perl6.
if long-computation() -> $result {
say "The result is $result";
}
@@ -387,99 +387,100 @@ if long-computation() -> $result {
```perl6
## Since Perl languages are very much operator-based languages,
## Perl 6 operators are actually just funny-looking subroutines, in syntactic
-## categories, like infix:<+> (addition) or prefix:<!> (bool not).
+## categories, like infix:<+> (addition) or prefix:<!> (bool not).
## The categories are:
-# - "prefix": before (like `!` in `!True`).
-# - "postfix": after (like `++` in `$a++`).
-# - "infix": in between (like `*` in `4 * 3`).
-# - "circumfix": around (like `[`-`]` in `[1, 2]`).
-# - "post-circumfix": around, after another term (like `{`-`}` in `%hash{'key'}`)
+## - "prefix": before (like `!` in `!True`).
+## - "postfix": after (like `++` in `$a++`).
+## - "infix": in between (like `*` in `4 * 3`).
+## - "circumfix": around (like `[`-`]` in `[1, 2]`).
+## - "post-circumfix": around, after another term (like `{`-`}` in
+## `%hash{'key'}`)
## The associativity and precedence list are explained below.
-# Alright, you're set to go !
+## Alright, you're set to go !
## * Equality Checking
-# - `==` is numeric comparison
+## - `==` is numeric comparison
3 == 4; # False
3 != 4; # True
-# - `eq` is string comparison
+## - `eq` is string comparison
'a' eq 'b';
'a' ne 'b'; # not equal
'a' !eq 'b'; # same as above
-# - `eqv` is canonical equivalence (or "deep equality")
+## - `eqv` is canonical equivalence (or "deep equality")
(1, 2) eqv (1, 3);
-# - Smart Match Operator: `~~`
-# Aliases the left hand side to $_ and then evaluates the right hand side.
-# Here are some common comparison semantics:
+## - Smart Match Operator: `~~`
+## Aliases the left hand side to $_ and then evaluates the right hand side.
+## Here are some common comparison semantics:
-# String or Numeric Equality
+## String or Numeric Equality
'Foo' ~~ 'Foo'; # True if strings are equal.
12.5 ~~ 12.50; # 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.
+## Regex - For matching a regular expression against the left side.
+## Returns a (Match) object, which evaluates as True if regexp matches.
my $obj = 'abc' ~~ /a/;
say $obj; # 「a」
say $obj.WHAT; # (Match)
-# Hashes
+## Hashes
'key' ~~ %hash; # True if key exists in hash
-# Type - Checks if left side "has type" (can check superclasses and roles)
+## Type - Checks if left side "has type" (can check superclasses and roles)
1 ~~ Int; # True
-# Smart-matching against a boolean always returns that boolean (and will warn).
+## Smart-matching against a boolean always returns that boolean (and will warn).
1 ~~ True; # True
False ~~ True; # True
-# # General syntax is $arg ~~ &bool-returning-function;
-# For a complete list of combinations, use this table:
-# http://perlcabal.org/syn/S03.html#Smart_matching
+## General syntax is $arg ~~ &bool-returning-function;
+## For a complete list of combinations, use this table:
+## http://perlcabal.org/syn/S03.html#Smart_matching
-# You also, of course, have `<`, `<=`, `>`, `>=`.
-# Their string equivalent are also available : `lt`, `le`, `gt`, `ge`.
+## You also, of course, have `<`, `<=`, `>`, `>=`.
+## Their string equivalent are also available : `lt`, `le`, `gt`, `ge`.
3 > 4;
## * Range constructors
3 .. 7; # 3 to 7, both included
-# `^` on either side them exclusive on that side :
+## `^` on either side them exclusive on that side :
3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`)
-# This also works as a shortcut for `0..^N`:
+## This also works as a shortcut for `0..^N`:
^10; # means 0..^10
-# This also allows us to demonstrate that Perl 6 has lazy/infinite arrays,
-# using the Whatever Star:
+## This also allows us to demonstrate that Perl 6 has lazy/infinite arrays,
+## using the Whatever Star:
my @array = 1..*; # 1 to Infinite ! `1..Inf` is the same.
say @array[^10]; # you can pass arrays as subscripts and it'll return
# an array of results. This will print
# "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !)
-# Note : when reading an infinite list, Perl 6 will "reify" the elements
-# it needs, then keep them in memory. They won't be calculated more than once.
-# It also will never calculate more elements that are needed.
-# Trying
+## Note : when reading an infinite list, Perl 6 will "reify" the elements
+## it needs, then keep them in memory. They won't be calculated more than once.
+## It also will never calculate more elements that are needed.
+## Trying
-# An array subscript can also be a closure.
-# It'll be called with the length as the argument
+## An array subscript can also be a closure.
+## It'll be called with the length as the argument
say join(' ', @array[15..*]); #=> 15 16 17 18 19
-# which is equivalent to:
+## which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
-# Note: if you try to do either of those with an infinite array,
-# you'll trigger an infinite loop (your program won't finish)
+## Note: if you try to do either of those with an infinite array,
+## you'll trigger an infinite loop (your program won't finish)
-# You can use that in most places you'd expect, even assigning to an array
+## You can use that in most places you'd expect, even assigning to an array
my @numbers = ^20;
-# Here numbers increase by "6"; more on `...` operator later.
+## Here numbers increase by "6"; more on `...` operator later.
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
# only the 15 needed values will be calculated.
@@ -496,11 +497,11 @@ say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87
my ( $a, $b, $c ) = 1, 0, 2;
$a && $b && $c; # Returns 0, the first False value
-# || Returns the first argument that evaluates to True
+## || Returns the first argument that evaluates to True
$b || $a; # 1
-# And because you're going to want them,
-# you also have compound assignment operators:
+## And because you're going to want them,
+## you also have compound assignment operators:
$a *= 2; # multiply and assignment. Equivalent to $a = $a * 2;
$b %%= 5; # divisible by and assignment
@array .= sort; # calls the `sort` method and assigns the result back
@@ -509,15 +510,15 @@ $b %%= 5; # divisible by and assignment
## More on subs !
```perl6
-# As we said before, Perl 6 has *really* powerful subs. We're going to see
-# a few more key concepts that make them better than in any other language :-).
+## As we said before, Perl 6 has *really* powerful subs. We're going to see
+## a few more key concepts that make them better than in any other language :-).
```
### Unpacking !
```perl6
-# It's the ability to "extract" arrays and keys (AKA "destructuring").
-# It'll work in `my`s and in parameter lists.
+## It's the ability to "extract" arrays and keys (AKA "destructuring").
+## It'll work in `my`s and in parameter lists.
my ($f, $g) = 1, 2;
say $f; #=> 1
my ($, $, $h) = 1, 2, 3; # keep the non-interesting anonymous
@@ -533,50 +534,50 @@ sub unpack_array(@array [$fst, $snd]) {
unpack_array(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
-# If you're not using the array itself, you can also keep it anonymous,
-# much like a scalar:
+## If you're not using the array itself, you can also keep it anonymous,
+## much like a scalar:
sub first-of-array(@ [$fst]) { $fst }
first-of-array(@small); #=> 1
first-of-array(@tail); # Throws an error "Too many positional parameters passed"
# (which means the array is too big).
-# You can also use a slurp ...
+## You can also use a slurp ...
sub slurp-in-array(@ [$fst, *@rest]) { # You could keep `*@rest` anonymous
say $fst + @rest.elems; # `.elems` returns a list's length.
# Here, `@rest` is `(3,)`, since `$fst` holds the `2`.
}
slurp-in-array(@tail); #=> 3
-# You could even extract on a slurpy (but it's pretty useless ;-).)
+## You could even extract on a slurpy (but it's pretty useless ;-).)
sub fst(*@ [$fst]) { # or simply : `sub fst($fst) { ... }`
say $fst;
}
fst(1); #=> 1
fst(1, 2); # errors with "Too many positional parameters passed"
-# You can also destructure hashes (and classes, which you'll learn about later !)
-# The syntax is basically `%hash-name (:key($variable-to-store-value-in))`.
-# The hash can stay anonymous if you only need the values you extracted.
+## You can also destructure hashes (and classes, which you'll learn about later)
+## The syntax is basically `%hash-name (:key($variable-to-store-value-in))`.
+## The hash can stay anonymous if you only need the values you extracted.
sub key-of(% (:value($val), :qua($qua))) {
say "Got val $val, $qua times.";
}
-# Then call it with a hash: (you need to keep the brackets for it to be a hash)
+## Then call it with a hash: (you need to keep the brackets for it to be a hash)
key-of({value => 'foo', qua => 1});
#key-of(%hash); # the same (for an equivalent `%hash`)
## The last expression of a sub is returned automatically
-# (though you may use the `return` keyword, of course):
+## (though you may use the `return` keyword, of course):
sub next-index($n) {
$n + 1;
}
my $new-n = next-index(3); # $new-n is now 4
-# This is true for everything, except for the looping constructs
-# (due to performance reasons): there's reason to build a list
-# if we're just going to discard all the results.
-# If you still want to build one, you can use the `do` statement prefix:
-# (or the `gather` prefix, which we'll see later)
+## This is true for everything, except for the looping constructs
+## (due to performance reasons): there's reason to build a list
+## if we're just going to discard all the results.
+## If you still want to build one, you can use the `do` statement prefix:
+## (or the `gather` prefix, which we'll see later)
sub list-of($n) {
do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`)
$_ # current loop iteration
@@ -590,16 +591,16 @@ my @list3 = list-of(3); #=> (0, 1, 2)
```perl6
## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block")
my &lambda = -> $argument { "The argument passed to this lambda is $argument" }
-# `-> {}` and `{}` 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.
+## `-> {}` and `{}` 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.
-# We can, for example, add 3 to each value of an array using map:
+## We can, for example, add 3 to each value of an array using map:
my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument
-# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
-# A block doesn't have a "function context" (though it can have arguments),
-# which means that if you return from it,
-# you're going to return from the parent function. Compare:
+## A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
+## A block doesn't have a "function context" (though it can have arguments),
+## which means that if you return from it,
+## you're going to return from the parent function. Compare:
sub is-in(@array, $elem) {
# this will `return` out of the `is-in` sub
# once the condition evaluated to True, the loop won't be run anymore
@@ -612,8 +613,8 @@ sub truthy-array(@array) {
# ^ the `return` only returns from the anonymous `sub`
}
-# You can also use the "whatever star" to create an anonymous function
-# (it'll stop at the furthest operator in the current expression)
+## You can also use the "whatever star" to create an anonymous function
+## (it'll stop at the furthest operator in the current expression)
my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }`
my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }`
# also `sub ($a, $b) { $a + $b + 3 }`
@@ -622,41 +623,41 @@ say (*/2)(4); #=> 2
say ((*+3)/5)(5); #=> 1.6
# works even in parens !
-# But if you need to have more than one argument (`$_`)
-# in a block (without wanting to resort to `-> {}`),
-# you can also use the implicit argument syntax, `$^` :
+## But if you need to have more than one argument (`$_`)
+## in a block (without wanting to resort to `-> {}`),
+## you can also use the implicit argument syntax, `$^` :
map({ $^a + $^b + 3 }, @array); # equivalent to following:
map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)
-# Note : those are sorted lexicographically.
+## Note : those are sorted lexicographically.
# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }`
```
### About types...
```perl6
-# Perl6 is gradually typed. This means you can specify the type
-# of your variables/arguments/return types, or you can omit them
-# and they'll default to "Any".
-# You obviously get access to a few base types, like Int and Str.
-# The constructs for declaring types are "class", "role",
-# which you'll see later.
-
-# For now, let us examine "subset":
-# a "subset" is a "sub-type" with additional checks.
-# For example: "a very big integer is an Int that's greater than 500"
-# You can specify the type you're subtyping (by default, Any),
-# and add additional checks with the "where" keyword:
+## Perl6 is gradually typed. This means you can specify the type
+## of your variables/arguments/return types, or you can omit them
+## and they'll default to "Any".
+## You obviously get access to a few base types, like Int and Str.
+## The constructs for declaring types are "class", "role",
+## which you'll see later.
+
+## For now, let us examine "subset":
+## a "subset" is a "sub-type" with additional checks.
+## For example: "a very big integer is an Int that's greater than 500"
+## You can specify the type you're subtyping (by default, Any),
+## and add additional checks with the "where" keyword:
subset VeryBigInteger of Int where * > 500;
```
### Multiple Dispatch
```perl6
-# Perl 6 can decide which variant of a `sub` to call based on the type of the
-# arguments, or on arbitrary preconditions, like with a type or a `where`:
+## Perl 6 can decide which variant of a `sub` to call based on the type of the
+## arguments, or on arbitrary preconditions, like with a type or a `where`:
-# with types
+## with types
multi sub sayit(Int $n) { # note the `multi` keyword here
say "Number: $n";
}
@@ -667,7 +668,7 @@ sayit("foo"); # prints "String: foo"
sayit(True); # fails at *compile time* with
# "calling 'sayit' will never work with arguments of types ..."
-# with arbitrary precondition (remember subsets?):
+## with arbitrary precondition (remember subsets?):
multi is-big(Int $n where * > 50) { "Yes !" } # using a closure
multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching
# (could use a regexp, etc)
@@ -679,7 +680,7 @@ multi odd-or-even(Even) { "Even" } # The main case using the type.
# We don't name the argument.
multi odd-or-even($) { "Odd" } # "else"
-# You can even dispatch based on a positional's argument presence !
+## You can even dispatch based on a positional's argument presence !
multi with-or-without-you(:$with!) { # You need make it mandatory to
# be able to dispatch against it.
say "I can live ! Actually, I can't.";
@@ -687,26 +688,26 @@ multi with-or-without-you(:$with!) { # You need make it mandatory to
multi with-or-without-you {
say "Definitely can't live.";
}
-# This is very, very useful for many purposes, like `MAIN` subs (covered later),
-# and even the language itself is using it in several places.
-#
-# - `is`, for example, is actually a `multi sub` named `trait_mod:<is>`,
-# and it works off that.
-# - `is rw`, is simply a dispatch to a function with this signature:
-# sub trait_mod:<is>(Routine $r, :$rw!) {}
-#
-# (commented because running this would be a terrible idea !)
+## This is very, very useful for many purposes, like `MAIN` subs (covered
+## later), and even the language itself is using it in several places.
+##
+## - `is`, for example, is actually a `multi sub` named `trait_mod:<is>`,
+## and it works off that.
+## - `is rw`, is simply a dispatch to a function with this signature:
+## sub trait_mod:<is>(Routine $r, :$rw!) {}
+##
+## (commented because running this would be a terrible idea !)
```
## Scoping
```perl6
-# In Perl 6, unlike many scripting languages, (such as Python, Ruby, PHP),
-# you must declare your variables before using them. The `my` declarator
-# you have learned uses "lexical scoping". There are a few other declarators,
-# (`our`, `state`, ..., ) which we'll see later.
-# This is called "lexical scoping", where in inner blocks,
-# you can access variables from outer blocks.
+## In Perl 6, unlike many scripting languages, (such as Python, Ruby, PHP),
+## you must declare your variables before using them. The `my` declarator
+## you have learned uses "lexical scoping". There are a few other declarators,
+## (`our`, `state`, ..., ) which we'll see later.
+## This is called "lexical scoping", where in inner blocks,
+## you can access variables from outer blocks.
my $file_scoped = 'Foo';
sub outer {
my $outer_scoped = 'Bar';
@@ -717,27 +718,27 @@ sub outer {
}
outer()(); #=> 'Foo Bar'
-# As you can see, `$file_scoped` and `$outer_scoped` were captured.
-# But if we were to try and use `$bar` outside of `foo`,
-# the variable would be undefined (and you'd get a compile time error).
+## As you can see, `$file_scoped` and `$outer_scoped` were captured.
+## But if we were to try and use `$bar` outside of `foo`,
+## the variable would be undefined (and you'd get a compile time error).
```
## Twigils
```perl6
-# There are many special `twigils` (composed sigil's) in Perl 6.
-# Twigils define the variables' scope.
-# The * and ? twigils work on standard variables:
-# * Dynamic variable
-# ? Compile-time variable
-# The ! and the . twigils are used with Perl 6's objects:
-# ! Attribute (class member)
-# . Method (not really a variable)
-
-# `*` Twigil: Dynamic Scope
-# These variables use the`*` twigil to mark dynamically-scoped variables.
-# Dynamically-scoped variables are looked up through the caller, not through
-# the outer scope
+## There are many special `twigils` (composed sigil's) in Perl 6.
+## Twigils define the variables' scope.
+## The * and ? twigils work on standard variables:
+## * Dynamic variable
+## ? Compile-time variable
+## The ! and the . twigils are used with Perl 6's objects:
+## ! Attribute (class member)
+## . Method (not really a variable)
+
+## `*` Twigil: Dynamic Scope
+## These variables use the`*` twigil to mark dynamically-scoped variables.
+## Dynamically-scoped variables are looked up through the caller, not through
+## the outer scope
my $*dyn_scoped_1 = 1;
my $*dyn_scoped_2 = 10;
@@ -750,8 +751,9 @@ sub call_say_dyn {
my $*dyn_scoped_1 = 25; # Defines $*dyn_scoped_1 only for this sub.
$*dyn_scoped_2 = 100; # Will change the value of the file scoped variable.
say_dyn(); #=> 25 100 $*dyn_scoped 1 and 2 will be looked for in the call.
- # It 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).
+ # It 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).
}
say_dyn(); #=> 1 10
call_say_dyn(); #=> 25 100
@@ -764,20 +766,20 @@ say_dyn(); #=> 1 100 We changed the value of $*dyn_scoped_2 in call_say_dyn
## Object Model
```perl6
-# To call a method on an object, add a dot followed by the method name:
-# => $object.method
-# Classes are declared with the `class` keyword. Attributes are declared
-# with the `has` keyword, and methods declared with `method`.
-# Every attribute that is private uses the ! twigil for example: `$!attr`.
-# Immutable public attributes use the `.` twigil.
-# (you can make them mutable with `is rw`)
-# The easiest way to remember the `$.` twigil is comparing it to how methods
-# are called.
-
-# Perl 6's object model ("SixModel") is very flexible,
-# and allows you to dynamically add methods, change semantics, etc ...
-# (these will not all be covered here, and you should refer to:
-# https://docs.perl6.org/language/objects.html.
+## To call a method on an object, add a dot followed by the method name:
+## => $object.method
+## Classes are declared with the `class` keyword. Attributes are declared
+## with the `has` keyword, and methods declared with `method`.
+## Every attribute that is private uses the ! twigil for example: `$!attr`.
+## Immutable public attributes use the `.` twigil.
+## (you can make them mutable with `is rw`)
+## The easiest way to remember the `$.` twigil is comparing it to how methods
+## are called.
+
+## Perl 6's object model ("SixModel") is very flexible,
+## and allows you to dynamically add methods, change semantics, etc ...
+## (these will not all be covered here, and you should refer to:
+## https://docs.perl6.org/language/objects.html.
class Attrib-Class {
has $.attrib; # `$.attrib` is immutable.
@@ -801,11 +803,11 @@ class Attrib-Class {
}
};
-# Create a new instance of Attrib-Class with $.attrib set to 5 :
-# Note: you can't set private-attribute from here (more later on).
+## Create a new instance of Attrib-Class with $.attrib set to 5 :
+## Note: you can't set private-attribute from here (more later on).
my $class-obj = Attrib-Class.new(attrib => 5);
say $class-obj.get-value; #=> 15
-#$class-obj.attrib = 5; # This fails, because the `has $.attrib` is immutable
+# $class-obj.attrib = 5; # This fails, because the `has $.attrib` is immutable
$class-obj.other-attrib = 10; # This, however, works, because the public
# attribute is mutable (`rw`).
```
@@ -813,11 +815,11 @@ $class-obj.other-attrib = 10; # This, however, works, because the public
### Object Inheritance
```perl6
-# Perl 6 also has inheritance (along with multiple inheritance)
-# While `method`'s are inherited, `submethod`'s are not.
-# Submethods are useful for object construction and destruction tasks,
-# such as BUILD, or methods that must be overridden by subtypes.
-# We will learn about BUILD later on.
+## Perl 6 also has inheritance (along with multiple inheritance)
+## While `method`'s are inherited, `submethod`'s are not.
+## Submethods are useful for object construction and destruction tasks,
+## such as BUILD, or methods that must be overridden by subtypes.
+## We will learn about BUILD later on.
class Parent {
has $.age;
@@ -837,24 +839,24 @@ class Child is Parent {
my Parent $Richard .= new(age => 40, name => 'Richard');
$Richard.favorite-color; #=> "My favorite color is Blue"
$Richard.talk; #=> "Hi, my name is Richard"
-# # $Richard is able to access the submethod, he knows how to say his name.
+## $Richard is able to access the submethod, he knows how to say his name.
my Child $Madison .= new(age => 1, name => 'Madison');
$Madison.talk; # prints "Goo goo ga ga" due to the overridden method.
-# $Madison.favorite-color does not work since it is not inherited
-
-# When you use `my T $var`, `$var` starts off with `T` itself in it,
-# so you can call `new` on it.
-# (`.=` is just the dot-call and the assignment operator:
-# `$a .= b` is the same as `$a = $a.b`)
-# Also note that `BUILD` (the method called inside `new`)
-# will set parent properties too, so you can pass `val => 5`.
+# $Madison.favorite-color # does not work since it is not inherited
+
+## When you use `my T $var`, `$var` starts off with `T` itself in it,
+## so you can call `new` on it.
+## (`.=` is just the dot-call and the assignment operator:
+## `$a .= b` is the same as `$a = $a.b`)
+## Also note that `BUILD` (the method called inside `new`)
+## will set parent properties too, so you can pass `val => 5`.
```
### Roles, or Mixins
```perl6
-# Roles are supported too (also called Mixins in other languages)
+## Roles are supported too (also called Mixins in other languages)
role PrintableVal {
has $!counter = 0;
method print {
@@ -862,105 +864,108 @@ role PrintableVal {
}
}
-# you "import" a mixin (a "role") with "does":
+## you "import" a mixin (a "role") with "does":
class Item does PrintableVal {
has $.val;
- # When `does`-ed, a `role` literally "mixes in" the class:
- # the methods and attributes are put together, which means a class can access
- # the private attributes/methods of its roles (but not the inverse !):
+ ## When `does`-ed, a `role` literally "mixes in" the class:
+ ## the methods and attributes are put together, which means a class can access
+ ## the private attributes/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
- # However, this:
- # method print {}
- # is ONLY valid when `print` isn't a `multi` with the same dispatch.
- # (this means a parent class can shadow a child class's `multi print() {}`,
- # but it's an error if a role does)
+ ## However, this:
+ ## method print {}
+ ## is ONLY valid when `print` isn't a `multi` with the same dispatch.
+ ## (this means a parent class can shadow a child class's `multi print() {}`,
+ ## but it's an error if a role does)
- # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
- # will be shadowed, since the compiler will consider `ROLE` to be a class.
+ ## NOTE: You can use a role as a class (with `is ROLE`). In this case,
+ ## methods will be shadowed, since the compiler will consider `ROLE` to
+ ## be a class.
}
```
## Exceptions
```perl6
-# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-# In Perl6 exceptions are automatically 'thrown'
+## Exceptions are built on top of classes, in the package `X` (like `X::IO`).
+## In Perl6 exceptions are automatically 'thrown'
open 'foo'; #> Failed to open file foo: no such file or directory
-# It will also print out what line the error was thrown at and other error info
+## It will also print out what line the error was thrown at and other error info
-# You can throw an exception using `die`:
+## You can throw an exception using `die`:
die 'Error!'; #=> Error!
-# Or more explicitly:
+
+## Or more explicitly:
die X::AdHoc.new(payload => 'Error!');
-# In Perl 6, `orelse` is similar to the `or` operator, except it only matches
-# undefined variables instead of anything evaluating as false.
-# Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
-# and other types that have not been initialized to any value yet.
-# You can check if something is defined or not using the defined method:
+## In Perl 6, `orelse` is similar to the `or` operator, except it only matches
+## undefined variables instead of anything evaluating as false.
+## Undefined values include: `Nil`, `Mu` and `Failure` as well as `Int`, `Str`
+## and other types that have not been initialized to any value yet.
+## You can check if something is defined or not using the defined method:
my $uninitialized;
say $uninitiazilzed.defined; #> False
-# When using `orelse` it will disarm the exception and alias $_ to that failure
-# This will avoid it being automatically handled and printing lots of scary
-# error messages to the screen.
-# We can use the exception method on $_ to access the exception
+## When using `orelse` it will disarm the exception and alias $_ to that failure
+## This will avoid it being automatically handled and printing lots of scary
+## error messages to the screen.
+## We can use the exception method on $_ to access the exception
open 'foo' orelse say "Something happened {.exception}";
-# This also works:
+
+## This also works:
open 'foo' orelse say "Something happened $_"; #> Something happened
#> Failed to open file foo: no such file or directory
-# Both of those above work but in case we get an object from the left side that
-# is not a failure we will probably get a warning. We see below how we can use
-# `try` and `CATCH` to be more specific with the exceptions we catch.
+## Both of those above work but in case we get an object from the left side that
+## is not a failure we will probably get a warning. We see below how we can use
+## `try` and `CATCH` to be more specific with the exceptions we catch.
```
### Using `try` and `CATCH`
```perl6
-# By using `try` and `CATCH` you can contain and handle exceptions without
-# disrupting the rest of the program. `try` will set the last exception to
-# the special variable `$!` Note: This has no relation to $!variables.
+## By using `try` and `CATCH` you can contain and handle exceptions without
+## disrupting the rest of the program. `try` will set the last exception to
+## the special variable `$!` Note: This has no relation to $!variables.
try open 'foo';
say "Well, I tried! $!" if defined $!; #> Well, I tried! Failed to open file
#foo: no such file or directory
-# Now, what if we want more control over handling the exception?
-# Unlike many other languages, in Perl 6, you put the `CATCH` block *within*
-# the block to `try`. Similar to how $_ was set when we 'disarmed' the
-# exception with orelse, we also use $_ in the CATCH block.
-# Note: ($! is only set *after* the `try` block)
-# By default, a `try` has a `CATCH` block that catches
-# any exception (`CATCH { default {} }`).
+## Now, what if we want more control over handling the exception?
+## Unlike many other languages, in Perl 6, you put the `CATCH` block *within*
+## the block to `try`. Similar to how $_ was set when we 'disarmed' the
+## exception with orelse, we also use $_ in the CATCH block.
+## Note: ($! is only set *after* the `try` block)
+## By default, a `try` has a `CATCH` block that catches
+## any exception (`CATCH { default {} }`).
try { my $a = (0 %% 0); CATCH { say "Something happened: $_" } }
#=> Something happened: Attempt to divide by zero using infix:<%%>
-# You can redefine it using `when`s (and `default`)
-# to handle the exceptions you want:
+## You can redefine it using `when`s (and `default`)
+## to handle the exceptions you want:
try {
open 'foo';
CATCH { # In the `CATCH` block, the exception is set to $_
when X::AdHoc { say "Error: $_" }
#=>Error: Failed to open file /dir/foo: no such file or directory
- # Any other exception will be re-raised, since we don't have a `default`
- # 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`.
- # You still can re-throw the exception (see below) by hand.
+ ## Any other exception will be re-raised, since we don't have a `default`
+ ## 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`.
+ ## You still can re-throw the exception (see below) by hand.
}
}
-# There are also some subtleties to exceptions. Some Perl 6 subs return a
-# `Failure`, which is a kind of "unthrown exception". They're not thrown until
-# you tried to look at their content, unless you call `.Bool`/`.defined` on
-# them - then they're handled.
-# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
-#
-# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
-# is on, `fail` will throw an exception (like `die`).
+## There are also some subtleties to exceptions. Some Perl 6 subs return a
+## `Failure`, which is a kind of "unthrown exception". They're not thrown until
+## you tried to look at their content, unless you call `.Bool`/`.defined` on
+## them - then they're handled.
+## (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
+##
+## You can throw a `Failure` using `fail`. Note that if the pragma `use fatal`
+## is on, `fail` will throw an exception (like `die`).
fail "foo"; # We're not trying to access the value, so no problem.
try {
fail "foo";
@@ -969,28 +974,28 @@ try {
}
}
-# There is also another kind of exception: Control exceptions.
-# Those are "good" exceptions, which happen when you change your program's flow,
-# using operators like `return`, `next` or `last`.
-# You can "catch" those with `CONTROL` (not 100% working in Rakudo yet).
+## There is also another kind of exception: Control exceptions.
+## Those are "good" exceptions, which happen when you change your program's
+## flow, using operators like `return`, `next` or `last`.
+## You can "catch" those with `CONTROL` (not 100% working in Rakudo yet).
```
## Packages
```perl6
-# Packages are a way to reuse code. Packages are like "namespaces", and any
-# element of the six model (`module`, `role`, `class`, `grammar`, `subset`
-# and `enum`) are actually packages. (Packages are the lowest common denominator)
-# Packages are important - especially as Perl is well-known for CPAN,
-# the Comprehensive Perl Archive Network.
+## Packages are a way to reuse code. Packages are like "namespaces", and any
+## element of the six model (`module`, `role`, `class`, `grammar`, `subset` and
+## `enum`) are actually packages. (Packages are the lowest common denominator)
+## Packages are important - especially as Perl is well-known for CPAN,
+## the Comprehensive Perl Archive Network.
-# You can use a module (bring its declarations into scope) with `use`
+## You can use a module (bring its declarations into scope) with `use`
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; #=> [1]
-# You should not declare packages using the `package` keyword (unlike Perl 5).
-# Instead, use `class Package::Name::Here;` to declare a class, or if you only want to
-# export variables/subs, you can use `module`.
+## You should not declare packages using the `package` keyword (unlike Perl 5).
+## Instead, use `class Package::Name::Here;` to declare a class, or if you only
+## want to export variables/subs, you can use `module`.
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
@@ -1002,22 +1007,22 @@ unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
} # You will learn more about grammars in the regex section
-# As said before, any part of the six model is also a package.
-# Since `JSON::Tiny` uses (its own) `JSON::Tiny::Actions` class, you can use it:
+## As said before, any part of the six model is also a package.
+## Since `JSON::Tiny` uses its own `JSON::Tiny::Actions` class, you can use it:
my $actions = JSON::Tiny::Actions.new;
-# We'll see how to export variables and subs in the next part:
+## We'll see how to export variables and subs in the next part:
```
## Declarators
```perl6
-# In Perl 6, you get different behaviors based on how you declare a variable.
-# You've already seen `my` and `has`, we'll now explore the others.
+## In Perl 6, you get different behaviors based on how you declare a variable.
+## You've already seen `my` and `has`, we'll now explore the others.
## * `our` declarations happen at `INIT` time -- (see "Phasers" below)
-# It's like `my`, but it also creates a package variable.
-# (All packagish things (`class`, `role`, etc) are `our` by default)
+## It's like `my`, but it also creates a package variable.
+## (All packagish things (`class`, `role`, etc) are `our` by default)
module Var::Increment {
our $our-var = 1; # Note: you can't put a type constraint like Int on an
my $my-var = 22; # `our` variable.
@@ -1044,26 +1049,26 @@ Var::Increment::Inc; #=> 3 # Notice how the value of $our-var was
Var::Increment::unavailable; #> Could not find symbol '&unavailable'
## * `constant` (happens at `BEGIN` time)
-# You can use the `constant` keyword to declare a compile-time variable/symbol:
+## You can use the `constant` keyword to declare a compile-time variable/symbol:
constant Pi = 3.14;
constant $var = 1;
-# And if you're wondering, yes, it can also contain infinite lists.
+## And if you're wondering, yes, it can also contain infinite lists.
constant why-not = 5, 15 ... *;
say why-not[^5]; #=> 5 15 25 35 45
## * `state` (happens at run time, but only once)
-# State variables are only initialized one time
-# (they exist in other languages such as C as `static`)
+## State variables are only initialized one time
+## (they exist in other languages such as C as `static`)
sub fixed-rand {
state $val = rand;
say $val;
}
fixed-rand for ^10; # will print the same number 10 times
-# Note, however, that they exist separately in different enclosing contexts.
-# If you declare a function with a `state` within a loop, it'll re-create the
-# variable for each iteration of the loop. See:
+## Note, however, that they exist separately in different enclosing contexts.
+## If you declare a function with a `state` within a loop, it'll re-create the
+## variable for each iteration of the loop. See:
for ^5 -> $a {
sub foo {
state $val = rand; # This will be a different value for every value of `$a`
@@ -1078,13 +1083,14 @@ for ^5 -> $a {
## Phasers
```perl6
-# Phasers in Perl 6 are blocks that happen at determined points of time in your
-# program. They are called phasers because they mark a change in the phase
-# of a program. For example, when the program is compiled, a for loop runs,
-# you leave a block, or an exception gets thrown. (`CATCH` is actually a phaser !)
-# Some of them can be used for their return values, some of them can't
-# (those that can have a "[*]" in the beginning of their explanation text).
-# Let's have a look !
+## Phasers in Perl 6 are blocks that happen at determined points of time in your
+## program. They are called phasers because they mark a change in the phase
+## of a program. For example, when the program is compiled, a for loop runs,
+## you leave a block, or an exception gets thrown.
+## (`CATCH` is actually a phaser!)
+## Some of them can be used for their return values, some of them can't
+## (those that can have a "[*]" in the beginning of their explanation text).
+## Let's have a look !
## * Compile-time phasers
BEGIN { say "[*] Runs at compile time, as soon as possible, only once" }
@@ -1105,7 +1111,8 @@ PRE {
say "If this block doesn't return a truthy value,
an exception of type X::Phaser::PrePost is thrown.";
}
-# example:
+
+## example:
for 0..2 {
PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
}
@@ -1122,8 +1129,10 @@ for 0..2 {
## * Block/exceptions phasers
sub {
- KEEP { say "Runs when you exit a block successfully (without throwing an exception)" }
- UNDO { say "Runs when you exit a block unsuccessfully (by throwing an exception)" }
+ KEEP { say "Runs when you exit a block successfully
+ (without throwing an exception)" }
+ UNDO { say "Runs when you exit a block unsuccessfully
+ (by throwing an exception)" }
}
## * Loop phasers
@@ -1136,10 +1145,10 @@ for ^5 {
## * Role/class phasers
COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" }
-# They allow for cute tricks or clever code ...:
+## They allow for cute tricks or clever code ...:
say "This code took " ~ (time - CHECK time) ~ "s to compile";
-# ... or clever organization:
+## ... or clever organization:
sub do-db-stuff {
$db.start-transaction; # start a new transaction
KEEP $db.commit; # commit the transaction if all went well
@@ -1150,29 +1159,29 @@ sub do-db-stuff {
## Statement prefixes
```perl6
-# Those act a bit like phasers: they affect the behavior of the following code.
-# Though, they run in-line with the executable code, so they're in lowercase.
-# (`try` and `start` are theoretically in that list, but explained somewhere else)
-# Note: all of these (except start) don't need explicit brackets `{` and `}`.
-
-# - `do` (that you already saw) - runs a block or a statement as a term
-# You can't normally use a statement as a value (or "term"):
-#
-# my $value = if True { 1 } # `if` is a statement - parse error
-#
-# This works:
+## Those act a bit like phasers: they affect the behavior of the following code.
+## Though, they run in-line with the executable code, so they're in lowercase.
+## (`try` and `start` are theoretically in that list, but explained elsewhere)
+## Note: all of these (except start) don't need explicit brackets `{` and `}`.
+
+## - `do` (that you already saw) - runs a block or a statement as a term
+## You can't normally use a statement as a value (or "term"):
+##
+## my $value = if True { 1 } # `if` is a statement - parse error
+##
+## This works:
my $a = do if True { 5 } # with `do`, `if` is now a term.
-# - `once` - Makes sure a piece of code only runs once
+## - `once` - Makes sure a piece of code only runs once
for ^5 { once say 1 }; #=> 1
# Only prints ... once.
-# Like `state`, they're cloned per-scope
+## Like `state`, they're cloned per-scope
for ^5 { sub { once say 1 }() } #=> 1 1 1 1 1
# Prints once per lexical scope
-# - `gather` - Co-routine thread
-# Gather allows you to `take` several values in an array,
-# much like `do`, but allows you to take any expression.
+## - `gather` - Co-routine thread
+## Gather allows you to `take` several values in an array,
+## much like `do`, but allows you to take any expression.
say gather for ^5 {
take $_ * 3 - 1;
take $_ * 3 + 1;
@@ -1183,41 +1192,43 @@ say join ',', gather if False {
take 3;
} # Doesn't print anything.
-# - `eager` - Evaluate statement eagerly (forces eager context)
-# Don't try this at home:
-#
-# eager 1..*; # this will probably hang for a while (and might crash ...).
-#
-# But consider:
+## - `eager` - Evaluate statement eagerly (forces eager context)
+## Don't try this at home:
+##
+## eager 1..*; # this will probably hang for a while (and might crash ...).
+##
+## But consider:
constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything
-# versus:
+
+## versus:
constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2
```
## Iterables
```perl6
-# Iterables are objects that can be iterated similar to the `for` construct
-# `flat`, flattens iterables:
+## Iterables are objects that can be iterated similar to the `for` construct
+## `flat`, flattens iterables:
say (1, 10, (20, 10) ); #> (1 10 (20 10)) Notice how grouping is maintained
say (1, 10, (20, 10) ).flat; #> (1 10 20 10) Now the iterable is flat
-# - `lazy` - Defer actual evaluation until value is fetched (forces lazy context)
+## - `lazy` - Defer actual evaluation until value is fetched
+## (forces lazy context)
my @lazy-array = (1..100).lazy;
say @lazy-array.is-lazy; #> True # Check for laziness with the `is-lazy` method.
say @lazy-array; #> [...] List has not been iterated on!
-my @lazy-array { .print }; # This works and will only do as much work as is
-# needed.
+my @lazy-array { .print }; # This works and will only do as much work as
+ # is needed.
[//]: # ( TODO explain that gather/take and map are all lazy)
-# - `sink` - An `eager` that discards the results (forces sink context)
+## - `sink` - An `eager` that discards the results (forces sink context)
constant nilthingie = sink for ^3 { .say } #=> 0 1 2
say nilthingie.perl; #=> Nil
-# - `quietly` blocks will suppress warnings:
+## - `quietly` blocks will suppress warnings:
quietly { warn 'This is a warning!' }; #=> No output
-# - `contend` - Attempts side effects under STM
-# Not yet implemented !
+## - `contend` - Attempts side effects under STM
+## Not yet implemented !
```
## More operators thingies !
@@ -1225,18 +1236,18 @@ quietly { warn 'This is a warning!' }; #=> No output
```perl6
## Everybody loves operators ! Let's get more of them
-# The precedence list can be found here:
-# https://docs.perl6.org/language/operators#Operator_Precedence
-# But first, we need a little explanation about associativity:
+## The precedence list can be found here:
+## https://docs.perl6.org/language/operators#Operator_Precedence
+## But first, we need a little explanation about associativity:
-# * Binary operators:
+## * Binary operators:
$a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c`
$a ! $b ! $c; # with a right-associative `!`, this is `$a ! ($b ! $c)`
$a ! $b ! $c; # with a non-associative `!`, this is illegal
$a ! $b ! $c; # with a chain-associative `!`, this is `($a ! $b) and ($b ! $c)`
$a ! $b ! $c; # with a list-associative `!`, this is `infix:<>`
-# * Unary operators:
+## * Unary operators:
!$a! # with left-associative `!`, this is `(!$a)!`
!$a! # with right-associative `!`, this is `!($a!)`
!$a! # with non-associative `!`, this is illegal
@@ -1245,12 +1256,12 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>`
### Create your own operators !
```perl6
-# Okay, you've been reading all of that, so I guess I should try
-# to show you something exciting.
-# I'll tell you a little secret (or not-so-secret):
-# In Perl 6, all operators are actually just funny-looking subroutines.
+## Okay, you've been reading all of that, so I guess I should try
+## to show you something exciting.
+## I'll tell you a little secret (or not-so-secret):
+## In Perl 6, all operators are actually just funny-looking subroutines.
-# You can declare an operator just like you declare a sub:
+## You can declare an operator just like you declare a sub:
sub prefix:<win>($winner) { # refer to the operator categories
# (yes, it's the "words operator" `<>`)
say "$winner Won !";
@@ -1258,7 +1269,7 @@ sub prefix:<win>($winner) { # refer to the operator categories
win "The King"; #=> The King Won !
# (prefix is before)
-# you can still call the sub with its "full name"
+## you can still call the sub with its "full name":
say prefix:<!>(True); #=> False
sub postfix:<!>(Int $n) {
@@ -1281,7 +1292,7 @@ sub infix:<times>(Int $n, Block $r) { # infix in the middle
# You're very recommended to put spaces
# around your infix operator calls.
-# For circumfix and post-circumfix ones
+## For circumfix and post-circumfix ones
sub circumfix:<[ ]>(Int $n) {
$n ** $n
}
@@ -1289,95 +1300,96 @@ say [5]; #=> 3125
# circumfix is around. Again, no whitespace.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
- # post-circumfix is
- # "after a term, around something"
+ ## post-circumfix is
+ ## "after a term, around something"
$s.substr($idx, 1);
}
say "abc"{1}; #=> b
# after the term `"abc"`, and around the index (1)
-# This really means a lot -- because everything in Perl 6 uses this.
-# For example, to delete a key from a hash, you use the `:delete` adverb
-# (a simple named argument underneath):
+## This really means a lot -- because everything in Perl 6 uses this.
+## For example, to delete a key from a hash, you use the `:delete` adverb
+## (a simple named argument underneath):
%h{$key}:delete;
-# equivalent to:
+## equivalent to:
postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)
-# It's *all* using the same building blocks!
-# Syntactic categories (prefix infix ...), named arguments (adverbs), ...,
-# - used to build the language - are available to you.
-# (you are, obviously, recommended against making an operator out of
-# *everything* -- with great power comes great responsibility)
+## It's *all* using the same building blocks!
+## Syntactic categories (prefix infix ...), named arguments (adverbs), ...,
+## - used to build the language - are available to you.
+## (you are, obviously, recommended against making an operator out of
+## *everything* -- with great power comes great responsibility)
```
### Meta operators !
```perl6
-# Oh boy, get ready. Get ready, because we're delving deep
-# into the rabbit's hole, and you probably won't want to go
-# back to other languages after reading that.
-# (I'm guessing you don't want to already at that point).
-# Meta-operators, as their name suggests, are *composed* operators.
-# Basically, they're operators that apply another operator.
+## Oh boy, get ready. Get ready, because we're delving deep
+## into the rabbit's hole, and you probably won't want to go
+## back to other languages after reading that.
+## (I'm guessing you don't want to already at that point).
+## Meta-operators, as their name suggests, are *composed* operators.
+## Basically, they're operators that apply another operator.
## * Reduce meta-operator
-# It's a prefix meta-operator that takes a binary function and
-# one or many lists. If it doesn't get passed any argument,
-# it either returns a "default value" for this operator
-# (a meaningless value) or `Any` if there's none (examples below).
-#
-# Otherwise, it pops an element from the list(s) one at a time, and applies
-# the binary function to the last result (or the list's first element)
-# and the popped element.
-#
-# To sum a list, you could use the reduce meta-operator with `+`, i.e.:
+## It's a prefix meta-operator that takes a binary function and
+## one or many lists. If it doesn't get passed any argument,
+## it either returns a "default value" for this operator
+## (a meaningless value) or `Any` if there's none (examples below).
+##
+## Otherwise, it pops an element from the list(s) one at a time, and applies
+## the binary function to the last result (or the list's first element)
+## and the popped element.
+##
+## To sum a list, you could use the reduce meta-operator with `+`, i.e.:
say [+] 1, 2, 3; #=> 6
-# equivalent to `(1+2)+3`
+## equivalent to `(1+2)+3`
+
say [*] 1..5; #=> 120
-# equivalent to `((((1*2)*3)*4)*5)`.
+## equivalent to `((((1*2)*3)*4)*5)`.
-# You can reduce with any operator, not just with mathematical ones.
-# For example, you could reduce with `//` to get
-# the first defined element of a list:
+## You can reduce with any operator, not just with mathematical ones.
+## For example, you could reduce with `//` to get
+## the first defined element of a list:
say [//] Nil, Any, False, 1, 5; #=> False
# (Falsey, but still defined)
-
-# Default value examples:
+## Default value examples:
say [*] (); #=> 1
say [+] (); #=> 0
# meaningless values, since N*1=N and N+0=N.
say [//]; #=> (Any)
# There's no "default value" for `//`.
-# You can also call it with a function you made up, using double brackets:
+## You can also call it with a function you made up, using double brackets:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * Zip meta-operator
-# This one is an infix meta-operator than also can be used as a "normal"
-# operator. It takes an optional binary function (by default, it just creates
-# a pair), and will pop one value off of each array and call its binary function
-# on these until it runs out of elements. It returns an array with all of these
-# new elements.
-(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array
+## This one is an infix meta-operator that also can be used as a "normal"
+## operator. It takes an optional binary function (by default, it just creates
+## a pair), and will pop one value off of each array and call its binary
+## function on these until it runs out of elements. It returns an array with
+## all of these new elements.
+(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function
+ # makes an array.
1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function
-# Since `Z` is list-associative (see the list above),
-# you can use it on more than one list
+## Since `Z` is list-associative (see the list above),
+## you can use it on more than one list
(True, False) Z|| (False, False) Z|| (False, False); # (True, False)
-# And, as it turns out, you can also use the reduce meta-operator with it:
+## And, as it turns out, you can also use the reduce meta-operator with it:
[Z||] (True, False), (False, False), (False, False); # (True, False)
## And to end the operator list:
## * Sequence operator
-# The sequence operator is one of Perl 6's most powerful features:
-# it's composed of first, on the left, the list you want Perl 6 to deduce from
-# (and might include a closure), and on the right, a value or the predicate
-# that says when to stop (or Whatever for a lazy infinite list).
+## The sequence operator is one of Perl 6's most powerful features:
+## it's composed of first, on the left, the list you want Perl 6 to deduce from
+## (and might include a closure), and on the right, a value or the predicate
+## that says when to stop (or Whatever for a lazy infinite list).
my @list = 1, 2, 3 ... 10; # basic deducing
#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end
my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element
@@ -1390,175 +1402,189 @@ my @fib = 1, 1, *+* ... *; # lazy infinite list of fibonacci series,
# computed using a closure!
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above)
my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above)
-# $a and $b will always take the previous values, meaning here
-# they'll start with $a = 1 and $b = 1 (values we set by hand).
-# then $a = 1 and $b = 2 (result from previous $a+$b), and so on.
+## $a and $b will always take the previous values, meaning here
+## they'll start with $a = 1 and $b = 1 (values we set by hand).
+## then $a = 1 and $b = 2 (result from previous $a+$b), and so on.
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
# (using a range as the index)
-# Note : as for ranges, once reified, elements aren't re-calculated.
-# That's why `@primes[^100]` will take a long time the first time you print
-# it, then be instant.
+## Note : as for ranges, once reified, elements aren't re-calculated.
+## That's why `@primes[^100]` will take a long time the first time you print
+## it, then be instant.
```
## Regular Expressions
```perl6
-# I'm sure a lot of you have been waiting for this one.
-# Well, now that you know a good deal of Perl 6 already, we can get started.
-# First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps).
-#
-# IMPORTANT: Don't skip them because you know PCRE. They're different.
-# Some things are the same (like `?`, `+`, and `*`),
-# but sometimes the semantics change (`|`).
-# Make sure you read carefully, because you might trip over a new behavior.
-#
-# Perl 6 has many features related to RegExps. After all, Rakudo parses itself.
-# We're first going to look at the syntax itself,
-# then talk about grammars (PEG-like), differences between
-# `token`, `regex` and `rule` declarators, and some more.
-# Side note: you still have access to PCRE regexps using the `:P5` modifier.
-# (we won't be discussing this in this tutorial, however)
-#
-# In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars").
-# The pecking order for ambiguous parses is determined by a multi-level
-# tie-breaking test:
-# - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions)
-# - Longest literal prefix. `food\w*` beats `foo\w*` (by 1)
-# - Declaration from most-derived to less derived grammars
-# (grammars are actually classes)
-# - Earliest declaration wins
+## I'm sure a lot of you have been waiting for this one.
+## Well, now that you know a good deal of Perl 6 already, we can get started.
+## First off, you'll have to forget about "PCRE regexps" (perl-compatible
+## regexps).
+##
+## IMPORTANT: Don't skip them because you know PCRE. They're different.
+## Some things are the same (like `?`, `+`, and `*`),
+## but sometimes the semantics change (`|`).
+## Make sure you read carefully, because you might trip over a new behavior.
+##
+## Perl 6 has many features related to RegExps. After all, Rakudo parses itself.
+## We're first going to look at the syntax itself,
+## then talk about grammars (PEG-like), differences between
+## `token`, `regex` and `rule` declarators, and some more.
+## Side note: you still have access to PCRE regexps using the `:P5` modifier.
+## (we won't be discussing this in this tutorial, however)
+##
+## In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars").
+## The pecking order for ambiguous parses is determined by a multi-level
+## tie-breaking test:
+## - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions)
+## - Longest literal prefix. `food\w*` beats `foo\w*` (by 1)
+## - Declaration from most-derived to less derived grammars
+## (grammars are actually classes)
+## - Earliest declaration wins
say so 'a' ~~ /a/; #=> True
say so 'a' ~~ / a /; #=> True # More readable with some spaces!
-# In all our examples, we're going to use the smart-matching operator against
-# a regexp. We're converting the result using `so`, but in fact, it's
-# returning a `Match` object. They know how to respond to list indexing,
-# hash indexing, and return the matched string.
-# The results of the match are available as `$/` (implicitly lexically-scoped).
-# You can also use the capture variables which start at 0:
-# `$0`, `$1', `$2`...
-#
-# You can also note that `~~` does not perform start/end checking
-# (meaning the regexp can be matched with just one char of the string),
-# we're going to explain later how you can do it.
-
-# In Perl 6, you can have any alphanumeric as a literal,
-# everything else has to be escaped, using a backslash or quotes.
-say so 'a|b' ~~ / a '|' b /; # `True`. Wouldn't mean the same if `|` wasn't escaped
-say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it.
-
-# The whitespace in a regexp is actually not significant,
-# unless you use the `:s` (`:sigspace`, significant space) adverb.
+## In all our examples, we're going to use the smart-matching operator against
+## a regexp. We're converting the result using `so`, but in fact, it's
+## returning a `Match` object. They know how to respond to list indexing,
+## hash indexing, and return the matched string.
+## The results of the match are available as `$/` (implicitly lexically-scoped).
+## You can also use the capture variables which start at 0:
+## `$0`, `$1', `$2`...
+##
+## You can also note that `~~` does not perform start/end checking
+## (meaning the regexp can be matched with just one char of the string),
+## we're going to explain later how you can do it.
+
+## In Perl 6, you can have any alphanumeric as a literal,
+## everything else has to be escaped, using a backslash or quotes.
+say so 'a|b' ~~ / a '|' b /; # `True`. Wouldn't mean the same if `|` wasn't
+ # escaped
+say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it.
+
+## The whitespace in a regexp is actually not significant,
+## unless you use the `:s` (`:sigspace`, significant space) adverb.
say so 'a b c' ~~ / a b c /; #> `False`. Space is not significant here
say so 'a b c' ~~ /:s a b c /; #> `True`. We added the modifier `:s` here.
-# If we use only one space between strings in a regex, Perl 6 will warn us:
-say so 'a b c' ~~ / a b c /; #> 'False' #> Space is not significant here; please
-# use quotes or :s (:sigspace) modifier (or, to suppress this warning, omit the
-# space, or otherwise change the spacing)
-# To fix this and make the spaces less ambiguous, either use at least two
-# spaces between strings or use the `:s` adverb.
-
-# As we saw before, we can embed the `:s` inside the slash delimiters, but we can
-# also put it outside of them if we specify `m` for 'match':
+## If we use only one space between strings in a regex, Perl 6 will warn us:
+say so 'a b c' ~~ / a b c /; #> 'False' #> Space is not significant here;
+## please use quotes or :s (:sigspace) modifier (or, to suppress this warning,
+## omit the space, or otherwise change the spacing)
+## To fix this and make the spaces less ambiguous, either use at least two
+## spaces between strings or use the `:s` adverb.
+
+## As we saw before, we can embed the `:s` inside the slash delimiters, but we
+## can also put it outside of them if we specify `m` for 'match':
say so 'a b c' ~~ m:s/a b c/; #> `True`
-# By using `m` to specify 'match' we can also use delimiters other than slashes:
+## By using `m` to specify 'match', we can also use delimiters other
+## than slashes:
say so 'abc' ~~ m{a b c}; #> `True`
-# Use the :i adverb to specify case insensitivity:
+
+## Use the :i adverb to specify case insensitivity:
say so 'ABC' ~~ m:i{a b c}; #> `True`
-# It is, however, important as for how modifiers (that you're gonna see just below)
-# are applied ...
+
+## It is, however, important as for how modifiers (that you're gonna see just
+## below) are applied ...
## Quantifying - `?`, `+`, `*` and `**`.
-# - `?` - 0 or 1
+## - `?` - 0 or 1
so 'ac' ~~ / a b c /; # `False`
so 'ac' ~~ / a b? c /; # `True`, the "b" matched 0 times.
so 'abc' ~~ / a b? c /; # `True`, the "b" matched 1 time.
-# ... As you read just before, whitespace is important because it determines
-# which part of the regexp is the target of the modifier:
+## ... As you read just before, whitespace is important because it determines
+## which part of the regexp is the target of the modifier:
so 'def' ~~ / a b c? /; # `False`. Only the `c` is optional
so 'def' ~~ / a b? c /; # `False`. Whitespace is not significant
so 'def' ~~ / 'abc'? /; # `True`. The whole "abc" group is optional.
-# Here (and below) the quantifier applies only to the `b`
+## Here (and below) the quantifier applies only to the `b`
-# - `+` - 1 or more
+## - `+` - 1 or more
so 'ac' ~~ / a b+ c /; # `False`; `+` wants at least one matching
so 'abc' ~~ / a b+ c /; # `True`; one is enough
so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
-# - `*` - 0 or more
+## - `*` - 0 or more
so 'ac' ~~ / a b* c /; # `True`, they're all optional.
so 'abc' ~~ / a b* c /; # `True`
so 'abbbbc' ~~ / a b* c /; # `True`
so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
-# - `**` - (Unbound) Quantifier
-# If you squint hard enough, you might understand
-# why exponentation is used for quantity.
+## - `**` - (Unbound) Quantifier
+## If you squint hard enough, you might understand
+## why exponentation is used for quantity.
so 'abc' ~~ / a b**1 c /; # `True` (exactly one time)
so 'abc' ~~ / a b**1..3 c /; # `True` (one to three times)
so 'abbbc' ~~ / a b**1..3 c /; # `True`
so 'abbbbbbc' ~~ / a b**1..3 c /; # `False` (too much)
so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (infinite ranges are okay)
-# - `<[]>` - Character classes
-# Character classes are the equivalent of PCRE's `[]` classes, but
-# they use a more perl6-ish syntax:
+## - `<[]>` - Character classes
+## Character classes are the equivalent of PCRE's `[]` classes, but
+## they use a more perl6-ish syntax:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
-# You can use ranges:
+
+## You can use ranges:
say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae'
-# Just like in normal regexes, if you want to use a special character, escape it
-# (the last one is escaping a space)
+
+## Just like in normal regexes, if you want to use a special character,
+## escape it (the last one is escaping a space)
say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !'
-# You'll get a warning if you put duplicate names
-# (which has the nice effect of catching the wrote quoting:)
-'he he' ~~ / <[ h e ' ' ]> /; # Warns "Repeated characters found in characters class"
-# You can also negate them ... (equivalent to `[^]` in PCRE)
+## You'll get a warning if you put duplicate names
+## (which has the nice effect of catching the wrote quoting:)
+'he he' ~~ / <[ h e ' ' ]> /; # Warns "Repeated characters found in characters
+ # class"
+
+## You can also negate them ... (equivalent to `[^]` in PCRE)
so 'foo' ~~ / <-[ f o ]> + /; # False
-# ... and compose them: :
-so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (any letter except f and o)
-so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letter except f and o)
-so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left part)
+## ... and compose them: :
+so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (any letter except f and o)
+so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letter except f and o)
+so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the
+ # left part)
```
### Grouping and capturing
```perl6
-# Group: you can group parts of your regexp with `[]`.
-# These groups are *not* captured (like PCRE's `(?:)`).
+## Group: you can group parts of your regexp with `[]`.
+## These groups are *not* captured (like PCRE's `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
-# The previous line returns `True`.
-# We match the "012" 1 or more time (the `+` was applied to the group).
-
-# But this does not go far enough, because we can't actually get back what
-# we matched.
-# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
-
-# So, starting with the grouping explanations.
-# As we said before, our `Match` object is available as `$/`:
-say $/; # Will print some weird stuff (we'll explain) (or "Nil" if nothing matched).
-
-# As we also said before, it has array indexing:
+## The previous line returns `True`.
+## We match the "012" 1 or more time (the `+` was applied to the group).
+
+## But this does not go far enough, because we can't actually get back what
+## we matched.
+## Capture: We can actually *capture* the results of the regexp,
+## using parentheses.
+so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so`
+ # here, `$/` below)
+
+## So, starting with the grouping explanations.
+## As we said before, our `Match` object is available as `$/`:
+say $/; # Will print some weird stuff (we'll explain) (or "Nil" if
+ # nothing matched).
+
+## As we also said before, it has array indexing:
say $/[0]; #=> 「ABC」 「ABC」
# These weird brackets are `Match` objects.
# Here, we have an array of these.
say $0; # The same as above.
-# Our capture is `$0` because it's the first and only one capture in the regexp.
-# You might be wondering why it's an array, and the answer is simple:
-# Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array
-# IFF it can have more than one element
-# (so, with `*`, `+` and `**` (whatever the operands), but not with `?`).
-# Let's use examples to see that:
+## Our capture is `$0` because it's the first and only one capture in the
+## regexp. You might be wondering why it's an array, and the answer is simple:
+## Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array
+## IFF it can have more than one element
+## (so, with `*`, `+` and `**` (whatever the operands), but not with `?`).
+## Let's use examples to see that:
-# Note: We quoted A B C to demonstrate that the whitespace between them isn't significant.
-# If we want the whitespace to *be* significant there, we can use the :sigspace modifier.
+## Note: We quoted A B C to demonstrate that the whitespace between them isn't
+## significant. If we want the whitespace to *be* significant there, we
+## can use the :sigspace modifier.
so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # `True`
say $/[0]; #=> 「ABC」
say $0.WHAT; #=> (Match)
@@ -1571,16 +1597,16 @@ say $0.WHAT; #=> (Array)
# A specific quantifier will always capture an Array,
# may it be a range or a specific value (even 1).
-# The captures are indexed per nesting. This means a group in a group will be nested
-# under its parent group: `$/[0][0]`, for this code:
+## The captures are indexed per nesting. This means a group in a group will be
+## nested under its parent group: `$/[0][0]`, for this code:
'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /;
say $/[0].Str; #=> hello~
say $/[0][0].Str; #=> ~
-# This stems from a very simple fact: `$/` does not contain strings, integers or arrays,
-# it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods.
-# (but you can also just use `match<key>` for hash access
-# and `match[idx]` for array access)
+## This stems from a very simple fact: `$/` does not contain strings, integers
+## or arrays, it only contains match objects. These contain the `.list`, `.hash`
+## and `.Str` methods. (but you can also just use `match<key>` for hash access
+## and `match[idx]` for array access)
say $/[0].list.perl; #=> (Match.new(...),).list
# We can see it's a list of Match objects. Those contain
# a bunch of infos: where the match started/ended,
@@ -1588,82 +1614,84 @@ say $/[0].list.perl; #=> (Match.new(...),).list
# You'll see named capture below with grammars.
## Alternatives - the `or` of regexps
-# WARNING: They are DIFFERENT from PCRE regexps.
+## WARNING: They are DIFFERENT from PCRE regexps.
so 'abc' ~~ / a [ b | y ] c /; # `True`. Either "b" or "y".
so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
-# The difference between this `|` and the one you're used to is LTM.
-# LTM means "Longest Token Matching". This means that the engine will always
-# try to match as much as possible in the strng
+## The difference between this `|` and the one you're used to is LTM.
+## LTM means "Longest Token Matching". This means that the engine will always
+## try to match as much as possible in the strng
'foo' ~~ / fo | foo /; # `foo`, because it's longer.
-# To decide which part is the "longest", it first splits the regex in two parts:
-# The "declarative prefix" (the part that can be statically analyzed)
-# and the procedural parts.
-# Declarative prefixes include alternations (`|`), conjunctions (`&`),
-# sub-rule calls (not yet introduced), literals, characters classes and quantifiers.
-# The latter include everything else: back-references, code assertions,
-# and other things that can't traditionnaly be represented by normal regexps.
-#
-# Then, all the alternatives are tried at once, and the longest wins.
-# Examples:
-# DECLARATIVE | PROCEDURAL
+## To decide which part is the "longest", it first splits the regex in
+## two parts:
+## The "declarative prefix" (the part that can be statically analyzed)
+## and the procedural parts.
+## Declarative prefixes include alternations (`|`), conjunctions (`&`),
+## sub-rule calls (not yet introduced), literals, characters classes and
+## quantifiers.
+## The latter include everything else: back-references, code assertions,
+## and other things that can't traditionnaly be represented by normal regexps.
+##
+## Then, all the alternatives are tried at once, and the longest wins.
+## Examples:
+## DECLARATIVE | PROCEDURAL
/ 'foo' \d+ [ <subrule1> || <subrule2> ] /;
-# DECLARATIVE (nested groups are not a problem)
+## DECLARATIVE (nested groups are not a problem)
/ \s* [ \w & b ] [ c | d ] /;
-# However, closures and recursion (of named regexps) are procedural.
-# ... There are also more complicated rules, like specificity
-# (literals win over character classes)
+## However, closures and recursion (of named regexps) are procedural.
+## ... There are also more complicated rules, like specificity
+## (literals win over character classes)
-# Note: the first-matching `or` still exists, but is now spelled `||`
+## Note: the first-matching `or` still exists, but is now spelled `||`
'foo' ~~ / fo || foo /; # `fo` now.
```
## Extra: the MAIN subroutine
```perl6
-# The `MAIN` subroutine is called when you run a Perl 6 file directly.
-# It's very powerful, because Perl 6 actually parses the arguments
-# and pass them as such to the sub. It also handles named argument (`--foo`)
-# and will even go as far as to autogenerate a `--help`
+## The `MAIN` subroutine is called when you run a Perl 6 file directly.
+## It's very powerful, because Perl 6 actually parses the arguments
+## and pass them as such to the sub. It also handles named argument (`--foo`)
+## and will even go as far as to autogenerate a `--help`
sub MAIN($name) { say "Hello, $name !" }
-# This produces:
-# $ perl6 cli.pl
-# Usage:
-# t.pl <name>
-
-# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
-# (using a "Bool" for the named argument so that we can do `--replace`
-# instead of `--replace=1`)
+## This produces:
+## $ perl6 cli.pl
+## Usage:
+## t.pl <name>
+
+## And since it's a regular Perl 6 sub, you can have multi-dispatch:
+## (using a "Bool" for the named argument so that we can do `--replace`
+## instead of `--replace=1`)
subset File of Str where *.IO.d; # convert to IO object to check the file exists
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
-# This produces:
-# $ perl6 cli.pl
-# Usage:
-# t.pl [--replace] add <key> <value>
-# t.pl remove <key>
-# t.pl [--as=<Str>] import (File)
-# As you can see, this is *very* powerful.
-# It even went as far as to show inline the constants.
-# (the type is only displayed if the argument is `$`/is named)
+## This produces:
+## $ perl6 cli.pl
+## Usage:
+## t.pl [--replace] add <key> <value>
+## t.pl remove <key>
+## t.pl [--as=<Str>] import (File)
+## As you can see, this is *very* powerful.
+## It even went as far as to show inline the constants.
+## (the type is only displayed if the argument is `$`/is named)
```
## APPENDIX A:
### List of things
```perl6
-# It's considered by now you know the Perl6 basics.
-# This section is just here to list some common operations,
-# but which are not in the "main part" of the tutorial to bloat it up
+## It's considered by now you know the Perl6 basics.
+## This section is just here to list some common operations,
+## but which are not in the "main part" of the tutorial to bloat it up
## Operators
## * Sort comparison
-# They return one value of the `Order` enum : `Less`, `Same` and `More`
-# (which numerify to -1, 0 or +1).
+## They return one value of the `Order` enum : `Less`, `Same` and `More`
+## (which numerify to -1, 0 or +1).
1 <=> 4; # sort comparison for numerics
'a' leg 'b'; # sort comparison for string
$obj eqv $obj2; # sort comparison using eqv semantics
@@ -1673,20 +1701,20 @@ $obj eqv $obj2; # sort comparison using eqv semantics
'b' after 'a'; # True
## * Short-circuit default operator
-# Like `or` and `||`, but instead returns the first *defined* value :
+## Like `or` and `||`, but instead returns the first *defined* value :
say Any // Nil // 0 // 5; #=> 0
## * Short-circuit exclusive or (XOR)
-# Returns `True` if one (and only one) of its arguments is true
+## Returns `True` if one (and only one) of its arguments is true
say True ^^ False; #=> True
## * Flip Flop
-# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`).
-# are operators that take two predicates to test:
-# They are `False` until their left side returns `True`, then are `True` until
-# their right side returns `True`.
-# Like for ranges, you can exclude the iteration when it became `True`/`False`
-# by using `^` on either side.
-# Let's start with an example :
+## The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`).
+## are operators that take two predicates to test:
+## They are `False` until their left side returns `True`, then are `True` until
+## their right side returns `True`.
+## Like for ranges, you can exclude the iteration when it became `True`/`False`
+## by using `^` on either side.
+## Let's start with an example :
for <well met young hero we shall meet later> {
# by default, `ff`/`fff` smart-match (`~~`) against `$_`:
if 'met' ^ff 'meet' { # Won't enter the if for "met"
@@ -1698,35 +1726,36 @@ for <well met young hero we shall meet later> {
say "This ... probably will never run ...";
}
}
-# This will print "young hero we shall meet" (excluding "met"):
-# the flip-flop will start returning `True` when it first encounters "met"
-# (but will still return `False` for "met" itself, due to the leading `^`
-# on `ff`), until it sees "meet", which is when it'll start returning `False`.
-
-# The difference between `ff` (awk-style) and `fff` (sed-style) is that
-# `ff` will test its right side right when its left side changes to `True`,
-# and can get back to `False` right away
-# (*except* it'll be `True` for the iteration that matched) -
-# While `fff` will wait for the next iteration to
-# try its right side, once its left side changed:
+## This will print "young hero we shall meet" (excluding "met"):
+## the flip-flop will start returning `True` when it first encounters "met"
+## (but will still return `False` for "met" itself, due to the leading `^`
+## on `ff`), until it sees "meet", which is when it'll start returning `False`.
+
+## The difference between `ff` (awk-style) and `fff` (sed-style) is that
+## `ff` will test its right side right when its left side changes to `True`,
+## and can get back to `False` right away
+## (*except* it'll be `True` for the iteration that matched) -
+## While `fff` will wait for the next iteration to
+## try its right side, once its left side changed:
.say if 'B' ff 'B' for <A B C B A>; #=> B B
# because the right-hand-side was tested
# directly (and returned `True`).
- # "B"s are printed since it matched that time
- # (it just went back to `False` right away).
+ # "B"s are printed since it matched that
+ # time (it just went back to `False`
+ # right away).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
# The right-hand-side wasn't tested until
# `$_` became "C"
# (and thus did not match instantly).
-# A flip-flop can change state as many times as needed:
+## 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> {
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
#=> "print it print again"
}
-# you might also use a Whatever Star,
-# which is equivalent to `True` for the left side or `False` for the right:
+## You might also use a Whatever Star,
+## which is equivalent to `True` for the left side or `False` for the right:
for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here
# (sometimes called "superstitious parentheses")
.say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50,
@@ -1734,8 +1763,8 @@ for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here
#=> 60 3 40 60
}
-# You can also use this property to create an `If`
-# that'll not go through the first time :
+## You can also use this property to create an `If`
+## that'll not go through the first time :
for <a b c> {
.say if * ^ff *; # the flip-flop is `True` and never goes back to `False`,
# but the `^` makes it *not run* on the first iteration
@@ -1743,8 +1772,8 @@ for <a b c> {
}
-# - `===` is value identity and uses `.WHICH` on the objects to compare them
-# - `=:=` is container identity and uses `VAR()` on the objects to compare them
+## - `===` is value identity and uses `.WHICH` on the objects to compare them
+## - `=:=` is container identity and uses `VAR()` on the objects to compare them
```
@@ -1760,6 +1789,11 @@ If you want to go further, you can:
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 Perl 6.c was released.
- - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- - Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
+ - Come along on `#perl6` at `irc.freenode.net`. The folks here are
+ always helpful.
+ - Check the [source of Perl 6's functions and
+ classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is
+ mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset
+ easier to implement and optimize).
+ - Read [the language design documents](http://design.perl6.org). They explain
+ P6 from an implementor point-of-view, but it's still very interesting.
diff --git a/prolog.html.markdown b/prolog.html.markdown
index 7a18a144..4f3984c7 100644
--- a/prolog.html.markdown
+++ b/prolog.html.markdown
@@ -104,7 +104,7 @@ magicNumber(42).
?- plus(1, 2, 3). % True
?- plus(1, 2, X). % X = 3 because 1+2 = X.
?- plus(1, X, 3). % X = 2 because 1+X = 3.
-?- plus(X, 2, 3). % X = 1 because X+1 = 3.
+?- plus(X, 2, 3). % X = 1 because X+2 = 3.
?- plus(X, 5, Y). % Error - although this could be solved,
% the number of solutions is infinite,
% which most predicates try to avoid.
@@ -230,14 +230,14 @@ nearby3(X,Y) :- nearby2(X,Y).
% Here is the structured comment declaration for nearby3:
-%% nearby3(+X:Int, +Y:Int) is semidet.
+%% nearby3(+X:Int, +Y:Int) is semideterministic.
%% nearby3(+X:Int, -Y:Int) is multi.
%% nearby3(-X:Int, +Y:Int) is multi.
% For each variable we list a type. The + or - before the variable name
% indicates if the parameter is bound (+) or free (-). The word after
% "is" describes the behaviour of the predicate:
-% semidet - can succeed once or fail
+% semideterministic - can succeed once or fail
% ( Two specific numbers are either nearby or not )
% multi - can succeed multiple times but cannot fail
% ( One number surely has at least 3 nearby numbers )
@@ -267,8 +267,8 @@ character(darthVader). % Creates atom value darthVader
% Note that below, writeln is used instead of print because print is
% intended for debugging.
-%% countTo(+X:Int) is det.
-%% countUpTo(+Value:Int, +Limit:Int) is det.
+%% countTo(+X:Int) is deterministic.
+%% countUpTo(+Value:Int, +Limit:Int) is deterministic.
countTo(X) :- countUpTo(1,X).
countUpTo(Value, Limit) :- Value = Limit, writeln(Value), !.
countUpTo(Value, Limit) :- Value \= Limit, writeln(Value),
@@ -281,7 +281,7 @@ countUpTo(Value, Limit) :- Value \= Limit, writeln(Value),
% IF test. If Value = Limit fails the second declaration is run.
% There is also a more elegant syntax.
-%% countUpTo2(+Value:Int, +Limit:Int) is det.
+%% countUpTo2(+Value:Int, +Limit:Int) is deterministic.
countUpTo2(Value, Limit) :- writeln(Value),
Value = Limit -> true ; (
NextValue is Value+1,
@@ -294,14 +294,14 @@ countUpTo2(Value, Limit) :- writeln(Value),
% called a "failure-driven loop" to do this, but newer ones use a higher
% order function.
-%% countTo2(+X:Int) is det.
+%% countTo2(+X:Int) is deterministic.
countTo2(X) :- forall(between(1,X,Y),writeln(Y)).
?- countTo2(10). % Outputs 1 to 10
% Lists are given in square brackets. Use memberchk to check membership.
% A group is safe if it doesn't include Joker or does include Batman.
-%% safe(Group:list(atom)) is det.
+%% safe(Group:list(atom)) is deterministic.
safe(Group) :- memberchk(joker, Group) -> memberchk(batman, Group) ; true.
?- safe([robin]). % True
diff --git a/pt-br/amd.html.markdown b/pt-br/amd-pt.html.markdown
index 38c1f70f..40c7cd09 100644
--- a/pt-br/amd.html.markdown
+++ b/pt-br/amd-pt.html.markdown
@@ -141,7 +141,7 @@ require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coo
coolLib.facaAlgoDoidoCom(helpers.transform($('#foo')));
});
```
-Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página:
+Apps baseados em `require.js` geralmente terão um único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página:
```html
<!DOCTYPE html>
diff --git a/pt-br/asciidoc-pt.html.markdown b/pt-br/asciidoc-pt.html.markdown
index 1dee31db..b12c0693 100644
--- a/pt-br/asciidoc-pt.html.markdown
+++ b/pt-br/asciidoc-pt.html.markdown
@@ -99,7 +99,7 @@ Para criar uma lista com marcadores use asteriscos.
* baz
```
-Para criar uma lista númerada use pontos.
+Para criar uma lista numerada use pontos.
```
. item 1
diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown
index 2e299d09..aecc2194 100644
--- a/pt-br/asymptotic-notation-pt.html.markdown
+++ b/pt-br/asymptotic-notation-pt.html.markdown
@@ -38,7 +38,7 @@ Na primeira seção desse documento, descrevemos como Notação Assintótica ide
*f*, *n* como o tamanho da entrada e *f(n)* sendo o tempo de execução. Então,
para dado algoritmo *f*, com entrada de tamanho *n*, você terá tempo de execução
*f(n)*. Isto resulta em um gráfico onde a coordernada Y é o tempo de execução
-, a coordernada X representa o tamanho da entrada e os pontos representao o tempo
+, a coordernada X representa o tamanho da entrada e os pontos representam o tempo
de execução para dado tamanho de entrada.
Você pode representar a função, ou o algoritmo, com Notação Assintótica de várias
diff --git a/pt-br/asymptoticnotation-pt.html.markdown b/pt-br/asymptoticnotation-pt.html.markdown
deleted file mode 100644
index c5299a11..00000000
--- a/pt-br/asymptoticnotation-pt.html.markdown
+++ /dev/null
@@ -1,161 +0,0 @@
----
-category: Algorithms & Data Structures
-name: Asymptotic Notation
-contributors:
- - ["Jake Prather", "http://github.com/JakeHP"]
-translators:
- - ["Carolina Knoll", "http://github.com/carolinaknoll"]
-lang: pt-br
----
-
-# Aprenda X em Y minutos
-## Onde X=Notação Assintótica
-
-# Notações Assintóticas
-## O que são?
-
-Notações assintóticas são notações matemáticas que nos permitem analisar tempo de execução
-de um algoritmo, identificando o seu comportamento de acordo como o tamanho de entrada para
-o algoritmo aumenta. Também é conhecido como taxa de "crescimento" de um algoritmo. O algoritmo
-simplesmente se torna incrivelmente lento conforme o seu tamanho aumenta? Será que pode-se na
-maior parte manter o seu tempo de execução rápido mesmo quando o tamanho de entrada aumenta?
-A notação assintótica nos dá a capacidade de responder a essas perguntas.
-
-## Além desta, existem outras alternativas para responder a essas perguntas?
-
-Uma forma seria a de contar o número de operações primitivas em diferentes tamanhos de entrada.
-Embora esta seja uma solução válida, a quantidade de trabalho necessário, mesmo para algoritmos
-simples, não justifica a sua utilização.
-
-Outra maneira é a de medir fisicamente a quantidade de tempo que leva para se executar um algoritmo
-de diferentes tamanhos. No entanto, a precisão e a relatividade (já que tempos obtidos só teriam
-relação à máquina em que eles foram testados) deste método estão ligadas a variáveis ambientais,
-tais como especificações de hardware, poder de processamento, etc.
-
-## Tipos de Notação Assintótica
-
-Na primeira seção deste documento nós descrevemos como uma notação assintótica identifica o comportamento
-de um algoritmo como as alterações de tamanho de entrada (input). Imaginemos um algoritmo como uma função
-f, n como o tamanho da entrada, e f (n) sendo o tempo de execução. Assim, para um determinado algoritmo f,
-com tamanho de entrada n você obtenha algum tempo de execução resultante f (n). Isto resulta num gráfico,
-em que o eixo Y representa o tempo de execução, o eixo X é o tamanho da entrada, e os pontos marcados são
-os resultantes da quantidade de tempo para um dado tamanho de entrada.
-
-Pode-se rotular uma função ou algoritmo com uma notação assintótica de diversas maneiras diferentes.
-Dentre seus exemplos, está descrever um algoritmo pelo seu melhor caso, pior caso, ou caso equivalente.
-O mais comum é o de analisar um algoritmo pelo seu pior caso. Isso porque você normalmente não avaliaria
-pelo melhor caso, já que essas condições não são as que você está planejando. Um bom exemplo disto é o de
-algoritmos de ordenação; especificamente, a adição de elementos a uma estrutura de tipo árvore. O melhor
-caso para a maioria dos algoritmos pode ser tão simples como uma única operação. No entanto, na maioria
-dos casos, o elemento que você está adicionando terá de ser ordenado de forma adequada através da árvore,
-o que poderia significar a análise de um ramo inteiro. Este é o pior caso, e é por ele que precisamos seguir.
-
-### Tipos de funções, limites, e simplificação
-
-```
-Função Logaritmica - log n
-Função Linear - an + b
-Função Quadrática - an^2 + bn + c
-Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde z é uma constante
-Função Exponencial - a^n, onde a é uma constante
-```
-
-Estas são algumas classificações básicas de crescimento de função usados em várias notações. A lista
-começa com a função crescimento mais lento (logarítmica, com tempo de execução mais rápido) e vai até
-a mais rápida (exponencial, com tempo de execução mais lento). Observe que 'n', ou nossa entrada,
-cresce em cada uma dessas funções, e o resultado claramente aumenta muito mais rapidamente em função
-quadrática, polinomial e exponencial, em comparação com a logarítmica e a linear.
-
-Uma observação de boa importância é que, para as notações a serem discutidas, deve-se fazer o melhor
-para utilizar termos mais simples. Isto significa desrespeitar constantes, e simplificar termos de
-ordem, porque, como o tamanho da entrada (ou n no nosso f (n) exemplo) aumenta infinitamente (limites
-matemáticos), os termos em ordens mais baixas e constantes são de pouca ou nenhuma importância. Dito
-isto, se você possui constantes com valor 2^9001, ou alguma outra quantidade ridícula, inimaginável,
-perceberá que a simplificação distorcerá a precisão de sua notação.
-
-Já que nós queremos a forma mais simples, vamos modificar nossas funções um pouco.
-
-```
-Logaritmica - log n
-Linear - n
-Quadrática - n^2
-Polinomial - n^z, onde z é uma constante
-Exponencial - a^n, onde a é uma constante
-```
-
-### O Grande-O
-
-Grande-O, geralmente escrita como O, é uma Notação Assintótica para o pior caso para uma dada função. Digamos
-que `f(n)` é o tempo de execução de seu algoritmo, e `g(n)` é uma complexidade de tempo arbitrário que você está
-tentando se relacionar com o seu algoritmo. `f(n)` será O(g(n)), se, por qualquer constante real c (c > 0),
-`f(n)` <= `c g(n)` para cada tamanho de entrada n (n > 0).
-
-*Exemplo 1*
-
-```
-f(n) = 3log n + 100
-g(n) = log n
-```
-
-É `f(n)` um O(g(n))?
-É 3 `log n + 100` igual a O(log n)?
-Vamos checar na definição de Grande-O.
-
-```
-3log n + 100 <= c * log n
-```
-
-Existe alguma constante c que satisfaça isso para todo n?
-
-```
-3log n + 100 <= 150 * log n, n > 2 (indefinido em n = 1)
-```
-
-Sim! A definição de Grande-O foi satisfeita. Sendo assim, `f(n)` é O(g(n)).
-
-*Exemplo 2*
-
-```
-f(n) = 3 * n^2
-g(n) = n
-```
-
-É `f(n)` um O(g(n))?
-É `3 * n^2` um O(n)?
-Vamos ver na definição de Grande-O.
-
-```
-3 * n^2 <= c * n
-```
-
-Existe alguma constante que satisfaça isso para todo n?
-Não, não existe. `f(n)` NÃO É O(g(n)).
-
-### Grande-Omega
-
-Grande-Omega, comumente escrito como Ω, é uma Notação Assintótica para o melhor caso, ou
-uma taxa de crescimento padrão para uma determinada função.
-
-`f(n)` é Ω(g(n)), se, por qualquer constante c real (c > 0), `f(n)` é >= `c g(n)` para cada
-tamanho de entrada n (n > 0).
-
-Sinta-se livre para pesquisar recursos adicionais e obter mais exemplos sobre este assunto!
-Grande-O é a notação primária utilizada para tempo de execução de algoritmos, de modo geral.
-
-### Notas de Finalização
-
-É complicado exibir este tipo de assunto de forma tão curta, então é definitivamente recomendado
-pesquisar além dos livros e recursos on-line listados. Eles serão capazes de analisar o assunto com
-uma profundidade muito maior, além de ter definições e exemplos. Mais sobre onde X="Algoritmos e
-Estruturas de Dados" está a caminho: Haverá conteúdo focado na análise de exemplos de códigos reais
-em breve.
-
-## Livros
-
-* [Algorithms] (http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
-* [Algorithm Design] (http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
-
-## Recursos Online
-
-* [MIT] (http://web.mit.edu/16.070/www/lecture/big_o.pdf)
-* [KhanAcademy] (https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation)
diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown
new file mode 100644
index 00000000..75b73abe
--- /dev/null
+++ b/pt-br/awk-pt.html.markdown
@@ -0,0 +1,376 @@
+---
+language: awk
+filename: learnawk-pt.awk
+contributors:
+ - ["Marshall Mason", "http://github.com/marshallmason"]
+translators:
+ - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
+lang: pt-br
+
+---
+
+AWK é uma ferramenta padrão em todos os sistemas UNIX compatíveis com POSIX. É
+como um Perl despojado, perfeito para tarefas de processamento de texto e
+outras tarefas de script. Possui uma sintaxe C-like, mas sem ponto e vírgula,
+gerenciamento manual de memória, ou tipagem estática. Destaca-se no
+processamento de texto. Você pode chamá-lo a partir de um shell-script, ou você
+pode usá-lo como uma linguagem de script autônomo.
+
+Por que usar AWK ao invés de Perl? Principalmente porque AWK faz parte do UNIX.
+Você pode sempre contar com ele, enquanto o futuro do Perl é indefinido. AWK é
+também mais fácil de ler que Perl. Para scripts simples de processamento de
+texto, particularmente aqueles que leem arquivos linha por linha e fatiam texto
+por delimitadores, AWK é provavelmente a ferramenta certa para a tarefa.
+
+```awk
+#!/usr/bin/awk -f
+
+# Comentários são assim
+
+# Programas AWK consistem de uma coleção de padrões e ações. O mais
+# importante padrão é chamado BEGIN. Ações estão dentro de blocos
+# entre chaves.
+
+BEGIN {
+
+ # O bloco BEGIN será executado no começo do programa. É onde você coloca
+ # todo código que prepara a execução, antes que você processe qualquer
+ # arquivo de texto. Se você não tem arquivos de texto, então pense no
+ # BEGIN como o ponto principal de entrada.
+
+ # Variáveis são globais. Simplesmente atribua valores ou as use, sem
+ # necessidade de declarar.
+
+ # Operadores são como em C e similares
+ a = count + 1
+ b = count - 1
+ c = count * 1
+ d = count / 1 # divisão inteira
+ e = count % 1 # módulo
+ f = count ^ 1 # exponenciação
+
+ a += 1
+ b -= 1
+ c *= 1
+ d /= 1
+ e %= 1
+ f ^= 1
+
+ # Incrementando e decrementando por um
+ a++
+ b--
+
+ # Como um operador pré-fixado, retorna o valor incrementado
+ ++a
+ --b
+
+ # Perceba, não há pontuação, como ponto-e-vírgula, ao final das declarações
+
+ # Declarações de controle
+ if (count == 0)
+ print "Começando com count em 0"
+ else
+ print "Como é que é?"
+
+ # Ou você pode usar o operador ternário
+ print (count == 0) ? "Começando com count em 0" : "Como é que é?"
+
+ # Blocos multilinhas devem usar chaves
+ while (a < 10) {
+ print "Concatenação de texto é feita" " com uma série" " de"
+ " textos separados por espaço"
+ print a
+
+ a++
+ }
+
+ for (i = 0; i < 10; i++)
+ print "Uma boa opção para um loop de uma linha"
+
+ # Quanto a comparações, eis os padrões:
+ a < b # Menor que
+ a <= b # Menor ou igual a
+ a != b # Não igual
+ a == b # Igual
+ a > b # Maior que
+ a >= b # Maior ou igual a
+
+ # Bem como operadores lógicos
+ a && b # E
+ a || b # OU (inclusivo)
+
+ # Em adição, há o utilíssimo operador para expressões regulares
+ if ("foo" ~ "^fo+$")
+ print "Fooey!"
+ if ("boo" !~ "^fo+$")
+ print "Boo!"
+
+ # Matrizes
+ arr[0] = "foo"
+ arr[1] = "bar"
+ # Infelizmente, não há outra forma para inicializar uma matriz. Apenas
+ # coloque cada valor em uma linha, como mostrado acima.
+
+ # Você também pode ter matrizes associativas
+ assoc["foo"] = "bar"
+ assoc["bar"] = "baz"
+
+ # E matrizes multidimensionais, com algumas limitações que não mencionarei
+ multidim[0,0] = "foo"
+ multidim[0,1] = "bar"
+ multidim[1,0] = "baz"
+ multidim[1,1] = "boo"
+
+ # Você pode testar a pertinência de um elemento em uma matriz
+ if ("foo" in assoc)
+ print "Fooey!"
+
+ # Você pode também usar o operador 'in' para percorrer as chaves de uma
+ # matriz associativa
+ for (key in assoc)
+ print assoc[key]
+
+ # Os argumentos da linha de comando estão em uma matriz especial ARGV
+ for (argnum in ARGV)
+ print ARGV[argnum]
+
+ # Você pode remover elementos de uma matriz
+ # Isso é muito útil para prevenir que o AWK assuma que os argumentos são
+ # arquivo para ele processar
+ delete ARGV[1]
+
+ # A quantidade de argumentos passados está na variável ARGC
+ print ARGC
+
+ # O AWK tem várias funções nativas. Elas estão separadas em três categorias.
+ # Demonstrarei cada uma delas logo mais abaixo.
+
+ return_value = arithmetic_functions(a, b, c)
+ string_functions()
+ io_functions()
+}
+
+# Eis como você deve definir uma função
+function arithmetic_functions(a, b, c, d) {
+
+ # Provavelmente a parte mais irritante do AWK é ele não possuir variáveis
+ # locais. Tudo é global. Para pequenos scripts, isso não é problema, e
+ # pode até mesmo ser considerado útil, mas para grandes scripts, isso pode
+ # ser um problema.
+
+ # Mas há como contornar isso (um hack). Os argumentos de função são locais
+ # para a função e o AWK permite que você defina mais argumentos de função
+ # do que ele precise. Então, coloque a variável local na declaração de
+ # função, como eu fiz acima. Como uma convenção, adicione alguns espaços
+ # extras para distinguir entre parâmetros de função reais e variáveis
+ # locais. Neste exemplo, a, b e c são parâmetros reais, enquanto d é
+ # meramente uma variável local.
+
+ # Agora, serão demonstradas as funções aritméticas
+
+ # Muitas implementações AWK possuem algumas funções trigonométricas padrão
+ localvar = sin(a)
+ localvar = cos(a)
+ localvar = atan2(a, b) # arco-tangente de b / a
+
+ # E conteúdo logarítmico
+ localvar = exp(a)
+ localvar = log(a)
+
+ # Raiz quadrada
+ localvar = sqrt(a)
+
+ # Descartando a parte não inteira de um número em ponto flutuante.
+ localvar = int(5.34) # localvar => 5
+
+ # Números aleatórios
+ srand() # Forneça uma semente como argumento. Por padrão, ele usa a hora atual
+ localvar = rand() # Número aleatório entre 0 e 1.
+
+ # Aqui mostramos como retornar um valor
+ return localvar
+}
+
+function string_functions( localvar, arr) {
+
+ # Sendo o AWK uma linguagem para processamento de texto, ele possui
+ # várias funções para manipulação de texto, muitas das quais
+ # fortemente dependentes de expressões regulares.
+
+ # Procurar e substituir, primeira instância (sub), ou todas (gsub)
+ # Ambas retornam o número de instâncias substituídas
+ localvar = "fooooobar"
+ sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
+ gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+
+ # Localiza um texto que casa com uma expressão regular
+ # index() faz a mesma coisa, mas não permite uma expressão regular
+ match(localvar, "t") # => 4, pois 't' é o quarto carácter
+
+ # Separa por delimitador
+ split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"]
+
+ # Outras coisas úteis
+ sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3"
+ substr("foobar", 2, 3) # => "oob"
+ substr("foobar", 4) # => "bar"
+ length("foo") # => 3
+ tolower("FOO") # => "foo"
+ toupper("foo") # => "FOO"
+}
+
+function io_functions( localvar) {
+
+ # Você já viu como imprimir
+ print "Hello world"
+
+ # Também há o printf
+ printf("%s %d %d %d\n", "Testing", 1, 2, 3)
+
+ # O AWK não disponibiliza manipuladores de arquivo. Ele irá automaticamente
+ # manipular um arquivo quando você fizer algo que precise disso. O texto
+ # que você usou para isso pode ser usado como um manipulador de arquivo,
+ # para propósitos de E/S. Isso faz ele parecer com um shell script:
+
+ print "foobar" >"/tmp/foobar.txt"
+
+ # Agora a string "/tmp/foobar.txt" é um manipulador de arquivos. Você pode
+ # fechá-lo:
+ close("/tmp/foobar.txt")
+
+ # Aqui está como você pode executar alguma coisa no shell
+ system("echo foobar") # => prints foobar
+
+ # Lê uma linha da entrada padrão e armazena em localvar
+ getline localvar
+
+ # Lê uma linha de um pipe
+ "echo foobar" | getline localvar # localvar => "foobar"
+ close("echo foobar")
+
+ # Lê uma linha de um arquivo e armazena em localvar
+ getline localvar <"/tmp/foobar.txt"
+ close("/tmp/foobar.txt")
+}
+
+# Como dito no início, os programas AWK consistem de uma coleção de padrões
+# e ações. Você já viu o padrão BEGIN, o mais importante. Outros padrões são
+# usados apenas se você estiver processando linhas de arquivos ou a entrada
+# padrão.
+
+# Quando você passa argumentos para o AWK, eles são tratados como nomes de
+# arquivos para processar. Todos serão processados, em ordem. Pense nisso como
+# um implícito para loop, iterando sobre as linhas nesses arquivos. Esses
+# padrões e ações são como instruções de mudança dentro do loop.
+
+/^fo+bar$/ {
+
+ # Esta ação será executada para cada linha que corresponda à expressão
+ # regular, / ^ fo + bar $ /, e será ignorada para qualquer linha que não
+ # corresponda. Vamos apenas imprimir a linha:
+
+ print
+
+ # Opa, sem argumento! Isso ocorre pois print tem um argumento padrão: $0.
+ # $0 é o nome da linha atual que está sendo processada. Essa variável é
+ # criada automaticamente para você.
+
+ # Você provavelmente pode adivinhar que existem outras variáveis $. Toda
+ # linha é implicitamente dividida antes de cada ação ser chamada, como
+ # o shell faz. E, como o shell, cada campo pode ser acessado com um sinal
+ # de cifrão
+
+ # Isso irá imprimir o segundo e quarto campos da linha
+ print $2, $4
+
+ # O AWK automaticamente define muitas outras variáveis para ajudar você
+ # a inspecionar processar cada linha. A mais importante delas é NF.
+
+ # Imprime o número de campos da linha atual
+ print NF
+
+ # Imprime o último campo da linha atual
+ print $NF
+}
+
+# Todo padrão é na verdade um teste verdadeiro/falso. A expressão regular no
+# último padrão também é um teste verdadeiro/falso, mas parte dele estava
+# escondido. Se você não informar um texto para testar, AWK assumirá $0,
+# a linha que está atualmente sendo processada. Assim, a versão completa
+# é a seguinte:
+
+$0 ~ /^fo+bar$/ {
+ print "Equivalente ao último padrão"
+}
+
+a > 0 {
+ # Isso será executado uma vez para cada linha, quando a for positivo
+}
+
+# Você entendeu. Processar arquivos de texto, ler uma linha de cada vez, e
+# fazer algo com ela, particularmente dividir com base em um delimitador, é
+# tão comum no UNIX que AWK é uma linguagem de script que faz tudo por você,
+# sem você precisa perguntar. Tudo o que você precisa fazer é escrever os
+# padrões e ações com base no que você espera da entrada, e o que você quer
+# fazer com isso.
+
+# Aqui está um exemplo rápido de um script simples, o tipo de coisa que o AWK
+# é perfeito para fazer. Ele irá ler um nome da entrada padrão e depois
+imprimirá a média de idade de todos com esse primeiro nome. Digamos que você
+forneça como argumento o nome de um arquivo com esses dados:
+
+# Bob Jones 32
+# Jane Doe 22
+# Steve Stevens 83
+# Bob Smith 29
+# Bob Barker 72
+#
+# Eis o script:
+
+BEGIN {
+
+ # Primeiro, pergunte o nome do usuário
+ print "Para qual nome você quer calcular a média de idade?"
+
+ # Pega uma linha da entrada padrão, não dos arquivos indicados na
+ # linha de comando
+ getline name <"/dev/stdin"
+}
+
+# Agora, processa cada linha em que o primeiro nome é o nome informado
+$1 == name {
+
+ # Dentro desse bloco, nós temos acesso a algumas variáveis uteis, que
+ # foram pré-carregadas para nós:
+ # $0 é a linha corrente completa
+ # $3 é o terceiro campo, que é o que nos interessa aqui
+ # NF é a quantidade de campos, que deve ser 3
+ # NR é o número de registros (linhas) lidas até agora
+ # FILENAME é o nome do arquivo sendo processado
+ # FS é o delimitador em uso, que é " " aqui
+ # ...etc. Há muito mais, documentadas no manual.
+
+ # Mantenha um registro do total e da quantidade de linhas encontradas
+ sum += $3
+ nlines++
+}
+
+# Outro padrão especial é chamado END. Ele será executado após o processamento
+# de todos os arquivos de texto. Ao contrário de BEGIN, ele só será executado
+# se você tiver dado a ele dados para processar. Ele será executado depois de
+# todos os arquivos terem sido lidos e processados de acordo com as regras e
+# ações que você forneceu. O objetivo disso em geral é produzir algum tipo de
+# relatório final, ou fazer algo com o agregado dos dados acumulados ao longo
+# do script.
+
+END {
+ if (nlines)
+ print "A média da idade para " name " é " sum / nlines
+}
+
+```
+Leituras adicionais (em inglês):
+
+* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
+* [Awk man page](https://linux.die.net/man/1/awk)
+* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux.
diff --git a/pt-br/bf.html.markdown b/pt-br/bf-pt.html.markdown
index 52a5269e..52a5269e 100644
--- a/pt-br/bf.html.markdown
+++ b/pt-br/bf-pt.html.markdown
diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown
index c1cfbbb1..cd4adde7 100644
--- a/pt-br/c++-pt.html.markdown
+++ b/pt-br/c++-pt.html.markdown
@@ -18,9 +18,9 @@ foi concebida para
- suportar programação orientada a objetos
- suportar programação genérica
-Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais
-recentes, C++ é amplamente utilizado porque compila para instruções nativas que
-podem ser executadas diretamente pelo processador e oferece um controlo rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os
+Embora sua sintaxe possa ser mais difícil ou complexa do que as linguagens mais
+recentes, C++ é amplamente utilizada porque compila para instruções nativas que
+podem ser executadas diretamente pelo processador e oferece um controle rígido sobre o hardware (como C), enquanto oferece recursos de alto nível, como os
genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade
faz C++ uma das linguagens de programação mais utilizadas.
@@ -40,10 +40,10 @@ faz C++ uma das linguagens de programação mais utilizadas.
int main(int argc, char** argv)
{
- // Argumentos de linha de comando são passados em pelo argc e argv da mesma
+ // Argumentos de linha de comando são passados para argc e argv da mesma
// forma que eles estão em C.
// argc indica o número de argumentos,
- // e argv é um array de strings, feito C (char*) representado os argumentos
+ // e argv é um array de strings, feito C (char*) representando os argumentos
// O primeiro argumento é o nome pelo qual o programa foi chamado.
// argc e argv pode ser omitido se você não se importa com argumentos,
// dando a assinatura da função de int main()
@@ -274,7 +274,7 @@ public:
void setWeight(int dogsWeight);
- // Funções que não modificam o estado do objecto devem ser marcadas como
+ // Funções que não modificam o estado do objeto devem ser marcadas como
// const. Isso permite que você chamá-los se for dada uma referência const
// para o objeto. Além disso, observe as funções devem ser explicitamente
// declarados como _virtual_, a fim de ser substituídas em classes
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 6e7aa8c2..0dca7ab0 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -182,7 +182,7 @@ int main() {
int a, b, c;
a = b = c = 0;
- // Aritimética é óbvia
+ // Aritmética é óbvia
i1 + i2; // => 3
i2 - i1; // => 1
i2 * i1; // => 2
@@ -191,7 +191,7 @@ int main() {
f1 / f2; // => 0.5, mais ou menos epsilon
// Números e cálculos de ponto flutuante não são exatos
- // Modulo também existe
+ // Módulo também existe
11 % 3; // => 2
// Operadores de comparação provavelmente são familiares,
diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp-pt.html.markdown
index 547f4817..b6e95d36 100644
--- a/pt-br/csharp.html.markdown
+++ b/pt-br/csharp-pt.html.markdown
@@ -6,23 +6,23 @@ contributors:
lang: pt-br
---
-C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework.
+C# é uma linguagem elegante, altamente tipada e orientada a objetos que permite aos desenvolvedores criar uma variedade de aplicações seguras e robustas que são executadas no .NET Framework.
-[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx)
+[Leia mais aqui.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx)
```c#
-// Comentário de linha única começa com //
+// Comentários de linha única começam com //
/*
-Múltipas linhas é desta forma
+Comentários de múltiplas linhas são desta forma
*/
/// <summary>
-/// Esta é uma documentação comentário XML que pode ser usado para gerar externo
-/// documentação ou fornecer ajuda de contexto dentro de um IDE
+/// Este é um comentário de documentação XML que pode ser usado para gerar documentação
+/// externa ou para fornecer ajuda de contexto dentro de uma IDE
/// </summary>
//public void MethodOrClassOrOtherWithParsableHelp() {}
-// Especificar qual namespace seu código irá usar
-// Os namespaces a seguir são padrões do .NET Framework Class Library
+// Especifica os namespaces que o código irá usar
+// Os namespaces a seguir são padrões da biblioteca de classes do .NET Framework
using System;
using System.Collections.Generic;
using System.Dynamic;
@@ -33,11 +33,11 @@ using System.IO;
// Mas este aqui não é :
using System.Data.Entity;
-// Para que consiga utiliza-lo, você precisa adicionar novas referências
+// Para que consiga utilizá-lo, você precisa adicionar novas referências
// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework`
-// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos"
-// Usando este código a partir de outra arquivo de origem: using Learning.CSharp;
+// Namespaces são escopos definidos para organizar o código em "pacotes" ou "módulos"
+// Usando este código a partir de outro arquivo de origem: using Learning.CSharp;
namespace Learning.CSharp
{
// Cada .cs deve conter uma classe com o mesmo nome do arquivo
@@ -762,7 +762,7 @@ on a new line! ""Wow!"", the masses cried";
}
}
- //Method to display the attribute values of this Object.
+ //Método para exibir os valores dos atributos deste objeto.
public virtual string Info()
{
return "Gear: " + Gear +
@@ -784,13 +784,13 @@ on a new line! ""Wow!"", the masses cried";
} // end class Bicycle
- // PennyFarthing is a subclass of Bicycle
+ // PennyFarthing é uma subclasse de Bicycle
class PennyFarthing : Bicycle
{
- // (Penny Farthings are those bicycles with the big front wheel.
- // They have no gears.)
+ // (Penny Farthings são aquelas bicicletas com uma grande roda frontal.
+ // Elas não tem correias.)
- // calling parent constructor
+ // chamando construtor pai
public PennyFarthing(int startCadence, int startSpeed) :
base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
{
@@ -823,10 +823,10 @@ on a new line! ""Wow!"", the masses cried";
}
}
- // Interfaces only contain signatures of the members, without the implementation.
+ // Interfaces contêm apenas as assinaturas dos membros, sem a implementação.
interface IJumpable
{
- void Jump(int meters); // all interface members are implicitly public
+ void Jump(int meters); // todos os membros da interface são implicitamente públicos
}
interface IBreakable
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index b1fbd961..956b3614 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -25,7 +25,7 @@ O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais.
```css
/* Comentários aparecem dentro do slash-asterisk, tal como esta linha!
- não há "comentários de uma linha"; este é o único estilo de comentário * /
+ Não há "comentários de uma linha"; este é o único estilo de comentário * /
/* ####################
## SELETORES
diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown
index 8de9bee6..84b055d9 100644
--- a/pt-br/dynamic-programming-pt.html.markdown
+++ b/pt-br/dynamic-programming-pt.html.markdown
@@ -22,16 +22,16 @@ Sempre se lembre!!
## Maneiras de Solucionar tais Problemas
-1. Top-Down (De cima para baixo): Começe solucionando o problema quebrando-o em
+1. Top-Down (De cima para baixo): Comece solucionando o problema quebrando-o em
partes. Se você perceber que o problema já foi resolvido, então simplemente
pegue a resposta salva. Se ainda não foi resolvido, solucione-o e salve a
resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente
referenciado como Memorização.
2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os
-subproblemas são resolvidos e começe a solucionar dos problemas mais triviais,
+subproblemas são resolvidos e comece a solucionar dos problemas mais triviais,
até o problema dado. Neste processo, é garantido que os subproblemas são
-resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica.
+resolvidos antes de resolver o problema. Isto é referenciado como Programação Dinâmica.
## Exemplo de Programação Dinâmica
@@ -51,7 +51,7 @@ array antecedente e uma variável como maiorSequenciasAteAgora e seu índice
ajudariam a poupar muito tempo.
Um conceito similar poderia ser aplicado ao procurar o maior caminho em um
grafo acíclico dirigido.
----------------------------------------------------------------------------
+
```
for i=0 to n-1
LS[i]=1
@@ -62,7 +62,7 @@ grafo acíclico dirigido.
if (largest < LS[i])
```
-### Alguns Problemas Famosos de Programação Dinâmica
+## Alguns Problemas Famosos de Programação Dinâmica
```
Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir-pt.html.markdown
index f8c56101..f8c56101 100644
--- a/pt-br/elixir.html.markdown
+++ b/pt-br/elixir-pt.html.markdown
diff --git a/pt-br/elm-pt.html.markdown b/pt-br/elm-pt.html.markdown
index 78a4f1b7..d2469a93 100644
--- a/pt-br/elm-pt.html.markdown
+++ b/pt-br/elm-pt.html.markdown
@@ -76,8 +76,8 @@ List.head [] -- Nothing
-- Acesse os elementos de um par com as funções first e second.
-- (Este é um atalho; nós iremos para o "caminho real" em breve.)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- Uma tupla vazia ou "unidade" às vezes é utilizada como um placeholder.
-- É o único valor de seu tipo, também chamado de "Unit".
diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
index 25e123c0..aed23df1 100644
--- a/pt-br/groovy-pt.html.markdown
+++ b/pt-br/groovy-pt.html.markdown
@@ -226,10 +226,12 @@ for (i in array) {
//Itera sobre um mapa
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
-x = 0
+x = ""
for ( e in map ) {
x += e.value
+ x += " "
}
+assert x.equals("Roberto Grails Groovy ")
/*
Operadores
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index 82989502..1b9d7fc6 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -42,7 +42,7 @@ public class LearnJava {
" Double: " + 3.14 +
" Boolean: " + true);
- // Para imprimir sem inserir uma nova lina, use o System.out.print
+ // Para imprimir sem inserir uma nova linha, use o System.out.print
System.out.print("Olá ");
System.out.print("Mundo");
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 7b6729ef..ed4a6ff3 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -25,7 +25,7 @@ Feedback são muito apreciados! Você me encontrar em
```js
// Comentários são como em C. Comentários de uma linha começam com duas barras,
-/* e comentários de múltplas linhas começam com barra-asterisco
+/* e comentários de múltiplas linhas começam com barra-asterisco
e fecham com asterisco-barra */
// comandos podem ser terminados com ;
diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown
index fd822c03..62d9ccad 100644
--- a/pt-br/json-pt.html.markdown
+++ b/pt-br/json-pt.html.markdown
@@ -16,7 +16,7 @@ Como JSON é um formato de intercâmbio de dados, este será, muito provavelment
JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores
aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade.
-Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null.
+Um valor JSON pode ser um número, uma string, um array, um objeto, um booleano (true, false) ou null.
Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+.
diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown
new file mode 100644
index 00000000..a9ed566e
--- /dev/null
+++ b/pt-br/latex-pt.html.markdown
@@ -0,0 +1,291 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+ - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
+ - ["Svetlana Golubeva", "https://attillax.github.io/"]
+translators:
+ - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
+lang: pt-br
+filename: learn-latex-pt.tex
+---
+
+```tex
+% Todas as linhas de comentários começam com %
+% Não existem comentários multilinhas
+
+$ LaTeX não é um programa processador de textos "Visual" como
+% MS Word ou OpenOffice Writer
+
+$ Todo comando LaTeX começa com uma barra invertida (\)
+
+% Documentos LaTeX começam com a definição do tipo que será % compilado
+% Os tipos de documento podem ser livro, relatório, apresentação, etc.
+% As opções para um documento aparecem entre [] chaves. Nesse caso
+% está especificado que queremos o tamanho da fonte em 12pt.
+\documentclass[12pt]{article}
+
+% Em seguida definimos os pacotes que o documento usa.
+% Se você quiser incluir gráficos, texto colorido, ou código fonte de outra
+% linguagem em outro arquivo em seu documento, você precisa ampliar as
+% capacidade do LaTeX. Isso é feito adicionando-se pacotes.
+% Serão incluídos os pacotes float e caption para imagens e hyperref
+% para links.
+\usepackage{caption}
+\usepackage{float}
+\usepackage{hyperref}
+
+% Para poder usar caracteres acentuados, use o seguinte pacote:
+\usepackage[utf8]{inputenc}
+
+% Podemos definir algumas outras propriedades do documento também!
+\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\
+Svetlana Golubeva}
+\date{\today}
+\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!}
+
+% Agora estamos pronto para começar o documento
+% Tudo antes dessa linha é chamado "preâmbulo".
+\begin{document}
+% Se informarmos os campos author (autores), date (data), "title" (título),
+% LaTeX poderá cria uma página inicial para nós.
+\maketitle
+% Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso,
+% o documento deve ser compilado duas vezes, para que tudo apareça na ordem
+% correta.
+% É uma voa prática separar a tabela de conteúdo do corpo do documento. Para
+% isso usa-se o comando \newpage
+\newpage
+\tableofcontents
+
+\newpage
+
+% Muitos artigos de pesquisa possuem um resumo, e pode-se isar comandos
+% predefinidos para isso.
+% Isso deve aparecer em sua ordem lógica, portanto, após o topo,
+% mas antes das seções principais do corpo.
+% Esse comando está disponível para os documentos do tipo artigo (article)
+% e relatório (report).
+\begin{abstract}
+ Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original!
+\end{abstract}
+
+% Comandos para seções são intuitivos.
+% Todos os títulos de seção são adicionados automaticamente à tabela de conteúdo.
+\section{Introdução}
+Olá, meu nome é Colton e juntos estamos explorando o mundo do \LaTeX!
+
+\section{Outra seção}
+Esse é o texto para outra seção. Penso que precisamos de uma subseção.
+
+\subsection{Isso é uma subseção} % Subseções também são intuitivas.
+Penso que precisamos de mais uma
+
+\subsubsection{Pythagoras}
+Muito melhor agora.
+\label{subsec:pythagoras}
+
+% Ao usar o asterisco nós impedimos a numeração automática.
+% Isso funciona para outros comandos \LaTeX também.
+\section*{Essa é uma seção não numerada}
+Afinal nem todas as seções precisam ser numeradas!
+
+\section{Algumas notas sobre texto}
+%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço.
+\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve
+ser posto. Se
+uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash
+\hspace{1pt} ao código de seu documento. \\
+
+\section{Listas}
+Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras
+amanhã, então façamos uma lista de compras.
+\begin{enumerate} % Isso cria o bloco "enumerate".
+ % \item faz com que o enumerate incremente
+ \item Salada.
+ \item 27 melancias.
+ \item Uma lebre.
+ % pode-se também sobrescrever o número do item usando []
+ \item[quantas?] Pistolas de água médias.
+
+ Não é um item da lista, mas faz parte do bloco enumerate.
+
+ \end{enumerate} % Todos os blocos devem ter um final (end{}).
+
+\section{Matemática}
+
+Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos
+acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é
+necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\
+
+A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado;
+símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas
+para mencionar alguns.\\
+
+Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática.
+Aqui está como você pode indicar como todo x que pertence
+a X, $\forall$ x $\in$ X. \\
+% Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos.
+% Isso é porque quando escrevendo, estamos em modo texto.
+% Mas os símbolos de matemática só existem no modo matemática.
+% Podemos entrar no modo matemática a partir do modo texto com os símbolos $.
+% O oposto também pode ocorrer. Variáveis podem ser renderizadas no modo
+% matemática.
+% Também podemos entrar no modo matemática com \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$.
+Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\
+
+Operadores são parte essencial de um documento sobre matemática:
+funções trigonométricas ($\sin$, $\cos$, $\tan$),
+logaritmo e exponencial ($\log$, $\exp$),
+limites ($\lim$), etc.
+possuem comandos pré-definidos em LaTex.
+Vamos escrever uma equação para ver como se faz:
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
+
+Frações (numerador/denominador) podem ser escritas dessa forma:
+
+% 10 / 7
+$$ ^{10}/_{7} $$
+
+% Frações relativamente complexas podem ser escritas como
+% \frac{numerator}{denominator}
+$$ \frac{n!}{k!(n - k)!} $$ \\
+
+Também podemos escrever equações em um ``bloco de equação''.
+
+% Apresenta matemática com o 'bloco' equação
+\begin{equation} % entra no modo matemática
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % para referência
+ \end{equation} % toda declaração \begin precisa de uma declaração end
+
+Podemos então referenciar nossa nova equação!
+A equação~\ref{eq:pythagoras} é também conhecida como Teorema de Pitágoras que é
+também assunto da Seção~\ref{subsec:pythagoras}. Muitas coisas podem ser
+rotuladas: figuras, equações, seções, etc.
+
+Somatórios e Integrais são escritas com os comandos sum e int:
+
+% Alguns compiladores LaTeX irão reclamar se existirem linhas em branco
+% em um bloco de equação.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figuras}
+
+Insiramos uma Figura. O local para colocar a figura pode ser difícil
+de determinar. Eu tenho sempre que verificar as opções toda vez.
+
+\begin{figure}[H] % H aqui é uma opção para o local da figura.
+ \centering % centra a figura na página
+ % Inclui uma figura com escala de 0.8 do tamanho da página.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Comentado para propósitos de compilação. Por favor, use sua imaginação.
+ \caption{Triângulo retângulo com lados $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Tabelas}
+Também podemos incluir tabelas da mesma forma que figuras.
+
+\begin{table}[H]
+ \caption{Título para a Tabela.}
+ % os argumentos {} abaixo descrevem como cada linha da tabela é desenhada.
+ % Aqui também, Preciso ver isso. Toda. E. Cada. Vez.
+ \begin{tabular}{c|cc}
+ Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por &
+ \hline % uma linha horizontal
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)}
+Digamos que precisamos incluir algum código dentro do nosso
+documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt}
+não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos
+isso com o bloco verbatim.
+
+% Existem outros pacotes (por exemplo, minty, lstlisting, etc.)
+% mas verbatim é o básico
+\begin{verbatim}
+ print("Hello World!")
+ a%b; % olha só! Podemos usar os sinais % no bloco verbatim.
+ random = 4; #decided by fair random dice roll
+\end{verbatim}
+
+\section{Compilando}
+
+Imagino que agora você esteja pensando como compilar esse fantástico documento
+e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf.
+(sim, esse documento é compilável). \\
+
+Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos:
+ \begin{enumerate}
+ \item Escrever o documento em texto puro (o ``código fonte'').
+ \item Compilar o código fonte para gerar um pdf.
+ Os passos para compilar se parecem (em Linux) com: \\
+ \begin{verbatim}
+ > pdflatex learn-latex.tex
+ \end{verbatim}
+ \end{enumerate}
+
+Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo
+sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por
+completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar
+referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o
+passo 2 várias vezes, para gerar arquivos *.aux intermediários.}.
+% É assim que você adiciona notas de rodapé em seus documentos!
+
+Você escreve toda a informação de formatação em texto puro, no passo 1. O
+momento da compilação no passo 2 é responsável por produzir o documento no
+formato que você definiu no passo 1.
+
+\section{Links}
+Nós podemos inserir links em nosso documento. Para isso nós necessitamos incluir
+o pacote hyperref no preâmbulo com o comando:
+\begin{verbatim}
+ \usepackage{hyperref}
+\end{verbatim}
+
+Existem dois tipos principais de links: URL visíveis \\
+\url{https://learnxinyminutes.com/docs/latex/}, ou
+\href{https://learnxinyminutes.com/docs/latex/}{um texto alternativo}
+% Você não pode adicionar espaços extras ou símbolos especiais no texto
+% alternativo, pois isso causará problemas na compilação.
+
+Esse pacote também produz uma lista de thumbnails no documento pdf gerado e
+ativa os links na tabela de conteúdo.
+
+\section{End}
+
+Por enquanto é isso!
+
+% Frequentemente você precisa de uma seção de referências em seu documento.
+% A forma mais fácil de configurá-la é usando uma seção de bibliografia
+\begin{thebibliography}{1}
+ % como em outras listas, o comando \bibitem pode ser usado para itens da lista
+ % cada entrada pode ser citada diretamente no corpo do texto
+ \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
+https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
+\end{thebibliography}
+
+% end the document
+\end{document}
+```
+
+## Mais sobre LaTeX
+
+* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown
index cc07a2ec..217861f9 100644
--- a/pt-br/perl-pt.html.markdown
+++ b/pt-br/perl-pt.html.markdown
@@ -21,7 +21,7 @@ Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada
# Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo.
# Um nome de variável válido começa com uma letra ou sublinhado,
-# seguido por qualquer número de letras, números ou sublinhados.
+# seguido por qualquer quantidade de letras, números ou sublinhados.
### Perl has three main variable types: $scalar, @array, e %hash.
@@ -52,10 +52,10 @@ my %fruta_cor = (
banana => "amarelo",
);
-# Scalars, arrays and hashes são documentados mais profundamentes em perldata.
+# Scalars, arrays and hashes são documentados mais profundamente em perldata.
# (perldoc perldata).
-# Mais tipos de dados complexos podem ser construídas utilizando referências,
+# Mais tipos de dados complexos podem ser construídos utilizando referências,
# o que permite que você crie listas e hashes dentro de listas e hashes.
#### Condicionais e construtores de iteração
diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown
new file mode 100644
index 00000000..10d55784
--- /dev/null
+++ b/pt-br/pyqt-pt.html.markdown
@@ -0,0 +1,92 @@
+---
+category: tool
+tool: PyQT
+filename: learnpyqt-pt.py
+contributors:
+ - ["Nathan Hughes", "https://github.com/sirsharpest"]
+translators:
+ - ["Lucas Pugliesi", "https://github.com/fplucas"]
+lang: pt-br
+---
+
+**Qt** é amplamente conhecido como um framework para desenvolvimento de
+software multi-plataforma que pode rodar em vários outras plataformas de
+softwares e hardwares com pouca ou nenhuma alteração no código, enquanto mantém
+o poder e a velocidade de uma aplicação nativa. Embora o **Qt** tenha sido
+originalmente escrito em *C++*.
+
+
+Essa é uma adaptação de uma introdução ao QT em C++ por
+[Aleksey Kholovchuk](https://github.com/vortexxx192), alguns dos exemplos de
+código podem resultar na mesma funcionalidade que essa versão, apenas usando
+o pyqt!
+
+```python
+import sys
+from PyQt4 import QtGui
+
+def window():
+ # Cria um objeto para a aplicação
+ app = QtGui.QApplication(sys.argv)
+ # Cria um widget onde o nosso label será inserido
+ w = QtGui.QWidget()
+ # Adiciona um label ao widget
+ b = QtGui.QLabel(w)
+ # Informa algum texto ao label
+ b.setText("Hello World!")
+ # Define os tamanhos e posições dos objetos
+ w.setGeometry(100, 100, 200, 50)
+ b.move(50, 20)
+ # Define o título da janela
+ w.setWindowTitle("PyQt")
+ # Exibe a janela
+ w.show()
+ # Executa tudo o que foi pedido, apenas uma vez
+ sys.exit(app.exec_())
+
+if __name__ == '__main__':
+ window()
+
+```
+
+Para utilizar mais funcionalidades no **pyqt** veremos a construção de alguns
+outros elementos.
+Aqui mostraremos como criar uma janela popup, muito útil para perguntar ao
+usuário qual decisão tomar ou exibir alguma informação.
+
+```Python
+import sys
+from PyQt4.QtGui import *
+from PyQt4.QtCore import *
+
+
+def window():
+ app = QApplication(sys.argv)
+ w = QWidget()
+ # Cria um botão e o anexa ao widget w
+ b = QPushButton(w)
+ b.setText("Press me")
+ b.move(50, 50)
+ # Informa b a chamar essa função quando for clicado
+ # observe que a função chamada não necessita de "()"
+ b.clicked.connect(showdialog)
+ w.setWindowTitle("PyQt Dialog")
+ w.show()
+ sys.exit(app.exec_())
+
+# Essa função deve criar uma janela de diálogo com um botão,
+# aguarda ser clicado e encerra o programa
+def showdialog():
+ d = QDialog()
+ b1 = QPushButton("ok", d)
+ b1.move(50, 50)
+ d.setWindowTitle("Dialog")
+ # Essa modalidade define que o popup deve bloquear as outras janelas quando ativo
+ d.setWindowModality(Qt.ApplicationModal)
+ # Ao ser clicado deve encerrar o processo
+ b1.clicked.connect(sys.exit)
+ d.exec_()
+
+if __name__ == '__main__':
+ window()
+```
diff --git a/pt-br/qt-pt.html.markdown b/pt-br/qt-pt.html.markdown
new file mode 100644
index 00000000..99579c35
--- /dev/null
+++ b/pt-br/qt-pt.html.markdown
@@ -0,0 +1,174 @@
+---
+category: tool
+tool: Qt Framework
+language: c++
+filename: learnqt-pt.cpp
+contributors:
+ - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
+translators:
+ - ["Lucas Pugliesi", "https://github.com/fplucas"]
+lang: pt-br
+---
+
+**Qt** é amplamente conhecido como um framework para desenvolvimento de
+software multi-plataforma que pode rodar em vários outras plataformas de
+softwares e hardwares com pouca ou nenhuma alteração no código, enquanto mantém
+o poder e a velocidade de uma aplicação nativa. Embora o **Qt** tenha sido
+originalmente escrito em *C++*, é possível utilizá-lo em outras linguagens:
+*[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
+
+**Qt** é ótimo para criar aplicações com interface gráfica (GUI). Esse tutorial
+será feito em *C++*.
+
+```c++
+/*
+ * Vamos começar
+ */
+
+// Todos as dependências do framework Qt iniciam com a letra 'Q' maiúscula
+#include <QApplication>
+#include <QLineEdit>
+
+int main(int argc, char *argv[]) {
+ // Cria um objeto para utilizar todos os recursos da aplicação
+ QApplication app(argc, argv);
+
+ // Cria um widget com linha editável e exibe na tela
+ QLineEdit lineEdit("Hello world!");
+ lineEdit.show();
+
+ // Inicia a aplicação em um evento de loop
+ return app.exec();
+}
+```
+
+A parte gráfica do **Qt** é toda composta de *widgets* e *conexões* entre eles.
+
+[LEIA MAIS SOBRE WIDGETS](http://doc.qt.io/qt-5/qtwidgets-index.html)
+
+```c++
+/*
+ * Vamos criar um label e um botão.
+ * Um label irá aparecer quando o botão for clicado
+ *
+ * O próprio código do Qt é autoexplicativo.
+ */
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QLabel>
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ // Adiciona um layout vertical
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ QLabel textLabel("Thanks for pressing that button");
+ layout.addWidget(&textLabel);
+ textLabel.hide();
+
+ QPushButton button("Press me");
+ layout.addWidget(&button);
+
+ // Exibe o label oculto quando o botão é clicado
+ QObject::connect(&button, &QPushButton::pressed,
+ &textLabel, &QLabel::show);
+
+ return app.exec();
+}
+```
+
+Veja o *QObject::connect*. O método é usado para conectar o *SINAL* de um objeto
+ao *ENCAIXE* outro.
+
+**Sinais** são emitidos quando algo ocorre com o objeto, como quando o sinal de
+*clique* é acionado apertando o QPushButton.
+
+**Encaixes** são *ações* que são executadas em resposta aos sinais recebidos.
+
+[LEIA MAIS SOBRE SINAIS E ENCAIXES](http://doc.qt.io/qt-5/signalsandslots.html)
+
+
+A seguir vamos aprender como usar não somente o comportamento padrão dos
+widgets, mas também extender seus comportamentos usando herança. Vamos criar um
+botão e contar quantas vezes é pressionado. Para esse propósito definiremos
+nossa própria classe *CounterLabel*. Ela deve ser declarada em um arquivo
+diferente devido a estrutura específica do Qt.
+
+```c++
+// counterlabel.hpp
+
+#ifndef COUNTERLABEL
+#define COUNTERLABEL
+
+#include <QLabel>
+
+class CounterLabel : public QLabel {
+ Q_OBJECT // Define os macros presente em todo objeto Qt
+
+public:
+ CounterLabel() : counter(0) {
+ setText("Counter has not been increased yet"); // método do QLabel
+ }
+
+public slots:
+ // Ação que será chamada em resposta ao clique do botão
+ void increaseCounter() {
+ setText(QString("Counter value: %1").arg(QString::number(++counter)));
+ }
+
+private:
+ int counter;
+};
+
+#endif // COUNTERLABEL
+```
+
+```c++
+// main.cpp
+// Quase igual ao exemplo anterior
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QString>
+#include "counterlabel.hpp"
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ CounterLabel counterLabel;
+ layout.addWidget(&counterLabel);
+
+ QPushButton button("Push me once more");
+ layout.addWidget(&button);
+ QObject::connect(&button, &QPushButton::pressed,
+ &counterLabel, &CounterLabel::increaseCounter);
+
+ return app.exec();
+}
+```
+
+É isso! Claro, o framework Qt é muito maior do que exemplificamos no tutorial,
+então esteja preparado para ler e praticar mais.
+
+## Leitura complementar
+
+- [Tutoriais Qt 4.8](http://doc.qt.io/qt-4.8/tutorials.html)
+- [Tutoriais Qt 5](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
+
+Boa sorte e divirta-se!
diff --git a/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown
index 8134d3c5..8134d3c5 100644
--- a/rust-pt.html.markdown
+++ b/pt-br/rust-pt.html.markdown
diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown
index ebf74b6f..bf410352 100644
--- a/pt-br/swift-pt.html.markdown
+++ b/pt-br/swift-pt.html.markdown
@@ -389,13 +389,13 @@ if mySquare === mySquare {
// Podem conter métodos do mesmo jeito que classes.
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown
index 76cca567..b94ab609 100644
--- a/pt-br/visualbasic-pt.html.markdown
+++ b/pt-br/visualbasic-pt.html.markdown
@@ -15,9 +15,9 @@ module Module1
Sub Main ()
' Uma visão geral de console de aplicativos do Visual Basic antes de
- ' mergulharmos mais profundamente na linguagem
+ ' mergulharmos mais profundamente na linguagem.
' Aspas simples começam comentários.
- ' Para Navegar este tutorial dentro do compilador do Visual Basic,
+ ' Para navegar neste tutorial dentro do compilador do Visual Basic,
' eu criei um sistema de navegação.
' Este sistema de navegação vai ser explicado conforme avançarmos no
' tutorial, e você vai entender o que isso significa.
@@ -93,16 +93,16 @@ module Module1
Private Sub HelloWorldInput ()
Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes"
' Variáveis
- 'Os dados inseridos por um usuário precisa ser armazenada .
+ 'Os dados inseridos por um usuário precisam ser armazenados.
' As variáveis ​​também começar com um Dim e terminar com um Como VariableType .
- ' Neste tutorial, nós queremos saber o que o seu nome, e faça o programa
+ ' Neste tutorial, nós queremos saber qual é o seu nome, e faça o programa
' Responder ao que é dito.
Nome de usuário Dim As String
" Nós usamos string como string é uma variável de texto baseado .
Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome.
- username = Console.ReadLine () ' armazena o nome usuários.
- Console.WriteLine (" Olá " + nome do usuário) " A saída é Olá ' Seu nome '
+ username = Console.ReadLine () ' armazena o nome do usuário.
+ Console.WriteLine (" Olá " + username) ' A saída é "Olá < seu nome >".
Console.ReadLine () ' Outsputs acima.
' O código acima irá lhe fazer uma pergunta seguiu imprimindo sua resposta.
" Outras variáveis ​​incluem Integer e usamos inteiro para números inteiros.
diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown
new file mode 100644
index 00000000..989bae05
--- /dev/null
+++ b/pt-br/whip-pt.html.markdown
@@ -0,0 +1,247 @@
+---
+language: whip
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
+author: Tenor Biel
+author_url: http://github.com/L8D
+translators:
+ - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
+lang: pt-br
+filename: whip-pt.lisp
+---
+
+Whip é um dialeto de Lisp feito para construir scripts e trabalhar com
+conceitos mais simples.
+Ele também copia muitas funções e sintaxe de Haskell (uma linguagem não correlata)
+
+Esse documento foi escrito pelo próprio autor da linguagem. Então é isso.
+
+```scheme
+; Comentário são como em Lisp. Pontos-e-vírgulas...
+
+; A maioria das declarações de primeiro nível estão dentro de "listas"
+; que nada mais são que coisas entre parêntesis separadas por espaços em branco
+nao_é_uma_lista
+(uma lista)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 1. Números, texto e operadores
+
+; Whip tem um tipo numérico (que é um double de 64 bits IEE 754, do JavaScript)
+3 ; => 3
+1.5 ; => 1.5
+
+; Funções são chamadas se elas são o primeiro elemento em uma lista
+(funcao_chamada argumentos)
+
+; A maioria das operações são feitas com funções
+; Todas as funções aritméticas básicas são bem diretas
+(+ 1 1) ; => 2
+(- 2 1) ; => 1
+(* 1 2) ; => 2
+(/ 2 1) ; => 2
+; até mesmo o módulo
+(% 9 4) ; => 1
+; Divisão não inteira ao estilo JavaScript.
+(/ 5 2) ; => 2.5
+
+; Aninhamento de listas funciona como esperado.
+(* 2 (+ 1 3)) ; => 8
+
+; Há um tipo boleano.
+true
+false
+
+; Textos são criados com ".
+"Hello, world"
+
+; Caracteres são criados com '.
+'a'
+
+; Para negação usa-se a função 'not'.
+(not true) ; => false
+(not false) ; => true
+
+; Mas a maioria das funções não-haskell tem atalhos
+; o não atalho é um '!'.
+(! (! true)) ; => true
+
+; Igualdade é `equal` ou `=`.
+(= 1 1) ; => true
+(equal 2 1) ; => false
+
+; Por exemplo, inigualdade pode ser verificada combinando as funções
+;`not` e `equal`.
+(! (= 2 1)) ; => true
+
+; Mais comparações
+(< 1 10) ; => true
+(> 1 10) ; => false
+; e suas contra partes para texto.
+(lesser 1 10) ; => true
+(greater 1 10) ; => false
+
+; Texto pode ser concatenado com +.
+(+ "Hello " "world!") ; => "Hello world!"
+
+; Você pode usar as características comparativas do JavaScript.
+(< 'a' 'b') ; => true
+; ... e coerção de tipos
+(= '5' 5)
+
+; As funções `at` ou `@` acessarão caracteres de um texto, começando em 0.
+(at 0 'a') ; => 'a'
+(@ 3 "foobar") ; => 'b'
+
+; Também existem as variáveis `null` e `undefined`.
+null ; usada para indicar a ausência de algum valor
+undefined ; usada para indicar que um valor não foi informado
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 2. Variáveis, matrizes e dicionários
+
+; Variáveis são declaradas com as funções `def` ou `let`.
+; Variáveis que não tiveram valor atribuído serão `undefined`.
+(def some_var 5)
+; `def` deixará a variável no contexto global.
+; `let` deixará a variável no contexto local, e tem uma sintaxe estranha.
+(let ((a_var 5)) (+ a_var 5)) ; => 10
+(+ a_var 5) ; = undefined + 5 => undefined
+
+; Matrizes são listas de valores de qualquer tipo.
+; Elas basicamente são listas sem funções no início
+(1 2 3) ; => [1, 2, 3] (sintaxe JavaScript)
+
+; Dicionários em Whip são o equivalente a 'object' em JavaScript ou
+; 'dict' em python ou 'hash' em Ruby: eles s]ão uma coleção desordenada
+de pares chave-valor.
+{"key1" "value1" "key2" 2 3 3}
+
+; Chaves podem ser apenas identificadores, números ou texto.
+(def my_dict {my_key "my_value" "my other key" 4})
+; Mas em Whip, dicionários são parceados como: valor, espaço, valor;
+; com mais espaço entre cada. Então isso significa que
+{"key" "value"
+"another key"
+1234
+}
+é avaliado da mesma forma que
+{"key" "value" "another key" 1234}
+
+; Dicionários podem ser acessados usando a função `at`
+; (como em texto e listas)
+(@ "my other key" my_dict) ; => 4
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 3. Lógica e controle de fluxo
+
+; A função `if` é muito simples, ainda que muito diferente do que em muitas
+linguagens imperativas.
+(if true "returned if first arg is true" "returned if first arg is false")
+; => "returned if first arg is true"
+
+; E por conta do legado operador ternário
+; `?` é o atalho não utilizado para `if`.
+(? false true false) ; => false
+
+; `both` é uma declaração lógica `and`, e `either` é o `or` lógico.
+(both true true) ; => true
+(both true false) ; => false
+(either true false) ; => true
+(either false false) ; => false
+; E seus atalhos são
+; & => both
+; ^ => either
+(& true true) ; => true
+(^ false true) ; => true
+
+;;;;;;;;;
+; Lambdas
+
+; Lambdas em Whip são declaradas com as funções `lambda` ou `->`.
+; E funções são na verdade lambdas com nomes.
+(def my_function (-> (x y) (+ (+ x y) 10)))
+; | | | |
+; | | | valor retornado (com escopo contento argumentos)
+; | | argumentos
+; | declaração de funções lambda
+; |
+; nome do lambda a ser declarado
+
+(my_function 10 10) ; = (+ (+ 10 10) 10) => 30
+
+; Obviamente, todos os lambdas por definição são anônimos e
+; tecnicamente sempre usados anonimamente. Redundância.
+((lambda (x) x) 10) ; => 10
+
+;;;;;;;;;;;;;;;;
+; Comprehensions
+
+; `range` or `..` geram uma lista dos números para
+; cada número entre seus dois argumentos.
+(range 1 5) ; => (1 2 3 4 5)
+(.. 0 2) ; => (0 1 2)
+
+; `map` aplica seu primeiro argumento (que deve ser um lambda/função)
+; a cada item dos argumentos seguintes (que precisa ser uma lista)
+(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4)
+
+; Reduce
+(reduce + (.. 1 5))
+; equivalente a
+((+ (+ (+ 1 2) 3) 4) 5)
+
+; Nota: map e reduce não possuem atalhos
+
+; `slice` ou `\` é similar ao .slice() do JavaScript
+; mas veja que ele pega uma lista como primeiro argumento, não o último.
+(slice (.. 1 5) 2) ; => (3 4 5)
+(\ (.. 0 100) -5) ; => (96 97 98 99 100)
+
+; `append` ou `<<` são auto explicativos
+(append 4 (1 2 3)) ; => (1 2 3 4)
+(<< "bar" ("foo")) ; => ("foo" "bar")
+
+; Length é auto explicativo.
+(length (1 2 3)) ; => 3
+(_ "foobar") ; => 6
+
+;;;;;;;;;;;;;;;
+; Delicadezas Haskell
+
+; Primeiro item de uma lista
+(head (1 2 3)) ; => 1
+; Pega do segundo ao último elemento de uma lista
+(tail (1 2 3)) ; => (2 3)
+; Último item de uma lista
+(last (1 2 3)) ; => 3
+; Contrário de `tail`
+(init (1 2 3)) ; => (1 2)
+; Pega do primeiro até o elemento especificado da lista
+(take 1 (1 2 3 4)) ; (1 2)
+; Contrário de `take`
+(drop 1 (1 2 3 4)) ; (3 4)
+; Menos valor em uma lista
+(min (1 2 3 4)) ; 1
+; Maior valor em uma lista
+(max (1 2 3 4)) ; 4
+; Verifica se o valor está em uma lista ou objeto
+(elem 1 (1 2 3)) ; true
+(elem "foo" {"foo" "bar"}) ; true
+(elem "bar" {"foo" "bar"}) ; false
+; Inverte a ordem de uma lista
+(reverse (1 2 3 4)) ; => (4 3 2 1)
+; Verifica se o valor é par ou ímpar
+(even 1) ; => false
+(odd 1) ; => true
+; Separa um texto cortando por espaço em branco
+(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese")
+; Junta lista de textos
+(unwords ("foo" "bar")) ; => "foobar"
+; Sucessor e predecessor
+(pred 21) ; => 20
+(succ 20) ; => 21
+```
+
+Para mais informação, verifique o [repositório](http://github.com/L8D/whip)
diff --git a/pt-pt/bf.html.markdown b/pt-pt/bf-pt.html.markdown
index 13c22387..13c22387 100644
--- a/pt-pt/bf.html.markdown
+++ b/pt-pt/bf-pt.html.markdown
diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift-pt.html.markdown
index 9462ee1c..6b263942 100644
--- a/pt-pt/swift.html.markdown
+++ b/pt-pt/swift-pt.html.markdown
@@ -445,49 +445,49 @@ if let circle = myEmptyCircle {
// Enums pode opcionalmente ser um tipo especifico ou não.
// Enums podem conter métodos tal como as classes.
-enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+enum suit {
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum
// quando a variável é explicitamente definida.
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas
enum BookName: String {
- case John = "John"
- case Luke = "Luke"
+ case john = "John"
+ case luke = "Luke"
}
-print("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.john.rawValue)")
// Enum com valores associados
enum Furniture {
// Associar com um inteiro (Int)
- case Desk(height: Int)
+ case desk(height: Int)
// Associar com uma String e um Int
- case Chair(String, Int)
+ case chair(String, Int)
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Desk with \(height) cm"
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
-var chair = Furniture.Chair("Foo", 40)
+var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
diff --git a/python.html.markdown b/python.html.markdown
index 946cbc0c..89fa7046 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -363,6 +363,12 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Check for existence in a set with in
2 in filled_set # => True
10 in filled_set # => False
+10 not in filled_set # => True
+
+# Check data type of variable
+type(li) # => list
+type(filled_dict) # => dict
+type(5) # => int
####################################################
diff --git a/python3.html.markdown b/python3.html.markdown
index 5aa61b65..37987582 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -669,7 +669,7 @@ class Human:
# An instance method. All methods take "self" as the first argument
def say(self, msg):
- print ("{name}: {message}".format(name=self.name, message=msg))
+ print("{name}: {message}".format(name=self.name, message=msg))
# Another instance method
def sing(self):
@@ -740,10 +740,105 @@ if __name__ == '__main__':
####################################################
-## 6.1 Multiple Inheritance
+## 6.1 Inheritance
+####################################################
+
+# Inheritance allows new child classes to be defined that inherit methods and
+# 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
+# "species", "name", and "age", as well as methods, like "sing" and "grunt"
+# from the Human class, but can also have its own unique properties.
+
+# To take advantage of modularization by file you could place the classes above in their own files,
+# say, human.py
+
+# To import functions from other files use the following format
+# from "filename-without-extension" import "function-or-class"
+
+from human import Human
+
+
+# Specify the parent class(es) as parameters to the class definition
+class Superhero(Human):
+
+ # If the child class should inherit all of the parent's definitions without
+ # any modifications, you can just use the "pass" keyword (and nothing else)
+ # but in this case it is commented out to allow for a unique child class:
+ # pass
+
+ # Child classes can override their parents' attributes
+ species = 'Superhuman'
+
+ # Children automatically inherit their parent class's constructor including
+ # its arguments, but can also define additional arguments or definitions
+ # and override its methods such as the class constructor.
+ # This constructor inherits the "name" argument from the "Human" class and
+ # adds the "superpower" and "movie" arguments:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
+
+ # add additional class attributes:
+ self.fictional = True
+ self.movie = movie
+ self.superpowers = superpowers
+
+ # The "super" function lets you access the parent class's methods
+ # that are overridden by the child, in this case, the __init__ method.
+ # This calls the parent class constructor:
+ super().__init__(name)
+
+ # overload the sing method
+ def sing(self):
+ return 'Dun, dun, DUN!'
+
+ # add an additional class method
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # Instance type checks
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
+
+ # Get the Method Resolution search Order used by both getattr() and super()
+ # This attribute is dynamic and can be updated
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
+
+ # Calls parent method but uses its own class attribute
+ print(sup.get_species()) # => Superhuman
+
+ # Calls overloaded method
+ print(sup.sing()) # => Dun, dun, DUN!
+
+ # Calls method from Human
+ sup.say('Spoon') # => Tick: Spoon
+
+ # Call method that exists only in Superhero
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # Inherited class attribute
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Attribute that only exists within Superhero
+ print('Am I Oscar eligible? ' + str(sup.movie))
+
+####################################################
+## 6.2 Multiple Inheritance
####################################################
# Another class definition
+# bat.py
class Bat:
species = 'Baty'
@@ -765,21 +860,14 @@ if __name__ == '__main__':
print(b.say('hello'))
print(b.fly)
-# To take advantage of modularization by file you could place the classes above in their own files,
-# say, human.py and bat.py
-
-# To import functions from other files use the following format
-# from "filename-without-extension" import "function-or-class"
+# And yet another class definition that inherits from Superhero and Bat
# superhero.py
-from human import Human
+from superhero import Superhero
from bat import Bat
-# Batman inherits from both Human and Bat
-class Batman(Human, Bat):
-
- # Batman has its own value for the species class attribute
- species = 'Superhero'
+# Define Batman as a child that inherits from both Superhero and Bat
+class Batman(Superhero, Bat):
def __init__(self, *args, **kwargs):
# Typically to inherit attributes you have to call super:
@@ -789,7 +877,8 @@ class Batman(Human, 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".
- Human.__init__(self, 'anonymous', *args, **kwargs)
+ 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
self.name = 'Sad Affleck'
@@ -801,20 +890,15 @@ class Batman(Human, Bat):
if __name__ == '__main__':
sup = Batman()
- # Instance type checks
- if isinstance(sup, Human):
- print('I am human')
- if isinstance(sup, Bat):
- print('I am bat')
- if type(sup) is Batman:
- print('I am Batman')
-
# 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 'human.Human'>, <class 'bat.Bat'>, <class 'object'>)
+ 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
- print(sup.get_species()) # => Superhero
+ print(sup.get_species()) # => Superhuman
# Calls overloaded method
print(sup.sing()) # => nan nan nan nan nan batman!
@@ -827,10 +911,10 @@ if __name__ == '__main__':
# Inherited class attribute
sup.age = 100
- print(sup.age)
+ print(sup.age) # => 100
# Inherited attribute from 2nd ancestor whose default value was overridden.
- print('Can I fly? ' + str(sup.fly))
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown
index 79bbcd8d..6dde1cf0 100644
--- a/pythonstatcomp.html.markdown
+++ b/pythonstatcomp.html.markdown
@@ -13,10 +13,11 @@ This is a tutorial on how to do some typical statistical programming tasks using
# 0. Getting set up ====
-""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
+""" To get started, pip install the following: jupyter, numpy, scipy, pandas,
matplotlib, seaborn, requests.
- Make sure to do this tutorial in the IPython notebook so that you get
- the inline plots and easy documentation lookup.
+ Make sure to do this tutorial in a Jupyter notebook so that you get
+ the inline plots and easy documentation lookup. The shell command to open
+ one is simply `jupyter notebook`, then click New -> Python.
"""
# 1. Data acquisition ====
diff --git a/r.html.markdown b/r.html.markdown
index 7a94ba05..e7486e60 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -663,7 +663,8 @@ require(plyr)
# "pets.csv" is a file on the internet
# (but it could just as easily be a file on your own computer)
-pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
+require(RCurl)
+pets <- read.csv(textConnection(getURL("http://learnxinyminutes.com/docs/pets.csv")))
pets
head(pets, 2) # first two rows
tail(pets, 1) # last row
diff --git a/ru-ru/haml-ru.html.markdown b/ru-ru/haml-ru.html.markdown
new file mode 100644
index 00000000..c2f8852e
--- /dev/null
+++ b/ru-ru/haml-ru.html.markdown
@@ -0,0 +1,233 @@
+---
+language: haml
+filename: learnhaml-ru.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Vasiliy Petrov", "https://github.com/Saugardas"]
+translators:
+ - ["Vasiliy Petrov", "https://github.com/Saugardas"]
+lang: ru-ru
+---
+
+Haml - язык разметки (в основном используемый с Ruby), с помощью которого могут быть легко описаны HTML-документы.
+Он является популярной альтернативой используемому в Rails шаблонизатору (.erb), и позволяет вставлять Ruby-код в вашу разметку.
+
+Haml убирает избыточность закрывающих тегов благодаря отступам.
+В результате получается меньшая по размерам, хорошо структурированная, логичная и читаемая разметка.
+
+Вы можете использовать Haml и вне Ruby-проекта. Установите гем Haml и используйте командную строку для конвертирования html-файлов:
+
+```shell
+$ haml input_file.haml output_file.html
+```
+
+
+```haml
+/ -------------------------------------------
+/ Отступы
+/ -------------------------------------------
+
+/
+ Отступы являются важным элементом синтаксиса, поэтому они должны быть
+ одинаковыми во всём документе. Обычно используют два пробела,
+ но это не является обязательным правилом - можно использовать любое
+ количество пробелов для отступов. Главное, чтобы это количество было
+ одинаковым во всём документе.
+
+
+/ -------------------------------------------
+/ Комментарии
+/ -------------------------------------------
+
+/ Комментари начинается с символа косой черты.
+
+/
+ Для написания многострочного комментария расположите ваш комментарий
+ на следующем уровне вложенности от символа косой черты
+
+-# "Скрытый" комментарий. Этот комментарий не попадёт в результирующий документ
+
+
+/ -------------------------------------------
+/ Элементы HTML
+/ -------------------------------------------
+
+/ Чтобы написать тег, используйте символ процента (%) и название тега
+%body
+ %header
+ %nav
+
+/ Обратите внимание на отсутствие закрывающих тегов. Код выше выведет:
+ <body>
+ <header>
+ <nav></nav>
+ </header>
+ </body>
+
+/
+ Так как тег div используется очень часто, его можно опустить.
+ Можно указать только имя класса или идентификатора (. или #)
+ Например код:
+
+%div.my_class
+ %div#my_id
+
+/ Можно записать:
+.my_class
+ #my_id
+
+/ Для добавления контента в тег, просто добавьте текст после объявления тега
+%h1 Заголовок
+
+/ Для многострочного содержания используйте отступы
+%p
+ Многострочное содержание
+ в две строки.
+
+/
+ Амперсанд - равно (&=) обрабатывают Ruby код также, как и без амперсанда,
+ но HTML-символы в результате будут экранированы. Например:
+
+%p
+ &= "Да & да"
+
+/ выведет 'Да &amp; да'
+
+/
+ Чтобы выполнять Ruby-код без экранрования, можно использовать
+ "восклицательный знак" и "равно" (!=)
+
+%p
+ != "Тег абзаца <p></p>"
+
+/ выведет 'Тег абзаца <p></p>'
+
+/ CSS - классы могут быть добавлены через точку от определения тега
+%div.foo.bar
+
+/ Или с помощью хеша атрибутов
+%div{ :class => 'foo bar' }
+
+/ Хеш атрибутов может быть добавлен для любого тега
+%a{ :href => '#', :class => 'bar', :title => 'Bar' }
+
+/ Для булевых атрибутов просто присвойте значение 'true'
+%input{ :selected => true }
+
+/ Для data - атрибутов присвойте ключу :data хеш с данными
+%div{ :data => { :attribute => 'foo' } }
+
+/ Для Ruby версии 1.9 или выше, можно использовать новый синтаксис хешей
+%div{ data: { attribute: 'foo' } }
+
+/ Также можно использовать HTML-синтаксис атрибутов
+%a(href='#' title='bar')
+
+/ Можно использовать оба варианта одновременно
+%a(href='#'){ title: @my_class.title }
+
+
+/ -------------------------------------------
+/ Включение Ruby
+/ -------------------------------------------
+
+/ Для включения Ruby кода используйте знак "равно"
+
+%h1= book.name
+
+%p
+ = book.author
+ = book.publisher
+
+
+/ Для выполнения Ruby кода без вывода в HTML, используйте знак дефиса
+- books = ['book 1', 'book 2', 'book 3']
+
+/
+ Можно выполнять любой Ruby код, например с блоками.
+ Закрывающий "end" не нужен, так как они будут закрыты автоматически,
+ основываясь на вложенности.
+
+- books.shuffle.each_with_index do |book, index|
+ %h1= book
+
+ - if book do
+ %p This is a book
+
+/ Добавление списка
+%ul
+ %li
+ =item1
+ =item2
+
+/ -------------------------------------------
+/ Пример таблицы с классами Bootstrap'a
+/ -------------------------------------------
+
+%table.table.table-hover
+ %thead
+ %tr
+ %th Header 1
+ %th Header 2
+
+ %tr
+ %td Value1
+ %td value2
+
+ %tfoot
+ %tr
+ %td
+ Foot value
+
+
+/ -------------------------------------------
+/ Интерполяция Ruby кода
+/ -------------------------------------------
+
+/ Ruby код может быть интерполирован в текст с помощью #{}
+%p Ваша самая любимая игра - #{best_game}
+
+/ Тоже самое, что и:
+%p= "Ваша самая любимая игра - #{best_game}"
+
+
+/ -------------------------------------------
+/ Фильтры
+/ -------------------------------------------
+
+/
+ Фильтры передают связанный блок текста в соотвествующую
+ фильтрующую программу и возвращают результат в Haml
+ Фильтр обозначается двоеточием и названием фильтра:
+
+/ Markdown filter
+:markdown
+ # Заголовк
+
+ Текст **внутри** *блока*
+
+/ Код выше будет скомпилирован в
+<h1>Заголовок</h1>
+
+<p>Текст <strong>внутри</strong> <em>блока</em></p>
+
+/ Javascript - фильтр
+:javascript
+ console.log('This is inline <script>');
+
+/ скомпилируется в:
+<script>
+ console.log('This is inline <script>');
+</script>
+
+/
+ Существует множество типов фильров (:markdown, :javascript, :coffee,
+ :css, :ruby и так далее). Вы можете определить собственный фильтр c
+ помощью Haml::Filters.
+
+```
+
+## Дополнительные ресурсы
+
+- [О Haml](https://haml.ru) - Хорошее введение, описывает преимущества Haml.
+- [Документация](https://haml.ru/documentation/) - Документация Haml на русском языке.
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 014ff5d0..af77a9ca 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -61,6 +61,8 @@ $int4 = 0x0F; // => 15 (ведущие символы 0x означают шес
// Двоичная запись integer доступна начиная с PHP 5.4.0.
$int5 = 0b11111111; // 255 (0b в начале означает двоичное число)
+// Удаление переменной
+unset($int1);
// Дробные числа
$float = 1.234;
diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown
index 2b6b59a7..bf80fed2 100644
--- a/ru-ru/python3-ru.html.markdown
+++ b/ru-ru/python3-ru.html.markdown
@@ -106,6 +106,9 @@ False or True #=> True
# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
"Привет " + "мир!" #=> "Привет мир!"
+# Строки можно умножать.
+"aa" * 4 #=> "aaaaaaaa"
+
# Со строкой можно работать, как со списком символов
"Это строка"[0] #=> 'Э'
diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown
index f54c89b4..e69c6d94 100644
--- a/ru-ru/ruby-ru.html.markdown
+++ b/ru-ru/ruby-ru.html.markdown
@@ -182,8 +182,9 @@ array.[] 12 #=> nil
array[-1] #=> 5
array.last #=> 5
-# С заданными левой и правой границами индексов
-array[2, 4] #=> [3, 4, 5]
+# Задавая индекс и количество элементов
+array[0,2] #=> [1, 2]
+array[0,999] #=> [1, 2, 3, 4, 5]
# Или с использованием диапазона значений
array[1..3] #=> [2, 3, 4]
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index 7ff660e1..f2b1fd36 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -376,14 +376,14 @@ print("Имя :\(name)") // Имя: Яков
// Протокол `Error` используется для перехвата выбрасываемых ошибок
enum MyError: Error {
- case BadValue(msg: String)
- case ReallyBadValue(msg: String)
+ case badValue(msg: String)
+ case reallyBadValue(msg: String)
}
// фунции помеченные словом `throws` должны вызываться с помощью `try`
func fakeFetch(value: Int) throws -> String {
guard 7 == value else {
- throw MyError.ReallyBadValue(msg: "Действительно плохое значение")
+ throw MyError.reallyBadValue(msg: "Действительно плохое значение")
}
return "тест"
@@ -401,7 +401,7 @@ func testTryStuff() {
do {
// обычно try оператор, позволяющий обработать ошибку в `catch` блоке
try fakeFetch(value: 1)
- } catch MyError.BadValue(let msg) {
+ } catch MyError.badValue(let msg) {
print("Ошибка: \(msg)")
} catch {
// все остальное
@@ -535,49 +535,49 @@ if let circle = myEmptyCircle {
// Они могут содержать методы подобно классам.
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
// Значения перечислений допускают сокращенный синтаксис, нет необходимости
// указывать тип перечисления, когда переменная объявляется явно
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// Значения нецелочисленных перечислений должны быть указаны явно
// или могут выводится с помощью функции `rawValue` из имени
enum BookName: String {
- case John
- case Luke = "Лука"
+ case john
+ case luke = "Лука"
}
-print("Имя: \(BookName.John.rawValue)")
+print("Имя: \(BookName.john.rawValue)")
// Перечисление (enum) со связанными значениями
enum Furniture {
// Связать с типом Int
- case Desk(height: Int)
+ case desk(height: Int)
// Связать с типами String и Int
- case Chair(String, Int)
+ case chair(String, Int)
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Письменный стол высотой \(height) см."
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Стул марки \(brand) высотой \(height) см."
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Письменный стол высотой 80 см."
-var chair = Furniture.Chair("Foo", 40)
+var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Стул марки Foo высотой 40 см."
diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash-sk.html.markdown
index e9d1490c..e9d1490c 100644
--- a/sk-sk/bash.html.markdown
+++ b/sk-sk/bash-sk.html.markdown
diff --git a/sk-sk/coffeescript.html.markdown b/sk-sk/coffeescript-sk.html.markdown
index 30bbceec..30bbceec 100644
--- a/sk-sk/coffeescript.html.markdown
+++ b/sk-sk/coffeescript-sk.html.markdown
diff --git a/sk-sk/elixir.html.markdown b/sk-sk/elixir-sk.html.markdown
index 2401f92e..2401f92e 100644
--- a/sk-sk/elixir.html.markdown
+++ b/sk-sk/elixir-sk.html.markdown
diff --git a/sk-sk/git.html.markdown b/sk-sk/git-sk.html.markdown
index 21741406..21741406 100644
--- a/sk-sk/git.html.markdown
+++ b/sk-sk/git-sk.html.markdown
diff --git a/sk-sk/json.html.markdown b/sk-sk/json-sk.html.markdown
index 2b1fbb58..2b1fbb58 100644
--- a/sk-sk/json.html.markdown
+++ b/sk-sk/json-sk.html.markdown
diff --git a/sk-sk/latex.html.markdown.tex b/sk-sk/latex-sk.html.markdown.tex
index 5e2f9c7f..5e2f9c7f 100644
--- a/sk-sk/latex.html.markdown.tex
+++ b/sk-sk/latex-sk.html.markdown.tex
diff --git a/sk-sk/ruby.html.markdown b/sk-sk/ruby-sk.html.markdown
index 799865b0..799865b0 100644
--- a/sk-sk/ruby.html.markdown
+++ b/sk-sk/ruby-sk.html.markdown
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index fd40afe9..a253df55 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -186,7 +186,7 @@ x := Float pi. "pi"
x := Float e. "exp constant"
x := Float infinity. "infinity"
x := Float nan. "not-a-number"
-x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)
+x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)"
x := 100 atRandom. "quick random number"
```
@@ -904,7 +904,7 @@ b := String isVariable. "true if has indexed
b := String isPointers. "true if index instance vars contain objects"
b := String isBits. "true if index instance vars contain bytes/words"
b := String isBytes. "true if index instance vars contain bytes"
-b := String isWords. true if index instance vars contain words"
+b := String isWords. "true if index instance vars contain words"
Object withAllSubclasses size. "get total number of class entries"
```
diff --git a/solidity.html.markdown b/solidity.html.markdown
index fc54d6e4..a0f8cd40 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -37,8 +37,8 @@ features are typically marked, and subject to change. Pull requests welcome.
// simple_bank.sol (note .sol extension)
/* **** START EXAMPLE **** */
-// Declare the source file compiler version.
-pragma solidity ^0.4.2;
+// Declare the source file compiler version
+pragma solidity ^0.4.19;
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
@@ -65,7 +65,7 @@ contract SimpleBank { // CapWords
event LogDepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
- function SimpleBank() {
+ function SimpleBank() public {
// msg provides details about the message that's sent to the contract
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
@@ -73,7 +73,11 @@ contract SimpleBank { // CapWords
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
- function deposit() public returns (uint) {
+ function deposit() public payable returns (uint) {
+ // Use 'require' to test user inputs, 'assert' for internal invariants
+ // Here we are making sure that there isn't an overflow issue
+ require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
+
balances[msg.sender] += msg.value;
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
@@ -88,18 +92,17 @@ contract SimpleBank { // CapWords
/// @param withdrawAmount amount you want to withdraw
/// @return The balance remaining for the user
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
- if(balances[msg.sender] >= withdrawAmount) {
- // Note the way we deduct the balance right away, before sending - due to
- // the risk of a recursive call that allows the caller to request an amount greater
- // than their balance
- balances[msg.sender] -= withdrawAmount;
-
- if (!msg.sender.send(withdrawAmount)) {
- // increment back only on fail, as may be sending to contract that
- // has overridden 'send' on the receipt end
- balances[msg.sender] += withdrawAmount;
- }
- }
+ require(withdrawAmount <= balances[msg.sender]);
+
+ // Note the way we deduct the balance right away, before sending
+ // Every .transfer/.send from this contract can call an external function
+ // This may allow the caller to request an amount greater
+ // than their balance using a recursive call
+ // Aim to commit state before calling external functions, including .transfer/.send
+ balances[msg.sender] -= withdrawAmount;
+
+ // this automatically throws on a failure, which means the updated balance is reverted
+ msg.sender.transfer(withdrawAmount);
return balances[msg.sender];
}
@@ -108,18 +111,9 @@ contract SimpleBank { // CapWords
/// @return The balance of the user
// 'constant' prevents function from editing state variables;
// allows function to run locally/off blockchain
- function balance() constant returns (uint) {
+ function balance() constant public returns (uint) {
return balances[msg.sender];
}
-
- // Fallback function - Called if other functions don't match call or
- // sent ether without data
- // Typically, called when invalid data is sent
- // Added so ether sent to this contract is reverted if the contract fails
- // otherwise, the sender's money is transferred to contract
- function () {
- throw; // throw reverts state to before call
- }
}
// ** END EXAMPLE **
@@ -137,6 +131,11 @@ int256 constant a = 8; // same effect as line above, here the 256 is explicit
uint constant VERSION_ID = 0x123A1; // A hex constant
// with 'constant', compiler replaces each occurrence with actual value
+// All state variables (those outside a function)
+// are by default 'internal' and accessible inside contract
+// and in all contracts that inherit ONLY
+// Need to explicitly set to 'public' to allow external contracts to access
+int256 public a = 8;
// For int and uint, can explicitly set space in steps of 8 up to 256
// e.g., int8, int16, int24
@@ -145,6 +144,12 @@ int64 c;
uint248 e;
// Be careful that you don't overflow, and protect against attacks that do
+// For example, for an addition, you'd do:
+uint256 c = a + b;
+assert(c >= a); // assert tests for internal invariants; require is used for user inputs
+// For more examples of common arithmetic issues, see Zeppelin's SafeMath library
+// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
+
// No random functions built in, use other contracts for randomness
@@ -165,14 +170,14 @@ address public owner;
// a getter is automatically created, but NOT a setter
// All addresses can be sent ether
-owner.send(SOME_BALANCE); // returns false on failure
-if (owner.send) {} // REMEMBER: wrap in 'if', as contract addresses have
+owner.transfer(SOME_BALANCE); // fails and reverts on failure
+
+// Can also do a lower level .send call, which returns a false if it failed
+if (owner.send) {} // REMEMBER: wrap send in 'if', as contract addresses have
// functions executed on send and these can fail
// Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive
// call that can drain the contract
-// can override send by defining your own
-
// Can check balance
owner.balance; // the balance of the owner (user or contract)
@@ -213,7 +218,7 @@ uint x = 5;
// Destructuring/Tuples
-(x, y) = (2, 7); // assign/swap multiple value
+(x, y) = (2, 7); // assign/swap multiple values
// 2. DATA STRUCTURES
@@ -250,7 +255,7 @@ delete balances; // sets all elements to 0
// mapping, without knowing source keys - can build data structure
// on top to do this
-// Structs and enums
+// Structs
struct Bank {
address owner;
uint balance;
@@ -262,7 +267,7 @@ Bank b = Bank({
// or
Bank c = Bank(msg.sender, 5);
-c.amount = 5; // set to new value
+c.balance = 5; // set to new value
delete b;
// sets to initial value, set all variables in struct to 0, except mappings
@@ -273,7 +278,7 @@ state = State.Created;
// enums can be explicitly converted to ints
uint createdState = uint(State.Created); // 0
-// Data locations: Memory vs. storage vs. stack - all complex types (arrays,
+// Data locations: Memory vs. storage vs. calldata - all complex types (arrays,
// structs) have a data location
// 'memory' does not persist, 'storage' does
// Default is 'storage' for local and state variables; 'memory' for func params
@@ -292,13 +297,13 @@ uint createdState = uint(State.Created); // 0
// 4. Global Variables of note
// ** this **
this; // address of contract
-// often used at end of contract life to send remaining balance to party
+// often used at end of contract life to transfer remaining balance to party
this.balance;
this.someFunction(); // calls func externally via call, not via internal jump
// ** msg - Current message received by the contract ** **
msg.sender; // address of sender
-msg.value; // amount of ether provided to this contract in wei
+msg.value; // amount of ether provided to this contract in wei, the function should be marked "payable"
msg.data; // bytes, complete call data
msg.gas; // remaining gas
@@ -308,6 +313,8 @@ tx.gasprice; // gas price of the transaction
// ** block - Information about current block **
now; // current time (approximately), alias for block.timestamp (uses Unix time)
+// Note that this can be manipulated by miners, so use carefully
+
block.number; // current block number
block.difficulty; // current block difficulty
block.blockhash(1); // returns bytes32, only works for most recent 256 blocks
@@ -334,9 +341,10 @@ function increment(uint x, uint y) returns (uint x, uint y) {
// Call previous functon
uint (a,b) = increment(1,1);
-// 'constant' indicates that function does not/cannot change persistent vars
+// 'constant' (alias for 'view')
+// indicates that function does not/cannot change persistent vars
// Constant function execute locally, not on blockchain
-uint y;
+uint y = 1;
function increment(uint x) constant returns (uint x) {
x += 1;
@@ -344,13 +352,21 @@ function increment(uint x) constant returns (uint x) {
// y is a state variable, and can't be changed in a constant function
}
+// 'pure' is more strict than 'constant', and does not
+// even allow reading of state vars
+// The exact rules are more complicated, so see more about
+// constant/pure:
+// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions
+
// 'Function Visibility specifiers'
// These can be placed where 'constant' is, including:
-// public - visible externally and internally (default)
-// external
+// public - visible externally and internally (default for function)
+// external - only visible externally (including a call made with this.)
// private - only visible in the current contract
// internal - only visible in current contract, and those deriving from it
+// Generally, a good idea to mark each function explicitly
+
// Functions hoisted - and can assign a function to a variable
function a() {
var z = b;
@@ -361,8 +377,15 @@ function b() {
}
+// All functions that receive ether must be marked 'payable'
+function depositEther() public payable {
+ balances[msg.sender] += msg.value;
+}
+
// Prefer loops to recursion (max call stack depth is 1024)
+// Also, don't setup loops that you haven't bounded,
+// as this can hit the gas limit
// B. Events
// Events are notify external parties; easy to search and
@@ -378,7 +401,8 @@ event LogSent(address indexed from, address indexed to, uint amount); // note ca
// Call
Sent(from, to, amount);
-// For an external party (a contract or external entity), to watch:
+// For an external party (a contract or external entity), to watch using
+// the Web3 Javascript library:
Coin.Sent().watch({}, '', function(error, result) {
if (!error) {
console.log("Coin transfer: " + result.args.amount +
@@ -398,10 +422,10 @@ Coin.Sent().watch({}, '', function(error, result) {
// '_' (underscore) often included as last line in body, and indicates
// function being called should be placed there
-modifier onlyAfter(uint _time) { if (now <= _time) throw; _ }
-modifier onlyOwner { if (msg.sender == owner) _ }
+modifier onlyAfter(uint _time) { require (now >= _time); _; }
+modifier onlyOwner { require(msg.sender == owner) _; }
// commonly used with state machines
-modifier onlyIfState (State currState) { if (currState != State.A) _ }
+modifier onlyIfStateA (State currState) { require(currState == State.A) _; }
// Append right after function declaration
function changeOwner(newOwner)
@@ -415,12 +439,10 @@ onlyIfState(State.A)
// underscore can be included before end of body,
// but explicitly returning will skip, so use carefully
modifier checkValue(uint amount) {
- _
+ _;
if (msg.value > amount) {
uint amountToRefund = amount - msg.value;
- if (!msg.sender.send(amountToRefund)) {
- throw;
- }
+ msg.sender.transfer(amountToRefund);
}
}
@@ -437,22 +459,21 @@ modifier checkValue(uint amount) {
// amount of gas for a block of code - and will fail if that is exceeded
// For example:
for(uint x = 0; x < refundAddressList.length; x++) {
- if (!refundAddressList[x].send(SOME_AMOUNT)) {
- throw;
- }
+ refundAddressList[x].transfer(SOME_AMOUNT);
}
// Two errors above:
-// 1. A failure on send stops the loop from completing, tying up money
+// 1. A failure on transfer stops the loop from completing, tying up money
// 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and
// therefore may always fail as it exceeds the max gas for a block
// Instead, you should let people withdraw individually from their subaccount, and mark withdrawn
+// e.g., favor pull payments over push payments
// 7. OBJECTS/CONTRACTS
// A. Calling external contract
-contract infoFeed {
+contract InfoFeed {
function info() returns (uint ret) { return 42; }
}
@@ -502,23 +523,10 @@ function someAbstractFunction(uint x);
import "filename";
import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
-// Importing under active development
-// Cannot currently be done at command line
-
// 8. OTHER KEYWORDS
-// A. Throwing
-// Throwing
-throw; // reverts unused money to sender, state is reverted
-// Can't currently catch
-
-// Common design pattern is:
-if (!addr.send(123)) {
- throw;
-}
-
-// B. Selfdestruct
+// A. Selfdestruct
// selfdestruct current contract, sending funds to address (often creator)
selfdestruct(SOME_ADDRESS);
@@ -543,7 +551,7 @@ function remove() {
// that is private needs to be obfuscated (e.g., hashed w/secret)
// Steps: 1. Commit to something, 2. Reveal commitment
-sha3("some_bid_amount", "some secret"); // commit
+keccak256("some_bid_amount", "some secret"); // commit
// call contract's reveal function in the future
// showing bid plus secret that hashes to SHA3
@@ -617,6 +625,7 @@ contract SomeOracle {
// ** START EXAMPLE **
// CrowdFunder.sol
+pragma solidity ^0.4.19;
/// @title CrowdFunder
/// @author nemild
@@ -650,22 +659,20 @@ contract CrowdFunder {
event LogWinnerPaid(address winnerAddress);
modifier inState(State _state) {
- if (state != _state) throw;
- _
+ require(state == _state);
+ _;
}
modifier isCreator() {
- if (msg.sender != creator) throw;
- _
+ require(msg.sender == creator);
+ _;
}
- // Wait 6 months after final contract state before allowing contract destruction
+ // Wait 24 weeks after final contract state before allowing contract destruction
modifier atEndOfLifecycle() {
- if(!((state == State.ExpiredRefund || state == State.Successful) &&
- completeAt + 6 months < now)) {
- throw;
- }
- _
+ require(((state == State.ExpiredRefund || state == State.Successful) &&
+ completeAt + 24 weeks < now));
+ _;
}
function CrowdFunder(
@@ -673,6 +680,7 @@ contract CrowdFunder {
string _campaignUrl,
address _fundRecipient,
uint _minimumToRaise)
+ public
{
creator = msg.sender;
fundRecipient = _fundRecipient;
@@ -683,7 +691,9 @@ contract CrowdFunder {
function contribute()
public
+ payable
inState(State.Fundraising)
+ returns(uint256 id)
{
contributions.push(
Contribution({
@@ -699,7 +709,9 @@ contract CrowdFunder {
return contributions.length - 1; // return id
}
- function checkIfFundingCompleteOrExpired() {
+ function checkIfFundingCompleteOrExpired()
+ public
+ {
if (totalRaised > minimumToRaise) {
state = State.Successful;
payOut();
@@ -715,31 +727,23 @@ contract CrowdFunder {
public
inState(State.Successful)
{
- if(!fundRecipient.send(this.balance)) {
- throw;
- }
-
-
+ fundRecipient.transfer(this.balance);
LogWinnerPaid(fundRecipient);
}
- function getRefund(id)
- public
+ function getRefund(uint256 id)
inState(State.ExpiredRefund)
+ public
+ returns(bool)
{
- if (contributions.length <= id || id < 0 || contributions[id].amount == 0 ) {
- throw;
- }
+ require(contributions.length > id && id >= 0 && contributions[id].amount != 0 );
- uint amountToRefund = contributions[id].amount;
+ uint256 amountToRefund = contributions[id].amount;
contributions[id].amount = 0;
- if(!contributions[id].contributor.send(amountToSend)) {
- contributions[id].amount = amountToSend;
- return false;
- }
+ contributions[id].contributor.transfer(amountToRefund);
- return true;
+ return true;
}
function removeContract()
@@ -750,8 +754,6 @@ contract CrowdFunder {
selfdestruct(msg.sender);
// creator gets all money that hasn't be claimed
}
-
- function () { throw; }
}
// ** END EXAMPLE **
@@ -798,6 +800,7 @@ someContractAddress.callcode('function_name');
// 13. STYLE NOTES
// Based on Python's PEP8 style guide
+// Full Style guide: http://solidity.readthedocs.io/en/develop/style-guide.html
// Quick summary:
// 4 spaces for indentation
@@ -825,11 +828,16 @@ someContractAddress.callcode('function_name');
## Additional resources
- [Solidity Docs](https://solidity.readthedocs.org/en/latest/)
+- [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices)
- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide.
-- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/)
+- [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/)
+- [Browser-based Solidity Editor](https://remix.ethereum.org/)
- [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity)
- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/)
+## Important libraries
+- [Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity/): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+
## Sample contracts
- [Dapp Bin](https://github.com/ethereum/dapp-bin)
- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
@@ -841,9 +849,6 @@ someContractAddress.callcode('function_name');
- [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/)
- [Hacking Distributed Blog](http://hackingdistributed.com/)
-## Information purposefully excluded
-- Libraries
-
## Style
- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy
diff --git a/swift.html.markdown b/swift.html.markdown
index 60915d72..516debed 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -361,14 +361,14 @@ print("Name is \(name)") // Name is Them
// The `Error` protocol is used when throwing errors to catch
enum MyError: Error {
- case BadValue(msg: String)
- case ReallyBadValue(msg: String)
+ case badValue(msg: String)
+ case reallyBadValue(msg: String)
}
// functions marked with `throws` must be called using `try`
func fakeFetch(value: Int) throws -> String {
guard 7 == value else {
- throw MyError.ReallyBadValue(msg: "Some really bad value")
+ throw MyError.reallyBadValue(msg: "Some really bad value")
}
return "test"
@@ -385,7 +385,7 @@ func testTryStuff() {
do {
// normal try operation that provides error handling via `catch` block
try fakeFetch(value: 1)
- } catch MyError.BadValue(let msg) {
+ } catch MyError.badValue(let msg) {
print("Error message: \(msg)")
} catch {
// must be exhaustive
@@ -518,49 +518,49 @@ if let circle = myEmptyCircle {
// They can contain methods like classes.
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
// Enum values allow short hand syntax, no need to type the enum type
// when the variable is explicitly declared
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// String enums can have direct raw value assignments
// or their raw values will be derived from the Enum field
enum BookName: String {
- case John
- case Luke = "Luke"
+ case john
+ case luke = "Luke"
}
-print("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.john.rawValue)")
// Enum with associated Values
enum Furniture {
// Associate with Int
- case Desk(height: Int)
+ case desk(height: Int)
// Associate with String and Int
- case Chair(String, Int)
+ case chair(String, Int)
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Desk with \(height) cm"
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
-var chair = Furniture.Chair("Foo", 40)
+var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown
index e694d95d..4c2cf59b 100644
--- a/tr-tr/swift-tr.html.markdown
+++ b/tr-tr/swift-tr.html.markdown
@@ -443,47 +443,47 @@ if let daire = benimBosDairem {
// Sınıflar gibi metotlar içerebilirler.
enum Kart {
- case Kupa, Maca, Sinek, Karo
+ case kupa, maca, sinek, karo
func getIcon() -> String {
switch self {
- case .Maca: return "♤"
- case .Kupa: return "♡"
- case .Karo: return "♢"
- case .Sinek: return "♧"
+ case .maca: return "♤"
+ case .kupa: return "♡"
+ case .karo: return "♢"
+ case .sinek: return "♧"
}
}
}
// Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz.
-var kartTipi: Kart = .Kupa
+var kartTipi: Kart = .kupa
// Integer olmayan enumlar direk değer (rawValue) atama gerektirir.
enum KitapAdi: String {
- case John = "John"
- case Luke = "Luke"
+ case john = "John"
+ case luke = "Luke"
}
-print("Name: \(KitapAdi.John.rawValue)")
+print("Name: \(KitapAdi.john.rawValue)")
// Değerlerle ilişkilendirilmiş Enum
enum Mobilya {
// Int ile ilişkilendirilmiş
- case Masa(yukseklik: Int)
+ case masa(yukseklik: Int)
// String ve Int ile ilişkilendirilmiş
- case Sandalye(String, Int)
-
+ case sandalye(String, Int)
+
func aciklama() -> String {
switch self {
- case .Masa(let yukseklik):
+ case .masa(let yukseklik):
return "Masa boyu \(yukseklik) cm"
- case .Sandalye(let marka, let yukseklik):
+ case .sandalye(let marka, let yukseklik):
return "\(brand) marka sandalyenin boyu \(yukseklik) cm"
}
}
}
-var masa: Mobilya = .Masa(yukseklik: 80)
+var masa: Mobilya = .masa(yukseklik: 80)
print(masa.aciklama()) // "Masa boyu 80 cm"
-var sandalye = Mobilya.Sandalye("Foo", 40)
+var sandalye = Mobilya.sandalye("Foo", 40)
print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm"
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 44fd791a..acc258b4 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat
TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript.
It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript.
-This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown).
+This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](/docs/javascript).
To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript.
@@ -29,7 +29,7 @@ let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
-// Use const keyword for constant variables
+// Use const keyword for constants
const numLivesForCat = 9;
numLivesForCat = 1; // Error
diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown
index ac6a2bde..397b1c5e 100644
--- a/uk-ua/javascript-ua.html.markdown
+++ b/uk-ua/javascript-ua.html.markdown
@@ -17,7 +17,7 @@ JavaScript було створено в 1995 році Бренданом Айк
вбудована підтримка браузерами призвела до того, що JavaScript став популярніший
за власне Java.
-Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js,
+Зараз JavaScript не обмежується тільки веб-браузером. Наприклад, Node.js,
програмна платформа, що дозволяє виконувати JavaScript код з використанням
рушія V8 від браузера Google Chrome, стає все більш і більш популярною.
diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown
new file mode 100644
index 00000000..594ccc31
--- /dev/null
+++ b/vi-vn/less-vi.html.markdown
@@ -0,0 +1,395 @@
+---
+language: less
+contributors:
+ - ["Saravanan Ganesh", "http://srrvnn.me"]
+translators:
+ - ["Thanh Duy Phan", "https://github.com/thanhpd"]
+filename: learnless-vi.less
+lang: vi-vn
+---
+
+Less là một CSS pre-processor (bộ tiền xử lí CSS), nó thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Less cùng với các CSS pre-processor khác như [Sass](http://sass-lang.com/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself).
+
+```css
+
+
+// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS
+
+/* Comment trên nhiều dòng sẽ được giữ lại */
+
+
+
+/* Biến
+==============================*/
+
+
+/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến.
+ Sử dụng ký hiệu '@' để khai báo một biến. */
+
+@primary-color: #a3a4ff;
+@secondary-color: #51527f;
+@body-font: 'Roboto', sans-serif;
+
+/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet.
+ Nhờ sử dụng biến ta chỉ cần thay đổi một lần
+ tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */
+
+body {
+ background-color: @primary-color;
+ color: @secondary-color;
+ font-family: @body-font;
+}
+
+/* Đoạn code trên sẽ được biên dịch thành: */
+
+body {
+ background-color: #a3a4ff;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn
+ việc phải đổi giá trị mỗi lần nó xuất hiện
+ trong tệp stylesheet. */
+
+
+
+/* Mixins
+==============================*/
+
+
+/* Nếu đang viết một đoạn code cho nhiều hơn một
+ element, ta có thể sử dụng lại nó dễ dàng. */
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Ta có thể dùng mixin chỉ bằng việc thêm selector
+ vào trong nội dung style của element khác */
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* Đoạn code trên sẽ được biên dịch thành: */
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+/* Ta có thể ngăn không cho code mixin được biên dịch
+ bằng cách thêm cặp ngoặc tròn đằng sau selector */
+
+.center() {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/* Đoạn code trên sẽ được biên dịch thành: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #a3a4ff;
+}
+
+
+
+/* Nesting - Lồng
+==============================*/
+
+
+/* Less cho phép ta có thể lồng selector bên trong selector */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #f00;
+ }
+}
+
+/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&'
+ với selector cha. */
+/* Ta cũng có thể lồng các pseudo-class với nhau */
+/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì.
+ Kinh nghiệm cho thấy không nên lồng quá 3 lần.
+ Ví dụ: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Biên dịch thành: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Function
+==============================*/
+
+
+/* Less cung cấp các function có thể được dùng để hoàn thành
+ các công việc khác nhau. */
+
+/* Function được gọi sử dụng tên của nó và truyền vào
+ các tham số được yêu cầu. */
+
+body {
+ width: round(10.25px);
+}
+
+.header {
+ background-color: lighten(#000, 0.5);
+}
+
+.footer {
+ background-color: fadeout(#000, 0.25)
+}
+
+/* Biên dịch thành: */
+
+body {
+ width: 10px;
+}
+
+.header {
+ background-color: #010101;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Ta có thể định nghĩa function mới.
+ Function khá tương tự với mixin bởi chúng đều có thể được tái
+ sử dụng. Khi lựa chọn giữa việc sử dụng function hay mixin,
+ hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi
+ function sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng
+ xuyên suốt Less code. Các ví dụ trong phần 'Toán tử' là ứng cử viên
+ sáng giá cho việc dùng function có thể tái sử dụng được.
+*/
+
+/* Function này tính giá trị trung bình của hai số: */
+.average(@x, @y) {
+ @average-result: ((@x + @y) / 2);
+}
+
+div {
+ .average(16px, 50px); // gọi mixin
+ padding: @average-result; // sử dụng giá trị trả về của mixin
+}
+
+/* Biên dịch thành: */
+
+div {
+ padding: 33px;
+}
+
+
+
+/* Mở rộng (Thừa kế)
+==============================*/
+
+
+/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */
+
+.display {
+ height: 50px;
+}
+
+.display-success {
+ &:extend(.display);
+ border-color: #22df56;
+}
+
+/* Biên dịch thành: */
+.display,
+.display-success {
+ height: 50px;
+}
+.display-success {
+ border-color: #22df56;
+}
+
+/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới
+ bởi cách nó nhóm các lớp có chung một style gốc.
+ Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp
+ cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó
+ tạo ra các đoạn code CSS thừa sau khi được biên dịch.
+*/
+
+
+/* Partials and Imports - Chia nhỏ và nhập vào
+==============================*/
+
+
+/* Less cho phép ta tạo các partial file (tệp con).
+ Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống.
+ Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less
+ và được nhập vào file Less chính để được biên dịch thành CSS */
+
+/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Less cung cấp cú pháp @import cho phép nhập các partial vào một file.
+ Cú pháp này trong Less sẽ nhập các file và kết hợp chúng lại với
+ code CSS được sinh ra. Nó khác với cú pháp @import của CSS,
+ bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Biên dịch thành: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Toán học
+==============================*/
+
+
+/* Less cung cấp các toán tử sau: +, -, *, / và %.
+ Điều này rất có ích cho việc tính toán giá trị trực tiếp
+ trong tệp Less thay vì phải tính toán thủ công.
+ Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */
+
+@content-area: 960px;
+@main-content: 600px;
+@sidebar-content: 300px;
+
+@main-size: @main-content / @content-area * 100%;
+@sidebar-size: @sidebar-content / @content-area * 100%;
+@gutter: 100% - (@main-size + @sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: @main-size;
+}
+
+.sidebar {
+ width: @sidebar-size;
+}
+
+.gutter {
+ width: @gutter;
+}
+
+/* Biên dịch thành: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+## Tập sử dụng Less
+
+Nếu bạn cần xài thử Less trên trình duyệt, hãy ghé qua:
+* [Codepen](http://codepen.io/)
+* [LESS2CSS](http://lesscss.org/less-preview/)
+
+## Tính tương thích
+
+Less có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS.
+
+## Tìm hiểu thêm
+* [Tài liệu chính thức](http://lesscss.org/features/)
+* [Less CSS - Hướng dẫn cho người mới bắt đầu](http://www.hongkiat.com/blog/less-basic/) \ No newline at end of file
diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown
new file mode 100644
index 00000000..0ba267f9
--- /dev/null
+++ b/vi-vn/markdown-vi.html.markdown
@@ -0,0 +1,325 @@
+---
+language: markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
+translators:
+ - ["Thanh Duy Phan", "https://github.com/thanhpd"]
+filename: markdown-vi.md
+lang: vi-vn
+---
+
+
+Ngôn ngữ Markdown được sáng lập bởi John Gruber vào năm 2004. Nó được tạo ra với mục đích dễ đọc với cú pháp có thể được dễ dàng chuyển đổi qua HTML và các ngôn ngữ khác
+
+Markdown có sự khác biệt trong cách cài đặt giữa các trình phân tích cú pháp. Hướng dẫn này sẽ đề cập, giải thích tới nếu tính năng có thể được sử dụng chung hay nó chỉ áp dụng cho một trình phân tích riêng biệt.
+
+- [Phần tử HTML](#html-elements)
+- [Đầu mục](#headings)
+- [Định dạng văn bản](#simple-text-styles)
+- [Đoạn văn](#paragraphs)
+- [Danh sách](#lists)
+- [Khối code](#code-blocks)
+- [Đường kẻ ngang](#horizontal-rule)
+- [Liên kết](#links)
+- [Ảnh](#images)
+- [Khác](#miscellany)
+
+## Phần tử HTML
+Markdown là tập cha của HTML, vì vậy bất cứ file HTML nào đều là Markdown đúng.
+
+```markdown
+<!-- Điều này đồng nghĩa ta có thể sử dụng các phần tử HTML
+trong Markdown, ví dụ như phần tử chú thích/comment.
+Tuy nhiên, nếu sử dụng một phần tử HTML trong file Markdown,
+ta không thể sử dụng cú pháp Markdown cho nội dung bên trong phần tử đó. -->
+```
+
+## Đầu mục
+
+Ta có thể tạo các phần tử đầu mục HTML từ `<h1>` cho đến `<h6>` dễ dàng
+bằng cách thêm số lượng dấu thăng (#) đằng trước chuỗi cần tạo đầu mục.
+
+```markdown
+# Đây là đầu mục <h1>
+## Đây là đầu mục <h2>
+### Đây là đầu mục <h3>
+#### Đây là đầu mục <h4>
+##### Đây là đầu mục <h5>
+###### Đây là đầu mục <h6>
+```
+Markdown còn cung cấp cách khác để tạo đầu mục hạng nhất h1 và hạng nhì h2.
+
+```markdown
+Đây là đầu mục h1
+=============
+
+Đây là đầu mục h2
+-------------
+```
+
+## Định dạng văn bản
+
+Văn bản có thể được định dạng dễ dàng như in nghiêng hay làm đậm sử dụng Markdown.
+
+```markdown
+*Đoạn văn bản này được in nghiêng.*
+_Và đoạn này cũng như vậy._
+
+**Đoạn văn bản này được in đậm.**
+__Và đoạn này cũng vậy.__
+
+***Đoạn văn bản này được in nghiêng và đậm.***
+**_Cách này cũng tương tự_**
+*__Và cách này nữa__*
+```
+
+Trong cài đặt Markdown để hiển thị file của GitHub,ta còn có gạch ngang:
+
+```markdown
+~~Đoạn văn bản này được gạch ngang.~~
+```
+## Đoạn văn
+
+Đoạn văn bao gồm một hay nhiều dòng văn bản liên tiếp nhau được phân cách
+bởi một hay nhiều dòng trống.
+
+```markdown
+Đây là đoạn văn thứ nhất.
+
+Đây là đoạn văn thứ hai.
+Dòng này vẫn thuộc đoạn văn thứ hai, do không có cách dòng.
+
+
+Đây là đoạn văn thứ ba.
+```
+
+Nếu cần chèn thêm thẻ ngắt dòng `<br />` của HTML, ta có thể kết thúc đoạn văn bản
+bằng cách thêm vào từ 2 dấu cách (space) trở lên và bắt đầu đoạn văn bản mới.
+
+```markdown
+Dòng này kết thúc với 2 dấu cách (highlight để nhìn thấy).
+
+Có phần tử <br /> ở bên trên.
+```
+
+Khối trích dẫn được sử dụng với kí tự >
+
+```markdown
+> Đây là khối trích dẫn. Ta có thể
+> ngắt dòng thủ công và thêm kí tự `>` trước mỗi dòng hoặc ta có thể để dòng tự ngắt nếu cần thiệt khi quá dài.
+> Không có sự khác biệt nào, chỉ cần nó bắt đầu với kí tự `>`
+
+> Ta còn có thể dùng nhiều mức
+>> của khối trích dẫn.
+> Như vậy có tốt không?
+
+```
+
+## Danh sách
+
+Danh sách không có thứ tự có thể được tạo sử dụng dấu sao, dấu cộng hay dấu trừ đầu dòng.
+
+```markdown
+* Một mục
+* Một mục
+* Một mục nữa
+
+hoặc
+
++ Một mục
++ Một mục
++ Một mục khác
+
+hay
+
+- Một mục
+- Một mục
+- Một mục sau
+```
+
+Danh sách có thứ tự được tạo bởi một số theo sau bằng một dấu chấm.
+
+```markdown
+1. Mục thứ nhất
+2. Mục thứ hai
+3. Mục thứ ba
+```
+
+Ta không nhất thiết phải điền số thứ thự cho chỉ mục đúng mà Markdown sẽ tự hiển thị danh sách theo thứ tự đã được sắp xếp, tuy nhiên cách làm này không tốt!
+
+```markdown
+1. Mục thứ nhất
+1. Mục thứ hai
+1. Mục thứ ba
+```
+(Sẽ hiển thị như ví dụ trước đó)
+
+Ta còn có thể sử dụng danh sách con
+
+```markdown
+1. Mục thứ nhất
+2. Mục thứ hai
+3. Mục thứ ba
+ * Mục nhỏ
+ * Mục nhỏ
+4. Mục thứ tư
+```
+
+Markdown còn cung cấp danh mục (checklist). Nó sẽ hiển thị ra hộp đánh dấu dạng HTML.
+
+```markdown
+Boxes below without the 'x' are unchecked HTML checkboxes.
+- [ ] First task to complete.
+- [ ] Second task that needs done
+This checkbox below will be a checked HTML checkbox.
+- [x] This task has been completed
+```
+
+## Khối code
+
+Ta có thể đánh dấu một đoạn code (tương tự sử dụng phần tử HTML `<code>`) bằng việc thụt đầu dòng sử dụng bốn dấu cách (space) hoặc một dấu nhảy (tab)
+
+```markdown
+ This is code
+ So is this
+```
+
+Ta còn có thể thêm dấu nhảy (hoặc thêm vào bốn dấu cách nữa) để căn chỉnh phần bên trong đoạn code
+
+```markdown
+ my_array.each do |item|
+ puts item
+ end
+```
+
+Code hiển thị cùng dòng có thể được đánh dấu sử dụng cặp ``.
+
+```markdown
+John didn't even know what the `go_to()` function did!
+```
+
+Trong Markdown của GitHub, ta còn có thêm cách để hiển thị code:
+
+<pre>
+<code class="highlight">&#x60;&#x60;&#x60;ruby
+def foobar
+ puts "Hello world!"
+end
+&#x60;&#x60;&#x60;</code></pre>
+
+The above text doesn't require indenting, plus GitHub will use syntax
+highlighting of the language you specify after the \`\`\`
+Đoạn trên không cần sử dụng thụt đầu dòng, và GitHub sẽ tô sáng cú pháp sử dụng ngôn ngữ mà ta cung cấp sau đoạn kí tự \`\`\`
+
+## Kẻ ngang
+
+Dòng kẻ ngang (`<hr />`) có thể được thêm vào dễ dàng sử dụng từ 3 kí tự sao (*) hoặc gạch ngang (-), không quan trọng có khoảng cách giữa các kí tự hay không.
+
+
+```markdown
+***
+---
+- - -
+****************
+```
+
+## Liên kết
+
+Một trong những thứ tốt nhất khi làm việc với Markdown là khả năng tạo liên kết hết sức dễ dàng. Đoạn text hiển thị được đóng trong cặp ngoặc vuông [] kèm theo đường dẫn url trong cặp ngoặc tròn ().
+
+```markdown
+[Click me!](http://test.com/)
+```
+Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nháy bên trong cặp ngoặc tròn
+
+```markdown
+[Click me!](http://test.com/ "Link to Test.com")
+```
+Đường dẫn tương đối cũng hoạt động.
+
+```markdown
+[Go to music](/music/).
+```
+
+Markdown còn hỗ trợ liên kết kiểu tham chiếu.
+
+<pre><code class="highlight">&#x5b;<span class="nv">Nhấn vào đây</span>][<span class="ss">link1</span>] để xem thêm!
+&#x5b;<span class="nv">Ngoài ra nhấn vào đây</span>][<span class="ss">foobar</span>] nếu bạn muốn xem qua.
+
+&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Tuyệt!"</span>
+&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Tốt!"</span></code></pre>
+
+Tiêu đề có thể được đóng trong dấu nháy hay ngoặc đơn, hoặc có thể được bỏ qua. Tham chiếu có thể được đặt bất kì đâu trong văn bản và ID của tham chiếu có thể là bất kì gì miễn là nó độc nhất.
+
+Ngoài ra còn có kiểu đặt tên ngầm cho phép ta sử dụng đường dẫn làm ID.
+
+<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+
+&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+
+Nhưng nó không được sử dụng rộng rãi.
+
+## Ảnh
+
+Hiển thị ảnh tương tự như liên kết nhưng có thêm dấu chấm than đằng trước
+
+```markdown
+![Thuộc tính alt cho ảnh](http://imgur.com/myimage.jpg "Tiêu đề tùy chọn")
+```
+
+Và kiểu tham chiếu cũng hoạt động như vậy.
+
+<pre><code class="highlight">!&#x5b;<span class="nv">Đây là thuộc tính alt.</span>][<span class="ss">myimage</span>]
+
+&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Đây là tiêu đề"</span></code></pre>
+
+## Khác
+
+### Tự động đặt liên kết
+
+```markdown
+<http://testwebsite.com/> tương đương với
+[http://testwebsite.com/](http://testwebsite.com/)
+```
+
+### Tự động đặt liên kết cho email
+
+```markdown
+<foo@bar.com>
+```
+
+### Hiển thị Kí tự đặc biệt
+
+```markdown
+Khi ta muốn viết *đoạn văn bản này có dấu sao bao quanh* nhưng ta không muốn nó bị in nghiêng, ta có thể sử dụng: \*đoạn văn bản này có dấu sao bao quanh\*.
+```
+
+### Phím bàn phím
+
+Trong Markdown của Github, ta có thể sử dụng thẻ `<kbd>` để thay cho phím trên bàn phím.
+
+```markdown
+Máy treo? Thử bấm tổ hợp
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+### Bảng biểu
+
+Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v và khá khó viết:
+
+```markdown
+| Cột 1 | Cột2 | Cột 3 |
+| :----------- | :------: | ------------: |
+| Căn trái | Căn giữa | Căn phải |
+| blah | blah | blah |
+```
+Hoặc có thể sử dụng kết quả dưới đây
+
+```markdown
+Cột 1 | Cột 2 | Cột 3
+:-- | :-: | --:
+blah | blah | blah
+```
+
+---
+Để biết thêm thông tin, hãy ghé qua hướng dẫn chính thức về cú pháp của John Gruber [tại đây](http://daringfireball.net/projects/markdown/syntax) và cheatsheet của Adam Pritchard [tại đây](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown
new file mode 100644
index 00000000..313890d4
--- /dev/null
+++ b/vi-vn/sass-vi.html.markdown
@@ -0,0 +1,590 @@
+---
+language: sass
+filename: learnsass-vi.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Kyle Mendes", "https://github.com/pink401k"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["Thanh Duy Phan", "https://github.com/thanhpd"]
+lang: vi-vn
+---
+
+Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself).
+
+Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy.
+Bài hướng dẫn này sử dụng SCSS.
+
+Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn.
+
+```sass
+
+
+// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS
+
+/* Comment trên nhiều dòng sẽ được giữ lại */
+
+
+
+/* Variable - Biến
+============================== */
+
+
+
+/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến.
+ Sử dụng ký hiệu '$' để khai báo một biến. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet.
+ Nhờ sử dụng biến ta chỉ cần thay đổi một lần
+ tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Đoạn code trên sẽ được biên dịch thành: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn
+ việc phải đổi giá trị mỗi lần nó xuất hiện
+ trong tệp stylesheet. */
+
+
+
+/* Control Directive - Chỉ thị
+============================== */
+
+
+/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */
+
+/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */
+
+$debug: true !default;
+
+@mixin debugmode {
+ @if $debug {
+ @debug "Debug mode enabled";
+
+ display: inline-block;
+ }
+ @else {
+ display: none;
+ }
+}
+
+.info {
+ @include debugmode;
+}
+
+/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại.
+ Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line).
+ Chế độ này rất có ích khi thực hiện debug trên file SCSS. */
+
+.info {
+ display: inline-block;
+}
+
+/* @for là khối vòng lặp trên một khoảng các giá trị.
+ Nó rất có ích cho việc đặt style của một tập hợp các phần tử.
+ Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */
+
+// Lặp 3 lần (không kể 4)
+@for $c from 1 to 4 {
+ div:nth-of-type(#{$c}) {
+ left: ($c - 1) * 900 / 3;
+ }
+}
+
+// Lặp 3 lần (kể cả 3)
+@for $c from 1 through 3 {
+ .myclass-#{$c} {
+ color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3);
+ }
+}
+
+/* Biên dịch thành */
+
+div:nth-of-type(1) {
+ left: 0;
+}
+
+div:nth-of-type(2) {
+ left: 300;
+}
+
+div:nth-of-type(3) {
+ left: 600;
+}
+
+.myclass-1 {
+ color: #555555;
+}
+
+.myclass-2 {
+ color: #aaaaaa;
+}
+
+.myclass-3 {
+ color: white;
+// SASS tự động chuyển mã #FFFFFF thành white (trắng)
+}
+
+/* Khối lặp @while rất cơ bản: */
+
+$columns: 4;
+$column-width: 80px;
+
+@while $columns > 0 {
+ .col-#{$columns} {
+ width: $column-width;
+ left: $column-width * ($columns - 1);
+ }
+
+ $columns: $columns - 1;
+}
+
+/* Sẽ được biên dịch thành: */
+
+.col-4 {
+ width: 80px;
+ left: 240px;
+}
+
+.col-3 {
+ width: 80px;
+ left: 160px;
+}
+
+.col-2 {
+ width: 80px;
+ left: 80px;
+}
+
+.col-1 {
+ width: 80px;
+ left: 0px;
+}
+
+/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm.
+ List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */
+
+$social-links: facebook twitter linkedin reddit;
+
+.social-links {
+ @each $sm in $social-links {
+ .icon-#{$sm} {
+ background-image: url("images/#{$sm}.png");
+ }
+ }
+}
+
+/* Sẽ sinh ra: */
+
+.social-links .icon-facebook {
+ background-image: url("images/facebook.png");
+}
+
+.social-links .icon-twitter {
+ background-image: url("images/twitter.png");
+}
+
+.social-links .icon-linkedin {
+ background-image: url("images/linkedin.png");
+}
+
+.social-links .icon-reddit {
+ background-image: url("images/reddit.png");
+}
+
+
+/* Mixin
+==============================*/
+
+/* Nếu đang viết một đoạn code cho nhiều hơn một
+ element, ta có thể sử dụng lại nó dễ dàng.
+ Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Được biên dịch thành: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height
+ bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Biên dịch thành: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/* Function - Hàm
+============================== */
+
+
+
+/* Less cung cấp các hàm có thể được dùng để hoàn thành
+ các công việc khác nhau. */
+
+/* Hàm được gọi sử dụng tên của nó và truyền vào
+ các tham số được yêu cầu. */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25);
+}
+
+/* Biên dịch thành: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Ta có thể định nghĩa hàm mới.
+ hàm khá tương tự với mixin bởi chúng đều có thể được tái
+ sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin,
+ hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi
+ hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng
+ xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên
+ sáng giá cho việc dùng hàm có thể tái sử dụng được.
+*/
+
+/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Biên dịch thành: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Mở rộng (Thừa kế)
+============================== */
+
+
+
+/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Biên dịch thành: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới
+ bởi cách nó nhóm các lớp có chung một style gốc.
+ Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp
+ cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó
+ tạo ra các đoạn code CSS thừa sau khi được biên dịch.
+*/
+
+
+
+/* Nesting - Lồng
+============================== */
+
+
+
+/* Sass cho phép ta có thể lồng selector bên trong selector */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&'
+ với selector cha. */
+/* Ta cũng có thể lồng các pseudo-class với nhau */
+/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì.
+ Kinh nghiệm cho thấy không nên lồng quá 3 lần.
+ Ví dụ: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Biên dịch thành: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào
+============================== */
+
+
+/* Less cho phép ta tạo các partial file (tệp con).
+ Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống.
+ Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less
+ và được nhập vào file Less chính để được biên dịch thành CSS.
+ File con không được biên dịch thành file CSS riêng. */
+
+/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file.
+ Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với
+ code CSS được sinh ra. Nó khác với cú pháp @import của CSS,
+ bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Biên dịch thành: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/* Placeholder Selectors - Selector trống
+============================== */
+
+
+
+/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng.
+ Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể
+ sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì
+ sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Biên dịch thành: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/* Toán tử toán học
+============================== */
+
+
+
+/* Sass cung cấp các toán tử sau: +, -, *, / và %.
+ Điều này rất có ích cho việc tính toán giá trị trực tiếp
+ trong tệp Sass thay vì phải tính toán thủ công.
+ Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Biên dịch thành: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+```
+
+## SASS hay Sass?
+Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass.
+Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc).
+
+
+## Tập sử dụng Sass
+Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS.
+
+## Tính tương thích
+Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS.
+
+
+## Tìm hiểu thêm
+* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức.
diff --git a/vi-vn/typescript-vi.html.markdown b/vi-vn/typescript-vi.html.markdown
new file mode 100644
index 00000000..ba459c11
--- /dev/null
+++ b/vi-vn/typescript-vi.html.markdown
@@ -0,0 +1,193 @@
+---
+language: TypeScript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+translators:
+ - ["Thanh Duy Phan", "https://github.com/thanhpd"]
+filename: learntypescript-vi.ts
+lang: vi-vn
+---
+
+TypeScript là ngôn ngữ được viết nhằm tinh giản quá trình phát triển ứng dụng quy mô lớn được viết bằng JavaScript.
+TypeScript bổ sung thêm các khái niệm phổ biến như Class, Module, Interface, Generic và Static typing (tùy chọn) vào JavaScript.
+Ngôn ngữ này là tập lớn hơn của JavaScript: tất cả code JavaScript đều là code TypeScript đúng nên nó có thể được thêm vào các dự án một cách nhanh chóng. Trình biên dịch TypeScript sẽ sinh ra JavaScript.
+
+Bài viết này sẽ chỉ tập trung tới các cú pháp bổ sung mà TypeScript thêm vào thay vì nói đến cả các cú pháp [JavaScript](javascript-vi.html.markdown).
+
+Để thử dùng TypeScript với trình biên dịch, đi đến [Sân chơi TypeScript](http://www.typescriptlang.org/play) nơi mà bạn có thể nhập code, sử dụng chức năng hỗ trợ tự hoàn thành code - autocompletion và trực tiếp quan sát mã JavaScript được sinh ra.
+
+```ts
+// Đây là 3 khai báo kiểu biến cơ bản trong TypeScript
+// (JavaScript chỉ có kiểu của giá trị, không có kiểu của biến)
+let isDone: boolean = false;
+let lines: number = 42;
+let name: string = "Anders";
+
+// Bạn có thể bỏ khai báo kiểu của biến nếu như nó đã được suy ra từ kiểu giá trị cơ bản
+let isDone = false;
+let lines = 42;
+let name = "Anders";
+
+// Có kiểu biến "any" tương thích với mọi kiểu của biến,
+// được dùng khi ta không chắc chắn về kiểu của biến khi được khai báo
+let notSure: any = 4;
+notSure = "có thể là một biến kiểu string";
+notSure = false; // cũng có thể là biến kiểu boolean
+
+// Dùng từ khóa const cho khái báo biến không thay đổi (constant variable)
+const numLivesForCat = 9;
+numLivesForCat = 1; // Có lỗi!
+
+// Khi khai báo tập hợp ta có thể dùng mảng có kiểu được khai báo trước - typed array
+let list: number[] = [1, 2, 3];
+// Ta cũng có thể sử dụng mảng kiểu chung - generic array
+let list: Array<number> = [1, 2, 3];
+
+// Để dùng enumeration - danh sách của một tập hợp:
+enum Color { Red, Green, Blue };
+let c: Color = Color.Green;
+
+// Nếu function không trả về kết quả, sử dụng "void" cho kết quả trả về
+function bigHorribleAlert(): void {
+ alert("I'm a little annoying box!");
+}
+
+// Function trong TypeScript là first-class citizen (tạm dịch: phần tử hạng nhất), hỗ trợ thao tác tới các thực thể khác
+// (vd: truyền vào như tham số, được trả về từ function, chỉnh sửa, gán vào một biến)
+// TypeScript hỗ trợ sử dụng function với cú pháp lambda (mũi tên) và suy luận kiểu trả về
+
+// Các cú pháp dưới đây tương đương với nhau,
+// trình biên dịch sẽ tự nhận biết và sinh ra mã JavaScript giống nhau
+let f1 = function (i: number): number { return i * i; }
+// Kiểu trả về nếu không khai báo được tự suy diễn
+let f2 = function (i: number) { return i * i; }
+// Cú pháp mũi tên (arrow syntax)
+let f3 = (i: number): number => { return i * i; }
+// Cú pháp mũi tên với kiểu trả về được suy diễn
+let f4 = (i: number) => { return i * i; }
+// Cú pháp mũi tên với kiểu trả về được suy diễn
+// khi không sử dụng dấu ngoặc nhọn {} thì không cần sử dụng return
+let f5 = (i: number) => i * i;
+
+// Interface mang tính cấu trúc, mọi thứ có các đặc điểm (property) đều tương thích
+interface IPerson {
+ name: string;
+ // Đặc điểm có thể tùy chọn bằng sử dụng dấu "?"
+ age?: number;
+ // Có thể sử dụng function
+ move(): void;
+}
+
+// Object sử dụng interface IPerson nói trên
+// có thể được coi là 1 thực thể Person vì nó có đặc điểm name và chức năng move
+let p: Person = { name: "Bobby", move: () => { } };
+// Object sử dụng property tùy chọn
+let validPerson: Person = { name: "Bobby", age: 42, move: () => { } };
+// Khai báo dưới đây gây lỗi vì giá trị đặc điểm age không mang kiểu number
+let invalidPerson: Person = { name: "Bobby", age: true };
+
+// Interface cũng có thể mô tả đặc tả của function
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+// Chỉ có kiểu của tham số là quan trọng còn tên không quan trọng
+let mySearch: SearchFunc;
+mySearch = function (src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// Class - các khai báo mặc định là public
+class Point {
+ // Property
+ x: number;
+
+ // Constructor - sử dụng tham số với từ khóa public/private
+ // sẽ tạo ra property tương ứng (ví dụ với property y)
+ // Có thể khai báo giá trị mặc định
+
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // Function
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Biến Static
+ static origin = new Point(0, 0);
+}
+
+let p1 = new Point(10, 20);
+let p2 = new Point(25); // y sử dụng giá trị mặc định là 0
+
+// Thừa kế - Inheritance
+class Point3D extends Point {
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Bắt buộc phải gọi constructor của class cha
+ }
+
+ // Overwrite/Polymorphism - Ghi đè/Đa hình
+ dist() {
+ let d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// module, "." có thể được dùng như những module con
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+let s1 = new Geometry.Square(5);
+
+// Bí danh (alias) có thể được sử dụng để tham vấn module khác
+import G = Geometry;
+
+let s2 = new G.Square(10);
+
+// Generic
+// Class
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// Interface
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// Function
+let pairToTuple = function <T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+let tuple = pairToTuple({ item1: "hello", item2: "world" });
+
+// Các thư viện viết bằng JavaScript thường đi kèm file định nghĩa kiểu để có thể sử dụng cho TypeScript
+// Thêm vào tham vấn tới file định nghĩa:
+/// <reference path="jquery.d.ts" />
+
+// Template Strings - Chuỗi dạng mẫu (string sử dụng dấu `)
+// String Interpolation - Nội suy chuỗi with với template string
+let name = 'Tyrone';
+let greeting = `Chào ${name}, bạn khỏe không?`
+// Chuỗi nhiều dòng với template string
+let multiline = `Đây là ví dụ
+cho chuỗi nhiều dòng`;
+
+```
+
+## Tìm hiểu thêm
+
+* [Website TypeScript chính thức](http://www.typescriptlang.org/)
+* [Đặc tả ngôn ngữ TypeScript] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)
+* [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+* [Mã nguồn trên GitHub] (https://github.com/Microsoft/TypeScript)
+* [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/vim.html.markdown b/vim.html.markdown
index 7723136f..15144b8d 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -8,15 +8,16 @@ filename: LearnVim.txt
[Vim](http://www.vim.org)
-(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text
-editor designed for speed and increased productivity, and is ubiquitous in most
-unix-based systems. It has numerous keybindings for speedy navigation to
+(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text
+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.
## Basics of navigating Vim
```
vim <filename> # Open <filename> in vim
+ :help <topic> # Open up built-in help docs about <topic> if any exists
:q # Quit vim
:w # Save current file
:wq # Save file and quit vim
@@ -51,12 +52,12 @@ specific points in the file, and for fast editing.
# Jumping to characters
f<character> # Jump forward and land on <character>
- t<character> # Jump forward and land right before <character>
+ t<character> # Jump forward and land right before <character>
- # For example,
+ # For example,
f< # Jump forward and land on <
t< # Jump forward and land right before <
-
+
# Moving by word
w # Move forward by one word
@@ -73,19 +74,28 @@ specific points in the file, and for fast editing.
L # Move to the bottom of the screen
```
+## Help docs:
+
+Vim has built in help documentation that can accessed with `:help <topic>`.
+For example `:help navigation` will pull up documentation about how to navigate
+your workspace!
+
+`:help` can also be used without an option. This will bring up a default help dialog
+that aims to make getting started with vim more approachable!
+
## Modes:
Vim is based on the concept on **modes**.
-Command Mode - vim starts up in this mode, used to navigate and write commands
-Insert Mode - used to make changes in your file
-Visual Mode - used to highlight text and do operations to them
+Command Mode - vim starts up in this mode, used to navigate and write commands
+Insert Mode - used to make changes in your file
+Visual Mode - used to highlight text and do operations to them
Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands
```
i # Puts vim into insert mode, before the cursor position
a # Puts vim into insert mode, after the cursor position
- v # Puts vim into visual mode
+ v # Puts vim into visual mode
: # Puts vim into ex mode
<esc> # 'Escapes' from whichever mode you're in, into Command mode
@@ -102,18 +112,18 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm
## The 'Grammar' of vim
-Vim can be thought of as a set of commands in a
+Vim can be thought of as a set of commands in a
'Verb-Modifier-Noun' format, where:
-Verb - your action
-Modifier - how you're doing your action
+Verb - your action
+Modifier - how you're doing your action
Noun - the object on which your action acts on
A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
```
# 'Verbs'
-
+
d # Delete
c # Change
y # Yank (copy)
@@ -135,7 +145,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
s # Sentence
p # Paragraph
b # Block
-
+
# Sample 'sentences' or commands
d2w # Delete 2 words
@@ -180,7 +190,7 @@ Here's a sample ~/.vimrc file:
```
" Example ~/.vimrc
-" 2015.10
+" 2015.10
" Required for vim to be iMproved
set nocompatible
diff --git a/whip.html.markdown b/whip.html.markdown
index e7e5e427..c692714a 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -3,6 +3,7 @@ language: whip
contributors:
- ["Tenor Biel", "http://github.com/L8D"]
- ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
+ - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
author: Tenor Biel
author_url: http://github.com/L8D
filename: whip.lisp
@@ -232,6 +233,7 @@ undefined ; user to indicate a value that hasn't been set
(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese")
; Join list of strings together.
(unwords ("foo" "bar")) ; => "foobar"
+; Successor and Predecessor
(pred 21) ; => 20
(succ 20) ; => 21
```
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 3b32a069..52658453 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -2,8 +2,8 @@
language: yaml
filename: learnyaml.yaml
contributors:
- - ["Adam Brenecki", "https://github.com/adambrenecki"]
- - ["Suhas SG", "https://github.com/jargnar"]
+- [Adam Brenecki, 'https://github.com/adambrenecki']
+- [Suhas SG, 'https://github.com/jargnar']
---
YAML is a data serialisation language designed to be directly writable and
@@ -11,7 +11,7 @@ readable by humans.
It's a strict superset of JSON, with the addition of syntactically
significant newlines and indentation, like Python. Unlike Python, however,
-YAML doesn't allow literal tab characters at all.
+YAML doesn't allow literal tab characters for indentation.
```yaml
# Comments in YAML look like this.
@@ -32,8 +32,10 @@ boolean: true
null_value: null
key with spaces: value
# Notice that strings don't need to be quoted. However, they can be.
-however: "A string, enclosed in quotes."
-"Keys can be quoted too.": "Useful if you want to put a ':' in your key."
+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."
# Multiple-line strings can be written either as a 'literal block' (using |),
# or a 'folded block' (using '>').
@@ -59,12 +61,12 @@ folded_style: >
# COLLECTION TYPES #
####################
-# Nesting is achieved by indentation.
+# Nesting uses indentation. 2 space indent is preferred (but not required).
a_nested_map:
- key: value
- another_key: Another Value
- another_nested_map:
- hello: hello
+ key: value
+ another_key: Another Value
+ another_nested_map:
+ hello: hello
# Maps don't have to have string keys.
0.25: a float key
@@ -72,8 +74,8 @@ a_nested_map:
# Keys can also be complex, like multi-line objects
# We use ? followed by a space to indicate the start of a complex key.
? |
- This is a key
- that has multiple lines
+ This is a key
+ that has multiple lines
: and this is its value
# YAML also allows mapping between sequences with the complex key syntax
@@ -83,22 +85,26 @@ a_nested_map:
- Real Madrid
: [ 2001-01-01, 2002-02-02 ]
-# Sequences (equivalent to lists or arrays) look like this:
+# Sequences (equivalent to lists or arrays) look like this
+# (note that the '-' counts as indentation):
a_sequence:
- - Item 1
- - Item 2
- - 0.5 # sequences can contain disparate types.
- - Item 4
- - key: value
- another_key: another_value
- -
- - This is a sequence
- - inside another sequence
+- Item 1
+- Item 2
+- 0.5 # sequences can contain disparate types.
+- Item 4
+- key: value
+ another_key: another_value
+-
+ - This is a sequence
+ - inside another sequence
+- - - Nested sequence indicators
+ - can be collapsed
# Since YAML is a superset of JSON, you can also write JSON-style maps and
# sequences:
json_map: {"key": "value"}
json_seq: [3, 2, 1, "takeoff"]
+and quotes are optional: {key: [3, 2, 1, takeoff]}
#######################
# EXTRA YAML FEATURES #
@@ -111,15 +117,15 @@ other_anchor: *anchor_name
# Anchors can be used to duplicate/inherit properties
base: &base
- name: Everyone has same name
+ name: Everyone has same name
foo: &foo
- <<: *base
- age: 10
+ <<: *base
+ age: 10
bar: &bar
- <<: *base
- age: 20
+ <<: *base
+ age: 20
# foo and bar would also have name: Everyone has same name
@@ -147,22 +153,23 @@ date: 2002-12-14
# The !!binary tag indicates that a string is actually a base64-encoded
# representation of a binary blob.
gif_file: !!binary |
- R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
- OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
- +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
- AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# YAML also has a set type, which looks like this:
set:
- ? item1
- ? item2
- ? item3
+ ? item1
+ ? item2
+ ? item3
+or: {item1, item2, item3}
# Like Python, sets are just maps with null values; the above is equivalent to:
set2:
- item1: null
- item2: null
- item3: null
+ item1: null
+ item2: null
+ item3: null
```
### More Resources
diff --git a/zfs.html.markdown b/zfs.html.markdown
index 3d033da9..fad6b62d 100644
--- a/zfs.html.markdown
+++ b/zfs.html.markdown
@@ -149,6 +149,7 @@ $ zpool destroy test
### Datasets
Actions:
+
* Create
* List
* Rename
@@ -269,6 +270,7 @@ ZFS snapshots are one of the things about zfs that are a really big deal
* They are easy to automate.
Actions:
+
* Create
* Delete
* Rename
diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index 75498367..37b4b137 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -142,6 +142,7 @@ func learnTypes() {
func learnNamedReturns(x, y int) (z int) {
z = x * y
return // z is implicit here, because we named it earlier.
+}
// Go全面支持垃圾回收。Go有指针,但是不支持指针运算。
// 你会因为空指针而犯错,但是不会因为增加指针而犯错。
diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown
index 562a0284..0e7a020c 100644
--- a/zh-cn/groovy-cn.html.markdown
+++ b/zh-cn/groovy-cn.html.markdown
@@ -219,10 +219,12 @@ for (i in array) {
//遍历映射
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
-x = 0
+x = ""
for ( e in map ) {
x += e.value
+ x += " "
}
+assert x.equals("Roberto Grails Groovy ")
/*
运算符
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index bdef0099..360f7c65 100644
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -12,12 +12,9 @@ translators:
lang: zh-cn
---
-Javascript于1995年由网景公司的Brendan Eich发明。
-最初发明的目的是作为一个简单的网站脚本语言,来作为
-复杂网站应用java的补充。但由于它与网页结合度很高并且由浏览器内置支持,
-所以javascript变得比java在前端更为流行了。
+Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为一种简单的,用于开发网站的脚本语言而被发明出来,是用于开发复杂网站的 Java 的补充。但由于它与网页结合度很高并且在浏览器中得到内置的支持,所以在网页前端领域 Javascript 变得比 Java 更流行了。
-不过 JavaScript 可不仅仅只用于浏览器: Node.js,一个基于Google Chrome V8引擎的独立运行时环境,也越来越流行。
+不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。
很欢迎来自您的反馈,您可以通过下列方式联系到我:
[@adambrenecki](https://twitter.com/adambrenecki), 或者
diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown
index 5d655029..f6dcd847 100644
--- a/zh-cn/kotlin-cn.html.markdown
+++ b/zh-cn/kotlin-cn.html.markdown
@@ -22,7 +22,7 @@ package com.learnxinyminutes.kotlin
/*
Kotlin程序的入口点是一个"main"函数
-该函数传递一个包含任何命令行参数的数组。
+该函数传递一个包含所有命令行参数的数组。
*/
fun main(args: Array<String>) {
/*
@@ -67,10 +67,10 @@ fun helloWorld(val name : String) {
模板表达式从一个美元符号($)开始。
*/
val fooTemplateString = "$fooString has ${fooString.length} characters"
- println(fooTemplateString)
+ println(fooTemplateString) // => 输出 My String Is Here! has 18 characters
/*
- 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。
+ 当某个变量的值可以为 null 的时候,我们必须明确指定它是可为空的。
在变量声明处的类型后面加上?来标识它是可为空的。
我们可以用?.操作符来访问可为空的变量。
我们可以用?:操作符来指定一个在变量为空时使用的替代值。
@@ -96,24 +96,24 @@ fun helloWorld(val name : String) {
println(hello()) // => Hello, world!
/*
- 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数
+ 函数的可变参数可使用 "vararg" 关键字来修饰
*/
fun varargExample(vararg names: Int) {
println("Argument has ${names.size} elements")
}
- varargExample() // => Argument has 0 elements
- varargExample(1) // => Argument has 1 elements
- varargExample(1, 2, 3) // => Argument has 3 elements
+ varargExample() // => 传入 0 个参数
+ varargExample(1) // => 传入 1 个参数
+ varargExample(1, 2, 3) // => 传入 3 个参数
/*
- 当函数只包含一个单独的表达式时,大括号可以被省略。
- 函数体可以被指定在一个=符号后面。
+ 当函数只包含一个单独的表达式时,大括号可以省略。
+ 函数体可以写在一个=符号后面。
*/
fun odd(x: Int): Boolean = x % 2 == 1
println(odd(6)) // => false
println(odd(7)) // => true
- // 如果返回值类型可以被推断,那么我们不需要指定它。
+ // 如果返回值类型可以推断,那么我们不需要指定它。
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
@@ -122,15 +122,14 @@ fun helloWorld(val name : String) {
fun not(f: (Int) -> Boolean) : (Int) -> Boolean {
return {n -> !f.invoke(n)}
}
- // 命名函数可以用::运算符被指定为参数。
+ // 普通函数可以用::运算符传入引用作为函数参数。
val notOdd = not(::odd)
val notEven = not(::even)
- // 匿名函数可以被指定为参数。
+ // lambda 表达式可以直接作为参数传递。
val notZero = not {n -> n == 0}
/*
- 如果一个匿名函数只有一个参数
- 那么它的声明可以被省略(连同->)。
- 这个参数的名字是"it"。
+ 如果一个 lambda 表达式只有一个参数
+ 那么它的声明可以省略(连同->),内部以 "it" 引用。
*/
val notPositive = not {it > 0}
for (i in 0..4) {
@@ -152,7 +151,7 @@ fun helloWorld(val name : String) {
注意,Kotlin没有"new"关键字。
*/
val fooExampleClass = ExampleClass(7)
- // 可以使用一个点号来调用成员函数。
+ // 可以使用一个点号来调用成员方法。
println(fooExampleClass.memberFunction(4)) // => 11
/*
如果使用"infix"关键字来标记一个函数
@@ -162,7 +161,7 @@ fun helloWorld(val name : String) {
/*
数据类是创建只包含数据的类的一个简洁的方法。
- "hashCode"、"equals"和"toString"方法将被自动生成。
+ "hashCode"、"equals"和"toString"方法将自动生成。
*/
data class DataClassExample (val x: Int, val y: Int, val z: Int)
val fooData = DataClassExample(1, 2, 4)
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index cba9252d..c25b2918 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -445,47 +445,47 @@ if let circle = myEmptyCircle {
// 枚举可以像类一样,拥有方法
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
+ case spades, hearts, diamonds, clubs
func getIcon() -> String {
switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case .spades: return "♤"
+ case .hearts: return "♡"
+ case .diamonds: return "♢"
+ case .clubs: return "♧"
}
}
}
// 当变量类型明确指定为某个枚举类型时,赋值时可以省略枚举类型
-var suitValue: Suit = .Hearts
+var suitValue: Suit = .hearts
// 非整型的枚举类型需要在定义时赋值
enum BookName: String {
- case John = "John"
- case Luke = "Luke"
+ case john = "John"
+ case luke = "Luke"
}
-print("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.john.rawValue)")
// 与特定数据类型关联的枚举
enum Furniture {
// 和 Int 型数据关联的枚举记录
- case Desk(height: Int)
+ case desk(height: Int)
// 和 String, Int 关联的枚举记录
- case Chair(brand: String, height: Int)
+ case chair(brand: String, height: Int)
func description() -> String {
switch self {
- case .Desk(let height):
+ case .desk(let height):
return "Desk with \(height) cm"
- case .Chair(let brand, let height):
+ case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
-var desk: Furniture = .Desk(height: 80)
+var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
-var chair = Furniture.Chair(brand: "Foo", height: 40)
+var chair = Furniture.chair(brand: "Foo", height: 40)
print(chair.description()) // "Chair of Foo with 40 cm"