summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--c++.html.markdown20
-rw-r--r--coldfusion.html.markdown50
-rw-r--r--common-lisp.html.markdown9
-rw-r--r--cs-cz/markdown.html.markdown258
-rw-r--r--cs-cz/python3.html.markdown2
-rw-r--r--cs-cz/sass.html.markdown439
-rw-r--r--csharp.html.markdown4
-rw-r--r--d.html.markdown28
-rw-r--r--dart.html.markdown2
-rw-r--r--edn.html.markdown16
-rw-r--r--elisp.html.markdown3
-rw-r--r--elixir.html.markdown2
-rw-r--r--elm.html.markdown346
-rw-r--r--erlang.html.markdown2
-rw-r--r--es-es/brainfuck-es.html.markdown18
-rw-r--r--es-es/git-es.html.markdown14
-rw-r--r--es-es/javascript-es.html.markdown20
-rw-r--r--es-es/json-es.html.markdown16
-rw-r--r--es-es/python3-es.html.markdown8
-rw-r--r--es-es/ruby-es.html.markdown6
-rw-r--r--es-es/swift-es.html.markdown596
-rw-r--r--fi-fi/go-fi.html.markdown441
-rw-r--r--fi-fi/markdown-fi.html.markdown259
-rw-r--r--fr-fr/HTML-fr.html.markdown115
-rw-r--r--fr-fr/css-fr.html.markdown8
-rw-r--r--fr-fr/d.html.markdown264
-rw-r--r--fr-fr/hy-fr.html.markdown180
-rw-r--r--fr-fr/javascript-fr.html.markdown264
-rw-r--r--fr-fr/markdown.html.markdown2
-rw-r--r--fr-fr/perl-fr.html.markdown174
-rw-r--r--fr-fr/python3-fr.html.markdown2
-rw-r--r--fr-fr/typescript-fr.html.markdown58
-rw-r--r--fsharp.html.markdown6
-rw-r--r--haskell.html.markdown2
-rw-r--r--hu-hu/coffeescript-hu.html.markdown3
-rw-r--r--javascript.html.markdown7
-rw-r--r--json.html.markdown51
-rw-r--r--julia.html.markdown16
-rw-r--r--latex.html.markdown10
-rw-r--r--less.html.markdown379
-rw-r--r--lt-lt/json-lt.html.markdown81
-rw-r--r--lua.html.markdown2
-rw-r--r--markdown.html.markdown235
-rw-r--r--matlab.html.markdown5
-rw-r--r--objective-c.html.markdown13
-rw-r--r--perl6.html.markdown31
-rw-r--r--pl-pl/python-pl.html.markdown159
-rw-r--r--pl-pl/ruby-pl.html.markdown593
-rw-r--r--powershell.html.markdown320
-rw-r--r--pt-br/javascript-pt.html.markdown3
-rw-r--r--python.html.markdown6
-rw-r--r--python3.html.markdown7
-rw-r--r--ru-ru/.directory4
-rw-r--r--ru-ru/bash-ru.html.markdown9
-rw-r--r--ru-ru/d-ru.html.markdown753
-rw-r--r--ru-ru/erlang-ru.html.markdown2
-rw-r--r--ru-ru/objective-c-ru.html.markdown27
-rw-r--r--ru-ru/perl-ru.html.markdown195
-rw-r--r--ru-ru/python3-ru.html.markdown2
-rw-r--r--ruby.html.markdown10
-rw-r--r--sass.html.markdown203
-rw-r--r--scala.html.markdown9
-rw-r--r--sk-sk/LearnGit-sk.txt208
-rw-r--r--sk-sk/git.html.markdown523
-rw-r--r--sk-sk/latex.html.markdown.tex227
-rw-r--r--sk-sk/learn-latex-sk.tex209
-rw-r--r--swift.html.markdown160
-rw-r--r--tr-tr/python3-tr.html.markdown2
-rw-r--r--typescript.html.markdown60
-rw-r--r--uk-ua/bash-ua.html.markdown296
-rw-r--r--uk-ua/javascript-ua.html.markdown (renamed from ua-ua/javascript-ua.html.markdown)92
-rw-r--r--uk-ua/json-ua.html.markdown67
-rw-r--r--visualbasic.html.markdown126
-rw-r--r--whip.html.markdown8
-rw-r--r--yaml.html.markdown33
-rw-r--r--zh-cn/python3-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown131
-rw-r--r--zh-tw/python-tw.html.markdown727
78 files changed, 8872 insertions, 768 deletions
diff --git a/c++.html.markdown b/c++.html.markdown
index d03092e5..f4aa2f5a 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -149,7 +149,7 @@ namespace First {
namespace Second {
void foo()
{
- printf("This is Second::foo\n")
+ printf("This is Second::foo\n");
}
}
@@ -801,6 +801,24 @@ void doSomethingWithAFile(const std::string& filename)
// all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock
+// containers with object keys of non-primitive values (custom classes) require
+// compare function in the object itself or as a function pointer. Primitives
+// have default comparators, but you can override it.
+class Foo {
+public:
+ int j;
+ Foo(int a) : j(a) {}
+};
+struct compareFunction {
+ bool operator()(const Foo& a, const Foo& b) const {
+ return a.j < b.j;
+ }
+};
+//this isn't allowed (although it can vary depending on compiler)
+//std::map<Foo, int> fooMap;
+std::map<Foo, int, compareFunction> fooMap;
+fooMap[Foo(1)] = 1;
+fooMap.find(Foo(1)); //true
/////////////////////
// Fun stuff
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index d49ad254..482612fe 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -233,40 +233,38 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl
<em>Code for reference (Functions must return something to support IE)</em>
-<pre>
-&lt;cfcomponent&gt;
- &lt;cfset this.hello = "Hello" /&gt;
- &lt;cfset this.world = "world" /&gt;
-
- &lt;cffunction name="sayHello"&gt;
- &lt;cfreturn this.hello & ", " & this.world & "!" /&gt;
- &lt;/cffunction&gt;
+<cfcomponent>
+ <cfset this.hello = "Hello" />
+ <cfset this.world = "world" />
+
+ <cffunction name="sayHello">
+ <cfreturn this.hello & ", " & this.world & "!" />
+ </cffunction>
- &lt;cffunction name="setHello"&gt;
- &lt;cfargument name="newHello" type="string" required="true" /&gt;
+ <cffunction name="setHello">
+ <cfargument name="newHello" type="string" required="true" />
- &lt;cfset this.hello = arguments.newHello /&gt;
+ <cfset this.hello = arguments.newHello />
- &lt;cfreturn true /&gt;
- &lt;/cffunction&gt;
+ <cfreturn true />
+ </cffunction>
- &lt;cffunction name="setWorld"&gt;
- &lt;cfargument name="newWorld" type="string" required="true" /&gt;
+ <cffunction name="setWorld">
+ <cfargument name="newWorld" type="string" required="true" />
- &lt;cfset this.world = arguments.newWorld /&gt;
+ <cfset this.world = arguments.newWorld />
- &lt;cfreturn true /&gt;
- &lt;/cffunction&gt;
+ <cfreturn true />
+ </cffunction>
- &lt;cffunction name="getHello"&gt;
- &lt;cfreturn this.hello /&gt;
- &lt;/cffunction&gt;
+ <cffunction name="getHello">
+ <cfreturn this.hello />
+ </cffunction>
- &lt;cffunction name="getWorld"&gt;
- &lt;cfreturn this.world /&gt;
- &lt;/cffunction&gt;
-&lt;/cfcomponent&gt;
-</pre>
+ <cffunction name="getWorld">
+ <cfreturn this.world />
+ </cffunction>
+</cfcomponent>
<cfset this.hello = "Hello" />
<cfset this.world = "world" />
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index 63183c1e..2b1f5de4 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -614,9 +614,16 @@ nil ; for false - and the empty list
## Further Reading
-[Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
+* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
+* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf)
+## Extra Info
+
+* [CLiki](http://www.cliki.net/)
+* [common-lisp.net](https://common-lisp.net/)
+* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
+
## Credits.
Lots of thanks to the Scheme people for rolling up a great starting
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
new file mode 100644
index 00000000..637f0ab6
--- /dev/null
+++ b/cs-cz/markdown.html.markdown
@@ -0,0 +1,258 @@
+---
+language: markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Michal Martinek", "https://github.com/MichalMartinek"]
+filename: markdown.md
+---
+
+Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná
+a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
+dalších formátů)
+
+```markdown
+<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
+Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
+nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v
+Markdownu, tak nemůžete používat syntaxi Markdownu uvnitř tohoto elementu. -->
+
+<!-- Markdown se také mírně liší v jednotlivých interpretacích parseru. Tento
+návod vás bude upozorňovat, které vlastnosti jsou obecné a které specifické pro
+konkrétní parser. -->
+
+<!-- Nadpisy -->
+<!-- Můžete vytvořit HTML elementy <h1> až <h6> jednoduše tak, že text předsadíte
+počtem křížků (#), podle toho jaké úrovně to má být nadpis -->
+# Toto je <h1>
+## Toto je <h2>
+### Toto je <h3>
+#### Toto je <h4>
+##### Toto je <h5>
+###### Toto je <h6>
+
+<!-- Markdown obsahuje taky dvě další cesty, jak udělat h1 a h2 -->
+Toto je h1
+==========
+
+Toto je h2
+----------
+
+<!-- Jednoduché stylování textu -->
+<!-- Pomocí markdownu můžete text jednoduše označit jako kurzívu či tučný -->
+
+*Tento text je kurzívou;*
+_Stejně jako tento._
+
+**Tento text je tučně**
+__Stejně jako tento.__
+
+***Tento text je obojí***
+**_Jako tento!_**
+*__A tento!__*
+
+<!-- Ve verzi Markdownu od Githubu, máme k dispozici taky prošktrnutí: -->
+
+~~Tento text je prošktrnutý.~~
+
+<!-- Odstavce jsou jedna nebo více řádek textu, oddělených jednou nebo více prázdnými řádky. -->
+
+Toto je odstavec. Píši odstavec, není to zábava?
+
+Teď jsem v odstavci 2.
+Jsem pořád v odstavci 2!
+
+
+Toto je odstavec 3.
+
+<!-- Chtěli jste někdy vložit znak <br /> tag? Můžete napsat na konec odstavce
+dvě nebo více mezer a potom začít nový odstavec. -->
+
+Tento odstavec končí dvěma mezerami.
+
+Nad tímto odstavcem je <br />!
+
+<!-- Blokové citace se dělají jednoduše pomocí znaku >. -->
+
+> Toto je bloková citace. Můžete dokonce
+> manuálně rozdělit řádky, a před každý vložit >, nebo nechat vaše řádky jakkoliv dlouhé, ať se zarovnají sami.
+> Nedělá to rozdíl, dokud začínáte vždy znakem >.
+
+> Můžu použít více než jednu
+>> odsazení?
+> Jak je to úhledné, že?
+
+<!-- Seznamy -->
+<!-- Nečíslovaný seznam můžete jednoduše udělat pomocí hvězdiček, plusů, nebo
+ pomlček -->
+
+* Položka
+* Položka
+* Jinná položka
+
+nebo
+
++ Položka
++ Položka
++ Další položka
+
+nebo
+
+- Položka
+- Položka
+- Další položka
+
+<!-- Číslovaný seznam se dělají pomocí čísla a . -->
+
+1. Položka jedna
+2. Položka dvě
+3. Položka tři
+
+<!-- Nemusíte dokonce psát čísla správně a markdown je zobrazi správně,
+ ale nemusí to být vždy dobrý nápad -->
+
+1. Položka jedna
+1. Položka dvě
+1. Položka tři
+<!-- (Toto zobrazí to samě, jako příklad nadtím.) -->
+
+<!-- Můžete také tvořit podseznamy -->
+
+1. Položka jedna
+2. Položka dvě
+3. Položka tři
+ * Podpoložka
+ * Podpoložka
+4. Položka čtyři
+
+<!-- Existují i zašktávací seznamy. Toto vytvoří HTML checkboxy. -->
+
+Boxy níže bez 'x' jsou nezašktrnuté checkboxy.
+- [ ] První úkol
+- [ ] Druhý úkol
+Tento box bude zašktrnutý
+- [x] Tento úkol byl dokončen
+
+<!-- Bloky ködu -->
+<!-- Můžete označit kód bloku (který používá <code> element) odsazením pomocí 4
+ mezer, nebo tabu -->
+
+ Toto je kód
+ Stejně jako toto
+
+<!-- Můžete dokonce přidat další 4 mezery nebo tab pro další odsazení -->
+
+ moje_pole.each do |i|
+ puts i
+ end
+
+<!-- Kód na řádku může být označen pomocí zpětných apostrofů ` -->
+
+Jan nevědel, jak se dělá `go_to()` funkce!
+
+<!-- V Markdownu od Githubu , můžete použít speciální syntaxi pro kód -->
+
+\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
+def neco
+ puts "Ahoj světe!"
+end
+\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
+
+<!-- Text výše nepotřebuje odsazení a navíc Github použije zvýraznění označeného
+ jazyka. -->
+
+<!-- Horizontální čára (<hr />) -->
+<!-- Horizontální čára se jednoduše přidá pomocí 3 nebo více hvězdiček nebo pomlček
+s nebo bez mezer. -->
+
+***
+---
+- - -
+****************
+
+<!-- Odkazy -->
+<!-- Jedna z nejlepších věcí na Markdownu je, jak jednoduše se dělají odkazy.
+Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a je to. -->
+
+[Klikni na mě!](http://test.com/)
+
+<!-- Můžete také přidat jméno linku pomocí uvozovek -->
+
+[Klikni na mě!](http://test.com/ "Odkaz na Test.com")
+
+<!-- Relativní cesty fungují taky -->
+
+[Jdi na hudbu](/hudba/).
+
+<!-- Markdown taktéž podporuje reference odkazů. -->
+
+[Klikni na tento odkaz][link1] pro více informací!
+[Taky zkontrolujte tento odkaz][neco], když chcete.
+
+[link1]: http://test.com/ "Cool!"
+[neco]: http://neco.czz/ "Dobře!"
+
+<!-- Titulek může být v apostrofech nebo závorkách, nebo vyjmutý úplně. Reference
+ může být kdekoliv ve vašem dokumentu a identifikátor může být jakýkoliv, dokud
+ je unikátní.-->
+
+<!-- Také existuje "implicitní pojmenování", které použije text jako id -->
+
+[Toto][] je odkaz..
+
+[toto]: http://totojelink.cz/
+
+<!-- Ale toto není zrovna běžné užívané. -->
+
+<!-- Obrázky -->
+<!-- Obrázky se dělají stejně jako odkazy, ale s vykřičníkem na začátku -->
+
+![Toto je atribut alt pro obrázek](http://imgur.com/myimage.jpg "Nepovinný titulek")
+
+<!-- Reference fungují, jak bychom čekali-->
+
+![Toto je atribut alt][mujobrazek]
+
+[mujobrazek]: relativni/cesta/obrazek.jpg "a toto by byl titulek"
+
+<!-- Ostatní -->
+<!-- Automatické odkazy -->
+
+<http://stranka.cz/> je stejná jako
+[http://stranka.cz/](http://stranka.cz/)
+
+<!-- Automatické odkazy pro emaily-->
+
+<jmeno@prijmeni.cz>
+
+<!-- Escapování znaků -->
+
+Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*.
+
+<!-- Klávesové zkratky -->
+<!-- V Markdownu od Githubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
+
+Váš počítač přestal pracovat? Zkuste
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+
+<!-- Tabulky -->
+<!-- Tabulky jsou povolené pouze v Markdownu od Githubu a jsou trochu podivně,
+ ale když je opravdu chcete: -->
+
+| Sloupec1 | Sloupec2 | Sloupec3 |
+| :----------- | :------: | ------------: |
+| Vlevo zarovn.| Na střed | Vpravo zarovn.|
+| blah | blah | blah |
+
+<!-- nebo, to jde i taky: -->
+
+Sloupec 1 | Sloupec2 | Sloupec3
+:-- | :-: | --:
+Ohh toto je tak ošklivé | radši to | nedělejte
+
+<!-- Konec -->
+
+```
+
+Pro více informací, prozkoumejte oficiální článek o syntaxi od Johna Grubera
+ [zde](http://daringfireball.net/projects/markdown/syntax) a skvělý tahák od Adama Pritcharda [zde](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown
index 6d2fd1eb..b498046a 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python3.html.markdown
@@ -566,7 +566,7 @@ Clovek.odkaslej_si() # => "*ehm*"
# Lze importovat moduly
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16.0)) # => 4
# Lze také importovat pouze vybrané funkce z modulu
from math import ceil, floor
diff --git a/cs-cz/sass.html.markdown b/cs-cz/sass.html.markdown
new file mode 100644
index 00000000..0d2fca64
--- /dev/null
+++ b/cs-cz/sass.html.markdown
@@ -0,0 +1,439 @@
+---
+language: sass
+filename: learnsass-cz.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+translators:
+ - ["Michal Martinek", "https://github.com/MichalMartinek"]
+lang: cs-cz
+---
+
+Sass je rozšíření jazyka CSS, který přidává nové vlastnosti jako proměnné, zanořování, mixiny a další.
+Sass (a další preprocesory, jako [Less](http://lesscss.org/)) pomáhají vývojářům psát udržovatelný a neopakující (DRY) kód.
+
+Sass nabízí dvě možnosti syntaxe. SCSS, které je stejná jako CSS, akorát obsahuje nové vlastnosti Sassu. Nebo Sass, který používá odsazení místo složených závorek a středníků.
+Tento tutoriál bude používat syntaxi CSS.
+
+
+Pokud jste již obeznámeni s CSS3, budete schopni používat Sass relativně rychle. Nezprostředkovává nějaké úplně nové stylové možnosti, spíše nátroje, jak psát Vás CSS kód více efektivně, udržitelně a jednoduše.
+
+```scss
+
+
+//Jednořádkové komentáře jsou ze Sassu při kompilaci vymazány
+
+/*Víceřádkové komentáře jsou naopak zachovány */
+
+
+
+/*Proměnné
+==============================*/
+
+
+
+/* Můžete uložit CSS hodnotu (jako třeba barvu) do proměnné.
+Použijte symbol '$' k jejímu vytvoření. */
+
+$hlavni-barva: #A3A4FF;
+$sekundarni-barva: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Můžete používat proměnné napříč vaším souborem.
+Teď, když chcete změnit barvu, stačí ji změnit pouze jednou.*/
+
+body {
+ background-color: $hlavni-barva;
+ color: $sekundarni-barva;
+ font-family: $body-font;
+}
+
+/* Toto se zkompiluje do: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* Toto je o hodně více praktické, než měnit každý výskyt barvy. */
+
+
+
+/*Mixiny
+==============================*/
+
+
+
+/* Pokud zjistíte, že píšete kód pro více než jeden element, můžete jej uložit do mixinu.
+
+Použijte '@mixin' direktivu, plus jméno vašeho mixinu.*/
+
+@mixin na-stred {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Mixin vložíte pomocí '@include' a jména mixinu */
+
+div {
+ @include na-stred;
+ background-color: $hlavni-barva;
+}
+
+/*Což se zkompiluje do: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* Můžete využít mixiny i třeba pro takovéto ušetření práce: */
+
+@mixin velikost($sirka, $vyska) {
+ width: $sirka;
+ height: $vyska;
+}
+
+/*Stačí vložit argumenty: */
+
+.obdelnik {
+ @include velikost(100px, 60px);
+}
+
+.ctverec {
+ @include velikost(40px, 40px);
+}
+
+/* Toto se zkompiluje do: */
+.obdelnik {
+ width: 100px;
+ height: 60px;
+}
+
+.ctverec {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/*Funkce
+==============================*/
+
+
+
+/* Sass obsahuje funkce, které vám pomůžou splnit různé úkoly. */
+
+/* Funkce se spouštějí pomocí jejich jména, které následuje seznam argumentů uzavřený v kulatých závorkách. */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Se zkompiluje do: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* Můžete také definovat vlastní funkce. Funkce jsou velmi podobné mixinům.
+ Když se snažíte vybrat mezi funkcí a mixinem, mějte na paměti, že mixiny
+ jsou lepší pro generování CSS kódu, zatímco funkce jsou lepší pro logiku.
+ Příklady ze sekce Matematické operátory jsou skvělí kandidáti na
+ znovupoužitelné funkce. */
+
+/* Tato funkce vrací poměr k velikosti rodiče v procentech.
+@function vypocitat-pomer($velikost, $velikost-rodice) {
+ @return $velikost / $velikost-rodice * 100%;
+}
+
+$hlavni obsah: vypocitat-pomer(600px, 960px);
+
+.hlavni-obsah {
+ width: $hlavni-obsah;
+}
+
+.sloupec {
+ width: vypocitat-pomer(300px, 960px);
+}
+
+/* Zkompiluje do: */
+
+.hlavni-obsah {
+ width: 62.5%;
+}
+
+.sloupec {
+ width: 31.25%;
+}
+
+
+
+/*Dědění
+==============================*/
+
+
+
+/*Dědění je způsob jak používat vlastnosti pro jeden selektor ve druhém. */
+
+.oznameni {
+ @include velikost(5em, 5em);
+ border: 5px solid $sekundarni-barva;
+}
+
+.oznameni-uspech {
+ @extend .oznameni;
+ border-color: #22df56;
+}
+
+/* Zkompiluje do: */
+.oznameni, .oznameni-uspech {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.oznameni-uspech {
+ border-color: #22df56;
+}
+
+
+/* Dědění CSS výrazů je preferováno před vytvořením mixinu kvůli způsobu,
+ jakým způsobem Sass dává dohromady třídy, které sdílejí stejný kód.
+ Kdyby to bylo udělané pomocí mixinu, tak výška, šířka, rámeček by byl v
+ každém výrazu, který by volal mixin. I když tohle neovlivní vaše workflow,
+ přidá to kód navíc do souborů. */
+
+
+/*Zanořování
+==============================*/
+
+
+
+/*Sass vám umožňuje zanořovat selektory do selektorů */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' nahradí rodičovský element. */
+/* Můžete také zanořovat pseudo třídy. */
+/* Pamatujte, že moc velké zanoření do hloubky snižuje čitelnost.
+ Doporučuje se používat maximálně trojité zanoření.
+ Na příklad: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Zkompiluje do: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Částečné soubory a importy
+==============================*/
+
+
+
+/* Sass umožňuje vytvářet částečné soubory. Tyto soubory pomahájí udržovat váš
+ kód modulární. Tyto soubory by měli začínat vždy '_', např. _reset.css.
+ Částečné soubory se nepřevádí do CSS. */
+
+/* Toto je kód, který si uložíme do souboru _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass obsahuje @import, které může být použit pro import částečných souborů.
+ Toto se liší od klasického CSS @import, který dělá HTTP požadavek na stáhnutí
+ souboru. Sass vezme importovaný soubor a vloží ho do kompilovaného kódu. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Zkompiluje do: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Zástupné selektory
+==============================*/
+
+
+
+/* Zástupné selektory jsou užitečné, když vytváříte CSS výraz, ze kterého
+ chcete později dědit. Když chcete vytvořit výraz, ze kterého je možné pouze
+ dědit pomocí @extend, vytvořte zástupný selektor s CSS výrazem. Ten začíná
+ symbolem '%' místo '.' nebo '#'. Tyto výrazy se neobjeví ve výsledném CSS */
+
+%okno-obsahu {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.okno-zpravy {
+ @extend %okno-obsahu;
+ background-color: #0000ff;
+}
+
+/* Zkompiluje do: */
+
+.okno-zpravy {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.okno-zpravy {
+ background-color: #0000ff;
+}
+
+
+
+/*Matematické operace
+==============================*/
+
+
+
+/* Sass obsahuje následující operátory: +, -, *, /, and %. Tyto operátory
+ můžou být velmi užitečné pro počítání hodnot přímo ve vašem souboru Sass.
+ Níže je příklad, jak udělat jednoduchý dvousloupcový layout. */
+
+$oblast-obsahu: 960px;
+$hlavni-obsah: 600px;
+$vedlejsi-sloupec: 300px;
+
+$obsah-velikost: $hlavni-obsah / $oblast-obsahu * 100%;
+$vedlejsi-sloupec-velikost: $vedlejsi-sloupec / $oblast-obsahu * 100%;
+$zbytek-velikost: 100% - ($main-size + $vedlejsi-sloupec-size);
+
+body {
+ width: 100%;
+}
+
+.hlavni-obsah {
+ width: $obsah-velikost;
+}
+
+.vedlejsi-sloupec {
+ width: $vedlejsi-sloupec-velikost;
+}
+
+.zbytek {
+ width: $zbytek-velikost;
+}
+
+/* Zkompiluje do: */
+
+body {
+ width: 100%;
+}
+
+.hlavni-obsah {
+ width: 62.5%;
+}
+
+.vedlejsi-sloupec {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+
+
+## SASS nebo Sass?
+Divili jste se někdy, jestli je Sass zkratka nebo ne? Pravděpodobně ne, ale řeknu vám to stejně. Jméno tohoto jazyka je slovo, "Sass", a ne zkratka.
+Protože to lidé konstatně píší jako "SASS", nazval ho autor jazyka jako "Syntactically Awesome StyleSheets" (Syntaktický úžasně styly).
+
+
+## Procvičování Sassu
+Pokud si chcete hrát se Sassem ve vašem prohlížeči, navštivte [SassMeister](http://sassmeister.com/).
+Můžete používát oba dva způsoby zápisu, stačí si vybrat v nastavení SCSS nebo SASS.
+
+
+## Kompatibilita
+
+Sass může být použit v jakémkoliv projektu, jakmile máte program, pomocí kterého ho zkompilujete do CSS. Pokud si chcete ověřit, že CSS, které Sass produkuje je kompatibilní s prohlížeči:
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) a [CanIUse](http://caniuse.com) jsou skvělé stránky pro kontrolu kompatibility.
+
+
+## Kam dál?
+* [Oficiální dokumentace](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) obsahuje tutoriál a řadu skvělých článků
diff --git a/csharp.html.markdown b/csharp.html.markdown
index dfdd98de..677c2591 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -45,8 +45,8 @@ using System.Data.Entity;
// Using this code from another source file: using Learning.CSharp;
namespace Learning.CSharp
{
- // Each .cs file should at least contain a class with the same name as the file
- // you're allowed to do otherwise, but shouldn't for sanity.
+ // Each .cs file should at least contain a class with the same name as the file.
+ // You're allowed to do otherwise, but shouldn't for sanity.
public class LearnCSharp
{
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
diff --git a/d.html.markdown b/d.html.markdown
index 6f3710ab..6f88cf84 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -53,15 +53,15 @@ void main() {
// For and while are nice, but in D-land we prefer 'foreach' loops.
// The '..' creates a continuous range, including the first value
// but excluding the last.
- foreach(i; 1..1_000_000) {
+ foreach(n; 1..1_000_000) {
if(n % 2 == 0)
- writeln(i);
+ writeln(n);
}
// There's also 'foreach_reverse' when you want to loop backwards.
- foreach_reverse(i; 1..int.max) {
+ foreach_reverse(n; 1..int.max) {
if(n % 2 == 1) {
- writeln(i);
+ writeln(n);
} else {
writeln("No!");
}
@@ -70,7 +70,7 @@ void main() {
```
We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions
-are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore,
+are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore,
we can use templates to parameterize all of these on both types and values!
```c
@@ -218,7 +218,7 @@ void main() {
// from 1 to 100. Easy!
// Just pass lambda expressions as template parameters!
- // You can pass any old function you like, but lambdas are convenient here.
+ // You can pass any function you like, but lambdas are convenient here.
auto num = iota(1, 101).filter!(x => x % 2 == 0)
.map!(y => y ^^ 2)
.reduce!((a, b) => a + b);
@@ -228,7 +228,7 @@ void main() {
```
Notice how we got to build a nice Haskellian pipeline to compute num?
-That's thanks to a D innovation know as Uniform Function Call Syntax.
+That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS).
With UFCS, we can choose whether to write a function call as a method
or free function call! Walter wrote a nice article on this
[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
@@ -238,21 +238,23 @@ is of some type A on any expression of type A as a method.
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
```c
+// Let's say we want to populate a large array with the square root of all
+// consecutive integers starting from 1 (up until the size of the array), and we
+// want to do this concurrently taking advantage of as many cores as we have
+// available.
+
import std.stdio;
import std.parallelism : parallel;
import std.math : sqrt;
void main() {
- // We want take the square root every number in our array,
- // and take advantage of as many cores as we have available.
+ // Create your large array
auto arr = new double[1_000_000];
- // Use an index, and an array element by reference,
- // and just call parallel on the array!
+ // Use an index, access every array element by reference (because we're
+ // going to change each element) and just call parallel on the array!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
}
}
-
-
```
diff --git a/dart.html.markdown b/dart.html.markdown
index f7601271..fc7b220e 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -498,7 +498,7 @@ main() {
## Further Reading
-Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a
+Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
useful Try Dart online.
http://www.dartlang.org/
http://try.dartlang.org/
diff --git a/edn.html.markdown b/edn.html.markdown
index 0a0dc9b5..d0bdddfc 100644
--- a/edn.html.markdown
+++ b/edn.html.markdown
@@ -5,13 +5,13 @@ contributors:
- ["Jason Yeo", "https://github.com/jsyeo"]
---
-Extensible Data Notation or EDN for short is a format for serializing data.
+Extensible Data Notation (EDN) is a format for serializing data.
-The notation is used internally by Clojure to represent programs and it also
+The notation is used internally by Clojure to represent programs. It is also
used as a data transfer format like JSON. Though it is more commonly used in
-Clojure land, there are implementations of EDN for many other languages.
+Clojure, there are implementations of EDN for many other languages.
-The main benefit of EDN over JSON and YAML is that it is extensible, which we
+The main benefit of EDN over JSON and YAML is that it is extensible. We
will see how it is extended later on.
```Clojure
@@ -59,7 +59,7 @@ false
; Vectors allow random access
[:gelato 1 2 -2]
-; Maps are associative data structures that associates the key with its value
+; Maps are associative data structures that associate the key with its value
{:eggs 2
:lemon-juice 3.5
:butter 1}
@@ -68,7 +68,7 @@ false
{[1 2 3 4] "tell the people what she wore",
[5 6 7 8] "the more you see the more you hate"}
-; You may use commas for readability. They are treated as whitespaces.
+; You may use commas for readability. They are treated as whitespace.
; Sets are collections that contain unique elements.
#{:a :b 88 "huat"}
@@ -82,11 +82,11 @@ false
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
; Let me explain this with a clojure example. Suppose I want to transform that
-; piece of edn into a MenuItem record.
+; piece of EDN into a MenuItem record.
(defrecord MenuItem [name rating])
-; To transform edn to clojure values, I will need to use the built in EDN
+; To transform EDN to clojure values, I will need to use the built in EDN
; reader, edn/read-string
(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
diff --git a/elisp.html.markdown b/elisp.html.markdown
index 3bed5d1c..da86cab3 100644
--- a/elisp.html.markdown
+++ b/elisp.html.markdown
@@ -2,6 +2,7 @@
language: elisp
contributors:
- ["Bastien Guerry", "http://bzg.fr"]
+ - ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
filename: learn-emacs-lisp.el
---
@@ -26,7 +27,7 @@ filename: learn-emacs-lisp.el
;;
;; Going through this tutorial won't damage your computer unless
;; you get so angry that you throw it on the floor. In that case,
-;; I hereby decline any responsability. Have fun!
+;; I hereby decline any responsibility. Have fun!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
diff --git a/elixir.html.markdown b/elixir.html.markdown
index eedeb227..720e080c 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -343,6 +343,7 @@ rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
+#=> "rescued a runtime error"
# All exceptions have a message
try do
@@ -351,6 +352,7 @@ rescue
x in [RuntimeError] ->
x.message
end
+#=> "some error"
## ---------------------------
## -- Concurrency
diff --git a/elm.html.markdown b/elm.html.markdown
new file mode 100644
index 00000000..8c191509
--- /dev/null
+++ b/elm.html.markdown
@@ -0,0 +1,346 @@
+---
+language: Elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+---
+
+Elm is a functional reactive programming language that compiles to (client-side)
+JavaScript. Elm is statically typed, meaning that the compiler catches most
+errors immediately and provides a clear and understandable error message. Elm is
+great for designing user interfaces and games for the web.
+
+
+```haskell
+-- Single line comments start with two dashes.
+{- Multiline comments can be enclosed in a block like this.
+{- They can be nested. -}
+-}
+
+{-- The Basics --}
+
+-- Arithmetic
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Every number literal without a decimal point can be either an Int or a Float.
+33 / 2 -- 16.5 with floating point division
+33 // 2 -- 16 with integer division
+
+-- Exponents
+5 ^ 2 -- 25
+
+-- Booleans
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings and characters
+"This is a string."
+'a' -- character
+'You cant use single quotes for strings.' -- error!
+
+-- Strings can be appended
+"Hello " ++ "world!" -- "Hello world!"
+
+{-- Lists, Tuples, and Records --}
+
+-- Every element in a list must have the same type.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- The second example can also be written with two dots.
+[1..5]
+
+-- Append lists just like strings
+[1..5] ++ [6..10] == [1..10] -- True
+
+-- To add one item, use "cons"
+0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- The head and tail of a list are returned as a Maybe. Instead of checking
+-- every value to see if it's null, you deal with missing values explicitly.
+List.head [1..5] -- Just 1
+List.tail [1..5] -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+
+-- Every element in a tuple can be a different type, but a tuple has a
+-- fixed length.
+("elm", 42)
+
+-- Access the elements of a pair with the first and second functions.
+-- (This is a shortcut; we'll come to the "real way" in a bit.)
+fst ("elm", 42) -- "elm"
+snd ("elm", 42) -- 42
+
+-- Records are like tuples but the fields have names.
+-- Notice that equals signs, not colons, are used.
+{ x = 3, y = 7}
+
+-- Access a field with a dot and the field name.
+{ x = 3, y = 7}.x -- 3
+
+-- Or with an accessor fuction, a dot and then the field name.
+.y { x = 3, y = 7} -- 7
+
+-- Update the fields of a record. (It must have the fields already.)
+{ person |
+ name = "George" }
+
+{ physics |
+ position = physics.position + physics.velocity,
+ velocity = physics.velocity + physics.acceleration }
+
+{-- Control Flow --}
+
+-- If statements always have an else, and the branches must be the same type.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- If statements can be chained.
+if n < 0 then
+ "n is negative"
+else if n > 0 then
+ "n is positive"
+else
+ "n is zero"
+
+-- Use case statements to pattern match on different possibilities.
+case aList of
+ [] -> "matches the empty list"
+ x::xs -> "matches a list of at least one item whose head is " ++ toString x
+
+case List.head aList of
+ Just x -> "The head is " ++ toString x
+ Nothing -> "The list was empty"
+
+{-- Functions --}
+
+-- Elm's syntax for functions is very minimal, relying mostly on whitespace
+-- rather than parentheses and curly brackets. There is no "return" keyword.
+
+-- Define a function with its name, arguments, an equals sign, and the body.
+multiply a b =
+ a * b
+
+-- Apply (call) a function by passing it arguments (no commas necessay).
+multiply 7 6 -- 42
+
+-- Partially apply a function by passing only some of its arguments.
+-- Then give that function a new name.
+double =
+ multiply 2
+
+-- Constants are similar, except there are no arguments.
+answer =
+ 42
+
+-- Pass functions as arguments to other functions.
+List.map double [1..4] -- [2, 4, 6, 8]
+
+-- Or write an anonymous function.
+List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
+
+-- You can pattern match in function definitions when there's only one case.
+-- This function takes one tuple rather than two arguments.
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Use curly brackets to pattern match record field names
+-- Use let to define intermediate values
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Functions can be recursive
+fib n =
+ if n < 2 then
+ 1
+ else
+ fib (n - 1) + fib (n - 2)
+
+List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34]
+
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Function application happens before any infix operation
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- First degrees is applied to 30, then the result is passed to the trig
+-- functions, which is then squared, and the addition happens last.
+
+{-- Types and Type Annotations --}
+
+-- The compiler will infer the type of every value in your program.
+-- Types are always uppercase. Read x : T as "x has type T".
+-- Some common types, which you might see in Elm's REPL.
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Functions have types too. Read -> as "goes to". Think of the rightmost type
+-- as the type of the return value.
+not : Bool -> Bool
+round : Float -> Int
+
+-- When you define a value, it's good practice to write its type above it.
+-- The annotation is a form of documentation, which is verified by the compiler.
+double : Int -> Int
+double x = x * 2
+
+-- Function arguments are passed in parentheses.
+-- Lowercase types are type variables: they can be any type, as long as each
+-- call is consistent.
+List.map : (a -> b) -> List a -> List b
+-- "List dot map has type a-goes-to-b, goes to list of a, goes to list of b."
+
+-- There are three special lowercase types: number, comparable, and appendable.
+-- Numbers allow you to use arithmetic on Ints and Floats.
+-- Comparable allows you to order numbers and strings, like a < b.
+-- Appendable things can be combined with a ++ b.
+
+{-- Type Aliases and Union Types --}
+
+-- When you write a record or tuple, its type already exists.
+-- (Notice that record types use colon and record values use equals.)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- You can give existing types a nice name with a type alias.
+type alias Point3D = { x : Float, y : Float, z : Float }
+
+-- If you alias a record, you can use the name as a constructor function.
+otherOrigin : Point3D
+otherOrigin = Point3D 0 0 0
+
+-- But it's still the same type, you can equate them
+origin == otherOrigin -- True
+
+-- By contrast, defining a union type creates a type that didn't exist before.
+-- A union type is so called because it can be one of many possibilities.
+-- Each of the possibilities is represented as a "tag".
+type Direction = North | South | East | West
+
+-- Tags can carry other values of known type. This can work recursively.
+type IntTree = Leaf | Node Int IntTree IntTree
+
+-- "Leaf" and "Node" are the tags. Everything following a tag is a type.
+-- Tags can be used as values or functions.
+root : IntTree
+root = Node 7 Leaf Leaf
+
+-- Union types (and type aliases) can use type variables.
+type Tree a = Leaf | Node a (Tree a) (Tree a)
+
+-- You can pattern match union tags. The uppercase tags must be matched exactly.
+-- The lowercase variables will match anything. Underscore also matches
+-- anything, but signifies that you aren't using it.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+-- That's pretty much it for the language itself. Now let's see how to organize
+-- and run your code.
+
+{-- Modules and Imports --}
+
+-- The core libraries are organized into modulues, as are any third-party
+-- libraries you may use. For large projects, you can define your own modulues.
+
+-- Put this at the top of the file. If omitted, you're in Main.
+module Name where
+
+-- By default, everything is exported.
+-- Limit what values and types are exported
+module Name (Type, value) where
+
+-- One common pattern is to export a union type but not its tags. This is known
+-- as an "opaque type", and is frequently used in libraries.
+
+-- Import code from other modules to use it in this one
+-- Places Dict in scope, so you can call Dict.insert
+import Dict
+
+-- Imports the Dict module and the Dict type, so your annotations don't have to
+-- say Dict.Dict. You can still use Dict.insert.
+import Dict exposing (Dict)
+
+-- Rename an import.
+import Graphics.Collage as C
+
+{-- Ports --}
+
+-- A port indicates that you will be communicating with the outside world.
+-- Ports are only allowed in the Main module.
+
+-- An incoming port is just a type signature.
+port clientID : Int
+
+-- An outgoing port has a defintion.
+port clientOrders : List String
+port clientOrders = ["Books", "Groceries", "Furniture"]
+
+-- We won't go into the details, but you set up callbacks in JavaScript to send
+-- on incoming ports and receive on outgoing ports.
+
+{-- Command Line Tools --}
+
+-- Compile a file.
+$ elm make MyFile.elm
+
+-- The first time you do this, Elm will install the core libraries and create
+-- elm-package.json, where information about your project is kept.
+
+-- The reactor is a server that compiles and runs your files.
+-- Click the wrench next to file names to enter the time-travelling debugger!
+$ elm reactor
+
+-- Experiment with simple expressions in a Read-Eval-Print Loop.
+$ elm repl
+
+-- Packages are identified by GitHub username and repo name.
+-- Install a new package, and record it in elm-package.json.
+$ elm package install evancz/elm-html
+
+-- Elm's package manager enforces semantic versioning, so minor version bumps
+-- will never break your build!
+```
+
+The Elm language is surprisingly small. You can now look through almost any Elm
+source code and have a rough idea of what is going on. However, the possibilties
+for error-resistant and easy-to-refactor code are endless!
+
+Here are some useful resources.
+
+* The [Elm website](http://elm-lang.org/). Includes:
+ * Links to the [installers](http://elm-lang.org/install)
+ * [Documentation guides](http://elm-lang.org/docs), including the [syntax reference](http://elm-lang.org/docs/syntax)
+ * Lots of helpful [examples](http://elm-lang.org/examples)
+
+* Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of:
+ * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default
+ * Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [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) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components.
+
+* The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful.
+
+
+Go out and write some Elm!
diff --git a/erlang.html.markdown b/erlang.html.markdown
index d6ed7b86..a57f295f 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -177,7 +177,7 @@ is_dog(A) -> false.
% A guard sequence is either a single guard or a series of guards, separated
% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at
% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`.
-is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true;
+is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true;
is_pet(A) -> false.
% Warning: not all valid Erlang expressions can be used as guard expressions;
diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown
index e33d672d..550511da 100644
--- a/es-es/brainfuck-es.html.markdown
+++ b/es-es/brainfuck-es.html.markdown
@@ -9,8 +9,10 @@ lang: es-es
---
Brainfuck (con mayúscula sólo al inicio de una oración) es un
-lenguaje de programación mínimo, computacionalmente universal
-en tamaño con sólo 8 comandos.
+lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos.
+
+Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
```
@@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
será ignorado.
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
-en cero y un apuntador en la celda actual.
+en cero y un puntero apuntando la celda actual.
Existen ocho comandos:
@@ -26,7 +28,7 @@ Existen ocho comandos:
- : Decrementa 1 al valor de la celda actual.
> : Mueve el apuntador a la siguiente celda. (a la derecha)
< : Mueve el apuntador a la celda anterior. (a la izquierda)
-. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
+. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A')
, : Lee un caracter como input y lo escribe en la celda actual.
[ : Si el valor en la celda actual es cero mueve el apuntador
hasta el primer ']' que encuentre. Si no es cero sigue a la
@@ -37,7 +39,7 @@ Existen ocho comandos:
[ y ] forman un while. Obviamente, deben estar balanceados.
-Ahora unos ejemplos de programas escritos con brainfuck.
+Estos son algunos ejemplos de programas escritos con brainfuck.
++++++ [ > ++++++++++ < - ] > +++++ .
@@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
-Ten en mente que los espacios son sólo para fines de legibilidad.
+Ten en cuenta que los espacios son sólo para fines de legibilidad.
Es lo mismo escribir el ejemplo de arriba que esto:
,[>+<-]>.
@@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
el resultado.
```
-Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
+Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
-intenta construir tu proprio intérprete de brainfuck... en brainfuck.
+puedes intentar construir tu propio intérprete de brainfuck... en brainfuck.
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 18b544b4..4e1e68ba 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente.
## Versionamiento, conceptos.
-### Qué es el control de versiones?
+### ¿Qué es el control de versiones?
El control de versiones es un sistema que guarda todos los cambios realizados en
uno o varios archivos, a lo largo del tiempo.
-### Versionamiento centralizado vs Versionamiento Distribuido.
+### Versionamiento centralizado vs versionamiento distribuido.
+ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
archivos.
@@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo.
[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
-### Por qué usar Git?
+### ¿Por qué usar Git?
-* Se puede trabajar sin conexion.
+* Se puede trabajar sin conexión.
* ¡Colaborar con otros es sencillo!.
* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
* Combinar (aka: Merging)
@@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo.
### Repositorio
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
-comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
+commits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
y que sus atributos otorgan acceso al historial del elemento, además de otras
cosas.
@@ -62,12 +62,12 @@ y mas.
### Directorio de trabajo (componentes del repositorio)
-Es basicamente los directorios y archivos dentro del repositorio. La mayoría de
+Es básicamente los directorios y archivos dentro del repositorio. La mayoría de
las veces se le llama "directorio de trabajo".
### Índice (componentes del directorio .git)
-El índice es el área de inicio en git. Es basicamente la capa que separa el
+El índice es el área de inicio en git. Es básicamente la capa que separa el
directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
más poder sobre lo que se envía y se recibe del repositorio.
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index d475cf42..9ef0c63e 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -30,7 +30,7 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto
// Cada sentencia puede ser terminada con punto y coma ;
hazAlgo();
-// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente
+// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente
// cada que se detecta una nueva línea, a excepción de algunos casos.
hazAlgo()
@@ -109,7 +109,7 @@ null == undefined; // = true
null === undefined; // false
// Los Strings funcionan como arreglos de caracteres
-// Puedes accesar a cada caracter con la función charAt()
+// Puedes acceder a cada caracter con la función charAt()
"Este es un String".charAt(0); // = 'E'
// ...o puedes usar la función substring() para acceder a pedazos más grandes
@@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor"
// agregar nuevas llaves.
miObjeto.miTerceraLlave = true;
-// Si intentas accesar con una llave que aún no está asignada tendrás undefined.
+// Si intentas acceder con una llave que aún no está asignada tendrás undefined.
miObjeto.miCuartaLlave; // = undefined
///////////////////////////////////
@@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per
//inmediatamente", que preveé variables temporales de fugarse al ámbito global
(function(){
var temporal = 5;
- // Podemos accesar al ámbito global asignando al 'objeto global', el cual
+ // Podemos acceder al ámbito global asignando al 'objeto global', el cual
// en un navegador siempre es 'window'. El objeto global puede tener
// un nombre diferente en ambientes distintos, por ejemplo Node.js .
window.permanente = 10;
@@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){
alert(texto);
}
setTimeout(interna, 5000);
- // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos
+ // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos
// terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos
// Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene
// acceso a la variable 'texto' cuando es llamada.
@@ -339,7 +339,7 @@ var miObjeto = {
};
miObjeto.miFuncion(); // = "¡Hola Mundo!"
-// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables
+// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables
// del objeto con la palabra clave 'this'.
miObjeto = {
miString: "¡Hola Mundo!",
@@ -401,11 +401,11 @@ var MiConstructor = function(){
miNuevoObjeto = new MiConstructor(); // = {miNumero: 5}
miNuevoObjeto.miNumero; // = 5
-// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una
+// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una
// propiedad en un objeto que no existe en el objeto el intérprete buscará en
// el prototipo.
-// Algunas implementaciones de JavaScript te permiten accesar al prototipo de
+// Algunas implementaciones de JavaScript te permiten acceder al prototipo de
// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar
// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos
// más adelante.
@@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43;
miObjeto.sentidoDeLaVida; // = 43
// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no
-// existe una forma estándar de accesar al prototipo de un objeto. De todas formas.
+// existe una forma estándar de acceder al prototipo de un objeto. De todas formas.
// hay dos formas de crear un nuevo objeto con un prototipo dado.
// El primer método es Object.create, el cual es una adición reciente a JavaScript,
@@ -476,7 +476,7 @@ typeof miNumero; // = 'number'
typeof miNumeroObjeto; // = 'object'
miNumero === miNumeroObjeyo; // = false
if (0){
- // Este código no se ejecutara porque 0 es false.
+ // Este código no se ejecutará porque 0 es false.
}
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown
index fff678eb..c98049f9 100644
--- a/es-es/json-es.html.markdown
+++ b/es-es/json-es.html.markdown
@@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
"numeros": 0,
"strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
- "soporta booleanos?": true,
- "vacios": null,
+ "¿soporta booleanos?": true,
+ "vacíos": null,
"numero grande": 1.2e+100,
"objetos": {
- "comentario": "La mayoria de tu estructura vendra de objetos.",
+ "comentario": "La mayoría de tu estructura vendrá de objetos.",
"arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
"otro objeto": {
- "comentario": "Estas cosas pueden estar anidadas, muy util."
+ "comentario": "Estas cosas pueden estar anidadas, muy útil."
}
},
- "tonteria": [
+ "tontería": [
{
"fuentes de potasio": ["bananas"]
},
@@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"estilo alternativo": {
"comentario": "Mira esto!"
- , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido"
- , "otro comentario": "que lindo"
+ , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido"
+ , "otro comentario": "qué lindo"
},
- "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer."
+ "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer."
}
```
diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown
index 1c69481a..05fd7065 100644
--- a/es-es/python3-es.html.markdown
+++ b/es-es/python3-es.html.markdown
@@ -97,7 +97,7 @@ not False # => True
None # => None
# No uses el símbolo de igualdad `==` para comparar objetos con None
-# Usa `is` en lugar de
+# Usa `is` en su lugar
"etc" is None #=> False
None is None #=> True
@@ -383,7 +383,7 @@ def keyword_args(**kwargs):
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
-# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres
+# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
print args
print kwargs
@@ -478,7 +478,7 @@ Humano.roncar() #=> "*roncar*"
# Puedes importar módulos
import math
-print(math.sqrt(16)) #=> 4
+print(math.sqrt(16)) #=> 4.0
# Puedes obtener funciones específicas desde un módulo
from math import ceil, floor
@@ -511,7 +511,7 @@ def duplicar_numeros(iterable):
for i in iterable:
yield i + i
-# Un generador cera valores sobre la marcha.
+# Un generador crea valores sobre la marcha.
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
index d8b67fe7..e3e43c18 100644
--- a/es-es/ruby-es.html.markdown
+++ b/es-es/ruby-es.html.markdown
@@ -29,7 +29,7 @@ Nadie los usa.
Tu tampoco deberías
=end
-# Lo primero y principal: Todo es un objeto
+# En primer lugar: Todo es un objeto
# Los números son objetos
@@ -128,7 +128,7 @@ ruta = '/mal/nombre/'
# Los símbolos (son objetos)
# Los símbolos son inmutables, constantes reusables representadas internamente por un
-# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
+# valor entero. Son normalmente usados en vez de strings para expresar eficientemente
# valores específicos y significativos
:pendiente.class #=> Symbol
@@ -156,7 +156,7 @@ arreglo[0] #=> 1
arreglo.first #=> 1
arreglo[12] #=> nil
-# Tal como la aritmética, el acceso como variable[índice]
+# Al igual que en aritmética, el acceso como variable[índice]
# es sólo azúcar sintáctica
# para llamar el método [] de un objeto
arreglo.[] 0 #=> 1
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
new file mode 100644
index 00000000..c04ab02b
--- /dev/null
+++ b/es-es/swift-es.html.markdown
@@ -0,0 +1,596 @@
+---
+language: swift
+contributors:
+ - ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Anthony Nguyen", "http://github.com/anthonyn60"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: learnswift-es.swift
+---
+
+Swift es un lenguaje de programación para el desarrollo en iOS y OS X 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.
+
+Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift.
+
+
+```swift
+// Importar un módulo
+import UIKit
+
+//
+// MARK: Básicos
+//
+
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la
+// barra de saltos.
+// MARK: Marca de sección
+// TODO: Hacer algo pronto
+// FIXME: Arreglar este código
+
+// En Swift 2, println y print fueron combinados en un solo método print.
+// Print añade una nueva línea automáticamente.
+print("Hola, mundo") // println ahora es print
+print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
+
+// Valores de variables (var) pueden cambiar después de ser asignados
+// Valores de constrantes (let) no pueden cambiarse después de ser asignados
+
+var myVariable = 42
+let øπΩ = "value" // nombres de variable unicode
+let π = 3.1415926
+let convenience = "keyword" // nombre de variable contextual
+// Las declaraciones pueden ser separadas por punto y coma (;)
+let weak = "keyword"; let override = "another keyword"
+// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
+// variable
+let `class` = "keyword"
+let explicitDouble: Double = 70
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Conversión (casting)
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
+
+// Valores específicos de la compilación (build)
+// utiliza la configuración -D
+#if false
+ print("No impreso")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+print("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Las opcionales son un aspecto del lenguaje Swift que permite el
+ almacenamiento de un valor `Some` (algo) o `None` (nada).
+
+ Debido a que Swift requiere que cada propiedad tenga un valor,
+ hasta un valor 'nil' debe de ser explicitamente almacenado como un
+ valor opcional.
+
+ Optional<T> es un enum.
+*/
+var someOptionalString: String? = "opcional" // Puede ser nil
+// Al igual que lo anterior, pero ? es un operador postfix (sufijo)
+var someOptionalString2: Optional<String> = "opcional"
+
+if someOptionalString != nil {
+ // No soy nil
+ if someOptionalString!.hasPrefix("opt") {
+ print("Tiene el prefijo")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// Opcional implícitamente desenvuelto
+var unwrappedString: String! = "Un valor esperado."
+// Al igual que lo anterior, pero ! es un operador postfix (sufijo)
+var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Un valor esperado."
+
+if let someOptionalStringConstant = someOptionalString {
+ // tiene valor `Some` (algo), no nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // No tiene el prefijo
+ }
+}
+
+// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
+// AnyObject == id
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
+// valor (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
+
+/*
+ Comentar aquí
+
+ /*
+ Comentarios anidados también son soportados
+ */
+*/
+
+//
+// MARK: Colecciones
+//
+
+/*
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
+ Así que `let` y `var` también indican si son mudables (var) o
+ inmutables (let) durante la declaración de sus tipos.
+*/
+
+// Array (arreglo)
+var shoppingList = ["catfish", "water", "lemons"]
+shoppingList[1] = "bottle of water"
+let emptyArray = [String]() // let == inmutable
+let emptyArray2 = Array<String>() // igual que lo anterior
+var emptyMutableArray = [String]() // var == mudable
+
+
+// Dictionary (diccionario)
+var occupations = [
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
+]
+occupations["Jayne"] = "Public Relations"
+let emptyDictionary = [String: Float]() // let == inmutable
+let emptyDictionary2 = Dictionary<String, Float>() // igual que lo anterior
+var emptyMutableDictionary = [String: Float]() // var == mudable
+
+
+//
+// MARK: Flujo de control
+//
+
+// Ciclo for (array)
+let myArray = [1, 1, 2, 3, 5]
+for value in myArray {
+ if value == 1 {
+ print("Uno!")
+ } else {
+ print("No es uno!")
+ }
+}
+
+// Ciclo for (dictionary)
+var dict = ["uno": 1, "dos": 2]
+for (key, value) in dict {
+ print("\(key): \(value)")
+}
+
+// Ciclo for (range)
+for i in -1...shoppingList.count {
+ print(i)
+}
+shoppingList[1...2] = ["steak", "peacons"]
+// Utilizar ..< para excluir el último valor
+
+// Ciclo while
+var i = 1
+while i < 1000 {
+ i *= 2
+}
+
+// Ciclo do-while
+do {
+ print("Hola")
+} while 1 == 2
+
+// Switch
+// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_
+// Soportan String, instancias de objetos, y primitivos (Int, Double, etc)
+let vegetable = "red pepper"
+switch vegetable {
+case "celery":
+ let vegetableComment = "Add some raisins and make ants on a log."
+case "cucumber", "watercress":
+ let vegetableComment = "That would make a good tea sandwich."
+case let localScopeValue where localScopeValue.hasSuffix("pepper"):
+ let vegetableComment = "Is it a spicy \(localScopeValue)?"
+default: // obligatorio (se debe cumplir con todos los posibles valores de entrada)
+ let vegetableComment = "Everything tastes good in soup."
+}
+
+
+//
+// MARK: Funciones
+//
+
+// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados
+// en funciones y pueden ser pasados como parámetros
+
+// Función en documentación de cabeceras Swift (formato reStructedText)
+
+/**
+ Una operación de saludo
+
+ - Una viñeta en la documentación
+ - Otra viñeta en la documentación
+
+ :param: name Un nombre
+ :param: day Un día
+ :returns: Un string que contiene el valor de name y day
+*/
+func greet(name: String, day: String) -> String {
+ return "Hola \(name), hoy es \(day)."
+}
+greet("Bob", "Martes")
+
+// Similar a lo anterior, a excepción del compartamiento de los parámetros
+// de la función
+func greet2(requiredName: String, externalParamName localParamName: String) -> String {
+ return "Hola \(requiredName), hoy es el día \(localParamName)"
+}
+greet2(requiredName:"John", externalParamName: "Domingo")
+
+// Función que devuelve múltiples valores en una tupla
+func getGasPrices() -> (Double, Double, Double) {
+ return (3.59, 3.69, 3.79)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignorar tupla (u otros) valores utilizando _ (guión bajo)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
+
+// Cantidad variable de argumentos
+func setup(numbers: Int...) {
+ // Es un arreglo
+ let number = numbers[0]
+ let argCount = numbers.count
+}
+
+// Pasando y devolviendo funciones
+func makeIncrementer() -> (Int -> Int) {
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
+}
+var increment = makeIncrementer()
+increment(7)
+
+// Pasando como referencia
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+print(someIntB) // 7
+
+
+//
+// MARK: Closures (Clausuras)
+//
+var numbers = [1, 2, 6]
+
+// Las funciones son un caso especial de closure ({})
+
+// Ejemplo de closure.
+// `->` Separa los argumentos del tipo de retorno
+// `in` Separa la cabecera del cuerpo del closure
+numbers.map({
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
+
+// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto
+numbers = numbers.map({ number in 3 * number })
+// o esto
+//numbers = numbers.map({ $0 * 3 })
+
+print(numbers) // [3, 6, 18]
+
+// Closure restante
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Bastante corto, debido a que el operador < infiere los tipos
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
+
+//
+// MARK: Estructuras
+//
+
+// Las estructuras y las clases tienen capacidades similares
+struct NamesTable {
+ let names = [String]()
+
+ // Subscript personalizado
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+// Las estructuras tienen un inicializador designado autogenerado (implícitamente)
+let namesTable = NamesTable(names: ["Me", "Them"])
+let name = namesTable[1]
+print("Name is \(name)") // Name is Them
+
+//
+// MARK: Clases
+//
+
+// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso
+// Éstos son: internal (predeterminado), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
+// Todos los métodos y las propiedades de una clase son public (públicas)
+// Si solo necesitas almacenar datos en un objecto estructurado,
+// debes de utilizar `struct`
+
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Getter y setter personalizado
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` es una variable implícita disponible para los setters
+ sideLength = newValue / 4
+ }
+ }
+
+ // Lazily loading (inicialización bajo demanda) a una propiedad
+ // subShape queda como nil (sin inicializar) hasta que getter es llamado
+ lazy var subShape = Rect(sideLength: 4)
+
+ // Si no necesitas un getter y setter personalizado
+ // pero aún quieres ejecutar código antes y después de hacer get o set
+ // a una propiedad, puedes utilizar `willSet` y `didSet`
+ var identifier: String = "defaultID" {
+ // El argumento `willSet` será el nombre de variable para el nuevo valor
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
+ }
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // Siempre poner super.init de último al momento de inicializar propiedades
+ // personalizadas
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
+ }
+}
+
+// Una clase simple `Square` que extiende de `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
+}
+
+var mySquare = Square()
+print(mySquare.getArea()) // 25
+mySquare.shrink()
+print(mySquare.sideLength) // 4
+
+// Conversión de tipo de instancia
+let aShape = mySquare as Shape
+
+// Comparar instancias, no es igual a == que compara objetos (equal to)
+if mySquare === mySquare {
+ print("Yep, it's mySquare")
+}
+
+// Inicialización (init) opcional
+class Circle: Shape {
+ var radius: Int
+ override func getArea() -> Int {
+ return 3 * radius * radius
+ }
+
+ // Un signo de interrogación como sufijo después de `init` es un init opcional
+ // que puede devolver nil
+ init?(radius: Int) {
+ self.radius = radius
+ super.init()
+
+ if radius <= 0 {
+ return nil
+ }
+ }
+}
+
+var myCircle = Circle(radius: 1)
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
+var myEmptyCircle = Circle(radius: -1)
+print(myEmptyCircle?.getArea()) // "nil"
+if let circle = myEmptyCircle {
+ // no será ejecutado debido a que myEmptyCircle es nil
+ print("circle is not nil")
+}
+
+
+//
+// MARK: Enums
+//
+
+
+// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo
+// Al igual que las clases, pueden contener métodos
+
+enum Suit {
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
+ }
+}
+
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner
+// el tipo del enum cuando la variable es declarada de manera explícita
+var suitValue: Suit = .Hearts
+
+// Enums de tipo no-entero requiere asignaciones de valores crudas directas
+enum BookName: String {
+ case John = "John"
+ case Luke = "Luke"
+}
+print("Name: \(BookName.John.rawValue)")
+
+// Enum con valores asociados
+enum Furniture {
+ // Asociación con Int
+ case Desk(height: Int)
+ // Asociación con String e Int
+ case Chair(String, Int)
+
+ func description() -> String {
+ switch self {
+ case .Desk(let height):
+ return "Desk with \(height) cm"
+ case .Chair(let brand, let height):
+ return "Chair of \(brand) with \(height) cm"
+ }
+ }
+}
+
+var desk: Furniture = .Desk(height: 80)
+print(desk.description()) // "Desk with 80 cm"
+var chair = Furniture.Chair("Foo", 40)
+print(chair.description()) // "Chair of Foo with 40 cm"
+
+
+//
+// MARK: Protocolos
+//
+
+// `protocol` puede requerir que los tipos tengan propiedades
+// de instancia específicas, métodos de instancia, métodos de tipo,
+// operadores, y subscripts
+
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+// Protocolos declarados con @objc permiten funciones opcionales,
+// que te permite evaluar conformidad
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ // Pon un signo de interrogación después de la propiedad opcional,
+ // método, o subscript para ignorar un valor nil y devolver nil
+ // en lugar de tirar un error de tiempo de ejecución
+ // ("optional chaining")
+ if let allow = self.delegate?.canReshape?() {
+ // test for delegate then for method
+ self.delegate?.reshaped?()
+ }
+ }
+}
+
+
+//
+// MARK: Otros
+//
+
+// `extension`: Agrega funcionalidades a tipos existentes
+
+// Square ahora se "conforma" al protocolo `Printable`
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+print("Square: \(mySquare)")
+
+// También puedes hacer extend a tipos prefabricados (built-in)
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
+
+// Generics: Similar Java y C#. Utiliza la palabra clave `where` para
+// especificar los requerimientos de los genéricos.
+
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+print(foundAtIndex == 2) // true
+
+// Operadores:
+// Operadores personalizados puede empezar con los siguientes caracteres:
+// / = - + * % < > ! & | ^ . ~
+// o
+// Caracteres unicode: math, symbol, arrow, dingbat, y line/box.
+prefix operator !!! {}
+
+// Un operador prefix que triplica la longitud del lado cuando es utilizado
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// Valor actual
+print(mySquare.sideLength) // 4
+
+// Cambiar la longitud del lado utilizando el operador !!!,
+// incrementa el tamaño por 3
+!!!mySquare
+print(mySquare.sideLength) // 12
+```
diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown
new file mode 100644
index 00000000..9ed4e0d2
--- /dev/null
+++ b/fi-fi/go-fi.html.markdown
@@ -0,0 +1,441 @@
+---
+name: Go
+category: language
+language: Go
+filename: learngo-fi.go
+contributors:
+ - ["Sonia Keys", "https://github.com/soniakeys"]
+ - ["Christopher Bess", "https://github.com/cbess"]
+ - ["Jesse Johnson", "https://github.com/holocronweaver"]
+ - ["Quint Guvernator", "https://github.com/qguv"]
+ - ["Jose Donizetti", "https://github.com/josedonizetti"]
+ - ["Alexej Friesen", "https://github.com/heyalexej"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
+translators:
+ - ["Timo Virkkunen", "https://github.com/ComSecNinja"]
+lang: fi-fi
+---
+
+Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi,
+mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia.
+
+Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja
+konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän
+samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten
+prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten
+projektien käsittelemiseksi.
+
+Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön.
+
+```go
+// Yhden rivin kommentti
+/* Useamman
+ rivin kommentti */
+
+// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto.
+// Main on erityinen nimi joka ilmoittaa
+// suoritettavan tiedoston kirjaston sijasta.
+package main
+
+// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot.
+import (
+ "fmt" // Paketti Go:n oletuskirjastosta.
+ "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita.
+ m "math" // Matematiikkakirjasto jolla on paikallinen nimi m.
+ "net/http" // Kyllä, web-palvelin!
+ "strconv" // Kirjainjonojen muuntajia.
+)
+
+// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen
+// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita.
+func main() {
+ // Println tulostaa rivin stdoutiin.
+ // Se tulee paketin fmt mukana, joten paketin nimi on mainittava.
+ fmt.Println("Hei maailma!")
+
+ // Kutsu toista funktiota tämän paketin sisällä.
+ beyondHello()
+}
+
+// Funktioilla voi olla parametrejä sulkeissa.
+// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset.
+func beyondHello() {
+ var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä.
+ x = 3 // Arvon antaminen muuttujalle.
+ // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa
+ // sekä antaa arvon muuttujalle.
+ y := 4
+ sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa.
+ fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste.
+ learnTypes() // < y minuuttia, opi lisää!
+}
+
+/* <- usean rivin kommentti
+Funktioilla voi olla parametrejä ja (useita!) palautusarvoja.
+Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan.
+Huomaa että `x` ja `sum` saavat tyyin `int`.
+*/
+func learnMultiple(x, y int) (sum, prod int) {
+ return x + y, x * y // Palauta kaksi arvoa.
+}
+
+// Sisäänrakennettuja tyyppejä ja todellisarvoja.
+func learnTypes() {
+ // Lyhyt ilmoitus antaa yleensä haluamasi.
+ str := "Opi Go!" // merkkijonotyyppi.
+
+ s2 := `"raaka" todellisarvoinen merrkijono
+voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi.
+
+ // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8.
+ g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen.
+
+ f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku.
+ c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla.
+
+ // var -syntaksi alkuarvoilla.
+ var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int.
+ var pi float32 = 22. / 7
+
+ // Muuntosyntaksi lyhyellä ilmoituksella.
+ n := byte('\n') // byte on leminimi uint8:lle.
+
+ // Listoilla on kiinteä koko kääntöhetkellä.
+ var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi.
+ a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3
+ // alkiota, jotka saavat arvot 3, 1, ja 5.
+
+ // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa,
+ // mutta siivut ovat yleisempiä käyttötapojensa vuoksi.
+ s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...).
+ s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi.
+ var d2 [][]float64 // Vain ilmoitus, muistia ei varata.
+ bs := []byte("a slice") // Tyypinmuuntosyntaksi.
+
+ // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan.
+ // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota.
+ // Ensimmäinen argumentti on siivu, johon alkoita lisätään.
+ s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista.
+ s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6.
+ fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6]
+
+ // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin
+ // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin
+ // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s.
+ s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu.
+ fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9]
+
+ p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin.
+ fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä.
+
+ // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai
+ // dictionary toisissa kielissä.
+ m := map[string]int{"three": 3, "four": 4}
+ m["one"] = 1
+
+ // Käyttämättömät muuttujat ovat virheitä Go:ssa.
+ // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon.
+ _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
+ // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi.
+ fmt.Println(s, c, a4, s3, d2, m)
+
+ learnFlowControl() // Takaisin flowiin.
+}
+
+// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä
+// palautusarvoja.
+// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä
+// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä
+// pelkän return-lausekkeen käytön ilman muita mainintoja.
+func learnNamedReturns(x, y int) (z int) {
+ z = x * y
+ return // z on epäsuorasti tässä, koska nimesimme sen aiemmin.
+}
+
+// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa.
+// Voit tehdä virheen mitättömällä osoittajalla, mutta et
+// kasvattamalla osoittajaa.
+func learnMemory() (p, q *int) {
+ // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin.
+ p = new(int) // Sisäänrakennettu funktio new varaa muistia.
+ // Varattu int on alustettu nollaksi, p ei ole enää mitätön.
+ s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa.
+ s[3] = 7 // Anna yhdelle niistä arvo.
+ r := -2 // Ilmoita toinen paikallinen muuttuja.
+ return &s[3], &r // & ottaa asian osoitteen muistissa.
+}
+
+func expensiveComputation() float64 {
+ return m.Exp(10)
+}
+
+func learnFlowControl() {
+ // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita.
+ if true {
+ fmt.Println("mitä mä sanoin")
+ }
+ // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt".
+ if false {
+ // Nyrpistys.
+ } else {
+ // Nautinto.
+ }
+ // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta.
+ x := 42.0
+ switch x {
+ case 0:
+ case 1:
+ case 42:
+ // Tapaukset eivät "tipu läpi".
+ /*
+ Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso:
+ https://github.com/golang/go/wiki/Switch#fall-through
+ */
+ case 43:
+ // Saavuttamaton.
+ default:
+ // Oletustapaus (default) on valinnainen.
+ }
+ // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita.
+ // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden
+ // piireissä.
+ for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1".
+ fmt.Println("iteraatio", x)
+ }
+ // x == 42 tässä.
+
+ // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja.
+ for { // Päättymätön silmukka.
+ break // Kunhan vitsailin.
+ continue // Saavuttamaton.
+ }
+
+ // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki-
+ // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai
+ // kaksi arvoa (lista, siivu, merkkijono ja kartta).
+ for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} {
+ // jokaista kartan paria kohden, tulosta avain ja arvo
+ fmt.Printf("avain=%s, arvo=%d\n", key, value)
+ }
+
+ // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja
+ // arvon asettamista.
+ // Aseta ensin y, sitten testaa onko y > x.
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
+ // Todellisarvoiset funktiot ovat sulkeumia.
+ xBig := func() bool {
+ return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään.
+ }
+ fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10).
+ x = 1.3e3 // Tämä tekee x == 1300
+ fmt.Println("xBig:", xBig()) // epätosi nyt.
+
+ // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että
+ // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan:
+ // a) todellisarvoinen funktio kutsutaan välittömästi (),
+ // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä.
+ fmt.Println("Lisää ja tuplaa kaksi numeroa: ",
+ func(a, b int) int {
+ return (a + b) * 2
+ }(10, 2)) // Kutsuttu argumenteilla 10 ja 2
+ // => Lisää ja tuplaa kaksi numeroa: 24
+
+ // Kun tarvitset sitä, rakastat sitä.
+ goto love
+love:
+
+ learnFunctionFactory() // Funktioita palauttavat funktiot
+ learnDefer() // Nopea kiertoreitti tärkeään avainsanaan.
+ learnInterfaces() // Hyvää kamaa tulossa!
+}
+
+func learnFunctionFactory() {
+ // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi
+ fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!"))
+
+ d := sentenceFactory("kesä")
+ fmt.Println(d("Kaunis", "päivä!"))
+ fmt.Println(d("Laiska", "iltapäivä!"))
+}
+
+// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä
+// todellisarvoisia funktioita jotka ottavat vastaan argumentteja.
+func sentenceFactory(mystring string) func(before, after string) string {
+ return func(before, after string) string {
+ return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono
+ }
+}
+
+func learnDefer() (ok bool) {
+ // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista.
+ defer fmt.Println("lykätyt lausekkeet suorittuvat")
+ defer fmt.Println("käänteisessä järjestyksessä (LIFO).")
+ defer fmt.Println("\nTämä rivi tulostuu ensin, koska")
+ // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta
+ // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota.
+ return true
+}
+
+// Määrittele Stringer rajapintatyypiksi jolla on
+// yksi jäsenfunktio eli metodi, String.
+type Stringer interface {
+ String() string
+}
+
+// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int.
+type pair struct {
+ x, y int
+}
+
+// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan.
+func (p pair) String() string { // p:tä kutsutaan nimellä "receiver"
+ // Sprintf on toinen julkinen funktio paketissa fmt.
+ // Pistesyntaksilla viitataan P:n kenttiin.
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
+}
+
+func learnInterfaces() {
+ // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi
+ // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi.
+ p := pair{3, 4}
+ fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String.
+ var i Stringer // Ilmoita i Stringer-rajapintatyypiksi.
+ i = p // Pätevä koska pair tyydyttää rajapinnan Stringer.
+ // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä.
+ fmt.Println(i.String())
+
+ // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota
+ // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta.
+ fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia.
+ fmt.Println(i) // Tuloste on sama kuin yllä.
+
+ learnVariadicParams("loistavaa", "oppimista", "täällä!")
+}
+
+// Funktioilla voi olla muuttuva eli variteettinen
+// määrä argumentteja eli parametrejä.
+func learnVariadicParams(myStrings ...interface{}) {
+ // Iteroi jokaisen argumentin läpi.
+ // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi.
+ for _, param := range myStrings {
+ fmt.Println("param:", param)
+ }
+
+ // Luovuta variteettinen arvo variteettisena parametrinä.
+ fmt.Println("params:", fmt.Sprintln(myStrings...))
+
+ learnErrorHandling()
+}
+
+func learnErrorHandling() {
+ // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei.
+ m := map[int]string{3: "kolme", 4: "neljä"}
+ if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa.
+ fmt.Println("ei ketään täällä")
+ } else {
+ fmt.Print(x) // x olisi arvo jos se olisi kartassa.
+ }
+ // Virhearvo voi kertoa muutakin ongelmasta.
+ if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon
+ // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax
+ fmt.Println(err)
+ }
+ // Palaamme rajapintoihin hieman myöhemmin. Sillä välin,
+ learnConcurrency()
+}
+
+// c on kanava, samanaikaisturvallinen viestintäolio.
+func inc(i int, c chan int) {
+ c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla.
+}
+
+// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen.
+func learnConcurrency() {
+ // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make
+ // varaa muistin ja alustaa siivut, kartat ja kanavat.
+ c := make(chan int)
+ // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat
+ // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein
+ // määritelty. Kaikki kolme lähettävät samalle kanavalle.
+ go inc(0, c) // go -lauseke aloittaa uuden gorutiinin.
+ go inc(10, c)
+ go inc(-805, c)
+ // Lue kolme palautusarvoa kanavalta ja tulosta ne.
+ // Niiden saapumisjärjestystä ei voida taata!
+ // <- on "vastaanotto-operaattori" jos kanava on oikealla
+ fmt.Println(<-c, <-c, <-c)
+
+ cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja.
+ ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia.
+ go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi.
+ go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa.
+ // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta
+ // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen
+ // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita
+ select {
+ case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle
+ fmt.Printf("se on %T", i)
+ case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa.
+ fmt.Println("se on merkkijono")
+ case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon.
+ fmt.Println("ei tapahtunut.")
+ }
+ // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta
+ // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa.
+
+ learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä.
+}
+
+// Yksittäinen funktio http -paketista aloittaa web-palvelimen.
+func learnWebProgramming() {
+
+ // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan.
+ // Toinen parametri on rajapinta, http.Handler.
+ go func() {
+ err := http.ListenAndServe(":8080", pair{})
+ fmt.Println(err) // älä sivuuta virheitä.
+ }()
+
+ requestServer()
+}
+
+// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP.
+func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Tarjoa dataa metodilla http.ResponseWriter.
+ w.Write([]byte("Opit Go:n Y minuutissa!"))
+}
+
+func requestServer() {
+ resp, err := http.Get("http://localhost:8080")
+ fmt.Println(err)
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(resp.Body)
+ fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body))
+}
+```
+
+## Lisää luettavaa
+
+Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/).
+Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon.
+Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa
+siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta.
+
+Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja
+yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.)
+
+Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm).
+Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org)
+[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista.
+
+Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/).
+Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista,
+-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja
+lähdekoodi tulee esille!
+
+Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/).
+
+Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia
+Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile).
diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown
new file mode 100644
index 00000000..14b0f1d9
--- /dev/null
+++ b/fi-fi/markdown-fi.html.markdown
@@ -0,0 +1,259 @@
+---
+language: markdown
+filename: markdown-fi.md
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Timo Virkkunen", "https://github.com/ComSecNinja"]
+lang: fi-fi
+---
+
+John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi).
+
+```markdown
+<!-- Jokainen HTML-tiedosto on pätevää Markdownia. Tämä tarkoittaa että voimme
+käyttää HTML-elementtejä Markdownissa, kuten kommentteja, ilman että markdown
+-jäsennin vaikuttaa niihin. Tästä johtuen et voi kuitenkaan käyttää markdownia
+HTML-elementtien sisällä jos luot sellaisen markdown-tiedostoon. -->
+
+<!-- Markdownin toteutus vaihtelee jäsentimestä toiseen. Tämä opas yrittää
+selventää mitkä ominaisuudet ovat yleisiä ja mitkä ovat eritysesti tiettyjen
+jäsentimien ominaisuuksia. -->
+
+<!-- Otsikot -->
+<!-- Voit luoda HTML-elementtejä <h1> - <h6> helposti aloittamalla rivin
+haluamallasi määrällä ristikkomerkkejä (#). -->
+# Tämä on <h1>
+## Tämä on <h2>
+### Tämä on <h3>
+#### Tämä on <h4>
+##### Tämä on <h5>
+###### Tämä on <h6>
+
+<!-- Markdownissa on myös vaihtoehtoisia tapoja ilmaista h1 ja h2. -->
+Tämä on h1
+=============
+
+Tämä on h2
+-------------
+
+<!-- Yksinkertaiset tekstimuotoilut -->
+<!-- Tekstin voi helposti muotoilla kursiiviksi tai lihavoiduksi. -->
+
+*Tämä teksti on kursivoitua.*
+_Kuten on myös tämä teksti._
+
+**Tämä teksti on lihavoitua.**
+__Kuten on tämäkin teksti.__
+
+***Tämä teksti on molempia.***
+**_Kuten tämäkin!_**
+*__Kuten tämäkin!__*
+
+<!-- Github-tyylisessä Markdownissa, jota käytetään tiedostojen esittämiseksi
+Githubissa, meillä on käytössämme myös yliviivaus: -->
+
+~~Tämä teksti on yliviivattua.~~
+
+<!-- Kappaleet ovat yhdellä tai useammalla peräkkäisellä tekstirivillä jotka
+erotellaan yhdellä tai useammalla tyhjällä rivillä -->
+
+Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa?
+
+Nyt olen kappaleessa 2.
+Olen edelleen toisessa kappaleessa!
+
+
+Olen kolmannessa kappaleessa!
+
+<!-- Jos haluat lisätä <br /> HTML-elementin, päätä kappale kahdella tai
+useammalla välilyönnillä ja aloita sitten uusi kappale -->
+
+Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne).
+
+There's a <br /> above me!
+
+<!-- Lainaukset ovat helppoja ja ne tehdään >-merkillä -->
+
+> Tämä on lainaus. Voit joko
+> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit.
+> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä.
+
+> Voit myös käyttää useampaa
+>> sisennystasoa
+> Kuinka hienoa se on?
+
+<!-- Listat -->
+<!-- Järjestämättömät listat tehdään asteriskilla, plussalla tai viivalla -->
+
+* Kohta
+* Kohta
+* Kolmas kohta
+
+tai
+
++ Kohta
++ Kohta
++ Kolmas kohta
+
+tai
+
+- Kohta
+- Kohta
+- Kolmas kohta
+
+<!-- Järjestetyt listat tehdään järjestysluvuilla. -->
+
+1. Kohta yksi
+2. Kohta kaksi
+3. Kohta kolme
+
+<!-- Sinun ei tarvitse edes merkitä kohtia oikein ja silti markdown näyttää
+oikean järjestyksen, mutta se ei välttämättä ole hyvä idea. -->
+
+1. Kohta yksi
+1. Kohta kaksi
+1. Kohta kolme
+<!-- (Tämä korjaantuu samanlaiseksi kuin yllä oleva esimerkki) -->
+
+<!-- Voit myös käyttää alalistoja. -->
+
+1. Kohta yksi
+2. Kohta kaksi
+3. Kohta kolme
+ * Alakohta
+ * Alakohta
+4. Kohta neljä
+
+<!-- Myös tehtävälistoja on olemassa. Tämä tekee HTML-valintaruutuja. -->
+
+Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja.
+- [ ] Ensimmäinen suoritettava tehtävä.
+- [ ] Toinen tehtävä joka täytyy tehdä
+Tämä alla oleva ruutu on merkitty HTML-valintaruutu.
+- [x] Tämä tehtävä on suoritettu
+
+<!-- Koodiosiot -->
+<!-- Voit merkitä koodiosion (jaka käyttää <code> -elementtiä) sisentämällä
+rivin neljällä välilyönnillä tai tabulaattorilla. -->
+
+ Tämä on koodia
+ Kuten tämäkin
+
+<!-- Voit myös sisentää koodia samalla tavalla. -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Muun tekstin seassa oleva koodi merkitään kahden `-merkin väliin -->
+
+John ei tiennyt edes mitä `go_to()` -funktio teki!
+
+<!-- Githubin Markdownissa voit käyttää erityissyntaksia koodille. -->
+
+\`\`\`ruby <!-- paitsi että poista nuo kenoviivat, vain ```ruby ! -->
+def foobar
+ puts "Hello world!"
+end
+\`\`\` <!-- tästä myös, ei kenoviivoja, vain ``` -->
+
+<!-- Yllä oleva teksti ei vaadi sisennystä. Lisäksi Github käyttää ``` jälkeen
+mainitsemasi kielen syntaksin korostusta -->
+
+<!-- Vaakaviiva (<hr />) -->
+<!-- Vaakaviivojen lisääminen käy näppärästi kolmella tai useammalla
+asteriskilla taikka viivalla, välilyönneillä tai ilman -->
+
+***
+---
+- - -
+****************
+
+<!-- Linkit -->
+<!-- yksi markdownin parhaita ominaisuuksia on yksinkertaiset hyperlinkit. Laita
+näytettävä teksti hakasulkuihin [] ja URL-osoite perään sulkeissa (). -->
+
+[Klikkaa tästä!](http://example.com/)
+
+<!-- Voit myös lisätä linkin otsikon heittomerkeissä osoitteen perään. -->
+
+[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin")
+
+<!-- Suhteelliset polut toimivat myös. -->
+
+[Musiikkia](/musiikki/).
+
+<!-- Markdown tukee myös viittaustyylisiä linkkejä. -->
+
+[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja!
+[Katso myös tämä linkki][foobar] jos haluat.
+
+[link1]: http://example.com/ "Siistii!"
+[foobar]: http://foobar.biz/ "Selkis!"
+
+<!-- Otsikko voi olla myös ykittäisissä heittomerkeissä tai sulkeissa, tai
+ohitettu kokonaan. Viittaukset voivat olla missä tahansa kohdassa dokumenttia ja
+viittausten ID:t voivat olla mitä tahansa kunhan ne ovat uniikkeja. -->
+
+<!-- Voit myös käyttää linkin tekstiä ID:nä näin: -->
+
+[This][] is a link.
+
+[this]: http://tämäonlinkki.com/
+
+<!-- Mutta tämä tapa ei ole yleinen. -->
+
+<!-- Kuvat -->
+<!-- Kuvat tehdään samalla tavalla kuin linkitkin, mutta huutomerkki edessä! -->
+
+![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko")
+
+<!-- Ja viittaukset toimivat odotetusti. -->
+
+![Tämä on se alt-attribuutti][munkuva]
+
+[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa"
+
+<!-- Sekalaista -->
+<!-- Automaattiset linkit -->
+
+<http://testwebsite.com/> on sama kuin
+[http://testwebsite.com/](http://testwebsite.com/)
+
+<!-- Automaattiset sähköpostilinkit -->
+
+<foo@bar.com>
+
+<!-- Varattujen merkkien käyttö -->
+
+haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua
+sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*.
+
+<!-- Näppäimistön näppäimet -->
+<!-- Githubin Markdownissa, voit käyttää <kbd> -tagia esittämään näppäimiä -->
+
+Tietokoneesi kaatui? Kokeile painaa
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+
+<!-- Taulukot -->
+<!-- Taulukot ovat saatavilla vain Githubin markdownissa ja ne ovat melko
+vaivalloisia käyttää, mutta jos todella haluat: -->
+
+| Kolumni1 | Kolumni2 | Kolumni3 |
+| :----------- | :------: | ------------: |
+| Vasemmalle | Keskelle | Oikealle |
+| blaa | blaa | blaa |
+
+<!-- vaihtoehtoisesti, sama tulos -->
+
+Kolumni 1 | Kolumni 2 | Kolumni 3
+:-- | :-: | --:
+Hyi tämä on ruma | saa se | loppumaan
+
+<!-- Loppu! -->
+
+```
+
+Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax)
+ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown
new file mode 100644
index 00000000..fdde9107
--- /dev/null
+++ b/fr-fr/HTML-fr.html.markdown
@@ -0,0 +1,115 @@
+---
+language: html
+filename: learnhtml-fr.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+lang: fr-fr
+---
+HTML signifie HyperText Markup Language.
+C'est un langage (format de fichiers) qui permet d'écrire des pages internet.
+C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais).
+Les fichiers HTML sont en réalité de simple fichier texte.
+Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante.
+Ce balisage sert à donner une signification au texte ainsi entouré.
+Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5.
+
+**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
+Cet article porte principalement sur la syntaxe et quelques astuces.
+
+
+```HTML
+<!-- Les commentaires sont entouré comme cette ligne! -->
+
+<!-- #################### Les balises #################### -->
+
+<!-- Voici un exemple de fichier HTML que nous allons analyser -->
+<!-- Venez voir ce que ça donne -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Mon Site</title>
+ </head>
+ <body>
+ <h1>Hello, world!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a>
+ <p>Ceci est un paragraphe</p>
+ <p>Ceci est un autre paragraphe</p>
+ <ul>
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML -->
+
+<!doctype html>
+
+<!-- Après ça on commence par ouvrir une balise <html> -->
+<html>
+</html>
+<!-- Et puis on la referme à la fin du fichier avec </html> -->
+<!-- après cette balise de fin, plus rien ne doit apparaître. -->
+
+<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : -->
+
+<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) -->
+<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées -->
+
+<head>
+ <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre -->
+</head>
+
+<!-- Après la balise <head>, on trouve la balise <body> -->
+<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. -->
+<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu -->
+
+<body>
+ <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre -->
+ <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" -->
+ <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html -->
+ <p>Ceci est un autre paragraphe</p>
+ <ul> <!-- La balise <ul> permet d'introduire une liste à puces -->
+ <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc -->
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+</body>
+
+<!-- Voilà comment créer un fichier HTML simple -->
+
+<!-- Mais il est possible d'ajouter encore des balises plus spécifiques -->
+
+<!-- Pour insérer une image -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" -->
+<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur -->
+
+<!-- Il est possible de réaliser des tableaux également -->
+
+<table> <!-- On ouvre la balise <table> -->
+ <tr> <!-- <tr> permet de créer une ligne -->
+ <th>First Header</th> <!-- <th> permet de créer un titre au tableau -->
+ <th>Second Header</th>
+ </tr>
+ <tr>
+ <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule -->
+ <td>Première ligne, deuxième cellule</td>
+ </tr>
+ <tr>
+ <td>Deuxième ligne, première cellule</td>
+ <td>Deuxième ligne, deuxième cellule</td>
+ </tr>
+</table>
+
+## Utilisation
+
+Le HTML s'écrit dans des fichiers `.html`.
+
+## En savoir plus
+
+* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html)
+* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown
index bdab9715..35673c47 100644
--- a/fr-fr/css-fr.html.markdown
+++ b/fr-fr/css-fr.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: fr-fr
---
-Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs,
+Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs,
des pages avec du contenu visuel sont arrivées.
CSS est le langage standard qui existe et permet de garder une séparation entre
le contenu (HTML) et le style d'une page web.
@@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web.
En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
sur une page HTML afin de leur donner des propriétés visuelles différentes.
-Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0
-qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur.
+Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0
+qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs.
**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
Cet article porte principalement sur la syntaxe et quelques astuces.
@@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces.
/* Généralement, la première déclaration en CSS est très simple */
selecteur { propriete: valeur; /* autres proprietés...*/ }
-/* Le sélécteur sert à cibler un élément du HTML
+/* Le sélecteur sert à cibler un élément du HTML
Vous pouvez cibler tous les éléments d'une page! */
* { color:red; }
diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown
new file mode 100644
index 00000000..d9bd9b48
--- /dev/null
+++ b/fr-fr/d.html.markdown
@@ -0,0 +1,264 @@
+---
+language: D
+filename: learnd-fr.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Quentin Ladeveze", "aceawan.eu"]
+lang: fr-fr
+---
+
+```d
+// Commençons par un classique
+module hello;
+
+import std.stdio;
+
+// args n'est pas obligatoire
+void main(string[] args) {
+ writeln("Bonjour le monde !");
+}
+```
+
+Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a
+de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/).
+D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient
+des fonctionnalités aussi bien de bas niveau que de haut niveau.
+
+D est activement développé par de nombreuses personnes très intelligents, guidées par
+[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et
+[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu).
+Après cette petite introduction, jetons un coup d'oeil à quelques exemples.
+
+```d
+import std.stdio;
+
+void main() {
+ //Les conditions et les boucles sont classiques.
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ // On peut utiliser auto pour inférer automatiquement le
+ // type d'une variable.
+ auto n = 1;
+
+ // On peut faciliter la lecture des valeurs numériques
+ // en y insérant des `_`.
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // For et while sont très utiles, mais en D, on préfère foreach.
+ // Les deux points : '..', créent un intervalle continue de valeurs
+ // incluant la première mais excluant la dernière.
+ foreach(i; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(i);
+ }
+
+ // On peut également utiliser foreach_reverse pour itérer à l'envers.
+ foreach_reverse(i; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(i);
+ } else {
+ writeln("Non !");
+ }
+ }
+}
+```
+On peut définir de nouveaux types avec les mots-clés `struct`, `class`,
+`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés)
+De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques.
+
+```d
+// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java.
+struct LinkedList(T) {
+ T data = null;
+
+ // Utilisez '!' pour instancier un type paramétré.
+ // Encore une fois semblable à '<T>'
+ LinkedList!(T)* next;
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Si il n'y a qu'un seul paramètre de template,
+ // on peut s'abstenir de mettre des parenthèses.
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Utilisez alias pour créer des abreviations pour les types.
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// On peut tout aussi bien créer des templates de function !
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé
+// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur.
+// Ici ils seront toujours passés par référence à 'swap()'.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Avec les templates, on peut également passer des valeurs en paramètres.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // T est 'int' par défaut
+
+```
+À propos de classes, parlons des propriétés. Une propriété est, en gros,
+une méthode qui peut se comporter comme une lvalue. On peut donc utiliser
+la syntaxe des structures classiques (`struct.x = 7`) comme si il
+s'agissait de méthodes getter ou setter.
+
+```d
+// Considérons une classe paramétrée avec les types 'T' et 'U'
+class MyClass(T, U) {
+ T _data;
+ U _other;
+}
+
+// Et des méthodes "getter" et "setter" comme suit:
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Les constructeurs s'apellent toujours 'this'.
+ this(T t, U u) {
+ // Ceci va appeller les setters ci-dessous.
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ @property void data(T t) {
+ _data = t;
+ }
+
+ @property void other(U u) {
+ _other = u;
+ }
+}
+
+// Et on l'utilise de cette façon:
+void main() {
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Importer le module 'stdio' de la bibliothèque standard permet
+ // d'écrire dans la console (les imports peuvent être locaux à une portée)
+ import std.stdio;
+
+ // On appelle les getters pour obtenir les valeurs.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // On appelle les setter pour assigner de nouvelles valeurs.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // On appelle les setter pour obtenir les nouvelles valeurs.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
+}
+```
+Avec les propriétés, on peut constuire nos setters et nos getters
+comme on le souhaite, tout en gardant un syntaxe très propre,
+comme si on accédait directement à des membres de la classe.
+
+Les autres fonctionnalités orientées objets à notre disposition
+incluent les interfaces, les classes abstraites, et la surcharge
+de méthodes. D gère l'héritage comme Java: On ne peut hériter que
+d'une seule classe et implémenter autant d'interface que voulu.
+
+Nous venons d'explorer les fonctionnalités objet du D, mais changeons
+un peu de domaine. D permet la programmation fonctionelle, avec les fonctions
+de premier ordre, les fonctions `pure` et les données immuables.
+De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter)
+sont disponibles dans le module `std.algorithm`.
+
+```d
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // construit un intervalle excluant la dernière valeur.
+
+void main() {
+ // On veut un algorithm qui affiche la somme de la listes des carrés
+ // des entiers paires de 1 à 100. Un jeu d'enfant !
+
+ // On se content de passer des expressions lambda en paramètre à des templates.
+ // On peut fournier au template n'importe quelle fonction, mais dans notre
+ // cas, les lambdas sont pratiques.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ?
+C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax".
+Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière
+classique, ou comme un appelle à une méthode. Walter Brighter a écrit un
+article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Pour faire court, on peut appeller une fonction dont le premier paramètre
+est de type A, comme si c'était une méthode de A.
+
+J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça
+Voyons comment on le fait en D !
+
+```d
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // On veut calculer la racine carré de tous les nombres
+ // dans notre tableau, et profiter de tous les coeurs
+ // à notre disposition.
+ auto arr = new double[1_000_000];
+
+ // On utilise un index et une référence à chaque élément du tableau.
+ // On appelle juste la fonction parallel sur notre tableau !
+ foreach(i, ref elem; parallel(arr)) {
+ ref = sqrt(i + 1.0);
+ }
+}
+
+
+```
diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown
new file mode 100644
index 00000000..bd7c6839
--- /dev/null
+++ b/fr-fr/hy-fr.html.markdown
@@ -0,0 +1,180 @@
+---
+language: hy
+filename: learnhy-fr.hy
+contributors:
+ - ["Abhishek L", "http://twitter.com/abhishekl"]
+translators:
+ - ["Hughes Perreault", "https://github.com/hperreault"]
+lang: fr-fr
+---
+
+Hy est un dialecte du lisp bâti par dessus python. Il fonctionne en
+convertissant le code hy en un arbre de syntaxe abstraite de python (ast).
+Ceci permet à hy d'appeler du code python et à python d'appeler du code hy.
+
+Ce tutoriel fonctionne pour hy > 0.9.12
+
+```clojure
+;; Ceci est une introduction simple à hy, pour un tutoriel rapide aller à
+;; http://try-hy.appspot.com
+;;
+; Les commentaires se font avec des points-virgules, comme les autres LISPS
+
+;; les s-expression de bases
+; Les programmes Lisp sont fait d'expressions symboliques ou sexps qui
+; ressemblent à
+(some-function args)
+; maintenant le quintessentiel hello world
+(print "hello world")
+
+;; les types de données simples
+; Tous les types de données simples sont exactement similaires à leurs
+; homologues de python
+42 ; => 42
+3.14 ; => 3.14
+True ; => True
+4+10j ; => (4+10j) un nombre complexe
+
+; Commençons par un peu d'arithmétique très simple
+(+ 4 1) ;=> 5
+; l'opérateur est appliqué à tous les arguments, comme les autres lisps
+(+ 4 1 2 3) ;=> 10
+(- 2 1) ;=> 1
+(* 4 2) ;=> 8
+(/ 4 1) ;=> 4
+(% 4 2) ;=> 0 l'opérateur modulo
+; l'opérateur d'élévation à la puissance est représenté par ** comme en python
+(** 3 2) ;=> 9
+; les expressions imbriquées vont se comporter comme on s'y attend
+(+ 2 (* 4 2)) ;=> 10
+; aussi, les opérateurs logiques and or not et equal to etc. vont se comporter
+; comme on s'y attend
+(= 5 4) ;=> False
+(not (= 5 4)) ;=> True
+
+;; variables
+; les variables sont déclarées en utilisant setv, les noms de variables
+; peuvent utiliser l'UTF-8 à l'exception de ()[]{}",'`;#|
+(setv a 42)
+(setv π 3.14159)
+(def *foo* 42)
+;; d'autres types de conteneurs
+; les chaînes, les listes, les tuples et dicts
+; ce sont exactement les mêmes que les types de conteneurs de python
+"hello world" ;=> "hello world"
+; les opérations sur les chaînes fonctionnent comme en python
+(+ "hello " "world") ;=> "hello world"
+; les listes sont créés en utilisant [], l'indexation commence à 0
+(setv mylist [1 2 3 4])
+; les tuples sont des structures de données immuables
+(setv mytuple (, 1 2))
+; les dictionnaires sont des paires clé-valeur
+(setv dict1 {"key1" 42 "key2" 21})
+; :nom peut être utilisé pour définir des mots clés dans hy qui peuvent être
+; utilisées comme clés
+(setv dict2 {:key1 41 :key2 20})
+; utilisez `get' pour obtenir l'élément à l'index / clé
+(get mylist 1) ;=> 2
+(get dict1 "key1") ;=> 42
+; Alternativement, si des mots clés ont été utilisés, l'élément peut être
+; obtenu directement
+(:key1 dict2) ;=> 41
+
+;; fonctions et autres constructions de programme
+; les fonctions sont définies en utilisant defn, la dernière sexp est renvoyé par défaut
+(defn greet [name]
+ "A simple greeting" ; une docstring optionnelle
+ (print "hello " name))
+
+(greet "bilbo") ;=> "hello bilbo"
+
+; les fonctions peuvent prendre des arguments optionnels ainsi que des
+; arguments sous forme de mots clés
+(defn foolists [arg1 &optional [arg2 2]]
+ [arg1 arg2])
+
+(foolists 3) ;=> [3 2]
+(foolists 10 3) ;=> [10 3]
+
+; les fonctions anonymes sont créés en utilisant `fn' ou `lambda'
+; qui sont semblable à `defn '
+(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16]
+
+;; Opérations sur les séquences
+; hy a des utilitaires natifs pour les opérations sur les séquences etc.
+; récupérez le premier élément en utilisant `first' ou `car'
+(setv mylist [1 2 3 4])
+(setv mydict {"a" 1 "b" 2})
+(first mylist) ;=> 1
+
+; découpez les listes en utilisant slice
+(slice mylist 1 3) ;=> [2 3]
+
+; obtenez les éléments d'une liste ou dict en utilisant `get'
+(get mylist 1) ;=> 2
+(get mydict "b") ;=> 2
+; l'indexation des listes commence à 0 comme en python
+; assoc peut définir les éléments à clés/index
+(assoc mylist 2 10) ; makes mylist [1 2 10 4]
+(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3}
+; il ya tout un tas d'autres fonctions de base qui rend le travail avec
+; les séquences amusant
+
+;; les importations fonctionnent comme en pyhtonn
+(import datetime)
+(import [functools [partial reduce]]) ; importe fun1 et fun2 de module1
+(import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar
+; toutes les méthodes natives de python sont accessibles à partir de hy
+; a.foo(arg) est appelé (.foo a arg)
+(.split (.strip "hello world ")) ;=> ["hello" "world"]
+
+;; Conditionelles
+; (if condition (body-if-true) (body-if-false)
+(if (= passcode "moria")
+ (print "welcome")
+ (print "Speak friend, and Enter!"))
+
+; imbriquez plusieurs if else if avec le mot clé cond
+(cond
+ [(= someval 42)
+ (print "Life, universe and everything else!")]
+ [(> someval 42)
+ (print "val too large")]
+ [(< someval 42)
+ (print "val too small")])
+
+; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt
+; les expressions comme defn ont un do implicite
+(do
+ (setv someval 10)
+ (print "someval is set to " someval)) ;=> 10
+
+; créer une liaison lexicale avec `let', toutes les variables déclarées
+; comme cela ont une portée locale
+(let [[nemesis {"superman" "lex luther"
+ "sherlock" "moriarty"
+ "seinfeld" "newman"}]]
+ (for [(, h v) (.items nemesis)]
+ (print (.format "{0}'s nemesis was {1}" h v))))
+
+;; classes
+; les classes sont définies comme ceci
+(defclass Wizard [object]
+ [[--init-- (fn [self spell]
+ (setv self.spell spell) ; init the spell attr
+ None)]
+ [get-spell (fn [self]
+ self.spell)]])
+
+;; allez voir hylang.org
+```
+
+### Lectures complémentaires
+
+Ce tutoriel est juste une simple introduction à hy/lisp/python.
+
+La documentation de HY: [http://hy.readthedocs.org](http://hy.readthedocs.org)
+
+Le repo GitHub de HY: [http://github.com/hylang/hy](http://github.com/hylang/hy)
+
+Sur freenode irc #hy, twitter hashtag #hylang
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
index 15478cdb..f1977dac 100644
--- a/fr-fr/javascript-fr.html.markdown
+++ b/fr-fr/javascript-fr.html.markdown
@@ -6,23 +6,26 @@ contributors:
filename: javascript-fr.js
translators:
- ['@nbrugneaux', 'https://nicolasbrugneaux.me']
+ - ['Michel Antoine', 'https://github.com/antoin-m']
lang: fr-fr
---
JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
Le langage avait à l'origine pour but d'être un langage de scripting simple
pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
-pour des applications web complexes. Mais son intégration très proche et
-simple des pages web, ainsi que le support natif des navigateurs a rendu
-le JavaScript incontournable aujourd'hui tant bien dans le front-end que
+pour des applications web complexes. Mais son intégration très proche et
+simple des pages web, ainsi que le support natif des navigateurs a rendu
+le JavaScript incontournable aujourd'hui tant bien dans le front-end que
dans le back-end.
En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
-Node.JS, un projet qui offre un environnement indépendant dans lequel un
-interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
+Node.JS, un projet qui offre un environnement indépendant dans lequel un
+interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
peut être utilisé directement côté serveur pour exécuter des programmes écrits
en JavaScript.
+ECMAScript (la norme du langage Javascript) entre en version 6. Cette version introduit de nombreuses mises à jour tout en restant rétrocompatible. L'implémentation de ces nouvelles fonctionnalités est en cours et celles-ci ne sont donc pas forcément compatibles avec tous les navigateurs.
+
```js
// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
@@ -31,7 +34,7 @@ en JavaScript.
// Toutes les expressions peuvent finir par ;
doStuff();
-// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
+// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
// lors de l’interprétation aux sauts de ligne, sauf exceptions
doStuff()
@@ -79,6 +82,12 @@ false; // faux
"abc";
'Hello, world';
+// *ES6:* Les chaines de caractères peuvent être crées en utilisant un modèle
+// entouré des quotes inverses (`) à la place des quotes classiques (' ou ").
+// Les variables sont interprétées avec ${var}
+let banta = "Harry", santa = "Hermione";
+`${banta}, your santa is ${santa}.` // = "Harry, your santa is Hermione."
+
// La négation utilise le symbole !
!true; // = false
!false; // = true
@@ -117,26 +126,34 @@ false; // faux
// Il y a également null et undefined
null; // utilisé pour une non-valeur
-undefined; // utilisé pour une valeur actuellement non présente (cependant,
+undefined; // utilisé pour une valeur actuellement non présente (cependant,
// undefined est aussi une valeur valide)
// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
// est 'presque-vrai' (truthy)
// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
+// *ES6:* Introduction d'un nouveau type primitif : Symbol
+var symbol_one = Symbol();
+var symbol_two = Symbol('This is optional description, for debugging');
+typeof symbol_one === 'symbol' // = true
+
+// *ES6:* Un Symbol est immutable et unique
+Symbol() === Symbol() // = false
+Symbol('learnx') === Symbol('learnx') // = false
///////////////////////////////////
-// 2. Variables, Tableaux et Objets
+// 2. Variables, Tableaux, Objets, Maps et Sets
-// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
+// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
var someVar = 5;
// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
someOtherVar = 10;
-// ... mais la variable aura une portée globale (plus communément trouvé en tant
-// que "global scope" en anglais), et non pas une portée limitée à la fonction
+// ... mais la variable aura une portée globale (plus communément trouvé en tant
+// que "global scope" en anglais), et non pas une portée limitée à la fonction
// dans laquelle vous l'aviez définie.
// Les variables déclarées et non assignées sont undefined par défaut
@@ -145,6 +162,32 @@ var someThirdVar = undefined;
// ... sont deux déclarations identiques.
+// Il est possible de déclarer plusieurs variables en séparant leur déclaration
+// avec l'opérateur virgule
+var someFourthVar = 2, someFifthVar = 4;
+
+// *ES6:* Les variables peuvent maintenant être déclarées avec les mots-clés
+// `let` et `const`
+let someSixthVar = 6;
+const someSeventhVar = 7;
+
+// *ES6:* Le mot-clé `let` attache la variable au block de code et non à la fonction
+// à l'inverse de `var`
+for (let i = 0; i < 10; i++) {
+ x += 10;
+}
+i; // = raises ReferenceError
+
+// *ES6:* Les variables "const" doivent être assignées lors de l'initialisation
+const someEighthVar = 7;
+const someNinthVar; // raises SyntaxError
+
+// *ES6:* Modifier une variable constante ne lève par d'erreur mais échoue
+// silencieusement
+const someNinthVar = 9;
+someNinthVar = 10;
+someNinthVar; // = 9
+
// Il y a des raccourcis pour les opérations mathématiques:
someVar += 5; // équivalent pour someVar = someVar + 5;
someVar *= 10; // de même, someVar = someVar * 100;
@@ -165,6 +208,22 @@ myArray.length; // = 4
// Ajout/Modification à un index spécifique
myArray[3] = 'Hello';
+// *ES6:* Les Arrays peuvent maintenant être déstructurés en utilisant le pattern matching
+var [a, b] = [1, 2];
+var [a, , b] = [1, -2, 2]
+
+a; // = 1
+b; // = 2
+
+// *ES6:* La déstructuration peut échouer silencieusement.
+// Il est aussi possible d'utiliser des valeurs par défaut
+var [a] = [];
+a; // = undefined;
+var [a = 1] = [];
+a; // = 1;
+var [a = 1] = [2];
+a; // = 2;
+
// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
// langages : ils sont une liste non-ordonnée de paires clé-valeur.
var myObj = {key1: 'Hello', key2: 'World'};
@@ -179,12 +238,55 @@ myObj['my other key']; // = 4
// .. ou avec un point si la clé est un identifiant valide.
myObj.myKey; // = 'myValue'
+// *ES6:* Un Symbol peut être utilisé en tant que clé. Puisque ceux-ci sont uniques,
+// le seul moyen d'accéder à la propriété est d'avoir une référence sur ce Symbol.
+myObj["key"] = "public value";
+myObj[Symbol("key")] = "secret value";
+myObj[Symbol("key")]; // = undefined
+
// Les objets sont eux aussi modifiables.
myObj.myThirdKey = true;
// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
myObj.myFourthKey; // = undefined
+// *ES6:* Comme les Arrays, les Objects peuvent être déstructurés en utilisant le pattern matching
+var {foo} = {foo: "bar"};
+foo // = "bar"
+
+// *ES6:* Les Objects déstructurés peuvent utiliser des noms de variables différents
+// de ceux d'origine grâce au pattern matching
+var {foo, moo: baz} = {foo: "bar", moo: "car"};
+foo // = "bar"
+baz // = "car"
+
+// *ES6:* Il est possible d'utiliser des valeurs par défaut lor de la déstructuration d'un Object
+var {foo="bar"} = {moo: "car"};
+foo // = "bar"
+
+// *ES6:* Une erreur lors de la déstructuration restera silencieuse
+var {foo} = {};
+foo // = undefined
+
+// *ES6:* Les Maps sont des objets itérables de type clé-valeur.
+// Il est possible de créer une nouvelle map en utilisant `new Map()`
+var myMap = new Map();
+
+// *ES6:* Il est possible d'ajouter un couple clé-valeur avec la méthode `.set()`,
+// de récupérer une valeur avec `.get()`,
+// de vérifier qu'une clé existe avec `.has()`
+// et enfin de supprimer un couple clé-valeur avec `.delete()`
+
+myMap.set("name", "Douglas");
+myMap.get("name"); // = "Douglas"
+myMap.has("name"); // = true
+myMap.delete("name");
+
+// *ES6:* Les Sets sont des ensembles de valeurs uniques.
+// Il est possible de créer un set avec `new Set()`.
+// Toute valeur non unique est ignorée.
+var mySet = new Set([1,2,2]);
+console.log([...mySet]); // = [1,2]
///////////////////////////////////
// 3. Logique et structures de contrôle
@@ -198,7 +300,7 @@ else if (count === 4) {
// uniquement quand count est 4
}
else {
- // le reste du temps, si ni 3, ni 4.
+ // le reste du temps, si ni 3, ni 4.
}
// De même pour while.
@@ -218,6 +320,22 @@ for (var i = 0; i < 5; i++){
// sera exécutée 5 fois
}
+// La boucle for...in permet d'itérer sur les noms des propriétés d'un objet
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+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 + " ";
+}
+description; // = "Paul Ken 18 "
+
// && est le "et" logique, || est le "ou" logique
if (house.size === 'big' && house.colour === 'blue'){
house.contains = 'bear';
@@ -264,7 +382,21 @@ function myFunction(thing){
}
myFunction('foo'); // = 'FOO'
-// Les fonctions JavaScript sont des objets de première classe, donc peuvent
+// Attention, la valeur à retourner doit se trouver sur la même ligne que
+// le mot-clé `return` sinon la fonction retournera systématiquement `undefined`
+function myFunction(){
+ return // <- semicolon automatically inserted here
+ {thisIsAn: 'object literal'}
+}
+myFunction(); // = undefined
+
+// *ES6:* Les paramètres des fonctions peuvent désormais avoir des valeurs par défaut
+function default(x, y = 2) {
+ return x + y;
+}
+default(10); // == 12
+
+// Les fonctions JavaScript sont des objets de première classe, donc peuvent
// être réassignées à d'autres variables et passées en tant que paramètres pour
// d'autres fonctions
function myFunction(){
@@ -274,13 +406,17 @@ setTimeout(myFunction, 5000);
// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
// que Node.js le rendent disponible
-// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
+// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
// anonymes
setTimeout(function(){
// ce code s'exécutera dans 5 secondes
}, 5000);
-// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
+// *ES6:* Introduction d'un sucre syntaxique permettant de créer
+// une fonction anonyme de la forme : `param => returnValue`.
+setTimeout(() => console.log('5 seconds, are up.'), 5000);
+
+// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
// les fonctions, et pas dans les autres blocs.
if (true){
var i = 5;
@@ -293,7 +429,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
var temporary = 5;
// Nous pouvons accéder au scope global en assignant à l'objet global,
// qui dans les navigateurs est "window". Il est différent dans Node.js,
- // le scope global sera en fait local au module dans lequel vous
+ // le scope global sera en fait local au module dans lequel vous
// vous trouvez. http://nodejs.org/api/globals.html
window.permanent = 10;
})();
@@ -302,8 +438,8 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre
temporary; // raises ReferenceError
permanent; // = 10
-// Une des fonctionnalités les plus puissantes de Javascript est le système de
-// closures. Si une fonction est définie dans une autre fonction, alors la
+// Une des fonctionnalités les plus puissantes de Javascript est le système de
+// closures. Si une fonction est définie dans une autre fonction, alors la
// fonction interne aura accès aux variables de la fonction parente, même si
// celle-ci a déjà finie son exécution.
function sayHelloInFiveSeconds(name){
@@ -318,6 +454,18 @@ function sayHelloInFiveSeconds(name){
}
sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
+// *ES6:* Les paramètres des fonctions appelées avec un tableau en entré
+// préfixé par `...` vont se peupler avec les éléments du tableau
+function spread(x, y, z) {
+ return x + y + z;
+}
+spread(...[1,2,3]); // == 6
+
+// *ES6:* Les fonctions peuvent recevoir les paramètres dans un tableau en utilisant l'opérateur `...`
+function spread(x, y, z) {
+ return x + y + z;
+}
+spread(...[1,2,3]); // == 6
///////////////////////////////////
// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
@@ -340,7 +488,7 @@ myObj = {
};
myObj.myFunc(); // = 'Hello world!'
-// La valeur de "this" change de par l'endroit où la fonction est appelée, et
+// La valeur de "this" change de par l'endroit où la fonction est appelée, et
// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
// est appelée hors du contexte l'objet.
var myFunc = myObj.myFunc;
@@ -356,7 +504,7 @@ myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = 'HELLO WORLD!'
// Le contexte correspond à la valeur de "this".
-// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
+// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
// pour une fonction quand elle est appelée grâce à "call" ou "apply".
var anotherFunc = function(s){
return this.myString + s;
@@ -371,19 +519,19 @@ Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
-// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
-// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
+// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
+// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
// "bind" pour garder une référence à la fonction avec ce "this".
var boundFunc = anotherFunc.bind(myObj);
boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
-// "bind" peut aussi être utilisé pour créer une application partielle de la
+// "bind" peut aussi être utilisé pour créer une application partielle de la
// fonction (curry)
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
-// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
+// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
// crée et mis à disposition de la fonction via "this". Ces fonctions sont
// communément appelées constructeurs.
var MyConstructor = function(){
@@ -395,8 +543,8 @@ myNewObj.myNumber; // = 5
// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
-// Quelques implémentations de JS vous laissent accéder au prototype avec la
-// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
+// Quelques implémentations de JS vous laissent accéder au prototype avec la
+// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
// et ne fonctionne pas dans certains des navigateurs actuels.
var myObj = {
myString: 'Hello world!'
@@ -478,7 +626,7 @@ String.prototype.firstCharacter = function(){
'abc'.firstCharacter(); // = 'a'
// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
-// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
+// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
// les vieux navigateurs.
//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
@@ -492,31 +640,83 @@ if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe
return new Constructor();
}
}
+
+// *ES6:* Les objets peuvent être équipés de proxies qui permettent d'intercepter
+// les actions sur leurs propriétés. Voici comment créer un proxy sur un objet :
+var proxyObject = new Proxy(object, handler);
+
+// *ES6:* Les méthodes d'un objet handler sont appelées lors de l'interception d'une action.
+// La méthode `.get()` est appelée à chaque lecture d'une propriété
+// tandis que la méthode `.set()` est appelée à chaque écriture.
+var handler = {
+ get (target, key) {
+ console.info('Get on property' + key);
+ return target[key];
+ },
+ set (target, key, value) {
+ console.info('Set on property' + key);
+ return true;
+ }
+}
+
+// *ES6:* Les classes peuvent désormais être définies en utilisant le mot-clé `class`.
+// Le constructeur s'appelle `constructor` et les méthodes statiques utilisent le mot-clé `static`
+class Foo {
+ constructor() {console.log("constructing Foo");}
+ bar() {return "bar";}
+ static baz() {return "baz";}
+}
+
+// *ES6:* Les objets issus des classes sont initialisés avec le mot-clé `new`.
+// Il est possible d'hériter d'une classe avec le mot-clé `extends`
+var FooObject = new Foo(); // = "constructing Foo"
+class Zoo extends Foo {}
+
+// *ES6:* Les méthodes statiques doivent être appelées par la classe, les autres méthodes par l'objet
+Foo.baz() // = "baz"
+FooObject.bar() // = "bar"
+
+// *ES6:* Il est désormais possible d'exporter des valeurs en tant que module.
+// Les exports peuvent être n'importe quel objet, valeur ou fonction.
+var api = {
+ foo: "bar",
+ baz: "ponyfoo"
+};
+export default api;
+
+// *ES6:* La syntaxe `export default` permet d'exporter l'objet sans en changer le nom.
+// Il y a plusieurs façons de l'importer:
+import coolapi from "api"; // = importe le module dans la variable `coolapi`
+import {foo, baz} from "api"; // = importe les attributs `foo` et `baz` du module
+import {foo as moo, baz} from "api"; // = importe les attributs `foo` (en le renommant `moo`) et `baz` du module
+import _, {map} from "api"; // = importe les exports par défaut ET `map`
+import * as coolapi from "api"; // = importe le namespace global du module
+
```
## Pour aller plus loin (en anglais)
The [Mozilla Developer
Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
-excellente documentation pour le Javascript dans les navigateurs. Et contient
+excellente documentation pour le Javascript dans les navigateurs. Et contient
également un wiki pour s'entraider.
MDN's [A re-introduction to
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
-à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
+à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
plutôt ici :
[Document Object
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
un guide pour vous éviter les faux-amis dans le JavaScript.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
-En addition aux contributeurs de cet article, du contenu provient du
+En addition aux contributeurs de cet article, du contenu provient du
"Python tutorial" de Louie Dinh, et de [JS
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
sur le réseau Mozilla.
diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown
index e5e7c73a..66f0efbe 100644
--- a/fr-fr/markdown.html.markdown
+++ b/fr-fr/markdown.html.markdown
@@ -2,7 +2,7 @@
language: markdown
contributors:
- ["Andrei Curelaru", "http://www.infinidad.fr"]
-filename: markdown.md
+filename: markdown-fr.md
lang: fr-fr
---
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
new file mode 100644
index 00000000..e737b7aa
--- /dev/null
+++ b/fr-fr/perl-fr.html.markdown
@@ -0,0 +1,174 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-fr.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+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 5 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
+# Les commentaires en une ligne commencent par un dièse
+
+
+#### Types de variables de Perl
+
+# Les variables comment par un symbole précisant le type.
+# Un nom de variable valide commence par une lettre ou un underscore,
+# suivi d'un nombre quelconque de lettres, chiffres ou underscores.
+
+### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
+
+## Scalaires
+# Un scalaire représente une valeur unique :
+my $animal = "chameau";
+my $reponse = 42;
+
+# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante
+# et Perl les convertira automatiquement entre elles quand nécessaire.
+
+## Tableaux
+# Un tableau représente une liste de valeurs :
+my @animaux = ("chameau", "lama", "chouette");
+my @nombres = (23, 42, 69);
+my @melange = ("chameau", 42, 1.23);
+
+## Hashes
+# Un hash représente un ensemble de paires de clé/valeur :
+my %fruit_couleur = ("pomme", "rouge", "banane", "jaune");
+
+# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment :
+
+my %fruit_couleur = (
+ pomme => "rouge",
+ banane => "jaune"
+);
+
+# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata
+# (perldoc perldata)
+
+# Des types de données plus complexes peuvent être construits en utilisant des références,
+# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes.
+
+#### Conditions et boucles
+
+# Perl possède la plupart des conditions et boucles habituelles.
+
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (condition) {
+ ...
+}
+# Ceci est fourni en tant que version plus lisible de "if (!condition)"
+
+# la postcondition à la sauce Perl
+
+print "Yow!" if $zippy;
+print "Nous n'avons pas de banane." unless $bananes;
+
+# while
+while (condition) {
+ ...
+}
+
+# boucle for et iteration
+for (my $i = 0; $i < $max; $i++) {
+ print "l'index est $i";
+}
+
+for (my $i = 0; $i < @elements; $i++) {
+ print "L'élément courant est " . $elements[$i];
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+# implicitement
+
+# La variable de contexte scalaire $_ est utilisée par défaut dans différentes
+# situations, comme par exemple dans la boucle foreach ou en argument par défaut
+# de la plupart des fonctions pour en simplifier l'écriture.
+
+# Dans l'exemple suivant, $_ prends successivement la valeur de
+# chaque élément de la liste.
+
+for (@elements) {
+ print; # affiche le contenu de $_
+}
+
+
+#### Expressions régulières
+
+# Le support des expressions régulières par Perl est aussi large que profond
+# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs.
+# Cependant, pour faire court :
+
+# Simple correspondance
+if (/foo/) { ... } # vrai si $_ contient "foo"
+if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
+
+# Simple substitution
+
+$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a
+$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
+
+
+#### Fichiers et E/S
+
+# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
+
+open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!";
+open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!";
+open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
+
+# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>".
+# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier
+# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un
+# élément de la liste :
+
+my $ligne = <$in>
+my $lignes = <$in>
+
+#### Ecrire des fonctions
+
+# Ecrire des fonctions est facile :
+
+sub logger {
+ my $logmessage = shift;
+
+ open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!";
+
+ print $logfile $logmessage;
+}
+
+# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée :
+
+logger("On a une fonction de logging!!");
+```
+
+#### Utiliser des modules Perl
+
+Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl.
+
+Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser.
+
+#### Pour en savoir plus
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn at www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - and perl built-in : `perldoc perlintro`
diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown
index 04d0a55d..3d60157c 100644
--- a/fr-fr/python3-fr.html.markdown
+++ b/fr-fr/python3-fr.html.markdown
@@ -627,7 +627,7 @@ Human.grunt() # => "*grunt*"
# On peut importer des modules
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# On peut importer des fonctions spécifiques d'un module
from math import ceil, floor
diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown
index b8807104..52d34650 100644
--- a/fr-fr/typescript-fr.html.markdown
+++ b/fr-fr/typescript-fr.html.markdown
@@ -87,22 +87,22 @@ mySearch = function(src: string, sub: string) {
// Les membres des classes sont publiques par défaut.
class Point {
- // Propriétés
- x: number;
-
- // Constructeur - Les mots clés "public" et "private" dans ce contexte
- // génèrent le code de la propriété et son initialisation dans le
- // constructeur. Ici, "y" sera défini de la même façon que "x",
- // mais avec moins de code. Les valeurs par défaut sont supportées.
- constructor(x: number, public y: number = 0) {
- this.x = x;
- }
+ // Propriétés
+ x: number;
+
+ // Constructeur - Les mots clés "public" et "private" dans ce contexte
+ // génèrent le code de la propriété et son initialisation dans le
+ // constructeur. Ici, "y" sera défini de la même façon que "x",
+ // mais avec moins de code. Les valeurs par défaut sont supportées.
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
- // Fonctions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ // Fonctions
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
- // Membres statiques
- static origin = new Point(0, 0);
+ // Membres statiques
+ static origin = new Point(0, 0);
}
var p1 = new Point(10 ,20);
@@ -110,17 +110,17 @@ var p2 = new Point(25); // y sera 0
// Héritage
class Point3D extends Point {
- constructor(x: number, y: number, public z: number = 0) {
- // Un appel explicite au constructeur de la super classe
- // est obligatoire.
- super(x, y);
- }
+ constructor(x: number, y: number, public z: number = 0) {
+ // Un appel explicite au constructeur de la super classe
+ // est obligatoire.
+ super(x, y);
+ }
- // Redéfinition
- dist() {
- var d = super.dist();
- return Math.sqrt(d * d + this.z * this.z);
- }
+ // Redéfinition
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
}
// Modules, "." peut être utilisé comme un séparateur de sous modules.
@@ -144,19 +144,19 @@ var s2 = new G.Square(10);
// Génériques
// Classes
class Tuple<T1, T2> {
- constructor(public item1: T1, public item2: T2) {
- }
+ constructor(public item1: T1, public item2: T2) {
+ }
}
// Interfaces
interface Pair<T> {
- item1: T;
- item2: T;
+ item1: T;
+ item2: T;
}
// Et fonctions
var pairToTuple = function<T>(p: Pair<T>) {
- return new Tuple(p.item1, p.item2);
+ return new Tuple(p.item1, p.item2);
};
var tuple = pairToTuple({ item1:"hello", item2:"world"});
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index d63b9f1d..809a1da2 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -335,10 +335,10 @@ module DataTypeExamples =
let worker = Worker jdoe
// ------------------------------------
- // Modelling with types
+ // Modeling with types
// ------------------------------------
- // Union types are great for modelling state without using flags
+ // Union types are great for modeling state without using flags
type EmailAddress =
| ValidEmailAddress of string
| InvalidEmailAddress of string
@@ -526,7 +526,7 @@ module AsyncExample =
|> Async.RunSynchronously // start them off
// ================================================
-// .NET compatability
+// .NET compatibility
// ================================================
module NetCompatibilityExamples =
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 936744a0..34eee748 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -426,7 +426,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
greater = filter (>= p) xs
```
-Haskell is easy to install. Get it [here](http://www.haskell.org/platform/).
+There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install).
You can find a much gentler introduction from the excellent
[Learn you a Haskell](http://learnyouahaskell.com/) or
diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown
index 267db4d0..b5ae2107 100644
--- a/hu-hu/coffeescript-hu.html.markdown
+++ b/hu-hu/coffeescript-hu.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Xavier Yao", "http://github.com/xavieryao"]
translators:
- ["Tamás Diószegi", "http://github.com/ditam"]
+lang: hu-hu
filename: coffeescript-hu.coffee
---
@@ -103,4 +104,4 @@ eat food for food in foods when food isnt 'chocolate'
## További források
- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
-- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) \ No newline at end of file
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/javascript.html.markdown b/javascript.html.markdown
index e285ca4e..98261334 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -561,7 +561,9 @@ of the language.
[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
-[Javascript: The Right Way][9] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
+[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
+
+[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
In addition to direct contributors to this article, some content is adapted from
@@ -577,4 +579,5 @@ Mozilla Developer Network.
[6]: http://www.amazon.com/gp/product/0596805527/
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
[8]: http://eloquentjavascript.net/
-[9]: http://jstherightway.org/
+[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
+[10]: http://jstherightway.org/
diff --git a/json.html.markdown b/json.html.markdown
index cde7bc40..a612cffe 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -8,27 +8,24 @@ contributors:
- ["Michael Neth", "https://github.com/infernocloud"]
---
-As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever.
+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 in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
-
-For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
-
-A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null.
-
-Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
-
-File extension for JSON files is ".json" and the MIME type for JSON text is "application/json".
+A piece of JSON must represent either:
+* A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
+* An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence.
+ an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`).
-Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data.
+JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility.
-More information can be found at http://www.json.org/
+For the purposes of this tutorial, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
-JSON is built on two structures:
-* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
-* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
+Supported data types:
-An object with various name/value pairs.
+* Strings: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"`
+* Numbers: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4`
+* Objects: `{ "key": "value" }`
+* Arrays: `["Values"]`
+* Miscellaneous: `true`, `false`, `null`
```json
{
@@ -66,20 +63,20 @@ An object with various name/value pairs.
"alternative style": {
"comment": "check this out!"
- , "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
+ , "comma position": "doesn't matter, if it's before the next key, it's valid"
, "another comment": "how nice"
- }
-}
-```
+ },
-A single array of values by itself is also valid JSON.
-```json
-[1, 2, 3, "text", true]
-```
-Objects can be a part of the array as well.
+ "whitespace": "Does not matter.",
-```json
-[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}]
+
+
+ "that was short": "And done. You now know everything JSON has to offer."
+}
```
+
+## Further Reading
+
+* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics.
diff --git a/julia.html.markdown b/julia.html.markdown
index cba7cd45..ef3ea244 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -2,6 +2,7 @@
language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
+ - ["Pranit Bauva", "http://github.com/pranitbauva1997"]
filename: learnjulia.jl
---
@@ -102,6 +103,11 @@ false
# Printing is easy
println("I'm Julia. Nice to meet you!")
+# String can be compared lexicographically
+"good" > "bye" # => true
+"good" == "good" # => true
+"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true
+
####################################################
## 2. Variables and Collections
####################################################
@@ -390,6 +396,14 @@ end
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
+# Compact assignment of functions
+f_add(x, y) = x + y # => "f (generic function with 1 method)"
+f_add(3, 4) # => 7
+
+# Function can also return multiple values as tuple
+f(x, y) = x + y, x - y
+f(3, 4) # => (7, -1)
+
# You can define functions that take a variable number of
# positional arguments
function varargs(args...)
@@ -723,7 +737,7 @@ code_native(square_area, (Float64,))
# ret
#
# Note that julia will use floating point instructions if any of the
-# arguements are floats.
+# arguments are floats.
# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
diff --git a/latex.html.markdown b/latex.html.markdown
index 31231a70..2492f226 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- ["Colton Kohnke", "http://github.com/voltnor"]
- ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+ - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"]
filename: learn-latex.tex
---
@@ -227,6 +228,15 @@ format you defined in Step 1.
That's all for now!
+% Most often, you would want to have a references section in your document.
+% The easiest way to set this up would be by using the bibliography section
+\begin{thebibliography}{1}
+ % similar to other lists, the \bibitem command can be used to list items
+ % each entry can then be cited directly in the body of the text
+ \bibitem{latexwiki} The amazing LaTeX wikibook: {\em https://en.wikibooks.org/wiki/LaTeX}
+ \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
+\end{thebibliography}
+
% end the document
\end{document}
```
diff --git a/less.html.markdown b/less.html.markdown
new file mode 100644
index 00000000..41d66a54
--- /dev/null
+++ b/less.html.markdown
@@ -0,0 +1,379 @@
+---
+language: less
+filename: learnless.less
+contributors:
+ - ["Saravanan Ganesh", "http://srrvnn.me"]
+---
+
+Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more.
+Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
+
+```less
+
+
+//Single line comments are removed when Less is compiled to CSS.
+
+/*Multi line comments are preserved. */
+
+
+/*Variables
+==============================*/
+
+
+
+/* You can store a CSS value (such as a color) in a variable.
+Use the '@' symbol to create a variable. */
+
+@primary-color: #A3A4FF;
+@secondary-color: #51527F;
+@body-font: 'Roboto', sans-serif;
+
+/* You can use the variables throughout your stylesheet.
+Now if you want to change a color, you only have to make the change once.*/
+
+body {
+ background-color: @primary-color;
+ color: @secondary-color;
+ font-family: @body-font;
+}
+
+/* This would compile to: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* This is much more maintainable than having to change the color
+each time it appears throughout your stylesheet. */
+
+
+/*Mixins
+==============================*/
+
+
+
+/* If you find you are writing the same code for more than one
+element, you might want to reuse that easily.*/
+
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* You can use the mixin by simply adding the selector as a style */
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/*Which would compile to: */
+.center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+/* You can omit the mixin code from being compiled by adding paranthesis
+ after the selector */
+
+.center() {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+div {
+ .center;
+ background-color: @primary-color;
+}
+
+/*Which would compile to: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/*Functions
+==============================*/
+
+
+
+/* Less provides functions that can be used to accomplish a variety of
+ tasks. Consider the following */
+
+/* Functions can be invoked by using their name and passing in the
+ required arguments */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fadeout(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Less code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+.average(@x, @y) {
+ @average_result: ((@x + @y) / 2);
+}
+
+div {
+ .average(16px, 50px); // "call" the mixin
+ padding: @average_result; // use its "return" value
+}
+
+/* Compiles to: */
+
+div {
+ padding: 33px;
+}
+
+/*Extend (Inheritance)
+==============================*/
+
+
+
+/*Extend is a way to share the properties of one selector with another. */
+
+.display {
+ height: 50px;
+}
+
+.display-success {
+ &:extend(.display);
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display,
+.display-success {
+ height: 50px;
+}
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way it groups together the classes that all share
+ the same base styling. If this was done with a mixin, the properties
+ would be duplicated for each statement that
+ called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Less compiler. */
+
+
+
+/*Nesting
+==============================*/
+
+
+
+/*Less allows you to nest selectors within selectors */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' will be replaced by the parent selector. */
+/* You can also nest pseudo-classes. */
+/* Keep in mind that over-nesting will make your code less maintainable.
+Best practices recommend going no more than 3 levels deep when nesting.
+For example: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compiles to: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Partials and Imports
+==============================*/
+
+
+
+/* Less allows you to create partial files. This can help keep your Less
+ code modularized. Partial files conventionally begin with an '_',
+ e.g. _reset.less. and are imported into a main less file that gets
+ compiled into CSS */
+
+/* Consider the following CSS which we'll put in a file called _reset.less */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Less offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Less takes the
+ imported file and combines it with the compiled code. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+/*Math Operations
+==============================*/
+
+
+
+/* Less provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Less files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+@content-area: 960px;
+@main-content: 600px;
+@sidebar-content: 300px;
+
+@main-size: @main-content / @content-area * 100%;
+@sidebar-size: @sidebar-content / @content-area * 100%;
+@gutter: 100% - (@main-size + @sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: @main-size;
+}
+
+.sidebar {
+ width: @sidebar-size;
+}
+
+.gutter {
+ width: @gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+## Practice Less
+
+If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/).
+
+## Compatibility
+
+Less can be used in any project as long as you have a program to compile it
+into CSS. You'll want to verify that the CSS you're using is compatible
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
+
+## Further reading
+* [Official Documentation](http://lesscss.org/features/)
diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown
new file mode 100644
index 00000000..8c97e598
--- /dev/null
+++ b/lt-lt/json-lt.html.markdown
@@ -0,0 +1,81 @@
+---
+language: json
+filename: learnjson.json
+lang: lt-lt
+contributors:
+ - ["Zygimantus", "https://github.com/zygimantus"]
+---
+
+JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka.
+
+JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo.
+
+JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null.
+
+Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+.
+
+Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“.
+
+Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą.
+
+Daugiau informacijos galima rasti http://www.json.org/
+
+JSON yra pastatytas iš dviejų struktūrų:
+* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas.
+* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka.
+
+Objektas su įvairiomis vardo/reikšmės poromis.
+
+```json
+{
+ "raktas": "reikšmė",
+
+ "raktai": "privalo visada būti uždaryti dvigubomis kabutėmis",
+ "skaičiai": 0,
+ "eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".",
+ "turi logiką?": true,
+ "niekas": null,
+
+ "didelis skaičius": 1.2e+100,
+
+ "objektai": {
+ "komentaras": "Dauguma tavo struktūrų ateis iš objektų.",
+
+ "masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5],
+
+ "kitas objektas": {
+ "komentaras": "Šie dalykai gali būti įdedami naudingai."
+ }
+ },
+
+ "kvailumas": [
+ {
+ "kalio šaltiniai": ["bananai"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "alternativus stilius": {
+ "komentaras": "tik pažiūrėk!"
+ , "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas"
+ , "kitas komentaras": "kaip gražu"
+ }
+}
+```
+
+Paprastas reikšmių masyvas pats savaime yra galiojantis JSON.
+
+```json
+[1, 2, 3, "tekstas", true]
+```
+
+Objektai taip pat gali būti masyvų dalis.
+
+```json
+[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}]
+```
diff --git a/lua.html.markdown b/lua.html.markdown
index 3d95c146..2cd4d7bb 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -190,7 +190,7 @@ end
--------------------------------------------------------------------------------
-- A table can have a metatable that gives the table operator-overloadish
--- behavior. Later we'll see how metatables support js-prototypey behaviour.
+-- behaviour. Later we'll see how metatables support js-prototypey behaviour.
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
f2 = {a = 2, b = 3}
diff --git a/markdown.html.markdown b/markdown.html.markdown
index b956a5f2..8961c995 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -2,45 +2,63 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
filename: markdown.md
---
-Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
-
-Give me as much feedback as you want! / Feel free to fork and pull request!
+Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
+Markdown also varies in implementation from one parser to a next. This
+guide will attempt to clarify when features are universal or when they are
+specific to a certain parser.
+
+- [HTML Elements](#html-elements)
+- [Headings](#headings)
+- [Simple Text Styles](#simple-text-styles)
+- [Paragraphs](#paragraphs)
+- [Lists](#lists)
+- [Code blocks](#code-blocks)
+- [Horizontal rule](#horizontal-rule)
+- [Links](#links)
+- [Images](#images)
+- [Miscellany](#miscellany)
+
+## HTML Elements
+Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. This
-means we can use HTML elements in Markdown, such as the comment element, and
-they won't be affected by a markdown parser. However, if you create an HTML
-element in your markdown file, you cannot use markdown syntax within that
-element's contents. -->
+<!--This means we can use HTML elements in Markdown, such as the comment element,
+and they won't be affected by a markdown parser. However, if you create an HTML element
+in your markdown file, you cannot use markdown syntax within that element's contents.-->
+```
-<!-- Markdown also varies in implementation from one parser to a next. This
-guide will attempt to clarify when features are universal or when they are
-specific to a certain parser. -->
+## Headings
-<!-- Headings -->
-<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#). -->
+You can create HTML elements `<h1>` through `<h6>` easily by prepending the
+text you want to be in that element by a number of hashes (#).
+
+```markdown
# This is an <h1>
## This is an <h2>
### This is an <h3>
#### This is an <h4>
##### This is an <h5>
###### This is an <h6>
+```
+Markdown also provides us with two alternative ways of indicating h1 and h2.
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. -->
+```markdown
This is an h1
=============
This is an h2
-------------
+```
+## Simple text styles
-<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown. -->
+Text can be easily styled as italic or bold using markdown.
+```markdown
*This text is in italics.*
_And so is this text._
@@ -50,15 +68,20 @@ __And so is this text.__
***This text is in both.***
**_As is this!_**
*__And this!__*
+```
-<!-- In Github Flavored Markdown, which is used to render markdown files on
-Github, we also have strikethrough: -->
+In Github Flavored Markdown, which is used to render markdown files on
+Github, we also have strikethrough:
+```markdown
~~This text is rendered with strikethrough.~~
+```
+## Paragraphs
-<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or
-multiple blank lines. -->
+Paragraphs are a one or multiple adjacent lines of text separated by one or
+multiple blank lines.
+```markdown
This is a paragraph. I'm typing in a paragraph isn't this fun?
Now I'm in paragraph 2.
@@ -66,16 +89,20 @@ I'm still in paragraph 2 too!
I'm in paragraph three!
+```
-<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
-with two or more spaces and then begin a new paragraph. -->
+Should you ever want to insert an HTML <br /> tag, you can end a paragraph
+with two or more spaces and then begin a new paragraph.
+```markdown
I end with two spaces (highlight me to see them).
There's a <br /> above me!
+```
-<!-- Block quotes are easy and done with the > character. -->
+Block quotes are easy and done with the > character.
+```markdown
> This is a block quote. You can either
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
> It doesn't make a difference so long as they start with a `>`.
@@ -84,9 +111,12 @@ There's a <br /> above me!
>> of indentation?
> How neat is that?
-<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens. -->
+```
+
+## Lists
+Unordered lists can be made using asterisks, pluses, or hyphens.
+```markdown
* Item
* Item
* Another item
@@ -102,159 +132,182 @@ or
- Item
- Item
- One last item
+```
+Ordered lists are done with a number followed by a period.
-<!-- Ordered lists are done with a number followed by a period. -->
-
+```markdown
1. Item one
2. Item two
3. Item three
+```
-<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea. -->
+You don't even have to label the items correctly and markdown will still
+render the numbers in order, but this may not be a good idea.
+```markdown
1. Item one
1. Item two
1. Item three
-<!-- (This renders the same as the above example) -->
-
-<!-- You can also use sublists. -->
+```
+(This renders the same as the above example)
+You can also use sublists
+```markdown
1. Item one
2. Item two
3. Item three
* Sub-item
* Sub-item
4. Item four
+```
-<!-- There are even task lists. This creates HTML checkboxes. -->
+There are even task lists. This creates HTML checkboxes.
+```markdown
Boxes below without the 'x' are unchecked HTML checkboxes.
- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
+```
+
+## Code blocks
-<!-- Code blocks -->
-<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab. -->
+You can indicate a code block (which uses the `<code>` element) by indenting
+a line with four spaces or a tab.
+```markdown
This is code
So is this
+```
-<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code. -->
+You can also re-tab (or add an additional four spaces) for indentation
+inside your code
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Inline code can be created using the backtick character ` -->
+Inline code can be created using the backtick character `
+```markdown
John didn't even know what the `go_to()` function did!
+```
-<!-- In Github Flavored Markdown, you can use a special syntax for code. -->
-
+In Github Flavored Markdown, you can use a special syntax for code
+```markdown
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
def foobar
puts "Hello world!"
end
\`\`\` <!-- here too, no backslashes, just ``` -->
+```
-<!-- The above text doesn't require indenting, plus Github will use syntax
-highlighting of the language you specify after the ``` -->
+The above text doesn't require indenting, plus Github will use syntax
+highlighting of the language you specify after the \`\`\`
-<!-- Horizontal rule (<hr />) -->
-<!-- Horizontal rules are easily added with three or more asterisks or hyphens,
-with or without spaces. -->
+## Horizontal rule
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
+with or without spaces.
+```markdown
***
---
- - -
****************
+```
-<!-- Links -->
-<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses (). -->
+## Links
-[Click me!](http://test.com/)
-
-<!-- You can also add a link title using quotes inside the parentheses. -->
+One of the best things about markdown is how easy it is to make links. Put
+the text to display in hard brackets [] followed by the url in parentheses ()
+```markdown
+[Click me!](http://test.com/)
+```
+You can also add a link title using quotes inside the parentheses.
+```markdown
[Click me!](http://test.com/ "Link to Test.com")
-
-<!-- Relative paths work too. -->
-
+```
+Relative paths work too.
+```markdown
[Go to music](/music/).
-
-<!-- Markdown also supports reference style links. -->
-
+```
+Markdown also supports reference style links.
+```markdown
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
[link1]: http://test.com/ "Cool!"
[foobar]: http://foobar.biz/ "Alright!"
-
-<!-- The title can also be in single quotes or in parentheses, or omitted
+```
+The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
-can be anything so long as they are unique. -->
-
-<!-- There is also "implicit naming" which lets you use the link text as the id. -->
+can be anything so long as they are unique.
+There is also "implicit naming" which lets you use the link text as the id.
+```markdown
[This][] is a link.
[this]: http://thisisalink.com/
+```
+But it's not that commonly used.
-<!-- But it's not that commonly used. -->
-
-<!-- Images -->
-<!-- Images are done the same way as links but with an exclamation point in front! -->
-
+## Images
+Images are done the same way as links but with an exclamation point in front!
+```markdown
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
-
-<!-- And reference style works as expected. -->
-
+```
+And reference style works as expected.
+```markdown
![This is the alt-attribute.][myimage]
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
+```
-<!-- Miscellany -->
-<!-- Auto-links -->
-
+## Miscellany
+### Auto-links
+```markdown
<http://testwebsite.com/> is equivalent to
[http://testwebsite.com/](http://testwebsite.com/)
+```
-<!-- Auto-links for emails -->
-
+### Auto-links for emails
+```markdown
<foo@bar.com>
+```
-<!-- Escaping characters -->
-
+### Escaping characters
+```markdown
I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
+```
-<!-- Keyboard keys -->
-<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. -->
+### Keyboard keys
+In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
+```markdown
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+### Tables
-<!-- Tables -->
-<!-- Tables are only available in Github Flavored Markdown and are slightly
-cumbersome, but if you really want it: -->
-
+Tables are only available in Github Flavored Markdown and are slightly
+cumbersome, but if you really want it:
+```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| Left-aligned | Centered | Right-aligned |
| blah | blah | blah |
+```
+or, for the same results
-<!-- or, for the same results -->
-
+```markdown
Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
-
-<!-- The end! -->
-
```
-
+---
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 9d78978e..ddc0cb40 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -15,6 +15,7 @@ If you have any feedback please feel free to reach me at
[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
```matlab
+%% Code sections start with two percent signs. Section titles go on the same line.
% Comments start with a percent sign.
%{
@@ -72,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
% Calling functions can be done in either of two ways:
% Standard function syntax:
-load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
+load('myFile.mat', 'y') % arguments within parentheses, separated by commas
% Command syntax:
load myFile.mat y % no parentheses, and spaces instead of commas
% Note the lack of quote marks in command form: inputs are always passed as
@@ -278,7 +279,7 @@ clf clear % clear current figure window, and reset most figure properties
% Properties can be set and changed through a figure handle.
% You can save a handle to a figure when you create it.
-% The function gcf returns a handle to the current figure
+% The function get returns a handle to the current figure
h = plot(x, y); % you can save a handle to a figure when you create it
set(h, 'Color', 'r')
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 1fa731e3..097cb846 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -1,13 +1,12 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
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.
@@ -152,13 +151,13 @@ int main (int argc, const char * argv[])
[mutableDictionary setObject:@"value1" forKey:@"key1"];
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
-
+
// Change types from Mutable To Immutable
//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
-
-
+
+
// Set object
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
@@ -605,7 +604,7 @@ int main (int argc, const char * argv[]) {
// Starting in Xcode 7.0, you can create Generic classes,
// allowing you to provide greater type safety and clarity
-// without writing excessive boilerplate.
+// without writing excessive boilerplate.
@interface Result<__covariant A> : NSObject
- (void)handleSuccess:(void(^)(A))success
@@ -633,7 +632,7 @@ Result<NSArray *> *result;
@property (nonatomic) NSNumber * object;
@end
-// It should be obvious, however, that writing one
+// It should be obvious, however, that writing one
// Class to solve a problem is always preferable to writing two
// Note that Clang will not accept generic types in @implementations,
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 45b15f05..1829f964 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,10 +1,9 @@
---
-name: perl6
category: language
language: perl6
filename: learnperl6.pl
contributors:
- - ["Nami-Doc", "http://github.com/Nami-Doc"]
+ - ["vendethiel", "http://github.com/vendethiel"]
---
Perl 6 is a highly capable, feature-rich programming language made for at
@@ -374,6 +373,8 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return
say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
+# Note: if you try to do either of those with an infinite array,
+# you'll trigger an infinite loop (your program won't finish)
# You can use that in most places you'd expect, even assigning to an array
my @numbers = ^20;
@@ -735,7 +736,7 @@ try {
# You can throw an exception using `die`:
die X::AdHoc.new(payload => 'Error !');
-# You can access the last exception with `$!` (usually used in a `CATCH` block)
+# You can access the last exception with `$!` (use `$_` in a `CATCH` block)
# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
# which is a kind of "unthrown exception". They're not thrown until you tried to look
@@ -763,8 +764,9 @@ try {
# 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 usually don't use packages directly: you use `class Package::Name::Here;`,
-# or if you only want to export variables/subs, you can use `module`:
+# You're not supposed to use the package keyword, usually:
+# you use `class Package::Name::Here;` to declare a class,
+# or if you only want to export variables/subs, you can use `module`:
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
@@ -774,11 +776,6 @@ unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
-# NOTE for Perl 5 users: even though the `package` keyword exists,
-# the braceless form is invalid (to catch a "perl5ism"). This will error out:
-# package Foo; # because Perl 6 will think the entire file is Perl 5
-# Just use `module` or the brace version of `package`.
-
# You can use a module (bring its declarations into scope) with `use`
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; #=> [1]
@@ -870,8 +867,16 @@ LEAVE { say "Runs everytime you leave a block, even when an exception
PRE { say "Asserts a precondition at every block entry,
before ENTER (especially useful for loops)" }
+# exemple:
+for 0..2 {
+ PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
+}
+
POST { say "Asserts a postcondition at every block exit,
after LEAVE (especially useful for loops)" }
+for 0..2 {
+ POST { $_ < 2 } # This is going to blow up with "Postcondition failed"
+}
## * Block/exceptions phasers
sub {
@@ -1239,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
# Group: you can group parts of your regexp with `[]`.
# These groups are *not* captured (like PCRE's `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
-so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
+so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
# The previous line returns `True`.
-# We match the "ABC" 1 or more time (the `+` was applied to the group).
+# We match the "012" 1 or more time (the `+` was applied to the group).
# But this does not go far enough, because we can't actually get back what
# we matched.
# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
+so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
# So, starting with the grouping explanations.
# As we said before, our `Match` object is available as `$/`:
diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown
index ade1d7ca..023c3e6b 100644
--- a/pl-pl/python-pl.html.markdown
+++ b/pl-pl/python-pl.html.markdown
@@ -30,7 +30,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
# Pojedyncze komentarze oznaczamy takim symbolem.
""" Wielolinijkowe napisy zapisywane są przy użyciu
- trzech znaków cudzysłowiu i często
+ potrójnych cudzysłowów i często
wykorzystywane są jako komentarze.
"""
@@ -47,11 +47,11 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
10 * 2 # => 20
35 / 5 # => 7
-# Dzielenie może być kłopotliwe. Poniższe to dzielenie
+# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie
# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany.
5 / 2 # => 2
-# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
+# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych.
2.0 # To liczba zmiennoprzecinkowa, tzw. float
11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej
@@ -65,7 +65,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron
# Operator modulo - wyznaczanie reszty z dzielenia
7 % 3 # => 1
-# Potęgowanie (x do potęgi ytej)
+# Potęgowanie (x do potęgi y-tej)
2**4 # => 16
# Wymuszanie pierwszeństwa w nawiasach
@@ -83,7 +83,7 @@ False or True #=> True # Prawda
2 == True #=> False
k1 == True #=> True
-# aby zanegować użyj "not"
+# aby zanegować, użyj "not"
not True # => False
not False # => True
@@ -112,7 +112,7 @@ not False # => True
# Napisy można dodawać!
"Witaj " + "świecie!" # => "Witaj świecie!"
-# ... a nawet mnożone
+# ... a nawet mnożyć
"Hej" * 3 # => "HejHejHej"
# Napis może być traktowany jako lista znaków
@@ -124,7 +124,7 @@ not False # => True
# Jednak nowszym sposobem formatowania jest metoda "format".
# Ta metoda jest obecnie polecana:
"{0} są {1}".format("napisy", "fajne")
-# Jeśli nie chce ci się liczyć użyj słów kluczowych.
+# Jeśli nie chce ci się liczyć, użyj słów kluczowych.
"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron")
# None jest obiektem
@@ -135,12 +135,12 @@ None # => None
"etc" is None # => False
None is None # => True
-# Operator 'is' testuje identyczność obiektów. To nie jest zbyt
+# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt
# pożyteczne, gdy działamy tylko na prostych wartościach,
# ale przydaje się, gdy mamy do czynienia z obiektami.
-# None, 0, i pusty napis "" są odpowiednikami logicznego False.
-# Wszystkie inne wartości są True
+# None, 0 i pusty napis "" są odpowiednikami logicznego False.
+# Wszystkie inne wartości są uznawane za prawdę (True)
bool(0) # => False
bool("") # => False
@@ -149,20 +149,20 @@ bool("") # => False
## 2. Zmienne i zbiory danych
####################################################
-# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale
-# zostało usunięte z wersji 3.
-print "Jestem Python. Miło poznać!"
-# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3...
+# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale
+# została ona usunięta z wersji 3.
+print "Jestem Python. Miło Cię poznać!"
+# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3...
# ale w 2.7 musisz dodać import (odkomentuj):
# from __future__ import print_function
print("Ja też jestem Python! ")
# Nie trzeba deklarować zmiennych przed przypisaniem.
-jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _
+jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _
jakas_zmienna # => 5
# Próba dostępu do niezadeklarowanej zmiennej da błąd.
-# Przejdź do sekcji Obsługa wyjątków po więcej...
+# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej...
inna_zmienna # Wyrzuca nazwę błędu
# "if" może być użyte jako wyrażenie
@@ -173,7 +173,7 @@ li = []
# Możesz zacząć od wypełnionej listy
inna_li = [4, 5, 6]
-# Dodaj na koniec używając "append"
+# Dodaj na koniec, używając "append"
li.append(1) # li to teraz [1]
li.append(2) # li to teraz [1, 2]
li.append(4) # li to teraz [1, 2, 4]
@@ -185,7 +185,7 @@ li.append(3) # li to znowu [1, 2, 4, 3].
# Dostęp do list jak do każdej tablicy
li[0] # => 1
-# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście
+# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku =
li[0] = 42
li[0] # => 42
li[0] = 1 # Uwaga: ustawiamy starą wartość
@@ -195,7 +195,7 @@ li[-1] # => 3
# Jeżeli wyjdziesz poza zakres...
li[4] # ... zobaczysz IndexError
-# Możesz tworzyć wyniki.
+# Możesz też tworzyć wycinki.
li[1:3] # => [2, 4]
# Bez początku
li[2:] # => [4, 3]
@@ -213,12 +213,12 @@ del li[2] # li to teraz [1, 2, 3]
# Listy można dodawać
li + inna_li # => [1, 2, 3, 4, 5, 6]
-# Uwaga: wartości poszczególnych list się nie zmieniają.
+# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają.
# Do łączenia list użyj "extend()"
li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6]
-# Sprawdź czy jest w liście używając "in"
+# Sprawdź, czy element jest w liście używając "in"
1 in li # => True
# "len()" pokazuje długość listy
@@ -238,7 +238,7 @@ tup[:2] # => (1, 2)
# Można rozpakować krotki i listy do poszczególych zmiennych
a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3
-# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki
+# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki
d, e, f = 4, 5, 6
# Popatrz jak prosto zamienić wartości
e, d = d, e # d to teraz 5 a e to 4
@@ -252,28 +252,28 @@ pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3}
# Podglądany wartość
pelen_slownik["one"] # => 1
-# Wypisz wszystkie klucze używając "keys()"
+# Wypisz wszystkie klucze, używając "keys()"
pelen_slownik.keys() # => ["trzy", "dwa", "raz"]
-# Uwaga: słowniki nie gwarantują kolejności występowania kluczy.
+# Uwaga: słowniki nie zapamiętują kolejności kluczy.
# A teraz wszystkie wartości "values()"
pelen_slownik.values() # => [3, 2, 1]
# Uwaga: to samo dotyczy wartości.
-# Sprawdzanie czy występuje to "in"
+# Sprawdzanie czy klucz występuje w słowniku za pomocą "in"
"raz" in pelen_slownik # => True
1 in pelen_slownik # => False
# Próba dobrania się do nieistniejącego klucza da KeyError
pelen_slownik["cztery"] # KeyError
-# Użyj "get()" method aby uniknąć KeyError
+# Użyj metody "get()", aby uniknąć błędu KeyError
pelen_slownik.get("raz") # => 1
pelen_slownik.get("cztery") # => None
# Metoda get zwraca domyślną wartość gdy brakuje klucza
pelen_slownik.get("one", 4) # => 1
pelen_slownik.get("cztery", 4) # => 4
-# zauważ, że pelen_slownik.get("cztery") jest wciąż => None
+# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None
# (get nie ustawia wartości słownika)
# przypisz wartość do klucza podobnie jak w listach
@@ -284,12 +284,12 @@ pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5
pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5
-# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń)
+# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń
pusty_zbior = set()
# Inicjalizujemy "set()" pewnymi wartościami
jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4])
-# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane
+# kolejność nie jest zachowana, nawet gdy wydaje się posortowane
inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4])
# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru
@@ -298,7 +298,7 @@ pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Dodaj więcej elementów przez "add()"
pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5}
-# Znajdź przecięcie zbiorów używając &
+# Znajdź przecięcie (część wspólną) zbiorów, używając &
inny_zbior = {3, 4, 5, 6}
pelen_zbior & other_set # => {3, 4, 5}
@@ -317,32 +317,32 @@ pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6}
## 3. Kontrola przepływu
####################################################
-# Tworzymy zmienną some_var
-some_var = 5
+# Tworzymy zmienną jakas_zm
+jakas_zm = 5
-# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie!
-# wypisze "some_var jest mniejsza niż 10"
-if some_var > 10:
- print("some_var jest wieksza niż 10")
-elif some_var < 10: # This elif clause is optional.
- print("some_var jest mniejsza niż 10")
-else: # This is optional too.
- print("some_var jest równa 10")
+# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne!
+# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10"
+if jakas_zm > 10:
+ print("jakas_zm jest wieksza niż 10")
+elif some_var < 10: # Opcjonalna klauzula elif
+ print("jakas_zm jest mniejsza niż 10")
+else: # Również opcjonalna klauzula else
+ print("jakas_zm jest równa 10")
"""
-Pętla for iteruje po elementach listy wypisując:
+Pętla for iteruje po elementach listy, wypisując:
pies to ssak
kot to ssak
mysz to ssak
"""
for zwierze in ["pies", "kot", "mysz"]:
- # Możesz użyć % aby stworzyć sformatowane napisy
- print("%s to ssak" % zwierze)
+ # Użyj metody format, aby umieścić wartość zmiennej w ciągu
+ print("{0} to ssak".format(zwierze))
"""
"range(liczba)" zwraca listę liczb
-od zera do danej liczby:
+z przedziału od zera do wskazanej liczby (bez niej):
0
1
2
@@ -352,7 +352,7 @@ for i in range(4):
print(i)
"""
-While to pętla która jest wykonywana dopóki spełniony jest warunek:
+While to pętla, która jest wykonywana, dopóki spełniony jest warunek:
0
1
2
@@ -363,46 +363,46 @@ while x < 4:
print(x)
x += 1 # Skrót od x = x + 1
-# Wyjątki wyłapujemy używając try, except
+# Wyjątki wyłapujemy, używając try i except
# Działa w Pythonie 2.6 i wyższych:
try:
- # Użyj "raise" aby wyrzucić wyjąte
+ # Użyj "raise" aby wyrzucić wyjątek
raise IndexError("To błąd indeksu")
except IndexError as e:
- pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki.
+ pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu.
except (TypeError, NameError):
- pass # kilka wyjątków może być przechwyce razem.
+ pass # kilka wyjątków można przechwycić jednocześnie.
else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu
print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku.
####################################################
-## 4. Funkcjie
+## 4. Funkcje
####################################################
-# Użyj "def" aby stworzyć nową funkcję
+# Użyj "def", aby stworzyć nową funkcję
def dodaj(x, y):
- print("x to %s a y to %s" % (x, y))
- return x + y # słówko kluczowe return zwraca wynik działania
+ print("x to %s, a y to %s" % (x, y))
+ return x + y # słowo kluczowe return zwraca wynik działania
-# Tak wywołuje się funkcję z parametrami (args):
-dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11
+# Tak wywołuje się funkcję z parametrami:
+dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11
# Innym sposobem jest wywołanie z parametrami nazwanymi.
dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia.
-# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
-# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz *
+# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych,
+# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args"
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
-# Można też stworzyć funkcję, które przyjmują różną ilość parametrów
-# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz **
+# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów
+# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs"
def keyword_args(**kwargs):
return kwargs
@@ -410,12 +410,12 @@ def keyword_args(**kwargs):
keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"}
-# Możesz też to pomieszać
+# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)
"""
-all_the_args(1, 2, a=3, b=4) wyrzuci:
+all_the_args(1, 2, a=3, b=4) wypisze:
(1, 2)
{"a": 3, "b": 4}
"""
@@ -435,7 +435,7 @@ def pass_all_the_args(*args, **kwargs):
print varargs(*args)
print keyword_args(**kwargs)
-# Zakres widoczności
+# Zasięg zmiennych
x = 5
def setX(num):
@@ -461,14 +461,14 @@ def rob_dodawacz(x):
dodaj_10 = rob_dodawacz(10)
dodaj_10(3) # => 13
-# Są również funkcje nienazwane "lambda"
+# Są również funkcje anonimowe "lambda"
(lambda x: x > 2)(3) # => True
-# Są także wbudowane funkcje wysokiego poziomu
+# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr)
map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter)
+# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania
[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]
@@ -485,18 +485,18 @@ class Czlowiek(object):
# Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji.
# Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają
- # obietky lub atrybuty, który żyją tylko w kontrolowanej przez
- # użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach.
+ # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona.
+ # Nie używaj ich we własnych metodach.
def __init__(self, nazwa):
# przypisz parametr "nazwa" do atrybutu instancji
self.nazwa = nazwa
- # Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument
+ # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument
def mow(self, wiadomosc):
return "%s: %s" % (self.nazwa, wiadomosc)
# Metoda klasowa współdzielona przez instancje.
- # Ma wywołującą klasę jako pierwszy argument.
+ # Przyjmuje wywołującą klasę jako pierwszy argument.
@classmethod
def daj_gatunek(cls):
return cls.gatunek
@@ -540,7 +540,8 @@ print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
# Można zaimportować wszystkie funkcje z danego modułu.
-# Ostrzeżenie: nie jest to polecane.
+# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się,
+# która funkcja pochodzi z którego modułu.
from math import *
# Można skracać nazwy modułów.
@@ -550,7 +551,7 @@ math.sqrt(16) == m.sqrt(16) # => True
from math import sqrt
math.sqrt == m.sqrt == sqrt # => True
-# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz
+# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz
# pisać własne i importować je. Nazwa modułu to nazwa pliku.
# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu.
@@ -568,14 +569,16 @@ def podwojne_liczby(iterowalne):
yield i + i
# Generatory tworzą wartości w locie.
-# W przeciwienstwie do wygenerowania wartości raz i ich zachowania,
-# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości
-# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby".
+# Zamiast generować wartości raz i zapisywać je (np. w liście),
+# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza,
+# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone
+# w funkcji "podwojne_liczby".
# Zauważ, że xrange to generator, który wykonuje tę samą operację co range.
# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci,
-# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range.
-# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego
-# Pythona.
+# a xrange tworzy obiekt generatora zamiast budować całą listę jak range.
+
+# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy
+# zwykle na końcu znaku podkreślenia
xrange_ = xrange(1, 900000000)
# poniższa pętla będzie podwajać liczby aż do 30
@@ -587,7 +590,7 @@ for i in podwojne_liczby(xrange_):
# Dekoratory
# w tym przykładzie "beg" jest nakładką na "say"
-# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość
+# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość
# zostanie zmieniona
from functools import wraps
diff --git a/pl-pl/ruby-pl.html.markdown b/pl-pl/ruby-pl.html.markdown
new file mode 100644
index 00000000..73b1a7d8
--- /dev/null
+++ b/pl-pl/ruby-pl.html.markdown
@@ -0,0 +1,593 @@
+---
+language: ruby
+filename: learnruby.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+translators:
+ - ["Marcin Klocek", "https://github.com/mklocek"]
+lang: pl-pl
+---
+
+```ruby
+# To jest komentarz
+
+=begin
+To jest wielolinijkowy komentarz
+Nikt ich nie używa
+Ty też nie powinieneś
+=end
+
+# Przede wszystkim: Wszystko jest obiektem.
+
+# Liczby są obiektami
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Trochę podstawowej arytmetyki
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+5 % 3 #=> 2
+5 ^ 6 #=> 3
+
+# Arytmetyka jest zastąpeniem składni
+# metod wywoływanych na obiektach
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Wartości specjalne są obiektami
+nil # To na prawdę jest niczym
+true # prawda
+false # fałsz
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Równość
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Nierówność
+1 != 1 #=> false
+2 != 1 #=> true
+
+# jedyną 'fałszywą' wartością poza false, jest nil
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Więcej porównań
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Operatory logiczne
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# Istnieją alternatywne wersje operatorów logicznych ze znacznie mniejszym
+# pierwszeństwem. Używane są by kontrolować wyrażenia w łańcuchach wyrażeń
+# aż jedno z nich wróci true lub false.
+
+# `zrob_cos_innego` wywołaj tylko wtedy gdy `zrob_cos` zakończy się sukcesem.
+zrob_cos_innego() and zrob_cos()
+# `log_error` wywołaj tylko wtedy gdy `zrob_cos` nie zakończy się sukcesem.
+zrob_cos() or log_error()
+
+
+# Stringi są obiektami
+
+'Jestem stringiem.'.class #=> String
+"Ja również jestem stringiem.".class #=> String
+
+wypelnienie = 'użyć interpolacji stringa'
+"Potrafię #{wypelnienie} używając podwójnych cudzysłowów."
+#=> "Potrafię użyć interpolacji stringa używając podwójnych cudzysłowów."
+
+# Staraj się zapisywać stringi za pomocą apostrof, zamiast cudzysłowów tam, gdzie to możliwe
+# Cudzysłowy wykonują dodatkowe wewnętrzne operacje
+
+
+# Łączenie stringów, ale nie liczb
+'hej ' + 'świecie' #=> "hej świecie"
+'hej ' + 3 #=> TypeError: can't convert Fixnum into String
+'hej ' + 3.to_s #=> "hej 3"
+
+# Łączenie stringów i operatorów
+'hej ' * 3 #=> "hej hej hej "
+
+# Dodawanie do stringa
+'hej' << ' świecie' #=> "hej świecie"
+
+# wydrukowanie wartości wraz z nową linią na końcu
+puts "Drukuję!"
+#=> Drukuję!
+#=> nil
+
+# wydrukowanie wartości bez nowej linii na końcu
+print "Drukuję!"
+#=> Drukuję! => nill
+
+# Zmienne
+x = 25 #=> 25
+x #=> 25
+
+# Zauważ, że przypisanie zwraca przypisywaną wartość
+# To znaczy, że możesz wykonać wielokrotne przypisanie:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Zwyczajowo, używaj notacji nazwa_zmiennej dla nazw zmiennych
+nazwa_zmiennej = true
+
+# Używaj opisowych nazw zmiennych
+sciezka_do_projektu = '/dobra/nazwa/'
+sciezka = '/zla/nazwa/'
+
+# Symbole (są obiektami)
+# Symbole są niezmiennymi, wielokrotnie używanymi stałymi reprezentowanymi wewnętrznie jako
+# liczby całkowite. Często używane są zamiast stringów w celu wydajniejszego przekazywania danych
+
+:oczekujacy.class #=> Symbol
+
+status = :oczekujacy
+
+status == :oczekujacy #=> true
+
+status == 'oczekujacy' #=> false
+
+status == :zatwierdzony #=> false
+
+# Tablice
+
+# To jest tablica
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Tablice mogą zwierać różne typy danych
+
+[1, 'hej', false] #=> [1, "hej", false]
+
+# Tablice mogę być indeksowane
+# Od początku
+tablica[0] #=> 1
+tablica.first #=> 1
+tablica[12] #=> nil
+
+# Podobnie jak przy arytmetyce, dostęp poprzez [zmienna]
+# jest tylko czytelniejszą składnią
+# dla wywoływania metody [] na obiekcie
+tablica.[] 0 #=> 1
+tablica.[] 12 #=> nil
+
+# Od końca
+tablica[-1] #=> 5
+tablica.last #=> 5
+
+# Z początkowym indeksem i długością
+tablica[2, 3] #=> [3, 4, 5]
+
+# Odwrotność tablicy
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Lub zakres
+array[1..3] #=> [2, 3, 4]
+
+# Dodawanie do tablicy w taki sposób
+tablica << 6 #=> [1, 2, 3, 4, 5, 6]
+# Lub taki
+tablica.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Sprawdzanie, czy tablica zawiera element
+tablica.include?(1) #=> true
+
+# Hasze są Ruby'owymi podstawowymi słownikami z parami klucz/wartość.
+# Hasze są zapisywane za pomocą nawiasów klamrowych
+hasz = { 'kolor' => 'zielony', 'numer' => 5 }
+
+hasz.keys #=> ['kolor', 'numer']
+
+# Można szybko sprawdzić zawartość hasza za pomocą kluczy:
+hasz['kolor'] #=> 'zielony'
+hasz['numer'] #=> 5
+
+# Sprawdzenie wartośći dla nieistniejącego klucza zwraca nil:
+hasz['nic tutaj nie ma'] #=> nil
+
+# Od wersji 1.9, Ruby posiada specjalną składnię, gdy używamy symboli jako kluczy:
+
+nowy_hasz = { stan: 3, akcja: true }
+
+nowy_hasz.keys #=> [:stan, :akcja]
+
+# Sprawdzenie istnienia kluczy i wartości w haszu
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
+# Wskazówka: Zarówno tablice, jak i hasze, są policzalne
+# Współdzielą wiele metod takich jak each, map, count, i inne
+
+# Instrukcje warunkowe
+
+if true
+ 'wyrażenie if'
+elsif false
+ 'wyrażenie if, opcjonalne'
+else
+ 'wyrażenie else, również opcjonalne'
+end
+
+for licznik in 1..5
+ puts "powtórzenie #{licznik}"
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# JEDNAKŻE, Nikt nie używa pętli for.
+# Zamiast tego, powinno się używać metody "each" i podawać jej blok.
+# Blok jest kawałkiem kodu, który możesz podać metodzie podobnej do "each".
+# Jest analogiczny do wyrażeń lambda, funkcji anonimowych lub zamknięć w innych
+# językach programowania.
+#
+# Metoda "each" danego zakresu, wykonuje blok dla każdego elementu w zakresie.
+# Do bloku zostaje przekazany licznik jako parametr.
+# Wykonanie metody "each" z przekazaniem bloku wygląda następująco:
+
+(1..5).each do |licznik|
+ puts "powtórzenie #{licznik}"
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# Możesz również otoczyć blok nawiasami klamrowymi:
+(1..5).each { |licznik| puts "powtórzenie #{licznik}" }
+
+# Zawartość struktur danych również może być powtarzana używając each.
+tablica.each do |element|
+ puts "#{element} jest częścią tablicy"
+end
+hasz.each do |klucz, wartosc|
+ puts "#{klucz} jest #{wartosc}"
+end
+
+# Jeśli nadal potrzebujesz indeksum, możesz użyć "each_with_index" i zdefiniować
+# zmienną odpowiadającą indeksowi
+tablica.each_with_index do |element, indeks|
+ puts "#{element} jest numerem #{indeks} w tablicy"
+end
+
+licznik = 1
+while licznik <= 5 do
+ puts "powtórzenie #{licznik}"
+ licznik += 1
+end
+#=> powtórzenie 1
+#=> powtórzenie 2
+#=> powtórzenie 3
+#=> powtórzenie 4
+#=> powtórzenie 5
+
+# W Ruby istnieje dużo pomocnych funkcji wykonujących pętle,
+# na przykład "map", "reduce", "inject" i wiele innych. Map,
+# w każdym wywołaniu, pobiera tablicę, na której wykonuję pętlę,
+# wykonuje kod zapisany za pomocą bloku i zwraca całkowicie nową tablicę.
+tablica = [1,2,3,4,5]
+podwojone = tablica.map do |element|
+ element * 2
+end
+puts podwojona
+#=> [2,4,6,8,10]
+puts tablica
+#=> [1,2,3,4,5]
+
+ocena = 2
+
+case ocena
+when 1
+ puts 'Dobra robota, masz wolne'
+when 2
+ puts 'Następnym razem będziesz miał więcej szczęścia'
+when 3
+ puts 'Możesz to zrobić lepiej'
+when 4
+ puts 'Przebrnąłeś'
+when 5
+ puts 'Oblałeś!'
+else
+ puts 'Inny system oceniania?'
+end
+#=> "Następnym razem będziesz miał więcej szczęścia"
+
+# case może również użwać zakresów
+ocena = 82
+case ocena
+when 90..100
+ puts 'Hurra!'
+when 80...90
+ puts 'Dobra robota'
+else
+ puts 'Oblałeś!'
+end
+#=> "Dobra robota"
+
+# obsługa błędów:
+begin
+ # kod, który może wywołać wyjątek
+ raise NoMemoryError, 'Zabrakło pamięci.'
+rescue NoMemoryError => zmienna_wyjatku
+ puts 'Został wywołany NoMemoryError', zmienna_wyjatku
+rescue RuntimeError => inna_zmienna_wyjatku
+ puts 'Teraz został wywołany RuntimeError'
+else
+ puts 'To zostanie uruchomione, jeśli nie wystąpi żaden wyjątek'
+ensure
+ puts 'Ten kod wykona się zawsze'
+end
+
+# Funkcje
+
+def podwojenie(x)
+ x * 2
+end
+
+# Funkcje (i wszystkie bloki) zawsze zwracają wartość ostatniego wyrażenia
+podwojenie(2) #=> 4
+
+# Okrągłe nawiady są opcjonalne, gdy wynik jest jednoznaczny
+podwojenie 3 #=> 6
+
+podwojenie podwojenie 3 #=> 12
+
+def suma(x, y)
+ x + y
+end
+
+# Argumenty metod są oddzielone przecinkami
+suma 3, 4 #=> 7
+
+suma suma(3, 4), 5 #=> 12
+
+# yield
+# Wszystkie metody mają ukryty, opcjonalny parametr bloku,
+# który może być wykonany używając słowa kluczowego 'yield'
+
+def otoczenie
+ puts '{'
+ yield
+ puts '}'
+end
+
+otoczenie { puts 'hej świecie' }
+
+# {
+# hej świecie
+# }
+
+
+# Możesz przekazać blok do funkcji
+# "&" oznacza referencję to przekazanego bloku
+def goscie(&blok)
+ blok.call 'jakis_argument'
+end
+
+# Możesz przekazać listę argumentów, które będę przekonwertowane na tablicę
+# Do tego służy operator ("*")
+def goscie(*tablica)
+ tablica.each { |gosc| puts gosc }
+end
+
+# Definiowanie klas używając słowa kluczowego class
+class Czlowiek
+
+ # Zmienna klasowa. Jest współdzielona przez wszystkie instancje tej klasy.
+ @@gatunek = 'H. sapiens'
+
+ # Podstawowe inicjalizowanie
+ def initialize(imie, wiek = 0)
+ # Przypisanie argumentu do zmiennej danej instancji o nazwie "imie"
+ @imie = imie
+ # Jeśli nie podano wieku, zostanie użyta domyślna wartość z listy argumentów.
+ @wiek = wiek
+ end
+
+ # Podstawowa metoda przypisująca wartość
+ def imie=(imie)
+ @imie = imie
+ end
+
+ # Podstawowa metoda pobierająca wartość
+ def imie
+ @imie
+ end
+
+ # Powyższa funkcjonalność może być zastąpiona używając metody attr_accessor w taki sposób
+ attr_accessor :imie
+
+ # Metody przypisujące/pobierające mogą być stworzone indywidualnie
+ attr_reader :imie
+ attr_writer :imie
+
+ # Metody klasowe używają self aby odróżnić się od metody instancji.
+ # To może być wywołane na klasie, nie na instancji.
+ def self.powiedz(wiadomosc)
+ puts wiadomosc
+ end
+
+ def gatunek
+ @@gatunek
+ end
+end
+
+
+# Tworzenie instancji klasy
+jim = Czlowiek.new('Jim Halpert')
+
+dwight = Czlowiek.new('Dwight K. Schrute')
+
+# Wywołajmy parę metod
+jim.gatunek #=> "H. sapiens"
+jim.imie #=> "Jim Halpert"
+jim.imie = "Jim Halpert II" #=> "Jim Halpert II"
+jim.imie #=> "Jim Halpert II"
+dwight.gatunek #=> "H. sapiens"
+dwight.imie #=> "Dwight K. Schrute"
+
+# Wywołanie metody klasowej
+Czlowiek.powiedz('Cześć') #=> "Cześć"
+
+# Zasięg zmiennej jest definiowany poprzez jej nazwę.
+# Zmienne, które zaczynają się na $ mają zasięg globalny
+$zmienna = "Jestem zmienną globalną"
+defined? $zmienna #=> "global-variable"
+
+# Zmienne zczynające się na @ mają zasięg danej instancji
+@zmienna = "Jestem zmienną instancji"
+defined? @zmienna #=> "instance-variable"
+
+# Zmienne, które zaczynają się na @@ mają zasięg danej klasy
+@@zmienna = "Jestem zmienną klasową"
+defined? @@zmienna #=> "class variable"
+
+# Zmienne, które zaczynają się na dużą literę, są stałymi
+Zmienna = "Jestem stałą"
+defined? Zmienna #=> "constant"
+
+# Klasa jest również obiektem w ruby. Może więc mieć zmienne instancji.
+# Zmienna klasowa może być współdzielona między klasą i jej potomstwem.
+
+# podstawowa klasa
+class Czlowiek
+ @@cokolwiek = 0
+
+ def self.cokolwiek
+ @@cokolwiek
+ end
+
+ def self.cokolwiek=(wartosc)
+ @@cokolwiek = wartosc
+ end
+end
+
+# klasa pochodna
+class Pracownik < Czlowiek
+end
+
+Czlowiek.cokolwiek # 0
+Pracownik.cokolwiek # 0
+
+Czlowiek.cokolwiek = 2 # 2
+Pracownik.cokolwiek # 2
+
+# Zmienna instancji danej klasy nie jest współdzielona przez jej potomstwo.
+
+class Czlowiek
+ @cos = 0
+
+ def self.cos
+ @cos
+ end
+
+ def self.cos=(wartosc)
+ @cos = wartosc
+ end
+end
+
+class Doktor < Czlowiek
+end
+
+Czlowiek.cos # 0
+Doktor.cos # nil
+
+module PrzykladowyModul
+ def cokolwiek
+ 'cokolwiek'
+ end
+end
+
+# Włączanie modułów łączy ich metody z metodami instancji klasy
+# Rozszerzanie modułów łączy ich metody z metodami klasy
+
+class Osoba
+ include PrzykladowyModul
+end
+
+class Ksiazka
+ extend PrzykladowyModul
+end
+
+Osoba.cokolwiek # => NoMethodError: undefined method `cokolwiek' for Osoba:Class
+Osoba.new.cokolwiek # => 'cokolwiek'
+Ksiazka.cokolwiek # => 'cokolwiek'
+Ksiazka.new.cokolwiek # => NoMethodError: undefined method `cokolwiek'
+
+# Gdy włączamy lub rozszerzamy muduły, wykonywane są tzw. wywołania zwrotne
+
+module PrzykladowyModul
+ def self.included(baza)
+ baza.extend(MotodyKlasowe)
+ baza.send(:include, MetodyInstancji)
+ end
+
+ module MotodyKlasowe
+ def cos
+ 'cos'
+ end
+ end
+
+ module MetodyInstancji
+ def xyz
+ 'xyz'
+ end
+ end
+end
+
+class Cokolwiek
+ include PrzykladowyModul
+end
+
+Cokolwiek.cos # => 'cos'
+Cokolwiek.xyz # => NoMethodError: undefined method `xyz'
+Cokolwiek.new.cos # => NoMethodError: undefined method `cos'
+Cokolwiek.new.xyz # => 'qux'
+```
+
+## Dodatkowe źródła
+### Polskie
+
+- [Dokumentacja](https://www.ruby-lang.org/pl/documentation/quickstart/)
+
+### Angielskie
+
+- [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/)
+- [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.
diff --git a/powershell.html.markdown b/powershell.html.markdown
new file mode 100644
index 00000000..4bc1ab39
--- /dev/null
+++ b/powershell.html.markdown
@@ -0,0 +1,320 @@
+---
+category: tool
+tool: powershell
+contributors:
+ - ["Wouter Van Schandevijl", "https://github.com/laoujin"]
+filename: LearnPowershell.ps1
+---
+
+PowerShell is the Windows scripting language and configuration management
+framework from Microsoft built on the .NET Framework. Windows 7 and up ship
+with PowerShell.
+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.
+
+[Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx)
+
+If you are uncertain about your environment:
+```
+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
+```
+
+Getting help:
+```
+# 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
+
+Show-Command Get-EventLog # Display GUI to fill in the parameters
+
+Update-Help # Run as admin
+```
+
+The tutorial starts here:
+```
+# 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
+$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'
+}
+
+# Switch statements are more powerfull compared to most languages
+$val = "20"
+switch($val) {
+ { $_ -eq 42 } { "The answer equals 42"; break }
+ '20' { "Exactly 20"; break }
+ { $_ -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"
+}
+# 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
+}
+
+
+### 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
+
+# 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
+
+# ` 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
+
+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" }
+
+# 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
+
+
+### Functions
+# The [string] attribute is optional.
+function foo([string]$name) {
+ echo "Hey $name, have a function"
+}
+
+# Calling your function
+foo "Say my name"
+
+# Functions with named parameters, parameter attributes, parsable documention
+<#
+.SYNOPSIS
+Setup a new website
+.DESCRIPTION
+Creates everything your new website needs for much win
+.PARAMETER siteName
+The name for the new website
+.EXAMPLE
+New-Website -Name FancySite -Po 5000
+New-Website SiteWithDefaultPort
+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' }
+}
+
+
+### 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
+$writer = New-Object System.IO.StreamWriter($path, $true)
+$writer.Write([Environment]::NewLine)
+$write.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
+
+# 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()
+```
+
+
+Configuring your shell
+```
+# $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
+}
+# More info: `help about_profiles`
+# For a more usefull shell, be sure to check the project PSReadLine below
+```
+
+Interesting Projects
+* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials
+* [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!)
+* [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](http://pscx.codeplex.com/) (Dead)
+
+Not covered
+* WMI: Windows Management Intrumentation (Get-CimInstance)
+* Multitasking: Start-Job -scriptBlock {...},
+* Code Signing
+* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 406042fa..6424214e 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -436,7 +436,6 @@ var myPrototype = {
myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42
-// This works for functions, too.
// Isto funciona para funções, também.
myObj.myFunc(); // = "olá mundo!"
@@ -506,7 +505,7 @@ String.prototype.firstCharacter = function(){
// Havíamos mencionado que `Object.create` não estava ainda disponível em
// todos as implementações, mas nós podemos usá-lo com esse polyfill:
-if (Object.create === undefined){ // don't overwrite it if it exists
+if (Object.create === undefined){ // Não o sobrescreve se já existir
Object.create = function(proto){
// faz um construtor temporário com o prototype certo
var Constructor = function(){};
diff --git a/python.html.markdown b/python.html.markdown
index 2b43c5fc..d8f18e9b 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -124,7 +124,7 @@ not False # => True
"This is a string"[0] # => 'T'
#String formatting with %
-#Even though the % string operator will be deprecated on Python 3.1 and removed
+#Even though the % string operator will be deprecated on Python 3.1 and removed
#later at some time, it may still be good to know how it works.
x = 'apple'
y = 'lemon'
@@ -458,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
-# positional args, which will be interpreted as a tuple if you do not use the *
+# positional args, which will be interpreted as a tuple by using *
def varargs(*args):
return args
@@ -466,7 +466,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
-# keyword args, as well, which will be interpreted as a dict if you do not use **
+# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
return kwargs
diff --git a/python3.html.markdown b/python3.html.markdown
index 2398e7ac..8cc03320 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -224,8 +224,8 @@ li.remove(2) # Raises a ValueError as 2 is not in the list
# Insert an element at a specific index
li.insert(1, 2) # li is now [1, 2, 3] again
-# Get the index of the first item found
-li.index(2) # => 3
+# Get the index of the first item found matching the argument
+li.index(2) # => 1
li.index(4) # Raises a ValueError as 4 is not in the list
# You can add lists
@@ -425,7 +425,6 @@ by step. If step is not indicated, the default value is 1.
prints:
4
6
- 8
"""
for i in range(4, 8, 2):
print(i)
@@ -689,7 +688,7 @@ i.age # => raises an AttributeError
# You can import modules
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# You can get specific functions from a module
from math import ceil, floor
diff --git a/ru-ru/.directory b/ru-ru/.directory
new file mode 100644
index 00000000..4d20336b
--- /dev/null
+++ b/ru-ru/.directory
@@ -0,0 +1,4 @@
+[Dolphin]
+SortRole=size
+Timestamp=2015,10,31,18,6,13
+Version=3
diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown
index 21377b6c..5e99afc2 100644
--- a/ru-ru/bash-ru.html.markdown
+++ b/ru-ru/bash-ru.html.markdown
@@ -95,6 +95,15 @@ else
echo "Имя совпадает с именем пользователя"
fi
+# Примечание: если $Name пустой, bash интерпретирует код как:
+if [ -ne $USER ]
+# а это ошибочная команда
+# поэтому такие переменные нужно использовать так:
+if [ "$Name" -ne $USER ] ...
+# когда $Name пустой, bash видит код как:
+if [ "" -ne $USER ] ...
+# что работает правильно
+
# Также есть условное исполнение
echo "Исполнится всегда" || echo "Исполнится, если первая команда завершится ошибкой"
echo "Исполнится всегда" && echo "Исполнится, если первая команда выполнится удачно"
diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown
new file mode 100644
index 00000000..8f4233fd
--- /dev/null
+++ b/ru-ru/d-ru.html.markdown
@@ -0,0 +1,753 @@
+---
+language: d
+filename: learnd-ru.d
+contributors:
+ - ["Anton Pastukhov", "http://dprogramming.ru/"]
+ - ["Robert Brights-Gray", "http://lhs-blog.info/"]
+ - ["Andre Polykanine", "http://oire.me/"]
+lang: ru-ru
+---
+D - современный компилируемый язык общего назначения с Си-подобным синтаксисом,
+который сочетает удобство, продуманный дизайн и высокую производительность.
+D - это С++, сделанный правильно.
+
+```d
+// Welcome to D! Это однострочный комментарий
+
+/* многострочный
+ комментарий */
+
+/+
+ // вложенные комментарии
+
+ /* еще вложенные
+ комментарии */
+
+ /+
+ // мало уровней вложенности? Их может быть сколько угодно.
+ +/
++/
+
+/*
+ Имя модуля. Каждый файл с исходным кодом на D — модуль.
+ Если имя не указано явно, то предполагается, что оно совпадает с именем
+ файла. Например, для файла "test.d" имя модуля будет "test", если явно
+ не указать другое
+ */
+module app;
+
+// импорт модуля. Std — пространство имен стандартной библиотеки (Phobos)
+import std.stdio;
+
+// можно импортировать только нужные части, не обязательно модуль целиком
+import std.exception : enforce;
+
+// точка входа в программу — функция main, аналогично C/C++
+void main()
+{
+ writeln("Hello, world!");
+}
+
+
+
+/*** типы и переменные ***/
+
+int a; // объявление переменной типа int (32 бита)
+float b = 12.34; // тип с плавающей точкой
+double c = 56.78; // тип с плавающей точкой (64 бита)
+
+/*
+ Численные типы в D, за исключением типов с плавающей точкой и типов
+ комплексных чисел, могут быть беззнаковыми.
+ В этом случае название типа начинается с префикса "u"
+*/
+uint d = 10; ulong e = 11;
+bool b = true; // логический тип
+char d = 'd'; // UTF-символ, 8 бит. D поддерживает UTF "из коробки"
+wchar e = 'é'; // символ UTF-16
+dchar f; // и даже UTF-32, если он вам зачем-то понадобится
+
+string s = "для строк есть отдельный тип, это не просто массив char-ов из Си";
+wstring ws = "поскольку у нас есть wchar, должен быть и wstring";
+dstring ds = "...и dstring, конечно";
+
+string кириллица = "Имена переменных должны быть в Unicode, но не обязательно на латинице.";
+
+typeof(a) b = 6; // typeof возвращает тип своего выражения.
+ // В результате, b имеет такой же тип, как и a
+
+// Тип переменной, помеченной ключевым словом auto,
+// присваивается компилятором исходя из значения этой переменной
+auto x = 1; // Например, тип этой переменной будет int.
+auto y = 1.1; // этой — double
+auto z = "Zed is dead!"; // а этой — string
+
+int[3] arr = [1, 2, 3]; // простой одномерный массив с фиксированным размером
+int[] arr2 = [1, 2, 3, 4]; // динамический массив
+int[string] aa = ["key1": 5, "key2": 6]; // ассоциативный массив
+
+/*
+ Строки и массивы в D — встроенные типы. Для их использования не нужно
+ подключать ни внешние, ни даже стандартную библиотеку, хотя в последней
+ есть множество дополнительных инструментов для работы с ними.
+ */
+immutable int ia = 10; // неизменяемый тип,
+ // обозначается ключевым словом immutable
+ia += 1; // — вызовет ошибку на этапе компиляции
+
+// перечислимый (enumerable) тип,
+// более правильный способ работы с константами в D
+enum myConsts = { Const1, Const2, Const3 };
+
+// свойства типов
+writeln("Имя типа : ", int.stringof); // int
+writeln("Размер в байтах : ", int.sizeof); // 4
+writeln("Минимальное значение : ", int.min); // -2147483648
+writeln("Максимальное значение : ", int.max); // 2147483647
+writeln("Начальное значение : ", int.init); // 0. Это значение,
+ // присвоенное по умолчанию
+
+// На самом деле типов в D больше, но все мы здесь описывать не будем,
+// иначе не уложимся в Y минут.
+
+
+
+/*** Приведение типов ***/
+
+// to!(имя типа)(выражение) - для большинства конверсий
+import std.conv : to; // функция "to" - часть стандартной библиотеки, а не языка
+double d = -1.75;
+short s = to!short(d); // s = -1
+
+/*
+ cast - если вы знаете, что делаете. Кроме того, это единственный способ
+ преобразования типов-указателей в "обычные" и наоборот
+*/
+void* v;
+int* p = cast(int*)v;
+
+// Для собственного удобства можно создавать псевдонимы
+// для различных встроенных объектов
+alias int newInt; // теперь можно обращаться к newInt так, как будто бы это int
+newInt a = 5;
+
+alias newInt = int; // так тоже допустимо
+alias uint[2] pair; // дать псевдоним можно даже сложным структурам данных
+
+
+
+/*** Операторы ***/
+
+int x = 10; // присваивание
+x = x + 1; // 11
+x -= 2; // 9
+x++; // 10
+++x; // 11
+x *= 2; // 22
+x /= 2; // 11
+x = x ^^ 2; // 121 (возведение в степень)
+x ^^= 2; // 1331 (то же самое)
+
+string str1 = "Hello";
+string str2 = ", world!";
+string hw = str1 ~ str2; // Конкатенация строк
+
+int[] arr = [1, 2, 3];
+arr ~= 4; // [1, 2, 3, 4] - добавление элемента в конец массива
+
+
+
+/*** Логика и сравнения ***/
+
+int x = 0; int y = 1;
+
+x == y; // false
+x > y; // false
+x < y; // true
+x >= y; // false
+x != y; // true. ! — логическое "не"
+x > 0 || x < 1; // true. || — логическое "или"
+x > 0 && x < 1; // false && — логическое "и"
+x ^ y // true; ^ - xor (исключающее "или")
+
+// Тернарный оператор
+auto y = (x > 10) ? 1 : 0; // если x больше 10, то y равен 1,
+ // в противном случае y равен нулю
+
+
+/*** Управляющие конструкции ***/
+
+// if - абсолютно привычен
+if (a == 1) {
+ // ..
+} else if (a == 2) {
+ // ..
+} else {
+ // ..
+}
+
+// switch
+switch (a) {
+ case 1:
+ // делаем что-нибудь
+ break;
+ case 2:
+ // делаем что-нибудь другое
+ break;
+ case 3:
+ // делаем что-нибудь еще
+ break;
+ default:
+ // default обязателен, без него будет ошибка компиляции
+ break;
+}
+
+// в D есть констукция "final switch". Она не может содержать секцию "defaul"
+// и применяется, когда все перечисляемые в switch варианты должны быть
+// обработаны явным образом
+
+int dieValue = 1;
+final switch (dieValue) {
+ case 1:
+ writeln("You won");
+ break;
+
+ case 2, 3, 4, 5:
+ writeln("It's a draw");
+ break;
+
+ case 6:
+ writeln("I won");
+ break;
+}
+
+// while
+while (a > 10) {
+ // ..
+ if (number == 42) {
+ break;
+ }
+}
+
+while (true) {
+ // бесконечный цикл
+}
+
+// do-while
+do {
+ // ..
+} while (a == 10);
+
+// for
+for (int number = 1; number < 11; ++number) {
+ writeln(number); // все абсолютно стандартно
+}
+
+for ( ; ; ) {
+ // секции могут быть пустыми. Это бесконечный цикл в стиле Си
+}
+
+// foreach - универсальный и самый "правильный" цикл в D
+foreach (element; array) {
+ writeln(element); // для простых массивов
+}
+
+foreach (key, val; aa) {
+ writeln(key, ": ", val); // для ассоциативных массивов
+}
+
+foreach (c; "hello") {
+ writeln(c); // hello. Поскольку строки - это вариант массива,
+ // foreach применим и к ним
+}
+
+foreach (number; 10..15) {
+ writeln(number); // численные интервалы можно указывать явным образом
+ // этот цикл выведет значения с 10 по 14, но не 15,
+ // поскольку диапазон не включает в себя верхнюю границу
+}
+
+// foreach_reverse - в обратную сторону
+auto container = [1, 2, 3];
+foreach_reverse (element; container) {
+ writefln("%s ", element); // 3, 2, 1
+}
+
+// foreach в массивах и им подобных структурах не меняет сами структуры
+int[] a = [1, 2 ,3 ,4 ,5];
+foreach (elem; array) {
+ elem *= 2; // сам массив останется неизменным
+}
+
+writeln(a); // вывод: [1, 2, 3, 4, 5] Т.е изменений нет
+
+// добавление ref приведет к тому, что массив будет изменяться
+foreach (ref elem; array) {
+ elem *= 2;
+}
+
+writeln(a); // [2, 4, 6, 8, 10]
+
+// foreach умеет рассчитывать индексы элементов
+int[] a = [1, 2, 3, 4, 5];
+foreach (ind, elem; array) {
+ writeln(ind, " ", elem); // через ind - доступен индекс элемента,
+ // а через elem - сам элемент
+}
+
+
+
+/*** Функции ***/
+
+test(42); // Что, вот так сразу? Разве мы где-то уже объявили эту функцию?
+
+// Нет, вот она. Это не Си, здесь объявление функции не обязательно должно быть
+// до первого вызова
+int test(int argument) {
+ return argument * 2;
+}
+
+
+// В D используется единый синтаксис вызова функций
+// (UFCS, Uniform Function Call Syntax), поэтому так тоже можно:
+int var = 42.test();
+
+// и даже так, если у функции нет аргументов:
+int var2 = 42.test;
+
+// можно выстраивать цепочки:
+int var3 = 42.test.test;
+
+/*
+ Аргументы в функцию передаются по значению (т.е. функция работает не с
+ оригинальными значениями, переданными ей, а с их локальными копиями.
+ Исключение составляют объекты классов, которые передаются по ссылке.
+ Кроме того, любой параметр можно передать в функцию по ссылке с помощью
+ ключевого слова "ref"
+*/
+int var = 10;
+
+void fn1(int arg) {
+ arg += 1;
+}
+
+void fn2(ref int arg) {
+ arg += 1;
+}
+
+fn1(var); // var все еще = 10
+fn2(var); // теперь var = 11
+
+// Возвращаемое значение тоже может быть auto,
+// если его можно "угадать" из контекста
+auto add(int x, int y) {
+ return x + y;
+}
+
+auto z = add(x, y); // тип int - компилятор вывел его автоматически
+
+// Значения аргументов по умолчанию
+float linearFunction(float k, float x, float b = 1)
+{
+ return k * x + b;
+}
+
+auto linear1 = linearFunction(0.5, 2, 3); // все аргументы используются
+auto linear2 = linearFunction(0.5, 2); // один аргумент пропущен, но в функции
+ // он все равно использован и равен 1
+
+// допускается описание вложенных функций
+float quarter(float x) {
+ float doubled(float y) {
+ return y * y;
+ }
+
+ return doubled(doubled(x));
+}
+
+// функции с переменным числом аргументов
+int sum(int[] a...)
+{
+ int s = 0;
+ foreach (elem; a) {
+ s += elem;
+ }
+ return s;
+}
+
+auto sum1 = sum(1);
+auto sum2 = sum(1,2,3,4);
+
+/*
+ модификатор "in" перед аргументами функций говорит о том, что функция имеет
+ право их только просматривать. При попытке модификации такого аргумента
+ внутри функции - получите ошибку
+*/
+float printFloat(in float a)
+{
+ writeln(a);
+}
+printFloat(a); // использование таких функций - самое обычное
+
+// модификатор "out" позволяет вернуть из функции несколько результатов
+// без посредства глобальных переменных или массивов
+uint remMod(uint a, uint b, out uint modulus)
+{
+ uint remainder = a / b;
+ modulus = a % b;
+ return remainder;
+}
+
+uint modulus; // пока в этой переменной ноль
+uint rem = remMod(5, 2, modulus); // наша "хитрая" функция, и теперь
+ // в modulus - остаток от деления
+writeln(rem, " ", modulus); // вывод: 2 1
+
+
+
+/*** Структуры, классы, базовое ООП ***/
+
+// Объявление структуры. Структуры почти как в Си
+struct MyStruct {
+ int a;
+ float b;
+
+ void multiply() {
+ return a * b;
+ }
+}
+
+MyStruct str1; // Объявление переменной с типом MyStruct
+str1.a = 10; // Обращение к полю
+str1.b = 20;
+auto result = str1.multiply();
+MyStruct str2 = {4, 8} // Объявление + инициализация в стиле Си
+auto str3 = MyStruct(5, 10); // Объявление + инициализация в стиле D
+
+
+// области видимости полей и методов - 3 способа задания
+struct MyStruct2 {
+ public int a;
+
+ private:
+ float b;
+ bool c;
+
+ protected {
+ float multiply() {
+ return a * b;
+ }
+ }
+ /*
+ в дополнение к знакомым public, private и protected, в D есть еще
+ область видимости "package". Поля и методы с этим атрибутом будут
+ доступны изо всех модулей, включенных в "пакет" (package), но не
+ за его пределами. package - это "папка", в которой может храниться
+ несколько модулей. Например, в "import.std.stdio", "std" - это
+ package, в котором есть модуль stdio (и еще множество других)
+ */
+ package:
+ string d;
+
+ /* помимо этого, имеется еще один модификатор - export, который позволяет
+ использовать объявленный с ним идентификатор даже вне самой программы !
+ */
+ export:
+ string description;
+}
+
+// Конструкторы и деструкторы
+struct MyStruct3 {
+ this() { // конструктор. Для структур его не обязательно указывать явно,
+ // в этом случае пустой конструктор добавляется компилятором
+ writeln("Hello, world!");
+ }
+
+
+ // а вот это конструкция - одна из интересных идиом и представляет собой
+ // конструктор копирования, т.е конструктор, возвращающий копию структуры.
+ // Работает только в структурах.
+ this(this)
+ {
+ return this;
+ }
+
+ ~this() { // деструктор, также необязателен
+ writeln("Awww!");
+ }
+}
+
+// Объявление простейшего класса
+class MyClass {
+ int a; // в D по умолчанию данные-члены являются public
+ float b;
+}
+
+auto mc = new MyClass(); // ...и создание его экземпляра
+auto mc2 = new MyClass; // ... тоже сработает
+
+// Конструктор
+class MyClass2 {
+ int a;
+ float b;
+
+ this(int a, float b) {
+ this.a = a; // ключевое слово "this" - ссылка на объект класса
+ this.b = b;
+ }
+}
+
+auto mc2 = new MyClass2(1, 2.3);
+
+// Классы могут быть вложенными
+class Outer
+{
+ int m;
+
+ class Inner
+ {
+ int foo()
+ {
+ return m; // можно обращаться к полям "внешнего" класса
+ }
+ }
+}
+
+// наследование
+class Base {
+ int a = 1;
+ float b = 2.34;
+
+
+ // это статический метод, т.е метод который можно вызывать, обращаясь
+ // к классу напрямую, а не через создание экземпляра объекта
+ static void multiply(int x, int y)
+ {
+ writeln(x * y);
+ }
+}
+
+Base.multiply(2, 5); // используем статический метод. Результат: 10
+
+class Derived : Base {
+ string c = "Поле класса - наследника";
+
+
+ // override означает то, что наследник предоставит свою реализацию метода,
+ // переопределив метод базового класса
+ override static void multiply(int x, int y)
+ {
+ super.multiply(x, y); // super - это ссылка на класс-предок, или базовый класс
+ writeln(x * y * 2);
+ }
+}
+
+auto mc3 = new Derived();
+writeln(mc3.a); // 1
+writeln(mc3.b); // 2.34
+writeln(mc3.c); // Поле класса - наследника
+
+// Финальный класс, наследовать от него нельзя
+// кроме того, модификатор final работает не только для классов, но и для методов
+// и даже для модулей !
+final class FC {
+ int a;
+}
+
+class Derived : FC { // это вызовет ошибку
+ float b;
+}
+
+// Абстрактный класс не может быть истанциирован, но может иметь наследников
+abstract class AC {
+ int a;
+}
+
+auto ac = new AC(); // это вызовет ошибку
+
+class Implementation : AC {
+ float b;
+
+ // final перед методом нефинального класса означает запрет возможности
+ // переопределения метода
+ final void test()
+ {
+ writeln("test passed !");
+ }
+}
+
+auto impl = new Implementation(); // ОК
+
+
+
+/*** Примеси (mixins) ***/
+
+// В D можно вставлять код как строку, если эта строка известна на этапе
+// компиляции. Например:
+void main() {
+ mixin(`writeln("Hello World!");`);
+}
+
+// еще пример
+string print(string s) {
+ return `writeln("` ~ s ~ `");`;
+}
+
+void main() {
+ mixin (print("str1"));
+ mixin (print("str2"));
+}
+
+
+
+/*** Шаблоны ***/
+
+/*
+ Шаблон функции. Эта функция принимает аргументы разных типов, которые
+ подставляются вместо T на этапе компиляции. "T" - это не специальный
+ символ, а просто буква. Вместо "T" может быть любое слово, кроме ключевого.
+ */
+void print(T)(T value) {
+ writefln("%s", value);
+}
+
+void main() {
+ print(42); // В одну и ту же функцию передается: целое
+ print(1.2); // ...число с плавающей точкой,
+ print("test"); // ...строка
+}
+
+// "Шаблонных" параметров может быть сколько угодно
+void print(T1, T2)(T1 value1, T2 value2) {
+ writefln(" %s %s", value1, value2);
+}
+
+void main() {
+ print(42, "Test");
+ print(1.2, 33);
+}
+
+// Шаблон класса
+class Stack(T)
+{
+ private:
+ T[] elements;
+
+ public:
+ void push(T element) {
+ elements ~= element;
+ }
+
+ void pop() {
+ --elements.length;
+ }
+
+ T top() const @property {
+ return elements[$ - 1];
+ }
+
+ size_t length() const @property {
+ return elements.length;
+ }
+}
+
+void main() {
+ /*
+ восклицательный знак - признак шаблона. В данном случае мы создаем
+ класс и указываем, что "шаблонное" поле будет иметь тип string
+ */
+ auto stack = new Stack!string;
+
+ stack.push("Test1");
+ stack.push("Test2");
+
+ writeln(stack.top);
+ writeln(stack.length);
+
+ stack.pop;
+ writeln(stack.top);
+ writeln(stack.length);
+}
+
+
+
+/*** Диапазоны (ranges) ***/
+
+/*
+ Диапазоны - это абстракция, которая позволяет легко использовать разные
+ алгоритмы с разными структурами данных. Вместо того, чтобы определять свои
+ уникальные алгоритмы для каждой структуры, мы можем просто указать для нее
+ несколько единообразных функций, определяющих, _как_ мы получаем доступ
+ к элементам контейнера, вместо того, чтобы описывать внутреннее устройство
+ этого контейнера. Сложно? На самом деле не очень.
+
+ Простейший вид диапазона - Input Range. Для того, чтобы превратить любой
+ контейнер в Input Range, достаточно реализовать для него 3 метода:
+ - empty - проверяет, пуст ли контейнер
+ - front - дает доступ к первому элементу контейнера
+ - popFront - удаляет из контейнера первый элемент
+*/
+struct Student
+{
+ string name;
+ int number;
+ string toString() {
+ return format("%s(%s)", name, number);
+ }
+}
+
+struct School
+{
+ Student[] students;
+}
+
+struct StudentRange
+{
+ Student[] students;
+
+ this(School school) {
+ this.students = school.students;
+ }
+
+ bool empty() {
+ return students.length == 0;
+ }
+
+ Student front() {
+ return students[0];
+ }
+
+ void popFront() {
+ students = students[1 .. $];
+ }
+}
+
+void main(){
+ auto school = School([
+ Student("Mike", 1),
+ Student("John", 2) ,
+ Student("Dan", 3)
+ ]);
+ auto range = StudentRange(school);
+ writeln(range); // [Mike(1), John(2), Dan(3)]
+ writeln(school.students.length); // 3
+ writeln(range.front()); // Mike(1)
+ range.popFront();
+ writeln(range.empty()); // false
+ writeln(range); // [John(2), Dan(3)]
+}
+/*
+ Смысл в том, что нам не так уж важно внутреннее устройство контейнера, если
+ у нас есть унифицированные методы доступа к его элементам.
+ Кроме Input Range в D есть и другие типы диапазонов, которые требуют
+ реализации большего числа методов, зато дают больше контроля. Это большая
+ тема и мы не будем в подробностях освещать ее здесь.
+
+ Диапазоны - это важная часть D, они используются в нем повсеместно.
+*/
+```
+## Что дальше?
+
+- [Официальный сайт](http://dlang.org/)
+- [Онлайн-книга](http://ddili.org/ders/d.en/)
+- [Официальная вики](http://wiki.dlang.org/)
diff --git a/ru-ru/erlang-ru.html.markdown b/ru-ru/erlang-ru.html.markdown
index 99ea79ee..69f81800 100644
--- a/ru-ru/erlang-ru.html.markdown
+++ b/ru-ru/erlang-ru.html.markdown
@@ -18,7 +18,7 @@ lang: ru-ru
% Пунктуационные знаки, используемые в Erlang:
% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и
% образцах.
-% Точка (`.`) (с пробелом после них) разделяет функции и выражения в
+% Точка (`.`) (с пробелом после неё) разделяет функции и выражения в
% оболочке.
% Точка с запятой (`;`) разделяет выражения в следующих контекстах:
% формулы функций, выражения `case`, `if`, `try..catch` и `receive`.
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 8eac4ddb..d60db1d8 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -381,20 +381,21 @@ if ([myClass respondsToSelector:selectorVar]) { // Проверяет содер
NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar));
}
-// Имплементируйте методы в файле МойКласс.m:
+// Имплементируйте методы в файле MyClass.m:
@implementation MyClass {
long distance; // Переменная экземпляра с закрытым (private) доступом
NSNumber height;
}
-// To access a public variable from the interface file, use '_' followed by variable name:
-_count = 5; // References "int count" from MyClass interface
-// Access variables defined in implementation file:
-distance = 18; // References "long distance" from MyClass implementation
-// To use @property variable in implementation, use @synthesize to create accessor variable:
-@synthesize roString = _roString; // _roString available now in @implementation
+// Для доступа к public переменной, объявленной в интерфейсе, используйте '_' перед названием переменной:
+_count = 5; // Ссылается на "int count" из интерфейса MyClass
+// Получение доступа к переменной, объявленной в реализации происходит следующим образом:
+distance = 18; // Ссылается на "long distance" из реализации MyClass
+// Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property,
+// следует использовать @synthesize для создания переменной аксессора:
+@synthesize roString = _roString; // Теперь _roString доступна в @implementation (реализации интерфейса)
-// Called before calling any class methods or instantiating any objects
+// Вызывается в первую очередь, перед вызовом других медотов класса или инициализации других объектов
+ (void)initialize
{
if (self == [MyClass class]) {
@@ -505,10 +506,10 @@ distance = 18; // References "long distance" from MyClass implementation
@end
-// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет
-// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить
-// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим
-// категорию для добавления его очистительных методов:
+// Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что
+// изменит функционал Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить
+// определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
+// категорию, которая добавит несколько методов для чистки автомобиля в класс Car:
// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h)
#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения.
@@ -794,7 +795,7 @@ MyClass *arcMyClass = [[MyClass alloc] init];
// weakVar-свойство автоматически примет значение nil,
// во избежание падения приложения
@property (strong) MyClass *strongVar; // 'strong' принимает право на владение
-// объектом. Гарантирует, что объект останится в памяти для использования
+// объектом. Гарантирует, что объект останется в памяти для использования
// Для обычных переменных (не объявленных с помощью @property), используйте
// следующий способ:
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
new file mode 100644
index 00000000..a907ba41
--- /dev/null
+++ b/ru-ru/perl-ru.html.markdown
@@ -0,0 +1,195 @@
+---
+category: language
+language: perl
+filename: learnperl-ru.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+translators:
+ - ["Elena Bolshakova", "http://github.com/liruoko"]
+lang: ru-ru
+---
+
+Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
+
+Perl 5 работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
+
+```perl
+# Комментарии начинаются с символа решетки.
+
+
+#### Типы переменных в Perl
+
+# Скалярные переменные начинаются с знака доллара $.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
+
+### В Perl три основных типа переменных: скаляры, массивы, хеши.
+
+## Скаляры
+# Скаляр хранит отдельное значение:
+my $animal = "camel";
+my $answer = 42;
+
+# Скаляры могут быть строками, целыми и вещественными числами.
+# Когда требуется, Perl автоматически выполняет преобразования к нужному типу.
+
+## Массивы
+# Массив хранит список значений:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+
+## Хеши
+# Хеш хранит набор пар ключ/значение:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# Можно использовать оператор "=>" для большей наглядности:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+ );
+
+# Важно: вставка и поиск в хеше выполняются за константное время,
+# независимо от его размера.
+
+# Скаляры, массивы и хеши подробно описаны в разделе perldata
+# (perldoc perldata).
+
+# Более сложные структуры данных можно получить, если использовать ссылки.
+# С помощью ссылок можно получить массив массивов хешей, в которых хранятся другие хеши.
+
+#### Условные операторы и циклы
+
+# В 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 ) {
+ ...
+ }
+
+
+# for, foreach
+for ($i = 0; $i <= $max; $i++) {
+ ...
+ }
+
+foreach (@array) {
+ print "This element is $_\n";
+ }
+
+for my $el (@array) {
+ print "This element is $el\n";
+ }
+
+#### Регулярные выражения
+
+# Регулярные выражения занимают важное место в Perl-е,
+# и подробно описаны в разделах документации perlrequick, perlretut и других.
+# Вкратце:
+
+# Сопоставление с образцом
+if (/foo/) { ... } # выполняется, если $_ содержит "foo"
+if ($a =~ /foo/) { ... } # выполняется, если $a содержит "foo"
+
+# Простые замены
+
+$a =~ s/foo/bar/; # заменяет foo на bar в строке $a
+$a =~ s/foo/bar/g; # заменяет ВСЕ ВХОЖДЕНИЯ foo на bar в строке $a
+
+
+#### Файлы и ввод-вывод
+
+# Открыть файл на чтение или запись можно с помощью функции "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>;
+
+#### Подпрограммы (функции)
+
+# Объявить функцию просто:
+
+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-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
+поставку Perl.
+
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
+задачах, и часто предлагает подходящие CPAN-модули.
+
+
+#### Unicode
+
+Вам наверняка понадобится работать с не-ASCII текстами.
+Добавьте эти прагмы в начало скрипта:
+
+```perl
+use utf8;
+use open ':std' => ':utf8';
+```
+
+Подробнее читайте в perldoc, разделы perlunicode и open.
+
+
+#### strict, warnings
+
+Прагмы strict и warnings включают полезные проверки во время компиляции:
+
+```perl
+use strict;
+use warnings;
+```
+
+Подробнее смотрите perldoc strict и perldoc warnings.
+
+
+#### Смотрите также
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [обучающий раздел на www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc в вебе](http://perldoc.perl.org/)
+ - встроенная справка : `perldoc perlintro`
diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown
index 2a7b3f7b..2b6b59a7 100644
--- a/ru-ru/python3-ru.html.markdown
+++ b/ru-ru/python3-ru.html.markdown
@@ -549,7 +549,7 @@ Human.grunt() #=> "*grunt*"
# Вы можете импортировать модули
import math
-print(math.sqrt(16)) #=> 4
+print(math.sqrt(16)) #=> 4.0
# Вы можете импортировать отдельные функции модуля
from math import ceil, floor
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 8720fec6..b7f8b4a1 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -14,6 +14,7 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gabriel Halley", "https://github.com/ghalley"]
- ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
---
```ruby
@@ -53,7 +54,7 @@ You shouldn't either
10.* 5 #=> 50
# Special values are objects
-nil # Nothing to see here
+nil # equivalent to null in other languages
true # truth
false # falsehood
@@ -131,7 +132,7 @@ puts "I'm printing!"
# print to the output without a newline
print "I'm printing!"
-#=> I'm printing! => nill
+#=> I'm printing! => nil
# Variables
x = 25 #=> 25
@@ -229,8 +230,8 @@ new_hash = { defcon: 3, action: true }
new_hash.keys #=> [:defcon, :action]
# Check existence of keys and values in hash
-new_hash.has_key?(:defcon) #=> true
-new_hash.has_value?(3) #=> true
+new_hash.key?(:defcon) #=> true
+new_hash.value?(3) #=> true
# Tip: Both Arrays and Hashes are Enumerable
# They share a lot of useful methods such as each, map, count, and more
@@ -588,6 +589,7 @@ Something.new.qux # => 'qux'
## Additional resources
- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials.
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
- [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.
diff --git a/sass.html.markdown b/sass.html.markdown
index 02bec47f..4d4ece71 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -4,40 +4,41 @@ filename: learnsass.scss
contributors:
- ["Laura Kyle", "https://github.com/LauraNK"]
- ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Kyle Mendes", "https://github.com/pink401k"]
---
-Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
-Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
+Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
+Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers write maintainable and DRY (Don't Repeat Yourself) code.
-Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
+Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
This tutorial is written using SCSS.
-If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier.
+If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling properties but rather the tools to write your CSS more efficiently and make maintenance much easier.
```scss
-
+
//Single line comments are removed when Sass is compiled to CSS.
-/*Multi line comments are preserved. */
-
-
-
-/*Variables
-==============================*/
-
-
+/* Multi line comments are preserved. */
+
+
+
+/* Variables
+============================== */
+
+
/* You can store a CSS value (such as a color) in a variable.
Use the '$' symbol to create a variable. */
-
+
$primary-color: #A3A4FF;
$secondary-color: #51527F;
-$body-font: 'Roboto', sans-serif;
+$body-font: 'Roboto', sans-serif;
+
+/* You can use the variables throughout your stylesheet.
+Now if you want to change a color, you only have to make the change once. */
-/* You can use the variables throughout your stylesheet.
-Now if you want to change a color, you only have to make the change once.*/
-
body {
background-color: $primary-color;
color: $secondary-color;
@@ -54,18 +55,18 @@ body {
/* This is much more maintainable than having to change the color
each time it appears throughout your stylesheet. */
-
-/*Mixins
-==============================*/
+
+/* Mixins
+============================== */
/* If you find you are writing the same code for more than one
element, you might want to store that code in a mixin.
-Use the '@mixin' directive, plus a name for your mixin.*/
+Use the '@mixin' directive, plus a name for your mixin. */
@mixin center {
display: block;
@@ -82,7 +83,7 @@ div {
background-color: $primary-color;
}
-/*Which would compile to: */
+/* Which would compile to: */
div {
display: block;
margin-left: auto;
@@ -99,8 +100,8 @@ div {
width: $width;
height: $height;
}
-
-/*Which you can invoke by passing width and height arguments. */
+
+/* Which you can invoke by passing width and height arguments. */
.rectangle {
@include size(100px, 60px);
@@ -110,31 +111,31 @@ div {
@include size(40px, 40px);
}
-/* This compiles to: */
+/* Compiles to: */
.rectangle {
width: 100px;
- height: 60px;
+ height: 60px;
}
.square {
width: 40px;
- height: 40px;
+ height: 40px;
}
-/*Functions
-==============================*/
-
-
-
-/* Sass provides functions that can be used to accomplish a variety of
+/* Functions
+============================== */
+
+
+
+/* Sass provides functions that can be used to accomplish a variety of
tasks. Consider the following */
-/* Functions can be invoked by using their name and passing in the
+/* Functions can be invoked by using their name and passing in the
required arguments */
body {
- width: round(10.25px);
+ width: round(10.25px);
}
.footer {
@@ -149,18 +150,18 @@ body {
.footer {
background-color: rgba(0, 0, 0, 0.75);
-}
-
-/* You may also define your own functions. Functions are very similar to
+}
+
+/* You may also define your own functions. Functions are very similar to
mixins. When trying to choose between a function or a mixin, remember
- that mixins are best for generating CSS while functions are better for
- logic that might be used throughout your Sass code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Sass code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
function. */
-/* This function will take a target size and the parent size and calculate
+/* This function will take a target size and the parent size and calculate
and return the percentage */
-
+
@function calculate-percentage($target-size, $parent-size) {
@return $target-size / $parent-size * 100%;
}
@@ -187,12 +188,12 @@ $main-content: calculate-percentage(600px, 960px);
-/*Extend (Inheritance)
-==============================*/
+/* Extend (Inheritance)
+============================== */
-/*Extend is a way to share the properties of one selector with another. */
+/* Extend is a way to share the properties of one selector with another. */
.display {
@include size(5em, 5em);
@@ -208,36 +209,36 @@ $main-content: calculate-percentage(600px, 960px);
.display, .display-success {
width: 5em;
height: 5em;
- border: 5px solid #51527F;
+ border: 5px solid #51527F;
}
.display-success {
- border-color: #22df56;
+ border-color: #22df56;
}
-/* Extending a CSS statement is preferable to creating a mixin
- because of the way it groups together the classes that all share
- the same base styling. If this was done with a mixin, the width,
- height, and border would be duplicated for each statement that
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way Sass groups together the classes that all share
+ the same base styling. If this was done with a mixin, the width,
+ height, and border would be duplicated for each statement that
called the mixin. While it won't affect your workflow, it will
add unnecessary bloat to the files created by the Sass compiler. */
-
-/*Nesting
-==============================*/
+
+/* Nesting
+============================== */
-/*Sass allows you to nest selectors within selectors */
+/* Sass allows you to nest selectors within selectors */
ul {
list-style-type: none;
margin-top: 2em;
-
+
li {
- background-color: #FF0000;
- }
+ background-color: #FF0000;
+ }
}
/* '&' will be replaced by the parent selector. */
@@ -249,18 +250,18 @@ For example: */
ul {
list-style-type: none;
margin-top: 2em;
-
+
li {
background-color: red;
-
+
&:hover {
background-color: blue;
}
-
+
a {
color: white;
}
- }
+ }
}
/* Compiles to: */
@@ -284,17 +285,17 @@ ul li a {
-/*Partials and Imports
-==============================*/
-
-
-
+/* Partials and Imports
+============================== */
+
+
+
/* Sass allows you to create partial files. This can help keep your Sass
code modularized. Partial files should begin with an '_', e.g. _reset.css.
Partials are not generated into CSS. */
-
+
/* Consider the following CSS which we'll put in a file called _reset.css */
-
+
html,
body,
ul,
@@ -302,14 +303,14 @@ ol {
margin: 0;
padding: 0;
}
-
+
/* Sass offers @import which can be used to import partials into a file.
- This differs from the traditional CSS @import statement which makes
- another HTTP request to fetch the imported file. Sass takes the
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Sass takes the
imported file and combines it with the compiled code. */
-
+
@import 'reset';
-
+
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
@@ -320,25 +321,25 @@ body {
html, body, ul, ol {
margin: 0;
padding: 0;
-}
+}
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
-
-
-/*Placeholder Selectors
-==============================*/
-
-
-
+
+
+/* Placeholder Selectors
+============================== */
+
+
+
/* Placeholders are useful when creating a CSS statement to extend. If you
wanted to create a CSS statement that was exclusively used with @extend,
you can do so using a placeholder. Placeholders begin with a '%' instead
of '.' or '#'. Placeholders will not appear in the compiled CSS. */
-
+
%content-window {
font-size: 14px;
padding: 10px;
@@ -364,18 +365,18 @@ body {
background-color: #0000ff;
}
-
-
-/*Math Operations
-==============================*/
-
-
-
+
+
+/* Math Operations
+============================== */
+
+
+
/* Sass provides the following operators: +, -, *, /, and %. These can
be useful for calculating values directly in your Sass files instead
of using values that you've already calculated by hand. Below is an example
of a setting up a simple two column design. */
-
+
$content-area: 960px;
$main-content: 600px;
$sidebar-content: 300px;
@@ -418,14 +419,11 @@ body {
width: 6.25%;
}
-
-```
-
-
+```
## SASS or Sass?
-Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym.
-Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets".
+Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym.
+Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets".
## Practice Sass
@@ -434,14 +432,13 @@ You can use either syntax, just go into the settings and select either Sass or S
## Compatibility
-
Sass can be used in any project as long as you have a program to compile it
into CSS. You'll want to verify that the CSS you're using is compatible
-with your target browsers.
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
-[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
-
## Further reading
* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles.
diff --git a/scala.html.markdown b/scala.html.markdown
index 4ba9a31b..a82983a5 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -169,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
// Syntax for calling functions is familiar:
sumOfSquares(3, 4) // => 25
+// You can use parameters names to specify them in different order
+def subtract(x: Int, y: Int): Int = x - y
+
+subtract(10, 3) // => 7
+subtract(y=10, x=3) // => -7
+
// In most cases (with recursive functions the most notable exception), function
// return type can be omitted, and the same type inference we saw with variables
// will work with function return values:
@@ -460,6 +466,9 @@ def matchEverything(obj: Any): String = obj match {
// You can nest patterns:
case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
+
+ // Match any case (default) if all previous haven't matched
+ case _ => "Got unknown object"
}
// In fact, you can pattern match any object with an "unapply" method. This
diff --git a/sk-sk/LearnGit-sk.txt b/sk-sk/LearnGit-sk.txt
new file mode 100644
index 00000000..070a0489
--- /dev/null
+++ b/sk-sk/LearnGit-sk.txt
@@ -0,0 +1,208 @@
+$ git init
+
+# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
+$ git config --global user.email "MôjEmail@Zoho.com"
+$ git config --global user.name "Moje Meno
+
+# Rýchlo zobraz všetky dostupné príkazy
+$ git help
+
+# Zobraz všetky dostupné príkazy
+$ git help -a
+
+# Zobraz konkrétnu pomoc - použivateľský manuál
+# git help <príkaz_tu>
+$ git help add
+$ git help commit
+$ git help init
+# alebo git <príkaz_tu> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+
+# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
+$ git status
+# Zistí iné vychytávky o git statuse
+$ git help status
+
+# pridá súbor z tvojho pracovného adresára
+$ git add HelloWorld.java
+
+# pridá súbor z iného adresára
+$ git add /cesta/k/súboru/HelloWorld.c
+
+# Môžeš použiť regulárne výrazy!
+$ git add ./*.java
+
+# zobraz existujúce vetvy a vzdialené repozitáre
+$ git branch -a
+
+# vytvor novú vetvu
+$ git branch myNewBranch
+
+# vymaž vetvu
+$ git branch -d myBranch
+
+# premenuj vetvu
+# git branch -m <starémeno> <novémeno>
+$ git branch -m mojaStaraVetva mojaNovaVetva
+
+# zmeň opis vetvy
+$ git branch myBranchName --edit-description
+
+# Zobrazí tagy
+$ git tag
+# Vytvorí tag so správou
+# -m špecifikuje správu, ktorá bude s tagom uložená.
+# Ak nešpeficikuješ správu pri tagu so správou,
+# Git spustí tvoj editor, aby si ju napísal.
+$ git tag -a v2.0 -m 'moja verzia 2.0'
+
+# Ukáž informácie o tagu
+# Zobrazí zadané informácie, dátum tagnutia commitu
+# a správu pred zobrazením informácií o commite.
+$ git show v2.0
+
+# Zverejní (pushne) jediný tag do vzdialeného repozitára
+$ git push origin v2.0
+
+# Zverejní viacero tagov do vzdialeného repozitára
+$ git push origin --tags
+
+# Aktualizuj strom, aby odpovedal (predvolene)
+# hlavnej vetve repozitáru (master branch)
+$ git checkout
+
+# Aktualizuj strom, aby odpovedal konrkétnej vetve
+$ git checkout menoVetvy
+
+# Vytvor novú vetvu & prepni sa na ňu
+# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
+$ git checkout -b nováVetva
+
+# Naklonuj learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+
+# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+
+# naklonuj iba konkrétnu vetvu
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
+
+# commitni so správou
+$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
+
+# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
+$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
+
+# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
+$ git commit --amend -m "Správna správa"
+
+# Ukáž rozdiel medzi pracovným repozitárom a indexom.
+$ git diff
+
+# Ukáž rozdiely medzi indexom a najnovším commitom.
+$ git diff --cached
+
+# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
+$ git diff HEAD
+
+# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
+$ git config --global grep.lineNumber true
+
+# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
+$ git config --global alias.g "grep --break --heading --line-number"
+
+# Vďaka Travisovi Jefferymu za túto sekciu
+# Hľadaj "názovPremennej" vo všetkých java súboroch
+$ git grep 'názovPremennej' -- '*.java'
+
+# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+
+# Zobraz všetky commity
+$ git log
+
+# Zobraz iba správy a referencie commitov
+$ git log --oneline
+
+# Zobraz zlúčené (merged) commity
+$ git log --merges
+
+# Zobraz všetky commity vo forme ASCII grafu
+$ git log --graph
+
+# Zlúč vybranú vetvu do aktuálnej.
+$ git merge názovVetvy
+
+# Vždy vytvor zlučovací commit
+$ git merge --no-ff názovVetvy
+
+# Premenuj súbor
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Presuň súbor
+$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
+
+# "Nasilu" premenuj, alebo presuň
+# "existujúciSúbor" už v adresári existuje, bude prepísaný
+$ git mv -f môjSúbor existujúciSúbor
+
+# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
+# zo vzdialených "origin" a "master" vetiev.
+# git pull <alias-vzdialeného-repo> <vetva>
+$ git pull origin master
+
+# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
+# zlúčením nových zmien zo vzdialenej vetvy
+$ git pull
+
+# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
+# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
+$ git pull origin master --rebase
+
+# Zverejni a zlúč zmeny z lokálneho repozitára do
+# vzdialených vetiev s názvom "origin" a "master".
+# git push <vzdialené> <vetvy>
+$ git push origin master
+
+# Predvolene git zverejní a zlúči zmeny z
+# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
+$ git push
+
+# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
+$ git push -u origin master
+# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
+$ git push
+
+# Aplikuj commity z experimentálnej vetvy na master
+# git rebase <základnáVetva> <ináVetva>
+$ git rebase master experimentBranch
+
+# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
+$ git reset
+
+# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
+$ git reset --hard
+
+# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
+# všetky zmeny sú zachované v adresári.
+$ git reset 31f2bb1
+
+# Vezmi späť konkrétny commit
+$ git revert <commit>
+
+# odstráň HelloWorld.c
+$ git rm HelloWorld.c
+
+# Odstráň súbor z vnoreného adresára
+$ git rm /pather/to/the/file/HelloWorld.c
+
+
+
+
+
+
+
+
+
diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown
new file mode 100644
index 00000000..21741406
--- /dev/null
+++ b/sk-sk/git.html.markdown
@@ -0,0 +1,523 @@
+---
+category: tool
+tool: git
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Leo Rudberg" , "http://github.com/LOZORD"]
+ - ["Betsy Lorton" , "http://github.com/schbetsy"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
+ - ["Andrew Taylor", "http://github.com/andrewjt71"]
+translators:
+ - ["Terka Slanináková", "http://github.com/TerkaSlan"]
+lang: sk-sk
+filename: LearnGit-sk.txt
+---
+
+Git je distribuovaný systém riadenia revízií a správy zdrojového kódu.
+
+Funguje robením "snímkov" tvojho projektu, s ktorými ďalej pracuje na revíziach a správe zdrojových kódov.
+
+## Koncept Revízií
+
+### Čo je riadenie revízií?
+
+Riadenie revízií je systém, ktorý postupom času zaznamenáva zmeny súboru (súborov).
+
+### Centralizované Revízie VS Distribuované revízie
+
+* Centralizované riadenie revízií sa zameriava na synchronizáciu, sledovanie a zálohovanie súborov.
+* Distribuované riadenie revízií sa zameriava na zdieľanie zmien. Kaťdá zmena má jedinečný identifikátor (id).
+* Distribuované systémy nemajú definovanú štruktúru. S gitom môžeš mať centralizovaný systém v subversion (SVN) štýle.
+
+[Ďalšie informácie](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
+
+### Prečo Používať Git?
+
+* Môžeš pracovať offline.
+* Spolupráca s ostatnými je jednoduchá!
+* Vetvenie je jednoduché!
+* Zlučovanie je jednoduché!
+* Git je rýchly.
+* Git je flexibilný.
+
+## Architektúra Gitu
+
+
+### Repozitár
+
+Skupina súborov, adresárov, minulých záznamov, commitov (konkrétnych revízií) a odkazy na aktuálu vetvu (HEADs). Predstav si ho ako údajovú štruktúru, kde ti každý "prvok" zdrojového kódu poskytne (okrem iného) prístup k minulým revíziam.
+
+Git repozitár sa skladá z .git adresára a pracovného stromu
+
+### .git Adresár (časť repozitára)
+
+.git adresár obsahuje všetky konfigurácie, logy, vetvy, odkaz na aktuálnu vetvu (HEAD) a ostatné.
+[Detailný zoznam.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Pracovný Strom (Working Tree - časť repozitára)
+
+Toto sú adresáre a súbory v tvojom repozitári. Tiež sa tomu hovorí pracovný adresár.
+
+### Index (časť .git adresára)
+
+Index je také odpočívadlo Gitu. Je to v podstate vrstva, ktorá oddeľuje pracovný strom od Git repozitára. Toto dáva vývojárom viac možností nad tým, čo do repozitára naozaj pošlú.
+
+### Commit
+
+Commit je "snímka" zmien, či manipulácií s tvojím Pracovným Stromom. Ak si napríklad pridal 5 súborov a odstránil 2 ďalšie, tieto zmeny budú zachytené v commite. Ten môže (ale nemusí) byť zverejnený (pushed) do iných repozitárov.
+
+### Vetva (Branch)
+
+Vetva je ukazateľ na posledný vykonaný commit. Po ďalších commitnutiach sa ukazateľ bude automaticky posúvať na ten najnovší.
+
+### Tag
+
+Tag je označenie špecifického bodu v minulosti. Typicky sa používa na značenie vydaných verzií (v1.0, atď).
+
+### HEAD a head (časť .git adresára)
+
+HEAD je ukazateľ na aktuálnu vetvu. Repozitár má len 1 *aktívny* HEAD.
+head je ukazateľ, ktorý môže ukazovať na akýkoľvek commit. Repozitár môže mať niekoľko headov.
+
+### Štádia Gitu
+* Modified - Súbor bol zmenený, no nebol ešte commitnutý do Git Databázy.
+* Staged - Zmenený súbor, ktorý pôjde do najbližšieho commit snímku.
+* Committed - Súbory boli commitnuté do Git Databázy.
+
+### Koncepčné zdroje
+
+* [Git Pre Informatikov](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git Pre Designerov](http://hoth.entp.com/output/git_for_designers.html)
+
+
+## Príkazy
+
+
+### init
+
+Vytvorí prázdny Git repozitár. Jeho nastavenia, uložené informácie a mnoho iného sú uložené v adresári (zložke) s názvom ".git".
+
+```bash
+$ git init
+```
+
+### config
+
+Konfiguruj nastavenia. Či už pre repozitár, samotný systém, alebo globálne konfigurácie (súbor pre globálny config je `~/.gitconfig`).
+
+
+```bash
+# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne)
+$ git config --global user.email "MôjEmail@Zoho.com"
+$ git config --global user.name "Moje Meno "
+```
+
+[Prečítaj si viac o git configu.](http://git-scm.com/docs/git-config)
+
+### pomoc
+
+Máš tiež prístup k extrémne detailnej dokumentácií pre každý príkaz (po anglicky). Hodí sa, ak potrebuješ pripomenúť semantiku.
+
+```bash
+# Rýchlo zobraz všetky dostupné príkazy
+$ git help
+
+# Zobraz všetky dostupné príkazy
+$ git help -a
+
+# Zobraz konkrétnu pomoc - použivateľský manuál
+# git help <príkaz_tu>
+$ git help add
+$ git help commit
+$ git help init
+# alebo git <príkaz_tu> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+```
+
+### ignoruj súbory
+
+Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári.
+```bash
+$ echo "temp/" >> .gitignore
+$ echo "private_key" >> .gitignore
+```
+
+
+### status
+
+Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a aktuálnym HEAD commitom.
+
+
+```bash
+# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely
+$ git status
+
+# Zistí iné vychytávky o git statuse
+$ git help status
+```
+
+### add
+
+Pripraví súbory na commit pridaním do tzv. staging indexu. Ak ich nepridáš pomocou `git add` do staging indexu, nebudú zahrnuté v commitoch!
+
+```bash
+# pridá súbor z tvojho pracovného adresára
+$ git add HelloWorld.java
+
+# pridá súbor z iného adresára
+$ git add /cesta/k/súboru/HelloWorld.c
+
+# Môžeš použiť regulárne výrazy!
+$ git add ./*.java
+```
+Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára.
+
+### branch
+
+Spravuj svoje vetvy. Môžeš ich pomocou tohto príkazu zobraziť, meniť, vytvoriť, či zmazať.
+
+```bash
+# zobraz existujúce vetvy a vzdialené repozitáre
+$ git branch -a
+
+# vytvor novú vetvu
+$ git branch myNewBranch
+
+# vymaž vetvu
+$ git branch -d myBranch
+
+# premenuj vetvu
+# git branch -m <starémeno> <novémeno>
+$ git branch -m mojaStaraVetva mojaNovaVetva
+
+# zmeň opis vetvy
+$ git branch myBranchName --edit-description
+```
+
+### tag
+
+Spravuj svoje tagy
+
+```bash
+# Zobraz tagy
+$ git tag
+# Vytvor tag so správou
+# -m špecifikuje správu, ktorá bude s tagom uložená.
+# Ak nešpeficikuješ správu pri tagu so správou,
+# Git spustí tvoj editor, aby si ju napísal.
+$ git tag -a v2.0 -m 'moja verzia 2.0'
+# Ukáž informácie o tagu
+# Zobrazí zadané informácie, dátum tagnutia commitu
+# a správu pred zobrazením informácií o commite.
+$ git show v2.0
+# Zverejní (pushne) jediný tag do vzdialeného repozitára
+$ git push origin v2.0
+# Zverejní viacero tagov do vzdialeného repozitára
+$ git push origin --tags
+```
+
+### checkout
+
+Aktualizuje všetky súbory v pracovnom strome, aby odpovedali verzií v indexe, alebo v inom strome.
+
+```bash
+# Aktualizuj strom, aby odpovedal (predvolene)
+# hlavnej vetve repozitáru (master branch)
+$ git checkout
+# Aktualizuj strom, aby odpovedal konrkétnej vetve
+$ git checkout menoVetvy
+# Vytvor novú vetvu & prepni sa na ňu
+# ekvivalentný príkaz: "git branch <meno>; git checkout <meno>"
+$ git checkout -b nováVetva
+```
+
+### clone
+
+"Naklonuje", alebo vytvorí kópiu existujúceho repozitára do nového adresára. Tiež pridá špeciálne ďiaľkovo-monitorujúce vetvy (remote-tracking branches), ktoré ti umožnia zverejňovať do vzdialených vetiev.
+
+```bash
+# Naklonuj learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+# naklonuj iba konkrétnu vetvu
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
+```
+
+### commit
+
+Uloží aktuálny obsah indexu v novom "commite". Ten obsahuje vytvorené zmeny a s nimi súvisiace správy vytvorené použivateľom.
+
+```bash
+# commitni so správou
+$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c"
+
+# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni.
+$ git commit -a -m "Zmenil som foo.php a vymazal bar.php"
+
+# zmeň posledný commit (toto nahradí predchádzajúci commit novým)
+$ git commit --amend -m "Správna správa"
+```
+
+### diff
+
+Ukáže rozdiel medzi súborom v pracovnom repozitári, indexe a commitoch.
+
+```bash
+# Ukáž rozdiel medzi pracovným repozitárom a indexom.
+$ git diff
+
+# Ukáž rozdiely medzi indexom a najnovším commitom.
+$ git diff --cached
+
+# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom.
+$ git diff HEAD
+```
+
+### grep
+
+Umožní ti rýchlo prehľadávať repozitár.
+
+Možná konfigurácia:
+
+```bash
+# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku
+$ git config --global grep.lineNumber true
+
+# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Vďaka Travisovi Jefferymu za túto sekciu
+# Hľadaj "názovPremennej" vo všetkých java súboroch
+$ git grep 'názovPremennej' -- '*.java'
+
+# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Google je tvoj kamarát; pre viac príkladov skoč na
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Zobral commity do repozitára.
+
+```bash
+# Zobraz všetky commity
+$ git log
+
+# Zobraz iba správy a referencie commitov
+$ git log --oneline
+
+# Zobraz zlúčené (merged) commity
+$ git log --merges
+
+# Zobraz všetky commity vo forme ASCII grafu
+$ git log --graph
+```
+
+### merge
+
+"Zlúč" zmeny externých commitov do aktuálnej vetvy.
+
+```bash
+# Zlúč vybranú vetvu do aktuálnej.
+$ git merge názovVetvy
+
+# Vždy vytvor zlučovací commit
+$ git merge --no-ff názovVetvy
+```
+
+### mv
+
+Premenuj, alebo presuň súbor
+
+```bash
+# Premenuj súbor
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Presuň súbor
+$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c
+
+# "Nasilu" premenuj, alebo presuň
+# "existujúciSúbor" už v adresári existuje, bude prepísaný
+$ git mv -f môjSúbor existujúciSúbor
+```
+
+### pull
+
+Uloží obsah repozitára a zlúči ho s inou vetvou.
+
+```bash
+# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien
+# zo vzdialených "origin" a "master" vetiev.
+# git pull <alias-vzdialeného-repo> <vetva>
+$ git pull origin master
+
+# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu
+# zlúčením nových zmien zo vzdialenej vetvy
+$ git pull
+
+# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase)
+# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull <alias-vzdialeného-repo> <vrstva>, git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+Zverejní a zlúči zmeny z lokálnej do vzdialenej vetvy.
+
+```bash
+# Zverejni a zlúč zmeny z lokálneho repozitára do
+# vzdialených vetiev s názvom "origin" a "master".
+# git push <vzdialené> <vetvy>
+$ git push origin master
+
+# Predvolene git zverejní a zlúči zmeny z
+# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej
+$ git push
+
+# Na spojenie lokálnej vetvy so vzdialenou pridaj -u:
+$ git push -u origin master
+# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz:
+$ git push
+```
+
+### stash
+
+Umožní ti opustiť chaotický stav pracovného adresára a uloží ho na zásobník nedokončených zmien, ku ktorým sa môžeš kedykoľvek vrátiť.
+
+Povedzme, že si urobil nejaké zmeny vo svojom git repozitári, ale teraz potrebuješ pullnúť zo vzdialenej repo. Keďže máš necommitnuté zmeny, príkaz `git pull` nebude fungovať. Namiesto toho môžeš použiť `git stash` a uložiť svoje nedokončené zmeny na zásobník!
+
+```bash
+$ git stash
+Saved working directory and index state \
+ "WIP on master: 049d078 added the index file"
+ HEAD is now at 049d078 added the index file
+ (To restore them type "git stash apply")
+```
+
+Teraz môžeš uložiť vzdialenú vetvu!
+
+```bash
+$ git pull
+```
+
+Over, či je všetko v poriadku
+
+```bash
+$ git status
+# On branch master
+nothing to commit, working directory clean
+```
+
+Môžeš si pozrieť, čo za chaos je na zásobníku cez `git stash list`.
+Nedokončené zmeny sú uložené ako Last-In-First-Out (Prvý dnu, posledný von) štruktúra, navrchu sa objavia najnovšie zmeny.
+
+```bash
+$ git stash list
+stash@{0}: WIP on master: 049d078 added the index file
+stash@{1}: WIP on master: c264051 Revert "added file_size"
+stash@{2}: WIP on master: 21d80a5 added number to log
+```
+
+Keď so zmenami budeš chcieť pracovať, odstráň ich zo stacku.
+
+```bash
+$ git stash pop
+# On branch master
+# Changes not staged for commit:
+# (use "git add <file>..." to update what will be committed)
+#
+# modified: index.html
+# modified: lib/simplegit.rb
+#
+```
+
+`git stash apply` urobí presne to isté
+
+Hotovo, môžeš pokračovať v práci!
+
+[Čítaj viac.](http://git-scm.com/book/en/v1/Git-Tools-Stashing)
+
+### rebase (pozor)
+
+Zober všetky zmeny commitnuté do vetvy a aplikuj ich na inú vetvu.
+*Tento príkaz nerob na verejných repozitároch*.
+
+```bash
+# Aplikuj commity z experimentálnej vetvy na master
+# git rebase <základnáVetva> <ináVetva>
+$ git rebase master experimentBranch
+```
+
+[Čítaj viac.](http://git-scm.com/book/en/Git-Branching-Rebasing)
+
+### reset (pozor)
+
+Resetni HEAD (ukazateľ na aktuálnu vetvu) do konrkétneho stavu. To ti umožní vziať späť zlúčenia, zverejnenia, commity, pridania atď. Je to užitočný, no nebezpečný príkaz, pokiaľ nevieš, čo robíš.
+
+```bash
+# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený)
+$ git reset
+
+# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše)
+$ git reset --hard
+
+# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený)
+# všetky zmeny sú zachované v adresári.
+$ git reset 31f2bb1
+
+# Presunie vrchol aktuálnuej vetvy naopak do konkrétneho commitu
+# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny).
+$ git reset --hard 31f2bb1
+```
+### revert
+
+Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav
+projektu do predchádzajúceho bodu v čase. Revert pridá nový commit, inverzný tomu, ktorý chceš vymazať, tým ho od-urobí.
+
+```bash
+# Vezmi späť konkrétny commit
+$ git revert <commit>
+```
+
+### rm
+
+Opak od git add, rm odstráni súbory z aktuálneho pracovného stromu.
+
+```bash
+# odstráň HelloWorld.c
+$ git rm HelloWorld.c
+
+# Odstráň súbor z vnoreného adresára
+$ git rm /pather/to/the/file/HelloWorld.c
+```
+
+## Ďalšie informácie
+
+* [tryGit - Zábavný interaktívny spôsob, ako sa naučiť Git.](http://try.github.io/levels/1/challenges/1)
+
+* [Udemy Git Tutoriál: Kompletný návod](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+
+* [Git Immersion - Návod, ktorý Ťa prevedie základmi Gitu](http://gitimmersion.com/)
+
+* [git-scm - Video Tutoriály](http://git-scm.com/videos)
+
+* [git-scm - Dokumentácia](http://git-scm.com/docs)
+
+* [Atlassian Git - Tutoriály & Postupy](https://www.atlassian.com/git/)
+
+* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
+* [GitGuys](http://www.gitguys.com/)
+
+* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html)
+
+* [Pro Git](http://www.git-scm.com/book/en/v2)
+
+* [Úvod do Gitu a GitHubu pre začiatočníkov (Tutoriál)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
diff --git a/sk-sk/latex.html.markdown.tex b/sk-sk/latex.html.markdown.tex
new file mode 100644
index 00000000..5e2f9c7f
--- /dev/null
+++ b/sk-sk/latex.html.markdown.tex
@@ -0,0 +1,227 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+translators:
+ - ["Terka Slanináková", "http://github.com/TerkaSlan"]
+filename: learn-latex-sk.tex
+---
+
+```tex
+% Všetky komentáre začínajú s %
+% Viac-riadkové komentáre sa nedajú urobiť
+
+% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer
+
+% Každý LaTeX príkaz začína s opačným lomítkom (\)
+
+% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu
+% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď.
+% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu.
+\documentclass[12pt]{article}
+
+% Ďalej definujeme balíčky, ktoré dokuemnt používa.
+% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami.
+% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček.
+\usepackage{caption}
+\usepackage{float}
+\usepackage[utf8]{inputenc}
+% Tu môžme definovať ostatné vlastnosti dokumentu!
+% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok"
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková}
+% Vygeneruje dnešný dátum
+\date{\today}
+\title{Nauč sa LaTeX za Y Minút!}
+% Teraz môžme začať pracovať na samotnom dokumente.
+% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble")
+\begin{document}
+% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu.
+\maketitle
+
+% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy.
+% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke,
+% no pred hlavnými sekciami tela..
+% Tento príkaz je tiež dostupný v triedach article a report.
+% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract
+% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom
+\renewcommand\abstractname{Abstrakt}
+
+\begin{abstract}
+LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu!
+\end{abstract}
+
+% Príkazy pre sekciu sú intuitívne
+% Všetky nadpisy sekcií sú pridané automaticky do obsahu.
+\section{Úvod}
+Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)!
+
+\section{Ďalšia sekcia}
+Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu.
+
+\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne.
+Zdá sa mi, že treba ďalšiu.
+
+\subsubsection{Pytagoras}
+To je ono!
+\label{subsec:pytagoras}
+
+% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu.
+% Toto funguje aj na iné príkazy.
+\section*{Toto je nečíslovaná sekcia}
+Všetky číslované byť nemusia!
+
+\section{Nejaké poznámočky}
+Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak
+potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do
+zdrojového kódu. \\
+
+\section{Zoznamy}
+Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam.
+\begin{enumerate} % "enumerate" spustí číslovanie prvkov.
+ % \item povie LaTeXu, ako že treba pripočítať 1
+ \item Vlašský šalát.
+ \item 5 rožkov.
+ \item 3 Horalky.
+ % číslovanie môžeme pozmeniť použitím []
+ \item[koľko?] Stredne veľkých guličkoviek.
+
+ Ja už nie som položka zoznamu, no stále som časť "enumerate".
+
+\end{enumerate} % Všetky prostredia končia s "end".
+
+\section{Matika}
+
+Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\
+
+Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať;
+Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\
+
+Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch.
+Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\
+% Všimni si, že som pridal $ pred a po symboloch. Je to
+% preto, lebo pri písaní sme v textovom móde,
+% no matematické symboly existujú len v matematickom.
+% Vstúpime doňho z textového práve '$' znamienkami.
+% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto.
+% Do matematického módu sa dá dostať aj s \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$.
+Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal!
+
+Operátory sú dôležitou súčasťou matematických dokumentov:
+goniometrické funkcie ($\sin$, $\cos$, $\tan$),
+logaritmy and exponenciálne výrazy ($\log$, $\exp$),
+limity ($\lim$), atď.
+majú pred-definované LaTeXové príkazy.
+Napíšme si rovnicu, nech vidíme, ako to funguje: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatívne komplexné zlomky sa píšu ako
+% \frac{čitateľ}{menovateľ}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Rovnice tiež môžeme zadať v "rovnicovom prostredí".
+
+% Takto funguje rovnicové prostredie
+\begin{equation} % vstúpi do matematického módu
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % na odkazovanie
+\end{equation} % všetky \begin príkazy musia mať konečný príkaz.
+
+Teraz môžeme odkázať na novovytvorenú rovnicu!
+Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie.
+
+Sumácie a Integrály sa píšu príkazmi sum a int:
+
+% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú)
+% v rovnicovom prostredí.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Obrázky}
+
+Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok.
+\renewcommand\figurename{Obrázok}
+\begin{figure}[H] % H značí možnosť zarovnania.
+ \centering % nacentruje obrázok na stránku
+ % Vloží obrázok na 80% šírky stránky.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Zakomentované kvôli kompilácií, použi svoju predstavivosť :).
+ \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj
+\renewcommand\tablename{Tabuľka}
+
+\subsection{Tabuľky}
+Tabuľky sa vkládajú podobne ako obrázky.
+
+\begin{table}[H]
+ \caption{Nadpis tabuľky.}
+ % zátvorky: {} hovoria ako sa vykreslí každý riadok.
+ % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz!
+ \begin{tabular}{c|cc}
+ Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $
+ \hline % horizontálna čiara
+ 1 & Ladislav & Meliško \\
+ 2 & Eva & Máziková
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Už čoskoro :)
+
+\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)}
+Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom.
+Toto sa robí vo verbatim prostredí.
+
+% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.)
+% ale verbatim je to najzákladnejšie, čo môžeš použiť.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; pozri! Vo verbatime môžme použiť % znamienka.
+ random = 4; #priradené randomným hodom kockou
+\end{verbatim}
+
+\section{Kompilácia}
+
+Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš?
+(áno, tento dokument sa musí kompilovať). \\
+Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov:
+ \begin{enumerate}
+ \item Napíš dokument v čistom texte (v "zdrojáku").
+ \item Skompiluj zdroják na získanie pdfka.
+ Kompilácia by mala vyzerať nasledovne (v Linuxe): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie.
+Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte.
+
+\section{Koniec}
+
+To je zatiaľ všetko!
+
+% koniec dokumentu
+\end{document}
+```
+
+## Viac o LaTeXe (anglicky)
+
+* Úžasná LaTeX wikikniha: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* Naozajstný tutoriál: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex
new file mode 100644
index 00000000..5cc7b11f
--- /dev/null
+++ b/sk-sk/learn-latex-sk.tex
@@ -0,0 +1,209 @@
+% Všetky komentáre začínajú s %
+% Viac-riadkové komentáre sa nedajú urobiť
+
+% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer
+
+% Každý LaTeX príkaz začína s opačným lomítkom (\)
+
+% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu
+% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď.
+% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu.
+\documentclass[12pt]{article}
+
+% Ďalej definujeme balíčky, ktoré dokuemnt používa.
+% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami.
+% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček.
+\usepackage{caption}
+\usepackage{float}
+\usepackage[utf8]{inputenc}
+% Tu môžme definovať ostatné vlastnosti dokumentu!
+% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok"
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková}
+% Vygeneruje dnešný dátum
+\date{\today}
+\title{Nauč sa LaTeX za Y Minút!}
+% Teraz môžme začať pracovať na samotnom dokumente.
+% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble")
+\begin{document}
+% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu.
+\maketitle
+
+% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy.
+% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke,
+% no pred hlavnými sekciami tela..
+% Tento príkaz je tiež dostupný v triedach article a report.
+% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract
+% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom
+\renewcommand\abstractname{Abstrakt}
+
+\begin{abstract}
+LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu!
+\end{abstract}
+
+% Príkazy pre sekciu sú intuitívne
+% Všetky nadpisy sekcií sú pridané automaticky do obsahu.
+\section{Úvod}
+Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)!
+
+\section{Ďalšia sekcia}
+Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu.
+
+\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne.
+Zdá sa mi, že treba ďalšiu.
+
+\subsubsection{Pytagoras}
+To je ono!
+\label{subsec:pytagoras}
+
+% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu.
+% Toto funguje aj na iné príkazy.
+\section*{Toto je nečíslovaná sekcia}
+Všetky číslované byť nemusia!
+
+\section{Nejaké poznámočky}
+Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak
+potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do
+zdrojového kódu. \\
+
+\section{Zoznamy}
+Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam.
+\begin{enumerate} % "enumerate" spustí číslovanie prvkov.
+ % \item povie LaTeXu, ako že treba pripočítať 1
+ \item Vlašský šalát.
+ \item 5 rožkov.
+ \item 3 Horalky.
+ % číslovanie môžeme pozmeniť použitím []
+ \item[koľko?] Stredne veľkých guličkoviek.
+
+ Ja už nie som položka zoznamu, no stále som časť "enumerate".
+
+\end{enumerate} % Všetky prostredia končia s "end".
+
+\section{Matika}
+
+Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\
+
+Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať;
+Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\
+
+Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch.
+Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\
+% Všimni si, že som pridal $ pred a po symboloch. Je to
+% preto, lebo pri písaní sme v textovom móde,
+% no matematické symboly existujú len v matematickom.
+% Vstúpime doňho z textového práve '$' znamienkami.
+% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto.
+% Do matematického módu sa dá dostať aj s \[\]
+
+\[a^2 + b^2 = c^2 \]
+
+Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$.
+Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal!
+
+Operátory sú dôležitou súčasťou matematických dokumentov:
+goniometrické funkcie ($\sin$, $\cos$, $\tan$),
+logaritmy and exponenciálne výrazy ($\log$, $\exp$),
+limity ($\lim$), atď.
+majú pred-definované LaTeXové príkazy.
+Napíšme si rovnicu, nech vidíme, ako to funguje: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatívne komplexné zlomky sa píšu ako
+% \frac{čitateľ}{menovateľ}
+$\frac{n!}{k!(n - k)!}$ \\
+
+Rovnice tiež môžeme zadať v "rovnicovom prostredí".
+
+% Takto funguje rovnicové prostredie
+\begin{equation} % vstúpi do matematického módu
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % na odkazovanie
+\end{equation} % všetky \begin príkazy musia mať konečný príkaz.
+
+Teraz môžeme odkázať na novovytvorenú rovnicu!
+Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie.
+
+Sumácie a Integrály sa píšu príkazmi sum a int:
+
+% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú)
+% v rovnicovom prostredí.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Obrázky}
+
+Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok.
+\renewcommand\figurename{Obrázok}
+\begin{figure}[H] % H značí možnosť zarovnania.
+ \centering % nacentruje obrázok na stránku
+ % Vloží obrázok na 80% šírky stránky.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Zakomentované kvôli kompilácií, použi svoju predstavivosť :).
+ \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj
+\renewcommand\tablename{Tabuľka}
+
+\subsection{Tabuľky}
+Tabuľky sa vkládajú podobne ako obrázky.
+
+\begin{table}[H]
+ \caption{Nadpis tabuľky.}
+ % zátvorky: {} hovoria ako sa vykreslí každý riadok.
+ % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz!
+ \begin{tabular}{c|cc}
+ Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $
+ \hline % horizontálna čiara
+ 1 & Ladislav & Meliško \\
+ 2 & Eva & Máziková
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Už čoskoro :)
+
+\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)}
+Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom.
+Toto sa robí vo verbatim prostredí.
+
+% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.)
+% ale verbatim je to najzákladnejšie, čo môžeš použiť.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; pozri! Vo verbatime môžme použiť % znamienka.
+ random = 4; #priradené randomným hodom kockou
+\end{verbatim}
+
+\section{Kompilácia}
+
+Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš?
+(áno, tento dokument sa musí kompilovať). \\
+Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov:
+ \begin{enumerate}
+ \item Napíš dokument v čistom texte (v "zdrojáku").
+ \item Skompiluj zdroják na získanie pdfka.
+ Kompilácia by mala vyzerať nasledovne (v Linuxe): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie.
+Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte.
+
+\section{Koniec}
+
+To je zatiaľ všetko!
+
+% koniec dokumentu
+\end{document}
diff --git a/swift.html.markdown b/swift.html.markdown
index 1ca81bc2..e6bf1621 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: learnswift.swift
---
@@ -25,13 +26,13 @@ import UIKit
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
-// MARK: - Section mark with a separator line
+// MARK: - Section mark with a separator line
// TODO: Do something soon
// FIXME: Fix this code
// In Swift 2, println and print were combined into one print method. Print automatically appends a new line.
print("Hello, world") // println is now print
-print("Hello, world", appendNewLine: false) // printing without appending a newline
+print("Hello, world", terminator: "") // printing without appending a newline
// variables (var) value can change after being set
// constants (let) value can NOT be changed after being set
@@ -45,7 +46,7 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names
let explicitDouble: Double = 70
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
-let label = "some text " + String(myVariable) // Casting
+let label = "some text " + String(myVariable) // String construction
let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
// Build Specific values
@@ -59,14 +60,14 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals are a Swift language feature that either contains a value,
- or contains nil (no value) to indicate that a value is missing.
- A question mark (?) after the type marks the value as optional.
+Optionals are a Swift language feature that either contains a value,
+or contains nil (no value) to indicate that a value is missing.
+A question mark (?) after the type marks the value as optional.
- Because Swift requires every property to have a value, even nil must be
- explicitly stored as an Optional value.
+Because Swift requires every property to have a value, even nil must be
+explicitly stored as an Optional value.
- Optional<T> is an enum.
+Optional<T> is an enum.
*/
var someOptionalString: String? = "optional" // Can be nil
// same as above, but ? is a postfix operator (syntax candy)
@@ -83,9 +84,9 @@ if someOptionalString != nil {
someOptionalString = nil
/*
- Trying to use ! to access a non-existent optional value triggers a runtime
- error. Always make sure that an optional contains a non-nil value before
- using ! to force-unwrap its value.
+Trying to use ! to access a non-existent optional value triggers a runtime
+error. Always make sure that an optional contains a non-nil value before
+using ! to force-unwrap its value.
*/
// implicitly unwrapped optional
@@ -119,8 +120,8 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
//
/*
- Array and Dictionary types are structs. So `let` and `var` also indicate
- that they are mutable (var) or immutable (let) when declaring these types.
+Array and Dictionary types are structs. So `let` and `var` also indicate
+that they are mutable (var) or immutable (let) when declaring these types.
*/
// Array
@@ -148,6 +149,14 @@ var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
// MARK: Control Flow
//
+// Condition statements support "where" clauses, which can be used
+// to help provide conditions on optional values.
+// Both the assignment and the "where" clause must pass.
+let someNumber = Optional<Int>(7)
+if let num = someNumber where num > 3 {
+ print("num is greater than 3")
+}
+
// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
@@ -177,8 +186,8 @@ while i < 1000 {
i *= 2
}
-// do-while loop
-do {
+// repeat-while loop
+repeat {
print("hello")
} while 1 == 2
@@ -197,7 +206,6 @@ default: // required (in order to cover all possible input)
let vegetableComment = "Everything tastes good in soup."
}
-
//
// MARK: Functions
//
@@ -208,25 +216,25 @@ default: // required (in order to cover all possible input)
// Function with Swift header docs (format as reStructedText)
/**
- A greet operation
+A greet operation
- - A bullet in docs
- - Another bullet in the docs
+- A bullet in docs
+- Another bullet in the docs
- :param: name A name
- :param: day A day
- :returns: A string containing the name and day value.
+:param: name A name
+:param: day A day
+:returns: A string containing the name and day value.
*/
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
-greet("Bob", "Tuesday")
+greet("Bob", day: "Tuesday")
// similar to above except for the function parameter behaviors
-func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
+func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String {
return "Hello \(requiredName), the day is \(localParamName)"
}
-greet2(requiredName:"John", externalParamName: "Sunday")
+greet2(requiredName: "John", externalParamName: "Sunday")
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
@@ -239,11 +247,33 @@ let (_, price1, _) = pricesTuple // price1 == 3.69
print(price1 == pricesTuple.1) // true
print("Gas price: \(price)")
+// Labeled/named tuple params
+func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) {
+ return (1.77, 37.70, 7.37)
+}
+let pricesTuple2 = getGasPrices2()
+let price2 = pricesTuple2.lowestPrice
+let (_, price3, _) = pricesTuple2
+print(pricesTuple2.highestPrice == pricesTuple2.1) // true
+print("Highest gas price: \(pricesTuple2.highestPrice)")
+
+// guard statements
+func testGuard() {
+ // guards provide early exits or breaks, placing the error handler code near the conditions.
+ // it places variables it declares in the same scope as the guard statement.
+ guard let aNumber = Optional<Int>(7) else {
+ return
+ }
+
+ print("number is \(aNumber)")
+}
+testGuard()
+
// Variadic Args
func setup(numbers: Int...) {
// its an array
- let number = numbers[0]
- let argCount = numbers.count
+ let _ = numbers[0]
+ let _ = numbers.count
}
// Passing and returning functions
@@ -264,7 +294,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
}
var someIntA = 7
var someIntB = 3
-swapTwoInts(&someIntA, &someIntB)
+swapTwoInts(&someIntA, b: &someIntB)
print(someIntB) // 7
@@ -292,23 +322,17 @@ numbers = numbers.map({ number in 3 * number })
print(numbers) // [3, 6, 18]
// Trailing closure
-numbers = sorted(numbers) { $0 > $1 }
+numbers = numbers.sort { $0 > $1 }
print(numbers) // [18, 6, 3]
-// Super shorthand, since the < operator infers the types
-
-numbers = sorted(numbers, < )
-
-print(numbers) // [3, 6, 18]
-
//
// MARK: Structures
//
// Structures and classes have very similar capabilities
struct NamesTable {
- let names = [String]()
+ let names: [String]
// Custom subscript
subscript(index: Int) -> String {
@@ -322,6 +346,44 @@ let name = namesTable[1]
print("Name is \(name)") // Name is Them
//
+// MARK: Error Handling
+//
+
+// The `ErrorType` protocol is used when throwing errors to catch
+enum MyError: ErrorType {
+ case BadValue(msg: String)
+ case ReallyBadValue(msg: String)
+}
+
+// functions marked with `throws` must be called using `try`
+func fakeFetch(value: Int) throws -> String {
+ guard 7 == value else {
+ throw MyError.ReallyBadValue(msg: "Some really bad value")
+ }
+
+ return "test"
+}
+
+func testTryStuff() {
+ // assumes there will be no error thrown, otherwise a runtime exception is raised
+ let _ = try! fakeFetch(7)
+
+ // if an error is thrown, then it proceeds, but if the value is nil
+ // it also wraps every return value in an optional, even if its already optional
+ let _ = try? fakeFetch(7)
+
+ do {
+ // normal try operation that provides error handling via `catch` block
+ try fakeFetch(1)
+ } catch MyError.BadValue(let msg) {
+ print("Error message: \(msg)")
+ } catch {
+ // must be exhaustive
+ }
+}
+testTryStuff()
+
+//
// MARK: Classes
//
@@ -352,6 +414,11 @@ internal class Rect: Shape {
}
}
+ // Computed properties must be declared as `var`, you know, cause' they can change
+ var smallestSideLength: Int {
+ return self.sideLength - 1
+ }
+
// Lazily load a property
// subShape remains nil (uninitialized) until getter called
lazy var subShape = Rect(sideLength: 4)
@@ -456,9 +523,10 @@ enum Suit {
// when the variable is explicitly declared
var suitValue: Suit = .Hearts
-// Non-Integer enums require direct raw value assignments
+// String enums can have direct raw value assignments
+// or their raw values will be derived from the Enum field
enum BookName: String {
- case John = "John"
+ case John
case Luke = "Luke"
}
print("Name: \(BookName.John.rawValue)")
@@ -502,7 +570,7 @@ protocol ShapeGenerator {
// Protocols declared with @objc allow optional functions,
// which allow you to check for conformance
@objc protocol TransformShape {
- optional func reshaped()
+ optional func reshape()
optional func canReshape() -> Bool
}
@@ -515,9 +583,9 @@ class MyShape: Rect {
// Place a question mark after an optional property, method, or
// subscript to gracefully ignore a nil value and return nil
// instead of throwing a runtime error ("optional chaining").
- if let allow = self.delegate?.canReshape?() {
+ if let reshape = self.delegate?.canReshape?() where reshape {
// test for delegate then for method
- self.delegate?.reshaped?()
+ self.delegate?.reshape?()
}
}
}
@@ -529,8 +597,8 @@ class MyShape: Rect {
// `extension`s: Add extra functionality to an already existing type
-// Square now "conforms" to the `Printable` protocol
-extension Square: Printable {
+// Square now "conforms" to the `CustomStringConvertible` protocol
+extension Square: CustomStringConvertible {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
@@ -555,8 +623,8 @@ print(14.multiplyBy(3)) // 42
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
// requirements of the generics.
-func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
- for (index, value) in enumerate(array) {
+func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
+ for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown
index 2477c5da..c7de2922 100644
--- a/tr-tr/python3-tr.html.markdown
+++ b/tr-tr/python3-tr.html.markdown
@@ -538,7 +538,7 @@ Insan.grunt() # => "*grunt*"
# Modülleri içe aktarabilirsiniz
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# Modülden belirli bir fonksiyonları alabilirsiniz
from math import ceil, floor
diff --git a/typescript.html.markdown b/typescript.html.markdown
index e9135510..47e41405 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -83,23 +83,23 @@ mySearch = function(src: string, sub: string) {
// Classes - members are public by default
class Point {
// Properties
- x: number;
+ x: number;
- // Constructor - the public/private keywords in this context will generate
- // the boiler plate code for the property and the initialization in the
- // constructor.
- // In this example, "y" will be defined just like "x" is, but with less code
- // Default values are also supported
+ // Constructor - the public/private keywords in this context will generate
+ // the boiler plate code for the property and the initialization in the
+ // constructor.
+ // In this example, "y" will be defined just like "x" is, but with less code
+ // Default values are also supported
- constructor(x: number, public y: number = 0) {
- this.x = x;
- }
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
- // Functions
- dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+ // Functions
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
- // Static members
- static origin = new Point(0, 0);
+ // Static members
+ static origin = new Point(0, 0);
}
var p1 = new Point(10 ,20);
@@ -107,15 +107,15 @@ var p2 = new Point(25); //y will be 0
// Inheritance
class Point3D extends Point {
- constructor(x: number, y: number, public z: number = 0) {
- super(x, y); // Explicit call to the super class constructor is mandatory
- }
+ constructor(x: number, y: number, public z: number = 0) {
+ super(x, y); // Explicit call to the super class constructor is mandatory
+ }
- // Overwrite
- dist() {
- var d = super.dist();
- return Math.sqrt(d * d + this.z * this.z);
- }
+ // Overwrite
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
}
// Modules, "." can be used as separator for sub modules
@@ -139,19 +139,19 @@ var s2 = new G.Square(10);
// Generics
// Classes
class Tuple<T1, T2> {
- constructor(public item1: T1, public item2: T2) {
- }
+ constructor(public item1: T1, public item2: T2) {
+ }
}
// Interfaces
interface Pair<T> {
- item1: T;
- item2: T;
+ item1: T;
+ item2: T;
}
// And functions
var pairToTuple = function<T>(p: Pair<T>) {
- return new Tuple(p.item1, p.item2);
+ return new Tuple(p.item1, p.item2);
};
var tuple = pairToTuple({ item1:"hello", item2:"world"});
@@ -159,6 +159,14 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"});
// Including references to a definition file:
/// <reference path="jquery.d.ts" />
+// Template Strings (strings that use backticks)
+// String Interpolation with Template Strings
+var name = 'Tyrone';
+var greeting = `Hi ${name}, how are you?`
+// Multiline Strings with Template Strings
+var multiline = `This is an example
+of a multiline string`;
+
```
## Further Reading
diff --git a/uk-ua/bash-ua.html.markdown b/uk-ua/bash-ua.html.markdown
new file mode 100644
index 00000000..b7e4a5ba
--- /dev/null
+++ b/uk-ua/bash-ua.html.markdown
@@ -0,0 +1,296 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+ - ["Anton Strömkvist", "http://lutic.org/"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gregrory Kielian", "https://github.com/gskielian"]
+ - ["Etan Reisner", "https://github.com/deryni"]
+translators:
+ - ["Ehreshi Ivan", "https://github.com/IvanEh"]
+lang: uk-ua
+---
+
+Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для
+операційної системи GNU і зараз використовується як командна оболонка за замовчуванням
+для Linux i Max OS X.
+Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell.
+Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або
+виконані в оболонці
+
+[Більш детально тут.](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+# Перший рядок скрипта - це shebang, який вказує системі, як потрібно виконувати
+# скрипт. Як ви вже зрозуміли, коментарі починаються з #. Shebang - тоже коментар
+
+# Простий приклад hello world:
+echo Hello world!
+
+# Окремі команди починаються з нового рядка або розділяються крапкою з комкою:
+echo 'Перший рядок'; echo 'Другий рядок'
+
+# Оголошення змінної
+VARIABLE="Просто рядок"
+
+# Але не так!
+VARIABLE = "Просто рядок"
+# Bash вирішить, що VARIABLE - це команда, яку він може виконати,
+# і видасть помилку, тому що не зможе знайти її
+
+# І так також не можна писати:
+VARIABLE= 'Просто рядок'
+# Bash сприйме рядок 'Просто рядок' як команду. Але такої команди не має, тому
+# видасть помилку.
+# (тут 'VARIABLE=' інтерпретується як присвоєння тільки в контексті
+# виконання команди 'Просто рядок')
+
+# Використання змінних:
+echo $VARIABLE
+echo "$VARIABLE"
+echo '$VARIABLE'
+# Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. -
+# пишіть її імя без $. А для отримання значення змінної використовуйте $.
+# Одинарні лапки ' не розкривають значення змінних
+
+# Підстановка рядків в змінні
+echo ${VARIABLE/Просто/A}
+# Цей вираз замінить перше входження підрядка "Просто" на "А"
+
+# Отримання підрядка із рядка
+LENGTH=7
+echo ${VARIABLE:0:LENGTH}
+# Цей вираз поверне тільки перші 7 символів змінної VARIABLE
+
+# Значення за замовчуванням
+echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"}
+# Це спрацює при відсутності значення (FOO=) і при пустому рядку (FOO="")
+# Нуль (FOO=0) поверне 0.
+# Зауважте, що у всіх випадках значення самої змінної FOO не зміниться
+
+# Вбудовані змінні:
+# В bash є корисні вбудовані змінні, наприклад
+echo "Значення, яке було повернуте в останній раз: $?"
+echo "PID скрипта: $$"
+echo "Кількість аргументів: $#"
+echo "Аргументи скрипта: $@"
+echo "Аргументи скрипта, розподілені по різним змінним: $1 $2..."
+
+# Зчитування змінних з пристроїв введення
+echo "Як вас звати?"
+read NAME # Зверніть увагу, що вам не потрібно оголошувати нову змінну
+echo Привіт, $NAME!
+
+# В bash є звичайна умовна конструкція if:
+# наберіть 'man test', щоб переглянути детальну інформацію про формати умов
+if [ $NAME -ne $USER ]
+then
+ echo "Ім’я користувача не збігається з введеним"
+else
+ echo "Ім’я збігаєтьяс з іменем користувача"
+fi
+
+# Зауважте! якщо $Name пуста, bash інтерпретує код вище як:
+if [ -ne $USER ]
+# що є неправильним синтаксисом
+# тому безпечний спосіб використання потенційно пустих змінних має вигляд:
+if [ "$Name" -ne $USER ] ...
+# коли $Name пуста, інтерпретується наступним чином:
+if [ "" -ne $USER ] ...
+# що працює як і очікувалося
+
+# Умовне виконання (conditional execution)
+echo "Виконується завжди" || echo "Виконається, якщо перша команда завершиться з помилкою"
+echo "Виконується завжди" && echo "Виконається, якщо перша команда завершиться успішно"
+
+# Щоб використати && і || у конструкції if, потрібно декілька пар дужок:
+if [ $NAME == "Steve" ] && [ $AGE -eq 15 ]
+then
+ echo "Виконається, якщо $NAME="Steve" i AGE=15."
+fi
+
+if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ]
+then
+ echo "Виконається, якщо NAME="Steve" або NAME="Zach"."
+fi
+
+# Вирази позначаються наступним форматом:
+echo $(( 10 + 5 ))
+
+# На відмінно від інших мов програмування, Bash - це командна оболонка, а
+# отже, працює в контексті поточної директорії
+ls
+
+# Ця команда може використовуватися з опціями
+ls -l # Показати кожен файл і директорію на окремому рядку
+
+# Результат попередньої команди можна перенаправити на вхід наступної.
+# Команда grep фільтрує вхід по шаблону.
+# Таким чином ми можемо переглянути тільки *.txt файли в поточній директорії:
+ls -l | grep "\.txt"
+
+# Ви можете перенаправ вхід і вихід команди (stdin, stdout, stderr).
+# Наступна команда означає: читати із stdin, поки не зустрінеться ^EOF$, і
+# перезаписати hello.py наступними рядками (до рядка "EOF"):
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ import print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("#stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Запуск hello.py з різними варіантами перенаправлення stdin,
+# stdout, stderr (стандартні потоки введення, виведення і помилок):
+python hello.py < "input.in"
+python hello.py > "output.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# Поток помилок перезапише фпйл, якщо цей файл існує
+# тому, якщо ви хочете дописувати до файлу, використовуйте ">>":
+python hello.py >> "output.out" 2>> "error.err"
+
+# Перезаписати output.txt, дописати error.err і порахувати кількість рядків:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Запустити команду і вивести її файловий дескриптор (див.: man fd; наприклад /dev/fd/123)
+echo <(echo "#helloworld")
+
+# Перезаписати output.txt рядком "#helloworld":
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим)
+# Очистити тимчасові файли з детальним виводом (додайте '-i'
+# для інтерактивного режиму)
+rm -v output.out error.err output-and-error.log
+
+# Команди можуть бути підставлені в інші команди використовуючи $():
+# наступна команда виводить кількість файлів і директорій в поточній директорії
+echo "Тут $(ls | wc -l) елементів."
+
+# Те саме можна зробити використовуючи зворотні лапки
+# Але вони не можуть бути вкладеними, тому перший варіант бажаніший
+echo "Тут `ls | wc -l` елементів."
+
+# В Bash є структура case, яка схожа на switch в Java и C++:
+case "$VARIABLE" in
+ # перерахуйте шаблони, які будуть використовуватися в якості умов
+ 0) echo "Тут нуль.";;
+ 1) echo "Тут один.";;
+ *) echo "Не пусте значення.";;
+esac
+
+# Цикл for перебирає елементи передані в аргумент:
+# Значення $VARIABLE буде напечатано тричі.
+for VARIABLE in {1..3}
+do
+ echo "$VARIABLE"
+done
+
+# Aбо можна використати звичний синтаксис for:
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Цикл for можно використати, щоб виконувати дії над файлами.
+# Цей код запустить команду 'cat' для файлів file1 и file2
+for VARIABLE in file1 file2
+do
+ cat "$VARIABLE"
+done
+
+# ... або дії над виводом команд
+# Запустимо cat для виведення із ls.
+for OUTPUT in $(ls)
+do
+ cat "$OUTPUT"
+done
+
+# Цикл while:
+while [ true ]
+do
+ echo "Тіло циклу..."
+ break
+done
+
+# Ви також можете оголосити функцію
+# Оголошення:
+function foo ()
+{
+ echo "Аргументи функції доступні так само, як і аргументи скрипта: $@"
+ echo "$1 $2..."
+ echo "Це функція"
+ return 0
+}
+
+# Або просто
+bar ()
+{
+ echo "Інший спосіб оголошення функцій!"
+ return 0
+}
+
+# Виклик функцій
+foo "Мое имя" $NAME
+
+# Є багато корисних команд:
+# вивести останні 10 рядків файла file.txt
+tail -n 10 file.txt
+# вивести перші 10 рядків файла file.txt
+head -n 10 file.txt
+# відсортувати рядки file.txt
+sort file.txt
+# відібрати або пропустити рядки, що дублюються (з опцією -d відбирає)
+uniq -d file.txt
+# вивести тільки першу колонку перед символом ','
+cut -d ',' -f 1 file.txt
+# замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex)
+sed -i 's/okay/great/g' file.txt
+# вивести в stdout все рядки з file.txt, що задовольняють шаблону regex;
+# цей приклад виводить рядки, що починаються на foo і закінчуються на bar:
+grep "^foo.*bar$" file.txt
+# використайте опцію -c, щоб вивести кількість входжень
+grep -c "^foo.*bar$" file.txt
+# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F)
+# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F)
+fgrep "^foo.*bar$" file.txt
+
+# Читайте вбудовану документацію Bash командою 'help':
+help
+help help
+help for
+help return
+help source
+help .
+
+# Читайте Bash man-документацію
+apropos bash
+man 1 bash
+man bash
+
+# Читайте документацію info (? для допомоги)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+# Читайте bash info документацію:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
+```
diff --git a/ua-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown
index fedbf5ac..9614f9ca 100644
--- a/ua-ua/javascript-ua.html.markdown
+++ b/uk-ua/javascript-ua.html.markdown
@@ -3,11 +3,11 @@ language: javascript
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
- ["Ariel Krakowski", "http://www.learneroo.com"]
-filename: javascript-ru.js
+filename: javascript-uk.js
translators:
- - ["Alexey Gonchar", "http://github.com/finico"]
- - ["Andre Polykanine", "https://github.com/Oire"]
-lang: ru-ru
+ - ["Ivan", "https://github.com/IvanEh"]
+ - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"]
+lang: uk-ua
---
JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape.
@@ -25,7 +25,7 @@ JavaScript було створено в 1995 році Бренданом Айк
/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і
закінчуються символами зірочка-слеш */
-Інструкції можуть закінчуватися крапкою з комою ;
+//Інструкції можуть закінчуватися крапкою з комою ;
doStuff();
// ... але не обов’язково, тому що крапка з комою автоматично вставляється на
@@ -51,7 +51,7 @@ doStuff()
10 * 2; // = 20
35 / 5; // = 7
-// В тому числі ділення з остачою
+// В тому числі ділення з остачею
5 / 2; // = 2.5
// В JavaScript є побітові операції; коли ви виконуєте таку операцію,
@@ -73,7 +73,7 @@ false;
// Рядки створюються за допомогою подвійних та одинарних лапок
'абв';
-"Hello, world!";
+"Привіт, світе!";
// Для логічного заперечення використовується знак оклику.
!true; // = false
@@ -93,10 +93,10 @@ false;
2 <= 2; // = true
2 >= 2; // = true
-// Рядки об’єднуються за допомогою оператор +
+// Рядки об’єднуються за допомогою оператора +
"hello, " + "world!"; // = "hello, world!"
-// І порівнюються за допомогою > і <
+// І порівнюються за допомогою > та <
"a" < "b"; // = true
// Перевірка на рівність з приведнням типів здійснюється оператором ==
@@ -112,7 +112,7 @@ null === undefined; // = false
"13" + !0; // '13true'
// Можна отримати доступ до будь-якого символа рядка за допомгою charAt
-"Это строка".charAt(0); // = 'Э'
+"Це рядок".charAt(0); // = 'Ц'
// ... або використати метод substring, щоб отримати більший кусок
"Hello, world".substring(0, 5); // = "Hello"
@@ -124,8 +124,8 @@ null === undefined; // = false
null; // навмисна відсутність результату
undefined; // використовується для позначення відсутності присвоєного значення
-// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина.
-// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що:
+// false, null, undefined, NaN, 0 та "" — хиба; все інше - істина.
+// Потрібно відмітити, що 0 — це хиба, а "0" — істина, не зважаючи на те що:
// 0 == "0".
///////////////////////////////////
@@ -139,7 +139,7 @@ var someVar = 5;
// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ...
someOtherVar = 10;
-// ... але ваша змінна буде створення в глобальному контексті, а не там, де
+// ... але вашу змінну буде створено в глобальному контексті, а не там, де
// ви її оголосили
// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined
@@ -153,21 +153,21 @@ someVar *= 10; // тепер someVar = 100
someVar++; // тепер someVar дорівнює 101
someVar--; // а зараз 100
-// Масиви — це нумеровані списку, які зберігають значення будь-якого типу.
-var myArray = ["Hello", 45, true];
+// Масиви — це нумеровані списки, які зберігають значення будь-якого типу.
+var myArray = ["Привіт", 45, true];
// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками
// Індексація починається з нуля
myArray[1]; // = 45
-// Массивы можно изменять, как и их длину,
-myArray.push("Мир");
+// Масиви в JavaScript змінюють свою довжину при додаванні нових елементів
+myArray.push("Привіт");
myArray.length; // = 4
-// додавання і редагування елементів
-myArray[3] = "Hello";
+// Додавання і редагування елементів
+myArray[3] = "світ";
-// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах
+// Об’єкти в JavaScript схожі на словники або асоціативні масиви в інших мовах
var myObj = {key1: "Hello", key2: "World"};
// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє
@@ -183,11 +183,11 @@ myObj.myKey; // = "myValue"
// Об’єкти можна динамічно змінювати й додавати нові поля
myObj.myThirdKey = true;
-// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined
+// Коли ви звертаєтесь до поля, що не існує, ви отримуєте значення undefined
myObj.myFourthKey; // = undefined
///////////////////////////////////
-// 3. Управляючі конструкції
+// 3. Керуючі конструкції
// Синтаксис для цього розділу майже такий самий, як у Java
@@ -212,7 +212,7 @@ do {
input = getInput();
} while (!isValid(input))
-// цикл for такий самий, кяк в C і Java:
+// цикл for такий самий, як в C і Java:
// ініціалізація; умова; крок.
for (var i = 0; i < 5; i++) {
// виконається 5 разів
@@ -226,7 +226,7 @@ if (color == "red" || color == "blue") {
// колір червоний або синій
}
-// && і || використовують скорочене обчислення
+// && та || використовують скорочене обчислення
// тому їх можна використовувати для задання значень за замовчуванням.
var name = otherName || "default";
@@ -258,9 +258,9 @@ function myFunction(thing) {
}
myFunction("foo"); // = "FOO"
-// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж
+// Зверніть увагу, що значення яке буде повернено, повинно починатися на тому ж
// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined
-// із-за автоматичної вставки крапки з комою
+// через автоматичну вставку крапки з комою
function myFunction()
{
return // <- крапка з комою вставляється автоматично
@@ -279,20 +279,18 @@ function myFunction() {
setTimeout(myFunction, 5000);
// setTimeout не є частиною мови, але реалізований в браузерах і Node.js
-// Функции не обязательно должны иметь имя при объявлении — вы можете написать
-// анонимное определение функции непосредственно в аргументе другой функции.
// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати
-// анонімну функцію прямо в якості аргумента іншої функції
+// анонімну функцію як аргумент іншої функції
setTimeout(function() {
// Цей код буде виконано через п’ять секунд
}, 5000);
// В JavaScript реалізована концепція області видимості; функції мають свою
-// область видимости, а інші блоки не мають
+// область видимості, а інші блоки не мають
if (true) {
var i = 5;
}
-i; // = 5, а не undefined, як це звичайно буває в інших мова
+i; // = 5, а не undefined, як це звичайно буває в інших мовах
// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе"
// що дозволяє уникнути проникнення змінних в глобальну область видимості
@@ -305,26 +303,22 @@ i; // = 5, а не undefined, як це звичайно буває в інши
temporary; // повідомлення про помилку ReferenceError
permanent; // = 10
-// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция
-// определена внутри другой функции, то внутренняя функция имеет доступ к
-// переменным внешней функции даже после того, как контекст выполнения выйдет из
-// внешней функции.
-// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена
+// Замикання - один з найпотужніших інструментів JavaScript. Якщо функція визначена
// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої
// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції
function sayHelloInFiveSeconds(name) {
- var prompt = "Hello, " + name + "!";
+ var prompt = "Привіт, " + name + "!";
// Внутрішня функція зберігається в локальній області так,
// ніби функція була оголошена за допомогою ключового слова var
function inner() {
alert(prompt);
}
setTimeout(inner, 5000);
- // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться,
+ // setTimeout асинхронна, тому функція sayHelloInFiveSeconds одразу завершиться,
// після чого setTimeout викличе функцію inner. Але функція inner
// «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt
}
-sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!»
+sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Привіт, Адам!»
///////////////////////////////////
// 5. Об’єкти: конструктори і прототипи
@@ -394,7 +388,7 @@ myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому
-// об’єктів, інтерпретатор буде шукати поле в прототипі
+// об’єкті, інтерпретатор буде шукати поле в прототипі
// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через
// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують
@@ -415,24 +409,24 @@ myObj.meaningOfLife; // = 42
// Аналогічно для функцій
myObj.myFunc(); // = "Hello, world!"
-// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук
+// Якщо інтерпретатор не знайде властивості в прототипі, то він продовжить пошук
// в прототипі прототипа і так далі
myPrototype.__proto__ = {
myBoolean: true
};
myObj.myBoolean; // = true
-// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити
+// Кожен об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити
// наш прототип, і наші зміни будуть всюди відображені.
myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43
-// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу
-// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим
+// Ми сказали, що властивість __proto__ нестандартна, і нема ніякого стандартного способу
+// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт із заданим
// прототипом
-// Перший спосіб — це Object.create, який з’явився JavaScript недавно,
-// а тому в деяких реалізаціях може бути не доступним.
+// Перший спосіб — це Object.create, який з’явився в JavaScript недавно,
+// а тому в деяких реалізаціях може бути недоступним.
var myObj = Object.create(myPrototype);
myObj.meaningOfLife; // = 43
@@ -461,7 +455,7 @@ typeof myNumber; // = 'number'
typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0) {
- // Этот код не выполнится, потому что 0 - это ложь.
+ // Цей код не виконається, тому що 0 - це хиба.
}
// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому
@@ -475,9 +469,9 @@ String.prototype.firstCharacter = function() {
// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих
// середовищах
-// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо
+// Наприклад, Object.create доступний не у всіх реалізаціях, але ми можемо
// використати функції за допомогою наступного поліфіла:
-if (Object.create === undefined) { // не перезаписываем метод, если он существует
+if (Object.create === undefined) { // не перезаписуємо метод, якщо він існує
Object.create = function(proto) {
// Створюємо правильний конструктор з правильним прототипом
var Constructor = function(){};
diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown
new file mode 100644
index 00000000..8ee12a93
--- /dev/null
+++ b/uk-ua/json-ua.html.markdown
@@ -0,0 +1,67 @@
+---
+language: json
+filename: learnjson-ru.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Ehreshi Ivan", "https://github.com/IvanEh"]
+lang: uk-ua
+---
+
+JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом
+"Learn X in Y Minutes".
+
+В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють
+використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього
+поля, але все-таки краще такого уникати для кращої сумісності
+
+```json
+{
+ "ключ": "значеннь",
+
+ "ключі": "завжди мають бути обгорнуті в подвійні лапки",
+ "числа": 0,
+ "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".",
+ "логічний тип": true,
+ "нічого": null,
+
+ "велике число": 1.2e+100,
+
+ "об’єкти": {
+ "коментар": "Більшість ваших структур будуть складатися з об’єктів",
+
+ "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5],
+
+ "інший об’єкт": {
+ "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно."
+ }
+ },
+
+ "безглуздя": [
+ {
+ "джерело калія": ["банани"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "нео"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "альтернативнтй стиль": {
+ "коментар": "Гляньте!"
+ , "позиція коми": "неважлива, поки вона знаходиться до наступного поля"
+ , "інший коментар": "класно"
+ },
+
+ "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON."
+}
+
+Одиничний масив значень теж є правильним JSON
+
+[1, 2, 3, "text", true]
+
+
+```
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index accdbf56..0371e6f6 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -9,13 +9,13 @@ filename: learnvisualbasic.vb
Module Module1
Sub Main()
- ' A Quick Overview of Visual Basic Console Applications before we dive
- ' in to the deep end.
- ' Apostrophe starts comments.
- ' To Navigate this tutorial within the Visual Basic Complier, I've put
- ' together a navigation system.
- ' This navigation system is explained however as we go deeper into this
- ' tutorial, you'll understand what it all means.
+ 'A Quick Overview of Visual Basic Console Applications before we dive
+ 'in to the deep end.
+ 'Apostrophe starts comments.
+ 'To Navigate this tutorial within the Visual Basic Complier, I've put
+ 'together a navigation system.
+ 'This navigation system is explained however as we go deeper into this
+ 'tutorial, you'll understand what it all means.
Console.Title = ("Learn X in Y Minutes")
Console.WriteLine("NAVIGATION") 'Display
Console.WriteLine("")
@@ -32,9 +32,9 @@ Module Module1
Console.WriteLine("50. About")
Console.WriteLine("Please Choose A Number From The Above List")
Dim selection As String = Console.ReadLine
- ' The "Case" in the Select statement is optional.
- ' For example, "Select selection" instead of "Select Case selection"
- ' will also work.
+ 'The "Case" in the Select statement is optional.
+ 'For example, "Select selection" instead of "Select Case selection"
+ 'will also work.
Select Case selection
Case "1" 'HelloWorld Output
Console.Clear() 'Clears the application and opens the private sub
@@ -45,10 +45,10 @@ Module Module1
Case "3" 'Calculating Whole Numbers
Console.Clear()
CalculatingWholeNumbers()
- Case "4" 'Calculting Decimal Numbers
+ Case "4" 'Calculating Decimal Numbers
Console.Clear()
CalculatingDecimalNumbers()
- Case "5" 'Working Calcculator
+ Case "5" 'Working Calculator
Console.Clear()
WorkingCalculator()
Case "6" 'Using Do While Loops
@@ -77,10 +77,10 @@ Module Module1
'One - I'm using numbers to help with the above navigation when I come back
'later to build it.
- 'We use private subs to seperate different sections of the program.
+ 'We use private subs to separate different sections of the program.
Private Sub HelloWorldOutput()
'Title of Console Application
- Console.Title = "Hello World Ouput | Learn X in Y Minutes"
+ Console.Title = "Hello World Output | Learn X in Y Minutes"
'Use Console.Write("") or Console.WriteLine("") to print outputs.
'Followed by Console.Read() alternatively Console.Readline()
'Console.ReadLine() prints the output to the console.
@@ -91,18 +91,18 @@ Module Module1
'Two
Private Sub HelloWorldInput()
Console.Title = "Hello World YourName | Learn X in Y Minutes"
- ' Variables
- ' Data entered by a user needs to be stored.
- ' Variables also start with a Dim and end with an As VariableType.
+ 'Variables
+ 'Data entered by a user needs to be stored.
+ 'Variables also start with a Dim and end with an As VariableType.
- ' In this tutorial, we want to know what your name, and make the program
- ' respond to what is said.
+ 'In this tutorial, we want to know what your name, and make the program
+ 'respond to what is said.
Dim username As String
'We use string as string is a text based variable.
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
username = Console.ReadLine() 'Stores the users name.
Console.WriteLine("Hello " + username) 'Output is Hello 'Their name'
- Console.ReadLine() 'Outsputs the above.
+ Console.ReadLine() 'Outputs the above.
'The above will ask you a question followed by printing your answer.
'Other variables include Integer and we use Integer for whole numbers.
End Sub
@@ -110,7 +110,7 @@ Module Module1
'Three
Private Sub CalculatingWholeNumbers()
Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes"
- Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect
+ Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104, etc
Dim a As Integer = Console.ReadLine()
Console.Write("Second number: ") 'Enter second whole number.
Dim b As Integer = Console.ReadLine()
@@ -126,10 +126,10 @@ Module Module1
'Of course we would like to be able to add up decimals.
'Therefore we could change the above from Integer to Double.
- 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect
+ 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9, etc
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
+ Console.Write("Second number: ") 'Enter second floating-point number.
Dim b As Double = Console.ReadLine
Dim c As Double = a + b
Console.WriteLine(c)
@@ -145,15 +145,15 @@ Module Module1
'Copy and paste the above again.
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Console.Write("Second number: ") 'Enter second floating-point number.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
'By adding the below lines we are able to calculate the subtract,
- 'multply as well as divide the a and b values
+ 'multiply as well as divide the a and b values
Console.Write(a.ToString() + " + " + b.ToString())
'We want to pad the answers to the left by 3 spaces.
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -179,11 +179,11 @@ Module Module1
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
Console.Write("Second number: ")
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
Console.Write(a.ToString() + " + " + b.ToString())
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -196,10 +196,10 @@ Module Module1
Console.ReadLine()
'Ask the question, does the user wish to continue? Unfortunately it
'is case sensitive.
- Console.Write("Would you like to continue? (yes / no)")
+ Console.Write("Would you like to continue? (yes / no) ")
'The program grabs the variable and prints and starts again.
answer = Console.ReadLine
- 'The command for the variable to work would be in this case "yes"
+ 'The command for the variable to work would be in this case "yes"
Loop While answer = "yes"
End Sub
@@ -211,7 +211,7 @@ Module Module1
Console.Title = "Using For Loops | Learn X in Y Minutes"
'Declare Variable and what number it should count down in Step -1,
- 'Step -2, Step -3 ect.
+ 'Step -2, Step -3, etc.
For i As Integer = 10 To 0 Step -1
Console.WriteLine(i.ToString) 'Print the value of the counter
Next i 'Calculate new value
@@ -222,7 +222,7 @@ Module Module1
'Eight
Private Sub ConditionalStatement()
Console.Title = "Conditional Statements | Learn X in Y Minutes"
- Dim userName As String = Console.ReadLine
+ Dim userName As String
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
userName = Console.ReadLine() 'Stores the users name.
If userName = "Adam" Then
@@ -238,36 +238,34 @@ Module Module1
'Nine
Private Sub IfElseStatement()
- Console.Title = "If / Else Statement | Learn X in Y Minutes"
+ Console.Title = "If / Else Statement | Learn X in Y Minutes"
'Sometimes it is important to consider more than two alternatives.
'Sometimes there are a good few others.
'When this is the case, more than one if statement would be required.
'An if statement is great for vending machines. Where the user enters a code.
- 'A1, A2, A3, ect to select an item.
- 'All choices can be combined into a single if statement.
+ 'A1, A2, A3, etc to select an item.
+ 'All choices can be combined into a single if block.
- Dim selection As String = Console.ReadLine 'Value for selection
- Console.WriteLine("A1. for 7Up")
- Console.WriteLine("A2. for Fanta")
- Console.WriteLine("A3. for Dr. Pepper")
- Console.WriteLine("A4. for Diet Coke")
- Console.ReadLine()
- If selection = "A1" Then
- Console.WriteLine("7up")
- Console.ReadLine()
- ElseIf selection = "A2" Then
- Console.WriteLine("fanta")
- Console.ReadLine()
- ElseIf selection = "A3" Then
- Console.WriteLine("dr. pepper")
- Console.ReadLine()
- ElseIf selection = "A4" Then
- Console.WriteLine("diet coke")
- Console.ReadLine()
- Else
- Console.WriteLine("Please select a product")
- Console.ReadLine()
- End If
+ Dim selection As String 'Declare a variable for selection
+ Console.WriteLine("Please select a product form our lovely vending machine.")
+ Console.WriteLine("A1. for 7Up")
+ Console.WriteLine("A2. for Fanta")
+ Console.WriteLine("A3. for Dr. Pepper")
+ Console.WriteLine("A4. for Diet Coke")
+
+ selection = Console.ReadLine() 'Store a selection from the user
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ ElseIf selection = "A4" Then
+ Console.WriteLine("diet coke")
+ Else
+ Console.WriteLine("Sorry, I don't have any " + selection)
+ End If
+ Console.ReadLine()
End Sub
diff --git a/whip.html.markdown b/whip.html.markdown
index 61c301a5..e7e5e427 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -9,7 +9,7 @@ filename: whip.lisp
---
Whip is a LISP-dialect made for scripting and simplified concepts.
-It has also borrowed a lot of functions and syntax from Haskell(a non-related language).
+It has also borrowed a lot of functions and syntax from Haskell (a non-related language).
These docs were written by the creator of the language himself. So is this line.
@@ -172,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set
; Comprehensions
; `range` or `..` generates a list of numbers for
-; each number between it's two args.
+; each number between its two args.
(range 1 5) ; => (1 2 3 4 5)
(.. 0 2) ; => (0 1 2)
-; `map` applies it's first arg(which should be a lambda/function)
-; to each item in the following arg(which should be a list)
+; `map` applies its first arg (which should be a lambda/function)
+; to each item in the following arg (which should be a list)
(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4)
; Reduce
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 6e3e2c94..507c4d1f 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -3,6 +3,7 @@ language: yaml
filename: learnyaml.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Suhas SG", "https://github.com/jargnar"]
---
YAML is a data serialisation language designed to be directly writable and
@@ -24,6 +25,8 @@ YAML doesn't allow literal tab characters at all.
key: value
another_key: Another value goes here.
a_number_value: 100
+# If you want to use number 1 as a value, you have to enclose it in quotes,
+# otherwise, YAML parser will assume that it is a boolean value of true.
scientific_notation: 1e+12
boolean: true
null_value: null
@@ -66,14 +69,19 @@ a_nested_map:
# Maps don't have to have string keys.
0.25: a float key
-# Keys can also be multi-line objects, using ? to indicate the start of a key.
+# Keys can also be complex, like multi-line objects
+# We use ? followed by a space to indicate the start of a complex key.
? |
This is a key
that has multiple lines
: and this is its value
-# YAML also allows collection types in keys, but many programming languages
-# will complain.
+# YAML also allows mapping between sequences with the complex key syntax
+# Some language parsers might complain
+# An example
+? - Manchester United
+ - Real Madrid
+: [ 2001-01-01, 2002-02-02 ]
# Sequences (equivalent to lists or arrays) look like this:
a_sequence:
@@ -101,12 +109,31 @@ json_seq: [3, 2, 1, "takeoff"]
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
+# Anchors can be used to duplicate/inherit properties
+base: &base
+ name: Everyone has same name
+
+foo: &foo
+ <<: *base
+ age: 10
+
+bar: &bar
+ <<: *base
+ age: 20
+
+# foo and bar would also have name: Everyone has same name
+
# YAML also has tags, which you can use to explicitly declare types.
explicit_string: !!str 0.5
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j
+# We can also use yaml complex keys with language specific tags
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Would be {(5, 7): 'Fifty Seven'} in python
+
####################
# EXTRA YAML TYPES #
####################
diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown
index c223297c..76455a46 100644
--- a/zh-cn/python3-cn.html.markdown
+++ b/zh-cn/python3-cn.html.markdown
@@ -535,7 +535,7 @@ Human.grunt() # => "*grunt*"
# 用import导入模块
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# 也可以从模块中导入个别值
from math import ceil, floor
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 28001e3f..3efe4941 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -5,7 +5,8 @@ contributors:
- ["Grant Timmerman", "http://github.com/grant"]
translators:
- ["Xavier Yao", "http://github.com/xavieryao"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["CY Lim", "http://github.com/cylim"]
lang: zh-cn
---
@@ -13,13 +14,13 @@ Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于20
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
-亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) ——一个完整的Swift 教程
+亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程
```swift
// 导入外部模块
import UIKit
-//
+//
// MARK: 基础
//
@@ -28,12 +29,14 @@ import UIKit
// TODO: TODO 标记
// FIXME: FIXME 标记
-println("Hello, world")
+// Swift2.0 println() 及 print() 已经整合成 print()。
+print("Hello, world") // 这是原本的 println(),会自动进入下一行
+print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
var myVariable = 42
-let øπΩ = "value" // 可以支持 unicode 变量名
+let øπΩ = "value" // 可以支持 unicode 变量名
let π = 3.1415926
let myConstant = 3.1415926
let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型
@@ -46,16 +49,17 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串
// 条件编译
// 使用 -D 定义编译开关
#if false
- println("Not printed")
+ print("Not printed")
let buildValue = 3
#else
let buildValue = 7
#endif
-println("Build value: \(buildValue)") // Build value: 7
+print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None
-
+ Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。
+ 可在值名称后加个问号 (?) 来表示这个值是 Optional。
+
Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil
Optional<T> 是个枚举类型
@@ -67,13 +71,17 @@ var someOptionalString2: Optional<String> = "optional"
if someOptionalString != nil {
// 变量不为空
if someOptionalString!.hasPrefix("opt") {
- println("has the prefix")
+ print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+ 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。
+*/
+
// 显式解包 optional 变量
var unwrappedString: String! = "Value is expected."
// 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖
@@ -94,7 +102,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
这里是注释
-
+
/*
支持嵌套的注释
*/
@@ -116,6 +124,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容
let emptyArray2 = Array<String>() // 与上一语句等价,上一语句更常用
var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素
+var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价
// 字典
var occupations = [
@@ -126,6 +135,7 @@ occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存
let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值
let emptyDictionary2 = Dictionary<String, Float>() // 与上一语句类型等价,上一语句更常用
var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
+var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价
//
@@ -136,21 +146,21 @@ var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
- println("One!")
+ print("One!")
} else {
- println("Not one!")
+ print("Not one!")
}
}
// 字典的 for 循环
var dict = ["one": 1, "two": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ print("\(key): \(value)")
}
// 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3)
for i in -1...shoppingList.count {
- println(i)
+ print(i)
}
shoppingList[1...2] = ["steak", "peacons"]
// 可以使用 `..<` 来去掉最后一个元素
@@ -163,7 +173,7 @@ while i < 1000 {
// do-while 循环
do {
- println("hello")
+ print("hello")
} while 1 == 2
// Switch 语句
@@ -177,7 +187,7 @@ case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(localScopeValue)?"
-default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
+default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
let vegetableComment = "Everything tastes good in soup."
}
@@ -219,8 +229,8 @@ let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// 通过下划线 (_) 来忽略不关心的值
let (_, price1, _) = pricesTuple // price1 == 3.69
-println(price1 == pricesTuple.1) // true
-println("Gas price: \(price)")
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
@@ -248,7 +258,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
var someIntA = 7
var someIntB = 3
swapTwoInts(&someIntA, &someIntB)
-println(someIntB) // 7
+print(someIntB) // 7
//
@@ -256,7 +266,7 @@ println(someIntB) // 7
//
var numbers = [1, 2, 6]
-// 函数是闭包的一个特例
+// 函数是闭包的一个特例 ({})
// 闭包实例
// `->` 分隔了闭包的参数和返回值
@@ -296,7 +306,7 @@ print(numbers) // [3, 6, 18]
struct NamesTable {
let names = [String]()
-
+
// 自定义下标运算符
subscript(index: Int) -> String {
return names[index]
@@ -306,7 +316,7 @@ struct NamesTable {
// 结构体有一个自动生成的隐含的命名构造函数
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
-println("Name is \(name)") // Name is Them
+print("Name is \(name)") // Name is Them
//
// MARK: 类
@@ -329,7 +339,7 @@ public class Shape {
internal class Rect: Shape {
// 值属性 (Stored properties)
var sideLength: Int = 1
-
+
// 计算属性 (Computed properties)
private var perimeter: Int {
get {
@@ -340,11 +350,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化
// subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例
lazy var subShape = Rect(sideLength: 4)
-
+
// 监控属性值的变化。
// 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数
// `willSet`: 值改变之前被调用
@@ -352,14 +362,14 @@ internal class Rect: Shape {
var identifier: String = "defaultID" {
// `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue`
willSet(someIdentifier) {
- println(someIdentifier)
+ print(someIdentifier)
}
// `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue`
didSet {
- println(oldValue)
+ print(oldValue)
}
}
-
+
// 命名构造函数 (designated inits),它必须初始化所有的成员变量,
// 然后调用父类的命名构造函数继续初始化父类的所有变量。
init(sideLength: Int) {
@@ -367,13 +377,13 @@ internal class Rect: Shape {
// 必须显式地在构造函数最后调用父类的构造函数 super.init
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
// 函数重载使用 override 关键字
override func getArea() -> Int {
return sideLength * sideLength
@@ -394,16 +404,16 @@ class Square: Rect {
}
var mySquare = Square()
-println(mySquare.getArea()) // 25
+print(mySquare.getArea()) // 25
mySquare.shrink()
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 类型转换
let aShape = mySquare as Shape
// 使用三个等号来比较是不是同一个实例
if mySquare === aShape {
- println("Yep, it's mySquare")
+ print("Yep, it's mySquare")
}
class Circle: Shape {
@@ -411,12 +421,12 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// optional 构造函数,可能会返回 nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -425,13 +435,13 @@ class Circle: Shape {
// 根据 Swift 类型推断,myCircle 是 Optional<Circle> 类型的变量
var myCircle = Circle(radius: 1)
-println(myCircle?.getArea()) // Optional(3)
-println(myCircle!.getArea()) // 3
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
-println(myEmptyCircle?.getArea()) // "nil"
+print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// 此语句不会输出,因为 myEmptyCircle 变量值为 nil
- println("circle is not nil")
+ print("circle is not nil")
}
@@ -461,7 +471,7 @@ enum BookName: String {
case John = "John"
case Luke = "Luke"
}
-println("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.John.rawValue)")
// 与特定数据类型关联的枚举
enum Furniture {
@@ -469,7 +479,7 @@ enum Furniture {
case Desk(height: Int)
// 和 String, Int 关联的枚举记录
case Chair(brand: String, height: Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -481,9 +491,9 @@ enum Furniture {
}
var desk: Furniture = .Desk(height: 80)
-println(desk.description()) // "Desk with 80 cm"
+print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair(brand: "Foo", height: 40)
-println(chair.description()) // "Chair of Foo with 40 cm"
+print(chair.description()) // "Chair of Foo with 40 cm"
//
@@ -512,7 +522,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -539,21 +549,21 @@ extension Square: Printable {
}
}
-println("Square: \(mySquare)") // Area: 16 - ID: defaultID
+print("Square: \(mySquare)") // Area: 16 - ID: defaultID
// 也可以给系统内置类型添加功能支持
extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
}
-println(7.customProperty) // "This is 7"
-println(14.multiplyBy(3)) // 42
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
@@ -566,7 +576,7 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
return nil
}
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
-println(foundAtIndex == 2) // true
+print(foundAtIndex == 2) // true
// 自定义运算符:
// 自定义运算符可以以下面的字符打头:
@@ -581,11 +591,24 @@ prefix func !!! (inout shape: Square) -> Square {
}
// 当前值
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 使用自定义的 !!! 运算符来把矩形边长放大三倍
!!!mySquare
-println(mySquare.sideLength) // 12
+print(mySquare.sideLength) // 12
-```
+// 运算符也可以是泛型
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
+
+```
diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown
new file mode 100644
index 00000000..553181d8
--- /dev/null
+++ b/zh-tw/python-tw.html.markdown
@@ -0,0 +1,727 @@
+---
+language: python
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "http://aminbandali.com"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+translators:
+ - ["Michael Yeh", "https://hinet60613.github.io/"]
+filename: learnpython-tw.py
+lang: zh-tw
+---
+
+Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。
+
+非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。
+
+註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。
+Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/).
+
+讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入
+ [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組.
+ `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。
+
+```python
+
+# 單行註解從井字號開始
+
+""" 多行字串可以用三個雙引號
+ 包住,不過通常這種寫法會
+ 被拿來當作多行註解
+"""
+
+####################################################
+## 1. 原始型別與運算元
+####################################################
+
+# 你可以使用數字
+3 # => 3
+
+# 還有四則運算
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# 除法比較麻煩,除以整數時會自動捨去小數位。
+5 / 2 # => 2
+
+# 要做精確的除法,我們需要浮點數
+2.0 # 浮點數
+11.0 / 4.0 # => 2.75 精確多了!
+
+# 整數除法的無條件捨去對正數或負數都適用
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮點數的整數也適用
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# 我們可以用除法模組(參考第六節:模組),讓
+# 單一斜線代表普通除法,而非無條件捨去
+from __future__ import division
+11/4 # => 2.75 ...普通除法
+11//4 # => 2 ...無條件捨去
+
+# 取餘數
+7 % 3 # => 1
+
+# 指數 (x的y次方)
+2**4 # => 16
+
+# 用括號改變運算順序
+(1 + 3) * 2 # => 8
+
+# 布林運算
+# 注意 "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取反向
+not True # => False
+not False # => True
+
+# 等於判斷是用 ==
+1 == 1 # => True
+2 == 1 # => False
+
+# 不等於判斷是用 !=
+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
+
+# 字串用單引號 ' 或雙引號 " 建立
+"This is a string."
+'This is also a string.'
+
+# 字串相加會被串接再一起
+"Hello " + "world!" # => "Hello world!"
+# 不用加號也可以做字串相加
+"Hello " "world!" # => "Hello world!"
+
+# ... 也可以做相乘
+"Hello" * 3 # => "HelloHelloHello"
+
+# 字串可以被視為字元的陣列
+"This is a string"[0] # => 'T'
+
+# 字串的格式化可以用百分之符號 %
+# 儘管在Python 3.1後這個功能被廢棄了,並且在
+# 之後的版本會被移除,但還是可以了解一下
+x = 'apple'
+y = 'lemon'
+z = "The items in the basket are %s and %s" % (x,y)
+
+# 新的格式化方式是使用format函式
+# 這個方式也是較為推薦的
+"{} is a {}".format("This", "placeholder")
+"{0} can be {1}".format("strings", "formatted")
+# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話
+"{name} wants to eat {food}".format(name="Bob", food="lasagna")
+
+# 無(None) 是一個物件
+None # => None
+
+# 不要用等於符號 "==" 對 無(None)做比較
+# 用 "is"
+"etc" is None # => False
+None is None # => True
+
+# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用,
+# 但對物件來說是很有用的。
+
+# 任何物件都可以被當作布林值使用
+# 以下的值會被視為是False :
+# - 無(None)
+# - 任何型別的零 (例如: 0, 0L, 0.0, 0j)
+# - 空序列 (例如: '', (), [])
+# - 空容器 (例如: {}, set())
+# - 自定義型別的實體,且滿足某些條件
+# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值).
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+## 2. 變數與集合
+####################################################
+
+# Python的輸出很方便
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# 從命令列獲得值也很方便
+input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數
+input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行
+# 注意: 請謹慎使用input()函式
+# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input()
+
+# 使用變數前不需要先宣告
+some_var = 5 # 方便好用
+lower_case_with_underscores
+some_var # => 5
+
+# 對沒有被賦值的變數取值會造成例外
+# 請參考錯誤流程部分做例外處理
+some_other_var # 造成 NameError
+
+# if可以當判斷式使用
+# 相當於C語言中的二元判斷式
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# 串列型態可以儲存集合
+li = []
+# 你可以預先填好串列內容
+other_li = [4, 5, 6]
+
+# 用append()在串列後新增東西
+li.append(1) # 此時 li 內容為 [1]
+li.append(2) # 此時 li 內容為 [1, 2]
+li.append(4) # 此時 li 內容為 [1, 2, 4]
+li.append(3) # 此時 li 內容為 [1, 2, 4, 3]
+# 用pop()移除串列尾端的元素
+li.pop() # => 3 ,此時 li 內容為 [1, 2, 4]
+# 然後再塞回去
+li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3]
+
+# 你可以像存取陣列一樣的存取串列
+li[0] # => 1
+# 用等號 = 給串列中特定索引的元素賦值
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # 註: 將其設定回原本的值
+# 用 -1 索引值查看串列最後一個元素
+li[-1] # => 3
+
+# 存取超過範圍會產生IndexError
+li[4] # Raises an 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[開始索引:結束索引:間隔]
+
+# 用 "del" 從串列中移除任意元素
+del li[2] # 現在 li 內容為 [1, 2, 3]
+
+# 你可以做串列相加
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# 註: li 及 other_li 沒有被更動
+
+# 用 "extend()" 做串列串接
+li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6]
+
+# 移除特定值的第一次出現
+li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6]
+li.remove(2) # 2 不在串列中,造成 ValueError
+
+# 在特定位置插入值
+li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6]
+
+# 取得特定值在串列中第一次出現的位置
+li.index(2) # => 1
+li.index(7) # 7 不在串列中,造成 ValueError
+
+# 用 "in" 檢查特定值是否出現在串列中
+1 in li # => True
+
+# 用 "len()" 取得串列長度
+len(li) # => 6
+
+
+# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # 產生TypeError
+
+# 能對串列做的東西都可以對tuple做
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 你可以把tuple拆開並分別將值存入不同變數
+a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3
+d, e, f = 4, 5, 6 # 也可以不寫括號
+# 如果不加括號,預設會產生tuple
+g = 4, 5, 6 # => (4, 5, 6)
+# 你看,交換兩個值很簡單吧
+e, d = d, e # 此時 d 的值為 5 且 e 的值為 4
+
+
+# 字典(Dictionary)用來儲存映射關係
+empty_dict = {}
+# 你可以對字典做初始化
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# 用 [] 取值
+filled_dict["one"] # => 1
+
+# 用 "keys()" 將所有的Key輸出到一個List中
+filled_dict.keys() # => ["three", "two", "one"]
+# 註: 字典裡key的排序是不固定的
+# 你的執行結果可能與上面不同
+# 譯註: 只能保證所有的key都有出現,但不保證順序
+
+# 用 "values()" 將所有的Value輸出到一個List中
+filled_dict.values() # => [3, 2, 1]
+# 註: 同上,不保證順序
+
+# 用 "in" 來檢查指定的Key是否在字典中
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 查詢不存在的Key會造成KeyError
+filled_dict["four"] # KeyError
+
+# 用 "get()" 來避免KeyError
+# 若指定的Key不存在的話會得到None
+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("four") 仍然為 None
+# (get()此時並沒有產生出任何的值)
+
+# 像操作list一樣,對指定的Key賦值
+filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4
+
+# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary
+filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5
+
+
+# 集合(Set)被用來儲存...集合。
+# 跟串列(List)有點像,但集合內不會有重複的元素
+empty_set = set()
+# 初始化 "set()" 並給定一些值
+some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入
+
+# 一樣,不保證順序,就算真的有照順序排也只是你運氣好
+another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4])
+
+# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# 加入更多元素進入Set
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+
+# 用 & 來對兩個集合取交集
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# 用 | 來對兩個集合取聯集
+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, 5}
+
+# 檢查左邊是否為右邊的母集
+{1, 2} >= {1, 2, 3} # => False
+
+# 檢查左邊是否為右邊的子集
+{1, 2} <= {1, 2, 3} # => True
+
+# 用 in 來檢查某元素是否存在於集合內
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. 控制流程
+####################################################
+
+# 首先,先宣告一個變數
+some_var = 5
+
+# 這邊是 if 判斷式。注意,縮排對Python是很重要的。
+# 下面應該會印出 "some_var is smaller than 10"
+if some_var > 10:
+ print "some_var is totally bigger than 10."
+elif some_var < 10: # elif 可有可無
+ print "some_var is smaller than 10."
+else: # else 也可有可無
+ print "some_var is indeed 10."
+
+
+"""
+For 迴圈會遞迴整的List
+下面的程式碼會輸出:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # 你可以用{0}來組合0出格式化字串 (見上面.)
+ print "{0} is a mammal".format(animal)
+
+"""
+"range(number)" 回傳一個包含從0到給定值的數字List,
+下面的程式碼會輸出:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print i
+
+"""
+"range(lower, upper)" 回傳一個包含從給定的下限
+到給定的上限的數字List
+下面的程式碼會輸出:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+While迴圈會執行到條件不成立為止
+下面的程式碼會輸出:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print x
+ x += 1 # x = x + 1 的簡寫
+
+# 用try/except處理例外
+
+# 適用Python 2.6及以上版本
+try:
+ # 用 "raise" 來發起例外
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理
+except (TypeError, NameError):
+ pass # 有需要的話,多種例外可以一起處理
+else: # else 可有可無,但必須寫在所有的except後
+ print "All good!" # 只有在try的時候沒有產生任何except才會被執行
+finally: # 不管什麼情況下一定會被執行
+ print "We can clean up resources here"
+
+# 除了try/finally以外,你可以用 with 來簡單的處理清理動作
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+####################################################
+## 4. 函式
+####################################################
+
+# 用 "def" 來建立新函式
+def add(x, y):
+ print "x is {0} and y is {1}".format(x, y)
+ return x + y # 用 "return" 來回傳值
+
+# 用參數來呼叫函式
+add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11
+
+# 你也可以寫上參數名稱來呼叫函式
+add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行
+
+
+# 你可以定義接受多個變數的函式,用*來表示參數tuple
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+
+# 你可以定義接受多個變數的函式,用**來表示參數dictionary
+def keyword_args(**kwargs):
+ return kwargs
+
+# 呼叫看看會發生什麼事吧
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# 如果你想要,你也可以兩個同時用
+def all_the_args(*args, **kwargs):
+ print args
+ print kwargs
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# 呼叫函式時,你可以做反向的操作
+# 用 * 將變數展開為順序排序的變數
+# 用 ** 將變數展開為Keyword排序的變數
+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)
+
+# 你可以把args跟kwargs傳到下一個函式內
+# 分別用 * 跟 ** 將它展開就可以了
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+# 函式範圍
+x = 5
+
+def set_x(num):
+ # 區域變數 x 和全域變數 x 不是同一個東西
+ x = num # => 43
+ print x # => 43
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # 全域變數 x 在set_global_x(6)被設定為 6
+ print x # => 6
+
+set_x(43)
+set_global_x(6)
+
+# Python有一級函式
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 也有匿名函式
+(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]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用
+[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. 類別
+####################################################
+
+# 我們可以由object繼承出一個新的類別
+class Human(object):
+
+ # 類別的參數,被所有這個類別的實體所共用
+ species = "H. sapiens"
+
+ # 基礎建構函式,當class被實體化的時候會被呼叫
+ # 注意前後的雙底線
+ # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用
+ def __init__(self, name):
+ # 將函式引入的參數 name 指定給實體的 name 參數
+ self.name = name
+
+ # 初始化屬性
+ self.age = 0
+
+
+ # 一個實體的方法(method)。 所有的method都以self為第一個參數
+ def say(self, msg):
+ return "{0}: {1}".format(self.name, msg)
+
+ # 一個類別方法會被所有的實體所共用
+ # 他們會以類別為第一參數的方式被呼叫
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # 靜態方法
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # 屬性就像是用getter取值一樣
+ # 它將方法 age() 轉為同名的、只能讀取的屬性
+ @property
+ def age(self):
+ return self._age
+
+ # 這樣寫的話可以讓屬性被寫入新的值
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # 這樣寫的話允許屬性被刪除
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# 將類別實體化
+i = Human(name="Ian")
+print i.say("hi") # prints out "Ian: hi"
+
+j = Human("Joel")
+print j.say("hello") # prints out "Joel: hello"
+
+# 呼叫類別方法
+i.get_species() # => "H. sapiens"
+
+# 更改共用的屬性
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# 呼叫靜態方法
+Human.grunt() # => "*grunt*"
+
+# 更新屬性
+i.age = 42
+
+# 取得屬性
+i.age # => 42
+
+# 移除屬性
+del i.age
+i.age # => raises an AttributeError
+
+
+####################################################
+## 6. 模組
+####################################################
+
+# 你可以引入模組來做使用
+import math
+print math.sqrt(16) # => 4
+ # math.sqrt()為取根號
+
+# 你可以只從模組取出特定幾個函式
+from math import ceil, floor
+print ceil(3.7) # => 4.0
+print floor(3.7) # => 3.0
+
+# 你可以將所有的函式從模組中引入
+# 注意:不建議這麼做
+from math import *
+
+# 你可以用 as 簡寫模組名稱
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+# 你也可以測試函示是否相等
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
+
+# Python的模組就只是一般的Python檔。
+# 你可以自己的模組自己寫、自己的模組自己引入
+# 模組的名稱和檔案名稱一樣
+
+# 你可以用dir()來查看有哪些可用函式和屬性
+import math
+dir(math)
+
+
+####################################################
+## 7. 進階
+####################################################
+
+# 產生器(Generator)可以讓你寫更懶惰的程式碼
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 產生器可以讓你即時的產生值
+# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時
+# 產生值。 這也意味著大於15的值不會在double_numbers中產生。
+# 這邊,xrange()做的事情和range()一樣
+# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間
+# xrange() 建立一個產生器物件,而不是如range()建立整個List
+# 我們用底線來避免可能和python的關鍵字重複的名稱
+xrange_ = xrange(1, 900000000)
+
+# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值
+for i in double_numbers(xrange_):
+ print i
+ if i >= 30:
+ break
+
+
+# 裝飾子
+# 在這個範例中,beg會綁在say上
+# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print say() # Can you buy me a beer?
+print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
+```
+
+## 準備好學更多了嗎?
+
+### 線上免費資源
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [The Official Docs](http://docs.python.org/2/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### 或買本書?
+
+* [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)