summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitattributes2
-rw-r--r--.github/CODEOWNERS5
-rw-r--r--.github/ISSUE_TEMPLATE.md (renamed from ISSUE_TEMPLATE.md)0
-rw-r--r--.github/PULL_REQUEST_TEMPLATE.md (renamed from PULL_REQUEST_TEMPLATE.md)2
-rw-r--r--bash.html.markdown45
-rw-r--r--bg-bg/perl-bg.html.markdown7
-rw-r--r--c++.html.markdown47
-rw-r--r--c.html.markdown129
-rw-r--r--chapel.html.markdown2
-rw-r--r--clojure.html.markdown4
-rw-r--r--cobol.html.markdown198
-rw-r--r--coq.html.markdown8
-rw-r--r--crystal.html.markdown74
-rw-r--r--dart.html.markdown8
-rw-r--r--de-de/bash-de.html.markdown2
-rw-r--r--de-de/clojure-macros-de.html.markdown161
-rw-r--r--de-de/elixir-de.html.markdown4
-rw-r--r--de-de/elm-de.html.markdown376
-rw-r--r--de-de/nix-de.html.markdown3
-rw-r--r--de-de/perl-de.html.markdown4
-rw-r--r--de-de/processing-de.html.markdown498
-rw-r--r--de-de/pug-de.html.markdown208
-rw-r--r--de-de/ruby-de.html.markdown782
-rw-r--r--de-de/swift-de.html.markdown2
-rw-r--r--de-de/vim-de.html.markdown282
-rw-r--r--docker.html.markdown13
-rw-r--r--el-gr/bash-gr.html.markdown2
-rw-r--r--el-gr/rust-gr.html.markdown339
-rw-r--r--el-gr/vim-gr.html.markdown267
-rw-r--r--elixir.html.markdown5
-rw-r--r--es-es/bash-es.html.markdown2
-rw-r--r--es-es/c++-es.html.markdown67
-rw-r--r--es-es/matlab-es.html.markdown2
-rw-r--r--es-es/objective-c-es.html.markdown2
-rw-r--r--es-es/perl-es.html.markdown16
-rw-r--r--es-es/raku-es.html.markdown (renamed from es-es/perl6-es.html.markdown)508
-rw-r--r--es-es/swift-es.html.markdown2
-rw-r--r--es-es/typescript-es.html.markdown2
-rw-r--r--fi-fi/ruby-fi.html.markdown2
-rw-r--r--fortran95.html.markdown1
-rw-r--r--fr-fr/asymptotic-notation-fr.html.markdown14
-rw-r--r--fr-fr/bash-fr.html.markdown2
-rw-r--r--fr-fr/c++-fr.html.markdown6
-rw-r--r--fr-fr/crystal-fr.html.markdown2
-rw-r--r--fr-fr/elisp-fr.html.markdown10
-rw-r--r--fr-fr/fsharp-fr.html.markdown3
-rw-r--r--fr-fr/java-fr.html.markdown64
-rw-r--r--fr-fr/javascript-fr.html.markdown22
-rw-r--r--fr-fr/markdown-fr.html.markdown34
-rw-r--r--fr-fr/objective-c-fr.html.markdown4
-rw-r--r--fr-fr/perl-fr.html.markdown4
-rw-r--r--fr-fr/set-theory-fr.html.markdown134
-rw-r--r--fr-fr/typescript-fr.html.markdown2
-rw-r--r--fsharp.html.markdown4
-rw-r--r--git.html.markdown4
-rw-r--r--go.html.markdown2
-rw-r--r--groovy.html.markdown2
-rw-r--r--haskell.html.markdown2
-rw-r--r--hd-hd/json-hd.html.markdown86
-rw-r--r--id-id/ruby-id.html.markdown2
-rw-r--r--images/solidity/copy-address.pngbin0 -> 75859 bytes
-rw-r--r--images/solidity/metamask-kovan.pngbin0 -> 167647 bytes
-rw-r--r--images/solidity/remix-add-token.pngbin0 -> 94850 bytes
-rw-r--r--images/solidity/remix-choose-file.pngbin0 -> 474613 bytes
-rw-r--r--images/solidity/remix-compile.pngbin0 -> 757033 bytes
-rw-r--r--images/solidity/remix-deploy.pngbin0 -> 755589 bytes
-rw-r--r--images/solidity/remix-interact.pngbin0 -> 792300 bytes
-rw-r--r--images/solidity/remix-solidity.pngbin0 -> 343697 bytes
-rw-r--r--images/solidity/remix-testnet.pngbin0 -> 869929 bytes
-rw-r--r--images/solidity/send-link.pngbin0 -> 120488 bytes
-rw-r--r--it-it/bash-it.html.markdown2
-rw-r--r--it-it/ruby-it.html.markdown2
-rw-r--r--it-it/sql-it.html.markdown112
-rw-r--r--it-it/zfs-it.html.markdown361
-rw-r--r--ja-jp/python-jp.html.markdown32
-rw-r--r--ja-jp/vim-jp.html.markdown275
-rw-r--r--janet.html.markdown328
-rw-r--r--java.html.markdown53
-rw-r--r--jquery.html.markdown2
-rw-r--r--json.html.markdown5
-rw-r--r--jsonnet.html.markdown139
-rw-r--r--julia.html.markdown65
-rw-r--r--ko-kr/vim-kr.html.markdown56
-rw-r--r--kotlin.html.markdown4
-rw-r--r--latex.html.markdown43
-rw-r--r--lbstanza.html.markdown282
-rw-r--r--ldpl.html.markdown13
-rw-r--r--lua.html.markdown4
-rw-r--r--matlab.html.markdown4
-rw-r--r--mips.html.markdown4
-rw-r--r--mongodb.html.markdown405
-rw-r--r--moonscript.html.markdown2
-rw-r--r--ms-my/bash-my.html.markdown2
-rw-r--r--nim.html.markdown2
-rw-r--r--nix.html.markdown2
-rw-r--r--nl-nl/bash-nl.html.markdown2
-rw-r--r--nl-nl/json-nl.html.markdown13
-rw-r--r--no-nb/bash-no.html.markdown2
-rw-r--r--objective-c.html.markdown2
-rw-r--r--opencv.html.markdown22
-rw-r--r--p5.html.markdown2
-rw-r--r--perl.html.markdown4
-rw-r--r--php.html.markdown8
-rw-r--r--pl-pl/perl-pl.html.markdown4
-rw-r--r--powershell.html.markdown958
-rw-r--r--processing.html.markdown10
-rw-r--r--pt-br/awk-pt.html.markdown4
-rw-r--r--pt-br/bash-pt.html.markdown10
-rw-r--r--pt-br/css-pt.html.markdown10
-rw-r--r--pt-br/elixir-pt.html.markdown2
-rw-r--r--pt-br/fsharp-pt.html.markdown639
-rw-r--r--pt-br/groovy-pt.html.markdown14
-rw-r--r--pt-br/julia-pt.html.markdown2
-rw-r--r--pt-br/kotlin-pt.html.markdown4
-rw-r--r--pt-br/lua-pt.html.markdown423
-rw-r--r--pt-br/matlab-pt.html.markdown2
-rw-r--r--pt-br/perl-pt.html.markdown4
-rw-r--r--pt-br/sass-pt.html.markdown67
-rw-r--r--pt-br/self-pt.html.markdown2
-rw-r--r--pt-br/solidity-pt.html.markdown2
-rw-r--r--pt-br/swift-pt.html.markdown2
-rw-r--r--pt-br/typescript-pt.html.markdown16
-rw-r--r--pt-pt/swift-pt.html.markdown2
-rw-r--r--purescript.html.markdown117
-rw-r--r--python.html.markdown61
-rw-r--r--qsharp.html.markdown204
-rw-r--r--r.html.markdown14
-rw-r--r--raku-pod.html.markdown (renamed from perl6-pod.html.markdown)90
-rw-r--r--raku.html.markdown1036
-rw-r--r--raylib.html.markdown146
-rw-r--r--red.html.markdown2
-rw-r--r--ro-ro/bash-ro.html.markdown2
-rw-r--r--rst.html.markdown18
-rw-r--r--ru-ru/bash-ru.html.markdown2
-rw-r--r--ru-ru/c-ru.html.markdown2
-rw-r--r--ru-ru/forth-ru.html.markdown3
-rw-r--r--ru-ru/nim-ru.html.markdown254
-rw-r--r--ru-ru/objective-c-ru.html.markdown2
-rw-r--r--ru-ru/pascal-ru.html.markdown217
-rw-r--r--ru-ru/perl-ru.html.markdown30
-rw-r--r--ru-ru/python-ru.html.markdown963
-rw-r--r--ru-ru/ruby-ru.html.markdown2
-rw-r--r--ru-ru/swift-ru.html.markdown2
-rw-r--r--ruby.html.markdown20
-rw-r--r--scala.html.markdown5
-rw-r--r--set-theory.html.markdown132
-rw-r--r--sk-sk/bash-sk.html.markdown2
-rw-r--r--smalltalk.html.markdown6
-rw-r--r--solidity.html.markdown140
-rw-r--r--sql.html.markdown2
-rw-r--r--sv-se/nix-sv.html.markdown5
-rw-r--r--swift.html.markdown13
-rw-r--r--tcl.html.markdown4
-rwxr-xr-xtoml.html.markdown5
-rw-r--r--tr-tr/jquery-tr.html.markdown338
-rw-r--r--tr-tr/ruby-tr.html.markdown1598
-rw-r--r--typescript.html.markdown6
-rw-r--r--uk-ua/c-ua.html.markdown860
-rw-r--r--uk-ua/ruby-ua.html.markdown2
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--vim.html.markdown5
-rw-r--r--wasm.html.markdown2
-rw-r--r--xml.html.markdown13
-rw-r--r--yaml.html.markdown6
-rw-r--r--zh-cn/asciidoc-cn.html.md135
-rw-r--r--zh-cn/bash-cn.html.markdown2
-rw-r--r--zh-cn/c-cn.html.markdown4
-rw-r--r--zh-cn/cmake-cn.html.markdown168
-rw-r--r--zh-cn/go-cn.html.markdown2
-rw-r--r--zh-cn/haskell-cn.html.markdown2
-rw-r--r--zh-cn/java-cn.html.markdown4
-rw-r--r--zh-cn/make-cn.html.markdown8
-rw-r--r--zh-cn/mips-cn.html.markdown334
-rw-r--r--zh-cn/opencv-cn.html.markdown145
-rw-r--r--zh-cn/perl-cn.html.markdown12
-rw-r--r--zh-cn/python-cn.html.markdown6
-rw-r--r--zh-cn/pythonlegacy-cn.html.markdown2
-rw-r--r--zh-cn/qt-cn.html.markdown160
-rw-r--r--zh-cn/ruby-cn.html.markdown2
-rw-r--r--zh-cn/set-theory-cn.html.markdown138
-rw-r--r--zh-cn/solidity-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown2
-rw-r--r--zh-cn/wolfram-cn.html.markdown140
-rw-r--r--zh-cn/yaml-cn.html.markdown55
-rw-r--r--zh-tw/bash-tw.html.markdown2
-rw-r--r--zh-tw/perl-tw.html.markdown328
186 files changed, 14332 insertions, 2571 deletions
diff --git a/.gitattributes b/.gitattributes
index 183b7cdb..96d2bb5a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -61,5 +61,5 @@ paren*.html.markdown linguist-language=lisp
pcre*.html.markdown linguist-language=Perl
perl.html.markdown linguist-language=Perl
perl-*.html.markdown linguist-language=Perl
-perl6*.html.markdown linguist-language=Perl6
+raku*.html.markdown linguist-language=Perl6
ruby*.html.markdown linguist-language=Ruby
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 00000000..4c779152
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,5 @@
+/fr-fr/ @vendethiel
+/ru-ru/ @Menelion
+/uk-ua/ @Menelion
+/zh-cn/ @geoffliu @imba-tjd
+/zh-tw/ @geoffliu @imba-tjd
diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 96278da9..96278da9 100644
--- a/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
diff --git a/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index fd9d1b31..6a496409 100644
--- a/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,5 +1,5 @@
- [ ] I solemnly swear that this is all original content of which I am the original author
-- [ ] Pull request title is prepended with `[language/lang-code]`
+- [ ] Pull request title is prepended with `[language/lang-code]` (example `[python/fr-fr]` or `[java/en]`)
- [ ] Pull request touches only one file (or a set of logically related files with similar changes made)
- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts)
- [ ] If you've changed any part of the YAML Frontmatter, make sure it is formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
diff --git a/bash.html.markdown b/bash.html.markdown
index 856db706..4ed638e6 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -17,22 +17,23 @@ contributors:
- ["John Detter", "https://github.com/jdetter"]
- ["Harry Mumford-Turner", "https://github.com/harrymt"]
- ["Martin Nicholson", "https://github.com/mn113"]
+ - ["Mark Grimwood", "https://github.com/MarkGrimwood"]
filename: LearnBash.sh
translators:
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
---
Bash is a name of the unix shell, which was also distributed as the shell
-for the GNU operating system and as default shell on Linux and Mac OS X.
+for the GNU operating system and as the default shell on most Linux distros.
Nearly all examples below can be a part of a shell script
or executed directly in the shell.
-[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
+[Read more here.](https://www.gnu.org/software/bash/manual/bashref.html)
```bash
#!/usr/bin/env bash
# First line of the script is the shebang which tells the system how to execute
-# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# the script: https://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured, comments start with #. Shebang is also a comment.
# Simple hello world example:
@@ -88,6 +89,11 @@ echo ${Variable: -5} # => tring
# String length
echo ${#Variable} # => 11
+# Indirect expansion
+OtherVariable="Variable"
+echo ${!OtherVariable} # => Some String
+# This will expand the value of OtherVariable
+
# Default value for variable
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# => DefaultValueIfFooIsMissingOrEmpty
@@ -193,7 +199,7 @@ then
fi
# Note that =~ only works within double [[ ]] square brackets,
# which are subtly different from single [ ].
-# See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
+# See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
# Redefine command `ping` as alias to send only 5 packets
alias ping='ping -c 5'
@@ -225,7 +231,9 @@ cat file.txt
# We can also read the file using `cat`:
Contents=$(cat file.txt)
-echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character
+# "\n" prints a new line character
+# "-e" to interpret the newline escape characters as escape characters
+echo -e "START OF FILE\n$Contents\nEND OF FILE"
# => START OF FILE
# => [contents of file.txt]
# => END OF FILE
@@ -318,6 +326,9 @@ echo "#helloworld" | tee output.out >/dev/null
# WARNING: `rm` commands cannot be undone
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively delete
+# You can install the `trash-cli` Python package to have `trash`
+# which puts files in the system trash and doesn't delete them directly
+# see https://pypi.org/project/trash-cli/ if you want to be careful
# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
@@ -325,15 +336,15 @@ rm -r tempDir/ # recursively delete
echo "There are $(ls | wc -l) items here."
# The same can be done using backticks `` but they can't be nested -
-#the preferred way is to use $( ).
+# the preferred way is to use $( ).
echo "There are `ls | wc -l` items here."
# Bash uses a `case` statement that works similarly to switch in Java and C++:
case "$Variable" in
- #List patterns for the conditions you want to meet
+ # List patterns for the conditions you want to meet
0) echo "There is a zero.";;
1) echo "There is a one.";;
- *) echo "It is not null.";;
+ *) echo "It is not null.";; # match everything
esac
# `for` loops iterate for as many arguments given:
@@ -370,6 +381,13 @@ do
cat "$Output"
done
+# Bash can also accept patterns, like this to `cat`
+# all the Markdown files in current directory
+for Output in ./*.markdown
+do
+ cat "$Output"
+done
+
# while loop:
while [ true ]
do
@@ -385,13 +403,17 @@ function foo ()
echo "Arguments work just like script arguments: $@"
echo "And: $1 $2..."
echo "This is a function"
- return 0
+ returnValue=0 # Variable values can be returned
+ return $returnValue
}
# 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
+# Return values can be obtained with $?
+resultValue=$?
+# More than 9 arguments are also possible by using braces, e.g. ${10}, ${11}, ...
# or simply
bar ()
@@ -424,6 +446,8 @@ cut -d ',' -f 1 file.txt
# replaces every occurrence of 'okay' with 'great' in file.txt
# (regex compatible)
sed -i 's/okay/great/g' file.txt
+# be aware that this -i flag means that file.txt will be changed
+# -i or --in-place erase the input file (use --in-place=.backup to keep a back-up)
# print to stdout all lines of file.txt which match some regex
# The example prints lines which begin with "foo" and end in "bar"
@@ -441,7 +465,7 @@ grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files
grep "^foo.*bar$" file.txt | grep -v "baz"
# if you literally want to search for the string,
-# and not the regex, use fgrep (or grep -F)
+# and not the regex, use `fgrep` (or `grep -F`)
fgrep "foobar" file.txt
# The `trap` command allows you to execute a command whenever your script
@@ -450,6 +474,7 @@ fgrep "foobar" file.txt
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
# `sudo` is used to perform commands as the superuser
+# usually it will ask interactively the password of superuser
NAME1=$(whoami)
NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"
diff --git a/bg-bg/perl-bg.html.markdown b/bg-bg/perl-bg.html.markdown
index 2ae7a8fd..e6da8965 100644
--- a/bg-bg/perl-bg.html.markdown
+++ b/bg-bg/perl-bg.html.markdown
@@ -11,10 +11,10 @@ translators:
lang: bg-bg
---
-Perl 5 е изключително мощен език за програмиране с широка област на приложение
+Perl е изключително мощен език за програмиране с широка област на приложение
и над 25 годишна история.
-Perl 5 работи на повече от 100 операционни системи от мини до супер-компютри и е
+Perl работи на повече от 100 операционни системи от мини до супер-компютри и е
подходящ както за бърза разработка на скриптове така и за огромни приложения.
```perl
@@ -281,7 +281,7 @@ sub increment {
1;
-# Методите могат да се извикват на клас или на обект като се използва оператора
+# Методите могат да се извикват на клас или на обект като се използва оператора
# стрелка (->).
use MyCounter;
@@ -323,4 +323,3 @@ sub increment {
- [Learn at www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- и идващото с perl: `perldoc perlintro`
-
diff --git a/c++.html.markdown b/c++.html.markdown
index f3dc8e20..6e94e03e 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -2,16 +2,16 @@
language: c++
filename: learncpp.cpp
contributors:
- - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Steven Basart", "https://github.com/xksteven"]
- ["Matt Kline", "https://github.com/mrkline"]
- ["Geoff Liu", "http://geoffliu.me"]
- - ["Connor Waters", "http://github.com/connorwaters"]
- - ["Ankush Goyal", "http://github.com/ankushg07"]
+ - ["Connor Waters", "https://github.com/connorwaters"]
+ - ["Ankush Goyal", "https://github.com/ankushg07"]
- ["Jatin Dhankhar", "https://github.com/jatindhankhar"]
---
C++ is a systems programming language that,
-[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
+[according to its inventor Bjarne Stroustrup](https://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
was designed to
- be a "better C"
@@ -37,7 +37,7 @@ one of the most widely-used programming languages.
// Just like in C, your program's entry point is a function called
// main with an integer return type.
// This value serves as the program's exit status.
-// See http://en.wikipedia.org/wiki/Exit_status for more information.
+// See https://en.wikipedia.org/wiki/Exit_status for more information.
int main(int argc, char** argv)
{
// Command line arguments are passed in by argc and argv in the same way
@@ -199,10 +199,10 @@ int main()
cin >> myInt;
// cout can also be formatted
- cout << "Your favorite number is " << myInt << "\n";
+ cout << "Your favorite number is " << myInt << '\n';
// prints "Your favorite number is <myInt>"
- cerr << "Used for error messages";
+ cerr << "Used for error messages";
}
//////////
@@ -461,7 +461,7 @@ void Dog::print() const
Dog::~Dog()
{
- std::cout << "Goodbye " << name << "\n";
+ std::cout << "Goodbye " << name << '\n';
}
int main() {
@@ -483,7 +483,7 @@ public:
void setOwner(const std::string& dogsOwner);
// Override the behavior of the print function for all OwnedDogs. See
- // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
+ // https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
// for a more general introduction if you are unfamiliar with
// subtype polymorphism.
// The override keyword is optional but makes sure you are actually
@@ -504,7 +504,7 @@ void OwnedDog::setOwner(const std::string& dogsOwner)
void OwnedDog::print() const
{
Dog::print(); // Call the print function in the base Dog class
- std::cout << "Dog is owned by " << owner << "\n";
+ std::cout << "Dog is owned by " << owner << '\n';
// Prints "Dog is <name> and weights <weight>"
// "Dog is owned by <owner>"
}
@@ -616,7 +616,7 @@ boxOfBox.insert(intBox);
// template<typename T>
// instead. The 'class' keyword and 'typename' keywords are _mostly_
// interchangeable in this case. For the full explanation, see
-// http://en.wikipedia.org/wiki/Typename
+// https://en.wikipedia.org/wiki/Typename
// (yes, that keyword has its own Wikipedia page).
// Similarly, a template function:
@@ -660,7 +660,7 @@ printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!"
/////////////////////
// The standard library provides a few exception types
-// (see http://en.cppreference.com/w/cpp/error/exception)
+// (see https://en.cppreference.com/w/cpp/error/exception)
// but any type can be thrown as an exception
#include <exception>
#include <stdexcept>
@@ -915,7 +915,7 @@ ST.erase(20); // Will erase element with value 20
// Set ST: 10 30
// To iterate through Set we use iterators
set<int>::iterator it;
-for(it=ST.begin();it<ST.end();it++) {
+for(it=ST.begin();it!=ST.end();it++) {
cout << *it << endl;
}
// Output:
@@ -946,7 +946,7 @@ mymap.insert(pair<char,int>('Z',26));
// To iterate
map<char,int>::iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
- std::cout << it->first << "->" << it->second << '\n';
+ std::cout << it->first << "->" << it->second << std::cout;
// Output:
// A->1
// Z->26
@@ -1030,7 +1030,7 @@ sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) {
return weight[lhs] < weight[rhs];
});
// Note we captured "weight" by reference in the above example.
-// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
+// More on Lambdas in C++ : https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11
///////////////////////////////
// Range For (C++11 and above)
@@ -1106,7 +1106,8 @@ f1 = f2;
#include<tuple>
-// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members,
+// Conceptually, Tuples are similar to old data structures (C-like structs)
+// but instead of having named data members,
// its elements are accessed by their order in the tuple.
// We start with constructing a tuple.
@@ -1117,33 +1118,33 @@ const int maxL = 15;
auto second = make_tuple(maxN, maxL);
// Printing elements of 'first' tuple
-cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A
+cout << get<0>(first) << " " << get<1>(first) << '\n'; //prints : 10 A
// Printing elements of 'second' tuple
-cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15
+cout << get<0>(second) << " " << get<1>(second) << '\n'; // prints: 1000000000 15
// Unpacking tuple into variables
int first_int;
char first_char;
tie(first_int, first_char) = first;
-cout << first_int << " " << first_char << "\n"; // prints : 10 A
+cout << first_int << " " << first_char << '\n'; // prints : 10 A
// We can also create tuple like this.
tuple<int, char, double> third(11, 'A', 3.14141);
// tuple_size returns number of elements in a tuple (as a constexpr)
-cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3
+cout << tuple_size<decltype(third)>::value << '\n'; // prints: 3
// tuple_cat concatenates the elements of all the tuples in the same order.
auto concatenated_tuple = tuple_cat(first, second, third);
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141)
-cout << get<0>(concatenated_tuple) << "\n"; // prints: 10
-cout << get<3>(concatenated_tuple) << "\n"; // prints: 15
-cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A'
+cout << get<0>(concatenated_tuple) << '\n'; // prints: 10
+cout << get<3>(concatenated_tuple) << '\n'; // prints: 15
+cout << get<5>(concatenated_tuple) << '\n'; // prints: 'A'
///////////////////////////////////
diff --git a/c.html.markdown b/c.html.markdown
index a57be1dc..7405c7ab 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -46,31 +46,47 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
// Enumeration constants are also ways to declare constants.
// All statements must end with a semicolon
-enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
+enum days {SUN, MON, TUE, WED, THU, FRI, SAT};
+// SUN gets 0, MON gets 1, TUE gets 2, etc.
+
+// Enumeration values can also be specified
+enum days {SUN = 1, MON, TUE, WED = 99, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
+// WED get 99, THU gets 100, FRI gets 101, etc.
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
-// (File names between <angle brackets> are headers from the C standard library.)
-// For your own headers, use double quotes instead of angle brackets:
-//#include "my_header.h"
+// File names between <angle brackets> tell the compiler to look in your system
+// libraries for the headers.
+// For your own headers, use double quotes instead of angle brackets, and
+// provide the path:
+#include "my_header.h" // local file
+#include "../my_lib/my_lib_header.h" //relative path
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
void function_1();
int function_2(void);
-// Must declare a 'function prototype' before main() when functions occur after
-// your main() function.
+// At a minimum, you must declare a 'function prototype' before its use in any function.
+// Normally, prototypes are placed at the top of a file before any function definition.
int add_two_ints(int x1, int x2); // function prototype
// although `int add_two_ints(int, int);` is also valid (no need to name the args),
// it is recommended to name arguments in the prototype as well for easier inspection
-// Your program's entry point is a function called
-// main with an integer return type.
+// Function prototypes are not necessary if the function definition comes before
+// any other function that calls that function. However, it's standard practice to
+// always add the function prototype to a header file (*.h) and then #include that
+// file at the top. This prevents any issues where a function might be called
+// before the compiler knows of its existence, while also giving the developer a
+// clean header file to share with the rest of the project.
+
+// Your program's entry point is a function called "main". The return type can
+// be anything, however most operating systems expect a return type of `int` for
+// error code processing.
int main(void) {
// your program
}
@@ -96,13 +112,14 @@ int main (int argc, char** argv)
// For the sake of the tutorial, variables are declared dynamically under
// C99-compliant standards.
- // ints are usually 4 bytes
+ // ints are usually 4 bytes (use the `sizeof` operator to check)
int x_int = 0;
- // shorts are usually 2 bytes
+ // shorts are usually 2 bytes (use the `sizeof` operator to check)
short x_short = 0;
- // chars are guaranteed to be 1 byte
+ // chars are defined as the smallest addressable unit for a processor.
+ // This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
char x_char = 0;
char y_char = 'y'; // Char literals are quoted with ''
@@ -224,24 +241,41 @@ int main (int argc, char** argv)
(float)i1 / i2; // => 0.5f
i1 / (double)i2; // => 0.5 // Same with double
f1 / f2; // => 0.5, plus or minus epsilon
- // Floating-point numbers and calculations are not exact
-
- // Modulo is there as well
- 11 % 3; // => 2
+
+ // Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
+ // exact values. For instance, the following does not produce expected results
+ // because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
+ // might be stored as 0.300000000001.
+ (0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
+ // and it is NOT associative due to reasons mentioned above.
+ 1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
+ // this notation is scientific notations for numbers: 1e123 = 1*10^123
+
+ // It is important to note that most all systems have used IEEE 754 to
+ // represent floating points. Even python, used for scientific computing,
+ // eventually calls C which uses IEEE 754. It is mentioned this way not to
+ // indicate that this is a poor implementation, but instead as a warning
+ // that when doing floating point comparisons, a little bit of error (epsilon)
+ // needs to be considered.
+
+ // Modulo is there as well, but be careful if arguments are negative
+ 11 % 3; // => 2 as 11 = 2 + 3*x (x=3)
+ (-11) % 3; // => -2, as one would expect
+ 11 % (-3); // => 2 and not -2, and it's quite counter intuitive
// Comparison operators are probably familiar, but
// there is no Boolean type in C. We use ints instead.
- // (Or _Bool or bool in C99.)
+ // (C99 introduced the _Bool type provided in stdbool.h)
// 0 is false, anything else is true. (The comparison
// operators always yield 0 or 1.)
3 == 2; // => 0 (false)
3 != 2; // => 1 (true)
- 3 > 2; // => 1
- 3 < 2; // => 0
+ 3 > 2; // => 1
+ 3 < 2; // => 0
2 <= 2; // => 1
2 >= 2; // => 1
- // C is not Python - comparisons don't chain.
+ // C is not Python - comparisons do NOT chain.
// Warning: The line below will compile, but it means `(0 < a) < 2`.
// This expression is always true, because (0 < a) could be either 1 or 0.
// In this case it's 1, because (0 < 1).
@@ -349,25 +383,30 @@ int main (int argc, char** argv)
break;
}
/*
- using "goto" in C
+ Using "goto" in C
*/
typedef enum { false, true } bool;
// for C don't have bool as data type before C99 :(
bool disaster = false;
int i, j;
- for(i=0;i<100;++i)
- for(j=0;j<100;++j)
+ for(i=0; i<100; ++i)
+ for(j=0; j<100; ++j)
{
if((i + j) >= 150)
disaster = true;
if(disaster)
- goto error;
+ goto error; // exit both for loops
}
- error :
+ error: // this is a label that you can "jump" to with "goto error;"
printf("Error occurred at i = %d & j = %d.\n", i, j);
/*
- https://ideone.com/GuPhd6
- this will print out "Error occurred at i = 51 & j = 99."
+ https://ideone.com/GuPhd6
+ this will print out "Error occurred at i = 51 & j = 99."
+ */
+ /*
+ it is generally considered bad practice to do so, except if
+ you really know what you are doing. See
+ https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
*/
///////////////////////////////////////
@@ -378,13 +417,16 @@ int main (int argc, char** argv)
// if you want (with some constraints).
int x_hex = 0x01; // You can assign vars with hex literals
+ // binary is not in the standard, but allowed by some
+ // compilers (x_bin = 0b0010010110)
// Casting between types will attempt to preserve their numeric values
printf("%d\n", x_hex); // => Prints 1
printf("%d\n", (short) x_hex); // => Prints 1
printf("%d\n", (char) x_hex); // => Prints 1
- // Types will overflow without warning
+ // If you assign a value greater than a types max val, it will rollover
+ // without warning.
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
// For determining the max value of a `char`, a `signed char` and an `unsigned char`,
@@ -575,6 +617,24 @@ printf("first: %d\nsecond: %d\n", first, second);
// values will be swapped
*/
+// Return multiple values.
+// C does not allow for returning multiple values with the return statement. If
+// you would like to return multiple values, then the caller must pass in the
+// variables where they would like the returned values to go. These variables must
+// be passed in as pointers such that the function can modify them.
+int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
+{
+ if(array_of_3 == NULL)
+ return 0; //return error code (false)
+
+ //de-reference the pointer so we modify its value
+ *ret1 = array_of_3[0];
+ *ret2 = array_of_3[1];
+ *ret3 = array_of_3[2];
+
+ return 1; //return error code (true)
+}
+
/*
With regards to arrays, they will always be passed to functions
as pointers. Even if you statically allocate an array like `arr[10]`,
@@ -703,6 +763,10 @@ typedef void (*my_fnp_type)(char *);
// my_fnp_type f;
+/////////////////////////////
+// Printing characters with printf()
+/////////////////////////////
+
//Special characters:
/*
'\a'; // alert (bell) character
@@ -741,11 +805,12 @@ typedef void (*my_fnp_type)(char *);
// Order of Evaluation
///////////////////////////////////////
+// From top to bottom, top has higher precedence
//---------------------------------------------------//
// Operators | Associativity //
//---------------------------------------------------//
// () [] -> . | left to right //
-// ! ~ ++ -- + = *(type)sizeof | right to left //
+// ! ~ ++ -- + = *(type) sizeof | right to left //
// * / % | left to right //
// + - | left to right //
// << >> | left to right //
@@ -783,8 +848,8 @@ as the C file.
/* included into files that include this header. */
#include <string.h>
-/* Like c source files macros can be defined in headers and used in files */
-/* that include this header file. */
+/* Like for c source files, macros can be defined in headers */
+/* and used in files that include this header file. */
#define EXAMPLE_NAME "Dennis Ritchie"
/* Function macros can also be defined. */
@@ -823,7 +888,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://
It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
-Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/).
+Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free).
If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com).
@@ -833,4 +898,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Other than that, Google is your friend.
-[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
+[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 7e8fc41a..cfab6f34 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -1171,7 +1171,7 @@ You will need to `source util/setchplenv.EXT` from within the Chapel directory
(`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop
that command in a script that will get executed on startup (like .bashrc).
-Chapel is easily installed with Brew for OS X
+Chapel is easily installed with Brew for macOS
1. `brew update`
2. `brew install chapel`
diff --git a/clojure.html.markdown b/clojure.html.markdown
index 16771e25..20812a9b 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -298,8 +298,8 @@ keymap ; => {:a 1, :b 2, :c 3}
(as-> [1 2 3] input
(map inc input);=> You can use last transform's output at the last position
(nth input 2) ;=> and at the second position, in the same expression
- (conj [4 5 6] input [8 9 10])) ;=> or in the middle !
-
+ (conj [4 5 6] input 8 9 10)) ;=> or in the middle !
+ ; Result: [4 5 6 4 8 9 10]
; Modules
diff --git a/cobol.html.markdown b/cobol.html.markdown
new file mode 100644
index 00000000..1b33f9cc
--- /dev/null
+++ b/cobol.html.markdown
@@ -0,0 +1,198 @@
+---
+language: COBOL
+contributors:
+ - ["Hyphz", "http://github.com/hyphz/"]
+filename: learn.COB
+---
+COBOL is a business-oriented language revised multiple times since its original design in 1960. It is claimed to still be used in over 80% of
+organizations.
+
+```cobol
+ *COBOL. Coding like it's 1985.
+ *Compiles with GnuCOBOL in OpenCobolIDE 4.7.6.
+
+ *COBOL has significant differences between legacy (COBOL-85)
+ *and modern (COBOL-2002 and COBOL-2014) versions.
+ *Legacy versions require columns 1-6 to be blank (they are used
+ *to store the index number of the punched card..)
+ *A '*' in column 7 means a comment.
+ *In legacy COBOL, a comment can only be a full line.
+ *Modern COBOL doesn't require fixed columns and uses *> for
+ *a comment, which can appear in the middle of a line.
+ *Legacy COBOL also imposes a limit on maximum line length.
+ *Keywords have to be in capitals in legacy COBOL,
+ *but are case insensitive in modern.
+ *Although modern COBOL allows you to use mixed-case characters
+ *it is still common to use all caps when writing COBOL code.
+ *This is what most professional COBOL developers do.
+ *COBOL statements end with a period.
+
+ *COBOL code is broken up into 4 divisions.
+ *Those divisions, in order, are:
+ *IDENTIFICATION DIVISION.
+ *ENVIRONMENT DIVISION.
+ *DATA DIVISION.
+ *PROCEDURE DIVISION.
+
+ *First, we must give our program an ID.
+ *Identification division can include other values too,
+ *but they are comments only. Program-id is the only one that is mandatory.
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARN.
+ AUTHOR. JOHN DOE.
+ DATE-WRITTEN. 05/02/2020.
+
+ *Let's declare some variables.
+ *We do this in the WORKING-STORAGE section within the DATA DIVISION.
+ *Each data item (aka variable) starts with a level number,
+ *then the name of the item, followed by a picture clause
+ *describing the type of data that the variable will contain.
+ *Almost every COBOL programmer will abbreviate PICTURE as PIC.
+ *A is for alphabetic, X is for alphanumeric, and 9 is for numeric.
+
+ *example:
+ 01 MYNAME PIC xxxxxxxxxx. *> A 10 character string.
+
+ *But counting all those x's can lead to errors,
+ *so the above code can, and should
+ *be re-written as:
+ 01 MYNAME PIC X(10).
+
+ *Here are some more examples:
+ 01 AGE PIC 9(3). *> A number up to 3 digits.
+ 01 LAST_NAME PIC X(10). *> A string up to 10 characters.
+
+ *In COBOL, multiple spaces are the same as a single space, so it is common
+ *to use multiple spaces to line up your code so that it is easier for other
+ *coders to read.
+ 01 inyear picture s9(7). *> S makes number signed.
+ *> Brackets indicate 7 repeats of 9,
+ *> ie a 6 digit number (not an array).
+
+ *Now let's write some code. Here is a simple, Hello World program.
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLO.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 THE-MESSAGE PIC X(20).
+ PROCEDURE DIVISION.
+ DISPLAY "STARTING PROGRAM".
+ MOVE "HELLO WORLD" TO THE-MESSAGE.
+ DISPLAY THE-MESSAGE.
+ STOP RUN.
+
+ *The above code will output:
+ *STARTING PROGRAM
+ *HELLO WORLD
+
+
+
+ ********COBOL can perform math***************
+ ADD 1 TO AGE GIVING NEW-AGE.
+ SUBTRACT 1 FROM COUNT.
+ DIVIDE VAR-1 INTO VAR-2 GIVING VAR-3.
+ COMPUTE TOTAL-COUNT = COUNT1 PLUS COUNT2.
+
+
+ *********PERFORM********************
+ *The PERFORM keyword allows you to jump to another specified section of the code,
+ *and then to return to the next executable
+ *statement once the specified section of code is completed.
+ *You must write the full word, PERFORM, you cannot abbreviate it.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLOCOBOL.
+
+ PROCEDURE DIVISION.
+ FIRST-PARA.
+ DISPLAY 'THIS IS IN FIRST-PARA'.
+ PERFORM THIRD-PARA THRU FOURTH-PARA. *>skip second-para and perfrom 3rd & 4th
+ *> then after performing third and fourth,
+ *> return here and continue the program until STOP RUN.
+
+ SECOND-PARA.
+ DISPLAY 'THIS IS IN SECOND-PARA'.
+ STOP RUN.
+
+ THIRD-PARA.
+ DISPLAY 'THIS IS IN THIRD-PARA'.
+
+ FOURTH-PARA.
+ DISPLAY 'THIS IS IN FOURTH-PARA'.
+
+
+ *When you compile and execute the above program, it produces the following result:
+ THIS IS IN FIRST-PARA
+ THIS IS IN THIRD-PARA
+ THIS IS IN FOURTH-PARA
+ THIS IS IN SECOND-PARA
+
+
+ **********Combining variables together using STRING ***********
+
+ *Now it is time to learn about two related COBOL verbs: string and unstring.
+
+ *The string verb is used to concatenate, or put together, two or more stings.
+ *Unstring is used, not surprisingly, to separate a
+ *string into two or more smaller strings.
+ *It is important that you remember to use ‘delimited by’ when you
+ *are using string or unstring in your program.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARNING.
+ ENVIRONMENT DIVISION.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 FULL-NAME PIC X(20).
+ 01 FIRST-NAME PIC X(13) VALUE "BOB GIBBERISH".
+ 01 LAST-NAME PIC X(5) VALUE "COBB".
+ PROCEDURE DIVISION.
+ STRING FIRST-NAME DELIMITED BY SPACE
+ " "
+ LAST-NAME DELIMITED BY SIZE
+ INTO FULL-NAME
+ END-STRING.
+ DISPLAY "THE FULL NAME IS: "FULL-NAME.
+ STOP RUN.
+
+
+ *The above code will output:
+ THE FULL NAME IS: BOB COBB
+
+
+ *Let’s examine it to see why.
+
+ *First, we declared all of our variables, including the one that we are creating
+ *by the string command, in the DATA DIVISION.
+
+ *The action takes place down in the PROCEDURE DIVISION.
+ *We start with the STRING keyword and end with END-STRING. In between we
+ *list what we want to combine together into the larger, master variable.
+ *Here, we are combining FIRST-NAME, a space, and LAST-NAME.
+
+ *The DELIMITED BY phrase that follows FIRST-NAME and
+ *LAST-NAME tells the program how much of each variable we want to capture.
+ *DELIMITED BY SPACE tells the program to start at the beginning,
+ *and capture the variable until it runs into a space.
+ *DELIMITED BY SIZE tells the program to capture the full size of the variable.
+ *Since we have DELIMITED BY SPACE after FIRST-NAME, the GIBBERISH part is ignored.
+
+ *To make this clearer, change line 10 in the above code to:
+
+ STRING FIRST-NAME DELIMITED BY SIZE
+
+ *and then re-run the program. This time the output is:
+
+ THE FULL NAME IS: BOB GIBBERISH COBB
+
+
+
+
+
+
+```
+
+##Ready For More?
+
+* [GnuCOBOL](https://sourceforge.net/projects/open-cobol/)
+
diff --git a/coq.html.markdown b/coq.html.markdown
index 4c1ad690..3a924a19 100644
--- a/coq.html.markdown
+++ b/coq.html.markdown
@@ -61,8 +61,8 @@ Locate "+".
(* Calling a function with insufficient number of arguments does not cause
an error, it produces a new function. *)
-Definition make_inc x y := x + y. (* make_inc is int -> int -> int *)
-Definition inc_2 := make_inc 2. (* inc_2 is int -> int *)
+Definition make_inc x y := x + y. (* make_inc is nat -> nat -> nat *)
+Definition inc_2 := make_inc 2. (* inc_2 is nat -> nat *)
Compute inc_2 3. (* Evaluates to 5 *)
@@ -370,7 +370,7 @@ Close Scope string_scope.
power series and results,...)
• Relations : Relations (definitions and basic results)
• Sorting : Sorted list (basic definitions and heapsort correctness)
-• Strings : 8-bits characters and strings
+• Strings : 8-bit characters and strings
• Wellfounded : Well-founded relations (basic results)
*)
@@ -472,7 +472,7 @@ Proof.
intros A B ab. destruct ab as [ a b ]. apply a.
Qed.
-(* We can prove easily prove simple polynomial equalities using the
+(* We can easily prove simple polynomial equalities using the
automated tactic ring. *)
Require Import Ring.
diff --git a/crystal.html.markdown b/crystal.html.markdown
index 9fae9da3..d32712ce 100644
--- a/crystal.html.markdown
+++ b/crystal.html.markdown
@@ -4,6 +4,7 @@ filename: learncrystal.cr
contributors:
- ["Vitalii Elenhaupt", "http://veelenga.com"]
- ["Arnaud Fernandés", "https://github.com/TechMagister/"]
+ - ["Valentin Baca", "https://github.com/valbaca/"]
---
@@ -64,24 +65,25 @@ true.class #=> Bool
1.5e10.class #=> Float64
1.5e-7.class #=> Float64
-# Chars
+# Chars use 'a' pair of single quotes
'a'.class #=> Char
-# Octal codepoint
-'\101' #=> 'A' : Char
+# Chars are 32-bit unicode
+'あ' #=> 'あ' : Char
# Unicode codepoint
'\u0041' #=> 'A' : Char
-# Strings
+# Strings use a "pair" of double quotes
"s".class #=> String
# Strings are immutable
s = "hello, " #=> "hello, " : String
s.object_id #=> 134667712 : UInt64
-s += "Crystal" #=> "hello, Crystal" : String
+s += "Crystal"
+s #=> "hello, Crystal" : String
s.object_id #=> 142528472 : UInt64
# Supports interpolation
@@ -89,7 +91,8 @@ s.object_id #=> 142528472 : UInt64
# Multiline string
"This is
- multiline string"
+ multiline string" #=> "This is\n multiline string"
+
# String with double quotes
%(hello "world") #=> "hello \"world\""
@@ -110,7 +113,7 @@ sentence == "question?" #=> false : Bool
# Arrays
[1, 2, 3].class #=> Array(Int32)
-[1, "hello", 'x'].class #=> Array(Int32 | String | Char)
+[1, "hello", 'x'].class #=> Array(Char | Int32 | String)
# Empty arrays should specify a type
[] # Syntax error: for empty arrays use '[] of ElementType'
@@ -154,24 +157,24 @@ array.includes? 3 #=> true
# There is a special array syntax with other types too, as long as
# they define a .new and a #<< method
-set = Set{1, 2, 3} #=> [1, 2, 3]
+set = Set{1, 2, 3} #=> Set{1, 2, 3}
set.class #=> Set(Int32)
# The above is equivalent to
-set = Set(typeof(1, 2, 3)).new
-set << 1
-set << 2
-set << 3
+set = Set(typeof(1, 2, 3)).new #=> Set{} : Set(Int32)
+set << 1 #=> Set{1} : Set(Int32)
+set << 2 #=> Set{1, 2} : Set(Int32)
+set << 3 #=> Set{1, 2, 3} : Set(Int32)
# Hashes
{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32)
-{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32)
+{1 => 2, 'a' => 3}.class #=> Hash(Char| Int32, Int32)
-# Empty hashes should specify a type
-{} # Syntax error
-{} of Int32 => Int32 # {}
-Hash(Int32, Int32).new # {}
+# Empty hashes must specify a type
+{} # Syntax Error: for empty hashes use '{} of KeyType => ValueType'
+{} of Int32 => Int32 # {} : Hash(Int32, Int32)
+Hash(Int32, Int32).new # {} : Hash(Int32, Int32)
# Hashes can be quickly looked up by key
hash = {"color" => "green", "number" => 5}
@@ -179,6 +182,9 @@ hash["color"] #=> "green"
hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError)
hash["no_such_key"]? #=> nil
+# The type of the returned value is based on all key types
+hash["number"] #=> 5 : (Int32 | String)
+
# Check existence of keys hash
hash.has_key? "color" #=> true
@@ -220,7 +226,7 @@ Range.new(1, 10).class #=> Range(Int32, Int32)
# Access tuple's value by its index
tuple = {:key1, :key2}
tuple[1] #=> :key2
-tuple[2] #=> syntax error : Index out of bound
+tuple[2] #=> Error: index out of bounds for Tuple(Symbol, Symbol) (2 not in -2..1)
# Can be expanded into multiple variables
a, b, c = {:a, 'b', "c"}
@@ -229,7 +235,7 @@ b #=> 'b'
c #=> "c"
# Procs represent a function pointer with an optional context (the closure data)
-# It is typically created with a proc litteral
+# It is typically created with a proc literal
proc = ->(x : Int32) { x.to_s }
proc.class # Proc(Int32, String)
# Or using the new method
@@ -246,7 +252,7 @@ elsif false
"else-if, optional"
else
"else, also optional"
-end
+end
puts "if as a suffix" if true
@@ -314,7 +320,7 @@ if a < 3
else
a = true
end
-typeof a #=> (Bool | String)
+typeof(a) #=> (Bool | String)
if a && b
# here both a and b are guaranteed not to be Nil
@@ -388,15 +394,19 @@ dinner #=> "quesadilla"
5.even? # false
5.odd? # true
-# And if a method ends with an exclamation mark, it does something destructive
-# like mutate the receiver. Some methods have a ! version to make a change, and
+# Also by convention, if a method ends with an exclamation mark, it does
+# something destructive like mutate the receiver.
+# Some methods have a ! version to make a change, and
# a non-! version to just return a new changed version
-company_name = "Dunder Mifflin"
-company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin"
-company_name #=> "Dunder Mifflin"
-company_name.gsub! "Dunder", "Donald"
-company_name #=> "Donald Mifflin"
+fruits = ["grapes", "apples", "bananas"]
+fruits.sort #=> ["apples", "bananas", "grapes"]
+fruits #=> ["grapes", "apples", "bananas"]
+fruits.sort! #=> ["apples", "bananas", "grapes"]
+fruits #=> ["apples", "bananas", "grapes"]
+# However, some mutating methods do not end in !
+fruits.shift #=> "apples"
+fruits #=> ["bananas", "grapes"]
# Define a class with the class keyword
class Human
@@ -404,7 +414,7 @@ class Human
# A class variable. It is shared by all instances of this class.
@@species = "H. sapiens"
- # type of name is String
+ # An instance variable. Type of name is String
@name : String
# Basic initializer
@@ -469,9 +479,9 @@ class TestClass
end
# Variables that start with a capital letter are constants
Var = "I'm a constant"
-Var = "can't be updated" # Already initialized constant Var
+Var = "can't be updated" # Error: already initialized constant Var
-# Class is also an object in crystal. So class can have instance variables.
+# Class is also an object in Crystal. So a class can have instance variables.
# Class variable is shared among the class and all of its descendants.
# base class
@@ -551,4 +561,4 @@ ex #=> "ex2"
## Additional resources
-- [Official Documentation](http://crystal-lang.org/)
+- [Official Documentation](https://crystal-lang.org/)
diff --git a/dart.html.markdown b/dart.html.markdown
index 2672dc6a..b215474a 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -6,7 +6,7 @@ contributors:
- ["Vince Ramces Oliveros", "https://github.com/ram231"]
---
-**Dart** is a single threaded, general puprose programming languages.
+**Dart** is a single threaded, general purpose programming language.
It borrows a lot from other mainstream languages.
It supports Streams, Futures(known as Promises in JavaScript), Generics, First-class functions(closures) and static type checking.
Dart can run in any platform such as Web, CLI, Desktop, Mobile and IoT devices.
@@ -198,7 +198,7 @@ class GenericExample<T>{
/// or outside of class have to be constant. Strings and numbers are constant
/// by default. But arrays and maps are not. They can be made constant by
/// declaring them "const". Kind of similar to Javascript's Object.freeze()
-const example8List = ["Example8 const array"],
+const example8List = ["Example8 const array"];
const example8Map = {"someKey": "Example8 const map"};
/// Declare List or Maps as Objects.
List<String> explicitList = new List<String>();
@@ -206,7 +206,6 @@ const example8Map = {"someKey": "Example8 const map"};
explicitList.add("SomeArray");
example8() {
- print(example8Array[0]);
print(example8Map["someKey"]);
print(explicitList[0]);
}
@@ -224,7 +223,7 @@ var newExplicitLists = explicitList.toList() // Converts Iterable<E> to List<E>
/// supported features, starting with forEach,map and where.
var example9Array = const ["a", "b"];
example9() {
- for (final i = 0; i < example9Array.length; i++) {
+ for (int i = 0; i < example9Array.length; i++) {
print("Example9 for loop '${example9Array[i]}'");
}
var i = 0;
@@ -694,7 +693,6 @@ example33() {
/// Dart has also added feature such as Null aware operators
var isBool = true;
var hasString = isBool ?? "default String";
-var hasValue ??= "default Value";
/// Programs have only one entry point in the main function.
/// Nothing is expected to be executed on the outer scope before a program
diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown
index 3a76708a..12da1df8 100644
--- a/de-de/bash-de.html.markdown
+++ b/de-de/bash-de.html.markdown
@@ -10,7 +10,7 @@ translators:
filename: LearnBash-de.sh
---
-Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und Mac OS X ausgeliefert wurde.
+Bash ist der Name der Unix-Shell, die als Shell des GNU-Betriebssystems und auch als Standard-Shell von Linux und macOS ausgeliefert wurde.
Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder direkt in der Shell ausgeführt werden.
[Weitere Informationen \(Englisch\)](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown
new file mode 100644
index 00000000..088a29a8
--- /dev/null
+++ b/de-de/clojure-macros-de.html.markdown
@@ -0,0 +1,161 @@
+---
+language: "clojure macros"
+filename: learnclojuremacros-de.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Wie mit allen Lisps besitzt auch Clojure die inhärente [Homoikonizität](https://en.wikipedia.org/wiki/Homoiconic),
+die dir den vollen Zugang der Sprache gibt, um
+ Code-Generierungsroutinen zu schreiben. Diese werden "Macros" genannt.
+Macros geben dir eine leistungsarke Möglichkeit, die Sprache
+an deine Bedürfnisse anzupassen.
+
+Sei aber vorsichtig, es wird als schlechter Stil angesehen, wenn du
+ein Macro schreibst, obwohl eine Funktion genausogut funktionieren würde.
+Verwende nur dann ein Macro, wenn du Kontrolle darüber brauchst, wann oder ob Argumente in einer Form evaluiert werden.
+
+Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Clojure in Y Minutes](/docs/clojure/) verstehst.
+
+```clojure
+;; Definiere ein Macro mit defmacro. Dein Macro sollte eine Liste zurückgeben,
+;; die als Clojure Code evaluiert werden kann.
+;;
+;; Dieses Macro ist das Gleiche, als ob du (reverse "Hallo Welt") geschrieben
+;; hättest
+(defmacro my-first-macro []
+ (list reverse "Hallo Welt"))
+
+;; Inspiziere das Ergebnis eines Macros mit macroexpand oder macroexpand-1.
+;;
+;; Beachte, dass der Aufruf zitiert sein muss.
+(macroexpand '(my-first-macro))
+;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hallo Welt")
+
+;; Du kannst das Ergebnis von macroexpand direkt auswerten.
+(eval (macroexpand '(my-first-macro)))
+; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Aber du solltest diese prägnante und funktionsähnliche Syntax verwenden:
+(my-first-macro) ; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Du kannst es dir leichter machen, indem du die Zitiersyntax verwendest
+;; um Listen in ihren Makros zu erstellen:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hallo Welt"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hallo Welt")
+;; Beachte, dass reverse nicht mehr ein Funktionsobjekt ist, sondern ein Symbol
+
+;; Macros können Argumente haben.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Aber wenn du versuchst das mit einer zitierten Liste zu machen wirst du
+;; einen Fehler bekommen, weil das Argument auch zitiert sein wird.
+;; Um dies zu umgehen, bietet Clojure einee Art und Weise Macros zu zitieren: `
+;; In ` kannst du ~ verwenden um in den äußeren Bereich zu kommen.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Du kannst die normalen destruktuierungs Argumente verwenden. Expandiere
+;; Listenvariablen mit ~@.
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Erinnere dich an das do!
+
+(macroexpand '(unless true (reverse "Hallo Welt")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hallo Welt")))
+
+;; (unless) evaluiert und gibt body zurück, wenn das erste Argument falsch ist.
+;; Andernfalls gibt es nil zurück
+
+(unless true "Hallo") ; -> nil
+(unless false "Hallo") ; -> "Hallo"
+
+;; Die Verwendung Macros ohne Sorgfalt kann viel Böses auslösen, indem es
+;; deine Variablen überschreibt
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;; Um das zu verhindern kannst du gensym verwenden um einen eindeutigen
+;; Identifikator zu bekommen
+(gensym 'x) ; -> x1281 (oder etwas Ähnliches)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Du kannst # innerhalb von ` verwenden um für jedes Symbol automatisch
+;; ein gensym zu erstellen
+(defmacro define-x-hygienically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygienically) ; -> (2)
+(list x) ; -> (4)
+
+;; Es ist üblich, Hilfsfunktionen mit Macros zu verwenden. Lass uns einige
+;; erstellen, die uns helfen , eine (dumme) arithmetische Syntax
+;; zu unterstützen
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Bekomme die Argumente [x (+ y)], gebe (+ x y) zurück"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Wir können es sofort testen, ohne ein Macro zu erstellen
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Allerdings, brauchen wir ein Macro, wenn wir es zur Kompilierungszeit
+; ausführen wollen
+(defmacro inline-2 [form]
+ (inline-2-helper form))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (eigentlich, 3N, da die Zahl zu einem rationalen Bruch mit / umgewandelt wird)
+```
+
+### Weiterführende Literatur
+
+[Macros schreiben](http://www.braveclojure.com/writing-macros/)
+
+[Offiziele Docs](http://clojure.org/macros)
+
+[Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/)
diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown
index 29d5132d..254cca51 100644
--- a/de-de/elixir-de.html.markdown
+++ b/de-de/elixir-de.html.markdown
@@ -35,6 +35,10 @@ viele Features mit.
0x1F # Integer
3.0 # Float
+# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden
+1_000_000 == 1000000 # Integer
+1_000.567 == 1000.567 # Float
+
# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem
# ':'.
:hello # Atom
diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown
new file mode 100644
index 00000000..08832327
--- /dev/null
+++ b/de-de/elm-de.html.markdown
@@ -0,0 +1,376 @@
+---
+language: Elm
+filename: learnelm.elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+translators:
+ - ["waynee95", "https://waynee95.me"]
+lang: de-de
+---
+
+Elm ist eine pure funktionale Programmiersprache. Mit Elm werden GUIs
+(grafische Benutzeroberfläche) für Webanwendungen erstellt. Durch die statische
+Typisierung kann Elm viele Fehler schon bei der Kompilierung abfangen. Ein
+Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen.
+
+```haskell
+-- Einzeilige Kommentare beginnen mit 2 Bindestrichen.
+{- So wird ein mehrzeiliger Kommentar angelegt.
+{- Diese können auch verschachtelt werden. -}
+-}
+
+{-- Die Grundlagen --}
+
+-- Arithmetik
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Zahlen ohne Punkt sind entweder vom Typ Int oder Float.
+33 / 2 -- 16.5 mit Division von Gleitkommazahlen
+33 // 2 -- 16 mit ganzzahliger Division
+
+-- Exponenten
+5 ^ 2 -- 25
+
+-- Boolsche Werte
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings (Zeichenketten) und Zeichen
+"Das hier ist ein String."
+'a' -- Zeichen
+
+-- Strings können konkateniert werden.
+"Hello " ++ "world!" -- "Hello world!"
+
+{-- Listen und Tupel --}
+
+-- Jedes Element einer Liste muss vom gleichen Typ sein. Listen sind homogen.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- Das zweite Beispiel kann man auch mit Hilfe der "range" Funktion schreiben.
+List.range 1 5
+
+-- Listen werden genauso wie Strings konkateniert.
+List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True
+
+-- Mit dem "cons" Operator lässt sich ein Element an den Anfang einer Liste anfügen.
+0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5]
+
+-- Die Funktionen "head" und "tail" haben als Rückgabewert den "Maybe" Typ.
+-- Dadurch wird die Fehlerbehandlung von fehlenden Elementen explizit, weil
+-- man immer mit jedem möglichen Fall umgehen muss.
+List.head (List.range 1 5) -- Just 1
+List.tail (List.range 1 5) -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.funktionsName bedeutet, dass diese Funktion aus dem "List"-Modul stammt.
+
+-- Tupel sind heterogen, jedes Element kann von einem anderen Typ sein.
+-- Jedoch haben Tupel eine feste Länge.
+("elm", 42)
+
+-- Das Zugreifen auf Elemente eines Tupels geschieht mittels den Funktionen
+-- "first" und "second".
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
+
+-- Das leere Tupel, genannt "Unit", wird manchmal als Platzhalter verwendet.
+-- Es ist das einzige Element vom Typ "Unit".
+()
+
+{-- Kontrollfluss --}
+
+-- Eine If-Bedingung hat immer einen Else-Zweig und beide Zweige müssen den
+-- gleichen Typ haben.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- If-Bedingungen können verkettet werden.
+if n < 0 then
+ "n is negative"
+else if n > 0 then
+ "n is positive"
+else
+ "n is zero"
+
+-- Mit dem Mustervergleich (pattern matching) kann man bestimmte Fälle direkt
+-- behandeln.
+case aList of
+ [] -> "matches the empty list"
+ [x]-> "matches a list of exactly one item, " ++ toString x
+ x::xs -> "matches a list of at least one item whose head is " ++ toString x
+-- Mustervergleich geht immer von oben nach unten. Würde man [x] als letztes
+-- platzieren, dann würde dieser Fall niemals getroffen werden, weil x:xs diesen
+-- Fall schon mit einschließt (xs ist in dem Fall die leere Liste).
+
+-- Mustervergleich an einem Maybe Typ.
+case List.head aList of
+ Just x -> "The head is " ++ toString x
+ Nothing -> "The list was empty."
+
+{-- Funktionen --}
+
+-- Die Syntax für Funktionen in Elm ist minimal. Hier werden Leerzeichen anstelle
+-- von runden oder geschweiften Klammern verwendet. Außerdem gibt es kein "return"
+-- Keyword.
+
+-- Eine Funktion wird durch ihren Namen, einer Liste von Parametern gefolgt von
+-- einem Gleichheitszeichen und dem Funktionskörper angegeben.
+multiply a b =
+ a * b
+
+-- Beim Aufruf der Funktion (auch Applikation genannt) werden die Argumente ohne
+-- Komma übergeben.
+multiply 7 6 -- 42
+
+-- Partielle Applikation einer Funktion (Aufrufen einer Funktion mit fehlenden
+-- Argumenten). Hierbei entsteht eine neue Funktion, der wir einen Namen geben.
+double =
+ multiply 2
+
+-- Konstanten sind Funktionen ohne Parameter.
+answer =
+ 42
+
+-- Funktionen, die Funktionen als Parameter haben, nennt man Funktionen höherer
+-- Ordnung. In funktionalen Programmiersprachen werden Funktionen als "first-class"
+-- behandelt. Man kann sie als Argument übergeben, als Rückgabewert einer Funktion
+-- zurückgeben oder einer Variable zuweisen.
+List.map double (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Funktionen können auch als anonyme Funktion (Lambda-Funktionen) übergeben werden.
+-- Diese werden mit einem Blackslash eingeleitet, gefolgt von allen Argumenten.
+-- Die Funktion "\a -> a * 2" beschreibt die Funktion f(x) = x * 2.
+List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Mustervergleich kann auch in der Funktionsdefinition verwendet werden.
+-- In diesem Fall hat die Funktion ein Tupel als Parameter. (Beachte: Hier
+-- werden die Werte des Tupels direkt ausgepackt. Dadurch kann man auf die
+-- Verwendung von "first" und "second" verzichten.)
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Mustervergleich auf Records macht man mit geschweiften Klammern.
+-- Bezeichner (lokale Variablen) werden mittels dem "let" Keyword angelegt.
+-- (Mehr zu Records weiter unten!)
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Rekursive Funktion
+fib n =
+ if n < 2 then
+ 1
+ else
+ fib (n - 1) + fib (n - 2)
+
+List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
+
+-- Noch eine rekursive Funktion (Nur ein Beispiel, verwende stattdessen immer
+-- List.length!)
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Funktionsapplikation hat die höchste Präzedenz, sie binden stärker als Operatoren.
+-- Klammern bietet die Möglichkeit der Bevorrangung.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen.
+-- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben.
+-- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese
+-- beiden Werte dann addiert.
+
+{-- Typen und Typ Annotationen --}
+
+-- Durch Typinferenz kann der Compiler jeden Typ genau bestimmen. Man kann diese
+-- aber auch manuell selber angeben (guter Stil!).
+-- Typen beginnen immer mit eine Großbuchstaben. Dabei liest man "x : Typ" als
+-- "x" ist vom Typ "Typ".
+-- Hier ein paar übliche Typen:
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Funktionen haben ebenfalls einen Typ. Dabei ist der ganz rechte Typ der
+-- Rückgabetyp der Funktion und alle anderen sind die Typen der Parameter.
+not : Bool -> Bool
+round : Float -> Int
+
+-- Es ist guter Stil immer den Typ anzugeben, da diese eine Form von Dokumentation
+-- sind. Außerdem kann so der Compiler genauere Fehlermeldungen geben.
+double : Int -> Int
+double x = x * 2
+
+-- Funktionen als Parameter werden durch Klammern angegeben. Die folgende Funktion
+-- ist nicht auf einen Typ festgelegt, sondern enthält Typvariablen (beginnend
+-- mit Kleinbuchstaben). Die konkreten Typen werden erst bei Anwendung der
+-- Funktion festgelegt. "List a" bedeutet, dass es sich um eine Liste mit
+-- Elementen vom Typ "a" handelt.
+List.map : (a -> b) -> List a -> List b
+
+-- Es gibt drei spezielle kleingeschriebene Typen: "number", "comparable" und
+-- "appendable".
+add : number -> number -> number
+add x y = x + y -- funktioniert mit Ints und Floats.
+
+max :: comparable -> comparable -> comparable
+max a b = if a > b then a else b -- funktioniert mit Typen, die vergleichbar sind.
+
+append :: appendable -> appendable -> appendable
+append xs ys = xs ++ ys -- funktioniert mit Typen, die konkatenierbar sind.
+
+append "hello" "world" -- "helloworld"
+append [1,1,2] [3,5,8] -- [1,1,2,3,5,8]
+
+{-- Eigene Datentypen erstellen --}
+
+-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat.
+-- Dabei spielt die Reihenfolge keine Rolle.
+{ x = 3, y = 7 }
+
+-- Um auf Werte eines Records zuzugreifen, benutzt man einen Punkt gefolgt
+-- von dem Namen des Feldes.
+{ x = 3, y = 7 }.x -- 3
+
+-- Oder mit einer Zugriffsfunktion, welche aus einem Punkt und dem Feldnamen besteht.
+.y { x = 3, y = 7 } -- 7
+
+-- Wert eines Feldes ändern. (Achtung: Das Feld muss aber vorher schon vorhanden sein!)
+{ person |
+ name = "George" }
+
+-- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes.
+{ particle |
+ position = particle.position + particle.velocity,
+ velocity = particle.velocity + particle.acceleration }
+
+-- Du kannst ein Record auch als Typ Annotation verwenden.
+-- (Beachte: Ein Record Typ benutzt einen Doppelpunkt und ein Record Wert benutzt
+-- ein Gleichheitszeichen!)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- Durch das "type" Keyword kann man einem existierenden Typen einen Namen geben.
+type alias Point3D =
+ { x : Float, y : Float, z : Float }
+
+-- Der Name kann dann als Konstruktor verwendet werden.
+otherOrigin : Point3D
+otherOrigin =
+ Point3D 0 0 0
+
+-- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist!
+origin == otherOrigin -- True
+
+-- Neben den Records gibt es auch noch so genannte Summentypen.
+-- Ein Summentyp hat mehrere Konstruktoren.
+type Direction =
+ North | South | East | West
+
+-- Ein Konstruktor kann außerdem noch andere Typen enthalten. Rekursion ist
+-- auch möglich.
+type IntTree =
+ Leaf | Node Int IntTree IntTree
+
+-- Diese können auch als Typ Annotation verwendet werden.
+root : IntTree
+root =
+ Node 7 Leaf Leaf
+
+-- Außerdem können auch Typvariablen verwendet werden in einem Konstruktor.
+type Tree a =
+ Leaf | Node a (Tree a) (Tree a)
+
+-- Beim Mustervergleich kann man auf die verschiedenen Konstruktoren matchen.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+{-- Module und Imports --}
+
+-- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt.
+-- Für große Projekte können auch eigene Module erstellt werden.
+
+-- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich
+-- automatisch im Modul "Main".
+module Name where
+
+-- Ohne genaue Angabe von Exports wird alles exportiert. Es können aber alle
+-- Exporte explizit angegeben werden.
+module Name (MyType, myValue) where
+
+-- Importiert das Modul "Dict". Jetzt kann man Funktionen mittels "Dict.insert"
+-- aufrufen.
+import Dict
+
+-- Importiert das "Dict" Modul und den "Dict" Typ. Dadurch muss man nicht "Dict.Dict"
+-- verwenden. Man kann trotzdem noch Funktionen des Moduls aufrufen, wie "Dict.insert".
+import Dict exposing (Dict)
+
+-- Abkürzung für den Modulnamen. Aufrufen der Funktionen mittels "C.funktionsName".
+import Graphics.Collage as C
+
+{-- Kommandozeilen Programme --}
+
+-- Eine Elm-Datei kompilieren.
+$ elm make MyFile.elm
+
+-- Beim ersten Aufruf wird Elm die "core" Bibliotheken installieren und eine
+-- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes
+-- speichert.
+
+-- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt.
+$ elm reactor
+
+-- Starte das REPL (read-eval-print-loop).
+$ elm repl
+
+-- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert.
+-- Installieren einer neuen Bibliothek.
+$ elm package install elm-lang/html
+-- Diese wird der elm-package.json Datei hinzugefügt.
+
+-- Zeigt alle Veränderungen zwischen zwei bestimmten Versionen an.
+$ elm package diff elm-lang/html 1.1.0 2.0.0
+-- Der Paketmanager von Elm erzwingt "semantic versioning"!
+```
+
+Elm ist eine besonders kleine Programmiersprache. Jetzt hast du genug Wissen an
+deiner Seite, um dich in fast jedem Elm Code zurecht zu finden.
+
+Noch ein paar weitere hilfreiche Ressourcen (in Englisch):
+
+- Die [Elm Homepage](http://elm-lang.org/). Dort findest du:
+
+ - [Anleitung zur Installierung von Elm](http://elm-lang.org/install)
+ - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax)
+ - Viele hilfreiche [Beispiele](http://elm-lang.org/examples)
+
+- Dokumentation der [Elm Kernbibliotheken](http://package.elm-lang.org/packages/elm-lang/core/latest/). Insbesondere:
+
+ - [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics) (standardmäßig importiert)
+ - [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) sowie [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) (benutzt für Fehlerbehandlung)
+ - Datenstrukturen, wie [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), und [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ - JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) und [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+- [Die Elm Architektur](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture).
+
+- Die [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss).
diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown
index ea02e81d..ffe8dffc 100644
--- a/de-de/nix-de.html.markdown
+++ b/de-de/nix-de.html.markdown
@@ -356,3 +356,6 @@ with builtins; [
* [Susan Potter - Nix Cookbook - Nix By Example]
(https://ops.functionalalgebra.com/nix-by-example/)
+
+* [Rommel Martinez - A Gentle Introduction to the Nix Family]
+ (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown
index fd8fb3c4..13c00b01 100644
--- a/de-de/perl-de.html.markdown
+++ b/de-de/perl-de.html.markdown
@@ -8,9 +8,9 @@ translators:
lang: de-de
---
-Perl 5 ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
+Perl ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
-Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl 5 ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
+Perl läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
```perl
# Einzeilige Kommentare beginnen mit dem # Symbol.
diff --git a/de-de/processing-de.html.markdown b/de-de/processing-de.html.markdown
new file mode 100644
index 00000000..42ae2233
--- /dev/null
+++ b/de-de/processing-de.html.markdown
@@ -0,0 +1,498 @@
+---
+language: processing
+filename: learnprocessing.pde
+contributors:
+ - ["Phone Thant Ko", "http://github.com/phonethantko"]
+ - ["Divay Prakash", "https://github.com/divayprakash"]
+translators:
+ - ["caminsha", "https://github.com/caminsha"]
+filename: processing-de.md
+lang: de-de
+---
+
+## Einführung
+
+Processing ist eine Programmiersprache, welche es ermöglicht, digitale Kunst
+und multimediale Inhalte zu erstellen. Mit Processing können Personen ohne
+Programmiererfahrung die Grundlagen der Computerprogrammierung in einem
+visuellen Kontext erlernen.
+
+Obwohl Processing von Java beeinflusst wurde und auf Java basiert, ist die Syntax
+sowohl von Java als auch Javascript beeinflusst worden. Weitere Informationen
+sind [hier](https://processing.org/reference/) zu finden.
+
+Die Programmiersprache wird statisch programmiert und kommt mit einer eigenen
+offiziellen IDE, damit die Programme kompiliert und ausgeführt werden können.
+
+```
+/* ------------
+ Mehrzeilige Kommentare werden so gemacht
+*/
+
+// Einzeilige Kommentare funktionieren so //
+
+/*
+ Da Processing von Java abstammt, ist die Syntax für Kommentare gleich
+ wie bei Java (wie du vielleicht oben bemerkt hast)!
+ Mehrzeilige Kommentare werden wie hier umschloßen.
+*/
+
+/* -------------------------------------------------
+ Schreiben und Ausführen von Processing Programmen
+ -------------------------------------------------
+*/
+
+// In Processing ist der Startpunkt eines Programms die Funktion `setup()`
+// mit dem Rückgabetyp `void`.
+// Beachte: Die Syntax ist derjenigen von C++ ziemlich ähnlich.
+void setup() {
+ // Dies gibt beim Ausführen "Hallo Welt!" auf der Konsole aus.
+ println("Hallo Welt!"); // eine weitere Sprache mit einem Semikolon am Ende.
+}
+
+// Normalerweise wird der Code für statische Elemente innerhalb der Methode
+// `setup()` geschrieben, da diese lediglich einmal ausgeführt wird.
+// Dies kann zum Beispiel das Setzen der Hintergrundfarbe oder das Bestimmen
+// der Canvas-Größe sein.
+background(color); // Setze die Hintergrundfarbe
+size(width, height, [renderer]); // bestimme die Canvasgröße mit dem optionalen
+ // Parameter `renderer`.
+// Du wirst innerhalb dieses Dokuments noch weitere Parameter sehen.
+
+// Wenn du möchstest, dass Code unendlich oft ausgeführt wird, so muss dieser
+// Code innerhalb der `draw()`-Methode stehen.
+// `draw()` muss existieren, wenn du möchtest, dass das Programm durchgehend
+// läuft. Die `draw()`-Methode darf nur einmal vorkommen.
+
+int i = 0;
+void draw() {
+ // Dieser Codeblock wird ausgeführt bis er gestoppt wird.
+ print(i);
+ i++; // Inkrement-Operator
+}
+
+// Da wir nun wissen, wie man ein funktionierendes Skript erstellen kann und wie
+// dieses ausgeführt wird, fahren wir mit den unterschiedlichen Datentypen und
+// Collections weiter, welche in Processing unterstützt werden.
+
+/* -------------------------------------------------
+ Datentypen und Collections
+ -------------------------------------------------
+*/
+
+// Gemäß den Angaben in der Processingreferenz, unterstützt Processing die
+// folgenden acht primitiven Datentypen:
+boolean booleanValue = true; // Boolean
+byte byteValueOfA = 23; // Byte
+char charValueOfA = 'A'; // Char (einzelnes Zeichen)
+color colorValueOfWhiteM = color(255, 255, 255); // Farben (angegeben durch die
+ // `color()`-Methode)
+color colorValueOfWhiteH = #FFFFFF; // Farbe (angegeben mit der Hexadezimal-
+ // schreibweise.)
+int intValue = 5; // Integer (ganze Zahl)
+long longValue = 2147483648L; // "L" wird hinzugefügt, um es als `long` zu
+ // markieren.
+float floatValue = 1.12345; // Float (32-Bit Gleitkommazahl)
+double doubleValue = 1.12345D // Double (64-Bit Gleitkommazahl)
+
+//BEACHTE!
+// Auch wenn es die Datentypen "long" und "double" gibt und auch funktionieren,
+// verwenden Processing-Funktionen diese Datentypen nicht. Das bedeutet, dass
+// diese zu "int" resp. "float" konvertiert werden müssen.
+// Dies geschieht, indem man `(int)` oder `(float)` vor die Variable schreibt,
+// bevor diese einer Funktion übergeben werden.
+
+// Es gibt eine ganze Reiher zusammengesetzter Datentypen, welche in Processing
+// gebraucht werden können. Um Zeit zu sparen, gehen wir in diesem Tutorial
+// lediglich die wichtigsten durch.
+
+// String
+// Während der Datentyp `char` einfache Anzührungszeichen (' ') braucht, haben
+// Strings doppelte Anführungszeichen (" ").
+String sampleString = "Hallo, Processing!";
+// Strings können auch durch ein Array von `char`s erstellt werden.
+// Wir werden Arrays gleich anschauen.
+char source = {'H', 'A', 'L', 'L', 'O'};
+String stringFromSource = new String(source); // HALLO
+// Wie auch in Java können in Processing Strings auch zusammengefügt werden
+// mit dem +-Operator.
+print("Hallo " + "Welt!"); // => Hallo Welt!
+
+
+// Arrays
+// In Processing können Arrays jeden Datentypen beinhalten, sogar Objekte.
+// Da Arrays ähnlich wie Objekte sind, müssen diese mit dem Schlüsselwort `new`
+// erstellt werden.
+int[] intArray = new int[5];
+int[] intArrayWithValues = {1, 2, 3} // Arrays können auch mit Daten gefüllt
+ // werden.
+// ArrayList
+// Die Funktionen einer ArrayList sind ähnlich wie die eines Arrays und können
+// auch jegliche Datentypen beinhalten. Der einzige Unterschied zwischen Arrays
+// und `ArrayList`s ist, dass eine `ArrayList` die Größe dynamisch anpassen kann,
+// da es eine Implementierung des "List" Interface in Java ist.
+ArrayList<Integer> intArrayList = new ArrayList<Integer>();
+
+// Objekte
+// Da Processing auf Java basiert, unterstützt Processing die Objektorientierte
+// Programmierung. Dies bedeutet, dass du grundsätzlich jegliche Datentypen
+// selber erstellen kannst und diese nach deinen Bedürfnissen manipulieren kannst.
+// Selbstverständlich muss eine Klasse definiert werden bevor du ein Objekt
+// davon instanzieren kannst.
+// Format: ClassName InstanceName
+SomeRandomClass myObject // hier musst du das Objekt später instazieren
+// Hier wird das Objekt direkt instanziert:
+SomeRandomClass myObjectInstantiated = new SomeRandomClass();
+
+// Processing hat noch weitere Collections (wie zum Beispiel Dictionaries und
+// Listen). Aus Einfachheitsgründen wird dies in diesem Tutorial weggelassen.
+
+/* -------------------------------------------------
+ Mathematik
+ -------------------------------------------------
+*/
+
+// Arithmetik
+1 + 1 // => 2
+2 -1 // => 1
+2 * 3 // => 6
+3 / 2 // => 1
+3.0 / 2 // => 1.5
+3.0 % 2 // => 1.0 (Modulo)
+
+// Processing beinhaltet auch einige Funktionen, welche mathematische
+// Operationen vereinfachen
+float f = sq(3); // Quadrat => f = 9.0
+float p = pow(3, 3); // Potenz => p = 27.0
+int a = abs(-13); // Absolute Zahl => a = 13
+int r1 = round(3.1); // Runden => r1 = 3
+int r2 = round(3.7); // Runden => r2 = 4
+int sr = sqrt(25); // Quadratwurzel => sr = 5.0
+
+// Vektoren
+// Processing bietet eine einfache Möglichkeit an, mit Vektoren zu arbeiten mit
+// der Klasse PVector. Die Klasse kann zwei- und dreidimensionale Vektoren
+// darstellen und bietet Methoden an, welche nützlich sein können für Matrizen-
+// Operationen. Weitere Informationen findest du hier:
+// (https://processing.org/reference/PVector.html)
+
+// Trigonometrie
+// Processing unterstützt auch trigonometrische Operationen mit Hilfe dieser
+// Funktionen: `sin()`, `cos()`, `tan()`, `asin()`, `atan()`. Für die einfache
+// Konvertierung gibt es außerdem noch die Funktionen `degrees()` und `radians()`.
+// Die trigonometrischen Funktionen rechnen mit dem Winkelmaß Radian, wodurch
+// die Gradzahlen zuerst konvertiert werden müssen.
+float one = sin(PI/2); // => one = 1.0
+// Wie du vielleicht bemerkt hast, existieren einige Konstanten für trigo-
+// metrische Operationen; `PI`, `HALF_PI`, `QUARTER_PI` und so weiter ...
+
+/* -------------------------------------------------
+ Kontrollstrukturen
+ -------------------------------------------------
+*/
+
+// Bedingte Anweisungen
+// Bedinge Anweisungen werden gleich wie in Java geschrieben.
+if (author.getAppearence().equals("hot")) {
+ print("Narzissmus vom Feinsten!")
+} else {
+ // Du kannst hier weitere Bedingungen prüfen.
+ print("Irgendetwas ist falsch hier!");
+}
+// Für die `if`-Anweisungen gibt es auch eine Kurzschreibweise
+// Dies sind sogenannte ternäre Operatoren.
+int i = 3;
+String value = (i > 5) ? "Groß" : "Klein"; // => "Klein"
+
+// Die Switch-Case-Anweisung kann verwendet werden, um mehrere Bedingungen
+// zu prüfen.
+// Wichtig ist, dass nach jeder Bedingung ein `break`-Statement verwendet wird,
+// sonst werden alle folgenden ausgeführt und es wird nicht mehr überprüft, ob
+// die Bedingung wahr ist.
+int value = 2;
+switch(value) {
+ case 0:
+ print("Auf keinen Fall!"); // Dies wird nicht ausgeführt.
+ break; // Geht zum nächsten Statement und prüft dieses
+ case 1:
+ print("Wir kommen näher..."); // Auch dies wird nicht ausgeführt
+ break;
+ case 2:
+ print("Bravo!"); // Dies wird ausgeführt.
+ break;
+ default:
+ print("Nicht gefunden."); // Diese Zeile wird ausgeführt, wenn keine
+ // der anderen Operatoren wahr sind.
+ break;
+}
+
+// Wiederholungen
+// For-Schleifen - Auch hier ist die Syntax wieder gleich wie in Java
+for(int i = 0; i < 5; i++) {
+ print(i); // Gibt die Zahlen 0 bis 4 aus.
+}
+
+// While-Statements
+int j = 3;
+while(j > 0) {
+ print(j);
+ j--; // Dies ist wichtig, dass der Code nicht unendlich lange läuft.
+}
+
+// `loop()` | `noloop()` | `redraw()` | `exit()`
+// Dies sind spezifische Funktionen, welche in Processing verwendet werden
+// können, um den Programmablauf zu steuern.
+loop(); // erlaubt es der `draw()`-Methode immer zu laufen, während
+noloop(); // dies nur für einmal erlaubt.
+redraw(); // führt die `draw()`-Methode noch einmal aus.
+exit(); // Diese Methode stoppt das Programm. Dies kann nützlich sein, wenn die
+ // Methode `draw()` immer läuft.
+```
+
+## Mit Processing zeichnen
+
+Da du nun die Grundsätze der Programmiersprache verstanden hast, schauen wir
+uns nun das Beste an Processing an - Das Zeichnen!
+
+```
+
+/* -------------------------------------------------
+ Figuren
+ -------------------------------------------------
+*/
+
+// 2D-Figuren
+
+// Punkte
+point(x,y); // im zweidimensionalen Raum
+point(x, y, z); // im dreidimensionalen Raum
+// Diese Befehle zeichnen einen Punkt an der Koordinate.
+
+// Linien
+line(x1, y1, x2, y2); // im zweidimensionalen Raum
+// Dies zeichnet eine Linie, welche durch die zwei Punkte (x1, y1) und (x2, y2)
+// definiert wird.
+line(x1, y1, z1, x2, y2, z2); // im dreidimensionalen Raum
+// Analog wird hier eine Linie gezeichnet mit drei Punkten
+
+// Dreieck
+triangle(x1, y1, x2, y2, x3, y3);
+// Zeichnet ein Dreieck, welches als Eckpunkte die drei Koordinaten hat.
+
+// Rechteck
+rect(a, b, c, d, [r]); // Mit dem optionalen Parameter kann der Winkel aller
+ // vier Ecken definiert werden
+rect(a, b, c, d, [tl, tr, br, bl]); // Mit weiteren optionalen Parametern kann
+ // jeder Winkel des Rechtecks definiert werden.
+// Dies zeichnet ein Quadrat mit der Koordinate {a, b} als linke obere Ecke
+// die Parameter c und d sind für die Breite und Höhe.
+
+// Vierecke
+quad(x, y, x2, y2, x3, y3, x4, y4);
+// Dies zeichnet ein Viereck, welches die einzelnen Koordinaten als Eckpunkte hat.
+
+// Ellipse
+ellipse(x, y, width, height);
+// Zeichnet eine Ellipse beim Punkt {x. y}. Die Breite und die Höhe werden durch
+// die Parameter width und height definiert.
+
+// Arc
+arc(x, y, width, height, start, stop, [mode]);
+// Die ersten vier Parameter sollten selbsterklärend sein.
+// start und end definieren die Winkel, bei welchen `arc` starten resp. enden
+// (in Radians)
+// Der optionale Parameter `mode` definiert, ob der Kreisbogen gefüllt wird
+// oder nicht.
+// Die möglichen Optionen für `mode` sind: PIE, CHORD und OPEN.
+
+// Kurven
+// Processing bietet zwei mögliche Kurven an, welche verwendet werden können.
+// Da es hier darum geht, dass es möglichst simpel ist, werden hier keine
+// weiteren Details genannt. Wenn du Kurven in deinem Programm verwenden möchtest,
+// sind die folgenden Links empfehlenswert:
+// https://processing.org/reference/curve_.html
+// https://processing.org/reference/bezier_.html
+
+
+// 3D-Figuren
+
+// Der dreidimensionale Raum kann aktiviert werden, indem man den Renderer-
+// Parameter in der Methode `size()` zu "P3D" setzt.
+size(width, height, P3D);
+// Im dreidimensionalen Raum müssen die Koordinaten übersetzt werden, damit
+// diese korrekt gerendert werden.
+
+// Box
+box(size); // Würfel mit der Seitenlänge `size`
+box(w, h, d); // Quader definiert durch Breite, Höhe und Tiefe
+
+// Kugel
+sphere(radius); // Die Größe wird definiert durch den Parameter `radius`
+// Der Mechanismus hinter dem Rendern von Kugeln wurde durch mosaikartige
+// Dreiecke implementiert.
+// Mit der folgenden Funktion ist es möglich, zu bestimmen wie detailliert die
+// Kugel gerendert wird.
+// spereDetail(res);
+// Weitere Informationen sind hier zu finden: (https://processing.org/reference/sphereDetail_.html)
+
+// Unregelmäßige Figuren
+// Was ist, wenn du etwas zeichnen möchtest, was nicht durch Processing-Funktionen
+// abgedeckt ist?
+// Es ist möglich, die Funktionen `beginShape()`, `endShape()` und `vertex(x,y)
+// zu verwenden.
+// Weitere Informationen findest du hier: (https://processing.org/reference/beginShape_.html)
+// Du kannst selber gemachte Formen auch verwenden mit der PShape-Klasse.
+// Informationen zu PShape gibt es hier: (https://processing.org/reference/PShape.html)
+
+/* -------------------------------------------------
+ Transformationen
+ -------------------------------------------------
+*/
+
+// Tranformationen sind nützlich, um ständig zu wissen, wo die Koordinaten und
+// die Ecken einer Form sind, welche du gezeichnet hast. Grundsätzlich sind dies
+// Matrizenoperationen. `pushMatrix()`, `popMatrix()` und `translate()`.
+pushMatrix(); // Speichert das aktuelle Koordinatensystem auf dem Stack
+ // alle Transformationen werden hier angewendet.
+popMatrix(); // Stellt das gespeicherte Koordinatensystem wieder her.
+// Wenn du diese Funktionen verwendest, kann das Koordinatensystem gespeichert
+// und visualisiert werden, ohne dass es Konflikte gibt.
+
+// Translate
+translate(x,y); // Setzt den Ursprung zu diesem Punkt.
+translate(x, y, z); // Pendant zu der oberen Funktion im dreidimensionalen Raum
+
+// Rotationen
+rotate(angle); // Rotiere, um den Betrag, welcher spezifiert wurde.
+// Es gibt drei Pendants im dreidimensionalen Raum.
+// Namentlich sind dies: `rotateX(angle)`, `rotateY(angle)` und `rotateZ(angle)`
+
+// Skalierung
+scale(s); // Skaliert das Koordinatensystem (entweder erweitern oder verkleinern)
+
+/* -------------------------------------------------
+ Styling und Texturen
+ -------------------------------------------------
+*/
+
+// Farben
+// Wie ich zuvor schon erklärt habe, kann die Hintergrundfarbe mit der Funktion
+// `background()` definiert werden. Außerdem ist es möglich, dass man zuerst
+// eine Farbe definiert und diese erst danach der Funktion übergeben wird.
+color c = color(255, 255, 255); // WEISS!
+// Standardmäßig verwendet Processing das RGB-Farbschema, aber dies kann
+// zu HSB konfiguriert werden, indem die Funktion `colorMode()` verwendet wird.
+// Weitere Informationen findest du hier: (https://processing.org/reference/colorMode_.html)
+background(c); // Ab jetzt ist der Hintergrund in weiß.
+// Du kannst die Funktion `fill()` verwenden, um die Farbe auszuwählen, mit
+// welcher die Formen ausgefüllt werden.
+// Dies muss konfiguriert werden bevor Formen und Figuren gezeichnet werden.
+fill(color(0, 0, 0));
+// Wenn du nur die Farbe der Umrandungen definieren möchtest, kannst du die
+// Funktion `stroke()` verwenden.
+stroke(255, 255, 0, 200); // Linienfarbe wird zu gelb mit einer höheren
+ // Transparenz geändert.
+
+// Bilder
+// Processing kann Bilder rendern und diese unterschiedlich verwenden. Die
+// meisten Bilder sind im Datentyp `PImage` gespeichert.
+filter(shader); // Processing unterstützt mehrere Filter-Funktionen, damit
+ // Bilder verändert werden können.
+texture(image); // PImage kann als Argument, weiteren Funktionen übergeben
+ // werden, um die Figuren zu "Text" zu machen.
+```
+
+Wenn du weitere Dinge mit Processing kennenlernen willst, dann gibt es unzählige
+Dinge, welche du mit Processing machen kannst. Das Rendern von Modellen,
+Schattierungen und viele mehr. Für ein kurzes Tutorial bietet Processing zu viel,
+daher verweise ich dich, falls du interessiert bist, auf die offizielle
+Dokumentaion.
+
+```
+// Bevor wir weiterfahren, werde ich einige Aspekte zum Importieren von
+// Bibliotheken und Paketen sagen, damit du Processing erweitern kannst..
+
+/* -------------------------------------------------
+ Import
+ -------------------------------------------------
+*/
+
+// Die Macht von Processing kann besser veranschaulicht werden, wenn wir
+// Bibliotheken und Pakete importieren.
+// Die Import-Anweisung kann wie unten geschrieben zu Beginn des Quelltextes
+// geschrieben werden.
+import processing.something.*;
+```
+
+## Beispielprogramm
+
+Lass uns ein Beispiel von openprocessing.org ansehen, welches verdeutlicht,
+was man in Processing mit nur wenigen Zeilen Code machen kann.
+
+Kopiere den nachfolgenden Code in deine Processing IDE.
+
+```
+// Disclaimer: Ich habe das Porgramm nicht selbst geschriben. Diese Skizze
+// stammt aus openprocessing, allerdings soll dieses Programm zeigen, wie wenig
+// Zeilen Code notwendig sind, um etwas Cooles zu machen.
+// Abgerufen von: (https://www.openprocessing.org/sketch/559769)
+
+float theta;
+float a;
+float col;
+float num;
+
+void setup() {
+ size(600,600);
+}
+
+void draw() {
+ background(#F2F2F2);
+ translate(width/2, height/2);
+ theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6);
+
+ float num=6;
+ for (int i=0; i<num; i++) {
+ a =350;
+ rotate(TWO_PI/num);
+ branch(a);
+ }
+}
+
+void branch(float len) {
+ col=map(len, 0, 90, 150, 255);
+ fill(col, 0, 74);
+ stroke (col, 0, 74);
+ line(0, 0, 0, -len);
+ ellipse(0, -len, 3, 3);
+ len*=0.7;
+
+ if (len>30) {
+ pushMatrix();
+ translate(0, -30);
+ rotate(theta);
+ branch(len);
+ popMatrix();
+
+ pushMatrix();
+ translate(0, -30);
+ rotate(-theta);
+ branch(len);
+ popMatrix();
+ }
+}
+```
+
+Processing ist einfach zu erlernen und ist vorallem nützlich, um Multimedia-
+Inhalte (auch in 3D) zu erstellen ohne viel Code zu schreiben. Es ist so einfach
+gehalten, dass man den Code durchlesen kann und man versteht den Programmablauf
+bereits.
+
+Wenn du externe Bibliotheken, Pakete oder eigene Klassen einbindest, kann ein
+Programm, welches mit Processing geschrieben wurde, durchaus auch kompliziert
+werden.
+
+## Einige nützliche Links
+
+- [Processing Webseite](http://processing.org)
+- [Processing Sketches](http://openprocessing.org)
diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown
new file mode 100644
index 00000000..c86494ce
--- /dev/null
+++ b/de-de/pug-de.html.markdown
@@ -0,0 +1,208 @@
+---
+language: Pug
+contributors:
+ - ["Michael Warner", "https://github.com/MichaelJGW"]
+filename: lernepug-de.pug
+translators:
+ - ["denniskeller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+## Erste Schritte mit Pug
+
+Pug ist eine kleine Sprache, die zu HTML kompiliert. Sie hat eine
+saubere Syntax mit zusätzlichen Funktionen wie if Anweisungen und Schleifen.
+Sie kann auch als serverseitige Templatingsprache für Serversprachen
+wie NodeJS verwendet werden.
+
+### Die Sprache
+```pug
+
+//- Einzeilenkommentar
+
+//- Mehrzeiliger
+ Kommentar
+
+//- ---TAGS---
+//- Grundlagen
+div
+//- <div></div>
+h1
+//- <h1></h1>
+mein-benutzerdefiniertesTag
+//- <mein-benutzerdefiniertesTag></mein-benutzerdefiniertesTag>
+
+//- Geschwister
+div
+div
+//- <div></div>
+ <div></div>
+
+//- Kind
+div
+ div
+//- <div>
+ <div></div>
+ </div>
+
+//- Text
+h1 Hallo Welt
+//- <h1>Hallo Welt</h1>
+
+//- Multizeilentext
+div.
+ Hallo
+ Welt
+//- <div>
+ Hallo
+ Welt
+ </div>
+
+//- ---ATTRIBUTE---
+div(class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled)
+//- <div class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled></div>
+
+//- Kurzhand
+span.meine-klasse
+//- <span class="meine-klasse"></span>
+.meine-klasse
+//- <div class="meine-klasse"></div>
+div#meine-id
+//- <div id="meine-id"></div>
+div#meine-id.meine-klasse
+//- <div class="meine-klasse" id="meine-id"></div>
+
+
+//- ---JS---
+- const sprache = "pug";
+
+//- Multizeilen JS
+-
+ const srache = "pug";
+ const cool = true;
+
+//- JS Klassen
+- const meineKlasse = ['class1', 'class2', 'class3']
+div(class=meineKlasse)
+//- <div class="class1 class2 class3"></div>
+
+//- JS Stil
+- const meineStile = {'color':'white', 'background-color':'blue'}
+div(styles=meineStile)
+//- <div styles="{&quot;color&quot;:&quot;white&quot;,&quot;background-color&quot;:&quot;blue&quot;}"></div>
+
+//- JS Attributte
+- const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"}
+img&attributes(meineAttribute)
+//- <img src="foto.png" alt="meine Bilder">
+- let deaktiviert = false
+input(type="text" disabled=deaktiviert)
+//- <input type="text">
+- deaktiviert = true
+input(type="text" disabled=deaktiviert)
+//- <input type="text" disabled>
+
+//- JS Templating
+- const name = "Bob";
+h1 Hi #{name}
+h1= name
+//- <h1>Hi Bob</h1>
+//- <h1>Bob</h1>
+
+//- ---Schleifen---
+
+//- 'each' und 'for' machen das Selbe. Wir werden nur 'each' verwenden.
+
+each value, i in [1,2,3]
+ p=value
+//-
+ <p>1</p>
+ <p>2</p>
+ <p>3</p>
+
+each value, index in [1,2,3]
+ p=value + '-' + index
+//-
+ <p>1-0</p>
+ <p>2-1</p>
+ <p>3-2</p>
+
+each value in []
+ p=value
+//-
+
+each value in []
+ p=value
+else
+ p Keine Werte sind hier
+
+//- <p>Keine Werte sind hier</p>
+
+//- ---BEDINGUNGEN---
+
+- const zahl = 5
+if zahl < 5
+ p zahl ist kleiner als 5
+else if zahl > 5
+ p zahl ist größer als 5
+else
+ p zahl ist 5
+//- <p>zahl ist 5</p>
+
+- const bestellungsStatus = "Ausstehend";
+case bestellungsStatus
+ when "Ausstehend"
+ p.warn Deine Bestellung steht noch aus
+ when "Abgeschlossen"
+ p.success Bestellung ist abgeschlossen.
+ when -1
+ p.error Ein Fehler ist aufgetreten
+ default
+ p kein Bestellprotokoll gefunden
+//- <p class="warn">Deine Bestellung steht noch aus</p>
+
+//- --INCLUDE--
+//- File path -> "includes/nav.png"
+h1 Firmenname
+nav
+ a(href="index.html") Home
+ a(href="about.html") Über uns
+
+//- Dateipfad -> "index.png"
+html
+ body
+ include includes/nav.pug
+//-
+ <html>
+ <body>
+ <h1>Firmenname</h1>
+ <nav><a href="index.html">Home</a><a href="about.html">Über uns</a></nav>
+ </body>
+ </html>
+
+//- Importiere JS und CSS
+script
+ include scripts/index.js
+style
+ include styles/theme.css
+
+//- ---MIXIN---
+mixin basic()
+ div Hallo
++basic("Bob")
+//- <div>Hallo</div>
+
+mixin comment(name, kommentar)
+ div
+ span.comment-name= name
+ div.comment-text= kommentar
++comment("Bob", "Das ist super")
+//- <div>Hallo</div>
+
+```
+
+
+### Zusätzliche Ressourcen
+- [The Site](https://pugjs.org/)
+- [The Docs](https://pugjs.org/api/getting-started.html)
+- [Github Repo](https://github.com/pugjs/pug)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index e14603cd..23571377 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -1,5 +1,6 @@
---
language: ruby
+filename: ruby-de.rb
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
@@ -11,602 +12,677 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
+ - ["Corey Ward", "https://github.com/coreyward"]
+ - ["Jannik Siebert", "https://github.com/janniks"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
- ["Dennis Keller", "https://github.com/denniskeller"]
-filename: ruby-de.rb
+ - ["Paul Götze", "https://gitub.com/paulgoetze"]
lang: de-de
---
-# Dies ist ein Kommentar
+```ruby
+# Das ist ein Kommentar
=begin
-Dies sind multi-line
-Kommentare. Niemand benutzt
-die wirklich.
+Das ist ein mehrzeiliger Kommentar.
+Die Anfangszeile muss mit "=begin" beginnen
+und die Endzeile muss mit "=end" beginnen.
+
+Alternativ kannst du jede Zeile in einem
+mehrzeiligen Kommentar mit dem # Zeichen beginnen.
=end
-# Objekte - Alles ist ein Objekt
+# In Ruby ist (fast) alles ein Objekt.
+# Das schließt Zahlen ein...
+3.class #=> Integer
-## Zahlen sind Objekte
-```
-3.class #=> Fixnum
-3.to_s #=> "3"
-```
+# ...und Zeichenketten (Strings)...
+"Hallo".class #=> String
-### Simple Arithmetik
-```
+# ...und sogar Methoden!
+"Hallo".method(:class).class #=> Method
+
+# Simple Arithmetik
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
-2**5 #=> 32
-```
+2 ** 5 #=> 32
+5 % 3 #=> 2
-// Arithmetik ist aber eigentlich nur syntaktischer Zucker
-// um eine Methode eines Objekt aufzurufen
-```
+# Bitweise Operatoren
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Arithmetik ist aber eigentlich nur syntaktischer Zucker
+# um eine Methode eines Objekts aufzurufen
1.+(3) #=> 4
10.* 5 #=> 50
-```
+100.methods.include?(:/) #=> true
-## Special values sind Objekte
-```
-nil # Nothing to see here
-true # truth
-false # falsehood
+## Spezielle Werte sind Objekte
+nil # Equivalent zu null in anderen Sprachen
+true # Wahrheitswert
+false # Falschheitswert
nil.class #=> NilClass
true.class #=> TrueClass
false.class #=> FalseClass
-```
-## Objektvergleiche
-### Gleicheit
-```
+# Gleicheit
1 == 1 #=> true
2 == 1 #=> false
-```
-### Ungleichheit
-```
+
+# Ungleichheit
1 != 1 #=> false
2 != 1 #=> true
-```
-### Neben false selbst, nil ist ein anderer 'falsey' Wert
-```
-!nil #=> true
-!false #=> true
-!0 #=> false
-```
-### Weitere Vergleiche
-```
+
+# Neben false selbst, ist nil der einzige andere
+# zu Falsch evaluierende Wert
+
+!!nil #=> false
+!!false #=> false
+!!0 #=> true
+!!"" #=> true
+
+# Weitere Vergleiche
1 < 10 #=> true
1 > 10 #=> false
2 <= 2 #=> true
2 >= 2 #=> true
-```
+
+# Kombinierter Vergleichsoperator (gibt `1` zurück wenn das erste Argument
+# größer ist, und `-1`, wenn das zweite Argument größer ist, sonst `0`)
+1 <=> 10 #=> -1 (1 < 10)
+10 <=> 1 #=> 1 (10 > 1)
+1 <=> 1 #=> 0 (1 == 1)
+
### Logische Operatoren
-```
true && false #=> false
true || false #=> true
-!true #=> false
-```
-Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
-Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um
-verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
-liefert.
+# Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
+# Wertigkeit. Diese werden meistens zur Flusskontrolle eingesetzt, um
+# verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
+# liefert.
-#### and
-##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
+# `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
do_something() and do_something_else()
-
-#### or
-#####`log_error` wird nur ausgewertet wenn `do_something` false ist.
+# `log_error` wird nur ausgewertet wenn `do_something` false ist.
do_something() or log_error()
-## Strings sind Objekte
-```
-'I am a string'.class #=> String
-"I am a string too".class #=> String
+# String Interpolation
+placeholder = 'Ruby'
+"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungszeichen füllen."
+#=> "Ich kann in Ruby Platzhalter mit doppelten Anführungszeichen füllen."
-platzhalter = 'Ruby'
-"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen."
-```
-Einfache Anführungszeichen sollten bevorzugt werden.
-Doppelte Anführungszeichen führen interne Berechnungen durch.
+# Du kannst Strings mit `+` verbinden, nicht jedoch mit anderen Typen
+'hallo ' + 'Welt' #=> "hallo Welt"
+'Hallo ' + 3 #=> TypeError: no implicit conversion of Integer into String
+'hallo ' + 3.to_s #=> "hallo 3"
+"hallo #{3}" #=> "hallo 3"
+
+# ...oder Strings mit Operatoren kombinieren
+'hallo ' * 3 #=> "hallo hallo hallo "
+
+# ...oder Strings an andere Strings anhängen
+'hallo' << ' Welt' #=> "hallo Welt"
+
+# Du kannst Text mit einer neuen Zeile am Ende ausgeben
+puts "Ich gebe Text aus!"
+#=> Ich gebe Text aus!
+#=> nil
+
+# ...oder Text ohne einen Zeilenumbruch ausgeben
+print "Ich gebe Text aus!"
+#=> "Ich gebe Text aus!" => nil
-### Strings können verbunden werden, aber nicht mit Zahlen
-```
-'hello ' + 'world' #=> "hello world"
-'hello ' + 3 #=> TypeError: can't convert Fixnum into String
-```
-#### Zahl muss in String konvertiert werden
-```
-'hello ' + 3.to_s #=> "hello 3"
-```
-### Text ausgeben
-```
-puts "I'm printing!"
-```
# Variablen
-## Zuweisungen
-### Diese Zuweisung gibt den zugeordneten Wert zurück
-```
x = 25 #=> 25
x #=> 25
-```
-### Damit funktionieren auch mehrfache Zuweisungen
-```
+
+# Beachte, dass Zuweisungen den zugewiesenen Wert zurückgeben.
+# D.h. du kannst mehrfache Zuweisungen machen.
+
x = y = 10 #=> 10
x #=> 10
y #=> 10
-```
-## Benennung
-### Konvention ist snake_case
-```
+
+# Nutze snake_case für Variablennamen.
snake_case = true
-```
-### Benutze verständliche Variablennamen
-```
-path_to_project_root = '/good/name/'
-path = '/bad/name/'
-```
-# Symbols (sind auch Objekte)
-Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
-als integer repräsentiert werden. Sie werden häufig anstelle von Strings
-verwendet, um sinnvoll Werte zu übermitteln.
-Symbols werden mit dem Doppelpunkt gekennzeichnet.
-```
+# Nutze verständliche Variablennamen.
+path_to_project_root = '/guter/Name/'
+m = '/schlechter/Name/'
+
+
+# Symbole sind unveränderliche, wiederverwendbare Konstanten, welche intern
+# als Integer repräsentiert werden. Sie werden häufig anstelle von Strings
+# verwendet, um semantisch sinnvoll Werte zu übermitteln.
+# Symbols werden mit dem Doppelpunkt gekennzeichnet.
+
:pending.class #=> Symbol
+
status = :pending
+
status == :pending #=> true
+
status == 'pending' #=> false
+
status == :approved #=> false
-```
+
+# Strings können in Symbole konvertiert werden und umgekehrt.
+status.to_s #=> "pending"
+"argon".to_sym #=> :argon
+
# Arrays
-## Ein Array anlegen
-```
+# Das ist ein Array.
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
-```
-## Array können verschiedene Typen beinhalten
-```
+# Array können verschiedene Typen beinhalten
[1, 'hello', false] #=> [1, "hello", false]
-```
-## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf
-## [0] eigentlich die Methode [] des Array Objekts aufgerufen.
-```
-array.[] 0 #=> 1
-array.[] 12 #=> nil
-```
+## Arrays könnenindiziert werden.
-## Arrays können von vorne indiziert werden
-```
+# Von vorne...
array[0] #=> 1
+array.first #=> 1
array[12] #=> nil
-```
-## Arrays können von hinten indiziert werden
-```
+# ...oder von hinten...
array[-1] #=> 5
-```
+array.last #=> 5
-## Arrays können mit Start Index und Länge indiziert werden
-```
+# ...oder mit einem Startindex und einer Länge...
array[2, 3] #=> [3, 4, 5]
-```
-## Arrays können mit einer Range indiziert werden
-```
+# ...oder mit einem Range...
array[1..3] #=> [2, 3, 4]
-```
-## Einen Wert hinzufügen
-```
+# Du kanns ein Array umkehren.
+# Gib ein neues Array mit umgkehrten Werten zurück
+[1,2,3].reverse #=> [3,2,1]
+
+# Kehre ein Array an Ort und Stelle um, um die Variable mit den
+# umgekehrten Werten zu aktualisieren.
+a = [1,2,3]
+a.reverse! #=> a==[3,2,1] wegen des Aufrufs von reverse mit Ausrufezeichens ('!')
+
+# Wie bei der Arithmetik, ist Zugriff mit [index] nur
+# syntaktischer Zucker für den Aufruf der `[]` Methode auf dem Objekt.
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Du kannst Werte zu einem Array hinzufügen...
array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Oder so
array.push(6) #=> [1, 2, 3, 4, 5, 6]
-```
-## Testen, ob ein Element schon vorhanden ist
-```
+# ...und testen ob ein Element schon vorhanden ist
array.include?(1) #=> true
-```
-# Hashes
-Hashes sind das Hauptfeature um Key/Values zu speichern
+# Hashes sind Rubys Hauptdatenstruktur for Schlüssel/Wert Paare.
+# Hashes werden durch geschweifte Klammern gekennzeichnet.
+hash = { 'Farbe' => 'grün', 'Nummer' => 5 }
-## Ein Hash anlegen
-```
-hash = { 'color' => 'green', 'number' => 5 }
-hash.keys #=> ['color', 'number']
-```
+hash.keys #=> ['farbe', 'nummer']
-## Wert per key herausfinden
-```
-hash['color'] #=> 'green'
-hash['number'] #=> 5
-hash['nothing here'] #=> nil
-// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
-```
+# Hashes can be quickly looked up by key.
+hash['Farbe'] #=> "grün"
+hash['Nummer'] #=> 5
-## Symbols können auch keys sein
-```
-new_hash = { defcon: 3, action: true }
-new_hash.keys #=> [:defcon, :action]
-```
+# Abfragen eines nicht vorhandenen Schlüssels, gibt nil zurück.
+hash['nicht vorhanden'] #=> nil
-## Testen ob ein Key oder ein Value existiert
-```
-new_hash.has_key?(:defcon) #=> true
-new_hash.has_value?(3) #=> true
-```
+# Wenn du Symbole als Schlüssel in einem Hash verwendest, kannst du
+# eine alternative Syntax verwenden.
+hash = { :defcon => 3, :action => true }
+hash.keys #=> [:defcon, :action]
-### Tipp: Arrays und Hashes sind Enumerable
-### Und haben gemeinsame, hilfreiche Methoden wie:
-### each, map, count, and more
+hash = { defcon: 3, action: true }
+hash.keys #=> [:defcon, :action]
+
+# Testen ob ein Schlüssel oder Wert im Hash existiert
+hash.key?(:defcon) #=> true
+hash.value?(3) #=> true
+
+# Tipp: Arrays und Hashes sind Enumerables!
+# Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere.
# Kontrolstrukturen
-## if
-```
+
+# Bedingungen
if true
- 'if statement'
+ 'wenn Bedingung'
elsif false
- 'else if, optional'
+ 'sonst wenn, optional'
else
- 'else, also optional'
+ 'sonst, auch optional'
end
-```
-## for - Allerdings werden for Schleifen nicht oft vewendet.
-```
-for counter in 1..5
- puts "iteration #{counter}"
-end
-```
-## Stattdessen: "each" Methode und einen Bloch übergeben
-Ein Block ist ein Codeteil, den man einer Methode übergeben kann
-Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
-Programmiersprachen.
-```
+# Wenn eine Kontrollstruktur keinen Code-Block, sondern einen einzigen
+# Ausdruck ausführt, dann kannst du die nachgestellte if-Notation verwenden
+warnings = ['Nachname fehlt', 'Adresse zu kurz']
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) if !warnings.empty?
+
+# Formuliere die Bedingung um, wenn sich `unless` besser liest als `if`
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) unless warnings.empty?
+
+# Schleifen
+# Traditionell ist das Benutzen von `for` Schleifen in Ruby eher unüblich.
+# Stattdessen werden diese mit Hilfe von Enumerables implementiert, was mit
+# dem Aufrufen von `each` einhergeht.
(1..5).each do |counter|
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
+end
+
+# Was in etwa das selbe ist wie Folgendes (selten in Ruby zu sehen).
+for counter in 1..5
+ puts "Iteration #{counter}"
end
-```
-Die each Methode einer Range führt den Block für jedes Element der Range aus.
+# Das `do |variable| ... end` Konstrukt wird `block` genannt.
+# Blocks sind vergleichbar mit Lambdas, anonymen Funktionen
+# oder Closures in anderen Programmiersprachen.
+# Sie können als Objekte übergeben, aufgerufen oder als Methoden
+# zugewiesen werden.
-Dem Block wird ein "counter" parameter übergeben.
+# Die `each` Methode eines Ranges führt den Block einmal für jedes
+# Element des Ranges aus.
+# Dem Block wird eine counter Variable als Parameter übergeben.
-### Den Block kann man auch in geschweiften Klammern schreiben
-```
-(1..5).each { |counter| puts "iteration #{counter}" }
-```
+# Du kannst einen Block auch mit geschweiften Klammern schreiben.
+(1..5).each { |counter| puts "Iteration #{counter}" }
-### Each kann auch über den Inhalt von Datenstrukturen iterieren
-```
+# Each kann auch über den Inhalt von Datenstrukturen iterieren.
array.each do |element|
- puts "#{element} is part of the array"
+ puts "#{element} is Teil des Arrays"
end
+
hash.each do |key, value|
- puts "#{key} is #{value}"
+ puts "#{key} ist #{value}"
+end
+
+# Um auf den Laufindex zuzugreifen kannst du `each_with_index` verwenden
+# und eine index Variable definieren.
+array.each_with_index do |element, index|
+ puts "#{element} ist Nummer #{index} im Array"
end
counter = 1
while counter <= 5 do
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
counter += 1
end
-```
+#=> Iteration 1
+#=> Iteration 2
+#=> Iteration 3
+#=> Iteration 4
+#=> Iteration 5
+
+# Es gibt einige andere hilfreiche Schleifenfunktionen in Ruby.
+# Wie etwa 'map', 'reduce', 'inject' und viele andere mehr.
+# Map zum Beispiel iteriert über das Array, führt für jedes Element
+# die Anweisungen aus,
+# die im Block definiert sind und gibt ein völlig neues Array zurück.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
-## case
-```
+# Case Konstruct
grade = 'B'
case grade
when 'A'
- puts 'Way to go kiddo'
+ puts 'So wird’s gemacht'
when 'B'
- puts 'Better luck next time'
+ puts 'Viel Glück beim nächsten Mal'
when 'C'
- puts 'You can do better'
+ puts 'Das kannst du besser'
when 'D'
- puts 'Scraping through'
+ puts 'Gerade so durch'
when 'F'
- puts 'You failed!'
+ puts 'Durchgefallen!'
else
- puts 'Alternative grading system, eh?'
+ puts 'Anderes Bewertungssystem, was?'
end
-=> "Better luck next time"
-```
+#=> "Viel Glück beim nächsten Mal"
-### Case können auch ranges
-```
+# Case kann auch Ranges benutzen
grade = 82
case grade
when 90..100
- puts 'Hooray!'
+ puts 'Hurra!'
when 80...90
- puts 'OK job'
+ puts 'OK gemacht'
else
- puts 'You failed!'
+ puts 'Durchgefallen!'
end
-=> "OK job"
-```
+#=> "OK gemacht"
-# Exception handling:
-```
+# Fehlerbehandlung
begin
- # code here that might raise an exception
- raise NoMemoryError, 'You ran out of memory.'
+ # Code der einen Fehler wirft...
+ raise NoMemoryError, 'Dein Speicher ist voll.'
rescue NoMemoryError => exception_variable
- puts 'NoMemoryError was raised', exception_variable
+ puts 'NoMemoryError ist aufgetreten', exception_variable
rescue RuntimeError => other_exception_variable
- puts 'RuntimeError was raised now'
+ puts 'RuntimeError ist aufgetreten'
else
- puts 'This runs if no exceptions were thrown at all'
+ puts 'Das wird ausgeführt, wenn keine Fehler geworfen wurden'
ensure
- puts 'This code always runs no matter what'
+ puts 'Dieser Code wird immer ausgeführt, egal was vorher passiert'
end
-```
-# Funktionen
-```
+
+# Methoden
+
def double(x)
x * 2
end
-```
-## Funktionen (und Blocks)
-## geben implizit den Wert des letzten Statements zurück
-```
+
+# Methoden (und Blocks) geben implizit den Wert des letzten Anweisung zurück.
double(2) #=> 4
-```
-### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
-```
+# Klammern sind optional wenn die Anweisung dadurch nicht mehrdeutig wird.
double 3 #=> 6
+
double double 3 #=> 12
+
def sum(x, y)
x + y
end
-```
-### Methoden Parameter werden per Komma getrennt
-```
+# Die Argumente einer Methode werden durch ein Komma getrennt.
sum 3, 4 #=> 7
+
sum sum(3, 4), 5 #=> 12
-```
-## yield
-### Alle Methoden haben einen impliziten, optionalen block Parameter
-### Dieser wird mit dem Schlüsselword "yield" aufgerufen
-```
+# yield
+# Alle Methoden haben implizit einen optionalen block Parameter.
+# Dieser kann durch das Schlüsselwort 'yield' ausgeführt werden.
def surround
puts '{'
yield
puts '}'
end
-surround { puts 'hello world' }
-```
-## Einen Block kann man auch einer Methoden übergeben
-### "&" kennzeichnet die Referenz zum übergebenen Block
-```
+surround { puts 'hallo Welt' }
+
+#=> {
+#=> hallo Welt
+#=> }
+
+# Blocks können in ein 'Proc' Objekt umgewandelt werden.
+# Dieses ist eine Art Container um den Block und erlaubt ihn an eine
+# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht
+# einzubinden oder ihn andersweitig zu verändern.
+# Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form
+# eines letzten '&block' Parameters, der den Block – wenn es einen gibt –
+# entgegen nimmt und ihn in ein 'Proc' umwandelt. Die Benennung '&block' ist
+# hier nur eine Konvention; es würde genauso mit '&pineapple' funktionieren.
def guests(&block)
- block.call 'some_argument'
+ block.class #=> Proc
+ block.call(4)
end
-```
-### Eine Liste von Parametern kann man auch übergeben,
-### Diese wird in ein Array konvertiert
-### "*" kennzeichnet dies.
-```
+# Die 'call' Methode eines Proc ist ganz ähnlich zum Aufruf von 'yield', wenn
+# ein Block vorhanden ist. Die Argumente, die 'call' übergeben werden, werden
+# als Argumente and den Block weitergereicht.
+
+guests { |n| "Du hast #{n} Gäste." }
+# => "Du hast 4 Gäste."
+
+# Du kannst eine Liste von Argumenten übergeben, die dann in ein Array
+# umgewandelt werden. Dafür gibt es den splat-Operator (`*`).
def guests(*array)
array.each { |guest| puts guest }
end
-```
+
+# Destrukturierung
+
+# Ruby destrukturiert Arrays automatisch beim Zuweisen mehrerer Variablen.
+a, b, c = [1, 2, 3]
+a #=> 1
+b #=> 2
+c #=> 3
+
+# In manchen Fällen will man den splat-Operator (`*`) verwenden um ein Array in
+# eine Liste zu destrukturieren.
+ranked_competitors = ["John", "Sally", "Dingus", "Moe", "Marcy"]
+
+def best(first, second, third)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+end
+
+best *ranked_competitors.first(3) #=> Gewinner sind John, Sally and Dingus.
+
+# Der splat-Operator kann auch in Parametern verwendet werden.
+def best(first, second, third, *others)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+ puts "Es gab #{others.count} andere Teilnehmer."
+end
+
+best *ranked_competitors
+#=> Gewinner sind John, Sally und Dingus.
+#=> Es gab 2 andere Teilnehmer.
+
+# Per Konvention enden alle Methoden, die einen Wahrheitswert zurück geben, mit einem
+# Fragezeichen.
+5.even? #=> false
+5.odd? #=> true
+
+# Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode
+# per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu
+# verändern.
+# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und
+# eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt.
+company_name = "Dunder Mifflin"
+company_name.upcase #=> "DUNDER MIFFLIN"
+company_name #=> "Dunder Mifflin"
+# Diesmal verändern wir company_name direkt.
+company_name.upcase! #=> "DUNDER MIFFLIN"
+company_name #=> "DUNDER MIFFLIN"
+
# Klassen
-## Werden mit dem class Schlüsselwort definiert
-```
+
+# Du kannst eine Klasse mit dem Schlüsselwort 'class' definieren.
class Human
-```
-### Konstruktor bzw. Initializer
-```
+ # Eine Klassenvariable. Sie wird von allen Instanzen einer Klasse geteilt.
+ @@species = 'H. sapiens'
+
+ # Konstruktor bzw. Initializer
def initialize(name, age = 0)
- # Assign the argument to the "name" instance variable for the instance
+ # Weise das Argument der Instanzvariable 'name' zu.
@name = name
- # If no age given, we will fall back to the default in the arguments list.
+ # Wenn kein 'age' angegeben wurde wird der Standartwert aus der Argumentenlist verwendet.
@age = age
end
-```
-### setter Methode
-```
+ # Setter Methode
def name=(name)
@name = name
end
-```
-### getter Methode
-```
+
+ # Getter Methode
def name
@name
end
-```
-#### getter können mit der attr_accessor Methode vereinfacht definiert werden
-```
+ # Getter & Setter können auch kürzer mit der attr_accessor Methode erstellt werden.
attr_accessor :name
- # Getter/setter methods can also be created individually like this
+
+ # Getter & Setter Methoden können auch einzeln erstellt werden.
attr_reader :name
attr_writer :name
- # A class method uses self to distinguish from instance methods.
- # It can only be called on the class, not an instance.
+
+ # Eine Klassenmethode unterscheidet sich durch ein 'self' von einer
+ # Instanzmethode.
+ # Sie kann nur auf der Klasse und nicht auf einer Instanz der Klasse
+ # aufgerufen werden.
def self.say(msg)
puts msg
end
+
def species
@@species
end
end
-```
-## Eine Klasse instanziieren
-```
+# Instanziieren einer Klasse
jim = Human.new('Jim Halpert')
dwight = Human.new('Dwight K. Schrute')
-```
-## Methodenaufrufe
-```
+# Du kannst die Methoden des erstellten Objekts aufrufen.
jim.species #=> "H. sapiens"
jim.name #=> "Jim Halpert"
jim.name = "Jim Halpert II" #=> "Jim Halpert II"
jim.name #=> "Jim Halpert II"
dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
-```
-## Eine Klassenmethode aufrufen
-```
+# Aufrufen einer Klassenmethode
Human.say('Hi') #=> "Hi"
-```
-## Variable Gültigkeit
-### Variablen die mit "$" starten, gelten global
-```
-$var = "I'm a global var"
+# Der Gültigkeitsbereich einer Variablen wird durch ihren Namen definiert.
+# Variablen, die mit $ beginnen sind global gültig.
+$var = "Ich bin eine globale Variable"
defined? $var #=> "global-variable"
-```
-### Variablen die mit "@" starten, gelten für die Instanz
-```
-@var = "I'm an instance var"
+# Variablen, die mit @ beginnen, sind innerhalb einer Instanz gültig.
+@var = "Ich bin eine Instanzvariable"
defined? @var #=> "instance-variable"
-```
-### Variablen die mit "@@" starten, gelten für die Klasse
-```
-@@var = "I'm a class var"
+# Variablen, die mit @@ beginnen, sind für die Klasse gültig.
+@@var = "Ich bin eine Klassenvariable"
defined? @@var #=> "class variable"
-```
-### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten
-```
-Var = "I'm a constant"
+# Variablen, die mit einem Großbuchstaben beginnen, sind Konstanten
+Var = "Ich bin eine Konstante"
defined? Var #=> "constant"
-```
-## Class ist auch ein Objekt
-### Hat also auch Instanzvariablen
-### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt.
+# Class ist in Ruby auch ein Objekt. Deshalb kann eine Klasse Instanzvariablen
+# haben. Eine Klassenvariable wird zwischen der Klasse und all ihren
+# Ableitungen geteilt.
-### Basis Klasse
-```
+# Basis Klasse
class Human
@@foo = 0
+
def self.foo
@@foo
end
+
def self.foo=(value)
@@foo = value
end
end
-```
-### Abgeleitete Klasse
-```
+# Abgeleitete Klasse
class Worker < Human
end
-Human.foo # 0
-Worker.foo # 0
-Human.foo = 2 # 2
-Worker.foo # 2
-```
-### Eine Klasseninstanzvariable wird nicht geteilt
-```
+Human.foo #=> 0
+Worker.foo #=> 0
+
+Human.foo = 2
+Worker.foo #=> 2
+
+# Ableitungen einer Klasse haben keinen Zugriff auf eine Eine Klassen-Instanzvariable.
class Human
@bar = 0
+
def self.bar
@bar
end
+
def self.bar=(value)
@bar = value
end
end
-```
-```
+
class Doctor < Human
end
-```
-```
-Human.bar # 0
-Doctor.bar # nil
-```
-```
+
+Human.bar #=> 0
+Doctor.bar #=> nil
+
module ModuleExample
def foo
'foo'
end
end
-```
-### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden
-### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden
-```
+
+# Ein Einbinden (include) eines Moduls bindet seine Methoden an die Instanzen
+# der Klasse.
+# Ein Erweitern (extend) eines Moduls bindet seine Methoden an die Klasse
+# selbst.
class Person
include ModuleExample
end
-```
-```
+
class Book
extend ModuleExample
end
-```
-```
-Person.foo # => NoMethodError: undefined method `foo' for Person:Class
-Person.new.foo # => 'foo'
-Book.foo # => 'foo'
-Book.new.foo # => NoMethodError: undefined method `foo'
-```
-### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird
-```
- module ConcernExample
- def self.included(base)
- base.extend(ClassMethods)
- base.send(:include, InstanceMethods)
- end
- module ClassMethods
- def bar
- 'bar'
- end
- end
- module InstanceMethods
- def qux
- 'qux'
- end
+
+Person.foo #=> NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo #=> "foo"
+Book.foo #=> "foo"
+Book.new.foo #=> NoMethodError: undefined method `foo'
+
+
+# Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird.
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
end
end
- class Something
- include ConcernExample
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
end
-```
-```
-Something.bar # => 'bar'
-Something.qux # => NoMethodError: undefined method `qux'
-Something.new.bar # => NoMethodError: undefined method `bar'
-Something.new.qux # => 'qux'
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar #=> "bar"
+Something.qux #=> NoMethodError: undefined method `qux'
+Something.new.bar #=> NoMethodError: undefined method `bar'
+Something.new.qux #=> "qux"
```
-## Weiterführende Hinweise
+## Weitere Links
-//EN
+_(z.T. auf Englisch)_
-- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
-- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Offizielle Ruby Website](https://www.ruby-lang.org/de/)
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Eine Variante dieses Dokuments mit in-Browser Challenges.
+- [RubyMonk](https://rubymonk.com/) - Lerne Ruby mit einer Reihe interaktiver Tutorials.
+- [Offizielle Dokumentation](http://ruby-doc.org/core)
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
-- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
-- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide.
+- [Try Ruby](https://try.ruby-lang.org/) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown
index 08f72a35..5828b5d3 100644
--- a/de-de/swift-de.html.markdown
+++ b/de-de/swift-de.html.markdown
@@ -11,7 +11,7 @@ filename: learnswift-de.swift
lang: de-de
---
-Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und OS X Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
+Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und macOS Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown
new file mode 100644
index 00000000..8abf9a14
--- /dev/null
+++ b/de-de/vim-de.html.markdown
@@ -0,0 +1,282 @@
+---
+category: tool
+tool: vim
+lang: de-de
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["caminsha", "https://github.com/caminsha"]
+filename: LearnVim-de.txt
+---
+
+
+[Vim](http://www.vim.org)
+(Vi IMproved) ist ein Klon von vi, dem bekannten Editor für Unix. Es ist ein
+Texteditor, welcher mit Fokus auf Geschwindigkeit und Prouktivität entwickelt
+wurde.
+Vim hat viele Keybindings für ein schnelles navigieren und schnelles bearbeiten
+einer Datei.
+
+## Grundlagen, um in Vim zu navigieren
+
+```
+ vim <filename> # Öffne <filename> in Vim
+ :help <topic> # Open up built-in help docs about <topic> if any exists
+ :help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
+ # es existiert
+ :q # Schließe vim
+ :w # Speichere diese Datei
+ :wq # Speichere diese Datei und schließe vim
+ ZZ # Speichere diese Datei und schließe vim
+ :q! # Schließe vim ohne die Datei zu speichern
+ # ! *zwingt* die Ausführung von :q,
+ # daher wird die Datei nicht gespeichert.
+ ZQ # Beende vim ohne die Datei zu speichern
+ :x # Speichere die Datei und beende vim
+ # Dies ist eine kürzere Version von :wq
+
+ u # Änderung rückgängig machen
+ CTRL+R # Änderung wiederherstellen
+
+ h # Den Cursor um ein Zeichen nach links bewegen
+ j # Den Cursor eine Zeile nach unten bewegen
+ k # Den Cursor eine Zeile nach oben bewegen
+ l # Den Cursor um ein Zeichen nach rechts bewegen
+
+ Ctrl+B # Gehe eine Bildschirmanzeige zurück
+ Ctrl+F # Gehe eine Bildschirmanzeige vorwärts
+ Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts
+ Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück
+
+ # Navigieren innerhalb einer Zeile
+
+ 0 # Navigiere zum Anfang der Zeile
+ $ # Navigiere zum Ende der Zeile
+ ^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist
+
+ # Im Text suchen
+
+ /word # Hebt alle Ergebnisse nach dem Cursor hervor
+ ?word # Hebt alle Ergebnisse vor dem Cursor hervor
+ n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche
+ N # Bewegt den Cursor zum vorherigen Ergebnis der Suche
+
+ :%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen
+ :s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile
+ :%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch
+ # ein carriage return
+
+ # Zu einzelnen Zeichen springen
+
+ f<character> # Springe vorwärts und auf dem Zeichen <character>
+ t<character> # Springe vorwärts und lande vor dem Zeichen <character>
+
+ # Zum Beispiel,
+ f< # Springe vorwärts und lande auf <
+ t< # Springe vorwärts und lande vor <
+
+ # Wortweise navigieren
+
+ w # Springe um ein Wort vorwärts
+ b # Gehe ein Wort zurück
+ e # Springe zum Ende des aktuellen Wortes
+
+ # Weitere Befehle, um zu navigieren
+
+ gg # Gehe an den Start der Datei
+ G # Gehe an das Ende der Datei
+ :NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein)
+ H # Navigiere zum Start der aktuellen Bildschirmanzeige
+ M # Navigiere in die Mitte der aktuellen Bildschirmanzeige
+ L # Navigiere an das Ende der aktuellen Bildschirmanzeige
+```
+
+## Hilfsdokumente:
+
+Vim hat eine eingebaute Dokumentation, welche mit `:help <topic>` aufgerufen
+werden kann.
+Zum Beispiel öffnet `:help navigation` die Dokumentation über das Navigieren
+
+`:help` kann auch ohne ein Argument verwendet werden. Dies zeigt den Standard-
+Hilfsdialog an, welcher den Start mit vim einfacher macht.
+that aims to make getting started with vim more approachable!
+
+## Modi:
+
+Vim basiert auf dem Konzept von **modes**.
+
+- Command Mode - Vim startet in diesem Modus, hier kann man navigieren und Befehle eingeben
+- Insert Mode - Wird verwendet, um Änderungen in der Datei zu machen.
+- Visual Mode - Wird verwendet, um Text zu markieren und Operationen durchzuführen
+- Ex Mode - Wird verwendet, um im ':'-Prompt Befehle einzugeben
+
+```
+ i # Führt vim in den Insert Mode, vor der Cursorposition
+ a # Führt vim in den Insert Mode, nach der Cursorposition
+ v # Führt vim in den Visual Mode
+ : # Führt vim in den Ex Mode
+ <esc> # Führt zurück in den Command Mode, egal in welchem Mode
+ # man sich gerade befindet.
+
+ # Kopieren und einfügen von Text
+
+ y # Kopiere alles, was im Moment ausgewählt ist
+ yy # Kopiert die aktuelle Zeile
+ d # Löscht alles, was im Moment ausgewählt ist
+ dd # Löscht die aktuelle Zeile
+ p # Fügt den kopierten Text nach dem Cursor ein
+ P # Fügt den kopierten Text vor dem Cursor ein
+ x # Löscht das Zeichen unter dem Cursor
+```
+
+## Die 'Grammatik' von Vim
+
+Vim kann als Satz von Kommandos angesehen werden, welche im Format
+'Verb-Modifier-Noun' sind. Hierbei gilt:
+
+- Verb - die Aktion, du machen willst
+- Modifier - wie die Aktion gemacht wird
+- Noun - das Objekt, auf welchem die Aktion ausgeführt wird.
+
+Einige wichtige Beispiele von 'Verb', 'Modifier' und 'Nouns':
+
+```
+ # 'Verb'
+
+ d # löschen
+ c # ändern
+ y # kopieren
+ v # visuelles auswählen
+
+ # 'Modifiers'
+
+ i # innerhalb
+ a # außerhalb
+ NUM # Nummer (NUM kann irgendeine Zahl sein)
+ f # Sucht nach etwas und landet darauf
+ t # Sucht nach etwas und stoppt davor
+ / # Suche eine Zeichenfolge ab dem Cursor
+ ? # Suche eine Zeichenfolge vor dem Cursor
+
+ # 'Nouns'
+
+ w # Wort
+ s # Satz
+ p # Abschnitt
+ b # Block
+
+ # Beispielsätze resp. Kommandos
+
+ d2w # lösche zwei Wörter
+ cis # Ändere innerhalb des Satzes.
+ yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt,
+ # in welchem du bist)
+ ct< # Ändere bis zur spitzen Klammer
+ # Ändere den Text von deiner aktuellen Cursorposition bis
+ # zur nächsten spitzen Klammer
+ d$ # Lösche bis zum Ende der Zeile
+```
+
+## Einige Shortcuts und Tricks
+
+```
+ > # Rücke die Auswahl um einen Block ein
+ < # Lösche eine Einrückung der Auswahl
+ :earlier 15m # Stellt das Dokument so wieder her, wie es vor 15
+ # Minuten war
+ :later 15m # den oberen Befehl rückgängig machen
+ ddp # Vertauschen zweier aufeinanderfolgenden Zeilen
+ # Zuerst dd, dann p
+ . # Wiederhole die vorherige Aktion
+ :w !sudo tee % # Speichere die Datei als Root
+ :set syntax=c # Stelle das Syntax-Highlighting für 'C' ein
+ :sort # Alle Zeilen sortieren
+ :sort! # Alle Zeilen rückwärts sortieren
+ :sort u # Alle Zeilen sortieren und Duplikate entfernen
+ ~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes
+ u # Ausgewählten Text zu Kleinschreibung ändern
+ U # Ausgewählten Text zu Großschreibung ändern
+
+ # Text-Folding (Textfaltung)
+ zf # Erstelle eine Faltung des ausgewählten Textes
+ zo # Öffne die aktuelle Faltung
+ zc # Schließe die aktuelle Faltung
+ zR # Öffne alle Faltungen
+ zM # Schließe alle Faltungen
+```
+
+## Makros
+
+Makros sind grundsätzlich einfach aufgezeichnete Aktionen
+Wenn du mit dem Aufnehmen eines Makros beginnst, werden **alle** Aktionen und
+Kommandos, welche du braucht, aufgenommen bis die Aufnahme gestoppt wird.
+Wenn du ein Makro ausführst, werden exakt die gleichen Schritte gemacht.
+
+```
+ qa # Starte das Aufnehmen des Makros 'a'
+ q # Beende das Aufnehmen
+ @a # Führe das Makro 'a' aus
+```
+
+### Konfigurieren mit ~/.vimrc
+
+Die Datei .vimrc kann verwendet werden, um Vim beim Starten zu konfigurieren
+
+Hier ist eine Beispiel ~/.vimrc Datei:
+
+```
+" Beispiel ~/.vimrc
+
+" Erforderlich für vim, dass es iMproved ist.
+set nocompatible
+
+" Bestimme den Dateityp anhand des Namens, um ein intelligentes Einrücken etc.
+" zu ermöglichen
+filetype indent plugin on
+
+" Aktiviere das Syntax-Highlighting
+syntax on
+
+" Bessere Kommandozeilen-Vervollständigung
+set wildmenu
+
+" Verwende die Suche ohne die Berücksichtigung der Groß-/Kleinschreibung, außer
+" wenn mit Großbuchstaben gesucht wird.
+set ignorecase
+set smartcase
+
+" Wenn eine neue Zeile erstellt wird und kein Dateispezifisches Einrücken
+" aktiviert ist, behält die neue Zeile die gleiche Einrückung wie die aktuelle
+" Zeile
+set autoindent
+
+" Zeige links die Zeilennummern an
+set number
+
+" Einrückungsoptionen, ändere diese nach deinen Vorlieben
+
+" Anzahl sichtbarer Leerzeichen bei einem TAB
+set tabstop=4
+
+" Anzahl der Leerzeichen während des Bearbeitens bei einem TAB
+set softtabstop=4
+
+" Anzahl der Einrückungstiefe bei den Operationen (>> und <<)
+set shiftwidth=4
+
+" Konvertiere TABs zu Leerzeichen
+set expandtab
+
+" Enable intelligent tabbing and spacing for indentation and alignment
+" Aktiviere intelligente Tabs und Leerzeichen bei der Einrückung und Ausrichtung
+set smarttab
+```
+
+### Verweise
+
+- [Vim | Homepage](http://www.vim.org/index.php)
+- In der Shell eingeben: `vimtutor`
+- [Ein vim Tutorial und Primer, englisch](https://danielmiessler.com/study/vim/)
+- [Deutsches Arch Linux Wiki](https://wiki.archlinux.de/title/Vim)
+- [Arch Linux Wiki, englisch (dafür ausführlicher)](https://wiki.archlinux.org/index.php/Vim)
+- [What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
diff --git a/docker.html.markdown b/docker.html.markdown
index 24f85247..1dad267a 100644
--- a/docker.html.markdown
+++ b/docker.html.markdown
@@ -3,9 +3,10 @@ language: docker
filename: docker.bat
contributors:
- ["Ruslan López", "http://javapro.org/"]
+ - ["Michael Chen", "https://github.com/ML-Chen"]
---
-```
+```bat
:: download, install and run hello-world image
docker run hello-world
@@ -37,12 +38,12 @@ docker run hello-world
:: For more examples and ideas, visit:
:: https://docs.docker.com/get-started/
-:: now lets see currently running images
+:: now let's see currently running images
docker ps
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
:: NAMES
-:: lets see the images we have ran previously
+:: let's see the images we have ran previously
docker ps -a
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
@@ -54,7 +55,7 @@ docker ps -a
:: let's remove our previously generated image
docker rm happy_poincare
-:: lets test if it was really deleted
+:: let's test if it was really deleted
docker ps -a
:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
:: NAMES
@@ -89,7 +90,7 @@ docker ps -a
:: test_container
:: as you can see the name is now what we have specified
-:: retireve logs from a named container
+:: retrieve logs from a named container
docker logs test_container
:: Hello from Docker!
:: This message shows that your installation appears to be working correctly.
@@ -143,4 +144,4 @@ docker ps -a
:: nifty_goldwasser
docker rm nifty_goldwasser
-``` \ No newline at end of file
+```
diff --git a/el-gr/bash-gr.html.markdown b/el-gr/bash-gr.html.markdown
index 2989969d..239beaa4 100644
--- a/el-gr/bash-gr.html.markdown
+++ b/el-gr/bash-gr.html.markdown
@@ -8,7 +8,7 @@ lang: el-gr
---
Η λέξη «bash» είναι ένα από τα ονόματα του unix shell (τερματικός), το οποίο
-διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα Mac OS X.
+διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα macOS.
Σχεδόν όλα τα παραδείγματα που ακολουθούν μπορούν να αποτελέσουν μέρος ενός
προγράμματος τερματικού (shell script) ή να εκτελεσθούν απευθείας από τον
τερματικό.
diff --git a/el-gr/rust-gr.html.markdown b/el-gr/rust-gr.html.markdown
new file mode 100644
index 00000000..79f210ac
--- /dev/null
+++ b/el-gr/rust-gr.html.markdown
@@ -0,0 +1,339 @@
+---
+language: Rust
+contributors:
+ - ["P1start", "http://p1start.github.io/"]
+ - ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
+filename: learnrust-gr.rs
+lang: el-gr
+---
+
+_[ΣτΜ.: οι όροι "χαμηλό/υψηλό επίπεδο" αναφέρονται στην εγγύτητα μιας γλώσσας προγραμματισμού ή γενικότερα ενός
+στοιχείου στην "μηχανή", ή το υλικό του υπολογιστή. Για παράδειγμα, η φράση "η C είναι μια γλώσσα χαμηλού επιπέδου"
+αναφέρεται στο γεγονός ότι η C επιτρέπει άμεση και λεπτομερή διαχείρηση μνήμης, και πιο άμεσο έλεγχο του επεξεργαστή·
+σε καμία περίπτωση δεν σημαίνει ότι η C έχει λιγότερες δυνατότητες, και γενικότερα δεν φέρει αρνητική σημασία.]_
+
+Η Rust είναι μια γλώσσα προγραμματισμού ανεπτυγμένη από την Mozilla Research.
+Συνδυάζει τον έλεγχο της απόδοσης χαμηλού επιπέδου με διευκολύνσεις και ασφάλεια υψηλού επιπέδου.
+
+Πετυχαίνει αυτούς τους στόχους χωρίς να χρειάζεται garbage collector ή runtime, το οποίο καθιστά δυνατή τη χρήση
+βιβλιοθηκών της Rust ως αντικατάσταση της C.
+
+Η έκδοση 0.1 (η πρώτη της Rust) δημοσιεύθηκε τον Ιανουάριο του 2012, και για τα επόμενα 3 χρόνια η ανάπτυξή της
+εξελίχθηκε τόσο γρήγορα που, μέχρι πρότινος, προτείνονταν η χρήση μη-σταθερών εκδόσεων (nightly builds) αντί σταθερών
+εκδόσεων.
+
+Τις 15 Μαΐου 2015 δημοσιεύτηκε η εκδοχή 1.0 της Rust, με πλήρη εγγύηση συμβατότητας με προηγούμενες εκδοχές. Οι
+μη-σταθερές εκδόσεις συνήθως περιλαμβάνουν γρηγορότερους χρόνους μεταγλώττισης και γενικότερες βελτιώσεις όσον αφορά
+τον μεταγλωττιστή. Η μέθοδος [train release](https://www.plutora.com/blog/agile-release-train) χρησιμοποιείται, με
+συστηματικές εκδόσεις να δημοσιεύονται κάθε έξι εβδομάδες. Η beta έκδοση της Rust 1.1 δημοσιεύθηκε ταυτοχρόνως με την
+σταθερή έκδοση 1.0.
+
+Αν και η Rust είναι μια γλώσσα σχετικά χαμηλού επιπέδου, ο σχεδιασμός της περιλαμβάνει κάποιες έννοιες που συναντώνται
+συνχότερα σε γλώσσες υψηλού επιπέδου. Αυτό καθιστά την Rust γρήγορη και αποδοτική αλλά επίσης εύκολη και προσβάσιμη.
+
+
+```rust
+// Αυτό είναι ένα σχόλιο. Τα σχόλια μίας γραμμής γράφονται έτσι...
+// Και επεκτείνονται σε περισσότερες από μία γραμμές έτσι.
+
+/// Τα σχόλια documentation γράφονται έτσι, και υποστηρίζουν markdown.
+/// # Παράδειγμα
+///
+/// ```
+/// let five = 5
+/// ```
+
+//////////////////////
+// 1. Βασικές αρχές //
+//////////////////////
+
+#[allow(dead_code)]
+// Συναρτήσεις
+// `i32` είναι ο τύπος που αντιστοιχεί στους 32-bit signed ακέραιους
+fn add2(x: i32, y: i32) -> i32 {
+ // Έμεσα εννοούμενη επιστροφή του αποτελέσματος, χωρίς semicolon (;)
+ x + y
+}
+
+#[allow(unused_variables)]
+#[allow(unused_assignments)]
+#[allow(dead_code)]
+// Συνάρτηση main
+fn main() {
+ // Αριθμοί //
+
+ // Αμετάβλητη σύνδεση
+ let x: i32 = 1;
+
+ // Καταλήξεις integer/float
+ let y: i32 = 13i32;
+ let f: f64 = 1.3f64;
+
+ // Εξακρίβωση τύπου (type inference)
+ // Τις περισσότερες φορες ο μεταγλωττιστής της Rust μπορεί να εξακριβώσει τον τύπο μιας μεταβλητής, επομένως δεν
+ // χρειάζεται ο προγραμματιστής να τον δηλώνει ρητά.
+ // Σε αυτό το tutorial, οι τύποι δηλώνονται ρητά σε διάφορα σημεία, αλλά μόνο προκειμένου να είναι πιο ευανάγνωστος
+ // ο κώδικας. Ο μεταγλωττιστής μπορεί να το διαχειριστεί αυτόματα στις περισσότερες περιπτώσεις.
+ let implicit_x = 1;
+ let implicit_f = 1.3;
+
+ // Πράξεις
+ let sum = x + y + 13;
+
+ // Μη-αμετάβλητη αξία (με την έννοια ότι μπορεί να αλλάξει)
+ let mut mutable = 1;
+ mutable = 4;
+ mutable += 2;
+
+ // Αλφαριθμητικά //
+
+ // Σταθερά αλφαριθμητικά
+ let x: &str = "καλημέρα κόσμε!";
+
+ // Εκτύπωση αλφαριθμητικών
+ println!("{} {}", f, x); // 1.3 καλημέρα κόσμε!
+
+ // A `String` – a heap-allocated string
+ let s: String = "καλημέρα κόσμε".to_string();
+
+ // Ένα κομμάτι αλφαριθμητικού (string slice) – μια μη-μεταβλητή οπτική γωνία προς ένα άλλο αλφαριθμητικό
+ // Το αλφαριθμητικό μπορεί να είναι στατικό όπως τα σταθερά αλφαριθμητικά, ή να περιλαμβάνεται σε ένα άλλο,
+ // δυναμικό αντικείμενο (σε αυτή την περίπτωση τη μεταβλητή `s`)
+ let s_slice: &str = &s;
+
+ println!("{} {}", s, s_slice); // καλημέρα κόσμε καλημέρα κόσμε
+
+ // Διανύσματα/πίνακες //
+
+ // Πίνακας σταθερού μεγέθους
+ let four_ints: [i32; 4] = [1, 2, 3, 4];
+
+ // Δυναμικός πίνακας (διάνυσμα)
+ let mut vector: Vec<i32> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // Ένα κομμάτι – μια μη-μεταβλητή οπτική γωνία προς ένα διάνυσμα ή πίνακα
+ // Είναι παρόμοιο με το κομμάτι αλφαριθμητικού που είδαμε προηγουμένως
+ let slice: &[i32] = &vector;
+
+ // Μπορούμε να χρησιμοποιήσουμε το `{:?}` για να εκτυπώσουμε κάτι σε στυλ debug
+ println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ // Tuples (πλειάδες) //
+
+ // Ένα tuple είναι μια σταθερού μεγέθους σειρά από αξίες (πιθανά διαφορετικού τύπου)
+ let x: (i32, &str, f64) = (1, "καλημέρα", 3.4);
+
+ // Μπορούμε να χρησιμοποιήσουμε το `let` και ένα tuple για να δώσουμε πολλές αξίες σε πολλές μεταβλητές ταυτόχρονα
+ // (destructuring `let`)
+ let (a, b, c) = x;
+ println!("{} {} {}", a, b, c); // 1 καλημέρα 3.4
+
+ // Μπορούμε επίσης να επιλέξουμε ένα συγκεκριμένο στοιχείο από ένα tuple
+ println!("{}", x.1); // καλημέρα
+
+ //////////////
+ // 2. Τύποι //
+ //////////////
+
+ // Δομή
+ struct Point {
+ x: i32,
+ y: i32,
+ }
+
+ let origin: Point = Point { x: 0, y: 0 };
+
+ // Μια δομή με ανώνυμα πεδία, ή αλλιώς μια `δομή tuple` (`tuple struct`)
+ struct Point2(i32, i32);
+
+ let origin2 = Point2(0, 0);
+
+ // Enum, όπως στην C
+ enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+ }
+
+ let up = Direction::Up;
+
+ // Enum με πεδία
+ enum OptionalI32 {
+ AnI32(i32),
+ Nothing,
+ }
+
+ let two: OptionalI32 = OptionalI32::AnI32(2);
+ let nothing = OptionalI32::Nothing;
+
+ // Γενικότητα (genericity) //
+
+ struct Foo<T> { bar: T }
+
+ // Αυτό ορίζεται στην standard library ως `Option`
+ enum Optional<T> {
+ SomeVal(T),
+ NoVal,
+ }
+
+ // Μέθοδοι //
+
+ impl<T> Foo<T> {
+ // Οι μέθοδοι παίρνουν πάντα μια ρητή παράμετρο `self`
+ fn bar(&self) -> &T { // Δανειζόμαστε το self
+ &self.bar
+ }
+ fn bar_mut(&mut self) -> &mut T { // Δανειζόμαστε το self ως μη-αμετάβλητη αξία
+ &mut self.bar
+ }
+ fn into_bar(self) -> T { // Εδώ το self καταναλώνεται
+ self.bar
+ }
+ }
+
+ let a_foo = Foo { bar: 1 };
+ println!("{}", a_foo.bar()); // 1
+
+ // Χαρακτηρηστικά (traits) (γνωστά ως interfaces ή typeclasses σε άλλες γλώσσες) //
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ let another_foo = Foo { bar: 1 };
+ println!("{:?}", another_foo.frobnicate()); // Some(1)
+
+ //////////////////////////////////////////////////
+ // 3. Αντιστοιχίσεις Μοτίβων (Pattern Matching) //
+ //////////////////////////////////////////////////
+
+ let foo = OptionalI32::AnI32(1);
+ match foo {
+ OptionalI32::AnI32(n) => println!("Είναι ένα i32: {}", n),
+ OptionalI32::Nothing => println!("Δεν είναι τίποτα!"),
+ }
+
+ // Προχωρημένο pattern matching
+ struct FooBar { x: i32, y: OptionalI32 }
+ let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
+
+ match bar {
+ FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
+ println!("Οι αριθμοί είναι μηδέν!"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
+ println!("Οι αριθμοί είναι οι ίδιοι"),
+ FooBar { x: n, y: OptionalI32::AnI32(m) } =>
+ println!("Διαφορετικοί αριθμοί: {} {}", n, m),
+ FooBar { x: _, y: OptionalI32::Nothing } =>
+ println!("Ο δεύτερος αριθμός δεν είναι τίποτα!"),
+ }
+
+ /////////////////////
+ // 4. Έλεγχος ροής //
+ /////////////////////
+
+ // Βρόγχοι `for`
+ let array = [1, 2, 3];
+ for i in array.iter() {
+ println!("{}", i);
+ }
+
+ // Διαστήματα
+ for i in 0u32..10 {
+ print!("{} ", i);
+ }
+ println!("");
+ // Τυπώνει `0 1 2 3 4 5 6 7 8 9 `
+
+ // Βρόγχοι `if`
+ if 1 == 1 {
+ println!("Τα μαθηματικά δουλεύουν!");
+ } else {
+ println!("Ωχ όχι...");
+ }
+
+ // `if` ως έκφραση
+ let value = if true {
+ "καλό"
+ } else {
+ "κακό"
+ };
+
+ // Βρόγχοι `while`
+ while 1 == 1 {
+ println!("Το σύμπαν λειτουργεί κανονικά.");
+ // Μπορούμε να βγούμε από το βρόγχο με το `break`
+ break
+ }
+
+ // Ατέρμονος βρόχγος
+ loop {
+ println!("Καλημέρα!");
+ // Μπορούμε να βγούμε από το βρόγχο με το `break`
+ break
+ }
+
+ //////////////////////////////////
+ // 5. Ασφάλεια μνήμης & δείκτες //
+ //////////////////////////////////
+
+ // Δείκτης με ιδιοκτήτη – μόνο ένα αντικείμενο μπορεί να είναι ο "ιδιοκτήτης" αυτού του δείκτη ανά πάσα στιγμή
+ // Αυτό σημαίνει ότι μόλις το `Box` βγει εκτός πλαισίου (out of scope), ο δείκτης μπορεί να ελευθερωθεί με ασφάλεια
+ let mut mine: Box<i32> = Box::new(3);
+ *mine = 5; // Dereference του δείκτη
+ // Εδώ, το `now_its_mine` γίνεται ιδιοκτήτης του `mine`. Δηλαδή, το `mine` μετακινείται.
+ let mut now_its_mine = mine;
+ *now_its_mine += 2;
+
+ println!("{}", now_its_mine); // 7
+ // println!("{}", mine); // Αυτό παράγει λάθος κατά τη μεταγλώττιση διότι τώρα ο δείκτης ανοίκει στο `now_its_mine`
+
+ // Reference (αναφορά) – ένας αμετάβλητος δείκτης που αναφέρεται σε άλλα δεδομένα
+ // Όταν μια αναφορά δίνεται σε μια αξία, λέμε πως η αξία έχει "δανειστεί".
+ // Όταν μια αξία δανείζεται αμετάβλητα, δεν μπορεί να είναι mutated (να μεταβληθεί) ή να μετακινηθεί.
+ // Ένας "δανεισμός" παραμένει ενεργός μέχρι την τελευταία χρήση της μεταβλητής που δανείζεται.
+ let mut var = 4;
+ var = 3;
+ let ref_var: &i32 = &var;
+
+ println!("{}", var); // Αντίθετα με το `mine` προηγουμένως, η μεταβλητή `var` μπορεί ακόμα να χρησιμοποιηθεί
+ println!("{}", *ref_var);
+ // var = 5; // Αυτό παράγει λάθος κατά τη μεταγλώττιση γιατί η μεταβλητή `var` είναι δανεισμένη
+ // *ref_var = 6; // Το ίδιο εδώ, γιατί η `ref_var` αποτελεί αμετάβλητη αναφορά
+ ref_var; // Εντολή no-op (τίποτα δεν εκτελείται από τον επεξεργαστή), η οποία όμως μετράει ως χρήση και κρατά τον
+ // "δανεισμό" ενεργό
+ var = 2; // Η `ref_var` δεν χρησιμοποιείται από εδώ και στο εξής, άρα ο "δανεισμός" τελειώνει
+
+ // Μεταβλητή αναφορά
+ // Όσο μια αξία είναι μεταβλητά δανεισμένη, παραμένει τελείως απροσβάσιμη.
+ let mut var2 = 4;
+ let ref_var2: &mut i32 = &mut var2;
+ *ref_var2 += 2; // Ο αστερίσκος (*) χρησιμοποιείται ως δείκτης προς την μεταβλητά δανεισμένη `var2`
+
+ println!("{}", *ref_var2); // 6 , // Αν είχαμε `var2` εδώ θα προκαλούνταν λάθος μεταγλώττισης.
+ // O τύπος της `ref_var2` είναι &mut i32, άρα αποθηκεύει μια αναφορά προς μια αξία i32, όχι την αξία την ίδια.
+ // var2 = 2; // Λάθος μεταγλώττισης, γιατί η `var2` είναι δανεισμένη.
+ ref_var2; // Εντολή no-op (τίποτα δεν εκτελείται από τον επεξεργαστή), η οποία όμως μετράει ως χρήση και κρατά τον
+ // "δανεισμό" ενεργό
+}
+```
+
+## Μάθετε περισσότερα
+
+Υπάρχουν πολλά ακόμα πράγματα να μάθει κανείς· αυτά είναι μόνο τα βασικά της Rust, που επιτρέπουν να καταλάβουμε το
+βασικό τρόπο λειτουργίας της. Για να μάθετε περισσότερα για τη Rust, διαβάστε το [The Rust Programming
+Language](http://doc.rust-lang.org/book/index.html) και επισκεφθείτε το subreddit [/r/rust](http://reddit.com/r/rust).
+Οι άνθρωποι πίσω από το κανάλι #rust στο irc.mozilla.org είναι επίσης πάντα πρόθυμοι να βοηθήσουν τους αρχάριους.
+
+Μπορείτε επίσης να παίξετε με τη Rust χρησιμοποιώντας τους εξής online μεταγλωττιστές:
+
+- [Rust playpen](http://play.rust-lang.org)
+- [Rust website](http://rust-lang.org)
diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown
new file mode 100644
index 00000000..b11b5c33
--- /dev/null
+++ b/el-gr/vim-gr.html.markdown
@@ -0,0 +1,267 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+filename: LearnVim-gr.txt
+lang: el-gr
+---
+
+
+[Vim](http://www.vim.org)
+To (Vi IMproved) είναι ένας κλώνος του δημοφιλούς vi editor για Unix.
+Είναι ένας text editor σχεδιασμένος για ταχύτητα και αυξημένη παραγωγικότητα,
+και υπάρχει σχεδόν σε όλα τα Unix-based συστήματα. Έχει διάφορα keybindings
+(συντομεύσεις πλήκτρων) για να πλοηγούμαστε γρήγορα σε συγκεκριμένα σημεία ενός αρχείου,
+καθώς και για γρήγορη επεξεργασία.
+
+## Τα βασικά της πλοήγησης στον Vim
+
+```
+ vim <filename> # Άνοιξε το <filename> στον vim
+ :help <topic> # Άνοιξε το built-in βοήθημα για το <topic> αν υπάρχει
+ :q # Βγες από τον vim
+ :w # Αποθήκευσε το τρέχον αρχείο
+ :wq # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ ZZ # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ :q! # Βγες χωρίς αποθήκευση
+ # ! *αναγκάζει* το :q να εκτελεστεί, γι αυτό βγαίνει χωρίς saving
+ :x # Ίδιο με το wq αλλά πιο σύντομο
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # Μετακινήσου κατά ένα χαρακτήρα αριστερά
+ j # Μετακινήσου μια γραμμή κάτω
+ k # Μετακινήσου μια γραμμή πάνω
+ l # Μετακινήσου μια γραμμή δεξιά
+
+ Ctrl+B # Πήγαινε μία οθόνη πίσω
+ Ctrl+F # Πήγαινε μία οθόνη μπροστά
+ Ctrl+U # Πήγαινε μισή οθόνη πίσω
+ Ctrl+D # Πήγαινε μισή οθόνη μπροστά
+
+ # Μετακινήσεις στην ίδια γραμμή
+
+ 0 # Πήγαινε στην αρχή της γραμμής
+ $ # Πήγαινε στο τέλος της γραμμής
+ ^ # Πήγαινε στον πρώτο μη κενό χαρακτήρα της γραμμής
+
+ # Αναζήτηση στο κείμενο
+
+ /word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης μετά τον cursor
+ ?word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης πριν τον cursor
+ n # Μετακινεί τον cursor στην επόμενη εμφάνιση της λέξης
+ N # Μετακινεί τον cursor στην προηγούμενη εμφάνιση της λέξης
+
+ :%s/foo/bar/g # άλλαξε το 'foo' σε 'bar' σε κάθε γραμμή του αρχείου
+ :s/foo/bar/g # άλλαξε το 'foo' σε 'bar' στην τρέχουσα γραμμή
+
+ # Άλματα σε χαρακτήρες
+
+ f<character> # Άλμα μπροστά και προσγείωση στο επόμενο <character>
+ t<character> # Άλμα μπροστά και προσγείωση αμέσως πριν το προηγούμενο <character>
+
+ # Για παράδειγμα,
+ f< # Άλμα μπροστά και προσγείωση σε <
+ t< # Άλμα μπροστά και προσγείωση αμέσως πριν <
+
+ # Μετακινήσεις κατά λέξεις
+
+ w # Πήγαινε μια λέξη μπροστά
+ b # Πήγαινε μια λέξη πίσω
+ e # Πήγαινε στο τέλος της λέξης στην οποία είσαι
+
+ # Άλλοι χαρακτήρες για να τριγυρνάμε
+
+ gg # Πήγαινε στην αρχή του αρχείου
+ G # Πήγαινε στο τέλος του αρχείου
+ :NUM # Πήγαινε στη γραμμή με αριθμό NUM (οποιοσδήποτε αριθμός)
+ H # Πήγαινε στην κορυφή της σελίδας
+ M # Πήγαινε στην μέση της σελίδας
+ L # Πήγαινε στο κάτω άκρο της σελίδας
+```
+
+## Help docs:
+Το Vim έχει built-in help documentation που μπορείς να δεις με `:help <topic>`.
+Για παράδειγμα το `:help navigation` θα σου εμφανίσει documentation σχετικό με
+το πως να πλοηγείσαι στο αρχείο!
+
+To `:help` μπορεί να χρησιμοποιηθεί και χωρίς option. Αυτό θα εμφανίσει το default
+help dialog που σκοπεύει να κάνει το vim πιο προσιτό σε αρχάριους!
+
+## Modes:
+
+O Vim στηρίζεται στο concept των **modes**.
+
+- Command Mode - ο vim εκκινεί σε αυτό mode, χρησιμοποιείται για πλοήγηση και εντολές
+- Insert Mode - χρησιμοποιείται για να κάνουμε αλλαγές στα αρχεία
+- Visual Mode - χρησιμοποιείται για να υπογραμμίζουμε κείμενα και να κάνουμε διάφορα σε αυτά
+- Ex Mode - χρησιμοποιείται για να πάμε στο κάτω μέρος με το ':' που δίνουμε εντολές
+
+```
+ i # Βάζει το vim σε insert mode, πριν τη θέση cursor
+ a # Βάζει το vim σε insert mode, μετά τη θέση cursor
+ v # βάζει τον vim σε visual mode
+ : # Βάζει τον vim σε ex mode
+ <esc> # φεύγει από όποιο mode είμαστε και πάει σε command mode
+
+ # Αντιγραφή-Επικόληση κειμένου
+
+ y # Yank (κάνε copy) ό,τι είναι επιλεγμένο
+ yy # Yank την γραμμή στην οποία είσαι
+ d # διάγραψε ό,τι είναι επιλεγμένο
+ dd # Διάγραψε τη γραμμή στην οποία είσαι
+ p # Κάνε Paste το αντεγραμένο κείμενο μετά την θέση του cursor
+ P # Κάνε Paste το αντεγραμένο κείμενο πριν την θέση του cursor
+ x # Διάγραψε τον χαρακτήρα που είναι κάτω από τον cursor
+```
+
+## Η 'γραμματική' του Vim
+
+Μπορείς να σκεφτείς τον Vim ως ένα σύνολο εντολών
+σε μορφή 'Verb-Modifier-Noun', όπου
+
+- Verb - η ενέργεια που θες να κάνεις
+- Modifier - πώς κάνεις την ενέργεια
+- Noun - το αντικείμενο που δέχεται την ενέργεια
+
+Μερικά παραδείγματα ''Ρημάτων', 'Modifiers' και 'Ουσιαστικών':
+
+```
+ # 'Ρήματα'
+
+ d # Διάγραψε
+ c # Άλλαξε
+ y # Yank (αντίγραψε)
+ v # Επίλεξε οπτικά
+
+ # 'Modifiers'
+
+ i # Μέσα
+ a # Γύρω
+ NUM # Αριθμός (NUM = οποιοσδήποτε αριθμός)
+ f # Ψάξε κάτι και πήγαινε εκεί που βρίσκεται
+ t # Ψάξε κάτι και πήγαινε πριν από εκεί που βρίσκεται
+ / # Βρες κάποιο string μετά από τον cursor
+ ? # Βρες κάποιο string πριν τον cursor
+
+ # 'Ουσιαστικά'
+
+ w # Λέξη
+ s # Πρόταση
+ p # Παράγραφος
+ b # Block
+
+ # Δείγματα 'προτάσεων' ή εντολών
+
+ d2w # Διάγραψε 2 λέξεις
+ cis # Άλλαξε μέσα στην πρώταση
+ yip # Αντίγραψε την παράγραφο στην οποία βρίσκεσαι
+ ct< # Άλλαξε σε <
+ # Άλλαξε το κείμενο από το οποίο είσαι πριν το επόμενο bracketChange the text from where you are to the next open bracket
+ d$ # Διάγραψε μέχρι το τέλος της γραμμής
+```
+
+## Μερικά shortcuts και κόλπα
+
+ <!--TODO: Βάλτε κι άλλα!-->
+```
+ > # Στοίχισε προς τα δεξιά την επιλογή σου κατά ένα block
+ < # Στοίχισε προς τα αριστερά την επιλογή σου κατά ένα block
+ :earlier 15m # Κάνε το αρχείο όπως ήταν πριν 15 λεπτά
+ :later 15m # Ακύρωση για την παραπάνω εντολή
+ ddp # Αντάλλαξε τις θέσεις διαδοχικών γραμμών
+ . # Επανάλαβε την προηγούμενη ενέργεια
+ :w !sudo tee % # Σώσε το τρέχον αρχείο ως root
+ :set syntax=c # Κάνε syntax highlighting για τη γλώσσα c
+ :sort # Ταξινόμησε όλες τις γραμμές
+ :sort! # Ταξινόμησε ανάποδα όλες τις γραμμές (αύξουσα σειρά)
+ :sort u # Ταξινόμησε όλες τις γραμμές και διάγραψε τις διπλές γραμμές
+ ~ # Άλλαξε τα κεφαλαία σε μικρά στο επιλεγμένο κείμενο
+ u # Το επιλεγμένο κείμενο να γίνει πεζά γράμματα
+ U # Το επιλεγμένο κείμενο να γίνει κεφαλαία γράμματα
+
+ # Fold text
+ zf # Διπλώνει (συμπιέζει τις γραμμές σε μία) το επιλεγμένο κείμενο
+ zo # Ξεδιπλώνει το επιλεγμένο fold
+ zc # Κλείνει το επιλεγμένο fold
+ zR # Ανοίγει όλα τα folds
+ zM # Κλείνει όλα τα folds
+```
+
+## Macros
+
+Τα macros βασικά είναι καταγραφή ενεργειών.
+Όταν ξεικάς να καταγράφεις ένα macro καταγράφονται **όλες** οι ενέργεις και οι
+εντολές που χρησιμοποιείς, μέχρι να σταματήσεις την καταγραφή. Όταν καλείς ένα macro,
+εκτελείται πάλι η ίδια σειρά από ενέργειες και εντολές στο επιλεγμένο κείμενο.
+
+```
+ qa # Ξεκίνα να καταγράφεις ένα macro που θα ονομαστεί 'a'
+ q # Σταμάτα την καταγραφή
+ @a # Τρέξε το macro
+```
+
+### Configuring ~/.vimrc
+
+Το αρχείο .vimrc μπορεί να χρησιμοποιηθεί για να κάνεις configure το Vim στο startup.
+
+Εδώ βλέπουμε δείγμα ενός ~/.vimrc file:
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" Determines filetype from name to allow intelligent auto-indenting, etc.
+filetype indent plugin on
+
+" Enable syntax highlighting
+syntax on
+
+" Better command-line completion
+set wildmenu
+
+" Use case insensitive search except when using capital letters
+set ignorecase
+set smartcase
+
+" When opening a new line and no file-specific indenting is enabled,
+" keep same indent as the line you're currently on
+set autoindent
+
+" Display line numbers on the left
+set number
+
+" Indentation options, change according to personal preference
+
+" Number of visual spaces per TAB
+set tabstop=4
+
+" Number of spaces in TAB when editing
+set softtabstop=4
+
+" Number of spaces indented when reindent operations (>> and <<) are used
+set shiftwidth=4
+
+" Convert TABs to spaces
+set expandtab
+
+" Enable intelligent tabbing and spacing for indentation and alignment
+set smarttab
+```
+
+### Αναφορές
+
+[Vim | Home](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 0b717ca6..9f96be49 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -33,7 +33,7 @@ and many more features.
0x1F # integer
3.0 # float
-# Atoms, that are literals, a constant with name. They start with `:`.
+# Atoms are constants whose values are their own name. They start with `:`.
:hello # atom
# Tuples that are stored contiguously in memory.
@@ -439,7 +439,7 @@ self() #=> #PID<0.27.0>
# Create an agent with `Agent.start_link`, passing in a function
# The initial state of the agent will be whatever that function returns
-{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
+{:ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
# `Agent.get` takes an agent name and a `fn` that gets passed the current state
# Whatever that `fn` returns is what you'll get back
@@ -457,3 +457,4 @@ Agent.update(my_agent, fn colors -> ["blue" | colors] end)
* [Elixir Cheat Sheet](https://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
* ["Learn You Some Erlang for Great Good!"](https://learnyousomeerlang.com/) by Fred Hebert
* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong
+* [Introduction to Elixir](https://learn-elixir.com/)
diff --git a/es-es/bash-es.html.markdown b/es-es/bash-es.html.markdown
index fb89b2a0..27070e79 100644
--- a/es-es/bash-es.html.markdown
+++ b/es-es/bash-es.html.markdown
@@ -18,7 +18,7 @@ Tutorial de Shell en español.
Bash es el nombre del shell de unix, el cual también es distribuido como
el shell del sistema operativo GNU. También es el shell
-por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden
+por defecto de Linux y macOS. Casi todos los ejemplos abajo pueden
ser parte de un script shell o ser ejecutados directamente en la terminal.
[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown
index 2c3762d5..9db2c802 100644
--- a/es-es/c++-es.html.markdown
+++ b/es-es/c++-es.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Connor Waters", "http://github.com/connorwaters"]
translators:
- ["Gerson Lázaro", "https://gersonlazaro.com"]
+ - ["Diego Ramirez", "https://DiddiLeija.github.io"]
lang: es-es
---
@@ -101,8 +102,8 @@ void print(int myInt)
int main()
{
- print("Hello"); // Resolves to void print(const char*)
- print(15); // Resolves to void print(int)
+ print("Hello"); // Corresponde a void print(const char*)
+ print(15); // Corresponde a void print(int)
}
////////////////////////////////////
@@ -114,7 +115,7 @@ int main()
void doSomethingWithInts(int a = 1, int b = 4)
{
- // Hacer algo con los enteros aqui
+ // Hacer algo con los enteros aquí
}
int main()
@@ -134,7 +135,7 @@ void invalidDeclaration(int a = 1, int b) // Error!
// Espacios de nombre
/////////////////////
-// Espacios de nombres proporcionan ámbitos separados para variable, función y
+// Los espacios de nombres proporcionan ámbitos separados para variable, función y
// otras declaraciones.
// Los espacios de nombres se pueden anidar.
@@ -184,7 +185,7 @@ int main()
#include <iostream> // Incluir para el flujo de entrada/salida
-using namespace std; // Los streams estan en std namespace (libreria estandar)
+using namespace std; // Los streams estan en el espacio de nombre std (libreria estandar)
int main()
{
@@ -208,7 +209,7 @@ int main()
// Las cadenas en C++ son objetos y tienen muchas funciones
#include <string>
-using namespace std; // Strings también estan en namespace std
+using namespace std; // Las cadenas también estan en el nombre de espacio std
string myString = "Hola";
string myOtherString = " Mundo";
@@ -252,7 +253,7 @@ fooRef = bar;
const string& barRef = bar; // Crea una referencia constante a bar.
// Como en C, los valores constantes (y punteros y referencias) no pueden ser
// modificados.
-barRef += ". Hola!"; // Error, referencia constante no puede ser modificada.
+barRef += ". Hola!"; // Error, una referencia constante no puede ser modificada.
// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un
// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código:
@@ -264,7 +265,7 @@ string retVal = tempObjectFun();
// - Una nueva cadena se construye con el objeto devuelto como argumento al
// constructor
// - El objeto devuelto es destruido
-// El objeto devuelto se llama objeto temporal. Objetos temporales son
+// El objeto devuelto se llama objeto temporal. Los objetos temporales son
// creados cada vez que una función devuelve un objeto, y es destruido en el
// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la
// norma dice, pero los compiladores están autorizados a cambiar este
@@ -295,7 +296,7 @@ void someFun(string&& s) { ... } // Referencia a objeto temporal
string foo;
someFun(foo); // Llama la función con referencia regular
-someFun(tempObjectFun()); // Llama la versión con referencia temporal
+someFun(tempObjectFun()); // Llama la función con referencia temporal
// Por ejemplo, puedes ver estas dos versiones de constructores para
// std::basic_string:
@@ -305,7 +306,7 @@ basic_string(basic_string&& other);
// La idea es que si estamos construyendo una nueva cadena de un objeto temporal
// (que va a ser destruido pronto de todos modos), podemos tener un constructor
// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este
-// Concepto denominado "movimiento semántico".
+// concepto denominado "movimiento semántico".
////////////////////////////////////////////
// Clases y programación orientada a objetos
@@ -322,9 +323,7 @@ class Dog {
int weight;
// Todos los miembros siguientes de este son públicos
-// Hasta que se encuentre "private" o "protected".
-// All members following this are public
-// until "private:" or "protected:" is found.
+// hasta que se encuentre "private" o "protected".
public:
// Constructor por defecto
@@ -339,8 +338,8 @@ public:
void setWeight(int dogsWeight);
// Funciones que no modifican el estado del objeto
- // Deben marcarse como const.
- // Esto le permite llamarlas si se envia una referencia constante al objeto.
+ // deben marcarse como const.
+ // Esto le permite llamarlas si se envía una referencia constante al objeto.
// También tenga en cuenta que las funciones deben ser declaradas
// explícitamente como _virtual_ para que sea reemplazada en las clases
// derivadas.
@@ -357,8 +356,8 @@ public:
// Esto permite paradigmas potentes como RAII
// (mira abajo)
// El destructor debe ser virtual si una clase es dervada desde el;
- // Si no es virtual, entonces la clase derivada destructor
- // No será llamada si el objeto se destruye a través de una referencia de
+ // Si no es virtual, entonces la clase destructora derivada
+ // no será llamada si el objeto se destruye a través de una referencia de
// la clase base o puntero.
virtual ~Dog();
@@ -373,7 +372,7 @@ Dog::Dog()
}
// Objetos (tales como cadenas) deben ser pasados por referencia
-// Si los estas modificando o referencia constante en caso contrario.
+// si los estás modificando, o referencia constante en caso contrario.
void Dog::setName(const std::string& dogsName)
{
name = dogsName;
@@ -413,9 +412,9 @@ class OwnedDog : public Dog {
// Reemplaza el comportamiento de la función de impresión
// de todos los OwnedDogs. Mira
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
- // Para una introducción más general si no está familiarizado con el
+ // para una introducción más general si no está familiarizado con el
// polimorfismo de subtipo.
- // La palabra clave override es opcional, pero asegura que estás
+ // La palabra clave override es opcional, pero asegúrate de que estás
// reemplazando el método de una clase base.
void print() const override;
@@ -460,8 +459,8 @@ public:
// pero inicializa el punto al valor por defecto (0, 0)
Point() { };
- // The following syntax is known as an initialization list
- // and is the proper way to initialize class member values
+ // La siguiente sintaxis se conoce como lista de inicialización
+ // y es la forma correcta de inicializar los valores de los miembros de la clase
Point (double a, double b) :
x(a),
y(b)
@@ -474,7 +473,7 @@ public:
Point& operator+=(const Point& rhs);
// También tendría sentido añadir los operadores - y -=,
-    // Pero vamos a omitirlos por razones de brevedad.
+    // pero vamos a omitirlos por razones de brevedad.
};
Point Point::operator+(const Point& rhs) const
@@ -496,7 +495,7 @@ int main () {
// Llama al operador + de Point
// Point llama la función + con right como parámetro
Point result = up + right;
- // Prints "Result is upright (1,1)"
+ // Imprime "Result is upright (1,1)"
cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
return 0;
}
@@ -525,7 +524,7 @@ public:
// plantilla con parámetros sustituidos, por lo que la definición completa
// de la clase debe estar presente en cada invocación.
// Es por esto que usted verá clases de plantilla definidas
-// Enteramente en archivos de cabecera.
+// enteramente en archivos de cabecera.
//Para crear una instancia de una clase de plantilla en la pila:
Box<int> intBox;
@@ -544,7 +543,7 @@ boxOfBox.insert(intBox);
// A veces verás
// template<typename T>
-// en su lugar. La palabra clave "class" y las palabras clave "typename" son
+// en su lugar. La palabra clave "class" y la palabra clave "typename" son
// mayormente intercambiables en este caso. Para la explicación completa, mira
// http://en.wikipedia.org/wiki/Typename
// (sí, esa palabra clave tiene su propia página de Wikipedia).
@@ -568,7 +567,7 @@ Dog fluffy;
fluffy.setName("Fluffy")
barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces.
-Los parámetros de la plantilla no tienen que ser las clases:
+// Los parámetros de la plantilla no tienen que ser las clases:
template<int Y>
void printMessage() {
cout << "Aprende C++ en " << Y << " minutos!" << endl;
@@ -604,7 +603,7 @@ printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!"
//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser
// capturados por los siguientes manejadores _catch_.
try {
- // No asignar excepciones en el heap usando _new_.
+ // No asigne excepciones en el heap usando _new_.
throw std::runtime_error("Ocurrió un problema");
}
@@ -629,10 +628,10 @@ catch (...)
// (Adquisición de recursos es inicialización).
// A menudo se considera el paradigma más poderoso en C++
// Y el concepto es simple: un constructor de un objeto
-// Adquiere recursos de ese objeto y el destructor les libera.
+// adquiere recursos de ese objeto y el destructor les libera.
// Para entender cómo esto es útil,
-// Considere una función que utiliza un identificador de archivo C:
+// considere una función que utiliza un identificador de archivo C:
void doSomethingWithAFile(const char* filename)
{
// Para empezar, asuma que nada puede fallar.
@@ -691,11 +690,11 @@ bool doSomethingWithAFile(const char* filename)
failure:
fclose(fh);
- return false; // Propagate el error
+ return false; // Propaga el error
}
// Si las funciones indican errores mediante excepciones,
-// Las cosas son un poco más claras, pero pueden optimizarse mas.
+// las cosas son un poco más claras, pero pueden optimizarse más.
void doSomethingWithAFile(const char* filename)
{
FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura
@@ -732,9 +731,9 @@ void doSomethingWithAFile(const std::string& filename)
// Esto tiene ventajas _enormes_:
// 1. No importa lo que pase,
-// El recurso (en este caso el manejador de archivo) será limpiado.
+// el recurso (en este caso el manejador de archivo) será limpiado.
// Una vez que escribes el destructor correctamente,
-// Es _imposible_ olvidar cerrar el identificador y permitir
+// es _imposible_ olvidar cerrar el identificador y permitir
// fugas del recurso.
// 2. Tenga en cuenta que el código es mucho más limpio.
// El destructor se encarga de cerrar el archivo detrás de cámaras
diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown
index 9f1656bb..faa3dead 100644
--- a/es-es/matlab-es.html.markdown
+++ b/es-es/matlab-es.html.markdown
@@ -31,7 +31,7 @@ esto
% Dos símbolos de porcentaje denotan el comienzo de una nueva sección de código.
% Secciones de código individuales pueden ser ejecutadas moviendo el cursor hacia la sección,
% seguida por un clic en el botón de “Ejecutar Sección”
-% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (OS X)
+% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (macOS)
%% Este es el comienzo de una sección de código
% Una forma de usar las secciones es separar un código de inicio costoso que no cambia, como cargar datos
diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown
index 26cd14d9..28733cfb 100644
--- a/es-es/objective-c-es.html.markdown
+++ b/es-es/objective-c-es.html.markdown
@@ -9,7 +9,7 @@ translators:
lang: es-es
filename: LearnObjectiveC-es.m
---
-Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
+Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos macOS y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch.
Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown
index 644182ff..76e9b6e6 100644
--- a/es-es/perl-es.html.markdown
+++ b/es-es/perl-es.html.markdown
@@ -11,9 +11,9 @@ translators:
lang: es-es
---
-Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
+Perl es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
-Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
+Perl corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
```perl
# Comentarios de una sola línea con un carácter hash
@@ -31,7 +31,7 @@ Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores cen
my $animal = "camello";
my $respuesta = 42;
-# Los valores escalares pueden ser cadenas de caracteres, números enteros o
+# Los valores escalares pueden ser cadenas de caracteres, números enteros o
# de punto flotante; Perl automáticamente los convertirá como sea requerido
## Arreglos
@@ -52,7 +52,7 @@ my %color_fruta = (
# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata)
-# Los tipos de datos más complejos se pueden construir utilizando
+# Los tipos de datos más complejos se pueden construir utilizando
# referencias, las cuales le permiten construir listas y hashes dentro
# de listas y hashes
@@ -61,7 +61,7 @@ my %color_fruta = (
# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
if ( $var ) {
...;
-} elsif ( $var eq 'bar' ) {
+} elsif ( $var eq 'bar' ) {
...;
} else {
...;
@@ -98,7 +98,7 @@ foreach (@array) {
#### Expresiones regulares
-# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
+# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
# Sin embargo, resumiendo:
@@ -113,7 +113,7 @@ $a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en
#### Archivos y E/S
-# Puede abrir un archivo para obtener datos o escribirlos utilizando la
+# Puede abrir un archivo para obtener datos o escribirlos utilizando la
# función "open()"
open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!";
@@ -122,7 +122,7 @@ open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!";
# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>".
# En contexto escalar, leer una sola línea desde el gestor de archivo, y
-# en contexto de lista, leer el archivo completo en donde asigna
+# en contexto de lista, leer el archivo completo en donde asigna
# cada línea a un elemento de la lista
my $linea = <$entrada>;
diff --git a/es-es/perl6-es.html.markdown b/es-es/raku-es.html.markdown
index bf3ae65e..e916d0fd 100644
--- a/es-es/perl6-es.html.markdown
+++ b/es-es/raku-es.html.markdown
@@ -1,8 +1,8 @@
---
name: perl6
category: language
-language: perl6
-filename: perl6-es.p6
+language: Raku
+filename: learnraku-es.raku
contributors:
- ["vendethiel", "http://github.com/vendethiel"]
- ["Samantha McVey", "https://cry.nu"]
@@ -11,10 +11,10 @@ translators:
lang: es-es
---
-Perl 6 es un lenguaje de programación altamente capaz y con características
+Raku es un lenguaje de programación altamente capaz y con características
abundantes para hacerlo el lenguage ideal por los próximos 100 años.
-El compilador primario de Perl 6 se llama [Rakudo](http://rakudo.org), el cual
+El compilador primario de Raku se llama [Rakudo](http://rakudo.org), el cual
se ejecuta en JVM y en [MoarVM](http://moarvm.com).
Meta-nota: dos signos de números (##) son usados para indicar párrafos,
@@ -26,7 +26,7 @@ mientras que un solo signo de número (#) indica notas.
# Un comentario de una sola línea comienza con un signo de número
#`(
- Comentarios multilíneas usan #` y signos de encerradura tales
+ Comentarios multilíneas usan #` y signos de encerradura tales
como (), [], {}, 「」, etc.
)
```
@@ -34,28 +34,28 @@ mientras que un solo signo de número (#) indica notas.
## Variables
```perl6
-## En Perl 6, se declara una variable lexical usando `my`
+## En Raku, se declara una variable lexical usando `my`
my $variable;
-## Perl 6 tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
+## Raku tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
```
### Escalares
```perl6
-# Un escalar representa un solo valor. Variables escalares comienzan
+# Un escalar representa un solo valor. Variables escalares comienzan
# con un `$`
my $str = 'Cadena';
-# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
+# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
# luego):
my $str2 = "Cadena";
## Los nombres de variables pueden contener pero no terminar con comillas
-## simples y guiones. Sin embargo, pueden contener
+## simples y guiones. Sin embargo, pueden contener
## (y terminar con) guiones bajos (_):
my $nombre'de-variable_ = 5; # Esto funciona!
-my $booleano = True; # `True` y `False` son valores booleanos en Perl 6.
+my $booleano = True; # `True` y `False` son valores booleanos en Raku.
my $inverso = !$booleano; # Puedes invertir un booleano con el operador prefijo `!`
my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
# convierte su operador en un Bool
@@ -70,7 +70,7 @@ my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
my @array = 'a', 'b', 'c';
# equivalente a:
my @letras = <a b c>; # array de palabras, delimitado por espacios.
- # Similar al qw de perl5, o el %w de Ruby.
+ # Similar al qw de perl, o el %w de Ruby.
my @array = 1, 2, 3;
say @array[2]; # Los índices de un array empiezan por el 0 -- Este es
@@ -83,7 +83,7 @@ say "Interpola todos los elementos de un array usando [] : @array[]";
@array[0, 1] = 5, 6; # Asigna varios valores
my @llaves = 0, 2;
-@array[@llaves] = @letras; # Asignación usando un array que contiene valores
+@array[@llaves] = @letras; # Asignación usando un array que contiene valores
# índices
say @array; #=> a 6 b
```
@@ -93,19 +93,19 @@ say @array; #=> a 6 b
```perl6
## Un hash contiene parejas de llaves y valores.
## Puedes construir un objeto Pair usando la sintaxis `LLave => Valor`.
-## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
+## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
## sin ningún orden.
## Ten en cuenta que las llaves son "aplanadas" en contexto de hash, y
## cualquier llave duplicada es deduplicada.
my %hash = 1 => 2,
3 => 4;
-my %hash = foo => "bar", # las llaves reciben sus comillas
+my %hash = foo => "bar", # las llaves reciben sus comillas
# automáticamente.
"some other" => "value", # las comas colgantes estań bien.
;
## Aunque los hashes son almacenados internamente de forma diferente a los
-## arrays, Perl 6 te permite crear un hash usando un array
+## arrays, Raku te permite crear un hash usando un array
## con un número par de elementos fácilmente.
my %hash = <llave1 valor1 llave2 valor2>;
@@ -122,7 +122,7 @@ my %hash = :w(1), # equivalente a `w => 1`
say %hash{'llave1'}; # Puedes usar {} para obtener el valor de una llave
say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
- # (`{llave1}` no funciona, debido a que Perl 6 no tiene
+ # (`{llave1}` no funciona, debido a que Raku no tiene
# palabras desnudas (barewords en inglés))
```
@@ -133,7 +133,7 @@ say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
## creadas con la palabra clave `sub`.
sub di-hola { say "¡Hola, mundo!" }
-## Puedes proveer argumentos (tipados). Si especificado,
+## Puedes proveer argumentos (tipados). Si especificado,
## el tipo será chequeado al tiempo de compilación si es posible.
## De lo contrario, al tiempo de ejecución.
sub di-hola-a(Str $nombre) {
@@ -165,7 +165,7 @@ say return-for; # imprime Nil
## Una subrutina puede tener argumentos opcionales:
sub con-opcional($arg?) { # el signo "?" marca el argumento opcional
- say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
+ say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
un argumento, o returnaré mi argumento";
$arg;
}
@@ -173,7 +173,7 @@ con-opcional; # devuelve Any
con-opcional(); # devuelve Any
con-opcional(1); # devuelve 1
-## También puedes proveer un argumento por defecto para
+## También puedes proveer un argumento por defecto para
## cuando los argumentos no son proveídos:
sub hola-a($nombre = "Mundo") {
say "¡Hola, $nombre!";
@@ -190,10 +190,10 @@ sub con-nombre($arg-normal, :$nombrado) {
}
con-nombre(1, nombrado => 6); #=> 7
## Sin embargo, debes tener algo en cuenta aquí:
-## Si pones comillas alrededor de tu llave, Perl 6 no será capaz de verla
+## Si pones comillas alrededor de tu llave, Raku no será capaz de verla
## al tiempo de compilación, y entonces tendrás un solo objeto Pair como
-## un argumento posicional, lo que significa que el siguiente ejemplo
-## falla:
+## un argumento posicional, lo que significa que el siguiente ejemplo
+## falla:
con-nombre(1, 'nombrado' => 6);
con-nombre(2, :nombrado(5)); #=> 7
@@ -205,7 +205,7 @@ sub con-nombre-mandatorio(:$str!) {
}
con-nombre-mandatorio(str => "Mi texto"); #=> Mi texto!
con-nombre-mandatorio; # error al tiempo de ejecución:
- # "Required named parameter not passed"
+ # "Required named parameter not passed"
# ("Parámetro nombrado requerido no proveído")
con-nombre-mandatorio(3);# error al tiempo de ejecución:
# "Too many positional parameters passed"
@@ -226,7 +226,7 @@ sub nombrado-definido(:$def = 5) {
nombrado-definido; #=> 5
nombrado-definido(def => 15); #=> 15
-## Dado que puedes omitir los paréntesis para invocar una función sin
+## Dado que puedes omitir los paréntesis para invocar una función sin
## argumentos, necesitas usar "&" en el nombre para almacenar la función
## `di-hola` en una variable.
my &s = &di-hola;
@@ -240,8 +240,8 @@ sub muchos($principal, *@resto) { #`*@` (slurpy) consumirá lo restante
say @resto.join(' / ') ~ "!";
}
say muchos('Feliz', 'Cumpleaño', 'Cumpleaño'); #=> Feliz / Cumpleaño!
- # Nota que el asterisco (*) no
- # consumió el parámetro frontal.
+ # Nota que el asterisco (*) no
+ # consumió el parámetro frontal.
## Puedes invocar un función con un array usando el
## operador "aplanador de lista de argumento" `|`
@@ -256,12 +256,12 @@ concat3(|@array); #=> a, b, c
## Contenedores
```perl6
-## En Perl 6, valores son actualmente almacenados en "contenedores".
-## El operador de asignación le pregunta al contenedor en su izquierda
+## En Raku, valores son actualmente almacenados en "contenedores".
+## El operador de asignación le pregunta al contenedor en su izquierda
## almacenar el valor a su derecha. Cuando se pasan alrededor, contenedores
## son marcados como inmutables. Esto significa que, en una función, tu
## tendrás un error si tratas de mutar uno de tus argumentos.
-## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
+## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
## mutable usando `is rw`:
sub mutar($n is rw) {
$n++;
@@ -276,7 +276,7 @@ mutar $m; # ¡$n es ahora 43!
## dado que no contenedor ha sido pasado y números enteros son inmutables
## por naturaleza:
-mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
+mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
# pero recibió un valor Int
## Si en cambio quieres una copia, debes usar `is copy`.
@@ -286,7 +286,7 @@ mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
my $x = 42;
sub x-almacena() is rw { $x }
x-almacena() = 52; # En este caso, los paréntesis son mandatorios
- # (porque de otra forma, Perl 6 piensa que la función
+ # (porque de otra forma, Raku piensa que la función
# `x-almacena` es un identificador).
say $x; #=> 52
```
@@ -297,9 +297,9 @@ say $x; #=> 52
```perl6
## - `if`
## Antes de hablar acerca de `if`, necesitamos saber cuales valores son
-## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
-## (o "Falsy") -- representa False (falso). Solo estos valores son
-## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
+## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
+## (o "Falsy") -- representa False (falso). Solo estos valores son
+## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
## por supuesto False. Todos los valores son Truthy.
if True {
say "¡Es verdadero!";
@@ -316,8 +316,8 @@ unless False {
## También puedes usar sus versiones sufijos seguidas por la palabra clave:
say "Un poco verdadero" if True;
-## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
-## devuelve $valor-si-verdadera si la condición es verdadera y
+## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
+## devuelve $valor-si-verdadera si la condición es verdadera y
## $valor-si-falsa si es falsa.
## my $resultado = $valor condición ?? $valor-si-verdadera !! $valor-si-falsa;
@@ -338,21 +338,21 @@ say $edad > 18 ?? "Eres un adulto" !! "Eres menor de 18";
##
## `given` simplemente pone su argumento en `$_` (como un bloque lo haría),
## y `when` lo compara usando el operador de "coincidencia inteligente" (`~~`).
-##
-## Dado que otras construcciones de Perl 6 usan esta variable (por ejemplo,
+##
+## Dado que otras construcciones de Raku usan esta variable (por ejemplo,
## el bucle `for`, bloques, etc), esto se significa que el poderoso `when` no
-## solo se aplica con un `given`, sino que se puede usar en cualquier
+## solo se aplica con un `given`, sino que se puede usar en cualquier
## lugar donde exista una variable `$_`.
given "foo bar" {
say $_; #=> foo bar
- when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
+ when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
# solo ten presente que `when` la usa.
# Esto es equivalente a `if $_ ~~ /foo/`.
say "¡Yay!";
}
when $_.chars > 50 { # coincidencia inteligente con cualquier cosa True es True,
- # i.e. (`$a ~~ True`)
+ # i.e. (`$a ~~ True`)
# por lo tanto puedes también poner condiciones "normales".
# Este `when` es equivalente a este `if`:
# if $_ ~~ ($_.chars > 50) {...}
@@ -373,12 +373,12 @@ given "foo bar" {
## pero también puede ser un bucle for al estilo de C:
loop {
say "¡Este es un bucle infinito!";
- last; # last interrumpe el bucle, como la palabra clave `break`
+ last; # last interrumpe el bucle, como la palabra clave `break`
# en otros lenguajes.
}
loop (my $i = 0; $i < 5; $i++) {
- next if $i == 3; # `next` salta a la siguiente iteración, al igual
+ next if $i == 3; # `next` salta a la siguiente iteración, al igual
# que `continue` en otros lenguajes. Ten en cuenta que
# también puedes usar la condicionales postfix (sufijas)
# bucles, etc.
@@ -391,29 +391,29 @@ for @array -> $variable {
}
## Como vimos con `given`, la variable de una "iteración actual" por defecto
-## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
+## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
## normalmente lo harías con `given`.
for @array {
say "he conseguido a $_";
.say; # Esto es también permitido.
- # Una invocación con punto (dot call) sin "tópico" (recibidor) es
- # enviada a `$_` por defecto.
+ # Una invocación con punto (dot call) sin "tópico" (recibidor) es
+ # enviada a `$_` por defecto.
$_.say; # lo mismo de arriba, lo cual es equivalente.
}
for @array {
# Puedes...
- next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
+ next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
# lenguages parecido a C)
- redo if $_ == 4; # Re-hacer la iteración, manteniendo la
+ redo if $_ == 4; # Re-hacer la iteración, manteniendo la
# misma variable tópica (`$_`)
- last if $_ == 5; # Salir fuera del bucle (como `break`
+ last if $_ == 5; # Salir fuera del bucle (como `break`
# en lenguages parecido a C)
}
-## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
-## Es solo una manera de expresar un bloque en Perl 6.
+## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
+## Es solo una manera de expresar un bloque en Raku.
if computación-larga() -> $resultado {
say "El resultado es $resultado";
}
@@ -423,7 +423,7 @@ if computación-larga() -> $resultado {
```perl6
## Dados que los lenguajes de la familia Perl son lenguages basados
-## mayormente en operadores, los operadores de Perl 6 son actualmente
+## mayormente en operadores, los operadores de Raku son actualmente
## subrutinas un poco cómicas en las categorías sintácticas. Por ejemplo,
## infix:<+> (adición) o prefix:<!> (bool not).
@@ -455,7 +455,7 @@ if computación-larga() -> $resultado {
(1, 2) eqv (1, 3);
## - Operador de coincidencia inteligente (smart matching): `~~`
-## Asocia (aliasing en inglés) el lado izquierda a la variable $_
+## Asocia (aliasing en inglés) el lado izquierda a la variable $_
## y después evalúa el lado derecho.
## Aquí algunas comparaciones semánticas comunes:
@@ -464,8 +464,8 @@ if computación-larga() -> $resultado {
'Foo' ~~ 'Foo'; # True si las cadenas de texto son iguales.
12.5 ~~ 12.50; # True si los números son iguales.
-## Regex - Para la comparación de una expresión regular en contra
-## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
+## Regex - Para la comparación de una expresión regular en contra
+## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
## como True si el regex coincide con el patrón.
my $obj = 'abc' ~~ /a/;
@@ -475,12 +475,12 @@ say $obj.WHAT; # (Match)
## Hashes
'llave' ~~ %hash; # True si la llave existe en el hash
-## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
+## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
## superclases y roles)
1 ~~ Int; # True (1 es un número entero)
-## Coincidencia inteligente contra un booleano siempre devuelve ese
+## Coincidencia inteligente contra un booleano siempre devuelve ese
## booleano (y lanzará una advertencia).
1 ~~ True; # True
@@ -502,13 +502,13 @@ False ~~ True; # True
## Esto también funciona como un atajo para `0..^N`:
^10; # significa 0..^10
-## Esto también nos permite demostrar que Perl 6 tiene arrays
+## Esto también nos permite demostrar que Raku tiene arrays
## ociosos/infinitos, usando la Whatever Star:
my @array = 1..*; # 1 al Infinito! `1..Inf` es lo mismo.
say @array[^10]; # puedes pasar arrays como subíndices y devolverá
# un array de resultados. Esto imprimirá
# "1 2 3 4 5 6 7 8 9 10" (y no se quedaré sin memoria!)
-## Nota: Al leer una lista infinita, Perl 6 "cosificará" los elementos que
+## Nota: Al leer una lista infinita, Raku "cosificará" los elementos que
## necesita y los mantendrá en la memoria. Ellos no serán calculados más de
## una vez. Tampoco calculará más elementos de los que necesita.
@@ -517,14 +517,14 @@ say @array[^10]; # puedes pasar arrays como subíndices y devolverá
say join(' ', @array[15..*]); #=> 15 16 17 18 19
## lo que es equivalente a:
say join(' ', @array[-> $n { 15..$n }]);
-## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
+## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
## provocará un array infinito (tu programa nunca terminará)
## Puedes usar eso en los lugares que esperaría, como durante la asignación
## a un array
my @números = ^20;
-## Aquí los números son incrementados por "6"; más acerca del
+## Aquí los números son incrementados por "6"; más acerca del
## operador `...` adelante.
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@números[5..*] = 3, 9 ... *; # aunque la secuencia es infinita,
@@ -546,7 +546,7 @@ $a && $b && $c; # Devuelve 0, el primer valor que es False
$b || $a; # 1
## Y porque tu lo querrás, también tienes operadores de asignación
-## compuestos:
+## compuestos:
$a *= 2; # multiplica y asigna. Equivalente a $a = $a * 2;
$b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
@array .= sort; # invoca el método `sort` y asigna el resultado devuelto.
@@ -555,8 +555,8 @@ $b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
## ¡Más sobre subrutinas!
```perl6
-## Como dijimos anteriormente, Perl 6 tiene subrutinas realmente poderosas.
-## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
+## Como dijimos anteriormente, Raku tiene subrutinas realmente poderosas.
+## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
## lenguaje :-).
```
@@ -602,14 +602,14 @@ sub fst(*@ [$fst]) { # o simplemente: `sub fst($fst) { ... }`
fst(1); #=> 1
fst(1, 2); # errores con "Too many positional parameters passed"
-## También puedes desestructurar hashes (y clases, las cuales
-## veremos adelante). La sintaxis es básicamente
+## También puedes desestructurar hashes (y clases, las cuales
+## veremos adelante). La sintaxis es básicamente
## `%nombre-del-hash (:llave($variable-para-almacenar))`.
## El hash puede permanecer anónimos si solo necesitas los valores extraídos.
sub llave-de(% (:azul($val1), :red($val2))) {
say "Valores: $val1, $val2.";
}
-## Después invócala con un hash: (necesitas mantener las llaves
+## Después invócala con un hash: (necesitas mantener las llaves
## de los parejas de llave y valor para ser un hash)
llave-de({azul => 'blue', rojo => "red"});
#llave-de(%hash); # lo mismo (para un `%hash` equivalente)
@@ -621,11 +621,11 @@ sub siguiente-indice($n) {
}
my $nuevo-n= siguiente-indice(3); # $nuevo-n es ahora 4
-## Este es cierto para todo, excepto para las construcciones de bucles
+## Este es cierto para todo, excepto para las construcciones de bucles
## (debido a razones de rendimiento): Hay una razón de construir una lista
## si la vamos a desechar todos los resultados.
## Si todavías quieres construir una, puedes usar la sentencia prefijo `do`:
-## (o el prefijo `gather`, el cual veremos luego)
+## (o el prefijo `gather`, el cual veremos luego)
sub lista-de($n) {
do for ^$n { # nota el uso del operador de rango `^` (`0..^N`)
$_ # iteración de bucle actual
@@ -639,19 +639,19 @@ my @list3 = lista-de(3); #=> (0, 1, 2)
```perl6
## Puedes crear una lambda con `-> {}` ("bloque puntiagudo") o `{}` ("bloque")
my &lambda = -> $argumento { "El argumento pasado a esta lambda es $argumento" }
-## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
+## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
## tomar argumentos, y la segunda puede ser malinterpretada como un hash
## por el parseador.
## Podemos, por ejemplo, agregar 3 a cada valor de un array usando map:
my @arraymas3 = map({ $_ + 3 }, @array); # $_ es el argumento implícito
-## Una subrutina (`sub {}`) tiene semánticas diferentes a un
-## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
+## Una subrutina (`sub {}`) tiene semánticas diferentes a un
+## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
## (aunque puede tener argumentos), lo que significa que si quieres devolver
## algo desde un bloque, vas a returnar desde la función parental. Compara:
sub is-in(@array, $elem) {
- # esto `devolverá` desde la subrutina `is-in`
+ # esto `devolverá` desde la subrutina `is-in`
# Una vez que la condición evalúa a True, el bucle terminará
map({ return True if $_ == $elem }, @array);
}
@@ -685,7 +685,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (aquí con `sub`)
### Acerca de tipos...
```perl6
-## Perl 6 es gradualmente tipado. Esto quiere decir que tu especifica el
+## Raku es gradualmente tipado. Esto quiere decir que tu especifica el
## tipo de tus variables/argumentos/devoluciones (return), o puedes omitirlos
## y serán "Any" por defecto.
## Obviamente tienes acceso a algunas tipos básicos, como Int y Str.
@@ -703,7 +703,7 @@ subset EnteroGrande of Int where * > 500;
### Despacho Múltiple (Multiple Dispatch)
```perl6
-## Perl 6 puede decidir que variante de una subrutina invocar basado en el
+## Raku puede decidir que variante de una subrutina invocar basado en el
## tipo de los argumento, o precondiciones arbitrarias, como con un tipo o
## un `where`:
@@ -740,9 +740,9 @@ multi sin_ti-o-contigo {
}
## Esto es muy útil para muchos propósitos, como subrutinas `MAIN` (de las
## cuales hablaremos luego), y hasta el mismo lenguaje la está usando
-## en muchos lugares.
+## en muchos lugares.
##
-## - `is`, por ejemplo, es actualmente un `multi sub` llamado
+## - `is`, por ejemplo, es actualmente un `multi sub` llamado
## `trait_mod:<is>`.
## - `is rw`, es simplemente un despacho a una función con esta signatura:
## sub trait_mod:<is>(Routine $r, :$rw!) {}
@@ -754,7 +754,7 @@ multi sin_ti-o-contigo {
## Ámbito (Scoping)
```perl6
-## En Perl 6, a diferencia de otros lenguajes de scripting, (tales como
+## En Raku, a diferencia de otros lenguajes de scripting, (tales como
## (Python, Ruby, PHP), debes declarar tus variables antes de usarlas. El
## declarador `my`, del cual aprendiste anteriormente, usa "ámbito léxical".
## Hay otros declaradores (`our`, `state`, ..., ) los cuales veremos luego.
@@ -770,7 +770,7 @@ sub externo {
}
outer()(); #=> 'Foo Bar'
-## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
+## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
## fueron capturados. Pero si intentaramos usar `$bar` fuera de `foo`,
## la variable estaría indefinida (y obtendrías un error al tiempo de
## compilación).
@@ -779,12 +779,12 @@ outer()(); #=> 'Foo Bar'
## Twigils
```perl6
-## Hay muchos `twigils` especiales (sigilos compuestos) en Perl 6.
-## Los twigils definen el ámbito de las variables.
+## Hay muchos `twigils` especiales (sigilos compuestos) en Raku.
+## Los twigils definen el ámbito de las variables.
## Los twigils * y ? funcionan con variables regulares:
## * Variable dinámica
## ? Variable al tiempo de compilación
-## Los twigils ! y . son usados con los objetos de Perl 6:
+## Los twigils ! y . son usados con los objetos de Raku:
## ! Atributo (miembro de la clase)
## . Método (no una variable realmente)
@@ -820,20 +820,20 @@ di_ambito(); #=> 1 100 Cambiamos el valor de $*ambito_din_2 en invoca_a_di_ambit
```perl6
## Para invocar a un método en un objeto, agrega un punto seguido por el
-## nombre del objeto:
+## nombre del objeto:
## => $object.method
## Las classes son declaradas usando la palabra clave `class`. Los atributos
## son declarados con la palabra clave `has`, y los métodos con `method`.
## Cada atributo que es privado usa el twigil `!`. Por ejemplo: `$!attr`.
-## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
+## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
## mutables con `is rw`).
-## La manera más fácil de recordar el twigil `$.` is comparándolo
+## La manera más fácil de recordar el twigil `$.` is comparándolo
## con como los métodos son llamados.
-## El modelo de objeto de Perl 6 ("SixModel") es muy flexible, y te permite
+## El modelo de objeto de Raku ("SixModel") es muy flexible, y te permite
## agregar métodos dinámicamente, cambiar la semántica, etc ...
-## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
-## https://docs.perl6.org/language/objects.html).
+## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
+## https://docs.raku.org/language/objects.html).
class Clase-Atrib {
has $.atrib; # `$.atrib` es inmutable.
@@ -858,7 +858,7 @@ class Clase-Atrib {
};
## Crear una nueva instancia de Clase-Atrib con $.atrib asignado con 5:
-## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
+## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
## esto adelante).
my $class-obj = Clase-Atrib.new(atrib => 5);
say $class-obj.devolver-valor; #=> 5
@@ -870,12 +870,12 @@ $class-obj.otro-atrib = 10; # En cambio, esto funciona porque el atributo
### Herencia de Objeto
```perl6
-## Perl 6 también tiene herencia (junto a herencia múltiple)
+## Raku también tiene herencia (junto a herencia múltiple)
## Mientras los métodos declarados con `method` son heredados, aquellos
## declarados con `submethod` no lo son.
## Submétodos son útiles para la construcción y destrucción de tareas,
## tales como BUILD, o métodos que deben ser anulados por subtipos.
-## Aprenderemos acerca de BUILD más adelante.
+## Aprenderemos acerca de BUILD más adelante.
class Padre {
has $.edad;
@@ -890,7 +890,7 @@ class Padre {
# Herencia usa la palabra clave `is`
class Niño is Padre {
method hablar { say "Goo goo ga ga" }
- # Este método opaca el método `hablar` de Padre.
+ # Este método opaca el método `hablar` de Padre.
# Este niño no ha aprendido a hablar todavía.
}
my Padre $Richard .= new(edad => 40, nombre => 'Richard');
@@ -899,19 +899,19 @@ $Richard.hablar; #=> "Hola, mi nombre es Richard"
## $Richard es capaz de acceder el submétodo; él sabe como decir su nombre.
my Niño $Madison .= new(edad => 1, nombre => 'Madison');
-$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
+$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
# en la clase Niño.
# $Madison.color-favorito # no funciona porque no es heredado
## Cuando se usa `my T $var` (donde `T` es el nombre de la clase), `$var`
## inicia con `T` en si misma, por lo tanto puedes invocar `new` en `$var`.
-## (`.=` es sólo la invocación por punto y el operador de asignación:
+## (`.=` es sólo la invocación por punto y el operador de asignación:
## `$a .= b` es lo mismo que `$a = $a.b`)
## Por ejemplo, la instancia $Richard pudo también haber sido declarada así:
## my $Richard = Padre.new(edad => 40, nombre => 'Richard');
-## También observa que `BUILD` (el método invocado dentro de `new`)
-## asignará propiedades de la clase padre, por lo que puedes pasar
+## También observa que `BUILD` (el método invocado dentro de `new`)
+## asignará propiedades de la clase padre, por lo que puedes pasar
## `val => 5`.
```
@@ -932,7 +932,7 @@ class Item does PrintableVal {
has $.val;
## Cuando se utiliza `does`, un `rol` se mezcla en al clase literalmente:
- ## los métodos y atributos se ponen juntos, lo que significa que una clase
+ ## los métodos y atributos se ponen juntos, lo que significa que una clase
## puede acceder los métodos y atributos privados de su rol (pero no lo inverso!):
method access {
say $!counter++;
@@ -945,17 +945,17 @@ class Item does PrintableVal {
## de su clase hijo/a, pero es un error sin un rol lo hace)
## NOTA: Puedes usar un rol como una clase (con `is ROLE`). En este caso,
- ## métodos serán opacados, dado que el compilador considerará `ROLE`
- ## como una clase.
+ ## métodos serán opacados, dado que el compilador considerará `ROLE`
+ ## como una clase.
}
```
## Excepciones
```perl6
-## Excepciones están construidas al tope de las clases, en el paquete
+## Excepciones están construidas al tope de las clases, en el paquete
## `X` (como `X::IO`).
-## En Perl 6, excepciones son lanzadas automáticamente.
+## En Raku, excepciones son lanzadas automáticamente.
open 'foo'; #=> Failed to open file foo: no such file or directory
## También imprimirá la línea donde el error fue lanzado y otra información
## concerniente al error.
@@ -966,16 +966,16 @@ die 'Error!'; #=> Error!
## O más explícitamente:
die X::AdHoc.new(payload => 'Error!');
-## En Perl 6, `orelse` es similar al operador `or`, excepto que solamente
+## En Raku, `orelse` es similar al operador `or`, excepto que solamente
## coincide con variables indefinidas, en cambio de cualquier cosa
## que evalúa a falso.
-## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
+## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
## `Int`, `Str` y otros tipos que no han sido inicializados a ningún valor
## todavía.
## Puedes chequear si algo está definido o no usando el método defined:
my $no-inicializada;
say $no-inicializada.defined; #=> False
-## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
+## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
## fallo en $_
## Esto evitará que sea automáticamente manejado e imprima una marejada de
## mensajes de errores en la pantalla.
@@ -986,7 +986,7 @@ open 'foo' orelse say "Algo pasó {.exception}";
open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
#=> Failed to open file foo: no such file or directory
## Ambos ejemplos anteriores funcionan pero en caso de que consigamos un
-## objeto desde el lado izquierdo que no es un fallo, probablemente
+## objeto desde el lado izquierdo que no es un fallo, probablemente
## obtendremos una advertencia. Más abajo vemos como usar `try` y `CATCH`
## para ser más expecíficos con las excepciones que capturamos.
```
@@ -994,8 +994,8 @@ open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
### Usando `try` y `CATCH`
```perl6
-## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
-## interrumpir el resto del programa. `try` asignará la última excepción
+## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
+## interrumpir el resto del programa. `try` asignará la última excepción
## a la variable especial `$!`.
## Nota: Esto no tiene ninguna relación con las variables $!.
@@ -1003,12 +1003,12 @@ try open 'foo';
say "Bueno, lo intenté! $!" if defined $!; #=> Bueno, lo intenté! Failed to open file
#foo: no such file or directory
## Ahora, ¿qué debemos hacer si queremos más control sobre la excepción?
-## A diferencia de otros lenguajes, en Perl 6 se pone el bloque `CATCH`
+## A diferencia de otros lenguajes, en Raku se pone el bloque `CATCH`
## *dentro* del bloque a intentar (`try`). Similarmente como $_ fue asignada
## cuando 'disarmamos' la excepción con `orelse`, también usamos $_ en el
## bloque CATCH.
## Nota: ($! es solo asignada *después* del bloque `try`)
-## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
+## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
## cualquier excepción (`CATCH { default {} }`).
try { my $a = (0 %% 0); CATCH { say "Algo pasó: $_" } }
@@ -1022,9 +1022,9 @@ try {
when X::AdHoc { say "Error: $_" }
#=>Error: Failed to open file /dir/foo: no such file or directory
- ## Cualquier otra excepción será levantada de nuevo, dado que no
+ ## Cualquier otra excepción será levantada de nuevo, dado que no
## tenemos un `default`.
- ## Básicamente, si un `when`
+ ## Básicamente, si un `when`
## Basically, if a `when` matches (or there's a `default`) marks the
## exception as
## "handled" so that it doesn't get re-thrown from the `CATCH`.
@@ -1032,14 +1032,14 @@ try {
}
}
-## En Perl 6, excepciones poseen ciertas sutilezas. Algunas
-## subrutinas en Perl 6 devuelven un `Failure`, el cual es un tipo de
+## En Raku, excepciones poseen ciertas sutilezas. Algunas
+## subrutinas en Raku devuelven un `Failure`, el cual es un tipo de
## "excepción no levantada". Ellas no son levantadas hasta que tu intentas
-## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
+## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
## ellas - entonces, son manejadas.
## (el método `.handled` es `rw`, por lo que puedes marcarlo como `False`
## por ti mismo)
-## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
+## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
## `use fatal` estás siendo utilizado, `fail` levantará una excepión (como
## `die`).
fail "foo"; # No estamos intentando acceder el valor, por lo tanto no problema.
@@ -1053,27 +1053,27 @@ try {
## También hay otro tipo de excepción: Excepciones de control.
## Esas son excepciones "buenas", las cuales suceden cuando cambias el flujo
## de tu programa, usando operadores como `return`, `next` or `last`.
-## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
+## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
```
## Paquetes
```perl6
-## Paquetes son una manera de reusar código. Paquetes son como
-## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
+## Paquetes son una manera de reusar código. Paquetes son como
+## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
## modelo seis (`module`, `role`, `class`, `grammar`, `subset` y `enum`)
-## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
+## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
## denominador)
-## Los paquetes son importantes - especialmente dado que Perl es bien
+## Los paquetes son importantes - especialmente dado que Perl es bien
## reconocido por CPAN, the Comprehensive Perl Archive Nertwork.
## Puedes usar un módulo (traer sus declaraciones al ámbito) con `use`
use JSON::Tiny; # si intalaste Rakudo* o Panda, tendrás este módulo
say from-json('[1]').perl; #=> [1]
-## A diferencia de Perl 5, no deberías declarar paquetes usando
+## A diferencia de Perl, no deberías declarar paquetes usando
## la palabra clave `package`. En vez, usa `class Nombre::Paquete::Aquí;`
-## para declarar una clase, o si solamente quieres exportar
+## para declarar una clase, o si solamente quieres exportar
## variables/subrutinas, puedes usar `module`.
module Hello::World { # forma de llaves
@@ -1083,11 +1083,11 @@ module Hello::World { # forma de llaves
}
unit module Parse::Text; # forma de ámbito de archivo
-grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
+grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
# en el cual puedes usar `use`
} # Aprenderás más acerca de gramáticas en la sección de regex
-## Como se dijo anteriormente, cualquier parte del modelo seis es también un
+## Como se dijo anteriormente, cualquier parte del modelo seis es también un
## paquete. Dado que `JSON::Tiny` usa su propia clase `JSON::Tiny::Actions`,
## tu puedes usarla de la manera siguiente:
my $acciones = JSON::Tiny::Actions.new;
@@ -1098,13 +1098,13 @@ my $acciones = JSON::Tiny::Actions.new;
## Declaradores
```perl6
-## En Perl 6, tu obtienes diferentes comportamientos basado en como declaras
+## En Raku, tu obtienes diferentes comportamientos basado en como declaras
## una variable.
## Ya has visto `my` y `has`, ahora exploraremos el resto.
## * las declaraciones `our` ocurren al tiempo `INIT` (ve "Phasers" más abajo)
## Es como `my`, pero también crea una variable paquete.
-## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
+## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
## `our` por defecto)
module Var::Incrementar {
our $nuestra-var = 1; # Nota: No puedes colocar una restricción de tipo
@@ -1132,7 +1132,7 @@ Var::Incrementar::Inc; #=> 3 # Nota como el valor de $nuestra-var fue
Var::Incrementar::no-disponible; #=> Could not find symbol '&no-disponible'
## * `constant` (ocurre al tiempo `BEGIN`)
-## Puedes usar la palabra clave `constant` para declarar una
+## Puedes usar la palabra clave `constant` para declarar una
## variable/símbolo al tiempo de compilación:
constant Pi = 3.14;
constant $var = 1;
@@ -1151,11 +1151,11 @@ sub aleatorio-fijo {
aleatorio-fijo for ^10; # imprimirá el mismo número 10 veces
## Nota, sin embargo, que ellas existen separadamente en diferentes contextos.
-## Si declaras una función con un `state` dentro de un bucle, recreará la
+## Si declaras una función con un `state` dentro de un bucle, recreará la
## variable por cada iteración del bucle. Observa:
for ^5 -> $a {
sub foo {
- state $valor = rand; # Esto imprimirá un valor diferente
+ state $valor = rand; # Esto imprimirá un valor diferente
# por cada valor de `$a`
}
for ^5 -> $b {
@@ -1165,11 +1165,11 @@ for ^5 -> $a {
}
```
-## Phasers
+## Phasers
```perl6
-## Un phaser en Perl 6 es un bloque que ocurre a determinados puntos de tiempo
-## en tu programa. Se les llama phaser porque marca un cambio en la fase de
+## Un phaser en Raku es un bloque que ocurre a determinados puntos de tiempo
+## en tu programa. Se les llama phaser porque marca un cambio en la fase de
## de tu programa. Por ejemplo, cuando el programa es compilado, un bucle
## for se ejecuta, dejas un bloque, o una excepción se levanta.
## (¡`CATCH` es actualmente un phaser!)
@@ -1191,13 +1191,13 @@ END { say "Se ejecuta al tiempo de ejecución, " ~
"tan tarde como sea posible, una sola vez" }
## * Phasers de bloques
-ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
+ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
"se repite en bloques de bucle" }
-LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
+LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
"cuando una excepción ocurre. Se repite en bloques de bucle"}
PRE {
- say "Impone una precondición a cada entrada de un bloque, " ~
+ say "Impone una precondición a cada entrada de un bloque, " ~
"antes que ENTER (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada.";
@@ -1209,7 +1209,7 @@ for 0..2 {
}
POST {
- say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
+ say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
"después de LEAVE (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada, como con PRE.";
@@ -1250,14 +1250,14 @@ sub do-db-stuff {
## Prefijos de sentencias
```perl6
-## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
+## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
## comportamiento del siguiente código.
## Debido a que son ejecutados en línea con el código ejecutable, ellos
## se escriben en letras minúsculas. (`try` and `start` están teoréticamente
## en esa lista, pero serán explicados en otra parte)
## Nota: Ningunos de estos (excepto `start`) necesitan las llaves `{` y `}`.
-## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
+## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
## término.
## Normalmente no puedes usar una sentencia como un valor (o término):
##
@@ -1289,7 +1289,7 @@ say join ',', gather if False {
## - `eager` - Evalúa una sentencia ávidamente (forza contexto ávido)
## No intentes esto en casa:
##
-## eager 1..*; # esto probablemente se colgará por un momento
+## eager 1..*; # esto probablemente se colgará por un momento
## # (y podría fallar...).
##
## Pero considera lo siguiente:
@@ -1302,13 +1302,13 @@ constant tres-veces = eager gather for ^3 { say take $_ }; #=> 0 1 2
## Iterables
```perl6
-## En Perl 6, los iterables son objetos que pueden ser iterados similar
-## a la construcción `for`.
+## En Raku, los iterables son objetos que pueden ser iterados similar
+## a la construcción `for`.
## `flat`, aplana iterables:
say (1, 10, (20, 10) ); #=> (1 10 (20 10)) Nota como la agrupación se mantiene
say (1, 10, (20, 10) ).flat; #=> (1 10 20 10) Ahora el iterable es plano
-## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
+## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
## (forza contexto perezoso)
my @lazy-array = (1..100).lazy;
say @lazy-array.is-lazy; #=> True # Chequea por "pereza" con el método `is-lazy`.
@@ -1333,7 +1333,7 @@ quietly { warn 'Esto es una advertencia!' }; #=> No salida
## ¡Todo el mundo ama los operadores! Tengamos más de ellos.
## La lista de precedencia puede ser encontrada aquí:
-## https://docs.perl6.org/language/operators#Operator_Precedence
+## https://docs.raku.org/language/operators#Operator_Precedence
## Pero primero, necesitamos un poco de explicación acerca
## de la asociatividad:
@@ -1356,7 +1356,7 @@ $a ! $b ! $c; # con asociatividad de lista `!`, esto es `infix:<>`
## Okay, has leído todo esto y me imagino que debería mostrarte
## algo interesante.
## Te mostraré un pequeño secreto (o algo no tan secreto):
-## En Perl 6, todos los operadores son actualmente solo subrutinas.
+## En Raku, todos los operadores son actualmente solo subrutinas.
## Puedes declarar un operador como declaras una subrutina:
sub prefix:<ganar>($ganador) { # se refiere a las categorías de los operadores
@@ -1374,14 +1374,14 @@ sub postfix:<!>(Int $n) {
}
say 5!; #=> 120
# Operadores sufijos (postfix) van *directamente* después del témino.
- # No espacios en blanco. Puedes usar paréntesis para disambiguar,
+ # No espacios en blanco. Puedes usar paréntesis para disambiguar,
# i.e. `(5!)!`
sub infix:<veces>(Int $n, Block $r) { # infijo va en el medio
for ^$n {
$r(); # Necesitas los paréntesis explícitos para invocar la función
- # almacenada en la variable `$r`. De lo contrario, te estaría
+ # almacenada en la variable `$r`. De lo contrario, te estaría
# refiriendo a la variable (no a la función), como con `&r`.
}
}
@@ -1399,33 +1399,33 @@ say [5]; #=> 3125
# un circunfijo va alrededor. De nuevo, no espacios en blanco.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
- ## un pos-circunfijo es
+ ## un pos-circunfijo es
## "después de un término y alrededor de algo"
$s.substr($idx, 1);
}
say "abc"{1}; #=> b
# depués del término `"abc"`, y alrededor del índice (1)
-## Esto es de gran valor -- porque todo en Perl 6 usa esto.
+## Esto es de gran valor -- porque todo en Raku usa esto.
## Por ejemplo, para eliminar una llave de un hash, tu usas el adverbio
## `:delete` (un simple argumento con nombre debajo):
%h{$llave}:delete;
## es equivalente a:
-postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
+postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
# operadores de esta forma)
-## ¡*Todos* usan los mismos bloques básicos!
+## ¡*Todos* usan los mismos bloques básicos!
## Categorías sintácticas (prefix, infix, ...), argumentos nombrados
## (adverbios), ... - usados para construir el lenguaje - están al alcance
## de tus manos y disponibles para ti.
-## (obviamente, no se te recomienda que hagas un operador de *cualquier
+## (obviamente, no se te recomienda que hagas un operador de *cualquier
## cosa* -- Un gran poder conlleva una gran responsabilidad.)
```
### Meta-operadores!
```perl6
-## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
-## en el agujero del conejo, y probablemente no querrás regresar a
+## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
+## en el agujero del conejo, y probablemente no querrás regresar a
## otros lenguajes después de leer esto.
## (Me imagino que ya no quieres a este punto).
## Meta-operadores, como su nombre lo sugiere, son operadores *compuestos*.
@@ -1434,14 +1434,14 @@ postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
## * El meta-operador reduce (reducir)
## Es un meta-operador prefijo que toman una función binaria y
## una o varias listas. Sino se pasa ningún argumento,
-## returna un "valor por defecto" para este operador
+## returna un "valor por defecto" para este operador
## (un valor sin significado) o `Any` si no hay ningún valor.
##
-## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
+## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
## aplica la función binaria al último resultado (o al primer elemento de
## la lista y el elemento que ha sido removido).
##
-## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
+## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
## i.e.:
say [+] 1, 2, 3; #=> 6
## es equivalente a `(1+2)+3`
@@ -1461,20 +1461,20 @@ say [+] (); #=> 0
# valores sin significado, dado que N*1=N y N+0=N.
say [//]; #=> (Any)
# No hay valor por defecto para `//`.
-## También puedes invocarlo con una función de tu creación usando
+## También puedes invocarlo con una función de tu creación usando
## los dobles corchetes:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * El meta-operador zip
-## Este es un meta-operador infijo que también puede ser usado como un
+## Este es un meta-operador infijo que también puede ser usado como un
## operador "normal". Toma una función binaria opcional (por defecto, solo
-## crear un par), y remueve un valor de cada array e invoca su función
+## crear un par), y remueve un valor de cada array e invoca su función
## binaria hasta que no tenga más elementos disponibles. Al final, returna
## un array con todos estos nuevos elementos.
-(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
+(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
# crea un array.
-1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
+1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
## Dado que `Z` tiene asociatividad de lista (ve la lista más arriba),
## puedes usarlo en más de una lista
@@ -1487,13 +1487,13 @@ say [[&add]] 1, 2, 3; #=> 6
## Y para terminar la lista de operadores:
## * El operador secuencia
-## El operador secuencia es uno de la más poderosas características de
-## Perl 6: Está compuesto, en la izquierda, de la lista que quieres que
-## Perl 6 use para deducir (y podría incluir una clausura), y en la derecha,
-## un valor o el predicado que dice cuando parar (o Whatever para una
+## El operador secuencia es uno de la más poderosas características de
+## Raku: Está compuesto, en la izquierda, de la lista que quieres que
+## Raku use para deducir (y podría incluir una clausura), y en la derecha,
+## un valor o el predicado que dice cuando parar (o Whatever para una
## lista infinita perezosa).
my @list = 1, 2, 3 ... 10; # deducción básica
-#my @list = 1, 3, 6 ... 10; # esto muere porque Perl 6 no puede deducir el final
+#my @list = 1, 3, 6 ... 10; # esto muere porque Raku no puede deducir el final
my @list = 1, 2, 3 ...^ 10; # como con rangos, puedes excluir el último elemento
# (la iteración cuando el predicado iguala).
my @list = 1, 3, 9 ... * > 30; # puedes usar un predicado
@@ -1505,8 +1505,8 @@ my @fib = 1, 1, *+* ... *; # lista infinita perezosa de la serie fibonacci,
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalene a lo de arriba)
my @fib = 1, 1, { $^a + $^b } ... *; #(... también equivalene a lo de arriba)
## $a and $b siempre tomarán el valor anterior, queriendo decir que
-## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
-## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
+## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
+## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
## etc.
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
@@ -1519,29 +1519,29 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
## Expresiones Regulares
```perl6
-## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
-## sabes algo acerca de Perl 6, podemos comenzar. Primeramente, tendrás
-## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
+## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
+## sabes algo acerca de Raku, podemos comenzar. Primeramente, tendrás
+## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
## (expresiones regulares compatible de perl).
##
## IMPORTANTE: No salte esto porque ya sabes acerca de PCRE. Son totalmente
-## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
+## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
## algunas veces la semántica cambia (`|`). Asegúrate de leer esto
## cuidadosamente porque podrías trospezarte sino lo haces.
##
-## Perl 6 tiene muchas características relacionadas con RegExps. Después de
+## Raku tiene muchas características relacionadas con RegExps. Después de
## todo, Rakudo se parsea a si mismo. Primero vamos a estudiar la sintaxis
## por si misma, después hablaremos acerca de gramáticas (parecido a PEG),
-## las diferencias entre los declaradores `token`, `regex`, y `rule` y
+## las diferencias entre los declaradores `token`, `regex`, y `rule` y
## mucho más.
-## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
+## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
## mofificador `:P5` (Sin embargo, no lo discutiremos en este tutorial).
##
-## En esencia, Perl 6 implementa PEG ("Parsing Expression Grammars")
+## En esencia, Raku implementa PEG ("Parsing Expression Grammars")
## ("Parseado de Expresiones de Gramáticas") nativamente. El orden jerárquico
-## para los parseos ambiguos es determinado por un examen multi-nivel de
+## para los parseos ambiguos es determinado por un examen multi-nivel de
## desempate:
-## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
+## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
## (por 2 o más posiciones)
## - El prefijo literal más largo. `food\w*` le gana a `foo\w*` (por 1)
## - Declaración desde la gramática más derivada a la menos derivada
@@ -1550,48 +1550,48 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
say so 'a' ~~ /a/; #=> True
say so 'a' ~~ / a /; #=> True # ¡Más legible con los espacios!
-## Nota al lector (del traductor):
+## Nota al lector (del traductor):
## Como pudiste haber notado, he decidido traducir "match" y sus diferentes
-## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
+## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
## un regex (o regexp) coincide con cierto texto, me refiero a que el regex
## describe cierto patrón dentro del texto. Por ejemplo, el regex "cencia"
-## coincide con el texto "reminiscencia", lo que significa que dentro del
+## coincide con el texto "reminiscencia", lo que significa que dentro del
## texto aparece ese patrón de caracteres (una `c`, seguida de una `e`,
-## (seguida de una `n`, etc.)
+## (seguida de una `n`, etc.)
-## En todos nuestros ejemplos, vamos a usar el operador de
-## "coincidencia inteligente" contra una expresión regular ("regexp" or
+## En todos nuestros ejemplos, vamos a usar el operador de
+## "coincidencia inteligente" contra una expresión regular ("regexp" or
## "regex" de aquí en adelante). Estamos convirtiendo el resultado usando `so`,
## pero en efecto, está devolviendo un objeto Match. Ellos saben como responder
-## a la indexación de lista, indexación de hash, y devolver la cadena de
+## a la indexación de lista, indexación de hash, y devolver la cadena de
## texto coincidente.
-## Los resultados de la coincidencia están disponible como `$/` (en
+## Los resultados de la coincidencia están disponible como `$/` (en
## ámbito implícito lexical). También puedes usar las variables de captura
## las cuales comienzan con 0:
## `$0`, `$1', `$2`...
##
-## Nota que `~~` no hace un chequeo de inicio/final (es decir,
+## Nota que `~~` no hace un chequeo de inicio/final (es decir,
## el regexp puede coincider con solo un carácter de la cadena de texto).
## Explicaremos luego como hacerlo.
-## En Perl 6, puedes tener un carácter alfanumérico como un literal,
+## En Raku, puedes tener un carácter alfanumérico como un literal,
## todo lo demás debe escaparse usando una barra invertida o comillas.
-say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
+say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
say so 'a|b' ~~ / a \| b /; # `True`. Otra forma de escaparlo
-## El espacio en blanco actualmente no se significa nada en un regexp,
+## El espacio en blanco actualmente no se significa nada en un regexp,
## a menos que uses el adverbio `:s` (`:sigspace`, espacio significante).
say so 'a b c' ~~ / a b c /; #=> `False`. Espacio no significa nada aquí.
say so 'a b c' ~~ /:s a b c /; #=> `True`. Agregamos el modificador `:s` aquí.
-## Si usamos solo un espacio entre cadenas de texto en un regexp, Perl 6
+## Si usamos solo un espacio entre cadenas de texto en un regexp, Raku
## nos advertirá:
say so 'a b c' ~~ / a b c /; #=> 'False' # Espacio no significa nada aquí.
## Por favor usa comillas o el modificador :s (:sigspace) para suprimir
-## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
-## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
+## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
+## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
## dos espacios entre las cadenas de texto o usa el adverbio `:s`.
-## Como vimos anteriormente, podemos incorporar `:s` dentro de los
+## Como vimos anteriormente, podemos incorporar `:s` dentro de los
## delimitadores de barras. También podemos ponerlos fuera de ellos si
## especificamos `m` for `match` (coincidencia):
say so 'a b c' ~~ m:s/a b c/; #=> `True`
@@ -1603,7 +1603,7 @@ say so 'abc' ~~ m[a b c]; #=> `True`
## minúsculas y mayúsculas:
say so 'ABC' ~~ m:i{a b c}; #=> `True`
-## Sin embargo, es importante para como los modificadores son aplicados
+## Sin embargo, es importante para como los modificadores son aplicados
## (lo cual verás más abajo)...
## Cuantificando - `?`, `+`, `*` y `**`.
@@ -1612,7 +1612,7 @@ so 'ac' ~~ / a b c /; # `False`
so 'ac' ~~ / a b? c /; # `True`, la "b" coincidió (apareció) 0 veces.
so 'abc' ~~ / a b? c /; # `True`, la "b" coincidió 1 vez.
-## ... Como debes saber, espacio en blancos son importante porque
+## ... Como debes saber, espacio en blancos son importante porque
## determinan en que parte del regexp es el objetivo del modificador:
so 'def' ~~ / a b c? /; # `False`. Solamente la `c` es opcional
so 'def' ~~ / a b? c /; # `False`. Espacio en blanco no es significante
@@ -1642,7 +1642,7 @@ so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (rangos infinitos no son un problem
## - `<[]>` - Clases de carácteres
## Las clases de carácteres son equivalentes a las clases `[]` de PCRE,
-## pero usan una sintaxis de Perl 6:
+## pero usan una sintaxis de Raku:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
## Puedes usar rangos:
@@ -1663,7 +1663,7 @@ so 'foo' ~~ / <-[ f o ]> + /; # False
## ... y componerlos:
so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (cualquier letra excepto f y o)
so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letra excepto f and o)
-so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
+so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
# parte de la izquierda)
```
@@ -1671,7 +1671,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
```perl6
## Grupo: Puedes agrupar partes de tu regexp con `[]`.
-## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
+## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
so 'abc' ~~ / a [ b ] c /; # `True`. El agrupamiento no hace casi nada
so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## La línea anterior returna `True`.
@@ -1680,15 +1680,15 @@ so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## Pero esto no va demasiado lejos, porque no podemos actualmente obtener
## devuelta el patrón que coincidió.
-## Captura: Podemos actualmente *capturar* los resultados del regexp,
+## Captura: Podemos actualmente *capturar* los resultados del regexp,
## usando paréntesis.
so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (usando `so`
# aquí, `$/` más abajo)
-## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
+## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
### nuestra objeto `Match` está disponible en la variable `$/`:
-say $/; # Imprimirá algo extraño (explicaremos luego) o
- # "Nil" si nada coincidió
+say $/; # Imprimirá algo extraño (explicaremos luego) o
+ # "Nil" si nada coincidió
## Como dijimos anteriormente, un objeto Match tiene indexación de array:
say $/[0]; #=> 「ABC」 「ABC」
@@ -1696,15 +1696,15 @@ say $/[0]; #=> 「ABC」 「ABC」
# Aquí, tenemos un array de ellos.
say $0; # Lo mismo que lo anterior.
-## Nuestra captura es `$0` porque es la primera y única captura en el
-## regexp. Podrías estarte preguntando porque un array y la respuesta es
+## Nuestra captura es `$0` porque es la primera y única captura en el
+## regexp. Podrías estarte preguntando porque un array y la respuesta es
## simple: Algunas capturas (indezadas usando `$0`, `$/[0]` o una nombrada)
## será un array si y solo si puedes tener más de un elemento.
## (Así que, con `*`, `+` y `**` (cualquiera los operandos), pero no con `?`).
## Usemos algunos ejemplos para ver como funciona:
## Nota: Pusimos A B C entre comillas para demostrar que el espacio en blanco
-## entre ellos no es significante. Si queremos que el espacio en blanco
+## entre ellos no es significante. Si queremos que el espacio en blanco
## *sea* significante, podemos utilizar el modificador `:sigspace`.
so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # `True`
say $/[0]; #=> 「ABC」
@@ -1718,22 +1718,22 @@ say $0.WHAT; #=> (Array)
# Un cuantificador específico siempre capturará un Array,
# puede ser un rango o un valor específico (hasta 1).
-## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
-## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
+## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
+## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
## para este código:
'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /;
say $/[0].Str; #=> hello~
say $/[0][0].Str; #=> ~
-## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
-## texto, números enteros o arrays sino que solo contiene objetos Match.
-## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
-## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
+## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
+## texto, números enteros o arrays sino que solo contiene objetos Match.
+## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
+## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
## para accesar un array.
say $/[0].list.perl; #=> (Match.new(...),).list
# Podemos ver que es una lista de objetos Match.
- # Estos contienen un montón de información: dónde la
- # coincidencia comenzó o terminó, el "ast"
+ # Estos contienen un montón de información: dónde la
+ # coincidencia comenzó o terminó, el "ast"
# (chequea las acciones más abajo), etc.
# Verás capturas nombradas más abajo con las gramáticas.
@@ -1743,9 +1743,9 @@ so 'abc' ~~ / a [ b | y ] c /; # `True`. o "b" o "y".
so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## La diferencia entre este `|` y el otro al que estás acustombrado es LTM.
-## LTM significa "Longest Token Matching", traducido libremente como
+## LTM significa "Longest Token Matching", traducido libremente como
## "Coincidencia de Token Más Larga". Esto significa que el motor ("engine")
-## siempre intentará coindidir tanto como sea posible en la cadena de texto.
+## siempre intentará coindidir tanto como sea posible en la cadena de texto.
## Básicamente, intentará el patrón más largo que concuerde con el regexp.
'foo' ~~ / fo | foo /; # `foo` porque es más largo.
## Para decidir cual parte es la "más larga", primero separa el regex en
@@ -1759,19 +1759,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## anteriores, aserciones de código, y otras cosas que tradicionalmente no pueden
## ser representadas por regexes normales.
##
-## Entonces, todas las alternativas se intentan al mismo tiempo, y la
+## Entonces, todas las alternativas se intentan al mismo tiempo, y la
## más larga gana.
## Ejemplos:
## DECLARATIVO | PROCEDIMENTAL
/ 'foo' \d+ [ <subrule1> || <subrule2> ] /;
## DECLARATIVO (grupos anidados no son un problema)
/ \s* [ \w & b ] [ c | d ] /;
-## Sin embargo, las clausuras y la recursión (de regexes nombrados)
+## Sin embargo, las clausuras y la recursión (de regexes nombrados)
## son procedimentales.
## ... Hay más reglas complicadas, como la especifidad (los literales ganan
## son las clases de caracteres)
+
-## Nota: la primera coincidencia `or` todavía existen, pero ahora se
+## Nota: la primera coincidencia `or` todavía existen, pero ahora se
## deletrea `||`
'foo' ~~ / fo || foo /; # `fo` ahora.
```
@@ -1779,19 +1779,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## Extra: la subrutina MAIN
```perl6
-## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Perl 6
-## directamente. Es realmente poderosa porque Perl 6 actualmente parsea
-## los argumentos y los pasas a la subrutina. También maneja argumentos
+## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Raku
+## directamente. Es realmente poderosa porque Raku actualmente parsea
+## los argumentos y los pasas a la subrutina. También maneja argumentos
## nombrados (`--foo`) y hasta autogenerará un `--help`.
sub MAIN($nombre) { say "¡Hola, $nombre!" }
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl <nombre>
-## Y dado que una subrutina regular en Perl 6, puedes tener múltiples
+## Y dado que una subrutina regular en Raku, puedes tener múltiples
## despachos:
-## (usando un "Bool" por un argumento nombrado para que podamos hacer
+## (usando un "Bool" por un argumento nombrado para que podamos hacer
## `--replace` a cambio de `--replace=1`)
subset File of Str where *.IO.d; # convierte a un objeto IO para chequear si
# un archivo existe
@@ -1800,7 +1800,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl [--replace] add <key> <value>
## t.pl remove <key>
@@ -1814,7 +1814,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
### Lista de cosas
```perl6
-## Consideramos que por ahora ya sabes lo básico de Perl 6.
+## Consideramos que por ahora ya sabes lo básico de Raku.
## Esta sección es solo para listar algunas operaciones comunes
## las cuales no están en la "parte principal" del tutorial.
@@ -1825,13 +1825,13 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## (los cuales representan los números -1, 0 o +1).
1 <=> 4; # comparación de orden para caracteres numéricos
'a' leg 'b'; # comparación de orden para cadenas de texto
-$obj eqv $obj2; # comparación de orden usando la semántica eqv
+$obj eqv $obj2; # comparación de orden usando la semántica eqv
## * Ordenación genérica
3 before 4; # True
'b' after 'a'; # True
-## * Operador (por defecto) de circuito corto
+## * Operador (por defecto) de circuito corto
## Al igual que `or` y `||`, pero devuelve el primer valor *defined*
## (definido):
say Any // Nil // 0 // 5; #=> 0
@@ -1843,9 +1843,9 @@ say True ^^ False; #=> True
## * Flip Flop
## Los operadores flip flop (`ff` y `fff`, equivalente a `..`/`...` en P5)
## son operadores que toman dos predicados para evalualarlos:
-## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
+## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
## son `True` hasta que su lado derecho devuelve `True`.
-## Como los rangos, tu puedes excluir la iteración cuando se convierte en
+## Como los rangos, tu puedes excluir la iteración cuando se convierte en
## `True`/`False` usando `^` en cualquier lado.
## Comencemos con un ejemplo:
for <well met young hero we shall meet later> {
@@ -1861,25 +1861,25 @@ for <well met young hero we shall meet later> {
}
## Esto imprimirá "young hero we shall meet" (exluyendo "met"):
## el flip-flop comenzará devolviendo `True` cuando primero encuentra "met"
-## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
+## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
## hasta que ve "meet", lo cual es cuando comenzará devolviendo `False`.
## La diferencia entre `ff` (al estilo de awk) y `fff` (al estilo de sed)
-## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
+## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
## a `True`, y puede returnar a `False` inmediamente (*excepto* que será
-## `True` por la iteración con la cual coincidió). Por lo contrario,
-## `fff` esperará por la próxima iteración para intentar su lado
+## `True` por la iteración con la cual coincidió). Por lo contrario,
+## `fff` esperará por la próxima iteración para intentar su lado
## derecho, una vez que su lado izquierdo ha cambiado:
.say if 'B' ff 'B' for <A B C B A>; #=> B B
# porque el lado derecho se puso a prueba
# directamente (y returnó `True`).
# Las "B"s se imprimen dadó que coincidió
- # en ese momento (returnó a `False`
+ # en ese momento (returnó a `False`
# inmediatamente).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
# El lado derecho no se puso a prueba
# hasta que `$_` se convirtió en "C"
- # (y por lo tanto no coincidió
+ # (y por lo tanto no coincidió
# inmediamente).
## Un flip-flop puede cambiar estado cuantas veces se necesite:
@@ -1901,35 +1901,35 @@ for (1, 3, 60, 3, 40, 60) { # Nota: los paréntesis son superfluos aquí
## que no pasará la primera vez:
for <a b c> {
.say if * ^ff *; # el flip-flop es `True` y nunca returna a `False`,
- # pero el `^` lo hace *que no se ejecute* en la
+ # pero el `^` lo hace *que no se ejecute* en la
# primera iteración
#=> b c
}
-## - `===` es la identidad de valor y usa `.WHICH`
+## - `===` es la identidad de valor y usa `.WHICH`
## en los objetos para compararlos.
-## - `=:=` es la identidad de contenedor y usa `VAR()`
+## - `=:=` es la identidad de contenedor y usa `VAR()`
## en los objetos para compararlos.
```
Si quieres ir más allá de lo que se muestra aquí, puedes:
- - Leer la [documentación de Perl 6](https://docs.perl6.org/). Esto es un recurso
- grandioso acerca de Perl 6. Si estás buscando por algo en particular, usa la
+ - Leer la [documentación de Raku](https://docs.raku.org/). Esto es un recurso
+ grandioso acerca de Raku. Si estás buscando por algo en particular, usa la
barra de búsquedas. Esto te dará un menú de todas las páginas concernientes
a tu término de búsqueda (¡Es mucho mejor que usar Google para encontrar
- documentos acerca de Perl 6!)
- - Leer el [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). Este es
- un gran recurso de fragmentos de código de Perl 6 y explicaciones. Si la documentación
+ documentos acerca de Raku!)
+ - Leer el [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). Este es
+ un gran recurso de fragmentos de código de Raku y explicaciones. Si la documentación
no describe algo lo suficientemente bien, puedes encontrar información más detallada
aquí. Esta información puede ser un poquito más antigua pero hay muchos ejemplos y
- explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
- el lenguaje fue declarado estable y Perl 6.c fue lanzado.
- - Unirte a `#perl6` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
- - Chequear la [fuente de las funciones y clases de Perl 6
- ](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo está principalmente
- escrito en Perl 6 (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
- subconjunto de Perl 6 que es más fácil de implementar y optimizar).
- - Leer [documentos acerca del diseño del lenguaje](http://design.perl6.org).
+ explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
+ el lenguaje fue declarado estable y Raku.c fue lanzado.
+ - Unirte a `#raku` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
+ - Chequear la [fuente de las funciones y clases de Raku
+ ](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo está principalmente
+ escrito en Raku (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
+ subconjunto de Raku que es más fácil de implementar y optimizar).
+ - Leer [documentos acerca del diseño del lenguaje](http://design.raku.org).
Estos explican P6 desde la perspectiva de un implementador, lo cual es bastante
interesante.
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
index 22e3c532..60af1913 100644
--- a/es-es/swift-es.html.markdown
+++ b/es-es/swift-es.html.markdown
@@ -11,7 +11,7 @@ lang: es-es
filename: learnswift-es.swift
---
-Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
+Swift es un lenguaje de programación para el desarrollo en iOS y macOS creado
por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
de desarrolladores de Apple.
diff --git a/es-es/typescript-es.html.markdown b/es-es/typescript-es.html.markdown
index c42da4a4..fbe1290b 100644
--- a/es-es/typescript-es.html.markdown
+++ b/es-es/typescript-es.html.markdown
@@ -12,7 +12,7 @@ TypeScript es un lenguaje cuyo objetivo es facilitar el desarrollo de aplicacion
TypeScript añade conceptos comunes como clases, módulos, interfaces, genéricos y (opcionalmente) tipeo estático a JavaScript.
Es un superset de JavaScript: todo el código JavaScript es código válido en TypeScript de manera que se puede integrar fácilmente a cualquier proyecto . El compilador TypeScript emite JavaScript.
-Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript/).
+Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript-es/).
Para probar el compilador de TypeScript, diríjase al [Área de Pruebas] (http://www.typescriptlang.org/Playground) donde podrá tipear código, y ver como se auto-completa al tiempo que ve el código emitido JavaScript.
diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown
index 52c60182..84a5844f 100644
--- a/fi-fi/ruby-fi.html.markdown
+++ b/fi-fi/ruby-fi.html.markdown
@@ -605,4 +605,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas
-- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti
+- [Try Ruby](https://try.ruby-lang.org/) - Rubyn perusteet interaktiivisesti
diff --git a/fortran95.html.markdown b/fortran95.html.markdown
index c256bb38..5fa8ca88 100644
--- a/fortran95.html.markdown
+++ b/fortran95.html.markdown
@@ -443,6 +443,7 @@ end module fruity
For more information on Fortran:
+ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
++ [Fortran-lang Organization](https://fortran-lang.org/)
+ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
+ [fortranwiki.org](http://fortranwiki.org)
+ [www.fortran90.org/](http://www.fortran90.org)
diff --git a/fr-fr/asymptotic-notation-fr.html.markdown b/fr-fr/asymptotic-notation-fr.html.markdown
index 491dc3c4..fb0a8220 100644
--- a/fr-fr/asymptotic-notation-fr.html.markdown
+++ b/fr-fr/asymptotic-notation-fr.html.markdown
@@ -67,21 +67,21 @@ f(n) = 3log n + 100
g(n) = log n
```
-Est-ce que `f(n)` O(g(n))?
-Est-ce que `3 log n + 100` O(log n)?
+Est-ce que `f(n)` est égal à O(g(n))?
+Est-ce que `3 log n + 100` est égal à O(log n)?
Regardons maintenant la définition de Big-O.
```
3log n + 100 <= c * log n
```
-Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
+Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
```
3log n + 100 <= 150 * log n, n > 2 (Indéfini avec n = 1)
```
-Oui ! La définition de Big-O a été satisfaite, donc `f(n)` is O(g(n)).
+Oui ! La définition de Big-O a été satisfaite, donc `f(n)` est égal à O(g(n)).
*Exemple 2*
@@ -90,15 +90,15 @@ f(n) = 3*n^2
g(n) = n
```
-Est-ce que `f(n)` O(g(n))?
-Est-ce que `3 * n^2` O(n)?
+Est-ce que `f(n)` est égal à O(g(n))?
+Est-ce que `3 * n^2` est égal à O(n)?
Regardons de nouveau la définition de Big-O.
```
3 * n^2 <= c * n
```
-Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > <sub>0</sub>?
+Existe t-il une paire de constantes c, n<sub>0</sub> qui satisfait cela pour tout n > n<sub>0</sub>?
Non, il n'en existe pas. `f(n)` n'est pas égal à O(g(n)).
### Big-Omega
diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown
index 0e764d7d..58d01e6a 100644
--- a/fr-fr/bash-fr.html.markdown
+++ b/fr-fr/bash-fr.html.markdown
@@ -17,7 +17,7 @@ lang: fr-fr
---
Bash est le nom du shell UNIX, qui était aussi distribué avec le système
-d’exploitation GNU et est le shell par défaut sur Linux et Mac OS X.
+d’exploitation GNU et est le shell par défaut sur Linux et macOS.
Presque tous les exemples ci-dessous peuvent être écrits dans un script shell
ou exécutés directement dans le terminal.
diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown
index 863162f7..c8603756 100644
--- a/fr-fr/c++-fr.html.markdown
+++ b/fr-fr/c++-fr.html.markdown
@@ -69,11 +69,11 @@ void func(); // fonction qui ne prend aucun argument
// En C
void func(); // fonction qui peut prendre n'importe quel nombre d'arguments
-// Utilise nullptr au lieu de NULL in C++
+// Utilise nullptr au lieu de NULL en C++
int* ip = nullptr;
// Les en-têtes standards du C sont disponibles en C++,
-// mais son préfixés avec "c" et n'ont pas de suffixe .h
+// mais sont préfixés avec "c" et n'ont pas de suffixe .h
#include <cstdio>
int main()
@@ -722,7 +722,7 @@ catch (...)
// gestion d'un fichier C :
void faireQuelqueChoseAvecUnFichier(const char* nomDuFichier)
{
- // Pour commencer, supposns que rien ne peut échouer.
+ // Pour commencer, supposons que rien ne peut échouer.
FILE* fh = fopen(nomDuFichier, "r"); // Ouvre le fichier en lecture
diff --git a/fr-fr/crystal-fr.html.markdown b/fr-fr/crystal-fr.html.markdown
index 2bb17fc5..02ab3b2b 100644
--- a/fr-fr/crystal-fr.html.markdown
+++ b/fr-fr/crystal-fr.html.markdown
@@ -350,7 +350,7 @@ sum 3, 4 #=> 7
sum sum(3, 4), 5 #=> 12
# yield
-# Toutes les méthodes on un paramètre optionel et implicite de type bloc
+# Toutes les méthodes ont un paramètre optionel et implicite de type bloc
# il peut être appelé avec le mot clé 'yield'
def surround
puts '{'
diff --git a/fr-fr/elisp-fr.html.markdown b/fr-fr/elisp-fr.html.markdown
index 2e0a9408..f9bf589c 100644
--- a/fr-fr/elisp-fr.html.markdown
+++ b/fr-fr/elisp-fr.html.markdown
@@ -328,9 +328,9 @@ lang: fr-fr
(other-window 1))
;; Cette fonction introduit `re-search-forward' : au lieu de chercher
-;; la chaîne "Bonjour", nous cherchons un "pattern" en utilisant une
-;; "expression régulière" (le préfixe "re-" signifie "regular
-;; expression").
+;; la chaîne "Bonjour", nous cherchons un motif ("pattern" en anglais)
+;; en utilisant une "expression régulière" (le préfixe "re-" signifie
+;; "regular expression").
;; L'expression régulière est "Bonjour \\(.+\\)!" et se lit :
;; la chaîne "Bonjour ", et
@@ -343,7 +343,7 @@ lang: fr-fr
(boldify-names)
-;; `add-text-properties' ajoute des propriétés textuelles telle que
+;; `add-text-properties' ajoute des propriétés textuelles telles que
;; des "faces" (une "face" définit la fonte, la couleur, la taille et
;; d'autres propriétés du texte.)
@@ -361,7 +361,7 @@ lang: fr-fr
;; Pour lire en ligne une introduction à Emacs Lisp :
;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
-;; Merci à ces personnes pour leurs retours et suggetions :
+;; Merci à ces personnes pour leurs retours et suggestions :
;; - Wes Hardaker
;; - notbob
;; - Kevin Montuori
diff --git a/fr-fr/fsharp-fr.html.markdown b/fr-fr/fsharp-fr.html.markdown
index 3fd41676..dda9945f 100644
--- a/fr-fr/fsharp-fr.html.markdown
+++ b/fr-fr/fsharp-fr.html.markdown
@@ -140,7 +140,8 @@ module FunctionExamples =
let a = add 1 2
printfn "1+2 = %i" a
- // partial application to "bake in" parameters (?)
+ // application partielle des paramètres (curryfication ou "currying" en anglais)
+ // add42 est une nouvelle fonction qui ne prend plus qu'un paramètre
let add42 = add 42
let b = add42 1
printfn "42+1 = %i" b
diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown
index d6c68343..b72200d6 100644
--- a/fr-fr/java-fr.html.markdown
+++ b/fr-fr/java-fr.html.markdown
@@ -31,7 +31,7 @@ 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:
+ * Attributs principaux :
*
* @author Nom (et information de contact comme l'email) de(s) auteur(s).
* @version Version actuelle du programme.
@@ -82,7 +82,7 @@ public class JavaFr {
*/
// Utilisez Scanner pour lire l'entrée
- // Nécessite: import java.util.Scanner;
+ // Nécessite : import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
// Lire une chaîne de caractères
@@ -160,7 +160,7 @@ public class JavaFr {
// 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
+ // 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
@@ -203,7 +203,7 @@ public class JavaFr {
// BigDecimal - entier immuable et positif de taille arbitraire
//
- // BigDecimal comprend deux parties: une entier 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.
//
@@ -240,13 +240,13 @@ public class JavaFr {
// 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.
+ // 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é
+ // 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.
@@ -255,7 +255,7 @@ public class JavaFr {
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.
+ // 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.
@@ -276,7 +276,7 @@ public class JavaFr {
// #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().
+ // Affiche : Or you may prefer String.format().
// Tableau
// La taille du tableau doit être précisée à l'instantiation
@@ -419,7 +419,7 @@ public class JavaFr {
System.out.println("fooFor Value: " + fooFor);
// Fin d'une boucle for avec un label
- outer:
+ outer :
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (i == 5 && j ==5) {
@@ -433,9 +433,9 @@ public class JavaFr {
// 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
+ // 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
@@ -511,7 +511,7 @@ public class JavaFr {
// Convert Integer To String
Integer.toString(123); // retourne un object String correspondant à"123"
- // Pour les autres conversions, référer vous aux classes suivantes:
+ // Pour les autres conversions, référer vous aux classes suivantes :
// Double
// Long
// String
@@ -537,7 +537,7 @@ public class JavaFr {
// 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:
+ // manière simple. Généralement, on utilise la forme suivante :
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
COUNTRIES.add("DENMARK");
@@ -566,7 +566,7 @@ public class JavaFr {
// Cependant, il est préférable de séparer les
// classes dans des fichiers différents.
-// Syntaxe de déclaration des classes:
+// 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.
@@ -575,11 +575,11 @@ public class JavaFr {
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-
+ 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
+ String name; // default : Uniquement accesible depuis ce package
static String className; // Variable de classe static
// Bloc static
@@ -595,7 +595,7 @@ class Bicycle {
// 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):
+ // appelant le constructeur de la classe mère (voir héritage) :
// this(1, 50, 5, "Bontrager");
gear = 1;
cadence = 50;
@@ -665,7 +665,7 @@ class PennyFarthing extends Bicycle {
// 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/
+ // out : http://docs.oracle.com/javase/tutorial/java/annotations/
@Override
public void setGear(int gear) {
this.gear = 0;
@@ -719,7 +719,7 @@ public class Fruit implements Edible, Digestible {
}
// En Java, on peut hériter uniquement d'une classe mais on peut implémenter
-// plusieurs interfaces:
+// plusieurs interfaces :
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
@@ -734,7 +734,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// Classes abstraites
-// Syntaxe de déclaration:
+// 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
@@ -758,7 +758,7 @@ public abstract class Animal
public void eat()
{
System.out.println("I am an animal and I am Eating.");
- // Note: On peut accéder à une variable privée ici.
+ // Note : On peut accéder à une variable privée ici.
age = 30;
}
@@ -790,7 +790,7 @@ class Dog extends Animal
// age = 30; ==> ERREUR! age est privé et n'est pas accesible.
}
- // NOTE: Vous obtiendrez une erreur si vous utilisé l'annotation @Override
+ // 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) :
@@ -828,7 +828,7 @@ public final class SaberToothedCat extends Animal
// Méthodes final
public abstract class Mammal()
{
- // Syntaxe:
+ // 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
@@ -846,13 +846,13 @@ public abstract class Mammal()
// 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:
+// jours de la semaine :
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
-// On l'utilise ainsi:
+// On l'utilise ainsi :
public class EnumTest {
// On utilise notre énumération
Day day;
@@ -889,7 +889,7 @@ public class EnumTest {
// 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):
+// Vous pouvez en savoir plus ici (en anglais) :
//https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
```
@@ -899,7 +899,7 @@ public class EnumTest {
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**:
+**Guides officiels d'Oracle** :
* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html)
@@ -918,7 +918,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
-* Nouvelles fonctionnalités Java 8:
+* 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)
@@ -928,7 +928,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques.
* [Codingbat.com](http://codingbat.com/java)
-**Livres**:
+**Livres** :
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
index 7aad2da8..186859ab 100644
--- a/fr-fr/javascript-fr.html.markdown
+++ b/fr-fr/javascript-fr.html.markdown
@@ -1,12 +1,12 @@
---
language: javascript
contributors:
- - ['Leigh Brenecki', 'https://leigh.net.au']
- - ['Ariel Krakowski', 'http://www.learneroo.com']
+ - ["Leigh Brenecki", "https://leigh.net.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
filename: javascript-fr.js
translators:
- - ['@nbrugneaux', 'https://nicolasbrugneaux.me']
- - ['Michel Antoine', 'https://github.com/antoin-m']
+ - ["@nbrugneaux", "https://nicolasbrugneaux.me"]
+ - ["Michel Antoine", "https://github.com/antoin-m"]
lang: fr-fr
---
@@ -328,13 +328,15 @@ for (var x in person){
}
description; // = "Paul Ken 18 "
-// *ES6:* La boucle for...of permet d'itérer sur les propriétés d'un objet
-var description = "";
-var person = {fname:"Paul", lname:"Ken", age:18};
-for (var x of person){
- description += x + " ";
+// *ES6:* La boucle for...of permet de parcourir un objet itérable
+// (ce qui inclut les objets Array, Map, Set, String, ... Mais pas un objet littéral !)
+let myPets = "";
+const pets = ["cat", "dog", "hamster", "hedgehog"];
+for (let pet of pets){ //`(const pet of pets)` est également possible
+
+ myPets += pet + " ";
}
-description; // = "Paul Ken 18 "
+myPets; // = 'cat dog hamster hedgehog '
// && est le "et" logique, || est le "ou" logique
if (house.size === 'big' && house.colour === 'blue'){
diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown
index 26c2546a..1fd22883 100644
--- a/fr-fr/markdown-fr.html.markdown
+++ b/fr-fr/markdown-fr.html.markdown
@@ -178,8 +178,8 @@ Vous pouvez également utiliser des sous-listes.
1. Item un
2. Item deux
3. Item trois
-* Sub-item
-* Sub-item
+ * Sub-item
+ * Sub-item
4. Item quatre
```
@@ -230,7 +230,7 @@ En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques.
```
Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
-va utiliser une coloration syntaxique pour le langage indiqué après les ```.
+va utiliser une coloration syntaxique pour le langage indiqué après les <code>```</code>.
## Ligne Horizontale
@@ -267,13 +267,13 @@ Markdown supporte aussi les liens relatifs.
Les liens de références sont eux aussi disponibles en Markdown.
-```md
-[Cliquez ici][link1] pour plus d'information!
-[Regardez aussi par ici][foobar] si vous voulez.
+<div class="highlight"><code><pre>
+[<span class="nv">Cliquez ici</span>][<span class="ss">link1</span>] pour plus d'information!
+[<span class="nv">Regardez aussi par ici</span>][<span class="ss">foobar</span>] si vous voulez.
-[link1]: http://test.com/ "Cool!"
-[foobar]: http://foobar.biz/ "Génial!"
-```
+[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
+[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Génial!"</span>
+</pre></code></div>
Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou
absent. Les références peuvent être placées où vous voulez dans le document et
@@ -282,11 +282,11 @@ les identifiants peuvent être n'importe quoi tant qu'ils sont uniques.
Il y a également le nommage implicite qui transforme le texte du lien en
identifiant.
-```md
-[Ceci][] est un lien.
+<div class="highlight"><code><pre>
+[<span class="nv">Ceci</span>][] est un lien.
-[ceci]: http://ceciestunlien.com/
-```
+[<span class="nv">Ceci</span>]:<span class="sx">http://ceciestunlien.com/</span>
+</pre></code></div>
Mais ce n'est pas beaucoup utilisé.
@@ -302,11 +302,11 @@ d'un point d'exclamation!
Là aussi, on peut utiliser le mode "références".
-```md
-![Ceci est l'attribut ALT de l'image][monimage]
+<div class="highlight"><code><pre>
+![<span class="nv">Ceci est l'attribut ALT de l'image</span>][<span class="ss">monimage</span>]
-[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
-```
+[<span class="nv">monimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"si vous voulez un titre, c'est ici."</span>
+</pre></code></div>
## Divers
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index fbe1741e..191cdfb6 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -10,7 +10,7 @@ filename: LearnObjectiveC-fr.m
lang: fr-fr
---
-L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
+L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations macOS et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
```objective-c
// Les commentaires sur une seule ligne commencent par //
@@ -30,7 +30,7 @@ ceci
#import <Foundation/Foundation.h>
#import "MaClasse.h"
-// Si vous activez les modules dans les projets iOS >= 7 ou Mac OS X >= 10.9
+// Si vous activez les modules dans les projets iOS >= 7 ou OS X >= 10.9
// dans Xcode 5, vous pouvez importer les frameworks comme cela :
@import Foundation;
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
index e737b7aa..e073bcf5 100644
--- a/fr-fr/perl-fr.html.markdown
+++ b/fr-fr/perl-fr.html.markdown
@@ -10,9 +10,9 @@ translators:
- ["Matteo Taroli", "http://www.matteotaroli.be"]
lang: fr-fr
---
-Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+Perl est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
-Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+Perl fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
```perl
diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown
new file mode 100644
index 00000000..50a4ea30
--- /dev/null
+++ b/fr-fr/set-theory-fr.html.markdown
@@ -0,0 +1,134 @@
+```
+---
+category: tool
+lang: fr-fr
+name: Set theory
+contributors:
+ - ["kieutrang", "https://github.com/kieutrang1729"]
+---
+La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés.
+
+* Un ensemble est une collection d'éléments disjoints.
+
+## Symboles de base
+
+### Opérateurs
+* l'opérateur réunion, `∪`, signifie "ou" ;
+* l'opérateur intersection, `∩`, signifie "et" ;
+* l'opérateur différence, `\`, signifie "sans", (lire "A moins B") ;
+* l'opérateur complémentaire, `'`, signifie "le complémentaire de" ;
+* l'opérateur croix, `×`, signifie "le produit cartésien de".
+
+### Autres symboles
+* le symbole deux-points, `:`, signifie "tel que" ;
+* le symbole d'appartenance, `∈`, signifie "appartient à" ;
+* le symbole sous-ensemble, `⊆`, signifie "est un sous-ensemble de" ;
+* le symbole sous-ensemble propre, `⊂`, signifie "est un sous-ensemble de mais n'est pas égal à".
+
+### Ensembles importants
+* `∅`, l'ensemble vide, c'est-à-dire l'ensemble ne contenant aucun élément ;
+* `ℕ`, l'ensemble des nombres naturels ;
+* `ℤ`, l'ensemble des entiers ;
+* `ℚ`, l'ensemble des nombres rationnels ;
+* `ℝ`, l'ensemble des nombres réels.
+
+Quelques mise en gardes sur les ensembles definis ci-dessus:
+1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble.
+2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas.
+
+
+### Cardinalité
+
+La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'éléments dans l'ensemble. L'opérateur de cardinalité s'écrit, `| ... |`.
+Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
+
+### L'ensemble vide
+* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
+* il n'y a qu'un seul ensemble vide.
+* l'ensemble vide est sous-ensemble de tout ensemble.
+* la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`.
+
+## Notation ensembliste
+
+### Définition par extension
+
+Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`.
+
+Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers.
+
+### Définition par comprehension
+
+C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple,
+
+```
+A = { x : x est une voyelle } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+On peut même appliquer une fonction au sujet, e.g.
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## Relations
+
+### Appartenance
+
+* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
+* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
+
+### Égalité
+
+* On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`.
+* Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
+* Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
+* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`.
+
+## Ensemble puissance
+* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`.
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## Opérations ensemblistes
+### Réunion
+La réunion de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à `A` ou à `B`.
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### Intersection
+L'intersection de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments qui appartient à la fois à `A` et à `B`.
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### Différence
+La différence de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de l'ensemble `A` qui n'appartient pas à `B`.
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### Différence symétrique
+Le différence symétrique de deux ensembles `A` et `B` est l'ensemble contenant tous les éléments de `A` et `B` qui n'apparaissent pas dans leur intersection.
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Produit cartésien
+Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont la première élément appartient à `A` et la deuxième à `B`.
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
+
+```
diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown
index 52d34650..8a761f61 100644
--- a/fr-fr/typescript-fr.html.markdown
+++ b/fr-fr/typescript-fr.html.markdown
@@ -12,7 +12,7 @@ TypeScript est un langage visant à faciliter le développement d'applications l
TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript.
C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur.
-Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/).
+Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript-fr/).
Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript.
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 064a9fdd..c140d6b1 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -633,6 +633,6 @@ module NetCompatibilityExamples =
## More Information
-For more demonstrations of F#, go to the [Try F#](http://www.tryfsharp.org/Learn) site, or my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
+For more demonstrations of F#, go to my [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) series.
-Read more about F# at [fsharp.org](http://fsharp.org/).
+Read more about F# at [fsharp.org](http://fsharp.org/) and [dotnet's F# page](https://dotnet.microsoft.com/languages/fsharp).
diff --git a/git.html.markdown b/git.html.markdown
index aa96c90a..a40ef01b 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -82,12 +82,12 @@ pushed to other repositories, or not!
### Branch
A branch is essentially a pointer to the last commit you made. As you go on
-committing, this pointer will automatically update to point the latest commit.
+committing, this pointer will automatically update to point to the latest commit.
### Tag
A tag is a mark on specific point in history. Typically people use this
-functionality to mark release points (v1.0, and so on)
+functionality to mark release points (v1.0, and so on).
### HEAD and head (component of .git dir)
diff --git a/go.html.markdown b/go.html.markdown
index b727e59d..5a9214b0 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -33,7 +33,7 @@ Go comes with a good standard library and a sizeable community.
line comment */
/* A build tag is a line comment starting with // +build
- and can be execute by go build -tags="foo bar" command.
+ and can be executed by go build -tags="foo bar" command.
Build tags are placed before the package clause near or at the top of the file
followed by a blank line or other line comments. */
// +build prod, dev, test
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 89ca973a..0d589c10 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -184,7 +184,7 @@ class Foo {
Methods with optional parameters
*/
-// A mthod can have default values for parameters
+// A method can have default values for parameters
def say(msg = 'Hello', name = 'world') {
"$msg $name!"
}
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 1cc79ec9..328da5c9 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -61,6 +61,8 @@ not False -- True
-- A string is a list of characters
['H', 'e', 'l', 'l', 'o'] -- "Hello"
+
+-- Lists can be indexed with the `!!` operator followed by an index
"This is a string" !! 0 -- 'T'
diff --git a/hd-hd/json-hd.html.markdown b/hd-hd/json-hd.html.markdown
new file mode 100644
index 00000000..dd1657cd
--- /dev/null
+++ b/hd-hd/json-hd.html.markdown
@@ -0,0 +1,86 @@
+---
+language: json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+ - ["Michael Neth", "https://github.com/infernocloud"]
+ - ["Athanasios Emmanouilidis", "https://github.com/athanasiosem"]
+translators:
+ - ["Namami Shanker", "https://github.com/NamamiShanker"]
+lang: hd-hd
+---
+
+जैसन(JSON) इस अत्यंत सरल डाटा-इंटरचेंज फॉर्मेट है| जैसा [json.org](https://json.org) कहती है, ये इंसानो के पढ़ने और लिखने के लिए भी आसान है और और मशीन के लिए इसे पार्स और उतपन्न करना भी बेहद सरल है|
+
+जैसन(JSON) के एक अंश को इनमे से किसी एक का प्रतिनिधित्व(represent) करना चाहिए:
+
+* एक नाम/वैल्यू जोड़े का कलेक्शन (`{ }`). कई दूसरी भाषाओ में इसे ऑब्जेक्ट, रिकॉर्ड, स्ट्रक्ट, डिक्शनरी, हैश टेबल, कीड लिस्ट, या असोसिएटिव ऐरे का भी नाम दिया जाता है|
+* वैल्यूज की एक व्यवस्थित लिस्ट(ordered list) (`[ ]`). कई दूसरी भाषाओ में इसे ऐरे, वेक्टर, लिस्ट, या सीक्वेंस भी कहा जाता है|
+
+जैसन(JSON) अपने शुद्धतम रूप में कमैंट्स सपोर्ट नहीं करता है, पर ज़्यादातर पारसर C स्टाइल की कमैंट्स (`//`, `/* */`) सपोर्ट करेंगे| कुछ पारसर्स अंतिम कॉमा भी स्वीकार करते हैं (जब आप किसी ऐरे के अंतिम एलिमेंट या किसी ऑब्जेक्ट की अंतिम प्रॉपर्टी के बार एक कॉमा छोड़ देते हैं), पर ऐसी गलतियों से बचना चाहिए बेहतर कम्पेटिबिलिटी के लिए|
+
+ ये उदाहरण १०० प्रतिशत मान्य जैसन(JSON) है| किस्मत से, जैसन(JSON) डॉक्यूमेंट को पढ़ के ही आप इसे समझ जायेंगे|
+
+समर्थित डाटा टाइप्स:
+
+* स्ट्रिंग्स(Strings): `"नमस्ते"`, `"\"एक उद्धरण\""`, `"\u0abe"`, `"नयी पंक्ति|\n"`
+* अंक(Numbers): `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* ऑब्जेक्ट्स(Objects): `{ "की": "मूल्य" }`
+* ऐरे(Arrays): `["बहुत सारे मूल्य"]`
+* विविध(Miscellaneous): `true`, `false`, `null`
+
+```json
+{
+ "की": "मूल्य",
+
+ "की": "हमेशा दोहरे उद्धरण चिह्नों में संलग्न होना चाहिए",
+ "अंक": 0,
+ "स्ट्रिंग्स": "नमस्ते| यूनिकोड और \"एस्केप\" सीक्वेंस की अनुमति है|",
+ "बूलियन है?": true,
+ "शून्यता ": null,
+
+ "बड़े अंक": 1.2e+100,
+
+ "ऑब्जेक्ट्स": {
+ "टिप्पणी": "आपके जैसन(JSON) ऑब्जेक्ट को ज़्यादातर ऑब्जेक्ट से ही ढांचा मिलेगा|",
+
+ "ऐरे": [0, 1, 2, 3, "ऐरे में आप कुछ भी रख सकते हैं|", 5],
+
+ "एक और ऑब्जेक्ट": {
+ "टिप्पणी": "आप एक ऑब्जेक्ट दूसरे ऑब्जेक्ट के अंदर रख सकते हैं| ये बहुत उपयोगी होता है|"
+ }
+ },
+
+ "फ़र्ज़ी": [
+ {
+ "पोटेशियम के स्रोत": ["केला"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "नव"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "वैकल्पिक शैली": {
+ "टिप्पणी": "ये देखिये!"
+ , "कॉमा के स्थान": "से फरक नहीं पड़ता, अगर आपने उसे अगली की से पहले लगाया है तो वो मान्य है|"
+ , "एक और टिप्पणी": "कितनी अच्छी बात है"
+ },
+
+
+
+ "खाली स्थान": "से फरक नहीं पड़ता",
+
+
+
+ "ये काफी छोटा था :>": "और ख़तम| अब आपको जैसन(JSON) के बारे में सब कुछ पता है|"
+}
+```
+
+## और जानकारी के लिए
+
+* [JSON.org](https://json.org) पूरा जैसन(JSON) फ्लोचार्ट के माध्यम से खूबसूरत तरह से दर्शित|
+* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) जैसन(JSON) का एक संक्षिप्त परिचय|
diff --git a/id-id/ruby-id.html.markdown b/id-id/ruby-id.html.markdown
index 28135da1..a94aefb2 100644
--- a/id-id/ruby-id.html.markdown
+++ b/id-id/ruby-id.html.markdown
@@ -619,4 +619,4 @@ Sesuatu.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas.
-- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser.
diff --git a/images/solidity/copy-address.png b/images/solidity/copy-address.png
new file mode 100644
index 00000000..b0a698ee
--- /dev/null
+++ b/images/solidity/copy-address.png
Binary files differ
diff --git a/images/solidity/metamask-kovan.png b/images/solidity/metamask-kovan.png
new file mode 100644
index 00000000..c5d5ae4b
--- /dev/null
+++ b/images/solidity/metamask-kovan.png
Binary files differ
diff --git a/images/solidity/remix-add-token.png b/images/solidity/remix-add-token.png
new file mode 100644
index 00000000..a1c2f1ac
--- /dev/null
+++ b/images/solidity/remix-add-token.png
Binary files differ
diff --git a/images/solidity/remix-choose-file.png b/images/solidity/remix-choose-file.png
new file mode 100644
index 00000000..6a16afc8
--- /dev/null
+++ b/images/solidity/remix-choose-file.png
Binary files differ
diff --git a/images/solidity/remix-compile.png b/images/solidity/remix-compile.png
new file mode 100644
index 00000000..7afd0d7c
--- /dev/null
+++ b/images/solidity/remix-compile.png
Binary files differ
diff --git a/images/solidity/remix-deploy.png b/images/solidity/remix-deploy.png
new file mode 100644
index 00000000..7f855f48
--- /dev/null
+++ b/images/solidity/remix-deploy.png
Binary files differ
diff --git a/images/solidity/remix-interact.png b/images/solidity/remix-interact.png
new file mode 100644
index 00000000..79f89ae9
--- /dev/null
+++ b/images/solidity/remix-interact.png
Binary files differ
diff --git a/images/solidity/remix-solidity.png b/images/solidity/remix-solidity.png
new file mode 100644
index 00000000..f4500967
--- /dev/null
+++ b/images/solidity/remix-solidity.png
Binary files differ
diff --git a/images/solidity/remix-testnet.png b/images/solidity/remix-testnet.png
new file mode 100644
index 00000000..6cc845ea
--- /dev/null
+++ b/images/solidity/remix-testnet.png
Binary files differ
diff --git a/images/solidity/send-link.png b/images/solidity/send-link.png
new file mode 100644
index 00000000..1cd9188e
--- /dev/null
+++ b/images/solidity/send-link.png
Binary files differ
diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown
index cfe58f30..dd55b84c 100644
--- a/it-it/bash-it.html.markdown
+++ b/it-it/bash-it.html.markdown
@@ -22,7 +22,7 @@ translators:
lang: it-it
---
-Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X.
+Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e macOS.
Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell.
[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown
index 295bf28a..1f466cce 100644
--- a/it-it/ruby-it.html.markdown
+++ b/it-it/ruby-it.html.markdown
@@ -650,4 +650,4 @@ Something.new.qux #=> 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una passata [edizione libera](http://ruby-doc.com/docs/ProgrammingRuby/) è disponibile online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser.
diff --git a/it-it/sql-it.html.markdown b/it-it/sql-it.html.markdown
new file mode 100644
index 00000000..7db2eec1
--- /dev/null
+++ b/it-it/sql-it.html.markdown
@@ -0,0 +1,112 @@
+---
+language: SQL
+filename: learnsql-it.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["Christian Grasso", "https://grasso.io"]
+lang: it-it
+---
+
+Structured Query Language (SQL) è un linguaggio standard ISO per la creazione e la gestione
+di database organizzati in un insieme di tabelle. Le diverse implementazioni aggiungono
+spesso le proprie estensioni al linguaggio base ([confronto tra le diverse implementazioni](http://troels.arvin.dk/db/rdbms/))
+
+Le diverse implementazioni forniscono inoltre un prompt per inserire in modo interattivo i comandi
+o eseguire il contenuto di uno script.
+
+I comandi di seguito lavorano sul [database di esempio MySQL](https://dev.mysql.com/doc/employee/en/)
+disponibile su [GitHub](https://github.com/datacharmer/test_db). I file .sql contengono liste di comandi
+simili a quelli mostrati di seguito, che creano e riempiono delle tabelle con dati di un'azienda fittizia.
+Il comando per eseguire questi script può variare in base all'implementazione in uso.
+
+
+```sql
+-- I commenti iniziano con due trattini. Ogni comando va terminato con il punto e virgola
+
+-- SQL è case-insensitive per quanto riguarda i comandi; in genere si
+-- preferisce scriverli in maiuscolo per distinguerli dai nomi di
+-- database, tabelle e colonne
+
+-- Crea ed elimina un database. I nomi di database e tabelle sono case-sensitive
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- Lista dei database disponibili
+SHOW DATABASES;
+
+-- Attiva uno specifico database
+USE employees;
+
+-- Seleziona tutte le righe e le colonne dalla tabella departments
+SELECT * FROM departments;
+
+-- Seleziona tutte le righe della tabella departments,
+-- ma solo le colonne dept_no e dept_name.
+-- È possibile suddividere i comandi su più righe.
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- Seleziona solo le prime 5 righe della tabella departments.
+SELECT * FROM departments LIMIT 5;
+
+-- Ottiene la colonna dept_name della tabella departments
+-- solo per le righe il cui valore di dept_name contiene 'en'.
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- Ottiene tutte le colonne della tabella departments
+-- solo per le righe che hanno un dept_name formato da una 'S'
+-- seguita esattamente da altri 4 caratteri
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- Seleziona i valori di title dalla tabella titles eliminando i duplicati
+SELECT DISTINCT title FROM titles;
+
+-- Come sopra, ma i valori sono ordinati alfabeticamente
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- Mostra il numero di righe della tabella departments
+SELECT COUNT(*) FROM departments;
+
+-- Mostra il numero di righe della tabella departments
+-- il cui valore di dept_name contiene 'en'.
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+-- Un JOIN tra più tabelle: la tabella titles contiene gli
+-- incarichi lavorativi associati ad un certo numero di impiegato.
+-- Con il JOIN utilizziamo il numero di impiegato per ottenere
+-- le informazioni ad esso associate nella tabella employees.
+-- (Inoltre selezioniamo solo le prime 10 righe)
+
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- Mostra tutte le tabelle di tutti i database.
+-- Spesso le implementazioni forniscono degli shortcut per questo comando
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- Crea una tabella tablename1, con due colonne, per il database in uso.
+-- Per le colonne specifichiamo il tipo di dato (stringa di max 20 caratteri)
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- Inserisce una riga nella tabella tablename1. I valori devono essere
+-- appropriati per la definizione della tabella
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+-- In tablename1, modifica il valore di fname a 'John'
+-- in tutte le righe che hanno come lname 'Mutt'.
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+-- Elimina tutte le righe di tablename1
+-- il cui lname inizia per 'M'.
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- Elimina tutte le righe della tabella tablename1
+DELETE FROM tablename1;
+
+-- Elimina la tabella tablename1
+DROP TABLE tablename1;
+```
diff --git a/it-it/zfs-it.html.markdown b/it-it/zfs-it.html.markdown
new file mode 100644
index 00000000..c1307e67
--- /dev/null
+++ b/it-it/zfs-it.html.markdown
@@ -0,0 +1,361 @@
+---
+category: tool
+tool: zfs
+contributors:
+ - ["sarlalian", "http://github.com/sarlalian"]
+translators:
+ - ["Christian Grasso","https://grasso.io"]
+filename: LearnZfs-it.txt
+lang: it-it
+---
+
+
+[ZFS](http://open-zfs.org/wiki/Main_Page) è un sistema di storage che combina file system
+tradizionali e volume manager in un unico strumento. ZFS utilizza della terminologia
+specifica, diversa da quella usata da altri sistemi di storage, ma le sue funzioni lo
+rendono un ottimo tool per gli amministratori di sistema.
+
+
+## Concetti base di ZFS
+
+### Virtual Device
+
+Un VDEV è simile a un dispositivo gestito da una scheda RAID. Esistono diversi tipi di
+VDEV che offrono diversi vantaggi, tra cui ridondanza e velocità. In generale,
+i VDEV offrono una maggiore affidabilità rispetto alle schede RAID. Si sconsiglia di
+utilizzare ZFS insieme a RAID, poichè ZFS è fatto per gestire direttamente i dischi fisici.
+
+Tipi di VDEV:
+
+* stripe (disco singolo, senza ridondanza)
+* mirror (mirror su più dischi)
+* raidz
+ * raidz1 (parity a 1 disco, simile a RAID 5)
+ * raidz2 (parity a 2 dischi, simile a RAID 6)
+ * raidz3 (parity a 3 dischi)
+* disk
+* file (non consigliato in production poichè aggiunge un ulteriore filesystem)
+
+I dati vengono distribuiti tra tutti i VDEV presenti nella Storage Pool, per cui un maggior
+numero di VDEV aumenta le operazioni al secondo (IOPS).
+
+### Storage Pool
+
+Le Storage Pool di ZFS sono un'astrazione del livello inferiore (VDEV) e consentono di
+separare il filesystem visibile agli utenti dal layout reale dei dischi.
+
+### Dataset
+
+I dataset sono simili ai filesystem tradizionali, ma con molte più funzioni che rendono
+vantaggioso l'utilizzo di ZFS. I dataset supportano il [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write)
+gli snapshot, la gestione delle quota, compressione e deduplicazione.
+
+
+### Limiti
+
+Una directory può contenere fino a 2^48 file, ognuno dei quali di 16 exabyte.
+Una storage pool può contenere fino a 256 zettabyte (2^78), e può essere distribuita
+tra 2^64 dispositivi. Un singolo host può avere fino a 2^64 storage pool.
+
+
+## Comandi
+
+### Storage Pool
+
+Azioni:
+
+* List (lista delle pool)
+* Status (stato)
+* Destroy (rimozione)
+* Get/Set (lettura/modifica proprietà)
+
+Lista delle zpool
+
+```bash
+# Crea una zpool raidz
+$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+
+# Lista delle zpool
+$ zpool list
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+
+# Informazioni dettagliate su una zpool
+$ zpool list -v zroot
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75%
+```
+
+Stato delle zpool
+
+```bash
+# Informazioni sullo stato delle zpool
+$ zpool status
+ pool: zroot
+ state: ONLINE
+ scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+
+# "Scrubbing" (correzione degli errori)
+$ zpool scrub zroot
+$ zpool status -v zroot
+ pool: zroot
+ state: ONLINE
+ scan: scrub in progress since Thu Oct 15 16:59:14 2015
+ 39.1M scanned out of 106G at 1.45M/s, 20h47m to go
+ 0 repaired, 0.04% done
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+```
+
+Proprietà delle zpool
+
+```bash
+
+# Proprietà di una zpool (gestite dal sistema o dall'utente)
+$ zpool get all zroot
+NAME PROPERTY VALUE SOURCE
+zroot size 141G -
+zroot capacity 75% -
+zroot altroot - default
+zroot health ONLINE -
+...
+
+# Modifica di una proprietà
+$ zpool set comment="Dati" zroot
+$ zpool get comment
+NAME PROPERTY VALUE SOURCE
+tank comment - default
+zroot comment Dati local
+```
+
+Rimozione di una zpool
+
+```bash
+$ zpool destroy test
+```
+
+
+### Dataset
+
+Azioni:
+
+* Create
+* List
+* Rename
+* Delete
+* Get/Set (proprietà)
+
+Creazione dataset
+
+```bash
+# Crea un dataset
+$ zfs create tank/root/data
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+
+# Crea un sottodataset
+$ zfs create tank/root/data/stuff
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+
+
+# Crea un volume
+$ zfs create -V zroot/win_vm
+$ zfs list zroot/win_vm
+NAME USED AVAIL REFER MOUNTPOINT
+tank/win_vm 4.13G 17.9G 64K -
+```
+
+Lista dei dataset
+
+```bash
+# Lista dei dataset
+$ zfs list
+NAME USED AVAIL REFER MOUNTPOINT
+zroot 106G 30.8G 144K none
+zroot/ROOT 18.5G 30.8G 144K none
+zroot/ROOT/10.1 8K 30.8G 9.63G /
+zroot/ROOT/default 18.5G 30.8G 11.2G /
+zroot/backup 5.23G 30.8G 144K none
+zroot/home 288K 30.8G 144K none
+...
+
+# Informazioni su un dataset
+$ zfs list zroot/home
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home 288K 30.8G 144K none
+
+# Lista degli snapshot
+$ zfs list -t snapshot
+zroot@daily-2015-10-15 0 - 144K -
+zroot/ROOT@daily-2015-10-15 0 - 144K -
+zroot/ROOT/default@daily-2015-10-15 0 - 24.2G -
+zroot/tmp@daily-2015-10-15 124K - 708M -
+zroot/usr@daily-2015-10-15 0 - 144K -
+zroot/home@daily-2015-10-15 0 - 11.9G -
+zroot/var@daily-2015-10-15 704K - 1.42G -
+zroot/var/log@daily-2015-10-15 192K - 828K -
+zroot/var/tmp@daily-2015-10-15 0 - 152K -
+```
+
+Rinominare un dataset
+
+```bash
+$ zfs rename tank/root/home tank/root/old_home
+$ zfs rename tank/root/new_home tank/root/home
+```
+
+Eliminare un dataset
+
+```bash
+# I dataset non possono essere eliminati se hanno degli snapshot
+$ zfs destroy tank/root/home
+```
+
+Lettura/modifica proprietà
+
+```bash
+# Tutte le proprietà di un dataset
+$ zfs get all zroot/usr/home │157 # Create Volume
+NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm
+zroot/home type filesystem - │159 $ zfs list zroot/win_vm
+zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT
+zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K -
+zroot/home available 94.1G - │162 ```
+zroot/home referenced 11.9G - │163
+zroot/home mounted yes -
+...
+
+# Proprietà specifica
+$ zfs get compression zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home compression off default
+
+# Modifica di una proprietà
+$ zfs set compression=gzip-9 mypool/lamb
+
+# Specifiche proprietà per tutti i dataset
+$ zfs list -o name,quota,reservation
+NAME QUOTA RESERV
+zroot none none
+zroot/ROOT none none
+zroot/ROOT/default none none
+zroot/tmp none none
+zroot/usr none none
+zroot/home none none
+zroot/var none none
+...
+```
+
+
+### Snapshot
+
+Gli snapshot sono una delle funzioni più importanti di ZFS:
+
+* Lo spazio occupato è la differenza tra il filesystem e l'ultimo snapshot
+* Il tempo di creazione è di pochi secondi
+* Possono essere ripristinati alla velocità di scrittura del disco
+* Possono essere automatizzati molto semplicemente
+
+Azioni:
+
+* Create
+* Delete
+* Rename
+* Access
+* Send / Receive
+* Clone
+
+
+Creazione di uno snapshot
+
+```bash
+# Crea uno snapshot di un singolo dataset
+zfs snapshot tank/home/sarlalian@now
+
+# Crea uno snapshot di un dataset e dei suoi sottodataset
+$ zfs snapshot -r tank/home@now
+$ zfs list -t snapshot
+NAME USED AVAIL REFER MOUNTPOINT
+tank/home@now 0 - 26K -
+tank/home/sarlalian@now 0 - 259M -
+tank/home/alice@now 0 - 156M -
+tank/home/bob@now 0 - 156M -
+...
+```
+
+Eliminazione di uno snapshot
+
+```bash
+# Elimina uno snapshot
+$ zfs destroy tank/home/sarlalian@now
+
+# Elimina uno snapshot ricorsivamente
+$ zfs destroy -r tank/home/sarlalian@now
+
+```
+
+Rinominare uno snapshot
+
+```bash
+$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today
+$ zfs rename tank/home/sarlalian@now today
+
+$ zfs rename -r tank/home@now @yesterday
+```
+
+Accedere ad uno snapshot
+
+```bash
+# Utilizzare il comando cd come per una directory
+$ cd /home/.zfs/snapshot/
+```
+
+Invio e ricezione
+
+```bash
+# Backup di uno snapshot su un file
+$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz
+
+# Invia uno snapshot ad un altro dataset
+$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian
+
+# Invia uno snapshot ad un host remoto
+$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian'
+
+# Invia l'intero dataset e i suoi snapshot ad un host remoto
+$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home'
+```
+
+Clonare gli snapshot
+
+```bash
+# Clona uno snapshot
+$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new
+
+# Rende il clone indipendente dallo snapshot originale
+$ zfs promote tank/home/sarlalian_new
+```
+
+### Letture aggiuntive (in inglese)
+
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html)
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html)
+* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning)
+* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide)
diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown
index c80b4d4c..18e7d1b8 100644
--- a/ja-jp/python-jp.html.markdown
+++ b/ja-jp/python-jp.html.markdown
@@ -160,8 +160,8 @@ len("This is a string") # => 16
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
-# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。
-f"{name} is {len(name)} characters long."
+# 基本的に、任意のPythonの文を中括弧に書くことができ、それは文字列で出力されます。
+f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
# None はオブジェクトです(大文字からです!)
None # => None
@@ -191,7 +191,7 @@ print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
print("Hello, World", end="!") # => Hello, World!
# コンソールから入力を得るための簡単な例
-input_string_var = input("Enter some data: ") # 入力を文字列として返します
+input_string_var = input("Enter some data: ") # 入力を文字列として返します。
# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。
# Pythonでは変数の宣言は存在せず、代入のみです。
@@ -201,7 +201,7 @@ some_var # => 5
# 代入されていない変数へのアクセスは例外を引き起こします。
# 例外の取り扱いについては、3章の制御の流れをご確認ください。
-some_unknown_var # NameError を送出します
+some_unknown_var # NameError を送出します。
# ifは式として使用できます。
# C言語の「?:(三項演算子)」に対応する例:
@@ -228,7 +228,7 @@ li[0] # => 1
li[-1] # => 3
# 範囲外の要素を参照すると IndexError になります。
-li[4] # IndexError が発生します
+li[4] # IndexError が発生します。
# スライス構文により範囲を参照できます。
# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。
@@ -238,28 +238,28 @@ li[2:] # => [4, 3]
# 末尾を取り除いたリスト
li[:3] # => [1, 2, 4]
# 1つ飛ばしで選択する
-li[::2] # =>[1, 4]
+li[::2] # => [1, 4]
# 反転したリストを得る
li[::-1] # => [3, 4, 2, 1]
# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。
# li[start:end:step]
# スライスにより、深いコピーを1階層分行うことができます。
-li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。
+li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) は False になる。
# "del"によりリストから任意の要素を削除できます。
del li[2] # li は [1, 2, 3] になりました。
# "remove"で最初に出現する要素を削除できます。
li.remove(2) # li は [1, 3] になりました。
-li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。
+li.remove(2) # 2 はリストの中に存在しないので、 ValueError が発生します。
# 要素を好きなところに挿入できます。
li.insert(1, 2) # li は [1, 2, 3] に戻りました。
# "index"で引数の要素が最初に出現する場所のインデックスを得られます。
li.index(2) # => 1
-li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。
+li.index(4) # 4 はリストの中に存在しないので、 ValueError が発生します。
# リスト同士を足すこともできます。
# Note: li と other_li の値は変更されません。
@@ -295,11 +295,11 @@ tup[:2] # => (1, 2)
# タプルやリストから複数の変数に代入することができます。
a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。
# 拡張記法もあります。
-a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。
+a, *b, c = (1, 2, 3, 4) # a は 1、 b は [2, 3]、c は 4 になります。
# 括弧を作成しなくてもデフォルトでタプルが作成されます。
d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。
# 2つの変数を交換するのがどれほど簡単か見てみましょう。
-e, d = d, e # d は 5 、 e は e になります。
+e, d = d, e # d は 5、 e は 4 になります。
# 辞書はマップ(キーと値の組み合わせ)を保存できます。
@@ -373,7 +373,7 @@ valid_set = {(1,), 1}
filled_set = some_set
filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。
# 集合は重複した要素を持ちません。
-filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。
+filled_set.add(5) # 以前の {1, 2, 3, 4, 5} のままです。
# & により、集合同士の共通部分が得られます。
other_set = {3, 4, 5, 6}
@@ -453,7 +453,7 @@ for i in range(4, 8):
"""
"range(lower, upper, step)" は、lower の数値から upper の数値までが、
-step 刻みで表現されるiterableを返します
+step 刻みで表現されるiterableを返します。
step が与えられない場合、デフォルトは1になります。
出力:
4
@@ -552,7 +552,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
def keyword_args(**kwargs):
return kwargs
-# 何が起こるか、試してみましょう
+# 何が起こるか、試してみましょう。
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
@@ -591,7 +591,7 @@ x = 5
def set_x(num):
- # ローカル変数の x はグローバル変数の x とは異なります
+ # ローカル変数の x はグローバル変数の x とは異なります。
x = num # => 43
print(x) # => 43
@@ -783,7 +783,7 @@ if __name__ == '__main__':
from human import Human
-# 親クラスを子クラスのパラメータとして指定します
+# 親クラスを子クラスのパラメータとして指定します。
class Superhero(Human):
# もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。
diff --git a/ja-jp/vim-jp.html.markdown b/ja-jp/vim-jp.html.markdown
new file mode 100644
index 00000000..1d9867ca
--- /dev/null
+++ b/ja-jp/vim-jp.html.markdown
@@ -0,0 +1,275 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Kota Kato", "https://github.com/kato-k"]
+filename: LearnVim-jp.txt
+lang: ja-jp
+---
+
+
+[Vim](http://www.vim.org)
+(Vi IMproved) は、Unix用の人気なエディタである vi のクローンです。
+これは、速度と生産性を高めることを目的に設計されたエディタであり、
+ほとんどのUnix互換のシステムに組込まれています。
+ファイル内の特定の位置に移動したり、素早く編集したりするための多数のキーバインドを持ちます。
+
+`vimtutor`はあなたに`Vim`の使い方を教える素晴しいアプリケーションです。
+Vimパッケージのインストール時に一緒に付属しますので、
+コマンドラインで「vimtutor」を実行するだけで、このチュートリアルを開けるはずです。
+これは、`vim`の全ての主要機能を説明します。
+
+訳注) 日本語で`vimtutor`を利用するには、「vimtutor ja」を実行しなければならない場合があります。
+
+## 基本のVim操作
+
+```
+ vim <filename> # <filename>をVimで開く
+ :help <topic> # <topic>についての組み込みドキュメントが存在する場合、
+ # それを開く
+ :q # Vimを終了する
+ :w # 編集中のファイルを保存する
+ :wq # ファイルを保存して、Vimを終了する
+ ZZ # ファイルを保存して、Vimを終了する。:xと同様
+ :q! # ファイルを保存せずにVimを終了する
+ # :q を ! *強制的に* 実行するため保存せずにVimが終了します
+ ZQ # ファイルを保存せずにVimを終了する
+ :x # 変更点がある時、ファイルを保存してVimを終了する
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # 左に一文字移動
+ j # 一行下に移動
+ k # 一行上に移動
+ l # 右に一文字移動
+
+ Ctrl+B # ウィンドウを一画面上に移動
+ Ctrl+F # ウィンドウを一画面下に移動
+ Ctrl+D # ウィンドウを半画面上に移動
+ Ctrl+U # ウィンドウを半画面下に移動
+
+ # 行内を移動する
+
+ 0 # 行頭に移動
+ $ # 行末に移動
+ ^ # 行の初めの非空白文字に移動
+
+ # テキストの検索
+
+ /word # カーソル以降に出現する全ての一致をハイライト
+ ?word # カーソル以前に出現する全ての一致をハイライト
+ n # カーソルを次の一致に移動
+ N # カーソルを前の一致に移動
+
+ :%s/foo/bar/g # 全ての行について「foo」を「bar」に置換
+ :s/foo/bar/g # 現在の行について「foo」を「bar」に置換
+ :%s/\n/\r/g # 改行文字の置換
+
+ # 文字への移動
+
+ f<character> # 前方の<character>に移動する
+ t<character> # 前方の<character>の一文字前に移動する
+
+ # 例
+ f< # 前方の < に移動
+ t< # 前方の < の一文字前に移動
+
+ # 単語ごとの移動
+
+ w # 一単語前に移動
+ b # 一単語後ろに移動
+ e # 現在の単語の後部に移動
+
+ # 移動のためのキーバインド
+
+ gg # ファイルの先頭に移動
+ G # ファイルの最後に移動
+ :NUM # ファイルのNUM行に移動(NUMは任意の行数)
+ H # カーソルをウィンドウ上部に移動
+ M # カーソルをウィンドウ中央に移動
+ L # カーソルをウィンドウ下部に移動
+```
+
+## ヘルプドキュメント:
+
+Vimには`:help <topic>`でアクセスできるヘルプドキュメントが組込まれています。
+例えば、`:help navigation`はカーソルを移動する方法についてのドキュメントを開きます。
+
+`:help`はオプション無しでも利用できます。
+これにより、Vimにより親しみやすくすることを目的としたデフォルトのヘルプダイアログが開かれます。
+
+## モード:
+
+Vimは**モード**の概念に基づいています。
+
+- Command Mode - Vimはこのモードで起動し、移動とコマンドの実行に使われます
+- Insert Mode - ファイルに変更を加えるのに使われます
+- Visual Mode - テキストをハイライトしてオペレータを適用するために使われます
+- Ex Mode - コマンドを入力するための「:」プロンプトで使われます
+
+```
+ i # カーソル位置の前からInsert Modeに入る
+ a # カーソル位置の後ろからInsert Modeに入る
+ v # Visual Modeに入る
+ : # Ex Modeに入る
+ <esc> # 現在のモードからコマンドモードに「脱出」
+
+ # テキストのコピーと貼り付け
+
+ y # 選択された対象をヤンクする
+ yy # 現在の行をヤンクする
+ d # 選択された対象を削除する
+ dd # 現在の行を削除する
+ p # ヤンクされたテキストをカーソルの後ろに貼り付ける
+ P # ヤンクされたテキストをのカーソルの前に貼り付ける
+ x # カーソル位置の文字を削除
+```
+
+## Vimの「文法」
+
+Vimの操作は「動詞・修飾子・名詞」形式のコマンドとして考えることができます。
+
+- 動詞 - 動作
+- 修飾子 - 動作の実行方法
+- 名詞 - 動作が作用するオブジェクト
+
+「動詞・修飾子・名詞」関するいくつかの重要な例:
+
+```
+ # '動詞'
+
+ d # 削除
+ c # 変更
+ y # ヤンク (コピー)
+ v # ビジュアル選択
+
+ # '修飾子'
+
+ i # 内部
+ a # 周り
+ NUM # 回数 (NUMは任意の番号)
+ f # 任意の一文字まで
+ t # 任意の一文字の手前まで
+ / # カーソル以降の任意の文字列まで
+ ? # カーソル以前の任意の文字列まで
+
+ # '名詞'
+
+ w # 単語
+ s # 文
+ p # 段落
+ b # ブロック
+
+ # 「文」の例
+
+ d2w # 削除 2 単語 (2単語を削除)
+ cis # 変更 内部 文 (文の内部を変更)
+ yip # ヤンク 内部 段落 (段落の内部をヤンク)
+ ct< # 変更 手前 < (<の手前まで変更)
+ d$ # 削除 行末まで (行末まで削除)
+```
+
+## いくつかのショートカットと小技
+
+ <!--TODO: Add more!-->
+```
+ > # 選択部を1ブロックインデント
+ < # 選択部を1ブロックデインデント
+ :earlier 15m # ファイルを15分前の状態に戻す
+ :later 15m # 上記のコマンドの逆
+ ddp # 連続する行を入れ替え
+ . # 前回の動作を繰り返す
+ :w !sudo tee % # 編集中のファイルを管理者として保存
+ :set syntax=c # 「C言語」のシンタックスハイライトを利用する
+ :sort # 全ての行をソートする
+ :sort! # 全ての行を降順にソートする
+ :sort u # 全ての行をソートして重複を削除する
+ ~ # 選択部分の大文字小文字を入れ替える
+ u # 選択部分を小文字にする
+ U # 選択部分を大文字にする
+ J # 現在の行と次の行を結合する
+
+ # テキストの折り畳み
+ zf # 選択したテキストを折り畳む
+ zo # 折り畳みを開く
+ zc # 折り畳みを閉じる
+ zR # 全ての折り畳みを開く
+ zM # 全ての折り畳みを閉じる
+```
+
+## マクロ
+
+マクロは基本的に記録可能なアクションです。
+マクロの記録を開始すると、記録を停止するまで**全て**の操作とコマンドが記録されます。
+マクロを呼びだすと、まったく同じ一連の操作とコマンドが文書に再度適用されます。
+
+```
+ qa # 「a」という名前のマクロの記録を開始する
+ q # 記録を停止する
+ @a # 「a」マクロを再生する
+```
+
+### ~/.vimrc の設定
+
+ファイル.vimrcは起動時にVimの設定として利用されます
+
+次は~/.vimrcファイルのサンプルです
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" 自動インデントなどを利用するために、ファイル名からファイルタイプを決定する
+filetype indent plugin on
+
+" シンタックスハイライトを利用する
+syntax on
+
+" より良いコマンドライン補完
+set wildmenu
+
+" 大文字を利用しない場合、検索で大文字・小文字を区別しない
+set ignorecase
+set smartcase
+
+" ファイル固有のインデントが有効でない場合、現在行のインデントを継続する
+set autoindent
+
+" 行番号の表示
+set number
+
+" インデントに関するオプション
+
+" TAB文字の幅
+set tabstop=4
+
+" 編集中TABキーを押した際の挙動
+set softtabstop=4
+
+" << >> を利用した再インデント時のスペースの数
+set shiftwidth=4
+
+" TABキーをスペースに変換する
+set expandtab
+
+" 賢いTAB機能を有効にする
+set smarttab
+```
+
+### 参考文献
+
+[Vim | Home](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/janet.html.markdown b/janet.html.markdown
new file mode 100644
index 00000000..ec53b018
--- /dev/null
+++ b/janet.html.markdown
@@ -0,0 +1,328 @@
+---
+language: Janet
+filename: learnJanet.janet
+contributors:
+ - ["John Gabriele", "http://www.unexpected-vortices.com/"]
+---
+
+[Janet](https://janet-lang.org/) is a Lisp-like (Clojure-like),
+lexically-scoped, dynamically-typed, garbage-collected, C-based, high-level
+language. The entire language (core library, interpreter, compiler, assembler,
+PEG) is about 300-500 kB and should run on many constrained systems.
+
+I encourage you to try out the code snippets below in the Janet
+repl (either by [installing Janet](https://janet-lang.org/docs/index.html),
+or else by using the repl embedded in the Janet homepage).
+
+As we only have a scant *y* minutes, we'll survey the basics here and
+leave the remaining details for the manual. So please, keep your arms and
+legs inside the vehicle at all times, and on with the scenic tour!
+
+```janet
+# A comment.
+
+# Some literal values.
+true
+false
+nil
+
+# Typical style for symbols (identifiers-for / names-of things).
+do-stuff
+pants-on-fire!
+foo->bar # Evidently for converting foos to bars.
+fully-charged?
+_ # Usually used as a dummy variable.
+
+# Keywords are like symbols that start with a colon, are treated like
+# constants, and are typically used as map keys or pieces of syntax in
+# macros.
+:a
+:some-val
+
+# Numbers #####################################################################
+5
+1e3 # => 1000
+1_000 # => 1000
+2e-03 # => 0.002
+0xff # => 255
+
+# You can specify a radix (base) like so:
+16rff # => 255 (same as 0xff)
+2r1101 # => 13
+
+# Some numbers in the math library:
+math/pi # => 3.14159
+math/e # => 2.71828
+
+# Strings #####################################################################
+"hello"
+"hey\tthere" # contains a tab
+
+# For multi-line strings, use one or more backticks. No escapes allowed.
+``a long
+multi-line
+string`` # => "a long\nmulti-line\nstring"
+
+# Strings and data structures in Janet come in two varieties: mutable and
+# immutable. The literal for the mutable variety is written with a `@` in
+# front of it.
+
+# A mutable string (aka "buffer").
+@"this"
+@`a multi-line
+one here`
+
+(string "con" "cat" "enate") # => "concatenate"
+
+# To get a substring:
+(string/slice "abcdefgh" 2 5) # => "cde"
+# To find a substring:
+(string/find "de" "abcdefgh") # => 3
+
+# See the string library for more (splitting, replacement, etc.)
+
+# Arrays and Tuples ###########################################################
+# Arrays are mutable, tuples are immutable.
+
+# Arrays (mutable)
+@(4 5 6)
+@[4 5 6]
+
+# Tuples (immutable)
+# Note that an open paren usually indicates a function call, so if you want a
+# literal tuple with parens, you need to "quote" it (with a starting single
+# quote mark).
+'(4 5 6)
+[4 5 6] # ... or just use square brackets.
+
+# Tables and Structs (AKA: "maps", "hashmaps", "dictionaries")
+@{:a 1 :b 2 :c 3} # table (mutable)
+{:a 1 :b 2 :c 3} # struct (immutable)
+
+# More about how to work with arrays/tuples and tables/structs below.
+
+# Bindings ####################################################################
+# ... or "Name Some Things!" (that is, bind a value to a symbol)
+(def x 4.7) # Define a constant, `x`.
+x # => 4.7
+(quote x) # => x (the symbol x)
+'x # => x (the symbol x (shorthand))
+(print x) # prints 4.7
+
+# Since we used `def`, can't change to what `x` refers:
+(set x 5.6) # Error, `x` is a constant.
+
+(var y 10)
+(set y 12) # Works, since `y` was made var.
+
+# Note that bindings are local to the scope they're called in. `let`
+# creates a local scope and makes some bindings all in one shot:
+(let [a 2
+ b 3]
+ (print "Hello from inside this local scope.")
+ (* a b)) # => 6
+
+# Destructuring is supported, both for arrays/tuples ...
+(def a ["foos" "bars" "moos"])
+(let [[s1 _ s2] a]
+ (print s1 s2)) # foosmoos
+
+# ... and for tables/structs.
+(def t {:a "ayy" :b "bee" :c "sea"})
+(let [{:a a :b b} t]
+ (print a b)) # ayybee
+
+# You can even destructure right in a `def`:
+(def [aa1 aa2] a)
+aa1 # => foos
+aa2 # => bars
+
+(def {:c body-of-water :b insect-friend} t)
+body-of-water # => sea
+insect-friend # => bee
+
+# Note that keywords evaluate to themselves, whereas symbols evaluate
+# to whatever value they're bound to (unless you quote them).
+
+# Operators ###################################################################
+# Janet supports the usual ensemble of operators.
+# +, -, *, /, and so on. Note:
+(/ 5 3) # => 1.66667
+(% 5 3) # => 2 (remainder)
+(- 5) # => -5 (or you can just write `-5`)
+
+(++ i) # increments
+(-- i) # decrements
+(+= i 3) # add 3 to `i`
+(*= i 3) # triple `i`
+# ... and so on for the other operations on numbers.
+
+# Comparison
+# = < > not= <= >=
+(< 2 7 12) # => true
+
+# Functions ###################################################################
+# Call them:
+(- 5 3) # => 2 (Yes, operators and functions work the same.)
+(math/sin (/ math/pi 2)) # => 1
+(range 5) # => @[0 1 2 3 4]
+
+# Create them:
+(defn mult-by-2
+ ``First line of docstring.
+
+ Some more of the docstring.
+
+ Possibly more!``
+ [x]
+ (print "Hi.")
+ (print "Will compute using: " x)
+ (* 2 x))
+
+(print (mult-by-2 6)) # => 12 (after printing "Hi" and so forth)
+
+# If you have a function named "main" in your file, `janet` will automatically
+# call it for you when you run the file.
+
+# Interactively read a function's docs from within the repl:
+(doc mult-by-2)
+
+# Note, functions have to be defined before they can be used in a function,
+# so if you design top-down, you'll need to write your functions from the
+# bottom of the file up.
+
+# You can make anonymous functions as well:
+(fn [x] (+ x x))
+(fn my-func [x] (+ x x)) # This one's less anonymous.
+
+# Use `do` to make some side-effecting calls and then evaluate to
+# the last form in the `do`:
+(def n (do
+ (print "hi")
+ (do-some-side-effecting 42)
+ 3))
+n # => 3
+
+# You might say that function bodies provide an "implicit do".
+
+# Operations on data structures ###############################################
+# (Making all these mutable so we can ... mutate them.)
+(def s @"Hello, World!")
+(def a @[:a :b :c :d :e])
+(def t @{:a 1 :b 2})
+
+(length s) # => 13
+(length a) # => 5
+(length t) # => 2
+
+# Getting values:
+(s 7) # => 87 (which is the code point for "W")
+(a 1) # => :b
+(t :a) # => 1
+(keys t) # => @[:a :b]
+(values t) # => @[1 2]
+
+# Changing values (for mutable data structures):
+(put s 2 87) # @"HeWlo, World!"
+(put a 2 :x) # @[:a :b :x :d :e]
+(put t :b 42) # @{:a 1 :b 42}
+
+# Adding & removing values (again, for mutable data structures):
+(buffer/push-string s "??") # @"HeWlo, World!??"
+(array/push a :f) # @[:a :b :x :d :e :f]
+(array/pop a) # => :f, and it's also removed from `a`.
+(put t :x 88) # @{:a 1 :b 42 :x 88}
+
+# See the manual for a wide variety of functions for working with
+# buffers/strings, arrays/tuples, and tables/struct.
+
+# Flow control ################################################################
+(if some-condition
+ 42
+ 38)
+
+# Only `nil` and `false` are falsey. Everything else is truthy.
+
+(if got-it?
+ 71) # No false-branch value. Returns `nil` if `got-it?` is falsey.
+
+(var i 10)
+(while (pos? i)
+ (print "... " i)
+ (-- i))
+# Now `i` is 0.
+
+# `case` compares the dispatch value to each of the options.
+(var x 2)
+(case x
+ 1 "won"
+ 2 "too"
+ 3 "tree"
+ "unknown") # => "too"
+
+# `cond` evaluates conditions until it gets a `true`.
+(set x 8)
+(cond
+ (= x 1) "won"
+ (= x 2) "too"
+ (< x 10) "tree"
+ "oof!") # => "tree"
+
+(when (avoided-wipeout?)
+ (do-side-effecty-thing 88)
+ (smell-the-roses)
+ (paint-fencepost-error))
+
+# Pattern matching.
+# `match` is like a high-powered switch expression. If you switch on a data
+# structure, it can look inside to try and match on its contents. For example,
+# matching on a table or struct:
+(def t {:a 1 :b 2 :c 3})
+(match t
+ {:yar v} (print "matches key :yar! " v)
+ {:moo v} (print "matches key :moo! " v)
+ {:c v} (print "matches key :c! " v)
+ _ (print "no match")) # => prints "matches key :c! 3"
+
+# Iterating ###################################################################
+# Iterate over an integer range:
+(for i 0 5
+ (print i)) # prints 0, 1, 2, 3, 4
+
+# There's also the more general `loop`:
+(loop [i :range [0 10] :when (even? i)]
+ (print i))
+
+# Loop over an array/tuple:
+(def words ["foo" "bar" "baz"])
+(each word words
+ (print word))
+
+# Loop over a table/struct:
+(def t {:a 1 :b 2})
+(eachp [k v] t # Loop over each pair in `t`.
+ (print k " --> " v))
+
+# Can also use `eachk` to loop over keys in a table or struct.
+
+# Functional programming ######################################################
+# You'll find many familiar old friends here.
+(filter even?
+ (map (fn [x]
+ (* x x))
+ (range 10))) # => @[0 4 16 36 64]
+
+(reduce + 0 (range 5)) # => 10
+
+# ...and lots more (see the API docs).
+
+# Errata ######################################################################
+(type a) # => the type of `a` (as a keyword)
+(describe a) # => a human-readable description of `a`
+(string/format "%j" a) # => Janet values, nicely-formatted
+```
+
+This tour didn't cover a number of other features such as modules, fibers,
+PEGs, macros, etc., but should give you a taste of what Janet is like. See
+the [Janet manual](https://janet-lang.org/docs/index.html) and the [Janet API
+docs](https://janet-lang.org/api/index.html) for more info.
diff --git a/java.html.markdown b/java.html.markdown
index 79769352..4be940be 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -510,10 +510,12 @@ public class LearnJava {
// toString returns this Object's string representation.
System.out.println("trek info: " + trek.toString());
+ } // End main method
+ private static class TestInitialization {
// Double Brace Initialization
- // The Java Language has no syntax for how to create static Collections
- // in an easy way. Usually you end up in the following way:
+ // Before Java 11, the Java Language had no syntax for how to create
+ // static Collections in an easy way. Usually you end up like this:
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
COUNTRIES.add("DENMARK");
@@ -521,10 +523,10 @@ public class LearnJava {
COUNTRIES.add("FINLAND");
}
- // But there's a nifty way to achieve the same thing in an
- // easier way, by using something that is called Double Brace
- // Initialization.
- private static final Set<String> COUNTRIES = new HashSet<String>() {{
+ // There's a nifty way to achieve the same thing,
+ // by using something that is called Double Brace Initialization.
+ private static final Set<String> COUNTRIES_DOUBLE_BRACE =
+ new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
@@ -535,8 +537,45 @@ public class LearnJava {
// is called when the anonymous inner class is created.
// This does not only work for Collections, it works for all
// non-final classes.
+
+
+ // Another option was to initialize the Collection from an array,
+ // using Arrays.asList() method:
+ private static final List<String> COUNTRIES_AS_LIST =
+ Arrays.asList("SWEDEN", "DENMARK", "NORWAY");
+ // This has one catch: the list we get is internally backed by the array,
+ // and since arrays can't change their size, the list backed by the array
+ // is not resizeable, which means we can't add new elements to it:
+ public static void main(String[] args) {
+ COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException!
+ // However, we can replace elements by index, just like in array:
+ COUNTRIES.set(1, "FINLAND");
+ System.out.println(COUNTRIES); // prints [SWEDEN, FINLAND, NORWAY]
+ }
+ // The resizing problem can be circumvented
+ // by creating another Collection from the List:
+ private static final Set<String> COUNTRIES_SET =
+ new HashSet<>(Arrays.asList("SWEDEN", "DENMARK", "NORWAY"));
+ // It's perfectly fine to add anything to the Set of COUNTRIES now.
+ } // End TestInitialization class
+
+ private static class TestJava11Initialization {
+ // Since Java 11, there is a convenient option to initialize Collections:
+ // Set.of() and List.of() methods.
+ private static final Set<String> COUNTRIES =
+ Set.of("SWEDEN", "DENMARK", "NORWAY");
+ // There is a massive catch, though: Lists and Sets initialized like this
+ // 1) are immutable
+ // 2) can't contain null elements (even check for null elements fails)!
+ public static void main(String[] args) {
+ COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException
+ COUNTRIES.remove("NORWAY"); // throws UnsupportedOperationException
+ COUNTRIES.contains(null); // throws NullPointerException
+ }
+ private static final Set<String> COUNTRIES_WITH_NULL =
+ Set.of("SWEDEN", null, "NORWAY"); // throws NullPointerException
- } // End main method
+ } // End TestJava11Initialization class
} // End LearnJava class
// You can include other, non-public outer-level classes in a .java file,
diff --git a/jquery.html.markdown b/jquery.html.markdown
index a1673c10..18077dca 100644
--- a/jquery.html.markdown
+++ b/jquery.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: jquery
contributors:
- ["Sawyer Charles", "https://github.com/xssc"]
+ - ["Devansh Patil", "https://github.com/subtra3t"]
filename: jquery.js
---
@@ -10,6 +11,7 @@ jQuery is a JavaScript library that helps you "do more, write less". It makes ma
Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/)
+**NOTE**: jQuery has fallen out of the limelight in recent years, since you can achieve the same thing with the vanilla DOM (Document Object Model) API. So the only thing it is used for is a couple of handy features, such as the [jQuery date picker](https://api.jqueryui.com/datepicker) (which actually has a standard, unlike the `<input type="date">` HTML element), and the obvious decrease in the code length.
```js
diff --git a/json.html.markdown b/json.html.markdown
index 3ec7a3af..1ccdb5cf 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -9,7 +9,7 @@ contributors:
- ["Athanasios Emmanouilidis", "https://github.com/athanasiosem"]
---
-JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
+JSON is an extremely simple data-interchange format. As [json.org](https://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
A piece of JSON must represent either:
@@ -80,6 +80,5 @@ Supported data types:
## Further Reading
-* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
-
+* [JSON.org](https://json.org) All of JSON beautifully explained using flowchart-like graphics.
* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON.
diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown
new file mode 100644
index 00000000..241caf5f
--- /dev/null
+++ b/jsonnet.html.markdown
@@ -0,0 +1,139 @@
+---
+language: jsonnet
+filename: learnjsonnet.jsonnet
+contributors:
+ - ["Huan Wang", "https://github.com/fredwangwang"]
+---
+
+Jsonnet is a powerful templating language for JSON. Any valid JSON
+document is a valid Jsonnet object. For an interactive demo/tutorial,
+click [here](https://jsonnet.org/learning/tutorial.html)
+
+```python
+// single line comment
+
+/*
+ multiline comment
+*/
+
+# as well as python style comment
+
+# define a variable.
+# Variables have no effect in the generated JSON without being used.
+local num1 = 1;
+local num2 = 1 + 1;
+local num3 = 5 - 2;
+local num4 = 9 % 5;
+local num5 = 10 / 2.0;
+# jsonnet is a lazy language, if a variable is not used, it is not evaluated.
+local num_runtime_error = 1 / 0;
+
+# fields are valid identifiers without quotes
+local obj1 = { a: 'letter a', B: 'letter B' };
+
+local arr1 = ['a', 'b', 'c'];
+
+# string literals use " or '.
+local str1 = 'a' + 'B';
+# multiline text literal in between |||
+# Each line must start with a white space.
+local str_multiline = |||
+ this is a
+ multiline string
+|||;
+# Python-compatible string formatting is available via %
+# When combined with ||| this can be used for templating text files.
+local str_templating = |||
+ %(f1)0.3f
+||| % { f1: 1.2345678 };
+assert str_templating == '1.235\n';
+
+# if b then e else e. The else branch is optional and defaults to null
+local var1 = if 3 < 2 then "YES";
+assert var1 == null;
+
+local obj2 = {
+ # variable defined inside the object ends with ','
+ local var_in_obj = 0,
+
+ local vowels = ['a', 'e', 'i', 'o', 'u'],
+ local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+
+ # [num] to look up an array element
+ first_vowel: vowels[0],
+ # can also slice the array like in Python
+ even_numbers: numbers[1::2],
+
+ # python-style list and object comprehensions are also supported
+ double_numbers: [x * 2 for x in numbers],
+ even_numbers_map: {
+ # [ ] syntax in field name is to compute the field name dynamically
+ [x + '_is_even']: true for x in numbers if x % 2 == 0
+ },
+
+ nested: {
+ nested_field1: 'some-value',
+ # self refers to the current object
+ # ["field-name"] or .field-name can be used to look up a field
+ nested_field2: self.nested_field1,
+ nested_field3: self.nested_field1,
+ # $ refers to outer-most object
+ nested_field4: $.first_vowel,
+
+ assert self.nested_field1 == self.nested_field2,
+ assert self.nested_field1 == self.nested_field3,
+ },
+
+ special_field: 'EVERYTHING FEELS BAD',
+};
+
+local obj3 = {
+ local var_in_obj = 1.234,
+ local var_in_obj2 = { a: { b: 'c' } },
+
+ concat_array: [1, 2, 3] + [4],
+ # strings can be concat with +,
+ # which implicitly converts one operand to string if needed.
+ concat_string: '123' + 4,
+
+ # == tests deep equality
+ equals: { a: { b: 'c', d: {} } } == var_in_obj2,
+
+ special_field: 'this feels good',
+};
+
+# objects can be merged with + where the right-hand side wins field conflicts
+local obj4 = obj2 + obj3;
+assert obj4.special_field == 'this feels good';
+
+# define a function
+# functions have positional parameters, named parameters, and default arguments
+local my_function(x, y, z=1) = x + y - z;
+local num6 = my_function(7, 8, 9);
+local num7 = my_function(8, z=10, y=9);
+local num8 = my_function(4, 5);
+# inline anonymous function
+local num9 = (function(x) x * x)(3);
+
+local obj5 = {
+ # define a method
+ # fields defined with :: are hidden, which does not apper in generated JSON
+ # function cannot be serialized so need to be hidden
+ # if the object is used in the generated JSON.
+ is_odd(x):: x % 2 == 1,
+};
+assert obj5 == {};
+
+# a jsonnet document has to evaluate to something
+# be it an object, list, number or just string literal
+"FIN"
+
+```
+
+## Further Reading
+There are a few but important concepts that are not touched in this exmaple, including:
+
+- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config)
+- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports)
+- In depth example of OOP aspect of Jsonnet: [Object-Orientation](https://jsonnet.org/learning/tutorial.html#Object-Orientation)
+- Useful standard library: [Stdlib](https://jsonnet.org/ref/stdlib.html)
diff --git a/julia.html.markdown b/julia.html.markdown
index 5e9ef1b8..4d8eb497 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -11,7 +11,7 @@ Julia is a new homoiconic functional language focused on technical computing.
While having the full power of homoiconic macros, first-class functions,
and low-level control, Julia is as easy to learn and use as Python.
-This is based on Julia 1.0.0
+This is based on Julia version 1.0.0.
```julia
# Single line comments start with a hash (pound) symbol.
@@ -83,7 +83,7 @@ false
1 > 10 # => false
2 <= 2 # => true
2 >= 2 # => true
-# Comparisons can be chained
+# Comparisons can be chained, like in Python but unlike many other languages
1 < 2 < 3 # => true
2 < 3 < 2 # => false
@@ -93,28 +93,29 @@ false
# Character literals are written with '
'a'
-# Strings are UTF8 encoded. Only if they contain only ASCII characters can
-# they be safely indexed.
-ascii("This is a string")[1]
+# Strings are UTF8 encoded, so strings like "π" or "☃" are not directly equivalent
+# to an array of single characters.
+# Only if they contain only ASCII characters can they be safely indexed.
+ascii("This is a string")[1] # => 'T'
# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase)
-# Julia indexes from 1
+# Beware, Julia indexes everything from 1 (like MATLAB), not 0 (like most languages).
# Otherwise, iterating over strings is recommended (map, for loops, etc).
-# String can be compared lexicographically
-"good" > "bye" # => true
+# String can be compared lexicographically, in dictionnary order:
+"good" > "bye" # => true
"good" == "good" # => true
"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true
-# $ can be used for string interpolation:
+# $(..) can be used for string interpolation:
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
# You can put any Julia expression inside the parentheses.
# Printing is easy
-println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
+println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you!
# Another way to format strings is the printf macro from the stdlib Printf.
-using Printf
-@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
+using Printf # this is how you load (or import) a module
+@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
####################################################
@@ -123,7 +124,7 @@ using Printf
# You don't declare variables before assigning to them.
someVar = 5 # => 5
-someVar # => 5
+someVar # => 5
# Accessing a previously unassigned variable is an error
try
@@ -137,9 +138,10 @@ end
SomeOtherVar123! = 6 # => 6
# You can also use certain unicode characters
+# here ☃ is a Unicode 'snowman' characters, see http://emojipedia.org/%E2%98%83%EF%B8%8F if it displays wrongly here
☃ = 8 # => 8
-# These are especially handy for mathematical notation
-2 * π # => 6.283185307179586
+# These are especially handy for mathematical notation, like the constant π
+2 * π # => 6.283185307179586
# A note on naming conventions in Julia:
#
@@ -171,7 +173,7 @@ matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4]
b = Int8[4, 5, 6] # => 3-element Array{Int8,1}: [4, 5, 6]
# Add stuff to the end of a list with push! and append!
-# By convention, the exclamation mark '!'' is appended to names of functions
+# By convention, the exclamation mark '!' is appended to names of functions
# that modify their arguments
push!(a, 1) # => [1]
push!(a, 2) # => [1,2]
@@ -202,10 +204,10 @@ a # => [7,2,4,3,4,5,6]
# Function names that end in exclamations points indicate that they modify
# their argument.
arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6]
-sort(arr) # => [4,5,6]
-arr # => [5,4,6]
-sort!(arr) # => [4,5,6]
-arr # => [4,5,6]
+sort(arr) # => [4,5,6]
+arr # => [5,4,6]
+sort!(arr) # => [4,5,6]
+arr # => [4,5,6]
# Looking out of bounds is a BoundsError
try
@@ -238,7 +240,7 @@ a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5]
a2 = [1:5] # => 1-element Array{UnitRange{Int64},1}: [1:5]
# You can look at ranges with slice syntax.
-a[1:3] # => [1, 2, 3]
+a[1:3] # => [1, 2, 3]
a[2:end] # => [2, 3, 4, 5]
# Remove elements from an array by index with splice!
@@ -276,15 +278,15 @@ in(2, tup) # => true
# You can unpack tuples into variables
a, b, c = (1, 2, 3) # => (1,2,3)
-a # => 1
-b # => 2
-c # => 3
+a # => 1
+b # => 2
+c # => 3
# Tuples are created even if you leave out the parentheses
d, e, f = 4, 5, 6 # => (4,5,6)
-d # => 4
-e # => 5
-f # => 6
+d # => 4
+e # => 5
+f # => 6
# A 1-element tuple is distinct from the value it contains
(1,) == 1 # => false
@@ -292,8 +294,8 @@ f # => 6
# Look how easy it is to swap two values
e, d = d, e # => (5,4)
-d # => 5
-e # => 4
+d # => 5
+e # => 4
# Dictionaries store mappings
emptyDict = Dict() # => Dict{Any,Any} with 0 entries
@@ -375,7 +377,8 @@ end
# Iterable types include Range, Array, Set, Dict, and AbstractString.
for animal = ["dog", "cat", "mouse"]
println("$animal is a mammal")
- # You can use $ to interpolate variables or expression into strings
+ # You can use $ to interpolate variables or expression into strings.
+ # In this special case, no need for parenthesis: $animal and $(animal) give the same
end
# => dog is a mammal
# => cat is a mammal
@@ -408,7 +411,7 @@ end
let x = 0
while x < 4
println(x)
- x += 1 # Shorthand for x = x + 1
+ x += 1 # Shorthand for in place increment: x = x + 1
end
end
# => 0
diff --git a/ko-kr/vim-kr.html.markdown b/ko-kr/vim-kr.html.markdown
index cd0fa236..76063143 100644
--- a/ko-kr/vim-kr.html.markdown
+++ b/ko-kr/vim-kr.html.markdown
@@ -5,12 +5,13 @@ contributors:
- ["RadhikaG", "https://github.com/RadhikaG"]
translators:
- ["Wooseop Kim", "https://github.com/linterpreteur"]
+ - ["Yeongjae Jang", "https://github.com/Liberatedwinner"]
filename: LearnVim-kr.txt
lang: ko-kr
---
[Vim](http://www.vim.org)
-(Vi IMproved)은 유닉스의 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
+(Vi IMproved)은 유닉스에서 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
설계된 텍스트 에디터로, 대부분의 유닉스 기반 시스템에 내장되어 있습니다. 다양한 단축 키를 통해
파일 안에서 빠르게 이동하고 편집할 수 있습니다.
@@ -18,19 +19,21 @@ lang: ko-kr
```
vim <filename> # vim으로 <filename> 열기
+ :help <topic> # (존재하는 경우에) <topic>에 대한, 내장된 도움말 문서 열기
:q # vim 종료
:w # 현재 파일 저장
:wq # 파일 저장 후 종료
+ ZZ # 파일 저장 후 종료
:q! # 저장하지 않고 종료
# ! *강제로* :q를 실행하여, 저장 없이 종료
- :x # 파일 저장 후 종료 (짧은 :wq)
+ :x # 파일 저장 후 종료 (:wq의 축약)
u # 동작 취소
CTRL+R # 되돌리기
h # 한 글자 왼쪽으로 이동
- j # 아래로 한 줄 이동
- k # 위로 한 줄 이동
+ j # 한 줄 아래로 이동
+ k # 한 줄 위로 이동
l # 한 글자 오른쪽으로 이동
# 줄 안에서의 이동
@@ -38,6 +41,11 @@ lang: ko-kr
0 # 줄 시작으로 이동
$ # 줄 끝으로 이동
^ # 줄의 공백이 아닌 첫 문자로 이동
+
+ Ctrl+B # 한 화면 뒤로 이동
+ Ctrl+F # 한 화면 앞으로 이동
+ Ctrl+D # 반 화면 앞으로 이동
+ Ctrl+U # 반 화면 뒤로 이동
# 텍스트 검색
@@ -48,6 +56,8 @@ lang: ko-kr
:%s/foo/bar/g # 파일 모든 줄에 있는 'foo'를 'bar'로 치환
:s/foo/bar/g # 현재 줄에 있는 'foo'를 'bar'로 치환
+ :%s/foo/bar/gc # 사용자에게 확인을 요구하는, 모든 줄에 있는 'foo'를 'bar'로 치환
+ :%s/\n/\r/g # 한 종류의 개행 문자에서 다른 종류의 것으로 치환 (\n에서 \r로)
# 문자로 이동
@@ -74,14 +84,22 @@ lang: ko-kr
L # 화면 바닥으로 이동
```
+## 도움말 문서
+
+Vim은 `:help <topic>` 명령을 통해 접근할 수 있는 도움말 문서를 내장하고 있습니다.
+예를 들어, `:help navigation` 은 당신의 작업 공간을 탐색하는 방법에 대한 문서를 표시합니다!
+
+`:help`는 옵션 없이도 사용할 수 있습니다. 이는 기본 도움말 대화 상자를 표시합니다.
+이 대화 상자는 Vim을 시작하는 것이 보다 용이하도록 도와줍니다.
+
## 모드
Vim은 **모드**의 개념에 기초를 두고 있습니다.
-명령어 모드 - vim을 시작하면 처음에 이 모드입니다. 이동과 명령어 입력에 사용합니다.
-삽입 모드 - 파일을 수정합니다.
-비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
-실행 모드 - ':' 이후 명령어를 입력합니다.
+- 명령어 모드 - vim은 이 모드로 시작됩니다. 이동과 명령어 입력에 사용합니다.
+- 삽입 모드 - 파일을 수정합니다.
+- 비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
+- 실행 모드 - ':' 이후 명령어를 입력합니다.
```
i # 커서 위치 앞에서 삽입 모드로 변경
@@ -97,11 +115,11 @@ Vim은 **모드**의 개념에 기초를 두고 있습니다.
d # 선택한 객체 삭제
dd # 현재 줄 삭제
p # 커서 위치 뒤에 복사한 텍스트 붙여넣기
- P # 커서 위치 뒤에 복사한 텍스트 붙여넣기
+ P # 커서 위치 앞에 복사한 텍스트 붙여넣기
x # 현재 커서 위치의 문자 삭제
```
-## vim의 문법
+## vim의 '문법'
Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니다.
@@ -134,7 +152,7 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
w # 단어를
s # 문장을
p # 문단을
- b # 블락을
+ b # 블록을
# 예시 '문장' (명령어)
@@ -157,6 +175,22 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
ddp # 이어지는 줄과 위치 맞바꾸기 (dd 후 p)
. # 이전 동작 반복
:w !sudo tee % # 현재 파일을 루트 권한으로 저장
+ :set syntax=c # 문법 강조를 'C'의 것으로 설정
+ :sort # 모든 줄을 정렬
+ :sort! # 모든 줄을 역순으로 정렬
+ :sort u # 모든 줄을 정렬하고, 중복되는 것을 삭제
+ ~ # 선택된 텍스트의 대/소문자 토글
+ u # 선택된 텍스트를 소문자로 바꾸기
+ U # 선택된 텍스트를 대문자로 바꾸기
+
+ # 텍스트 폴딩
+ zf # 선택된 텍스트 위치에서 폴딩 만들기
+ zo # 현재 폴딩 펴기
+ zc # 현재 폴딩 접기
+ zR # 모든 폴딩 펴기
+ zM # 모든 폴딩 접기
+ zi # 폴딩 접기/펴기 토글
+ zd # 접은 폴딩 삭제
```
## 매크로
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
index 5bbf6847..12008074 100644
--- a/kotlin.html.markdown
+++ b/kotlin.html.markdown
@@ -180,7 +180,7 @@ fun helloWorld(val name : String) {
// destructuring in "for" loop
for ((a, b, c) in listOf(fooData)) {
- println("$a $b $c") // => 1 100 4
+ println("$a $b $c") // => 1 2 4
}
val mapData = mapOf("a" to 1, "b" to 2)
@@ -426,7 +426,7 @@ data class Counter(var value: Int) {
operator fun invoke() = println("The value of the counter is $value")
}
-/* You can also overload operators through an extension methods */
+/* You can also overload operators through extension methods */
// overload -Counter
operator fun Counter.unaryMinus() = Counter(-this.value)
diff --git a/latex.html.markdown b/latex.html.markdown
index e8bc6064..29a9f638 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -2,7 +2,7 @@
language: latex
contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Colton Kohnke", "https://github.com/voltnor"]
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
- ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
- ["Svetlana Golubeva", "https://attillax.github.io/"]
@@ -123,7 +123,7 @@ Math has many symbols, far beyond what you can find on a keyboard;
Set and relation symbols, arrows, operators, and Greek letters to name a few.
Sets and relations play a vital role in many mathematical research papers.
-Here's how you state all x that belong to X, $\forall$ x $\in$ X.
+Here's how you state all x that belong to X, $\forall x \in X$.
% Notice how I needed to add $ signs before and after the symbols. This is
% because when writing, we are in text-mode.
% However, the math symbols only exist in math-mode.
@@ -181,7 +181,9 @@ Summations and Integrals are written with sum and int commands:
\section{Figures}
Let's insert a figure. Figure placement can get a little tricky.
+Basic options are [t] for top, [b] for bottom, [h] for here (approximately).
I definitely have to lookup the placement options each time.
+% See https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions for more details
\begin{figure}[H] % H here denoted the placement option.
\centering % centers the figure on the page
@@ -198,13 +200,21 @@ We can also insert Tables in the same way as figures.
\begin{table}[H]
\caption{Caption for the Table.}
% the {} arguments below describe how each row of the table is drawn.
- % Again, I have to look these up. Each. And. Every. Time.
- \begin{tabular}{c|cc}
+ % The basic is simple: one letter for each column, to control alignment:
+ % basic options are: c, l, r and p for centered, left, right and paragraph
+ % optionnally, you can add a | for a vertical line
+ % See https://en.wikibooks.org/wiki/LaTeX/Tables for more details
+ \begin{tabular}{c|cc} % here it means "centered | vertical line, centered centered"
Number & Last Name & First Name \\ % Column rows are separated by &
\hline % a horizontal line
1 & Biggus & Dickus \\
2 & Monty & Python
\end{tabular}
+ % it will approximately be displayed like this
+ % Number | Last Name First Name
+ % -------|--------------------------- % because of \hline
+ % 1 | Biggus Dickus
+ % 2 | Monty Python
\end{table}
\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)}
@@ -218,7 +228,8 @@ environment.
\begin{verbatim}
print("Hello World!")
a%b; % look! We can use % signs in verbatim.
- random = 4; #decided by fair random dice roll
+ random = 4; #decided by fair random dice roll, https://www.xkcd.com/221/
+ See https://www.explainxkcd.com/wiki/index.php/221:_Random_Number
\end{verbatim}
\section{Compiling}
@@ -244,6 +255,7 @@ Step 2 is still happening behind the scenes\footnote{In cases, where you use
references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2
multiple times, to generate an intermediary *.aux file.}.
% Also, this is how you add footnotes to your document!
+% with a simple \footnote{...} command. They are numbered ¹, ², ... by default.
You write all your formatting information in plain text in Step 1.
The compilation part in Step 2 takes care of producing the document in the
@@ -265,6 +277,27 @@ There exists two main types of links: visible URL \\
This package also produces list of thumbnails in the output pdf document and
active links in the table of contents.
+\section{Writing in ASCII or other encodings}
+
+By default, historically LaTeX accepts inputs which are pure ASCII (128),
+not even extened ASCII, meaning without accents (à, è etc.) and non-Latin symbols.
+
+It is easy to insert accents and basic Latin symbols, with backslash shortcuts
+Like \,c, \'e, \`A, \ae and \oe etc. % for ç, é, À, etc
+% See https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes for more
+
+To write directly in UTF-8, when compiling with pdflatex, use
+\begin{verbatim}
+ \usepackage[utf8]{inputenc}
+\end{verbatim}
+The selected font has to support the glyphs used for your document, you have to add
+\begin{verbatim}
+ \usepackage[T1]{fontenc}
+\end{verbatim}
+
+Not that there also exists LuaTeX and XeLaTeX that were designed to have builtin
+support for UTF-8 and case ease your life if you don't write in a latin alphabet.
+
\section{End}
That's all for now!
diff --git a/lbstanza.html.markdown b/lbstanza.html.markdown
new file mode 100644
index 00000000..19dc7db7
--- /dev/null
+++ b/lbstanza.html.markdown
@@ -0,0 +1,282 @@
+---
+language: LB Stanza
+filename: learn-stanza.stanza
+contributors:
+ - ["Mike Hilgendorf", "https://github.com/m-hilgendorf"]
+---
+
+LB Stanza (or Stanza for short) is a new optionally-typed general purpose programming language from the University of California, Berkeley. Stanza was designed to help programmers tackle the complexity of architecting large programs and significantly increase the productivity of application programmers across the entire software development life cycle.
+
+
+```stanza
+; this is a comment
+;<A>
+This is a block comment
+ ;<B>
+ block comments can be nested with optional tags.
+ ;<B>
+;<A>
+defpackage learn-stanza-in-y:
+ import core
+ import collections
+
+;==============================================================================
+; The basics, things you'd find in most programming languages
+;==============================================================================
+
+
+; Variables can be mutable (var) or immutable (val)
+val immutable = "this string can't be changed"
+var mutable = "this one can be"
+mutable = "like this"
+
+; The basic data types (annotations are optional)
+val an-int: Int = 12345
+val a-long: Long = 12345L
+val a-float: Float = 1.2345f
+val a-double: Double = 3.14159
+val a-string: String = "this is a string"
+val a-multiline-string = \<tag>
+ this is a "raw" string literal
+\<tag>
+
+; Print a formatted string with println and "..." % [...]
+println("this is a formatted string %_ %_" % [mutable, immutable])
+
+; Stanza is optionally typed, and has a ? (any) type.
+var anything:? = 0
+anything = 3.14159
+anything = "a string"
+
+; Stanza has basic collections like Tuples, Arrays, Vectors and HashTables
+val tuple: Tuple<?> = [mutable, immutable]
+
+val array = Array<?>(3)
+array[0] = "string"
+array[1] = 1
+array[2] = 1.23455
+; array[3] = "out-of-bounds" ; arrays are bounds-checked
+
+val vector = Vector<?>()
+vector[0] = "string"
+vector[1] = 1
+vector[2] = 3.14159
+
+val hash-table = HashTable<String, ?>()
+hash-table["0"] = 0
+hash-table["1"] = 1
+hash-table["2"] = 1
+
+
+;==============================================================================
+; Functions
+;==============================================================================
+; Functions are declared with the `defn` keyword
+defn my-function (arg:?) : ; note the space between identifier and arg list
+ println("called my-function with %_" % [arg])
+
+my-function("arg") ; note the lack of a space to call the function
+
+; Functions can be declared inside another function and capture variables from
+; the surrounding environment.
+defn outer (arg):
+ defn inner ():
+ println("outer had arg: %_" % [arg])
+ inner()
+
+outer("something")
+
+; functions are "first-class" in stanza, meaning you can assign variables
+; to functions and pass functions as arguments to other functions.
+val a-function = outer
+defn do-n-times (arg, func, n:Int):
+ for i in 0 to n do :
+ func(arg)
+do-n-times("argument", a-function, 3)
+
+; sometimes you want to define a function inline, or use an anonymous function.
+; for this you can use the syntax:
+; fn (args):
+; ...
+do-n-times("hello", fn (arg): println(arg), 2)
+
+; there is a shorthand for writing anonymous functions
+do-n-times("hello", { println(_) }, 2)
+
+; the short hand works for multiple arguments as well.
+val multi-lambda = { println(_ + 2 * _) }
+multi-lambda(1, 2)
+
+;==============================================================================
+; User defined types
+;==============================================================================
+; Structs are declared with the `defstruct` keyword
+defstruct MyStruct:
+ field
+
+; constructors are derived automatically
+val my-struct = MyStruct("field:value")
+
+; fields are accessed using function-call syntax
+println(field(my-struct))
+
+; Stanza supports subtyping with a "multimethod" system based on method
+; overloading.
+deftype MyType
+defmulti a-method (m:MyType)
+
+defstruct Foo <: MyType
+defstruct Bar <: MyType
+defmethod a-method (a-foo: Foo):
+ println("called a-method on a Foo")
+
+defmethod a-method (a-foo: Bar):
+ println("called a-method on a Bar")
+
+;==============================================================================
+; The Type System
+;==============================================================================
+; True and Falseare types with a single value.
+val a-true: True = true
+val a-false: False = false
+
+; You can declare a union type, or a value that is one of a set of types
+val a-boolean: True|False = true
+val another-boolean: True|False = false
+
+; You can pattern match on types
+match(a-boolean):
+ (t:True): println("is true")
+ (f:False): println("is false")
+
+; You can match against a single possible type
+match(a-boolean:True):
+ println("is still true")
+else:
+ println("is not true")
+
+; You can compose program logic around the type of a variable
+if anything is Float :
+ println("anything is a float")
+else if anything is-not String :
+ println("anything is not an int")
+else :
+ println("I don't know what anything is")
+
+;==============================================================================
+; Control Flow
+;==============================================================================
+; stanza has the standard basic control flow
+val condition = [false, false]
+if condition[0] :
+ ; do something
+ false
+else if condition[1] :
+ ; do another thing
+ false
+else :
+ ; whatever else
+ false
+
+; there is also a switch statement, which can be used to pattern match
+; on values (as opposed to types)
+switch(anything):
+ "this": false
+ "that": false
+ "the-other-thing": false
+ else: false
+
+; for and while loops are supported
+while condition[0]:
+ println("do stuff")
+
+for i in 0 to 10 do:
+ vector[i] = i
+
+; stanza also supports named labels which can functin as break or return
+; statements
+defn another-fn ():
+ label<False> return:
+ label<False> break:
+ while true:
+ if condition[0] is False:
+ break(false)
+ return(false)
+
+; For a comprehensive guide on Stanza's advanced control flow, check out
+; this page: http://lbstanza.org/chapter9.html from Stanza-by-Example
+
+;==============================================================================
+; Sequences
+;==============================================================================
+; for "loops" are sugar for a more powerful syntax.
+val xs = [1, 2, 3]
+val ys = ['a', 'b', 'c']
+val zs = ["foo", "bar", "baz"]
+
+for (x in xs, y in ys, z in zs) do :
+ println("x:%_, y:%_, z:%_" % [x, y, z])
+
+
+;xs, ys, and zs are all "Seqable" meaing they are Seq types (sequences).
+; the `do` identifier is a special function that just applies the body of
+; the for loop to each element of the sequence.
+;
+; A common sequence task is concatenating sequences. This is accomplished
+; using the `seq-cat` function. This is analogous to "flattening" iterateors
+val concat = to-tuple $
+ for sequence in [xs, ys, zs] seq-cat:
+ sequence
+
+; we can also use a variation to interleave the elements of multiple sequences
+val interleaved = to-tuple $
+ for (x in xs, y in ys, z in zs) seq-cat :
+ [x, y, z]
+
+println("[%,] [%,]" % [concat, interleaved])
+
+; Another common task is mapping a sequence to another, for example multiplying
+; all the elements of a list of numbers by a constant. To do this we use `seq`.
+var numbers = [1.0, 2.0, 3.0, 4.0]
+numbers = to-tuple $
+ for n in numbers seq :
+ 2.0 * n
+println("%," % [numbers])
+
+if find({_ == 2.0}, numbers) is-not False :
+ println("found it!")
+
+; or maybe we just want to know if there's something in a sequence
+var is-there =
+ for n in numbers any? :
+ n == 2.0
+
+; since this is "syntactic sugar" we can write it explicitly using an
+; anonymous function
+is-there = any?({_ == 2.0}, numbers)
+
+; a detailed reference of the sequence library and various adaptors can
+; be found here: http://lbstanza.org/reference.html#anchor439
+
+
+=========================================================================
+; Documentation
+;=========================================================================
+;
+; Top level statements can be prefixed with the "doc" field which takes
+; a string value and is used to autogenerate documentation for the package.
+doc: \<doc>
+ # Document Strings
+
+ ```stanza
+ val you-can = "include code snippets, too"
+ ```
+
+ To render documentation as markdown (compatible with mdbook)
+
+ ```bash
+ stanza doc source.stanza -o docs
+ ```
+\<doc>
+defn docfn () : false
+``` \ No newline at end of file
diff --git a/ldpl.html.markdown b/ldpl.html.markdown
index cc95f5fb..86603d94 100644
--- a/ldpl.html.markdown
+++ b/ldpl.html.markdown
@@ -165,19 +165,6 @@ display myNumber crlf
exit
```
-## Topics Not Covered
-
- * [Command line arguments](https://docs.ldpl-lang.org/variables-in-ldpl/command-line-arguments)
- * [Error variables](https://docs.ldpl-lang.org/variables-in-ldpl/errorcode-and-errortext)
- * [Import other files](https://docs.ldpl-lang.org/structure-of-ldpl-source-code/importing-other-sources)
- * [Identifier naming schemes](https://docs.ldpl-lang.org/naming-rules)
- * [Text Statements](https://docs.ldpl-lang.org/text-statements/join-and-in)
- * [List Statements](https://docs.ldpl-lang.org/list-statements/push-to)
- * [Map Statements](https://docs.ldpl-lang.org/vector-statements/clear)
- * [File loading / writing](https://docs.ldpl-lang.org/i-o-statements/load-file-in)
- * [Executing commands](https://docs.ldpl-lang.org/i-o-statements/execute)
- * [Extending LDPL with C++](https://docs.ldpl-lang.org/extensions/c++-extensions)
-
## Further Reading
* [LDPL Docs](https://docs.ldpl-lang.org)
diff --git a/lua.html.markdown b/lua.html.markdown
index 0a7c4f00..4a470623 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -116,7 +116,7 @@ function bar(a, b, c)
end
x, y = bar('zaphod') --> prints "zaphod nil nil"
--- Now x = 4, y = 8, values 15..42 are discarded.
+-- Now x = 4, y = 8, values 15...42 are discarded.
-- Functions are first-class, may be local/global.
-- These are the same:
@@ -395,7 +395,7 @@ g() -- Prints out 343; nothing printed before now.
I was excited to learn Lua so I could make games
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why.
-I started with <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
+I started with <a href="https://ebens.me/post/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book.
That's the how.
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 5790bcc6..ecf2fc96 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -28,7 +28,7 @@ this
% Two percent signs denote the start of a new code section
% Individual code sections can be run by moving the cursor to the section followed by
% either clicking the "Run Section" button
-% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X)
+% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (macOS)
%% This is the start of a code section
% One way of using sections is to separate expensive but unchanging start-up code like loading data
@@ -234,7 +234,7 @@ A' % Concise version of complex transpose
% On their own, the arithmetic operators act on whole matrices. When preceded
% by a period, they act on each element instead. For example:
A * B % Matrix multiplication
-A .* B % Multiple each element in A by its corresponding element in B
+A .* B % Multiply each element in A by its corresponding element in B
% There are several pairs of functions, where one acts on each element, and
% the other (whose name ends in m) acts on the whole matrix.
diff --git a/mips.html.markdown b/mips.html.markdown
index 7f759bec..4977cc65 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -209,7 +209,7 @@ gateways and routers.
## LOOPS ##
_loops:
# The basic structure of loops is having an exit condition and a jump
- instruction to continue its execution
+ # instruction to continue its execution
li $t0, 0
while:
bgt $t0, 10, end_while # While $t0 is less than 10,
@@ -242,7 +242,7 @@ gateways and routers.
## FUNCTIONS ##
_functions:
# Functions are callable procedures that can accept arguments and return
- values all denoted with labels, like above
+ # values all denoted with labels, like above
main: # Programs begin with main func
jal return_1 # jal will store the current PC in $ra
diff --git a/mongodb.html.markdown b/mongodb.html.markdown
new file mode 100644
index 00000000..959b57d0
--- /dev/null
+++ b/mongodb.html.markdown
@@ -0,0 +1,405 @@
+---
+language: MongoDB
+filename: mongo.js
+contributors:
+ - ["Raj Piskala", "https://www.rajpiskala.ml/"]
+---
+
+MongoDB is a NoSQL document database for high volume data storage.
+
+MongoDB uses collections and documents for its storage. Each document consists
+of key-value pairs using JSON-like syntax, similar to a dictionary or JavaScript
+object.
+
+Likewise, as MongoDB is a NoSQL database, it uses its own query language, Mongo
+Query Language (MQL) which uses JSON for querying.
+
+## Getting Started
+
+### Installation
+
+MongoDB can either be installed locally following the instructions
+[here](https://docs.mongodb.com/manual/installation/) or you can create a
+remotely-hosted free 512 MB cluster
+[here](https://www.mongodb.com/cloud/atlas/register). Links to videos with
+instructions on setup are at the bottom.
+
+This tutorial assumes that you have the MongoDB Shell from
+[here](https://www.mongodb.com/try/download/shell). You can also download the
+graphical tool, MongoDB Compass, down below from the same link.
+
+### Components
+
+After installing MongoDB, you will notice there are multiple command line tools.
+The three most important of which are:
+
+- `mongod` - The database server which is responsible for managing data and
+ handling queries
+- `mongos` - The sharding router, which is needed if data will be distributed
+ across multiple machines
+- `mongo` - The database shell (using JavaScript) through which we can configure
+ our database
+
+Usually we start the `mongod` process and then use a separate terminal with
+`mongo` to access and modify our collections.
+
+### JSON & BSON
+
+While queries in MongoDB are made using a JSON-like\* format, MongoDB stores its
+documents internally in the Binary JSON (BSON format). BSON is not human
+readable like JSON as it's a binary encoding. However, this allows for end users
+to have access to more types than regular JSON, such as an integer or float
+type. Many other types, such as regular expressions, dates, or raw binary are
+supported too.
+
+[Here](https://docs.mongodb.com/manual/reference/bson-types/) is the full list
+of all types that are supported.
+
+- We refer JSON-like to mean JSON but with these extended types. For example,
+ you can make queries directly with a regular expression or timestamp in
+ MongoDB and you can receive data that has those types too.
+
+```js
+/////////////////////////////////////////////////////////
+/////////////////// Getting Started /////////////////////
+/////////////////////////////////////////////////////////
+
+// Start up the mongo database server
+// NOTE - You will need to do this in a separate terminal as the process will
+// take over the terminal. You may want to use the --fork option
+mongod // --fork
+
+// Connecting to a remote Mongo server
+// mongo "mongodb+srv://host.ip.address/admin" --username your-username
+
+// Mongoshell has a proper JavaScript interpreter built in
+3 + 2 // 5
+
+// Show available databases
+// MongoDB comes with the following databases built-in: admin, config, local
+show dbs
+
+// Switch to a new database (pre-existing or about to exist)
+// NOTE: There is no "create" command for a database in MongoDB.
+// The database is created upon data being inserted into a collection
+use employees
+
+// Create a new collection
+// NOTE: Inserting a document will implicitly create a collection anyways,
+// so this is not required
+db.createCollection('engineers')
+db.createCollection('doctors')
+
+// See what collections exist under employees
+show collections
+
+/////////////////////////////////////////////////////////
+// Basic Create/Read/Update/Delete (CRUD) Operations: ///
+/////////////////////////////////////////////////////////
+
+/////////////// Insert (Create) /////////////////////////
+
+// Insert one employee into the database
+// Each insertion returns acknowledged true or false
+// Every document has a unique _id value assigned to it automatically
+db.engineers.insertOne({ name: "Jane Doe", age: 21, gender: 'Female' })
+
+// Insert a list of employees into the `engineers` collection
+// Can insert as an array of objects
+db.engineers.insert([
+ { name: "Foo Bar", age: 25, gender: 'Male' },
+ { name: "Baz Qux", age: 27, gender: 'Other' },
+])
+
+// MongoDB does not enforce a schema or structure for objects
+// Insert an empty object into the `engineers` collection
+db.engineers.insertOne({})
+
+// Fields are optional and do not have to match rest of documents
+db.engineers.insertOne({ name: "Your Name", gender: "Male" })
+
+// Types can vary and are preserved on insertion
+// This can require additional validation in some languages to prevent problems
+db.engineers.insert({ name: ['Foo', 'Bar'], age: 3.14, gender: true })
+
+// Objects or arrays can be nested inside a document
+db.engineers.insertOne({
+ name: "Your Name",
+ gender: "Female",
+ skilledIn: [
+ "MongoDB",
+ "NoSQL",
+ ],
+ "date-of-birth": {
+ "date": 1993-07-20T09:44:18.674Z,
+ "age": 26
+ },
+})
+
+// We can override the _id field
+// Works fine
+db.engineers.insertOne({
+ _id: 1,
+ name: "An Engineer",
+ age: 25,
+ gender: "Female",
+})
+
+// Be careful, as _id must ALWAYS be unique for the collection otherwise
+// the insertion will fail
+// Fails with a WriteError indicating _id is a duplicate value
+db.engineers.insertOne({
+ _id: 1,
+ name: "Another Engineer",
+ age: 25,
+ gender: "Male",
+})
+
+// Works fine as this is a different collection
+db.doctors.insertOne({
+ _id: 1,
+ name: "Some Doctor",
+ age: 26,
+ gender: "Other",
+})
+
+/////////////////// Find (Read) ////////////////////////
+// Queries are in the form of db.collectionName.find(<filter>)
+// Where <filter> is an object
+
+// Show everything in our database so far, limited to a
+// maximum of 20 documents at a time
+// Press i to iterate this cursor to the next 20 documents
+db.engineers.find({})
+
+// We can pretty print the result of any find() query
+db.engineers.find({}).pretty()
+
+// MongoDB queries take in a JS object and search for documents with matching
+// key-value pairs
+// Returns the first document matching query
+// NOTE: Order of insertion is not preserved in the database, output can vary
+db.engineers.findOne({ name: 'Foo Bar' })
+
+// Returns all documents with the matching key-value properties as a cursor
+// (which can be converted to an array)
+db.engineers.find({ age: 25 })
+
+// Type matters when it comes to queries
+// Returns nothing as all ages above are integer type
+db.engineers.find({ age: '25' })
+
+// find() supports nested objects and arrays just like create()
+db.engineers.find({
+ name: "Your Name",
+ gender: "Female",
+ skilledIn: [
+ "MongoDB",
+ "NoSQL",
+ ],
+ "date-of-birth": {
+ "date": 1993-07-20T09:44:18.674Z,
+ "age": 26
+ },
+})
+
+///////////////////////// Update ////////////////////////
+// Queries are in the form of db.collectionName.update(<filter>, <update>)
+// NOTE: <update> will always use the $set operator.
+// Several operators are covered later on in the tutorial.
+
+// We can update a single object
+db.engineers.updateOne({ name: 'Foo Bar' }, { $set: { name: 'John Doe', age: 100 }})
+
+// Or update many objects at the same time
+db.engineers.update({ age: 25 }, { $set: { age: 26 }})
+
+// We can use { upsert: true } if we would like it to insert if the document doesn't already exist,
+// or to update if it does
+// Returns matched, upserted, modified count
+db.engineers.update({ name: 'Foo Baz' },
+ { $set:
+ {
+ age: 26,
+ gender: 'Other'
+ }
+ },
+ { upsert: true }
+)
+
+/////////////////////// Delete /////////////////////////
+// Queries are in the form of db.collectionName.find(<filter>)
+
+// Delete first document matching query, always returns deletedCount
+db.engineers.deleteOne({ name: 'Foo Baz' })
+
+// Delete many documents at once
+db.engineers.deleteMany({ gender: 'Male' })
+
+// NOTE: There are two methods db.collection.removeOne(<filter>) and
+// db.collection.removeMany(<filter>) that also delete objects but have a
+// slightly different return value.
+// They are not included here as they have been deprecated in the NodeJS driver.
+
+/////////////////////////////////////////////////////////
+//////////////////// Operators //////////////////////////
+/////////////////////////////////////////////////////////
+
+// Operators in MongoDB have a $ prefix. For this tutorial, we are only looking
+// at comparison and logical operators, but there are many other types of
+// operators
+
+//////////////// Comparison Operators ///////////////////
+
+// Find all greater than or greater than equal to some condition
+db.engineers.find({ $gt: { age: 25 }})
+db.engineers.find({ $gte: { age: 25 }})
+
+// Find all less than or less than equal to some condition
+db.engineers.find({ $lte: { age: 25 }})
+db.engineers.find({ $lte: { age: 25 }})
+
+// Find all equal or not equal to
+// Note: the $eq operator is added implicitly in most queries
+db.engineers.find({ $eq: { age: 25 }})
+db.engineers.find({ $ne: { age: 25 }})
+
+// Find all that match any element in the array
+db.engineers.find({ age: ${ in: [ 20, 23, 24, 25 ]}})
+
+//////////////// Logical Operators ///////////////////
+
+// Join two query clauses together
+// NOTE: MongoDB does this implicitly for most queries
+db.engineers.find({ $and: [
+ gender: 'Female',
+ age: {
+ $gte: 18
+ }
+]})
+
+// Match either query condition
+db.engineers.find({ $or: [
+ gender: 'Female',
+ age: {
+ $gte: 18
+ }
+]})
+
+// Negates the query
+db.engineers.find({ $not: {
+ gender: 'Female'
+}})
+
+// Must match none of the query conditions
+db.engineers.find({ $nor [
+ gender: 'Female,
+ age: {
+ $gte: 18
+ }
+]})
+
+/////////////////////////////////////////////////////////
+//////////////// Database Operations: ///////////////////
+/////////////////////////////////////////////////////////
+
+// Delete (drop) the employees database
+// THIS WILL DELETE ALL DOCUMENTS IN THE DATABASE!
+db.dropDatabase()
+
+// Create a new database with some data
+use example
+db.test.insertOne({ name: "Testing data, please ignore!", type: "Test" })
+
+// Quit Mongo shell
+exit
+
+// Import/export database as BSON:
+
+// Mongodump to export data as BSON for all databases
+// Exported data is found in under "MongoDB Database Tools/bin/dump"
+// NOTE: If the command is not found, navigate to "MongoDB Database Tools/bin"
+// and use the executable from there mongodump
+
+// Mongorestore to restore data from BSON
+mongorestore dump
+
+// Import/export database as JSON:
+// Mongoexport to export data as JSON for all databases
+mongoexport --collection=example
+
+// Mongoimport to export data as JSON for all databases
+mongoimport --collection=example
+```
+
+## Further Reading
+
+### Setup Videos
+
+- [Install MongoDB - Windows 10](https://www.youtube.com/watch?v=85A6m1soKww)
+- [Install MongoDB - Mac](https://www.youtube.com/watch?v=DX15WbKidXY)
+- [Install MongoDB - Linux
+ (Ubuntu)](https://www.youtube.com/watch?v=wD_2pojFWoE)
+
+### Input Validation
+
+From the examples above, if input validation or structure is a concern, I would
+take a look at the following ORMs:
+
+- [Mongoose (Node.js)](https://mongoosejs.com/docs/) - Input validation through
+ schemas that support types, required values, minimum and maximum values.
+- [MongoEngine (Python)](http://mongoengine.org/) - Similar to Mongoose, but I
+ found it somewhat limited in my experience
+- [MongoKit (Python)](https://github.com/namlook/mongokit) - Another great
+ alternative to MongoEngine that I find easier to use than MongoEngine
+
+For statically strongly typed languages (e.g. Java, C++, Rust), input validation
+usually doesn't require a library as they define types and structure at compile
+time.
+
+### Resources
+
+If you have the time to spare, I would strongly recommend the courses on
+[MongoDB University](https://university.mongodb.com/). They're by MongoDB
+themselves and go into much more detail while still being concise. They're a mix
+of videos and quiz questions and this was how I gained my knowledge of MongoDB.
+
+I would recommend the following video series for learning MongoDB:
+
+- [MongoDB Crash Course - Traversy
+ Media](https://www.youtube.com/watch?v=-56x56UppqQ)
+- [MongoDB Tutorial for Beginners -
+ Amigoscode](https://www.youtube.com/watch?v=Www6cTUymCY)
+
+Language-specific ones that I used before:
+
+- [Build A REST API With Node.js, Express, & MongoDB - Web Dev
+ Simplified](https://www.youtube.com/watch?v=fgTGADljAeg)
+- [MongoDB with Python Crash Course - Tutorial for Beginners -
+ FreeCodeCamp](https://www.youtube.com/watch?v=E-1xI85Zog8)
+- [How to Use MongoDB with Java - Random
+ Coder](https://www.youtube.com/watch?v=reYPUvu2Giw)
+- [An Introduction to Using MongoDB with Rust -
+ MongoDB](https://www.youtube.com/watch?v=qFlftfLGwPM)
+
+Most of the information above was cross-referenced with the [MongoDB
+docs](https://www.mongodb.com/). Here are the docs for each section:
+
+- [MongoDB Types](https://docs.mongodb.com/manual/reference/bson-types/) - List
+ of all types that MongoDB supports natively
+- [MongoDB Operators](https://docs.mongodb.com/manual/reference/operator/) -
+ List of operators MongoDB supports natively
+- [MongoDB CRUD](https://docs.mongodb.com/manual/reference/command/nav-crud/) -
+ Commands for create, read, update, delete
+
+If you've been enjoying MongoDB so far and want to explore intermediate
+features, I would look at
+[aggregation](https://docs.mongodb.com/manual/reference/command/nav-aggregation/),
+[indexing](https://docs.mongodb.com/manual/indexes/), and
+[sharding](https://docs.mongodb.com/manual/sharding/).
+
+- Aggregation - useful for creating advanced queries to be executed by the
+ database
+- Idexing allows for caching, which allows for much faster execution of queries
+- Sharding allows for horizontal data scaling and distribution between multiple
+ machines.
diff --git a/moonscript.html.markdown b/moonscript.html.markdown
index 941578e7..193d7f97 100644
--- a/moonscript.html.markdown
+++ b/moonscript.html.markdown
@@ -192,7 +192,7 @@ items = {1, 2, 3, 4}
doubled = [item * 2 for item in *items]
-- Uses `when` to determine if a value should be included.
-slice = [item for item in *items when i > 1 and i < 3]
+slice = [item for item in *items when item > 1 and item < 3]
-- `for` clauses inside of list comprehensions can be chained.
diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown
index e4e55b2c..a97e651c 100644
--- a/ms-my/bash-my.html.markdown
+++ b/ms-my/bash-my.html.markdown
@@ -17,7 +17,7 @@ translators:
lang: ms-my
---
-Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
+Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan macOS. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell.
[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/nim.html.markdown b/nim.html.markdown
index 1e17d8f0..9730e579 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -28,7 +28,7 @@ Or for unparsable, broken code
var # Declare (and assign) variables,
letter: char = 'n' # with or without type annotations
lang = "N" & "im"
- nLength : int = len(lang)
+ nLength: int = len(lang)
boat: float
truth: bool = false
diff --git a/nix.html.markdown b/nix.html.markdown
index 5941f0e6..dde5dbec 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -279,7 +279,7 @@ with builtins; [
#=> 7
# This first line of tutorial starts with "with builtins;"
- # because builtins is a set the contains all of the built-in
+ # because builtins is a set that contains all of the built-in
# functions (length, head, tail, filter, etc.). This saves
# us from having to write, for example, "builtins.length"
# instead of just "length".
diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown
index af4a8cc8..8d127c57 100644
--- a/nl-nl/bash-nl.html.markdown
+++ b/nl-nl/bash-nl.html.markdown
@@ -17,7 +17,7 @@ lang: nl-nl
filename: LearnBash-nl.sh
---
-Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X.
+Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en macOS.
Bijna alle voorbeelden hieronder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell.
[Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown
index 906112ff..d243802d 100644
--- a/nl-nl/json-nl.html.markdown
+++ b/nl-nl/json-nl.html.markdown
@@ -5,26 +5,27 @@ contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["himanshu", "https://github.com/himanshu81494"]
+ - ["Maarten Jacobs", "https://github.com/maartenJacobs"]
translators:
- ["Niels van Velzen", "https://nielsvanvelzen.me"]
lang: nl-nl
---
-Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste
+Gezien JSON een zeer eenvouding formaat heeft zal dit één van de simpelste
Learn X in Y Minutes ooit zijn.
-JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de
+JSON heeft volgens de specificaties geen commentaar. Ondanks dat hebben de
meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.
Sommige parsers staan zelfs trailing komma's toe.
-(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object).
-Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken.
+(Een komma na het laatste element in een array of achter de laatste eigenschap van een object).
+Het is wel beter om dit soort dingen te vermijden omdat het niet in elke parser zal werken.
In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.
Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.
Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
-De extensie voor JSON bestanden is ".json". De MIME type is "application/json"
-Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD.
+De extensie voor JSON bestanden is ".json". De MIME type is "application/json".
+Enkele nadelen van JSON zijn het gebrek aan type definities en een manier van DTD.
```json
{
diff --git a/no-nb/bash-no.html.markdown b/no-nb/bash-no.html.markdown
index 481aecbd..9affaa21 100644
--- a/no-nb/bash-no.html.markdown
+++ b/no-nb/bash-no.html.markdown
@@ -17,7 +17,7 @@ lang: no-nb
---
Bash er navnet på unix skallet, som også var distribuert som skallet for GNU
operativsystemet og som standard skall på de fleste Linux distribusjoner og
-Mac OS X.
+macOS.
[Les mer her.](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index de3884af..c029c5fb 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -9,7 +9,7 @@ contributors:
filename: LearnObjectiveC.m
---
-Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
+Objective-C is the main programming language used by Apple for the macOS and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
```objective-c
diff --git a/opencv.html.markdown b/opencv.html.markdown
index f8763b35..d1f7ec51 100644
--- a/opencv.html.markdown
+++ b/opencv.html.markdown
@@ -14,9 +14,9 @@ Opencv currently supports wide variety of languages like, C++, Python, Java etc
#### Installation
Please refer to these articles for installation of OpenCV on your computer.
-* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]()
-* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]()
-* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]()
+* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows)
+* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a](https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a)
+* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv](https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv)
### Here we will be focusing on python implementation of OpenCV
@@ -133,12 +133,12 @@ cv2.destroyAllWindows()
### Further Reading:
-* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]()
-* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]()
-* An up-to-date language reference can be found at [https://opencv.org]()
-* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV]()
+* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades](https://github.com/opencv/opencv/blob/master/data/haarcascades)
+* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html](https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html)
+* An up-to-date language reference can be found at [https://opencv.org](https://opencv.org)
+* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV)
* Good OpenCv Tutorials
- * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]()
- * [https://realpython.com/python-opencv-color-spaces]()
- * [https://pyimagesearch.com]()
- * [https://www.learnopencv.com]()
+ * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html)
+ * [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces)
+ * [https://pyimagesearch.com](https://pyimagesearch.com)
+ * [https://www.learnopencv.com](https://www.learnopencv.com)
diff --git a/p5.html.markdown b/p5.html.markdown
index be22d3e5..f6084b98 100644
--- a/p5.html.markdown
+++ b/p5.html.markdown
@@ -7,7 +7,7 @@ contributors:
filename: p5.js
---
-p5.js is a JavaScript library that starts with the original goal of [Processing](http://processing.org"), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
+p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.
```js
diff --git a/perl.html.markdown b/perl.html.markdown
index 08001ab0..8811dd08 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -8,9 +8,9 @@ contributors:
- ["Dan Book", "http://github.com/Grinnz"]
---
-Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
+Perl is a highly capable, feature-rich programming language with over 25 years of development.
-Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
+Perl runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
```perl
# Single line comments start with a number sign.
diff --git a/php.html.markdown b/php.html.markdown
index d4103e97..57ba29c4 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -34,6 +34,7 @@ echo "World\n"; // Prints "World" with a line break
?>
Hello World Again!
<?php
+// That is because historically PHP started as a Template engine
/************************************
@@ -41,12 +42,15 @@ Hello World Again!
*/
// Variables begin with the $ symbol.
-// A valid variable name starts with a letter or underscore,
+// A valid variable name starts with a letter or an underscore,
// followed by any number of letters, numbers, or underscores.
+// You don't have to (and cannot) declare variables.
+// Once you assign a value, PHP will create the variable with the right type.
+
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
-$boolean = false; // or FALSE or False
+$boolean = FALSE; // or false or False
// Integers
$int1 = 12; // => 12
diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown
index 3e27cc4f..43d68b05 100644
--- a/pl-pl/perl-pl.html.markdown
+++ b/pl-pl/perl-pl.html.markdown
@@ -12,10 +12,10 @@ lang: pl-pl
---
-Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
+Perl jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
z ponad 25 latami nieustannego rozwoju.
-Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w
+Perl używany jest na ponad 100 różnych platformach (od przenośnych do w
pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak
i projektów deweloperskich prowadzonych na szeroką skalę.
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 5d74024d..318bf043 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: powershell
contributors:
- ["Wouter Van Schandevijl", "https://github.com/laoujin"]
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
filename: LearnPowershell.ps1
---
@@ -13,105 +14,374 @@ Nearly all examples below can be a part of a shell script or executed directly
in the shell.
A key difference with Bash is that it is mostly objects that you manipulate
-rather than plain text.
+rather than plain text. After years of evolving, it resembles Python a bit.
[Read more here.](https://docs.microsoft.com/powershell/scripting/overview)
-If you are uncertain about your environment:
+Powershell as a Language:
```powershell
-Get-ExecutionPolicy -List
-Set-ExecutionPolicy AllSigned
-# Execution policies include:
-# - Restricted: Scripts won't run.
-# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
-# - AllSigned: Scripts need to be signed by a trusted publisher.
-# - Unrestricted: Run all scripts.
-help about_Execution_Policies # for more info
-# Current PowerShell version:
-$PSVersionTable
-```
+# Single line comments start with a number symbol.
-Getting help:
+<#
+ Multi-line comments
+ like so
+#>
-```powershell
-# Find commands
-Get-Command about_* # alias: gcm
-Get-Command -Verb Add
-Get-Alias ps
-Get-Alias -Definition Get-Process
-Get-Help ps | less # alias: help
-ps | Get-Member # alias: gm
+####################################################
+## 1. Primitive Datatypes and Operators
+####################################################
+
+# Numbers
+3 # => 3
+
+# Math
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7.0
+
+# Powershell uses banker's rounding,
+# meaning [int]1.5 would round to 2 but so would [int]2.5
+# Division always returns a float.
+# You must cast result to [int] to round.
+[int]5 / [int]3 # => 1.66666666666667
+[int]-5 / [int]3 # => -1.66666666666667
+5.0 / 3.0 # => 1.66666666666667
+-5.0 / 3.0 # => -1.66666666666667
+[int]$result = 5 / 3
+$result # => 2
+
+# Modulo operation
+7 % 3 # => 1
+
+# Exponentiation requires longform or the built-in [Math] class.
+[Math]::Pow(2,3) # => 8
+
+# Enforce order of operations with parentheses.
+1 + 3 * 2 # => 7
+(1 + 3) * 2 # => 8
+
+# Boolean values are primitives (Note: the $)
+$True # => True
+$False # => False
+
+# negate with !
+!$True # => False
+!$False # => True
+
+# Boolean Operators
+# Note "-and" and "-or" usage
+$True -and $False # => False
+$False -or $True # => True
+
+# True and False are actually 1 and 0 but only support limited arithmetic.
+# However, casting the bool to int resolves this.
+$True + $True # => 2
+$True * 8 # => '[System.Boolean] * [System.Int32]' is undefined
+[int]$True * 8 # => 8
+$False - 5 # => -5
+
+# Comparison operators look at the numerical value of True and False.
+0 -eq $False # => True
+1 -eq $True # => True
+2 -eq $True # => False
+-5 -ne $False # => True
+
+# Using boolean logical operators on ints casts to booleans for evaluation.
+# but their non-cast value is returned
+# Don't mix up with bool(ints) and bitwise -band/-bor
+[bool](0) # => False
+[bool](4) # => True
+[bool](-6) # => True
+0 -band 2 # => 0
+-5 -bor 0 # => -5
+
+# Equality is -eq (equals)
+1 -eq 1 # => True
+2 -eq 1 # => False
+
+# Inequality is -ne (notequals)
+1 -ne 1 # => False
+2 -ne 1 # => True
+
+# More comparisons
+1 -lt 10 # => True
+1 -gt 10 # => False
+2 -le 2 # => True
+2 -ge 2 # => True
+
+# Seeing whether a value is in a range
+1 -lt 2 -and 2 -lt 3 # => True
+2 -lt 3 -and 3 -lt 2 # => False
+
+# (-is vs. -eq) -is checks if two objects are the same type.
+# -eq checks if the objects have the same values.
+# Note: we called '[Math]' from .NET previously without the preceeding
+# namespaces. We can do the same with [Collections.ArrayList] if preferred.
+[System.Collections.ArrayList]$a = @() # Point a at a new list
+$a = (1,2,3,4)
+$b = $a # => Point b at what a is pointing to
+$b -is $a.GetType() # => True, a and b equal same type
+$b -eq $a # => True, a and b values are equal
+[System.Collections.Hashtable]$b = @{} # => Point a at a new hash table
+$b = @{'one' = 1
+ 'two' = 2}
+$b -is $a.GetType() # => False, a and b types not equal
+
+# Strings are created with " or ' but " is required for string interpolation
+"This is a string."
+'This is also a string.'
+
+# Strings can be added too! But try not to do this.
+"Hello " + "world!" # => "Hello world!"
+
+# A string can be treated like a list of characters
+"Hello world!"[0] # => 'H'
+
+# You can find the length of a string
+("This is a string").Length # => 16
+
+# You can also format using f-strings or formatted string literals.
+$name = "Steve"
+$age = 22
+"He said his name is $name."
+# => "He said his name is Steve"
+"{0} said he is {1} years old." -f $name, $age
+# => "Steve said he is 22 years old"
+"$name's name is $($name.Length) characters long."
+# => "Steve's name is 5 characters long."
+
+# Escape Characters in Powershell
+# Many languages use the '\', but Windows uses this character for
+# file paths. Powershell thus uses '`' to escape characters
+# Take caution when working with files, as '`' is a
+# valid character in NTFS filenames.
+"Showing`nEscape Chars" # => new line between Showing and Escape
+"Making`tTables`tWith`tTabs" # => Format things with tabs
+
+# Negate pound sign to prevent comment
+# Note that the function of '#' is removed, but '#' is still present
+`#Get-Process # => Fail: not a recognized cmdlet
+
+# $null is not an object
+$null # => None
+
+# $null, 0, and empty strings and arrays all evaluate to False.
+# All other values are True
+function Test-Value ($value) {
+ if ($value) {
+ Write-Output 'True'
+ }
+ else {
+ Write-Output 'False'
+ }
+}
-Show-Command Get-EventLog # Display GUI to fill in the parameters
+Test-Value ($null) # => False
+Test-Value (0) # => False
+Test-Value ("") # => False
+Test-Value [] # => True
+# *[] calls .NET class; creates '[]' string when passed to function
+Test-Value ({}) # => True
+Test-Value @() # => False
-Update-Help # Run as admin
-```
-The tutorial starts here:
+####################################################
+## 2. Variables and Collections
+####################################################
+
+# Powershell uses the "Write-Output" function to print
+Write-Output "I'm Posh. Nice to meet you!" # => I'm Posh. Nice to meet you!
+
+# Simple way to get input data from console
+$userInput = Read-Host "Enter some data: " # Returns the data as a string
+
+# There are no declarations, only assignments.
+# Convention is to use camelCase or PascalCase, whatever your team uses.
+$someVariable = 5
+$someVariable # => 5
+
+# Accessing a previously unassigned variable does not throw exception.
+# The value is $null by default
+
+# Ternary Operators exist in Powershell 7 and up
+0 ? 'yes' : 'no' # => no
-```powershell
-# As you already figured, comments start with #
-
-# Simple hello world example:
-echo Hello world!
-# echo is an alias for Write-Output (=cmdlet)
-# Most cmdlets and functions follow the Verb-Noun naming convention
-
-# Each command starts on a new line, or after a semicolon:
-echo 'This is the first line'; echo 'This is the second line'
-
-# Declaring a variable looks like this:
-$aString="Some string"
-# Or like this:
-$aNumber = 5 -as [double]
-$aList = 1,2,3,4,5
-$anEmptyList = @()
-$aString = $aList -join '--' # yes, -split exists also
-$aHashtable = @{name1='val1'; name2='val2'}
-
-# Using variables:
-echo $aString
-echo "Interpolation: $aString"
-echo "$aString has length of $($aString.Length)"
-echo '$aString'
-echo @"
-This is a Here-String
-$aString
-"@
-# Note that ' (single quote) won't expand the variables!
-# Here-Strings also work with single quote
-
-# Builtin variables:
-# There are some useful builtin variables, like
-echo "Booleans: $TRUE and $FALSE"
-echo "Empty value: $NULL"
-echo "Last program's return value: $?"
-echo "Exit code of last run Windows-based program: $LastExitCode"
-echo "The last token in the last line received by the session: $$"
-echo "The first token: $^"
-echo "Script's PID: $PID"
-echo "Full path of current script directory: $PSScriptRoot"
-echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path
-echo "FUll path of current directory: $Pwd"
-echo "Bound arguments in a function, script or code block: $PSBoundParameters"
-echo "Unbound arguments: $($Args -join ', ')."
-# More builtins: `help about_Automatic_Variables`
-
-# Inline another file (dot operator)
-. .\otherScriptName.ps1
-
-
-### Control Flow
-# We have the usual if structure:
-if ($Age -is [string]) {
- echo 'But.. $Age cannot be a string!'
-} elseif ($Age -lt 12 -and $Age -gt 0) {
- echo 'Child (Less than 12. Greater than 0)'
-} else {
- echo 'Adult'
+
+# The default array object in Powershell is an fixed length array.
+$defaultArray = "thing","thing2","thing3"
+# you can add objects with '+=', but cannot remove objects.
+$defaultArray.Add("thing4") # => Exception "Collection was of a fixed size."
+# To have a more workable array, you'll want the .NET [ArrayList] class
+# It is also worth noting that ArrayLists are significantly faster
+
+# ArrayLists store sequences
+[System.Collections.ArrayList]$array = @()
+# You can start with a prefilled ArrayList
+[System.Collections.ArrayList]$otherArray = @(4, 5, 6)
+
+# Add to the end of a list with 'Add' (Note: produces output, append to $null)
+$array.Add(1) > $null # $array is now [1]
+$array.Add(2) > $null # $array is now [1, 2]
+$array.Add(4) > $null # $array is now [1, 2, 4]
+$array.Add(3) > $null # $array is now [1, 2, 4, 3]
+# Remove from end with index of count of objects-1; array index starts at 0
+$array.RemoveAt($array.Count-1) # => 3 and array is now [1, 2, 4]
+# Let's put it back
+$array.Add(3) > $null # array is now [1, 2, 4, 3] again.
+
+# Access a list like you would any array
+$array[0] # => 1
+# Look at the last element
+$array[-1] # => 3
+
+# Looking out of bounds returns nothing
+$array[4] # blank line returned
+
+# You can look at ranges with slice syntax.
+# The start index is included, the end index is not
+# (It's a closed/open range for you mathy types.)
+$array[1..3] # Return array from index 1 to 3 => [2, 4]
+$array[2..-1] # Return array starting from index 2 => [4, 3]
+$array[0..3] # Return array from beginning until index 3 => [1, 2, 4]
+$array[0..2] # Return array selecting every second entry => [1, 4]
+$array.Reverse() # mutates array to reverse order => [3, 4, 2, 1]
+# Use any combination of these to make advanced slices
+
+# Remove arbitrary elements from a array with "del"
+$array.Remove($array[2]) # $array is now [1, 2, 3]
+
+# Insert an element at a specific index
+$array.Insert(1, 2) # $array is now [1, 2, 3] again
+
+# Get the index of the first item found matching the argument
+$array.IndexOf(2) # => 1
+$array.IndexOf(6) # Returns -1 as "outside array"
+
+# You can add arrays
+# Note: values for $array and for $otherArray are not modified.
+$array + $otherArray # => [1, 2, 3, 4, 5, 6]
+
+# Concatenate arrays with "AddRange()"
+$array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6]
+
+# Check for existence in a array with "in"
+1 -in $array # => True
+
+# Examine length with "Count" (Note: "Length" on arrayList = each items length)
+$array.Count # => 6
+
+
+# Tuples are like arrays but are immutable.
+# To use Tuples in powershell, you must use the .NET tuple class.
+$tuple = [System.Tuple]::Create(1, 2, 3)
+$tuple.Item(0) # => 1
+$tuple.Item(0) = 3 # Raises a TypeError
+
+# You can do some of the array methods on tuples, but they are limited.
+$tuple.Length # => 3
+$tuple + (4, 5, 6) # => Exception
+$tuple[0..2] # => $null
+2 -in $tuple # => False
+
+
+# Hashtables store mappings from keys to values, similar to Dictionaries.
+$emptyHash = @{}
+# Here is a prefilled dictionary
+$filledHash = @{"one"= 1
+ "two"= 2
+ "three"= 3}
+
+# Look up values with []
+$filledHash["one"] # => 1
+
+# Get all keys as an iterable with ".Keys".
+# items maintain the order at which they are inserted into the dictionary.
+$filledHash.Keys # => ["one", "two", "three"]
+
+# Get all values as an iterable with ".Values".
+$filledHash.Values # => [1, 2, 3]
+
+# Check for existence of keys or values in a hash with "-in"
+"one" -in $filledHash.Keys # => True
+1 -in $filledHash.Values # => False
+
+# Looking up a non-existing key returns $null
+$filledHash["four"] # $null
+
+# Adding to a dictionary
+$filledHash.Add("five",5) # $filledHash["five"] is set to 5
+$filledHash.Add("five",6) # exception "Item with key "five" has already been added"
+$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
+
+# Remove keys from a dictionary with del
+$filledHash.Remove("one") # Removes the key "one" from filled dict
+
+
+####################################################
+## 3. Control Flow and Iterables
+####################################################
+
+# Let's just make a variable
+$someVar = 5
+
+# Here is an if statement.
+# This prints "$someVar is smaller than 10"
+if ($someVar -gt 10) {
+ Write-Output "$someVar is bigger than 10."
+}
+elseif ($someVar -lt 10) { # This elseif clause is optional.
+ Write-Output "$someVar is smaller than 10."
+}
+else { # This is optional too.
+ Write-Output "$someVar is indeed 10."
+}
+
+
+<#
+Foreach loops iterate over arrays
+prints:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+#>
+foreach ($animal in ("dog", "cat", "mouse")) {
+ # You can use -f to interpolate formatted strings
+ "{0} is a mammal" -f $animal
+}
+
+<#
+For loops iterate over arrays and you can specify indices
+prints:
+ 0 a
+ 1 b
+ 2 c
+ 3 d
+ 4 e
+ 5 f
+ 6 g
+ 7 h
+#>
+$letters = ('a','b','c','d','e','f','g','h')
+for($i=0; $i -le $letters.Count-1; $i++){
+ Write-Host $i, $letters[$i]
+}
+
+<#
+While loops go until a condition is no longer met.
+prints:
+ 0
+ 1
+ 2
+ 3
+#>
+$x = 0
+while ($x -lt 4) {
+ Write-Output $x
+ $x += 1 # Shorthand for x = x + 1
}
# Switch statements are more powerful compared to most languages
@@ -122,88 +392,53 @@ switch($val) {
{ $_ -like 's*' } { "Case insensitive"; break }
{ $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break }
{ $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break }
- { 'x' -contains 'x'} { "FALSE! -contains is for lists!"; break }
default { "Others" }
}
-# The classic for
-for($i = 1; $i -le 10; $i++) {
- "Loop number $i"
+# Handle exceptions with a try/catch block
+try {
+ # Use "throw" to raise an error
+ throw "This is an error"
}
-# Or shorter
-1..10 | % { "Loop number $_" }
-
-# PowerShell also offers
-foreach ($var in 'val1','val2','val3') { echo $var }
-# while () {}
-# do {} while ()
-# do {} until ()
-
-# Exception handling
-try {} catch {} finally {}
-try {} catch [System.NullReferenceException] {
- echo $_.Exception | Format-List -Force
+catch {
+ Write-Output $Error.ExceptionMessage
+}
+finally {
+ Write-Output "We can clean up resources here"
}
-### Providers
-# List files and directories in the current directory
-ls # or `dir`
-cd ~ # goto home
-
-Get-Alias ls # -> Get-ChildItem
-# Uh!? These cmdlets have generic names because unlike other scripting
-# languages, PowerShell does not only operate in the current directory.
-cd HKCU: # go to the HKEY_CURRENT_USER registry hive
-
-# Get all providers in your session
-Get-PSProvider
-
-
-### Pipeline
-# Cmdlets have parameters that control their execution:
-Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files
-# Only need to type as much of a parameter name until it is no longer ambiguous
-ls -fi *.txt -n # -f is not possible because -Force also exists
-# Use `Get-Help Get-ChildItem -Full` for a complete overview
-
-# Results of the previous cmdlet can be passed to the next as input.
-# `$_` is the current object in the pipeline object.
-ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt
-ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html
+# Writing to a file
+$contents = @{"aa"= 12
+ "bb"= 21}
+$contents | Export-CSV "$env:HOMEDRIVE\file.csv" # writes to a file
-# If you get confused in the pipeline use `Get-Member` for an overview
-# of the available methods and properties of the pipelined objects:
-ls | Get-Member
-Get-Date | gm
+$contents = "test string here"
+$contents | Out-File "$env:HOMEDRIVE\file.txt" # writes to another file
-# ` is the line continuation character. Or end the line with a |
-Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
- | Stop-Process -WhatIf
+# Read file contents and convert to json
+Get-Content "$env:HOMEDRIVE\file.csv" | ConvertTo-Json
-Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
-# Use % as a shorthand for ForEach-Object
-(a,b,c) | ForEach-Object `
- -Begin { "Starting"; $counter = 0 } `
- -Process { "Processing $_"; $counter++ } `
- -End { "Finishing: $counter" }
+####################################################
+## 4. Functions
+####################################################
-# Get-Process as a table with three columns
-# The third column is the value of the VM property in MB and 2 decimal places
-# Computed columns can be written more verbose as:
-# `@{name='lbl';expression={$_}`
-ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
+# Use "function" to create new functions
+# Keep the Verb-Noun naming convention for functions
+function Add-Numbers {
+ $args[0] + $args[1]
+}
+Add-Numbers 1 2 # => 3
-### Functions
-# The [string] attribute is optional.
-function foo([string]$name) {
- echo "Hey $name, have a function"
+# Calling functions with parameters
+function Add-ParamNumbers {
+ param( [int]$firstNumber, [int]$secondNumber )
+ $firstNumber + $secondNumber
}
-# Calling your function
-foo "Say my name"
+Add-ParamNumbers -FirstNumber 1 -SecondNumber 2 # => 3
# Functions with named parameters, parameter attributes, parsable documentation
<#
@@ -220,112 +455,353 @@ New-Website siteName 2000 # ERROR! Port argument could not be validated
('name1','name2') | New-Website -Verbose
#>
function New-Website() {
- [CmdletBinding()]
- param (
- [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
- [Alias('name')]
- [string]$siteName,
- [ValidateSet(3000,5000,8000)]
- [int]$port = 3000
- )
- BEGIN { Write-Verbose 'Creating new website(s)' }
- PROCESS { echo "name: $siteName, port: $port" }
- END { Write-Verbose 'Website(s) created' }
+ [CmdletBinding()]
+ param (
+ [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
+ [Alias('name')]
+ [string]$siteName,
+ [ValidateSet(3000,5000,8000)]
+ [int]$port = 3000
+ )
+ BEGIN { Write-Output 'Creating new website(s)' }
+ PROCESS { Write-Output "name: $siteName, port: $port" }
+ END { Write-Output 'Website(s) created' }
}
-### It's all .NET
-# A PS string is in fact a .NET System.String
-# All .NET methods and properties are thus available
-'string'.ToUpper().Replace('G', 'ggg')
-# Or more powershellish
-'string'.ToUpper() -replace 'G', 'ggg'
-
-# Unsure how that .NET method is called again?
-'string' | gm
-
-# Syntax for calling static .NET methods
-[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
-
-# Note that .NET functions MUST be called with parentheses
-# while PS functions CANNOT be called with parentheses.
-# If you do call a cmdlet/PS function with parentheses,
-# it is the same as passing a single parameter list
-$writer = New-Object System.IO.StreamWriter($path, $true)
-$writer.Write([Environment]::NewLine)
-$writer.Dispose()
-
-### IO
-# Reading a value from input:
-$Name = Read-Host "What's your name?"
-echo "Hello, $Name!"
-[int]$Age = Read-Host "What's your age?"
-
-# Test-Path, Split-Path, Join-Path, Resolve-Path
-# Get-Content filename # returns a string[]
-# Set-Content, Add-Content, Clear-Content
-Get-Command ConvertTo-*,ConvertFrom-*
-
-
-### Useful stuff
-# Refresh your PATH
-$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
- ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
-
-# Find Python in path
-$env:PATH.Split(";") | Where-Object { $_ -like "*python*"}
-
-# Change working directory without having to remember previous path
-Push-Location c:\temp # change working directory to c:\temp
-Pop-Location # change back to previous working directory
-# Aliases are: pushd and popd
-
-# Unblock a directory after download
-Get-ChildItem -Recurse | Unblock-File
-
-# Open Windows Explorer in working directory
-ii .
-
-# Any key to exit
-$host.UI.RawUI.ReadKey()
-return
-
-# Create a shortcut
-$WshShell = New-Object -comObject WScript.Shell
-$Shortcut = $WshShell.CreateShortcut($link)
-$Shortcut.TargetPath = $file
-$Shortcut.WorkingDirectory = Split-Path $file
-$Shortcut.Save()
+####################################################
+## 5. Modules
+####################################################
+
+# You can import modules and install modules
+# The Install-Module is similar to pip or npm, pulls from Powershell Gallery
+Install-Module dbaTools
+Import-Module dbaTools
+
+$query = "SELECT * FROM dbo.sometable"
+$queryParams = @{
+ SqlInstance = 'testInstance'
+ Database = 'testDatabase'
+ Query = $query
+}
+Invoke-DbaQuery @queryParams
+
+# You can get specific functions from a module
+Import-Module -Function Invoke-DbaQuery
+
+
+# Powershell modules are just ordinary Posh files. You
+# can write your own, and import them. The name of the
+# module is the same as the name of the file.
+
+# You can find out which functions and attributes
+# are defined in a module.
+Get-Command -module dbaTools
+Get-Help dbaTools -Full
+
+
+####################################################
+## 6. Classes
+####################################################
+
+# We use the "class" statement to create a class
+class Instrument {
+ [string]$Type
+ [string]$Family
+}
+
+$instrument = [Instrument]::new()
+$instrument.Type = "String Instrument"
+$instrument.Family = "Plucked String"
+
+$instrument
+
+<# Output:
+Type Family
+---- ------
+String Instrument Plucked String
+#>
+
+
+####################################################
+## 6.1 Inheritance
+####################################################
+
+# Inheritance allows new child classes to be defined that inherit
+# methods and variables from their parent class.
+
+class Guitar : Instrument
+{
+ [string]$Brand
+ [string]$SubType
+ [string]$ModelType
+ [string]$ModelNumber
+}
+
+$myGuitar = [Guitar]::new()
+$myGuitar.Brand = "Taylor"
+$myGuitar.SubType = "Acoustic"
+$myGuitar.ModelType = "Presentation"
+$myGuitar.ModelNumber = "PS14ce Blackwood"
+
+$myGuitar.GetType()
+
+<#
+IsPublic IsSerial Name BaseType
+-------- -------- ---- --------
+True False Guitar Instrument
+#>
+
+
+####################################################
+## 7. Advanced
+####################################################
+
+# The powershell pipeline allows things like High-Order Functions.
+
+# Group-Object is a handy cmdlet that does incredible things.
+# It works much like a GROUP BY in SQL.
+
+<#
+ The following will get all the running processes,
+ group them by Name,
+ and tell us how many instances of each process we have running.
+ Tip: Chrome and svcHost are usually big numbers in this regard.
+#>
+Get-Process | Foreach-Object ProcessName | Group-Object
+
+# Useful pipeline examples are iteration and filtering.
+1..10 | ForEach-Object { "Loop number $PSITEM" }
+1..10 | Where-Object { $PSITEM -gt 5 } | ConvertTo-Json
+
+# A notable pitfall of the pipeline is it's performance when
+# compared with other options.
+# Additionally, raw bytes are not passed through the pipeline,
+# so passing an image causes some issues.
+# See more on that in the link at the bottom.
+
+<#
+ Asynchronous functions exist in the form of jobs.
+ Typically a procedural language,
+ Powershell can operate non-blocking functions when invoked as Jobs.
+#>
+
+# This function is known to be non-optimized, and therefore slow.
+$installedApps = Get-CimInstance -ClassName Win32_Product
+
+# If we had a script, it would hang at this func for a period of time.
+$scriptBlock = {Get-CimInstance -ClassName Win32_Product}
+Start-Job -ScriptBlock $scriptBlock
+
+# This will start a background job that runs the command.
+# You can then obtain the status of jobs and their returned results.
+$allJobs = Get-Job
+$jobResponse = Get-Job | Receive-Job
+
+
+# Math is built in to powershell and has many functions.
+$r=2
+$pi=[math]::pi
+$r2=[math]::pow( $r, 2 )
+$area = $pi*$r2
+$area
+
+# To see all possibilities, check the members.
+[System.Math] | Get-Member -Static -MemberType All
+
+
+<#
+ This is a silly one:
+ You may one day be asked to create a func that could take $start and $end
+ and reverse anything in an array within the given range
+ based on an arbitrary array without mutating the original array.
+ Let's see one way to do that and introduce another data structure.
+#>
+
+$targetArray = 'a','b','c','d','e','f','g','h','i','j','k','l','m'
+
+function Format-Range ($start, $end, $array) {
+ [System.Collections.ArrayList]$firstSectionArray = @()
+ [System.Collections.ArrayList]$secondSectionArray = @()
+ [System.Collections.Stack]$stack = @()
+ for ($index = 0; $index -lt $array.Count; $index++) {
+ if ($index -lt $start) {
+ $firstSectionArray.Add($array[$index]) > $null
+ }
+ elseif ($index -ge $start -and $index -le $end) {
+ $stack.Push($array[$index])
+ }
+ else {
+ $secondSectionArray.Add($array[$index]) > $null
+ }
+ }
+ $finalArray = $firstSectionArray + $stack.ToArray() + $secondSectionArray
+ return $finalArray
+}
+
+Format-Range 2 6 $targetArray
+# => 'a','b','g','f','e','d','c','h','i','j','k','l','m'
+
+# The previous method works, but uses extra memory by allocating new arrays.
+# It's also kind of lengthy.
+# Let's see how we can do this without allocating a new array.
+# This is slightly faster as well.
+
+function Format-Range ($start, $end) {
+ while ($start -lt $end)
+ {
+ $temp = $targetArray[$start]
+ $targetArray[$start] = $targetArray[$end]
+ $targetArray[$end] = $temp
+ $start++
+ $end--
+ }
+ return $targetArray
+}
+
+Format-Range 2 6 # => 'a','b','g','f','e','d','c','h','i','j','k','l','m'
```
+Powershell as a Tool:
+
+Getting Help:
+```Powershell
+# Find commands
+Get-Command about_* # alias: gcm
+Get-Command -Verb Add
+Get-Alias ps
+Get-Alias -Definition Get-Process
-Configuring your shell
+Get-Help ps | less # alias: help
+ps | Get-Member # alias: gm
-```powershell
-# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1`
-# All code there will be executed when the PS session starts
-if (-not (Test-Path $Profile)) {
- New-Item -Type file -Path $Profile -Force
- notepad $Profile
+Show-Command Get-WinEvent # Display GUI to fill in the parameters
+
+Update-Help # Run as admin
+```
+
+If you are uncertain about your environment:
+
+```Powershell
+Get-ExecutionPolicy -List
+Set-ExecutionPolicy AllSigned
+# Execution policies include:
+# - Restricted: Scripts won't run.
+# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher.
+# - AllSigned: Scripts need to be signed by a trusted publisher.
+# - Unrestricted: Run all scripts.
+help about_Execution_Policies # for more info
+
+# Current PowerShell version:
+$PSVersionTable
+```
+
+```Powershell
+# Calling external commands, executables,
+# and functions with the call operator.
+# Exe paths with arguments passed or containing spaces can create issues.
+C:\Program Files\dotnet\dotnet.exe
+# The term 'C:\Program' is not recognized as a name of a cmdlet,
+# function, script file, or executable program.
+# Check the spelling of the name, or if a path was included,
+# verify that the path is correct and try again
+
+"C:\Program Files\dotnet\dotnet.exe"
+C:\Program Files\dotnet\dotnet.exe # returns string rather than execute
+
+&"C:\Program Files\dotnet\dotnet.exe --help" # fail
+&"C:\Program Files\dotnet\dotnet.exe" --help # success
+# Alternatively, you can use dot-sourcing here
+."C:\Program Files\dotnet\dotnet.exe" --help # success
+
+# the call operator (&) is similar to Invoke-Expression,
+# but IEX runs in current scope.
+# One usage of '&' would be to invoke a scriptblock inside of your script.
+# Notice the variables are scoped
+$i = 2
+$scriptBlock = { $i=5; Write-Output $i }
+& $scriptBlock # => 5
+$i # => 2
+
+invoke-expression ' $i=5; Write-Output $i ' # => 5
+$i # => 5
+
+# Alternatively, to preserve changes to public variables
+# you can use "Dot-Sourcing". This will run in the current scope.
+$x=1
+&{$x=2};$x # => 1
+
+.{$x=2};$x # => 2
+
+
+# Remoting into computers is easy.
+Enter-PSSession -ComputerName RemoteComputer
+
+# Once remoted in, you can run commands as if you're local.
+RemoteComputer\PS> Get-Process powershell
+
+<#
+Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
+------- ------ ----- ----- ------ -- -- -----------
+ 1096 44 156324 179068 29.92 11772 1 powershell
+ 545 25 49512 49852 25348 0 powershell
+#>
+RemoteComputer\PS> Exit-PSSession
+
+<#
+ Powershell is an incredible tool for Windows management and Automation.
+ Let's take the following scenario:
+ You have 10 servers.
+ You need to check whether a service is running on all of them.
+ You can RDP and log in, or PSSession to all of them, but why?
+ Check out the following
+#>
+
+$serverList = @(
+ 'server1',
+ 'server2',
+ 'server3',
+ 'server4',
+ 'server5',
+ 'server6',
+ 'server7',
+ 'server8',
+ 'server9',
+ 'server10'
+)
+
+[scriptblock]$script = {
+ Get-Service -DisplayName 'Task Scheduler'
+}
+
+foreach ($server in $serverList) {
+ $cmdSplat = @{
+ ComputerName = $server
+ JobName = 'checkService'
+ ScriptBlock = $script
+ AsJob = $true
+ ErrorAction = 'SilentlyContinue'
+ }
+ Invoke-Command @cmdSplat | Out-Null
}
-# More info: `help about_profiles`
-# For a more useful shell, be sure to check the project PSReadLine below
+
+<#
+ Here we've invoked jobs across many servers.
+ We can now Receive-Job and see if they're all running.
+ Now scale this up 100x as many servers :)
+#>
```
Interesting Projects
* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
+* [KevinMarquette's Powershell Blog](https://powershellexplained.com/) Excellent blog that goes into great detail on Powershell
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
+* [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac
* [PSake](https://github.com/psake/psake) Build automation tool
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
* [PowerShell Community Extensions](https://github.com/Pscx/Pscx)
-
-Not covered
-
-* WMI: Windows Management Intrumentation (Get-CimInstance)
-* Multitasking: Start-Job -scriptBlock {...},
-* Code Signing
-* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command)
+* [More on the Powershell Pipeline Issue](https://github.com/PowerShell/PowerShell/issues/1908)
diff --git a/processing.html.markdown b/processing.html.markdown
index d99912e7..777c6981 100644
--- a/processing.html.markdown
+++ b/processing.html.markdown
@@ -150,7 +150,7 @@ SomeRandomClass myObjectInstantiated = new SomeRandomClass();
// operations.
float f = sq(3); // f = 9.0
float p = pow(3, 3); // p = 27.0
-int a = abs(-13) // a = 13
+int a = abs(-13); // a = 13
int r1 = round(3.1); // r1 = 3
int r2 = round(3.7); // r2 = 4
float sr = sqrt(25); // sr = 5.0
@@ -191,6 +191,8 @@ int i = 3;
String value = (i > 5) ? "Big" : "Small"; // "Small"
// Switch-case structure can be used to check multiple conditions concisely.
+// It is important to use the break statement. If the `break`-statement does
+// not exist the program executes all the following cases after a case was true.
int value = 2;
switch(value) {
case 0:
@@ -209,7 +211,7 @@ switch(value) {
// Iterative statements
// For Statements - Again, the same syntax as in Java
-for(int i = 0; i < 5; i ++){
+for(int i = 0; i < 5; i++){
print(i); // prints from 0 to 4
}
@@ -354,14 +356,14 @@ color c = color(255, 255, 255); // WHITE!
// By default, Processing uses RGB colour scheme but it can be configured to
// HSB using colorMode(). Read more here:
// (https://processing.org/reference/colorMode_.html)
-background(color); // By now, the background colour should be white.
+background(c); // By now, the background colour should be white.
// You can use fill() function to select the colour for filling the shapes.
// It has to be configured before you start drawing shapes so the colours gets
// applied.
fill(color(0, 0, 0));
// If you just want to colour the outlines of the shapes then you can use
// stroke() function.
-stroke(255, 255, 255, 200); // stroke colour set to yellow with transparency
+stroke(255, 255, 0, 200); // stroke colour set to yellow with transparency
// set to a lower value.
// Images
diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown
index 9bf770fd..70d0a01c 100644
--- a/pt-br/awk-pt.html.markdown
+++ b/pt-br/awk-pt.html.markdown
@@ -317,8 +317,8 @@ a > 0 {
# 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:
+# 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
diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown
index 86d1a8ea..ab003a18 100644
--- a/pt-br/bash-pt.html.markdown
+++ b/pt-br/bash-pt.html.markdown
@@ -17,7 +17,7 @@ lang: pt-br
Tutorial de shell em português
Bash é o nome do shell do Unix, que também é distribuído como shell do sistema
-operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos
+operacional GNU e como shell padrão para Linux e macOS. Praticamente todos
os exemplos abaixo podem fazer parte de um shell script e pode ser executados
diretamente no shell.
@@ -47,7 +47,7 @@ Variavel = "Alguma string"
# Ou assim:
Variavel= 'Alguma string'
# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornará
-# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel='
+# um erro porque o comando não pôde ser encontrado. (Nesse caso a a parte 'Variavel='
# é vista com uma declaração de variável válida apenas para o escopo do comando 'Uma string').
# Usando a variável:
@@ -73,7 +73,7 @@ echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"}
# Note que isso apenas retornará o valor padrão e não mudará o valor da variável.
# Variáveis internas
-# Tem algumas variáveis internas bem uteis, como
+# Tem algumas variáveis internas bem úteis, como
echo "O ultimo retorno do programa: $?"
echo "PID do script: $$"
echo "Numero de argumentos passados para o script $#"
@@ -165,7 +165,7 @@ echo "#helloworld" | tee output.out > /dev/null
rm -v output.out error.err output-and-error.log
# Comando podem ser substituídos por outros comandos usando $( ):
-# O comando a seguir mostra o número de arquivos e diretórios no diretorio atual
+# O comando a seguir mostra o número de arquivos e diretórios no diretório atual
echo "Existem $(ls | wc -l) itens aqui."
# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se
@@ -248,7 +248,7 @@ sed -i 's/okay/legal/g' file.txt
# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex
# O exemplo exibe linhas que começam com "foo" e terminam com "bar"
grep "^foo.*bar$" arquivo.txt
-# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex
+# passe a opção "-c" para ao invés de imprimir o número da linha que bate com o regex
grep -c "^foo.*bar$" arquivo.txt
# se você quer literalmente procurar por uma string,
# e não pelo regex, use fgrep (ou grep -F)
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index 38937894..e6dea5b8 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -14,7 +14,7 @@ translators:
lang: pt-br
---
-No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornara comum.
+No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornaram comuns.
CSS ajuda a manter a separação entre o conteúdo (HTML) e o visual de uma página web.
@@ -130,7 +130,7 @@ seletor::after {}
   os elementos */
* {} /* */ Todos os elementos
.parent * {} /* */ todos os descendentes
-.parent> * {} /* */ todas as crianças
+.parent> * {} /* */ todos os filhos
/* ####################
   ## PROPRIEDADES
@@ -141,7 +141,7 @@ seletor {
    /* Unidades de comprimento pode ser absoluta ou relativa. */
    /* Unidades relativas */
-    width: 50%; /* Percentagem de largura elemento pai */
+    width: 50%; /* Percentagem de largura do elemento pai */
    font-size: 2em; /* Múltiplos de font-size original de elemento */
    font-size: 2rem; /* Ou do elemento raiz font-size */
    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
@@ -200,7 +200,7 @@ Salvar uma folha de estilo CSS com a extensão `.css`.
## Precedência ou Cascata
-Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
+Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre as outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata.
@@ -279,7 +279,7 @@ Muitos smartphones e tablets tentarão renderizar a página como se estivesse nu
## Compatibilidade
-A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso.
+A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática verificar antes de usar um novo recurso.
## Recursos
diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown
index f8c56101..4ba78f52 100644
--- a/pt-br/elixir-pt.html.markdown
+++ b/pt-br/elixir-pt.html.markdown
@@ -40,7 +40,7 @@ e muitos outros recursos.
# Tuplas que são guardadas contiguamente em memória.
{1,2,3} # tupla
-# Podemos acessar um elemento de uma tupla om a função `elem`:
+# Podemos acessar um elemento de uma tupla com a função `elem`:
elem({1, 2, 3}, 0) #=> 1
# Listas que são implementadas como listas ligadas.
diff --git a/pt-br/fsharp-pt.html.markdown b/pt-br/fsharp-pt.html.markdown
new file mode 100644
index 00000000..55966cda
--- /dev/null
+++ b/pt-br/fsharp-pt.html.markdown
@@ -0,0 +1,639 @@
+---
+language: F#
+filename: learnfsharp-pt.fs
+contributors:
+ - ["Scott Wlaschin", "http://fsharpforfunandprofit.com"]
+ - ["Adelar da Silva Queiróz", "https://adelarsq.github.io"]
+lang: pt-br
+---
+
+F# é uma linguagem de propósito geral funcional e orientada a objetos. É livre, de código aberto e executa em Linux, Mac, Windows e outros.
+
+Possui um sistema de tipagem poderoso que evita muitos erros em tempo de compilação. Para isto utilizando inferência de tipos, o que a faz se comportar como uma linguagem dinâmica.
+
+A sintaxe é diferente das linguagens do estilo C (C, C#, Java, etc):
+
+* Chaves não são usadas para delimitar blocos de código. Ao invés disso é utilizada indentação (semelhante ao Python).
+* Espaços em branco são usados para separar parâmetros, ao invés de vírgulas.
+
+Se você deseja executar o código abaixo, copie e cole em [https://try.fsharp.org](https://try.fsharp.org), que é um REPL online.
+
+```fsharp
+
+// comentários de linhas únicas usam barras duplas
+(* comentários de linhas múltiplas usam o par (* . . . *)
+
+-fim do comentário de linhas múltiplas- *)
+
+// ================================================
+// Sintaxe básica
+// ================================================
+
+// ------ "Variáveis" (mas não exatamente) ------
+// A palavra reservada "let" define um valor imutável
+let myInt = 5
+let myFloat = 3.14
+let myString = "hello" // note que nenhum tipo é necessário
+
+// ------ Listas ------
+let twoToFive = [2; 3; 4; 5] // Colchetes criam uma lista com
+ // ponto e vírgula como delimitadores
+let oneToFive = 1 :: twoToFive // :: cria uma lista com um novo primeiro elemento
+// O resultado é [1; 2; 3; 4; 5]
+let zeroToFive = [0; 1] @ twoToFive // @ concatena duas listas
+
+// IMPORTANTE: vírgulas nunca são usadas como delimitadores, somente ponto e vírgula!
+
+// ------ Funções ------
+// A palavra chave "let" também define nomes para funções.
+let square x = x * x // Note que não são usados parêntesis
+square 3 // Agora executando a função. Também sem parêntesis
+
+let add x y = x + y // Não use add (x,y)! Isto significa algo
+ // completamente diferente.
+add 2 3 // Agora execute a função.
+
+// para definir uma função de múltiplas linhas apenas use indentação. Nenhum ponto e vírgula é necessário
+let evens list =
+ let isEven x = x % 2 = 0 // Define "isEven"como uma sub função. Note
+ // que o operador de igualdade é um simples "=".
+ List.filter isEven list // List.filter é uma função da biblioteca padrão
+ // com dois parâmetros: uma função que retorna boolean
+ // e uma lista para verificar
+
+evens oneToFive // Agora executando a função
+
+// Usando parênteses é possível deixar mais clara a precedência. Neste exemplo,
+// "map" é usado primeiro, com dois argumentos, então executa "sum" no resultado.
+// Sem os parênteses, "List.map" seria passado como uma argumento para List.sum
+let sumOfSquaresTo100 =
+ List.sum ( List.map square [1..100] )
+
+// É possível redirecionar a saída de uma operação para a próxima usando pipe ("|>")
+// Redirecimento de dados é algo comum em F#, similar a pipes Unix.
+
+// Aqui é a mesma função sumOfSquares escrita com pipe
+let sumOfSquaresTo100piped =
+ [1..100] |> List.map square |> List.sum // "square" foi definido anteriormente
+
+// você pode definir lambdas (funções anônimas) usando a palavra reservada "fun"
+let sumOfSquaresTo100withFun =
+ [1..100] |> List.map (fun x -> x * x) |> List.sum
+
+// Em F# não há a palavra chave "return". Funções sempre
+// retornam o valor da última expressão usada.
+
+// ------ Casamento de padrões (Pattern Matching) ------
+// Match..with.. é um poderoso case/switch.
+let simplePatternMatch =
+ let x = "a"
+ match x with
+ | "a" -> printfn "x is a"
+ | "b" -> printfn "x is b"
+ | _ -> printfn "x is something else" // sublinhado combina com qualquer coisa
+
+// F# não permite null por padrão -- deve-se usar um Option
+// e então efetuar um casamento de padrão.
+// Some(..) e None são análogos a Nullable
+let validValue = Some(99)
+let invalidValue = None
+
+// Neste exemplo, match..with casa com "Some" e "None",
+// e também desconstrói o valor em "Some" ao mesmo tempo.
+let optionPatternMatch input =
+ match input with
+ | Some i -> printfn "input is an int=%d" i
+ | None -> printfn "input is missing"
+
+optionPatternMatch validValue
+optionPatternMatch invalidValue
+
+// ------ Escrevando na tela ------
+// As funções printf/printfn são similares às
+// Console.Write/WriteLine encontradas no C#.
+printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
+printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
+
+// Exitem também as funções sprintf/sprintfn para formatação de dados
+// em uma string, semelhante à String.Format do C#.
+
+// ================================================
+// Mais sobre funções
+// ================================================
+
+// F# é uma liguagem verdadeiramente funcional -- funções fazem
+// parte das classes e podem ser combinadas facilmente para criar
+// poderosos construtores
+
+// Módulos podem usar um grupo de funções
+// É necessário usar indentação para defini-las.
+module FunctionExamples =
+
+ // define uma função de soma
+ let add x y = x + y
+
+ // básico uso de uma função
+ let a = add 1 2
+ printfn "1 + 2 = %i" a
+
+ // aplicação parcial de parâmetros
+ let add42 = add 42
+ let b = add42 1
+ printfn "42 + 1 = %i" b
+
+ // composição para combinar funções
+ let add1 = add 1
+ let add2 = add 2
+ let add3 = add1 >> add2
+ let c = add3 7
+ printfn "3 + 7 = %i" c
+
+ // funções de alta ordem
+ [1..10] |> List.map add3 |> printfn "new list is %A"
+
+ // listas de funções e mais
+ let add6 = [add1; add2; add3] |> List.reduce (>>)
+ let d = add6 7
+ printfn "1 + 2 + 3 + 7 = %i" d
+
+// ================================================
+// Listas e coleções
+// ================================================
+
+// Existem três tipos de coleções ordenadas:
+// * Listas são o tipo mais básico de coleção imutável;
+// * Arrays são mutáveis e mais eficientes;
+// * Sequences são lazy e infinitas (semelhante a enumerator).
+//
+// Outras coleções incluem maps e conjuntos imutáveis
+// mais todas as coleções padrões do .NET
+
+module ListExamples =
+
+ // listas usam colchetes
+ let list1 = ["a"; "b"]
+ let list2 = "c" :: list1 // :: é usado para adicionar um elemento no início da lista
+ let list3 = list1 @ list2 // @ é o operador de concatenação
+
+ // list comprehensions (generators)
+ let squares = [for i in 1..10 do yield i * i]
+
+ // Um gerador de números primos
+ // - este usa a notação custa para casamento de padrões
+ // - (p::xs) significa 'primeiro :: cauda' da lista, e pode ser escrito como p :: xs
+ // isto significa que casa 'p' (o primeiro item da lista), e xs recebe o resto da lista
+ // que é chamdo de 'cons pattern'
+ // - usa a palavra chave 'rec', que é necessária quando se usa recursão
+ let rec sieve = function
+ | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
+ | [] -> []
+ let primes = sieve [2..50]
+ printfn "%A" primes
+
+ // casamento de padrões (pattern matching) com listas
+ let listMatcher aList =
+ match aList with
+ | [] -> printfn "the list is empty"
+ | [first] -> printfn "the list has one element %A " first
+ | [first; second] -> printfn "list is %A and %A" first second
+ | first :: _ -> printfn "the list has more than two elements, first element %A" first
+
+ listMatcher [1; 2; 3; 4]
+ listMatcher [1; 2]
+ listMatcher [1]
+ listMatcher []
+
+ // recursão usando listas
+ let rec sum aList =
+ match aList with
+ | [] -> 0
+ | x::xs -> x + sum xs
+ sum [1..10]
+
+ // -----------------------------------------
+ // Funções da biblioteca padrão
+ // -----------------------------------------
+
+ // mapas
+ let add3 x = x + 3
+ [1..10] |> List.map add3
+
+ // filtros
+ let even x = x % 2 = 0
+ [1..10] |> List.filter even
+
+ // muito mais -- veja a documentação
+
+module ArrayExamples =
+
+ // arrays usam colchetes com barra vertical
+ let array1 = [| "a"; "b" |]
+ let first = array1.[0] // acesso por índice usando ponto
+
+ // casamento de padrões (pattern matching) para arrays é feito da mesma forma que de listas
+ let arrayMatcher aList =
+ match aList with
+ | [| |] -> printfn "the array is empty"
+ | [| first |] -> printfn "the array has one element %A " first
+ | [| first; second |] -> printfn "array is %A and %A" first second
+ | _ -> printfn "the array has more than two elements"
+
+ arrayMatcher [| 1; 2; 3; 4 |]
+
+ // As funções da biblioteca padrão são as mesmas que para List
+
+ [| 1..10 |]
+ |> Array.map (fun i -> i + 3)
+ |> Array.filter (fun i -> i % 2 = 0)
+ |> Array.iter (printfn "value is %i. ")
+
+
+module SequenceExamples =
+
+ // sequências usam chaves
+ let seq1 = seq { yield "a"; yield "b" }
+
+ // sequências podem usar yield e
+ // podem conter subsequencias
+ let strange = seq {
+ // "yield" adiciona um elemento
+ yield 1; yield 2;
+
+ // "yield!" adiciona uma subsequencia
+ yield! [5..10]
+ yield! seq {
+ for i in 1..10 do
+ if i % 2 = 0 then yield i }}
+ // teste
+ strange |> Seq.toList
+
+ // Sequências podem ser criadas usando "unfold"
+ // Este é um exemplo da série de Fibonacci
+ let fib = Seq.unfold (fun (fst,snd) ->
+ Some(fst + snd, (snd, fst + snd))) (0,1)
+
+ // teste
+ let fib10 = fib |> Seq.take 10 |> Seq.toList
+ printf "first 10 fibs are %A" fib10
+
+
+// ================================================
+// Tipos de dados
+// ================================================
+
+module DataTypeExamples =
+
+ // Todos os dados são imutáveis por padrão
+
+ // Tuplas são uma forma rápida de reprentar n elementos de tipos anônimos
+ // -- Use a vírgula para criar uma tupla
+ let twoTuple = 1, 2
+ let threeTuple = "a", 2, true
+
+ // Casamento de padrões (pattern match) para desconstruir
+ let x, y = twoTuple // atribui x = 1, y = 2
+
+ // ------------------------------------
+ // O tipo registro possui nomes nos campos
+ // ------------------------------------
+
+ // Use "type" com chaves para definir um registro
+ type Person = {First:string; Last:string}
+
+ // Use "let" com chaves para criar um registro
+ let person1 = {First="John"; Last="Doe"}
+
+ // Casamento de padrões para desconstruir
+ let {First = first} = person1 // atribui first="John"
+
+ // ------------------------------------
+ // Tipos union (variantes) possuem um conjunto de escolhas
+ // Somente um caso pode ser válido por vez.
+ // ------------------------------------
+
+ // Use "type" com barra/pipe para definir um union
+ type Temp =
+ | DegreesC of float
+ | DegreesF of float
+
+ // Use qualquer dos tipos para criar um
+ let temp1 = DegreesF 98.6
+ let temp2 = DegreesC 37.0
+
+ // Casamento de padrões deve cobrir todos os tipos de definidos para desconstruir
+ let printTemp = function
+ | DegreesC t -> printfn "%f degC" t
+ | DegreesF t -> printfn "%f degF" t
+
+ printTemp temp1
+ printTemp temp2
+
+ // ------------------------------------
+ // Tipos recursivos
+ // ------------------------------------
+
+ // Tipos podem ser combinados recursivamente de formas complexas
+ // sem ter que criar subclasses
+ type Employee =
+ | Worker of Person
+ | Manager of Employee list
+
+ let jdoe = {First="John"; Last="Doe"}
+ let worker = Worker jdoe
+
+ // ------------------------------------
+ // Modelando com tipos
+ // ------------------------------------
+
+ // Tipos union são muito bons para modelagem de estados sem usar flags
+ type EmailAddress =
+ | ValidEmailAddress of string
+ | InvalidEmailAddress of string
+
+ let trySendEmail email =
+ match email with // casamento de padrões
+ | ValidEmailAddress address -> () // envia
+ | InvalidEmailAddress address -> () // não envia
+
+ // A combinação de tipos union e registros juntos
+ // provê uma grande fundação para DDD (Domain Driven Design).
+ // Você pode criar centenas de pequenos tipos que refletem
+ // exatamente o seu domínio.
+
+ type CartItem = { ProductCode: string; Qty: int }
+ type Payment = Payment of float
+ type ActiveCartData = { UnpaidItems: CartItem list }
+ type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
+
+ type ShoppingCart =
+ | EmptyCart // nenhum dado
+ | ActiveCart of ActiveCartData
+ | PaidCart of PaidCartData
+
+ // ------------------------------------
+ // Comportamento padrão para tipos
+ // ------------------------------------
+
+ // Tipos padrões possuem um padrão já definido, não precisando de codificação nenhuma.
+ // * Imutáveis
+ // * Impressão formatada para depuração
+ // * Igualdade e comparação
+ // * Serialização
+
+ // Impressão formatada usando %A
+ printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
+ twoTuple person1 temp1 worker
+
+ // Igualdade e comparação padrão.
+ // Um exemplo com cartas:
+ type Suit = Club | Diamond | Spade | Heart
+ type Rank = Two | Three | Four | Five | Six | Seven | Eight
+ | Nine | Ten | Jack | Queen | King | Ace
+
+ let hand = [ Club, Ace; Heart, Three; Heart, Ace;
+ Spade, Jack; Diamond, Two; Diamond, Ace ]
+
+ // ordenando
+ List.sort hand |> printfn "sorted hand is (low to high) %A"
+ List.max hand |> printfn "high card is %A"
+ List.min hand |> printfn "low card is %A"
+
+
+// ================================================
+// Padrões ativos (Active patterns)
+// ================================================
+
+module ActivePatternExamples =
+
+ // F# possui um tipo especial de casamento de padrões chamado "padrões ativos" ("active patterns")
+ // onde o padrão pode ser interpretado ou detectado dinamicamente.
+
+ // parêntesis e barra são a sintaxe para "padrões ativos"
+
+ // Você pode usar "elif" ao invés de "else if" em expressões condicionais.
+ // Elas são equivalentes em F#
+
+ // por exemplo, defina um "padrão ativo" para tratar tipos de caracteres...
+ let (|Digit|Letter|Whitespace|Other|) ch =
+ if System.Char.IsDigit(ch) then Digit
+ elif System.Char.IsLetter(ch) then Letter
+ elif System.Char.IsWhiteSpace(ch) then Whitespace
+ else Other
+
+ // ... e então use ele para interpretar de forma bem mais simples
+ let printChar ch =
+ match ch with
+ | Digit -> printfn "%c is a Digit" ch
+ | Letter -> printfn "%c is a Letter" ch
+ | Whitespace -> printfn "%c is a Whitespace" ch
+ | _ -> printfn "%c is something else" ch
+
+ // imprima a lista
+ ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
+
+ // ------------------------------------------------
+ // FizzBuzz usando padrões ativos (active patterns)
+ // ------------------------------------------------
+
+ // É possível criar casamento de padrões parcial também
+ // Apenas use sublinhado para a definição, e retorne Some se casado.
+ let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
+ let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
+
+ // a função principal
+ let fizzBuzz i =
+ match i with
+ | MultOf3 & MultOf5 -> printf "FizzBuzz, "
+ | MultOf3 -> printf "Fizz, "
+ | MultOf5 -> printf "Buzz, "
+ | _ -> printf "%i, " i
+
+ // teste
+ [1..20] |> List.iter fizzBuzz
+
+// ================================================
+// Expressividade
+// ================================================
+
+module AlgorithmExamples =
+
+ // F# possui uma alta razão sinais/ruídos, assim o código
+ // é lido praticamento como se descreve o algoritmo
+
+ // ------ Exemplo: defina uma função que faça soma dos quadrados ------
+ let sumOfSquares n =
+ [1..n] // 1) pega todos os números de 1 a n
+ |> List.map square // 2) eleva ao quadrado cada um
+ |> List.sum // 3) soma os resultados
+
+ // teste
+ sumOfSquares 100 |> printfn "Sum of squares = %A"
+
+ // ------ Examplo: defina uma função de ordenação ------
+ let rec sort list =
+ match list with
+ // Se a lista está vazia
+ | [] ->
+ [] // retorna a lista vazia
+ // Se a lista não está vazia
+ | firstElem::otherElements -> // pega o primeiro elemento
+ let smallerElements = // extrai os elementos menores
+ otherElements // dos restantes
+ |> List.filter (fun e -> e < firstElem)
+ |> sort // e ordena eles
+ let largerElements = // extrai os elementos maiores
+ otherElements // dos restantes
+ |> List.filter (fun e -> e >= firstElem)
+ |> sort // e ordena eles
+ // Combine as 3 partes em uma nova lista e retorne ela
+ List.concat [smallerElements; [firstElem]; largerElements]
+
+ // teste
+ sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
+
+// ================================================
+// Código assíncrono
+// ================================================
+
+module AsyncExample =
+
+ // F# possui suporte a funcionalidades para ajudar a escrever código assíncrono
+ // sem tornar o código difícil de manter ("pyramid of doom")
+ //
+ // O seguinte exemplo efetua download de um conjunto de páginas em paralelo.
+
+ open System.Net
+ open System
+ open System.IO
+ open Microsoft.FSharp.Control.CommonExtensions
+
+ // Obtém o conteúdo de cara página de forma assíncrona
+ let fetchUrlAsync url =
+ async { // a palavra chave "async" e chaves
+ // criam um objeto assíncrono
+ let req = WebRequest.Create(Uri(url))
+ use! resp = req.AsyncGetResponse()
+ // use! é uma atribuição assíncrona
+ use stream = resp.GetResponseStream()
+ // "use" dispara automaticamente close()
+ // no recurso no fim do escopo
+ use reader = new IO.StreamReader(stream)
+ let html = reader.ReadToEnd()
+ printfn "finished downloading %s" url
+ }
+
+ // uma lista de sites para fazer download
+ let sites = ["http://www.bing.com";
+ "http://www.google.com";
+ "http://www.microsoft.com";
+ "http://www.amazon.com";
+ "http://www.yahoo.com"]
+
+ // efetue
+ sites
+ |> List.map fetchUrlAsync // cria uma lista de tarefas assíncronas
+ |> Async.Parallel // coloca as tarefas para executarem em paralelo
+ |> Async.RunSynchronously // inicia cada uma
+
+// ================================================
+// Compatibilidade com .NET
+// ================================================
+
+module NetCompatibilityExamples =
+
+ // F# pode pode fazer praticamente tudo que C# pode fazer, e integra
+ // de forma simples com bibliotecas .NET e Mono
+
+ // ------- usando uma função de uma biblioteca existente -------
+
+ let (i1success, i1) = System.Int32.TryParse("123");
+ if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
+
+ // ------- Implementando interfaces de forma simples! -------
+
+ // cria um novo objeto que implementa IDisposable
+ let makeResource name =
+ { new System.IDisposable
+ with member this.Dispose() = printfn "%s disposed" name }
+
+ let useAndDisposeResources =
+ use r1 = makeResource "first resource"
+ printfn "using first resource"
+ for i in [1..3] do
+ let resourceName = sprintf "\tinner resource %d" i
+ use temp = makeResource resourceName
+ printfn "\tdo something with %s" resourceName
+ use r2 = makeResource "second resource"
+ printfn "using second resource"
+ printfn "done."
+
+ // ------- Código orientado a objetos -------
+
+ // F# também possui suporte a orientação a objetos.
+ // Possui suporte a classes, herança, métodos virtuais, etc.
+
+ // interface com tipo genérico
+ type IEnumerator<'a> =
+ abstract member Current : 'a
+ abstract MoveNext : unit -> bool
+
+ // classe base abstrata com métodos virtuais
+ [<AbstractClass>]
+ type Shape() =
+ // propriedades somente leitura
+ abstract member Width : int with get
+ abstract member Height : int with get
+ // método não virtual
+ member this.BoundingArea = this.Height * this.Width
+ // método virtual com implementação base
+ abstract member Print : unit -> unit
+ default this.Print () = printfn "I'm a shape"
+
+ // classe concreta que herda da classe base e sobrescreve
+ type Rectangle(x:int, y:int) =
+ inherit Shape()
+ override this.Width = x
+ override this.Height = y
+ override this.Print () = printfn "I'm a Rectangle"
+
+ // testes
+ let r = Rectangle(2, 3)
+ printfn "The width is %i" r.Width
+ printfn "The area is %i" r.BoundingArea
+ r.Print()
+
+ // ------- métodos de extensão -------
+
+ // Assim como em C#, F# pode extender classes já existentes com métodos de extensão.
+ type System.String with
+ member this.StartsWithA = this.StartsWith "A"
+
+ // testes
+ let s = "Alice"
+ printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
+
+ // ------- eventos -------
+
+ type MyButton() =
+ let clickEvent = new Event<_>()
+
+ [<CLIEvent>]
+ member this.OnClick = clickEvent.Publish
+
+ member this.TestEvent(arg) =
+ clickEvent.Trigger(this, arg)
+
+ // teste
+ let myButton = new MyButton()
+ myButton.OnClick.Add(fun (sender, arg) ->
+ printfn "Click event with arg=%O" arg)
+
+ myButton.TestEvent("Hello World!")
+
+```
+
+## Mais Informações
+
+Para mais demonstrações de F# acesse [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/).
+
+Leia mais sobre F# em [fsharp.org](http://fsharp.org/) e [dotnet's F# page](https://dotnet.microsoft.com/languages/fsharp).
diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
index 1eab9cc3..3acfce21 100644
--- a/pt-br/groovy-pt.html.markdown
+++ b/pt-br/groovy-pt.html.markdown
@@ -14,7 +14,7 @@ Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http:
```groovy
/*
- Prepara-se:
+ Prepare-se:
1) Instale a máquina virtual de Groovy - http://gvmtool.net/
2) Instale o Groovy: gvm install groovy
@@ -104,7 +104,7 @@ tecnologiasOrdenadas = tecnologias.sort( false )
/*** Manipulando listas ***/
-//Substitue todos os elementos da lista
+//Substitui todos os elementos da lista
Collections.replaceAll(tecnologias, 'Gradle', 'gradle')
//Desorganiza a lista
@@ -159,7 +159,7 @@ println devMap.values()
usará este campo.
* Se você quer uma propriedade private ou protected, você deve prover seus
- próprios getters e setter, que devem ser declarados como private ou protected.
+ próprios getters e setters, que devem ser declarados como private ou protected.
* Se você acessar uma propriedade dentro da classe e esta propriedade é definida
em tempo de compilação com 'this', implícito ou explícito (por exemplo,
@@ -236,7 +236,7 @@ assert x.equals("Roberto Grails Groovy ")
/*
Operadores
- Sobrecarregamento de Operadores para uma lsita dos operadores comuns que
+ Sobrecarga de Operadores para uma lista dos operadores comuns que
Grooby suporta:
http://www.groovy-lang.org/operators.html#Operator-Overloading
@@ -254,7 +254,7 @@ def nomeUsuario = usuario?.nomeUsuario
/*
Closures
- Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método.
+ Um closure, em Groovy, é como um "bloco de código" ou um ponteiro para método.
É um pedação de código que é definido e executado em um momento posterior.
Mais informação em: http://www.groovy-lang.org/closures.html
@@ -269,7 +269,7 @@ clos()
def soma = { a, b -> println a+b }
soma(2,4)
-//Closdures por referir-se a variáveis que não estão listadas em sua
+//Closures podem referir-se a variáveis que não estão listadas em sua
//lista de parêmetros.
def x = 5
def multiplicarPor = { num -> num * x }
@@ -309,7 +309,7 @@ chamaClosure(3, 4)
/*
Expando
- A classe Expando é um bean dinâmico que permite adicionar propriedade e
+ A classe Expando é um bean dinâmico que permite adicionar propriedades e
closures como métodos a uma instância desta classe
http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
diff --git a/pt-br/julia-pt.html.markdown b/pt-br/julia-pt.html.markdown
index 11771d96..52675bf5 100644
--- a/pt-br/julia-pt.html.markdown
+++ b/pt-br/julia-pt.html.markdown
@@ -104,7 +104,7 @@ println("Eu sou Julia. Prazer em conhece-lo!")
## 2. Variáveis e coleções
####################################################
-#Você não declara variáveis antes de atribui-lás.
+#Você não declara variáveis antes de atribui-las.
some_var = 5 # => 5
some_var # => 5
diff --git a/pt-br/kotlin-pt.html.markdown b/pt-br/kotlin-pt.html.markdown
index 7c3313fc..bbe8c0d1 100644
--- a/pt-br/kotlin-pt.html.markdown
+++ b/pt-br/kotlin-pt.html.markdown
@@ -70,7 +70,7 @@ fun olaMundo(val nome : String) {
println(umaStringModelo)
/*
- Para uma variável receber null deve-se explicitamente declara-la
+ Para uma variável receber null deve-se explicitamente declará-la
como anulável.
A declaração de anulável é realizada incluindo uma "?" ao fim do tipo.
Pode-se acessar uma variável anulável usando o operador "?."
@@ -166,7 +166,7 @@ fun olaMundo(val nome : String) {
/*
Classes de dados são um modo sucinto de criar classes que servem apenas
- para guardas informações.
+ para guardar informações.
Os métodos "hashCode", "equals" e "toString" são gerados automaticamente.
*/
data class ExemploClasseDados (val x: Int, val y: Int, val z: Int)
diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown
new file mode 100644
index 00000000..0c75da26
--- /dev/null
+++ b/pt-br/lua-pt.html.markdown
@@ -0,0 +1,423 @@
+---
+language: Lua
+contributors:
+ - ["Tyler Neylon", "http://tylerneylon.com/"]
+filename: learnlua.lua
+translators:
+ - ["Iaan Mesquita", "https://github.com/ianitow"]
+lang: pt-br
+---
+
+```lua
+-- Dois hífens começam um comentário de uma linha.
+
+--[[
+ Adicionar dois [ ] (colchetes) criam um comentário
+ de múltiplas linhas.
+--]]
+
+----------------------------------------------------
+-- 1. Variáveis e fluxo de controle.
+----------------------------------------------------
+
+num = 42 -- Todos os números são doubles.
+-- Não se preocupe, doubles de 64-bits contém 52 bits para
+-- armazenar corretamente valores int; a precisão da máquina
+-- não é um problema para ints que são < 52 bits.
+
+s = 'alternados' -- String são imutáveis, como em Python.
+t = "Aspas duplas também são válidas"
+u = [[ Dois colchetes
+ começam e terminam
+ strings de múltiplas linhas.]]
+t = nil -- Torna t undefined(indefinido); Lua tem um Garbage Collector.
+
+-- Blocos são representados com palavras do/end:
+while num < 50 do
+ num = num + 1 -- Sem operadores do tipo ++ ou +=
+end
+
+--Cláusula If :
+if num > 40 then
+ print('over 40')
+elseif s ~= 'walternate' then -- ~= signfica não é igual.
+ -- Para fazer checagem use == como em Python; Funciona para comparar strings também.
+ io.write('not over 40\n') -- Padrão para saídas.
+else
+ -- Variáveis são globais por padrão.
+ thisIsGlobal = 5 -- Camel case é o comum.
+
+ -- Como fazer variáveis locais:
+ local line = io.read() -- Leia a proxima linha de entrada.
+
+ -- Para concatenação de strings use o operador .. :
+ print('Winter is coming, ' .. line)
+end
+
+-- Variáveis indefinidas são do tipo nil.
+-- Isso não é um erro:
+foo = anUnknownVariable -- Agora foo = nil.
+
+aBoolValue = false
+
+-- Apenas nil e false são do tipo falso; 0 e '' são verdadeiros!
+if not aBoolValue then print('twas false') end
+
+-- 'or' e 'and' são operadores lógicos.
+-- Esse operador em C/JS a?b:c , em lua seria o mesmo que:
+ans = aBoolValue and 'yes' or 'no' --> 'no'
+
+karlSum = 0
+for i = 1, 100 do -- O intervalo inclui inicio e fim.
+ karlSum = karlSum + i
+end
+
+-- Use "100, 1, -1" para um intervalo que diminui:
+fredSum = 0
+for j = 100, 1, -1 do fredSum = fredSum + j end
+
+-- Em geral, o intervalo é começo, fim[, etapas].
+
+-- Outro construtor de loop:
+repeat
+ print('A estrada do futuro.')
+ num = num - 1
+until num == 0
+
+
+----------------------------------------------------
+-- 2. Funções.
+----------------------------------------------------
+
+function fib(n)
+ if n < 2 then return 1 end
+ return fib(n - 2) + fib(n - 1)
+end
+
+-- Closures e Funções anônimas são permitidas:
+function adder(x)
+ -- O retorno da função é criado quando adder é
+ -- chamado, e ele sabe o valor de x:
+ return function (y) return x + y end
+end
+a1 = adder(9)
+a2 = adder(36)
+print(a1(16)) --> 25
+print(a2(64)) --> 100
+
+-- Retornos, chamadas de funções e atribuições, todos eles trabalham
+-- com listas que podem ter tamanhos incompatíveis.
+-- Receptores incompatpiveis serão nil;
+-- Destinos incompatíveis serão descartados.
+
+x, y, z = 1, 2, 3, 4
+-- Agora x = 1, y = 2, z = 3, e 4 é jogado fora.
+
+function bar(a, b, c)
+ print(a, b, c)
+ return 4, 8, 15, 16, 23, 42
+end
+
+x, y = bar('zaphod') --> imprime "zaphod nil nil"
+-- Agora x = 4, y = 8, os valores 15...42 foram descartados.
+
+-- Funções são de primeira-classe, portanto podem ser local/global.
+-- Estes exemplos são equivalentes:
+function f(x) return x * x end
+f = function (x) return x * x end
+
+-- Logo, estes são equivalentes também:
+local function g(x) return math.sin(x) end
+local g; g = function (x) return math.sin(x) end
+-- 'local g' essa declaração de auto-referência é válida.
+
+-- A propósito, as funções de trigonometria trabalham em radianos.
+
+-- Chamadas de função com apenas um parâmetro de string não precisam de parênteses:
+print 'hello' -- Funciona perfeitamente.
+
+
+----------------------------------------------------
+-- 3. Tabelas.
+----------------------------------------------------
+
+-- Tabelas = A unica estrutura de dados composta em Lua;
+-- elas são matrizes associativas.
+-- Semelhantes aos arrays de PHP ou objetos de javascript, eles são:
+-- hash-lookup(chave:valor) que também podem ser usados como listas.
+
+-- Usando tabelas como dicionário / mapas:
+
+-- Dicionários literais tem strings como chaves por padrão:
+t = {key1 = 'value1', key2 = false}
+
+-- As chaves do tipo string podem usar notação de ponto,semelhante a javascript:
+print(t.key1) -- Imprime 'value1'.
+t.newKey = {} -- Adiciona um novo par chave/valor.
+t.key2 = nil -- Remove key2 da tabela.
+
+-- Qualquer notação literal (não-nulo) pode ser uma chave:
+u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
+print(u[6.28]) -- imprime "tau"
+
+-- A correspondência de chave é basicamente o valor para números
+-- e strings, mas por identidade para tabelas.
+a = u['@!#'] -- Agora a = 'qbert'.
+b = u[{}] -- Nós esperavamso o resultado 1729, mas ele é nil:
+-- b = nil já que a busca falha. Ela falha
+-- porque a chave que usamos não é a mesma que o objeto
+-- como aquele que usamos para guardar o valor original. Por isso
+-- strings & numeros são chaves mais recomendadas.
+
+-- Uma chamada de função de apenas um paramêtro de tabela, não precisa de parênteses:
+
+function h(x) print(x.key1) end
+h{key1 = 'Sonmi~451'} -- Imprime 'Sonmi~451'.
+
+for key, val in pairs(u) do -- Iteração de tabela.
+ print(key, val)
+end
+
+-- _G é uma tabela especial que guarda tudo que é global.
+print(_G['_G'] == _G) -- Imprime 'true'.
+
+-- Usando tabelas como listas / arrays:
+
+-- Listas literais com chaves int implícitas:
+v = {'value1', 'value2', 1.21, 'gigawatts'}
+for i = 1, #v do -- #v é o tamanho de v
+ print(v[i]) -- Índices começam em 1 !! MUITO LOCO!
+end
+-- Uma 'list' não é um tipo real. v é apenas uma tabela
+-- com chaves int consecutivas, tratando ela como uma lista.
+
+----------------------------------------------------
+-- 3.1 Metatabelas e metamétodos.
+----------------------------------------------------
+
+-- Uma tabela pode ter uma metatabela que fornece à tabela
+-- um compotamento de sobrecarga de operador. Depois veremos
+-- como metatabelas suportam o comportamento do Javascript-prototype.
+
+f1 = {a = 1, b = 2} -- Representa uma fração de a/b.
+f2 = {a = 2, b = 3}
+
+-- Isso falharia:
+-- s = f1 + f2
+
+metafraction = {}
+function metafraction.__add(f1, f2)
+ sum = {}
+ sum.b = f1.b * f2.b
+ sum.a = f1.a * f2.b + f2.a * f1.b
+ return sum
+end
+
+setmetatable(f1, metafraction)
+setmetatable(f2, metafraction)
+
+s = f1 + f2 -- chama __add(f1, f2) na metatabela de f1
+
+-- f1, f2 não tem chave para sua metatabela, ao contrário de
+-- prototypes em javascript, então você deve recuperá-lo com
+-- getmetatable(f1). A metatabela é uma tabela normal
+-- com chaves que Lua reconhece, como __add.
+
+-- Mas a proxima linha irá falhar porque s não tem uma metatabela:
+-- t = s + s
+-- O padrão de Classes abaixo consertam esse problema.
+
+-- Uma __index em uma metatable sobrecarrega pesquisas de ponto:
+defaultFavs = {animal = 'gru', food = 'donuts'}
+myFavs = {food = 'pizza'}
+setmetatable(myFavs, {__index = defaultFavs})
+eatenBy = myFavs.animal -- Funciona! obrigado, metatabela.
+
+-- As pesquisas diretas de tabela que falham tentarão pesquisar novamente usando
+-- o __index da metatabela, e isso é recursivo.
+
+-- Um valor de __index também pode ser uma function(tbl, key)
+-- para pesquisas mais personalizadas.
+
+-- Valores do tipo __index,add, .. são chamados de metamétodos.
+-- Uma lista completa com os metamétodos.
+
+-- __add(a, b) para a + b
+-- __sub(a, b) para a - b
+-- __mul(a, b) para a * b
+-- __div(a, b) para a / b
+-- __mod(a, b) para a % b
+-- __pow(a, b) para a ^ b
+-- __unm(a) para -a
+-- __concat(a, b) para a .. b
+-- __len(a) para #a
+-- __eq(a, b) para a == b
+-- __lt(a, b) para a < b
+-- __le(a, b) para a <= b
+-- __index(a, b) <fn or a table> para a.b
+-- __newindex(a, b, c) para a.b = c
+-- __call(a, ...) para a(...)
+
+----------------------------------------------------
+-- 3.2 Tabelas como Classes e sua herança.
+----------------------------------------------------
+
+-- Classes não são disseminadas; existem maneiras diferentes
+-- para fazer isso usando tabelas e metamétodos...
+
+-- A explicação para este exemplo está logo abaixo.
+
+Dog = {} -- 1.
+
+function Dog:new() -- 2.
+ newObj = {sound = 'woof'} -- 3.
+ self.__index = self -- 4.
+ return setmetatable(newObj, self) -- 5.
+end
+
+function Dog:makeSound() -- 6.
+ print('I say ' .. self.sound)
+end
+
+mrDog = Dog:new() -- 7.
+mrDog:makeSound() -- 'I say woof' -- 8.
+
+-- 1. Dog atua como uma classe; mas na verdade, é uma tabela.
+-- 2. function tablename:fn(...) é a mesma coisa que
+-- function tablename.fn(self, ...)
+-- O : apenas adiciona um primeiro argumento chamado self.
+-- Leia 7 & 8 abaixo para ver como self obtém seu valor.
+-- 3. newObj será uma instância da classe Dog.
+-- 4. self = a classe que que foi instanciada. Regularmente
+-- self = Dog, mas a herança pode mudar isso.
+-- newObj recebe as funções de self como se tivessimos definido em ambos
+-- a metatabela de newObj e self __index para self.
+-- 5. Lembre-se: setmetatable retorna seu primeiro argumento definido.
+-- 6. O : funciona como em 2, mas desta vez esperamos que
+-- self seja uma instância já instanciada da classe.
+-- 7. Igual a Dog.new(Dog), logo self = Dog no new().
+-- 8. Igual a mrDog.makeSound(mrDog); self = mrDog.
+
+----------------------------------------------------
+
+-- Heranças exemplos:
+
+LoudDog = Dog:new() -- 1.
+
+function LoudDog:makeSound()
+ s = self.sound .. ' ' -- 2.
+ print(s .. s .. s)
+end
+
+seymour = LoudDog:new() -- 3.
+seymour:makeSound() -- 'woof woof woof' -- 4.
+
+-- 1. LoudDog recebe os metodos e variáveis de Dog.
+-- 2. self tem uma chave 'sound' vindo de new(), veja o 3.
+-- 3. Mesma coisa que LoudDog.new(LoudDog), convertido para
+-- Dog.new(LoudDog) como LoudDog não tem uma chave 'new',
+-- mas tem uma chave __index = Dog na sua metatabela o
+-- resultado será: a metabela de seymour é a LoudDog, e
+-- LoudDog.__index = LoudDog. Então seymour.key será
+-- = seymour.key, LoudDog.key, Dog.key,seja qual for a primeira
+-- chave fornecida.
+-- 4. A chave 'makeSound' foi encontrada em LoudDog; isto
+-- é a mesma coisa que LoudDog.makeSound(seymour).
+
+-- Se precisar de, uma subclasse de new() como uma base:
+function LoudDog:new()
+ newObj = {}
+ -- define newObj
+ self.__index = self
+ return setmetatable(newObj, self)
+end
+
+----------------------------------------------------
+-- 4. Módulos.
+----------------------------------------------------
+
+
+--[[ Estou comentando esta seção, então o resto
+-- desse script é executável.
+```
+
+```lua
+-- Suponhamos que o arquivo mod.lua se pareça com isso:
+local M = {}
+
+local function sayMyName()
+ print('Hrunkner')
+end
+
+function M.sayHello()
+ print('Why hello there')
+ sayMyName()
+end
+
+return M
+
+-- Outro arquivo pode usar as funcionalidades de mod.lua:
+local mod = require('mod') -- Roda o arquivo mod.lua.
+
+-- require é a forma que usamos para incluir módulos.
+-- require atua como: (se não for cacheado; veja abaixo)
+local mod = (function ()
+ <contents of mod.lua>
+end)()
+-- É como se mod.lua fosse um corpo de uma função, então
+-- os locais dentro de mod.lua são invisíveis fora dele.
+
+-- Isso irá funcionar porque mod aqui = M dentro de mod.lua:
+mod.sayHello() -- Diz olá para Hrunkner.
+
+-- Isso aqui é errado; sayMyName existe apenas em mod.lua:
+mod.sayMyName() -- erro
+
+-- valores retornados de require são armazenados em cache para que um arquivo seja
+-- execute no máximo uma vez, mesmo quando é exigidos várias vezes.
+
+-- Suponhamos que mod2.lua contém "print('Hi!')".
+local a = require('mod2') -- Imprime Hi!
+local b = require('mod2') -- Não imprime;pois a=b.
+
+-- dofile é parecido com require, porém sem cacheamento:
+dofile('mod2.lua') --> Hi!
+dofile('mod2.lua') --> Hi! (roda novamente)
+
+-- loadfile carrega um arquivo lua, porém não o executa.
+f = loadfile('mod2.lua') -- Chame f() para executar.
+
+-- loadstring é um loadfile para strings.
+g = loadstring('print(343)') -- Retorna uma função.
+g() -- Imprime 343; nada foi impresso antes disso.
+
+--]]
+
+```
+
+## Referências
+
+Fiquei bastante animado para aprender Lua pois consegui fazer jogos
+com a <a href="http://love2d.org/">Love 2D engine de jogos</a>.
+
+Eu comecei com <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's para programadores LUA</a>.
+Em seguida, eu li a documentação oficial <a href="https://www.lua.org/manual/5.1/pt/index.html#contents">Programando em Lua</a>.
+É assim que se começa.
+
+Pode ser útil conferir <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Uma pequena referencia sobre LUA</a> em lua-users.org.
+
+Os principais tópicos não cobertos, são as bibliotecas padrões:
+
+- <a href="http://lua-users.org/wiki/StringLibraryTutorial">Biblioteca de strings</a>
+- <a href="http://lua-users.org/wiki/TableLibraryTutorial">Biblioteca de tabelas</a>
+- <a href="http://lua-users.org/wiki/MathLibraryTutorial">Biblioteca de matemática</a>
+- <a href="http://lua-users.org/wiki/IoLibraryTutorial">Biblioteca de entrada/saída</a>
+- <a href="http://lua-users.org/wiki/OsLibraryTutorial">Biblioteca do sistema operacional</a>
+
+A propósito, todo este arquivo é um código LUA válido, salve-o como
+aprenda.lua e rode-o com "lua aprenda.lua" !
+
+Este guia foi escrito pela primeira vez por tylerneylon.com, e agora
+também disponível em <a href="https://gist.github.com/tylerneylon/5853042">github gist</a>. E também em português.
+
+Se divirta com lua
diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown
index 5ed6b7ba..fae17bca 100644
--- a/pt-br/matlab-pt.html.markdown
+++ b/pt-br/matlab-pt.html.markdown
@@ -356,7 +356,7 @@ disp(a) % Imprime o valor da variável a
disp('Olá Mundo') % Imprime a string
fprintf % Imprime na janela de comandos com mais controle
-% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática)
+% Estruturas Condicionais (os parênteses são opcionais, porém uma boa prática)
if (a > 15)
disp('Maior que 15')
elseif (a == 23)
diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown
index 217861f9..55a10626 100644
--- a/pt-br/perl-pt.html.markdown
+++ b/pt-br/perl-pt.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: pt-br
---
-Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
+Perl é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
-Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
+Perl roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
```perl
# Comentários de uma linha começam com um sinal de número.
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
index 3d91f1ca..28df3c59 100644
--- a/pt-br/sass-pt.html.markdown
+++ b/pt-br/sass-pt.html.markdown
@@ -56,19 +56,19 @@ body {
}
-/ * Este é muito mais fácil de manter do que ter de mudar a cor
-cada vez que aparece em toda a sua folha de estilo. * /
+/* Este é muito mais fácil de manter do que ter de mudar a cor
+cada vez que aparece em toda a sua folha de estilo. */
-/*Mixins
+/* Mixins
==============================*/
-/* Se você achar que você está escrevendo o mesmo código para mais de um
-elemento, você pode querer armazenar esse código em um mixin.
+/* Se você achar que está escrevendo o mesmo código para mais de um
+elemento, você pode armazenar esse código em um mixin.
Use a diretiva '@mixin', além de um nome para o seu mixin. */
@@ -87,7 +87,7 @@ div {
background-color: $primary-color;
}
-/* Apoś compilar ficaria assim: */
+/* Após compilar ficaria assim: */
div {
display: block;
margin-left: auto;
@@ -128,7 +128,7 @@ div {
-/*Funções
+/* Funções
==============================*/
@@ -138,6 +138,7 @@ div {
/* Funções pode ser chamado usando seu nome e passando o
    argumentos necessários */
+
body {
width: round(10.25px);
}
@@ -156,14 +157,14 @@ body {
background-color: rgba(0, 0, 0, 0.75);
}
-/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
-   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
-   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
-   lógica que pode ser usado em todo o seu código Sass. Os exemplos
-   seção Operadores Math 'são candidatos ideais para se tornar um reutilizável
-   função. */
+/* Você também pode definir suas próprias funções. As funções são muito semelhantes
+ aos mixins. Ao tentar escolher entre uma função ou um mixin, lembre
+ que mixins são os melhores para gerar CSS enquanto as funções são melhores para
+ lógica que pode ser usado em todo o seu código Sass. Os exemplos na
+ seção "Operações Math" são candidatos ideais para se tornar um função
+ reutilizável. */
-/* Esta função terá um tamanho de destino eo tamanho do pai e calcular
+/* Esta função terá um tamanho de destino e o tamanho do pai (parent), calcular
   e voltar a percentagem */
@function calculate-percentage($target-size, $parent-size) {
@@ -220,21 +221,21 @@ $main-content: calculate-percentage(600px, 960px);
border-color: #22df56;
}
-/* Ampliando uma declaração CSS é preferível a criação de um mixin
-   por causa da maneira agrupa as classes que todos compartilham
+/* Ao ampliar uma declaração CSS é preferível a criação de um mixin,
+   por causa da maneira em que agrupa as classes com todos que compartilham
   o mesmo estilo base. Se isso for feito com um mixin, a largura,
   altura, e a borda seria duplicado para cada instrução que
   o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será
-   adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */
+   adicionado inchaço desnecessário para os arquivos criados pelo compilador Sass. */
-/*Assentamento
+/* Assentamento
==============================*/
-/ * Sass permite seletores ninhos dentro seletores * /
+/* Sass permite seletores ninhos dentro seletores */
ul {
list-style-type: none;
@@ -245,7 +246,7 @@ ul {
}
}
-/* '&' será substituído pelo selector pai. */
+/* '&' será substituído pelo selector pai (parent). */
/* Você também pode aninhar pseudo-classes. */
/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável.
Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação.
@@ -290,7 +291,7 @@ ul li a {
-/*Parciais e Importações
+/* Parciais e Importações
==============================*/
@@ -313,7 +314,7 @@ ol {
/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
   Isso difere da declaração CSS @import tradicional, que faz
   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
-   importadas arquivo e combina com o código compilado. */
+   arquivo importados e combina com o código compilado. */
@import 'reset';
@@ -322,7 +323,7 @@ body {
font-family: Helvetica, Arial, Sans-serif;
}
-/* Compiles to: */
+/* Compila para: */
html, body, ul, ol {
margin: 0;
@@ -336,14 +337,14 @@ body {
-/*Placeholder Selectors
+/* Placeholder Selectors
==============================*/
-/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
-   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
-   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
-   de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * /
+/* Os Placeholders são úteis na criação de uma declaração CSS para ampliar. Se você
+   deseja criar uma instrução CSS que foi usado exclusivamente com @extend,
+   você pode fazer isso usando um Placeholder. Placeholder começar com um '%' em vez
+   de '.' ou '#'. Placeholder não aparece no CSS compilado. */
%content-window {
font-size: 14px;
@@ -372,14 +373,14 @@ body {
-/*Operações Math
-============================== * /
+/* Operações Math
+============================== */
/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
-   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
-   de usar valores que você já calculados pela mão. Abaixo está um exemplo
-   de uma criação de um projeto simples de duas colunas. * /
+   ser úteis para calcular os valores diretamente no seu arquivos Sass em vez
+ de usar valores que você já calculados manualmente. O exemplo abaixo é
+ de um projeto simples de duas colunas. */
$content-area: 960px;
$main-content: 600px;
diff --git a/pt-br/self-pt.html.markdown b/pt-br/self-pt.html.markdown
index 2fb2953b..eb821474 100644
--- a/pt-br/self-pt.html.markdown
+++ b/pt-br/self-pt.html.markdown
@@ -147,7 +147,7 @@ o objeto '10' no slot 'x' e retornará o objeto original"
# Protótipos
-Não existem classes em Self. A maneira de obter um objeto é encontrar um protótipo e copia-lo.
+Não existem classes em Self. A maneira de obter um objeto é encontrar um protótipo e copiá-lo.
```
| d |
diff --git a/pt-br/solidity-pt.html.markdown b/pt-br/solidity-pt.html.markdown
index d4555fa7..c77ff298 100644
--- a/pt-br/solidity-pt.html.markdown
+++ b/pt-br/solidity-pt.html.markdown
@@ -259,7 +259,7 @@ nomes.length; // pega o tamanho
nomes.length = 1; // tamanhos pode ser alterados (para arrays dinâmicos)
// arrays multidimensionais
-uint x[][5]; // array com 5 arrays dinâmicos como elementos (ordem da maioria
+uint[][5] x; // array com 5 arrays dinâmicos como elementos (ordem da maioria
// das linguagens)
// Dicionários (qualquer tipo para qualquer tipo)
diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown
index bf410352..96b96427 100644
--- a/pt-br/swift-pt.html.markdown
+++ b/pt-br/swift-pt.html.markdown
@@ -10,7 +10,7 @@ lang: pt-br
---
-Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para
+Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e macOS criada pela Apple. Criada para
coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's
developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta.
diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown
index 6ece02ff..7d28bf53 100644
--- a/pt-br/typescript-pt.html.markdown
+++ b/pt-br/typescript-pt.html.markdown
@@ -10,11 +10,11 @@ lang: pt-br
Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript.
Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript.
-É um super conjunto de JavaScript: todo o código JavaScript é TypeScript válido então ele pode ser adicionado diretamente a qualquer projeto. O compilador emite typescript JavaScript.
+É um super conjunto de JavaScript: todo o código JavaScript é TypeScript válido então ele pode ser adicionado diretamente a qualquer projeto. O compilador emite TypeScript JavaScript.
-Este artigo irá se concentrar apenas em texto datilografado sintaxe extra, ao contrário de [JavaScript](javascript-pt.html.markdown).
+Este artigo irá se concentrar apenas na sintaxe extra do TypeScript, ao contrário de [JavaScript](../javascript-pt/).
-Para testar compilador do texto datilografado, de cabeça para o [Parque](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitida.
+Para testar o compilador TypeScript, vá para o [Playground](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitido.
```js
// Existem 3 tipos básicos no TypeScript
@@ -44,13 +44,13 @@ function bigHorribleAlert(): void {
// Funções são cidadãos de primeira classe, apoiar a sintaxe lambda "seta gordura" e
// Tipo de uso inferência
-// A seguir são equivalentes, a mesma assinatura será inferido pelo
-// Compilador, e mesmo JavaScript será emitido
+// A seguir são equivalentes, a mesma assinatura será inferida pelo
+// Compilador, e o mesmo JavaScript será emitido
var f1 = function(i: number): number { return i * i; }
-// Tipo de retorno inferida
+// Tipo de retorno inferido
var f2 = function(i: number) { return i * i; }
var f3 = (i: number): number => { return i * i; }
-// Tipo de retorno inferida
+// Tipo de retorno inferido
var f4 = (i: number) => { return i * i; }
// Tipo de retorno inferido, one-liner significa nenhuma palavra-chave retorno necessário
var f5 = (i: number) => i * i;
@@ -88,7 +88,7 @@ class Point {
// Propriedades
x: number;
- // Construtor - the public/private keywords in this context will generate
+ // Construtor - as palavras-chave public/private nesse contexto irão gerar
// o código clichê para a propriedade e a inicialização no
// construtor.
// Neste exemplo, "y" será definida como "X" é, mas com menos código
diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown
index 6b263942..a8d3e1ab 100644
--- a/pt-pt/swift-pt.html.markdown
+++ b/pt-pt/swift-pt.html.markdown
@@ -12,7 +12,7 @@ translators:
lang: pt-pt
---
-Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X.
+Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e macOS.
Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple.
Swift usa o compilador LLVM incluido no XCode 6+.
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 6b74ac64..c848c2a4 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -6,19 +6,20 @@ contributors:
- ["Thimoteus", "https://github.com/Thimoteus"]
---
-PureScript is a small strongly, statically typed language compiling to Javascript.
+PureScript is a small strongly, statically typed language compiling to JavaScript.
-* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
-* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/)
-* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
+* Learn more at [https://www.purescript.org/](https://www.purescript.org/)
+* Documentation: [https://pursuit.purescript.org/](https://pursuit.purescript.org/)
+* Book: Purescript by Example, [https://book.purescript.org/](https://book.purescript.org/)
-All the noncommented lines of code can be run in the PSCI REPL, though some will
-require the `--multi-line-mode` flag.
+All the noncommented lines of code can be run in the PSCi REPL, though some
+will require "paste" mode (`:paste` followed by multiple lines, terminated by
+^D).
```haskell
--
--- 1. Primitive datatypes that corresponds to their Javascript
+-- 1. Primitive datatypes that corresponds to their JavaScript
-- equivalents at runtime.
import Prelude
@@ -39,7 +40,7 @@ import Prelude
3.0 % 2.0 -- 1.0
4.0 % 2.0 -- 0.0
-- Inspect the type of an expression in psci
-:t 9.5/2.5 + 4.4 -- Prim.Number
+:t 9.5/2.5 + 4.4 -- Number
-- Booleans
true :: Boolean -- true
@@ -59,7 +60,7 @@ true && (9 >= 19 || 1 < 2) -- true
-- Strings
"Hellow" :: String -- "Hellow"
--- Multiline string without newlines, to run in psci use the --multi-line-mode flag
+-- Multiline string without newlines, to run in PSCi use "paste" mode.
"Hellow\
\orld" -- "Helloworld"
-- Multiline string with newlines
@@ -69,26 +70,26 @@ world""" -- "Hello\nworld"
"such " <> "amaze" -- "such amaze"
--
--- 2. Arrays are Javascript arrays, but must be homogeneous
+-- 2. Arrays are JavaScript arrays, but must be homogeneous
[1,1,2,3,5,8] :: Array Int -- [1,1,2,3,5,8]
[1.2,2.0,3.14] :: Array Number -- [1.2,2.0,3.14]
[true, true, false] :: Array Boolean -- [true,true,false]
-- [1,2, true, "false"] won't work
--- `Cannot unify Prim.Int with Prim.Boolean`
+-- `Cannot unify Int with Boolean`
+
+-- Requires purescript-arrays (Data.Array)
-- Cons (prepend)
1 : [2,4,3] -- [1,2,4,3]
--- Requires purescript-arrays (Data.Array)
-- and purescript-maybe (Data.Maybe)
-
-- Safe access return Maybe a
-head [1,2,3] -- Just (1)
-tail [3,2,1] -- Just ([2,1])
-init [1,2,3] -- Just ([1,2])
-last [3,2,1] -- Just (1)
+head [1,2,3] -- (Just 1)
+tail [3,2,1] -- (Just [2,1])
+init [1,2,3] -- (Just [1,2])
+last [3,2,1] -- (Just 1)
-- Array access - indexing
-[3,4,5,6,7] !! 2 -- Just (5)
+[3,4,5,6,7] !! 2 -- (Just 5)
-- Range
1..5 -- [1,2,3,4,5]
length [2,2,2] -- 3
@@ -97,31 +98,30 @@ take 3 [5,4,3,2,1] -- [5,4,3]
append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
--
--- 3. Records are Javascript objects, with zero or more fields, which
+-- 3. Records are JavaScript objects, with zero or more fields, which
-- can have different types.
--- In psci you have to write `let` in front of the function to get a
--- top level binding.
-let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
+book = {title: "Foucault's pendulum", author: "Umberto Eco"}
-- Access properties
book.title -- "Foucault's pendulum"
-let getTitle b = b.title
+getTitle b = b.title
-- Works on all records with a title (but doesn't require any other field)
getTitle book -- "Foucault's pendulum"
getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
-- Can use underscores as shorthand
_.title book -- "Foucault's pendulum"
-- Update a record
-let changeTitle b t = b {title = t}
+changeTitle b t = b {title = t}
getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa"
--
-- 4. Functions
--- In psci's multiline mode
-let sumOfSquares :: Int -> Int -> Int
- sumOfSquares x y = x*x + y*y
+-- In PSCi's paste mode
+sumOfSquares :: Int -> Int -> Int
+sumOfSquares x y = x*x + y*y
sumOfSquares 3 4 -- 25
-let myMod x y = x % y
+
+myMod x y = x % y
myMod 3.0 2.0 -- 1.0
-- Infix application of function
3 `mod` 2 -- 1
@@ -131,48 +131,47 @@ myMod 3.0 2.0 -- 1.0
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
-- Conditional
-let abs' n = if n>=0 then n else -n
+abs' n = if n>=0 then n else -n
abs' (-3) -- 3
-- Guarded equations
-let abs'' n | n >= 0 = n
- | otherwise = -n
+-- In PSCi's paste mode
+abs'' n | n >= 0 = n
+ | otherwise = -n
-- Pattern matching
-- Note the type signature, input is a list of numbers. The pattern matching
-- destructures and binds the list into parts.
--- Requires purescript-lists (Data.List)
-let first :: forall a. List a -> a
- first (Cons x _) = x
-first (toList [3,4,5]) -- 3
-let second :: forall a. List a -> a
- second (Cons _ (Cons y _)) = y
-second (toList [3,4,5]) -- 4
-let sumTwo :: List Int -> List Int
- sumTwo (Cons x (Cons y rest)) = x + y : rest
-fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6]
-
--- sumTwo doesn't handle when the list is empty or there's only one element in
--- which case you get an error.
-sumTwo [1] -- Failed pattern match
+-- Requires purescript-lists (Data.List) and purescript-maybe (Data.Maybe)
+first :: forall a. List a -> Maybe a
+first (x : _) = Just x
+first Nil = Nothing
+first (fromFoldable [3,4,5]) -- (Just 3)
+
+second :: forall a. List a -> Maybe a
+second Nil = Nothing
+second (_ : Nil) = Nothing
+second (_ : (y : _)) = Just y
+second (fromFoldable [3,4,5]) -- (Just 4)
-- Complementing patterns to match
-- Good ol' Fibonacci
-let fib 1 = 1
- fib 2 = 2
- fib x = fib (x-1) + fib (x-2)
+fib 1 = 1
+fib 2 = 2
+fib x = fib (x-1) + fib (x-2)
fib 10 -- 89
-- Use underscore to match any, where you don't care about the binding name
-let isZero 0 = true
- isZero _ = false
+isZero 0 = true
+isZero _ = false
+isZero 9 -- false
-- Pattern matching on records
-let ecoTitle {author = "Umberto Eco", title = t} = Just t
- ecoTitle _ = Nothing
+ecoTitle {author: "Umberto Eco", title: t} = Just t
+ecoTitle _ = Nothing
-ecoTitle book -- Just ("Foucault's pendulum")
+ecoTitle {title: "Foucault's pendulum", author: "Umberto Eco"} -- (Just "Foucault's pendulum")
ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
-- ecoTitle requires both field to type check:
ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author"
@@ -180,13 +179,13 @@ ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author"
-- Lambda expressions
(\x -> x*x) 3 -- 9
(\x y -> x*x + y*y) 4 5 -- 41
-let sqr = \x -> x*x
+sqr = \x -> x*x
-- Currying
-let myAdd x y = x + y -- is equivalent with
-let myAdd' = \x -> \y -> x + y
-let add3 = myAdd 3
-:t add3 -- Prim.Int -> Prim.Int
+myAdd x y = x + y -- is equivalent with
+myAdd' = \x -> \y -> x + y
+add3 = myAdd 3
+:t add3 -- Int -> Int
-- Forward and backward function composition
-- drop 3 followed by taking 5
@@ -195,7 +194,7 @@ let add3 = myAdd 3
(drop 3 <<< take 5) (1..20) -- [4,5]
-- Operations using higher order functions
-let even x = x `mod` 2 == 0
+even x = x `mod` 2 == 0
filter even (1..10) -- [2,4,6,8,10]
map (\x -> x + 11) (1..5) -- [12,13,14,15,16]
diff --git a/python.html.markdown b/python.html.markdown
index 56cb9aac..39e60455 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -50,17 +50,19 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
10.0 / 3 # => 3.3333333333333335
# Modulo operation
-7 % 3 # => 1
+7 % 3 # => 1
+# i % j have the same sign as j, unlike C
+-7 % 3 # => 2
# Exponentiation (x**y, x to the yth power)
2**3 # => 8
# Enforce precedence with parentheses
-1 + 3 * 2 # => 7
+1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8
# Boolean values are primitives (Note: the capitalization)
-True # => True
+True # => True
False # => False
# negate with not
@@ -126,13 +128,13 @@ b == a # => True, a's and b's objects are equal
"This is a string."
'This is also a string.'
-# Strings can be added too! But try not to do this.
+# Strings can be added too
"Hello " + "world!" # => "Hello world!"
# String literals (but not variables) can be concatenated without using '+'
"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
-"This is a string"[0] # => 'T'
+"Hello world!"[0] # => 'H'
# You can find the length of a string
len("This is a string") # => 16
@@ -140,10 +142,9 @@ len("This is a string") # => 16
# You can also format using f-strings or formatted string literals (in Python 3.6+)
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
-# You can basically put any Python statement inside the braces and it will be output in the string.
+# You can basically put any Python expression inside the braces and it will be output in the string.
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
-
# None is an object
None # => None
@@ -173,7 +174,6 @@ print("Hello, World", end="!") # => Hello, World!
# Simple way to get input data from console
input_string_var = input("Enter some data: ") # Returns the data as a string
-# Note: In earlier versions of Python, input() method was named as raw_input()
# There are no declarations, only assignments.
# Convention is to use lower_case_with_underscores
@@ -186,7 +186,7 @@ some_unknown_var # Raises a NameError
# if can be used as an expression
# Equivalent of C's '?:' ternary operator
-"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+"yay!" if 0 > 1 else "nay!" # => "nay!"
# Lists store sequences
li = []
@@ -482,7 +482,7 @@ except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
+finally: # Execute under all circumstances
print("We can clean up resources here")
# Instead of try/finally to cleanup resources you can use a with statement
@@ -506,7 +506,7 @@ print(contents)
with open('myfile2.txt', "r+") as file:
contents = json.load(file) # reads a json object from a file
-print(contents)
+print(contents)
# print: {"aa": 12, "bb": 21}
@@ -735,7 +735,7 @@ class Human:
return "*grunt*"
# A property is just like a getter.
- # It turns the method age() into an read-only attribute of the same name.
+ # It turns the method age() into a read-only attribute of the same name.
# There's no need to write trivial getters and setters in Python, though.
@property
def age(self):
@@ -772,11 +772,10 @@ if __name__ == '__main__':
# Call the static method
print(Human.grunt()) # => "*grunt*"
-
- # Cannot call static method with instance of object
- # because i.grunt() will automatically put "self" (the object i) as an argument
- print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
+
+ # Static methods can be called by instances too
+ print(i.grunt()) # => "*grunt*"
+
# Update the property for this instance
i.age = 42
# Get the property
@@ -792,7 +791,7 @@ if __name__ == '__main__':
####################################################
# Inheritance allows new child classes to be defined that inherit methods and
-# variables from their parent class.
+# variables from their parent class.
# Using the Human class defined above as the base or parent class, we can
# define a child class, Superhero, which inherits the class variables like
@@ -920,13 +919,13 @@ class Batman(Superhero, Bat):
def __init__(self, *args, **kwargs):
# Typically to inherit attributes you have to call super:
- # super(Batman, self).__init__(*args, **kwargs)
+ # super(Batman, self).__init__(*args, **kwargs)
# However we are dealing with multiple inheritance here, and super()
# only works with the next base class in the MRO list.
# So instead we explicitly call __init__ for all ancestors.
# The use of *args and **kwargs allows for a clean way to pass arguments,
# with each parent "peeling a layer of the onion".
- Superhero.__init__(self, 'anonymous', movie=True,
+ Superhero.__init__(self, 'anonymous', movie=True,
superpowers=['Wealthy'], *args, **kwargs)
Bat.__init__(self, *args, can_fly=False, **kwargs)
# override the value for the name attribute
@@ -941,9 +940,9 @@ if __name__ == '__main__':
# Get the Method Resolution search Order used by both getattr() and super().
# This attribute is dynamic and can be updated
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
# => <class 'bat.Bat'>, <class 'object'>)
# Calls parent method but uses its own class attribute
@@ -1030,13 +1029,15 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
-* [The Official Docs](http://docs.python.org/3/)
-* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Course](http://www.python-course.eu/index.php)
+* [The Official Docs](https://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/)
+* [Python Course](https://www.python-course.eu)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
-* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
-* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
-* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
-* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python 3 Computer Science Circles](https://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](https://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](https://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
diff --git a/qsharp.html.markdown b/qsharp.html.markdown
new file mode 100644
index 00000000..b256043c
--- /dev/null
+++ b/qsharp.html.markdown
@@ -0,0 +1,204 @@
+---
+language: Q#
+contributors:
+ - ["Vincent van Wingerden", "https://github.com/vivanwin"]
+ - ["Mariia Mykhailova", "https://github.com/tcNickolas"]
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
+filename: LearnQSharp.qs
+---
+
+Q# is a high-level domain-specific language which enables developers to write quantum algorithms. Q# programs can be executed on a quantum simulator running on a classical computer and (in future) on quantum computers.
+
+```C#
+// Single-line comments start with //
+
+
+/////////////////////////////////////
+// 1. Quantum data types and operators
+
+// The most important part of quantum programs is qubits.
+// In Q# type Qubit represents the qubits which can be used.
+// This will allocate an array of two new qubits as the variable qs.
+using (qs = Qubit[2]) {
+
+ // The qubits have internal state that you cannot access to read or modify directly.
+ // You can inspect the current state of your quantum program
+ // if you're running it on a classical simulator.
+ // Note that this will not work on actual quantum hardware!
+ DumpMachine();
+
+ // If you want to change the state of a qubit
+ // you have to do this by applying quantum gates to the qubit.
+ H(q[0]); // This changes the state of the first qubit
+ // from |0⟩ (the initial state of allocated qubits)
+ // to (|0⟩ + |1⟩) / sqrt(2).
+ // q[1] = |1⟩; - this does NOT work, you have to manipulate a qubit by using gates.
+
+ // You can apply multi-qubit gates to several qubits.
+ CNOT(qs[0], qs[1]);
+
+ // You can also apply a controlled version of a gate:
+ // a gate that is applied if all control qubits are in |1⟩ state.
+ // The first argument is an array of control qubits,
+ // the second argument is the target qubit.
+ Controlled Y([qs[0]], qs[1]);
+
+ // If you want to apply an anti-controlled gate
+ // (a gate that is applied if all control qubits are in |0⟩ state),
+ // you can use a library function.
+ ApplyControlledOnInt(0, X, [qs[0]], qs[1]);
+
+ // To read the information from the quantum system, you use measurements.
+ // Measurements return a value of Result data type: Zero or One.
+ // You can print measurement results as a classical value.
+ Message($"Measured {M(qs[0])}, {M(qs[1])}");
+}
+
+
+/////////////////////////////////////
+// 2. Classical data types and operators
+
+// Numbers in Q# can be stored in Int, BigInt or Double.
+let i = 1; // This defines an Int variable i equal to 1
+let bi = 1L; // This defines a BigInt variable bi equal to 1
+let d = 1.0; // This defines a Double variable d equal to 1
+
+// Arithmetic is done as expected, as long as the types are the same
+let n = 2 * 10; // = 20
+// Q# does not have implicit type cast,
+// so to perform arithmetic on values of different types,
+// you need to cast type explicitly
+let nd = IntAsDouble(2) * 1.0; // = 20.0
+
+// Boolean type is called Bool
+let trueBool = true;
+let falseBool = false;
+
+// Logic operators work as expected
+let andBool = true and false;
+let orBool = true or false;
+let notBool = not false;
+
+// Strings
+let str = "Hello World!";
+
+// Equality is ==
+let x = 10 == 15; // is false
+
+// Range is a sequence of integers and can be defined like: start..step..stop
+let xi = 1..2..7; // Gives the sequence 1,3,5,7
+
+// Assigning new value to a variable:
+// by default all Q# variables are immutable;
+// if the variable was defined using let, you cannot reassign its value.
+
+// When you want to make a variable mutable, you have to declare it as such,
+// and use the set word to update value
+mutable xii = true;
+set xii = false;
+
+// You can create an array for any data type like this
+let xiii = new Double[10];
+
+// Getting an element from an array
+let xiv = xiii[8];
+
+// Assigning a new value to an array element
+mutable xv = new Double[10];
+set xv w/= 5 <- 1;
+
+
+/////////////////////////////////////
+// 3. Control flow
+
+// If structures work a little different than most languages
+if (a == 1) {
+ // ...
+} elif (a == 2) {
+ // ...
+} else {
+ // ...
+}
+
+// Foreach loops can be used to iterate over an array
+for (qubit in qubits) {
+ X(qubit);
+}
+
+// Regular for loops can be used to iterate over a range of numbers
+for (index in 0 .. Length(qubits) - 1) {
+ X(qubits[index]);
+}
+
+// While loops are restricted for use in classical context only
+mutable index = 0;
+while (index < 10) {
+ set index += 1;
+}
+
+// Quantum equivalent of a while loop is a repeat-until-success loop.
+// Because of the probabilistic nature of quantum computing sometimes
+// you want to repeat a certain sequence of operations
+// until a specific condition is achieved; you can use this loop to express this.
+repeat {
+ // Your operation here
+}
+until (success criteria) // This could be a measurement to check if the state is reached
+fixup {
+ // Resetting to the initial conditions, if required
+}
+
+
+/////////////////////////////////////
+// 4. Putting it all together
+
+// Q# code is written in operations and functions
+operation ApplyXGate(source : Qubit) : Unit {
+ X(source);
+}
+
+// If the operation implements a unitary transformation, you can define
+// adjoint and controlled variants of it.
+// The easiest way to do that is to add "is Adj + Ctl" after Unit.
+// This will tell the compiler to generate the variants automatically.
+operation ApplyXGateCA (source : Qubit) : Unit is Adj + Ctl {
+ X(source);
+}
+
+// Now you can call Adjoint ApplyXGateCA and Controlled ApplyXGateCA.
+
+
+// To run Q# code, you can put @EntryPoint() before the operation you want to run first
+@EntryPoint()
+operation XGateDemo() : Unit {
+ using (q = Qubit()) {
+ ApplyXGate(q);
+ }
+}
+
+// Here is a simple example: a quantum random number generator.
+// We will generate a classical array of random bits using quantum code.
+@EntryPoint()
+operation QRNGDemo() : Unit {
+ mutable bits = new Int[5]; // Array we'll use to store bits
+ using (q = Qubit()) { // Allocate a qubit
+ for (i in 0 .. 4) { // Generate each bit independently
+ H(q); // Hadamard gate sets equal superposition
+ let result = M(q); // Measure qubit gets 0|1 with 50/50 prob
+ let bit = result == Zero ? 0 | 1; // Convert measurement result to integer
+ set bits w/= i <- bit; // Write generated bit to an array
+ }
+ }
+ Message($"{bits}"); // Print the result
+}
+```
+
+
+## Further Reading
+
+The [Quantum Katas][1] offer great self-paced tutorials and programming exercises to learn quantum computing and Q#.
+
+[Q# Documentation][2] is official Q# documentation, including language reference and user guides.
+
+[1]: https://github.com/microsoft/QuantumKatas
+[2]: https://docs.microsoft.com/quantum/
diff --git a/r.html.markdown b/r.html.markdown
index 3e855602..79af40ce 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -255,16 +255,16 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
-# Factors can be ordered (like childrens' grade levels) or unordered (like gender)
-factor(c("female", "female", "male", NA, "female"))
-# female female male <NA> female
-# Levels: female male
+# Factors can be ordered (like childrens' grade levels) or unordered (like colors)
+factor(c("blue", "blue", "green", NA, "blue"))
+# blue blue green <NA> blue
+# Levels: blue green
# The "levels" are the values the categorical data can take
# Note that missing data does not enter the levels
-levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
+levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green"
# If a factor vector has length 1, its levels will have length 1, too
-length(factor("male")) # 1
-length(levels(factor("male"))) # 1
+length(factor("green")) # 1
+length(levels(factor("green"))) # 1
# Factors are commonly seen in data frames, a data structure we will cover later
data(infert) # "Infertility after Spontaneous and Induced Abortion"
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
diff --git a/perl6-pod.html.markdown b/raku-pod.html.markdown
index 80a501b8..7e9b6fc3 100644
--- a/perl6-pod.html.markdown
+++ b/raku-pod.html.markdown
@@ -5,9 +5,9 @@ contributors:
filename: learnpod.pod6
---
-Pod is an easy-to-use and purely descriptive mark-up language,
+Pod is an easy-to-use and purely descriptive mark-up language,
with no presentational components. Besides its use for documenting
-Raku Perl 6 programs and modules, Pod can be utilized to write language
+Raku programs and modules, Pod can be utilized to write language
documentation, blogs, and other types of document composition as well.
Pod documents can be easily converted to HTML and many other formats
@@ -49,12 +49,12 @@ generate documentation.
```
=begin pod
-A very simple Raku Perl 6 Pod document. All the other directives go here!
+A very simple Raku Pod document. All the other directives go here!
=end pod
```
-Pod documents usually coexist with Raku Perl 6 code. If by themselves,
+Pod documents usually coexist with Raku code. If by themselves,
Pod files often have the `.pod6` suffix. Moving forward, it's assumed that
the constructs being discussed are surrounded by the `=begin pod ... =end pod`
directives.
@@ -65,7 +65,7 @@ directives.
Text can be easily styled as bold, italic, underlined or verbatim (for code
formatting) using the following formatting codes: `B<>`, `I<>`, `U<>`
-and `C<>`.
+and `C<>`.
```
B<This text is in Bold.>
@@ -83,7 +83,7 @@ just a single capital letter followed immediately by a set of single or double
angle brackets. The Unicode variant («») of the angle brackets can also be
used.
-### Headings
+### Headings
Headings are created by using the `=headN` directive where `N` is the
heading level.
@@ -145,7 +145,7 @@ Unordered lists can be created using the `=item` directive.
```
Sublists are achieved with items at each level specified using the `=item1`,
-`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
+`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
defaults to `=item1`.
```
@@ -157,7 +157,7 @@ defaults to `=item1`.
=item1 Item four
```
-Definition lists that define terms or commands use the `=defn` directive.
+Definition lists that define terms or commands use the `=defn` directive.
This is equivalent to the `<dl>` element in HTML.
```
@@ -186,13 +186,13 @@ As shown in the [Basic Text Formatting](#basic-text-formatting) section,
inline code can be created using the `C<>` code.
```
-In Raku Perl 6, there are several functions/methods to output text. Some of them
+In Raku, there are several functions/methods to output text. Some of them
are C<print>, C<put> and C<say>.
```
### Comments
-Although Pod blocks are ignored by the Raku Perl 6 compiler, everything
+Although Pod blocks are ignored by the Rakudo Raku compiler, everything
indentified as a Pod block will be read and interpreted by Pod renderers. In
order to prevent Pod blocks from being rendered by any renderer, use the
`=comment` directive.
@@ -206,21 +206,21 @@ order to prevent Pod blocks from being rendered by any renderer, use the
To create inline comments, use the `Z<>` code.
```
-Pod is awesome Z<Of course it is!>. And Raku Perl 6 too!
+Pod is awesome Z<Of course it is!>. And Raku too!
```
-Given that the Perl interpreter never executes embedded Pod blocks,
+Given that the Raku interpreter never executes embedded Pod blocks,
comment blocks can also be used as an alternative form of nestable block
-comments in Raku Perl 6.
+comments.
### Links
Creating links in Pod is quite easy and is done by enclosing them in
a `L<>` code. The general format is `L<Label|Url>` with `Label`
-being optional.
+being optional.
```
-Raku Perl 6 homepage is L<https://perl6.org>.
+Raku homepage is L<https://raku.org>.
L<Click me!|http://link.org/>.
```
@@ -242,7 +242,7 @@ The Pod specifications are not completely handled properly yet and this
includes the handling of table. For simplicity's sake, only one way of
constructing tables is shown here. To learn about good practices and see
examples of both good and bad tables, please visit
-<https://docs.perl6.org/language/tables>.
+<https://docs.raku.org/language/tables>.
```
=begin table
@@ -287,7 +287,7 @@ For example:
Delimited blocks are bounded by `=begin` and `=end` markers, both of which are
followed by a valid Pod identifier, which is the `typename` of the block.
-The general syntax is
+The general syntax is
```
=begin BLOCK_TYPE
@@ -304,7 +304,7 @@ Top level heading
```
This type of blocks is useful for creating headings, list items, code blocks,
-etc. with multiple paragraphs. For example,
+etc. with multiple paragraphs. For example,
* a multiline item of a list
@@ -345,7 +345,7 @@ say pow(6); #=> 36
Paragraph blocks are introduced by a `=for` marker and terminated by
the next Pod directive or the first blank line (which is not considered to
be part of the block's contents). The `=for` marker is followed by the
-`typename` of the block. The general syntax is
+`typename` of the block. The general syntax is
```
=for BLOCK_TYPE
@@ -360,10 +360,10 @@ Top level heading
```
## Configuration Data
-
+
Except for abbreviated blocks, both delimited blocks and paragraph
blocks can be supplied with configuration information about their
-contents right after the `typename` of the block. Thus the following
+contents right after the `typename` of the block. Thus the following
are more general syntaxes for these blocks:
* Delimited blocks
@@ -384,16 +384,16 @@ BLOCK DATA
```
The configuration information is provided in a format akin to the
-["colon pair"](https://docs.perl6.org/language/glossary#index-entry-Colon_Pair)
-syntax in Raku Perl 6. The following table is a simplified version of the
-different ways in which configuration info can be supplied. Please go to
-<https://docs.perl6.org/language/pod#Configuration_information> for a more
+["colon pair"](https://docs.raku.org/language/glossary#index-entry-Colon_Pair)
+syntax in Raku. The following table is a simplified version of the
+different ways in which configuration info can be supplied. Please go to
+<https://docs.raku.org/language/pod#Configuration_information> for a more
thorough treatment of the subject.
| Value | Specify with... | Example |
| :-------- | :------ | :------ |
-| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Perl6') |
-| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'perl6.org'} |
+| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Raku') |
+| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'raku.org'} |
| Boolean | :key/:key(True) | :skip-test(True) |
| Boolean | :!key/:key(False) | :!skip-test |
| String | :key('string') | :nonexec-reason('SyntaxError') |
@@ -450,7 +450,7 @@ we get the following output:
</pre>
This is highly dependent on the format output. For example, while this works
-when Pod is converted to HTML, it might not be preserved when converted
+when Pod is converted to HTML, it might not be preserved when converted
to Markdown.
### Block Pre-configuration
@@ -549,48 +549,48 @@ a Pod document, enclose them in a `E<>` code.
For example:
```
-Raku Perl 6 makes considerable use of the E<171> and E<187> characters.
-Raku Perl 6 makes considerable use of the E<laquo> and E<raquo> characters.
+Raku makes considerable use of the E<171> and E<187> characters.
+Raku makes considerable use of the E<laquo> and E<raquo> characters.
```
is rendered as:
-Raku Perl 6 makes considerable use of the « and » characters.
-Raku Perl 6 makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
## Rendering Pod
-To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
-have the Raku Perl 6 compiler installed. In addition, you must install
+To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
+have the Rakudo Raku compiler installed. In addition, you must install
a module (e.g., `Pod::To::Markdown`, `Pod::To::HTML`, `Pod::To::Text`, etc.)
that generates your desired output from Pod.
-For instructions about installing Raku Perl 6,
-[look here](https://perl6.org/downloads/).
+For instructions about installing Rakudo for running raku programs,
+[look here](https://raku.org/downloads/).
Run the following command to generate a certain output:
```
-perl6 --doc=TARGET input.pod6 > output.html
+raku --doc=TARGET input.pod6 > output.html
```
with `TARGET` being `Markdown`, `HTML`, `Text`, etc. Thus to generate
Markdown from Pod, run this:
```
-perl6 --doc=Markdown input.pod6 > output.html
+raku --doc=Markdown input.pod6 > output.html
```
## Accessing Pod
-In order to access Pod documentation from within a Raku Perl 6 program,
+In order to access Pod documentation from within a Raku program,
it is required to use the special `=` twigil (e.g., `$=pod`, `$=SYNOPSIS`,etc).
-The `$=` construct provides the introspection over the Pod structure,
+The `$=` construct provides the introspection over the Pod structure,
producing a `Pod::Block` tree root from which it is possible to access
the whole structure of the Pod document.
-If we place the following piece of Raku Perl 6 code and the Pod documentation
+If we place the following piece of Raku code and the Pod documentation
in the section [Semantic blocks](#semantic-blocks) in the same file:
```
@@ -615,8 +615,8 @@ AUTHOR
DESCRIPTION
```
-## Additional Information
+## Additional Information
-* <https://docs.perl6.org/language/pod> for the Pod documentation.
-* <https://docs.perl6.org/language/tables> for advices about Pod tables.
-* <https://design.perl6.org/S26.html> for the Pod specification.
+* <https://docs.raku.org/language/pod> for the Pod documentation.
+* <https://docs.raku.org/language/tables> for advices about Pod tables.
+* <https://design.raku.org/S26.html> for the Pod specification.
diff --git a/raku.html.markdown b/raku.html.markdown
index 2460ac7e..a8059791 100644
--- a/raku.html.markdown
+++ b/raku.html.markdown
@@ -15,7 +15,7 @@ the JVM and the [MoarVM](http://moarvm.com).
Meta-note:
-* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
+* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
comments (more below about them) are used whenever it's convenient.
* `# OUTPUT:` is used to represent the output of a command to any standard
stream. If the output has a newline, it's represented by the `␤` symbol.
@@ -23,7 +23,7 @@ Meta-note:
* `#=>` represents the value of an expression, return value of a sub, etc.
In some cases, the value is accompanied by a comment.
* Backticks are used to distinguish and highlight the language constructs
- from the text.
+ from the text.
```perl6
####################################################
@@ -95,7 +95,7 @@ my @array = 'a', 'b', 'c';
# equivalent to:
my @letters = <a b c>;
# In the previous statement, we use the quote-words (`<>`) term for array
-# of words, delimited by space. Similar to perl5's qw, or Ruby's %w.
+# of words, delimited by space. Similar to perl's qw, or Ruby's %w.
@array = 1, 2, 4;
@@ -116,12 +116,10 @@ say @array; # OUTPUT: «a 6 b␤»
# 1.3 Hashes, or key-value Pairs.
#
-=begin comment
-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.
-=end comment
+# 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 = 'a' => 1, 'b' => 2;
# Keys get auto-quoted when the fat comman (`=>`) is used. Trailing commas are
@@ -144,15 +142,13 @@ my %hash = 'a' => 1, 'b' => 2;
# The `:` (as in `:is-even`) and `:!` (as `:!is-odd`) constructs are known
# as the `True` and `False` shortcuts respectively.
-=begin comment
-As demonstrated in the example below, you can use {} to get the value from a key.
-If it's a string without spaces, you can actually use the quote-words operator
-(`<>`). Since Raku doesn't have barewords, as Perl does, `{key1}` doesn't work
-though.
-=end comment
+# As demonstrated in the example below, you can use {} to get the value from a key.
+# If it's a string without spaces, you can actually use the quote-words operator
+# (`<>`). Since Raku doesn't have barewords, as Perl does, `{key1}` doesn't work
+# though.
say %hash{'n'}; # OUTPUT: «2␤», gets value associated to key 'n'
say %hash<is-even>; # OUTPUT: «True␤», gets value associated to key 'is-even'
-
+
####################################################
# 2. Subroutines
####################################################
@@ -187,13 +183,11 @@ sub return-for {
}
say return-for; # OUTPUT: «Nil␤»
-=begin comment
-Positional arguments are required by default. To make them optional, use
-the `?` after the parameters' names.
+# Positional arguments are required by default. To make them optional, use
+# the `?` after the parameters' names.
-In the following example, the sub `with-optional` returns `(Any)` (Perl's
-null-like value) if no argument is passed. Otherwise, it returns its argument.
-=end comment
+# In the following example, the sub `with-optional` returns `(Any)` (Perl's
+# null-like value) if no argument is passed. Otherwise, it returns its argument.
sub with-optional( $arg? ) {
$arg;
}
@@ -201,13 +195,11 @@ with-optional; # returns Any
with-optional(); # returns Any
with-optional(1); # returns 1
-=begin comment
-You can also give provide a default value when they're not passed. Doing
-this make said parameter optional. Required parameters must come before
-optional ones.
+# You can also give provide a default value when they're not passed. Doing
+# this make said parameter optional. Required parameters must come before
+# optional ones.
-In the sub `greeting`, the parameter `$type` is optional.
-=end comment
+# In the sub `greeting`, the parameter `$type` is optional.
sub greeting( $name, $type = "Hello" ) {
say "$type, $name!";
}
@@ -215,22 +207,18 @@ sub greeting( $name, $type = "Hello" ) {
greeting("Althea"); # OUTPUT: «Hello, Althea!␤»
greeting("Arthur", "Good morning"); # OUTPUT: «Good morning, Arthur!␤»
-=begin comment
-You can also, by using a syntax akin to the one of hashes (yay unified syntax!),
-declared named parameters and thus pass named arguments to a subroutine.
-By default, named parameter are optional and will default to `Any`.
-=end comment
+# You can also, by using a syntax akin to the one of hashes (yay unified syntax!),
+# declared named parameters and thus pass named arguments to a subroutine.
+# By default, named parameter are optional and will default to `Any`.
sub with-named( $normal-arg, :$named ) {
say $normal-arg + $named;
}
with-named(1, named => 6); # OUTPUT: «7␤»
-=begin comment
-There's one gotcha to be aware of, here: If you quote your key, Raku
-won't be able to see it at compile time, and you'll have a single `Pair`
-object as a positional parameter, which means the function subroutine
-`with-named(1, 'named' => 6);` fails.
-=end comment
+# There's one gotcha to be aware of, here: If you quote your key, Raku
+# won't be able to see it at compile time, and you'll have a single `Pair`
+# object as a positional parameter, which means the function subroutine
+# `with-named(1, 'named' => 6);` fails.
with-named(2, :named(5)); # OUTPUT: «7␤»
# Similar to positional parameters, you can provide your named arguments with
@@ -241,11 +229,9 @@ sub named-def( :$def = 5 ) {
named-def; # OUTPUT: «5»
named-def(def => 15); # OUTPUT: «15»
-=begin comment
-In order to make a named parameter mandatory, you can append `!` to the
-parameter. This is the inverse of `?`, which makes a required parameter
-optional.
-=end comment
+# In order to make a named parameter mandatory, you can append `!` to the
+# parameter. This is the inverse of `?`, which makes a required parameter
+# optional.
sub with-mandatory-named( :$str! ) {
say "$str!";
@@ -254,33 +240,27 @@ with-mandatory-named(str => "My String"); # OUTPUT: «My String!␤»
# with-mandatory-named; # runtime error: "Required named parameter not passed"
# with-mandatory-named(3);# runtime error: "Too many positional parameters passed"
-=begin comment
-If a sub takes a named boolean argument, you can use the same "short boolean"
-hash syntax we discussed earlier.
-=end comment
+# If a sub takes a named boolean argument, you can use the same "short boolean"
+# hash syntax we discussed earlier.
sub takes-a-bool( $name, :$bool ) {
say "$name takes $bool";
}
takes-a-bool('config', :bool); # OUTPUT: «config takes True␤»
takes-a-bool('config', :!bool); # OUTPUT: «config takes False␤»
-=begin comment
-Since paranthesis can be omitted when calling a subroutine, you need to use
-`&` in order to distinguish between a call to a sub with no arguments and
-the code object.
+# Since parenthesis can be omitted when calling a subroutine, you need to use
+# `&` in order to distinguish between a call to a sub with no arguments and
+# the code object.
-For instance, in this example we must use `&` to store the sub `say-hello`
-(i.e., the sub's code object) in a variable, not a subroutine call.
-=end comment
+# For instance, in this example we must use `&` to store the sub `say-hello`
+# (i.e., the sub's code object) in a variable, not a subroutine call.
my &s = &say-hello;
my &other-s = sub { say "Anonymous function!" }
-=begin comment
-A sub can have a "slurpy" parameter, or what one'd call a
-"doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
-functions. For this, you must use `*@` (slurpy) which will "take everything
-else". You can have as many parameters *before* a slurpy one, but not *after*.
-=end comment
+# A sub can have a "slurpy" parameter, or what one'd call a
+# "doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
+# functions. For this, you must use `*@` (slurpy) which will "take everything
+# else". You can have as many parameters *before* a slurpy one, but not *after*.
sub as-many($head, *@rest) {
@rest.join(' / ') ~ " !";
}
@@ -289,35 +269,29 @@ say as-many('Happy', ['Happy', 'Birthday'], 'Day'); # OUTPUT: «Happy / Birthday
# Note that the splat (the *) did not consume the parameter before it.
-=begin comment
-There are other two variations of slurpy parameters in Raku. The previous one
-(namely, `*@`), known as flattened slurpy, flattens passed arguments. The other
-two are `**@` and `+@` known as unflattened slurpy and "single argument rule"
-slurpy respectively. The unflattened slurpy doesn't flatten its listy
-arguments (or Iterable ones).
-=end comment
+# There are other two variations of slurpy parameters in Raku. The previous one
+# (namely, `*@`), known as flattened slurpy, flattens passed arguments. The other
+# two are `**@` and `+@` known as unflattened slurpy and "single argument rule"
+# slurpy respectively. The unflattened slurpy doesn't flatten its listy
+# arguments (or Iterable ones).
sub b(**@arr) { @arr.perl.say };
b(['a', 'b', 'c']); # OUTPUT: «[["a", "b", "c"],]»
-b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
+b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
-=begin comment
-On the other hand, the "single argument rule" slurpy follows the "single argument
-rule" which dictates how to handle the slurpy argument based upon context and
-roughly states that if only a single argument is passed and that argument is
-Iterable, that argument is used to fill the slurpy parameter array. In any
-other case, `+@` works like `**@`.
-=end comment
+# On the other hand, the "single argument rule" slurpy follows the "single argument
+# rule" which dictates how to handle the slurpy argument based upon context and
+# roughly states that if only a single argument is passed and that argument is
+# Iterable, that argument is used to fill the slurpy parameter array. In any
+# other case, `+@` works like `**@`.
sub c(+@arr) { @arr.perl.say };
c(['a', 'b', 'c']); # OUTPUT: «["a", "b", "c"]␤»
c(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»
c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
-=begin comment
-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).
-=end comment
+# 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).
sub concat3($a, $b, $c) {
say "$a, $b, $c";
}
@@ -328,14 +302,12 @@ concat3(|@array); # OUTPUT: «a, b, c␤»
# 3. Containers
####################################################
-=begin comment
-In Raku, 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 by
-using the `is rw` trait.
-=end comment
+# In Raku, 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 by
+# using the `is rw` trait.
sub mutate( $n is rw ) {
$n++; # postfix ++ operator increments its argument but returns its old value
}
@@ -343,32 +315,26 @@ my $m = 42;
mutate $m; #=> 42, the value is incremented but the old value is returned
say $m; # OUTPUT: «43␤»
-=begin comment
-This works because we are passing the container $m to the `mutate` sub.
-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 the `mutate` sub.
+# 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
-=end comment
+# mutate 42; # Parameter '$n' expected a writable container, but got Int value
-=begin comment
-Similar error would be obtained, if a bound variable is passed to
-to the subroutine. In Raku, you bind a value to a variable using the binding
-operator `:=`.
-=end comment
+# Similar error would be obtained, if a bound variable is passed to
+# to the subroutine. In Raku, you bind a value to a variable using the binding
+# operator `:=`.
my $v := 50; # binding 50 to the variable $v
# mutate $v; # Parameter '$n' expected a writable container, but got Int value
-=begin comment
-If what you want is a copy instead, use the `is copy` trait which will
-cause the argument to be copied and allow you to modify the argument
-inside the routine without modifying the passed argument.
+# If what you want is a copy instead, use the `is copy` trait which will
+# cause the argument to be copied and allow you to modify the argument
+# inside the routine without modifying the passed argument.
-A sub itself returns a container, which means it can be marked as `rw`.
-Alternatively, you can explicitly mark the returned container as mutable
-by using `return-rw` instead of `return`.
-=end comment
+# A sub itself returns a container, which means it can be marked as `rw`.
+# Alternatively, you can explicitly mark the returned container as mutable
+# by using `return-rw` instead of `return`.
my $x = 42;
my $y = 45;
sub x-store is rw { $x }
@@ -390,12 +356,10 @@ say $y; # OUTPUT: «90␤»
# 4.1 if/if-else/if-elsif-else/unless
#
-=begin comment
-Before talking about `if`, we need to know which values are "truthy"
-(represent `True`), and which are "falsey" (represent `False`). Only these
-values are falsey: 0, (), {}, "", Nil, a type (like `Str`, `Int`, etc.) and
-of course, `False` itself. Any other value is truthy.
-=end comment
+# Before talking about `if`, we need to know which values are "truthy"
+# (represent `True`), and which are "falsey" (represent `False`). Only these
+# values are falsey: 0, (), {}, "", Nil, a type (like `Str`, `Int`, etc.) and
+# of course, `False` itself. Any other value is truthy.
my $number = 5;
if $number < 5 {
say "Number is less than 5"
@@ -422,11 +386,9 @@ unless False {
say "Quite truthy" if True; # OUTPUT: «Quite truthy␤»
say "Quite falsey" unless False; # OUTPUT: «Quite falsey␤»
-=begin comment
-The ternary operator (`??..!!`) is structured as follows `condition ??
-expression1 !! expression2` and it returns expression1 if the condition is
-true. Otherwise, it returns expression2.
-=end comment
+# The ternary operator (`??..!!`) is structured as follows `condition ??
+# expression1 !! expression2` and it returns expression1 if the condition is
+# true. Otherwise, it returns expression2.
my $age = 30;
say $age > 18 ?? "You are an adult" !! "You are under 18";
# OUTPUT: «You are an adult␤»
@@ -435,11 +397,9 @@ say $age > 18 ?? "You are an adult" !! "You are under 18";
# 4.2 with/with-else/with-orwith-else/without
#
-=begin comment
-The `with` statement is like `if`, but it tests for definedness rather than
-truth, and it topicalizes on the condition, much like `given` which will
-be discussed later.
-=end comment
+# The `with` statement is like `if`, but it tests for definedness rather than
+# truth, and it topicalizes on the condition, much like `given` which will
+# be discussed later.
my $s = "raku";
with $s.index("r") { say "Found a at $_" }
orwith $s.index("k") { say "Found c at $_" }
@@ -475,6 +435,7 @@ current iteration (unless explicitly named), etc.
Since other Raku constructs use this variable (as said before, like `for`,
blocks, `with` statement etc), this means the powerful `when` is not only
applicable along with a `given`, but instead anywhere a `$_` exists.
+
=end comment
given "foo bar" {
@@ -508,7 +469,7 @@ given "foo bar" {
# can also be a C-style `for` loop:
loop {
say "This is an infinite loop !";
- last;
+ last;
}
# In the previous example, `last` breaks out of the loop very much
# like the `break` keyword in other languages.
@@ -589,6 +550,7 @@ The categories are:
The associativity and precedence list are explained below.
Alright, you're set to go!
+
=end comment
#
@@ -614,8 +576,8 @@ say Int === Int; # OUTPUT: «True␤»
# Here are some common comparison semantics:
# String or numeric equality
-say 'Foo' ~~ 'Foo'; # OUTPU: «True␤», if strings are equal.
-say 12.5 ~~ 12.50; # OUTPU: «True␤», if numbers are equal.
+say 'Foo' ~~ 'Foo'; # OUTPUT: «True␤», if strings are equal.
+say 12.5 ~~ 12.50; # OUTPUT: «True␤», if numbers are equal.
# Regex - For matching a regular expression against the left side.
# Returns a `Match` object, which evaluates as True if regexp matches.
@@ -624,7 +586,7 @@ say $obj; # OUTPUT: «「a」␤»
say $obj.WHAT; # OUTPUT: «(Match)␤»
# Hashes
-say 'key' ~~ %hash; # OUTPUT:«True␤», if key exists in hash.
+say 'key' ~~ %hash; # OUTPUT: «True␤», if key exists in hash.
# Type - Checks if left side "is of type" (can check superclasses and roles).
say 1 ~~ Int; # OUTPUT: «True␤»
@@ -652,7 +614,7 @@ say 'a' le 'b'; # OUTPUT: «True␤»
# 5.2 Range constructor
#
-say 3 .. 7; # OUTPUT: «3..7␤», both included.
+say 3 .. 7; # OUTPUT: «3..7␤», both included.
say 3 ..^ 7; # OUTPUT: «3..^7␤», exclude right endpoint.
say 3 ^.. 7; # OUTPUT: «3^..7␤», exclude left endpoint.
say 3 ^..^ 7; # OUTPUT: «3^..^7␤», exclude both endpoints.
@@ -665,7 +627,7 @@ say 3.5 ~~ 3 ^.. 7; # OUTPUT: «True␤»,
# This is because the range `3 ^.. 7` only excludes anything strictly
# equal to 3. Hence, it contains decimals greater than 3. This could
-# mathematically be described as 3.5 ∈ (3,7] or in set notation,
+# mathematically be described as 3.5 ∈ (3,7] or in set notation,
# 3.5 ∈ { x | 3 < x ≤ 7 }.
say 3 ^.. 7 ~~ 4 .. 7; # OUTPUT: «False␤»
@@ -680,11 +642,9 @@ my @natural = 1..*; # 1 to Infinite! Equivalent to `1..Inf`.
# You can pass ranges as subscripts and it'll return an array of results.
say @natural[^10]; # OUTPUT: «1 2 3 4 5 6 7 8 9 10␤», doesn't run out of memory!
-=begin comment
-NOTE: when reading an infinite list, Raku 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.
-=end comment
+# NOTE: when reading an infinite list, Raku 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 than that are needed.
# An array subscript can also be a closure. It'll be called with the array's
# length as the argument. The following two examples are equivalent:
@@ -784,7 +744,7 @@ first-of-array(@small); #=> 1
# Here, `@rest` is `(3,)`, since `$fst` holds the `2`. This results
# since the length (.elems) of `@rest` is 1.
sub slurp-in-array(@ [$fst, *@rest]) {
- say $fst + @rest.elems;
+ say $fst + @rest.elems;
}
slurp-in-array(@tail); # OUTPUT: «3␤»
@@ -798,16 +758,14 @@ fst(1); # OUTPUT: «1␤»
# passed") though. After all, the `fst` sub declares only a single positional
# parameter.
-=begin comment
-You can also destructure hashes (and classes, which you'll learn about later).
-The syntax is basically the same as
-`%hash-name (:key($variable-to-store-value-in))`.
-The hash can stay anonymous if you only need the values you extracted.
-
-In order to call the function, you must supply a hash wither created with
-curly braces or with `%()` (recommended). Alternatively, you can pass
-a variable that contains a hash.
-=end comment
+# You can also destructure hashes (and classes, which you'll learn about later).
+# The syntax is basically the same as
+# `%hash-name (:key($variable-to-store-value-in))`.
+# The hash can stay anonymous if you only need the values you extracted.
+
+# In order to call the function, you must supply a hash wither created with
+# curly braces or with `%()` (recommended). Alternatively, you can pass
+# a variable that contains a hash.
sub key-of( % (:value($val), :qua($qua)) ) {
say "Got value $val, $qua time" ~~
@@ -826,12 +784,10 @@ sub next-index( $n ) {
}
my $new-n = next-index(3); # $new-n is now 4
-=begin comment
-This is true for everything, except for the looping constructs (due to
-performance reasons): there's no 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:
-=end comment
+# This is true for everything, except for the looping constructs (due to
+# performance reasons): there's no 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 { $_ }
@@ -842,7 +798,7 @@ my @list3 = list-of(3); #=> (0, 1, 2)
# 6.2 Lambdas (or anonymous subroutines)
#
-# You can create a lambda by using a pointy block (`-> {}`), a
+# You can create a lambda by using a pointy block (`-> {}`), a
# block (`{}`) or creating a `sub` without a name.
my &lambda1 = -> $argument {
@@ -857,31 +813,27 @@ my &lambda3 = sub ($argument) {
"The argument passed to this lambda is $argument"
}
-=begin comment
-Both pointy blocks and blocks are pretty much the same thing, except that
-the former can take arguments, and that the latter can be mistaken as
-a hash by the parser. That being said, blocks can declare what's known
-as placeholders parameters through the twigils `$^` (for positional
-parameters) and `$:` (for named parameters). More on them latern on.
-=end comment
+# Both pointy blocks and blocks are pretty much the same thing, except that
+# the former can take arguments, and that the latter can be mistaken as
+# a hash by the parser. That being said, blocks can declare what's known
+# as placeholders parameters through the twigils `$^` (for positional
+# parameters) and `$:` (for named parameters). More on them later on.
my &mult = { $^numbers * $:times }
say mult 4, :times(6); #=> «24␤»
# Both pointy blocks and blocks are quite versatile when working with functions
-# that accepts other functions such as `map`, `grep`, etc. For example,
+# that accepts other functions such as `map`, `grep`, etc. For example,
# we add 3 to each value of an array using the `map` function with a lambda:
my @nums = 1..4;
my @res1 = map -> $v { $v + 3 }, @nums; # pointy block, explicit parameter
my @res2 = map { $_ + 3 }, @nums; # block using an implicit parameter
my @res3 = map { $^val + 3 }, @nums; # block with placeholder parameter
-=begin comment
-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.
-=end comment
+# 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 ) {
@@ -895,23 +847,19 @@ sub truthy-array( @array ) {
say 'Hi';
}
-=begin comment
-In the `is-in` sub, the block will `return` out of the `is-in` sub once the
-condition evaluates to `True`, the loop won't be run anymore and the
-following statement won't be executed. The last statement is only executed
-if the block never returns.
-
-On the contrary, the `truthy-array` sub will produce an array of `True` and
-`False`, which will printed, and always execute the last execute statement.
-Thus, the `return` only returns from the anonymous `sub`
-=end comment
+# In the `is-in` sub, the block will `return` out of the `is-in` sub once the
+# condition evaluates to `True`, the loop won't be run anymore and the
+# following statement won't be executed. The last statement is only executed
+# if the block never returns.
-=begin comment
-The `anon` declarator can be used to create an anonymous sub from a
-regular subroutine. The regular sub knows its name but its symbol is
-prevented from getting installed in the lexical scope, the method table
-and everywhere else.
-=end comment
+# On the contrary, the `truthy-array` sub will produce an array of `True` and
+# `False`, which will printed, and always execute the last execute statement.
+# Thus, the `return` only returns from the anonymous `sub`
+
+# The `anon` declarator can be used to create an anonymous sub from a
+# regular subroutine. The regular sub knows its name but its symbol is
+# prevented from getting installed in the lexical scope, the method table
+# and everywhere else.
my $anon-sum = anon sub summation(*@a) { [+] @a }
say $anon-sum.name; # OUTPUT: «summation␤»
say $anon-sum(2, 3, 5); # OUTPUT: «10␤»
@@ -983,31 +931,27 @@ multi with-or-without-you {
say "Definitely can't live.";
}
-=begin comment
-This is very, very useful for many purposes, like `MAIN` subs (covered
-later), and even the language itself uses it in several places.
+# This is very, very useful for many purposes, like `MAIN` subs (covered
+# later), and even the language itself uses it in several places.
-For example, the `is` trait is actually a `multi sub` named `trait_mod:<is>`,
-and it works off that. Thus, `is rw`, is simply a dispatch to a function with
-this signature `sub trait_mod:<is>(Routine $r, :$rw!) {}`
-=end comment
+# For example, the `is` trait is actually a `multi sub` named `trait_mod:<is>`,
+# and it works off that. Thus, `is rw`, is simply a dispatch to a function with
+# this signature `sub trait_mod:<is>(Routine $r, :$rw!) {}`
####################################################
# 7. About types...
####################################################
-=begin comment
-Raku is gradually typed. This means you can specify the type of your
-variables/arguments/return types, or you can omit the type annotations in
-in which case they'll default to `Any`. Obviously you get access to a few
-base types, like `Int` and `Str`. The constructs for declaring types are
-`subset`, `class`, `role`, etc. which you'll see later.
-
-For now, let us examine `subset` which 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` clause.
-=end comment
+# Raku is gradually typed. This means you can specify the type of your
+# variables/arguments/return types, or you can omit the type annotations in
+# in which case they'll default to `Any`. Obviously you get access to a few
+# base types, like `Int` and `Str`. The constructs for declaring types are
+# `subset`, `class`, `role`, etc. which you'll see later.
+
+# For now, let us examine `subset` which 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` clause.
subset VeryBigInteger of Int where * > 500;
# Or the set of the whole numbers:
@@ -1025,14 +969,12 @@ my PENFO $yes-penfo = 36; # OK
# 8. Scoping
####################################################
-=begin comment
-In Raku, unlike many scripting languages, (such as Python, Ruby, PHP),
-you must declare your variables before using them. The `my` declarator
-we've used so far 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.
-=end comment
+# In Raku, unlike many scripting languages, (such as Python, Ruby, PHP),
+# you must declare your variables before using them. The `my` declarator
+# we've used so far 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 {
@@ -1052,17 +994,15 @@ outer()(); # OUTPUT: «Foo Bar␤»
# 9. Twigils
####################################################
-=begin comment
-There are many special `twigils` (composed sigils) in Raku. Twigils
-define a variable's scope.
-The `*` and `?` twigils work on standard variables:
- * for dynamic variables
- ? for compile-time variables
-
-The `!` and the `.` twigils are used with Raku's objects:
- ! for attributes (instance attribute)
- . for methods (not really a variable)
-=end comment
+# There are many special `twigils` (composed sigils) in Raku. Twigils
+# define a variable's scope.
+# The `*` and `?` twigils work on standard variables:
+# * for dynamic variables
+# ? for compile-time variables
+#
+# The `!` and the `.` twigils are used with Raku's objects:
+# ! for attributes (instance attribute)
+# . for methods (not really a variable)
#
# `*` twigil: Dynamic Scope
@@ -1084,14 +1024,14 @@ sub call_say_dyn {
my $*dyn_scoped_1 = 25;
# Will change the value of the file scoped variable.
- $*dyn_scoped_2 = 100;
+ $*dyn_scoped_2 = 100;
# $*dyn_scoped 1 and 2 will be looked for in the call.
say_dyn(); # OUTPUT: «25 100␤»
-
+
# The call to `say_dyn` uses the value of $*dyn_scoped_1 from inside
# this sub's lexical scope even though the blocks aren't nested (they're
- # call-nested).
+ # call-nested).
}
say_dyn(); # OUTPUT: «1 10␤»
@@ -1109,26 +1049,24 @@ say_dyn(); # OUTPUT: «1 100␤»
# 10. Object Model
####################################################
-=begin comment
-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 the `method` keyword.
-
-Every attribute that is private uses the `!` twigil. For example: `$!attr`.
-Immutable public attributes use the `.` twigil which creates a read-only
-method named after the attribute. In fact, declaring an attribute with `.`
-is equivalent to declaring the same attribute with `!` and then creating
-a read-only method with the attribute's name. However, this is done for us
-by Raku automatically. The easiest way to remember the `$.` twigil is
-by comparing it to how methods are called.
-
-Raku's object model ("SixModel") is very flexible, and allows you to
-dynamically add methods, change semantics, etc... Unfortunately, these will
-not all be covered here, and you should refer to:
-https://docs.raku.org/language/objects.html.
-=end comment
+# 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 the `method` keyword.
+
+# Every attribute that is private uses the `!` twigil. For example: `$!attr`.
+# Immutable public attributes use the `.` twigil which creates a read-only
+# method named after the attribute. In fact, declaring an attribute with `.`
+# is equivalent to declaring the same attribute with `!` and then creating
+# a read-only method with the attribute's name. However, this is done for us
+# by Raku automatically. The easiest way to remember the `$.` twigil is
+# by comparing it to how methods are called.
+
+# Raku's object model ("SixModel") is very flexible, and allows you to
+# dynamically add methods, change semantics, etc... Unfortunately, these will
+# not all be covered here, and you should refer to:
+# https://docs.raku.org/language/objects.html.
class Human {
has Str $.name; # `$.name` is immutable but with an accessor method.
@@ -1162,7 +1100,7 @@ class Human {
};
# Create a new instance of Human class.
-# NOTE: Only attributes declared with the `.` twigil can be set via the
+# NOTE: Only attributes declared with the `.` twigil can be set via the
# default constructor (more later on). This constructor only accepts named
# arguments.
my $person1 = Human.new(
@@ -1196,12 +1134,10 @@ $person1.get-info; #=> Jord born in Togo and now lives in France. Age: 10
# 10.1 Object Inheritance
#
-=begin comment
-Raku also has inheritance (along with multiple inheritance). While
-methods are inherited, submethods 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.
-=end comment
+# Raku also has inheritance (along with multiple inheritance). While
+# methods are inherited, submethods 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;
@@ -1232,13 +1168,11 @@ my Child $Madison .= new(age => 1, name => 'Madison');
$Madison.talk; # OUTPUT: «Goo goo ga ga␤», due to the overridden method.
# $Madison.favorite-color # does not work since it is not inherited.
-=begin comment
-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).
-Thus, `$a .= b` is the same as `$a = $a.b`. Also note that `BUILD` (the method
-called inside `new`) will set parent's properties too, so you can pass `val =>
-5`.
-=end comment
+# 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).
+# Thus, `$a .= b` is the same as `$a = $a.b`. Also note that `BUILD` (the method
+# called inside `new`) will set parent's properties too, so you can pass `val =>
+# 5`.
#
# 10.2 Roles, or Mixins
@@ -1281,15 +1215,13 @@ class Item does PrintableVal {
# 11. Exceptions
####################################################
-=begin comment
-Exceptions are built on top of classes, in the package `X` (like `X::IO`).
-In Raku, exceptions are automatically 'thrown':
+# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
+# In Raku, exceptions are automatically 'thrown':
-open 'foo'; # OUTPUT: «Failed to open file foo: no such file or directory␤»
+# open 'foo'; # OUTPUT: «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.
-=end comment
+# It will also print out what line the error was thrown at
+# and other error info.
# You can throw an exception using `die`. Here it's been commented out to
# avoid stopping the program's execution:
@@ -1298,58 +1230,48 @@ and other error info.
# Or more explicitly (commented out too):
# X::AdHoc.new(payload => 'Error!').throw; # OUTPUT: «Error!␤»
-=begin comment
-In Raku, `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:
-=end comment
+# In Raku, `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 $uninitialized.defined; # OUTPUT: «False␤»
-=begin comment
-When using `orelse` it will disarm the exception and alias $_ to that
-failure. This will prevent it to being automatically handled and printing
-lots of scary error messages to the screen. We can use the `exception`
-method on the `$_` variable to access the exception
-=end comment
+# When using `orelse` it will disarm the exception and alias $_ to that
+# failure. This will prevent it to being automatically handled and printing
+# lots of scary error messages to the screen. We can use the `exception`
+# method on the `$_` variable to access the exception
open 'foo' orelse say "Something happened {.exception}";
# This also works:
-open 'foo' orelse say "Something happened $_";
+open 'foo' orelse say "Something happened $_";
# OUTPUT: «Something happened Failed to open file foo: no such file or directory␤»
-=begin comment
-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.
-=end comment
+# 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.
#
# 11.1 Using `try` and `CATCH`
#
-=begin comment
-By using `try` and `CATCH` you can contain and handle exceptions without
-disrupting the rest of the program. The `try` block will set the last
-exception to the special variable `$!` (known as the error variable).
-NOTE: This has no relation to $!variables seen inside class definitions.
-=end comment
+# By using `try` and `CATCH` you can contain and handle exceptions without
+# disrupting the rest of the program. The `try` block will set the last
+# exception to the special variable `$!` (known as the error variable).
+# NOTE: This has no relation to $!variables seen inside class definitions.
try open 'foo';
say "Well, I tried! $!" if defined $!;
# OUTPUT: «Well, I tried! Failed to open file foo: no such file or directory␤»
-=begin comment
-Now, what if we want more control over handling the exception?
-Unlike many other languages, in Raku, you put the `CATCH` block *within*
-the block to `try`. Similar to how the `$_` variable was set when we
-'disarmed' the exception with `orelse`, we also use `$_` in the CATCH block.
-NOTE: The `$!` variable is only set *after* the `try` block has caught an
-exception. By default, a `try` block has a `CATCH` block of its own that
-catches any exception (`CATCH { default {} }`).
-=end comment
+# Now, what if we want more control over handling the exception?
+# Unlike many other languages, in Raku, you put the `CATCH` block *within*
+# the block to `try`. Similar to how the `$_` variable was set when we
+# 'disarmed' the exception with `orelse`, we also use `$_` in the CATCH block.
+# NOTE: The `$!` variable is only set *after* the `try` block has caught an
+# exception. By default, a `try` block has a `CATCH` block of its own that
+# catches any exception (`CATCH { default {} }`).
try {
my $a = (0 %% 0);
@@ -1387,15 +1309,13 @@ try {
}
# OUTPUT: «Failed to open file /dir/foo: no such file or directory␤»
-=begin comment
-There are also some subtleties to exceptions. Some Raku subs return a
-`Failure`, which is a wrapper around an `Exception` object which is
-"unthrown". They're not thrown until you try to use the variables containing
-them 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`).
-=end comment
+# There are also some subtleties to exceptions. Some Raku subs return a
+# `Failure`, which is a wrapper around an `Exception` object which is
+# "unthrown". They're not thrown until you try to use the variables containing
+# them 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`).
my $value = 0/0; # We're not trying to access the value, so no problem.
try {
@@ -1407,39 +1327,33 @@ try {
}
}
-=begin comment
-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).
-=end comment
+# 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).
####################################################
# 12. Packages
####################################################
-=begin comment
-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.
-=end comment
+# 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`:
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; # OUTPUT: «[1]␤»
-=begin comment
-You should not declare packages using the `package` keyword (unlike Perl 5).
-Instead, use `class Package::Name::Here;` to declare a class, or if you only
-want to export variables/subs, you can use `module` instead.
-=end comment
+# You should not declare packages using the `package` keyword (unlike Perl).
+# Instead, use `class Package::Name::Here;` to declare a class, or if you only
+# want to export variables/subs, you can use `module` instead.
# If `Hello` doesn't exist yet, it'll just be a "stub", that can be redeclared
-# as something else later.
+# as something else later.
module Hello::World { # bracketed form
- # declarations here
+ # declarations here
}
# The file-scoped form which extends until the end of the file. For
@@ -1460,14 +1374,12 @@ my $actions = JSON::Tiny::Actions.new;
# 13. Declarators
####################################################
-=begin comment
-In Raku, 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 Raku, 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` - these declarations happen at `INIT` time -- (see "Phasers" below).
-It's like `my`, but it also creates a package variable. All packagish
-things such as `class`, `role`, etc. are `our` by default.
-=end comment
+# `our` - these declarations happen at `INIT` time -- (see "Phasers" below).
+# It's like `my`, but it also creates a package variable. All packagish
+# things such as `class`, `role`, etc. are `our` by default.
module Var::Increment {
# NOTE: `our`-declared variables cannot be typed.
@@ -1520,7 +1432,7 @@ fixed-rand for ^10; # will print the same number 10 times
for ^5 -> $a {
sub foo {
# This will be a different value for every value of `$a`
- state $val = rand;
+ state $val = rand;
}
for ^5 -> $b {
# This will print the same value 5 times, but only 5. Next iteration
@@ -1533,15 +1445,13 @@ for ^5 -> $a {
# 14. Phasers
####################################################
-=begin comment
-Phasers in Raku 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 (The `CATCH` block 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!
-=end comment
+# Phasers in Raku 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 (The `CATCH` block 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!
#
# 14.1 Compile-time phasers
@@ -1558,9 +1468,9 @@ END { say "Runs at run time, as late as possible, only once" }
#
# 14.3 Block phasers
#
-ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" }
+ENTER { say "[*] Runs every time you enter a block, repeats on loop blocks" }
LEAVE {
- say "Runs everytime you leave a block, even when an exception
+ say "Runs every time you leave a block, even when an exception
happened. Repeats on loop blocks."
}
@@ -1610,7 +1520,7 @@ for ^5 {
#
# 14.6 Role/class phasers
#
-COMPOSE {
+COMPOSE {
say "When a role is composed into a class. /!\ NOT YET IMPLEMENTED"
}
@@ -1619,9 +1529,9 @@ say "This code took " ~ (time - CHECK time) ~ "s to compile";
# ... or clever organization:
class DB {
- method start-transaction { say "Starting transation!" }
- method commit { say "Commiting transaction..." }
- method rollback { say "Something went wrong. Rollingback!" }
+ method start-transaction { say "Starting transaction!" }
+ method commit { say "Committing transaction..." }
+ method rollback { say "Something went wrong. Rolling back!" }
}
sub do-db-stuff {
@@ -1637,17 +1547,14 @@ do-db-stuff();
# 15. Statement prefixes
####################################################
-=begin comment
-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 curly
-braces `{` and `}`.
-
-=end comment
+# 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 curly
+# braces `{` and `}`.
#
-# 15.1 `do` - It runs a block or a statement as a term.
+# 15.1 `do` - It runs a block or a statement as a term.
#
# Normally you cannot use a statement as a value (or "term"). `do` helps
@@ -1757,40 +1664,34 @@ quietly { warn 'This is a warning!' }; # No output
my ($p, $q, $r) = (1, 2, 3);
-=begin comment
-Given some binary operator § (not a Raku-supported operator), then:
+# Given some binary operator § (not a Raku-supported operator), then:
-$p § $q § $r; # with a left-associative §, this is ($p § $q) § $r
-$p § $q § $r; # with a right-associative §, this is $p § ($q § $r)
-$p § $q § $r; # with a non-associative §, this is illegal
-$p § $q § $r; # with a chain-associative §, this is ($p § $q) and ($q § $r)§
-$p § $q § $r; # with a list-associative §, this is `infix:<>`
-=end comment
+# $p § $q § $r; # with a left-associative §, this is ($p § $q) § $r
+# $p § $q § $r; # with a right-associative §, this is $p § ($q § $r)
+# $p § $q § $r; # with a non-associative §, this is illegal
+# $p § $q § $r; # with a chain-associative §, this is ($p § $q) and ($q § $r)§
+# $p § $q § $r; # with a list-associative §, this is `infix:<>`
#
# 17.2 Unary operators
#
-=begin comment
-Given some unary operator § (not a Raku-supported operator), then:
-§$p§ # with left-associative §, this is (§$p)§
-§$p§ # with right-associative §, this is §($p§)
-§$p§ # with non-associative §, this is illegal
-=end comment
+# Given some unary operator § (not a Raku-supported operator), then:
+# §$p§ # with left-associative §, this is (§$p)§
+# §$p§ # with right-associative §, this is §($p§)
+# §$p§ # with non-associative §, this is illegal
#
# 17.3 Create your own operators!
#
-=begin comment
-Okay, you've been reading all of that, so you might want to try something
-more exciting?! I'll tell you a little secret (or not-so-secret):
-In Raku, all operators are actually just funny-looking subroutines.
+# Okay, you've been reading all of that, so you might want to try something
+# more exciting?! I'll tell you a little secret (or not-so-secret):
+# In Raku, all operators are actually just funny-looking subroutines.
-You can declare an operator just like you declare a sub. In the following
-example, `prefix` refers to the operator categories (prefix, infix, postfix,
-circumfix, and post-circumfix).
-=end comment
+# You can declare an operator just like you declare a sub. In the following
+# example, `prefix` refers to the operator categories (prefix, infix, postfix,
+# circumfix, and post-circumfix).
sub prefix:<win>( $winner ) {
say "$winner Won!";
}
@@ -1805,7 +1706,7 @@ sub postfix:<!>( Int $n ) {
}
say 5!; # OUTPUT: «120␤»
-# Postfix operators ('after') have to come *directly* after the term.
+# Postfix operators ('after') have to come *directly* after the term.
# No whitespace. You can use parentheses to disambiguate, i.e. `(5!)!`
sub infix:<times>( Int $n, Block $r ) { # infix ('between')
@@ -1834,12 +1735,10 @@ say "abc"{1}; # OUTPUT: «b␤», after the term `"abc"`, and around the index (
# Post-circumfix is 'after a term, around something'
-=begin comment
-This really means a lot -- because everything in Raku uses this.
-For example, to delete a key from a hash, you use the `:delete` adverb
-(a simple named argument underneath). For instance, the following statements
-are equivalent.
-=end comment
+# This really means a lot -- because everything in Raku uses this.
+# For example, to delete a key from a hash, you use the `:delete` adverb
+# (a simple named argument underneath). For instance, the following statements
+# are equivalent.
my %person-stans =
'Giorno Giovanna' => 'Gold Experience',
'Bruno Bucciarati' => 'Sticky Fingers';
@@ -1848,34 +1747,30 @@ my $key = 'Bruno Bucciarati';
postcircumfix:<{ }>( %person-stans, 'Giorno Giovanna', :delete );
# (you can call operators like this)
-=begin comment
-It's *all* using the same building blocks! Syntactic categories
-(prefix infix ...), named arguments (adverbs), ..., etc. used to build
-the language - are available to you. Obviously, you're advised against
-making an operator out of *everything* -- with great power comes great
-responsibility.
-=end comment
+# It's *all* using the same building blocks! Syntactic categories
+# (prefix infix ...), named arguments (adverbs), ..., etc. used to build
+# the language - are available to you. Obviously, you're advised against
+# making an operator out of *everything* -- with great power comes great
+# responsibility.
#
# 17.4 Meta operators!
#
-=begin comment
-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 this. (I'm guessing you don't want to go back at this point but
-let's continue, for the journey is long and enjoyable!).
-
-Meta-operators, as their name suggests, are *composed* operators. Basically,
-they're operators that act on another operators.
-
-The reduce meta-operator is 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 first element of a list) and the popped element.
-=end comment
+# 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 this. (I'm guessing you don't want to go back at this point but
+# let's continue, for the journey is long and enjoyable!).
+
+# Meta-operators, as their name suggests, are *composed* operators. Basically,
+# they're operators that act on another operators.
+
+# The reduce meta-operator is 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 first element of a list) and the popped element.
# To sum a list, you could use the reduce meta-operator with `+`, i.e.:
say [+] 1, 2, 3; # OUTPUT: «6␤», equivalent to (1+2)+3.
@@ -1898,18 +1793,16 @@ say [+] (); # OUTPUT: «0␤», empty sum
say [//]; # OUTPUT: «(Any)␤»
# There's no "default value" for `//`.
-# You can also use it with a function you made up,
+# You can also use it with a function you made up,
# You can also surround using double brackets:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; # OUTPUT: «6␤»
-=begin comment
-The zip meta-operator 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.
-=end comment
+# The zip meta-operator 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.
say (1, 2) Z (3, 4); # OUTPUT: «((1, 3), (2, 4))␤»
say 1..3 Z+ 4..6; # OUTPUT: «(5, 7, 9)␤»
@@ -1922,12 +1815,10 @@ say 1..3 Z+ 4..6; # OUTPUT: «(5, 7, 9)␤»
# And to end the operator list:
-=begin comment
-The sequence operator (`...`) is one of Raku's most powerful features:
-It's composed by the list (which might include a closure) you want Raku to
-deduce from on the left and a value (or either a predicate or a Whatever Star
-for a lazy infinite list) on the right that states when to stop.
-=end comment
+# The sequence operator (`...`) is one of Raku's most powerful features:
+# It's composed by the list (which might include a closure) you want Raku to
+# deduce from on the left and a value (or either a predicate or a Whatever Star
+# for a lazy infinite list) on the right that states when to stop.
# Basic arithmetic sequence
my @listv0 = 1, 2, 3...10;
@@ -1954,68 +1845,60 @@ my @fibv1 = 1, 1, -> $a, $b { $a + $b } ... *;
# Equivalent to the above example but using a block with placeholder parameters.
my @fibv2 = 1, 1, { $^a + $^b } ... *;
-=begin comment
-In the examples with explicit parameters (i.e., $a and $b), $a and $b
-will always take the previous values, meaning that for the Fibonacci sequence,
-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.
-=end comment
+# In the examples with explicit parameters (i.e., $a and $b), $a and $b
+# will always take the previous values, meaning that for the Fibonacci sequence,
+# 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.
-=begin comment
# In the example we use a range as an index to access the sequence. However,
# it's worth noting that for ranges, once reified, elements aren't re-calculated.
# That's why, for instance, `@primes[^100]` will take a long time the first
-# time you print it but then it will be instateneous.
-=end comment
+# time you print it but then it will be instantaneous.
say @fibv0[^10]; # OUTPUT: «1 1 2 3 5 8 13 21 34 55␤»
####################################################
# 18. Regular Expressions
####################################################
-=begin comment
-I'm sure a lot of you have been waiting for this one. Well, now that you know
-a good deal of Raku 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.
-
-Raku 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 which we won't be discussing this in this tutorial, though.
-
-In essence, Raku 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
-=end comment
+# I'm sure a lot of you have been waiting for this one. Well, now that you know
+# a good deal of Raku 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.
+
+# Raku 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 which we won't be discussing this in this tutorial, though.
+
+# In essence, Raku 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/; # OUTPUT: «True␤»
say so 'a' ~~ / a /; # OUTPUT: «True␤», more readable with some spaces!
-=begin comment
-In all our examples, we're going to use the smart-matching operator against
-a regexp. We're converting the result using `so` to a Boolean value because,
-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 in the `$/` variable (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 character of the string. We'll
-explain later how you can do it.
-
-In Raku, you can have any alphanumeric as a literal, everything else has
-to be escaped by using a backslash or quotes.
-=end comment
+# In all our examples, we're going to use the smart-matching operator against
+# a regexp. We're converting the result using `so` to a Boolean value because,
+# 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 in the `$/` variable (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 character of the string. We'll
+# explain later how you can do it.
+
+# In Raku, you can have any alphanumeric as a literal, everything else has
+# to be escaped by using a backslash or quotes.
say so 'a|b' ~~ / a '|' b /; # OUTPUT: «True␤», it wouldn't mean the same
# thing if `|` wasn't escaped.
say so 'a|b' ~~ / a \| b /; # OUTPUT: «True␤», another way to escape it.
@@ -2030,12 +1913,10 @@ say so 'a b c' ~~ /:s a b c /; #=> `True`, we added the modifier `:s` here.
say so 'a b c' ~~ / a b c /; # OUTPUT: «False␤»
say so 'a b c' ~~ / a b c /; # OUTPUT: «False»
-=begin comment
-NOTE: 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.
-=end comment
+# NOTE: 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':
@@ -2078,19 +1959,19 @@ say so 'abc' ~~ / a b+ c /; # OUTPUT: «True␤», one is enough
say so 'abbbbc' ~~ / a b+ c /; # OUTPUT: «True␤», matched 4 "b"s
# `*` - zero or more matches
-say so 'ac' ~~ / a b* c /; # OUTPU: «True␤», they're all optional
-say so 'abc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'abbbbc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'aec' ~~ / a b* c /; # OUTPU: «False␤», "b"(s) are optional, not replaceable.
+say so 'ac' ~~ / a b* c /; # OUTPUT: «True␤», they're all optional
+say so 'abc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'aec' ~~ / a b* c /; # OUTPUT: «False␤», "b"(s) are optional, not replaceable.
# `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand why exponentation is used
# for quantity.
-say so 'abc' ~~ / a b**1 c /; # OUTPU: «True␤», exactly one time
-say so 'abc' ~~ / a b**1..3 c /; # OUTPU: «True␤», one to three times
-say so 'abbbc' ~~ / a b**1..3 c /; # OUTPU: «True␤»
-say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPU: «Fals␤», too much
-say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPU: «True␤», infinite ranges are ok
+say so 'abc' ~~ / a b**1 c /; # OUTPUT: «True␤», exactly one time
+say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «True␤», one to three times
+say so 'abbbc' ~~ / a b**1..3 c /; # OUTPUT: «True␤»
+say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPUT: «Fals␤», too much
+say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPUT: «True␤», infinite ranges are ok
#
# 18.2 `<[]>` - Character classes
@@ -2150,25 +2031,23 @@ say so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # OUTPUT: «True␤
say $/; # Will either print the matched object or `Nil` if nothing matched.
# As we also said before, it has array indexing:
-say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
+say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
# The corner brackets (「..」) represent (and are) `Match` objects. In the
# previous example, we have an array of them.
say $0; # The same as above.
-=begin comment
-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 captures (indexed using `$0`, `$/[0]` or a named one) will be an array
-if and only if they can have more than one element. Thus any capture 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.
-=end comment
+# 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 captures (indexed using `$0`, `$/[0]` or a named one) will be an array
+# if and only if they can have more than one element. Thus any capture 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.
say so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # OUTPUT: «True␤»
say $/[0]; # OUTPUT: «「ABC」␤»
say $0.WHAT; # OUTPUT: «(Match)␤»
@@ -2187,42 +2066,38 @@ say $0.WHAT; # OUTPUT: «(Array)␤», A specific quantifier will always capture
say $/[0].Str; # OUTPUT: «hello~␤»
say $/[0][0].Str; # OUTPUT: «~␤»
-=begin comment
-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.
-
-In the following example, we can see `$_` is a list of `Match` objects.
-Each of them contain a wealth of information: where the match started/ended,
-the "ast" (see actions later), etc. You'll see named capture below with
-grammars.
-=end comment
+# 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.
+
+# In the following example, we can see `$_` is a list of `Match` objects.
+# Each of them contain a wealth of information: where the match started/ended,
+# the "ast" (see actions later), etc. You'll see named capture below with
+# grammars.
say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list␤»
# Alternation - the `or` of regexes
# WARNING: They are DIFFERENT from PCRE regexps.
-say so 'abc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Either "b" or "y".
-say so 'ayc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Obviously enough...
+say so 'abc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Either "b" or "y".
+say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Obviously enough...
# The difference between this `|` and the one you're used to is
# LTM ("Longest Token Matching") strategy. This means that the engine will
# always try to match as much as possible in the string.
say 'foo' ~~ / fo | foo /; # OUTPUT: «foo», instead of `fo`, because it's longer.
-=begin comment
-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)
- which includes alternations (`|`), conjunctions (`&`), sub-rule calls (not
- yet introduced), literals, characters classes and quantifiers.
-
- * The "procedural part" includes everything else: back-references,
- code assertions, and other things that can't traditionnaly be represented
- by normal regexps.
+# 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)
+# which includes alternations (`|`), conjunctions (`&`), sub-rule calls (not
+# yet introduced), literals, characters classes and quantifiers.
+#
+# * The "procedural part" includes everything else: back-references,
+# code assertions, and other things that can't traditionally be represented
+# by normal regexps.
-Then, all the alternatives are tried at once, and the longest wins.
-=end comment
+# Then, all the alternatives are tried at once, and the longest wins.
# Examples:
# DECLARATIVE | PROCEDURAL
@@ -2243,55 +2118,49 @@ say 'foo' ~~ / fo || foo /; # OUTPUT: «fo␤», in this case.
# 19. Extra: the MAIN subroutine
####################################################
-=begin comment
-The `MAIN` subroutine is called when you run a Raku file directly. It's
-very powerful, because Raku 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` flag.
-=end comment
+# The `MAIN` subroutine is called when you run a Raku file directly. It's
+# very powerful, because Raku 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` flag.
sub MAIN($name) {
say "Hello, $name!";
}
-=begin comment
-Supposing the code above is in file named cli.raku, then running in the command
-line (e.g., $ raku cli.raku) produces:
-Usage:
- cli.raku <name>
-=end comment
+# Supposing the code above is in file named cli.raku, then running in the command
+# line (e.g., $ raku cli.raku) produces:
+# Usage:
+# cli.raku <name>
-=begin comment
-And since MAIN is a regular Raku sub, you can have multi-dispatch:
-(using a `Bool` for the named argument so that we can do `--replace`
-instead of `--replace=1`. The presence of `--replace` indicates truthness
-while its absence falseness). For example:
+# And since MAIN is a regular Raku sub, you can have multi-dispatch:
+# (using a `Bool` for the named argument so that we can do `--replace`
+# instead of `--replace=1`. The presence of `--replace` indicates truthness
+# while its absence falseness). For example:
# convert to IO object to check the file exists
+ =begin comment
subset File of Str where *.IO.d;
-
+
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
+ =end comment
-Thus $ raku cli.raku produces:
-Usage:
- cli.raku [--replace] add <key> <value>
- cli.raku remove <key>
- cli.raku [--as=<Str>] import <File>
+# Thus $ raku cli.raku produces:
+# Usage:
+# cli.raku [--replace] add <key> <value>
+# cli.raku remove <key>
+# cli.raku [--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).
-=end comment
+# 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).
####################################################
# 20. APPENDIX A:
####################################################
-=begin comment
-It's assumed by now you know the Raku basics. This section is just here to
-list some common operations, but which are not in the "main part" of the
-tutorial to avoid bloating it up.
-=end comment
+# It's assumed by now you know the Raku basics. This section is just here to
+# list some common operations, but which are not in the "main part" of the
+# tutorial to avoid bloating it up.
#
# 20.1 Operators
@@ -2316,14 +2185,12 @@ say Any // Nil // 0 // 5; # OUTPUT: «0␤»
# its arguments is true
say True ^^ False; # OUTPUT: «True␤»
-=begin comment
-Flip flops. These operators (`ff` and `fff`, equivalent to P5's `..`
-and `...`) 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`. Similar to ranges, you can exclude the iteration when
-it become `True`/`False` by using `^` on either side. Let's start with an
-example :
-=end comment
+# Flip flops. These operators (`ff` and `fff`, equivalent to P5's `..`
+# and `...`) 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`. Similar to ranges, you can exclude the iteration when
+# it become `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 `$_`:
@@ -2336,20 +2203,16 @@ for <well met young hero we shall meet later> {
}
}
-=begin comment
-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`.
-=end comment
+# 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`.
-=begin comment
-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:
-=end comment
+# 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:
# The output is due to the right-hand-side being tested directly (and returning
# `True`). "B"s are printed since it matched that time (it just went back to
@@ -2358,7 +2221,7 @@ side, once its left side changed:
# In this case the right-hand-side wasn't tested until `$_` became "C"
# (and thus did not match instantly).
-.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
+.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
# A flip-flop can change state as many times as needed:
for <test start print it stop not printing start print again stop not anymore> {
@@ -2392,21 +2255,20 @@ resource on Raku. If you are looking for something, use the search bar.
This will give you a dropdown menu of all the pages referencing your search
term (Much better than using Google to find Raku documents!).
-- Read the [Raku Advent Calendar](http://perl6advent.wordpress.com/). This
+- Read the [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). This
is a great source of Raku snippets and explanations. If the docs don't
describe something well enough, you may find more detailed information here.
This information may be a bit older but there are many great examples and
explanations. Posts stopped at the end of 2015 when the language was declared
-stable and Raku 6.c was released.
+stable and `Raku v6.c` was released.
-- Come along on `#raku` at `irc.freenode.net`. The folks here are
+- Come along on `#raku` at [`irc.libera.chat`](https://web.libera.chat/?channel=#raku). The folks here are
always helpful.
- Check the [source of Raku's functions and
-classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is
+classes](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo is
mainly written in Raku (with a lot of NQP, "Not Quite Perl", a Raku subset
easier to implement and optimize).
- Read [the language design documents](https://design.raku.org/). They explain
Raku from an implementor point-of-view, but it's still very interesting.
-
diff --git a/raylib.html.markdown b/raylib.html.markdown
new file mode 100644
index 00000000..0afc6e03
--- /dev/null
+++ b/raylib.html.markdown
@@ -0,0 +1,146 @@
+---
+category: tool
+tool: raylib
+filename: learnraylib.c
+contributors:
+ - ["Nikolas Wipper", "https://notnik.cc"]
+---
+
+**raylib** is a cross-platform easy-to-use graphics library, built around
+OpenGL 1.1, 2.1, 3.3 and OpenGL ES 2.0. Even though it is written in C
+it has bindings to over 50 different languages. This tutorial will use C,
+more specifically C99.
+
+```c
+#include <raylib.h>
+
+int main(void)
+{
+ const int screenWidth = 800;
+ const int screenHeight = 450;
+
+ // Before initialising raylib we can set configuration flags
+ SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
+
+ // raylib doesn't require us to store any instance structures
+ // At the moment raylib can handle only one window at a time
+ InitWindow(screenWidth, screenHeight, "MyWindow");
+
+ // Set our game to run at 60 frames-per-second
+ SetTargetFPS(60);
+
+ // Set a key that closes the window
+ // Could be 0 for no key
+ SetExitKey(KEY_DELETE);
+
+ // raylib defines two types of cameras: Camera3D and Camera2D
+ // Camera is a typedef for Camera3D
+ Camera camera = {
+ .position = {0.0f, 0.0f, 0.0f},
+ .target = {0.0f, 0.0f, 1.0f},
+ .up = {0.0f, 1.0f, 0.0f},
+ .fovy = 70.0f,
+ .type = CAMERA_PERSPECTIVE
+ };
+
+ // raylib supports loading of models, animations, images and sounds
+ // from various different file formats
+ Model myModel = LoadModel("my_model.obj");
+ Font someFont = LoadFont("some_font.ttf");
+
+ // Creates a 100x100 render texture
+ RenderTexture renderTexture = LoadRenderTexture(100, 100);
+
+ // WindowShouldClose checks if the user is closing the window
+ // This might happen using a shortcut, window controls
+ // or the key we set earlier
+ while (!WindowShouldClose())
+ {
+
+ // BeginDrawing needs to be called before any draw call
+ BeginDrawing();
+ {
+
+ // Sets the background to a certain color
+ ClearBackground(BLACK);
+
+ if (IsKeyDown(KEY_SPACE))
+ DrawCircle(400, 400, 30, GREEN);
+
+ // Simple draw text
+ DrawText("Congrats! You created your first window!",
+ 190, // x
+ 200, // y
+ 20, // font size
+ LIGHTGRAY
+ );
+
+ // For most functions there are several versions
+ // These are usually postfixed with Ex, Pro, V
+ // or sometimes Rec, Wires (only for 3D), Lines (only for 2D)
+ DrawTextEx(someFont,
+ "Text in another font",
+ (Vector2) {10, 10},
+ 20, // font size
+ 2, // spacing
+ LIGHTGRAY);
+
+ // Required for drawing 3D, has 2D equivalent
+ BeginMode3D(camera);
+ {
+
+ DrawCube((Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, 1.0f, 1.0f, RED);
+
+ // White tint when drawing will keep the original color
+ DrawModel(myModel, (Vector3) {0.0f, 0.0f, 3.0f},
+ 1.0f, //Scale
+ WHITE);
+
+ }
+ // End 3D mode so we can draw normally again
+ EndMode3D();
+
+ // Start drawing onto render texture
+ BeginTextureMode(renderTexture);
+ {
+
+ // It behaves the same as if we just called `BeginDrawing()`
+
+ ClearBackground(RAYWHITE);
+
+ BeginMode3D(camera);
+ {
+
+ DrawGrid(10, // Slices
+ 1.0f // Spacing
+ );
+
+ }
+ EndMode3D();
+
+ }
+ EndTextureMode();
+
+ // render textures have a Texture2D field
+ DrawTexture(renderTexture.texture, 40, 378, BLUE);
+
+ }
+ EndDrawing();
+ }
+
+ // Unloading loaded objects
+ UnloadFont(someFont);
+ UnloadModel(myModel);
+
+ // Close window and OpenGL context
+ CloseWindow();
+
+ return 0;
+}
+
+```
+
+## Further reading
+raylib has some [great examples](https://www.raylib.com/examples.html)
+If you don't like C check out the [raylib bindings](https://github.com/raysan5/raylib/blob/master/BINDINGS.md) \ No newline at end of file
diff --git a/red.html.markdown b/red.html.markdown
index 74538bd7..34c4bcd9 100644
--- a/red.html.markdown
+++ b/red.html.markdown
@@ -216,7 +216,7 @@ The Red/System language specification can be found [here](http://static.red-lang
To learn more about Rebol and Red join the [chat on Gitter](https://gitter.im/red/red). And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM).
-Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/red).
+Browse or ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/red).
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown
index 32a878b2..de946861 100644
--- a/ro-ro/bash-ro.html.markdown
+++ b/ro-ro/bash-ro.html.markdown
@@ -12,7 +12,7 @@ lang: ro-ro
filename: LearnBash-ro.sh
---
-Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si Mac OS X.
+Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si macOS.
Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda.
[Citește mai multe:](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/rst.html.markdown b/rst.html.markdown
index 2423622e..56d54501 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -6,9 +6,9 @@ contributors:
filename: restructuredtext.rst
---
-RST is a file format formely created by Python community to write documentation (and so, is part of Docutils).
+RST, Restructured Text, is a file format created by the Python community to write documentation. It is part of [Docutils](https://docutils.sourceforge.io/rst.html).
-RST files are simple text files with lightweight syntax (comparing to HTML).
+RST is a markdown language like HTML but is much more lightweight and easier to read.
## Installation
@@ -39,19 +39,21 @@ A simple example of the file syntax:
Main titles are written using equals signs over and under
=========================================================
-Note that there must be as many equals signs as title characters.
+Note that each character, including spaces, needs an equals sign above and below.
-Title are underlined with equals signs too
-==========================================
+Titles also use equals signs but are only underneath
+====================================================
Subtitles with dashes
---------------------
You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``.
+Special characters can be escaped using a backslash, e.g. \\ or \*.
+
Lists are similar to Markdown, but a little more involved.
-Remember to line up list symbols (like - or *) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
+Remember to line up list symbols (like - or \*) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
- First item
- Second item
@@ -82,11 +84,11 @@ More complex tables can be done easily (merged columns and/or rows) but I sugges
There are multiple ways to make links:
-- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage to not insert unnecessary URLs inside readable text).
+- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text).
- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)
- By making a more Markdown-like link: `Github <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _Github: https://github.com/
```
diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown
index ce918340..9978380a 100644
--- a/ru-ru/bash-ru.html.markdown
+++ b/ru-ru/bash-ru.html.markdown
@@ -26,7 +26,7 @@ lang: ru-ru
Bash — это командная оболочка unix, которая распространялась как оболочка
для операционной системы GNU и используется в качестве оболочки по умолчанию
-для Linux и Mac OS X.
+для Linux и macOS.
Почти все нижеприведённые примеры могут быть частью shell-скриптов
или исполнены напрямую в shell.
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index ba3c19ee..cc68d620 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -353,7 +353,7 @@ int main() {
// Это не работает, если строка является массивом
// (потенциально задаваемой с помощью строкового литерала)
- // который находиться в перезаписываемой части памяти:
+ // который находится в перезаписываемой части памяти:
char foo[] = "foo";
foo[0] = 'a'; // это выполнится и строка теперь "aoo"
diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown
index 05316578..2fc4ad7c 100644
--- a/ru-ru/forth-ru.html.markdown
+++ b/ru-ru/forth-ru.html.markdown
@@ -12,9 +12,10 @@ lang: ru-ru
Внимание: эта материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах.
+
```
\ Это комментарий
-( Это тоже комментарий, но использыется для предоределённых слов )
+( Это тоже комментарий, но используется для предоределённых слов )
\ --------------------------------- Прекурсор --------------------------------
diff --git a/ru-ru/nim-ru.html.markdown b/ru-ru/nim-ru.html.markdown
index d05583d7..0e08f1bf 100644
--- a/ru-ru/nim-ru.html.markdown
+++ b/ru-ru/nim-ru.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Dennis Felsing", "http://felsin9.de/nnis/"]
translators:
- ["Nomadic", "https://github.com/n0madic"]
+ - ["dvska", "https://github.com/dvska"]
lang: ru-ru
---
@@ -16,25 +17,25 @@ Nim (ранее известный, как Nimrod) — язык программ
Nim эффективный, выразительный и элегантный.
```nim
-var # Объявление (и присваивание) переменных,
- letter: char = 'n' # с указанием типа или без
- lang = "N" & "im"
- nLength : int = len(lang)
+var # Объявление (и присваивание) переменных,
+ буква: char = 'n' # с указанием типа или без
+ язык = "N" & "im"
+ nLength : int = len(язык)
boat: float
- truth: bool = false
+ правда: bool = false
-let # Используйте let *сразу* для объявления и связывания переменных.
- legs = 400 # legs неизменяемый.
- arms = 2_000 # Символ _ игнорируется и удобен для длинных чисел.
- aboutPi = 3.15
+let # Используйте let *сразу* для объявления и связывания переменных.
+ ноги = 400 # ноги неизменяемый.
+ руки = 2_000 # Символ _ игнорируется и удобен для длинных чисел.
+ почтиПи = 3.15
const # Константы вычисляются во время компиляции. Это обеспечивает
debug = true # производительность и полезно в выражениях этапа компиляции.
- compileBadCode = false
+ компилироватьПлохойКод = false
-when compileBadCode: # `when` это `if` этапа компиляции.
- legs = legs + 1 # Эта ошибка никогда не будет скомпилирована.
- const input = readline(stdin) # Значения констант должны быть известны во
+when компилироватьПлохойКод: # `when` это `if` этапа компиляции.
+ ноги = ноги + 1 # Эта ошибка никогда не будет скомпилирована.
+ const ввод = readline(stdin) # Значения констант должны быть известны во
# время компиляции.
discard 1 > 2 # Примечание. Компилятор будет жаловаться, если результат
@@ -52,27 +53,27 @@ discard """
# Кортежи
var
- child: tuple[name: string, age: int] # Кортежи определяют *как* имя поля
- today: tuple[sun: string, temp: float] # так *и* порядок полей.
+ дитя: tuple[имя: string, возраст: int] # Кортежи определяют *как* имя поля
+ сегодня: tuple[солнце: string, температура: float] # так *и* порядок полей.
-child = (name: "Rudiger", age: 2) # Присвоить все сразу литералом ()
-today.sun = "Overcast" # или отдельно по полям.
-today.temp = 70.1
+дитя = (имя: "Rudiger", возраст: 2) # Присвоить все сразу литералом ()
+сегодня.солнце = "Пасмурно" # или отдельно по полям.
+сегодня.температура = 20.1
# Последовательности
var
- drinks: seq[string]
+ напитки: seq[string]
-drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] является литералом
- # последовательности
+напитки = @["Вода", "Сок", "Какао"] # @[V1,..,Vn] является литералом
+ # последовательности
-drinks.add("Milk")
+напитки.add("Молоко")
-if "Milk" in drinks:
- echo "We have Milk and ", drinks.len - 1, " other drinks"
+if "Молоко" in напитки:
+ echo "У нас тут Молоко и ещё", напитки.len - 1, " напиток(ов)"
-let myDrink = drinks[2]
+let мойНапиток = напитки[2]
#
# Определение типов
@@ -82,30 +83,30 @@ let myDrink = drinks[2]
# Это то, что делает статическую типизацию мощной и полезной.
type
- Name = string # Псевдоним типа дает вам новый тип, который равнозначен
- Age = int # старому типу, но более нагляден.
- Person = tuple[name: Name, age: Age] # Определение структур данных.
- AnotherSyntax = tuple
+ Имя = string # Псевдоним типа дает вам новый тип, который равнозначен
+ Возраст = int # старому типу, но более нагляден.
+ Человек = tuple[имя: Имя, возраст: Возраст] # Определение структур данных.
+ АльтернативныйСинтаксис = tuple
fieldOne: string
secondField: int
var
- john: Person = (name: "John B.", age: 17)
- newage: int = 18 # Было бы лучше использовать Age, чем int
+ джон: Человек = (имя: "John B.", возраст: 17)
+ новыйВозраст: int = 18 # Было бы лучше использовать Возраст, чем int
-john.age = newage # Но это все же работает, потому что int и Age синонимы.
+джон.возраст = новыйВозраст # Но это все же работает, потому что int и Возраст синонимы.
type
- Cash = distinct int # `distinct` делает новый тип несовместимым с его
- Desc = distinct string # базовым типом.
+ Нал = distinct int # `distinct` делает новый тип несовместимым с его
+ Описание = distinct string # базовым типом.
var
- money: Cash = 100.Cash # `.Cash` преобразует int в наш тип
- description: Desc = "Interesting".Desc
+ money: Нал = 100.Нал # `.Нал` преобразует int в наш тип
+ описание: Описание = "Interesting".Описание
-when compileBadCode:
- john.age = money # Error! age is of type int and money is Cash
- john.name = description # Компилятор говорит: "Нельзя!"
+when компилироватьПлохойКод:
+ джон.возраст = money # Error! возраст is of type int and money is Нал
+ джон.имя = описание # Компилятор говорит: "Нельзя!"
#
# Дополнительные типы и структуры данных
@@ -114,50 +115,50 @@ when compileBadCode:
# Перечисления позволяют типу иметь одно из ограниченного числа значений
type
- Color = enum cRed, cBlue, cGreen
- Direction = enum # Альтернативный формат
- dNorth
- dWest
- dEast
- dSouth
+ Цвет = enum цКрасный, цГолубой, цЗеленый
+ Направление = enum # Альтернативный формат
+ нСевер
+ нЗапад
+ нВосток
+ нЮг
var
- orient = dNorth # `orient` имеет тип Direction, со значением `dNorth`
- pixel = cGreen # `pixel` имеет тип Color, со значением `cGreen`
+ напр = нСевер # `напр` имеет тип Направление, со значением `нСевер`
+ точка = цЗеленый # `точка` имеет тип Цвет, со значением `цЗеленый`
-discard dNorth > dEast # Перечисления обычно являются "порядковыми" типами
+discard нСевер > нВосток # Перечисления обычно являются "порядковыми" типами
# Поддиапазоны определяют ограниченный допустимый диапазон
type
- DieFaces = range[1..20] # Допустимым значением являются только int от 1 до 20
+ Кости = range[1..20] # 🎲 Допустимым значением являются только int от 1 до 20
var
- my_roll: DieFaces = 13
+ мой_бросок: Кости = 13
-when compileBadCode:
- my_roll = 23 # Error!
+when компилироватьПлохойКод:
+ мой_бросок = 23 # Error!
-# Arrays
+# Массивы
type
- RollCounter = array[DieFaces, int] # Массивы фиксированной длины и
- DirNames = array[Direction, string] # индексируются любым порядковым типом.
- Truths = array[42..44, bool]
+ СчетчикБросков = array[Кости, int] # Массивы фиксированной длины и
+ ИменаНаправлений = array[Направление, string] # индексируются любым порядковым типом.
+ Истины = array[42..44, bool]
var
- counter: RollCounter
- directions: DirNames
- possible: Truths
+ счетчик: СчетчикБросков
+ направления: ИменаНаправлений
+ возможны: Истины
-possible = [false, false, false] # Массивы создаются литералом [V1,..,Vn]
-possible[42] = true
+возможны = [false, false, false] # Массивы создаются литералом [V1,..,Vn]
+возможны[42] = true
-directions[dNorth] = "Ahh. The Great White North!"
-directions[dWest] = "No, don't go there."
+направления[нСевер] = "ОО. Великий белый Север!"
+направления[нЗапад] = "Нет, не иди туда."
-my_roll = 13
-counter[my_roll] += 1
-counter[my_roll] += 1
+мой_бросок = 13
+счетчик[мой_бросок] += 1
+счетчик[мой_бросок] += 1
-var anotherArray = ["Default index", "starts at", "0"]
+var ещеМассив = ["Идекс по умолчанию", "начинается с", "0"]
# Доступны другие структуры данных, в том числе таблицы, множества,
# списки, очереди и crit-bit деревья.
@@ -169,89 +170,94 @@ var anotherArray = ["Default index", "starts at", "0"]
# `case`, `readLine()`
-echo "Read any good books lately?"
+echo "Читали какие-нибудь хорошие книги в последнее время?"
+
case readLine(stdin)
-of "no", "No":
- echo "Go to your local library."
-of "yes", "Yes":
- echo "Carry on, then."
+of "нет", "Нет":
+ echo "Пойдите в свою местную библиотеку."
+of "да", "Да":
+ echo "Тогда продолжим"
else:
- echo "That's great; I assume."
+ echo "Здорово!"
# `while`, `if`, `continue`, `break`
-import strutils as str # http://nim-lang.org/docs/strutils.html (EN)
-echo "I'm thinking of a number between 41 and 43. Guess which!"
-let number: int = 42
+import strutils as str # http://nim-lang.org/docs/strutils.html (EN)
+echo "Я загадало число между 41 и 43. Отгадай!"
+let число: int = 42
var
- raw_guess: string
- guess: int
-while guess != number:
- raw_guess = readLine(stdin)
- if raw_guess == "": continue # Пропустить эту итерацию
- guess = str.parseInt(raw_guess)
- if guess == 1001:
+ ввод_догадка: string
+ догадка: int
+
+while догадка != число:
+ ввод_догадка = readLine(stdin)
+
+ if ввод_догадка == "": continue # Пропустить эту итерацию
+
+ догадка = str.parseInt(ввод_догадка)
+
+ if догадка == 1001:
echo("AAAAAAGGG!")
break
- elif guess > number:
- echo("Nope. Too high.")
- elif guess < number:
- echo(guess, " is too low")
+ elif догадка > число:
+ echo("Неа. Слишком большое.")
+ elif догадка < число:
+ echo(догадка, " это слишком мало")
else:
- echo("Yeeeeeehaw!")
+ echo("Точнооооо!")
#
# Итерации (циклы)
#
-for i, elem in ["Yes", "No", "Maybe so"]: # Или просто `for elem in`
- echo(elem, " is at index: ", i)
+for i, элем in ["Да", "Нет", "Может быть"]: # Или просто `for элем in`
+ echo(элем, " по индексу: ", i)
-for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]):
- echo v
+for ключ, значение in items(@[(человек: "You", сила: 100), (человек: "Me", сила: 9000)]):
+ echo значение
-let myString = """
-an <example>
-`string` to
-play with
+let мояСтрока = """
+<пример>
+`строки` для
+тренировки
""" # Многострочная "сырая" строка
-for line in splitLines(myString):
- echo(line)
+for строка in splitLines(мояСтрока):
+ echo(строка)
-for i, c in myString: # Индекс и символ. Или `for j in` только для символов
- if i mod 2 == 0: continue # Компактная форма `if`
- elif c == 'X': break
- else: echo(c)
+for i, симв in мояСтрока: # Индекс и символ. Или `for j in` только для символов
+ if i mod 2 == 0: continue # Компактная форма `if`
+ elif симв == 'X': break
+ else: echo(симв)
#
# Процедуры
#
-type Answer = enum aYes, aNo
+type Ответ = enum оДа, оНет
-proc ask(question: string): Answer =
- echo(question, " (y/n)")
+proc спрос(вопрос: string): Ответ =
+ echo(вопрос, " (д/н)")
while true:
case readLine(stdin)
- of "y", "Y", "yes", "Yes":
- return Answer.aYes # Перечисления могут быть квалифицированы
- of "n", "N", "no", "No":
- return Answer.aNo
- else: echo("Please be clear: yes or no")
-
-proc addSugar(amount: int = 2) = # Значение поумолчанию 2, ничего не возвращает
- assert(amount > 0 and amount < 9000, "Crazy Sugar")
- for a in 1..amount:
- echo(a, " sugar...")
-
-case ask("Would you like sugar in your tea?")
-of aYes:
- addSugar(3)
-of aNo:
- echo "Oh do take a little!"
- addSugar()
-# Здесь нет необходимости в `else`. Возможны только `yes` и `no`.
+ of "д", "Д", "да", "Да":
+ return Ответ.оДа # Перечисления могут быть квалифицированы
+ of "н", "Н", "нет", "Нет":
+ return Ответ.оНет
+ else: echo("Поточнее, да или нет")
+
+proc добавьСахар(количество: int = 2) = # Значение по умолчанию 2, ничего не возвращает
+ assert(количество > 0 and количество < 9000, "Диабет ☠")
+ for a in 1..количество:
+ echo(a, " кубик...")
+
+case спрос("Сахарку?")
+of оДа:
+ добавьСахар(3)
+of оНет:
+ echo "Ну немнооожко!"
+ добавьСахар()
+# Здесь нет необходимости в `else`. Возможны только `да` и `нет`.
#
# FFI (интерфейс внешних функций)
@@ -261,7 +267,7 @@ of aNo:
proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
-let cmp = strcmp("C?", "Easy!")
+let cmp = strcmp("C?", "Легко!")
```
Кроме того, Nim выделяется среди себе подобных метапрограммированием,
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 3baa15f8..092c3e2f 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -12,7 +12,7 @@ lang: ru-ru
---
Objective-C — основной язык программирования, используемый корпорацией Apple
-для операционных систем OS X и iOS и их соответствующих фреймворках Cocoa и
+для операционных систем macOS и iOS и их соответствующих фреймворках Cocoa и
Cocoa Touch.
Он является объектно-ориентированным языком программирования общего назначения,
который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C.
diff --git a/ru-ru/pascal-ru.html.markdown b/ru-ru/pascal-ru.html.markdown
new file mode 100644
index 00000000..5ea856bc
--- /dev/null
+++ b/ru-ru/pascal-ru.html.markdown
@@ -0,0 +1,217 @@
+---
+language: Pascal
+filename: learnpascal-ru.pas
+contributors:
+ - ["Ganesha Danu", "http://github.com/blinfoldking"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["Anton 'Dart' Nikolaev", "https://github.com/dartfnm"]
+lang: ru-ru
+---
+
+
+>Pascal - это процедурный язык программирования, который Никлаус Вирт разработал в 1968–69 годах и опубликовал в 1970 году как небольшой эффективный язык, предназначенный для поощрения хороших методов программирования с использованием структурированного программирования и структурирования данных. Он назван в честь французского математика, философа и физика Блеза Паскаля.
+>
+>source : [wikipedia](https://ru.wikipedia.org/wiki/Паскаль_(язык_программирования)))
+
+
+
+Для компиляции и запуска программы на языке Паскаль вы можете использовать бесплатный компилятор FreePascal. [Скачать здесь](https://www.freepascal.org/)
+
+Либо современный бесплатный компилятор Паскаля нового поколения под платформу .Net [PascalABC.NET](http://pascalabc.net)
+
+```pascal
+// это комментарий
+{
+ а вот это:
+ - комментарий на несколько строк
+}
+
+//объявляем имя программы
+program learn_pascal; //<-- не забываем ставить точку с запятой (;)
+
+const
+ {
+ это секция в которой вы должны объявлять константы
+ }
+type
+ {
+ здесь вы можете объявлять собственные типы данных
+ }
+var
+ {
+ секция для объявления переменных
+ }
+
+begin //начало основной программы
+ {
+ тело вашей программы
+ }
+end. // В конце основной программы обязательно должна стоять точка "."
+```
+
+```pascal
+//объявление переменных
+//вы можете сделать так
+var a:integer;
+var b:integer;
+//или так
+var
+ a : integer;
+ b : integer;
+//или даже так
+var a,b : integer;
+```
+
+```pascal
+program Learn_More;
+
+// Познакомимся с типами данных и с их операциями
+const
+ PI = 3.141592654;
+ GNU = 'GNU''s Not Unix';
+ // имена константам принято давать ЗАГЛАВНЫМИ_БУКВАМИ (в верхнем регистре)
+ // их значения фиксированны т.е никогда не меняются во время выполнения программы
+ // содержат любой стандартный тип данных (integer, real, boolean, char, string)
+
+type
+ ch_array : array [0..255] of char;
+ // массивы - это составной тип данных
+ // мы указываем индекс первого и последнего элемента массива ([0..255])
+ // здесь мы объявили новый тип данных содержащий 255 символов 'char'
+ // (по сути, это просто строка - string[256])
+
+ md_array : array of array of integer;
+ // массив в массиве - по сути является двумерным массивом
+ // можно задать массив нулевой (0) длины, а потом динамически расширить его
+ // это двумерный массив целых чисел
+
+//Объявление переменных
+var
+ int, c, d : integer;
+ // три переменные, которые содержат целые числа
+ // Тип "integer" это 16-битное число в диапазоне [-32,768..32,767]
+ r : real;
+ // переменная типа "real" принимает вещественные (дробные) значения
+ // в диапазоне [3.4E-38..3.4E38]
+ bool : boolean;
+ // переменная логического типа, принимающая булевы-значения: True/False (Правда/Ложь)
+ ch : char;
+ // эта переменная содержит значение кода одного символа
+ // тип 'char' это 8-битное число (1 байт), так что никакого Юникода
+ str : string;
+ // это переменная составного типа, являющееся строкой
+ // по сути, строка это массив в 255 символов длиною, по умолчанию
+
+ s : string[50];
+ // эта строка может содержать максимум 50 символов
+ // вы можете сами указать длину строки, чтобы минимизировать использование памяти
+ my_str: ch_array;
+ // вы можете объявлять переменные собственных типов
+ my_2d : md_array;
+ // динамически расширяемые массивы требуют указания длины перед их использованием.
+
+ // дополнительные целочисленные типы данных
+ b : byte; // диапазон [0..255]
+ shi : shortint; // диапазон [-128..127]
+ smi : smallint; // диапазон [-32,768..32,767] (стандартный Integer)
+ w : word; // диапазон [0..65,535]
+ li : longint; // диапазон [-2,147,483,648..2,147,483,647]
+ lw : longword; // диапазон [0..4,294,967,295]
+ c : cardinal; // тоже что и longword
+ i64 : int64; // диапазон [-9223372036854775808..9223372036854775807]
+ qw : qword; // диапазон [0..18,446,744,073,709,551,615]
+
+ // дополнительные вещественные типы данных (дробные)
+ rr : real; // диапазон зависит от платформы (т.е. 8-бит, 16-бит и т.д.)
+ rs : single; // диапазон [1.5E-45..3.4E38]
+ rd : double; // диапазон [5.0E-324 .. 1.7E308]
+ re : extended; // диапазон [1.9E-4932..1.1E4932]
+ rc : comp; // диапазон [-2E64+1 .. 2E63-1]
+
+Begin
+ int := 1; // так мы присваиваем значение переменной
+ r := 3.14;
+ ch := 'a';
+ str := 'apple';
+ bool := true;
+ // Паскаль не чувствителен к регистру
+
+ // арифметические операции
+ int := 1 + 1; // int = 2; заменяет предыдущее значение
+ int := int + 1; // int = 2 + 1 = 3;
+ int := 4 div 2; //int = 2; 'div' операция деления, с отбрасыванием дробной части
+ int := 3 div 2; //int = 1;
+ int := 1 div 2; //int = 0;
+
+ bool := true or false; // bool = true
+ bool := false and true; // bool = false
+ bool := true xor true; // bool = false
+
+ r := 3 / 2; // деления вещественных чисел с дробной частью
+ r := int; // вещественной переменной можно присвоить целочисленное значение, но не наоборот
+
+ my_str[0] := 'a'; // для доступа к элементу массива нужно указать его индекс в квадратных скобках ([0])
+
+ c := str[1]; // первая буква во всех Строках находится по индексу [1]
+ str := 'hello' + 'world'; //объединяем 2 строки в одну
+
+ SetLength(my_2d,10,10); // инициализируем динамически расширяемый массив
+ // задаём размер 2х-мерного массива 10×10
+
+ // первый элемент массива лежит в индексе [0], последний [длина_массива-1]
+ for c := 0 to 9 do
+ for d := 0 to 9 do // переменные для счетчиков циклов должны быть объявлены
+ my_2d[c,d] := c * d;
+ // обращаться к многомерным массивам нужно с помощью одного набора скобок
+
+End.
+```
+
+```pascal
+program Functional_Programming;
+
+Var
+ i, dummy : integer;
+
+function factorial_recursion(const a: integer) : integer;
+{ Функция расчёта Факториала целочисленного параметра 'a', рекурсивно. Возвращает целое значение }
+
+// Мы можем объявлять локальные переменные внутри своей функции:
+// Var
+// local_a : integer;
+
+Begin
+ If a >= 1 Then
+ factorial_recursion := a * factorial_recursion(a-1)
+ // возвращаем результат, присваивая найденное значение переменной с тем же именем, как у функции
+ Else
+ factorial_recursion := 1;
+End; // Для завершения функции, используется символ ";" после оператора "End;"
+
+
+
+procedure get_integer( var i : integer; dummy : integer );
+{ Эта процедура ждёт от пользователя ввода целого числа и возвращает его значение через параметр i.
+ Если параметр функции начинается с 'var', это означает, что его значение было передано, по ссылке, то есть, оно может использоваться не только как входное значение, но и для возвращения дополнительных результатов работы функции.
+ Параметры функции (без 'var'), (такие как "dummy" (пустышка)), передаются по значению, и по сути являются - локальными переменными, таким образом изменения, внесенные внутри функции/процедуры, не влияют на значение переменной за её пределами.
+}
+Begin // начало процедуры
+ write('Введите целое число: ');
+ readln(i); // число, введённое пользователем, сохранится в переменной i
+ // и её значение будет доступно вызывающей подпрограмме
+
+ dummy := 4; // значение 'dummy' не будет влиять на значения переменной вне процедуры
+End; // конец процедуры
+
+Begin // главный блок программы
+ dummy := 3;
+ get_integer(i, dummy); // вызываем процедуру получения числа от пользователя
+ writeln(i, '! = ', factorial_recursion(i)); // ввыводим значение факториала от i
+
+ writeln('dummy = ', dummy);
+ // всегда выводит "3", поскольку фиктивная переменная не изменяется.
+End. // конец программы
+
+```
+
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
index a907ba41..a9bb683b 100644
--- a/ru-ru/perl-ru.html.markdown
+++ b/ru-ru/perl-ru.html.markdown
@@ -9,12 +9,12 @@ translators:
lang: ru-ru
---
-Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
-Особенно хорош для обработки разнообразных текстовых данных.
+Perl -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
-Perl 5 работает более чем на 100 платформах, от портативных устройств
-до мейнфреймов, и подходит как для быстрого прототипирования,
-так и для крупных проектов.
+Perl работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
```perl
# Комментарии начинаются с символа решетки.
@@ -23,8 +23,8 @@ Perl 5 работает более чем на 100 платформах, от п
#### Типы переменных в Perl
# Скалярные переменные начинаются с знака доллара $.
-# Имя переменной состоит из букв, цифр и знаков подчеркивания,
-# начиная с буквы или подчеркивания.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
### В Perl три основных типа переменных: скаляры, массивы, хеши.
@@ -55,7 +55,7 @@ my %fruit_color = (
banana => "yellow",
);
-# Важно: вставка и поиск в хеше выполняются за константное время,
+# Важно: вставка и поиск в хеше выполняются за константное время,
# независимо от его размера.
# Скаляры, массивы и хеши подробно описаны в разделе perldata
@@ -81,7 +81,7 @@ unless ( condition ) {
}
# Это более читаемый вариант для "if (!condition)"
-# Специфические Perl-овые пост-условия:
+# Специфические Perl-овые пост-условия:
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
@@ -129,7 +129,7 @@ open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Читать из файлового дескриптора можно с помощью оператора "<>".
-# В скалярном контексте он читает одну строку из файла, в списковом --
+# В скалярном контексте он читает одну строку из файла, в списковом --
# читает сразу весь файл, сохраняя по одной строке в элементе массива:
my $line = <$in>;
@@ -152,13 +152,13 @@ logger("We have a logger subroutine!");
#### Perl-модули
-Perl-овые модули предоставляют широкий набор функциональности,
-так что вы можете не изобретать заново велосипеды, а просто скачать
-нужный модуль с CPAN (http://www.cpan.org/).
-Некоторое количество самых полезных модулей включено в стандартную
+Perl-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
поставку Perl.
-Раздел документации perlfaq содержит вопросы и ответы о многих частых
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
задачах, и часто предлагает подходящие CPAN-модули.
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index b2c00baf..e0e53b9c 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Steven Basart", "http://github.com/xksteven"]
translators:
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Anton Grouchtchak", "https://github.com/Teraskull"]
filename: learnpython-ru.py
---
@@ -20,8 +21,10 @@ filename: learnpython-ru.py
Если вы хотите изучить Python 2.7, обратитесь к другой статье.
```python
+
# Однострочные комментарии начинаются с символа решётки.
-""" Многострочный текст может быть
+
+""" Многострочный текст может быть
записан, используя 3 знака " и обычно используется
в качестве встроенной документации
"""
@@ -31,315 +34,397 @@ filename: learnpython-ru.py
####################################################
# У вас есть числа
-3 #=> 3
+3 # => 3
# Математика работает вполне ожидаемо
-1 + 1 #=> 2
-8 - 1 #=> 7
-10 * 2 #=> 20
-
-# Кроме деления, которое по умолчанию возвращает число с плавающей запятой
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
35 / 5 # => 7.0
# Результат целочисленного деления округляется в меньшую сторону
# как для положительных, так и для отрицательных чисел.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
--5 // 3 # => -2
+5 // 3 # => 1
+-5 // 3 # => -2
+5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
-5.0 // 3.0 # => -2.0
-# Когда вы используете числа с плавающей запятой,
-# результатом будет также число с плавающей запятой
-3 * 2.0 # => 6.0
+# # Результат деления возвращает число с плавающей запятой
+10.0 / 3 # => 3.3333333333333335
# Остаток от деления
-7 % 3 # => 1
+7 % 3 # => 1
# Возведение в степень
-2**4 # => 16
+2**3 # => 8
# Приоритет операций указывается скобками
-(1 + 3) * 2 #=> 8
+1 + 3 * 2 # => 7
+(1 + 3) * 2 # => 8
-# Для логических (булевых) значений существует отдельный примитивный тип
-True
-False
+# Булевы значения - примитивы (Обратите внимание на заглавную букву)
+True # => True
+False # => False
# Для отрицания используется ключевое слово not
-not True #=> False
-not False #=> True
-
-# Логические операторы
-# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв
-True and False #=> False
-False or True #=> True
-
-# Обратите внимание, что логические операторы используются и с целыми числами
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+not True # => False
+not False # => True
+
+# Булевы операторы
+# Обратите внимание: ключевые слова "and" и "or" чувствительны к регистру букв
+True and False # => False
+False or True # => True
+
+# True и False на самом деле 1 и 0, но с разными ключевыми словами
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
+
+# Операторы сравнения обращают внимание на числовое значение True и False
+0 == False # => True
+1 == True # => True
+2 == True # => False
+-5 != False # => True
+
+# Использование булевых логических операторов на типах int превращает их в булевы значения, но возвращаются оригинальные значения
+# Не путайте с bool(ints) и bitwise and/or (&,|)
+bool(0) # => False
+bool(4) # => True
+bool(-6) # => True
+0 and 2 # => 0
+-5 or 0 # => -5
# Равенство — это ==
-1 == 1 #=> True
-2 == 1 #=> False
+1 == 1 # => True
+2 == 1 # => False
# Неравенство — это !=
-1 != 1 #=> False
-2 != 1 #=> True
+1 != 1 # => False
+2 != 1 # => True
# Ещё немного сравнений
-1 < 10 #=> True
-1 > 10 #=> False
-2 <= 2 #=> True
-2 >= 2 #=> True
-
-# Сравнения могут быть записаны цепочкой:
-1 < 2 < 3 #=> True
-2 < 3 < 2 #=> False
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Проверка, находится ли значение в диапазоне
+1 < 2 and 2 < 3 # => True
+2 < 3 and 3 < 2 # => False
+
+# Сравнения могут быть записаны цепочкой
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==) ключевое слово is проверяет, относятся ли две переменные к одному и тому же объекту, но == проверяет если указанные объекты имеют одинаковые значения.
+a = [1, 2, 3, 4] # a указывает на новый список, [1, 2, 3, 4]
+b = a # b указывает на то, что указывает a
+b is a # => True, a и b относятся к одному и тому же объекту
+b == a # => True, Объекты a и b равны
+b = [1, 2, 3, 4] # b указывает на новый список, [1, 2, 3, 4]
+b is a # => False, a и b не относятся к одному и тому же объекту
+b == a # => True, Объекты a и b равны
# Строки определяются символом " или '
"Это строка."
'Это тоже строка.'
# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
-"Привет " + "мир!" #=> "Привет мир!"
+"Привет " + "мир!" # => "Привет мир!"
-# Строки можно умножать.
-"aa" * 4 #=> "aaaaaaaa"
+# Строки (но не переменные) могут быть объединены без использования '+'
+"Привет " "мир!" # => "Привет мир!"
# Со строкой можно работать, как со списком символов
-"Это строка"[0] #=> 'Э'
+"Привет мир!"[0] # => 'П'
-# Метод format используется для форматирования строк:
-"{0} могут быть {1}".format("строки", "форматированы")
+# Вы можете найти длину строки
+len("Это строка") # => 10
-# Вы можете повторять аргументы форматирования, чтобы меньше печатать.
-"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак")
-#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!"
-# Если вы не хотите считать, можете использовать ключевые слова.
-"{name} хочет есть {food}".format(name="Боб", food="лазанью")
+# Вы также можете форматировать, используя f-строки (в Python 3.6+)
+name = "Рейко"
+f"Она сказала, что ее зовут {name}." # => "Она сказала, что ее зовут Рейко"
+# Вы можете поместить любой оператор Python в фигурные скобки, и он будет выведен в строке.
+f"{name} состоит из {len(name)} символов." # => "Рэйко состоит из 5 символов."
-# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже,
-# вы также можете использовать старый способ форматирования:
-"%s можно %s %s способом" % ("строки", "интерполировать", "старым")
# None является объектом
-None #=> None
+None # => None
-# Не используйте оператор равенства '==' для сравнения
-# объектов с None. Используйте для этого 'is'
-"etc" is None #=> False
-None is None #=> True
+# Не используйте оператор равенства "==" для сравнения
+# объектов с None. Используйте для этого "is"
+"etc" is None # => False
+None is None # => True
-# Оператор «is» проверяет идентичность объектов. Он не
-# очень полезен при работе с примитивными типами, но
-# зато просто незаменим при работе с объектами.
-
-# None, 0 и пустые строки/списки/словари приводятся к False.
+# None, 0 и пустые строки/списки/словари/кортежи приводятся к False.
# Все остальные значения равны True
-bool(0) # => False
+bool(0) # => False
bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
####################################################
-## 2. Переменные и коллекции
+## 2. Переменные и Коллекции
####################################################
# В Python есть функция Print
-print("Я Python. Приятно познакомиться!")
+print("Я Python. Приятно познакомиться!") # => Я Python. Приятно познакомиться!
+
+# По умолчанию функция, print() также выводит новую строку в конце.
+# Используйте необязательный аргумент end, чтобы изменить последнюю строку.
+print("Привет мир", end="!") # => Привет мир!
+
+# Простой способ получить входные данные из консоли
+input_string_var = input("Введите данные: ") # Возвращает данные в виде строки
+# Примечание: в более ранних версиях Python метод input() назывался raw_input()
# Объявлять переменные перед инициализацией не нужно.
# По соглашению используется нижний_регистр_с_подчёркиваниями
some_var = 5
-some_var #=> 5
+some_var # => 5
+
+# При попытке доступа к неинициализированной переменной выбрасывается исключение.
+# Об исключениях см. раздел "Поток управления и итерируемые объекты".
+some_unknown_var # Выбрасывает ошибку NameError
-# При попытке доступа к неинициализированной переменной
-# выбрасывается исключение.
-# Об исключениях см. раздел «Поток управления и итерируемые объекты».
-some_unknown_var # Выбрасывает ошибку именования
+# if можно использовать как выражение
+# Эквивалент тернарного оператора '?:' в C
+"да!" if 0 > 1 else "нет!" # => "нет!"
# Списки хранят последовательности
li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
-# Объекты добавляются в конец списка методом append
-li.append(1) # [1]
-li.append(2) # [1, 2]
-li.append(4) # [1, 2, 4]
-li.append(3) # [1, 2, 4, 3]
-# И удаляются с конца методом pop
-li.pop() #=> возвращает 3 и li становится равен [1, 2, 4]
+# Объекты добавляются в конец списка методом append()
+li.append(1) # [1]
+li.append(2) # [1, 2]
+li.append(4) # [1, 2, 4]
+li.append(3) # [1, 2, 4, 3]
+# И удаляются с конца методом pop()
+li.pop() # => возвращает 3 и li становится равен [1, 2, 4]
# Положим элемент обратно
-li.append(3) # [1, 2, 4, 3].
+li.append(3) # [1, 2, 4, 3].
# Обращайтесь со списком, как с обычным массивом
-li[0] #=> 1
+li[0] # => 1
+
# Обратимся к последнему элементу
-li[-1] #=> 3
+li[-1] # => 3
# Попытка выйти за границы массива приведёт к ошибке индекса
-li[4] # Выдаёт IndexError
+li[4] # Выбрасывает ошибку IndexError
# Можно обращаться к диапазону, используя так называемые срезы
# (Для тех, кто любит математику, это называется замкнуто-открытый интервал).
-li[1:3] #=> [2, 4]
-# Опускаем начало
-li[2:] #=> [4, 3]
-# Опускаем конец
-li[:3] #=> [1, 2, 4]
-# Выбираем каждый второй элемент
-li[::2] # =>[1, 4]
-# Переворачиваем список
-li[::-1] # => [3, 4, 2, 1]
+li[1:3] # Вернуть список из индекса с 1 по 3 => [2, 4]
+li[2:] # Вернуть список, начиная с индекса 2 => [4, 3]
+li[:3] # Вернуть список с начала до индекса 3 => [1, 2, 4]
+li[::2] # Вернуть список, выбирая каждую вторую запись => [1, 4]
+li[::-1] # Вернуть список в обратном порядке => [3, 4, 2, 1]
# Используйте сочетания всего вышеназванного для выделения более сложных срезов
# li[начало:конец:шаг]
+# Сделать однослойную глубокую копию, используя срезы
+li2 = li[:] # => li2 = [1, 2, 4, 3], но (li2 is li) вернет False.
+
# Удаляем произвольные элементы из списка оператором del
-del li[2] # [1, 2, 3]
+del li[2] # [1, 2, 3]
+
+# Удалить первое вхождение значения
+li.remove(2) # [1, 3]
+li.remove(2) # Выбрасывает ошибку ValueError поскольку 2 нет в списке
+
+# Вставить элемент по определенному индексу
+li.insert(1, 2) # [1, 2, 3]
+
+# Получить индекс первого найденного элемента, соответствующего аргументу
+li.index(2) # => 1
+li.index(4) # Выбрасывает ошибку ValueError поскольку 4 нет в списке
# Вы можете складывать, или, как ещё говорят, конкатенировать списки
# Обратите внимание: значения li и other_li при этом не изменились.
-li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
+li + other_li # => [1, 2, 3, 4, 5, 6]
-# Объединять списки можно методом extend
+# Объединять списки можно методом extend()
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
-# Проверить элемент на вхождение в список можно оператором in
-1 in li #=> True
+# Проверить элемент на наличие в списке можно оператором in
+1 in li # => True
# Длина списка вычисляется функцией len
-len(li) #=> 6
+len(li) # => 6
-# Кортежи — это такие списки, только неизменяемые
+# Кортежи похожи на списки, только неизменяемые
tup = (1, 2, 3)
-tup[0] #=> 1
-tup[0] = 3 # Выдаёт TypeError
+tup[0] # => 1
+tup[0] = 3 # Выбрасывает ошибку TypeError
+
+# Обратите внимание, что кортеж длины 1 должен иметь запятую после последнего элемента, но кортежи другой длины, даже 0, не должны.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
# Всё то же самое можно делать и с кортежами
-len(tup) #=> 3
-tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
-tup[:2] #=> (1, 2)
-2 in tup #=> True
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
# Вы можете распаковывать кортежи (или списки) в переменные
-a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3
+a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3
+# Вы также можете сделать расширенную распаковку
+a, *b, c = (1, 2, 3, 4) # a теперь 1, b теперь [2, 3] и c теперь 4
# Кортежи создаются по умолчанию, если опущены скобки
-d, e, f = 4, 5, 6
+d, e, f = 4, 5, 6 # кортеж 4, 5, 6 распаковывается в переменные d, e и f
+# соответственно, d = 4, e = 5 и f = 6
# Обратите внимание, как легко поменять местами значения двух переменных
-e, d = d, e # теперь d == 5, а e == 4
+e, d = d, e # теперь d == 5, а e == 4
-# Словари содержат ассоциативные массивы
+# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
filled_dict = {"one": 1, "two": 2, "three": 3}
-# Значения извлекаются так же, как из списка, с той лишь разницей,
-# что индекс — у словарей он называется ключом — не обязан быть числом
-filled_dict["one"] #=> 1
+# Обратите внимание, что ключи для словарей должны быть неизменяемыми типами. Это
+# сделано для того, чтобы ключ может быть преобразован в хеш для быстрого поиска.
+# Неизменяемые типы включают целые числа, числа с плавающей запятой, строки, кортежи.
+invalid_dict = {[1,2,3]: "123"} # => Выбрасывает ошибку TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Однако значения могут быть любого типа.
-# Все ключи в виде списка получаются с помощью метода keys().
+# Поиск значений с помощью []
+filled_dict["one"] # => 1
+
+# Все ключи в виде списка получаются с помощью метода keys().
# Его вызов нужно обернуть в list(), так как обратно мы получаем
-# итерируемый объект, о которых поговорим позднее.
-list(filled_dict.keys()) # => ["three", "two", "one"]
-# Замечание: сохранение порядка ключей в словаре не гарантируется
-# Ваши результаты могут не совпадать с этими.
+# итерируемый объект, о которых поговорим позднее. Примечание - для Python
+# версии <3.7, порядок словарных ключей не гарантируется. Ваши результаты могут
+# не точно соответствовать приведенному ниже примеру. Однако, начиная с Python 3.7
+# элементы в словаре сохраняют порядок, в котором они вставляются в словарь.
+list(filled_dict.keys()) # => ["three", "two", "one"] в Python <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] в Python 3.7+
+
# Все значения в виде списка можно получить с помощью values().
# И снова нам нужно обернуть вызов в list(), чтобы превратить
# итерируемый объект в список.
-list(filled_dict.values()) # => [3, 2, 1]
# То же самое замечание насчёт порядка ключей справедливо и здесь
+list(filled_dict.values()) # => [3, 2, 1] в Python <3.7
+list(filled_dict.values()) # => [1, 2, 3] в Python 3.7+
-# При помощи оператора in можно проверять ключи на вхождение в словарь
-"one" in filled_dict #=> True
-1 in filled_dict #=> False
+# При помощи ключевого слова in можно проверять наличие ключей в словаре
+"one" in filled_dict # => True
+1 in filled_dict # => False
-# Попытка получить значение по несуществующему ключу выбросит ошибку ключа
-filled_dict["four"] # KeyError
+# Попытка получить значение по несуществующему ключу выбросит ошибку KeyError
+filled_dict["four"] # Выбрасывает ошибку KeyError
# Чтобы избежать этого, используйте метод get()
-filled_dict.get("one") #=> 1
-filled_dict.get("four") #=> None
-# Метод get также принимает аргумент по умолчанию, значение которого будет
-# возвращено при отсутствии указанного ключа
-filled_dict.get("one", 4) #=> 1
-filled_dict.get("four", 4) #=> 4
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# Метод get поддерживает аргумент по умолчанию, когда значение отсутствует
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
-# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
-filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
-filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
+# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
+filled_dict.setdefault("five", 5) # filled_dict["five"] возвращает 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] по-прежнему возвращает 5
# Добавление элементов в словарь
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 # Другой способ добавления элементов
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # Другой способ добавления элементов
+
+# Удаляйте ключи из словаря с помощью ключевого слова del
+del filled_dict["one"] # Удаляет ключ "one" из словаря
+
+# После Python 3.5 вы также можете использовать дополнительные параметры распаковки
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
-# Удаляйте ключи из словаря с помощью оператора del
-del filled_dict["one"] # Удаляет ключ «one» из словаря
# Множества содержат... ну, в общем, множества
empty_set = set()
# Инициализация множества набором значений.
-# Да, оно выглядит примерно как словарь… ну извините, так уж вышло.
-filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+# Да, оно выглядит примерно как словарь. Ну извините, так уж вышло.
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Similar to keys of a dictionary, elements of a set have to be immutable.
+# Как и ключи словаря, элементы множества должны быть неизменяемыми.
+invalid_set = {[1], 1} # => Выбрасывает ошибку TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
# Множеству можно назначать новую переменную
filled_set = some_set
-
-# Добавление новых элементов в множество
-filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5}
+filled_set.add(5) # {1, 2, 3, 4, 5}
+# В множествах нет повторяющихся элементов
+filled_set.add(5) # {1, 2, 3, 4, 5}
# Пересечение множеств: &
other_set = {3, 4, 5, 6}
-filled_set & other_set #=> {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
# Объединение множеств: |
-filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Разность множеств: -
-{1,2,3,4} - {2,3,5} #=> {1, 4}
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Симметричная разница: ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Проверить, является ли множество слева надмножеством множества справа
+{1, 2} >= {1, 2, 3} # => False
-# Проверка на вхождение во множество: in
-2 in filled_set #=> True
-10 in filled_set #=> False
+# Проверить, является ли множество слева подмножеством множества справа
+{1, 2} <= {1, 2, 3} # => True
+
+# Проверка на наличие в множестве: in
+2 in filled_set # => True
+10 in filled_set # => False
+
+# Сделать однослойную глубокую копию
+filled_set = some_set.copy() # {1, 2, 3, 4, 5}
+filled_set is some_set # => False
####################################################
## 3. Поток управления и итерируемые объекты
####################################################
-# Для начала заведём переменную
+# Для начала создадим переменную
some_var = 5
# Так выглядит выражение if. Отступы в python очень важны!
-# результат: «some_var меньше, чем 10»
+# Конвенция заключается в использовании четырех пробелов, а не табуляции.
+# Pезультат: "some_var меньше, чем 10"
if some_var > 10:
- print("some_var намного больше, чем 10.")
-elif some_var < 10: # Выражение elif необязательно.
+ print("some_var точно больше, чем 10.")
+elif some_var < 10: # Выражение elif необязательно.
print("some_var меньше, чем 10.")
-else: # Это тоже необязательно.
+else: # Это тоже необязательно.
print("some_var равно 10.")
-# Циклы For проходят по спискам. Результат:
- # собака — это млекопитающее
- # кошка — это млекопитающее
- # мышь — это млекопитающее
+"""
+Циклы For проходят по спискам.
+Выводит:
+ собака — это млекопитающее
+ кошка — это млекопитающее
+ мышь — это млекопитающее
+"""
for animal in ["собака", "кошка", "мышь"]:
# Можете использовать format() для интерполяции форматированных строк
print("{} — это млекопитающее".format(animal))
-
+
"""
-«range(число)» возвращает список чисел
+"range(число)" возвращает список чисел
от нуля до заданного числа
-Результат:
+Выводит:
0
1
2
@@ -349,8 +434,42 @@ for i in range(4):
print(i)
"""
+"range(нижнее, верхнее)" возвращает список чисел
+от нижнего числа к верхнему
+Выводит:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(нижнее, верхнее, шаг)" возвращает список чисел
+от нижнего числа к верхнему, от нижнего числа к верхнему, увеличивая
+шаг за шагом. Если шаг не указан, значение по умолчанию - 1.
+Выводит:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+Чтобы перебрать список и получить индекс и значение каждого элемента в списке
+Выводит:
+ 0 собака
+ 1 кошка
+ 2 мышь
+"""
+animals = ["собака", "кошка", "мышь"]
+for i, value in enumerate(animals):
+ print(i, value)
+
+"""
Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
-Результат:
+Выводит:
0
1
2
@@ -366,45 +485,77 @@ try:
# Чтобы выбросить ошибку, используется raise
raise IndexError("Это ошибка индекса")
except IndexError as e:
- # pass — это просто отсутствие оператора. Обычно здесь происходит
- # восстановление после ошибки.
- pass
+ pass # pass — это просто отсутствие оператора. Обычно здесь происходит восстановление после ошибки.
except (TypeError, NameError):
- pass # Несколько исключений можно обработать вместе, если нужно.
-else: # Необязательное выражение. Должно следовать за последним блоком except
- print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+ pass # Несколько исключений можно обработать вместе, если нужно.
+else: # Необязательное выражение. Должно следовать за последним блоком except
+ print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+finally: # Выполнить при любых обстоятельствах
+ print("Мы можем очистить ресурсы здесь")
+
+# Вместо try/finally чтобы очистить ресурсы, можно использовать оператор with
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Запись в файл
+contents = {"aa": 12, "bb": 21}
+with open("myfile1.txt", "w+") as file:
+ file.write(str(contents)) # Записывает строку в файл
+
+with open("myfile2.txt", "w+") as file:
+ file.write(json.dumps(contents)) # Записывает объект в файл
+
+# Чтение из файла
+with open('myfile1.txt', "r+") as file:
+ contents = file.read() # Читает строку из файла
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+with open('myfile2.txt', "r+") as file:
+ contents = json.load(file) # Читает объект json из файла
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
# Python предоставляет фундаментальную абстракцию,
-# которая называется итерируемым объектом (an iterable).
+# которая называется итерируемым объектом (Iterable).
# Итерируемый объект — это объект, который воспринимается как последовательность.
# Объект, который возвратила функция range(), итерируемый.
+
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). Это объект, реализующий интерфейс Iterable
# Мы можем проходить по нему циклом.
for i in our_iterable:
- print(i) # Выводит one, two, three
+ print(i) # Выводит one, two, three
# Но мы не можем обращаться к элементу по индексу.
-our_iterable[1] # Выбрасывает ошибку типа
+our_iterable[1] # Выбрасывает ошибку TypeError
# Итерируемый объект знает, как создавать итератор.
our_iterator = iter(our_iterable)
# Итератор может запоминать состояние при проходе по объекту.
-# Мы получаем следующий объект, вызывая функцию __next__.
-our_iterator.__next__() #=> "one"
+# Мы получаем следующий объект, вызывая функцию next().
+next(our_iterator) # => "one"
-# Он сохраняет состояние при вызове __next__.
-our_iterator.__next__() #=> "two"
-our_iterator.__next__() #=> "three"
+# Он сохраняет состояние при вызове next().
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
# Возвратив все данные, итератор выбрасывает исключение StopIterator
-our_iterator.__next__() # Выбрасывает исключение остановки итератора
+next(our_iterator) # Выбрасывает исключение StopIteration
+
+# Мы можем проходить по нему циклом.
+our_iterator = iter(our_iterable)
+for i in our_iterator:
+ print(i) # Выводит one, two, three
# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list().
-list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
+list(our_iterable) # => Возвращает ["one", "two", "three"]
+list(our_iterator) # => Возвращает [] потому что состояние сохраняется
####################################################
@@ -414,19 +565,19 @@ list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
# Используйте def для создания новых функций
def add(x, y):
print("x равен %s, а y равен %s" % (x, y))
- return x + y # Возвращайте результат с помощью ключевого слова return
+ return x + y # Возвращайте результат с помощью ключевого слова return
# Вызов функции с аргументами
-add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11
+add(5, 6) # => Выводит "x равен 5, а y равен 6" и возвращает 11
# Другой способ вызова функции — вызов с именованными аргументами
-add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
+add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
# Вы можете определить функцию, принимающую переменное число аргументов
def varargs(*args):
return args
-varargs(1, 2, 3) #=> (1,2,3)
+varargs(1, 2, 3) # => (1,2,3)
# А также можете определить функцию, принимающую переменное число
@@ -435,7 +586,7 @@ def keyword_args(**kwargs):
return kwargs
# Вызовем эту функцию и посмотрим, что из этого получится
-keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# Если хотите, можете использовать оба способа одновременно
def all_the_args(*args, **kwargs):
@@ -451,70 +602,135 @@ all_the_args(1, 2, a=3, b=4) выводит:
# Используйте символ * для распаковки кортежей и ** для распаковки словарей
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
-all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
-all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # эквивалентно all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # эквивалентно all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # эквивалентно all_the_args(1, 2, 3, 4, a=3, b=4)
+
+# Возврат нескольких значений (с назначением кортежей)
+def swap(x, y):
+ return y, x # Возвращает несколько значений в виде кортежа без скобок.
+ # (Примечание: скобки исключены, но могут быть включены)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Снова, скобки были исключены, но могут быть включены.
# Область определения функций
x = 5
-def setX(num):
+def set_x(num):
# Локальная переменная x — это не то же самое, что глобальная переменная x
- x = num # => 43
- print (x) # => 43
-
-def setGlobalX(num):
+ x = num # => 43
+ print(x) # => 43
+
+def set_global_x(num):
global x
- print (x) # => 5
- x = num # Глобальная переменная x теперь равна 6
- print (x) # => 6
+ print(x) # => 5
+ x = num # Глобальная переменная x теперь равна 6
+ print(x) # => 6
-setX(43)
-setGlobalX(6)
+set_x(43)
+set_global_x(6)
-# В Python функции — «объекты первого класса»
+# Python имеет функции первого класса
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
-add_10(3) #=> 13
+add_10(3) # => 13
# Также есть и анонимные функции
-(lambda x: x > 2)(3) #=> True
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# Есть встроенные функции высшего порядка
-map(add_10, [1,2,3]) #=> [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
+
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
+
+# Для удобного отображения и фильтрации можно использовать списочные интерпретации
+# Интерпретация списка сохраняет вывод в виде списка, который сам может быть вложенным списком
+[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]
+
+# Вы также можете создавать интерпретации множеств и словарей.
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
-# Для удобного отображения и фильтрации можно использовать списочные включения
-[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
####################################################
-## 5. Классы
+## 5. Модули
####################################################
-# Чтобы получить класс, мы наследуемся от object.
-class Human(object):
+# Вы можете импортировать модули
+import math
+print(math.sqrt(16)) # => 4.0
+
+# Вы можете получить определенные функции из модуля
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# Вы можете импортировать все функции из модуля.
+# Предупреждение: это не рекомендуется
+from math import *
+
+# Вы можете сократить имена модулей
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
- # Атрибут класса. Он разделяется всеми экземплярами этого класса
- species = "H. sapiens"
+# Модули Python - это обычные файлы Python. Вы
+# можете писать свои собственные и импортировать их. Имя
+# модуля совпадает с именем файла.
+
+# Вы можете узнать, какие функции и атрибуты
+# определены в модуле.
+import math
+dir(math)
+
+# Если у вас есть скрипт Python с именем math.py в той же папке,
+# что и ваш текущий скрипт, файл math.py будет
+# будет загружен вместо встроенного модуля Python.
+# Это происходит потому, что локальная папка имеет приоритет
+# над встроенными библиотеками Python.
+
+
+####################################################
+## 6. Классы
+####################################################
+
+# Мы используем оператор class для создания класса
+class Human:
+
+ # Атрибут класса. Он используется всеми экземплярами этого класса
+ species = "Гомосапиенс"
# Обычный конструктор, вызывается при инициализации экземпляра класса
# Обратите внимание, что двойное подчёркивание в начале и в конце имени
# означает объекты и атрибуты, которые используются Python, но находятся
# в пространствах имён, управляемых пользователем.
+ # Методы (или объекты или атрибуты), например:
+ # __init__, __str__, __repr__ и т. д. называются специальными методами.
# Не придумывайте им имена самостоятельно.
def __init__(self, name):
- # Присваивание значения аргумента атрибуту класса name
+ # Присваивание значения аргумента атрибуту
self.name = name
+ # Инициализация свойства
+ self._age = 0
+
# Метод экземпляра. Все методы принимают self в качестве первого аргумента
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
+ # Другой метод экземпляра
+ def sing(self):
+ return 'йо... йо... проверка микрофона... раз, два... раз, два...'
+
# Метод класса разделяется между всеми экземплярами
# Они вызываются с указыванием вызывающего класса в качестве первого аргумента
@classmethod
@@ -526,55 +742,242 @@ class Human(object):
def grunt():
return "*grunt*"
+ # property похоже на геттер.
+ # Оно превращает метод age() в одноименный атрибут только для чтения.
+ # Однако нет необходимости писать тривиальные геттеры и сеттеры в Python.
+ @property
+ def age(self):
+ return self._age
+
+ # Это позволяет установить свойство
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # Это позволяет удалить свойство
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# Когда интерпретатор Python читает исходный файл, он выполняет весь его код.
+# Проверка __name__ гарантирует, что этот блок кода выполняется только тогда, когда
+# этот модуль - это основная программа.
+if __name__ == '__main__':
+ # Инициализация экземпляра класса
+ i = Human(name="Иван")
+ i.say("привет") # Выводит: "Иван: привет"
+ j = Human("Пётр")
+ j.say("привет") # Выводит: "Пётр: привет"
+ # i и j являются экземплярами типа Human, или другими словами: они являются объектами Human
+
+ # Вызов метода класса
+ i.say(i.get_species()) # "Иван: Гомосапиенс"
+ # Изменение разделяемого атрибута
+ Human.species = "Неандертальец"
+ i.say(i.get_species()) # => "Иван: Неандертальец"
+ j.say(j.get_species()) # => "Пётр: Неандертальец"
+
+ # Вызов статического метода
+ print(Human.grunt()) # => "*grunt*"
+
+ # Невозможно вызвать статический метод с экземпляром объекта
+ # потому что i.grunt() автоматически поместит "self" (объект i) в качестве аргумента
+ print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
+
+ # Обновить свойство для этого экземпляра
+ i.age = 42
+ # Получить свойство
+ i.say(i.age) # => "Иван: 42"
+ j.say(j.age) # => "Пётр: 0"
+ # Удалить свойство
+ del i.age
+ # i.age # => это выбрасило бы ошибку AttributeError
+
+
+####################################################
+## 6.1 Наследование
+####################################################
+
+# Наследование позволяет определять новые дочерние классы, которые наследуют методы и
+# переменные от своего родительского класса.
+
+# Используя класс Human, определенный выше как базовый или родительский класс, мы можем
+# определить дочерний класс Superhero, который наследует переменные класса, такие как
+# "species", "name" и "age", а также методы, такие как "sing" и "grunt" из класса Human,
+# но также может иметь свои уникальные свойства.
+
+# Чтобы воспользоваться преимуществами модульности по файлам, вы можете поместить
+# вышеперечисленные классы в их собственные файлы, например, human.py
+
+# Чтобы импортировать функции из других файлов, используйте следующий формат
+# from "имя-файла-без-расширения" import "функция-или-класс"
+
+from human import Human
+
+
+# Укажите родительский класс(ы) как параметры определения класса
+class Superhero(Human):
+
+ # Если дочерний класс должен наследовать все определения родителя без каких-либо
+ # изменений, вы можете просто использовать ключевое слово pass (и ничего больше),
+ # но в этом случае оно закомментировано, чтобы разрешить уникальный дочерний класс:
+ # pass
+
+ # Дочерние классы могут переопределять атрибуты своих родителей
+ species = 'Сверхчеловек'
+
+ # Дочерние классы автоматически наследуют конструктор родительского класса, включая
+ # его аргументы, но также могут определять дополнительные аргументы или определения
+ # и переопределять его методы, такие как конструктор класса.
+ # Этот конструктор наследует аргумент "name" от класса "Human"
+ # и добавляет аргументы "superpower" и "movie":
+ def __init__(self, name, movie=False,
+ superpowers=["сверхсила", "пуленепробиваемость"]):
+
+ # добавить дополнительные атрибуты класса:
+ self.fictional = True
+ self.movie = movie
+ # помните об изменяемых значениях по умолчанию,
+ # поскольку значения по умолчанию являются общими
+ self.superpowers = superpowers
+
+ # Функция "super" позволяет вам получить доступ к методам родительского класса,
+ # которые переопределяются дочерним, в данном случае, методом __init__.
+ # Это вызывает конструктор родительского класса:
+ super().__init__(name)
+
+ # переопределить метод sing
+ def sing(self):
+ return 'Бам, бам, БАМ!'
+
+ # добавить дополнительный метод экземпляра
+ def boast(self):
+ for power in self.superpowers:
+ print("Я обладаю силой '{pow}'!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Тик")
-# Инициализация экземпляра класса
-i = Human(name="Иван")
-print(i.say("привет")) # Выводит: «Иван: привет»
+ # Проверка типа экземпляра
+ if isinstance(sup, Human):
+ print('Я человек')
+ if type(sup) is Superhero:
+ print('Я супергерой')
-j = Human("Пётр")
-print(j.say("Привет")) # Выводит: «Пётр: привет»
+ # Получить порядок поиска разрешения метода (MRO),
+ # используемый как getattr(), так и super()
+ # Этот атрибут является динамическим и может быть обновлен
+ print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
+ # => <class 'human.Human'>, <class 'object'>)
-# Вызов метода класса
-i.get_species() #=> "H. sapiens"
+ # Вызывает родительский метод, но использует свой собственный атрибут класса
+ print(sup.get_species()) # => Сверхчеловек
-# Изменение разделяемого атрибута
-Human.species = "H. neanderthalensis"
-i.get_species() #=> "H. neanderthalensis"
-j.get_species() #=> "H. neanderthalensis"
+ # Вызов переопределенного метода
+ print(sup.sing()) # => Бам, бам, БАМ!
-# Вызов статического метода
-Human.grunt() #=> "*grunt*"
+ # Вызывает метод из Human
+ sup.say('Ложка') # => Тик: Ложка
+
+ # Метод вызова, существующий только в Superhero
+ sup.boast() # => Я обладаю силой 'сверхсила'!
+ # => Я обладаю силой 'пуленепробиваемость'!
+
+ # Атрибут унаследованного класса
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Атрибут, который существует только в Superhero
+ print('Достоин ли я Оскара? ' + str(sup.movie))
####################################################
-## 6. Модули
+## 6.2 Множественное наследование
####################################################
-# Вы можете импортировать модули
-import math
-print(math.sqrt(16)) #=> 4.0
+# Eще одно определение класса
+# bat.py
+class Bat:
-# Вы можете импортировать отдельные функции модуля
-from math import ceil, floor
-print(ceil(3.7)) #=> 4.0
-print(floor(3.7)) #=> 3.0
+ species = 'Летучая мышь'
-# Можете импортировать все функции модуля.
-# (Хотя это и не рекомендуется)
-from math import *
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
-# Можете сокращать имена модулей
-import math as m
-math.sqrt(16) == m.sqrt(16) #=> True
+ # В этом классе также есть метод say
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
-# Модули в Python — это обычные Python-файлы. Вы
-# можете писать свои модули и импортировать их. Название
-# модуля совпадает с названием файла.
+ # И свой метод тоже
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('привет'))
+ print(b.fly)
+
+
+# И еще одно определение класса, унаследованное от Superhero и Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# Определите Batman как дочерний класс, унаследованный от Superhero и Bat
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # Обычно для наследования атрибутов необходимо вызывать super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # Однако здесь мы имеем дело с множественным наследованием, а super()
+ # работает только со следующим базовым классом в списке MRO.
+ # Поэтому вместо этого мы вызываем __init__ для всех родителей.
+ # Использование *args и **kwargs обеспечивает чистый способ передачи
+ # аргументов, когда каждый родитель "очищает слой луковицы".
+ Superhero.__init__(self, 'анонимный', movie=True,
+ superpowers=['Богатый'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # переопределить значение атрибута name
+ self.name = 'Грустный Бен Аффлек'
+
+ def sing(self):
+ return 'на на на на на бэтмен!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Получить порядок поиска разрешения метода (MRO),
+ # используемый как getattr(), так и super()
+ # Этот атрибут является динамическим и может быть обновлен
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
+ # => <class 'bat.Bat'>, <class 'object'>)
+
+ # Вызывает родительский метод, но использует свой собственный атрибут класса
+ print(sup.get_species()) # => Сверхчеловек
+
+ # Вызов переопределенного метода
+ print(sup.sing()) # => на на на на на бэтмен!
+
+ # Вызывает метод из Human, потому что порядок наследования имеет значение
+ sup.say('Я согласен') # => Грустный Бен Аффлек: Я согласен
+
+ # Вызов метода, существующий только во втором родителе
+ print(sup.sonar()) # => ))) ... (((
+
+ # Атрибут унаследованного класса
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Унаследованный атрибут от второго родителя,
+ # значение по умолчанию которого было переопределено.
+ print('Могу ли я летать? ' + str(sup.fly)) # => Могу ли я летать? False
-# Вы можете узнать, какие функции и атрибуты определены
-# в модуле
-import math
-dir(math)
####################################################
## 7. Дополнительно
@@ -585,27 +988,30 @@ def double_numbers(iterable):
for i in iterable:
yield i + i
-# Генератор создаёт значения на лету.
-# Он не возвращает все значения разом, а создаёт каждое из них при каждой
-# итерации. Это значит, что значения больше 15 в double_numbers
-# обработаны не будут.
-# Обратите внимание: range — это тоже генератор.
-# Создание списка чисел от 1 до 900000000 требует много места и времени.
-# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
-# мы используем подчёркивание в конце
-range_ = range(1, 900000000)
-
-# Будет удваивать все числа, пока результат не превысит 30
-for i in double_numbers(range_):
+# Генераторы эффективны с точки зрения памяти, потому что они загружают только данные,
+# необходимые для обработки следующего значения в итерации.
+# Это позволяет им выполнять операции с недопустимо большими диапазонами значений.
+# ПРИМЕЧАНИЕ: "range" заменяет "xrange" в Python 3.
+for i in double_numbers(range(1, 900000000)): # "range" - генератор.
print(i)
if i >= 30:
break
+# Так же, как вы можете создать интерпретации списков, вы можете создать и
+# интерпретации генераторов.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # Выводит -1 -2 -3 -4 -5
+
+# Вы также можете преобразовать интерпретацию генератора непосредственно в список.
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
# Декораторы
-# В этом примере beg оборачивает say
-# Метод beg вызовет say. Если say_please равно True,
-# он изменит возвращаемое сообщение
+# В этом примере "beg" оборачивает "say".
+# Если say_please равно True, он изменит возвращаемое сообщение.
from functools import wraps
@@ -614,7 +1020,7 @@ def beg(target_function):
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
- return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(")
+ return "{} {}".format(msg, "Пожалуйста! У меня нет денег :(")
return msg
return wrapper
@@ -626,8 +1032,8 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Вы не купите мне пива?
-print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
+print(say()) # Вы не купите мне пива?
+print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
```
@@ -635,17 +1041,18 @@ print(say(say_please=True)) # Вы не купите мне пива? Пожал
### Бесплатные онлайн-материалы
-* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
-* [Dive Into Python](http://www.diveintopython.net/)
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
* [Официальная документация](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
-* [Python Module of the Week](http://pymotw.com/3/)
-* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
-
-### Платные
-
-* [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)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)
+* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html)
+* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/)
+* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
+* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
+* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown
index b1fd04e1..8b263be6 100644
--- a/ru-ru/ruby-ru.html.markdown
+++ b/ru-ru/ruby-ru.html.markdown
@@ -480,7 +480,7 @@ class Human
@name
end
- # Тоже самое можно определить с помощью att_accessor
+ # Тоже самое можно определить с помощью attr_accessor
attr_accessor :name
# Также можно создать методы только для записи или чтения
diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown
index f2b1fd36..b1931f9a 100644
--- a/ru-ru/swift-ru.html.markdown
+++ b/ru-ru/swift-ru.html.markdown
@@ -13,7 +13,7 @@ lang: ru-ru
---
Swift - это язык программирования, созданный компанией Apple, для приложений
-под iOS и OS X. Разработанный, чтобы сосуществовать с Objective-C и
+под iOS и macOS. Разработанный, чтобы сосуществовать с Objective-C и
быть более устойчивым к ошибочному коду, Swift был представлен в 2014 году на
конференции разработчиков Apple, WWDC. Приложения на Swift собираются
с помощью LLVM-компилятора, включенного в Xcode 6+.
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 376f4a47..8e5f924a 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -181,6 +181,9 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can contain different types of items.
[1, 'hello', false] #=> [1, "hello", false]
+# You might prefer %w instead of quotes
+%w[foo bar baz] #=> ["foo", "bar", "baz"]
+
# Arrays can be indexed.
# From the front...
array[0] #=> 1
@@ -324,6 +327,11 @@ puts doubled
puts array
#=> [1,2,3,4,5]
+# another useful syntax is .map(&:method)
+a = ["FOO", "BAR", "BAZ"]
+a.map { |s| s.downcase } #=> ["foo", "bar", "baz"]
+a.map(&:downcase) #=> ["foo", "bar", "baz"]
+
# Case construct
grade = 'B'
@@ -430,6 +438,16 @@ def guests(*array)
array.each { |guest| puts guest }
end
+# There is also the shorthand block syntax. It's most useful when you need
+# to call a simple method on all array items.
+upcased = ['Watch', 'these', 'words', 'get', 'upcased'].map(&:upcase)
+puts upcased
+#=> ["WATCH", "THESE", "WORDS", "GET", "UPCASED"]
+
+sum = [1, 2, 3, 4, 5].reduce(&:+)
+puts sum
+#=> 15
+
# Destructuring
# Ruby will automatically destructure arrays on assignment to multiple variables.
@@ -652,4 +670,4 @@ Something.new.qux #=> "qux"
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/scala.html.markdown b/scala.html.markdown
index c7a8842e..08fd37e4 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -252,7 +252,7 @@ weirdSum(2, 4) // => 16
// The return keyword exists in Scala, but it only returns from the inner-most
// def that surrounds it.
// WARNING: Using return in Scala is error-prone and should be avoided.
-// It has no effect on anonymous functions. For example:
+// It has no effect on anonymous functions. For example here you may expect foo(7) should return 17 but it returns 7:
def foo(x: Int): Int = {
val anonFunc: Int => Int = { z =>
if (z > 5)
@@ -260,9 +260,10 @@ def foo(x: Int): Int = {
else
z + 2 // This line is the return value of anonFunc
}
- anonFunc(x) // This line is the return value of foo
+ anonFunc(x) + 10 // This line is the return value of foo
}
+foo(7) // => 7
/////////////////////////////////////////////////
// 3. Flow Control
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
new file mode 100644
index 00000000..c6e72960
--- /dev/null
+++ b/set-theory.html.markdown
@@ -0,0 +1,132 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+contributors:
+---
+Set theory is a branch of mathematics that studies sets, their operations, and their properties.
+
+* A set is a collection of disjoint items.
+
+## Basic symbols
+
+### Operators
+* the union operator, `∪`, pronounced "cup", means "or";
+* the intersection operator, `∩`, pronounced "cap", means "and";
+* the exclusion operator, `\`, means "without";
+* the compliment operator, `'`, means "the inverse of";
+* the cross operator, `×`, means "the Cartesian product of".
+
+### Qualifiers
+* the colon qualifier, `:`, means "such that";
+* the membership qualifier, `∈`, means "belongs to";
+* the subset qualifier, `⊆`, means "is a subset of";
+* the proper subset qualifier, `⊂`, means "is a subset of but is not equal to".
+
+### Canonical sets
+* `∅`, the empty set, i.e. the set containing no items;
+* `ℕ`, the set of all natural numbers;
+* `ℤ`, the set of all integers;
+* `ℚ`, the set of all rational numbers;
+* `ℝ`, the set of all real numbers.
+
+There are a few caveats to mention regarding the canonical sets:
+1. Even though the empty set contains no items, the empty set is a subset of itself (and indeed every other set);
+2. Mathematicians generally do not universally agree on whether zero is a natural number, and textbooks will typically explicitly state whether or not the author considers zero to be a natural number.
+
+
+### Cardinality
+
+The cardinality, or size, of a set is determined by the number of items in the set. The cardinality operator is given by a double pipe, `|...|`.
+
+For example, if `S = { 1, 2, 4 }`, then `|S| = 3`.
+
+### The Empty Set
+* The empty set can be constructed in set builder notation using impossible conditions, e.g. `∅ = { x : x ≠ x }`, or `∅ = { x : x ∈ N, x < 0 }`;
+* the empty set is always unique (i.e. there is one and only one empty set);
+* the empty set is a subset of all sets;
+* the cardinality of the empty set is 0, i.e. `|∅| = 0`.
+
+## Representing sets
+
+### Literal Sets
+
+A set can be constructed literally by supplying a complete list of objects contained in the set. For example, `S = { a, b, c, d }`.
+
+Long lists may be shortened with ellipses as long as the context is clear. For example, `E = { 2, 4, 6, 8, ... }` is clearly the set of all even numbers, containing an infinite number of objects, even though we've only explicitly written four of them.
+
+### Set Builder
+
+Set builder notation is a more descriptive way of constructing a set. It relies on a _subject_ and a _predicate_ such that `S = { subject : predicate }`. For example,
+
+```
+A = { x : x is a vowel } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+Sometimes the predicate may "leak" into the subject, e.g.
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## Relations
+
+### Membership
+
+* If the value `a` is contained in the set `A`, then we say `a` belongs to `A` and represent this symbolically as `a ∈ A`.
+* If the value `a` is not contained in the set `A`, then we say `a` does not belong to `A` and represent this symbolically as `a ∉ A`.
+
+### Equality
+
+* If two sets contain the same items then we say the sets are equal, e.g. `A = B`.
+* Order does not matter when determining set equality, e.g. `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
+* Sets are disjoint, meaning elements cannot be repeated, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
+* Two sets `A` and `B` are equal if and only if `A ⊆ B` and `B ⊆ A`.
+
+## Special Sets
+
+### The Power Set
+* Let `A` be any set. The set that contains all possible subsets of `A` is called a "power set" and is written as `P(A)`. If the set `A` contains `n` elements, then `P(A)` contains `2^n` elements.
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## Set operations among two sets
+### Union
+Given two sets `A` and `B`, the union of the two sets are the items that appear in either `A` or `B`, written as `A ∪ B`.
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### Intersection
+Given two sets `A` and `B`, the intersection of the two sets are the items that appear in both `A` and `B`, written as `A ∩ B`.
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### Difference
+Given two sets `A` and `B`, the set difference of `A` with `B` is every item in `A` that does not belong to `B`.
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### Symmetrical difference
+Given two sets `A` and `B`, the symmetrical difference is all items among `A` and `B` that doesn't appear in their intersections.
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Cartesian product
+Given two sets `A` and `B`, the cartesian product between `A` and `B` consists of a set containing all combinations of items of `A` and `B`.
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
diff --git a/sk-sk/bash-sk.html.markdown b/sk-sk/bash-sk.html.markdown
index e9d1490c..1b0f48d4 100644
--- a/sk-sk/bash-sk.html.markdown
+++ b/sk-sk/bash-sk.html.markdown
@@ -19,7 +19,7 @@ filename: LearnBash-sk.sh
Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol
tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený
-shell pre Linux a Mac OS X.
+shell pre Linux a macOS.
Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo
vykonané priamo v shelli.
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index d6d369cc..aaa592dc 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -22,7 +22,7 @@ Yes, everything. Integers are instances of one of the numeric classes. Classes a
- The system knows the class of the object receiving a message and looks up the message in that class's list of methods. If it is not found, the lookup continues in the super class until either it is found or the root of the classes is reached and there is still no relevant method.
- If a suitable method is found the code is run, and the same process keeps on going with all the methods sent by that method and so on forever.
- If no suitable method is found an exception is raised, which typically results in a user interface notifier to tell the user that the message was not understood. It is entirely possible to catch the exception and do something to fix the problem, which might range from 'ignore it' to 'load some new packages for this class and try again'.
-- A method (more strictly an instance of the class CompiledMethod) is a chunk of Smalltalk code that has been compiled into bytecodes. Executing methods start at the beginning and return to the sender when a return is encountered (we use ^ to signify 'return the follwing object') or the end of the code is reached, in which case the current object running the code is returned.
+- A method (more strictly an instance of the class CompiledMethod) is a chunk of Smalltalk code that has been compiled into bytecodes. Executing methods start at the beginning and return to the sender when a return is encountered (we use ^ to signify 'return the following object') or the end of the code is reached, in which case the current object running the code is returned.
### Simple syntax
Smalltalk has a simple syntax with very few rules.
@@ -41,7 +41,7 @@ We are sending the message 'doSomethingWith:' to myObject. This happens to be a
'myObject' is a 'MyExampleClass' instance so the system looks at the list of messages understood by MyExampleClass
- beClever
-- doWierdThing:
+- doWeirdThing:
- doSomethingWith
In searching we see what initially looks like a match - but no, it lacks the final colon. So we find the super class of MyExampleClass - BigExampleClass. Which has a list of known messages of its own
@@ -388,7 +388,7 @@ y := $A max: $B.
```smalltalk
| b x y |
x := #Hello. "symbol assignment"
-y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
+y := #Symbol, #Concatenation. "symbol concatenation (result is string)"
b := x isEmpty. "test if symbol is empty"
y := x size. "string size"
y := x at: 2. "char at location"
diff --git a/solidity.html.markdown b/solidity.html.markdown
index cc719ec7..5f8ef407 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Joseph Chow", ""]
- ["Bhoomtawath Plinsut", "https://github.com/varshard"]
- ["Shooter", "https://github.com/liushooter"]
+ - ["Patrick Collins", "https://gist.github.com/PatrickAlphaC"]
---
Solidity lets you program on [Ethereum](https://www.ethereum.org/), a
@@ -18,7 +19,7 @@ state variables, functions, and common data types. Contract-specific features
include modifier (guard) clauses, event notifiers for listeners, and custom
global variables.
-Some Ethereum contract examples include crowdfunding, voting, and blind auctions.
+Some Ethereum contract examples include crowdfunding, voting, [decentralized finance](https://defipulse.com/), and blind auctions.
There is a high risk and high cost of errors in Solidity code, so you must be very careful to test
and slowly rollout. WITH THE RAPID CHANGES IN ETHEREUM, THIS DOCUMENT IS UNLIKELY TO STAY UP TO
@@ -32,6 +33,66 @@ popular design patterns.
As Solidity and Ethereum are under active development, experimental or beta
features are typically marked, and subject to change. Pull requests welcome.
+# Working with Remix and Metamask
+
+One of the easiest ways to build, deploy, and test solidity code is by using the:
+
+1. [Remix Web IDE](https://remix.ethereum.org/)
+2. [Metamask wallet](https://metamask.io/).
+
+To get started, [download the Metamask Browser Extension](https://metamask.io/).
+
+Once installed, we will be working with Remix. The below code will be pre-loaded, but before we head over there, let's look at a few tips to get started with remix. Load it all by [hitting this link](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=f490c0d51141dd0515244db40bbd0c17&runs=200).
+
+1. Choose the Solidity compiler
+
+![Solidity-in-remix](images/solidity/remix-solidity.png)
+
+2. Open the file loaded by that link
+
+![Solidity-choose-file](images/solidity/remix-choose-file.png)
+
+3. Compile the file
+
+![Solidity-compile](images/solidity/remix-compile.png)
+
+4. Deploy
+
+![Solidity-deploy](images/solidity/remix-deploy.png)
+
+5. Play with contracts
+
+![Solidity-deploy](images/solidity/remix-interact.png)
+
+You've deployed your first contract! Congrats!
+
+You can test out and play with the functions defined. Check out the comments to learn about what each does.
+
+
+## Working on a testnet
+
+Deploying and testing on a testnet is the most accurate way to test your smart contracts in solidity.
+To do this let's first get some testnet ETH from the Kovan testnet.
+
+[Pop into this Gitter Channel](https://gitter.im/kovan-testnet/faucet) and drop your metamask address in.
+
+In your metamask, you'll want to change to the `Kovan` testnet.
+
+![Solidity-in-remix](images/solidity/metamask-kovan.png)
+
+You'll be given some free test Ethereum. Ethereum is needed to deploy smart contracts when working with a testnet.
+
+In the previous example, we didn't use a testnet, we deployed to a fake virtual environment.
+When working with a testnet, we can actually see and interact with our contracts in a persistent manner.
+
+To deploy to a testnet, on the `#4 Deploy` step, change your `environment` to `injected web3`.
+This will use whatever network is currently selected in your metamask as the network to deploy to.
+
+![Solidity-in-remix](images/solidity/remix-testnet.png)
+
+For now, please continue to use the `Javascript VM` unless instructed otherwise. When you deploy to a testnet, metamask will pop up to ask you to "confirm" the transaction. Hit yes, and after a delay, you'll get the same contract interface at the bottom of your screen.
+
+
```javascript
// First, a simple Bank contract
// Allows deposits, withdrawals, and balance checks
@@ -40,7 +101,7 @@ features are typically marked, and subject to change. Pull requests welcome.
/* **** START EXAMPLE **** */
// Declare the source file compiler version
-pragma solidity ^0.4.19;
+pragma solidity ^0.6.6;
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
@@ -67,7 +128,7 @@ contract SimpleBank { // CapWords
event LogDepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
- function SimpleBank() public {
+ constructor() 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;
@@ -84,7 +145,7 @@ contract SimpleBank { // CapWords
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
- LogDepositMade(msg.sender, msg.value); // fire event
+ emit LogDepositMade(msg.sender, msg.value); // fire event
return balances[msg.sender];
}
@@ -92,7 +153,7 @@ contract SimpleBank { // CapWords
/// @notice Withdraw ether from bank
/// @dev This does not return any excess ether sent to it
/// @param withdrawAmount amount you want to withdraw
- /// @return The balance remaining for the user
+ /// @return remainingBal
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
require(withdrawAmount <= balances[msg.sender]);
@@ -153,7 +214,8 @@ assert(c >= a); // assert tests for internal invariants; require is used for use
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
-// No random functions built in, use other contracts for randomness
+// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truely random number using something like Chainlink VRF.
+// https://docs.chain.link/docs/get-a-random-number
// Type casting
int x = int(b);
@@ -233,7 +295,7 @@ names.length; // get length
names.length = 1; // lengths can be set (for dynamic arrays in storage only)
// multidimensional array
-uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages)
+uint[][5] x; // arr with 5 dynamic array elements (opp order of most languages)
// Dictionaries (any type to any other type)
mapping (string => uint) public balances;
@@ -584,9 +646,35 @@ reveal(100, "mySecret");
// All data to start of time is stored in blockchain, so
// anyone can observe all previous data and changes
+// E. Oracles and External Data
+// Oracles are ways to interact with your smart contracts outside the blockchain.
+// They are used to get data from the real world, send post requests, to the real world
+// or vise versa.
+
+// Time-based implementations of contracts are also done through oracles, as
+// contracts need to be directly called and can not "subscribe" to a time.
+// Due to smart contracts being decentralized, you also want to get your data
+// in a decentralized manner, other your run into the centralized risk that
+// smart contract design matter prevents.
+
+// To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds
+// https://docs.chain.link/docs/get-the-latest-price
+// We can reference on-chain reference points that have already been aggregated by
+// multiple sources and delivered on-chain, and we can use it as a "data bank"
+// of sources.
+
+// You can see other examples making API calls here:
+// https://docs.chain.link/docs/make-a-http-get-request
+
+// And you can of course build your own oracle network, just be sure to know
+// how centralized vs decentralized your application is.
+
+// Setting up oracle networks yourself
+
// D. Cron Job
// Contracts must be manually called to handle time-based scheduling; can create external
// code to regularly ping, or provide incentives (ether) for others to
+//
// E. Observer Pattern
// An Observer Pattern lets you register as a subscriber and
@@ -628,23 +716,26 @@ contract SomeOracle {
// F. State machines
// see example below for State enum and inState modifier
+```
+Work with the full example below using the [`Javascript VM` in remix here.](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200)
+```javascript
// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) ***
// ** START EXAMPLE **
// CrowdFunder.sol
-pragma solidity ^0.4.19;
+pragma solidity ^0.6.6;
/// @title CrowdFunder
/// @author nemild
contract CrowdFunder {
// Variables set on create by creator
address public creator;
- address public fundRecipient; // creator may be different than recipient
+ address payable public fundRecipient; // creator may be different than recipient, and must be payable
uint public minimumToRaise; // required to tip, else everyone gets refund
string campaignUrl;
- byte constant version = 1;
+ byte version = "1";
// Data structures
enum State {
@@ -654,7 +745,7 @@ contract CrowdFunder {
}
struct Contribution {
uint amount;
- address contributor;
+ address payable contributor;
}
// State variables
@@ -684,10 +775,10 @@ contract CrowdFunder {
_;
}
- function CrowdFunder(
+ function crowdFund(
uint timeInHoursForFundraising,
- string _campaignUrl,
- address _fundRecipient,
+ string memory _campaignUrl,
+ address payable _fundRecipient,
uint _minimumToRaise)
public
{
@@ -712,7 +803,7 @@ contract CrowdFunder {
);
totalRaised += msg.value;
- LogFundingReceived(msg.sender, msg.value, totalRaised);
+ emit LogFundingReceived(msg.sender, msg.value, totalRaised);
checkIfFundingCompleteOrExpired();
return contributions.length - 1; // return id
@@ -736,7 +827,7 @@ contract CrowdFunder {
public
inState(State.Successful)
{
- fundRecipient.transfer(this.balance);
+ fundRecipient.transfer(address(this).balance);
LogWinnerPaid(fundRecipient);
}
@@ -766,6 +857,11 @@ contract CrowdFunder {
}
// ** END EXAMPLE **
+```
+
+Some more functions.
+
+```javascript
// 10. OTHER NATIVE FUNCTIONS
// Currency units
@@ -837,18 +933,27 @@ someContractAddress.callcode('function_name');
## Additional resources
- [Solidity Docs](https://solidity.readthedocs.org/en/latest/)
+- [Chainlink Beginner Tutorials](https://docs.chain.link/docs/beginners-tutorial)
- [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices)
- [Superblocks Lab - Browser based IDE for Solidity](https://lab.superblocks.com/)
- [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/)
+- [Chainlink Documentation](https://docs.chain.link/docs/getting-started)
+
+## Smart Contract Development Frameworks
+- [Hardhat](https://hardhat.org/)
+- [Brownie](https://github.com/eth-brownie/brownie)
+- [Truffle](https://www.trufflesuite.com/)
## Important libraries
-- [Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity/): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+- [Zeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+- [Chainlink](https://github.com/smartcontractkit/chainlink): Code that allows you to interact with external data
## Sample contracts
- [Dapp Bin](https://github.com/ethereum/dapp-bin)
+- [Defi Example](https://github.com/PatrickAlphaC/chainlink_defi)
- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts)
- [State of Dapps](http://dapps.ethercasts.com/)
@@ -862,6 +967,7 @@ someContractAddress.callcode('function_name');
- [Solidity Style Guide](http://solidity.readthedocs.io/en/latest/style-guide.html): Ethereum's style guide is heavily derived from Python's [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide.
## Editors
+- [Remix](https://remix.ethereum.org/)
- [Emacs Solidity Mode](https://github.com/ethereum/emacs-solidity)
- [Vim Solidity](https://github.com/tomlion/vim-solidity)
- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc))
diff --git a/sql.html.markdown b/sql.html.markdown
index 5edf0f7c..685e522d 100644
--- a/sql.html.markdown
+++ b/sql.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Bob DuCharme", "http://bobdc.com/"]
---
-Structured Query Language (SQL) is an ISO standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences.
+Structured Query Language (SQL) is an [ISO/IEC 9075](https://www.iso.org/standard/63555.html) standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences.
Implementations typically provide a command line prompt where you can enter the commands shown here interactively, and they also offer a way to execute a series of these commands stored in a script file. (Showing that you’re done with the interactive prompt is a good example of something that isn’t standardized--most SQL implementations support the keywords QUIT, EXIT, or both.)
diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown
index 15d9456b..647575fe 100644
--- a/sv-se/nix-sv.html.markdown
+++ b/sv-se/nix-sv.html.markdown
@@ -365,4 +365,7 @@ with builtins; [
(https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
* [Susan Potter - Nix Cookbook - Nix By Example]
- (http://funops.co/nix-cookbook/nix-by-example/)
+ (https://ops.functionalalgebra.com/nix-by-example/)
+
+* [Rommel Martinez - A Gentle Introduction to the Nix Family]
+ (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
diff --git a/swift.html.markdown b/swift.html.markdown
index 689c5191..39a5cc52 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -12,7 +12,7 @@ contributors:
filename: learnswift.swift
---
-Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
+Swift is a programming language for iOS and macOS development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book.
@@ -822,6 +822,17 @@ for _ in 0..<10 {
See more here: https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html
*/
+// MARK: Preventing Overrides
+
+// You can add keyword `final` before a class or instance method, or a property to prevent it from being overridden
+class Shape {
+ final var finalInteger = 10
+}
+
+// Prevent a class from being subclassed
+final class ViewManager {
+}
+
// MARK: Conditional Compilation, Compile-Time Diagnostics, & Availability Conditions
// Conditional Compilation
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 3d23870b..51e8651c 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -273,7 +273,7 @@ namespace eval people::person1 {
###############################################################################
-## 4. Built-in Routines
+## 5. Built-in Routines
###############################################################################
# Math can be done with the "expr":
@@ -308,7 +308,7 @@ set result [+ 5 3]
set name Neo
expr {{Bob} eq $name}
-# The general operators fall back to string string comparison if numeric
+# The general operators fall back to string comparison if numeric
# operation isn't feasible:
expr {{Bob} == $name}
diff --git a/toml.html.markdown b/toml.html.markdown
index 2b234965..79aa544c 100755
--- a/toml.html.markdown
+++ b/toml.html.markdown
@@ -225,6 +225,7 @@ sku = 284758393
color = "gray"
```
The equivalent in JSON would be:
+
```json
{
"products": [
@@ -270,8 +271,10 @@ The equivalent in JSON would be:
note = "I am an array item in banana fruit's table/map"
```
+
The equivalent in JSON would be:
-```json
+
+```
{
"fruit": [
diff --git a/tr-tr/jquery-tr.html.markdown b/tr-tr/jquery-tr.html.markdown
new file mode 100644
index 00000000..4a4ebeae
--- /dev/null
+++ b/tr-tr/jquery-tr.html.markdown
@@ -0,0 +1,338 @@
+---
+category: tool
+tool: jquery
+contributors:
+ - ["Seçkin KÜKRER", "https://github.com/leavenha"]
+filename: jquery-tr-tr.js
+lang: tr-tr
+---
+
+# Tanım
+
+jQuery, (IPA: ˈd͡ʒeɪˌkwɪəɹiː).
+j + Query, olarak isimlendirilmiş, çünkü çoğunlukla HTML elementlerini sorgulamak ve onları manipüle etmek için kullanılır.
+
+jQuery, 2006 yılında geliştirilmiş ve günümüzde halen kullanımı yaygın, görece en popüler çapraz-platform JavaScript kütüphanelerinden birisidir. Şimdilerde jQuery ekibi tarafından gelişimi devam etmektedir. Dünyanın bir çok yerinden büyük şirketler ve bağımsız yazılım ekipleri tarafından kullanılmaktadır.
+
+Genel kullanım amacı animasyonlardır; Galeri, ek menü, sayfa geçişleri, ve diğer tüm gerçeklemelere sağladığı kolaylıkla birlikte Flash'ın alternatifi olarak yorumlanabilir. [Ajax][ajax-wikipedia-page] işlemleri de dahil olmak üzere olay-yönetimi, döküman manipülasyonu ve bir çok programlama görevini kolaylaştırır.
+
+Resmi sitesinden ([jQuery][jquery-official-website]) indirip web sitenize yükleyebilirsiniz. jQuery günümüz JavaScript kütüphaneleri gibi, küçültülmüş boyutlarda bulut tabanlı İçerik Dağıtım Ağı sistemleri sayesinde bağımsız olarak da sitenize eklenebilir.
+
+Kütüphanenin kullanımı ile, jQueryUI gibi ek paketlerle gelişmiş ve modern arayüzler gerçekleyebilirsiniz.
+
+Fakat, jQuery'ye giriş yapmadan önce elbetteki bu kütüphanenin üzerine kurulduğu teknoloji olan [JavaScript'i öğrenmelisiniz][javascript-learnxinyminutes-page].
+
+```js
+
+// Bu belgedeki değişken isimleri Türkçe,
+// ve [Lower Camel Case] notasyonu uygulamaktadır.
+// Bu belgedeki kod parçalarının çıktıları,
+// onları uyguladığınız dökümanın içeriğine bağlı olarak değişmektedir.
+
+// Döküman boyunca, aşağıdaki gösterimde
+// Kod - Çıktı ikilisi ile içeriğin anlamlandırılması
+// kolaylaştırılmaya çalışmıştır.
+// ornek_kod_parcasi();
+// => "ÖRNEK ÇIKTI"
+
+// *. Konsept
+// jQuery DOM nesnelerini seçmek için inovatif bir yol sunar.
+// `$` değişkeni, `jQuery` kütüphanesine işaret eder.
+// Fonksiyon notasyonu ile DOM nesnelerini elde eder
+// ve üzerinde işlemler gerçekleştirirsiniz.
+$(window)
+// => jQuery [Window] (1)
+// Bize tarayıcının belirlediği window nesnesini verir.
+
+// 1. Seçiciler
+// Tüm nesneleri seçmek için `*` çağırımı yapılır.
+const hepsi = $('*');
+// => jQuery [<html>, <head>, <meta>,
+// .... <meta>, <title>, <meta>, <meta>,
+// .... <meta>, <link>, <link>, …] (1134) = $1
+
+// Seçiciler, jQuery'de bir nesne seçmek için kullanılırlar,
+const sayfa = $(window);
+// => jQuery [window] (1)
+// Sayfa, açık döküman nesnesini seçer.
+
+// Elementler, kendileri için seçicidirler.
+const tumParagraflar = $('p');
+// => jQuery [<p>, <p>, <p>] (3)
+
+// Seçiciler aynı zamanda CSS seçicileri olabilir.
+const mavi = $('.mavi');
+// => jQuery [<p class='mavi'] (1)
+
+// Aynı zamanda element ile birlikte kullanılabilirler.
+const maviParagraf = $('p.mavi');
+// => jQuery [<p class='mavi'>] (1)
+
+// Özellik seçicileri de mevcuttur,
+// Elementin özelliği için seçim yaparlar.
+const isimSecicisi = $('input[name*="kayit.form"]');
+// => jQuery [<input name='kayit.form.sifre'>,
+// <input name='kayit.form.dogumtarihi'> ...] (10)
+
+// Diğer özellik seçiciler;
+/*
+- Özelliğin içinde arayan; *=
+- Özelliğin içinde verilen kelimeleri arayan; ~=
+ |-(kelimeler boşlukla ayrılmalı, *='den farkına dikkat ediniz.)
+- Özelliğin başlangıç verisini arayan; ^=
+- Özelliğin bitiş verisini arayan; $=
+- Özelliği tamamen karşılaştıran; =
+- Özelliğin eşitsizlik durumunu karşılaştıran; !=
+
+Diğer tüm seçiciler için resmi siteyi kontrol ediniz.
+*/
+
+// 2. Olaylar ve Efektler
+// - Olaylar
+// jQuery kullanıcı ile tarayıcı arasındaki etkileşimi olaylar ile ele alır.
+
+// En yaygın kullanımı tartışmasız ki Dökümanın Yüklenmesi olayıdır.
+
+// $.ready fonksiyonu, argüman olarak aldığı fonksiyonu,
+// seçilen eleman tamamen yüklendiğinde çağıracaktır.
+$(document).ready(function(){
+ // Dökümanın tamamı yüklendiğine göre, iş mantığımı çağırabiliriz.
+ console.info('Döküman yüklendi!');
+})
+// => jQuery [#document] (1)
+
+// Bir dökümanın tamamının yüklenmeden,
+// herhangi bir iş mantığı çalıştırmanın
+// neden kötü bir fikir olduğunu merak ediyorsanız,
+// ileri okuma kısmına danışabilirsiniz.
+
+// Önce Olay tanımlayalım.
+
+// Tıklama olayı için `$.click` olay tetikleyicisi kullanılıyor.
+$('.mavi').click(function(){
+ // Unutmayın ki, önceden tanımlanmış
+ // bir fonksiyonu da argüman olarak verebilirsiniz.
+ console.info('Mavi butona tıkladın!');
+})
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Çift Tıklama olayı için `$.dblclick` olay tetikleyicisi kullanılıyor.
+$('.mavi').dblclick(function(){
+ console.info('Mavi butona çift tıkladın!');
+})
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Seçilen Elemente birden fazla tetiklenecek fonksiyon tanımalamak
+// istersek, Olayları ve Fonksiyonları Anahtar-Değer yapısı sağlayan
+// Objeleri kullanarak da çağırabiliriz.
+
+// => tetiklenecekFonksiyon
+$('.mor').on({
+ click: () => console.info('Tek tıklama ile tetiklendim!'),
+ dblclick: () => console.info('Çift tıklama ile tetiklendim!'),
+ // ...
+});
+// => jQuery [<button>, <button>, <button>, <button>, <button>, …] (365)
+
+// Diğer olay tetikleyicileri;
+/*
+Elemente,
+- Fokus/Odaklanma; $.focus
+- Fokus/Odaklanmanın kaybedilmesi; $.blur
+- Farenin alanına girmesi; $.mouseenter
+- Farenin alanından çıkması; $.mouseleave
+
+Diğer tüm olay tetikleyicileri için resmi siteyi kontrol ediniz.
+*/
+
+// Tanımlanan olayları tetiklemek için,
+// Kullanıcı-Tarayıcı etkileşimi yerine elle çağrı yapmak da mümkün.
+// Tanımlama ile çağırım arasındaki fark sadece sağlanan argümanlardır.
+// Argümansız çağırım, olayı tetikler.
+
+// Tıklama olayını tetiklemek için.
+$('.mavi').click();
+// => Mavi butona tıkladın!
+// => jQuery [<button>] (1)
+
+// Çift Tıklama olayını tetiklemek için.
+$('.mavi').dblclick();
+// => Mavi butona çift tıkladın!
+// => jQuery [<button>] (1)
+
+// - Efektler
+// jQuery bir çok ön-tanımlı efekt sunmakta.
+// Bu efektler, belirli parametlerle, farklı iş mantıklarını
+// gerçeklemenize izin verebilir.
+// Önce parametresiz işlevlere göz atalım.
+
+// Elementleri saklayabilir,
+$('#slaytresmi').hide();
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Gizlenen elementleri tekrar görünür yapabilir,
+$('#slaytresmi').show();
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Yada dilediğiniz CSS niteliğini anime edebilirsiniz,
+
+// Bu parametre, anime etmek istediğiniz CSS özelliklerini
+// belirleyen Obje bilgisidir.
+// Yükseklik ve Genişlik bilgileri için değerler belirliyoruz.
+const animeEdilecekCSSOzellikleri =
+ {
+ weight: "300px",
+ height: "300px"
+ };
+
+// Diğer anime edilebilir CSS özellikleri;
+/*
+Elementin,
+- Opaklık; opacity
+- Dış çevre mesafesi; margin
+- Çerçeve yüksekliği; borderWidth
+- Satır yüksekliği; lineHeight
+
+Diğer tüm özellikler için resmi siteyi kontrol ediniz.
+*/
+
+// Bu parametre animasyonun süresini belirler.
+const milisaniyeCinsindenAnimasyonSuresi =
+ 1200;
+
+// Bu parametre, 'linear' yada 'swing' metin
+// bilgilerinden birini alır ve animasyonun
+// akıcılığını belirler.
+// x ∈ {'linear', 'swing'}
+const animasyonAkiciligi = 'linear';
+
+// Bu parametre, bir fonksiyondur ve
+// animasyondan sonra çağırılır.
+// Bir geri-çağırım (callback*) olarak değerlendirilebilir.
+const animasyonGeriCagirimFonksiyonu = function(){
+ console.info('Animasyon bitti!');
+};
+
+// Şimdi tanımlanan bilgilerimizle animasyonu çağırıyoruz.
+$('#slaytresmi').animate(animeEdilecekCSSOzellikleri,
+ milisaniyeCinsindenAnimasyonSuresi,
+ animasyonAkiciligi,
+ animasyonGeriCagirimFonksiyonu);
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Kütüphane `$.animate` fonksiyonu için, anime edeceğiniz
+// CSS özellikleri dışındaki tüm argümanlar için
+// ön tanımlı değerler sağlamaktadır.
+// Bu değerler için resmi siteyi kontrol ediniz.
+
+// Diğer ön tanımlı efektler;
+/*
+Elementi,
+- Yukarı kaydırır; $.slideUp
+- Verilen saydamlık değerine anime eder; $.fadeTo
+- Görünür yada görünmez yapar (geçerli durumuna bağlı); $.toggle
+
+Diğer tüm efektler için resmi siteyi kontrol ediniz.
+*/
+
+// 3. Manipülasyon
+
+// jQuery'de, HTML elementlerinin isteğiniz doğrultusunda
+// değiştirilmesi için araçlar sunulmakta.
+
+// Bir ön-tanımlı CSS sınıfımız olduğunu hayal edebilirsiniz.
+// Bu sınıfı istediğimiz elemente uygulamak için,
+$('#slaytresmi').addClass('inanilmaz-bir-cerceve-sinifi');
+// => jQuery [<img id='slaytresmi' class='inanilmaz-bir-cerceve-sinifi'>] (1)
+
+// Bu CSS sınıfını istediğimiz zaman silebiliriz,
+$('#slaytresmi').removeClass('inanilmaz-bir-cerceve-sinifi');
+// => jQuery [<img id='slaytresmi'>] (1)
+
+// Bu HTML elementini, istediğimiz başka bir element ile çevreleyebiliriz,
+$('#slaytresmi').wrap('<div class="farkli-bir-cerceve"></div>');
+// => jQuery [<img id='slaytresmi'>] (1)
+// Sonucun gözlemlenebilmesi için, elementin çevreleme işlemi sonrası
+// döküman üzerindeki yapısını temel bir seçici ile gözlemleyebiliriz;
+$('.farli-bir-cerceve')
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// Elemente içerik ekleyebiliriz,
+// Eklemeler döküman içeriğinin sonuna yapılacaktır.
+// Bu süreci daha iyi gözlemleyebilmek için içeriğine bakmamız yeterli,
+// Ekleme öncesinde;
+$('.farkli-bir-cerceve');
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// `$.append` fonksiyonu ile ekleme işlemini yapıyoruz.
+$('.farkli-bir-cerceve').append('<h1>Bu çerçeve farklı!</h1>');
+// => jQuery [<div class='farkli-bir-cerceve>] (1)
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// <h1>Bu çerçeve farklı!</h1>
+// </div>
+
+// Dökümandan element silebiliriz,
+$('.farkli-bir-cerceve > h1').remove();
+// => jQuery [<h1>] (1)
+
+// Dökümanın güncel halini görmek için seçiciyi çağırıyoruz,
+$('.farkli-bir-cerceve');
+// => jQuery [<div class='farkli-bir-cerceve>] (1**
+// => <div class="farkli-bir-cerceve">
+// <img id='slaytresmi'>
+// </div>
+
+// Elementlerin özniteliklerini değiştirebilir yada
+// silebiliriz.
+// Öznitelik erişici ve değiştiricisi,
+// Bir fonksiyon notasyonuyla yapılanmış durumda.
+// Eğer bir öznitelik bilgisini almak istiyorsak, ilgili öznitelik
+// ismini;
+
+$('.farkli-bir-cerceve > img').attr('id');
+// => 'slaytresmi'
+
+// Eğer bir öznitelik bilgisini güncellemek istiyorsak,
+// ilgili öznitelik ismi ve sonrasında yeni değerini argüman
+// olarak $.attr fonksiyonuna iletiyoruz;
+
+$('.farkli-bir-cerceve > img').attr('id', 'cercevelislaytresmi');
+// => jQuery [<img id='cercevelislaytresmi'>] (1)
+
+// Diğer ön fonksiyonlar;
+/*
+Elementin,
+- Yükseklik değeri, $.height
+- HTML döküman içeriği, $.html
+- Girdi içeriği, $.val
+- Verilen CSS sınıfına sahipliği, $.hasClass
+
+Diğer tüm manipülasyon fonksiyonları için resmi siteyi kontrol ediniz.
+*/
+
+```
+
+## Notlar
+
+- Yaygın bir yanlış bilineni düzeltmek adına; jQuery bir çalışma-çatısı değil, bir *kütüphanedir*.
+- [Lower Camel Case][lower-camel-case-notasyonu] notasyonu için Wikipedia sayfası.
+
+## İleri Okuma
+
+### İngilizce
+
+- [jQuery][jquery-official-website] resmi sitesi.
+
+- [Jakob Jenkov | $(document).ready article](http://tutorials.jenkov.com/jquery/document-ready.html)
+
+[jquery-official-website]: https://jquery.com
+[ajax-wikipedia-page]: https://en.wikipedia.org/wiki/Ajax_(programming)
+[javascript-learnxinyminutes-page]: https://learnxinyminutes.com/docs/javascript/
+[lower-camel-case-notasyonu]: https://en.wikipedia.org/wiki/Camel_case#Programming_and_coding
diff --git a/tr-tr/ruby-tr.html.markdown b/tr-tr/ruby-tr.html.markdown
new file mode 100644
index 00000000..7bc21c83
--- /dev/null
+++ b/tr-tr/ruby-tr.html.markdown
@@ -0,0 +1,1598 @@
+---
+name: ruby
+language: ruby
+filename: learnruby-tr.rb
+contributors:
+ - ["Seçkin KÜKRER", "https://github.com/LeaveNhA"]
+lang: tr-tr
+---
+
+# Dile nazik bir giriş.
+
+## Ruby Nedir ?
+
+Ruby, doğrudan bir Google aramasıyla aklınızdakini bulmanız zor olabilir. İngilizce bu kelime, `Ruby` (IPA: ˈruːbi) "kırmızı taş" anlamına gelen Fransızca kökenli bir kelime olan `rubi`'den gelmektedir.
+
+Yaratıcısı tarafından, yine esinlenilen bir dil olarak ortaya çıkan `Ruby`, Perl, Smalltalk, Eiffel, Ada, Lisp programlama dillerinin en iyi özelliklerini almıştır. ! [İmperativ]() programlama mentalitesi üzerine kurmayı seçtiği bu teknoloji, günümüzde sektöründe öncü.
+
+
+## Tarihçe
+
+Ruby 1995’te halka duyurulduğundan beri, dünya çapında programcıların dikkatini çekmeye başlamıştır. 2006 Ruby’nin altın yılı olmuştur. Dünyanın en büyük şehirlerinde aktif kullanıcı grupları ve Ruby ile ilgili konferanslar gerçekleştirilmiştir.
+
+Daha sonraları `Ruby`, dünya çapında programlama dillerinin büyümesini ve popülaritesini ölçen dizinlerin (TIOBE dizini gibi) çoğunda ilk 10 içinde yer almıştır. Büyümenin çoğu, Ruby ile yazılmış yazılımların popülaritesiyle ilgilidir, özellikle de Ruby on Rails web çatısıyla.
+
+! [kaynak]()
+
+## Sektördeki Konumu ve Geleceği ?
+
+Çoğu uzmana göre, şu anda sadece `Rails` teknolojisi için bir betik dili olarak sıkışmış durumda.
+
+Bazıları ise, dilin kendi geleceğini, 2020 içinde yayınlanması planlanan `Ruby 3` ile sağlamlaştıracağını ve yeni imkanlar ve sektörek kullanım ve tercihler ile popüleritesinin artacağını düşünüyor.
+
+## Her Şey Nesne
+
+Matz'ın incelemiş olduğu diller sonucunda, teknik olarak en iyi sözdizimin kaynağını “Perl’den daha güçlü ama Python’dan daha nesneye yönelik bir betik dili” olarak tanımlamış.
+
+Her şeyin Nesne olarak görüldüğü bir programlama teknolojisi, bütünlük kavramı açısından herkese kucak açan bir pürüzsüzlük sunuyor. `Ruby`'nin neden tartışmasız, saf bir Nesne yönelimli bir programlama dili olduğuna dair örnekleri aşağıda vereceğim.
+
+## Diğer Gerçeklemeler
+
+- [JRuby](http://jruby.org/), JVM’in (Java Virtual Machine) üstünde çalışan Ruby’dir, JVM’in eniyileyen JIT derleyicisi, çöp toplayıcısı, eşzamanlı thread’leri, araç ekosistemi, ve muazzam sayıdaki kütüphanelerinden faydalanır.
+- [Rubinius](http://rubini.us/), ‘Ruby’da yazılmış Ruby’dir’. LLVM’in üstüne inşa edilmiştir ve ayrıca diğer dillerin üstüne inşa edebilecekleri şık bir sanal makine de sunar.
+- [TruffleRuby](https://github.com/oracle/truffleruby), GraalVM’in üstünde çalışan yüksek performanslı bir Ruby gerçeklemesidir.
+- [IronRuby](http://www.ironruby.net/), “.NET Web Çatısı’yla sıkı sıkıya bağlı” bir gerçeklemedir.
+
+Diğer gerçeklemeler için, lütfen ileri okumaya danışınız.
+
+```ruby
+# Bu karakter ile başlayan satırlar, yorum satırı olarak değerlendirilir.
+# Diğer yorum satırı tanımlamaları için tanımlamalar ve ifadeler kısmına danışın.
+
+## Örnek yapısı; bu örnek dosyadaki her Ruby ifadesi, Ruby yorumlayıcısı
+## tarafından yorumlanarak sonucu `=>` ifadesinin sağına yazılır.
+## örnek ifade #=> örnek sonuç
+## formatındadır.
+## Bazen satır aşımını önlemek için
+## örnek ifade
+## #=> örnek sonuç
+## şeklinde yer verilecektir.
+
+# --------------------------------
+# Veriler ve Temsilleri
+# --------------------------------
+
+## --
+## Sayılar:
+## --
+### Ruby, tamsayı veri tipini destekler. Sayısal değerlerin sisteminizdeki temsili
+### bu veri yapısıdır.
+
+# Tam sayı örneği.
+1453 #=> 1453
+
+## Okunabilirlik için, binlik ya da ondalık kısmını `_` ile
+## ayırmak mümkündür ve bu karakter tümüyle görmezden gelinir.
+3_14 #=> 314
+
+## Negatif sayılar `-` ile başlıyor.
+-3750 #=> -3750
+
+## Oktal sayılar
+03603 #=> 1923
+
+## Onaltılık sayılar
+0x23B #=> 571
+
+## İkilik sayılar
+0b11110000011 #=> 1923
+
+## Büyük sayılar temsili
+12345678901234567890 #=> 12345678901234567890
+
+## Kayan noktalı sayılar
+
+## Bir kayan-noktalı/Ondalıklı sayı.
+3.14 #=> 3.14
+
+## Bilimsel notasyon
+1.0e3 #=> 1000.0
+
+## Bir ipucu,
+## üsten önce işaret!
+3e+9 #=> 3000000000.0
+
+## --
+# Mantıksal Değerler
+## --
+
+## Mantıksal doğru ifadesi.
+true #=> true
+
+## Mantıksal yanlış ifadesi.
+false #=> false
+
+## --
+# Metinler
+## --
+
+## Metin sabitleri
+'Bu, bir metin ifadesi.'
+
+## Kaçışlar için
+'Kaçışlar için "\\"' #=> "Kaçışlar için \"\\\""
+
+## Alternatif ise çift tırnaklı ifadeler.
+"Bu da bir metin ifadesi."
+
+## Kaçışlarda farkı ise,
+"Kaçılar için '\\'" #=> "Kaçılar için '\\'"
+## bazı kaçış notasyonlarına gerek kalmaması.
+
+## Bazı notasyon karakterleri
+
+### Yeni Satır (New Line 0x0a)
+"\n" #=> "\n"
+
+### Boşluk (Space 0x20)
+"\s" #=> "\s"
+
+## --
+# Karakterler
+## --
+
+## Basitçe önlerine soru işareti getirilmiş
+## tek karakter sabitleridir.
+?a #=> "a"
+
+
+## --
+# Semboller
+## --
+## Ruby'de semboller, temsilleri bakımından
+## Clojure'daki semboller ile benzerlerdir.
+:sembol #=> :sembol
+
+## Kendileri, birinci sınıf değerdir.
+:türk.class #=> Symbol
+## Ve aynı zamanda Unicode desteği vardır. (1.9 sürümünden beri)
+
+
+## --
+# Diziler
+## --
+## Basitçe, Ruby dizileri birilerinden virgül ile ayrılmış,
+## değer veya değer sahibi referansların köşeli parantezler
+## ile çevrelenmesi ile oluşturulur. ([])
+[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+## Metinler için de durum aynı.
+["Mustafa", "Kemal", "ATATÜRK"] #=> ["Mustafa", "Kemal", "ATATÜRK"]
+
+## Aynı zamanda, Ruby dizileri tip bağımsız nesne ardışıklarıdır.
+[1881, "Mustafa", "Kemal", "ATATÜRK", 1923, "∞"]
+## Aynı zamanda Unicode destekler (1.9 sürümünden beri)
+
+## --
+# Eşlemeler
+## --
+## Ruby eşlemeleri, süslü parantezler içinde virgül ile ayrılan,
+## anahtar ve değer ikililieridir.
+
+## Bir tane de olabilir,
+{"izmir" => "kızları"} #=> {"izmir" => "kızları"}
+
+## Ya da, birden fazla...
+{"izmir" => "kızları", "paris" => "sokakları"} #=> {"izmir" => "kızları", "paris" => "sokakları"}
+
+## Aslında her değeri anahtar veya değer olarak
+## yerleştirmek mümkün.
+
+## Sembolleri,
+{:zafer => "30 Ağustos!"} #=> {:zafer=>"30 Ağustos!"}
+
+## Rakamları bile.
+{28101923 => "Efendiler, yarın Cumhuriyeti'i ilân edeceğiz!"}
+#=> {28101923=>"Efendiler, yarın Cumhuriyeti'i ilân edeceğiz!"}
+
+## Semboller için ufak bir sözdizimsel şekerleme mevcut ki,
+{istanbul: "beyefendi"} #=> {:istanbul=>"beyefendi"}
+## Bu kullanıma göre, sembol anahtarlar ile değerler arasına
+## `=>` yerine basitçe sembolün başına gelecek `:` sembolü
+## getiriliyor.
+
+
+## --
+# Aralıklar
+## --
+## Ruby aralıkları temeliyle başlangıç ve bitiş
+## değerleri arasındaki aralığın veriye dönüştürülmesi
+## için bir dil olanağıdır.
+
+## (başlangıç..bitiş) notasyonu kullanılabilir.
+(0..10) #=> 0..10
+## REPL'ın bize verdiği ifade sizi yanıltmasın, bu bir aralıktır.
+## Meraklılarıyla, dökümanın devamında içindeki değerleri
+## gezeceğiz.
+
+## Range.new notasyonu ile de ilklenebilirler.
+Range.new(0, 10) #=> 0..10
+
+## --
+# Düzenli İfadeler
+## --
+## İki / operatörünün ortasına tanımlanırlar.
+//.class #=> Regexp
+
+## Örnek bir düzenli ifade, a harfi için.
+/[a]/ #=> /[a]/
+
+# --------------------------------
+# Değelerin Manipüle edilmesi
+# --------------------------------
+
+## --
+## Rakamlar
+## --
+
+## Aritmatik, bildiğimiz şekilde.
+## !! infix notasyon
+
+235 + 1218 #=> 1453
+123 - 35 #=> 88
+2 * 2 #=> 4
+1 / 1 #=> 1
+
+## Bit tabanlı işlemler.
+2 & 5 #=> 0
+3 | 9 #=> 11
+2 ^ 5 #=> 7
+## Aslında C tipi ailesi dillerdeki gibi. Sezgisel bir yaklaşımla, hayatta kalınabilir.
+## Ama yine de dökümantasyona başvurulmasını tavsiye ederim.
+
+
+## --
+## Mantıksal
+## --
+
+## ! operatörü teklidir, ve aldığı değerin mantıksal tersini alır.
+!true #=> false
+!false #=> true
+
+
+## --
+## Metinler
+## --
+
+### Boş mu ?
+"".empty? #=> true
+
+### Bir bölümünü alalım.
+"Ölürüm TÜRKİYEM!".slice(7, 7) #=> "Türkiye"
+## Bir başka şekilde, indis notasyonu ile,
+"Ölürüm Türkiye'm!"[7, 7] #=> "Türkiye"
+
+## Küçük harfe dönüştürelim
+"LAY-LAY-LOM sana göre sevmeler...".downcase
+#=> "lay-lay-lom sana göre sevmeler..."
+
+## Büyük harfa dönüştürelim
+"beşiktaş".upcase #=> "BEŞIKTAŞ"
+
+## Karakterlerine ayıralım
+"BEŞİKTAŞ".chars #=> ["B", "E", "Ş", "İ", "K", "T", "A", "Ş"]
+
+## Çevrelemek için
+"Ahmet Mete IŞIKARA".center(30)
+#=> " Ahmet Mete IŞIKARA "
+
+## İçerik kontrolü için include metodu
+"aşk".include?(?a) #=> true
+## argümanı metin tipinde de verebilirdik, ama
+## yukarıdaki temsillerde gördüğümüz gibi,
+## yorumlayıcı, karakter sabitini metin olarak işliyor zaten.
+
+## Konumunu alalım.
+"Dayı".index("a") #=> 1
+## Elbette, tasarımında sağlıklı kararlar alınmış her
+## dil gibi, Ruby'de 0'dan saymaya başlıyor.
+
+## Metin yerleştirme yapalım
+"Ali Baba'nın x çiftliği var.".sub("x", "bir")
+#=> "Ali Baba'nın bir çiftliği var."
+
+## Birden fazla eşleşme için, değiştirme yapalım
+"Dal sarkar x kalkar, x kalkar dal sarkar.".gsub("x", "kartal")
+#=> "Dal sarkar kartal kalkar, kartal kalkar dal sarkar."
+
+## Düzenli ifadeler ile, cümledeki sesli harfleri değiştirelim.
+"Bir berber bir bere...".gsub(/[ie]/, "*")
+#=> "B*r b*rb*r b*r b*r*..."
+
+## Diğer işlevler için ileri okumadaki kaynağa başvurunuz.
+
+
+## --
+## Eşlemeler
+## --
+
+## basit bir eşleme ile başlayalım.
+{:boy => 1.74} #=> {:boy => 1.74}
+
+## Belirli bir anahtar, eşlememizde barınıyor mu diye
+## kontrol ediyoruz.
+{:boy => 1.74}.has_key? :boy
+#=> true
+## Parantezlerin yokluğu sizi yanıltmasın,
+## bu bir fonksiyon çağırısıdır.
+
+## Eşlemeden veri çekiyoruz
+{:boy => 1.74}.fetch :boy
+#=> 1.74
+
+## Eşlemelere veri ekliyoruz
+{:boy => 1.74}.merge!(kilo: 74)
+#=> {:boy=>1.74, :kilo=>74}
+
+## Anahtarlarımıza bakalım
+{:boy=>1.74, :kilo=>74}.keys
+#=> [:boy, :kilo]
+
+## Değerlerimize bakalım
+{:boy=>1.74, :kilo=>74}.values
+#=> [1.74, 74]
+
+## Dizi olarak almak istersek
+{:boy=>1.74, :kilo=>74}.to_a
+#=> [[:boy, 1.74], [:kilo, 74]]
+## Endişelenmeyin, dönüşümler için koca bir bölüm
+## ayırdım.
+
+
+## --
+## Diziler
+## --
+
+## Örnek bir dizi ile başlayalım.
+["Mustafa", "Kemal", "ATATÜRK"]
+#=> ["Mustafa", "Kemal", "ATATÜRK"]
+
+## İlk değeri alıyoruz
+["Mustafa", "Kemal", "ATATÜRK"].first
+#=> "Mustafa"
+
+## Son Değeri,
+["Mustafa", "Kemal", "ATATÜRK"].last
+#=> "ATATÜRK"
+
+## Indis araması için `fetch` metodu.
+["Mustafa", "Kemal", "ATATÜRK"].fetch 1
+#=> "Kemal"
+
+## Var olamyan bir indis ararsak hata alıyoruz.
+
+## Fakat seçimli ikinci argüman bize indisin
+## bulunamaması halinde döndürülecek değeri
+## belirleme imkanı veriyor.
+["Mustafa", "Kemal", "ATATÜRK"].fetch 20101927, "Nutuk"
+#=> "Nutuk"
+
+## Birden fazla değer almak için, slice metodunu
+## kullanabiliriz
+["Fatih", "Sultan", "Mehmet"].slice 1..2
+#=> ["Sultan", "Mehmet"]
+
+## Ya da, indis notasyonu da kullanılabilir.
+["Fatih", "Sultan", "Mehmet"][1..2]
+#=> ["Sultan", "Mehmet"]
+
+## Baştan n tane eleman almak için take metodunu kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].take 2
+#=> ["Fatih", "Sultan"]
+
+## Rastgele bir dizi elemanı elde etmek için sample metodunu
+## kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].sample
+#=> "Fatih"
+
+## `sample` metodu seçimli bir argüman kabul eder.
+## bu argüman rastgele istenen eleman sayısını temsil eder
+["Fatih", "Sultan", "Mehmet"].sample 2
+#=> ["Fatih", "Sultan"]
+
+## Aradığınız eleman, dizide var mı kontrolü için
+## include? metodu kullanılıyor
+["Fatih", "Sultan", "Mehmet"].include? "Fatih"
+#=> true
+
+## Dizinizdeki elemanları koşul dahilinde seçimlemek için
+## select metodunu kullanıyoruz
+["Fatih", "Sultan", "Mehmet"].select {|s| s.include? ?a}
+#=> ["Fatih", "Sultan"]
+## Süzme işleminin koşulu, a karakteri içeren nesneler için olumlu.
+## Not: filter metodu, select için bir takma addır.
+
+## Ters bir yöntem, süzgeçleme için ise;
+["Fatih", "Sultan", "Mehmet"].reject {|s| s.include? ?a}
+#=> ["Mehmet"]
+## koşulumuz aynıydı, seçimleme metodumuzu değiştirdik.
+
+### Yapısal düzenlemeler için:
+## Dizileri ters çevirmek,
+["Fatih", "Sultan", "Mehmet"].reverse
+#=> ["Mehmet", "Sultan", "Fatih"]
+
+## Sıralamak için sort metodu,
+["İş", "Aşk", "Para"].sort
+#=> ["Aşk", "Para", "İş"]
+
+## Ön koşulla sıralamak için,
+["İş", "Aşk", "Para"].sort {|a,b| b <=> a }
+#=> ["İş", "Para", "Aşk"]
+## Koşulumuz basitçe tersine sıralamak için bir tanımdır.
+## ileride karşılaştırma operatörlerini göreceğiz.
+
+## Tekrarlı elemanların temizlenmesi için
+[1,2,3,4,5,6,7,1,2,4,1,5,6,1,2,5].uniq
+#=> [1, 2, 3, 4, 5, 6, 7]
+
+## Dizilerin birleştirilmesi için
+[1,2] + [3,4]
+#=> [1, 2, 3, 4]
+## infix notasyon sizi yanıltmasın,
+## tasarımı gereği, her şey sınıflar ve metotlarına çağırım
+## olarak yürüyor.
+## Kanıtlayalım;
+[1,2].+([3,4])
+#=> [1, 2, 3, 4]
+
+## Peki ya aynı elemanları içerebilecek dizileri birleştirmek
+## istersek ?
+[1,2] | [2,3,4]
+#=> [1, 2, 3, 4]
+## | operatörü bizi, nihai sonuçtaki tekrarlı veriden koruyor.
+
+## Peki ya bir diziyi, eleman bazında diğeriyle
+## süzmek istersek ?
+[1,2] - [2,3,4]
+#=> [1]
+## Notasyon sizi yanıltmasın, Küme gibi davranan bir dizi işlevi.
+
+### Veri Dönüşümleri için:
+## Dizideki her elemana uygulamak istediğiniz bir
+## dönüşümü, map metodu ile uygulayabilirsiniz,
+["Kontak İsmi",
+ "Kontak Telefon Numarası"].map {|element| "<label>#{element}</label>"}
+#=> ["<label>Kontak İsmi</label>", "<label>Kontak Telefon Numarası</label>"]
+## HTML konusu için yine LearnXinYminutes'e danışabilirsiniz.
+
+## Son elde ettiğimiz veriyi birleştirmek için,
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"].join ""
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+
+## Veriyi indirgemek için ise reduce metodu kullanırız,
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"]
+ .reduce("") {|akümülatör, veri| akümülatör + veri}
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+## Akümülatör, her operasyondan dönen ara-geçici değer.
+## Bu değeri, parantez içinde ilkledik,
+## eğer vermeseydik, dizinin ilk elemanı olacaktı.
+
+## Tabi, daha kolay bir yolu var;
+["<label>Kontak İsmi</label>",
+ "<label>Kontak Telefon Numarası</label>"].reduce(:+)
+#=> "<label>Kontak İsmi</label><label>Kontak Telefon Numarası</label>"
+## reduce metodu, ikili bir operasyonu (akümülatör için metot!)
+## sembol olarak vermenize izin verir ve bu, reduce için
+## indirgeme fonksiyonu olarak kullanılır.
+
+## Nüansları olsa da, son üç Ruby çağırımı aynı sonucu vermektedir.
+
+
+## --
+## Semboller
+## --
+
+## Ruby sembolleri, çalışma zamanında değiştirilemezler.
+## Ama metinsel değerlerden semboller elde etmek mümkündür.
+## Bunu dönüşümler kısmında işlemek daha doğru olacak diye düşündüm.
+
+# --------------------------------
+# Dönüşümler
+# --------------------------------
+
+## --
+# Rakamlar
+## --
+
+## Sayısal değerlerin diğer tiplere dönüşümü;
+
+## Sayısal -> Metinsel
+1923.to_s #=> "1923"
+
+## Sayısal -> Mantıksal
+!1923 #=> false
+## Farkedebileceğiniz gibi,
+## sayısal değerler, mantıksal doğru'ya değerlendiriliyor.
+
+## Sayısal -> Sembol
+## Maalesef, Ruby bile Sayısal değerden Sembol değerlerine
+## doğrudan dönüşüm için metot barındırmıyor.
+## Bunu yine de başarmak istersek, değeri önce
+## Metinsel'e dönüştürerek Sembol dönüşümü için hazırlarız.
+1923.to_s.to_sym
+#=> :"1923"
+
+## Sayısal -> Dizi | bölümlenerek
+## Yine doğrudan bir dönüşüm yoktur.
+## Böyle bir doğrudan dönüşüm teşvik de edilmez.
+## Ama ihtiyaç olabilecek bir dönüşüm.
+1923.to_s.split('')
+#=> ["1", "9", "2", "3"]
+## Öncelikle Metinsel dönüşüm yapılır, sonra
+## her bir karakter için ayrılır.
+## Yine her bir rakamı sayısal bir şekilde elde etmek için
+## her birini Metinsel'den Sayısal değere dönüştürecek
+## ifade aşağıdaki gibidir.
+1923.to_s.split('').map { |i| i.to_i }
+#=> [1, 9, 2, 3]
+
+
+## --
+# Mantıksal
+## --
+
+## Mantıksal -> Metinsel
+true.to_s #=> "true"
+false.to_s #=> "false"
+
+## Mantıksal değeler için gerçeklenmiş başka bir dönüşüm
+## metodu olmadığı için, bu kısmı dilde ufak bir nüansa ayırmak
+## istedim.
+## Kaynak için ileri okumaya başvurunuz.
+
+## Hangi programlama dilinden gelirseniz gelin,
+## dilde doğruluk değerleri diye bir küme vardır.
+## Hangi değerlerin mantıksal doğru değerine dönüşeceği,
+## bu değer yerine geçebileceği
+## fikri üzerine kurulu bir küme.
+## Ve Ruby'de nil değeri, false dışında, mantıksal yanlış değerine çözümlenen tek şey.
+## Bu ön bilgi ile doyduysak, başlayalım.
+
+!!nil #=> false
+!!false #=> false
+!!0 #=> true
+!!"" #=> true
+## Şimdi ne oldu burada ?
+## `!!` ifadesi; değilinin değili, yani kendisi. Tek bir farkla.
+## Verinin türü değiştiriliyor. Mantıksal olarak yorumlanıyor.
+## Yukarıda, nil ve false ifadeleri mantıksal olarak yanlış olarak yorumlanıyor.
+## Diğerleri ise mantıksal doğru.
+
+
+## --
+# Metinsel
+## --
+
+## Metinsel -> Sayısal
+## Öncelikle dilde ufak bir tuzağa dikkat çekmek isterim.
+"".to_i #=> 0
+"asd".to_i #=> 0
+## Sayısal yorumlaması geçersiz ve boş her metinsel değer,
+## 0 rakamına değerlendirilir.
+
+## Başarılı bir dönüşüm,
+"1234".to_i #=> 1234
+
+## Sayı sistemini belirleyebileceğiniz seçimli bir argüman
+## kabul ediyor, to_i metodu.
+"1234".to_i 5 #=> 194
+## 1234 sayısının, beşlik tabandaki karşılığı.
+
+## Tam sayı dışında doğrudan dönüşümler
+## dil olanağı olarak sunulmuş durumda;
+
+## Kompleks sayı olarak,
+"1234".to_c #=> (1234+0i)
+
+## Ondalık (Kayan-noktalı) sayı olarak,
+"1234".to_f #=> 1234.0
+
+## Rasyonel sayı olarak,
+"1234".to_r #=> (1234/1)
+
+## Metinsel -> Mantıksal
+
+## Mantıksal değerin kendisi için tersinin, tersini alırız
+!!"seçkin" #=> true
+
+## Mantıksal tersi için ise tersini,
+!"seçkin" #=> false
+
+## Metinsel -> Sembol
+"cengiz".to_sym #=> :cengiz
+
+## Metinsel -> Dizi
+"Cengiz Han".split #=> ["Cengiz", "Han"]
+
+## split metodu, seçimli argümanının varsayılan değeri
+## boşluk karakteridir.
+
+## Metinsel -> Dizi | bölümlenerek
+"Cengiz Han".split ""
+#=> ["C", "e", "n", "g", "i", "z", " ", "H", "a", "n"]
+
+
+## --
+# Sembol
+## --
+
+## Sembol -> Metinsel
+:metin.to_s #=> "metin"
+## Başka bir dönüşüm için dilin bir teşviki yoktur.
+
+## --
+# Diziler
+## --
+
+## Dizi -> Metinsel
+[1,2,3,4,5].to_s #=> "[1, 2, 3, 4, 5]"
+
+
+## --
+# Eşlemeler
+## --
+
+## Eşleme -> Dizi
+{a: 1, b: 2, c: 3}.to_a
+#=> [[:a, 1], [:b, 2], [:c, 3]]
+## Her bir anahtar-değer çifti bir dizi olarak
+## değerlendirilir ve elemanları sırasıyla
+## anahtar ve değerdir.
+
+## Eşleme -> Metinsel
+{a: 1, b: 2, c: 3}.to_s
+#=> "{:a=>1, :b=>2, :c=>3}"
+## inspect metodu için bir takma addır.
+
+
+# --------------------------------
+# Tanımlamalar, ifadeler, yorumlama.
+# --------------------------------
+
+## --
+## Yorumlama
+## --
+
+## Dökümanın başından beri gördüğümüz bu tek satır yorumlama operatörü
+## (#)
+## kendinden sonra gelen her şeyin, satır boyunca yorumlama olarak
+## değerlendirilmesi gerektiğini Ruby yorumlayıcısına söyler.
+
+## Ruby, farklı yorumlama imkanları da sağlamaktadır.
+## Örneğin;
+=begin
+ Başlangıç ifadesi (=begin), sonlandırma ifadesi (=end)
+ ile arasında kalan her şeyi yorum satırı olarak ele alır.
+=end
+
+## --
+## Global değişkenler.
+## --
+
+## Ruby evrensel değişkenleri, kapsamı en geniş değişken türüdür.
+## Her yerden erişilebilir...
+
+## Basitçe dolar sembolü ( $ ) ile başlarlar.
+$evrensel_bir_değişken = 42 #=> 42
+
+## Bir çok metadoloji ve yöntem ve teknoloji, size
+## evrensel değişkenler kullanmanın projenizi karmaşıklaştıracağı
+## ve bakımını zorlaştıracağını söyler; Haklıdırlar...
+
+## --
+## Varlık değişkenleri.
+## --
+
+## At ( @ ) sembölü ile başlarlar ve isimlerinin de ifade ettiği
+## gibi, kendileri bir Sınıf'ın değeridir.
+
+class Varlık
+ def initialize()
+ @varlık_değişkeni = 101
+ end
+
+ def göster()
+ puts "Varlık değişkeni: #@varlık_değişkeni"
+ end
+end
+
+varlık1 = Varlık.new()
+
+varlık1.göster()
+#=> Varlık değişkeni: 101
+
+## Sınıf tanımı şimdilik kafanızı karıştırmasın.
+## İlgilenmemiz gereken kısım;
+## @varlık_değişkeni = 101
+## ifadesidir. Ve nesne özelinde tanımlama yapar.
+## Kapsamı sadece o nesnedir.
+
+## ! NOT: ilklenmemiş varlık değişkenleri nil ön değeri ile
+## yaşam döngüsüne başlar.
+
+## --
+## Sınıf değişkenleri.
+## --
+
+## Sınıf değişkenleri iki at ( @@ ) sembölü ile başlarlar.
+## Tanımlar, herhangi bir metot içinde
+## kullanılmadan önce ilklenmelidirler.
+## İlklenmemiş bir Sınıf Değişkenine referansta bulunmak,
+## bir hata oluşturur.
+
+class Sınıf
+ @@sınıf_nesne_sayısı = 0
+
+ def initialize()
+ @@sınıf_nesne_sayısı += 1
+ end
+
+ def göster()
+ puts "Sınıf sayısı: #@@sınıf_nesne_sayısı"
+ end
+end
+
+sınıf_varlığı1 = Sınıf.new()
+sınıf_varlığı2 = Sınıf.new()
+sınıf_varlığı3 = Sınıf.new()
+
+sınıf_varlığı1.göster()
+#=> Sınıf sayısı: 3
+
+
+## --
+## Yerel değişkenler.
+## --
+
+## Yerel değişkenlerin isimlendirmesi küçük harf
+## ya da alt çizgi ( _ ) ile başlar ve kapsamı tanımın
+## yapıldığı sınıf, modül, metot yada blok içinde kalır.
+
+## --
+## Sabitler.
+## --
+
+## Ruby sabitleri, büyük harf ile tanımlanırlar ve
+## kapsamları için iki senaryo mevcuttur;
+
+## - Sınıf ya da Modül içinde tanımlanırlarsa
+## Tanımın yapıldığı blok içinden erişilebilir.
+
+## - Sınıf ya da Modül dışında yapılan tanımlar ise
+## Evrensel bir kapsama sahiptir ve her yerden
+## erişilebilirler.
+
+## Örneğin:
+
+class Sabit
+ SABİT = 299_792_458
+
+ def göster
+ puts "Sabit değer: #{SABİT}"
+ end
+end
+
+# Create Objects
+sabit = Sabit.new()
+
+sabit.göster()
+#=> Sabit değer: 299792458
+
+## İfadenin tanımındaki alt çizgiler sizi yanıltmasın
+## binlik ayracı olarak kullandım ve Ruby yorumlayıcısı
+## tamamen görmezden geliyor.
+## Bknz: Veriler ve Temsiller: Sayılar.
+
+## --
+## Sözde Değişkenler.
+## --
+
+## Ruby özel bir dil.
+## Öyle ki, Bazı sözde-değişkenler ile
+## size, ihtiyacınız olabileceği erişimi sağlar.
+## Ama onlara atama yapamazsınız.
+
+## Sözde değişkenler ve kullanımları
+## ile ilgili İleri okumaya başvurunuz.
+
+
+# --------------------------------
+# Konvansiyonlar ve teşvikler.
+# --------------------------------
+
+## Konvansiyonlar:
+
+## --
+## İsimlendirme Konvansiyonları:
+## Döküman boyunca yaptığım gibi,
+## tanımlayıcılar ve erişilebilir tanımlanmış ifadeler
+## için lütfen önerildiği gibi İngilizce kullanın.
+## İsimlendirme, Bilgisayar bilimlerinde yeterince
+## ağır bir zemin ve dilin teşvik ettiği rehber
+## ve önerdiği konvansiyonları takip ederek
+## bakımı, okuması ve geliştirmesi kolay projeler
+## gerçeklemek mümkündür.
+
+## --
+## Semboller, Metotlar ve Değişkenler için
+##-Snake Case ( snake_case ) kullanılması önerilir.
+
+## --
+## Sınıflar için Camel Case (CamelCase):
+## Sınıf isimlendirmeleri için önerildiği gibi,
+## Camel Case isimlendirme notasyonuna sadık kalın.
+
+## --
+## Dosyalar ve Klasörler için Snake Case (snake_case):
+## Dosya ve klasörleri isimlendirmek için lütfen
+## Snake Case isimlendirme konvansiyonuna sadık kalın.
+
+## --
+## Dosya Başına Bir Sınıf:
+## Her dosyada bir sınıf barındırmaya özen gösterin.
+
+## ---
+## Bu kısımdaki teşvik içerikleri
+## rubocop-hq/ruby-style-guide'dan gelmektedir.
+
+## ! Rehbere göre bu dökümanı düzenle!
+
+## --
+## Girintileme:
+## Girintileme için TAB yerine, iki boşluk kullanın.
+
+def bir_metot
+ birşeyler_yap
+end
+## Yerine;
+def bir_metot
+ birşeyler_yap
+end
+
+## --
+## Satır Başına Karakter:
+## Satır başına maksimum 80 karakter olacak şekilde
+## dökümanı yapılandırın.
+
+## --
+## Satır Sonları:
+## Unix-Stili satır sonlarını kulanın.
+## Eğer Git kullanıyorsanız;
+## $ git config --global core.autocrlf true
+## ifadesi sizi bu zahmetten kurtaracaktır.
+
+## --
+## Satır Başına Bir İfade:
+## Satır başına bir ifade kullanın.
+
+puts 'test!'; puts 'test!'
+## Yerine;
+puts 'test!'
+puts 'test!'
+
+## --
+## Boşluklar ve Operatörler:
+## Operatörler, virgüller, ifade ayraçları
+## aralarında boşluk bırakın.
+
+toplam=1+2
+x,z=1,2
+class FooError<StandardError;end
+## Yerine;
+toplam = 1 + 2
+x , z = 1 , 2
+class FooError < StandardError; end
+## Bir kaç istisna hariç
+## - Üs operatörü
+## - Rasyonel sayı gösteriminde kullanılan eğik çizgi.
+## - Güvenli gösterim operatörü.
+
+
+### Daha fazlası için ileri okumadaki
+### bu rehbere danışabilirsiniz...
+
+# --------------------------------
+# Bloklar, Kontrol blokları ve örnekler.
+# --------------------------------
+
+## --
+## Ruby Blokları:
+## Süslü parantezler ya da `do`, `end` ile çevrelenen,
+## değişkenleri ortama bağlı işlevlerdir.
+## Diğer dillerde !{Closure} ( closure ) karşılığı
+## bulur.
+## Ruby'de bloklar, ifadeleri gruplamanın bir şeklidir.
+## Bloklar tanımlandıklarında çalıştırılmazlar,
+## Ruby, bu yönetimi akıllıca yapar.
+
+## Örneğin;
+
+## Tanımlamamız
+def selamla_sonra_çağır
+ puts 'Selamlar!'
+ yield ## tüm sihir burada!
+end
+
+## Şimdi tanımı çağıralım
+selamla_sonra_çağır {puts 'Çağrı, gerçekleşti!'}
+#= Selamlar!
+#= Çağrı, gerçekleşti!
+#=> nil
+## Çağırım, kendini çağıran kaynağa nil döndürmekte.
+## Değerlendirmenin sonucunda, Ruby yorumlayıcısı,
+## ifadenin değerini nil olarak çıktılar.
+## Fakat, puts çağrıları, girdi/çıktı işlevimizi
+## yerine getirir ve metinleri ekrana basar.
+
+## Blokların argüman almaları da mümkündür:
+def selamla_sonra_değer_ile_çağır
+ puts 'Selamlar!'
+ yield('Hain Kostok') ## tüm sihir burada!
+end
+
+selamla_sonra_değer_ile_çağır {|isim| puts "Sana da selam, #{isim}!"}
+#= Selamlar!
+#= Sana da selam, Hain Kostok!
+#=> nil
+
+## Detaylı bilgi için, ileri okumaya başvurunuz.
+
+## --
+## Eğer ( if ) kontrol ifadesi:
+## Algoritmanızda dallanma imkanı sağlar.
+## Şablonu:
+## if koşul_ifadesi [then]
+## yürütülecek_kod
+## [elsif bir_diğer_koşul [then]
+## yürütülecek_diğer_kod]
+## [else
+## yürütülecek_bir_diğer_kod]
+## end
+
+## Bu kalıba sadık kalarak, dallanmalarımızı kodlarız.
+## Köşeli parantezler, sezgisel olarak anlaşılacağı üzere
+## seçimli ifadelerdir.
+
+## Örnek:
+if true
+ puts 'Koşul ifadesi, buradan devam edecek!'
+else
+ puts 'Buradan değil.'
+end
+#= Koşul ifadesi, buradan devam edecek!
+#=> nil
+
+## --
+## Eğer ( if ) düzenleyicisi:
+## Kompak bir dil olanağıdır. Aynı şekilde, çalıştırılacak kod
+## ve bir koşul ifadesi alır. Ve koşul ifadesine bakarak
+## ifadenin yürütüleceğine karar verir.
+## Şablonu:
+## çalıştırılacak_kod if koşul_ifadesi
+
+## Örnek:
+
+puts 'Bu ifade yürütülecek!' if true
+#= Bu ifade yürütülecek!
+#=> nil
+
+
+## --
+## Durum ( case ) kontrol ifadesi:
+## Bir koşul ifadesi ve bir ya da daha fazla karşılaştırma ifadesi
+## alarak, eşleşen bloğu yürütür.
+## Şablonu:
+## case koşullanacak_ifade
+## [when karşılaştırma_ifadesi [, karşılaştırma_ifadeleri ...] [then]
+## yürütülecek_kod ]...
+## [else
+## eşleşme_olmazsa_yürütülecek_kod ]
+## end
+
+yaş = 27
+case yaş
+when 0 .. 2
+ puts "bebek"
+when 3 .. 6
+ puts "küçük çocuk"
+when 7 .. 12
+ puts "çocuk"
+when 13 .. 18
+ puts "genç"
+else
+ puts "yetişkin"
+end
+#= yetişkin
+#=> nil
+
+## --
+## .. Sürece ( while ) kontrol ifadesi:
+## Aldığı koşul ifadesini kontrol eder,
+## kontrol bloğunu çağırır ve tekrar kontrol eder.
+## Koşul ifadesi doğru olduğu sürece, kontrol bloğu
+## çağırılmaya devam eder.
+## Şablonu:
+## while koşul_ifadesi [do]
+## yürütülecek_kod
+## end
+
+## Örnek:
+
+$n = 0
+$sayı = 5
+
+while $n < $sayı do
+ puts("Döngü içinde n = #$n" )
+ $n +=1
+end
+#= Döngü içinde n = 0
+#= Döngü içinde n = 1
+#= Döngü içinde n = 2
+#= Döngü içinde n = 3
+#= Döngü içinde n = 4
+#=> nil
+
+## --
+## .. Sürece ( while ) düzenleyicisi:
+## Eğer düzenleyecisi gibi, kompak bir dil olanağıdur.
+## Kontrol ifadesinin işlevini yerine getirir,
+## ama satır içi kullanıma müsade ederek.
+## Şablonu:
+## çalıştırılacak_kod while koşul_ifadesi
+## Yada:
+## begin
+## çalıştırılacak_kod
+## end while koşul_ifadesi
+
+## --
+## İçin ( for ) kontrol ifadesi:
+## N kere, I kere, X kere gibi ifadelerin dildeki kontrol
+## karşılığıdır. Çoklu veri üzerinde iterasyonlar yapmanızı
+## veri üzerinde operasyonlar yürütmenizi sağlar.
+## Şablonu:
+## for değişken [, başka_değişken ...] in ifade [do]
+## yürütülecek_kod
+## end
+
+## Örnek:
+for i in 1..5
+ puts i
+end
+#= 0
+#= 1
+#= 2
+#= 3
+#= 4
+#= 5
+#=> 0..5
+
+## Ardışıkları itere etmek için tek yol bu değil tabii.
+## İlerleyen kısımda buna yer verilecektir.
+
+## --
+## Sonlandırıcı ( break ) kontrol ifadesi:
+## Bu kontrol ifadesi yürütüldüğünde, çalışma zamanını
+## en iç tekrarlı bloktan çıkarır.
+
+## Örnek:
+for i in 1..5
+ break if i > 2
+ puts i
+end
+#= 0
+#= 1
+#= 2
+#=> nil
+## break kontrol ifadesi, if düzenleyecisi ile çevrelenmiştir.
+## if i > 2
+## break
+## end
+## ifadesi ile eşdeğerdir.
+## ifade yürütüldüğü anda, en yakın tekrarlı blok terkedilir.
+## Yorumlayıcı, sonraki ifadeden yürütmeye devam eder.
+
+## Diğer kontrol ifadeleri ve kullanımları için ileri okumaya başvurunuz...
+
+
+# --------------------------------
+# Özel anahtar kelimeler; kullanımları ve örnekleri.
+# --------------------------------
+
+## --
+## __ENCODING__:
+## Bu anahtar kelime size yorumlayıcı kodlama türünü verecektir.
+
+__ENCODING__
+#=> "#<Encoding:UTF-8>"
+
+## Platform, araç ve çalışma zamanı yürütme
+## yönteminize bağlı olarak alacağınız çıktı
+## değişiklik gösterebilir.
+
+## --
+## __LINE__:
+## Geçerli dosyada, yürütme satır numarasını verir.
+
+__LINE__
+#=> 67
+
+## Platform, araç ve çalışma zamanı yürütme
+## yönteminize bağlı olarak alacağınız çıktı
+## değişiklik gösterebilir.
+
+## --
+## BEGIN ve END:
+## BEGIN:
+## Dosyadaki tüm içerikten önce yürütülür.
+## END:
+## Dosyadaki tüm içeriklerden sonra yürütülür.
+
+## --
+## alias:
+## Herhangi bir tanımlayıcı için takma ad tanımlamanıza
+## olanak sağlar.
+
+$eski = 0
+alias $yeni $eski
+
+$yeni
+#=> 0
+
+## --
+## and:
+## Düşük öncelikli bir Mantıksal VE operatörü.
+
+## --
+## begin / end ve rescue:
+## İstisnalar begin / end blokları
+## arasında ele alınır ve `rescue` anahtar kelimesi ile
+## işlenirler.
+## İstisnalar ve mantalitesine dair ön girişi
+## Teşvik edilen paradigma ve anlatımı kısmında bulabilirsiniz.
+
+## Hata yönetimi, Ruby'de de özenle işlenmiş bir konudur.
+
+## Örnek:
+
+begin
+ yanlış_bir_hesaplama = 2/0
+ puts "Hesaplama sonucu: #{yanlış_bir_hesaplama}"
+ rescue ZeroDivisionError => hata_nesnesi
+ puts "Sıfıra bölümle ilgili bir hata yakalandı: #{hata_nesnesi.message}"
+end
+#= Sıfıra bölümle ilgili bir hata yakalandı: divided by 0
+#=> nil
+
+## Örneğimizde matematiksel sistemimiz için hatalı bir
+## işlem gerçekleştiriyoruz. Sonrasında hatayı ilgili
+## hata durumu için belirlediğimi alanda yönetiyoruz.
+## Örnekte hatayı çıktılayarak yönettik, gerçek dünyada
+## biraz daha kompleks gerçekleşebilir.
+## Gerçek dünya örnekleri için ileri okumaya başvurabilirsiniz.
+
+
+## --
+## defined?:
+## defined?, argümanını metinsel olarak açıklayan bir dil olanağıdır.
+
+## Örnek:
+RUBY_VERSION
+#=> "2.4.0"
+
+defined? RUBY_VERSION
+#=> "constant"
+
+defined? nil
+#=> "nil"
+
+defined? puts
+#=> "method"
+
+
+## --
+## ensure:
+## Hata yönetiminin bir parçası olarak dilde görev atfedilen ensure,
+## blok içinde, hata olsun ya da olmasın yürütüleceği garanti edilen
+## dil ifadeleri için bir imkandır.
+
+## Örnek:
+
+begin
+ yanlış_bir_hesaplama = 2/0
+ puts "Hesaplama sonucu: #{yanlış_bir_hesaplama}"
+ rescue ZeroDivisionError => hata_nesnesi
+ puts "Sıfıra bölümle ilgili bir hata yakalandı: #{hata_nesnesi.message}"
+ ensure
+ puts "Hesaplama bloğu sonlandı!"
+end
+#= Sıfıra bölümle ilgili bir hata yakalandı: divided by 0
+#= Hesaplama bloğu sonlandı!
+#=> nil
+
+
+## --
+## self:
+## Nesnenin kendisine erişim sağlayan bir dil olanağı.
+
+## Örnek:
+
+dünya = "Dünya!"
+#=> "Dünya!"
+
+dünya
+#=> "Dünya!"
+
+dünya.class
+#=> String
+
+def dünya.selamla
+ "Merhaba, " + self
+end
+#=> :selamla
+
+dünya.selamla
+#=> "Merhaba, Dünya!"
+
+## Nesnenin kendisine bir metot tanımladık,
+## bunu yaparken de değerine erişim sağladık.
+
+## --
+## super:
+## Nesne yönelimli programlama (spesifik olarak, obje tabanlı)
+## paradigmasına göre, kalıtım konseptinde, türeyen sınıfın
+## türetildiği sınıfa erişimi (üst sınıfı, atası, hiyerarşik üstü)
+## bu anahtar kelime ile gerçekleşir.
+
+class A
+ def initialize(a)
+ @a = a
+ end
+end
+
+class B < A
+ def initialize(a, b)
+ @b = b
+ super a
+ end
+end
+
+b = B.new 1, 2
+#=> #<B:0x00007f852d04c7e8 @b=2, @a=1>
+## super ile üst sınıfın ilklenmesi gerçekleştirildi,
+## aldığımız çıktıda da @a=1 çıktısıyla gözlemlenebilir.
+
+## Bu konunun, dilin paradigma teşviği ile ilgili
+## olduğunu ve anlamazsanız, Paradigma başlığını bitirdikten
+## sonra tekrar bu örneği değerlendirmeniz gerektiğini hatırlatırım.
+
+## --
+## yield:
+## Ruby blokları kısmında anlattık, ama, burada da bir nüanstan
+## bahsetmeden geçemeyeceğim.
+## Çalıştırılabilir ifadeleri çalıştırmanın birden fazla yolu vardır.
+## Fakat yield, en performanslı dil olanağı olarak dökümanda işlenmiş.
+## Kaynak için ileri okumaya danışın.
+
+
+
+# --------------------------------
+# G/Ç ( I/O )
+# --------------------------------
+
+=begin
+ G/Ç, Girdi/Çıktı ( Input/Output ) kısaltmasıdır.
+ Temelde, sistemden girdi almak ve çıktı yaratmak amacıyla vardır.
+ Girdi örnekleri:
+ - Klavyeden bastığınız herhangi bir tuş.
+ - Fare hareketleriniz ya da tıklamalarınız.
+ - Mikrofonunuzun aldığı sesler.
+
+ Çıktı örnekleri:
+ - Herhangi bir dil ifadesinin sonucu.
+ - Dijital bir ses dosyasının sese dönüşmesi.
+ - Ekranda gördükleriniz.
+
+ Fakat endişelenmeyin, G/Ç derken, şu anda
+ biz sadece Ruby'de,
+ - Dosya okuma/yazma.
+ - Ekrana metin yazdırma / Bilgi okuma.
+ - Ağ soketleri. ( biraz da olsa )
+ işlerinden bahsediyor olacağız.
+=end
+
+defined? IO
+#=> "constant"
+
+IO.class
+#=> Class
+
+## IO sınıfı, File ve Socket gibi pratik kullanımı olan sınıfların atasıdır.
+## Septikler için;
+
+File.superclass
+#=> IO
+## Gözlemlediğiniz üzere, superclass metodu, üst sınıfı veriyor.
+
+## --
+## Dosya Okuma ve Yazma:
+## Ruby'de dosya okuma ve yazma işlemleri için, File
+## sınıfını kullanacağız.
+
+## Dosyaya yazmak için;
+File.write 'test.txt', "a,b,c"
+#=> 5
+## 5, ifadenin ürettiği dönüş değeridir.
+## ve, çıktılanan karakter sayısını verir.
+
+## Dosyadan okuma için;
+## Bu kısım, açıklayıcı olması açısından
+## ifadeleri teker teker işleyeceğiz.
+
+File
+#=> File
+## Sınıfımız.
+
+File.readlines 'test.txt'
+#=> ["a,b,c"]
+## readlines File sınıfının bir metodu ve aldığı argüman dosya yoludur.
+
+File.readlines('test.txt').first
+#=> "a,b,c"
+## Dönüş değeri bir diziydi, her bir satır bir eleman olacak şekilde.
+## Biz, kendi verilerimizi, kendi ayıracımızla kaydetmeyi seçtik.
+## Eğer, `\n` satır ifadesi ile ayırmayı seçseydik, readlines
+## metodu zaten işlevi gereği, bize değerleri ayrı ayrı verecekti.
+
+File.readlines('test.txt').first.split ','
+#=> ["a", "b", "c"]
+## verilerimizi aldık.
+
+## Eğer yeni satır karakterini ayıraç olarak kullansaydık;
+File.write 'ntest.txt', ['a', 'b', 'c'].join("\n")
+#=> 5
+
+File.readlines('ntest.txt').map(&:chomp)
+#=> ["a", "b", "c"]
+## Bu da genel kullanımlı bir yaklaşımdır.
+
+## --
+## Ekrana bilgi yazdırma ve Okuma:
+## Konsol'a bilgi çıktılamak için,
+## önceden tanımlanmış $stdout global nesnesini kullanacağız.
+## Pratik kullanımda, prints işlevinden bir farkı yoktur.
+## Aynı sonuca ikisi ile de ulaşabilirsiniz.
+
+$stdout.print "Bu bir çıktı.\n"
+#= Bu bir çıktı.
+#=> nil
+
+## Şimdi kullanıcıdan bilgi okuyalım:
+$stdin.gets
+#! Bu kısımda hiç bir çıktı verilmez ve aksine
+#! sizden girdi beklenir. Bir metin yazın ve onaylamak için
+#! enter tuşunu kullanın.
+#- Bu bir girdi metni!
+#=> "Bu bir girdi metni!\n"
+
+## Aldığımız veriyi temizlenin yolunu biliyoruz.
+## Dönüş değerine chomp metodunu uygulamak.
+$stdin.gets.chomp
+#- Bu bir girdi metni!
+#=> "Bu bir girdi metni!"
+
+
+## --
+## Ağ girdi/çıktı yönetimi
+## Ruby'de soketler (Socket)
+## haricen çalışma zamanına dahil edilir.
+
+require 'socket'
+#=> true
+
+soket = TCPSocket.new('google.com', 80)
+#=> #<TCPSocket:fd 13, AF_INET, 192.168.0.11, 63989>
+## Alacağınız çıktı değişiklik gösterebilir.
+## Soketi oluşturduk ve bir değişkene atadık.
+## Şimdi bunun üzerinden okuma ve yazma işlemlerini
+## gerçekleştireceğiz.
+
+soket.write "GET / HTTP/1.1"
+#=> 14
+
+soket.write "\r\n\r\n"
+#=> 4
+## İki write metodunun sonucu da, sokete yazılan verinin
+## uzunluğudur.
+
+## Şimdi okuma zamanı, soketi açtık, isteğimizi bildirdik.
+## Şimdi soket üzerinden aldığımız cevabı ekrana yazdıralım.
+
+soket.recv 80
+#=> "HTTP/1.1 200 OK\r\nDate: Thu, 03 Sep 2020 10:48:21 GMT\r\nExpires: -1\r\nCache-Control"
+## Alacağınız çıktı değişiklik gösterebilir.
+## Ancak, başarılı şekilde okuma yaptık.
+
+
+
+# --------------------------------
+# Teşviğinde bulunduğu paradigma ve derinlemesine anlatımı.
+# --------------------------------
+
+## --
+## Nesne Yönelimli Programlama Nedir?
+## Kısaca NYP, en basit anlatımıyla;
+## nesnelerle programlamadır.
+## Nesne paradigması, her programcıya doğal ve sezgisel gelir.
+## Bunun sebebi, zaten gerçekliği algılama şeklimize uygun olmasıdır.
+## Araba, onu bir araya getiren nesnelerden oluşur,
+## tekerlekleri, direksiyonu, kasası, ve diğer parçalarıyla.
+## Ama bu, tam tanım değildir. NYP'de, Nesneler,
+## Bilgilere ( evet, varlık olarak başka nesneler de sayılabilir )
+## ve bu bilgileri yönetecek ( hesaplamalar gerçekleştirecek
+## ya da aksiyonlar alacak -- G/Ç -- gibi ) metotlara sahiptir.
+
+## Bir nesnenin en net tanımı böyle yapılabilirken,
+## NYP, bir gerçek dünya problemi için bir araya getirilmiş
+## -- çoğunlukla birden fazla -- sınıfların yapıları,
+## ilişkileri ve işlevlerini ele alır.
+
+## Bir paradigma olarak NYP, bizlere her varlığı nesne olarak
+## modellemeyi ve problem uzayımızdaki nesnelerle olan ilişkilerini
+## Ruby'de NYP için sağlanan imkanlarla yönetmeyi öğütler.
+
+## Sınıf içerisinde saklanan bilgiye öznitelik ya da özellik,
+## işlevlere ise metot denilir.
+## NYP jargonu için ileri okumaya başvurabilirsiniz.
+
+## --
+## Ruby'de NYP teşviki:
+
+## Nesneler, Sınıfların gerçeklenmiş halleridir.
+## Tam tersi ile, Sınıflar ise, nesnelerin soyut kalıplarıdır.
+
+## Bir sınıf tanımı yapalım ve gerçekleyelim:
+
+class Araba
+end
+#=> nil
+## Evet, evet. Tanımımız hiç bir öznitelik ( attributes ) ya da
+## metot ( method ) içermiyor.
+
+## Şimdi bir özellik ekleyelim
+class Araba
+ def initialize(hız)
+ @hız = hız
+ end
+end
+
+araba = Araba.new 100
+#=> #<Araba:0x00007f7f300e59c8 @hız=100>
+
+## En naif haliyle, hız bilgisi saklayan bir araba sınıfı gerçekledik.
+## initialize metodu, Ruby imkanları ile, nesne yaşam döngünüzün ilk adımıdır.
+## Bu döngüyü aşağıdaki gibi betimlemek mümkündür.
+## İlkleme ( initialize ) -> [İşlevlerin çağırımı] -> Sonlandırma
+## İlkleme, initialize metodu ile ele alınır, alınacak tüm argümanlar,
+## sınıfın iş mantığı doğrultusuyla, bu ilk işlevde yönetilir ve nesne
+## kullanıma hazır hale getirilir.
+
+## Şimdi bir işlev ekleyelim.
+
+class Araba
+ def initialize(hız)
+ @hız = hız
+ end
+
+ def git!
+ puts 'Hınn, hınn!'
+ end
+end
+
+araba = Araba.new 100
+#=> #<Araba:0x00007f7f300e59c8 @hız=100>
+
+## Şimdi metodu çağırıyoruz.
+araba.git!
+#= Hınn, hınn!
+#=> nil
+
+## Başlığın amacı sadece Ruby'nin NYP olanaklarını ve
+## teşviğini işlemek değil. Paradigmaya bir giriş kazandırmak.
+## Bundan dolayı, etkileşim içinde birden fazla sınıf görmeliyiz.
+
+class Tekerlek
+ YERLİ = 5
+ İTHAL = 1
+
+ def initialize (tür)
+ @güç = tür
+ end
+
+ def döndür!
+ @güç -= 1
+ end
+end
+
+class Araba
+ def initialize (hız)
+ @hız = hız
+ @tekerlekler = (1..4).map {|| Tekerlek.new(Tekerlek::YERLİ)}
+ end
+
+ def git!
+ if @tekerlekler.map(&:döndür!).filter {|ömür| ömür < 0}.first then
+ puts 'Paat!'
+ else
+ puts 'Hınnn, hınnn!'
+ end
+ end
+end
+
+## nesnemizi oluşturuyoruz
+araba = Araba.new 100
+
+## altı sefer, araba nesnesinin git! metodunu çağırıyoruz.
+(0..6).map {|| araba.git! }
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Hınnn, hınnn!
+#= Paat!
+#= Paat!
+
+## İş mantığımıza göre, arabamızın dört tekeri ve ve Yerli olanlar
+## 5 birim dayanıklılığa sahip. ;)
+## Bu beş birim tükenince, araba gitmek yerine,
+## patlak teker çıktısı alıyoruz.
+
+
+## Şimdiye kadar gördüklerimizi bir analiz edelim;
+## Araba, sınıfın ismi. Her sınıf, tanımlamasak da, temel bir
+## kurucu metot içerecek şekilde dil işleyicisi tarafından
+## ele alınıyor.
+## Bizim bir tanımımız var ama.
+## Hız bilgisi alıyoruz.
+## bu bilgi, sınıf özniteliğidir. Sınıf, bu bilgiye kendi içinden erişebilir.
+## Bir de, binek araçların dört tekerleği olduğu fikriyle,
+## nesne içinde, kurucu metot içinde dört tane Tekerlek nesnesi gerçekliyor
+## ve saklıyoruz.
+## İş mantığımıza göre onlara erişmemiz gerekiyor.
+## git! metodu içinde, erişiyor ve kullanıyoruz.
+## metotların sonundaki ünlem işareti bir konvansiyondur,
+## metotların saf olmayan çağırımlar gerçeklediği anlamına gelmektedir.
+## Kendilerini ( ya da sahip olduğu diğer nesneleri ) değiştirdikleri,
+## bir girdi/çıktı gerçekleştirdikleri yada buna benzer yan etki içeren
+## bir ifade barındırdıkları anlamına gelir.
+
+## Sizi temin ederim ki, NYP, bu dökümanı ( hali hazırda ~1560 satır )
+## genel anlatımı için bile ikiye katlayabilir.
+## Lütfen detaylı bilgi için ileri okumaya başvurunuz.
+```
+
+# İleri okumalar.
+
+Tümüyle İngilizce olan bu ileri okumalara inat, bu detaylı özgün Türkçe içeriği üretmek istedim.
+Dilerim, benden sonra katkıda bulunanlar olur.
+
+- [Ruby Style Guide](https://rubystyle.guide), Ruby stil rehberi.
+- [Ruby-Doc üzerinde Proc](https://ruby-doc.org/core-2.4.0/Proc.html), Ruby Blokları ve Proc kavramı için.
+- [Ruby-Doc üzerinde String](https://ruby-doc.org/core-2.6/String.html) sınıfı, işlevleri, metotları.
+- [Ruby-Doc üzerinde TrueClass](https://ruby-doc.org/core-2.5.1/TrueClass.html#method-i-to_s) Dildeki mantıksal ifadelerin gerçeklemesi olan TrueClass (ve FalseClass için de aynı bağlantı üzerinden içeriğe ulaşılabilir) dönüşüm içeriği kaynağı.
+- [Ruby Gerçeklemeleri Listesi](https://github.com/codicoscepticos/ruby-implementations) Ruby'nin farklı platformlardaki gerçeklemeleri. Opal ve Topaz dikkat çekenleridir.
+- [The Object-Oriented Thought Process](https://www.amazon.com/Object-Oriented-Thought-Process-Developers-Library/dp/0321861272) kitap, bir paradigma olarak NYP ve düşünce yapısından bahsediyor. Bir paradigma olarak, NYP, türetildiği temel paradigmadan ne almış, başka paradigmalara ne kadar imkan sağlıyor ve paralel paradigma uyumu konusunda tüm sorularınıza cevap bulabilirsiniz. Yazar, belli etmese de, pragmatik bir yaklaşımda.
+- [Block Argument](https://docs.ruby-lang.org/en/2.4.0/syntax/methods_rdoc.html#label-Block+Argument) Ruby Blokları ve yield hakkındaki Ruby resmi döküman sayfası ve alt başlığı.
+- [A Theory of Objects]() Class-Based Languages başlığında inceleniyorlar.
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 640be0cd..f7a41ce1 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -114,7 +114,7 @@ class Point {
}
// Functions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
// Static members
static origin = new Point(0, 0);
@@ -137,9 +137,9 @@ class Point3D extends Point {
}
// Overwrite
- dist() {
+ dist(): number {
let d = super.dist();
- return Math.sqrt(d() * d() + this.z * this.z);
+ return Math.sqrt(d * d + this.z * this.z);
}
}
diff --git a/uk-ua/c-ua.html.markdown b/uk-ua/c-ua.html.markdown
new file mode 100644
index 00000000..c4dac75f
--- /dev/null
+++ b/uk-ua/c-ua.html.markdown
@@ -0,0 +1,860 @@
+---
+language: c
+filename: learnc-ua.c
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+ - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
+ - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
+ - ["Marco Scannadinari", "https://marcoms.github.io"]
+ - ["Zachary Ferguson", "https://github.io/zfergus2"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+ - ["Joshua Li", "https://github.com/JoshuaRLi"]
+ - ["Dragos B. Chirila", "https://github.com/dchirila"]
+translators:
+ - ["AstiaSun", "https://github.com/AstiaSun"]
+lang: uk-ua
+---
+
+О, C! Досі мова для сучасних обчислень у високопродуктивних продуктах.
+
+C це імовірно найбільш низькорівнева мова, яку будуть використовувати більшість програмістів. Проте, вона компенсує це не тільки швидкістю виконання. Як тільки ви оціните її можливість ручного управління пам'яттю, С зможе відвести саме в ті місця, в які вам потрібно було потрапити.
+
+> **Дещо про прапори компілятора**
+>
+> За замовчуванням, gcc та clang досить тихо інформують про попередження та помилки
+> при компіляції, хоч це і може бути дуже корисною інформацією. Тому рекомендується
+> використовувати більш вимогливий компілятор. Ось кілька рекомендацій:
+>
+> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic`
+>
+> За інформацією про ці та інші прапори зверніться до головної сторінки man вашого
+> компілятора C (наприклад, `man 1 gcc`) або ж просто заґуґліть.
+
+
+```c
+// Однорядкові коментарі починаються з //
+// Проте вони з'явились тільки після С99.
+
+/*
+Багаторядкові коментарі мають такий вигляд. І працюють в C89.
+*/
+
+/*
+Багаторядкові коментарі не можуть вкладатись один в одний.
+/* Будьте обережними */ // коментар закінчується на цьому рядку...
+*/ // ...а не на цьому!
+
+// Константа: #define <keyword>
+// Назви констант, як правило, пишуться великими літерами, проте це не вимога
+#define DAYS_IN_YEAR 365
+
+// Ще одним способом оголосити константи є перелічення констант.
+// До речі, всі вирази мають закінчуватись крапкою з комою.
+enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
+// MON отримає значення 2 автоматично, TUE дорівнюватиме 3 і т.д.
+
+// Імпортувати заголовки можна за допомогою #include
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+// (Заголовки із стандартної бібліотеки С вказуються між <кутовими дужками>.)
+// Щоб додати власні заголовки, потрібно використовувати "подвійні лапки"
+// замість кутових:
+//#include "my_header.h"
+
+// Сигнатури функцій попередньо оголошуються в .h файлах або на початку .с файлів.
+void function_1();
+int function_2(void);
+
+// Потрібно оголосити 'прототип функції' перед main(), реалізація функцій
+// відбувається після функції main().
+int add_two_ints(int x1, int x2); // прототип функції
+// Варіант `int add_two_ints(int, int);` теж правильний (не потрібно називати
+// аргументи). Рекомендується також називати аргументи в прототипі для
+// кращого розуміння.
+
+// Вхідною точкою програми є функція під назвою main. Вона повертає чисельний тип.
+int main(void) {
+ // реалізація програми
+}
+
+// Аргументи командного рядка, вказані при запуску програми, також передаються
+// у функцію main.
+// argc - це кількість переданих аргументів
+// argv — це масив масивів символів, що містить самі аргументи
+// argv[0] - назва програми, argv[1] - перший аргумент, і т.д.
+int main (int argc, char** argv)
+{
+ // printf дозволяє вивести на екран значення, вивід - це форматований рядок,
+ // в даному випадку %d позначає чисельне значення, \n — це новий рядок
+ printf("%d\n", 0); // => Виводить 0
+
+ ///////////////////////////////////////
+ // Типи
+ ///////////////////////////////////////
+
+ // Всі змінні повинні бути оголошені на початку поточного блоку області видимості.
+ // В цьому коді вони оголошуються динамічно. С99-сумісні компілятори
+ // дозволяють оголошення близько до місця, де значення використовується.
+
+ // int (цілочисельний знаковий тип) зазвичай займає 4 байти
+ int x_int = 0;
+
+ // short (цілочисельний знаковий тип) зазвичай займає 2 байти
+ //
+ short x_short = 0;
+
+ // Символьний тип char гарантовано займає 1 байт
+ char x_char = 0;
+ char y_char = 'y'; // Символьні літерали позначаються ''
+
+ // long (цілочисельний знаковий тип) має розмір від 4 до 8 байтів; великі значення
+ // типу long гарантовано займають 8 байтів
+ long x_long = 0;
+ long long x_long_long = 0;
+
+ // Тип float - це зазвичай 32-бітове число з плаваючою крапкою
+ float x_float = 0.0f; // Суфікс 'f' позначає літерал з плаваючою крапкою
+
+ // Тип double - це зазвийчай 64-бітове число з плаваючою крапкою
+ double x_double = 0.0; // дійсне число без суфіксів має тип double
+
+ // Цілочисельні типи можуть не мати знаку (бути більше, або ж рівними нулю)
+ unsigned short ux_short;
+ unsigned int ux_int;
+ unsigned long long ux_long_long;
+
+ // Char всередині одинарних лапок інтерпретуються як числа в наборі
+ // символів комп'ютера.
+ '0'; // => 48 в таблиці ASCII.
+ 'A'; // => 65 в таблиці ASCII.
+
+ // sizeof(T) повертає розмір змінної типу Т в байтах
+ // sizeof(obj) віддає розмір виразу (змінна, літерал, і т.п.)
+ printf("%zu\n", sizeof(int)); // => 4 (на більшості пристроїв з 4-байтним словом)
+
+ // Якщо аргумент оператора `sizeof` — це вираз, тоді його аргументи не оцінюються
+ // (крім масивів, розмір яких залежить від змінної).
+ // Значення, що повертається в цьому випадку, - це константа часу компіляції.
+ int a = 1;
+ // size_t - беззнаковий чисельний тип розміром щонайменше 2 байти, який
+ // використовується для відображення розміру об'єкта.
+ size_t size = sizeof(a++); // a++ не оцінюється
+ printf("sizeof(a++) = %zu where a = %d\n", size, a);
+ // Виводить "sizeof(a++) = 4 where a = 1" (на 32-бітній архітектурі)
+
+ // Масиви повинні бути проініціалізовані з конкретним розміром.
+ char my_char_array[20]; // Цей масив займає 1 * 20 = 20 байтів
+ int my_int_array[20]; // Цей масив займає 4 * 20 = 80 байтів
+ // (припускаючи 4-байтні числа)
+
+ // Таким чином можна проініціалізувати масив нулем:
+ char my_array[20] = {0};
+ // де "{0}" називається "ініціалізатором масиву".
+
+ // Зазначте, можна явно не оголошувати розмір масиву, ЯКЩО ви проініціалізуєте
+ // масив у тому ж рядку. Тому, наступне оголошення еквівалентне:
+ char my_array[] = {0};
+ // АЛЕ, потрібно визначити розмір масиву під час виконання, як тут:
+ size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
+
+ // ПОПЕРЕДЖЕННЯ якщо ви вирішили використовувати даний підхід, потрібно
+ // визначити розмір **перед тим**, як ви почнете передавати масив у функцію
+ // (побачите дискусію пізніше). Масиви перетворюються на вказівники при
+ // передачі як аргументи у функцію, тому попереднє твердження буде видавати
+ // хибний результат всередині функції.
+
+ // Індексація по масиву така ж сама, як і в інших мовах програмування або,
+ // скоріше, як у інших с-подібних мовах.
+ my_array[0]; // => 0
+
+ // Масиви незмінні, це просто частина пам'яті!
+ my_array[1] = 2;
+ printf("%d\n", my_array[1]); // => 2
+
+ // Масиви, розмір яких залежить від змінної, в С99 (та в С11 як вибірковий
+ // функціонал) можуть бути оголошені також. Розмір такого масиву не має бути
+ // константою під час компіляції:
+ printf("Enter the array size: "); // спитати користувача розмір масиву
+ int array_size;
+ fscanf(stdin, "%d", &array_size);
+ int var_length_array[array_size]; // оголосити масив
+ printf("sizeof array = %zu\n", sizeof var_length_array);
+
+ // Приклад:
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
+ // Рядки - це просто масиви символьних літералів (char), що закінчуються NULL
+ // (0x00) байтом, представленим у рядках як спеціальний символ '\0'.
+ // (Не потрібно включати байт NULL в рядкові літерали; компілятор сам вставляє
+ // його наприкінці масиву.)
+ char a_string[20] = "This is a string";
+ printf("%s\n", a_string); // %s форматує рядок
+
+ printf("%d\n", a_string[16]); // => 0
+ // тобто, байт #17 - це 0 (так само, як і 18-ий, 19-ий, та 20-ий)
+
+ // Якщо між одинарними лапками є букви, тоді це символьний літерал.
+ // Він має тип `int`, а не `char` (так історично склалось).
+ int cha = 'a'; // добре
+ char chb = 'a'; // також добре (неявне перетворення з int на char)
+
+ // Багатовимірні масиви:
+ int multi_array[2][5] = {
+ {1, 2, 3, 4, 5},
+ {6, 7, 8, 9, 0}
+ };
+ // Доступ до елементів:
+ int array_int = multi_array[0][2]; // => 3
+
+ ///////////////////////////////////////
+ // Оператори
+ ///////////////////////////////////////
+
+ // Скорочення для багатьох оголошень:
+ int i1 = 1, i2 = 2;
+ float f1 = 1.0, f2 = 2.0;
+
+ int b, c;
+ b = c = 0;
+
+ // Арифметичні операції
+ i1 + i2; // => 3
+ i2 - i1; // => 1
+ i2 * i1; // => 2
+ i1 / i2; // => 0 (0.5 округлено до 0)
+
+ // Потрібно перетворити хоча б одну з цілочисельних змінних на float, щоб
+ // отримати результат з плаваючою крапкою
+ (float)i1 / i2; // => 0.5f
+ i1 / (double)i2; // => 0.5 // Так само і для типу double
+ f1 / f2; // => 0.5, з певною точністю
+ // Такі обчислення не є точними
+
+ // Ділення за модулем також є
+ 11 % 3; // => 2, остача від ділення
+
+ // Оператори порівняння ймовірно схожі, проте в С немає логічного типу.
+ // Натомість використовується int.
+ // (Або _Bool або bool в C99.)
+ // 0 - хибно (false), всі інші значення - правда (true). Оператори
+ // порівняння завжди повертають 0 або 1.
+ 3 == 2; // => 0 (false)
+ 3 != 2; // => 1 (true)
+ 3 > 2; // => 1
+ 3 < 2; // => 0
+ 2 <= 2; // => 1
+ 2 >= 2; // => 1
+
+ // C - це не Python, порівняння не утворюють ланцюги.
+ // Попередження: Рядок нижче скомпілюється, але він означає `(0 < a) < 2`.
+ // В даному випадку, це 1, тому що (0 < 1).
+ int between_0_and_2 = 0 < a < 2;
+ // Натомість потрібно використати:
+ int between_0_and_2 = 0 < a && a < 2;
+
+ // Логічні оператори з числами
+ !3; // => 0 (Логічне НЕ)
+ !0; // => 1
+ 1 && 1; // => 1 (Логічне І)
+ 0 && 1; // => 0
+ 0 || 1; // => 1 (Логічне АБО)
+ 0 || 0; // => 0
+
+ // Тернарний вираз з умовою ( ? : )
+ int e = 5;
+ int f = 10;
+ int z;
+ z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
+
+ // Оператори збільшення та зменшення на 1:
+ int j = 0;
+ int s = j++; // Повернути j ПОТІМ збільшити j. (s = 0, j = 1)
+ s = ++j; // Збільшити j ПОТІМ повернути j. (s = 2, j = 2)
+ // так само і для j-- та --j
+
+ // Побітові операції!
+ ~0x0F; // => 0xFFFFFFF0 (побітове заперечення, "перше доповнення", результат
+ // для 32-бітного int)
+ 0x0F & 0xF0; // => 0x00 (побітове І)
+ 0x0F | 0xF0; // => 0xFF (побітове АБО)
+ 0x04 ^ 0x0F; // => 0x0B (побітове XOR)
+ 0x01 << 1; // => 0x02 (побітовий зсув вліво (на 1))
+ 0x02 >> 1; // => 0x01 (побітовий зсув вправо (на 1))
+
+ // Будьте обережними при зсуві цілочисельних значень зі знаком.
+ // Наступні дії дають невизначений результат:
+ // - зсув на біт, що зберігає знак числа (int a = 1 << 31)
+ // - зсув вліво на від'ємне число (int a = -1 << 2)
+ // - зсув на число, що більше за ширину типу
+ // TODO: LHS
+ // - зсув на зміщення, що >= ширині типу в лівій частині виразу:
+ // int a = 1 << 32; // Невизначена поведінка, якщо ширина int 32 біти.
+
+ ///////////////////////////////////////
+ // Структури розгалуження
+ ///////////////////////////////////////
+
+ // Оператор умови
+ if (0) {
+ printf("I am never run\n"); // ніколи не буде виконано
+ } else if (0) {
+ printf("I am also never run\n"); // теж ніколи не буде виконано
+ } else {
+ printf("I print\n"); // це буде надруковано
+ }
+
+ // Цикл з передумовою
+ int ii = 0;
+ while (ii < 10) { // БУДЬ-ЯКЕ значення, що менше 10 - правда.
+ printf("%d, ", ii++); // ii++ збільшує ii на 1 ПІСЛЯ передачі поточного значення.
+ } // => надрукує "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Цикл з післяумовою
+ int kk = 0;
+ do {
+ printf("%d, ", kk);
+ } while (++kk < 10); // ++kk збільшує kk на 1 ПЕРЕД передачою поточного значення.
+ // => надрукує "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // Цикл з лічильником
+ int jj;
+ for (jj=0; jj < 10; jj++) {
+ printf("%d, ", jj);
+ } // => виводить "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // *****Додатково*****:
+ // Цикли та функції обов'язково повинні мати тіло. Якщо тіло не потрібно:
+ int i;
+ for (i = 0; i <= 5; i++) {
+ ; // використовуйте крапку з комою, щоб симулювати тіло (пусте твердження)
+ }
+ // Або
+ for (i = 0; i <= 5; i++);
+
+ // Розгалуження з множинним вибором: switch()
+ switch (a) {
+ case 0: // значення повинні бути *константними* виразами і мати вбудований тип
+ //(наприклад, перелічення)
+ printf("Hey, 'a' equals 0!\n");
+ break; // якщо не використати break, то управління буде передано наступному блоку
+ case 1:
+ printf("Huh, 'a' equals 1!\n");
+ break;
+ // Будьте обережними, виконання продовжиться до тих пір, поки
+ // не зустрінеться наступний "break".
+ case 3:
+ case 4:
+ printf("Look at that.. 'a' is either 3, or 4\n");
+ break;
+ default:
+ // якщо вираз a не співпадає з описаними значеннями, то виконується
+ // блок default
+ fputs("Error!\n", stderr);
+ exit(-1);
+ break;
+ }
+ /*
+ Використання "goto" в С
+ */
+ typedef enum { false, true } bool;
+ // вводимо таке перелічення, оскільки С не має логічного типу до С99
+ bool disaster = false;
+ int i, j;
+ for(i=0;i<100;++i)
+ for(j=0;j<100;++j)
+ {
+ if((i + j) >= 150)
+ disaster = true;
+ if(disaster)
+ goto error;
+ }
+ error :
+ printf("Error occurred at i = %d & j = %d.\n", i, j);
+ /*
+ https://ideone.com/GuPhd6
+ Даний приклад виведе "Error occurred at i = 51 & j = 99."
+ */
+
+ ///////////////////////////////////////
+ // Приведення до типів
+ ///////////////////////////////////////
+
+ // Кожне значенння в С має тип, але можна перевести значення з одного типу в
+ // інший, якщо потрібно (із деякими обмеженнями).
+
+ int x_hex = 0x01; // Змінним можна присвоювати літерали в шістнадцятковій
+ // системі числення
+
+ // Приведення до типу призведе до спроби зберегти чисельне значення
+ printf("%d\n", x_hex); // => Виводить 1
+ printf("%d\n", (short) x_hex); // => Виводить 1
+ printf("%d\n", (char) x_hex); // => Виводить 1
+
+ // В данному випадку попередження не виникатиме, якщо значення виходить за межі
+ // значення типу
+ printf("%d\n", (unsigned char) 257); // => 1 (максимальне значення char = 255,
+ // якщо char має довжину 8 біт)
+
+ // Для того, щоб дізнатись максимальний розмір `char`, `signed char` або ж
+ // `unsigned char`, потрібно використати макроси CHAR_MAX, SCHAR_MAX та UCHAR_MAX
+ // відповідно з <limits.h>.
+
+ // Вбудовані типи можуть бути приведені до типу із плаваючою крапкою і навпаки.
+ printf("%f\n", (double) 100); // %f завжди перетворює число на double...
+ printf("%f\n", (float) 100); // ...навіть, якщо це float.
+ printf("%d\n", (char)100.0);
+
+ ///////////////////////////////////////
+ // Вказівники
+ ///////////////////////////////////////
+
+ // Вказівник - це змінна, що зберігає адресу у пам'яті. Оголошення вказівника
+ // також потребує інформації про тип об'єкта, на який він вказує. Можна
+ // отримати адресу пам'яті будь-якої змінної, а потім працювати з нею.
+
+ int x = 0;
+ printf("%p\n", (void *)&x); // Оператор & повертає адресу змінної у пам'яті
+ // (%p форматує об'єкт вказівника типу void *)
+ // => Виводить деяку адресу в пам'яті
+
+ // Для оголошення вказівника потрібно поставити * перед його назвою.
+ int *px, not_a_pointer; // px - це вказівник на цілочисельне значення (int)
+ px = &x; // Зберігає адресу змінної x в px
+ printf("%p\n", (void *)px); // => Виводить адресу в пам'яті
+ printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
+ // => Виводить "8, 4" на звичайній 64-бітній системі
+
+ // Щоб прочитати значення, яке зберігається за адресою, на яку вказує вказівник,
+ // потрібно поставити знак * перед назвою змінної.
+ // Так, * використовується одночасно і для оголошення вказівника, і для отримання
+ // значення за адресою. Звучить заплутано, проте тільки спочатку.
+ printf("%d\n", *px); // => Виводить 0, значення x
+
+ // Можна також змінити значення, на яке посилається вказівник.
+ // Тут звернення до адреси обернене у круглі дужки, тому що
+ // ++ має вищий пріоритет виконання, ніж *.
+ (*px)++; // Збільшити значення, на яке вказує px, на 1
+ printf("%d\n", *px); // => Виводить 1
+ printf("%d\n", x); // => Виводить 1
+
+ // Масиви зручно використовувати для виділення неперервного блоку пам'яті.
+ int x_array[20]; // оголошує масив з 20 елементів (розмір можна задати лише один раз)
+ int xx;
+ for (xx = 0; xx < 20; xx++) {
+ x_array[xx] = 20 - xx;
+ } // Ініціалізує x_array значеннями 20, 19, 18,... 2, 1
+
+ // Оголосити вказівник типу int, який посилається на масив x_array
+ int* x_ptr = x_array;
+ // x_ptr тепер вказує на перший елемент масиву (число 20).
+ //
+ // Це працює, тому що при зверненні до імені масиву повертається вказівник
+ // на перший елемент. Наприклад, коли масив передається у функцію або присвоюється
+ // вказівнику, він неявно приводиться до вказівника.
+ // Виключення:
+ // - коли вказівник передається як аргумент із оператором `&`:
+ int arr[10];
+ int (*ptr_to_arr)[10] = &arr; // &arr НЕ має тип `int *`!
+ // Він має тип "вказівник на масив" (з 10 чисел).
+ // - коли масив - це рядковий літерал, що використовується для ініціалізації
+ // масив символів:
+ char otherarr[] = "foobarbazquirk";
+ // - коли масив - це аргумент операторів `sizeof` або `alignof`:
+ int arraythethird[10];
+ int *ptr = arraythethird; // те ж саме, що з int *ptr = &arr[0];
+ printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr));
+ // Ймовірно, виводить "40, 4" або "40, 8"
+
+ // Інкрементація та декрементація вказівника залежить від його типу.
+ // (так звана арифметика вказівників)
+ printf("%d\n", *(x_ptr + 1)); // => Виводить 19
+ printf("%d\n", x_array[1]); // => Виводить 19
+
+ // Можна також динамічно виділити послідовні блоки в пам'яті за допомогою
+ // функції malloc зі стандартної бібліотеки. malloc приймає один аргумент типу
+ // size_t, що описує кількість байтів для виділення (зазвичай із купи, проте це
+ // може бути неправдою на вбудованих системах - стандарт С нічого про це не повідомляє).
+ int *my_ptr = malloc(sizeof(*my_ptr) * 20);
+ for (xx = 0; xx < 20; xx++) {
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
+ } // Проініціалізувати пам'ять значеннями 20, 19, 18, 17... 2, 1 (як int)
+
+ // Будьте обережними із передачею значень, що надаються користувачем, в malloc!
+ // Про всяк випадок, використовуйте calloc в таких ситуаціях (який, на відміну від
+ // malloc, також заповнює пам'ять нулями).
+ int* my_other_ptr = calloc(20, sizeof(int));
+
+ // Немає стандартного способу визначити розмір динамічно виділеного масиву в С.
+ // Через це, якщо масиви будуть часто передаватись в програмі, потрібна інша змінна,
+ // яка буде відслідковувати кількість елементів в масиві. Детальніше в розділі
+ // про функції.
+ size_t size = 10;
+ int *my_arr = calloc(size, sizeof(int));
+ // Додати елемент до масиву.
+ size++;
+ my_arr = realloc(my_arr, sizeof(int) * size);
+ if (my_arr == NULL) {
+ // Не забувайте перевіряти результат виконання realloc на помилки!
+ return
+ }
+ my_arr[10] = 5;
+
+ // Робота з вказівниками може призводити до неочікуваних і непрогнозованих
+ // результатів, якщо звернутись до пам'яті, що не була виділена вами.
+ printf("%d\n", *(my_ptr + 21)); // => Хто зна, що буде виведено.
+ // Може навіть вилетіти з помилкою.
+
+ // Після закінчення роботи із виділеною за допомогою malloc пам'яттю, її обов'язково
+ // потрібно звільнити. Інакше ніхто не зможе нею скористатися, аж поки програма не
+ // завершить свою роботу (така ситуація називається "витоком пам'яті").
+ free(my_ptr);
+
+ // Рядки - це масиви символів, проте вони найчастіше представлені як
+ // вказівник на символ (тобто, вказівник на перший елемент масиву). Вважається
+ // хорошим підходом використовувати `const char *', посилаючись на об'єкт
+ // рядка, оскільки його не можна змінити ("foo"[0] = 'a' ЗАБОРОНЕНО).
+ const char *my_str = "This is my very own string literal";
+ printf("%c\n", *my_str); // => 'T'
+
+ // Це не працюватиме, якщо рядок - це масив (потенційно створений за допомогою
+ // рядкового літерала), що зберігається у частині пам'яті, яку можна перезаписувати:
+ char foo[] = "foo";
+ foo[0] = 'a'; // Дозволяється, foo тепер містить "aoo"
+
+ function_1();
+} // Кінець функції main
+
+///////////////////////////////////////
+// Функції
+///////////////////////////////////////
+
+// Синтаксис оголошення функції:
+// <тип повернення> <назва функції>(<аргументи>)
+
+int add_two_ints(int x1, int x2)
+{
+ return x1 + x2; // Використовуйте return, щоб повернути значення
+}
+
+/*
+Дані у функцію передають за значенням. Коли функція викликається, аргументи, що
+передаються у функцію, копіюються з оригіналів (окрім масивів). Всі зміни над
+значенням аргументів всередині функції не впливають на значення оригіналів.
+
+Використовуйте вказівники, якщо потрібно редагувати безпосередньо оригінальні
+значення аргументів.
+
+Приклад: замінити рядок на обернений.
+*/
+
+// void означає, що функція нічого не повертає
+void str_reverse(char *str_in)
+{
+ char tmp;
+ size_t ii = 0;
+ size_t len = strlen(str_in); // `strlen()` це частина стандартної бібліотеки С
+ // Зауважте: довжина, яку повертає `strlen`, не включає
+ // термінальний NULL байт ('\0')
+ for (ii = 0; ii < len / 2; ii++) { // в C99 можна напряму оголошувати тип `ii` в циклі
+ tmp = str_in[ii];
+ str_in[ii] = str_in[len - ii - 1]; // ii-й символ з кінця
+ str_in[len - ii - 1] = tmp;
+ }
+}
+// Зауважте: для використання strlen() потрібно завантажити файл заголовку string.h
+
+/*
+char c[] = "This is a test.";
+str_reverse(c);
+printf("%s\n", c); // => ".tset a si sihT"
+*/
+/*
+Оскільки можна повертати тільки одну змінну, для зміни значення більшої
+кількості змінних можна використовувати виклик за посиланням
+*/
+void swapTwoNumbers(int *a, int *b)
+{
+ int temp = *a;
+ *a = *b;
+ *b = temp;
+}
+/*
+int first = 10;
+int second = 20;
+printf("first: %d\nsecond: %d\n", first, second);
+swapTwoNumbers(&first, &second);
+printf("first: %d\nsecond: %d\n", first, second);
+// змінні обмінюються значеннями
+*/
+
+/*
+Масиви завжди передаються у функції як вказівники, не зважаючи на тип масиву
+(статичний чи динамічний). Тому всередині функція не знає про розмір масиву.
+*/
+// Розмір масиву завжди має передаватись разом із масивом!
+void printIntArray(int *arr, size_t size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ printf("arr[%d] is: %d\n", i, arr[i]);
+ }
+}
+/*
+int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+int size = 10;
+printIntArray(my_arr, size);
+// виведе "arr[0] is: 1" і т.д.
+*/
+
+// Ключове слово extern використовується, якщо всередині функції потрібно звернутись
+// до змінної, що була оголошена поза функцією.
+int i = 0;
+void testFunc() {
+ extern int i; // використовуємо зовнішню змінну i
+}
+
+// Зробити зовнішню змінну приватною у вихідному файлі за допомогою static:
+static int j = 0; // інші файли, що використовують testFunc2(),
+ // не матимуть доступу до змінної j
+void testFunc2() {
+ extern int j;
+}
+// Ключове слово static робить змінну недоступною для коду поза даною одиницею
+// компіляції. (На більшості систем, одиниця компіляції - це файл).
+// static можна використовувати до глобальних змінних, функцій, локальних
+// змінних у функціях. Локальні змінні, проініціалізовані static, поводять
+// себе як глобальні змінні, проте тільки в межах даного файлу. Статичні
+// змінні ініціалізуються 0, якщо інше значення не було вказане.
+// **Як варіант, функції можна зробити приватними оголосивши їх як static**
+
+///////////////////////////////////////
+// Користувацькі типи та структури
+///////////////////////////////////////
+
+// Ключове слово typedef використовується, щоб створити псевдонім типу
+typedef int my_type;
+my_type my_type_var = 0;
+
+// Структури - це такі собі колекції з даними. Пам'ять для полів виділяється
+// послідовно, в порядку їх написання:
+struct rectangle {
+ int width;
+ int height;
+};
+
+// Проте це не означає, що
+// sizeof(struct rectangle) == sizeof(int) + sizeof(int)
+// в зв'язку з вирівнюванням пам'яті [1]
+
+void function_1()
+{
+ struct rectangle my_rec;
+
+ // Доступ до полів структури відбувається через .
+ my_rec.width = 10;
+ my_rec.height = 20;
+
+ // Можна створити вказівники на структуру
+ struct rectangle *my_rec_ptr = &my_rec;
+
+ // Звернення до структури через вказівник та зміна значень поля:
+ (*my_rec_ptr).width = 30;
+
+ // Але є й альтернативний спосіб звернутись до поля через вказівник, використовуючи
+ // оператор -> (краще читається)
+ my_rec_ptr->height = 10; // Те ж саме, що (*my_rec_ptr).height = 10;
+}
+
+// Можна використати typedef перед struct
+typedef struct rectangle rect;
+
+int area(rect r)
+{
+ return r.width * r.height;
+}
+
+// Якщо ваша структура доволі громіздка, можна звертатись до неї через вказівник,
+// щоб уникнути копіювання всієї структури:
+int areaptr(const rect *r)
+{
+ return r->width * r->height;
+}
+
+///////////////////////////////////////
+// Вказівники на функції
+///////////////////////////////////////
+/*
+Під час виконання функції знаходяться за відомими адресами в пам'яті. Вказівники
+на функції - це ті ж самі вказівники, що зберігають адресу у пам'яті, проте можуть
+використовуватись, щоб викликати функції напряму і передавати обробники (або функції зі
+зворотнім зв'язком). Хоча, синтаксис спочатку може бути доволі незрозумілим.
+
+Приклад: use str_reverse from a pointer
+*/
+void str_reverse_through_pointer(char *str_in) {
+ // Оголосити вказівник на функцію під назвою f.
+ void (*f)(char *); // Сигнатура повинна точно співпадати із цільовою функцією.
+ f = &str_reverse; // Присвойте адресу певної функції (визначається під час виконання)
+ // f = str_reverse; повинно працювати також
+ (*f)(str_in); // Виклик функції через вказівник
+ // f(str_in); // Це альтернативний, але теж вірний синтаксис виклику функції.
+}
+
+/*
+Якщо сигнатури функцій співпадають, можна присвоїти будь-яку функцію тому ж
+самому вказівнику. Вказівники на функції зазвичай використовуються як псевдоніми
+для спрощення та покращення читабельності коду. Приклад:
+*/
+
+typedef void (*my_fnp_type)(char *);
+
+// Використання при оголошенні змінної вказівника:
+// ...
+// my_fnp_type f;
+
+
+// Спеціальні символи:
+/*
+'\a'; // символ попередження (дзвінок)
+'\n'; // символ нового рядка
+'\t'; // символ табуляції (вирівнювання по лівому краю)
+'\v'; // вертикальна табуляція
+'\f'; // нова сторінка
+'\r'; // повернення каретки
+'\b'; // стирання останнього символу
+'\0'; // нульовий символ. Зазвичай розташовується в кінці рядка.
+// hello\n\0. \0 використовується для позначення кінця рядка.
+'\\'; // зворотній слеш
+'\?'; // знак питання
+'\''; // одинарні лапки
+'\"'; // подвійні лапки
+'\xhh'; // шістнадцяткове число. Наприклад: '\xb' = символ вертикальної табуляції
+'\0oo'; // вісімкове число. Наприклад: '\013' = символ вертикальної табуляції
+
+// форматування виводу:
+"%d"; // ціле число (int)
+"%3d"; // ціле число, щонайменше 3 символи (вирівнювання по правому краю)
+"%s"; // рядок
+"%f"; // число з плаваючою крапкою (float)
+"%ld"; // велике ціле число (long)
+"%3.2f"; // число з плаваючою крапкою, щонайменше 3 цифри зліва і 2 цифри справа
+"%7.4s"; // (аналогічно для рядків)
+"%c"; // символ
+"%p"; // вказівник. Зазначте: потребує перетворення типу на (void *) перед
+ // використанням у `printf`.
+"%x"; // шістнадцяткове число
+"%o"; // вісімкове число
+"%%"; // друкує %
+*/
+
+///////////////////////////////////////
+// Порядок виконання
+///////////////////////////////////////
+
+//---------------------------------------------------//
+// Оператори | Асоціативність//
+//---------------------------------------------------//
+// () [] -> . | зліва направо //
+// ! ~ ++ -- + = *(type)sizeof | справа наліво //
+// * / % | зліва направо //
+// + - | зліва направо //
+// << >> | зліва направо //
+// < <= > >= | зліва направо //
+// == != | зліва направо //
+// & | зліва направо //
+// ^ | зліва направо //
+// | | зліва направо //
+// && | зліва направо //
+// || | зліва направо //
+// ?: | справа наліво //
+// = += -= *= /= %= &= ^= |= <<= >>= | справа наліво //
+// , | зліва направо //
+//---------------------------------------------------//
+
+/****************************** Файли заголовків *********************************
+
+Файли заголовків важливі в С. Вони розділяють вихідний код та визначення на різні
+файли, що робить їх кращими для розуміння.
+
+Файли заголовків синтаксично подібні до вихідних файлів С, проте описуються у".h"
+файлах. Їх можна додати в код за допомогою директиви #include "example.h", якщо
+example.h існує в тому ж каталозі, що і файл С.
+*/
+
+/*
+Так можна запобігти тому, що заголовок буде оголошений кілька разів. Така ситуація
+виникає у випадку циклічної залежності, тобто коли вміст заголовку вже було
+оголошено.
+*/
+#ifndef EXAMPLE_H /* якщо EXAMPLE_H ще не оголошено. */
+#define EXAMPLE_H /* Визначити макрос EXAMPLE_H. */
+
+/*
+Заголовки можна додавати в інші заголовки, таким чином вони разом додаються
+у подальшому.
+*/
+#include <string.h>
+
+/*
+Макроси можуть бути визначені також у заголовку та використовуватись у файлах,
+що містять цей заголовок.
+*/
+#define EXAMPLE_NAME "Dennis Ritchie"
+
+/* Макроси функції також можна визначити. */
+#define ADD(a, b) ((a) + (b))
+/*
+Зверніть увагу на круглі дужки навколо аргументів! Важливо переконатись, що
+a та b не можна проінтерпретувати інакше. Наприклад:
+MUL(x, y) (x * y);
+MUL(1 + 2, 3) -> (1 + 2 * 3), що є помилкою
+*/
+
+/* Struct та typedef можуть використовуватись для узгодженості між файлами. */
+typedef struct Node
+{
+ int val;
+ struct Node *next;
+} Node;
+
+/* Так само і перелічення. */
+enum traffic_light_state {GREEN, YELLOW, RED};
+
+/*
+Прототипи функцій також можна оголосити так, щоб використовувати у кількох
+файлах. Але так робити не варто. Краще оголосити їх у С файлі.
+*/
+Node createLinkedList(int *vals, int len);
+
+/*
+Окрім вище згаданих випадків, всі інші визначення мають описуватись у С файлах.
+*/
+
+#endif /* Кінець директиви передкомпіляції if. */
+
+```
+## Додаткові матеріали
+
+Кращим посібником для вивчення С буде книга авторства Деніса Рітчі (творець С) та Браяна Кернігана,
+[K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language).
+Але обережно з нею, книга старезна і містить неточності (ідеї, що вже вважаються не надто прийнятними).
+
+Ще одним хорошим ресурсом є книга "Learn C The Hard Way" (наявна тільки англійською).
+
+На деякі часті запитання дасть відповідь англомовний ресурс [compl.lang.c Frequently Asked Questions](http://c-faq.com).
+
+Нагадаю, що важливо використовувати правильні інтервали, відступи та загалом мати узгоджений стиль коду.
+Зручний для читання код краще, ніж складний код або зроблений нашвидкоруч. За прикладом можна звернутись до
+[Linux kernel coding style](https://www.kernel.org/doc/Documentation/process/coding-style.rst).
+
+Щодо всього іншого, Ґуґл на допомогу!
+
+[1] [Чому розмір структури не дорівнює сумі розмірів її полів? (англ.)](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)
diff --git a/uk-ua/ruby-ua.html.markdown b/uk-ua/ruby-ua.html.markdown
index 74346dfe..a71c30bc 100644
--- a/uk-ua/ruby-ua.html.markdown
+++ b/uk-ua/ruby-ua.html.markdown
@@ -622,4 +622,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 8bc334ab..4656cf38 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -7,7 +7,7 @@ lang: vi-vn
filename: LearnObjectiveC-vi.m
---
-Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
+Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành macOS, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
```objective-c
diff --git a/vim.html.markdown b/vim.html.markdown
index 5b84a3ea..55649cb2 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -13,6 +13,9 @@ editor designed for speed and increased productivity, and is ubiquitous in most
unix-based systems. It has numerous keybindings for speedy navigation to
specific points in the file, and for fast editing.
+`vimtutor` is a an excellent application that teaches you how to use `Vim`. It comes with the vim package during installation. You should be able to just run "vimtutor" on the command line to open this tutor. It will guide you through all the major features in `vim`.
+
+
## Basics of navigating Vim
```
@@ -24,6 +27,7 @@ specific points in the file, and for fast editing.
ZZ # Save file and quit vim
:q! # Quit vim without saving file
# ! *forces* :q to execute, hence quiting vim without saving
+ ZQ # Quit vim without saving file
:x # Save file and quit vim, shorter version of :wq
u # Undo
@@ -181,6 +185,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
~ # Toggle letter case of selected text
u # Selected text to lower case
U # Selected text to upper case
+ J # Join the current line with the next line
# Fold text
zf # Create fold from selected text
diff --git a/wasm.html.markdown b/wasm.html.markdown
index aba2084f..81344abe 100644
--- a/wasm.html.markdown
+++ b/wasm.html.markdown
@@ -61,7 +61,7 @@ contributors:
;; We have to use the right data type for each operation:
;; (local.set $mult_result (f32.mul (f32.const 2.0) (f32.const 4.0))) ;; WRONG! mult_result is f64!
- (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0))) ;; WRONG! mult_result is f64!
+ (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0)))
;; WebAssembly has some builtin operations, like basic math and bitshifting.
;; Notably, it does not have built in trigonometric functions.
diff --git a/xml.html.markdown b/xml.html.markdown
index b4b54330..2a258d94 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -100,8 +100,9 @@ This is what makes XML versatile. It is human readable too. The following docume
A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed.
+Declaring a DTD externally:
+
```xml
-<!-- Declaring a DTD externally: -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "Bookstore.dtd">
<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path
@@ -114,8 +115,11 @@ A XML document is *well-formed* if it is syntactically correct. However, it is p
<price>30.00</price>
</book>
</bookstore>
+```
-<!-- The DTD file: -->
+The DTD file (Bookstore.dtd):
+
+```
<!ELEMENT bookstore (book+)>
<!-- The bookstore element may contain one or more child book elements. -->
<!ELEMENT book (title, price)>
@@ -128,10 +132,11 @@ A XML document is *well-formed* if it is syntactically correct. However, it is p
only contain text which is read by the parser and must not contain children.
Compare with CDATA, or character data. -->
<!ELEMENT price (#PCDATA)>
-]>
+```
-<!-- The DTD could be declared inside the XML file itself.-->
+The DTD could be declared inside the XML file itself:
+```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore [
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 4f10a128..6dc5905e 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -127,11 +127,11 @@ base: &base
# indicate that all the keys of one or more specified maps should be inserted
# into the current map.
-foo: &foo
+foo:
<<: *base
age: 10
-bar: &bar
+bar:
<<: *base
age: 20
@@ -184,5 +184,5 @@ set2:
### More Resources
-+ [YAML official website](http://yaml.org/)
++ [YAML official website](https://yaml.org/)
+ [Online YAML Validator](http://www.yamllint.com/)
diff --git a/zh-cn/asciidoc-cn.html.md b/zh-cn/asciidoc-cn.html.md
new file mode 100644
index 00000000..74eed445
--- /dev/null
+++ b/zh-cn/asciidoc-cn.html.md
@@ -0,0 +1,135 @@
+---
+language: asciidoc
+filename: asciidoc-cn.md
+contributors:
+ - ["Ryan Mavilia", "http://unoriginality.rocks/"]
+ - ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
+translators:
+ - ["Liu Yihua", "https://github.com/yihuajack"]
+lang: zh-cn
+---
+
+AsciiDoc 是一种类似于 Markdown 的标记语言,它可以用来写从书到博客的任何东西。它由 Stuart Rackham 在 2002 年发明,它的语言很简单,但同时也可以有丰富的定制。
+
+文档标题
+
+标题是可选的,且不可以包含空行。它必须离正文空出至少一个空行。
+
+仅标题
+
+```
+= 文档标题
+
+文档的第一句话。
+```
+
+标题和作者
+
+```
+= 文档标题
+张三 <san.zhang@learnxinyminutes.com>
+
+文档开始。
+```
+
+多名作者的情形
+
+```
+= 文档标题
+李四 <si@go.com>; 王五 <wu@yo.com>; 赵六 <xzhao@pirate.com>
+
+有多名作者的文档开始。
+```
+
+版本行(需要作者行)
+
+```
+= 文档标题(第一版)
+土豆人 <chip@crunchy.com>
+v1.0, 2016-01-13
+
+这篇关于炸薯条的文章会很有趣。
+```
+
+段落
+
+```
+段落不需要什么特别操作。
+
+在两段之间用一个空行隔开。
+
+当你需要换行时,添加一个 +
+你就会得到一个换行符!
+```
+
+文本格式化
+
+```
+_用下划线创建斜体_
+*用星号加粗*
+*_组合起来用更有趣_*
+`用重音符显示等宽字体`
+`*加粗等宽字体*`
+```
+
+节标题
+
+```
+= 第 0 级 (一般只用于文档标题)
+
+== 第 1 级 <h2>
+
+=== 第 2 级 <h3>
+
+==== 第 3 级 <h4>
+
+===== 第 4 级 <h5>
+
+```
+
+列表
+
+用星号创建无序列表。
+
+```
+* 甲
+* 乙
+* 丙
+```
+
+用句点创建有序列表。
+
+```
+. 项目 1
+. 项目 2
+. 项目 3
+```
+
+你可以用额外的星号或句点来嵌套最多五次列表。
+
+```
+* 甲 1
+** 甲 2
+*** 甲 3
+**** 甲 4
+***** 甲 5
+
+. 甲 1
+.. 甲 2
+... 甲 3
+.... 甲 4
+..... 甲 5
+```
+
+## 补充材料
+
+处理 AsciiDoc 文档有两种工具:
+
+1. [AsciiDoc](http://asciidoc.org/): 原版的 Python 实现,在主流 Linux 发行版中已附带,目前处于稳定版本维护模式。
+2. [Asciidoctor](http://asciidoctor.org/): 使用 Ruby 的另一种实现,也可以从 Java 和 JavaScript 中使用。它处于积极的开发中,目标是用新特性和输出格式扩展 AsciiDoc 的语法。
+
+以下是 `Asciidoctor` 实现的相关链接:
+
+* [Markdown - AsciiDoc 语法比较](http://asciidoctor.org/docs/user-manual/#comparison-by-example):并列比较一般 Markdown 和 AsciiDoc 的元素。
+* [入门](http://asciidoctor.org/docs/#get-started-with-asciidoctor):安装和快速启动指南,帮助构建简单的文档。
+* [Asciidoctor 用户手册](http://asciidoctor.org/docs/user-manual/): 完整的单文档指南,包含语法参考、示例、渲染工具等。
diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown
index d85e5b8f..225df06b 100644
--- a/zh-cn/bash-cn.html.markdown
+++ b/zh-cn/bash-cn.html.markdown
@@ -18,7 +18,7 @@ filename: LearnBash-cn.sh
lang: zh-cn
---
-Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的默认 shell。
+Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 macOS 下的默认 shell。
以下大多数例子可以作为脚本的一部分运行,也可直接在 shell 下交互执行。
[更多信息](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 8eecc56e..dbad5030 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -128,7 +128,7 @@ printf("Enter the array size: "); // 询问用户数组长度
char buf[0x100];
fgets(buf, sizeof buf, stdin);
-// stroul 将字符串解析为无符号整数
+// strtoul 将字符串解析为无符号整数
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // 声明VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
@@ -616,7 +616,7 @@ typedef void (*my_fnp_type)(char *);
如果你有问题,请阅读[compl.lang.c Frequently Asked Questions](http://c-faq.com/)。
-使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/CodingStyle)
+使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/process/coding-style.rst)
除了这些,多多Google吧
diff --git a/zh-cn/cmake-cn.html.markdown b/zh-cn/cmake-cn.html.markdown
new file mode 100644
index 00000000..dd9961ca
--- /dev/null
+++ b/zh-cn/cmake-cn.html.markdown
@@ -0,0 +1,168 @@
+---
+category: tool
+tool: cmake
+contributors:
+ - ["Bruno Alano", "https://github.com/brunoalano"]
+translators:
+ - ["tx23", "https://github.com/tx23"]
+filename: CMake-cn
+lang: zh-cn
+---
+
+CMake 是一个跨平台且开源的自动化构建系统工具。通过该工具你可以对你的源代码进行测试、编译或创建安装包。
+
+CMake 试图去解决Makefile 跨平台的自动配置问题(不同的make解释器有不同的命令),以及链接第三方库时的易用性问题。
+
+CMake是一个可扩展的开源系统,它以操作系统和与编译器无关的方式管理构建过程。与其他许多跨平台系统不同的是,
+CMake被设计为与本机的构建环境结合使用。它通过被放置于每个源文件目录下的简单配置文件(名为 CMakeLists.txt 的文件)
+来生成常规使用的标准构建文件(比如:Unix 下的 makefiles 文件或 Windows MSVC 中的 projects/workspaces)。
+
+```cmake
+# 在 CMake 中, 这是一条命令
+
+# 要运行我们的代码,请执行以下命令:
+# - mkdir build && cd build
+# - cmake ..
+# - make
+#
+# 通过上述命令,我们将遵循最佳实践在子目录中进行编译
+# 在第二行命令中我们请求Cmake 生成新的依赖于系统的Makefile文件。
+# 最后,我们运行本地的make 命令。
+
+#------------------------------------------------------------------------------
+# 基础部分
+#------------------------------------------------------------------------------
+#
+# Cmake文件必须被命令为 “CMakeLists.txt” 。
+
+# 设置生成Makefile的CMake所需最低版本要求
+cmake_minimum_required (VERSION 2.8)
+
+# 当版本小于2.8时,需要加入关键字 FATAL_ERROR。
+cmake_minimum_required (VERSION 2.8 FATAL_ERROR)
+
+# 在这里定义了项目的名称,同时会影响Cmake 生成的目录命名约定。
+# 我们可以将代码的语言作为第二个参数传入。
+project (learncmake C)
+
+# 设置项目的源目录(仅仅是由于惯例)
+set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} )
+set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} )
+
+# 在构建系统中用“semver”风格为我们代码设置当前版本是很有用的。
+set (LEARN_CMAKE_VERSION_MAJOR 1)
+set (LEARN_CMAKE_VERSION_MINOR 0)
+set (LEARN_CMAKE_VERSION_PATCH 0)
+
+# 将变量(版本号)发送到源代码头
+configure_file (
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+)
+
+# 包含目录
+# 在 GCC中, 该语句等同于 "-I" 命令
+include_directories( include )
+
+# 在哪里安装其他库?注意:在此处提供includes路径,后续检查将解决所有其他问题
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
+
+# 条件
+if ( CONDITION )
+ # 输出!
+
+ # 附带信息
+ message(STATUS "My message")
+
+ # CMake 警告,继续处理
+ message(WARNING "My message")
+
+ # CMake 警告 (dev),继续处理
+ message(AUTHOR_WARNING "My message")
+
+ # CMake 错误,继续处理但是会跳过生成
+ message(SEND_ERROR "My message")
+
+ # CMake 错误,停止处理和生成
+ message(FATAL_ERROR "My message")
+endif()
+
+if( CONDITION )
+
+elseif( CONDITION )
+
+else( CONDITION )
+
+endif( CONDITION )
+
+# 循环
+foreach(loop_var arg1 arg2 ...)
+ COMMAND1(ARGS ...)
+ COMMAND2(ARGS ...)
+ ...
+endforeach(loop_var)
+
+foreach(loop_var RANGE total)
+foreach(loop_var RANGE start stop [step])
+
+foreach(loop_var IN [LISTS [list1 [...]]]
+ [ITEMS [item1 [...]]])
+
+while(condition)
+ COMMAND1(ARGS ...)
+ COMMAND2(ARGS ...)
+ ...
+endwhile(condition)
+
+
+# 逻辑运算
+if(FALSE AND (FALSE OR TRUE))
+ message("Don't display!")
+endif()
+
+# 将常规,缓存或环境变量设置为给定值。
+# 如果指定了PARENT_SCOPE选项,则将在当前作用域上的作用域中设置变量
+# `set(<variable> <value>... [PARENT_SCOPE])`
+
+# 如何在带引号和不带引号的参数中引用变量?How to reference variables inside quoted and unquoted arguments?
+# 如果未设置变量,变量引用由变量值或空字符串替换。
+${variable_name}
+
+# 清单
+# 设置源文件列表
+set( LEARN_CMAKE_SOURCES
+ src/main.c
+ src/imagem.c
+ src/pather.c
+)
+
+# 调用编译器
+#
+# ${PROJECT_NAME} 即 Learn_CMake
+add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} )
+
+# 链接库
+target_link_libraries( ${PROJECT_NAME} ${LIBS} m )
+
+# 在哪里安装其他库?注意:在此处提供includes路径,后续检查将解决所有其他问题
+set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
+
+# 编译条件 (gcc ; g++)
+if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" )
+ message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" )
+ add_definitions( --std=c99 )
+endif()
+
+# 检查 OS
+if( UNIX )
+ set( LEARN_CMAKE_DEFINITIONS
+ "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" )
+endif()
+```
+
+### 资源
+
++ [CMake tutorial](https://cmake.org/cmake-tutorial/)
++ [CMake documentation](https://cmake.org/documentation/)
++ [Mastering CMake](http://amzn.com/1930934319/)
++ [An Introduction to Modern CMake](https://cliutils.gitlab.io/modern-cmake/)
diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index 37b4b137..2953acf3 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -40,7 +40,7 @@ import (
func main() {
// 往标准输出打印一行。
// 用包名fmt限制打印函数。
- fmt.Println("天坑欢迎你!")
+ fmt.Println("你好世界")
// 调用当前包的另一个函数。
beyondHello()
diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index c854169e..d653c58c 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -128,7 +128,7 @@ snd ("haskell", 1) -- 1
-- 一个接受两个变量的简单函数
add a b = a + b
--- 注意,如果你使用 ghci (Hakell 解释器),你需要使用 `let`,也就是
+-- 注意,如果你使用 ghci (Haskell 解释器),你需要使用 `let`,也就是
-- let add a b = a + b
-- 调用函数
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index 27003f3e..1de7f3e6 100644
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -297,8 +297,8 @@ class Bicycle {
// Bicycle 类的成员变量和方法
public int cadence; // Public: 任意位置均可访问
private int speed; // Private: 只在同类中可以访问
- protected int gear; // Protected: 可以在同类与子类中可以访问
- String name; // default: 可以在包内中可以访问
+ protected int gear; // Protected: 可以在同类与子类中访问
+ String name; // default: 可以在包内访问
// 构造函数是初始化一个对象的方式
// 以下是一个默认构造函数
diff --git a/zh-cn/make-cn.html.markdown b/zh-cn/make-cn.html.markdown
index 76dde941..641714ef 100644
--- a/zh-cn/make-cn.html.markdown
+++ b/zh-cn/make-cn.html.markdown
@@ -23,7 +23,7 @@ Makefile 用于定义如何创建目标文件, 比如如何从源码到可执行
```make
# 这行表示注释
-# 文件名一定要交 Makefile, 大小写区分, 使用 `make <target>` 生成 target
+# 文件名一定要叫 Makefile, 大小写区分, 使用 `make <target>` 生成 target
# 如果想要取别的名字, 可以用 `make -f "filename" <target>`.
# 重要的事情 - 只认识 TAB, 空格是不认的, 但是在 GNU Make 3.82 之后, 可以通过
@@ -87,7 +87,7 @@ ex0.txt ex1.txt: maker
maker:
touch ex0.txt ex1.txt
-# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显示的指明哪些 targets 是 phony
+# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显式地指明哪些 targets 是 phony
.PHONY: all maker process
# This is a special target. There are several others.
@@ -116,7 +116,7 @@ process: ex1.txt file0.txt
# 模式匹配
#-----------------------------------------------------------------------
-# 可以让 make 知道如何转换某些文件到别格式
+# 可以让 make 知道如何转换某些文件到其他格式
# 比如 从 svg 到 png
%.png: %.svg
inkscape --export-png $^
@@ -149,7 +149,7 @@ echo:
@echo $(name)
@echo ${name2}
@echo $name # 这个会被蠢蠢的解析成 $(n)ame.
- @echo \"$(name3)\" # 为声明的变量或扩展成空字符串.
+ @echo \"$(name3)\" # 未声明的变量会被处理成空字符串.
@echo $(name4)
@echo $(name5)
# 你可以通过4种方式设置变量.
diff --git a/zh-cn/mips-cn.html.markdown b/zh-cn/mips-cn.html.markdown
new file mode 100644
index 00000000..83888338
--- /dev/null
+++ b/zh-cn/mips-cn.html.markdown
@@ -0,0 +1,334 @@
+---
+language: "MIPS Assembly"
+filename: MIPS-cn.asm
+contributors:
+ - ["Stanley Lim", "https://github.com/Spiderpig86"]
+translators:
+ - ["Liu Yihua", "https://github.com/yihuajack"]
+lang: zh-cn
+---
+
+MIPS(Microprocessor without Interlocked Pipeline Stages)汇编语言是为了配合约翰·雷洛伊·亨尼西于1981年设计的 MIPS 微处理器范式而设计的,这些 RISC 处理器用于嵌入式系统,例如网关和路由器。
+
+[阅读更多](https://en.wikipedia.org/wiki/MIPS_architecture)
+
+```asm
+# 注释用一个 '#' 表示
+
+# 一行中 '#' 之后的所有文本都会被汇编器的词法分析器忽略
+
+# 程序通常包含 .data 和 .text 部分
+
+.data # 数据存储在内存中(在RAM中分配)
+ # 类似于高级语言中的变量
+
+ # 声明遵循( 标签: .类型 值 )的声明形式
+ hello_world: .asciiz "Hello World\n" # 声明一个 null 结束的字符串
+ num1: .word 42 # 整数被视为字
+ # (32位值)
+
+ arr1: .word 1, 2, 3, 4, 5 # 字数组
+ arr2: .byte 'a', 'b' # 字符数组(每个1字节)
+ buffer: .space 60 # 在 RAM 中分配空间
+ # (不清除为0)
+
+ # 数据类型的大小
+ _byte: .byte 'a' # 1字节
+ _halfword: .half 53 # 2字节
+ _word: .word 3 # 4字节
+ _float: .float 3.14 # 4字节
+ _double: .double 7.0 # 8字节
+
+ .align 2 # 数据的内存对齐
+ # 其中数字(应是2的幂)表示几字节对齐
+ # .align 2 表示字对齐(因为 2^2 = 4 字节)
+
+.text # 这部分包括指令和程序逻辑
+.globl _main # 声明一个全局指令标签
+ # 其他文件都可以访问
+
+ _main: # MIPS 程序按顺序执行指令
+ # 这条标签下的代码将首先执行
+
+ # 打印 "hello world"
+ la $a0, hello_world # 加载存储在内存中的字符串地址
+ li $v0, 4 # 加载 syscall 的值
+ # (数字代表要执行哪个 syscall)
+ syscall # 使用给定的参数($a0)执行指定的 syscall
+
+ # 寄存器(用于在程序执行期间保存数据)
+ # $t0 - $t9 # 临时寄存器,用于过程内部的中间计算
+ # (过程调用时不保存)
+
+ # $s0 - $s7 # 保留寄存器(被保留的寄存器,过程调用时保存)
+ # 通常保存在栈中
+
+ # $a0 - $a3 # 参数寄存器,用于传递过程的参数
+ # $v0 - $v1 # 返回寄存器,用于向调用过程返回值
+
+ # 存取指令
+ la $t0, label # 将内存中由 label 指定的值的地址复制到寄存器 $t0 中
+ lw $t0, label # 从内存中复制一个字
+ lw $t1, 4($s0) # 从寄存器中存储的地址复制一个字
+ # 偏移量为4字节(地址 + 4)
+ lb $t2, label # 把一个字节复制到寄存器 $t2 的低阶部分
+ lb $t2, 0($s0) # 从 $s0 的源地址复制一个字节
+ # 偏移量为0
+ # 同理也适用于 'lh' (取半字)
+
+ sw $t0, label # 将字存储到由 label 映射的内存地址中
+ sw $t0, 8($s0) # 将字存储到 $s0 指定的地址中
+ # 偏移量为8字节
+ # 同理也适用于 'sb' (存字)和 'sh' (存半字)。'sa'不存在
+
+### 数学 ###
+ _math:
+ # 记住要将值加载到寄存器中
+ lw $t0, num # 从数据部分
+ li $t0, 5 # 或者从一个立即数(常数)
+ li $t1, 6
+ add $t2, $t0, $t1 # $t2 = $t0 + $t1
+ sub $t2, $t0, $t1 # $t2 = $t0 - $t1
+ mul $t2, $t0, $t1 # $t2 = $t0 * $t1
+ div $t2, $t0, $t1 # $t2 = $t0 / $t1
+ # (MARS 的某些版本可能不支持)
+ div $t0, $t1 # 执行 $t0 / $t1。
+ # 用 'mflo' 得商,用 'mfhi' 得余数
+
+ # 移位
+ sll $t0, $t0, 2 # 按位左移立即数(常数值)2
+ sllv $t0, $t1, $t2 # 根据一个寄存器中的变量值左移相应位
+ srl $t0, $t0, 5 # 按位右移
+ # (不保留符号,用0符号扩展)
+ srlv $t0, $t1, $t2 # 根据一个寄存器中的变量值右移相应位
+ sra $t0, $t0, 7 # 按算术位右移(保留符号)
+ srav $t0, $t1, $t2 # 根据一个寄存器中的变量值右移相应算数位
+
+ # 按位运算符
+ and $t0, $t1, $t2 # 按位与
+ andi $t0, $t1, 0xFFF # 用立即数按位与
+ or $t0, $t1, $t2 # 按位或
+ ori $t0, $t1, 0xFFF # 用立即数按位或
+ xor $t0, $t1, $t2 # 按位异或
+ xori $t0, $t1, 0xFFF # 用立即数按位异或
+ nor $t0, $t1, $t2 # 按位或非
+
+## 分支 ##
+ _branching:
+ # 分支指令的基本格式通常遵循 <指令> <寄存器1> <寄存器2> <标签>
+ # 如果给定的条件求值为真,则跳转到标签
+ # 有时向后编写条件逻辑更容易,如下面的简单的 if 语句示例所示
+
+ beq $t0, $t1, reg_eq # 如果 $t0 == $t1,则跳转到 reg_eq
+ # 否则执行下一行
+ bne $t0, $t1, reg_neq # 当 $t0 != $t1 时跳转
+ b branch_target # 非条件分支,总会执行
+ beqz $t0, req_eq_zero # 当 $t0 == 0 时跳转
+ bnez $t0, req_neq_zero # 当 $t0 != 0 时跳转
+ bgt $t0, $t1, t0_gt_t1 # 当 $t0 > $t1 时跳转
+ bge $t0, $t1, t0_gte_t1 # 当 $t0 >= $t1 时跳转
+ bgtz $t0, t0_gt0 # 当 $t0 > 0 时跳转
+ blt $t0, $t1, t0_gt_t1 # 当 $t0 < $t1 时跳转
+ ble $t0, $t1, t0_gte_t1 # 当 $t0 <= $t1 时跳转
+ bltz $t0, t0_lt0 # 当 $t0 < 0 时跳转
+ slt $s0, $t0, $t1 # 当 $t0 < $t1 时结果为 $s0 (1为真)
+
+ # 简单的 if 语句
+ # if (i == j)
+ # f = g + h;
+ # f = f - i;
+
+ # 让 $s0 = f, $s1 = g, $s2 = h, $s3 = i, $s4 = j
+ bne $s3, $s4, L1 # if (i !=j)
+ add $s0, $s1, $s2 # f = g + h
+
+ L1:
+ sub $s0, $s0, $s3 # f = f - i
+
+ # 下面是一个求3个数的最大值的例子
+ # 从 Java 到 MIPS 逻辑的直接翻译:
+ # if (a > b)
+ # if (a > c)
+ # max = a;
+ # else
+ # max = c;
+ # else
+ # max = b;
+ # else
+ # max = c;
+
+ # 让 $s0 = a, $s1 = b, $s2 = c, $v0 = 返回寄存器
+ ble $s0, $s1, a_LTE_b # 如果 (a <= b) 跳转到 (a_LTE_b)
+ ble $s0, $s2, max_C # 如果 (a > b && a <= c) 跳转到 (max_C)
+ move $v0, $s1 # 否则 [a > b && a > c] max = a
+ j done # 跳转到程序结束
+
+ a_LTE_b: # 当 a <= b 时的标签
+ ble $s1, $s2, max_C # 如果 (a <= b && b <= c) 跳转到 (max_C)
+ move $v0, $s1 # 如果 (a <= b && b > c) max = b
+ j done # 跳转到 done
+
+ max_C:
+ move $v0, $s2 # max = c
+
+ done: # 程序结束
+
+## 循环 ##
+ _loops:
+ # 循环的基本结构是一个退出条件和一个继续执行的跳转指令
+ li $t0, 0
+ while:
+ bgt $t0, 10, end_while # 当 $t0 小于 10,不停迭代
+ addi $t0, $t0, 1 # 累加值
+ j while # 跳转回循环开始
+ end_while:
+
+ # 二维矩阵遍历
+ # 假设 $a0 存储整数 3 × 3 矩阵的地址
+ li $t0, 0 # 计数器 i
+ li $t1, 0 # 计数器 j
+ matrix_row:
+ bgt $t0, 3, matrix_row_end
+
+ matrix_col:
+ bgt $t1, 3, matrix_col_end
+
+ # 执行一些东西
+
+ addi $t1, $t1, 1 # 累加列计数器
+ matrix_col_end:
+
+ # 执行一些东西
+
+ addi $t0, $t0, 1
+ matrix_row_end:
+
+## 函数 ##
+ _functions:
+ # 函数是可调用的过程,可以接受参数并返回所有用标签表示的值,如前所示
+
+ main: # 程序以 main 函数开始
+ jal return_1 # jal 会把当前程序计数器(PC)存储在 $ra
+ # 并跳转到 return_1
+
+ # 如果我们想传入参数呢?
+ # 首先,我们必须将形参传递给参数寄存器
+ li $a0, 1
+ li $a1, 2
+ jal sum # 现在我们可以调用函数了
+
+ # 递归怎么样?
+ # 这需要更多的工作
+ # 由于 jal 会自动覆盖每次调用,我们需要确保在 $ra 中保存并恢复之前的程序计数器
+ li $a0, 3
+ jal fact
+
+ li $v0, 10
+ syscall
+
+ # 这个函数返回1
+ return_1:
+ li $v0, 1 # 将值取到返回寄存器 $v0 中
+ jr $ra # 跳转回原先的程序计数器继续执行
+
+
+ # 有2个参数的函数
+ sum:
+ add $v0, $a0, $a1
+ jr $ra # 返回
+
+ # 求阶乘的递归函数
+ fact:
+ addi $sp, $sp, -8 # 在栈中分配空间
+ sw $s0, ($sp) # 存储保存当前数字的寄存器
+ sw $ra, 4($sp) # 存储先前的程序计数器
+
+ li $v0, 1 # 初始化返回值
+ beq $a0, 0, fact_done # 如果参数为0则完成
+
+ # 否则继续递归
+ move $s0, $a0 # 复制 $a0 到 $s0
+ sub $a0, $a0, 1
+ jal fact
+
+ mul $v0, $s0, $v0 # 做乘法
+
+ fact_done:
+ lw $s0, ($sp)
+ lw $ra, ($sp) # 恢复程序计数器
+ addi $sp, $sp, 8
+
+ jr $ra
+
+## 宏 ##
+ _macros:
+ # 宏可以实现用单个标签替换重复的代码块,这可以增强程序的可读性
+ # 它们绝不是函数的替代品
+ # 它们必须在使用之前声明
+
+ # 用于打印换行符的宏(这可以被多次重用)
+ .macro println()
+ la $a0, newline # 存储在这里的新行字符串
+ li $v0, 4
+ syscall
+ .end_macro
+
+ println() # 汇编器会在运行前复制此代码块
+
+ # 参数可以通过宏传入。
+ # 它们由 '%' 符号表示,可以选择起任意名字
+ .macro print_int(%num)
+ li $v0, 1
+ lw $a0, %num
+ syscall
+ .end_macro
+
+ li $t0, 1
+ print_int($t0)
+
+ # 我们也可以给宏传递立即数
+ .macro immediates(%a, %b)
+ add $t0, %a, %b
+ .end_macro
+
+ immediates(3, 5)
+
+ # 以及标签
+ .macro print(%string)
+ la $a0, %string
+ li $v0, 4
+ syscall
+ .end_macro
+
+ print(hello_world)
+
+## 数组 ##
+.data
+ list: .word 3, 0, 1, 2, 6 # 这是一个字数组
+ char_arr: .asciiz "hello" # 这是一个字符数组
+ buffer: .space 128 # 在内存中分配块,不会自动清除
+ # 这些内存块彼此对齐
+
+.text
+ la $s0, list # 取 list 的地址
+ li $t0, 0 # 计数器
+ li $t1, 5 # list 的长度
+
+ loop:
+ bgt $t0, $t1, end_loop
+
+ lw $a0, ($s0)
+ li $v0, 1
+ syscall # 打印数字
+
+ addi $s0, $s0, 4 # 字的大小为4字节
+ addi $t0, $t0, 1 # 累加
+ j loop
+ end_loop:
+
+## INCLUDE ##
+# 使用 include 语句可以将外部文件导入到程序中
+# (它只是将文件中的代码放入 include 语句的位置)
+.include "somefile.asm"
+
+```
diff --git a/zh-cn/opencv-cn.html.markdown b/zh-cn/opencv-cn.html.markdown
new file mode 100644
index 00000000..06b997d5
--- /dev/null
+++ b/zh-cn/opencv-cn.html.markdown
@@ -0,0 +1,145 @@
+---
+category: tool
+tool: OpenCV
+filename: learnopencv.py
+contributors:
+ - ["Yogesh Ojha", "http://github.com/yogeshojha"]
+translators:
+ - ["GengchenXU", "https://github.com/GengchenXU"]
+lang: zh-cn
+---
+### Opencv
+
+Opencv(开源计算机视觉)是一个编程功能库,主要面向实时计算机视觉。最初由英特尔开发,后来由Willow Garage,然后Itseez(后来被英特尔收购)支持。Opencv 目前支持多种语言,如C++、Python、Java 等
+
+#### 安装
+有关在计算机上安装 OpenCV,请参阅这些文章。
+
+* Windows 安装说明: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]()
+* Mac 安装说明 (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]()
+* Linux 安装说明 (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]()
+
+### 在这里,我们将专注于 OpenCV 的 python 实现
+
+```python
+# OpenCV读取图片
+import cv2
+img = cv2.imread('cat.jpg')
+
+# 显示图片
+# imshow() 函数被用来显示图片
+cv2.imshow('Image',img)
+# 第一个参数是窗口的标题,第二个参数是image
+# 如果你得到错误,对象类型为None,你的图像路径可能是错误的。请重新检查图像包
+cv2.waitKey(0)
+# waitKey() 是一个键盘绑定函数,参数以毫秒为单位。对于GUI事件,必须使用waitKey()函数。
+
+# 保存图片
+cv2.imwrite('catgray.png',img)
+# 第一个参数是文件名,第二个参数是图像
+
+# 转换图像灰度
+gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+
+# 从摄像头捕捉视频
+cap = cv2.VideoCapture(0)
+#0 是你的相机,如果你有多台相机,你需要输入他们的id
+while(True):
+ # 一帧一帧地获取
+ _, frame = cap.read()
+ cv2.imshow('Frame',frame)
+ # 当用户按下q ->退出
+ if cv2.waitKey(1) & 0xFF == ord('q'):
+ break
+# 相机必须释放
+cap.release()
+
+# 在文件中播放视频
+cap = cv2.VideoCapture('movie.mp4')
+while(cap.isOpened()):
+ _, frame = cap.read()
+ # 灰度播放视频
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+ cv2.imshow('frame',gray)
+ if cv2.waitKey(1) & 0xFF == ord('q'):
+ break
+cap.release()
+
+# 在OpenCV中画线
+# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)(注 color颜色rgb参数 thickness粗细)
+cv2.line(img,(0,0),(511,511),(255,0,0),5)
+
+# 画矩形
+# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)
+# 粗细= -1用于填充矩形
+cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
+
+# 画圆
+cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness)
+cv2.circle(img,(200,90), 100, (0,0,255), -1)
+
+# 画椭圆
+cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
+
+# 在图像上增加文字
+cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
+
+# 合成图像
+img1 = cv2.imread('cat.png')
+img2 = cv2.imread('openCV.jpg')
+dst = cv2.addWeighted(img1,0.5,img2,0.5,0)
+
+# 阈值图像
+# 二进制阈值
+_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
+# Adaptive Thresholding
+adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
+
+# 模糊的形象
+# 高斯模糊
+blur = cv2.GaussianBlur(img,(5,5),0)
+# 模糊中值
+medianBlur = cv2.medianBlur(img,5)
+
+# Canny 边缘检测
+img = cv2.imread('cat.jpg',0)
+edges = cv2.Canny(img,100,200)
+
+# 用Haar Cascades进行人脸检测
+# 下载 Haar Cascades 在 https://github.com/opencv/opencv/blob/master/data/haarcascades/
+import cv2
+import numpy as np
+face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
+eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
+
+img = cv2.imread('human.jpg')
+gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+
+aces = face_cascade.detectMultiScale(gray, 1.3, 5)
+for (x,y,w,h) in faces:
+ cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
+ roi_gray = gray[y:y+h, x:x+w]
+ roi_color = img[y:y+h, x:x+w]
+ eyes = eye_cascade.detectMultiScale(roi_gray)
+ for (ex,ey,ew,eh) in eyes:
+ cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
+
+cv2.imshow('img',img)
+cv2.waitKey(0)
+
+cv2.destroyAllWindows()
+# destroyAllWindows() destroys all windows.
+# 如果您希望销毁特定窗口,请传递您创建的窗口的确切名称。
+```
+
+### 进一步阅读:
+
+* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]()
+* OpenCV 绘图函数 [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]()
+* 最新的语言参考 [https://opencv.org]()
+* 更多的资源 [https://en.wikipedia.org/wiki/OpenCV]()
+* 优秀的的 OpenCV 教程
+ * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]()
+ * [https://realpython.com/python-opencv-color-spaces]()
+ * [https://pyimagesearch.com]()
+ * [https://www.learnopencv.com]()
diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown
index 5b0d6179..46c54618 100644
--- a/zh-cn/perl-cn.html.markdown
+++ b/zh-cn/perl-cn.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: zh-cn
---
-Perl 5是一个功能强大、特性齐全的编程语言,有25年的历史。
+Perl 是一个功能强大、特性齐全的编程语言,有25年的历史。
-Perl 5可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
+Perl 可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
```perl
# 单行注释以#号开头
@@ -146,7 +146,7 @@ perlfaq有很多常见问题和相应回答,也经常有对优秀CPAN模块的
#### 深入阅读
- - [perl-tutorial](http://perl-tutorial.org/)
- - [www.perl.com的learn站点](http://www.perl.org/learn.html)
- - [perldoc](http://perldoc.perl.org/)
- - 以及 perl 内置的: `perldoc perlintro`
+- [perl-tutorial](http://perl-tutorial.org/)
+- [www.perl.com的learn站点](http://www.perl.org/learn.html)
+- [perldoc](http://perldoc.perl.org/)
+- 以及 perl 内置的: `perldoc perlintro`
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index da13275b..6c5556fc 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -436,9 +436,9 @@ all_the_args(1, 2, a=3, b=4) prints:
# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # 相当于 foo(1, 2, 3, 4)
-all_the_args(**kwargs) # 相当于 foo(a=3, b=4)
-all_the_args(*args, **kwargs) # 相当于 foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # 相当于 all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # 相当于 all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)
# 函数作用域
diff --git a/zh-cn/pythonlegacy-cn.html.markdown b/zh-cn/pythonlegacy-cn.html.markdown
index 756081d6..f8aa2332 100644
--- a/zh-cn/pythonlegacy-cn.html.markdown
+++ b/zh-cn/pythonlegacy-cn.html.markdown
@@ -163,7 +163,7 @@ li[:3] # => [1, 2, 4]
del li[2] # li 现在是 [1, 2, 3]
# 合并列表
-li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会不改变这两个列表
+li + other_li # => [1, 2, 3, 4, 5, 6] - 并不会改变这两个列表
# 通过拼接来合并列表
li.extend(other_li) # li 是 [1, 2, 3, 4, 5, 6]
diff --git a/zh-cn/qt-cn.html.markdown b/zh-cn/qt-cn.html.markdown
new file mode 100644
index 00000000..8681c85b
--- /dev/null
+++ b/zh-cn/qt-cn.html.markdown
@@ -0,0 +1,160 @@
+---
+category: tool
+tool: Qt Framework
+language: c++
+filename: learnqt-cn.cpp
+contributors:
+ - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
+translators:
+ - ["GengchenXU", "https://github.com/GengchenXU"]
+lang: zh-cn
+
+---
+
+**Qt** Qt是一个广为人知的框架,用于开发跨平台软件,该软件可以在各种软件和硬件平台上运行,代码几乎没有变化,同时具有本机应用程序的能力和速度。虽然**Qt**最初是用*C*++,但也有其他语言的端口: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, 等等.
+
+**Qt** 非常适合使用图形用户界面 (GUI) 创建应用程序。本教程是关于如何用*C++*去实现。
+
+```c++
+/*
+ * 让我们从最经典的开始
+ */
+
+// Qt框架的所有标头均以大写字母'Q'开头
+#include <QApplication>
+#include <QLineEdit>
+
+int main(int argc, char *argv[]) {
+ // 创建一个对象来管理应用程序范围内的资源
+ QApplication app(argc, argv);
+
+ // 创建行编辑widgets并在屏幕上显示
+ QLineEdit lineEdit("Hello world!");
+ lineEdit.show();
+
+ // 启动应用程序的事件循环
+ return app.exec();
+}
+```
+
+**Qt**与 GUI 相关的部分与*widgets*及其之间的*connection*有关。
+
+[阅读更多有关widgets的信息](http://doc.qt.io/qt-5/qtwidgets-index.html)
+
+```c++
+/*
+ * 让我们创建一个标签和一个按钮。
+ * 按下按钮时应显示一个标签。
+ * Qt代码本身就可以说明问题。
+ */
+
+#include <QApplication>
+#include <QDialog>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QLabel>
+
+int main(int argc, char *argv[]) {
+ QApplication app(argc, argv);
+
+ QDialog dialogWindow;
+ dialogWindow.show();
+
+ // 添加垂直布局
+ QVBoxLayout layout;
+ dialogWindow.setLayout(&layout);
+
+ QLabel textLabel("Thanks for pressing that button");
+ layout.addWidget(&textLabel);
+ textLabel.hide();
+
+ QPushButton button("Press me");
+ layout.addWidget(&button);
+
+ // 按下按钮时显示隐藏标签
+ QObject::connect(&button, &QPushButton::pressed,
+ &textLabel, &QLabel::show);
+
+ return app.exec();
+}
+```
+
+注意,*QObject :: connect*部分。 此方法用于将一个对象的*SIGNAL*连接到另一个对象的*SLOTS*。
+
+**Signals** 会被发出当对象发生某些事情时,例如当用户按下QPushButton对象时会发出*push*的信号。
+
+**Slots** 是可以响应于接收到的信号而执行的*action*。
+
+[阅读有关SLOTS和SIGNALS的更多信息](http://doc.qt.io/qt-5/signalsandslots.html)
+
+
+接下来,让我们了解到我们不仅可以使用标准的wigets,而且可以通过继承扩展其行为。 让我们创建一个按钮并计算其被按下的次数。 为此,我们定义了自己的类* CounterLabel *。 由于特定的Qt体系结构,必须在单独的文件中声明它。
+
+```c++
+// counterlabel.hpp
+
+#ifndef COUNTERLABEL
+#define COUNTERLABEL
+
+#include <QLabel>
+
+class CounterLabel : public QLabel {
+ Q_OBJECT // 在每个自定义wiget中必须存在的Qt定义的宏
+
+public:
+ CounterLabel() : counter(0) {
+ setText("Counter has not been increased yet"); // QLabel方法
+ }
+
+public slots:
+ // 将响应按钮按下而调用的操作
+ void increaseCounter() {
+ setText(QString("Counter value: %1").arg(QString::number(++counter)));
+ }
+
+private:
+ int counter;
+};
+
+#endif // COUNTERLABEL
+```
+
+```c++
+// main.cpp
+// 与前面的示例几乎相同
+
+#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();
+}
+```
+
+当然,Qt框架比本教程介绍的部分要复杂得多,因此请仔细阅读和练习。
+
+## 进一步阅读
+- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
+- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
+
+祝你好运,生活愉快!
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 9918c022..63adab64 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -657,4 +657,4 @@ Something.new.qux # => 'qux'
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
-- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser.
+- [Try Ruby](https://try.ruby-lang.org/) - Learn the basic of Ruby programming language, interactive in the browser.
diff --git a/zh-cn/set-theory-cn.html.markdown b/zh-cn/set-theory-cn.html.markdown
new file mode 100644
index 00000000..13ba2c80
--- /dev/null
+++ b/zh-cn/set-theory-cn.html.markdown
@@ -0,0 +1,138 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+contributors:
+translators:
+ - ["Tianchen Xu", "https://github.com/lo0b0o"]
+lang: zh-cn
+---
+集合论是数学的一个分支,研究集合、它们的运算和它们的性质。
+
+* 集合由不重复的项组成。
+
+## 基本符号
+
+### 运算符
+* 并运算符,`∪`,表示“或”;
+* 交运算符,`∩`,表示“且”;
+* 差运算符,`\`,表示“不包括”;
+* 补运算符,`'`,表示补集;
+* 叉积运算符,`×`,表示笛卡尔积。
+
+### 限定词
+* 冒号限定词,`:`,表示“使得”;
+* 从属限定词,`∈`,表示“属于”;
+* 子集限定词,`⊆`,表示“是……的子集”;
+* 真子集限定词,`⊂`,表示“是……的真子集”。
+
+### 重要的集合
+* `∅`,空集,即不包含任何元素的集合;
+* `ℕ`,自然数集;
+* `ℤ`,整数集;
+* `ℚ`,有理数集;
+* `ℝ`,实数集。
+
+关于以上集合,有如下几点需要注意:
+1. 空集是其本身的子集(并且也是任何其他集合的子集),即便空集不包含任何项;
+2. 数学家们对于零是否为自然数的看法通常并不统一,教科书一般会明确说明作者是否认为零是自然数。
+
+### 基数
+
+集合的基数,或者说大小,由该集合中的项目数量决定。基数运算符为 `|...|`。
+
+例如,若 `S = { 1, 2, 4 }`,则 `|S| = 3`。
+
+### 空集
+
+* 可以在集合符号中使用不成立的条件来构造空集,例如,`∅ = { x : x ≠ x }`,或 `∅ = { x : x ∈ N, x < 0 }`;
+* 空集总是唯一的(即,有且只有一个空集);
+* 空集是所有集合的子集;
+* 空集的基数为 0,即 `|∅| = 0`。
+
+## 集合的表示
+
+### 集合的逐项构造
+
+集合可以通过包含其全部项的列表逐项生成。例如,`S = { a, b, c, d }`。
+
+只要构成集合的项清楚,长列表可以用省略号缩短。例如,`E = { 2, 4, 6, 8, ... }` 显然为所有偶数构成的集合,它包含无穷多项,虽然我们只显式写出了其中四项。
+
+### 集合构造器
+
+集合构造器符号是构造集合的一种更具描述性的方式。它依赖于一个主语和一个谓词,使得 `S = { 主语 : 谓词 }`。 例如,
+
+```
+A = { x : x 是元音字母 } = { a, e, i, o, u, y}
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+有时,谓词可能会 "漏 "到主语中,例如,
+
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## 关系
+
+### 从属关系
+
+* 如果值 `a` 包含在集合 `A` 中,那么我们说 `a` 属于 `A`,并用符号表示为 `a ∈ A`。
+* 如果值 `a` 不包含于集合 `A` 中,那么我们说 `a` 不属于 `A`,并用符号表示为 `a ∉ A`。
+
+### 相等关系
+
+* 如果两个集合包括相同的项,那么我们说这两个集合相等,例如,`A = B`。
+* 集合的相等关系于顺序无关,例如 `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`。
+* 集合中的元素不能重复,例如 `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`。
+* 集合 `A` 与 `B` 相等当且仅当 `A ⊆ B` 且 `B ⊆ A`。
+
+## 特殊集合
+
+### 幂集
+
+* 令 `A` 为任意集合。幂集指的是包括了 `A` 的所有子集的集合,记作 `P(A)`。如果集合 `A` 由 `2n` 个元素组成,那么 `P(A)` 中有 `2^n` 个元素。
+
+```
+P(A) = { x : x ⊆ A }
+```
+
+## 两个集合的运算
+### 并
+
+给定集合 `A` 和 `B`,两个集合的并由出现在 `A` 或 `B` 中的项构成,记作 `A ∪ B`。
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### 交
+
+给定集合 `A` 和 `B`,两个集合的交由出现在 `A` 和 `B` 中的项构成,记作 `A ∩ B`。
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### 差
+给定集合 `A` 和 `B`,`A` 对于 `B` 的集合差指的是属于 `A` 但不属于 `B` 的每一项。
+
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### 对称差
+给定集合 `A` 和 `B`,对称差指的是属于 `A` 或 `B` 但不属于它们交集的所有项。
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### 笛卡尔积
+给定集合 `A` 和 `B`,`A` 和 `B` 的笛卡尔积由 `A` 和 `B` 的项的所有组合构成。
+
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
diff --git a/zh-cn/solidity-cn.html.markdown b/zh-cn/solidity-cn.html.markdown
index ec684997..12a532bc 100644
--- a/zh-cn/solidity-cn.html.markdown
+++ b/zh-cn/solidity-cn.html.markdown
@@ -213,7 +213,7 @@ names.length; // 获得数组长度
names.length = 1; // 可以设定长度(仅针对 storage 中的动态数组)
// 多维数组
-uint x[][5]; // 5个动态数组元素的数组(和多数语言的顺序相反)
+uint[][5] x; // 5个动态数组元素的数组(和多数语言的顺序相反)
// 字典类型 (任一类型到其他类型的映射)
mapping (string => uint) public balances;
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 18bc52ed..c56a0d33 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -10,7 +10,7 @@ translators:
lang: zh-cn
---
-Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。
+Swift 是 Apple 开发的用于 iOS 和 macOS 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
diff --git a/zh-cn/wolfram-cn.html.markdown b/zh-cn/wolfram-cn.html.markdown
new file mode 100644
index 00000000..9d6ef54f
--- /dev/null
+++ b/zh-cn/wolfram-cn.html.markdown
@@ -0,0 +1,140 @@
+---
+language: wolfram
+contributors:
+ - ["hyphz", "http://github.com/hyphz/"]
+translators:
+ - ["wuyudi", "http://github.com/wuyudi/"]
+filename: learnwolfram-cn.nb
+lang: zh-cn
+---
+
+Wolfram 语言是最初在 Mathematica 中使用的底层语言,但现在可用于多种场合。
+
+Wolfram 语言有几个界面。
+
+- Raspberry Pi 上的命令行内核界面(就叫 _The Wolfram Language_),它是交互式运行的,不能产生图形输入。
+- _Mathematica_ 是一个丰富的文本/数学编辑器,内置交互式的 Wolfram: 在 "代码单元 "上按 shift+Return 键可以创建一个输出单元,输出结果,这不是动态的。
+- _Wolfram Workbench_,这是 Eclipse 与 Wolfram 语言后端的界面。
+
+本例中的代码可以在任何界面中输入,并使用 Wolfram Workbench 进行编辑。直接加载到 Mathematica 中可能会很不方便,因为该文件不包含单元格格式化信息(这将使该文件作为文本阅读时变得一团糟)--它可以被查看/编辑,但可能需要一些设置。
+
+```mma
+(* 这是一个注释 *)
+
+(* 在Mathematica中,您可以创建一个文本单元格,用排版好的文本和图像来注释您的代码,而不是使用这些注释 *)
+
+(* 输入一个表达式返回结果 *)
+2*2 (* 4 *)
+5+8 (* 13 *)
+
+(* 调用函数 *)
+(* 注意,函数名(和其他所有东西)是区分大小写的 *)
+Sin[Pi/2] (* 1 *)
+
+(* 带有一个参数的函数调用的替代语法 *)
+Sin@(Pi/2) (* 1 *)
+(Pi/2) // Sin (* 1 *)
+
+(* WL 中的每一种语法都有一些等价的函数调用,即万物皆函数 *)
+Times[2, 2] (* 4 *)
+Plus[5, 8] (* 13 *)
+
+(* 第一次使用一个变量定义它,并使其成为全局变量 *)
+x = 5 (* 5 *)
+x == 5 (* 返回真,C-style 的赋值和相等测试 *)
+x (* 5 *)
+x = x + 5 (* 10 *)
+x (* 10 *)
+Set[x, 20] (* 当我说万物皆函数时 我是认真的 *)
+x (* 20 *)
+
+(* 因为WL是基于计算机代数系统的, *)
+(* 可以使用未定义的变量,它们只是阻碍了计算 *)
+cow + 5 (* 5 + cow, cow 是未定义的,所以无法进一步计算 *)
+cow + 5 + 10 (* 15 + cow, 它将尽力计算 *)
+% (* 15 + cow, % 获取最后一次返回的内容 *)
+% - cow (* 15, 未定义的变量cow被消去 *)
+moo = cow + 5 (* 小心,moo 现在是一个表达式,不是一个数字! *)
+
+(* 定义一个函数 *)
+Double[x_] := x * 2 (* 注意 := 防止对RHS进行即时计算。
+ 而 x 后面的 _ 表示没有模式匹配的约束条件*)
+Double[10] (* 20 *)
+Double[Sin[Pi/2]] (* 2 *)
+Double @ Sin @ (Pi/2) (* 2, @-syntax 避免了闭括号的队列 *)
+(Pi/2) // Sin // Double(* 2, //-syntax 按执行顺序列举了函数 *)
+
+(* 对于命令式编程,使用 ; 来分隔语句。 *)
+(* 丢弃 LHS 的任何输出并运行 RHS *)
+MyFirst[] := (Print@"Hello"; Print@"World") (* 请注意,外侧的小括号是关键
+ ;的优先级低于:= *)
+MyFirst[] (* 你好,世界 *)
+
+(* C-Style 的 For 循环,注:在 Mathematica 中使用 For 循环是低效的 *)
+PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* 开始,测试,自增,循环体 *)
+PrintTo[5] (* 0 1 2 3 4 *)
+
+(* While 循环 *)
+x = 0; While[x < 2, (Print@x; x++)] (* 带测试和程序体的 while 循环 *)
+
+(* If 和 条件 *)
+x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condition, true case, else case *)
+Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* 值匹配风格切换 *)
+Which[x==2, Print@"No", x==8, Print@"Yes"] (* Elif风格切换 *)
+
+(* 除参数外的变量默认为全局变量,即使在函数内部也是如此 *)
+y = 10 (* 10, 全局变量 y *)
+PrintTo[5] (* 0 1 2 3 4 *)
+y (* 5, 全局的 y 被 PrintTo 内的循环计数器所占用 *)
+x = 20 (* 20, 全局变量 x *)
+PrintTo[5] (* 0 1 2 3 4 *)
+x (* 20, PrintTo 中的 x 是一个参数,并自动局部化 *)
+
+(* 局部变量使用 Module 元函数声明 *)
+(* 带本地变量的版本 *)
+BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])]
+y = 20 (* 全局变量 y *)
+BetterPrintTo[5] (* 0 1 2 3 4 *)
+y (* 20, 那更好 *)
+
+(* 实际上,模块允许我们声明任何我们喜欢的作用域 *)
+Module[{count}, count=0; (* 声明这个变量count的作用域 *)
+ (IncCount[] := ++count); (* 这些函数都在该作用域内 *)
+ (DecCount[] := --count)]
+count (* count - 全局变量 count 未定义 *)
+IncCount[] (* 1, 使用作用域内的counter变量 *)
+IncCount[] (* 2, incCount 升级了它 *)
+DecCount[] (* 1, decCount 也是 *)
+count (* count - 这个名字依旧不是全局变量 *)
+
+(* Lists *)
+myList = {1, 2, 3, 4} (* {1, 2, 3, 4} *)
+myList[[1]] (* 1 - 注意列表索引从 1 开始,而不是从 0 开始。 *)
+Map[Double, myList] (* {2, 4, 6, 8} - 函数式列表的 map 函数 *)
+Double /@ myList (* {2, 4, 6, 8} - 以上的缩略语法 *)
+Scan[Print, myList] (* 1 2 3 4 - 命令式循环 *)
+Fold[Plus, 0, myList] (* 10 (0+1+2+3+4) *)
+FoldList[Plus, 0, myList] (* {0, 1, 3, 6, 10} - 存值的 Fold *)
+Append[myList, 5] (* {1, 2, 3, 4, 5} - 注意 myList 没有更新 *)
+Prepend[myList, 5] (* {5, 1, 2, 3, 4} - 如果想让 myList 更新,就加上 "myList = " *)
+Join[myList, {3, 4}] (* {1, 2, 3, 4, 3, 4} *)
+myList[[2]] = 5 (* {1, 5, 3, 4} - 这确实更新了myList *)
+
+(* 关联,又称字典/哈希值 *)
+myHash = <|"Green" -> 2, "Red" -> 1|> (* 创建一个关联 *)
+myHash[["Green"]] (* 2, 使用 *)
+myHash[["Green"]] := 5 (* 5, 更新 *)
+myHash[["Puce"]] := 3.5 (* 3.5, 扩展 *)
+KeyDropFrom[myHash, "Green"] (* 抹去绿色的键 *)
+Keys[myHash] (* {Red, Puce} *)
+Values[myHash] (* {1, 3.5} *)
+
+(* 做 Wolfram 的演示时 你不能不展示这个 *)
+Manipulate[y^2, {y, 0, 20}] (* 返回一个反应式的用户界面,显示y^2
+ 并允许通过滑块在 0-20 之间调整y。
+ 只适用于图形前端 *)
+```
+
+## 想多来点?
+
+- [Wolfram Language Documentation Center](http://reference.wolfram.com/language/)
diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown
index 7b6ff305..cfa22dfb 100644
--- a/zh-cn/yaml-cn.html.markdown
+++ b/zh-cn/yaml-cn.html.markdown
@@ -5,27 +5,27 @@ contributors:
translators:
- ["Zach Zhang", "https://github.com/checkcheckzz"]
- ["Jiang Haiyun", "https://github.com/haiiiiiyun"]
+ - ["Wen Sun", "https://github.com/HermitSun"]
filename: learnyaml-cn.yaml
lang: zh-cn
---
-YAML 是一个数据序列化语言,被设计成人类直接可写可读的。
+YAML 是一种数据序列化语言,旨在让人类直接可写可读。
-它是 JSON 的严格超集,增加了语法显著换行符和缩进,就像 Python。但和 Python 不一样,
-YAML 根本不容许文字制表符。
+它是 JSON 的严格超集,增加了*在语法上有意义的*(syntactically significant)换行符和缩进,就像 Python 一样。但和 Python 的不同之处在于,YAML 不允许使用*文字制表符*(literal tab characters)来表示缩进。
```yaml
--- # 文档开头
-# YAML 中的注解看起来像这样。
+# YAML 中的注释看起来像这样。
################
# 标量类型 #
################
-# 我们的根对象 (它们在整个文件里延续) 将会是一个映射,
-# 它等价于在别的语言里的一个字典,哈希表或对象。
+# 我们的根对象 (贯穿整个文档的始终) 是一个映射(map),
+# 它等价于其它语言中的一个字典(dictionary),哈希表(hash)或对象(object)。
key: value
another_key: Another value goes here.
a_number_value: 100
@@ -35,16 +35,16 @@ scientific_notation: 1e+12
boolean: true
null_value: null
key with spaces: value
-# 注意,字符串不必被括在引号中,但也可以被括起来。
+# 注意,字符串可以不括在引号里。当然,也可以括在引号里。
however: 'A string, enclosed in quotes.'
'Keys can be quoted too.': "Useful if you want to put a ':' in your key."
single quotes: 'have ''one'' escape pattern'
double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more."
-# UTF-8/16/32 字符需要被转义(encoded)
+# UTF-8/16/32字符需要指明编码(通过\u)。
Superscript two: \u00B2
-# 多行字符串既可以写成像一个'文字块'(使用 |),
-# 或像一个'折叠块'(使用 '>')。
+# 多行字符串既可以写成一个'字面量块'(使用 '|'),
+# 也可以写成一个'折叠块'(使用 '>')。
literal_block: |
This entire block of text will be the value of the 'literal_block' key,
with line breaks being preserved.
@@ -67,7 +67,7 @@ folded_style: >
# 集合类型 #
####################
-# 嵌套是通过缩进完成的。推荐使用 2 个空格的缩进(但非必须)
+# 嵌套是通过缩进完成的。推荐使用 2 个空格的缩进(但非必须)。
a_nested_map:
key: value
another_key: Another Value
@@ -77,22 +77,22 @@ a_nested_map:
# 映射的键不必是字符串。
0.25: a float key
-# 键也可以是复合型的,比如多行对象
-# 我们用 ? 后跟一个空格来表示一个复合键的开始。
+# 键也可以是复合(complex)的,比如多行对象
+# 我们用 '?' 后跟一个空格来表示一个复合键的开始。
? |
This is a key
that has multiple lines
: and this is its value
# YAML 也允许使用复杂键语法表示序列间的映射关系。
-# 但有些语言的解析器可能会不支持。
+# 但有些解析器可能会不支持。
# 一个例子:
? - Manchester United
- Real Madrid
: [ 2001-01-01, 2002-02-02 ]
-# 序列 (等价于列表或数组) 看起来像这样:
-# 注意 '-' 算作缩进
+# 序列 (sequences,等价于列表 list 或数组 array ) 看起来像这样:
+# 注意 '-' 也算缩进:
a_sequence:
- Item 1
- Item 2
@@ -115,7 +115,7 @@ and quotes are optional: {key: [3, 2, 1, takeoff]}
# 其余的 YAML 特性 #
#######################
-# YAML 还有一个方便的特性叫 '锚',它能让你很容易在文档中进行文本复用。
+# YAML 还有一个方便的特性叫“锚”(anchors)。你可以使用它在文档中轻松地完成文本复用。
# 如下两个键会有相同的值:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
@@ -124,8 +124,8 @@ other_anchor: *anchor_name
base: &base
name: Everyone has same name
-# The regexp << is called Merge Key Language-Independent Type.
-# 它表明指定映射的所有键值会插入到当前的映射中。
+# '<<'称为语言无关的合并键类型(Merge Key Language-Independent Type).
+# 它表明一个或多个指定映射中的所有键值会插入到当前的映射中。
foo: &foo
<<: *base
@@ -137,22 +137,22 @@ bar: &bar
# foo 和 bar 将都含有 name: Everyone has same name
-# YAML 还有标签,你可以用它显式地声明类型。
+# YAML 还有标签(tags),你可以用它显式地声明类型。
explicit_string: !!str 0.5
-# 一些解析器实现特定语言的标签,就像这个针对 Python 的复数类型。
+# 一些解析器实现了特定语言的标签,就像这个针对Python的复数类型的标签。
python_complex_number: !!python/complex 1+2j
-# 我们也可以在 YAML 的复合键中使用特定语言的标签
+# 我们也可以在 YAML 的复合键中使用特定语言的标签:
? !!python/tuple [5, 7]
: Fifty Seven
-# 将会是 Python 中的 {(5, 7): 'Fifty Seven'}
+# 将会是 Python 中的 {(5, 7): 'Fifty Seven'}
####################
# 其余的 YAML 类型 #
####################
-# 除了字符串和数字,YAML 还能理解其它标量。
-# ISO 格式的日期和日期时间文本也可以被解析。
+# 除了字符串和数字,YAML 还支持其它标量。
+# ISO 格式的日期和时间字面量也可以被解析。
datetime: 2001-12-15T02:59:43.1Z
datetime_with_spaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
@@ -165,14 +165,14 @@ gif_file: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML 还有一个集合类型,它看起来像这样:
+# YAML 还有一个集合(set)类型,它看起来像这样:
set:
? item1
? item2
? item3
or: {item1, item2, item3}
-# 集合只是值为 null 的映射;上面的集合等价于:
+# 集合只是值均为 null 的映射;上面的集合等价于:
set2:
item1: null
item2: null
@@ -184,4 +184,5 @@ set2:
### 更多资源
+ [YAML official website](http://yaml.org/)
++ [Online YAML Converter](http://yamlonline.com)
+ [Online YAML Validator](http://codebeautify.org/yaml-validator)
diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown
index 78b39f2d..5136d513 100644
--- a/zh-tw/bash-tw.html.markdown
+++ b/zh-tw/bash-tw.html.markdown
@@ -23,7 +23,7 @@ filename: LearnBash-tw.sh
lang: zh-tw
---
-Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 Mac OS X 下預設的 shell。
+Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 macOS 下預設的 shell。
以下大多數例子可以作爲腳本的一部分運行,也可直接在 shell 下互動執行。
[更多資訊](http://www.gnu.org/software/bash/manual/bashref.html)
diff --git a/zh-tw/perl-tw.html.markdown b/zh-tw/perl-tw.html.markdown
new file mode 100644
index 00000000..55876e2a
--- /dev/null
+++ b/zh-tw/perl-tw.html.markdown
@@ -0,0 +1,328 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-tw.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Dan Book", "http://github.com/Grinnz"]
+translators:
+ - ["Kang-min Liu", "https://gugod.org"]
+ - ["Shih-Kai Chiu", "https://twitter.com/zard1989"]
+lang: zh-tw
+---
+
+Perl 5 是一款強大且功能豐富的程式語言,已經持續發展超過 25 年。
+
+從大型主機到行動裝置,Perl 5 能在上百種平台執行,適合快速打造產品原型,也適合大
+型專案開發。
+
+```perl
+# 註解列皆以井字號為開頭
+
+#### 嚴謹度
+
+use strict;
+use warnings;
+
+# 所有的 perl 程式檔案都應當包含此兩列程式碼。在如變數名稱有拼寫錯誤之時,
+# strict 能使編譯過程失敗。而對於像是將未定義值接到字串中等等易犯之錯誤,
+# warnings 則能提供適當的警告訊息。
+
+#### Perl 變數與其型別
+
+# 變數的開頭皆為一印記(sigil),是為一符號,用以標示其型別。
+# 變數名稱唯有以字母或底線開頭,後接字母、數字、底線若干,方為有效。
+
+### 在 Perl 語言中,主要的變數型別有三種:$純量、@陣列、%雜湊。
+
+## 純量
+# 一個純量變數,只能裝一個值:
+my $animal = "camel";
+my $answer = 42;
+my $display = "You have $answer ${animal}s.\n";
+
+# 純量值可為字串、整數、浮點數。Perl 會自動地在需要之時進行轉換。
+
+# 以單引號括住的字串內容與其字面之值完全相同。而以雙引號括住的字串,
+# 其中則能內插變數與像是這種表示換列字符 "\n" 的控制碼。
+
+## 陣列
+# 一個陣列,可以裝下很多值:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+# 陣列元素的存取,需要角括號。前方的印記為 $ 符號,表示只取一個值。
+my $second = $animals[1];
+
+# 欲知陣列之大小,在純量語境之下使用陣列便可。例如,將陣列裝到一個純量變數中。
+# 又或者是使用 "scalar" 算符。
+
+my $num_animals = @animals;
+print "Number of numbers: ", scalar(@numbers), "\n";
+
+# 陣列也能夠被安插在雙引號字串之內。各內容元素間隔,預設是一個空白字符。
+
+print "We have these numbers: @numbers\n";
+
+# 雙引號字串中,若有像電子郵件地址的部分,會被視為是在內插某個陣列的內容物。
+# 請稍加留意。
+
+my @example = ('secret', 'array');
+my $oops_email = "foo@example.com"; # 'foosecret array.com'
+my $ok_email = 'foo@example.com';
+
+## 雜湊
+# 一個雜湊,能裝下許多對的鍵與值:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# 善用空白與 "=>" 算符,就能將其排得得好看一些:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+);
+
+# 雜湊元素的存取,需要大括號。前方的印記仍為 $ 符號,表示只取一個值。
+my $color = $fruit_color{apple};
+
+# 以 "keys" 與 "values" 兩個函數,則可一次取得雜湊中的所有鍵、所有值。
+my @fruits = keys %fruit_color;
+my @colors = values %fruit_color;
+
+# 關於純量、陣列、雜湊,在 perldata 文件之中,有更完整的描述。
+# (perldoc perldata)
+
+#### 參照
+
+# 以參照能組出結構更為複雜的資料型別。
+# 像是在陣列中放入雜湊、或是在雜湊裡放入陣列的雜湊。
+
+my $array_ref = \@array;
+my $hash_ref = \%hash;
+my @array_of_arrays = (\@array1, \@array2, \@array3);
+
+# 匿名陣列與匿名雜湊也是參照
+
+my $fruits = ["apple", "banana"];
+my $colors = {apple => "red", banana => "yellow"};
+
+# 在參照之前補上適當的印記,是為解參照。
+
+my @fruits_array = @$fruits;
+my %colors_hash = %$colors;
+
+# 以箭頭算符,便可在解參照同時存取其中一值。
+
+my $first = $array_ref->[0];
+my $value = $hash_ref->{banana};
+
+# 欲深入了解參照,詳見 perlreftut 與 perlref 兩份文件
+
+#### 條件結構與迴圈結構
+
+# Perl 語言中亦具備常見的條件結講與迴圈結構。
+
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (condition) {
+ ...
+}
+# 這算是可讀性較好的 "if (!condition)"
+
+# 倒裝句型算是某「很 Perl 的」寫法
+print "Yow!" if $zippy;
+print "We have no bananas" unless $bananas;
+
+# while
+while (condition) {
+ ...
+}
+
+my $max = 5;
+# 以 for 迴圈,$i 為迭代變數
+for my $i (0 .. $max) {
+ print "index is $i";
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+map {print} @elements;
+
+# 迭代變數為 $_
+for (@elements) {
+ print;
+}
+
+# 對雜湊進行迭代(for 與 foreach 完全相同)
+
+foreach my $key (keys %hash) {
+ print $key, ': ', $hash{$key}, "\n";
+}
+
+# 又是「很 Perl 的」倒裝句法
+print for @elements;
+
+# 對一雜湊參照之中迭代,逐一走過其鍵與值
+print $hash_ref->{$_} for keys %$hash_ref;
+
+#### 正規表示式
+
+# Perl 中,對正規表示式的支援既廣亦深,在 perlrequick、perlretut 等各處文件中
+# 都有更加完整的文件。不過,簡而言之:
+
+# 簡易比對
+if (/foo/) { ... } # 若 $_ 內含 "foo" 則為真
+if ($x =~ /foo/) { ... } # 若 $x 內含 "foo" 則為真
+
+# 簡易取代
+$x =~ s/foo/bar/; # 將 $x 中第一個出現的 foo 換為 bar
+$x =~ s/foo/bar/g; # 將 $x 中所有出現的 foo 換為 bar
+
+#### 檔案與輸出入
+
+# 以 "open" 函式開檔後,便可自檔案輸入或對其輸出
+
+# 讀檔:
+open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
+
+# 寫檔(若檔案已經存在,舊內容會被清空):
+open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
+
+# 寫檔(若檔案已經存在,會寫到檔尾去):
+open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
+
+# 使用 "<>" 算符,能對檔案代號進行讀取。在純量語境下,會自檔案代號讀一列內容。
+# 而在串列語境下,對讀入整個檔案。每一列都會成為串列中一項元素。
+
+my $line = <$in>;
+my @lines = <$in>;
+
+# 以 "print" 函式,則可對檔案代號進行輸出。
+
+print $out @lines;
+print $log $msg, "\n";
+
+#### 函式之撰寫
+
+# 撰寫函式很是容易:
+
+sub logger {
+ my $logmessage = shift;
+
+ open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
+
+ print $logfile $logmessage;
+}
+
+# 之後,使用起來就與內建函式無異:
+
+logger("We have a logger subroutine!");
+
+#### 模組
+
+# 所謂模組,就是一組 Perl 程式碼,由一些函式組成,並可讓其他 Perl 程式碼來利用。
+# 為了讓 perl 能找至,通常模組之副檔名 .pm 。
+
+package MyModule;
+use strict;
+use warnings;
+
+sub trim {
+ my $string = shift;
+ $string =~ s/^\s+//;
+ $string =~ s/\s+$//;
+ return $string;
+}
+
+1;
+
+# 自他處利用:
+
+use MyModule;
+MyModule::trim($string);
+
+# Exporter 模組能將函式出口,好讓它們能被這樣利用:
+
+use MyModule 'trim';
+trim($string);
+
+# 有許多 Perl 模組能從 CPAN (https://www.cpan.org) 下載下來,各式各樣的機能讓你
+# 能免於重新發明輪子。不少高人氣模組,如 Exporter,則是與 Perl 一同釋出、散佈。
+# 更多關於 Perl 模組的細節,詳見 perlmod 文件。
+
+#### 物件
+
+# Perl 中的物件,只是個參照,但同時又知道自己屬於哪個類別(package),於是對自身
+# 調用方法(函式)時方知去何處尋找函式本體。在建構子(通常是 "new")中,都是以
+# "bless" 函式來標記參照與其類別。只不過,若你使用像 Moose 或 Moo 模組的話,這些
+# 都不必自己來(總之請繼續往下讀)。
+
+package MyCounter;
+use strict;
+use warnings;
+
+sub new {
+ my $class = shift;
+ my $self = {count => 0};
+ return bless $self, $class;
+}
+
+sub count {
+ my $self = shift;
+ return $self->{count};
+}
+
+sub increment {
+ my $self = shift;
+ $self->{count}++;
+}
+
+1;
+
+# 以箭頭運算符,便可對某類別或某物件呼叫某方法:
+use MyCounter;
+my $counter = MyCounter->new;
+print $counter->count, "\n"; # 0
+$counter->increment;
+print $counter->count, "\n"; # 1
+
+# CPAN 上的 Moose 與 Moo 模組能助你撰寫類別本體。它們提供了建構子,與簡單易懂的
+# 語法能來宣告屬性。前述的類別改寫之後,如下:
+
+package MyCounter;
+use Moo; # 同時也啟用 strict 與 warnings
+
+has 'count' => (is => 'rwp', default => 0, init_arg => undef);
+
+sub increment {
+ my $self = shift;
+ $self->_set_count($self->count + 1);
+}
+
+1;
+
+# 物件導向程式設計於 perlootut 文件中有詳盡的說明。
+# 此外,perlobj 文件中更涵蓋了底層實做之細節。
+```
+
+#### 常見問答集
+
+perlfaq 是問與答,涵蓋許多常見問題和解法,常常對該用哪些 CPAN 模組有很好的建議。
+
+#### 延伸閱讀
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn Perl](https://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - 內建函式 : `perldoc perlintro`