From 283bac48db7ba2a12f1d7ee134ddaa9c38ef0939 Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:02:33 +0300 Subject: add untranslated file to ro-ro folder Add the original untranslated file to the ro-ro folder and rename it to respect the correct naming structure. --- ro-ro/json-ro.html.markdown | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 ro-ro/json-ro.html.markdown diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown new file mode 100644 index 00000000..f57b82b8 --- /dev/null +++ b/ro-ro/json-ro.html.markdown @@ -0,0 +1,58 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +--- + +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 in its purest form has no actual comments, but most parsers will accept +C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is +going to be 100% valid JSON. Luckily, it kind of speaks for itself. + +```json +{ + "key": "value", + + "keys": "must always be enclosed in double quotes", + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternative style": { + "comment": "check this out!" + , "comma position": "doesn't matter - as long as its before the value, then its valid" + , "another comment": "how nice" + }, + + "that was short": "And, you're done. You now know everything JSON has to offer." +} +``` -- cgit v1.2.3 From 52c567f664d3e2b79b094aa8e25a41685e34e57b Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:06:35 +0300 Subject: update header --- ro-ro/json-ro.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown index f57b82b8..7042dde7 100644 --- a/ro-ro/json-ro.html.markdown +++ b/ro-ro/json-ro.html.markdown @@ -1,9 +1,12 @@ --- language: json -filename: learnjson.json +filename: learnjson-ro.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Serban Constantin", "https://github.com/fuzzmz"] +lang: ro-ro --- As JSON is an extremely simple data-interchange format, this is most likely going -- cgit v1.2.3 From d5f62046c37de1b18bd2d5771314e1cc7b9be06a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:19:11 +0300 Subject: translate to romanian --- ro-ro/json-ro.html.markdown | 48 ++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown index 7042dde7..e897059c 100644 --- a/ro-ro/json-ro.html.markdown +++ b/ro-ro/json-ro.html.markdown @@ -9,38 +9,38 @@ translators: lang: ro-ro --- -As JSON is an extremely simple data-interchange format, this is most likely going -to be the simplest Learn X in Y Minutes ever. +Deoarece JSON este un fromat foarte simplu de schimb de date acesta va fi +probabil cel mai simplu Invata X in Y minute. -JSON in its purest form has no actual comments, but most parsers will accept -C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is -going to be 100% valid JSON. Luckily, it kind of speaks for itself. +JSON in forma cea mai pura nu contine comentarii insa majoritatea parserelor +vor accepta comentarii in stil C (`//`, `/* */`). Pentru acest caz insa totul +va fi JSON 100% valid. Din fericire codul vorbeste de la sine. ```json { - "key": "value", + "cheie": "valoare", - "keys": "must always be enclosed in double quotes", - "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", - "has bools?": true, - "nothingness": null, + "chei": "trebuie mereu inconjurate de ghilimele", + "numere": 0, + "stringuri": "Bunã. Tot setul unicode este permis, chiar si \"escaping\".", + "are booleane?": true, + "nimic": null, - "big number": 1.2e+100, + "numere mari": 1.2e+100, - "objects": { - "comment": "Most of your structure will come from objects.", + "obiecte": { + "comentariu": "Majoritatea structurii va veni din obiecte.", - "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + "vectori": [0, 1, 2, 3, "Vectorii pot avea orice in ei.", 5], - "another object": { - "comment": "These things can be nested, very useful." + "alt obiect": { + "comentariu": "Lucrurile pot fi subordonate. Foarte util." } }, - "silliness": [ + "glumite": [ { - "sources of potassium": ["bananas"] + "surse de potasiu": ["banane"] }, [ [1, 0, 0, 0], @@ -50,12 +50,12 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. ] ], - "alternative style": { - "comment": "check this out!" - , "comma position": "doesn't matter - as long as its before the value, then its valid" - , "another comment": "how nice" + "stil alternativ": { + "comentariu": "ia uite la asta!" + , "pozitia virgulei": "nu conteaza - daca e inaintea valorii atunci e valida" + , "alt comentariu": "ce dragut" }, - "that was short": "And, you're done. You now know everything JSON has to offer." + "a fost scurt": "Am terminat. Acum stii tot ce are JSON de oferit." } ``` -- cgit v1.2.3 From 556758b3ae16c2441a96edb85e72b3c170b53d7a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:24:36 +0300 Subject: add untranslated file to ro-ro folder Add the original untranslated file to the ro-ro folder and rename it to respect the correct naming structure. --- ro-ro/xml-ro.html.markdown | 126 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 ro-ro/xml-ro.html.markdown diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown new file mode 100644 index 00000000..fce1a3a4 --- /dev/null +++ b/ro-ro/xml-ro.html.markdown @@ -0,0 +1,126 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +--- + +XML is a markup language designed to store and transport data. + +Unlike HTML, XML does not specify how to display or to format data, just carry it. + +* XML Syntax + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Well-Formated Document x Validation + +A XML document is well-formated if it is syntactically correct. +However, it is possible to inject more constraints in the document, +using document definitions, such as DTD and XML Schema. + +A XML document which follows a document definition is called valid, +regarding that document. + +With this tool, you can check the XML data outside the application logic. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 1b799a72998e36f38086db7facc945ce63f1f66a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:26:20 +0300 Subject: update header --- ro-ro/xml-ro.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown index fce1a3a4..578b430e 100644 --- a/ro-ro/xml-ro.html.markdown +++ b/ro-ro/xml-ro.html.markdown @@ -1,8 +1,11 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-ro.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Serban Constantin", "https://github.com/fuzzmz"] +lang: ro-ro --- XML is a markup language designed to store and transport data. -- cgit v1.2.3 From 66f7710f6f6af18431b99ab46c40338b362af58a Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Wed, 30 Sep 2015 20:53:45 +0300 Subject: add translated file --- ro-ro/xml-ro.html.markdown | 166 +++++++++++++++++++++++---------------------- 1 file changed, 85 insertions(+), 81 deletions(-) diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown index 578b430e..269010c2 100644 --- a/ro-ro/xml-ro.html.markdown +++ b/ro-ro/xml-ro.html.markdown @@ -8,122 +8,126 @@ translators: lang: ro-ro --- -XML is a markup language designed to store and transport data. +XML este un limbaj de markup ce are ca scop stocarea si transportul de date. -Unlike HTML, XML does not specify how to display or to format data, just carry it. +Spre deosebire de HTML, XML nu specifica cum sa fie afisata sau formatata +informatia, ci doar o transporta. -* XML Syntax +* Sintaxa XML ```xml - + - - - Everyday Italian - Giada De Laurentiis - 2005 - 30.00 - - - Harry Potter - J K. Rowling - 2005 - 29.99 - - - Learning XML - Erik T. Ray - 2003 - 39.95 - - - - - - - + XML foloseste o structura arborescenta. Deasupra, nodul de baza este + 'librarie', care are trei noduri copil, toate 'carti'. Acele noduri au la + randul lor noduri copii si asa mai departe... + + Nodurile sunt create folosind taguri deschise/inchise, iar copii sunt doar + noduri intre tagurile de deschis si inchis.--> + + + - + computer.gif ``` -* Well-Formated Document x Validation +* Document bine formatat x Validare -A XML document is well-formated if it is syntactically correct. -However, it is possible to inject more constraints in the document, -using document definitions, such as DTD and XML Schema. +Un document XML este bine formatat daca este corect sintactic. +Cu toate astea este posibil sa injectam mai multe constrangeri in document +folosind definitii precum DTD si XML Schema. -A XML document which follows a document definition is called valid, -regarding that document. +Un document XML ce foloseste o definitie de document este numit valid in +contextul documentului. -With this tool, you can check the XML data outside the application logic. +Cu acest tool poti verifica datele XML in afara codului aplicatiei. ```xml - + - - - - Everyday Italian - 30.00 - - + + + + Everyday Italian + 30.00 + + - + - - - - + + + + + ]> - + - + - - - - + + + + + ]> - - - Everyday Italian - 30.00 - - + + + Everyday Italian + 30.00 + + ``` -- cgit v1.2.3 From 13807790e46d4b75b90d6da17e6c28f4ed9e5a49 Mon Sep 17 00:00:00 2001 From: DaKnOb Date: Fri, 2 Oct 2015 16:42:57 +0300 Subject: Add note about Python Module Order of Import --- python.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 352f7349..e306dabd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -569,6 +569,12 @@ math.sqrt == m.sqrt == sqrt # => True import math dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + #################################################### ## 7. Advanced -- cgit v1.2.3 From d1a143aed5c7b48888eccb690bf3bf69ae3667bc Mon Sep 17 00:00:00 2001 From: Mathieu De Coster Date: Sat, 3 Oct 2015 12:26:48 +0200 Subject: Add translation to Dutch for json --- nl-nl/json.html.markdown | 61 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 nl-nl/json.html.markdown diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown new file mode 100644 index 00000000..f025481a --- /dev/null +++ b/nl-nl/json.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Mathieu De Coster", "https://github.com/m-decoster"] +lang: nl-nl +--- + +Aangezien JSON een extreem eenvoudig data-uitwisselingsformaat is, zal dit waarschijnlijk +de meest eenvoudige Learn X in Y Minutes ooit zijn. + +Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl +van C (`//`, `/* */`) aanvaarden. In dit voorbeeld zal alles 100% correcte JSON zijn. +Gelukkig spreekt het meeste voor zichzelf. + +```json +{ + "key": "value", + + "keys": "moeten altijd tussen dubbele aanhalingstekens staan", + "getallen": 0, + "strings": "Hellø, world. Alle unicode karakters zijn toegelaten, zo ook \"escaping\".", + "heeft json booleans?": true, + "niets": null, + + "groot getal": 1.2e+100, + + "objecten": { + "commentaar": "De meeste structuur wordt gemaakt met objecten.", + + "array": [0, 1, 2, 3, "Arrays kunnen eender wat bevatten.", 5], + + "nog een object": { + "commentaar": "Hoe handig, we kunnen objecten nesten." + } + }, + + "dwaasheid": [ + { + "bronnen van kalium": ["banenen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatieve stijl": { + "commentaar": "kijk hier eens naar!" + , "komma locatie": "maakt niet uit - zo lang het voor de value komt, is alles in orde" + , "nog commentaar": "hoe leuk" + }, + + "dat was kort": "Je bent klaar. Je kent nu alles dat JSON kan aanbieden." +} +``` -- cgit v1.2.3 From c2e9577626d60a04409c8568b3fc8ae3d3ef5e96 Mon Sep 17 00:00:00 2001 From: Mathieu De Coster Date: Sat, 3 Oct 2015 12:33:33 +0200 Subject: Fix typo's in nl-nl/json --- nl-nl/json.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown index f025481a..a82f13c4 100644 --- a/nl-nl/json.html.markdown +++ b/nl-nl/json.html.markdown @@ -9,7 +9,7 @@ translators: lang: nl-nl --- -Aangezien JSON een extreem eenvoudig data-uitwisselingsformaat is, zal dit waarschijnlijk +Aangezien JSON een extreem eenvoudig datauitwisselingsformaat is, zal dit waarschijnlijk de meest eenvoudige Learn X in Y Minutes ooit zijn. Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl @@ -22,7 +22,7 @@ Gelukkig spreekt het meeste voor zichzelf. "keys": "moeten altijd tussen dubbele aanhalingstekens staan", "getallen": 0, - "strings": "Hellø, world. Alle unicode karakters zijn toegelaten, zo ook \"escaping\".", + "strings": "Hellø, world. Alle Unicode-karakters zijn toegelaten, zo ook \"escaping\".", "heeft json booleans?": true, "niets": null, @@ -40,7 +40,7 @@ Gelukkig spreekt het meeste voor zichzelf. "dwaasheid": [ { - "bronnen van kalium": ["banenen"] + "bronnen van kalium": ["bananen"] }, [ [1, 0, 0, 0], -- cgit v1.2.3 From aae89cbb3f146a2fa001430921870962f7af3597 Mon Sep 17 00:00:00 2001 From: Lari Kovanen Date: Sat, 3 Oct 2015 15:40:54 +0200 Subject: [json/sv] Translated to swedish Translated the english JSON document to swedish. --- sv-se/json-sv.html.markdown | 62 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sv-se/json-sv.html.markdown diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown new file mode 100644 index 00000000..8b76ebad --- /dev/null +++ b/sv-se/json-sv.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Lari Kovanen", "https://github.com/larkov"] +lang: sv-se +--- + +Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta +förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin. + +JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar +C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa +100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. + + +```json +{ + "nyckel": "värde", + + "nycklar": "måste alltid omslutas med dubbla citationstecken", + "nummer": 0, + "strängar": "Alla unicode-tecken (inklusive \"escaping\") är tillåtna.", + "boolska värden?": true, + "nullvärden": null, + + "stora tal": 1.2e+100, + + "objekt": { + "kommentar": "Det flesta datastukturerna i JSON kommer i form av objekt.", + + "matris": [0, 1, 2, 3, "Matriser kan innehålla vad som helst.", 5], + + "ytterligare objekt": { + "kommentar": "Objekten kan vara nästlade." + } + }, + + "trams": [ + { + "kaliumkällor": ["bananer"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativ formatering": { + "kommentar": "kolla på detta!" + , "kommats position": "spelar ingen roll - så länge det kommer innan värdet" + , "en kommentar till": "vad fint" + }, + + "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda." +} +``` -- cgit v1.2.3 From 6dabd9568d2a99e7bbc079d0466588bf68a42283 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Mon, 5 Oct 2015 10:15:07 +0200 Subject: Brainfuck cs_CZ translation --- cs-cz/brainfuck.html.markdown | 87 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 cs-cz/brainfuck.html.markdown diff --git a/cs-cz/brainfuck.html.markdown b/cs-cz/brainfuck.html.markdown new file mode 100644 index 00000000..92424ecf --- /dev/null +++ b/cs-cz/brainfuck.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +filename: learnbrainfuck.bf +lang: cs-cz +--- + +Brainfuck (psaný bez kapitálek s vyjímkou začátku věty) je extrémně minimální +Turingovsky kompletní (ekvivalentní) programovací jazyk a má pouze 8 příkazů. + +Můžete si ho vyzkoušet přímo v prohlížeči s [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Jakýkoliv znak mimo "><+-.,[]" (bez uvozovek) je ignorován. + +Brainfuck je reprezentován jako pole, které má 30.000 buněk s počátkem v nule +a datovým ukazatelem na aktuální buňce. + +Můžeme využít těchto osm příkazů: ++ : Přičte k aktuální buňce jedničku. +- : Odečte od aktuální buňky jedničku. +> : Posune datový ukazatel na další buňku, která je napravo. +< : Posune datový ukazatel na předchozí buňku, která je nalevo. +. : Vytiskne ASCII hodnotu aktuální buňky (například 65 = 'A'). +, : Načte jeden znak do aktuální buňky. +[ : Pokud je hodnota aktuální buňky nulová, přeskočí na buňku odpovídající ] . + Jinak skočí na další instrukci. +] : Pokud je hodnota aktuální buňky nulova, přeskočí na další instrukci. + Jinak skočí zpět na instrukci odpovídající [ . + +[ a ] tak tvoří 'while' smyčku a tyto symboly musí tak být v páru. + +Pojďme se mrknout na některé brainfuck programy. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Tento program vypíše písmeno 'A' (v ASCII je to číslo 65). Nejdříve navýší +buňku #1 na hodnotu 6. Buňka #1 bude použita pro smyčku. Potom program vstoupí +do smyčky ([) a sníží hodnotu buňky #1 o jedničku. Ve smyčce zvýší hodnotu +buňky #2 desetkrát, vrátí ze zpět na buňku #1 a sníží její hodnotu o jedničku. +Toto se stane šestkrát (je potřeba šestkrát snížit hodnotu buňky #1, aby byla +nulová a program přeskočil na konec cyklu označený znakem ]. + +Na konci smyčky, kdy jsme na buňce #1 (která má hodnotu 0), tak má buňka #2 +hodnotu 60. Přesuneme se na buňku #2 a pětkrát zvýšíme její hodnotu o jedničku +na hodnotu 65. Na konci vypíšeme hodnotu buňky #2 - 65, což je v ASCII znak 'A' +na terminálu. + + +, [ > + < - ] > . + +Tento program přečte znak z uživatelského vstupu a zkopíruje ho do buňky #1. +Poté začne smyčka - přesun na buňku #2, zvýšení hodnoty buňky #2 o jedničku, +přesun zpět na buňku #1 a snížení její hodnoty o jedničku. Takto smyčka pokračuje +do té doby, než je buňka #1 nulová a buňka #2 nabyde původní hodnotu buňky #1. +Protože jsme na buňce #1, přesuneme se na buňku #2 a vytiskneme její hodnotu +v ASCII. + +Je dobré vědět, že mezery jsou v programu uvedené pouze z důvodu čitelnosti. +Program je možné klidně zapsat i takto: + +,[>+<-]>. + + +Nyní se podívejte na tento program a zkuste zjistit co dělá: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Tento program vezme dvě čísla ze vstupu a vynásobí je. + +Program nejdříve načte dvě vstupní hodnoty. Poté začíná smyčka řízená hodnotou +v buňce #1 - přesun na buňku #2 a start druhé vnořené smyčky, která je řízená +hodnotou v buňce #2 a zvyšuje hodnotu v buňce #3. Nicméně je zde problém +kdy na konci vnitřní smyčky je v buňce #2 nula a smyčka by tak znovu +napokračovala. Vyřešíme to tak, že zvyšujeme o jedničku i buňku #4 a její +hodnotu poté překopírujeme do buňky #2. Na konci programu je v buňce #3 +výsledek. +``` + +A to je brainbuck. Zase tak složitý není, co? Zkuste si nyní napsat nějaký +vlastní brainfuck program a nebo interpretr v jiném jazyce, což není zase +tak složité, ale pokud jste opravdový masochista, zkuste si naprogramovat +interpretr jazyka brainfuck v jazyce... brainfuck :) -- cgit v1.2.3 From 4d619e9b0fc4a061fa720b47b22068c8661e9be6 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Wed, 7 Oct 2015 10:22:08 +0200 Subject: [json/cs] JSON translation to cs_CZ --- cs-cz/json.html.markdown | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 cs-cz/json.html.markdown diff --git a/cs-cz/json.html.markdown b/cs-cz/json.html.markdown new file mode 100644 index 00000000..8a685524 --- /dev/null +++ b/cs-cz/json.html.markdown @@ -0,0 +1,63 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +filename: learnjson.json +lang: cs-cz +--- + +JSON je exterémně jednoduchý datově nezávislý formát a bude asi jeden z +nejjednodušších 'Learn X in Y Minutes' ze všech. + +JSON nemá ve své nejzákladnější podobě žádné komentáře, ale většina parserů +umí pracovat s komentáři ve stylu jazyka C (`//`, `/* */`). Pro tyto účely +však budeme používat 100% validní JSON bez komentářů. Pojďme se podívat na +syntaxi formátu JSON: + +```json +{ + "klic": "value", + + "hodnoty": "Musí být vždy uvozený v dvojitých uvozovkách", + "cisla": 0, + "retezce": "Hellø, wørld. Všechny unicode znaky jsou povolené, společně s \"escapováním\".", + "pravdivostni_hodnota": true, + "prazdna_hodnota": null, + + "velke_cislo": 1.2e+100, + + "objekt": { + "komentar": "Most of your structure will come from objects.", + + "pole": [0, 1, 2, 3, "Pole nemusí být pouze homogenní.", 5], + + "jiny_objekt": { + "comment": "Je povolené jakkoli hluboké zanoření." + } + }, + + "cokoli": [ + { + "zdroje_drasliku": ["banány"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativni_styl_zapisu": { + "komentar": "Mrkni se na toto!" + , "pozice_carky": "Na pozici čárky nezáleží - pokud je před hodnotou, ať už je kdekoli, tak je validní." + , "dalsi_komentar": "To je skvělé." + }, + + "to_bylo_rychle": "A tím jsme hotový. Nyní již víte vše, co může formát JSON nabídnout!" +} +``` -- cgit v1.2.3 From 3c1e9a8bc06b654cd812306ed90ca61e9d8bb3eb Mon Sep 17 00:00:00 2001 From: davidsonmizael Date: Thu, 8 Oct 2015 00:33:55 -0300 Subject: Adding bash tutorial in pt-br --- pt-br/bash-pt.html.markdown | 282 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 pt-br/bash-pt.html.markdown diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown new file mode 100644 index 00000000..a604e7b8 --- /dev/null +++ b/pt-br/bash-pt.html.markdown @@ -0,0 +1,282 @@ +--- +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/"] +translators: + - ["Davidson Mizael", "https://github.com/davidsonmizael"] +filename: LearnBash-pt_br.sh +lang: pt-br +--- + +Tutorial de shell em português + +Bash é o nome do shell do Unix, que também é distribuido como shell do sistema +operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos +os exemplos abaixo podem fazer parte de um shell script e pode ser executados +diretamente no shell. + +[Leia mais sobre](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# A primeira linha do script é o shebang, que conta para o sistema como executar +# o script: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Como você já deve ter percebido, comentários começam com #. +# Shebang também é um comentário. + +# Exemplo simples de hello world: +echo Hello World! + +# Cada comando começa com uma nova linha, ou após um ponto virgula: +echo 'Essa é a primeira linha'; echo 'Essa é a segunda linha' + +# A declaração de variáveis é mais ou menos assim +Variavel="Alguma string" + +# Mas não assim: +Variavel = "Alguma string" +# Bash interpretará Variavel como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. + +# Ou assim: +Variavel= 'Alguma string' +# Bash interpretará 'Alguma string' como um comando e tentará executar e lhe retornar +# um erro porque o comando não pode ser encontrado. (Nesse caso a a parte 'Variavel=' +# é vista com uma declaração de variável valida apenas para o escopo do comando 'Uma string'). + +# Usando a variável: +echo $Variavel +echo "$Variavel" +echo '$Variavel' +# Quando você usa a variável em si — declarando valor, exportando, etc — você escreve +# seu nome sem o $. Se você quer usar o valor da variável você deve usar o $. +# Note que ' (aspas simples) não expandirão as variáveis! + +# Substituição de strings em variáveis +echo ${Variavel/Alguma/Uma} +# Isso substituirá a primeira ocorrência de "Alguma" por "Uma" + +# Substring de uma variável +Tamanho=7 +echo ${Variavel:0:Tamanho} +# Isso retornará apenas os 7 primeiros caractéres da variável + +# Valor padrão de uma variável +echo ${Foo:-"ValorPadraoSeFooNaoExistirOuEstiverVazia"} +# Isso funciona para nulo (Foo=) e (Foo=""); zero (Foo=0) retorna 0. +# Note que isso apenas retornar o valor padrão e não mudar o valor da variável. + +# Variáveis internas +# Tem algumas variáveis internas bem uteis, como +echo "O ultimo retorno do programa: $?" +echo "PID do script: $$" +echo "Numero de argumentos passados para o script $#" +echo "Todos os argumentos passados para o script $@" +echo "Os argumentos do script em variáveis diferentes: $1, $2..." + +# Lendo o valor do input: +echo "Qual o seu nome?" +read Nome # Note que nós não precisamos declarar a variável +echo Ola, $Nome + +# Nós temos a estrutura if normal: +# use 'man test' para mais infomações para as condicionais +if [ $Nome -ne $USER ] +then + echo "Seu nome não é o seu username" +else + echo "Seu nome é seu username" +fi + +# Tem também execução condicional +echo "Sempre executado" || echo "Somente executado se o primeiro falhar" +echo "Sempre executado" && "Só executado se o primeiro NÃO falhar" + +# Para usar && e || com o if, você precisa multiplicar os pares de colchetes +if [ $Nome == "Estevao"] && [ $Idade -eq 15] +then + echo "Isso vai rodar se $Nome é igual Estevao E $Idade é 15." +fi + +fi [ $Nome == "Daniela" ] || [ $Nome = "Jose" ] +then + echo "Isso vai rodar se $Nome é Daniela ou Jose." +fi + +# Expressões são denotadas com o seguinte formato +echo $(( 10 + 5)) + +# Diferentemente das outras linguagens de programação, bash é um shell, então ele +# funciona no diretório atual. Você pode listar os arquivos e diretórios no diretório +# atual com o comando ls: +ls + +#Esse comando tem opções que controlam sua execução +ls -l # Lista todo arquivo e diretorio em linhas separadas + +# Os resultados do comando anterior pode ser passado para outro comando como input. +# O comando grep filtra o input com o padrão passado. É assim que listamos apenas +# os arquivos .txt no diretório atual: +ls -l | grep "\.txt" + +# Você pode redirecionar o comando de input e output (stdin, stdout e stderr). +# Lê o stdin até ^EOF$ e sobrescreve hello.py com as linhas entre "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ imprt 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 + +# Rode hello.py com várias instruções stdin, stdout e stderr: +python hello.py < "input.in" +python hello.py > "ouput.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# O erro no output sobrescreverá o arquivo se existir, +# se ao invés disso você quiser complementar, use ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Sobrescreve output.out, complemente para error.err e conta as linhas +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +#Roda um comando e imprime o desencriptador (e.g. /dev/fd/123) +# veja: man fd +echo <(echo "#helloworld") + +# Sobrescreve ouput.out com "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out > /dev/null + +# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +rm -v output.out error.err output-and-error.log + +# Comando podem ser substituidos por outros comandos usando $( ): +# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +echo "Existem $(ls | wc -l) itens aqui." + +# O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se +# preferência ao uso do $( ) +echo "Existem `ls | wc -l` itens aqui." + +# Bash usa o comando case que funciona de uma maneira similar ao switch de Java e C++: +case "$Variavel" in + # Lista de parametros para condições que você quer encontrar + 0) echo "Isso é um Zero.";; + 1) echo "Isso é um Um.";; + *) echo "Isso não é null.";; +esac + +# loops for iteragem para quantos argumentos passados: +# O conteudo de $Variavel é exibido três vezes. +for Variavel in {1..3} +do + echo "$Variavel" +done + +# Ou use o loop da "maneira tradicional": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Eles também podem ser usados em arquivos... +# Isso irá rodar o comando 'cat' em arquivo1 e arquivo2 +for Variavel in arquivo1 arquivo2 +do + cat "$Variavel" +done + +# ...ou o output de um comando +# Isso irá usar cat no output do ls. +for Output in $(ls) +do + cat "$Output" +done + +# loop while: +while [ true ] +do + echo "corpo do loop aqui..." + break +done + +# Você também pode usar funções +# Definição: +function foo() { + echo "Argumentos funcionam bem assim como os dos scripts: $@" + echo "E: $1 $2..." + echo "Isso é uma função" + return 0 +} + +# ou simplesmente +bar () { + echo "Outro jeito de declarar funções!" + return 0 +} + +# Chamando sua função +foo "Meu nome é" $Nome + +# Existe um monte de comandos úteis que você deveria aprender: +# exibe as 10 ultimas linhas de arquivo.txt +tail -n 10 arquivo.txt +# exibe as primeiras 10 linhas de arquivo.txt +head -n 10 arquivo.txt +# ordena as linhas de arquivo.txt +sort arquivo.txt +# reporta ou omite as linhas repetidas, com -d você as reporta +uniq -d arquivo.txt +# exibe apenas a primeira coluna após o caráctere ',' +cut -d ',' -f 1 arquivo.txt +# substitui todas as ocorrencias de 'okay' por 'legal' em arquivo.txt (é compativel com regex) +sed -i 's/okay/legal/g' file.txt +# exibe para o stdout todas as linhas do arquivo.txt que encaixam com o regex +# O exemplo exibe linhas que começam com "foo" e terminam com "bar" +grep "^foo.*bar$" arquivo.txt +# passe a opção "-c" para ao invês de imprimir o numero da linha que bate com o regex +grep -c "^foo.*bar$" arquivo.txt +# se você quer literalmente procurar por uma string, +# e não pelo regex, use fgrep (ou grep -F) +fgrep "^foo.*bar$" arquivo.txt + + +# Leia a documentação interna do shell Bash com o comando interno 'help': +help +help help +help for +help return +help source +help . + +# Leia a página principal da documentação com man +apropos bash +man 1 bash +man bash + +# Leia a documentação de informação com info (? para ajuda) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +#Leia a documentação informativa do Bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 2813f49b8a00afc50a8cbcb1ac2960d594e5db9e Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Fri, 9 Oct 2015 10:50:34 +0200 Subject: First version of a german translation of the Tcl page --- de-de/tcl-de.html.markdown | 474 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 474 insertions(+) create mode 100644 de-de/tcl-de.html.markdown diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown new file mode 100644 index 00000000..1e24e379 --- /dev/null +++ b/de-de/tcl-de.html.markdown @@ -0,0 +1,474 @@ +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: learntcl-de.tcl +--- + +Tcl wurde kreiert von [John Ousterhout](http://wiki.tcl.tk/John Ousterout) als +eine wiederverwendbare Script-Sprache für Chip-Design Werkzeuge die er kreiert +hat. Im Jahre 1997 wurde er mit dem [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) für Tcl +ausgezeichnet. Tcl kann sowohl als eingebettete Scipt-Sprache als auch als +allgemeine Programmier-Sprache verwendet werden. Tcl kann auch als portable +C-Bibliothek verwendet werden. Sogar in Fällen in denen die Script-Fähigkeiten +nicht nötig sind. Denn Tcl stellt Daten-Strukturen wie dynamische Zeichenketten, +Listen und Hash-Tabellen bereit. Die C-Bilbiothek stellt auch portable +Funktionen zur Verfügung: Laden von dynamischen Bibliotheken, Zeichenketten +formatierung und Code Konversion, Dateisystem Operationen, Netzwerk Operationen +und mehr. + + +Verschiedenste herausragende Fähigkeiten von Tcl: + +* Praktische Cross-Platform Netzwerk-API + +* Vollständig virtualisiertes Dateisystem + +* Stapelbare I/O Kanäle + +* Asynchron bis zum Kern + +* Vollständige Ko-Routinen + +* Robustes und einfach zu verwendendes Thread-Modell + + +Wenn Lisp ein Listen-Prozessor ist, dann ist TCl ein Zeichenketten-Prozessor. +Alle Werte sind Zeichenketten. Eine Liste ist ein Zeichenketten-Format. Eine +Prozedur-Definition ist ein Zeichenketten-Format. Um leistungsfähig zu sein, +werden Tcl-intern diese Zeichenketten in Strukutierter-Form gepuffert. Ein +Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten +Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen +zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren- +beim-Schreiben-Design von Tcl erlaubt es Skript-Authoren mit großen Daten- +Strukturen zu arbeiten ohne zuätzlichen Speicher-Overhead. Prozeduren werden +automatisch byte-kompiliert außer sie verwenden dynamsiche Befehle wie zum +Beispiel "uplevel", "upvar und "trace". + +Es ist eine freude in Tcl zu programmieren. Hacker-Typen werden gefallen daran +finden, wenn sie Lisp, Forth oder Smalltalk interessant finden. Tcl wird auch +Ingenieuren und Wissenshaftlern gefallen die nur den Job erledigen wollen, +und zwar mit Werkzeugen die sich ihrem Willen anpassen. Bei Tcl ist jegliche +funktionalität in Befehlen ausgeführt, selbst Dinge wie Schleifen und +Mathematische-Funktionen die bei anderen Sprachen normalerweise Teil der Syntax +sind. Das erlaubt Tcl in den Hintergrund von Domänen spezischen Sprachen zu +treten die das jeweilige Projekt gerade benötigt. Die Tcl-Syntax ist sehr +leichtgewichtig. Sie ist selbst leichtgewichtiger als die Syntax von Lisp. +Tcl steht dir einfach nicht im Weg. + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Richtlinien +################################################################################ + +# Tcl ist nicht Bash oder C! Das muss gesagt werden, denn standard Shell-Quoting +# funktioniert fast mit Tcl. Daher glauben viele sie können diese Syntax für +# Tcl übernehmen. Am Beginn funktioniert das meist, führt aber schnell zu +# Frustrationen wenn die Skripte komplexer werden. + +# Eckige-Klammern sind nur Quoting-Mechanismen, keine Code-Block-Konstruktoren +# und auch keine Listen-Konstruktoren. In Tcl gibt es diese beiden Dinge nicht. +# Eckige-Klammern werden verwendet um Spezial-Zeichen in Prozeduren zu escapen +# und in Zeichenketten die als Listen formattiert sind. + +################################################################################ +## 2. Syntax +################################################################################ + +# Jede Zeile ist ein Befehl. Das erste Wort ist der Name des Befehls, jedes +# weitere Wort ist ein Argument des Befehls. Wörter sind begrenzt durch +# Leerzeichen. Da jedes Wort auch ein String ist, sind keine speziellen +# auszeichnungen wie Anführungs-Zeichen, Klammern oder Backslashes nötig. +# Selbst wenn Anführungs-Zeichen verwendet werden, denn sie sind ja keine +# String-Konstruktoren, sondern nur Escape-Zeichen. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +# Strichpunkte begrenzen auch Befehle +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Das Dollar-Zeichen zeigt eine Variablen-Substitution an. +set greeting $greeting1$greeting2$greeting3 + + +# Eckige-Klammern zeigen Befehls-Substitionen an. Das Ergebnis des Befehls wird an +# Stelle des Klammern-Ausdrucks eingefügt. Wenn man dem "set" Befehl nur den +# Namen einer Variablen übergibt, gibt er den Wert der Variablen zurück. +set greeting $greeting1$greeting2[set greeting3] + + +# Befehls-Substitution sollte eigentlich Script-Substitution heißen, denn ein +# komplettes Script, und nicht nur ein Befehl, kann zwischen die Eckigen-Klammern +# geschrieben werden. Der "incr" Befehl erhöht den Wert einer Variable um 1 +# und gibt den neuen Wert der Variable zurück. +set greeting $greeting[ + incr i + incr i + incr i +] + + +# Der Backslash unterdrück die Bedeutung von Sonderzeichen +set amount \$16.42 + + +# Der Backslash macht bestimmte Zeichen zu Sonderzeichen +puts lots\nof\n\n\n\n\n\nnewlines + +# Ein Wort das in geschweiften Klammern eingeschlossen wurde ist von jeglichen +# speziellen Interpretationen ausgeschlossen. Eine Ausnahme bilden Backslashes +# vor geschweiften Klammern, hiermit wird die geschweifte Klammer von der Suche +# nach der schließenden geschweiften Klammer ausgeschlossen. +set somevar { + Das ist ein literales $ Zeichen, diese geschweifte Klammer \} wird nicht + als Ende interpretiert. +} + + +# Bei einem Wort das in doppelten Anführungszeichen steht verlieren Leerzeichen +# ihre spezielle Bedeutung. +set name Neo +set greeting "Hallo, $name" + + +#Variablen-Namen können irgend eine Zeichenkette sein. +set {first name} New + + +# Die Geschweifte-Klammern-Form der Variablen-Substitution kann sehr komplexe +# Variblen-Namen handhaben. +set greeting "Hello, ${first name}" + + +# Der "set" Befehl kann immer anstatt einer Variablen-Substition verwendet +# werden. +set greeting "Hello, [set {first name}]" + + +# Mit dem Expansions-Operator "{*}" werden Wörter innerhalb eines Wortes wieder +# individuell als Teile des aktuellen Befehls behandelt. +set {*}{name Neo} + +# Ist Äquivalent zu +set name Neo + + +# Ein Array ist eine spezielle Varible die also Kontainer für andere Variablen +# dient. +set person(name) Neo +set person(gender) male +set greeting "Hello, $person(name)" + + +# Ein Namensraum enthält Befehle und Variablen +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +#Der volle Name einer Variablen beihaltet den/die umschließenden +# Namensraum/Namensräume begrenzt durch zwei Doppelpunkte. +set greeting "Hello $people::person1::name" +``` + +```tcl +################################################################################ +## 3. Einige Notizen +################################################################################ + +# Jede weitere Funktion ist über Befehle implementiert. Von nun an kommt keine +# neue Syntax hinzu. Alles weitere das es über Tcl zu lernen gibt ist das +# Verhalten individueller Befehle und die bedeutung ihrer Argumente. + + +# Um einen Interpreter zu bekommen mit dem man nichts mehr machen kann, lösche +# einfach den globalen Namensraum. Das ist nicht sehr sinnvoll, zeigt aber die +# Natur von Tcl. +namespace delete :: + + +# Wegen des Verhaltens der Namens-Auflösung ist es sicherer den "variable" +# Befehl zu verwenden um in einem Namensraum einen Wert zu deklarieren oder +# zuzuweisen. Wenn eine Variable mit dem namen "name" bereits im globalen +# Namensraum existiert, bewirkt der "set" Befehl das der globalen Variable ein +# Wert zugewiesen wird, anstatt eine Variable im lokalen Namensraum zu erzeugen +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# Es kann immer der vollständige Name einer Variable verwendet werden, falls +# gewünscht. +set people::person1::name Neo + + + +################################################################################ +## 4. Befehle +################################################################################ + +# Berechnungen werde mit dem "expr" Befehl durchgeführt. +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See + +# Da der "expr" Befehl eigene Variablen-Substitutionen durchführt, setze den +# zu berechnenden Ausdruck in Eckige-Klammern. Das hindert Tcl daran Variablen- +# Substitutionen durchzuführen. Für Details siehe: +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" + + +# Der "expr" Befehl versteht Variablen- und Befehls-Substitutionen +set c [expr {$a + [set b]}] + + +# Der "expr" Befehl stellt Mathematische-Funktionen zur Verfügung. +set c [expr {pow($a,$b)}] + + +# Mathematische Operatoren sind als Befehle auch im Namensraum +# ::tcl::mathop verfügbar. +::tcl::mathop::+ 5 3 + +# Befehle können aus anderen Namensräumen importiert werden. +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# Neu Befehle werden mit dem "proc" Befehl gebildet. +proc greet name { + return "Hello, $name!" +} + +#Es können mehrere Parameter spezifiziert werden. +proc greet {greeting name} { + return "$greeting, $name!" +} + + +# Wie bereits erwähnt, geschwungene Klammern erzeugen keinen Code-Block. +# Jeder Wert, sogar das dritte Argument für den "proc" Befehl ist eine +# Zeichenkette. Der vorherige Befehl kann daher auch ohne +# geschwungene Klammern geschrieben werden: +proc greet greeting\ name return\ \"Hello,\ \$name! + + + +# Wenn der letzte Parameter der literale Wert "args" ist, sammelt dieser Wert +# alle übrigen Argumente des Befehls ein wenn dieser aufgerufen wird. +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [$cmd $res $arg] + } +} +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + +# Bedingte Ausführung ist auch als Befehl implementiert +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Auch Schleifen sind Befehle. Das erste, zweite und dritte Argument des "for" +# Befehls wird als mathematischer Ausdruck behandelt. +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# Das erste Argument des "while" Befehls wird auch als mathematischer Ausdruck +# behandelt. +set i 0 +while {$i < 10} { + incr i 2 +} + + +# Eine Liste ist eine speziell formatierte Zeichenkette. Im einfachsten Fall +# genügen Leerzeichen als Trennzeichen zwischen den einzelnen Werten. +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Geschwungene Klammern und Backslashes können verwendet werden um komplexe +# Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript, +# allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre +# besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die +# folgende Liste enhtält drei Elemente. +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Da Listen auch Zeichenketten sind, kann man Zeichenketten-Operationen auf +# ihnen anwenden. Allerdings mit dem Risiko die Formatierung der Liste zu +# beschädigen. +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# Der sicherste Weg korrekt formatierte Liste zu erzeugen, ist den "list" +# Befehl zu verwenden. +set values [list one \{ three four] +lappend values { } ;# Ein Leerzeichen als Element der Liste hinzufügen + + +# Mit "eval" können Werte als Skripts evaluiert weden. +eval { + set name Neo + set greeting "Hello, $name" +} + + +# Eine Liste kann immer an "eval" übergeben werden, solange die Liste einen +# einzigen Befehl entält. +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Daher: Wenn "eval" verwendet wird, verwende [list] um den gewünschten Befehl +# aufzubauen. +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# Es ist ein häufiger Fehler die Listen funktionen beim Aufbauen von Listen +# nicht zu verwenden. +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# Hier passiert eine Fehler, denn der "set" Befehl hat nun zu \ + viele Argumente {set name Archibald Sorbisol} + + +# Dieser Fehler kann auch leicht beim "subst" Befehl passieren. +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: too many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# Die korrekte Vorgangsweise ist es den substituierten Wert mit dem "list" +# Befehl zu formatieren. +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# Der "list" Befehl wird sehr häufig verwendet um Werte zu formatieren die +# in Tcl Skript Vorlagen substituiert werden. Es gibt dazu viele Beispiele, +# siehe unterhalb. + + +# Der "apply" Befehl evaluiert eine Zeichenkette als Befehl. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# Der "uplevel" Befehl evaluiert ein Skript in einem höher liegenden +Gültigkeitsbereich. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + + +# Der "upvar" Befehl verknüpft eine Variable im aktuellen Gültigkeitsbereich +# mit einer Variable in einem höher liegenden Gültigkeitsbereich. +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +# Werde den eingebauten "while" Befehl los. +rename ::while {} + + +# Definieren einen neuen "while" Befehl mit hilfe des "proc" Befehls. +# Ausführlichere Fehler-Behandlung wird dem Leser als Übung überlassen. +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} + + +# Der "coroutine" Befehl erzeugt einen separaten Call-Stack, zusammen mit einem +# Befehl um diesem Call-Stack zu verwenden. Der "yield" Befehl unterbricht +# die Ausführung des aktuellen Call-Stacks. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + +``` + +## Referenzen + +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From 879337f9be2ef3c6ea2b01d34d2a21ad325c6cc4 Mon Sep 17 00:00:00 2001 From: DaKnOb Date: Fri, 9 Oct 2015 13:43:57 +0300 Subject: Add Python Order Of Module Import for Python 3 --- python3.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..f21604e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -591,6 +591,11 @@ math.sqrt(16) == m.sqrt(16) # => True import math dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From debf4073bd264b1da728b04feb2c25fd5d6df845 Mon Sep 17 00:00:00 2001 From: Arashk Date: Fri, 9 Oct 2015 18:50:38 +0330 Subject: [CSS/en] translated to [CSS/fa-ir] --- fa-ir/css.html.markdown | 299 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) create mode 100644 fa-ir/css.html.markdown diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown new file mode 100644 index 00000000..7214bb04 --- /dev/null +++ b/fa-ir/css.html.markdown @@ -0,0 +1,299 @@ +--- +language: CSS +translators: + - ["Arashk", "https://github.com/Arashk-A"] +lang: fa-ir +--- + +

در روزهای آغازین وب هیچگونه عنصر بصری مشاهده نمیشد و محتوا به صورت متن خالی بود.

+

اما با توسعه بیشتر مرورگرها صفحات وب کاملاً تصویری نیز رایج شد

+

CSS زبان استانداردی که موجودیت آن برای حفظ جدایی بین محتوا (HTML) و نگاه و احساس از

+

صفحات وب است.

+ +

به طور خلاصه, کاری که CSS انجام میدهد ارائه نحوه ایست که شما را قادر به هدف قرار دادن

+

عناصر مختلف در یک صفحه HTML کرده و امکان اختصاص خواص متفاوت بصری به آنها را میدهد.

+ + +

مانند هر زبانی, CSS نسخه های زیادی دارد که در اینجا توجه ما روی CSS2.0 است. با وجودی که این نسخه جدیدترین نسخه نمیباشد اما بیشترین پشتیبانی و سازگاری را در میان نسخه های مختلف را دارد

+ +

توجه: برای مشاهده برخی از نتایج جلوه های تصویری CSS به منظور یادگیری بیشتر شما باید چیزهای گوناگونی در محیطی مثل [dabblet](http://dabblet.com/) امتحان کنید. توجه اصلی این مقاله روی دستورات و برخی از نکات عمومی است.

+ + +

در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد

+ +```CSS +/* comments appear inside slash-asterisk, just like this line! + there are no "one-line comments"; this is the only comment style */ +``` + +

به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.

+ +```CSS +selector { property: value; /* more properties...*/ } +``` + +

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

+ +```CSS +* { color:red; } +``` + +

فرض کنید عنصری مثل این بر روی صفحه قرار دارد

+ +```html +
+``` +

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

+ +‍‍```CSS +.some-class { } +``` + +

یا با استفاده از نام دو کلاس

+ +```CSS +.some-class.class2 { } +``` + +

یا با استفاده از نام id

+ +```CSS +#someId { } +``` + +

یا با استفاده از نام خود عنصر

+ +```CSS +div { } +``` + +

یا با استفاده از 'attr'

+ +```CSS +[attr] { font-size:smaller; } +``` + +

یا با استفاده از ارزشی که برای 'attr' مشخص شده

+ +```CSS +[attr='value'] { font-size:smaller; } +``` + +

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'val' شروع میشود در CSS3

+ +```CSS +[attr^='val'] { font-size:smaller; } +``` + +

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'ue' به پایان میرسد در CSS3

+ +```CSS +[attr$='ue'] { font-size:smaller; } +``` + +

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست 'otherAttr' بوسیله فاصله از هم جدا شده اند در CSS3

+ +```CSS +[attr$='ue'] { font-size:smaller; } +``` + +

یا ارزش('value') دقیقاً خود ارزش('value') یا بوسیله '-' که یونیکد (U+002D) از حرف بعدی جدا شود

+ +```CSS +[otherAttr|='en'] { font-size:smaller; } +``` + +

و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند

+ +```CSS +div.some-class[attr$='ue'] { } +``` + +

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

+

برای مثال دستور زیر همه عناصری را که نام کلاس آنها '.class-name' و دارای پدر و مادری با این مشخصه 'div.some-parent' هستند را انتخاب میکند.

+ +```CSS +div.some-parent > .class-name {} +``` + + +

یا دستور زیر که همه عناصری را که نام کلاس آنها '.class-name' و داخل عنصری با مشخصه 'div.some-parent' هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان 'div.some-parent' باشند) انتخاب میکند.

+ +```CSS +div.some-parent .class-name {} +``` + +

نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.

+ +```CSS +div.some-parent.class-name {} +``` + +

دستور زیر همه عناصری را که نام کلاس آنها '.this-element' و بلافاصله بعد از عنصری با مشخصه '.i-am-before' قرار دارد را انتخاب میکند.

+ +```CSS +.i-am-before + .this-element { } +``` + +

هر خواهر یا برادری که بعد از '.i-am-before' بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

+ +```CSS +.i-am-any-before ~ .this-element {} +``` +

در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.

+

برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.

+ +```CSS +selector:hover {} +``` + +

یا زمانی از یک لینک بازید کردید.

+ +```CSS +selected:visited {} +``` + +

یا زمانی از لینکی بازید نشده است.

+ +```CSS +selected:link {} +``` + +

یا زمانی که روی یک عنصر ورودی متمرکز شده.

+ +```CSS +selected:focus {} +``` + +

واحدها

+ +```CSS +selector { + + /* واحدها اندازه */ + width: 50%; /* در اساس درصد */ + font-size: 2em; /* بر اساس اندازه font-size یعنی دو برابر اندازه فونت فعلی */ + width: 200px; /* بر اساس پیکسل */ + font-size: 20pt; /* بر اساس points (نکات) */ + width: 5cm; /* بر اساس سانتیمتر */ + min-width: 50mm; /* بر اساس میلیمتر */ + max-width: 5in; /* بر اساس اینچ. max-(width|height) */ + height: 0.2vh; /* بر اساس ارتفاع دید 'vh = نسبت به 1٪ از ارتفاع دید' (CSS3) */ + width: 0.4vw; /* بر اساس عرض دید 'vw = نسبت به 1٪ از عرض دید' (CSS3) */ + min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ + max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ + + /* رنگها */ + background-color: #F6E; /* بر اساس short hex */ + background-color: #F262E2; /* بر اساس long hex format */ + background-color: tomato; /* بر اساس نام رنگ */ + background-color: rgb(255, 255, 255); /* بر اساس rgb */ + background-color: rgb(10%, 20%, 50%); /* بر اساس درصد rgb , (rgb percent) */ + background-color: rgba(255, 0, 0, 0.3); /* بر اساس rgba (نیمه شفاف) , (semi-transparent rgb) (CSS3) */ + background-color: transparent; /* شفاف */ + background-color: hsl(0, 100%, 50%); /* بر اساس hsl format (CSS3). */ + background-color: hsla(0, 100%, 50%, 0.3); /* بر اساس hsla ,مثل RGBAکه میتوان شفافیت را در آخر انتخاب کرد (CSS3) */ + + + /* عکسها */ + background-image: url(/path-to-image/image.jpg); /* گذاشتن نقل قول داخل url() اختیاری است*/ + + /* فونتها */ + font-family: Arial; + font-family: "Courier New"; /* اگر اسم فونت با فاصله همراه باشد باید داخل نقل قول یک یا دو نوشته شود */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* اگر فونت اولی پیدا نشد مرورگر به سراغ نام بعدی میرود */ +} +``` + +

نحوه استفاده

+ +

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

+

حالا با استفاده از کد زیر آنرا در قسمت 'head' داخل فایل html خود تعریف کنید

+ +```html + +``` + +

یا میتوان با استفاده از تگ 'style' درون 'head' دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

+ +```html + +``` + +

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

+ +```html +
+
+``` + +

حق تقدم یا اولویت

+ +

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

+

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

+

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

+ +

به مثال زیر توجه کنید:

+ +```CSS +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } +``` + +

و همچنین به کد زیر:

+ +```html +

+

+``` +‍‍ +

حق تقدم یا اولویت برای مثال بالا به این صورت است:

+

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

+ +

E دارای بیشترین الویت برای اینکه از '!important' استفاده کرده.

+

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

+

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

+

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

+

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ 'p' + ۱ کلاس با نام 'class1' + ۱ خاصیت 'attr="value"'

+

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

+

اولویت بعدی با B

+

و در آخر D

+ +

سازگاری

+ +

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

+ +

[QuirksMode CSS](http://www.quirksmode.org/css/) یک منبع خوب برای این کار است

+ +

برای یک تست سازگاری سریع, [CanIUse](http://caniuse.com/) منبع بزرگی برای این کار است.

+ +

منابع دیگر

+ +
    +
  • +

    [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)

    +
  • +
  • +

    [QuirksMode CSS](http://www.quirksmode.org/css/)

    +
  • +
  • +

    [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)

    +
  • +
+
+ + -- cgit v1.2.3 From 197104715e61315d7214e081fd049091b68fe9ba Mon Sep 17 00:00:00 2001 From: zlarsen Date: Fri, 9 Oct 2015 15:09:26 -0600 Subject: forth-es Adds the Spanish translation of Forth. --- es-es/forth-es.html.markdown | 226 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 es-es/forth-es.html.markdown diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown new file mode 100644 index 00000000..05dc0cc5 --- /dev/null +++ b/es-es/forth-es.html.markdown @@ -0,0 +1,226 @@ +--- +language: forth +contributors: + - ["Horse M.D.", "http://github.com/HorseMD/"] +translators: + - ["Zach Larsen", "http://zachariahlarsen.com/"] +lang: es-es +filename: learnforth-es.fs +--- + +Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativo, basado en pila y entorno de programación, siendo usado en proyectos como Open Firmware. También esta usado por NASA. + +Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo +de lo que esta escrito aquí debe funcionar en otro sitio. + +``` +\ Este es un comentario +( Este es un comentario también pero solo esta usado cuando definiendo palabras. ) + +\ --------------------------------- Precursor ---------------------------------- + +\ Todo programación en Forth se hace manipulando el parámetro pila (mas +\ común se refiere como "el pila"). +5 2 3 56 76 23 65 \ ok + +\ estos números se añadieron al pila desde izquierda a derecho. +.s \ <7> 5 2 3 56 76 23 65 ok + +\ En Forth, todo es o una palabra o un numero. + +\ ------------------------------ Básico Aritmética ------------------------------ + +\ Aritmética (de hecho casi todas palabras que requieren datos) funciona manipulando datos +\ en el pila. +5 4 + \ ok + +\ `.` saca lo alto resulto desde el pila: +. \ 9 ok + +\ Mas ejemplos de aritmética: +6 7 * . \ 42 ok +1360 23 - . \ 1337 ok +12 12 / . \ 1 ok +13 2 mod . \ 1 ok + +99 negate . \ -99 ok +-99 abs . \ 99 ok +52 23 max . \ 52 ok +52 23 min . \ 23 ok + +\ ----------------------------- Pila Manipulación ----------------------------- + +\ Naturalmente, cuando trabajaremos con el pila, querremos algunos metidos útiles: + +3 dup - \ duplicar el primero articulo (1ra ahora igual a 2da): 3 - 3 +2 5 swap / \ intercambiar la primera con la segunda elemento: 5 / 2 +6 4 5 rot .s \ rotar los tres primero elementos: 4 5 6 +4 0 drop 2 / \ sacar el primero articulo (no imprima a la pantalla): 4 / 2 +1 2 3 nip .s \ sacar el segundo articulo (similar a drop): 1 3 + +\ ---------------------- Mas Avanzado Pila Manipulación ---------------------- + +1 2 3 4 tuck \ duplicar el primero articulo en el segundo hueco: 1 2 4 3 4 ok +1 2 3 4 over \ duplicar el segundo articulo a la primera del pila: 1 2 3 4 3 ok +1 2 3 4 2 roll \ *mover* el articulo en este posición a la primera del pila: 1 3 4 2 ok +1 2 3 4 2 pick \ *duplicar* el articulo en este posición a la primera del pila: 1 2 3 4 2 ok + +\ Cuando refiere a pila indices, ellos son basado en cero. + +\ ------------------------------ Creando Palabras -------------------------------- + +\ La `:` palabra hace que Forth entra modo de compilar hasta que se ve la `;` palabra. +: cuadrado ( n -- n ) dup * ; \ ok +5 cuadrado . \ 25 ok + +\ Podemos ver lo que hace una palabra también.: +see cuadrado \ : cuadrado dup * ; ok + +\ -------------------------------- Condicionales -------------------------------- + +\ -1 == cierto, 0 == falso. No obstante, valores que no son cero es usualmente tratado como +\ siendo cierto: +42 42 = \ -1 ok +12 53 = \ 0 ok + +\ `if` es una palabra que solamente compila. `if` `then` . +: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" then ; \ ok +100 ?>64 \ Mas que 64! ok + +\ Else: +: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" else ." Menos que 64!" then ; +100 ?>64 \ Mas que 64! ok +20 ?>64 \ Menos que 64! ok + +\ ------------------------------------ Loops ----------------------------------- + +\ `do` también es una palabra que solamente compila. +: miloop ( -- ) 5 0 do cr ." Hola!" loop ; \ ok +miloop +\ Hola! +\ Hola! +\ Hola! +\ Hola! +\ Hola! ok + +\ `do` espera dos números en el pila: el último numero y el primero numero. + +\ Podemos recibir el valor del indice mientras damos vuelta con `i`: +: uno-a-12 ( -- ) 12 0 do i . loop ; \ ok +uno-a-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok + +\ `?do` funciona similarmente, pero salta el loop si el último y primero +\ números son iguales. +: cuadrados ( n -- ) 0 ?do i cuadrado . loop ; \ ok +10 cuadrado \ 0 1 4 9 16 25 36 49 64 81 ok + +\ cambiar el "paso" con `+loop`: +: treces ( n n -- ) ?do i . 3 +loop ; \ ok +15 0 treces \ 0 3 6 9 12 ok + +\ Indefinido loops empiezan `begin` `until`: +: death ( -- ) begin ." Ya hemos llegado?" 0 until ; \ ok + +\ ---------------------------- Variables y Memoria ---------------------------- + +\ Use `variable` declarar `edad` ser un variable. +variable edad \ ok + +\ Ahora escribimos 21 a edad con la palabra `!`. +21 edad ! \ ok + +\ Por fin podemos imprimir nuestro variable usando la "leer" palabra `@`, que agregue el +\ valor a la pila, or usa `?` que lee y imprime todo juntos. +edad @ . \ 21 ok +edad ? \ 21 ok + +\ Constantes son muy similar, pero no nos importa los direcciones de memoria: +100 constant PUNTA-QUE-AQUA-HIERVA \ ok +PUNTA-QUE-AQUA-HIERVA . \ 100 ok + +\ ----------------------------------- Arrays ----------------------------------- + +\ Creando arrays es similar a variables, pero necesitamos alocar mas +\ memoria a ellos. + +\ Puede usar `2 cells allot` para crear un array que es sea 3 cédulas de tamaño: +variable minumeros 2 cells allot \ ok + +\ Inicializar todos los valores a 0 +minumeros 3 cells erase \ ok + +\ Alternativamente podemos usar `fill`: +minumeros 3 cells 0 fill + +\ o podemos saltar todo arriba y inicializar con valores específicos: +create minumeros 64 , 9001 , 1337 , \ ok (el último `,` es importante!) + +\ ...que es equivalente a: + +\ Manualmente escribiendo valores a cada indice: +64 minumeros 0 cells + ! \ ok +9001 minumeros 1 cells + ! \ ok +1337 minumeros 2 cells + ! \ ok + +\ Leyendo valores en particular array indices: +0 cells minumeros + ? \ 64 ok +1 cells minumeros + ? \ 9001 ok + +\ Podemos simplificar un poco cuando hacemos una palabra que ayuda cuando manipulando arrays: +: de-arr ( n n -- n ) cells + ; \ ok +minumeros 2 de-arr ? \ 1337 ok + +\ Que podemos usar cuando escribimos también: +20 minumeros 1 de-arr ! \ ok +minumeros 1 de-arr ? \ 20 ok + +\ ------------------------------ El Pila de Regreso ------------------------------ + +\ El pila de regreso se usa para retener punteros a cosas cuando palabras están +\ ejecutando otras palabras como loops. + +\ Ya hemos visto un uso de esto: `i`, que duplica el primero del pila +\ de regreso. `i` es equivalente a `r@`. +: miloop ( -- ) 5 0 do r@ . loop ; \ ok + +\ También como leyendo, podemos agregar al pila de regreso y sacarlo: +5 6 4 >r swap r> .s \ 6 5 4 ok + +\ NOTA: Porque Forth usa el pila de regreso por punteros de palabras, `>r` debe +\ siempre ser seguido por un `r>`. + +\ ------------------------- Flotante Punto Operaciones -------------------------- + +\ La mayoría Forths evitan el uso de flotante punto operaciones. +8.3e 0.8e f+ f. \ 9.1 ok + +\ Usualmente agregamos al frente palabras con 'f' cuando usando flotantes: +variable miflotantevar \ ok +4.4e miflotantevar f! \ ok +miflotantevar f@ f. \ 4.4 ok + +\ --------------------------------- Notas al Final -------------------------------- + +\ Usando una palabra que no existe vaciara el pila. No obstante, también hay una palabra +\ específicamente por esto: +clearstack + +\ vaciar la pantalla: +page + +\ Cargando Forth archivos: +\ s" archivodeforth.fs" included + +\ Puede listar cada palabra en el diccionario de Forth (pero es una lista gigante!): +\ words + +\ Terminando Gforth: +\ bye + +``` + +##Listo Para Mas? + +* [Starting Forth](http://www.forth.com/starting-forth/) +* [Simple Forth](http://www.murphywong.net/hello/simple.htm) +* [Thinking Forth](http://thinking-forth.sourceforge.net/) -- cgit v1.2.3 From 97ce7f1608f5bf32329e6a908a02193b6289d51c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9sar=20Su=C3=A1rez?= Date: Sat, 10 Oct 2015 12:56:25 +0200 Subject: Translation to Spanish if the article about Hack --- es-es/hack-es.html.markdown | 307 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 es-es/hack-es.html.markdown diff --git a/es-es/hack-es.html.markdown b/es-es/hack-es.html.markdown new file mode 100644 index 00000000..1059117a --- /dev/null +++ b/es-es/hack-es.html.markdown @@ -0,0 +1,307 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +translators: + - ["César Suárez", "https://github.com/csuarez"] +lang: es-es +filename: learnhack-es.hh +--- + +Hack es un superconjunto de PHP que se ejecuta en una máquina virtual llamada HHVM. Hack es casi totalmente compatible con código PHP ya existente y añade varias características típicas de los lenguajes de programación estáticamente tipados. + +En este artículo sólo se cubren las características específicas de Hack. Los detalles sobre la sintaxis de PHP están en el [artículo sobre PHP](http://learnxinyminutes.com/docs/php/) de esta misma web. + +```php +id = $id; + } +} + + +// Funciones anónimas concisas (lambdas) +$multiplier = 5; +array_map($y ==> $y * $multiplier, [1, 2, 3]); + + +// Genéricos +class Box +{ + protected T $data; + + public function __construct(T $data) { + $this->data = $data; + } + + public function getData(): T { + return $this->data; + } +} + +function openBox(Box $box) : int +{ + return $box->getData(); +} + + +// Shapes +// +// Hack añade el concepto de shape para definir estructuras similares a +// vectores, pero con un conjunto de claves garantizado y tipado +type Point2D = shape('x' => int, 'y' => int); + +function distance(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distance( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Alias de tipos +// +// Hack permite crear alias para hacer que los tipos complejos sean más legibles +newtype VectorArray = array>; + +// Una tupla que contiene dos enteros +newtype Point = (int, int); + +function addPoints(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +addPoints( + tuple(1, 2), + tuple(5, 6) +); + + +// Enumerados de primera clase +enum RoadType : int +{ + Road = 0; + Street = 1; + Avenue = 2; + Boulevard = 3; +} + +function getRoadType() : RoadType +{ + return RoadType::Avenue; +} + + +// Promoción de argumentos en constructores +// +// Para evitar repetir una y otra vez la definición de constructores que +// sólo asignan propiedades, Hack añade una sintaxis concisa para definir +// propiedades junto al constructor. +class ArgumentPromotion +{ + public function __construct(public string $name, + protected int $age, + private bool $isAwesome) {} +} + +class WithoutArgumentPromotion +{ + public string $name; + + protected int $age; + + private bool $isAwesome; + + public function __construct(string $name, int $age, bool $isAwesome) + { + $this->name = $name; + $this->age = $age; + $this->isAwesome = $isAwesome; + } +} + + +// Multitarea cooperativa +// +// "async" y "await" son dos palabras claves nuevas para realizar multi-tarea. +// Esto no implica que se usen hilos, sólo permiten transferir el control de la +// ejecución. +{ + for ($i = $start; $i <= $end; $i++) { + echo "$i "; + + // Da a otras tareas la oportunidad de hacer algo + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Esto imprime "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + cooperativePrint(1, 3), + cooperativePrint(4, 6), + cooperativePrint(7, 9) +])->getWaitHandle()->join(); + + +// Atributos +// +// Los atributos son una especie de metadatos para funciones. Hack implementa +// algunos atributos especiales para introducir esta característica. + +// El atributo especial __Memoize hace que el resultado de la función se cacheé. +<<__Memoize>> +function doExpensiveTask() : ?string +{ + return file_get_contents('http://example.com'); +} + +// Esta función se va a ejecutar sólo una vez: +doExpensiveTask(); +doExpensiveTask(); + + +// El atributo __ConsistentConstruct indica al comprobador de tipos de Hack que +// asegure que la signatura de __construct sea la misma para todas las +// subclases. +<<__ConsistentConstruct>> +class ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function someMethod() + { + // ... + } +} + +class ConsistentBar extends ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // El comprobador de tipos de Hack fuerza que los constructores de + // los padres sean llamados. + parent::__construct($x, $y); + + // ... + } + + // La anotación __Override es un atributo opcional para que el comprobador + // de tipos fuerce que ese método esté sobrecargando un método de un padre + // o de un trait. Sino, fallará. + <<__Override>> + public function someMethod() + { + // ... + } +} + +class InvalidFooSubclass extends ConsistentFoo +{ + // Este constructor no coincide con el padre y causará el siguiente error: + // + // "This object is of type ConsistentBaz. It is incompatible with this + // object of type ConsistentFoo because some of their methods are + // incompatible" + public function __construct(float $x) + { + // ... + } + + // Usando la anotación __Override en un método que no sobrecarga nada se + // producirá el siguiente error: + // + // "InvalidFooSubclass::otherMethod() is marked as override; no non-private + // parent definition found or overridden parent is defined in non-> + public function otherMethod() + { + // ... + } +} + + +// Los traits pueden implementar interfaces (PHP no soporta esto). +interface KittenInterface +{ + public function play() : void; +} + +trait CatTrait implements KittenInterface +{ + public function play() : void + { + // ... + } +} + +class Samuel +{ + use CatTrait; +} + + +$cat = new Samuel(); +$cat instanceof KittenInterface === true; // True + +``` + +## Más información + +Para obtener una explicación más detallada de las características que añade Hack a PHP visita la página de [referencia de Hack](http://docs.hhvm.com/manual/en/hacklangref.php) o la [página oficial de Hack](http://hacklang.org/) para información de caracter más general. + +Visita la [página oficial de HHVM](http://hhvm.com/) para ver las instrucciones de su instalación. + +También puedes visitar la [sección de características de PHP no soportadas por Hack](http://docs.hhvm.com/manual/en/hack.unsupported.php) para más detalles sobre la retrocompatibilidad entre Hack y PHP. -- cgit v1.2.3 From 2f1d29ce8064fe3f920f9d1429b9e5c9c228f5d4 Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sat, 10 Oct 2015 17:50:55 +0200 Subject: First version of german translation of Lua --- de-de/lua-de.html.markdown | 426 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 426 insertions(+) create mode 100644 de-de/lua-de.html.markdown diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown new file mode 100644 index 00000000..875629ad --- /dev/null +++ b/de-de/lua-de.html.markdown @@ -0,0 +1,426 @@ +--- +language: Lua +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: learnlua-de.lua +--- + +```lua +-- Zwei Gedankenstriche starten ein einzeiliges Kommentar. + +--[[ + Fügt man zwei '[' und ']' hinzu, + erzeugt man ein mehrzeiliges Kommentar. +--]] +-------------------------------------------------------------------------------- +-- 1. Variablen und Fluß-Kontrolle. +-------------------------------------------------------------------------------- + +num = 42 -- All Nummern sind vom Typ: Double. +-- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten +-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als +-- 52 Bit. + +s = 'walternate' -- Unveränderliche Zeichenkette wie by Python. +t = "Doppelte Anführungszeichen sind auch OK" +u = [[ Doppelte eckige Klammern + beginnen und beenden + mehrzeilige Zeichenketten.]] +t = nil -- Undefineren von t; Lua hat Garbage Collection. + +-- Blöcke werden durch Schlüsselwörter markiert wie do/end: +while num < 50 do + num = num + 1 -- Keine Operatoren wie ++ oder += +end + +-- If Bedingungen: +if num > 40 then + print('over 40') +elseif s ~= 'walternate' then -- ~= ist ungleich + -- Gleichheits-Check == wie bei Python; OK für Zeichenketten. + io.write('not over 40\n') -- Standard ist stdout. +else + -- Variablen sind standardmäßig global. + thisIsGlobal = 5 -- Camel case ist üblich. + + -- So macht man eine Variable lokal: + local line = io.read() -- Lies die nächste Zeile von stdin. + + -- Zeichenketten zusammenführen mit dem .. Operator: + print('Winter is coming, ' .. line) +end + +-- Undefinierte Variablen geben nil zurück. +-- Das ist kein Fehler: +foo = anUnknownVariable -- Nun ist foo = nil. + +aBoolValue = false + +-- Nur nil und false sind unwahr; 0 and '' sind wahr! +if not aBoolValue then print('was false') end + +-- 'or' und 'and' sind "kurz-geschlossen". Das ist so ähnlich wie der a?b:c +-- operator in C/js: +-- in C/js: +ans = aBoolValue and 'yes' or 'no' --> 'no' + +karlSum = 0 +for i = 1, 100 do -- Ein Bereich inkludiert beide Enden. + karlSum = karlSum + i +end + +-- Verwende "100, 1, -1" als Breich für Countdowns: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- Im Allgemeinen besteht ein Bereich aus: Anfang, Ende, [, Schrittweite]. + +-- Ein anderes Schleifen-Konstrukt: +repeat + print('Der Weg der Zukunft') + num = num - 1 +until num == 0 + +-------------------------------------------------------------------------------- +-- 2. Funktionen. +-------------------------------------------------------------------------------- + +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end + +-- Closures und anonyme Funktionen sind ok: +function adder(x) + -- Die zurückgegbe Funktion wird erzeugt wenn addr aufgerufen wird und merkt + -- sich den Wert von x: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- Rückgabewerte. Funktions-Aufrufe und Zuweisungen funktionieren all mit +-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfanger +-- bekommen nil; überzählige Sende werden entfernt. + +x, y, z = 1, 2, 3, 4 +-- Nun ist x = 1, y = 2, z = 3, und 4 wird entfernt. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> prints "zaphod nil nil" +-- Nun ist x = 4, y = 8, die Werte 15..42 werden entfernt. + +-- Funktionen sind erste Klasse, und können lokal oder global sein. +-- Das ist alles das Gleiche: +function f(x) return x * x end +f = function (x) return x * x end + +-- Und diese auch: +local function g(x) return math.sin(x) end +local g = function(x) return math.sin(x) end +-- Äquivalent zu local function g(x)..., außer das Referenzen auf g im +-- Funktions-Körper nicht wie erwartet funktionieren. +local g; g = function (x) return math.sin(x) end +-- Die 'local g' Deklaration macht G-Selbst-Referenzen OK. + +-- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten. + +-- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden +-- Klammern. +print 'hello' -- Works fine. + +-- Funktionsaufruge mit einem Tabellen-Parameter brauchen auch keine runden +-- Klammern. Mehr zu Tabellen später. +print {} -- Works fine too. + +-------------------------------------------------------------------------------- +-- 3. Tabellen. +-------------------------------------------------------------------------------- + +-- Tabellen sind die einzige zusammengesetzte Struktur in Lua. Sie sind +-- assoziative Arrays. Sie sind so ähnlich wie PHP arrays oder JavaScript +-- Objekte. Sie sind Hash-Lookup-Dictionaries die auch als Listen verwendet +-- werden können. + +-- Verwenden von Tabellen als Dictionaries oder Maps: +-- Using tables as dictionaries / maps: + +-- Dict lieterale haben standardmäßig Zeichenketten-Schlüssel: +t = {key1 = 'value1', key2 = false} + +-- Zeichenketten-Schlüssel verwenden ein JavaScript ähnliche Punkt-Notation. +print(t.key1) -- Ausgabe 'value1'. +t.newKey = {} -- Neues Schlüssel/Wert Paar hinzufügen. +t.key2 = nil -- key2 aus der Tabelle entfernen. + +-- Literale notation für jeden (nicht-nil) Wert als Schlüssel: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- ausgabe "tau" + +-- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten, +-- aber über die Identität bei Tabellen. +a = u['@!#'] -- Nun ist a = 'qbert'. +b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil: +-- b = nil weil der Lookup fehlschlägt. Er schlägt Fehl, weil der Schlüssel +-- den wir verwendet haben nicht das gleiche Objekt ist das wir verwendet +-- haben um den original Wert zu speichern. Zahlen und Zeichnkette sind daher +-- die praktischeren Schlüssel. + +-- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern. +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. + +for key, val in pairs(u) do -- Tabellen-Interation. + print(key, val) +end + +-- _G ist eine spezielle Tabelle die alles Globale enthält. +print(_G['_G'] == _G) -- Ausgabe 'true'. + +-- Verwenden von Tabellen als Listen/Arrays: + +-- Listen-Literale verwenden implizit Ganzzahlen als Schlüssel: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v ist die Größe von v für Listen. + print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT! +end +-- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden +-- Ganzzahlen als Schlüssel, behandelt wie eine Liste. + +-------------------------------------------------------------------------------- +-- 3.1 Metatabellen und Metamethoden +-------------------------------------------------------------------------------- + +-- Eine Tabelle kann eine Metatabelle haben die ihr so etwas wie +-- Tabellen-Operator-Überladungs-Verhalten verleiht. Später sehen wir wie +-- Metatabellen js-prototypen artiges Verhalten unterstützen. + +f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b. +f2 = {a = 2, b = 3} + +-- Dies würde Fehlschlagen: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + local sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf + +-- f1 und f2 haben keine Schlüssel für ihrer Metatabellen, anders als bei js +-- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen +-- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die +-- Lua bekannt sind, so wie __add. + + +-- Die nächste Zeile schlägt fehl weil s keine Metatabelle hat: +-- t = s + s +-- Mihilfe von Klassen ähnlichen Mustern kann das gelöst werden. +-- Siehe weiter unten. + +-- Ein __index einer Metatabelle überlädt Punkt-Lookups: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! + +-------------------------------------------------------------------------------- +-- Direkte Tabellen-Lookups die fehlschlagen werden mithilfe von __index der +-- Metatabelle wiederholt. Das geschieht rekursiv. + +-- __index kann auch eine Funktion mit der Form function(tbl, key) sein. +-- Damit kann man Lookups weiter anpassen. + +-- Werte wie __index,add, .. werden Metamethoden genannt. +-- Vollständige Liste aller Metamethoden. + +-- __add(a, b) für a + b +-- __sub(a, b) für a - b +-- __mul(a, b) für a * b +-- __div(a, b) für a / b +-- __mod(a, b) für a % b +-- __pow(a, b) für a ^ b +-- __unm(a) für -a +-- __concat(a, b) für a .. b +-- __len(a) für #a +-- __eq(a, b) für a == b +-- __lt(a, b) für a < b +-- __le(a, b) für a <= b +-- __index(a, b) für a.b +-- __newindex(a, b, c) für a.b = c +-- __call(a, ...) für a(...) + +-------------------------------------------------------------------------------- +-- 3.2 Klassen-Artihe Tabellen und vererbung. +-------------------------------------------------------------------------------- + +-- Klassen sind in Lua nicht eingebaut; es gibt verschieden Wege sie mithilfe +-- von Tabellen und Metatabellen zu erzeugen. + +-- Die Erklärund des Beispiels erfolgt unterhalb. + +Dog = {} -- 1. + +function Dog:new() -- 2. + local newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog verhält sich wie eine Klasse; Ist aber eine Tabelle. +-- 2. "function tablename:fn(...)" ist das gleiche wie +-- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens +-- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt. +-- 3. newObj wird eine Instanz von Dog. +-- 4. "self" ist die zu Instanzierende Klasse. Meisterns ist self = Doh, aber +-- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen +-- von self wenn wir die Metatabelle von newObj und __index von self auf +-- self setzen. +-- 5. Zur Erinnerung: setmetatable gibt sein erstes Argument zurück. +-- 6. Der Doppelpunkt funktioniert wie bei 2, aber dieses Mal erwarten wir das +-- self eine Instanz ist und keine Klasse. +-- 7. Das Selbe wie Dog.new(Dog), also self = Dog in new(). +-- 8. Das Selbe wie mrDog.makeSound(mrDog); self = mrDog. + +-------------------------------------------------------------------------------- + +-- Vererbungs-Beispiel: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + local s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-------------------------------------------------------------------------------- +-- 1. LoudDog bekommt die Methoden und Variablen von Dog. +-- 2. self hat einen 'sound' Schlüssel von new(), siehe 3. +-- 3. Das Gleiche wie "LoudDog.new(LoudDog)", und umgewandelt zu "Dog.new(LoudDog)" +-- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der +-- Metatabelle. +-- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog". +-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nacdem +-- welche Tabelle als erstes einen passenden Schlüssel hat. +-- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche +-- wie "LoudDog.makeSound(seymour)". + +-- Wenn nötig, sieht new() eine Sub-Klasse genau so aus wie new() der +-- Basis-Klasse: +function LoudDog:new() + local newObj = {} + -- set up newObj + self.__index = self + return setmetatable(newObj, self) +end + +-------------------------------------------------------------------------------- +-- 4. Module. +-------------------------------------------------------------------------------- + + +--[[ Dieser Abschnitt ist auskommentiert damit der Rest des Skripts lauffähig +-- bleibt. +``` + +```lua +-- Angenommen mod.lua sieht so aus: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('Why hello there') + sayMyName() +end + +return M + +-- Eine andere Datei könnte die Funktionen in mod.lua so verwenden: +local mod = require('mod') -- Führe mod.lua aus. + +-- require ist der Standard-Weg um Module zu inkludieren. +-- require verhält sich wie: (Wenn nicht gecached wird; siehe später) +local mod = (function () + +end)() +-- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in +-- mod.lua ausserhalb unsichtbar sind. + +-- Das funktioniert weil mod hier ist M in mod.lua: +mod.sayHello() -- Says hello to Hrunkner. + +-- Das ist Falsch: syMyName existiert nur in mod.lua: +mod.sayMyName() -- error + +-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass module nur +-- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden +-- werden. + +-- Nehmen wir an mod2.lua enthält "print('Hi!')". +local a = require('mod2') -- Ausgabe Hi! +local b = require('mod2') -- Keine Ausgabe; a=b. + +-- dofile ist wie require aber ohne Zwischenspeichern. +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (läuft nochmal, nicht wie require) + +-- loadfile ladet eine lua Datei aber die Datei wird noch nicht abgearbeitet. +f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua. + +-- loadstring ist loadfile für Zeichenketten +g = loadstring('print(343)') -- Gibt eine Funktion zurück.. +g() -- Ausgabe 343; Es kam keine Ausgabe bevor hier. + +--]] + +``` +## Referenzen + +Ich war so begeistert Lua zu lernen, um damit Spiele mit Love 2D game engine zu programmieren. + +Ich habe angefangen mit BlackBulletIV's Lua for programmers. +Danach habe ich das offizielle Lua Buch gelesen: Programming in Lua + +Es kann auch hilfreich sein hier vorbeizuschauen: Lua short +reference + +Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: + +* string library +* table library +* math library +* io library +* os library + +Übrigends, die gesamte Datei ist gültiges Lua. Speichere es als learn.lua und +starte es als "lua learn.lua" ! + +Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: github gist. Viel Spaß mit Lua! -- cgit v1.2.3 From c5b6113677e6d1a596d7e5ca53c642482412cacd Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sun, 11 Oct 2015 08:38:45 +0200 Subject: Improve grammar and correct spelling errors. --- de-de/lua-de.html.markdown | 91 +++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 46 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index 875629ad..eccfcf1e 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -12,33 +12,33 @@ filename: learnlua-de.lua --[[ Fügt man zwei '[' und ']' hinzu, - erzeugt man ein mehrzeiliges Kommentar. + erzeugt man einen mehrzeiligen Kommentar. --]] -------------------------------------------------------------------------------- -- 1. Variablen und Fluß-Kontrolle. -------------------------------------------------------------------------------- -num = 42 -- All Nummern sind vom Typ: Double. +num = 42 -- Alle Nummern sind vom Typ: Double. -- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten -- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als -- 52 Bit. -s = 'walternate' -- Unveränderliche Zeichenkette wie by Python. +s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python. t = "Doppelte Anführungszeichen sind auch OK" u = [[ Doppelte eckige Klammern beginnen und beenden mehrzeilige Zeichenketten.]] -t = nil -- Undefineren von t; Lua hat Garbage Collection. +t = nil -- Undefineren von t; Lua hat einen Garbage Collection. --- Blöcke werden durch Schlüsselwörter markiert wie do/end: +-- Blöcke werden durch Schlüsselwörter wie do/end markiert: while num < 50 do - num = num + 1 -- Keine Operatoren wie ++ oder += + num = num + 1 -- Es gibt Keine Operatoren wie ++ oder += end -- If Bedingungen: if num > 40 then print('over 40') -elseif s ~= 'walternate' then -- ~= ist ungleich +elseif s ~= 'walternate' then -- ~= bedeutet ungleich -- Gleichheits-Check == wie bei Python; OK für Zeichenketten. io.write('not over 40\n') -- Standard ist stdout. else @@ -94,7 +94,7 @@ end -- Closures und anonyme Funktionen sind ok: function adder(x) - -- Die zurückgegbe Funktion wird erzeugt wenn addr aufgerufen wird und merkt + -- Die zurückgegebene Funktion wird erzeugt wenn addr aufgerufen wird und merkt -- sich den Wert von x: return function (y) return x + y end end @@ -103,12 +103,12 @@ a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100 --- Rückgabewerte. Funktions-Aufrufe und Zuweisungen funktionieren all mit --- Listen die nicht immer gleich lang sein müssen. Überzählige Empfanger --- bekommen nil; überzählige Sende werden entfernt. +-- Rückgabewerte, Funktions-Aufrufe und Zuweisungen funktionieren alle mit +-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfänger +-- bekommen nil; überzählige Sender werden ignoriert. x, y, z = 1, 2, 3, 4 --- Nun ist x = 1, y = 2, z = 3, und 4 wird entfernt. +-- Nun ist x = 1, y = 2, z = 3, und 4 wird ignoriert. function bar(a, b, c) print(a, b, c) @@ -116,30 +116,30 @@ function bar(a, b, c) end x, y = bar('zaphod') --> prints "zaphod nil nil" --- Nun ist x = 4, y = 8, die Werte 15..42 werden entfernt. +-- Nun ist x = 4, y = 8, die Werte 15..42 werden ignoriert. -- Funktionen sind erste Klasse, und können lokal oder global sein. -- Das ist alles das Gleiche: function f(x) return x * x end f = function (x) return x * x end --- Und diese auch: +-- Das auch: local function g(x) return math.sin(x) end local g = function(x) return math.sin(x) end -- Äquivalent zu local function g(x)..., außer das Referenzen auf g im -- Funktions-Körper nicht wie erwartet funktionieren. local g; g = function (x) return math.sin(x) end --- Die 'local g' Deklaration macht G-Selbst-Referenzen OK. +-- Die Deklaration 'local g' macht Selbst-Referenzen auf g OK. -- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten. -- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden -- Klammern. -print 'hello' -- Works fine. +print 'hello' -- Funktioniert wunderbar. --- Funktionsaufruge mit einem Tabellen-Parameter brauchen auch keine runden --- Klammern. Mehr zu Tabellen später. -print {} -- Works fine too. +-- Funktionsaufrufe mit einem Tabellen-Parameter brauchen auch keine runden +-- Klammern. Mehr zu Tabellen kommt später. +print {} -- Funktioniert auch wunderbar. -------------------------------------------------------------------------------- -- 3. Tabellen. @@ -151,19 +151,18 @@ print {} -- Works fine too. -- werden können. -- Verwenden von Tabellen als Dictionaries oder Maps: --- Using tables as dictionaries / maps: --- Dict lieterale haben standardmäßig Zeichenketten-Schlüssel: +-- Dict-Literale haben standardmäßig Zeichenketten als Schlüssel: t = {key1 = 'value1', key2 = false} --- Zeichenketten-Schlüssel verwenden ein JavaScript ähnliche Punkt-Notation. +-- Zeichenketten-Schlüssel verwenden eine JavaScript ähnliche Punkt-Notation. print(t.key1) -- Ausgabe 'value1'. -t.newKey = {} -- Neues Schlüssel/Wert Paar hinzufügen. +t.newKey = {} -- Neues Schlüssel/Wert-Paar hinzufügen. t.key2 = nil -- key2 aus der Tabelle entfernen. -- Literale notation für jeden (nicht-nil) Wert als Schlüssel: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -print(u[6.28]) -- ausgabe "tau" +print(u[6.28]) -- Ausgabe "tau" -- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten, -- aber über die Identität bei Tabellen. @@ -176,9 +175,9 @@ b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil: -- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern. function h(x) print(x.key1) end -h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'. +h{key1 = 'Sonmi~451'} -- Ausgabe 'Sonmi~451'. -for key, val in pairs(u) do -- Tabellen-Interation. +for key, val in pairs(u) do -- Tabellen-Iteration. print(key, val) end @@ -193,14 +192,14 @@ for i = 1, #v do -- #v ist die Größe von v für Listen. print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT! end -- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden --- Ganzzahlen als Schlüssel, behandelt wie eine Liste. +-- Ganzzahlen als Schlüssel, die behandelt wird wie eine Liste. -------------------------------------------------------------------------------- -- 3.1 Metatabellen und Metamethoden -------------------------------------------------------------------------------- --- Eine Tabelle kann eine Metatabelle haben die ihr so etwas wie --- Tabellen-Operator-Überladungs-Verhalten verleiht. Später sehen wir wie +-- Eine Tabelle kann eine Metatabelle haben. Diese verleiht ihr so etwas wie +-- Tabellen-Operator-Überladungs-Verhalten. Später sehen wir wie -- Metatabellen js-prototypen artiges Verhalten unterstützen. f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b. @@ -220,9 +219,9 @@ end setmetatable(f1, metafraction) setmetatable(f2, metafraction) -s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf +s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf. --- f1 und f2 haben keine Schlüssel für ihrer Metatabellen, anders als bei js +-- f1 und f2 haben keine Schlüssel für ihre Metatabellen, anders als bei js -- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen -- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die -- Lua bekannt sind, so wie __add. @@ -247,7 +246,7 @@ eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! -- Damit kann man Lookups weiter anpassen. -- Werte wie __index,add, .. werden Metamethoden genannt. --- Vollständige Liste aller Metamethoden. +-- HIer eine vollständige Liste aller Metamethoden. -- __add(a, b) für a + b -- __sub(a, b) für a - b @@ -266,10 +265,10 @@ eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! -- __call(a, ...) für a(...) -------------------------------------------------------------------------------- --- 3.2 Klassen-Artihe Tabellen und vererbung. +-- 3.2 Klassen-Artige Tabellen und Vererbung. -------------------------------------------------------------------------------- --- Klassen sind in Lua nicht eingebaut; es gibt verschieden Wege sie mithilfe +-- Klassen sind in Lua nicht eingebaut. Es gibt verschieden Wege sie mithilfe -- von Tabellen und Metatabellen zu erzeugen. -- Die Erklärund des Beispiels erfolgt unterhalb. @@ -294,7 +293,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. -- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens -- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt. -- 3. newObj wird eine Instanz von Dog. --- 4. "self" ist die zu Instanzierende Klasse. Meisterns ist self = Doh, aber +-- 4. "self" ist die zu Instanzierende Klasse. Meistern ist self = Dog, aber -- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen -- von self wenn wir die Metatabelle von newObj und __index von self auf -- self setzen. @@ -325,12 +324,12 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der -- Metatabelle. -- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog". --- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nacdem +-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nachdem -- welche Tabelle als erstes einen passenden Schlüssel hat. -- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche -- wie "LoudDog.makeSound(seymour)". --- Wenn nötig, sieht new() eine Sub-Klasse genau so aus wie new() der +-- Wenn nötig, sieht new() einer Sub-Klasse genau so aus wie new() der -- Basis-Klasse: function LoudDog:new() local newObj = {} @@ -374,13 +373,13 @@ end)() -- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in -- mod.lua ausserhalb unsichtbar sind. --- Das funktioniert weil mod hier ist M in mod.lua: +-- Das funktioniert weil mod hier das Gleiche wie M in mod.lua ist: mod.sayHello() -- Says hello to Hrunkner. --- Das ist Falsch: syMyName existiert nur in mod.lua: -mod.sayMyName() -- error +-- Das ist Falsch: sayMyName existiert nur in mod.lua: +mod.sayMyName() -- Fehler --- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass module nur +-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass Module nur -- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden -- werden. @@ -397,14 +396,14 @@ f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua. -- loadstring ist loadfile für Zeichenketten g = loadstring('print(343)') -- Gibt eine Funktion zurück.. -g() -- Ausgabe 343; Es kam keine Ausgabe bevor hier. +g() -- Ausgabe 343; Vorher kam keine Ausgabe. --]] ``` ## Referenzen -Ich war so begeistert Lua zu lernen, um damit Spiele mit Love 2D game engine zu programmieren. +Ich war so begeistert Lua zu lernen, damit ich Spiele mit Love 2D game engine programmieren konnte. Ich habe angefangen mit BlackBulletIV's Lua for programmers. Danach habe ich das offizielle Lua Buch gelesen: Programming in Lua @@ -412,7 +411,7 @@ Danach habe ich das offizielle Lua Buch gelesen: Lua short reference -Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: +Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken: * string library * table library @@ -420,7 +419,7 @@ Wichtige Themen die hier nicht angesprochen wurden, die Standard-Bibliotheken: * io library * os library -Übrigends, die gesamte Datei ist gültiges Lua. Speichere es als learn.lua und -starte es als "lua learn.lua" ! +Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und +starte sie als "lua learn.lua" ! Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: github gist. Viel Spaß mit Lua! -- cgit v1.2.3 From ec813df15e46c80401db83b5719d369dc8a9ff03 Mon Sep 17 00:00:00 2001 From: Vinh Nguyen Date: Sun, 11 Oct 2015 17:24:27 +0700 Subject: Translate Ruby-ecosystem to Vietnamese --- vi-vn/ruby-ecosystem-vi.html.markdown | 148 ++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 vi-vn/ruby-ecosystem-vi.html.markdown diff --git a/vi-vn/ruby-ecosystem-vi.html.markdown b/vi-vn/ruby-ecosystem-vi.html.markdown new file mode 100644 index 00000000..518cf072 --- /dev/null +++ b/vi-vn/ruby-ecosystem-vi.html.markdown @@ -0,0 +1,148 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] + - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn +--- + +Nhìn chung các lập trình viên Ruby luôn có cách để cài đặt các phiên bản +Ruby khác nhau, quản lý các gói (hoặc gems), và quản lý các thư viện. + +## Trình quản lý Ruby + +Một vài nền tảng phải có Ruby đã được cài đặt trước hoặc có sẵn như một gói. +Số đông lập trình viên Ruby không sử dụng cái này, hoặc nếu có, họ chỉ sử +dụng chúng để bootstrap cài đặt Ruby. Thay vào đó, các lập trình viên Ruby +có xu hướng cài đặt trình quản lý Ruby để cài đặt và chuyển đổi các phiên +bản của Ruby và môi trường Ruby cho dự án của họ. + +Dưới đây là các trình quản lý môi trường Ruby nổi tiếng: + +* [RVM](https://rvm.io/) - Cài đặt và chuyển đổi các phiên bản Ruby. RVM cũng + có các khái niệm về tập các gems để quản lý môi trường dự án một + cách tốt nhất. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Chỉ cài đặt các + phiên bản Ruby. Sử dụng cái này giúp cho việc cài đặt Ruby tốt hơn. +* [rbenv](https://github.com/sstephenson/rbenv) - Chỉ dùng để chuyển đổi các + phiên bản Ruby. Được sử dụng đi kèm với ruby-build. Tiện ích này sẽ giúp + cho việc dùng Ruby tốt hơn. +* [chruby](https://github.com/postmodern/chruby) - Chỉ dùng để chuyển đổi các + phiên bản Ruby. Tương tự như rbenv. Không quan tâm làm thế nào Ruby được + cài đặt. + +## Các phiên bản Ruby + +Ruby được tạo ra bởi Yukihiro "Matz" Matsumoto, người được xem như là một +[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), mặc dầu gần +đây luôn thay đổi. Kết quả là, tham chiếu của Ruby được gọi là MRI(Matz' +Reference Implementation), và khi bạn biết về một phiên bản Ruby, nó đang +được tham chiếu để phát hành một phiên bản của MRI. + +Có ba phiên bản Ruby chính thức được dùng là: + +* 2.0.0 - Được phát hành vào tháng 2 năm 2013. Hầu hết các thư viện lớn, và +nền tảng đều hỗ trợ 2.0.0. +* 1.9.3 - Được phát hành vào tháng 10 năm 2011. Đây là phiên bản hầu hết các +lập trình viên Ruby đang dùng. [Nhưng đã không còn hỗ trợ]( + https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended + /) +* 1.8.7 - [Ruby 1.8.7 đã không còn được sử dụng]( + http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Sự thay đổi giữa phiên bản 1.8.7 đến 1.9.x lớn hơn nhiều so với thay đổi từ +1.9.3 đến 2.0.0. Ví dụ, các phiên bản 1.9 giới thiệu các bảng mã và một +byecote VM. Có các dự án vẫn đang ở 1.8.7, nhưng chúng chiếm một số lượng ít +, phần lớn cộng đồng đã chuyển sang ít nhất là 1.9.2 hoặc 1.9.3 + +## Các ứng dụng Ruby + +Hệ sinh thái Ruby có rất nhiều ứng dụng, với mỗi thế mạnh độc đáo và khả +năng tương thích. Để rõ ràng hơn, sự khác nhau giữa các ứng dụng được viết +bằng các ngôn ngữ khác nhau, nhưng *chúng vẫn là Ruby*. +Mỗi ứng dụng có các hook đặc trưng và những tính năng đặc biệt, nhưng tất cả +đều chạy Ruby rất tốt. Ví dụ, JRuby được viết bằng Java, nhưng bạn không +cần biết Java để sử dụng. + +Một số ứng dụng nổi tiếng/tương thích cao: + +* [MRI](https://github.com/ruby/ruby) - Được viết bằng C, đây là ứng dụng + tham chiếu của Ruby. Nó tương thích 100%. Tất cả các phiên bản Ruby có khả + năng duy trì với MRI(xem [RubySpec](#rubyspec) bên dưới). +* [JRuby](http://jruby.org/) - Được viết bằng Java và Ruby, ứng dụng này khá + nhanh. Điểm mạnh quan trọng nhất của JRuby là JVM/Java interop, tận dụng + các công cụ, dự án và ngôn ngữ hiện có của JVM. +* [Rubinius](http://rubini.us/) - Được viết bằng ngôn ngữ chính là Ruby với + một C++ bytecode VM. Rất nhanh. Bởi vì nó được phát triển bằng chính Ruby. + +Một số ứng dụng khá nổi tiếng/tương thích: + +* [Maglev](http://maglev.github.io/) - Đứng đầu Gemstone, một Smalltalk VM. + SmallTalk có một vài tiện ích hấp dẫn, và trong dự án này đã mang nó vào + môi trường Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Mang Ruby đến việc phát triển iOS. + +Một số ứng dụng tốt/tương thích: + +* [Topaz](http://topazruby.com/) - Được biết bằng RPython (sử dụng Pypy), + Topaz vẫn còn rất trẻ và chưa hoàn toàn tương thích. Nó hứa hẹn khả năng + trở thành một ứng dụng Ruby tương thích cao. +* [IronRuby](http://ironruby.net/) - Được viết bằng C# hướng đến nền tảng .NET + , IronRuby dường như đã dừng hoạt động kể từ khi Microsoft rút hỗ trợ. + +Các ứng dụng Ruby có các phiên bản riêng của mình, nhưng chúng luôn luôn +hướng đến sự một phiên bản đặc biệt của MRI cho sự tương thích. Nhiều ứng +dụng có khả năng đến các chế độ khác nhau (ví dụ, 1.8 hoặc 1.9) để hướng đến +phiên bản MRI. + +## RubySpec + +Hầu hết các ứng dụng Ruby dựa vào [RubySpec](http://rubyspec.org/). Ruby không +có thông báo chính thức, nhưng cộng đồng đã viết những specs thực thi trong +Ruby để kiểm tra sự tương thích với MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) là một cộng đồng quản lý các gói cho Ruby. +RubyGems đi kèm với Ruby, bởi vậy không cần cài đặt riêng lẻ. + +Các gói Ruby được gọi là "gems", và chúng được host bởi cộng đồng tại +RubyGems.org. Một gem chứa mã nguồn của nó và một vài mô tả, bao gồm những +thứ như phiên bản, các thư viện độc lập, các tác giả và các loại giấy phép. + +## Bundler + +[Bundler](http://bundler.io/) là một gem giải quyết độc lập. Nó sử dụng một +Gemfile để tìm kiếm các thư viện độc lập trong dự án, và sau đó sẽ lấy về +các thư viện của các thư viện độc lập này. Nó thực hiện cho đến khi việc +tải các thư viện hoàn tất, hoặc nó sẽ dừng nếu xuất hiện bất kỳ xung đột nào. + +Bundler sẽ hiển thị lỗi nếu tìm thấy bất kỳ xung đột giữa các thư viện. Ví +dụ, nếu như gem A yêu cầu gem Z có phiên bản 3 hoặc cao hơn, nhưng gem B lại +yêu cầu gem Z phiên bản 2. Bundler sẽ thông báo cho bạn sự xung đột này. +Điều này đã rất hữu ích khi nhiều gem tham chiếu các các gem khác (trong +gem này lại tham chiếu đến các gem khác nữa), có thể hình thành một đồ thị +lớn để nói. + +# Kiểm thử + +Kiểm thử là một phần lớn của Ruby. Ruby mang đến một nền tảng kiểm thử theo +kiểu Unit được gọi là minitest (hoặc TestUnit for phiên bản Ruby 1.8.x). +Có nhiều thư viện kiểm thử với các mục đích khác nhau. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/ + Unit.html) - Nền tảng kiểm thử theo kiểu Unit của Ruby 1.8. +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest + /rdoc/MiniTest.html) -Nền tảng kiểm thử được xây dựng cho Ruby 1.9/2.0 +* [RSpec](http://rspec.info/) - Một nền tảng kiểm thử tập trung vào sự + hoạt động. +* [Cucumber](http://cukes.info/) - Một nền tảng kiểm thử theo kiểu BDD dưới + định dạng Gherkin. + +## Be Nice + +Cộng đồng Ruby tự hào là một cộng đồng mở, đa dạng và chào đón tất cả mọi +người. Bản thân Matz là một người cực kỳ thân thiện, và các lập trình viên +Ruby rất tuyệt vời. -- cgit v1.2.3 From 1ba31a4a46a34dacdc85780e5b76507336cf456c Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 06:36:53 -0300 Subject: Create a new translate for csharp to pt-br language I started the feature to translate csharp docs to portuguese from Brazil (pt-br). --- pt-br/csharp.html.markdown | 899 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 899 insertions(+) create mode 100644 pt-br/csharp.html.markdown diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown new file mode 100644 index 00000000..1f6bea18 --- /dev/null +++ b/pt-br/csharp.html.markdown @@ -0,0 +1,899 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] +filename: LearnCSharp.cs +--- + +C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. + +[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) + +```c# +// Comentário de linha única começa com // +/* +Múltipas linhas é desta forma +*/ +/// +/// Esta é uma documentação comentário XML que pode ser usado para gerar externo +/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// +//public void MethodOrClassOrOtherWithParsableHelp() {} + +// Especificar qual namespace seu código irá usar +// Os namespaces a seguir são padrões do .NET Framework Class Library +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Mas este aqui não é : +using System.Data.Entity; +// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` + +// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" +// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +namespace Learning.CSharp +{ + // Cada .cs deve conter uma classe com o mesmo nome do arquivo + // você está autorizado a contrariar isto, mas evite por sua sanidade. + public class AprenderCsharp + { + // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes. + public static void Syntax() + { + // Use Console.WriteLine para apresentar uma linha + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para apresentar sem incluir uma nova linha, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // Tpos e Variáveis + // + // Declare uma variável usando + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor, +            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // Você pode acessar todos os caracteres de string com um indexador: + char charFromString = fooString[1]; // => 'e' + // Strings são imutáveis: você não pode fazer fooString[1] = 'X'; + + // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatando, baseado no sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Datas e formatações + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const ou read-only para fazer uma variável imutável + // os valores da const são calculados durante o tempo de compilação + const int HoursWorkPerWeek = 9001; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + + // Arrays - zero indexado + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays are mutable. + intArray[1] = 1; + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for generics - Check out the cool stuff section + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Others data structures to check out: + // Stack/Queue + // Dictionary (an implementation of a hash map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + // Start iteration 100 times, fooDoWhile 0->99 + if (false) + continue; // skip the current iteration + + fooDoWhile++; + + if (fooDoWhile == 50) + break; // breaks from the loop completely + + } while (fooDoWhile < 100); + + //for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterated 10 times, fooFor 0->9 + } + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Iterated over all the characters in the string + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), + // the String class, and a few special classes that wrap + // primitive types: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw a FormatException on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + // A method that differs only in return type is not unique + public static void MethodSignatures( + ref int maxCount, // Pass by reference + out int count) + { + count = 15; // out param must be assigned before control leaves the method + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // BY REF AND OUT PARAMETERS + int maxCount = 0, count; // ref params must have value + MethodSignatures(ref maxCount, out count); + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // ERROR HANDLING - coping with an uncertain world + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // will no longer execute because CreateWithGears throws an exception + string some = ""; + if (true) some = null; + some.ToLower(); // throws a NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // catch all other exceptions + { + throw new ApplicationException("It hit the fan", ex); + // throw; // A rethrow that preserves the callstack + } + // catch { } // catch-all without capturing the Exception + finally + { + // executes after try or catch + } + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + + // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on + [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // need to set the values manually! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + + // Static members belong to the type itself rather then specific object. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + public static int BicyclesCreated { get; set; } + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } + + // Properties can be auto-implemented + public int FrameSize + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new InvalidOperationException("You can't change gears on a PennyFarthing"); + } + } + + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // Oops, can't do this! + return penny; + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbContext + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Attributes + * async/await, yield, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From da6fc10553b457ef0d8ceb4f8898dfb2c5ddbbdd Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:03:18 -0300 Subject: Include and correct csharp docs Correct the csharp doc en-us language which was written intialize to initialize and include new more translated words to pt-br language. --- csharp.html.markdown | 2 +- pt-br/csharp.html.markdown | 92 +++++++++++++++++++++++----------------------- 2 files changed, 47 insertions(+), 47 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 02650038..811c2280 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -159,7 +159,7 @@ on a new line! ""Wow!"", the masses cried"; // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize + List z = new List { 9000, 1000, 1337 }; // initialize // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 1f6bea18..deba2263 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -136,76 +136,76 @@ on a new line! ""Wow!"", the masses cried"; const int HoursWorkPerWeek = 9001; /////////////////////////////////////////////////// - // Data Structures + // Estrutura de Dados /////////////////////////////////////////////////// - // Arrays - zero indexado - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; + // Matrizes - zero indexado + // O tamanho do array pode ser decidido ainda na declaração + // O formato para declarar uma matriz é o seguinte: + // [] = new []; int[] intArray = new int[10]; - // Another way to declare & initialize an array + // Outra forma de declarar & inicializar uma matriz int[] y = { 9000, 1000, 1337 }; - // Indexing an array - Accessing an element + // Indexando uma matriz - Acessando um elemento Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays are mutable. + // Matriz são alteráveis intArray[1] = 1; - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); + // Listas + // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis + // O formato de declarar uma lista é o seguinte: + // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for generics - Check out the cool stuff section + List z = new List { 9000, 1000, 1337 }; // inicializar + // O <> são para genéricos - Confira está interessante seção do material - // Lists don't default to a value; - // A value must be added before accessing the index + // Lista não possuem valores padrão. + // Um valor deve ser adicionado antes e depois acessado pelo indexador intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // Stack/Queue - // Dictionary (an implementation of a hash map) + // Outras estruturas de dados para conferir: + // Pilha/Fila + // Dicionário (uma implementação de map de hash) // HashSet - // Read-only Collections + // Read-only Coleção // Tuple (.Net 4+) /////////////////////////////////////// - // Operators + // Operadores /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis - // Arithmetic is straightforward + // Aritmética é clara Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 // Modulo Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - // Comparison operators - Console.WriteLine("3 == 2? " + (3 == 2)); // => false - Console.WriteLine("3 != 2? " + (3 != 2)); // => true - Console.WriteLine("3 > 2? " + (3 > 2)); // => true - Console.WriteLine("3 < 2? " + (3 < 2)); // => false - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + // Comparações de operadores + Console.WriteLine("3 == 2? " + (3 == 2)); // => falso + Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro + Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro + Console.WriteLine("3 < 2? " + (3 < 2)); // => falso + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro - // Bitwise operators! + // Operadores bit a bit (bitwise) /* - ~ Unary bitwise complement + ~ Unário bitwise complemento << Signed left shift >> Signed right shift & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ^ Bitwise exclusivo OR + | Bitwise inclusivo OR */ - // Incrementations + // Incrementações int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); Console.WriteLine(i++); //i = 1. Post-Incrementation @@ -214,11 +214,11 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// - // Control Structures + // Estrutura de Controle /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // Declaração if é como a linguagem C int j = 10; if (j == 10) { @@ -233,9 +233,9 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("I also don't"); } - // Ternary operators - // A simple if/else can be written as follows - // ? : + // Operador Ternário + // Um simples if/else pode ser escrito da seguinte forma + // ? : int toCompare = 17; string isTrue = toCompare == 17 ? "True" : "False"; @@ -251,25 +251,25 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - // Start iteration 100 times, fooDoWhile 0->99 + // Inicia a interação 100 vezes, fooDoWhile 0->99 if (false) - continue; // skip the current iteration + continue; // pule a intereção atual para apróxima fooDoWhile++; if (fooDoWhile == 50) - break; // breaks from the loop completely + break; // Interrompe o laço inteiro } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + //estrutura de loop for => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + //Iterado 10 vezes, fooFor 0->9 } // For Each Loop - // foreach loop structure => foreach( in ) + // Estrutura do foreach => foreach( in ) // The foreach loop loops over any object implementing IEnumerable or IEnumerable // All the collection types (Array, List, Dictionary...) in the .Net framework // implement one or both of these interfaces. -- cgit v1.2.3 From 6a6ac5560f6ec2813bff60b660b21d24bd80d011 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:38:30 -0300 Subject: Included new more words to pt-br --- pt-br/csharp.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index deba2263..02098ca8 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -270,20 +270,20 @@ on a new line! ""Wow!"", the masses cried"; // For Each Loop // Estrutura do foreach => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework - // implement one or both of these interfaces. - // (The ToCharArray() could be removed, because a string also implements IEnumerable) + // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable + // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework + // implementa uma ou mais destas interfaces. + // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable) foreach (char character in "Hello World".ToCharArray()) { //Iterated over all the characters in the string } // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // Um switch funciona com os tipos de dados byte, short, char, e int. + // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum), + // A classe String, and a few special classes that wrap + // tipos primitívos: Character, Byte, Short, and Integer. int month = 3; string monthString; switch (month) -- cgit v1.2.3 From bf12497636d9bcb2e5bd15e88493f2c0f95ce4a7 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 07:59:41 -0300 Subject: Alter the header file to correct contributor --- pt-br/csharp.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 02098ca8..9934afd9 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,12 +1,9 @@ --- language: c# +filename: learnruby-ptbr.cs contributors: - - ["Irfan Charania", "https://github.com/irfancharania"] - - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] - - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] - - ["Wouter Van Schandevijl", "http://github.com/laoujin"] -filename: LearnCSharp.cs + - ["Robson Alves", "http://robsonalves.net/"] +lang: pt-br --- C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. -- cgit v1.2.3 From 7b0c8231822472a1e0cdf99149b02aed21a71df0 Mon Sep 17 00:00:00 2001 From: Robson Alves Date: Mon, 12 Oct 2015 08:11:19 -0300 Subject: Correct the header file name --- pt-br/csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown index 9934afd9..547f4817 100644 --- a/pt-br/csharp.html.markdown +++ b/pt-br/csharp.html.markdown @@ -1,6 +1,6 @@ --- language: c# -filename: learnruby-ptbr.cs +filename: csharp-pt.cs contributors: - ["Robson Alves", "http://robsonalves.net/"] lang: pt-br -- cgit v1.2.3 From ac4823b3871010d90604daecc5f06c09859bacc2 Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Tue, 13 Oct 2015 11:39:54 -0300 Subject: add pt-br translation to git tags documentation --- pt-br/git-pt.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 981da503..ea3570d6 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -5,8 +5,12 @@ lang: pt-br filename: LearnGit.txt 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"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Bruno Volcov", "http://github.com/volcov"] --- Git é um sistema distribuido de gestão para código fonte e controle de versões. @@ -84,6 +88,11 @@ Um *branch* é essencialmente uma referência que aponta para o último *commit* efetuado. Na medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. +### *Tag* + +Uma tag é uma marcação em um ponto específico da história. Geralmente as +pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai) + ### *HEAD* e *head* (componentes do diretório .git) *HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem @@ -196,6 +205,29 @@ $ git branch -m myBranchName myNewBranchName $ git branch myBranchName --edit-description ``` +### Tag + +Gerencia as *tags* + +```bash +# Listar tags +$ git tag +# Criar uma tag anotada. +# O parâmetro -m define uma mensagem, que é armazenada com a tag. +# Se você não especificar uma mensagem para uma tag anotada, +# o Git vai rodar seu editor de texto para você digitar alguma coisa. +$ git tag -a v2.0 -m 'minha versão 2.0' +# Mostrar informações sobre a tag +# O comando mostra a informação da pessoa que criou a tag, +# a data de quando o commit foi taggeado, +# e a mensagem antes de mostrar a informação do commit. +$ git show v2.0 +# Enviar uma tag para o repositório remoto +$ git push origin v2.0 +# Enviar várias tags para o repositório remoto +$ git push origin --tags +``` + ### checkout Atualiza todos os arquivos no diretório do projeto para que fiquem iguais -- cgit v1.2.3 From eaeff26ba2fd921bb19db2e08a84d5e17019c5bf Mon Sep 17 00:00:00 2001 From: Serban Constantin Date: Tue, 13 Oct 2015 23:19:03 +0300 Subject: fix line lengths --- ro-ro/python-ro.html.markdown | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/ro-ro/python-ro.html.markdown b/ro-ro/python-ro.html.markdown index 125ba2f4..c96e30dc 100644 --- a/ro-ro/python-ro.html.markdown +++ b/ro-ro/python-ro.html.markdown @@ -8,14 +8,16 @@ filename: learnpython-ro.py lang: ro-ro --- -Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a devenit astăzi unul din -cele mai populare limbaje de programare. M-am indrăgostit de Python pentru claritatea sa sintactică. -Python este aproape pseudocod executabil. +Python a fost creat de Guido Van Rossum la începutul anilor '90. Python a +devenit astăzi unul din cele mai populare limbaje de programare. +M-am indrăgostit de Python pentru claritatea sa sintactică. Python este aproape +pseudocod executabil. -Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) sau ociule [at] [google's email service] +Opinia dumneavoastră este binevenită! Puteţi sa imi scrieţi la [@ociule](http://twitter.com/ociule) +sau ociule [at] [google's email service] -Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O versiune Python 3 va apărea -în curând, în limba engleză mai întâi. +Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. +O versiune Python 3 va apărea în curând, în limba engleză mai întâi. ```python # Comentariile pe o singură linie încep cu un caracter diez. @@ -36,7 +38,8 @@ Notă: Acest articol descrie Python 2.7, dar este util şi pentru Python 2.x. O 10 * 2 #=> 20 35 / 5 #=> 7 -# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere întregi şi rotunjeşte +# Împărţirea este un pic surprinzătoare. Este de fapt împărţire pe numere +# întregi şi rotunjeşte # automat spre valoarea mai mică 5 / 2 #=> 2 -- cgit v1.2.3 From 3b5071b9d637de87dba9d3baa2a23ec367bb0f70 Mon Sep 17 00:00:00 2001 From: Felipe Tarijon Date: Wed, 14 Oct 2015 12:57:53 -0300 Subject: Traduzido o artigo de AMD. --- pt-br/amd.html.markdown | 217 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 pt-br/amd.html.markdown diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown new file mode 100644 index 00000000..626481ff --- /dev/null +++ b/pt-br/amd.html.markdown @@ -0,0 +1,217 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Felipe Tarijon", "http://nanoincub.com/"] +filename: learnamd.js +--- + +## Começando com AMD + +A API de Definição de Módulos Assíncrona **Asynchronous Module Definition** +especifica um mecanismo para definição de módulos em JavaScript para os quais o +módulo e suas dependências podem ser carregados de forma assíncrona. Isso é +particularmente bem adequado para o ambiente do browser onde o carregamento de +módulos de forma síncrona fica sujeito a problemas de performance, usabilidade, +debugging e problemas de acesso em requisições cross-domain. + +### Conceito básico +```javascript +// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require` +// e isso é tudo sobre a definição de módulo e consumo: +// `define(id?, dependências?, factory)` define um módulo +// `require(dependências, callback)` importa uma série de dependências e +// consome elas no callback passado como parâmetro. + +// Vamos começar usando o define para definir um novo módulo +// que não tem dependências. Nós vamos fazer isso passando um nome +// e uma função factory para definir: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // O valor retornado da função de factory do módulo é + // o que os outros módulos ou chamadas de require irão + // receber quando requisitarem nosso módulo `awesomeAMD`. + // O valor exportado pode ser qualquer coisa, (construtor) funções, + // objetos, primitives, até mesmo undefined (apesar de que não irão ajudar muito). + return isAMDAwesome; +}); + +// Agora, vamos definir outro módulo que depende do nosso módulo `awesomeAMD`. +// Perceba que existe um argumento adicional definindo nossas dependências do +// módulo agora: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // dependências serão passadas como argumentos da factory + // na ordem que elas forem especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('Isso é tãaaao loko!'); + } else { + alert('Bem estúpido, né não?'); + } + }; + return tellEveryone; +}); + +// Agora que nós sabemos como usar o define, vamos usar o `require` para +// começar nosso programa. A assinatura do `require` é `(arrayDedependências, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para fazer esse tutorial executável, vamos implementar uma versão muito básica +// (não-assíncrona) de AMD bem aqui nesse lugar: +function define(nome, deps, factory){ + // perceba como os módulos sem dependências são manipulados + define[nome] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primeiro vamos recuperar todas as dependências necessárias + // pela chamada requerida + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // corresponder todas as dependências da função de callback + return callback.apply(null, args); +} +// você pode ver esse código em ação aqui: http://jsfiddle.net/qap949pd/ +``` + +### Uso na vida real com require.js + +Em contraste com o exemplo introdutório, `require.js` (a biblioteca mais popular de AMD) na verdade implementa o **A** do **AMD**, permitindo que você carregue os módulos e suas +dependências via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/algumaClasse'], function(AlgumaClasse){ + // o callback é deferido até que a dependencia seja carregada + var coisa = new AlgumaClasse(); +}); +console.log('Então aqui estamos nós, esperando!'); // isso vai rodar primeiro +``` + +Por convenção, você geralmente guarda um módulo em um arquivo. `require.js` pode resolver nome de módulos baseado no caminho das pastas, então você não precisa nomear os seus módulos, mas sim simplesmente referenciar eles usando sua origem. No exemplo `algumaClasse` é adotado a pasta `modules`, relativa a configuração da sua `baseUrl`: + +* app/ + * main.js + * modules/ + * algumaClasse.js + * algunsHelpers.js + * ... + * daos/ + * coisas.js + * ... + +Isso significa que nós podemos definir `algumaClasse` sem especificar o id de um módulo: + +```javascript +/* arquivo: app/modules/algumaClasse.js */ +define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){ + // definição de módulo, claro, irá acontecer também de forma assíncrona + function AlgumaClasse(){ + this.metodo = function(){/**/}; + // ... + } + return AlgumaClasse; +}); +``` +Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize +`requirejs.config(configObj)` em seu `main.js`: + +```javascript +/* arquivo: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // você pode também carregar módulos de outros locais + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coolLib, helpers){ + // um arquivo `main` precisa chamar o require pelo menos uma vez, + // caso contrário, o código jamais rodará + coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); +}); +``` +Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: + +```html + + + + Umas 100 tags de script? Nunca mais! + + + + + +``` + +### Otimizando um projeto inteiro utilizando r.js + +Muitas pessoas preferem usar AMD para sanar a organização do código durante o desenvolvimento, mas continuam querendo colocar um único arquivo de script em produção ao invés de realizarem centenas de requisições XHRs no carregamento da página. + +`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos. + +Instale-o utilizando `npm`: +```shell +$ npm install requirejs -g +``` + +Agora você pode alimentá-lo com um arquivo de configuração: +```shell +$ r.js -o app.build.js +``` + +Para o nosso exemplo acima a configuração pode ser essa: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nome do ponto de acesso + out : 'main-built.js', // nome o arquivo para gravar a saída + baseUrl : 'app', + paths : { + // `empty:` fala para o r.js que isso ainda deve ser baixado da CDN, usando + // o local especificado no `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`: +```html + +``` + +Uma incrível e detalhada visão geral [de build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponível no repositório do GitHub. + +### Tópicos não abordados nesse tutorial +* [Plugins de carregamento / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style carregamento e exportação](http://requirejs.org/docs/commonjs.html) +* [Configuração avançada](http://requirejs.org/docs/api.html#config) +* [Shim configuration (carregando módulos sem AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Carregando e otimizando CSS com require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para builds](https://github.com/jrburke/almond) + +### Outras leituras: + +* [Especificação oficial](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Por quê AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementações: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) \ No newline at end of file -- cgit v1.2.3 From 04eb0ca144440a54a4d69c0f02b5b376f4f62ea7 Mon Sep 17 00:00:00 2001 From: Razican Date: Thu, 15 Oct 2015 23:24:44 +0200 Subject: Added Rust translation to spanish --- es-es/rust-es.html.markdown | 313 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 313 insertions(+) create mode 100644 es-es/rust-es.html.markdown diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown new file mode 100644 index 00000000..43e388e5 --- /dev/null +++ b/es-es/rust-es.html.markdown @@ -0,0 +1,313 @@ +--- +language: rust +contributors: + - ["Razican", "https://www.razican.com/"] +filename: learnrust-es.rs +lang: es-es +--- + +Rust es un lenguaje de programación desarrollado por Mozzilla Research. +Rust combina el control del rendimiento a bajo nivel con la comodidad del alto nivel y +garantías de seguridad. + +Consigue cumplir estos objetivos sin necesidad de un recolector de basura o runtime, haciendo +posible usar las librerías de Rust como sustituto de C. + +La primera versión de Rust, la 0.1, fue lanzada en enero de 2012, y durante 3 años el desarrollo +fue tan rápido que hasta hace poco el uso de las versiones estables no era recomendable, y se +aconsejaba usar las compilaciones nocturnas. + +El 15 de mayo de 2015 se lanzó Rust 1.0, con una garantía completa de retrocompatibilidad. +A día de hoy los tiempos de compilación han mejorado mucho desde ese lanzamiento, así como +otros aspectos del lenguaje y el compilador. Rust ha adoptado un modelo de desarrollo por series +de publicaciones periódicas, con lanzamientos cada 6 semanas. Junto con cada lanzamiento, se lanza +la beta de la siguiente versión. + +A pesar de que Rust es un lenguaje relativamente de bajo nivel, tiene conceptos funcionales +que generalmente se encuentran en lenguajes de más alto nivel. Esto hace que Rust sea rápido +y al mismo tiempo fácil y eficiente a la hora de programar. + +```rust +// Esto es un comentario. Los comentarios de una sola línea se hacen así... +/* ...y los de múltiples líneas así */ + +////////////////////////// +// 1. Conceptos básicos // +////////////////////////// + +// Funciones +// `i32` es el tipo para enteros de 32 bits con signo +fn suma2(x: i32, y: i32) -> i32 { + // Retorno implícito (sin punto y coma) + x + y +} + +// Función principal +fn main() { + // N;umeros // + + // Bindings (variables) inmutables + let x: i32 = 1; + + // Sufijos para enteros / floats + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Inferencia de tipos + // La mayor parte del tiempo, el compilador de Rust puede inferir el tipo de una variable, por + // lo que no necesitas escribir una anotación de tipo explícita. + // A lo largo de este tutorial, los tipos están anotados explícitamente en varios sitios, + // pero solo con propósito demostrativo. La inferencia de tipos puede manejar esto por + // ti la mayor parte del tiempo. + let x_implicita = 1; + let f_implicita = 1.3; + + // Aritmética + let sum = x + y + 13; + + // Variable mutable + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Strings (cadenas de caracteres) // + + // Strings literales + let x: &str = "hola mundo!"; + + // Impresión por consola + println!("{} {}", f, x); // 1.3 hola mundo! + + // Un `String` – una cadena en memoria dinámica (heap) + let s: String = "hola mundo".to_string(); + + // Una porión de cadena (slice) – una vista inmutable a otra cadena + // Esto es básicamente un puntero inmutable a un string string – en realidad + // no contiene los caracteres de la cadena, solo un puntero a algo que los + // tiene (en este caso, `s`) + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hola mundo hola mundo + + // Vectores/arrays // + + // A fixed-size array + let cuatro_enteros: [i32; 4] = [1, 2, 3, 4]; + + // Un array dinámico (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // Una porción (slice) – una vista inmutable a un vector o array + // Esto es parecido a un slice de un string, pero para vectores + let slice: &[i32] = &vector; + + // Usa `{:?}` para imprimir algo en estilo debug + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuplas // + + // Una tupla es un conjunto de tamaño fijo de valores. Pueden ser de diferente tipo. + let x: (i32, &str, f64) = (1, "hola", 3.4); + + // Desestructurando `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hola 3.4 + + // Indexando + println!("{}", x.1); // hola + + ////////////// + // 2. Tipos // + ////////////// + + // Estructuras + struct Punto { + x: i32, + y: i32, + } + + let origen: Punto = Punto { x: 0, y: 0 }; + + // Una estructura con campos sin nombre, una ‘estructura de tupla’ + struct Punto2(i32, i32); + + let origen2 = Punto2(0, 0); + + // Enums básicos como en C + enum Direccion { + Izquierda, + Derecha, + Arriba, + Abajo, + } + + let arriba = Direccion::Arriba; + + // Enum con campos + enum OpcionalI32 { + UnI32(i32), + Nada, + } + + let dos: OpcionalI32 = OpcionalI32::UnI32(2); + let nada = OpcionalI32::Nada; + + // Genéricos // + + struct Foo { bar: T } + + // Esto está definido en la librería estándar como `Option` + enum Opcional { + AlgunVal(T), + SinVal, + } + + // Métodos // + + impl Foo { + // Los métodos reciben un parámetro explícito `self` + fn get_bar(self) -> T { + self.bar + } + } + + let un_foo = Foo { bar: 1 }; + println!("{}", un_foo.get_bar()); // 1 + + // Traits (conocidos como interfaces o typeclasses en otros lenguajes) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let otro_foo = Foo { bar: 1 }; + println!("{:?}", otro_foo.frobnicate()); // Some(1) + + ///////////////////////////////// + // 3. Comparación con patrones // + ///////////////////////////////// + + let foo = OpcionalI32::UnI32(1); + match foo { + OpcionalI32::UnI32(n) => println!("es un i32: {}", n), + OpcionalI32::Nada => println!("no es nada!"), + } + + // comparación de patrones avanzada + struct FooBar { x: i32, y: OpcionalI32 } + let bar = FooBar { x: 15, y: OpcionalI32::UnI32(32) }; + + match bar { + FooBar { x: 0, y: OpcionalI32::UnI32(0) } => + println!("Los números son cero!"), + FooBar { x: n, y: OpcionalI32::UnI32(m) } if n == m => + println!("Los números son iguales"), + FooBar { x: n, y: OpcionalI32::UnI32(m) } => + println!("Números diferentes: {} {}", n, m), + FooBar { x: _, y: OpcionalI32::Nada } => + println!("El segudo número no es nada!"), + } + + ///////////////////////// + // 4. Flujo de control // + ///////////////////////// + + // bucles `for` + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Rangos + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // imprime `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Las matemáticas funcionan!"); + } else { + println!("Oh no..."); + } + + // `if` como una expresión + let valor = if true { + "bueno" + } else { + "malo" + }; + + // bucle `while` + while 1 == 1 { + println!("El universo está funcionando correctamente."); + } + + // Bucle infinito + loop { + println!("Hola!"); + } + + //////////////////////////////////////// + // 5. Seguridad de memoria y punteros // + //////////////////////////////////////// + + // Posesión de punteros – solo una cosa puede ‘poseer’ este puntero en cada momento + // Esto significa que cuando la `Box` queda fuera del ámbito, puede ser liberada + // automáticamente de manera segura. + let mut mio: Box = Box::new(3); + *mio = 5; // dereferenciar + // Aquí, `ahora_es_mio`, toma posesión de `mio`. En otras palabras, `mio` se mueve. + let mut ahora_es_mio = mio; + *ahora_es_mio += 2; + + println!("{}", ahora_es_mio); // 7 + // println!("{}", mio); // esto no compilaría, porque `now_its_mine` es el que posee el puntero + + // Referencia – un puntero inmutable que referencia a otro dato + // Cuando se crea una referencia a un valor, decimos que el valor ha sido ‘tomado prestado’. + // Mientras un valor está prestado como inmutable, no puede ser modificado o movido. + // Una prestación dura hasta el fin del ámbito en el que se creó. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // A diferencia de `mio`, `var` se puede seguir usando + println!("{}", *ref_var); + // var = 5; // esto no compilaría, porque `var` está prestada + // *ref_var = 6; // esto tampoco, porque `ref_var` es una referencia inmutable + + // Referencia mutable + // Mientras que un valor está prestado como mutable, no puede ser accedido desde ningún + // otro sitio. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' se usa para apuntar al var2 prestado como mutable + + println!("{}", *ref_var2); // 6 , //var2 no compilaría. //ref_var2 es de tipo &mut i32, por + //lo que guarda una referencia a un i32 no el valor. + // var2 = 2; // esto no compilaría porque `var2` está prestado +} +``` + +## Lectura adicional + +Rust es mucho más que esto. Esto es solo lo más básico para que puedas entender las +cosas más importantes. Para aprender más sobre Rust, lee [The Rust Programming +Language](http://doc.rust-lang.org/book/index.html) y echa un vistazo al subreddit +[/r/rust](http://reddit.com/r/rust). Los compañeros en el canal #rust en irc.mozilla.org +también son muy buenos con los recien llegados. También puedes acceder a [Rust +users](https://users.rust-lang.org/) a pedir ayuda o a [Rust +internals](https://internals.rust-lang.org/) para aprender más sobre el lenguaje y +colaborar en su desarrollo. + +También puedes probar Rust con un compilador online en el oficial +[Rust playpen](http://play.rust-lang.org) o en la [web principal de Rust](http://rust-lang.org). -- cgit v1.2.3 From be4d5e595b5f81339743ef656fbc3d0b8cf97717 Mon Sep 17 00:00:00 2001 From: Razican Date: Thu, 15 Oct 2015 23:41:34 +0200 Subject: Adapted style --- es-es/rust-es.html.markdown | 99 ++++++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 45 deletions(-) diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown index 43e388e5..0628a37d 100644 --- a/es-es/rust-es.html.markdown +++ b/es-es/rust-es.html.markdown @@ -6,26 +6,28 @@ filename: learnrust-es.rs lang: es-es --- -Rust es un lenguaje de programación desarrollado por Mozzilla Research. -Rust combina el control del rendimiento a bajo nivel con la comodidad del alto nivel y -garantías de seguridad. +Rust es un lenguaje de programación desarrollado por Mozzilla Research. Rust +combina el control del rendimiento a bajo nivel con la comodidad del alto nivel +y garantías de seguridad. -Consigue cumplir estos objetivos sin necesidad de un recolector de basura o runtime, haciendo -posible usar las librerías de Rust como sustituto de C. +Consigue cumplir estos objetivos sin necesidad de un recolector de basura o +runtime, haciendo posible usar las librerías de Rust como sustituto de C. -La primera versión de Rust, la 0.1, fue lanzada en enero de 2012, y durante 3 años el desarrollo -fue tan rápido que hasta hace poco el uso de las versiones estables no era recomendable, y se -aconsejaba usar las compilaciones nocturnas. +La primera versión de Rust, la 0.1, fue lanzada en enero de 2012, y durante 3 +años el desarrollo fue tan rápido que hasta hace poco el uso de las versiones +estables no era recomendable, y se aconsejaba usar las compilaciones nocturnas. -El 15 de mayo de 2015 se lanzó Rust 1.0, con una garantía completa de retrocompatibilidad. -A día de hoy los tiempos de compilación han mejorado mucho desde ese lanzamiento, así como -otros aspectos del lenguaje y el compilador. Rust ha adoptado un modelo de desarrollo por series -de publicaciones periódicas, con lanzamientos cada 6 semanas. Junto con cada lanzamiento, se lanza -la beta de la siguiente versión. +El 15 de mayo de 2015 se lanzó Rust 1.0, con una garantía completa de +retrocompatibilidad. A día de hoy los tiempos de compilación han mejorado mucho +desde ese lanzamiento, así como otros aspectos del lenguaje y el compilador. +Rust ha adoptado un modelo de desarrollo por series de publicaciones periódicas, +con lanzamientos cada 6 semanas. Junto con cada lanzamiento, se lanza la beta de +la siguiente versión. -A pesar de que Rust es un lenguaje relativamente de bajo nivel, tiene conceptos funcionales -que generalmente se encuentran en lenguajes de más alto nivel. Esto hace que Rust sea rápido -y al mismo tiempo fácil y eficiente a la hora de programar. +A pesar de que Rust es un lenguaje relativamente de bajo nivel, tiene conceptos +funcionales que generalmente se encuentran en lenguajes de más alto nivel. Esto +hace que Rust sea rápido y al mismo tiempo fácil y eficiente a la hora de +programar. ```rust // Esto es un comentario. Los comentarios de una sola línea se hacen así... @@ -54,11 +56,11 @@ fn main() { let f: f64 = 1.3f64; // Inferencia de tipos - // La mayor parte del tiempo, el compilador de Rust puede inferir el tipo de una variable, por - // lo que no necesitas escribir una anotación de tipo explícita. - // A lo largo de este tutorial, los tipos están anotados explícitamente en varios sitios, - // pero solo con propósito demostrativo. La inferencia de tipos puede manejar esto por - // ti la mayor parte del tiempo. + // La mayor parte del tiempo, el compilador de Rust puede inferir el tipo de + // una variable, por lo que no necesitas escribir una anotación de tipo + // explícita. A lo largo de este tutorial, los tipos están anotados + // explícitamente en varios sitios, pero solo con propósito demostrativo. La + // inferencia de tipos puede manejar esto por ti la mayor parte del tiempo. let x_implicita = 1; let f_implicita = 1.3; @@ -260,21 +262,25 @@ fn main() { // 5. Seguridad de memoria y punteros // //////////////////////////////////////// - // Posesión de punteros – solo una cosa puede ‘poseer’ este puntero en cada momento - // Esto significa que cuando la `Box` queda fuera del ámbito, puede ser liberada - // automáticamente de manera segura. + // Posesión de punteros – solo uno puede ‘poseer’ un puntero en cada momento + // Esto significa que cuando la `Box` queda fuera del ámbito, puede ser + // liberada automáticamente de manera segura. let mut mio: Box = Box::new(3); *mio = 5; // dereferenciar - // Aquí, `ahora_es_mio`, toma posesión de `mio`. En otras palabras, `mio` se mueve. + // Aquí, `ahora_es_mio`, toma posesión de `mio`. En otras palabras, `mio` se + // mueve. let mut ahora_es_mio = mio; *ahora_es_mio += 2; println!("{}", ahora_es_mio); // 7 - // println!("{}", mio); // esto no compilaría, porque `now_its_mine` es el que posee el puntero + // println!("{}", mio); // esto no compilaría, porque `now_its_mine` es el + // que posee el puntero // Referencia – un puntero inmutable que referencia a otro dato - // Cuando se crea una referencia a un valor, decimos que el valor ha sido ‘tomado prestado’. - // Mientras un valor está prestado como inmutable, no puede ser modificado o movido. + // Cuando se crea una referencia a un valor, decimos que el valor ha sido + // ‘tomado prestado’. + // Mientras un valor está prestado como inmutable, no puede ser modificado o + // movido. // Una prestación dura hasta el fin del ámbito en el que se creó. let mut var = 4; var = 3; @@ -283,31 +289,34 @@ fn main() { println!("{}", var); // A diferencia de `mio`, `var` se puede seguir usando println!("{}", *ref_var); // var = 5; // esto no compilaría, porque `var` está prestada - // *ref_var = 6; // esto tampoco, porque `ref_var` es una referencia inmutable + // *ref_var = 6; // esto tampoco, porque `ref_var` es una referencia + // inmutable // Referencia mutable - // Mientras que un valor está prestado como mutable, no puede ser accedido desde ningún - // otro sitio. + // Mientras que un valor está prestado como mutable, no puede ser accedido + // desde ningún otro sitio. let mut var2 = 4; let ref_var2: &mut i32 = &mut var2; - *ref_var2 += 2; // '*' se usa para apuntar al var2 prestado como mutable + *ref_var2 += 2; // '*' se usa para apuntar al var2 prestado como mutable - println!("{}", *ref_var2); // 6 , //var2 no compilaría. //ref_var2 es de tipo &mut i32, por - //lo que guarda una referencia a un i32 no el valor. + println!("{}", *ref_var2); // 6 , //var2 no compilaría. //ref_var2 es de + // tipo &mut i32, por lo que guarda una + // referencia a un i32 no el valor. // var2 = 2; // esto no compilaría porque `var2` está prestado } ``` ## Lectura adicional -Rust es mucho más que esto. Esto es solo lo más básico para que puedas entender las -cosas más importantes. Para aprender más sobre Rust, lee [The Rust Programming -Language](http://doc.rust-lang.org/book/index.html) y echa un vistazo al subreddit -[/r/rust](http://reddit.com/r/rust). Los compañeros en el canal #rust en irc.mozilla.org -también son muy buenos con los recien llegados. También puedes acceder a [Rust -users](https://users.rust-lang.org/) a pedir ayuda o a [Rust -internals](https://internals.rust-lang.org/) para aprender más sobre el lenguaje y -colaborar en su desarrollo. - -También puedes probar Rust con un compilador online en el oficial -[Rust playpen](http://play.rust-lang.org) o en la [web principal de Rust](http://rust-lang.org). +Rust es mucho más que esto. Esto es solo lo más básico para que puedas entender +las cosas más importantes. Para aprender más sobre Rust, lee [The Rust +Programming Language](http://doc.rust-lang.org/book/index.html) y echa un +vistazo al subreddit [/r/rust](http://reddit.com/r/rust). Los compañeros en el +canal #rust en irc.mozilla.org también son muy buenos con los recien llegados. +También puedes acceder a [Rust users](https://users.rust-lang.org/) a pedir +ayuda o a [Rust internals](https://internals.rust-lang.org/) para aprender más +sobre el lenguaje y colaborar en su desarrollo. + +También puedes probar Rust con un compilador online en el oficial [Rust +playpen](http://play.rust-lang.org) o en la [web principal de +Rust](http://rust-lang.org). -- cgit v1.2.3 From ac474904b1d49a3d2372a9283a6b7e7bf5bc7ac0 Mon Sep 17 00:00:00 2001 From: meinkej Date: Fri, 16 Oct 2015 11:10:26 +0100 Subject: [hack/de] Translation to German of the article about Hack --- de-de/hack-de.html.markdown | 320 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 de-de/hack-de.html.markdown diff --git a/de-de/hack-de.html.markdown b/de-de/hack-de.html.markdown new file mode 100644 index 00000000..330d0b9b --- /dev/null +++ b/de-de/hack-de.html.markdown @@ -0,0 +1,320 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] + - ["Jerome Meinke", "https://github.com/jmeinke"] +filename: learnhack.hh +--- + +Hack ist eine von Facebook neu entwickelte Programmiersprache auf Basis von PHP. +Sie wird von der HipHop Virtual Machine (HHVM) ausgeführt. Die HHVM kann +aufgrund der Ähnlichkeit der Programmiersprachen nicht nur Hack, sondern auch +PHP-Code ausführen. Der wesentliche Unterschied zu PHP besteht in der statischen +Typisierung der Sprache, die eine wesentlich höhere Performance erlaubt. + + +Hier werden nur Hack-spezifische Eigenschaften beschrieben. Details über PHP's +Syntax findet man im [PHP Artikel](http://learnxinyminutes.com/docs/php/) dieser +Seite. + +```php +id = $id; + } +} + + +// Kurzgefasste anonyme Funktionen (lambdas) +$multiplier = 5; +array_map($y ==> $y * $multiplier, [1, 2, 3]); + + +// Weitere, spezielle Felder (Generics) +// Diese kann man sich als ein zugreifbares Interface vorstellen +class Box +{ + protected T $data; + + public function __construct(T $data) { + $this->data = $data; + } + + public function getData(): T { + return $this->data; + } +} + +function openBox(Box $box) : int +{ + return $box->getData(); +} + + +// Formen +// +// Hack fügt das Konzept von Formen hinzu, wie struct-ähnliche arrays +// mit einer typ-geprüften Menge von Schlüsseln +type Point2D = shape('x' => int, 'y' => int); + +function distance(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distance( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Typen-Definition bzw. Aliasing +// +// Hack erlaubt es Typen zu definieren und sorgt somit für bessere Lesbarkeit +newtype VectorArray = array>; + +// Ein Tupel mit zwei Integern +newtype Point = (int, int); + +function addPoints(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +addPoints( + tuple(1, 2), + tuple(5, 6) +); + + +// Erstklassige Aufzählungen (enums) +enum RoadType : int +{ + Road = 0; + Street = 1; + Avenue = 2; + Boulevard = 3; +} + +function getRoadType() : RoadType +{ + return RoadType::Avenue; +} + + +// Automatische Erstellung von Klassen-Eigenschaften durch Konstruktor-Argumente +// +// Wiederkehrende Definitionen von Klassen-Eigenschaften können durch die Hack- +// Syntax vermieden werden. Hack erlaubt es die Klassen-Eigenschaften über +// Argumente des Konstruktors zu definieren. +class ArgumentPromotion +{ + public function __construct(public string $name, + protected int $age, + private bool $isAwesome) {} +} + +class WithoutArgumentPromotion +{ + public string $name; + + protected int $age; + + private bool $isAwesome; + + public function __construct(string $name, int $age, bool $isAwesome) + { + $this->name = $name; + $this->age = $age; + $this->isAwesome = $isAwesome; + } +} + + +// Kooperatives Multitasking +// +// Die Schlüsselworte "async" and "await" führen Multitasking ein. +// Achtung, hier werden keine Threads benutzt, sondern nur Aktivität getauscht. +async function cooperativePrint(int $start, int $end) : Awaitable +{ + for ($i = $start; $i <= $end; $i++) { + echo "$i "; + + // Geben anderen Tasks die Möglichkeit aktiv zu werden + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Die Ausgabe von folgendem Code ist "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + cooperativePrint(1, 3), + cooperativePrint(4, 6), + cooperativePrint(7, 9) +])->getWaitHandle()->join(); + + +// Attribute +// +// Attribute repräsentieren eine Form von Metadaten für Funktionen. +// Hack bietet Spezial-Attribute, die nützliche Eigenschaften mit sich bringen. + +// Das __Memoize Attribut erlaubt es die Ausgabe einer Funktion zu cachen. +<<__Memoize>> +function doExpensiveTask() : ?string +{ + return file_get_contents('http://example.com'); +} + +// Der Funktionsrumpf wird im Folgenden nur ein einziges mal ausgeführt: +doExpensiveTask(); +doExpensiveTask(); + + +// Das __ConsistentConstruct Attribut signalisiert dem type-checker, dass +// die Funktionsdeklaration von __construct für alle Unterklassen dieselbe ist. +<<__ConsistentConstruct>> +class ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function someMethod() + { + // ... + } +} + +class ConsistentBar extends ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // Der Type-checker erzwingt den Aufruf des Eltern-Klassen-Konstruktors + parent::__construct($x, $y); + + // ... + } + + // Das __Override Attribut ist ein optionales Signal an den Type-Checker, + // das erzwingt, dass die annotierte Methode die Methode der Eltern-Klasse + // oder des Traits verändert. + <<__Override>> + public function someMethod() + { + // ... + } +} + +class InvalidFooSubclass extends ConsistentFoo +{ + // Wenn der Konstruktor der Eltern-Klasse nicht übernommen wird, + // wird der Type-Checker einen Fehler ausgeben: + // + // "This object is of type ConsistentBaz. It is incompatible with this object + // of type ConsistentFoo because some of their methods are incompatible" + // + public function __construct(float $x) + { + // ... + } + + // Auch bei der Benutzung des __Override Attributs für eine nicht veränderte + // Methode wird vom Type-Checker eine Fehler ausgegeben: + // + // "InvalidFooSubclass::otherMethod() is marked as override; no non-private + // parent definition found or overridden parent is defined in non-> + public function otherMethod() + { + // ... + } +} + +// Ein Trait ist ein Begriff aus der objektorientierten Programmierung und +// beschreibt eine wiederverwendbare Sammlung von Methoden und Attributen, +// ähnlich einer Klasse. + +// Anders als in PHP können Traits auch als Schnittstellen (Interfaces) +// implementiert werden und selbst Schnittstellen implementieren. +interface KittenInterface +{ + public function play() : void; +} + +trait CatTrait implements KittenInterface +{ + public function play() : void + { + // ... + } +} + +class Samuel +{ + use CatTrait; +} + + +$cat = new Samuel(); +$cat instanceof KittenInterface === true; // True + +``` + +## Weitere Informationen + +Die Hack [Programmiersprachen-Referenz](http://docs.hhvm.com/manual/de/hacklangref.php) +erklärt die neuen Eigenschaften der Sprache detailliert auf Englisch. Für +allgemeine Informationen kann man auch die offizielle Webseite [hacklang.org](http://hacklang.org/) +besuchen. + +Die offizielle Webseite [hhvm.com](http://hhvm.com/) bietet Infos zum Download +und zur Installation der HHVM. + +Hack's [nicht-untersützte PHP Syntax-Elemente](http://docs.hhvm.com/manual/en/hack.unsupported.php) +werden im offiziellen Handbuch beschrieben. -- cgit v1.2.3 From ac7a755ae960c5274bfe5a4d0c4d823df1fce441 Mon Sep 17 00:00:00 2001 From: flatt <123ioandragomir123@gmail.com> Date: Fri, 16 Oct 2015 15:11:51 +0300 Subject: Update bash-ro.html.markdown Tweaked around with the old translations --- ro-ro/bash-ro.html.markdown | 159 +++++++++++++++++++++++--------------------- 1 file changed, 82 insertions(+), 77 deletions(-) diff --git a/ro-ro/bash-ro.html.markdown b/ro-ro/bash-ro.html.markdown index debeb67a..32a878b2 100644 --- a/ro-ro/bash-ro.html.markdown +++ b/ro-ro/bash-ro.html.markdown @@ -12,166 +12,171 @@ lang: ro-ro filename: LearnBash-ro.sh --- -Bash este numele shell-ului unix, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU si ca shell implicit pentru Linux si Mac OS X. +Bash este numele shell-ului UNIX, care a fost de asemenea distribuit drept shell pentru sistemul de operare GNU și ca shell implicit pentru Linux si Mac OS X. Aproape toate exemplele de mai jos pot fi parte dintr-un script sau pot fi executate direct in linia de comanda. -[Citeste mai multe:](http://www.gnu.org/software/bash/manual/bashref.html) +[Citește mai multe:](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash # Prima linie din script se numeste "shebang" -# care spune systemului cum sa execute scriptul +# care spune sistemului cum să execute scriptul # http://en.wikipedia.org/wiki/Shebang_(Unix) -# Dupa cum te-ai prins deja, comentariile incep cu #. +# După cum te-ai prins deja, comentariile încep cu #. # Shebang este de asemenea un comentariu. # Exemplu simplu de hello world: echo Hello world! -# Fiecare comanda incepe pe o linie noua, sau dupa punct si virgula ; +# Fiecare comandă începe pe o linie nouă, sau după punct și virgula ; echo 'Prima linie'; echo 'A doua linie' # Declararea unei variabile se face astfel: -VARIABLE="Niste text" +VARIABLE="Niște text" -# DAR nu asa: +# DAR nu așa: VARIABLE = "Niste text" -# Bash va crede ca VARIABLE este o comanda care trebuie executata si va -# returna o eroare pentru ca nu va putea fi gasita. +# Bash va crede că VARIABLE este o comandă care trebuie executată și va +# returna o eroare pentru că nu va putea fi găsita. # Folosind variabila: echo $VARIABLE echo "$VARIABLE" echo '$VARIABLE' -# Atunci cand folosesti variabila, o atribui, o exporti sau altfel, -# numele ei se scrie fara $. -# Daca vrei sa folosesti valoarea variabilei, atunci trebuie sa folosesti $. -# Atentie la faptul ca ' (apostrof) nu va inlocui variabla cu valoarea ei. +# Atunci când folosesti variabila, o atribui, o exporți sau altfel, +# numele ei se scrie fără $. +# Daca vrei sa folosesti valoarea variabilei, atunci trebuie să folosești $. +# Atentie la faptul că ' (apostrof) nu va inlocui variabla cu valoarea ei. -# Inlocuirea de caractere in variabile -echo ${VARIABLE/Some/A} -# Asta va inlocui prima aparitie a "Some" cu "A" in variabila de mai sus. +# Inlocuirea de caractere în variabile +echo ${VARIABLE/Niște/Un} +# Asta va înlocui prima apariție a "Niște" cu "Un" în variabila de mai sus. -# Substring dintr-o variabila +# Substring dintr-o variabilă echo ${VARIABLE:0:7} # Asta va returna numai primele 7 caractere din variabila. # Valoarea implicita a unei variabile: -echo ${FOO:-"ValoareaImplicitaDacaFOOLipsesteSauEGoala"} -# Asta functioneaza pentru null (FOO=), -# sir de caractere gol (FOO=""), zero (FOO=0) returneaza 0 +echo ${FOO:-"ValoareaImplicitaDacaFOOLipseșteSauEGoală"} +# Asta functionează pentru null (FOO=), +# sir de caractere gol (FOO=""), zero (FOO=0) returnează 0 # Variabile pre-existente -echo "Ulima valoare returnata de ultimul program rulat: $?" -echo "ID-ul procesului (PID) care ruleaza scriptul: $$" -echo "Numarul de argumente: $#" +echo "Ulima valoare returnată de ultimul program rulat: $?" +echo "ID-ul procesului (PID) care rulează scriptul: $$" +echo "Numărul de argumente: $#" echo "Argumentele scriptului: $@" -echo "Argumentele scriptului separate in variabile: $1 $2..." +echo "Argumentele scriptului separate în variabile: $1 $2..." -# Citind o valoare din consola -echo "Care e numele tau?" -read NAME # Observa faptul ca nu a trebuit sa declaram o variabila noua +# Citind o valoare din consolă +echo "Care e numele tău?" +read NAME # Observă faptul că nu a trebuit să declarăm o variabilă nouă echo Salut, $NAME! # Avem obisnuita instructiune "if" -# Foloseste "man test" pentru mai multe informatii -# despre instructinea conditionala +# Folosește "man test" pentru mai multe informații +# despre instrucținea conditionala if [ $NAME -ne $USER ] then - echo "Numele tau este username-ul tau" + echo "Numele tău este username-ul tău" else - echo "Numele tau nu este username-ul tau" + echo "Numele tău nu este username-ul tău" fi -# Este de asemenea si executarea conditionala de comenzi -echo "Intotdeauna executat" || echo "Executat daca prima instructiune esueaza" -echo "Intotdeauna executat" && echo "Executat daca prima instructiune NU esueaza" +# Există, de asemenea, și executarea conditională de comenzi +echo "Întotdeauna executat" || echo "Executat dacă prima instrucțiune eșuează" +echo "Întotdeauna executat" && echo "Executat dacă prima instrucțiune NU esuează" -# Expresiile apar in urmatorul format +# Expresiile apar în urmatorul format echo $(( 10 + 5 )) -# Spre deosebire de alte limbaje de programare bash este un shell - asa ca -# functioneaza in contextul directorului curent. Poti vedea fisiere si directoare +# Spre deosebire de alte limbaje de programare, bash este un shell - așa că +# funcționează in contextul directorului curent. Poți vedea fișiere și directoare # din directorul curent folosind comanda "ls": ls -# Aceste comenzi au optiuni care la controleaza executia -ls -l # Listeaza fiecare fisier si director pe o linie separata +# Aceste comenzi au optiuni care le controlează execuțiă +ls -l # Listează fiecare fișier și director pe o linie separată # Rezultatele comenzii anterioare pot fi -# trimise urmatoarei comenzi drept argument -# Comanda grep filtreaza argumentele trimise cu sabloane. +# trimise următoarei comenzi drept argument +# Comanda grep filtrează argumentele trimise cu sabloane. # Astfel putem vedea fiserele .txt din directorul curent. ls -l | grep "\.txt" -# De asemenea poti redirectiona o comanda, input si error output -python2 hello.py < "input.in" -python2 hello.py > "output.out" -python2 hello.py 2> "error.err" -# Output-ul va suprascrie fisierul daca acesta exista. -# Daca vrei sa fie concatenate poti folosi ">>" - -# Comenzile pot fi inlocuite in interiorul altor comenzi folosind $( ): -# Urmatoarea comanda afiseaza numarul de fisiere -# si directoare din directorul curent -echo "Sunt $(ls | wc -l) fisiere aici." - -# Acelasi lucru se poate obtine folosind apostrf-ul inversat ``, -# dar nu pot fi folosite unele in interiorul celorlalte asa ca modalitatea -# preferata este de a folosi $( ) -echo "Sunt `ls | wc -l` fisiere aici." - -# Bash foloseste o instructiune 'case' care functioneaza -# in mod similar cu instructiunea switch din Java si C++ +# De asemenea, poți redirecționa date de intrare spre sau erori/date de ieșire +# dinspre o comandă +python2 hello.py < "intrare.in" +python2 hello.py > "ieșire.out" +python2 hello.py 2> "erori.err" +# Output-ul va suprascrie fișierul dacă acesta există. +# Daca vrei să fie concatenate datele poți folosi ">>" în loc de ">" + +# Comenzile pot fi înlocuite în interiorul altor comenzi folosind $( ): +# Urmatoarea comandă afișează numărul de fișiere +# și directoare din directorul curent +echo "Sunt $(ls | wc -l) fișiere aici." + +# Același lucru se poate obține folosind apostroful inversat ``, +# dar nu pot fi folosite limbricate, așa ca modalitatea +# preferată este de a folosi $( ) +echo "Sunt `ls | wc -l` fișiere aici." + +# Bash folosește o instrucțiune 'case' care funcționeaza +# în mod similar cu instructiunea switch din Java si C++ case "$VARIABLE" in 0) echo "Este un zero.";; 1) echo "Este un unu.";; *) echo "Nu este null";; esac -# Instructiunea for parcurge toate elementele trimise: -# Continutul variabilei $VARIABLE este printat de 3 ori +# Instrucțiunea 'for' parcurge toate elementele trimise: +# Conținutul variabilei $VARIABLE este printat de 3 ori for VARIABLE in {1..3} do echo "$VARIABLE" done -# while loop: +# Buclă while: while [true] do - echo "in interiorul iteratiei aici..." + echo "în interiorul iterației aici..." break done -# De asemenea poti defini functii -# Definitie: +# De asemenea poți defini funcții +# Definiție: function foo () { - echo "Argumentele functioneaza ca si argumentele scriptului: $@" + echo "Argumentele funcționeaza ca și argumentele scriptului: $@" echo "Si: $1 $2..." - echo "Asta este o functie" + echo "Asta este o funcție" return 0 } -# sau mai simplu +# sau mai simplu: bar () { - echo "Alta metoda de a declara o functie" + echo "Altă metodă de a declara o funcție" return 0 } -# Invocarea unei functii +# Invocarea unei funcții: foo "Numele meu este: " $NAME -# Sunt o multime de comenzi utile pe care ar trebui sa le inveti: +# Sunt o multime de comenzi utile pe care ar trebui să le inveți: tail -n 10 file.txt -# printeaza ultimele 10 linii din fisierul file.txt +# afișează ultimele 10 linii din fișierul file.txt + head -n 10 file.txt -# printeaza primele 10 linii din fisierul file.txt +# afișează primele 10 linii din fișierul file.txt + sort file.txt -# sorteaza liniile din file.txt +# sortează liniile din file.txt + uniq -d file.txt -# raporteaza sau omite liniile care se repeta, cu -d le raporteaza +# raporteaza sau omite liniile care se repetă. Cu -d le raporteaza + cut -d ',' -f 1 file.txt -# printeaza doar prima coloana inainte de caracterul "," +# printează doar prima coloană inainte de caracterul "," ``` -- cgit v1.2.3 From a81b72b29554b27a3d640711a3ead9d84f41db53 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Thu, 15 Oct 2015 23:57:48 +0300 Subject: [rmux/ru] Add russian translation for tmux doc --- ru-ru/tmux-ru.html.markdown | 253 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 ru-ru/tmux-ru.html.markdown diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown new file mode 100644 index 00000000..b379fb4b --- /dev/null +++ b/ru-ru/tmux-ru.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Davydov Anton", "https://github.com/davydovanton"] +filename: LearnTmux.txt +lang: ru-ru +--- + +[tmux](http://tmux.sourceforge.net) - терминальный мультиплексор. +Он позволяет создавать, получать доступ и контролировать любое +количество терминалов из единого окна. +Сессия tmux также может быть закрыта из экрана терминала, и она +будет работать в фоне, а после к ней можно будет подключиться. + + +``` + + tmux [command] # Запуск команды 'tmux' + # без какой-либо команды создаст новую сессию + + new # Создать новую сессию + -s "Session" # Создать именованную сессию + -n "Window" # Создать именованное окно + -c "/dir" # Запустить сессию в конкретной директории + + attach # Подключиться к последней/существующей сессии + -t "#" # Подключиться к определенной сессии + -d # Завершить определенную сессию + + ls # Список открытых сессий + -a # Список всех открытых сессиий + + lsw # Список окон + -a # Список всех окон + -s # Список всех окон в сессии + + lsp # Список панелей + -a # Список всех панелей + -s # Список всех панелей в сессии + -t # Список всех панелей для конкретного объекта + + kill-window # Закрыть текущее окно + -t "#" # Закрыть конкретное окно + -a # Закрыть все окна + -a -t "#" # Закрыть все окна кроме конкретного + + kill-session # Завершить текущую сессию + -t "#" # Завершить конкретную сессию + -a # Завершить все сессии + -a -t "#" # Завершить все сессии кроме конкретной + +``` + + +### Горячие клавиши + +Способ, с помощью которого контролируется любая tmux +сессия - комбинация клавиш, называемая 'Префиксом'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # 'Префикс' необходим для + # использования горячих клавиш + + (M-1) = Meta + 1 -или- Alt + 1 +---------------------------------------------------------------------- + + ? # Список всех горячих клавиш + : # Начать ввод в командной строке tmux + r # Принудительная перерисовка текущего клиента + c # Создать новое окно + + ! # Переместить текущую панель в отдельное окно + % # Разделить текущую панель на две: левую и правую + " # Разделить текущую панель на две: верхнюю и нижнюю + + n # Переместиться на следующее окно + p # Переместиться на предыдущее окно + { # Заменить текущую панель на предыдущую + } # Заменить текущую панель на следующую + + s # Интерактивный выбор запущенных сессий + w # Интерактивный выбор текущего окна + от 0 до 9 # Выбрать окно номер 0..9 + + d # Отключить текущий клиент + D # Выбрать клиент, который будет отключен + + & # Закрыть текущее окно + x # Закрыть текущую панель + + Up, Down # Переместиться на панель выше, ниже, левее + Left, Right # или правее + + M-1 to M-5 # Расставить панели: + # 1) выровнять по горизонтали + # 2) выровнять по вертикали + # 3) основное горизонтально + # 4) основное вертикально + # 5) мозаикой + + C-Up, C-Down # Изменение размера текущей панели с шагом в одну + C-Left, C-Right # колонку + + M-Up, M-Down # Изменение размера текущей панели с шагом в пять + M-Left, M-Right # колонок + +``` + + +### Настройка ~/.tmux.conf + +tmux.conf файл может быть использован для автоматической установки +опций при старте, как, например, .vimrc или init.el. + +``` +# Пример файла tmux.conf +# 2014.10 + + +### Основные конфигурации +########################################################################### + +# Включить поддержку UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Установить лимит истории +set -g history-limit 2048 + +# Порядковый номер первой панели +set -g base-index 1 + +# Включить поддержу мыши +set-option -g mouse-select-pane on + +# Принудительная перезагрузка конфигурационного файла +unbind r +bind r source-file ~/.tmux.conf + + +### Горячие клавиши +########################################################################### + +# Отменить комбинацию C-b как стандартный префикс +unbind C-b + +# Установить новую комбинацию как префикс +set-option -g prefix ` + +# Вернуть предыдущее окно, если префикс был нажат два раза +bind C-a last-window +bind ` last-window + +# Разрешить замену C-a и ` на F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Настройки клавиш +setw -g mode-keys vi +set-option -g status-keys vi + +# Перемещение между панелями как в vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Переключить/Заменить окно +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Комманды упрощающие разделением панелей +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Активировать inner-most сессию (когда вложенный tmux) для отправки команд +bind a send-prefix + + +### Цветовая схема +########################################################################### + +# Цветовая палитра статусбара +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Цветовая палитра окантовки панели +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Цветовая палитра сообщений +set-option -g message-fg black +set-option -g message-bg green + +# Цветовая палитра окна статусов +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Нотификации +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Автоматическая установка заголовка окна +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Настройки статусбара +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Показывать системные характеристики в статусбаре +# Требует https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Ссылки + +[Tmux | Домашняя страница](http://tmux.sourceforge.net) + +[Страница мануала Tmux](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Отображение CPU/MEM % в статусбаре](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From 43c180d954eb9ae25c7a4d5d86dc1a4edf4c123c Mon Sep 17 00:00:00 2001 From: Zirak Date: Fri, 16 Oct 2015 22:24:28 +0000 Subject: Update hy.html.markdown Added some more recent hy changes (class syntax, `cut` instead of slice), as well as some missing operators (`->` and `->>`) and function declarations (using `&rest` and `&kwargs` along with `apply`). Also changed the code block syntax to hy since github recognises it. --- hy.html.markdown | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/hy.html.markdown b/hy.html.markdown index 9beaff0c..039312db 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -3,15 +3,16 @@ language: hy filename: learnhy.hy contributors: - ["Abhishek L", "http://twitter.com/abhishekl"] + - ["Zirak", "http://zirak.me"] --- Hy is a lisp dialect built on top of python. This is achieved by converting hy code to python's abstract syntax tree (ast). This allows hy to call native python code or python to call native hy code as well -This tutorial works for hy ≥ 0.9.12 +This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11. -```clojure +```hy ;; this gives an gentle introduction to hy for a quick trial head to ;; http://try-hy.appspot.com ;; @@ -89,6 +90,17 @@ True ; => True (foolists 3) ;=> [3 2] (foolists 10 3) ;=> [10 3] +; you can use rest arguments and kwargs too: +(defn something-fancy [wow &rest descriptions &kwargs props] + (print "Look at" wow) + (print "It's" descriptions) + (print "And it also has:" props)) + +(something-fancy "My horse" "amazing" :mane "spectacular") + +; you use apply instead of the splat operators: +(apply something-fancy ["My horse" "amazing"] { "mane" "spectacular" }) + ; anonymous functions are created using `fn' or `lambda' constructs ; which are similiar to `defn' (map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] @@ -102,6 +114,8 @@ True ; => True ; slice lists using slice (slice mylist 1 3) ;=> [2 3] +; or, in hy 0.11, use cut instead: +(cut mylist 1 3) ;=> [2 3] ; get elements from a list or dict using `get' (get mylist 1) ;=> 2 @@ -122,6 +136,22 @@ True ; => True ; a.foo(arg) is called as (.foo a arg) (.split (.strip "hello world ")) ;=> ["hello" "world"] +; there is a shortcut for executing multiple functions on a value called the +; "threading macro", denoted by an arrow: +(-> "hello world " (.strip) (.split)) ;=> ["hello" "world] +; the arrow passes the value along the calls as the first argument, for instance: +(-> 4 (* 3) (+ 2)) +; is the same as: +(+ (* 4 3) 2) + +; there is also a "threading tail macro", which instead passes the value as the +; second argument. compare: +(-> 4 (- 2) (+ 1)) ;=> 3 +(+ (- 4 2) 1) ;=> 3 +; to: +(->> 4 (- 2) (+ 1)) ;=> -1 +(+ 1 (- 2 4)) ;=> -1 + ;; Conditionals ; (if condition (body-if-true) (body-if-false) (if (= passcode "moria") @@ -160,6 +190,14 @@ True ; => True [get-spell (fn [self] self.spell)]]) +; or, in hy 0.11: +(defclass Wizard [object] + (defn --init-- [self spell] + (setv self.spell spell)) + + (defn get-spell [self] + self.spell)) + ;; do checkout hylang.org ``` -- cgit v1.2.3 From 64aa38a1d28d6e3b9f770e97476f0111f180bd3e Mon Sep 17 00:00:00 2001 From: Akshay Kalose Date: Fri, 16 Oct 2015 22:07:08 -0400 Subject: Add More Magic Methods in PHP --- php.html.markdown | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 39ec5aef..78d9d1f2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -498,10 +498,23 @@ class MyClass print 'MyClass'; } - //final keyword would make a function unoverridable + // final keyword would make a function unoverridable final function youCannotOverrideMe() { } + + // Magic Methods + + // what to do if Object is treated as a String + public function __toString() { + return $property; + } + + // opposite to __construct() + // called when object no longer referenced + public function __destruct() { + print "Destroying" + } /* * Declaring class properties or methods as static makes them accessible without -- cgit v1.2.3 From 7f2f4b1dfc5183109bc7ef3a1892b79819015bbb Mon Sep 17 00:00:00 2001 From: Zirak Date: Sat, 17 Oct 2015 20:49:34 +0000 Subject: Changed code block language to clojure ...again :( --- hy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hy.html.markdown b/hy.html.markdown index 039312db..5333410e 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -12,7 +12,7 @@ hy to call native python code or python to call native hy code as well This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11. -```hy +```clojure ;; this gives an gentle introduction to hy for a quick trial head to ;; http://try-hy.appspot.com ;; -- cgit v1.2.3 From 13adcc49e616d81a8d89179e95619846eaf6f9b1 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 14:14:51 +0200 Subject: Translated git.html.markdown into Italian --- it-it/git-it.html.markdown | 497 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 it-it/git-it.html.markdown diff --git a/it-it/git-it.html.markdown b/it-it/git-it.html.markdown new file mode 100644 index 00000000..42510192 --- /dev/null +++ b/it-it/git-it.html.markdown @@ -0,0 +1,497 @@ +--- +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"] +translators: + - ["Christian Grasso", "http://chris54721.net"] +filename: LearnGit.txt +--- + +Git è un sistema di +[controllo versione distribuito](https://it.wikipedia.org/wiki/Controllo_versione_distribuito) +e di gestione del codice sorgente. + +Git esegue una serie di _snapshot_ per salvare lo stato di un progetto, così +facendo può fornirti la possibilità di gestire il tuo codice e di salvarne lo +stato assegnando delle versioni. + +## Basi del controllo versione + +### Cos'è il controllo versione? + +Il controllo versione (_Version Control_ o _Versioning_) è un sistema che +registra le modifiche apportate a uno o più file nel tempo. + +### Controllo versione centralizzato e distribuito + +* Il controllo versione centralizzato si concentra sulla sincronizzazione, il + monitoraggio e il backup dei file. +* Il controllo versione distribuito si concentra sulla condivisione delle + modifiche. Ogni modifica ha un identificatore univoco. +* I sistemi distribuiti non hanno una struttura definita. Si potrebbe creare + ad esempio un sistema centralizzato simile a SVN utilizzando Git. + +[Ulteriori informazioni](http://git-scm.com/book/it/v1/Per-Iniziare-Il-Controllo-di-Versione) + +### Perchè usare Git? + +* Consente di lavorare offline. +* Collaborare con altre persone è semplice! +* Utilizzare i branch (rami di sviluppo) è semplice! +* Git è veloce. +* Git è flessibile. + +## Architettura di Git + +### Repository + +Un insieme di file, cartelle, registrazioni della cronologia e versioni. +Immaginalo come una struttura dati del codice, con la caratteristica che ogni +"elemento" del codice ti fornisce accesso alla sua cronologia delle revisioni, +insieme ad altre cose. + +Un repository comprende la cartella .git e il working tree. + +### Cartella .git (componente del repository) + +La cartella .git contiene tutte le configurazioni, i log, i rami e altro. +[Lista dettagliata](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Working Tree (componente del repository) + +Si tratta semplicemente delle cartelle e dei file presenti nel repository. +Spesso viene indicato come "directory di lavoro" ("working directory"). + +### Index (componente della cartella .git) + +L'Index è l'area di staging di Git. Si tratta di un livello che separa il +working tree dal repository. Ciò fornisce agli sviluppatori più controllo su +cosa viene inviato al repository. + +### Commit + +Un commit è uno snapshot di una serie di modifiche apportate al working tree. +Ad esempio, se hai aggiunto 5 file e ne hai rimossi 2, ciò sarà registrato in +un commit. Il commit può essere pushato (inviato) o meno ad altri repository. + +### Branch (ramo) + +Un branch (ramo) è essenzialmente un puntatore all'ultimo commit che hai +effettuato. Effettuando altri commit, il puntatore verrà automaticamente +aggiornato per puntare all'ultimo commit. + +### Tag + +Un tag è un contrassegno applicato a un punto specifico nella cronologia dei +commit. Di solito i tag vengono utilizzati per contrassegnare le versioni +rilasciate (v1.0, v1.1, etc.). + +### HEAD e head (componenti della cartella .git) + +HEAD (in maiuscolo) è un puntatore che punta al branch corrente. Un repository +può avere solo 1 puntatore HEAD *attivo*. + +head (in minuscolo) è un puntatore che può puntare a qualsiasi commit. Un +repository può avere un numero qualsiasi di puntatori head. + +### Stadi di Git +* _Modified_ - Un file è stato modificato, ma non è ancora stato effettuato + un commit per registrare le modifiche nel database di Git +* _Staged_ - Un file modificato è stato contrassegnato per essere incluso nel + prossimo commit +* _Committed_ - È stato effettuato un commit e le modifiche sono state + registrate nel database di Git + +## Comandi + +### init + +Crea un repository Git vuoto. Le impostazioni e le informazioni del repository +sono salvate nella cartella ".git". + +```bash +$ git init +``` + +### config + +Utilizzato per configurare le impostazioni, sia specifiche del repository, sia +a livello globale. Le impostazioni globali sono salvate in `~/.gitconfig`. + +```bash +$ git config --global user.email "email@example.com" +$ git config --global user.name "Nome utente" +``` + +[Ulteriori informazioni su git config](http://git-scm.com/docs/git-config) + +### help + +Fornisce una documentazione molto dettagliata di ogni comando. + +```bash +# Mostra i comandi più comuni +$ git help + +# Mostra tutti i comandi disponibili +$ git help -a + +# Documentazione di un comando specifico +# git help +$ git help add +$ git help commit +$ git help init +# oppure git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### Ignorare file + +Per impedire intenzionalmente che file privati o temporanei vengano inviati +al repository Git. + +```bash +$ echo "temp/" >> .gitignore +$ echo "privato.txt" >> .gitignore +``` + + +### status + +Mostra le differenza tra lo stato attuale del working tree e l'attuale commit +HEAD. + +```bash +$ git status +``` + +### add + +Aggiunge file alla staging area, ovvero li contrassegna per essere inclusi nel +prossimo commit. Ricorda di aggiungere i nuovi file, altrimenti non saranno +inclusi nei commit! + +```bash +# Aggiunge un file nella directory attuale +$ git add HelloWorld.java + +# Aggiunge un file in una sottocartella +$ git add /path/to/file/HelloWorld.c + +# Il comando supporta le espressioni regolari +$ git add ./*.java + +# Aggiunge tutti i file non ancora contrassegnati +$ git add --all +``` + +Questo comando contrassegna soltanto i file, senza effettuare un commit. + +### branch + +Utilizzato per gestire i branch (rami). Puoi visualizzare, modificare, creare o +eliminare branch utilizzando questo comando. + +```bash +# Visualizza i branch e i remote +$ git branch -a + +# Crea un nuovo branch +$ git branch nuovoBranch + +# Elimina un branch +$ git branch -d nomeBranch + +# Rinomina un branch +$ git branch -m nomeBranch nuovoNomeBranch + +# Permette di modificare la descrizione di un branch +$ git branch nomeBranch --edit-description +``` + +### tag + +Utilizzato per gestire i tag. + +```bash +# Visualizza i tag esistenti +$ git tag +# Crea un nuovo tag +# L'opzione -m consente di specificare una descrizione per il tag. +# Se l'opzione -m non viene aggiunta, Git aprirà un editor per consentire +# l'inserimento del messaggio. +$ git tag -a v2.0 -m 'Versione 2.0' +# Mostra informazioni relative a un tag +# Include informazioni sul creatore del tag, la data di creazione, e il +# messaggio assegnato al tag oltre alle informazioni sul commit. +$ git show v2.0 +``` + +### checkout + +Consente di cambiare branch o ripristinare i file a una revisione specifica. +Tutti i file nel working tree vengono aggiornati per corrispondere alla versione +presente nel branch o nel commit specificato. + +```bash +# Effettua il checkout di un repository - il branch predefinito è 'master' +$ git checkout +# Effettua il checkout di un branch specifico +$ git checkout nomeBranch +# Crea un nuovo branch e ne effettua il checkout +# Equivalente a "git branch ; git checkout " +$ git checkout -b nuovoBranch +``` + +### clone + +Clona, o copia, un repository esistente in una nuova directory. Inoltre, +aggiunge dei branch _remote-tracking_, utilizzati per monitorare i branch +remoti corrispondenti a quelli locali, e consentendo così di inviare le +modifiche al repository remoto. + +```bash +# Clona learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +# Clona solo l'ultima revisione di un repository +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# Clona solo un branch specifico +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Effettua uno _snapshot_ dello stato attuale del working tree e registra le +modifiche in un nuovo commit. Il commit contiene, oltre alle modifiche apportate, +anche l'autore e una descrizione. + +```bash +# Crea un nuovo commit con un messaggio +$ git commit -m "Aggiunta la funzione multiplyNumbers() in HelloWorld.c" + +# Aggiunge (git add) automaticamente i file modificati o eliminati (ESCLUSI +# i nuovi file) e quindi effettua il commit +$ git commit -a -m "Modificato foo.php e rimosso bar.php" + +# Modifica l'ultimo commit (il comando elimina il commit precedente e lo +# sostituisce con uno nuovo) +$ git commit --amend -m "Messaggio corretto" +``` + +### diff + +Mostra la differenza tra un file nel working tree e la sua versione nell'index, +in un branch o ad un commit specifico. + +```bash +# Mostra la differenza tra il working tree e l'index +$ git diff + +# Mostra la differenza tra l'index e il commit più recente +$ git diff --cached + +# Mostra la differenza tra il working tree e un commit specifico +$ git diff + +# Mostra la differenza tra due commit +$ git diff +``` + +### grep + +Consente di effettuare una ricerca veloce nel repository. + +```bash +# Cerca "variableName" nei file Java +$ git grep 'variableName' -- '*.java' + +# Cerca una riga contenente "arrayListName" E "add" oppure "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Impostazioni relative a `git grep`: + +```bash +# Mostra il numero delle righe +$ git config --global grep.lineNumber true + +# Rende i risultati più leggibili +$ git config --global alias.g "grep --break --heading --line-number" +``` + +### log + +Mostra la cronologia dei commit inviati al repository. + +```bash +# Mostra tutti i commit +$ git log + +# Mostra ogni commit su una sola riga +$ git log --oneline + +# Mostra solo i commit legati ai merge +$ git log --merges +``` + +### merge + +Effettua un "merge", ovvero unisce le modifiche di un branch in quello attuale. + +```bash +# Unisce il branch specificato a quello attuale +$ git merge nomeBranch + +# Genera un commit in ogni caso dopo aver eseguito il merge +$ git merge --no-ff nomeBranch +``` + +### mv + +Rinomina o sposta un file. + +```bash +# Rinomina un file +$ git mv HelloWorld.c HelloNewWorld.c + +# Sposta un file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Forza l'esecuzione del comando +# Se un file "nuovoNomeFile" esiste già nella directory, verrà sovrascritto +$ git mv -f nomeFile nuovoNomeFile +``` + +### pull + +Aggiorna il repository effettuando il merge delle nuove modifiche. + +```bash +# Aggiorna il branch attuale dal remote "origin" +$ git pull + +# Di default, git pull aggiorna il branch attuale effettuando il merge +# delle nuove modifiche presenti nel branch remote-tracking corrispondente +$ git pull + +# Aggiorna le modifiche dal branch remoto, quindi effettua il rebase dei commit +# nel branch locale +# Equivalente a: "git pull ; git rebase " +$ git pull origin master --rebase +``` + +### push + +Invia ed effettua il merge delle modifiche da un branch locale ad uno remoto. + +```bash +# Invia ed effettua il merge delle modifiche dal branch "master" +# al remote "origin". +# git push +$ git push origin master + +# Di default, git push invia ed effettua il merge delle modifiche +# dal branch attuale al branch remote-tracking corrispondente +$ git push + +# Per collegare il branch attuale ad uno remoto, basta aggiungere l'opzione -u +$ git push -u origin master +``` + +### stash + +Salva lo stato attuale del working tree in una lista di modifiche non ancora +inviate al repository con un commit che possono essere applicate nuovamente +in seguito. + +Questo comando può essere utile se, ad esempio, mentre stai effettuando delle +modifiche non ancora completate, hai bisogno di aggiornare il repository locale +con `git pull`. Poichè non hai ancora effettuato il commit di tutte le modifiche, +non sarà possibile effettuare il pull. Tuttavia, puoi utilizzare `git stash` per +salvare temporaneamente le modifiche e applicarle in seguito. + +```bash +$ git stash +``` + +Ora puoi effettuare il pull: + +```bash +$ git pull +``` + +A questo punto, come già suggerito dall'output del comando `git stash`, puoi +applicare le modifiche: + +```bash +$ git stash apply +``` + +Infine puoi controllare che tutto sia andato bene: + +```bash +$ git status +``` + +Puoi visualizzare gli accantonamenti che hai effettuato finora utilizzando: + +```bash +$ git stash list +``` + +### rebase (attenzione) + +Applica le modifiche effettuate su un branch su un altro branch. +*Non effettuare il rebase di commit che hai già inviato a un repository pubblico!* + +```bash +# Effettua il rebase di experimentBranch in master +$ git rebase master experimentBranch +``` + +[Ulteriori informazioni](https://git-scm.com/book/it/v1/Diramazioni-in-Git-Rifondazione) + +### reset (attenzione) + +Effettua il reset del commit HEAD attuale ad uno stato specifico. +Questo comando consente di annullare `merge`, `pull`, `commit`, `add` e altro. +Tuttavia, può essere pericoloso se non si sa cosa si sta facendo. + +```bash +# Effettua il reset della staging area (annullando le aggiunte e le rimozioni +# di file dal repository, senza modificare il working tree) +$ git reset + +# Effettua il reset completo della staging area, ovvero annulla qualsiasi +# modifica al repository eliminando definitivamente anche tutte le modifiche +# ai file non inviate e ripristinando il working tree +$ git reset --hard + +# Effettua il reset del branch attuale al commit specificato (lasciando il +# working tree intatto) +$ git reset 31f2bb1 + +# Effettua il reset completo del branch attuale al commit specificato, +# eliminando qualsiasi modifica non inviata +$ git reset --hard 31f2bb1 +``` + +### rm + +Consente di rimuovere un file dal working tree e dal repository. +Per eliminare un file solo dal working tree ma non dal repository, è invece +necessario utilizzare `/bin/rm`. + +```bash +# Elimina un file nella directory attuale +$ git rm HelloWorld.c + +# Elimina un file da una sottocartella +$ git rm /pather/to/the/file/HelloWorld.c +``` -- cgit v1.2.3 From 6b58f22ec9bd3809f39a6ba62bcac02161fc6214 Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sun, 18 Oct 2015 18:07:43 +0200 Subject: First version of Make to german translation --- de-de/make-de.html.markdown | 260 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 de-de/make-de.html.markdown diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown new file mode 100644 index 00000000..bed7abf3 --- /dev/null +++ b/de-de/make-de.html.markdown @@ -0,0 +1,260 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: Makefile +lang: de-de +--- + +Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele) +zu erzeugen. Es dient dazu die geringste Menge an Arbeit zu verrichten um +ein Ziel in einklang mit dem Quellcode zu bringen. Make wurde berühmterweise +von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer +sehr verbreitet (vorallem im Unix umfeld) obwohl es bereits sehr viel +Konkurrenz und Kritik zu Make gibt. + +Es gibt eine vielzahl an Varianten von Make, dieser Artikel beschäftig sich +mit der Version GNU Make. Diese Version ist standard auf Linux. + +```make + +# Kommentare können so geschrieben werden. + +# Dateien sollten Makefile heißen, denn dann können sie als `make ` +# aufgerufen werden. Ansonsten muss `make -f "dateiname" ` verwendet +# werden. + +# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet +# werden. Niemals Leerzeichen! + +#----------------------------------------------------------------------- +# Grundlagen +#----------------------------------------------------------------------- + +# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt +# nicht existiert. +file0.txt: + echo "foo" > file0.txt + # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell + # weitergegeben. Versuche `make file0.txt` oder einfach `make` + # die erste Regel ist die Standard-Regel. + + +# Diese Regel wird nur abgearbeitet wenn file0.txt aktueller als file1.txt ist. +file1.txt: file0.txt + cat file0.txt > file1.txt + # Verwende die selben Quoting-Regeln wie die Shell + @cat file0.txt >> file1.txt + # @ unterdrückt die Ausgabe des Befehls an stdout. + -@echo 'hello' + # - bedeutet das Make die Abarbeitung fortsetzt auch wenn Fehler passieren. + # Versuche `make file1.txt` auf der Kommandozeile. + +# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben. +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt. +# Leere Rezepte zählen nicht und können dazu verwendet werden weitere +# Voraussetzungen hinzuzufügen. + +#----------------------------------------------------------------------- +# Phony-Ziele +#----------------------------------------------------------------------- + +# Ein Phony-Ziel ist ein Ziel das keine Datei ist. +# Es wird nie aktuell sein, daher wird Make immer versuchen es abzuarbeiten +all: maker process + +# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren. +maker: + touch ex0.txt ex1.txt + +# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den +# selben namen wie ein Phony-Ziel hat: +.PHONY: all maker process +# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon. + +# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet +ex0.txt ex1.txt: maker + +# Häufige Phony-Ziele sind: all make clean install ... + +#----------------------------------------------------------------------- +# Automatische Variablen & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt # Eine Wildcard um Dateinamen zu Vergleichen + @echo $^ # $^ ist eine Variable die eine Liste aller + # Voraussetzungen enthält. + @echo $@ # Namen des Ziels ausgeben. + #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung + #der Regel.) + @echo $< # Die erste Voraussetzung aus der Liste + @echo $? # Nur die Voraussetzungen die nicht aktuell sind. + @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich) + #@echo $| # Alle 'order only' Voraussetzungen + +# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden. +process: ex1.txt file0.txt +# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert. + +#----------------------------------------------------------------------- +# Muster +#----------------------------------------------------------------------- + +# Mit Mustern kann man make beibringen wie Dateien in andere Dateien +# umgewandelt werden. + +%.png: %.svg + inkscape --export-png $^ + +# Muster-Vergleichs-Regeln werden nur abgearbeitet wenn make entscheidet das Ziel zu +# erzeugen + +# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert. +# Aber make wird versuchen die am besten passende Regel zu verwenden. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden die es +# findet. +%.png: %.svg + @echo this rule is chosen + +# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden die das +# Ziel erzeugen kann. +%.png: %.ps + @echo this rule is not chosen if *.svg and *.ps are both present + +# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel +# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt. + +# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt +# Muster-Vergleichs-Regeln. +.png.ps: + @echo this rule is similar to a pattern rule. + +# Aktivieren der Suffix-Regel +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variablen +#----------------------------------------------------------------------- +# auch Makros genannt. + +# Variablen sind im Grunde genommen Zeichenketten-Typen. + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt. + @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt. + +# Es git 4 Stellen um Variablen zu setzen. +# In Reihenfolge der Priorität von höchster zu niedrigster: +# 1: Befehls-Zeilen Argumente +# 2: Makefile +# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch. +# 3: MAke hat einige vordefinierte Variablen. + +name4 ?= Jean +# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch +# nicht gibt. + +override name5 = David +# Verhindert das Kommando-Zeilen Argumente diese Variable ändern können. + +name4 +=grey +# Werte an eine Variable anhängen (inkludiert Leerzeichen). + +# Muster-Spezifische Variablen Werte (GNU Erweiterung). +echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb + # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören + # kann wenn es zu kompilizert wird!) + +# Ein paar Variablen die von Make automatisch definiert werden. +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variablen 2 +#----------------------------------------------------------------------- + +# Der erste Typ von Variablen wird bei jeder verwendung ausgewertet. +# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen. +# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung) + +var := hello +var2 ::= $(var) hello +#:= und ::= sind äquivalent. + +# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie +# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache! + +# Das funktioniert nicht +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funktionen +#----------------------------------------------------------------------- + +# Make verfügt über eine vielzahl von Funktionen. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Das Format ist $(func arg0,arg1,arg2...) + +# Ein paar Beispiele +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Direktiven +#----------------------------------------------------------------------- + +# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code +include foo.mk + +sport = tennis +# Konditionale kompiliereung +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Es gibt auch ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + + +### Mehr Resourcen + ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) + -- cgit v1.2.3 From 5cb7eba92135b3617b5247fddeb98a7e2585bca8 Mon Sep 17 00:00:00 2001 From: Brett Taylor Date: Mon, 19 Oct 2015 09:15:33 +1300 Subject: [asymptotic-notation/en] added link to Big-O Cheat Sheet --- asymptotic-notation.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown index a516737e..4167ba8d 100644 --- a/asymptotic-notation.html.markdown +++ b/asymptotic-notation.html.markdown @@ -137,3 +137,4 @@ code examples soon. * [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) * [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) +* [Big-O Cheatsheet](http://bigocheatsheet.com/) - common structures, operations, and algorithms, ranked by complexity. -- cgit v1.2.3 From 5c8942f7bcb02a59d1e0acefb0069e80de57e01e Mon Sep 17 00:00:00 2001 From: viv1 Date: Mon, 19 Oct 2015 02:50:55 +0530 Subject: [bash/en]...Added info on changing directories --- bash.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 211d2944..dfbf9a89 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -130,6 +130,15 @@ ls -l # Lists every file and directory on a separate line # .txt files in the current directory: ls -l | grep "\.txt" +# Since bash works in the context of a current directory, you might want to +# run your command in some other directory. We have cd for changing location: +cd ~ # change to home directory +cd .. # go up one directory + # (^^say, from /home/username/Downloads to /home/username) +cd /home/username/Documents # change to specified directory +cd ~/Documents/.. # still in home directory..isn't it?? + + # You can redirect command input and output (stdin, stdout, and stderr). # Read from stdin until ^EOF$ and overwrite hello.py with the lines # between "EOF": -- cgit v1.2.3 From d9f3b13e278eebb173253c756ffe847b3188f4af Mon Sep 17 00:00:00 2001 From: Akshay Kalose Date: Sun, 18 Oct 2015 17:37:39 -0400 Subject: Fix Grammar and Syntax --- php.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 78d9d1f2..ac0a83b9 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -511,9 +511,9 @@ class MyClass } // opposite to __construct() - // called when object no longer referenced + // called when object is no longer referenced public function __destruct() { - print "Destroying" + print "Destroying"; } /* -- cgit v1.2.3 From 7c342d41d141b375d287ed09c623d5c5a6cfb0e0 Mon Sep 17 00:00:00 2001 From: Felix Date: Mon, 19 Oct 2015 09:02:07 +0200 Subject: fixed link to the freebsd handbook --- zfs.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 74487e35..f99d7134 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -393,7 +393,7 @@ echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ### Additional Reading * [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) -* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/ZFS) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) * [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) * [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) * [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) -- cgit v1.2.3 From adefaa5fdf1de01dc8318a69d440bfc71a7629c7 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:07:17 -0300 Subject: Ruby Ecosystem translation to portuguese The whole article has been translated. --- pt-br/ruby-ecosystem-pt.html.markdown | 147 ++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 pt-br/ruby-ecosystem-pt.html.markdown diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown new file mode 100644 index 00000000..0298f8a1 --- /dev/null +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -0,0 +1,147 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Claudson Martins", "http://github.com/claudsonm"] +lang: pt-br + +--- + +Pessoas utilizando Ruby geralmente têm uma forma de instalar diferentes versões +do Ruby, gerenciar seus pacotes (ou gemas) e as dependências das gemas. + +## Gerenciadores Ruby + +Algumas plataformas possuem o Ruby pré-instalado ou disponível como um pacote. +A maioria dos "rubistas" não os usam, e se usam, é apenas para inicializar outro +instalador ou implementação do Ruby. Ao invés disso, rubistas tendêm a instalar +um gerenciador para instalar e alternar entre diversas versões do Ruby e seus +ambientes de projeto. + +Abaixo estão os gerenciadores Ruby mais populares: + +* [RVM](https://rvm.io/) - Instala e alterna entre os rubies. RVM também possui + o conceito de gemsets para isolar os ambientes dos projetos completamente. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Apenas instala os + rubies. Use este para um melhor controle sobre a instalação de seus rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Apenas alterna entre os rubies. + Usado com o ruby-build. Use este para um controle mais preciso sobre a forma + como os rubies são carregados. +* [chruby](https://github.com/postmodern/chruby) - Apenas alterna entre os rubies. + A concepção é bastante similar ao rbenv. Sem grandes opções sobre como os + rubies são instalados. + +## Versões do Ruby + +O Ruby foi criado por Yukihiro "Matz" Matsumoto, que continua a ser uma espécie +de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), embora +isso esteja mudando recentemente. Como resultado, a implementação de referência +do Ruby é chamada de MRI (Matz' Reference Implementation), e quando você ver uma +versão do Ruby, ela está se referindo a versão de lançamento do MRI. + +As três principais versões do Ruby em uso são: + +* 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e + suporte a frameworks 2.0.0. +* 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - O Ruby 1.8.7 foi + [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +A diferença entre a versão 1.8.7 para 1.9.x é muito maior do que a da 1.9.3 para +a 2.0.0. Por exemplo, a série 1.9 introduziu encodes e uma VM bytecode. Ainda +existem projetos na versão 1.8.7, mas eles estão tornando-se uma pequena minoria +pois a maioria da comunidade migrou para a versão, pelo menos, 1.9.2 ou 1.9.3. + +## Implementações Ruby + +O ecossistema Ruby conta com várias diferentes implementações do Ruby, cada uma +com pontos fortes e estados de compatibilidade. Para ser claro, as diferentes +implementações são escritas em diferentes linguagens, mas *todas elas são Ruby*. +Cada implementação possui hooks especiais e recursos extra, mas todas elas +executam arquivos normais do Ruby tranquilamente. Por exemplo, JRuby é escrita +em Java, mas você não precisa saber Java para utilizá-la. + +Muito maduras/compatíveis: + +* [MRI](https://github.com/ruby/ruby) - Escrita em C, esta é a implementação de + referência do Ruby. Por definição, é 100% compatível (consigo mesma). Todos os + outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). +* [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação + robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + linguagens existentes. +* [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com + uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação + em Ruby, ela expõe muitos recursos da VM na rubyland. + +Medianamente maduras/compatíveis: + +* [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma + máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + e este projeto tenta trazer isso para o desenvolvimento Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. + +Pouco maduras/compatíveis: + +* [Topaz](http://topazruby.com/) - Escrita em RPython (usando o conjunto de + ferramentas PyPy), Topaz é bastante jovem e ainda não compatível. Parece ser + promissora como uma implementação Ruby de alta performance. +* [IronRuby](http://ironruby.net/) - Escrita em C# visando a plataforma .NET, + o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. + +Implementações Ruby podem ter seus próprios números de lançamento, mas elas +sempre focam uma versão específica da MRI para compatibilidade. Diversas +implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por +exemplo) para especificar qual versão da MRI focar. + +## RubySpec + +A maioria das implementações Ruby dependem fortemente da [RubySpec](http://rubyspec.org/). +Ruby não tem uma especificação oficial, então a comunidade tem escrito +especificações executáveis em Ruby para testar a compatibilidade de suas +implementações com a MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) é um gerenciador de pacotes para Ruby mantido +pela comunidade. RubyGems vem com o Ruby, portanto não é preciso baixar separadamente. + +Os pacotes do Ruby são chamados de "gemas", e elas podem ser hospedadas pela +comunidade em RubyGems.org. Cada gema contém seu código-fonte e alguns metadados, +incluindo coisas como versão, dependências, autor(es) e licença(s). + +## Bundler + +[Bundler](http://bundler.io/) é um gerenciador de dependências para as gemas. +Ele usa a Gemfile de um projeto para encontrar dependências, e então busca as +dependências dessas dependências de forma recursiva. Ele faz isso até que todas +as dependências sejam resolvidas e baixadas, ou para se encontrar um conflito. + +O Bundler gerará um erro se encontrar um conflito entre dependências. Por exemplo, +se a gema A requer versão 3 ou maior que a gema Z, mas a gema B requer a versão +2, o Bundler irá notificá-lo que há um conflito. Isso se torna extremamente útil +quando diversas gemas começam a referenciar outras gemas (que referem-se a outras +gemas), o que pode formar uma grande cascata de dependências a serem resolvidas. + +# Testes + +Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio +framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). +Existem diversas bibliotecas de teste com diferentes objetivos. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) + - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) + - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade +* [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados + +## Seja Legal + +A comunidade Ruby orgulha-se de ser uma comunidade aberta, diversa, e receptiva. +O próprio Matz é extremamente amigável, e a generosidade dos rubistas em geral +é incrível. -- cgit v1.2.3 From 09ceb868bc045d81fc4cf91b77708bb1f9671e50 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:16:49 -0300 Subject: Test list fix and some other minor improvements --- pt-br/ruby-ecosystem-pt.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown index 0298f8a1..da4f6f37 100644 --- a/pt-br/ruby-ecosystem-pt.html.markdown +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -47,7 +47,7 @@ As três principais versões do Ruby em uso são: * 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e suporte a frameworks 2.0.0. * 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas - atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/). * 1.8.7 - O Ruby 1.8.7 foi [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). @@ -72,7 +72,7 @@ Muito maduras/compatíveis: outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). * [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a - interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projetos, e linguagens existentes. * [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação @@ -81,7 +81,7 @@ Muito maduras/compatíveis: Medianamente maduras/compatíveis: * [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma - máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + máquina virtual Smalltalk. O Smalltalk possui algumas ferramentas impressionantes, e este projeto tenta trazer isso para o desenvolvimento Ruby. * [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. @@ -94,7 +94,7 @@ Pouco maduras/compatíveis: o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. Implementações Ruby podem ter seus próprios números de lançamento, mas elas -sempre focam uma versão específica da MRI para compatibilidade. Diversas +sempre focam em uma versão específica da MRI para compatibilidade. Diversas implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por exemplo) para especificar qual versão da MRI focar. @@ -133,10 +133,10 @@ Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). Existem diversas bibliotecas de teste com diferentes objetivos. -* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) -* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - + Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - + Framework de testes para o Ruby 1.9/2.0 (built-in) * [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade * [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados -- cgit v1.2.3 From 6c0652bc9c3615df8a62791110c2d02c867b4615 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 14:39:09 -0700 Subject: objc-spanish --- es-es/objective-c-es.html.markdown | 780 +++++++++++++++++++++++++++++++++++++ 1 file changed, 780 insertions(+) create mode 100644 es-es/objective-c-es.html.markdown diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown new file mode 100644 index 00000000..fc769188 --- /dev/null +++ b/es-es/objective-c-es.html.markdown @@ -0,0 +1,780 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] +translators: + - ["David Hsieh", "http://github.com/deivuh"] +lang: es-es +filename: LearnObjectiveC.m + +--- +Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch. +Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk". + + +```objective_c +// Los comentarios de una sola línea inician con // + +/* +Los comentarios de múltiples líneas se ven así. +*/ + +// Importa los encabezados de Foundation con #import +// Utiliza <> para importar archivos globales (generalmente frameworks) +// Utiliza "" para importar archivos locales (del proyecto) +#import +#import "MyClass.h" + +// Si habilitas módulos para proyectos de iOS >= 7.0 u OS X >= 10.9 en +// Xcode 5, puedes importarlos de la siguiente manera: +@import Foundation; + +// El punto de entrada de tu programa es una función llamada +// main con un tipo de retorno entero. +int main (int argc, const char * argv[]) +{ + // Crear un autorelease pool para manejar la memoria al programa + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + // Si se utiliza el conteo automático de referencias (ARC), utiliza @autoreleasepool: + @autoreleasepool { + + // Utiliza NSLog para imprimir líneas a la consola + NSLog(@"Hello World!"); // Imprimir el string "Hello World!" + + /////////////////////////////////////// + // Tipos y variables + /////////////////////////////////////// + + // Declaraciones de primitivos + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Declaraciones de objetos + // Pon el * como prefijo de los nombre de las variables para declaraciones de + // objetos de tipos fuertes + MyClass *myObject1 = nil; // Tipo fuerte + id myObject2 = nil; // Tipo débil + // %@ es un objeto + // 'description' es una convención para mostrar el valor de los objetos + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // imprime => "(null) y (null)" + + // String + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // imprime => "Hello World!" + // NSMutableString es una versión mutable del objeto NSString + NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; + [mutableString appendString:@" World!"]; + NSLog(@"%@", mutableString); // imprime => "Hello World!" + + // Literales de caracteres + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; // o 'Z' + NSLog(@"%c", theLetterZ); + + // Literales de enteros + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwoNumber intValue]; // o 42 + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // o 42 + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // o 42 + NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // o 41 + NSLog(@"%u", fortyOneUnsigned); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // o 42 + NSLog(@"%li", fortyTwoLong); + + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // o 53 + NSLog(@"%lu", fiftyThreeUnsigned); + + // Literales de punto flotante + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; // o 3.141592654f + NSLog(@"%f", piFloat); // imprime => 3.141592654 + NSLog(@"%5.2f", piFloat); // imprime => " 3.14" + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; // o 3.1415926535 + NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // imprime => "3.14" + + // NSDecimalNumber es una clase de punto-fijo que es más preciso que float o double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber no tiene la capacidad de utilizar los operadores estándares + // +, -, * , /, por lo que cuenta con sus propios operadores: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // imprime => 10.99 como NSDecimalNumber es inmutable + + // Literales BOOL + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + // o + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // prints => 1 + + // Objecto arreglo + // Puede contener diferentes tipos de datos, pero deben de ser un objeto de + // Objective-C + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // imprime => "Third number = 3" + // NSMutableArray es una versión mutable de NSArray, permitiendo el cambio + // de los elementos del arreglo y el agrandado o encojimiento del objeto arreglo. + // Conveniente, pero no tan eficiente como NSArray en cuanto a rendimiento. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Hello"]; + [mutableArray addObject:@"World"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // imprime => "World" + + // Objecto Diccionario + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // imprime => "Object = (null)" + // NSMutableDictionary también está disponible como un objeto mutable + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"value1" forKey:@"key1"]; + [mutableDictionary setObject:@"value2" forKey:@"key2"]; + [mutableDictionary removeObjectForKey:@"key1"]; + + // Objeto de Set + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // imprime => {(Hello, World)} (el orden puede variar) + // NSMutableSet también está disponible como un objeto mutable + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Hello"]; + [mutableSet addObject:@"Hello"]; + NSLog(@"%@", mutableSet); // prints => {(Hello)} + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + + // Los operadores funcionan como en el lenguaje C + // Por ejemplo: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (and lógico) + 0 || 1; // => 1 (or lógico) + ~0x0F; // => 0xF0 (negación bitwise) + 0x0F & 0xF0; // => 0x00 (AND bitwise) + 0x01 << 1; // => 0x02 (acarreamiento a la izquierda bitwise (por 1)) + + /////////////////////////////////////// + // Estructuras de control + /////////////////////////////////////// + + // Declaraciones If-Else + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Declaración Switch + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // Declaración de ciclos While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de utilizar su valor + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaración de ciclos For + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaraciones foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de Objective-C + for (id item in values) { + NSLog(@"%@,", item); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaraciones Try-Catch-Finally + @try + { + // Tus declaraciones aquí + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar todos los objetos + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally. Time to clean up."); + } // imprime => "Exception: File Not Found on System" + // "Finally. Time to clean up." + + // Los objetos NSError son útiles para argumentos de función para los errores de usuario. + NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; + + /////////////////////////////////////// + // Objetos + /////////////////////////////////////// + + // Crea una instancia de objeto alocando memoria e inicializándola + // Un objeto no es completamente funcional hasta que ambos pasos hayan sido + // completados + MyClass *myObject = [[MyClass alloc] init]; + + // El modelo de programación orientada a objetos de Objective-C es basada en + // el envío de mensajes a instancias de objetos + // En Objective-C no se llama a un método; se envía un mensaje + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Limpiar la memoria que se utilizó en el programa + [pool drain]; + + // Fin de @autoreleasepool + } + + // Fin del programa + return 0; +} + +/////////////////////////////////////// +// Clases y funciones +/////////////////////////////////////// + +// Declara tu clase en archivo de encabezado (MyClass.h) +// Sintaxis de declaración de clase: +// @interface NombreDeClase : NombreDeClasePadre +// { +// type nombre; <= declaraciones de variables; +// } +// @property tipo nombre; <= declaración de propiedades +// -/+ (tipo) Declaración de método; <= Declaración de método +// @end +@interface MyClass : NSObject // NSObject es la clase de objeto base de Objective-C. +{ + // Declaraciones de variables de instancia (puede existir en el archivo de interfaz o de implementación) + int count; // Acceso protegido por defecto. + @private id data; // Acceso privado (Más conveniente de declarar en el archivo de implementación) + NSString *name; +} +// Notación conveneinte para acceso público de las variables para generar un método setter +// Por defecto, el nombre del método setter 'set' seguido del nombre de variable @property +@property int propInt; // Nombre del método 'setter' = 'setPropInt' +@property (copy) id copyId; // (copy) => Copia el objeto durante la asignación +// (readonly) => No se le puede asignar un valor fuera de @interface +@property (readonly) NSString *roString; // utiliza @synthesize en @implementation para crear un accesor +// Puedes personalizar el nombre del getter y del setter en lugar de utilizar el nombre por defecto "set". +@property (getter=lengthGet, setter=lengthSet:) int length; + +// Métodos ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// + Para métodos de clase: ++ (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; + +// - Para métodos de instancia: +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +// Métodos de constructor con argumentos +- (id)initWithDistance:(int)defaultDistance; +// Los nombres de los métodos de Objective-C son muy descriptivos. Siempre nombra los métodos +// de acuerdo con sus argumentos + +@end // Define el final de la interfaz + + +// Para acceder a las variables públicas desde el archivo de implementación, @property genera +// un método setter automáticamente. El nombre del método es 'set' seguido de un nombre de variable +// @property: +MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia del objeto MyClass +[myClass setCount:10]; +NSLog(@"%d", [myClass count]); // imprime => 10 +// O utilizando los métodos getter y setter personalizados en @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // imprime => 32 +// Por conveniencia, puedes utilizar la notación de punto para asignar y acceder a las variables +// de una instancia de objeto. +myClass.count = 45; +NSLog(@"%i", myClass.count); // imprime => 45 + +// Llama a métodos de clase: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Llama a métodos de instancia: +MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia de objeto Myclass +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + +// Selectors +// Una forma dinámica de representar métodos. Utilizados para llamar métodos de una clase, +// pasar métodos a través de funciones para avisar a otras clases para que lo llamen, y +// para guardar métodos como una variable. +// SEL es el tipo de dato. @selector() devuelve un selector del nombre de método proveído +// methodAparameterAsString:andAParameterAsNumber: es un nombre para un método en MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene un método + // Debe de poner todos los argumentos de método en un solo objeto para mandar una + // función performSelector. + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method +} else { + // NSStringFromSelector() devuelve un NSString del nombre de método de un selector dado + NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); +} + +// Implementa los métodos de un archivo de implementación (MyClass.m): +@implementation MyClass { + long distance; // Variable de instancia de acceso privado + NSNumber height; +} + +// Para acceder a una variable pública del archivo de interfaz, utiliza '_' seguido del +// nombre de la variable: +_count = 5; // Hace referencia a "int count" de la interfaz de MyClass +// Accede variables definidas en el archivo de implementación: +distance = 18; // Hace referencia a "long distance" de la implementación de MyClass +// Para utilizar una variable @property en el archivo de implementación, utiliza @synthesize +// para crear una variable de acceso: +@synthesize roString = _roString; // _roString ahora está disponible en @implementation + +// Lamado antes de llamar algún método o instanciar cualquier objeto ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} + +// Contraparte para inicializar un método. Llamado cuando el contador de referencias +// del objeto es cero +- (void)dealloc +{ + [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de objeto de las clases + [super dealloc]; // y llama el método dealloc de la clase padre +} + +// Los constructores son una manera de crear instancias de una clase +// Este es el constructor por defecto que es llamado cuando el objeto es inicializado. +- (id)init +{ + if ((self = [super init])) // 'super' es utilizado para acceder a los métodos de la clase padre. + { + self.count = 1; // 'self' es utilizado para que el objeto se llame a sí mismo. + } + return self; +} +// Se pueden crear constructores que contiene argumentos +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + ++ (NSString *)classMethod +{ + return @"Some string"; +} + ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Objective-C no tiene declaraciones de métodos privados, pero pueden ser simulados. +// Para simular un método privado, crea un método en @implementation pero no en @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method + +// Métodos declarados dentro de MyProtocol +- (void)myProtocolMethod +{ + // statements +} + +@end // Declara el final de la implementación + +/////////////////////////////////////// +// Categorías +/////////////////////////////////////// +// Una categoría es un grupo de métodos diseñados para extender una clase. Te permiten agregar +// nuevos métodos a una clase existente por propósitos de organización. Éstos no deben de ser +// confundidos con subclases. +// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras que las categorías +// le AGREGAN funcionalidad de un objeto. +// Las categorías te permiten: +// -- Agregar métodos a una clase existente por propósitos de oganización. +// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para agregar tus propios métodos. +// -- Agregar la habilidad de crear métodos protegidos y privados para las clases. +// NOTA: No sobreescribas los métodos de las clases base en una categoría aunque tengas la habilidad +// de poder hacerlo. Sobreescribir métodos puede causar errores en la compilación después entre +// diferentes categorías y puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. +// Utiliza subclass para sobreescribir métodos. + +// Aquí una clase base simple, Car. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// Y la implementación de la clase simple, Car +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una subclase de Car (Carro) como +// si le cambiaramos de funcionalidad de Car para que se comporte como un camión. Pero digamos que +// únicamente queremos agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería limpiar +// el carro. Así que crearíamos una cateog®iea para agregar los métodos de limpieza: +// Archivo @interface: Car+Clean.h (NombreBaseDeClase+NombreDeCategoria.h) +#import "Car.h" // Asegúrate de improtar la clase que deseas extener. + +@interface Car (Clean) // El nombre de la categoría está dentro de (), seguido del nombre de la + // clase base + +- (void)washWindows; // Nombres de los nuevos métodos que le agregamos a nuestro objeto Car +- (void)wax; + +@end + +// Archivo @implementation: Car+Clean.m (NombreBaseDeClase+NombreDeCategoria.m) +#import "Car+Clean.h" // Importa el archivo de @interface de la categoría Clean + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Cualquier instancia del objeto Car tiene la habilidad de utilizar una categoría. Todo lo +// que necesitan es importarlo: +#import "Car+Clean.h" // Importa todas las diferentes categorías que necesites utilizar +#import "Car.h" // También debes de importar la clase base para su funcionalidad original + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Utiliza métodos de la clase base Car. + [mustang washWindows]; // Utiliza métodos de la categoría Clean de Car. + } + return 0; +} + +// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes simular. +// Crea una categoría conteniendo todos los métodos protegidos, luego importa ÚNICAMENTE +// al archivo @implementation de una clase que pertenece a la clase Car. +@interface Car (Protected) // Nombrando la categoría 'Protected' para recordar que los métodos + // están protegidos + +- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados por objetos Car + +@end +// Para utilizar los métodos protegidos, importa la categoría, luego implementa sus métodos: +#import "Car+Protected.h" // Recuerda, importa únicamente el archivo de @implementation + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Las instancias de Car no puede utilizar lockCar porque no se + // encuentra en @interface +} + +@end + +/////////////////////////////////////// +// Extensiones +/////////////////////////////////////// +// Las Extensions te permiten sobreescribir atributos de propiedades de acceso público y métodos de +// un @interface +// Archivo @interface: Shape.h +@interface Shape : NSObject + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides para modificarlos con una +// extensión: +// Archivo @implementation: Shape.m +#import "Shape.h" +// Las extensiones se encuentran en el mismo archivo que el archivo de @implementation +@interface Shape () // () después del nombre de la clase base declara una extensión + +@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar de readonly. +-(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber en lugar de un int. +-(void)privateMethod; // También puedes crear una nuevos métodos privados dentro de las + // extensiones + +@end +// @implementation principal: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions deben de ser + // dentro de @implementation + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Private method created by extension. Shape instances cannot call me."); +} + +@end + +/////////////////////////////////////// +// Protocolos +/////////////////////////////////////// +// Un protocolo declara métodos que pueden ser implementados por cualquier otra clase +// Los protocolos no son clases. Simplementen define una interfaz que otros objetos +// deben de implementar. +// Archivo @protocol: "CarUtilities.h" +@protocol CarUtilities // => Nombre de otro protocolo que se incluye en éste + @property BOOL engineOn; // La clase que lo adopta debe de utilizar @synthesize para todas las + // @properties definidas + - (void)turnOnEngine; // y todos los métodos definidos +@end +// A continuación una clase ejemplo que implementa el protcolo +#import "CarUtilities.h" // Importar el archivo @protocol. + +@interface Car : NSObject // El nombre del protocolo dentro de <> + // No necesitas los nombres de @property o métodos aquí para CarUtilities. Estos solo + // es requerido por @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // También Puedes utilizar protocolos como datos. +@end +// El @implementation necesita que se implementen @properties y métodos del protocolo. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el @property engineOn. + +- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los protocolos no definen + _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. +} +// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables tiene implementado. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // Tienes acceso a las variables + [objectOfSomeKind turnOnEngine]; // y los métodos del objeto + [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo implementa como se quiera. +} + +@end +// Las instancias de Car ahora tienen acceso al protocolo. +Car *carInstance = [[Car alloc] init]; +[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // imprime => "Car engine is on." +} +// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes de llamar a sus métodos: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Las categorías también pueden implementar protcolos: @interface Car (CarCategory) +// Puedes implementar varios protocolos: @interface Car : NSObject +// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos de manera adelantada: +#import "Brother.h" + +@protocol Brother; // Declaración adelantada. Sin ésto, el compilador tira un error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +@end + +// Ver si el problema es que Sister depende de Brother, y Broteher dependa de Sister. +#import "Sister.h" + +@protocol Sister; // Estas líenas detienen la recursión, solucionando el problema. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end + + +/////////////////////////////////////// +// Bloques +/////////////////////////////////////// +// Los bloques son declaraciones de código, tal como una función, pueden ser utilizados como data +// A continuación un bloque simple con un argumento entero que devuelve un el argumento más 4. +int (^addUp)(int n); // Declarar una variable para almacenar el bloque. +void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable de bloque sin argumentos. +// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables son solo readonly +// y el valor pasado al bloque es el valor de la variable cuando el bloque es creado. +int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, outsideVar AÚN es 17. +__block long mutableVar = 3; // __block hace que las variables se puedan escribir en bloques. +addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe ningún parámetro + NSLog(@"You may have as many lines in a block as you would like."); + NSSet *blockSet; // También puedes declarar variables locales. + mutableVar = 32; // Asignar un nuevo valor a la variable __block. + return n + outsideVar; // Declaraciones de retorno son opcionales. +} +int addUp = add(10 + 16); // Llama al bloque de código con argumentos. +// Los bloques son usualmente utilizados como argumentos a funciones que son llamados +// más adelante o para callbacks. +@implementation BlockExample : NSObject + + - (void)runBlock:(void (^)(NSString))block { + NSLog(@"Block argument returns nothing and takes in a NSString object."); + block(@"Argument given to block to execute."); // Calling block. + } + + @end + + +/////////////////////////////////////// +// Manejo de memoria +/////////////////////////////////////// +/* +Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada para ese objeto. Cuando +la aplicación termina de utilizar ese objeto, la memoria debe de ser desalocada para asegurar la +eficiencia de la aplicación. +Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos de referencias. Mientras +haya al menos una referencia del objeto (también conocido como tener un objeto de adueñado), entonces +el objeto estará disponible para su uso. + +Cuando una instancia es dueña un objeto, su contador de referencia incrementa por uno. Cuando +el objeto es liberado, el contador de referencia decrementa uno. Cuando el conteo de referencia +es cero, el objeto es removido de la memoria. + +Con todas las interacciones de los objetos, sigue el patrón de: +(1) Crear e lobjeto, (2) utiliza el objeto, (3) libera el objeto de la memoria. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de referencias de classVar. Devuelve un puntero al objeto +[classVar release]; // Decrementa el conteo de referencias de classVar's +// 'retain' +// 'retain' adueña la instancia de objeto existente e incrementa el conteo de referencia por uno. Devuelve un puntero al objeto. +MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto aún se queda en memoria porque newVar es el dueño. +[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del bloque @autoreleasepool. Devuelve un puntero al objeto. + +// @property puede utilizar 'retain' y 'assign' también para pequeñas definiciones convenientes +@property (retain) MyClass *instance; // Libera el valor viejo y retiene uno nuevo (referencia fuerte) +@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar una referencia vieja (débil) + +// Conteo Automático de Referencias (ARC) +// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 se introdujo el Conteo Automático +// de Referencias (ARC). +// ARC es una funcionalidad del compilador que agrega retain, release y autorealase automáticamente, así que al +// utilizar ARC, no se debe de utilizar retain, release o autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... código utilizando arcMyClass +// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de utilizar arcMyClass. Pero con ARC, +// no hay necesidad. Insertará automáticamente la declaración de liberación. + +// Mientras que para los atributos de @property 'assign' y 'retain', con ARC utilizarás 'weak' y 'strong' +@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de referencias de la instancia original +// es fijado a ceor, weakVar autom´åticamente recibe el valor de nil para evitar cualquier 'crashing'. +@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. Asegura que el objeto se quede en memoria. + +// Para variables regulares (no variables de @property), utiliza lo siguiente: +__strong NSString *strongString; // Por defecto. La variables de retenida en memoria hasta que se salga del ámbito. +__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el objeto existente es liberado, weakSet le es asginado un valor nil +__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no es asginado a nil cuando el objeto existente es liberado. + +``` +## Lecturas sugeridas + +[Wikipedia Objective-C](http://es.wikipedia.org/wiki/Objective-C) + +[Programming with Objective-C. Libro PDF de Apple](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 2f7c68978bd42cc863985a451d018e20f9711fb8 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:45:03 +0200 Subject: [yaml/pt-br] YAML translation to Brazilian Portuguese --- pt-br/yaml-pt.html.markdown | 139 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 pt-br/yaml-pt.html.markdown diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown new file mode 100644 index 00000000..a7414f2d --- /dev/null +++ b/pt-br/yaml-pt.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +--- + +YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e +legível por seres humanos. + +É um estrito subconjunto de JSON, com a adição de sintaticamente +novas linhas e recuo significativos, como Python. Ao contrário de Python, no entanto, +YAML não permite caracteres de tabulação literais em tudo. + +```yaml +# Commentários em YAML são como este. + +################### +# TIPOS ESCALARES # +################### + +# Nosso objeto raiz (que continua por todo o documento) será um mapa, +# o que equivale a um dicionário, hash ou objeto em outras linguagens. +chave: valor +outra_chave: Outro valor vai aqui. +u_valor_numerico: 100 +notacao_cientifica: 1e+12 +boleano: true +valor_nulo: null +chave com espaco: valor +# Observe que strings não precisam de aspas. Porém, elas podem ter. +porem: "Uma string, entre aspas." +"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave." + +# Seqüências de várias linhas podem ser escritos como um 'bloco literal' (utilizando |), +# ou em um 'bloco compacto' (utilizando '>'). +bloco_literal: | + Todo esse bloco de texto será o valor da chave 'bloco_literal', + preservando a quebra de com linhas. + + O literal continua até de-dented, e a primeira identação é + removida. + + Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações - + estas linhas serão identadas com 4 espaços. +estilo_compacto: > + Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta + vez, todas as novas linhas serão substituídas com espaço simples. + + Linhas em branco, como acima, são convertidas em um carater de nova linha. + + Linhas 'mais-indentadas' mantém suas novas linhas também - + este texto irá aparecer em duas linhas. + +#################### +# TIPOS DE COLEÇÃO # +#################### + +# Texto aninhado é conseguido através de identação. +um_mapa_aninhado: + chave: valor + outra_chave: Outro valor + outro_mapa_aninhado: + ola: ola + +# Mapas não tem que ter chaves com string. +0.25: uma chave com valor flutuante + +# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave. +? | + Esta é uma chave + que tem várias linhas +: e este é o seu valor + +# também permite tipos de coleção de chaves, mas muitas linguagens de programação +# vão reclamar. + +# Sequências (equivalente a listas ou arrays) semelhante à isso: +uma_sequencia: + - Item 1 + - Item 2 + - 0.5 # sequencias podem conter tipos diferentes. + - Item 4 + - chave: valor + outra_chave: outro_valor + - + - Esta é uma sequencia + - dentro de outra sequencia + +# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e +# sequencias: +mapa_json: {"chave": "valor"} +json_seq: [3, 2, 1, "decolar"] + +########################## +# RECURSOS EXTRA DO YAML # +########################## + +# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique +# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor: +conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves. +outra_ancora: * nome_ancora + +# YAML também tem tags, que você pode usar para declarar explicitamente os tipos. +string_explicita: !! str 0,5 +# Alguns analisadores implementam tags específicas de linguagem, como este para Python de +# Tipo de número complexo. +numero_complexo_em_python: !! python / complex 1 + 2j + +#################### +# YAML TIPOS EXTRA # +#################### + +# Strings e números não são os únicos que escalares YAML pode entender. +# Data e 'data e hora' literais no formato ISO também são analisados. +datetime: 2001-12-15T02: 59: 43.1Z +datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5 +Data: 2002/12/14 + +# A tag !!binary indica que a string é na verdade um base64-encoded (condificado) +# representação de um blob binário. +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML também tem um tipo de conjunto, o que se parece com isso: +set: + ? item1 + ? item2 + ? item3 + +# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 251ffdf894a697ec58a59d620956f4cca7172810 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:48:17 +0200 Subject: [yaml/pt-br] fixing contributors and add translators --- pt-br/yaml-pt.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index a7414f2d..93fca3f7 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -2,6 +2,8 @@ language: yaml filename: learnyaml.yaml contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] --- @@ -133,7 +135,7 @@ set: # Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: set2: - item1: null - item2: null - item3: null + item1: nulo + item2: nulo + item3: nulo ``` -- cgit v1.2.3 From 6616ee7156f2e631e18b13d0e19eb29041eec1bf Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 14:54:53 -0700 Subject: Reduced line lengths larger than 80 characters --- es-es/objective-c-es.html.markdown | 349 ++++++++++++++++++++++--------------- 1 file changed, 211 insertions(+), 138 deletions(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index fc769188..c5532c0f 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -38,7 +38,8 @@ int main (int argc, const char * argv[]) { // Crear un autorelease pool para manejar la memoria al programa NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // Si se utiliza el conteo automático de referencias (ARC), utiliza @autoreleasepool: + // Si se utiliza el conteo automático de referencias (ARC), + // utiliza @autoreleasepool: @autoreleasepool { // Utiliza NSLog para imprimir líneas a la consola @@ -53,13 +54,14 @@ int main (int argc, const char * argv[]) long myPrimitive2 = 234554664565; // Declaraciones de objetos - // Pon el * como prefijo de los nombre de las variables para declaraciones de - // objetos de tipos fuertes + // Pon el * como prefijo de los nombre de las variables para declaraciones + // de objetos de tipos fuertes MyClass *myObject1 = nil; // Tipo fuerte id myObject2 = nil; // Tipo débil // %@ es un objeto // 'description' es una convención para mostrar el valor de los objetos - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // imprime => "(null) y (null)" + NSLog(@"%@ and %@", myObject1, [myObject2 description]); + // imprime => "(null) and (null)" // String NSString *worldString = @"World"; @@ -216,7 +218,8 @@ int main (int argc, const char * argv[]) int ii = 0; while (ii < 4) { - NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de utilizar su valor + NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de + // utilizar su valor } // imprime => "0," // "1," // "2," @@ -242,7 +245,8 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de Objective-C + // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de + // Objective-C for (id item in values) { NSLog(@"%@,", item); } // imprime => "0," @@ -256,7 +260,8 @@ int main (int argc, const char * argv[]) // Tus declaraciones aquí @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar todos los objetos + } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar + // todos los objetos { NSLog(@"Exception: %@", e); } @finally @@ -265,7 +270,8 @@ int main (int argc, const char * argv[]) } // imprime => "Exception: File Not Found on System" // "Finally. Time to clean up." - // Los objetos NSError son útiles para argumentos de función para los errores de usuario. + // Los objetos NSError son útiles para argumentos de función para los + // errores de usuario. NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; /////////////////////////////////////// @@ -305,20 +311,27 @@ int main (int argc, const char * argv[]) // @property tipo nombre; <= declaración de propiedades // -/+ (tipo) Declaración de método; <= Declaración de método // @end -@interface MyClass : NSObject // NSObject es la clase de objeto base de Objective-C. +@interface MyClass : NSObject // NSObject es la clase de objeto + // base de Objective-C. { - // Declaraciones de variables de instancia (puede existir en el archivo de interfaz o de implementación) + // Declaraciones de variables de instancia (puede existir en el archivo de + // interfaz o de implementación) int count; // Acceso protegido por defecto. - @private id data; // Acceso privado (Más conveniente de declarar en el archivo de implementación) + @private id data; // Acceso privado (Más conveniente de declarar en el + // archivo de implementación) NSString *name; } -// Notación conveneinte para acceso público de las variables para generar un método setter -// Por defecto, el nombre del método setter 'set' seguido del nombre de variable @property +// Notación conveneinte para acceso público de las variables para generar un +// método setter +// Por defecto, el nombre del método setter 'set' seguido del nombre de +// variable @property @property int propInt; // Nombre del método 'setter' = 'setPropInt' @property (copy) id copyId; // (copy) => Copia el objeto durante la asignación // (readonly) => No se le puede asignar un valor fuera de @interface -@property (readonly) NSString *roString; // utiliza @synthesize en @implementation para crear un accesor -// Puedes personalizar el nombre del getter y del setter en lugar de utilizar el nombre por defecto "set". +@property (readonly) NSString *roString; // utiliza @synthesize en + // @implementation para crear un accesor +// Puedes personalizar el nombre del getter y del setter en lugar de utilizar +// el nombre por defecto "set". @property (getter=lengthGet, setter=lengthSet:) int length; // Métodos @@ -334,23 +347,23 @@ int main (int argc, const char * argv[]) // Métodos de constructor con argumentos - (id)initWithDistance:(int)defaultDistance; -// Los nombres de los métodos de Objective-C son muy descriptivos. Siempre nombra los métodos -// de acuerdo con sus argumentos +// Los nombres de los métodos de Objective-C son muy descriptivos. +// Siempre nombra los métodos de acuerdo con sus argumentos @end // Define el final de la interfaz -// Para acceder a las variables públicas desde el archivo de implementación, @property genera -// un método setter automáticamente. El nombre del método es 'set' seguido de un nombre de variable -// @property: +// Para acceder a las variables públicas desde el archivo de implementación, +// @property genera un método setter automáticamente. El nombre del método +// es 'set' seguido de un nombre de variable @property: MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia del objeto MyClass [myClass setCount:10]; NSLog(@"%d", [myClass count]); // imprime => 10 // O utilizando los métodos getter y setter personalizados en @interface: [myClass lengthSet:32]; NSLog(@"%i", [myClass lengthGet]); // imprime => 32 -// Por conveniencia, puedes utilizar la notación de punto para asignar y acceder a las variables -// de una instancia de objeto. +// Por conveniencia, puedes utilizar la notación de punto para asignar y +// acceder a las variables de una instancia de objeto. myClass.count = 45; NSLog(@"%i", myClass.count); // imprime => 45 @@ -363,13 +376,14 @@ MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia de objeto Mycla NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; // Selectors -// Una forma dinámica de representar métodos. Utilizados para llamar métodos de una clase, -// pasar métodos a través de funciones para avisar a otras clases para que lo llamen, y -// para guardar métodos como una variable. -// SEL es el tipo de dato. @selector() devuelve un selector del nombre de método proveído -// methodAparameterAsString:andAParameterAsNumber: es un nombre para un método en MyClass +// Una forma dinámica de representar métodos. Utilizados para llamar métodos +// de una clase, pasar métodos a través de funciones para avisar a otras clases +// para que lo llamen, y para guardar métodos como una variable. +// SEL es el tipo de dato. @selector() devuelve un selector del nombre de +// método proveído methodAparameterAsString:andAParameterAsNumber: es un nombre +// para un método en MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); -if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene un método +if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene el método // Debe de poner todos los argumentos de método en un solo objeto para mandar una // función performSelector. NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; @@ -390,8 +404,8 @@ if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene u _count = 5; // Hace referencia a "int count" de la interfaz de MyClass // Accede variables definidas en el archivo de implementación: distance = 18; // Hace referencia a "long distance" de la implementación de MyClass -// Para utilizar una variable @property en el archivo de implementación, utiliza @synthesize -// para crear una variable de acceso: +// Para utilizar una variable @property en el archivo de implementación, utiliza +// @synthesize para crear una variable de acceso: @synthesize roString = _roString; // _roString ahora está disponible en @implementation // Lamado antes de llamar algún método o instanciar cualquier objeto @@ -406,7 +420,8 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC // del objeto es cero - (void)dealloc { - [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de objeto de las clases + [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de + // objeto de las clases [super dealloc]; // y llama el método dealloc de la clase padre } @@ -414,7 +429,8 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC // Este es el constructor por defecto que es llamado cuando el objeto es inicializado. - (id)init { - if ((self = [super init])) // 'super' es utilizado para acceder a los métodos de la clase padre. + if ((self = [super init])) // 'super' es utilizado para acceder a los + // métodos de la clase padre. { self.count = 1; // 'self' es utilizado para que el objeto se llame a sí mismo. } @@ -466,18 +482,20 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC /////////////////////////////////////// // Categorías /////////////////////////////////////// -// Una categoría es un grupo de métodos diseñados para extender una clase. Te permiten agregar -// nuevos métodos a una clase existente por propósitos de organización. Éstos no deben de ser -// confundidos con subclases. -// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras que las categorías -// le AGREGAN funcionalidad de un objeto. +// Una categoría es un grupo de métodos diseñados para extender una clase. +// Te permiten agregar nuevos métodos a una clase existente por propósitos +// de organización. Éstos no deben de serconfundidos con subclases. +// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras +// que las categoríasle AGREGAN funcionalidad de un objeto. // Las categorías te permiten: // -- Agregar métodos a una clase existente por propósitos de oganización. -// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para agregar tus propios métodos. +// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para +// agregar tus propios métodos. // -- Agregar la habilidad de crear métodos protegidos y privados para las clases. -// NOTA: No sobreescribas los métodos de las clases base en una categoría aunque tengas la habilidad -// de poder hacerlo. Sobreescribir métodos puede causar errores en la compilación después entre -// diferentes categorías y puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. +// NOTA: No sobreescribas los métodos de las clases base en una categoría +// aunque tengas la habilidad de poder hacerlo. Sobreescribir métodos puede +// causar errores en la compilación después entre diferentes categorías y +// puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. // Utiliza subclass para sobreescribir métodos. // Aquí una clase base simple, Car. @@ -508,17 +526,20 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC @end -// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una subclase de Car (Carro) como -// si le cambiaramos de funcionalidad de Car para que se comporte como un camión. Pero digamos que -// únicamente queremos agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería limpiar -// el carro. Así que crearíamos una cateog®iea para agregar los métodos de limpieza: +// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una +// subclase de Car (Carro) como si le cambiaramos de funcionalidad de Car +// para que se comporte como un camión. Pero digamos que únicamente queremos +// agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería +// limpiar el carro. Así que crearíamos una cateog®iea para agregar los +// métodos de limpieza: // Archivo @interface: Car+Clean.h (NombreBaseDeClase+NombreDeCategoria.h) #import "Car.h" // Asegúrate de improtar la clase que deseas extener. -@interface Car (Clean) // El nombre de la categoría está dentro de (), seguido del nombre de la - // clase base +@interface Car (Clean) // El nombre de la categoría está dentro de (), + // seguido del nombre de la clase base -- (void)washWindows; // Nombres de los nuevos métodos que le agregamos a nuestro objeto Car +- (void)washWindows; // Nombres de los nuevos métodos que le agregamos + // a nuestro objeto Car - (void)wax; @end @@ -537,10 +558,12 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC @end -// Cualquier instancia del objeto Car tiene la habilidad de utilizar una categoría. Todo lo -// que necesitan es importarlo: -#import "Car+Clean.h" // Importa todas las diferentes categorías que necesites utilizar -#import "Car.h" // También debes de importar la clase base para su funcionalidad original +// Cualquier instancia del objeto Car tiene la habilidad de utilizar una +// categoría. Todo lo que necesitan es importarlo: +#import "Car+Clean.h" // Importa todas las diferentes categorías que + // necesites utilizar +#import "Car.h" // También debes de importar la clase base para su + // funcionalidad original int main (int argc, const char * argv[]) { @autoreleasepool { @@ -554,23 +577,27 @@ int main (int argc, const char * argv[]) { return 0; } -// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes simular. -// Crea una categoría conteniendo todos los métodos protegidos, luego importa ÚNICAMENTE -// al archivo @implementation de una clase que pertenece a la clase Car. -@interface Car (Protected) // Nombrando la categoría 'Protected' para recordar que los métodos - // están protegidos +// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes +// simular. Crea una categoría conteniendo todos los métodos protegidos, +// luego importa ÚNICAMENTE al archivo @implementation de una clase que +// pertenece a la clase Car. +@interface Car (Protected) // Nombrando la categoría 'Protected' para + // recordar que los métodos están protegidos -- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados por objetos Car +- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados + // por objetos Car @end -// Para utilizar los métodos protegidos, importa la categoría, luego implementa sus métodos: -#import "Car+Protected.h" // Recuerda, importa únicamente el archivo de @implementation +// Para utilizar los métodos protegidos, importa la categoría, +// luego implementa sus métodos: +#import "Car+Protected.h" // Recuerda, importa únicamente el archivo + // de @implementation @implementation Car - (void)lockCar { - NSLog(@"Car locked."); // Las instancias de Car no puede utilizar lockCar porque no se - // encuentra en @interface + NSLog(@"Car locked."); // Las instancias de Car no puede utilizar + // lockCar porque no se encuentra en @interface } @end @@ -578,8 +605,8 @@ int main (int argc, const char * argv[]) { /////////////////////////////////////// // Extensiones /////////////////////////////////////// -// Las Extensions te permiten sobreescribir atributos de propiedades de acceso público y métodos de -// un @interface +// Las Extensions te permiten sobreescribir atributos de propiedades de +// acceso público y métodos de un @interface // Archivo @interface: Shape.h @interface Shape : NSObject @@ -588,17 +615,21 @@ int main (int argc, const char * argv[]) { - (int)getNumOfSides; @end -// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides para modificarlos con una -// extensión: +// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides +// para modificarlos con una extensión: // Archivo @implementation: Shape.m #import "Shape.h" -// Las extensiones se encuentran en el mismo archivo que el archivo de @implementation -@interface Shape () // () después del nombre de la clase base declara una extensión - -@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar de readonly. --(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber en lugar de un int. --(void)privateMethod; // También puedes crear una nuevos métodos privados dentro de las - // extensiones +// Las extensiones se encuentran en el mismo archivo que el archivo +// de @implementation +@interface Shape () // () después del nombre de la clase base declara + // una extensión + +@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar + // de readonly. +-(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber + // en lugar de un int. +-(void)privateMethod; // También puedes crear una nuevos métodos privados + // dentro de las extensiones @end // @implementation principal: @@ -606,8 +637,8 @@ int main (int argc, const char * argv[]) { @synthesize numOfSides = _numOfSides; --(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions deben de ser - // dentro de @implementation +-(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions + // deben de ser dentro de @implementation return _numOfSides; } -(void)privateMethod { @@ -619,36 +650,44 @@ int main (int argc, const char * argv[]) { /////////////////////////////////////// // Protocolos /////////////////////////////////////// -// Un protocolo declara métodos que pueden ser implementados por cualquier otra clase -// Los protocolos no son clases. Simplementen define una interfaz que otros objetos -// deben de implementar. +// Un protocolo declara métodos que pueden ser implementados por cualquier otra +// clase. Los protocolos no son clases. Simplementen define una interfaz que +// otros objetos deben de implementar. // Archivo @protocol: "CarUtilities.h" -@protocol CarUtilities // => Nombre de otro protocolo que se incluye en éste - @property BOOL engineOn; // La clase que lo adopta debe de utilizar @synthesize para todas las - // @properties definidas +@protocol CarUtilities // => Nombre de otro protocolo + // que se incluye en éste + @property BOOL engineOn; // La clase que lo adopta debe de utilizar + // @synthesize para todas las @properties definidas - (void)turnOnEngine; // y todos los métodos definidos @end // A continuación una clase ejemplo que implementa el protcolo #import "CarUtilities.h" // Importar el archivo @protocol. @interface Car : NSObject // El nombre del protocolo dentro de <> - // No necesitas los nombres de @property o métodos aquí para CarUtilities. Estos solo - // es requerido por @implementation. -- (void)turnOnEngineWithUtilities:(id )car; // También Puedes utilizar protocolos como datos. + // No necesitas los nombres de @property o métodos aquí para CarUtilities. + // Estos solo es requerido por @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // También Puedes + // utilizar protocolos + // como datos. @end -// El @implementation necesita que se implementen @properties y métodos del protocolo. +// El @implementation necesita que se implementen @properties y métodos +// del protocolo. @implementation Car : NSObject -@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el @property engineOn. +@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el + // @property engineOn. -- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los protocolos no definen - _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. +- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los + // protocolos no definen + _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. } -// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables tiene implementado. +// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables +// tiene implementado. - (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { [objectOfSomeKind engineOn]; // Tienes acceso a las variables [objectOfSomeKind turnOnEngine]; // y los métodos del objeto - [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo implementa como se quiera. + [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo + // implementa como se quiera. } @end @@ -659,18 +698,23 @@ Car *carInstance = [[Car alloc] init]; if ([carInstance engineOn]) { NSLog(@"Car engine is on."); // imprime => "Car engine is on." } -// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes de llamar a sus métodos: +// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes +// de llamar a sus métodos: if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); } else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { NSLog(@"This does run as the Car class implements the CarUtilities protocol."); } -// Las categorías también pueden implementar protcolos: @interface Car (CarCategory) -// Puedes implementar varios protocolos: @interface Car : NSObject -// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos de manera adelantada: +// Las categorías también pueden implementar protcolos: @interface Car +// (CarCategory) +// Puedes implementar varios protocolos: +// @interface Car : NSObject +// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos +// de manera adelantada: #import "Brother.h" -@protocol Brother; // Declaración adelantada. Sin ésto, el compilador tira un error. +@protocol Brother; // Declaración adelantada. Sin ésto, el compilador + // tira un error. @protocol Sister @@ -678,10 +722,11 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { @end -// Ver si el problema es que Sister depende de Brother, y Broteher dependa de Sister. +// Ver si el problema es que Sister depende de Brother, +// y Brother dependa de Sister. #import "Sister.h" -@protocol Sister; // Estas líenas detienen la recursión, solucionando el problema. +@protocol Sister; // Estas líneas detienen la recursión, resolviendo el problema. @protocol Brother @@ -693,23 +738,30 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Bloques /////////////////////////////////////// -// Los bloques son declaraciones de código, tal como una función, pueden ser utilizados como data -// A continuación un bloque simple con un argumento entero que devuelve un el argumento más 4. +// Los bloques son declaraciones de código, tal como una función, pueden +// ser utilizados como data. +// A continuación un bloque simple con un argumento entero que devuelve +// un el argumento más 4. int (^addUp)(int n); // Declarar una variable para almacenar el bloque. -void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable de bloque sin argumentos. -// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables son solo readonly -// y el valor pasado al bloque es el valor de la variable cuando el bloque es creado. -int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, outsideVar AÚN es 17. -__block long mutableVar = 3; // __block hace que las variables se puedan escribir en bloques. -addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe ningún parámetro +void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable + // de bloque sin argumentos. +// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables +// son solo readonly y el valor pasado al bloque es el valor de la variable +// cuando el bloque es creado. +int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, + // outsideVar AÚN es 17. +__block long mutableVar = 3; // __block hace que las variables se puedan + // escribir en bloques. +addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe + // ningún parámetro NSLog(@"You may have as many lines in a block as you would like."); NSSet *blockSet; // También puedes declarar variables locales. mutableVar = 32; // Asignar un nuevo valor a la variable __block. return n + outsideVar; // Declaraciones de retorno son opcionales. } int addUp = add(10 + 16); // Llama al bloque de código con argumentos. -// Los bloques son usualmente utilizados como argumentos a funciones que son llamados -// más adelante o para callbacks. +// Los bloques son usualmente utilizados como argumentos a funciones que +// son llamados más adelante o para callbacks. @implementation BlockExample : NSObject - (void)runBlock:(void (^)(NSString))block { @@ -724,51 +776,72 @@ int addUp = add(10 + 16); // Llama al bloque de código con argumentos. // Manejo de memoria /////////////////////////////////////// /* -Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada para ese objeto. Cuando -la aplicación termina de utilizar ese objeto, la memoria debe de ser desalocada para asegurar la -eficiencia de la aplicación. -Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos de referencias. Mientras -haya al menos una referencia del objeto (también conocido como tener un objeto de adueñado), entonces -el objeto estará disponible para su uso. - -Cuando una instancia es dueña un objeto, su contador de referencia incrementa por uno. Cuando -el objeto es liberado, el contador de referencia decrementa uno. Cuando el conteo de referencia -es cero, el objeto es removido de la memoria. +Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada +para ese objeto. Cuando la aplicación termina de utilizar ese objeto, la +memoria debe de ser desalocada para asegurar la eficiencia de la aplicación. +Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos +de referencias. Mientras haya al menos una referencia del objeto (también +conocido como tener un objeto de adueñado), entonces el objeto estará +disponible para su uso. + +Cuando una instancia es dueña un objeto, su contador de referencia incrementa +por uno. Cuando el objeto es liberado, el contador de referencia decrementa uno. +Cuando el conteo de referencia es cero, el objeto es removido de la memoria. Con todas las interacciones de los objetos, sigue el patrón de: (1) Crear e lobjeto, (2) utiliza el objeto, (3) libera el objeto de la memoria. */ -MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de referencias de classVar. Devuelve un puntero al objeto +MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de + // referencias de classVar. Devuelve un + // puntero al objeto [classVar release]; // Decrementa el conteo de referencias de classVar's // 'retain' -// 'retain' adueña la instancia de objeto existente e incrementa el conteo de referencia por uno. Devuelve un puntero al objeto. -MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto aún se queda en memoria porque newVar es el dueño. -[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del bloque @autoreleasepool. Devuelve un puntero al objeto. - -// @property puede utilizar 'retain' y 'assign' también para pequeñas definiciones convenientes -@property (retain) MyClass *instance; // Libera el valor viejo y retiene uno nuevo (referencia fuerte) -@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar una referencia vieja (débil) +// 'retain' adueña la instancia de objeto existente e incrementa el conteo de +// referencia por uno. Devuelve un puntero al objeto. +MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto + // aún se queda en memoria porque newVar + // es el dueño. +[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del + // bloque @autoreleasepool. Devuelve un puntero al objeto. + +// @property puede utilizar 'retain' y 'assign' también para pequeñas +// definiciones convenientes +@property (retain) MyClass *instance; // Libera el valor viejo y retiene + // uno nuevo (referencia fuerte) +@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar + // una referencia vieja (débil) // Conteo Automático de Referencias (ARC) -// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 se introdujo el Conteo Automático -// de Referencias (ARC). -// ARC es una funcionalidad del compilador que agrega retain, release y autorealase automáticamente, así que al +// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 +// se introdujo el Conteo Automático de Referencias (ARC). +// ARC es una funcionalidad del compilador que agrega retain, release y +// autorealase automáticamente, así que al // utilizar ARC, no se debe de utilizar retain, release o autorelease. MyClass *arcMyClass = [[MyClass alloc] init]; // ... código utilizando arcMyClass -// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de utilizar arcMyClass. Pero con ARC, -// no hay necesidad. Insertará automáticamente la declaración de liberación. - -// Mientras que para los atributos de @property 'assign' y 'retain', con ARC utilizarás 'weak' y 'strong' -@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de referencias de la instancia original -// es fijado a ceor, weakVar autom´åticamente recibe el valor de nil para evitar cualquier 'crashing'. -@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. Asegura que el objeto se quede en memoria. +// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de +// utilizar arcMyClass. Pero con ARC, no hay necesidad. Insertará +// automáticamente la declaración de liberación. + +// Mientras que para los atributos de @property 'assign' y 'retain', con ARC +// utilizarás 'weak' y 'strong' +@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de + // referencias de la instancia original +// es fijado a ceor, weakVar automáticamente recibe el valor de nil para +// evitar cualquier 'crashing'. +@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. + // Asegura que el objeto se quede en memoria. // Para variables regulares (no variables de @property), utiliza lo siguiente: -__strong NSString *strongString; // Por defecto. La variables de retenida en memoria hasta que se salga del ámbito. -__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el objeto existente es liberado, weakSet le es asginado un valor nil -__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no es asginado a nil cuando el objeto existente es liberado. +__strong NSString *strongString; // Por defecto. La variables de retenida en + // memoria hasta que se salga del ámbito. +__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el + // objeto existente es liberado, weakSet le es asginado + // un valor nil +__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no + // es asginado a nil cuando el objeto + // existente es liberado. ``` ## Lecturas sugeridas -- cgit v1.2.3 From 400b1a4b830b6d2cae677d916781dc88a45af027 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:58:47 +0200 Subject: [yaml/pt-br] fixing header --- pt-br/yaml-pt.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 93fca3f7..341ae675 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -1,10 +1,11 @@ --- language: yaml -filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +filename: learnyaml-pt.yaml +lang: pt-br --- YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e -- cgit v1.2.3 From 766be7094483a06b4e289081550e1f28744a3b51 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 16:25:31 -0700 Subject: Added R Spanish translation --- es-es/r-es.html.markdown | 717 +++++++++++++++++++++++++++++++++++++++++++++++ r.html.markdown | 2 +- 2 files changed, 718 insertions(+), 1 deletion(-) create mode 100644 es-es/r-es.html.markdown diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown new file mode 100644 index 00000000..db780c27 --- /dev/null +++ b/es-es/r-es.html.markdown @@ -0,0 +1,717 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["David Hsieh", "http://github.com/deivuh"] +lang: es-es +filename: learnr.r +--- + +R es un lenguaje de computación estadística. Tiene muchas librerías para cargar +y limpiar sets de datos, ejecutar procedimientos estadísticos y generar +gráficas. También puedes ejecutar comandos `R` dentro de un documento de +LaTeX. + +```r + +# Los comentariso inician con símbolos numéricos. + +# No puedes hacer comentarios de múltiples líneas +# pero puedes agrupar múltiples comentarios de esta manera. + +# En Windows puedes utilizar CTRL-ENTER para ejecutar una línea. +# En Mac utilizas COMMAND-ENTER + + +############################################################################# +# Cosas que puedes hacer sin entender nada acerca de programación +############################################################################# + +# En esta sección, mostramos algunas cosas chileras / cool que puedes hacer en +# R sin entender nada de programación. No te preocupes en entender nada +# de lo que hace este código. Solo disfruta! + +data() # Examinar sets de datos pre-cargados +data(rivers) # Obtiene este: Lengths of Major North American Rivers" +ls() # Fijarse que "rivers" ahora aparece en el workspace +head(rivers) # Echarle un ojo al set de datos +# 735 320 325 392 524 450 + +length(rivers) # ¿Cuántos ríos fueron medidos? +# 141 +summary(rivers) # ¿Cuáles son algunas estadísticas generales? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# Generar una gráfica tallo-y-hoja (Visualización de datos tipo histograma) +stem(rivers) + +# El punto decimal son 2 dígitos a la derecha de | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Fijarse que la data no es normal ni log-normal! +# Toma eso, fundamentalistas de la curva de campana! + +# El punto decimal está a 1 dígito a la izquierda del | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# Generar un histograma: +hist(rivers, col="#333333", border="white", breaks=25) # Juega con los estos parámetros +hist(log(rivers), col="#333333", border="white", breaks=25) # Generarás más gráficas después + +# Aquí hay otro set de datos pre-cargado. R tiene bastantes de éstos. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") + +# En lugar de dejar el orden por defecto (por año), +# podemos ordenar de tal manera que muestre qué es típico: +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# El punto decimal se encuentra en | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Tirar los dados varias veces +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Tus números será diferente de los míos, a menos que tengamos el mismo valor +# de random.seed(31337) + +# Dibuja de un Gaussian 9 veces +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# Tipos de datos y aritmética básica +################################################## + +# Ahora para la parte de programación orientada a objetos del tutorial. +# En esta sección conocerás los tipos de datos importantes de R: +# Enteros, numéricos, caracteres, lógicos, y factores. +# Hay otros, pero esos son los que menos necesitas para empezar. + +# ENTEROS +# Enteros de almacenamiento largo son escritos con L +5L # 5 +class(5L) # "integer" +# (Try ?class para más información en la función class().) +# En R, cada valor único, como 5L, es considerado un vector de logitud 1 +length(5L) # 1 +# También puedes tener un vector de enteros con longitud > 1: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMÉRICOS +# Un "numérico" es un número de punto flotante de doble precisión. +5 # 5 +class(5) # "numeric" +# Nuevamente, todo en R es un vector; +# puedes hacer un vector numérico con más de un elemento +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# También puedes utilizar el notación científica +5e4 # 50000 +6.02e23 # Número de Avogadro +1.6e-35 # Logintud Planck +# También puedes tener números infinitamente grandes o pequeños +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Puede que uses "Inf", por ejemplo, en integrate(dnorm, 3, Inf); +# esto obvia las tablas de puntos Z. + +# ARITMÉTICA BÁSICA +# Puedes hacer aritmética con números +# Haciendo aritmética en un mix de enteros y numéricos, te da otro numérico +10L + 66L # 76 # entero mas entero da entero +53.2 - 4 # 49.2 # entero menos entero da numérico +2.0 * 2L # 4 # numérico veces entero da numérico +3L / 4 # 0.75 # entero sobre numérico da numérico +3 %% 2 # 1 # el residuo de dos numéricos es otro numérico +# La aritmética ilegal rinde un "not-a-number" +0 / 0 # NaN +class(NaN) # "numeric" +# Puedes hacer aritmética con dos vectores con longitud mayor a 1, +# siempre que la longitud del vector mayor es un entero múltiplo del menor. +c(1,2,3) + c(1,2,3) # 2 4 6 + +# CARACTERES +# No hay diferencia entre strings y caracteres en R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Ambos eran vectores de caracteres de longitud 1 +# Aquí hay uno más largo: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Puedes hacer operaciones regex en vectores de caracteres: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R tiene varios vectores predefinidos de caracteres +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LÓGICOS +# En R, un "logical" es un boolean +class(TRUE) # "logical" +class(FALSE) # "logical" +# Ese comportamiento es normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# El dato faltante (NA) es lógico también +class(NA) # "logical" +# Utiliza | y & para operaciones lógicas +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Puedes probar si x es TRUE (verdadero) +isTRUE(TRUE) # TRUE +# Aquí tenemos un vector lógico con varios elementos: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# FACTORES +# La clase factor es para datos de categoría +# Los factores pueden ser ordenados (como las calificaciones de los niños) +# o sin orden (como el género) +factor(c("female", "female", "male", NA, "female")) +# female female male female +# Levels: female male +# Los "levels" son los valores que los datos categóricos pueden tener +# Tomar nota que los datos faltantes no entran a los niveles +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" +# Si un vector de factores tiene longitud 1, sus niveles también tendrán +# una longitud de 1 también + +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# Los factores son comúnmente vistos en marcos de dato, y una estructura de +# datos que cubriremos después +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" es uno raro; utilízalo para "limpiar" un vector +class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + +# COERCIÓN DE TIPO +# La coerción de tipos es cuando forzas un valor diferente tipo al que puede tomar. +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Si pones elementos de diferentes tipos en un vector, coerciones raras pasan: +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Warning message: +# NAs introduced by coercion + +# También tomar nota: Esos solo eran datos de tipos básicos +# Hay mucho más tipos de datos, como las fechas, series de tiempo, etc. + + +################################################## +# Variables, ciclos, condiciones (if/else) +################################################## + +# A variable is like a box you store a value in for later use. +# We call this "assigning" the value to the variable. +# Having variables lets us write loops, functions, and if/else statements + +# VARIABLES +# Muchas maneras de asignar valores: +x = 5 # esto es posible +y <- "1" # esto es preferido +TRUE -> z # estos funciona pero es raro + +# CICLOS +# Tenemos ciclos 'for' +for (i in 1:4) { + print(i) +} +# Tenemos ciclos 'while' +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Ten en mente que los ciclos 'for' y 'while' son lentos en R +# Operaciones con vectores enteros (i.e. una fila o columna completa) +# o tipos de función apply() (que discutiremos después) son preferidos + +# CONDICIONES (IF/ELSE) +# De nuevo, bastante normal +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + +# FUNCIONES +# Definidos de la siguiente manera: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) #agregar un poco de ruido (controlado) + return(x) +} +# Llamados como cualquier otra función de R +jiggle(5) # 5±ε. luego de set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Estructura de datos: Vectores, matrices, marcos da datos y arreglos +########################################################################### + +# UNIDIMENSIONAL + +# Empecemos desde el principio, y con algo que ya conoces: vectores. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Preguntamos por elementos específicos poniendo un subconjunto en corchetes +# (Toma nota de que R empieza los conteos desde 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# También podes buscar por los índices de componentes específicos, +which(vec %% 2 == 0) # 1 3 +# obtener la primera o las últimas entradas de un vector, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# o averiguar si cierto valor se encuentra dentro de un vector +any(vec == 10) # TRUE +# Si un índice "se pasa", obtendrás un NA: +vec[6] # NA +# Puedes encontrar la longitud de un vector con length() +length(vec) # 4 +# Puedes realizar operaciones con vectores enteros o con subconjuntos de vectores +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# y R tiene muchas funciones pre-definidas para resumir vectores +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Otras funciones pre-definidas: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# => +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# BIDIMENCIONAL (TODO EN UNA CLASE) + +# Puedes hacer una matriz de las entradas todos de un mismo tipo como: +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# A diferencia de un vector, una clase matriz es una 'matriz', +# sin importar qué contiene +class(mat) # => "matrix" +# Consulta la primera fila +mat[1,] # 1 4 +# Realiza una operación en la primera columna +3 * mat[,1] # 3 6 9 +# Consulta por una celda específica +mat[3,2] # 6 + +# Transpone una matriz entera +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# Multiplicación de matrices +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() une vectores como columnas para hacer una matriz +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# De nuevo, ten en cuenta lo que sucedió +# Debido a que las matrices deben de contener todas las entradas del mismo tipo, +# todo fue convertido a la clase caracter +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() une vectores como filas para hacer una matriz +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, todo es de la misma clase. No hay coerciones. Mucho mejor. + +# BIDIMENSIONAL (DIFERENTES CLASES) + +# Para columnas de tipos diferentes, utiliza un data frame +# Esta estructura de datos es muy útil para programación estadística, +# una versión de ésta fue agregada a Python en el paquete "pandas". + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students +# => +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# encontrar las dimensiones +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# La función data.frame() convierte vectores de caracteres en vectores +# de factores por defecto; deshabilita este atributo +# stringsAsFactors = FALSE cuando vayas a crear el data.frame +?data.frame + +# Hay otras formas de hacer subconjuntos de data frames +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# Una versión aumentada de la estructura data.frame es el data.table +# Si estás trabajando huge o panel data, o necesitas unificar algunos +# subconjuntos de datos, data.table puede ser una buena elección. +# Aquí un tour: +install.packages("data.table") # Descarga el paquete de CRAN +require(data.table) # Cárgalo +students <- as.data.table(students) +students # Tomar en cuenta la diferencia de la impresión +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] # obtener filas con name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # obtener filas con year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table hace que la unificación de dos sets de datos sea fácil +# Hagamos otro data.table para unifiar a los estudiantes +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # Unifica los dos sets de datos comparando "house" +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# data.table hace que sea fácil obtener resúmenes de las tablas +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Para eliminar una columna de un data.frame o data.table, +# asignarle el valor NULL. +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Elimina una fila poniendo un subconjunto +# Usando data.table: +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Usando data.frame: +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTI-DIMENSIONAL (TODOS LOS ELEMENTOS DE UN TIPO) + +# Arreglos crean una tabla de dimensión n +# Todos los elementos deben de ser del mismo tipo +# Puedes hacer una tabla bi-dimensional (como una matriz) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Puedes utilizar un arreglo para hacer una matriz tri-dimensional también +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LISTAS (MULTI-DIMENSIONAL, POSIBLEMENTE DESIGUALES, DE DIFERENTES TIPOS) + +# Finalmente, R tiene listas (de vectores) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # aleatorio +list1 +# Puedes obtener elementos de una lista de la siguiente manera +list1$time # Una manera +list1[["time"]] # Otra manera +list1[[1]] # Y otra manera +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Puedes crear una lista de subconjuntos como cualquier otro vector +list1$price[4] + +# Las listas no son la estructura de datos más eficiente para trabajar en R; +# a menos de que tengas una buena razón, deberías de quedarte con data.frames +# Las listas son usualmente devueltas por funciones que realizan regresiones +# lineales + +################################################## +# La familia de funciones apply() +################################################## + +# Te recuerdas de mat? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Utiliza apply(X, MARGIN, FUN) paraaplicar una función FUN a la matriz X +# sobre las filas (MAR = 1) o las columnas (MAR = 2) +# Eso es, R aplica FUN sobre cada fila (o columna) de X, mucho más rápido que +# lo que haría un ciclo 'for' o 'loop' +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Otras funciones: ?lapply, ?sapply + +# No te sientas muy intimidado; todos están de acuerdo que son confusas + +# El paquete plyr busca reemplazar (y mejorar) la familiar *apply() +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Carga de datos +######################### + +# "pets.csv" es un archivo en internet +# (pero puede ser tan fácil como tener el archivo en tu computadora) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # primeras dos filas +tail(pets, 1) # última fila + +# Para guardar un data frame o una matriz como un archivo .csv +write.csv(pets, "pets2.csv") # para hacer un nuevo archivo .csv +# definir el directorio de trabajo con setwd(), búscalo con getwd() + +# Prueba ?read.csv ?write.csv para más información + + +######################### +# Gráficas +######################### + +# FUNCIONES PREDEFINIDAS DE GRAFICACIÓN +# Gráficos de dispersión! +plot(list1$time, list1$price, main = "fake data") +# Regresiones! +linearModel <- lm(price ~ time, data = list1) +linearModel # Muestra el resultado de la regresión +# Grafica la línea de regresión +abline(linearModel, col = "red") +# Obtiene una veridad de diagnósticos +plot(linearModel) +# Histogramas! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Barras! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Pero éstas no son las gráficas más bonitas de R +# Prueba el paquete ggplot2 para mayor variedad y mejores gráficas +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 tiene una excelente documentación +# (disponible en http://docs.ggplot2.org/current/) + + + +``` + +## ¿Cómo obtengo R? + +* Obtén R y R GUI de [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) es otro GUI diff --git a/r.html.markdown b/r.html.markdown index 8896c5b0..fbc87b0e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -2,7 +2,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] - - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] filename: learnr.r --- -- cgit v1.2.3 From f02ad99fdd90c4c522e00aca3b46a0db5dd24083 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 16:25:31 -0700 Subject: Fixed filename --- es-es/r-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown index db780c27..2b710b27 100644 --- a/es-es/r-es.html.markdown +++ b/es-es/r-es.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["David Hsieh", "http://github.com/deivuh"] lang: es-es -filename: learnr.r +filename: learnr-es.r --- R es un lenguaje de computación estadística. Tiene muchas librerías para cargar -- cgit v1.2.3 From e0645015b528fcb365da34d617ade037f89c0db9 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 17:05:50 -0700 Subject: Fixed obj-c-es filename --- es-es/objective-c-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index c5532c0f..7f8d130b 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["David Hsieh", "http://github.com/deivuh"] lang: es-es -filename: LearnObjectiveC.m +filename: LearnObjectiveC-es.m --- Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch. -- cgit v1.2.3 From dca117cecfda42d38f13195da0cf3a05e4d7045a Mon Sep 17 00:00:00 2001 From: everblut Date: Mon, 19 Oct 2015 19:27:06 -0500 Subject: Fix typos and update yaml-es content --- es-es/yaml-es.html.markdown | 189 +++++++++++++++++++++++++++++++------------- 1 file changed, 132 insertions(+), 57 deletions(-) diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown index a5157b5d..cd3143fb 100644 --- a/es-es/yaml-es.html.markdown +++ b/es-es/yaml-es.html.markdown @@ -4,6 +4,7 @@ lang: es-es filename: learnyaml-es.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Everardo Medina","https://github.com/everblut"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] --- @@ -14,7 +15,7 @@ leído y escrito por humanos. Basa su funcionalidad en JSON, con la adición de líneas nuevas e indentación inspirada en Python. A diferencia de Python, YAML -no permite tabs literales. +no permite tabulaciones literales. ```yaml # Los comentarios en YAML se ven así. @@ -38,97 +39,177 @@ llave con espacios: valor llave: "Un string, entre comillas." "Las llaves tambien pueden estar entre comillas.": "valor entre comillas" -# Los strings de líneas múltiples pueden ser escritos +# Los strings de líneas múltiples pueden ser escritos # como un 'bloque literal' (usando pipes |) # o como un 'bloque doblado' (usando >) bloque_literal: | Este bloque completo de texto será preservado como el valor de la llave 'bloque_literal', incluyendo los saltos de línea. - - Se continúa guardando la literal hasta que se cese la indentación. + + Se continúa guardando la literal hasta que se cese la indentación. Cualquier línea que tenga más indentación, mantendrá los espacios dados (por ejemplo, estas líneas se guardarán con cuatro espacios) -nloque_doblado: > +bloque_doblado: > De la misma forma que el valor de 'bloque_literal', todas estas líneas se guardarán como una sola literal, pero en esta ocasión todos los saltos de línea serán reemplazados por espacio. - Las líneas en blanco, como la anterior, son convertidos a un salto de línea. + Las líneas en blanco, como la anterior, son convertidas a un salto de línea. Las líneas con mayor indentación guardan sus saltos de línea. Esta literal ocuparán dos líneas. -######################## -# TIPOS DE COLECCIONES # -######################## - -# La indentación se usa para anidar. +# La indentación se usa para anidar elementos un_mapa_indentado: llave: valor otra_llave: otro valor otro_mapa_indentado: llave_interna: valor_interno -# Las llaves de los mapas no deben ser strings necesariamente +# Las llaves de los mapas no requieren ser strings necesariamente 0.25: una llave numérica -# Las llaves también pueden ser objetos de multi línea, usando ? para indicar -# el inicio de una llave +# Las llaves también pueden ser objetos de multiples líneas, +# usando ? para indicar el inicio de una llave ? | Esto es una llave que tiene múltiples líneas : y este es su valor -# YAML tambien permite colecciones como llaves, pero muchos lenguajes de +######################## +# TIPOS DE COLECCIONES # +######################## + +# Las colecciones en YAML usan la indentación para delimitar el alcance +# y cada elemento de la colección inicia en su propia línea. +# YAML tambien permite colecciones como llaves, pero muchos lenguajes de # programación se quejarán. # Las secuencias (equivalentes a listas o arreglos) se ven así: -una_secuencia: - - Item 1 - - Item 2 - - 0.5 # las secuencias pueden tener distintos tipos en su contenido. - - Item 4 - - llave: valor - otra_llave: otro_valor +- Amarillo +- Verde +- Azul + +# Se puede usar una secuencia como valor para una llave. +secuencia: + - Elemento 1 + - Elemento 2 + - Elemento 3 + - Elemento 4 + +# Las secuencias pueden contener secuencias como elementos. +- [Uno, Dos, Tres] +- [Domingo, Lunes, Martes] +- [Luna, Marte, Tierra] + +# Las secuencias pueden tener distintos tipos en su contenido. +secuencia_combinada: + - texto + - 5 + - 0.6 + - llave: valor # se convierte en un json dentro de la secuencia - - Esta es una secuencia - ...dentro de otra secuencia -# Dado que todo JSON está incluído dentro de YAML, también puedes escribir -# mapas con la sintaxis de JSON y secuencias: -mapa_de_json: {"llave": "valor"} -secuencia_de_json: [3, 2, 1, "despegue"] +# Dado que todo JSON está incluído dentro de YAML, también puedes escribir +# mapas con la sintaxis de JSON y secuencias: +mapa_de_json_1: {"llave": "valor"} +mapa_de_json_2: + llave: valor + +# Las secuencias tambien se pueden escribir como un arreglo al estilo JSON +secuencia_de_json_1: [3, 2, 1, "despegue"] +secuencia_de_json_2: + - 3 + - 2 + - 1 + - "despegue" + +# YAML también soporta conjuntos usando el simbolo ? +# y se ven de la siguiente forma: +set: + ? item1 + ? item2 + ? item3 + +# Se puede usar el tag !!set +# Al igual que Python, los conjuntos sólo son mapas con valores nulos. +# El ejemplo de arriba es equivalente a: +set2: + item1: null + item2: null + item3: null ################################## # CARACTERÍSTICAS EXTRAS DE YAML # ################################## +# YAML usa tres guiones (---) para diferenciar entre directivas +# y contenido del documento. +# Por otra parte, tres puntos (...) se utilizan para indicar +# el final del documento en casos especiales. + # YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten -# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo -# a continuación, ambas llaves tendrán el mismo valor: -contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves -otra_ancla: *nombre_del_ancla - -# YAML también tiene tags, que puedes usar para declarar tipos explícitamente. -string_explícito: !!str 0.5 -# Algunos parseadores implementar tags específicas del lenguaje, como el +# duplicar fácilmente contenido a lo largo de tu documento. +# El ampersand indica la declaración del ancla, +declara_ancla: &texto texto de la llave +# el asterisco indica el uso de dicha ancla. +usa_ancla: *texto # tendrá el valor "texto de la llave" + +################ +# TAGS EN YAML # +################ + +# En YAML, los nodos que no tienen un tag obtienen su tipo +# según la aplicación que los use, al usar un tag +# se pueden declarar tipos explícitamente. +string_explicito: !!str 0.5 # !!str para declarar un string +integer_explicito: !!int 5 # !!int para declarar un integer +float_explicito: !!float 1.2 # !!float para declarar un float +conjunto_explicito: !!set # !!set para declarar un conjunto + ? Uno + ? Dos + ? Tres +mapa_ordenado_explicito: !!omap # !!omap para declarar un mapa ordenado +- Primero: 1 +- Segundo: 2 +- Tercero: 3 +- Cuarto: 4 + +# Tags para los numeros enteros +llave_canonica: 5222 +llave_decimal: +5222 +llave_octal: 010 +llave_hexadecimal: 0xC + +#Tags para los numeros flotantes +llave_canonica: 1.215e+3 +llave_exponencial: 12.3555e+02 +llave_fija: 12.15 +llave_negativa_infinita: -.inf +llave_numero_invalido: .NaN + +# Tags para las fechas y horas +llave_canonica: 2001-12-15T02:59:43.1Z +llave_iso8601: 2001-12-14t21:59:43.10-05:00 +llave_con_espacios: 2001-12-14 21:59:43.10 -5 +llave_fecha: 2002-12-14 + +# Además existen tags para +null: #valor nulo +booleans: [ true, false ] # Valores booleanos +string: '012345' # Valor en string + + +# Algunos parseadores implementan tags específicas del lenguaje, como el # que se muestra a continuación, encargado de manejar números complejos en # Python: numero_complejo_python: !!python/complex 1+2j -######################## -# TIPOS EXTRAS EN YAML # -######################## - -# Stirngs y números no son los únicos escalares que YAML puede entener. -# YAML también puede parsear fechas en formato ISO . -fechaHora: 2001-12-15T02:59:43.1Z -fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5 -fecha: 2002-12-14 - -# La tag !!binary indica que un string es, en realidad, un blob +# El tag !!binary indica que un string es en realidad un blob # representado en base-64. archivo_gif: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 @@ -136,16 +217,10 @@ archivo_gif: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML también tiene un tipo set, que se ve de la siguiente forma: -set: - ? item1 - ? item2 - ? item3 - -# Al igual que Python, los sets sólo son mapas con valores nulos. -# El ejemplo de arriba es equivalente a: -set2: - item1: null - item2: null - item3: null ``` + +### Recursos adicionales + ++ [Sitio oficial de YAML](http://yaml.org/) ++ [Parser en línea de de YAML](http://yaml-online-parser.appspot.com/) ++ [Validador en línea de YAML](http://codebeautify.org/yaml-validator) -- cgit v1.2.3 From dc235b3d13c1c7a3a11585dcce8adf992bf707f6 Mon Sep 17 00:00:00 2001 From: tricinel Date: Tue, 20 Oct 2015 10:18:08 +0200 Subject: [coffeescript/en] Add coffeescript translation to Romanian --- ro-ro/coffeescript-ro.html.markdown | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 ro-ro/coffeescript-ro.html.markdown diff --git a/ro-ro/coffeescript-ro.html.markdown b/ro-ro/coffeescript-ro.html.markdown new file mode 100644 index 00000000..ece502a0 --- /dev/null +++ b/ro-ro/coffeescript-ro.html.markdown @@ -0,0 +1,101 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Bogdan Lazar", "http://twitter.com/tricinel"] +filename: coffeescript.coffee +--- + +CoffeeScript este un limbaj de programare care este compilat in Javascript. Nu exista un interpretator la runtime-ul aplicatiei. Fiind unul din successorii Javascript, CoffeeScript incearca sa compileze Javascript usor de citit si performant. + +Mai cititi si [website-ul CoffeeScript](http://coffeescript.org/), care contine un tutorial complet Coffeescript. + +```coffeescript +# CoffeeScript este un limbaj de hipster. +# Se foloseste de trendurile multor limbaje moderne de programare. +# Comentarii sunt ca in Ruby sau Python. + +### +Comentariile in bloc sunt create cu `###`, iar acestea sunt transformate in `/*` si `*/` pentru Javascript + +Ar trebuie sa intelegeti Javascript pentru a continua cu acest ghid. +### + +# Atribuirea valorilor: +numar = 42 #=> var numar = 42; +opus = true #=> var opus = true; + +# Conditii: +numar = -42 if opus #=> if(opus) { numar = -42; } + +# Functii: +laPatrat = (x) -> x * x #=> var laPatrat = function(x) { return x * x; } + +plin = (recipient, lichid = "cafea") -> + "Umplem #{recipient} cu #{cafea}..." +#=>var plin; +# +#plin = function(recipient, lichid) { +# if (lichid == null) { +# lichid = "cafea"; +# } +# return "Umplem " + recipient + " cu " + lichid + "..."; +#}; + +# Liste: +lista = [1..5] #=> var lista = [1, 2, 3, 4, 5]; + +# Obiecte: +matematica = + radacina: Math.sqrt + laPatrat: laPatrat + cub: (x) -> x * square x +#=> var matematica = { +# "radacina": Math.sqrt, +# "laPatrat": laPatrat, +# "cub": function(x) { return x * square(x); } +# }; + +# Splats: +cursa = (castigator, alergatori...) -> + print castigator, alergatori +#=>cursa = function() { +# var alergatori, castigator; +# castigator = arguments[0], alergatori = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(castigator, alergatori); +# }; + +# Verificarea existentei: +alert "Stiam eu!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Stiam eu!"); } + +# Operatiuni cu matrice: +cuburi = (math.cube num for num in list) +#=>cuburi = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +alimente = ['broccoli', 'spanac', 'ciocolata'] +mananca aliment for aliment in alimente when aliment isnt 'ciocolata' +#=>alimente = ['broccoli', 'spanac', 'ciocolata']; +# +#for (_k = 0, _len2 = alimente.length; _k < _len2; _k++) { +# aliment = alimente[_k]; +# if (aliment !== 'ciocolata') { +# eat(aliment); +# } +#} +``` + +## Resurse aditionale + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 2f0acd34e28ee46e52391b349ddf3ca86ce95bc7 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:01:47 +0800 Subject: [Sass/ms-my] Added Malay (Malaysia) translation for Sass --- ms-my/sass-my.html.markdown | 232 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 ms-my/sass-my.html.markdown diff --git a/ms-my/sass-my.html.markdown b/ms-my/sass-my.html.markdown new file mode 100644 index 00000000..2249a790 --- /dev/null +++ b/ms-my/sass-my.html.markdown @@ -0,0 +1,232 @@ +--- +language: sass +filename: learnsass-my.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +Sass ialah bahasa sambungan CSS yang menambah ciri-ciri seperti pembolehubah, bersarang, mixins dan banyak lagi. +Sass (dan prapemproses lain, seperti [Less](http://lesscss.org/)) membantu pembangun untuk menulis kod mampu diselenggara dan DRY (Don't Repeat Yourself). + +Sass mempunyai dua perbezaan pilihan sintaks untuk dipilih. SCSS, yang mana mempunyai sintaks yang sama seperti CSS tetapi dengan ditambah ciri-ciri Sass. Atau Sass (sintaks asal), yang menggunakan indentasi bukannya tanda kurung dakap dan semikolon. +Tutorial ini ditulis menggunakan SCSS. + +```scss + +//Komen baris tunggal dikeluarkan apabila Sass dikompil ke CSS. + +/*Komen multi dikekalkan. */ + + + +/*Pembolehubah +==============================*/ + + + +/* Anda boleh menyimpan nilai CSS (seperti warna) dalam pembolehubah. +Guna simbol '$' untuk membuat pembolehubah. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Anda boleh mengguna pembolehubah diseluruh lembaran gaya anda. +Kini jika anda ingin mengubah warna, anda hanya perlu membuat perubahan sekali.*/ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Ia akan dikompil kepada: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Ini jauh lebih mampu diselenggara daripada perlu menukar warna +setiap yang ada diseluruh lembaran gaya anda. */ + + + +/*Mixins +==============================*/ + + + +/* Jika anda jumpa yang anda menulis kod yang sama pada lebih dari satu +elemen, anda mungkin ingin menyimpan kod itu di dalam mixin. + +Guna arahan '@mixin', tambah dengan nama untuk mixin anda.*/ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Anda boleh guna mixin bersama '@include' dan nama mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/*Ia akan dikompil kepada: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Anda boleh guna mixins untuk membuat singkatan property. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/*Yang mana anda boleh seru dengan memberi argumen lebar dan tinggi. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Ia dikompil kepada: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend ialah jalan untuk berkongsi sifat dengan satu pemilih dengan yang lain. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Dikompil kepada: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + + + + +/*Bersarang +==============================*/ + + + +/*Sass membenarkan anda untuk sarangkan pemilih dengan pemilih */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' akan digantikan dengan pemilih induk. */ +/* Anda juga boleh sarangkan kelas-pseudo. */ +/* Perlu diingat terlebih bersarang akan membuat kod anda kurang mampu diselenggara. +Sebagai contoh: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Dikompil kepada: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + + +``` + + + +## SASS atau Sass? +Adakah anda tertanya-tanya sama ada Sass adalah akronim atau tidak? Anda mungkin tidak perlu, tetapi saya akan memberitahu. Nama bahasa ini adalah perkataan, "Sass", dan tidak akronim. +Kerana orang sentiasa menulis ia sebagai "Sass", pencipta bahasa bergurau memanggilnya "Syntactically Awesome StyleSheets". + +## Berlatih Sass +Jika anda ingin bermain dengan Sass di pelayar anda, lihat [SassMeister](http://sassmeister.com/). +Anda boleh guna salah satu sintaks, hanya pergi ke tetapan dan pilih sama ada Sass atau SCSS. + + +## Bacaan lanjut +* [Dokumentasi Rasmi](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) menyediakan tutorial (asas-lanjutan) dan artikel. -- cgit v1.2.3 From 17d10c158227270573cb4110fe402ff1c42caee8 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:18:43 +0800 Subject: [Bash/ms-my] Added Malay (Malaysia) translation for Bash --- ms-my/bash-my.html.markdown | 284 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 284 insertions(+) create mode 100644 ms-my/bash-my.html.markdown diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown new file mode 100644 index 00000000..51036ad9 --- /dev/null +++ b/ms-my/bash-my.html.markdown @@ -0,0 +1,284 @@ +--- +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"] +filename: LearnBash.sh +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell. + +[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Baris pertama daripada skrip ialah shebang yang mana memberitahu sistem bagaimana untuk melaksana +# skrip: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Seperti yang anda sudah gambarkan, komen bermula dengan #. Shebang juga ialah komen. + +# Contoh mudah hello world: +echo Hello world! + +# Setiap arahan bermula pada baris baru, atau selepas semikolon: +echo 'This is the first line'; echo 'This is the second line' + +# Mengisytihar pembolehubah kelihatan seperti ini: +Variable="Some string" + +# Tetapi bukan seperti ini: +Variable = "Some string" +# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti dilaksanakan dan memberi ralat +# kerana ia tidak boleh dijumpai. + +# Atau seperti ini: +Variable= 'Some string' +# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti dilaksanakan dan memberi +# ralat kerana ia tidak dijumpai. (Dalam kes ini ‘Variable=' sebahagian dilihat +# sebagai penetapan pembolehubah sah hanya untuk skop ‘Beberapa rentetan’ +# arahan.) + +# Menggunakan pembolehubah: +echo $Variable +echo "$Variable" +echo '$Variable' +# Apabila anda guna pembolehubah itu sendiri - menetapkan, mengeksport, atau lain-lain - anda menulis +# nama ia tanpa $. Atau anda ingin menggunakan nilai pembolehubah, anda mesti guna $. +# Perlu diingatkan ‘(Petikan tunggal) tidak akan memperluaskan pembolehubah! + +# Penggantian rentetan dalam pembolehubah +echo ${Variable/Some/A} +# Ini akan menukarkan sebutan pertama bagi "Some" dengan "A" + +# Subrentetan daripada pembolehubah +Length=7 +echo ${Variable:0:Length} +# Ini akan kembalikan hanya 7 aksara pertama pada nilai + +# Nilai lalai untuk pembolehubah +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# Ini berfungsi untuk null (Foo=) dan rentetan kosong (Foo=“”); sifar (Foo=0) kembali 0. +# Perlu diingatkan ia hanya kembalikan nilai lalai dan tidak mengubah nilai pembolehubah. + +# Pembolehubah terbina: +# Terdapat beberapa pembolehubah terbina berguna, seperti +echo "Last program's return value: $?" +echo "Script's PID: $$" +echo "Number of arguments passed to script: $#" +echo "All arguments passed to script: $@" +echo "Script's arguments separated into different variables: $1 $2..." + +# Membaca nilai dari input: +echo "What's your name?" +read Name # Perlu diingatkan kita tidak perlu isytihar pembolehubah baru +echo Hello, $Name! + +# Kita ada yang biasa jika struktur: +# guna 'man test' untuk maklumat lanjut tentang bersyarat +if [ $Name -ne $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# Terdapat juga pelaksanaan bersyarat +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# Untuk guna & dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + +# Eskspresi ia ditandai dengan format berikut: +echo $(( 10 + 5 )) + +# Tidak seperti bahasa pengaturcaraan lain, bash adalah shell jadi ia berfungsi dalam konteks +# daripada direktori semasa. Anda boleh menyenaraikan fail dan direktori dalam direktori +# semasa dengan arahan ini: +ls + +# Arahan ini mempunyai opsyen yang mengawal perlaksanaannya: +ls -l # Senarai setiap fail dan direktori pada baris yang berbeza + +# Keputusan arahan sebelum boleh diberikan kepada arahan selepas sebagai input. +# arahan grep menapis input dengan memberi paten. Ini bagaimana kita boleh senaraikan +# fail .txt di dalam direktori semasa: +ls -l | grep "\.txt" + +# Anda boleh mengubah hala arahan input dan output (stdin, stdout, and stderr). +# Baca dari stdin sampai ^EOF$ dan menulis ganti hello.py dengan baris +# antara “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 + +# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, and 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 +# Output ralat akan menulis ganti fail jika ia wujud, +# jika anda ingin menambah sebaliknta, guna ‘>>”: +python hello.py >> "output.out" 2>> "error.err" + +# Menulis ganti output.out, menambah ke error.err, dan mengira baris: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Jalankan arahan dan cetak fail Deskriptor (e.g. /dev/fd/123) +# lihat: man fd +echo <(echo "#helloworld") + +# Menulis ganti output.out dengan “#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Membersihkan fail semantara keseluruhan (tambah ‘-i’ untuk interaktif) +rm -v output.out error.err output-and-error.log + +# Arahan boleh digantikan dalam arahan lain menggunakan $(): +# Arahan berikut memaparkan jumlah fail dan direktori dalam +# direktori semasa. +echo "There are $(ls | wc -l) items here." + +# Perkara yang sama boleh dilakukan dengan menggunakan backticks `` tetapi ia tidak boleh bersarang - cara yang terbaik +# ialah menggunakan $( ). +echo "There are `ls | wc -l` items here." + +# Bash menggunakan penyataan case yang berfungsi sama seperti ‘switch’ pada Java dan C++: +case "$Variable" in + # Senarai paten untuk syarat yang ada ingin ketemui + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# ‘for loops iterate' untuk sebanyak mana argumen yang ditetapkan: +# Kandungan dari $Variable dicetakan tiga kali. +for Variable in {1..3} +do + echo "$Variable" +done + +# Atau tulis ia cara "traditional for loop": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Ia juga boleh digunakan untuk bertindak ke atas fail.. +# Ini akan menjalankan arahan 'cat' pada file1 dan file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# ..atau output daripada arahan +# Ini akan 'cat' output dari ls. +for Output in $(ls) +do + cat "$Output" +done + +# while loop: +while [ true ] +do + echo "loop body here..." + break +done + +# Anda juga boleh mendefinasikan fungsi +# Definasi: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# atau lebih mudah +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# Memanggil fungsi +foo "My name is" $Name + +# Terdapat banyak arahan yang berguna yang perlu anda belajar: +# cetak 10 baris terakhir dalam file.txt +tail -n 10 file.txt +# cetak 10 baris pertama dalam file.txt +head -n 10 file.txt +# menyusun baris fail.txt +sort file.txt +# laporan atau meninggalkan garisan berulang, dengan -d ia melaporkan +uniq -d file.txt +# cetak hanya kolum pertama sebelum aksara ',' +cut -d ',' -f 1 file.txt +# menggantikan setiap kewujudan 'okay' dengan 'great' dalam file.txt, (serasi regex) +sed -i 's/okay/great/g' file.txt +# cetak ke stdoout semua baris dalam file.txt yang mana sepadan beberapa regex +# contoh cetak baris yang mana bermula dengan “foo” dan berakhir dengan “bar” +grep "^foo.*bar$" file.txt +# beri opsyen “-c” untuk sebaliknya mencetak jumlah baris sepadan regex +grep -c "^foo.*bar$" file.txt +# jika anda secara literal mahu untuk mencari rentetan, +# dan bukannya regexm guna fgrep (atau grep -F) +fgrep "^foo.*bar$" file.txt + + +# Baca dokumentasi Bash shell terbina dengan 'help' terbina: +help +help help +help for +help return +help source +help . + +# Baca dokumentasi Bash manpage dengan man +apropos bash +man 1 bash +man bash + +# Baca info dokumentasi dengan info (? for help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Baca dokumentasi bash info: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From de9539a7775b39328c4bbe5e01efcd826ce8ade2 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:34:34 +0800 Subject: Fix some word --- ms-my/bash-my.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown index 51036ad9..3632911d 100644 --- a/ms-my/bash-my.html.markdown +++ b/ms-my/bash-my.html.markdown @@ -96,7 +96,7 @@ fi echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" -# Untuk guna & dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: +# Untuk guna && dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: if [ $Name == "Steve" ] && [ $Age -eq 15 ] then echo "This will run if $Name is Steve AND $Age is 15." @@ -181,7 +181,7 @@ case "$Variable" in esac # ‘for loops iterate' untuk sebanyak mana argumen yang ditetapkan: -# Kandungan dari $Variable dicetakan tiga kali. +# Kandungan dari $Variable dicetakan sebanyak tiga kali. for Variable in {1..3} do echo "$Variable" @@ -270,7 +270,7 @@ apropos bash man 1 bash man bash -# Baca info dokumentasi dengan info (? for help) +# Baca dokumentasi info dengan info (? for help) apropos info | grep '^info.*(' man info info info -- cgit v1.2.3 From db8d8558809e7a6501f2f91ad3d6b12f16cf369f Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:17:44 -0300 Subject: Paren translation to brazillian portuguese --- pt-br/paren-pt.html.markdown | 196 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 pt-br/paren-pt.html.markdown diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown new file mode 100644 index 00000000..bd0c95e7 --- /dev/null +++ b/pt-br/paren-pt.html.markdown @@ -0,0 +1,196 @@ +--- +language: Paren +filename: learnparen-pt.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br +--- + +[Paren](https://bitbucket.org/ktg/paren) é um dialeto do Lisp. É projetado para ser uma linguagem embutida. + +Alguns exemplos foram retirados de . + +```scheme +;;; Comentários +# Comentários + +;; Comentários de única linha começam com um ponto e vírgula ou cerquilha + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Tipos de Dados Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Números +123 ; inteiro +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : inteiro +(double 123) ; => 123 : double + +;; O uso de funções é feito da seguinte maneira (f x y z ...) +;; onde f é uma função e x, y, z, ... são os operandos +;; Se você quiser criar uma lista literal de dados, use (quote) para impedir +;; que sejam interpretados +(quote (+ 1 2)) ; => (+ 1 2) +;; Agora, algumas operações aritméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Booleanos +true ; para verdadeiro +false ; para falso +(! true) ; => falso +(&& true false (prn "não chega aqui")) ; => falso +(|| false true (prn "não chega aqui")) ; => verdadeiro + +;;; Caracteres são inteiros. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Strings são arrays de caracteres de tamanho fixo. +"Olá, mundo!" +"Sebastião \"Tim\" Maia" ; Contra-barra é um caractere de escape +"Foo\tbar\r\n" ; Inclui os escapes da linguagem C: \t \r \n + +;; Strings podem ser concatenadas também! +(strcat "Olá " "mundo!") ; => "Olá mundo!" + +;; Uma string pode ser tratada como uma lista de caracteres +(char-at "Abacaxi" 0) ; => 65 + +;; A impressão é muito fácil +(pr "Isso é" "Paren. ") (prn "Prazer em conhecê-lo!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar ou definir uma variável usando (set) +;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +(set alguma-variavel 5) ; => 5 +alguma-variavel ; => 5 + +;; Acessar uma variável ainda não atribuída gera uma exceção +; x ; => Unknown variable: x : nil + +;; Ligações locais: Utiliza cálculo lambda! +;; 'a' e 'b' estão ligados a '1' e '2' apenas dentro de (fn ...) +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Listas + +;; Listas são estruturas de dados semelhantes a vetores. (A classe de comportamento é O(1).) +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; 'list' é uma variação conveniente para construir listas +(list 1 2 3) ; => (1 2 3) +;; Um quote também pode ser usado para uma lista de valores literais +(quote (+ 1 2)) ; => (+ 1 2) + +;; Você ainda pode utilizar 'cons' para adicionar um item ao início da lista +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Listas são um tipo muito básico, portanto existe *enorme* funcionalidade +;; para elas, veja alguns exemplos: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'fn' para criar funções. +;; Uma função sempre retorna o valor de sua última expressão +(fn () "Olá Mundo") ; => (fn () Olá Mundo) : fn + +;; Use parênteses para chamar todas as funções, incluindo uma expressão lambda +((fn () "Olá Mundo")) ; => "Olá Mundo" + +;; Atribuir uma função a uma variável +(set ola-mundo (fn () "Olá Mundo")) +(ola-mundo) ; => "Olá Mundo" + +;; Você pode encurtar isso utilizando a definição de função açúcar sintático: +(defn ola-mundo2 () "Olá Mundo") + +;; Os () acima é a lista de argumentos para a função +(set ola + (fn (nome) + (strcat "Olá " nome))) +(ola "Steve") ; => "Olá Steve" + +;; ... ou equivalente, usando a definição açucarada: +(defn ola2 (nome) + (strcat "Olá " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Para números utilize '==' +(== 3 3.0) ; => verdadeiro +(== 2 1) ; => falso + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Controle de Fluxo +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if true ; Testa a expressão + "isso é verdade" ; Então expressão + "isso é falso") ; Senão expressão +; => "isso é verdade" + +;;; Laços de Repetição + +;; O laço for é para número +;; (for SÍMBOLO INÍCIO FIM SALTO EXPRESSÃO ..) +(for i 0 10 2 (pr i "")) ; => Imprime 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => Imprime 0 2.5 5 7.5 10 + +;; Laço while +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => Imprime 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'set' para atribuir um novo valor a uma variável ou local +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros lhe permitem estender a sintaxe da linguagem. +;; Os macros no Paren são fáceis. +;; Na verdade, (defn) é um macro. +(defmacro setfn (nome ...) (set nome (fn ...))) +(defmacro defn (nome ...) (def nome (fn ...))) + +;; Vamos adicionar uma notação infixa +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Macros não são higiênicos, você pode sobrescrever as variáveis já existentes! +;; Eles são transformações de códigos. +``` -- cgit v1.2.3 From de34d88d94864ecf77151a866b512045ce196d74 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:26:25 -0300 Subject: Translation revision improvements --- pt-br/paren-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown index bd0c95e7..464a69d2 100644 --- a/pt-br/paren-pt.html.markdown +++ b/pt-br/paren-pt.html.markdown @@ -72,7 +72,7 @@ false ; para falso ;; 2. Variáveis ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Você pode criar ou definir uma variável usando (set) -;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +;; o nome de uma variável pode conter qualquer caracter, exceto: ();#" (set alguma-variavel 5) ; => 5 alguma-variavel ; => 5 -- cgit v1.2.3 From e675c887fe27538805a2b8deddf3f3d37a653d7c Mon Sep 17 00:00:00 2001 From: Dean Becker Date: Tue, 20 Oct 2015 16:32:49 +0100 Subject: Expanded XML Doc example Just an expansion of the XML documentation example, the tag can be very useful in Visual Studio, especially. --- csharp.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..c844c479 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -24,7 +24,9 @@ Multi-line comments look like this /// This is an XML documentation comment which can be used to generate external /// documentation or provide context help within an IDE /// -//public void MethodOrClassOrOtherWithParsableHelp() {} +/// This is some parameter documentation for firstParam +/// Information on the returned value of a function +//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {} // Specify the namespaces this source code will be using // The namespaces below are all part of the standard .NET Framework Class Libary -- cgit v1.2.3 From 0d5701f465d4304cf278d6d3aac3f8fd032fee7e Mon Sep 17 00:00:00 2001 From: hack1m Date: Wed, 21 Oct 2015 14:30:08 +0800 Subject: Fix some word and char --- ms-my/bash-my.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown index 3632911d..d430fd06 100644 --- a/ms-my/bash-my.html.markdown +++ b/ms-my/bash-my.html.markdown @@ -38,12 +38,12 @@ Variable="Some string" # Tetapi bukan seperti ini: Variable = "Some string" -# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti dilaksanakan dan memberi ralat +# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti laksanakan dan memberi ralat # kerana ia tidak boleh dijumpai. # Atau seperti ini: Variable= 'Some string' -# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti dilaksanakan dan memberi +# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti laksanakan dan memberi # ralat kerana ia tidak dijumpai. (Dalam kes ini ‘Variable=' sebahagian dilihat # sebagai penetapan pembolehubah sah hanya untuk skop ‘Beberapa rentetan’ # arahan.) @@ -123,7 +123,7 @@ ls -l # Senarai setiap fail dan direktori pada baris yang berbeza # fail .txt di dalam direktori semasa: ls -l | grep "\.txt" -# Anda boleh mengubah hala arahan input dan output (stdin, stdout, and stderr). +# Anda boleh mengubah hala arahan input dan output (stdin, stdout, dan stderr). # Baca dari stdin sampai ^EOF$ dan menulis ganti hello.py dengan baris # antara “EOF": cat > hello.py << EOF @@ -136,14 +136,14 @@ for line in sys.stdin: print(line, file=sys.stdout) EOF -# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, and stderr: +# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, dan 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 # Output ralat akan menulis ganti fail jika ia wujud, -# jika anda ingin menambah sebaliknta, guna ‘>>”: +# jika anda ingin menambah sebaliknya, guna ‘>>”: python hello.py >> "output.out" 2>> "error.err" # Menulis ganti output.out, menambah ke error.err, dan mengira baris: @@ -253,7 +253,7 @@ grep "^foo.*bar$" file.txt # beri opsyen “-c” untuk sebaliknya mencetak jumlah baris sepadan regex grep -c "^foo.*bar$" file.txt # jika anda secara literal mahu untuk mencari rentetan, -# dan bukannya regexm guna fgrep (atau grep -F) +# dan bukannya regex, guna fgrep (atau grep -F) fgrep "^foo.*bar$" file.txt -- cgit v1.2.3 From 976d3c1aec5d029e7b5da612b3f9b21325083f67 Mon Sep 17 00:00:00 2001 From: hack1m Date: Wed, 21 Oct 2015 14:39:41 +0800 Subject: [XML/ms-my] Added Malay (Malaysia) translation for XML --- ms-my/xml-my.html.markdown | 130 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 ms-my/xml-my.html.markdown diff --git a/ms-my/xml-my.html.markdown b/ms-my/xml-my.html.markdown new file mode 100644 index 00000000..68de35c9 --- /dev/null +++ b/ms-my/xml-my.html.markdown @@ -0,0 +1,130 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +XML adalah bahasa markup direka untuk menyimpan dan mengangkutan data. + +Tidak seperti HTML, XML tidak menyatakan bagaimana paparan atau mengformat data, hanya membawanya. + +* Sintaks XML + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + +computer.gif + + +``` + +* Dokumen Format sempurna x Pengesahan + +Satu dokumen XML adalah format sempurna jika ia adalah sintaksis yang betul. +Walau bagaimanapun, ia mungkin menyuntik lebih banyak kekangan dalam dokumen itu, +menggunakan definasi dokumen, seperti DTD dan Skema XML. + +Satu dokumen XML yang mana mengikut definasi dokumen dipanggil sah, +mengenai dokumen itu. + +Dengan alat ini, anda boleh menyemak data XML di luar logik aplikasi. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 89876929cb4181cac29c8aef149ae140a8c570be Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:19:08 +0200 Subject: Add dutch translation of JSON Add dutch translation of JSON --- nl-nl/json-nl.html.markdown | 71 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 nl-nl/json-nl.html.markdown diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown new file mode 100644 index 00000000..906112ff --- /dev/null +++ b/nl-nl/json-nl.html.markdown @@ -0,0 +1,71 @@ +--- +language: json +filename: learnjson-nl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste +Learn X in Y Minutes ooit zijn. + +JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de +meeste parsers support voor C-stijl (`//`, `/* */`) commentaar. +Sommige parsers staan zelfs trailing komma's toe. +(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object). +Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken. + +In het voorbeeld zal alleen 100% geldige JSON gebruikt worden. + +Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null. +Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. +De extensie voor JSON bestanden is ".json". De MIME type is "application/json" +Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD. + +```json +{ + "sleutel": "waarde", + + "sleutels": "zijn altijd in quotes geplaatst", + "nummers": 0, + "strings": "Hallø, wereld. Alle unicode karakters zijn toegestaan, samen met \"escaping\".", + "boolean": true, + "niks": null, + + "groot nummer": 1.2e+100, + + "objecten": { + "commentaar": "In JSON gebruik je vooral objecten voor je strutuur", + + "array": [0, 1, 2, 3, "Arrays kunnen alles in zich hebben.", 5], + + "nog een object": { + "commentaar": "Objecten kunnen genest worden, erg handig." + } + }, + + "dwaasheid": [ + { + "bronnen van kalium": ["bananen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatieve stijl": { + "commentaar": "Kijk dit!" + , "De komma positie": "maakt niet uit zolang het er maar is" + , "nog meer commentaar": "wat leuk" + }, + + "dat was kort": "En nu ben je klaar, dit was alles wat je moet weten over JSON." +} +``` -- cgit v1.2.3 From 5d09bdab933a6fca3eff2227714fac2da6b1538f Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:20:33 +0200 Subject: Add dutch translation of TypeScript Add dutch translation of TypeScript --- nl-nl/typescript-nl.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 nl-nl/typescript-nl.html.markdown diff --git a/nl-nl/typescript-nl.html.markdown b/nl-nl/typescript-nl.html.markdown new file mode 100644 index 00000000..dcea2a4d --- /dev/null +++ b/nl-nl/typescript-nl.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript-nl.ts +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +TypeScript is een taal gericht op het versoepelen van de ontwikkeling van +grote applicaties gemaakt in JavaScript. +TypeScript voegt veelgebruikte technieken zoals klassen, modules, interfaces, +generieken en statische typen toe aan JavaScript. +TypeScript is een superset van JavaScript: alle JavaScript code is geldige +TypeScript code waardoor de overgang van JavaScript naar TypeScript wordt versoepeld. + +Dit artikel focust zich alleen op de extra's van TypeScript tegenover [JavaScript] (../javascript-nl/). + +Om de compiler van TypeScript te kunnen proberen kun je naar de [Playground] (http://www.typescriptlang.org/Playground) gaan. +Hier kun je automatisch aangevulde code typen in TypeScript en de JavaScript variant bekijken. + +```js +// Er zijn 3 basis typen in TypeScript +var isKlaar: boolean = false; +var lijnen: number = 42; +var naam: string = "Peter"; + +// Wanneer het type onbekend is gebruik je "Any" +var nietZeker: any = 4; +nietZeker = "misschien een string"; +nietZeker = false; // Toch een boolean + +// Voor collecties zijn er "typed arrays" +var lijst: number[] = [1, 2, 3]; +// of generieke arrays +var lijst: Array = [1, 2, 3]; + +// Voor enumeraties: +enum Kleur {Rood, Groen, Blauw}; +var c: Kleur = Kleur.Groen; + +// Als laatst, "void" wordt gebruikt voor als een functie geen resultaat geeft +function groteVerschrikkelijkeMelding(): void { + alert("Ik ben een vervelende melding!"); +} + +// Functies zijn eersteklas ?, supporten de lambda "fat arrow" syntax en +// gebruiken gebruiken "type inference" + +// Het volgende is allemaal hetzelfde +var f1 = function(i: number): number { return i * i; } +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +var f4 = (i: number) => { return i * i; } +// Omdat we maar 1 lijn gebruiken hoeft het return keyword niet gebruikt te worden +var f5 = (i: number) => i * i; + +// Interfaces zijn structureel, elk object wat de eigenschappen heeft +// is een gebruiker van de interface +interface Persoon { + naam: string; + // Optionele eigenschappen worden gemarkeerd met "?" + leeftijd?: number; + // En natuurlijk functies + verplaats(): void; +} + +// Object die gebruikt maakt van de "Persoon" interface +// Kan gezien worden als persoon sinds het de naam en verplaats eigenschappen bevat +var p: Persoon = { naam: "Bobby", verplaats: () => {} }; +// Object met de optionele leeftijd eigenschap +var geldigPersoon: Persoon = { naam: "Bobby", leeftijd: 42, verplaats: () => {} }; +// Ongeldig persoon vanwege de leeftijds type +var ongeldigPersoon: Persoon = { naam: "Bobby", leeftijd: true }; + +// Interfaces kunnen ook een functie ype beschrijven +interface ZoekFunc { + (bron: string, subString: string): boolean; +} +// Alleen de parameters types zijn belangrijk, namen maken niet uit. +var mySearch: ZoekFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - leden zijn standaard publiek +class Punt { + // Eigenschappen + x: number; + + // Constructor - de publieke / prive trefwoorden in deze context zullen + // eigenschappen in de klasse kunnen aanmaken zonder ze te defineren. + // In dit voorbeeld zal "y" net als "x" gedefineerd worden met minder code. + // Standaard waardes zijn ook gesupport + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functies + dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statische leden + static origin = new Punt(0, 0); +} + +var p1 = new Punt(10 ,20); +var p2 = new Punt(25); // y zal de waarde 0 krijgen + +// Overnemen +class Punt3D extends Punt { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Constructor van ouder aanroepen (Punt) + } + + // Overschrijven + dist(): number { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules werken ongeveer hetzelfde als namespaces +// met "." kan je submodules defineren +module Geometrie { + export class Vierkant { + constructor(public zijLengte: number = 0) { + } + + oppervlakte() { + return Math.pow(this.zijLengte, 2); + } + } +} + +var s1 = new Geometrie.Vierkant(5); + +// Local alias for referencing a module +import G = Geometrie; + +var s2 = new G.Vierkant(10); + +// Generieken +// Classes +class Tupel { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Paar { + item1: T; + item2: T; +} + +// En functies +var paarNaarTupel = function(p: Paar) { + return new Tupel(p.item1, p.item2); +}; + +var tupel = paarNaarTupel({ item1: "hallo", item2: "wereld" }); + +// Refferentie naar een definitie bestand: +/// + +``` + +## Verder lezen (engels) + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From ac7d33f319dc9a8c9e26f68f558c834aaa3267f1 Mon Sep 17 00:00:00 2001 From: Scott Fisk Date: Wed, 21 Oct 2015 16:12:49 -0500 Subject: Changed wording for comments section Changed wording for overview of comments so it would make more sense to a beginner. Corrected grammar error. --- es-es/javascript-es.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index d475cf42..fdb938a8 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -23,7 +23,9 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js -// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //, +// Los comentarios en JavaScript son los mismos como comentarios en C. + +//Los comentarios de una sola línea comienzan con //, /* y los comentarios multilínea comienzan y terminan con */ -- cgit v1.2.3 From ce85711575d8b481d9de1dc8823a1e8c62211248 Mon Sep 17 00:00:00 2001 From: Arashk-A Date: Thu, 22 Oct 2015 02:16:31 +0330 Subject: Edit some translation behavior in links and codes --- fa-ir/css.html.markdown | 62 ++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown index 7214bb04..661cc5f2 100644 --- a/fa-ir/css.html.markdown +++ b/fa-ir/css.html.markdown @@ -34,6 +34,7 @@ selector { property: value; /* more properties...*/ }

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

+ ```CSS * { color:red; } ``` @@ -45,7 +46,8 @@ selector { property: value; /* more properties...*/ } ```

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

-‍‍```CSS + +```CSS .some-class { } ``` @@ -67,37 +69,37 @@ selector { property: value; /* more properties...*/ } div { } ``` -

یا با استفاده از 'attr'

+

یا با استفاده از `attr`

```CSS [attr] { font-size:smaller; } ``` -

یا با استفاده از ارزشی که برای 'attr' مشخص شده

+

یا با استفاده از ارزشی که برای `attr` مشخص شده

```CSS [attr='value'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'val' شروع میشود در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

```CSS [attr^='val'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'ue' به پایان میرسد در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست 'otherAttr' بوسیله فاصله از هم جدا شده اند در CSS3

+

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا ارزش('value') دقیقاً خود ارزش('value') یا بوسیله '-' که یونیکد (U+002D) از حرف بعدی جدا شود

+

یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

```CSS [otherAttr|='en'] { font-size:smaller; } @@ -110,14 +112,14 @@ div.some-class[attr$='ue'] { } ```

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

-

برای مثال دستور زیر همه عناصری را که نام کلاس آنها '.class-name' و دارای پدر و مادری با این مشخصه 'div.some-parent' هستند را انتخاب میکند.

+

برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

```CSS div.some-parent > .class-name {} ``` -

یا دستور زیر که همه عناصری را که نام کلاس آنها '.class-name' و داخل عنصری با مشخصه 'div.some-parent' هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان 'div.some-parent' باشند) انتخاب میکند.

+

یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

```CSS div.some-parent .class-name {} @@ -129,13 +131,13 @@ div.some-parent .class-name {} div.some-parent.class-name {} ``` -

دستور زیر همه عناصری را که نام کلاس آنها '.this-element' و بلافاصله بعد از عنصری با مشخصه '.i-am-before' قرار دارد را انتخاب میکند.

+

دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

```CSS .i-am-before + .this-element { } ``` -

هر خواهر یا برادری که بعد از '.i-am-before' بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

+

هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

```CSS .i-am-any-before ~ .this-element {} @@ -178,8 +180,8 @@ selector { width: 5cm; /* بر اساس سانتیمتر */ min-width: 50mm; /* بر اساس میلیمتر */ max-width: 5in; /* بر اساس اینچ. max-(width|height) */ - height: 0.2vh; /* بر اساس ارتفاع دید 'vh = نسبت به 1٪ از ارتفاع دید' (CSS3) */ - width: 0.4vw; /* بر اساس عرض دید 'vw = نسبت به 1٪ از عرض دید' (CSS3) */ + height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */ + width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */ min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ @@ -208,13 +210,13 @@ selector {

نحوه استفاده

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

-

حالا با استفاده از کد زیر آنرا در قسمت 'head' داخل فایل html خود تعریف کنید

+

حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید

```html ``` -

یا میتوان با استفاده از تگ 'style' درون 'head' دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

+

یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

```html +``` + +

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

+ +```html +
+
+``` + +

حق تقدم یا اولویت

+ +

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

+

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

+

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

+ +

به مثال زیر توجه کنید:

+ +```CSS +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +

و همچنین به کد زیر:

+ +```html +

+

+ +``` +‍‍ +

حق تقدم یا اولویت برای مثال بالا به این صورت است:

+

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

+ +

E دارای بیشترین الویت برای اینکه از `!important` استفاده کرده.

+

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

+

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

+

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

+

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ `p` + ۱ کلاس با نام `class1` + ۱ خاصیت `attr="value"`

+

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

+

اولویت بعدی با B

+

و در آخر D

+ +

سازگاری

+ +

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

+ +

یک منبع خوب برای این کار است

+[QuirksMode CSS](http://www.quirksmode.org/css/) + +

برای یک تست سازگاری سریع, منبع زیر میتواند کمک بزرگی برای این کار باشد.

+[CanIUse](http://caniuse.com/) + +

منابع دیگر

+ + +[Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) + +[QuirksMode CSS](http://www.quirksmode.org/css/) + +[Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) + + diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown deleted file mode 100644 index 661cc5f2..00000000 --- a/fa-ir/css.html.markdown +++ /dev/null @@ -1,299 +0,0 @@ ---- -language: CSS -translators: - - ["Arashk", "https://github.com/Arashk-A"] -lang: fa-ir ---- - -

در روزهای آغازین وب هیچگونه عنصر بصری مشاهده نمیشد و محتوا به صورت متن خالی بود.

-

اما با توسعه بیشتر مرورگرها صفحات وب کاملاً تصویری نیز رایج شد

-

CSS زبان استانداردی که موجودیت آن برای حفظ جدایی بین محتوا (HTML) و نگاه و احساس از

-

صفحات وب است.

- -

به طور خلاصه, کاری که CSS انجام میدهد ارائه نحوه ایست که شما را قادر به هدف قرار دادن

-

عناصر مختلف در یک صفحه HTML کرده و امکان اختصاص خواص متفاوت بصری به آنها را میدهد.

- - -

مانند هر زبانی, CSS نسخه های زیادی دارد که در اینجا توجه ما روی CSS2.0 است. با وجودی که این نسخه جدیدترین نسخه نمیباشد اما بیشترین پشتیبانی و سازگاری را در میان نسخه های مختلف را دارد

- -

توجه: برای مشاهده برخی از نتایج جلوه های تصویری CSS به منظور یادگیری بیشتر شما باید چیزهای گوناگونی در محیطی مثل [dabblet](http://dabblet.com/) امتحان کنید. توجه اصلی این مقاله روی دستورات و برخی از نکات عمومی است.

- - -

در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد

- -```CSS -/* comments appear inside slash-asterisk, just like this line! - there are no "one-line comments"; this is the only comment style */ -``` - -

به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.

- -```CSS -selector { property: value; /* more properties...*/ } -``` - -

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

- - -```CSS -* { color:red; } -``` - -

فرض کنید عنصری مثل این بر روی صفحه قرار دارد

- -```html -
-``` -

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

- - -```CSS -.some-class { } -``` - -

یا با استفاده از نام دو کلاس

- -```CSS -.some-class.class2 { } -``` - -

یا با استفاده از نام id

- -```CSS -#someId { } -``` - -

یا با استفاده از نام خود عنصر

- -```CSS -div { } -``` - -

یا با استفاده از `attr`

- -```CSS -[attr] { font-size:smaller; } -``` - -

یا با استفاده از ارزشی که برای `attr` مشخص شده

- -```CSS -[attr='value'] { font-size:smaller; } -``` - -

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

- -```CSS -[attr^='val'] { font-size:smaller; } -``` - -

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

- -```CSS -[attr$='ue'] { font-size:smaller; } -``` - -

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

- -```CSS -[attr$='ue'] { font-size:smaller; } -``` - -

یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

- -```CSS -[otherAttr|='en'] { font-size:smaller; } -``` - -

و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند

- -```CSS -div.some-class[attr$='ue'] { } -``` - -

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

-

برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

- -```CSS -div.some-parent > .class-name {} -``` - - -

یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

- -```CSS -div.some-parent .class-name {} -``` - -

نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.

- -```CSS -div.some-parent.class-name {} -``` - -

دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

- -```CSS -.i-am-before + .this-element { } -``` - -

هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

- -```CSS -.i-am-any-before ~ .this-element {} -``` -

در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.

-

برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.

- -```CSS -selector:hover {} -``` - -

یا زمانی از یک لینک بازید کردید.

- -```CSS -selected:visited {} -``` - -

یا زمانی از لینکی بازید نشده است.

- -```CSS -selected:link {} -``` - -

یا زمانی که روی یک عنصر ورودی متمرکز شده.

- -```CSS -selected:focus {} -``` - -

واحدها

- -```CSS -selector { - - /* واحدها اندازه */ - width: 50%; /* در اساس درصد */ - font-size: 2em; /* بر اساس اندازه font-size یعنی دو برابر اندازه فونت فعلی */ - width: 200px; /* بر اساس پیکسل */ - font-size: 20pt; /* بر اساس points (نکات) */ - width: 5cm; /* بر اساس سانتیمتر */ - min-width: 50mm; /* بر اساس میلیمتر */ - max-width: 5in; /* بر اساس اینچ. max-(width|height) */ - height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */ - width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */ - min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ - max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ - - /* رنگها */ - background-color: #F6E; /* بر اساس short hex */ - background-color: #F262E2; /* بر اساس long hex format */ - background-color: tomato; /* بر اساس نام رنگ */ - background-color: rgb(255, 255, 255); /* بر اساس rgb */ - background-color: rgb(10%, 20%, 50%); /* بر اساس درصد rgb , (rgb percent) */ - background-color: rgba(255, 0, 0, 0.3); /* بر اساس rgba (نیمه شفاف) , (semi-transparent rgb) (CSS3) */ - background-color: transparent; /* شفاف */ - background-color: hsl(0, 100%, 50%); /* بر اساس hsl format (CSS3). */ - background-color: hsla(0, 100%, 50%, 0.3); /* بر اساس hsla ,مثل RGBAکه میتوان شفافیت را در آخر انتخاب کرد (CSS3) */ - - - /* عکسها */ - background-image: url(/path-to-image/image.jpg); /* گذاشتن نقل قول داخل url() اختیاری است*/ - - /* فونتها */ - font-family: Arial; - font-family: "Courier New"; /* اگر اسم فونت با فاصله همراه باشد باید داخل نقل قول یک یا دو نوشته شود */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; /* اگر فونت اولی پیدا نشد مرورگر به سراغ نام بعدی میرود */ -} -``` - -

نحوه استفاده

- -

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

-

حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید

- -```html - -``` - -

یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

- -```html - -``` - -

همچنین شما میتوانید دستورات CSS را به عنوان یک مشخصه برای عنصر تعریف کنید ولی تا جای ممکن باید از این کار اجتناب کنید.

- -```html -
-
-``` - -

حق تقدم یا اولویت

- -

همانگونه که مشاهده کردید یک مشخصه می تواند به وسیله چندین انتخابگر انتخاب گردد.

-

و همچنین یک ویژگی میتواند چندین بار برای یک عنصر تعریف شود.

-

در این صورت یک دستور میتواند بر دستورات دیگر حق تقدم یا اولویت پیدا کند.

- -

به مثال زیر توجه کنید:

- -```CSS -/*A*/ -p.class1[attr='value'] - -/*B*/ -p.class1 {} - -/*C*/ -p.class2 {} - -/*D*/ -p {} - -/*E*/ -p { property: value !important; } - -``` - -

و همچنین به کد زیر:

- -```html -

-

- -``` -‍‍ -

حق تقدم یا اولویت برای مثال بالا به این صورت است:

-

توجه داشته باشید که حق تقدم برای هر کدام از ویژگیها است نه برای کل مجموعه.

- -

E دارای بیشترین الویت برای اینکه از `!important` استفاده کرده.

-

اما توصیه میشود تا جای ممکن از این کار اجتناب کنید مگر اینکه اینکار ضرورت داشته باشد

-

اولویت بعدی با F است زیرا که از روش درون برنامه ای استفاده کرده

-

اولویت بعدی با A است زیرا که بیشتر از بقیه مشخص تر تعریف شپه

-

مشخص تر = مشخص کننده بیشتر. دارای ۳ مشخص کننده: ۱ تگ `p` + ۱ کلاس با نام `class1` + ۱ خاصیت `attr="value"`

-

اولویت بعدی با C است که مشخصه یکسانی با B دارد ولی بعد از آن تعریف شده است.

-

اولویت بعدی با B

-

و در آخر D

- -

سازگاری

- -

بسیار از ویژگیهای CSS2 (و به تدریج CSS3) بر روی تمام مرورگرها و دستگاه ها سازگارند.اما همیشه حیاتی است که سازگاری CSS مورد استفاده خود را با مرورگر هدف چک کنید.

- -

یک منبع خوب برای این کار است

-[QuirksMode CSS](http://www.quirksmode.org/css/) - -

برای یک تست سازگاری سریع, منبع زیر میتواند کمک بزرگی برای این کار باشد.

-[CanIUse](http://caniuse.com/) - -

منابع دیگر

- - -[Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) - -[QuirksMode CSS](http://www.quirksmode.org/css/) - -[Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) - - -- cgit v1.2.3 From 1bec0f608977c00757c8f5732eedce2e57bb9bc3 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sun, 13 Mar 2016 10:10:06 +0000 Subject: created kotlin markdown --- kotlin.html.markdown | 321 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 kotlin.html.markdown diff --git a/kotlin.html.markdown b/kotlin.html.markdown new file mode 100644 index 00000000..ae0123a7 --- /dev/null +++ b/kotlin.html.markdown @@ -0,0 +1,321 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +filename: LearnKotlin.kt +--- + +Kotlin is a Statically typed programming language for the JVM, Android and the +browser. It is 100% interoperable with Java. +[Read more here.](https://kotlinlang.org/) + +```kotlin +// Single-line comments start with // +/* +Multi-line comments look like this. +*/ + +// The "package" keyword works in the same way as in Java. +package com.learnxinyminutes.kotlin + +/* +The entry point to a Kotlin program is a function named "main". +The function is passed an array containing any command line arguments. +*/ +fun main(args: Array) { + /* + Declaring values is done using either "var" or "val". + "val" declarations cannot be reassigned, whereas "vars" can. + */ + val fooVal = 10 // we cannot later reassign fooVal to something else + var fooVar = 10 + fooVar = 20 // fooVar can be reassigned + + /* + In most cases, Kotlin can determine what the type of a variable is, + so we don't have to explicitly specify it every time. + We can explicitly declare the type of a variable like so: + */ + val foo : Int = 7 + + /* + Strings can be represented in a similar way as in Java. + Escaping is done with a backslash. + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + A raw string is delimited by a triple quote ("""). + Raw strings can contain newlines and any other characters. + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + Strings can contain template expressions. + A template expression starts with a dollar sign ($). + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + For a variable to hold null it must be explicitly specified as nullable. + A variable can be specified as nullable by appending a ? to its type. + We can access a nullable variable by using the ?. operator. + We can use the ?: operator to specify an alternative value to use + if a variable is null + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + Functions can be declared using the "fun" keyword. + Function arguments are specified in brackets after the function name. + Function arguments can optionally have a default value. + The function return type, if required, is specified after the arguments. + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + A function parameter may be marked with the "vararg" keyword + to allow a variable number of arguments to be passed to the function. + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + When a function consists of a single expression then the curly brackets can + be omitted. The body is specified after a = symbol. + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // If the return type can be inferred then we don't need to specify it. + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // Functions can take functions as arguments and return functions. + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // Named functions can be specified as arguments using the :: operator. + val notOdd = not(::odd) + val notEven = not(::even) + // Anonymous functions can be specified as arguments. + val notZero = not {n -> n == 0} + /* + If an anonymous function has only one parameter + then its declaration can be omitted (along with the ->). + The name of the single parameter will be "it". + */ + val notPositive = not {it > 0} + for (i in (0..4)) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + //The "class" keyword is used to declare classes. + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + To create a new instance we call the constructor. + Note that Kotlin does not have a "new" keyword. + */ + val fooExampleClass = ExampleClass(7) + // Member functions can be called using dot notation. + println(fooExampleClass.memberFunction(4)) // => 11 + /* + If a function has been marked with the "infix" keyword then it can be + called using infix notation. + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + Data classes are a concise way to create classes that just hold data. + The "hashCode"/"equals" and "toString" methods are automatically generated. + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // Data classes have a "copy" function. + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // Objects can be destructured into multiple variables. + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // The "with" function is similar to the JavaScript "with" statement. + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + We can create a list using the "listOf" function. + The list will be immutable - elements cannot be added or removed. + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // elements can be accessed by index + println(fooList[1]) // => b + + // A mutable list can be created using the "mutableListOf" function. + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // We can create a set using the "setOf" function. + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // We can create a map using the "mapOf" function. + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // Map values can be accessed by their key. + println(fooMap["a"]) // => 8 + + // Kotlin provides higher-order functions for working with collections. + val x = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // A "for" loop can be used with anything that provides an iterator. + for (c in "hello") { + println(c) + } + + // "while" loops work in the same way as other languages. + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when" can be used as an alternative to "if-else if" chains. + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when" can be used with an argument. + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when" can be used as a function that returns a value. + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + We can check if an object is a particular type by using the "is" operator. + If an object passes a type check then it can be used as that type without + explicitly casting it. + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x is automatically cast to Boolean + return x + } else if (x is Int) { + // x is automatically cast to Int + return x > 0 + } else if (x is String) { + // x is automatically cast to String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + Extensions are a way to add new functionality to a class. + This is similar to C# extension methods. + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// Enum classes are similar to Java enum types. +enum class EnumExample { + A, B, C +} + +/* +The "object" keyword can be used to create singleton objects. +We cannot assign it to a variable, but we can refer to it by its name. +This is similar to Scala singleton objects. +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### Further Reading + +A web-based mini-IDE for Kotlin: +[http://try.kotlinlang.org/) -- cgit v1.2.3 From 03da44dd0b5ef9e351adf5881c25d1d25803c496 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 14 Mar 2016 10:26:18 -0600 Subject: [forth/en] don't -> don't --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index b4a5581b..55d755b2 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -54,7 +54,7 @@ Forth, but most of what is written here should work elsewhere. 3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3 2 5 swap / \ swap the top with the second element: 5 / 2 6 4 5 rot .s \ rotate the top 3 elements: 4 5 6 -4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2 +4 0 drop 2 / \ remove the top item (don't print to screen): 4 / 2 1 2 3 nip .s \ remove the second item (similar to drop): 1 3 \ ---------------------- More Advanced Stack Manipulation ---------------------- -- cgit v1.2.3