diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown index a516737e..a23ef1c8 100644 --- a/asymptotic-notation.html.markdown +++ b/asymptotic-notation.html.markdown @@ -3,41 +3,52 @@ category: Algorithms & Data Structures name: Asymptotic Notation contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Divay Prakash", "http://github.com/divayprakash"] --- # Asymptotic Notations ## What are they? -Asymptotic Notations are languages that allow us to analyze an algorithm's running time by -identifying its behavior as the input size for the algorithm increases. This is also known as -an algorithm's growth rate. Does the algorithm suddenly become incredibly slow when the input -size grows? Does it mostly maintain its quick run time as the input size increases? -Asymptotic Notation gives us the ability to answer these questions. +Asymptotic Notations are languages that allow us to analyze an algorithm's +running time by identifying its behavior as the input size for the algorithm +increases. This is also known as an algorithm's growth rate. Does the +algorithm suddenly become incredibly slow when the input size grows? Does it +mostly maintain its quick run time as the input size increases? Asymptotic +Notation gives us the ability to answer these questions. ## Are there alternatives to answering these questions? -One way would be to count the number of primitive operations at different input sizes. -Though this is a valid solution, the amount of work this takes for even simple algorithms -does not justify its use. +One way would be to count the number of primitive operations at different +input sizes. Though this is a valid solution, the amount of work this takes +for even simple algorithms does not justify its use. -Another way is to physically measure the amount of time an algorithm takes to complete -given different input sizes. However, the accuracy and relativity (times obtained would -only be relative to the machine they were computed on) of this method is bound to -environmental variables such as computer hardware specifications, processing power, etc. +Another way is to physically measure the amount of time an algorithm takes to +complete given different input sizes. However, the accuracy and relativity +(times obtained would only be relative to the machine they were computed on) +of this method is bound to environmental variables such as computer hardware +specifications, processing power, etc. ## Types of Asymptotic Notation -In the first section of this doc we described how an Asymptotic Notation identifies the -behavior of an algorithm as the input size changes. Let us imagine an algorithm as a function -f, n as the input size, and f(n) being the running time. So for a given algorithm f, with input -size n you get some resultant run time f(n). This results in a graph where the Y axis is the -runtime, X axis is the input size, and plot points are the resultants of the amount of time -for a given input size. +In the first section of this doc we described how an Asymptotic Notation +identifies the behavior of an algorithm as the input size changes. Let us +imagine an algorithm as a function f, n as the input size, and f(n) being +the running time. So for a given algorithm f, with input size n you get +some resultant run time f(n). This results in a graph where the Y axis is the +runtime, X axis is the input size, and plot points are the resultants of the +amount of time for a given input size. -You can label a function, or algorithm, with an Asymptotic Notation in many different ways. -Some examples are, you can describe an algorithm by its best case, worse case, or equivalent case. -The most common is to analyze an algorithm by its worst case. You typically don't evaluate by best case because those conditions aren't what you're planning for. A very good example of this is sorting algorithms; specifically, adding elements to a tree structure. Best case for most algorithms could be as low as a single operation. However, in most cases, the element you're adding will need to be sorted appropriately through the tree, which could mean examining an entire branch. This is the worst case, and this is what we plan for. +You can label a function, or algorithm, with an Asymptotic Notation in many +different ways. Some examples are, you can describe an algorithm by its best +case, worse case, or equivalent case. The most common is to analyze an +algorithm by its worst case. You typically don't evaluate by best case because +those conditions aren't what you're planning for. A very good example of this +is sorting algorithms; specifically, adding elements to a tree structure. Best +case for most algorithms could be as low as a single operation. However, in +most cases, the element you're adding will need to be sorted appropriately +through the tree, which could mean examining an entire branch. This is the +worst case, and this is what we plan for. ### Types of functions, limits, and simplification @@ -45,16 +56,25 @@ The most common is to analyze an algorithm by its worst case. You typically don' Logarithmic Function - log n Linear Function - an + b Quadratic Function - an^2 + bn + c -Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some constant +Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some +constant Exponential Function - a^n, where a is some constant ``` -These are some basic function growth classifications used in various notations. The list starts at the slowest growing function (logarithmic, fastest execution time) and goes on to the fastest growing (exponential, slowest execution time). Notice that as 'n', or the input, increases in each of those functions, the result clearly increases much quicker in quadratic, polynomial, and exponential, compared to logarithmic and linear. +These are some basic function growth classifications used in various +notations. The list starts at the slowest growing function (logarithmic, +fastest execution time) and goes on to the fastest growing (exponential, +slowest execution time). Notice that as 'n', or the input, increases in each +of those functions, the result clearly increases much quicker in quadratic, +polynomial, and exponential, compared to logarithmic and linear. -One extremely important note is that for the notations about to be discussed you should do your best to use simplest terms. This means to disregard constants, and lower order terms, because as the input size (or n in our f(n) -example) increases to infinity (mathematical limits), the lower order terms and constants are of little -to no importance. That being said, if you have constants that are 2^9001, or some other ridiculous, -unimaginable amount, realize that simplifying will skew your notation accuracy. +One extremely important note is that for the notations about to be discussed +you should do your best to use simplest terms. This means to disregard +constants, and lower order terms, because as the input size (or n in our f(n) +example) increases to infinity (mathematical limits), the lower order terms +and constants are of little to no importance. That being said, if you have +constants that are 2^9001, or some other ridiculous, unimaginable amount, +realize that simplifying will skew your notation accuracy. Since we want simplest form, lets modify our table a bit... @@ -67,10 +87,13 @@ Exponential - a^n, where a is some constant ``` ### Big-O -Big-O, commonly written as O, is an Asymptotic Notation for the worst case, or ceiling of growth -for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity -you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0), -`f(n)` <= `c g(n)` for every input size n (n > 0). +Big-O, commonly written as **O**, is an Asymptotic Notation for the worst +case, or ceiling of growth for a given function. It provides us with an +_**asymptotic upper bound**_ for the growth rate of runtime of an algorithm. +Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time +complexity you are trying to relate to your algorithm. `f(n)` is O(g(n)), if +for some real constant c (c > 0), `f(n)` <= `c g(n)` for every input size +n (n > 0). *Example 1* @@ -114,19 +137,62 @@ Is there some constant c that satisfies this for all n? No, there isn't. `f(n)` is NOT O(g(n)). ### Big-Omega -Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate -for a given function. +Big-Omega, commonly written as **Ω**, is an Asymptotic Notation for the best +case, or a floor growth rate for a given function. It provides us with an +_**asymptotic lower bound**_ for the growth rate of runtime of an algorithm. -`f(n)` is Ω(g(n)), if for any real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0). +`f(n)` is Ω(g(n)), if for some real constant c (c > 0), `f(n)` is >= `c g(n)` +for every input size n (n > 0). -Feel free to head over to additional resources for examples on this. Big-O is the primary notation used -for general algorithm time complexity. +### Note + +The asymptotic growth rates provided by big-O and big-omega notation may or +may not be asymptotically tight. Thus we use small-o and small-omega notation +to denote bounds that are not asymptotically tight. + +### Small-o +Small-o, commonly written as **o**, is an Asymptotic Notation to denote the +upper bound (that is not asymptotically tight) on the growth rate of runtime +of an algorithm. + +`f(n)` is o(g(n)), if for any real constant c (c > 0), `f(n)` is < `c g(n)` +for every input size n (n > 0). + +The definitions of O-notation and o-notation are similar. The main difference +is that in f(n) = O(g(n)), the bound f(n) <= g(n) holds for _**some**_ +constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for +_**all**_ constants c > 0. + +### Small-omega +Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote +the lower bound (that is not asymptotically tight) on the growth rate of +runtime of an algorithm. + +`f(n)` is ω(g(n)), if for any real constant c (c > 0), `f(n)` is > `c g(n)` +for every input size n (n > 0). + +The definitions of Ω-notation and ω-notation are similar. The main difference +is that in f(n) = Ω(g(n)), the bound f(n) >= g(n) holds for _**some**_ +constant c > 0, but in f(n) = ω(g(n)), the bound f(n) > c g(n) holds for +_**all**_ constants c > 0. + +### Theta +Theta, commonly written as **Θ**, is an Asymptotic Notation to denote the +_**asymptotically tight bound**_ on the growth rate of runtime of an algorithm. + +`f(n)` is Θ(g(n)), if for some real constants c1, c2 (c1 > 0, c2 > 0), +`c1 g(n)` is < `f(n)` is < `c2 g(n)` for every input size n (n > 0). + +∴ `f(n)` is Θ(g(n)) implies `f(n)` is O(g(n)) as well as `f(n)` is Ω(g(n)). + +Feel free to head over to additional resources for examples on this. Big-O +is the primary notation use for general algorithm time complexity. ### Ending Notes -It's hard to keep this kind of topic short, and you should definitely go through the books and online -resources listed. They go into much greater depth with definitions and examples. -More where x='Algorithms & Data Structures' is on its way; we'll have a doc up on analyzing actual -code examples soon. +It's hard to keep this kind of topic short, and you should definitely go +through the books and online resources listed. They go into much greater depth +with definitions and examples. More where x='Algorithms & Data Structures' is +on its way; we'll have a doc up on analyzing actual code examples soon. ## Books @@ -137,3 +203,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. diff --git a/bash.html.markdown b/bash.html.markdown index bd2d5984..f3c9cccc 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": diff --git a/c.html.markdown b/c.html.markdown index d4ff529d..7c9dd590 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -36,7 +36,6 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // MON gets 2 automatically, TUE gets 3, etc. - // Import headers with #include #include #include @@ -114,7 +113,6 @@ int main (int argc, char** argv) // sizeof(obj) yields the size of the expression (variable, literal, etc.). printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - // If the argument of the `sizeof` operator is an expression, then its argument // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. @@ -130,7 +128,6 @@ int main (int argc, char** argv) int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes // (assuming 4-byte words) - // You can initialize an array to 0 thusly: char my_array[20] = {0}; @@ -347,7 +344,6 @@ int main (int argc, char** argv) this will print out "Error occured at i = 52 & j = 99." */ - /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -386,7 +382,6 @@ int main (int argc, char** argv) // (%p formats an object pointer of type void *) // => Prints some address in memory; - // Pointers start with * in their declaration int *px, not_a_pointer; // px is a pointer to an int px = &x; // Stores the address of x in px @@ -432,7 +427,6 @@ int main (int argc, char** argv) printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8" - // Pointers are incremented and decremented based on their type // (this is called pointer arithmetic) printf("%d\n", *(x_ptr + 1)); // => Prints 19 @@ -578,8 +572,6 @@ void testFunc2() { } //**You may also declare functions as static to make them private** - - /////////////////////////////////////// // User-defined types and structs /////////////////////////////////////// @@ -696,6 +688,7 @@ typedef void (*my_fnp_type)(char *); "%o"; // octal "%%"; // prints % */ + /////////////////////////////////////// // Order of Evaluation /////////////////////////////////////// @@ -786,4 +779,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Other than that, Google is your friend. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file diff --git a/chapel.html.markdown b/chapel.html.markdown index 866e92d2..9c1daf40 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1066,7 +1066,7 @@ The more information you give the Chapel development team about issues you encou Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). If you're really interested in the development of the compiler or contributing to the project, -[check out the master Github repository](https://github.com/chapel-lang/chapel). +[check out the master GitHub repository](https://github.com/chapel-lang/chapel). It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). Installing the Compiler diff --git a/cs-cz/brainfuck.html.markdown b/cs-cz/brainfuck.html.markdown new file mode 100644 index 00000000..29abc21f --- /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-cz.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 :) diff --git a/cs-cz/json.html.markdown b/cs-cz/json.html.markdown new file mode 100644 index 00000000..5972da5e --- /dev/null +++ b/cs-cz/json.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] +filename: learnjson-cz.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!" +} +``` diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 0d44bc12..568e4343 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -53,7 +53,7 @@ __Stejně jako tento.__ **_Jako tento!_** *__A tento!__* - + ~~Tento text je prošktrnutý.~~ @@ -152,7 +152,7 @@ Tento box bude zašktrnutý Jan nevědel, jak se dělá `go_to()` funkce! - + \`\`\`ruby def neco @@ -160,7 +160,7 @@ def neco end \`\`\` - @@ -232,13 +232,13 @@ Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a j Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*. - + Váš počítač přestal pracovat? Zkuste Ctrl+Alt+Del - | Sloupec1 | Sloupec2 | Sloupec3 | diff --git a/csharp.html.markdown b/csharp.html.markdown index 7d7f4340..197f43e7 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -24,10 +24,12 @@ 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 +// The namespaces below are all part of the standard .NET Framework Class Library using System; using System.Collections.Generic; using System.Dynamic; @@ -421,7 +423,7 @@ on a new line! ""Wow!"", the masses cried"; // Item is an int Console.WriteLine(item.ToString()); } - + // YIELD // Usage of the "yield" keyword indicates that the method it appears in is an Iterator // (this means you can use it in a foreach loop) @@ -437,7 +439,7 @@ on a new line! ""Wow!"", the masses cried"; foreach (var counter in YieldCounter()) Console.WriteLine(counter); } - + // you can use more than one "yield return" in a method public static IEnumerable ManyYieldCounter() { @@ -446,7 +448,7 @@ on a new line! ""Wow!"", the masses cried"; yield return 2; yield return 3; } - + // you can also use "yield break" to stop the Iterator // this method would only return half of the values from 0 to limit. public static IEnumerable YieldCounterWithBreak(int limit = 10) @@ -482,7 +484,7 @@ on a new line! ""Wow!"", the masses cried"; // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 - + // ?. is an operator for null-propagation - a shorthand way of checking for null nullable?.Print(); // Use the Print() extension method if nullable isn't null @@ -913,17 +915,17 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } - + // Classes can be split across multiple .cs files // A1.cs - public partial class A + public partial class A { public static void A1() { Console.WriteLine("Method A1 in class A"); } } - + // A2.cs public partial class A { @@ -932,9 +934,9 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("Method A2 in class A"); } } - + // Program using the partial class "A" - public class Program + public class Program { static void Main() { diff --git a/css.html.markdown b/css.html.markdown index 8ee4f4b9..4ec95f8b 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - ["Tyler Mumford", "https://tylermumford.com"] + filename: learncss.css --- @@ -195,7 +196,7 @@ Save a CSS stylesheet with the extension `.css`. ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one (which also means that if two different linked stylesheets contain rules for an element and if the rules are of the same specificity, then order of linking would take precedence and the sheet linked latest would govern styling) . This process is called cascading, hence the name Cascading Style Sheets. diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 541d28bb..654fcdd4 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -92,12 +92,12 @@ echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschl echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat" # Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern: -if [ $NAME == "Steve" ] && [ $Alter -eq 15 ] +if [ "$NAME" == "Steve" ] && [ "$Alter" -eq 15 ] then echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15." fi -if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ] then echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'." fi diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index dea329d5..61f7bb67 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -33,6 +33,7 @@ Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichn * Ist offline einsetzbar. * Einfache Kollaboration! * Branching ist einfach! +* Branching ist schnell! * Merging ist einfach! * Git ist schnell. * Git ist flexibel. @@ -53,11 +54,11 @@ Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und meh ### Arbeitsverzeichnis (Teil des Repositorys) -Dies sind die Verzeichnisse und Dateien in deinem Repository. +Dies sind die Verzeichnisse und Dateien in deinem Repository, also z.B. dein Programmcode. ### Index (Teil des .git-Verzeichnisses) -Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht. +Der Index ist die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht. ### Commit @@ -84,7 +85,7 @@ Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Reposito ### init -Erstelle ein leeres Git-Repository. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt. +Erstelle ein leeres Git-Repository im aktuellen Verzeichnis. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt. ```bash $ git init @@ -180,6 +181,8 @@ Bringt alle Dateien im Arbeitsverzeichnis auf den Stand des Index oder des angeg ```bash # Ein Repo auschecken - wenn nicht anders angegeben ist das der master $ git checkout +# Eine Datei auschecken - sie befindet sich dann auf dem aktuellen Stand im Repository +$ git checkout /path/to/file # Einen bestimmten Branch auschecken $ git checkout branchName # Erstelle einen neuen Branch und wechsle zu ihm. Wie: "git branch ; git checkout " @@ -217,6 +220,9 @@ $ git diff --cached # Unterschiede zwischen deinem Arbeitsverzeichnis und dem aktuellsten Commit anzeigen $ git diff HEAD + +# Unterschiede zwischen dem Index und dem aktuellsten Commit (betrifft nur Dateien im Index) +$ git diff --staged ``` ### grep @@ -374,3 +380,5 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) + +* [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 94f48e65..dca88f01 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -4,6 +4,7 @@ filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] - ["Dennis Keller", "https://github.com/denniskeller"] +translators: - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de --- diff --git a/de-de/hack-de.html.markdown b/de-de/hack-de.html.markdown new file mode 100644 index 00000000..42428130 --- /dev/null +++ b/de-de/hack-de.html.markdown @@ -0,0 +1,322 @@ +--- +language: Hack +lang: de-de +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +translators: + - ["Jerome Meinke", "https://github.com/jmeinke"] +filename: learnhack-de.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. diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown new file mode 100644 index 00000000..7272b365 --- /dev/null +++ b/de-de/haml-de.html.markdown @@ -0,0 +1,156 @@ +--- +language: haml +filename: learnhaml-de.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Sol Bekic", "https://github.com/S0lll0s"] +lang: de-de +--- + +Haml ist eine Markup- und Templatingsprache, aufgesetzt auf Ruby, mit der HTML Dokumente einfach beschrieben werden können. + +Haml vermindert Wiederholung und Fehleranfälligkeit, indem es Tags basierend auf der Markup-Struktur schließt und schachtelt. +Dadurch ergibt sich kurzes, präzises und logisches Markup. + +Haml kann außerhalb eines Ruby-projekts verwendet werden. Mit dem installierten Haml gem kann man das Terminal benutzen um Haml zu HTML umzuwandeln: + +$ haml input_file.haml output_file.html + + +```haml +/ ------------------------------------------- +/ Einrückung +/ ------------------------------------------- + +/ + Einrückung ist ein wichtiges Element des Haml Syntax, deswegen ist es + wichtig ein konsequentes Schema zu verwenden. Meistens werden zwei spaces + verwendet, solange die Einrückungen das gleiche Schema verfolgen können + aber auch andere Breiten und Tabs verwendet werden + + +/ ------------------------------------------- +/ Kommentare +/ ------------------------------------------- + +/ Kommentare beginnen mit einem Slash + +/ + Mehrzeilige Kommentare werden eingerückt und mit einem Slash + eingeführt + +-# Diese Zeile ist ein "stummes" Kommentar, es wird nicht mitgerendert + + +/ ------------------------------------------- +/ HTML Elemente +/ ------------------------------------------- + +/ Tags werden durch ein Prozentzeichen und den Tagnamen erzeugt +%body + %header + %nav + +/ Die Zeilen oben würden folgendes ergeben: + +
+ +
+ + +/ Text kann direkt nach dem Tagnamen eingefügt werden: +%h1 Headline copy + +/ Mehrzeilige Inhalte müssen stattdessen eingerückt werden: +%p + This is a lot of content that we could probably split onto two + separate lines. + +/ + HTML kann mit &= escaped werden. So werden HTML-sensitive Zeichen + enkodiert. Zum Beispiel: + +%p + &= "Ja & Nein" + +/ würde 'Ja & Nein' ergeben + +/ HTML kann mit != dekodiert werden: +%p + != "so schreibt man ein Paragraph-Tag:

" + +/ ...was 'This is how you write a paragraph tag

' ergeben würde + +/ CSS Klassen können mit '.classname' an Tags angehängt werden: +%div.foo.bar + +/ oder über einen Ruby Hash: +%div{:class => 'foo bar'} + +/ Das div Tag wird standardmäßig verwendet, divs können also verkürzt werden: +.foo + +/ andere Attribute können über den Hash angegeben werden: +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ Booleesche Attribute können mit 'true' gesetzt werden: +%input{:selected => true} + +/ data-Attribute können in einem eigenen Hash im :data key angegeben werden: +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Verwendung von Ruby +/ ------------------------------------------- + +/ Mit dem = Zeichen können Ruby-werte evaluiert und als Tag-text verwendet werden: + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ Code nach einem Bindestrich wird ausgeführt aber nicht gerendert: +- books = ['book 1', 'book 2', 'book 3'] + +/ So können zum Beispiel auch Blöcke verwendet werden: +- books.shuffle.each_with_index do |book, index| + %h1= book + + if book do + %p This is a book + +/ + Auch hier werden wieder keine End-Tags benötigt! + Diese ergeben sich aus der Einrückung. + + +/ ------------------------------------------- +/ Inline Ruby / Ruby Interpolation +/ ------------------------------------------- + +/ Ruby variablen können mit #{} in Text interpoliert werden: +%p dein bestes Spiel ist #{best_game} + + +/ ------------------------------------------- +/ Filter +/ ------------------------------------------- + +/ + Mit dem Doppelpinkt können Haml Filter benutzt werden. + Zum Beispiel gibt es den :javascript Filter, mit dem inline JS + geschrieben werden kann: + +:javascript + console.log('Dies ist ein + + +``` + +### 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) diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown index c89fb622..2e299d09 100644 --- a/pt-br/asymptotic-notation-pt.html.markdown +++ b/pt-br/asymptotic-notation-pt.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - ["João Farias", "https://github.com/JoaoGFarias"] +lang: pt-br --- # Notação Assintótica 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 +``` diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown new file mode 100644 index 00000000..547f4817 --- /dev/null +++ b/pt-br/csharp.html.markdown @@ -0,0 +1,896 @@ +--- +language: c# +filename: csharp-pt.cs +contributors: + - ["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. + +[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; + + /////////////////////////////////////////////////// + // Estrutura de Dados + /////////////////////////////////////////////////// + + // 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]; + + // Outra forma de declarar & inicializar uma matriz + int[] y = { 9000, 1000, 1337 }; + + // Indexando uma matriz - Acessando um elemento + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Matriz são alteráveis + intArray[1] = 1; + + // 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 }; // inicializar + // O <> são para genéricos - Confira está interessante seção do material + + // 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]); + + // Outras estruturas de dados para conferir: + // Pilha/Fila + // Dicionário (uma implementação de map de hash) + // HashSet + // Read-only Coleção + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis + + // Aritmética é clara + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // 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 + + // Operadores bit a bit (bitwise) + /* + ~ Unário bitwise complemento + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusivo OR + | Bitwise inclusivo OR + */ + + // Incrementações + 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 + + /////////////////////////////////////// + // Estrutura de Controle + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // Declaração if é como a linguagem C + 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"); + } + + // Operador Ternário + // Um simples if/else pode ser escrito da seguinte forma + // ? : + 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 + { + // Inicia a interação 100 vezes, fooDoWhile 0->99 + if (false) + continue; // pule a intereção atual para apróxima + + fooDoWhile++; + + if (fooDoWhile == 50) + break; // Interrompe o laço inteiro + + } while (fooDoWhile < 100); + + //estrutura de loop for => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterado 10 vezes, fooFor 0->9 + } + + // For Each Loop + // Estrutura do foreach => foreach( in ) + // 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 + // 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) + { + 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) 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 diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown index 4230579d..5fa4df75 100644 --- a/pt-br/hy-pt.html.markdown +++ b/pt-br/hy-pt.html.markdown @@ -171,6 +171,6 @@ Este tutorial é apenas uma introdução básica para hy/lisp/python. Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org) -Repo Hy no Github: [http://github.com/hylang/hy](http://github.com/hylang/hy) +Repo Hy no GitHub: [http://github.com/hylang/hy](http://github.com/hylang/hy) Acesso ao freenode irc com #hy, hashtag no twitter: #hylang diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 3c9512aa..db087a5f 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -214,42 +214,42 @@ public class LearnJava { //Iteração feita 10 vezes, fooFor 0->9 } System.out.println("Valor do fooFor: " + fooFor); - - // O Loop For Each + + // O Loop For Each // Itera automaticamente por um array ou lista de objetos. int[] fooList = {1,2,3,4,5,6,7,8,9}; //estrutura do loop for each => for( : ) //lê-se: para cada objeto no array //nota: o tipo do objeto deve ser o mesmo do array. - + for( int bar : fooList ){ //System.out.println(bar); //Itera 9 vezes e imprime 1-9 em novas linhas } - + // Switch // Um switch funciona com os tipos de dados: byte, short, char e int // Ele também funciona com tipos enumerados (vistos em tipos Enum) // como também a classe String e algumas outras classes especiais // tipos primitivos: Character, Byte, Short e Integer - int mes = 3; - String mesString; - switch (mes){ + int mes = 3; + String mesString; + switch (mes){ case 1: - mesString = "Janeiro"; + mesString = "Janeiro"; break; case 2: - mesString = "Fevereiro"; + mesString = "Fevereiro"; break; case 3: - mesString = "Março"; + mesString = "Março"; break; default: - mesString = "Algum outro mês"; + mesString = "Algum outro mês"; break; } System.out.println("Resultado do Switch: " + mesString); - + // Condição de forma abreviada. // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas. // Lê-se "Se (declaração) é verdadeira, use @@ -287,9 +287,9 @@ public class LearnJava { // Classes e Métodos /////////////////////////////////////// - System.out.println("\n->Classes e Métodos"); + System.out.println("\n->Classes e Métodos"); - // (segue a definição da classe Bicicleta) + // (segue a definição da classe Bicicleta) // Use o new para instanciar uma classe Bicicleta caloi = new Bicicleta(); // Objeto caloi criado. @@ -318,9 +318,9 @@ class Bicicleta { // Atributos/Variáveis da classe Bicicleta. public int ritmo; // Public: Pode ser acessada em qualquer lugar. - private int velocidade; // Private: Apenas acessível a classe. + private int velocidade; // Private: Apenas acessível a classe. protected int catraca; // Protected: Acessível a classe e suas subclasses. - String nome; // default: Apenas acessível ao pacote. + String nome; // default: Apenas acessível ao pacote. // Construtores são uma forma de criação de classes // Este é o construtor padrão. @@ -388,7 +388,7 @@ class Bicicleta { // Velocipede é uma subclasse de bicicleta. class Velocipede extends Bicicleta { // (Velocípedes são bicicletas com rodas dianteiras grandes - // Elas não possuem catraca.) + // Elas não possuem catraca.) public Velocipede(int ritmoInicial, int velocidadeInicial){ // Chame o construtor do pai (construtor de Bicicleta) com o comando super. @@ -626,11 +626,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u Outros tópicos para pesquisar: -* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) +* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) * [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): +* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) @@ -646,3 +646,9 @@ Outros tópicos para pesquisar: Livros: * [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) + +Apostila: + +* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) + +* [Java para Desenvolvimento Web] (https://www.caelum.com.br/apostila-java-web/) diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown index 4030ce3c..f22093f9 100644 --- a/pt-br/markdown-pt.html.markdown +++ b/pt-br/markdown-pt.html.markdown @@ -56,7 +56,7 @@ __E este também está._ *--Danouse! Este também__* +GitHub, nós também temos: --> ~~Este texto é processado com tachado.~~ @@ -148,7 +148,7 @@ dentro do seu código --> John não sabia nem o que o função 'goto()' fazia! - + \`\`\`ruby @@ -157,7 +157,7 @@ def foobar end \`\`\` -<-- O texto acima não requer recuo, mas o Github vai usar a sintaxe +<-- O texto acima não requer recuo, mas o GitHub vai usar a sintaxe destacando do idioma que você especificar após a ``` --> @@ -230,7 +230,7 @@ Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*. - | Col1 | Col2 | Col3 | diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown new file mode 100644 index 00000000..464a69d2 --- /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 conter 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. +``` diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown new file mode 100644 index 00000000..da4f6f37 --- /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, 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 + 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. 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. + +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 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. + +## 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. diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown new file mode 100644 index 00000000..341ae675 --- /dev/null +++ b/pt-br/yaml-pt.html.markdown @@ -0,0 +1,142 @@ +--- +language: 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 +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: nulo + item2: nulo + item3: nulo +``` diff --git a/purescript.html.markdown b/purescript.html.markdown index 6d8cfbb9..b413a9e3 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -48,7 +48,7 @@ not true -- false 23 == 23 -- true 1 /= 4 -- true 1 >= 4 -- false --- Comparisions < <= > >= +-- Comparisons < <= > >= -- are defined in terms of compare compare 1 2 -- LT compare 2 2 -- EQ @@ -62,7 +62,7 @@ true && (9 >= 19 || 1 < 2) -- true "Hellow\ \orld" -- "Helloworld" -- Multiline string with newlines -"""Hello +"""Hello world""" -- "Hello\nworld" -- Concatenate "such " ++ "amaze" -- "such amaze" @@ -197,7 +197,7 @@ let even x = x `mod` 2 == 0 filter even (1..10) -- [2,4,6,8,10] map (\x -> x + 11) (1..5) -- [12,13,14,15,16] --- Requires purescript-foldable-traversabe (Data.Foldable) +-- Requires purescript-foldable-traversable (Data.Foldable) foldr (+) 0 (1..10) -- 55 sum (1..10) -- 55 @@ -208,4 +208,3 @@ any even [1,2,3] -- true all even [1,2,3] -- false ``` - diff --git a/python.html.markdown b/python.html.markdown index 2e7fd8be..12be4be1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -657,6 +657,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 diff --git a/python3.html.markdown b/python3.html.markdown index d88ccec1..ea29fdba 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -716,6 +716,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 diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index f8d83b98..0b02dca8 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -150,9 +150,8 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" r = requests.get(url) fp = "hre.csv" -f = open(fp, "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open(fp, "wb") as f: + f.write(r.text.encode("UTF-8")) hre = pd.read_csv(fp) diff --git a/r.html.markdown~ b/r.html.markdown~ new file mode 100644 index 00000000..ee9e7c90 --- /dev/null +++ b/r.html.markdown~ @@ -0,0 +1,807 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] +<<<<<<< HEAD +======= + - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] +>>>>>>> 6e38442b857a9d8178b6ce6713b96c52bf4426eb +filename: learnr.r +--- + +R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document. + +```r + +# Comments start with number symbols. + +# You can't make multi-line comments, +# but you can stack multiple comments like so. + +# in Windows you can use CTRL-ENTER to execute a line. +# on Mac it is COMMAND-ENTER + + + +############################################################################# +# Stuff you can do without understanding anything about programming +############################################################################# + +# In this section, we show off some of the cool stuff you can do in +# R without understanding anything about programming. Do not worry +# about understanding everything the code does. Just enjoy! + +data() # browse pre-loaded data sets +data(rivers) # get this one: "Lengths of Major North American Rivers" +ls() # notice that "rivers" now appears in the workspace +head(rivers) # peek at the data set +# 735 320 325 392 524 450 + +length(rivers) # how many rivers were measured? +# 141 +summary(rivers) # what are some summary statistics? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# make a stem-and-leaf plot (a histogram-like data visualization) +stem(rivers) + +# The decimal point is 2 digit(s) to the right of the | +# +# 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)) # Notice that the data are neither normal nor log-normal! +# Take that, Bell curve fundamentalists. + +# The decimal point is 1 digit(s) to the left of the | +# +# 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 + +# make a histogram: +hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters +hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later + +# Here's another neat data set that comes pre-loaded. R has tons of these. +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") + +# Rather than leaving the default ordering (by year), +# we could also sort to see what's typical: +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) +# +# The decimal point is at the | +# +# 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 + +# Roll a die a few times +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Your numbers will differ from mine unless we set the same random.seed(31337) + +# Draw from a standard Gaussian 9 times +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# Data types and basic arithmetic +################################################## + +# Now for the programming-oriented part of the tutorial. +# In this section you will meet the important data types of R: +# integers, numerics, characters, logicals, and factors. +# There are others, but these are the bare minimum you need to +# get started. + +# INTEGERS +# Long-storage integers are written with L +5L # 5 +class(5L) # "integer" +# (Try ?class for more information on the class() function.) +# In R, every single value, like 5L, is considered a vector of length 1 +length(5L) # 1 +# You can have an integer vector with length > 1 too: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMERICS +# A "numeric" is a double-precision floating-point number +5 # 5 +class(5) # "numeric" +# Again, everything in R is a vector; +# you can make a numeric vector with more than one element +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# You can use scientific notation too +5e4 # 50000 +6.02e23 # Avogadro's number +1.6e-35 # Planck length +# You can also have infinitely large or small numbers +class(Inf) # "numeric" +class(-Inf) # "numeric" +# You might use "Inf", for example, in integrate(dnorm, 3, Inf); +# this obviates Z-score tables. + +# BASIC ARITHMETIC +# You can do arithmetic with numbers +# Doing arithmetic on a mix of integers and numerics gives you another numeric +10L + 66L # 76 # integer plus integer gives integer +53.2 - 4 # 49.2 # numeric minus numeric gives numeric +2.0 * 2L # 4 # numeric times integer gives numeric +3L / 4 # 0.75 # integer over numeric gives numeric +3 %% 2 # 1 # the remainder of two numerics is another numeric +# Illegal arithmetic yeilds you a "not-a-number": +0 / 0 # NaN +class(NaN) # "numeric" +# You can do arithmetic on two vectors with length greater than 1, +# so long as the larger vector's length is an integer multiple of the smaller +c(1,2,3) + c(1,2,3) # 2 4 6 +# Since a single number is a vector of length one, scalars are applied +# elementwise to vectors +(4 * c(1,2,3) - 2) / 2 # 1 3 5 +# Except for scalars, use caution when performing arithmetic on vectors with +# different lengths. Although it can be done, +c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 +# Matching lengths is better practice and easier to read +c(1,2,3,1,2,3) * c(1,2,1,2,1,2) + +# CHARACTERS +# There's no difference between strings and characters in R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Those were both character vectors of length 1 +# Here is a longer one: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# You can do regex operations on character vectors: +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 has several built-in character vectors: +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" + +# LOGICALS +# In R, a "logical" is a boolean +class(TRUE) # "logical" +class(FALSE) # "logical" +# Their behavior is normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Missing data (NA) is logical, too +class(NA) # "logical" +# Use | and & for logic operations. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Applying | and & to vectors returns elementwise logic operations +c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE +c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +# You can test if x is TRUE +isTRUE(TRUE) # TRUE +# Here we get a logical vector with many elements: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# FACTORS +# The factor class is for categorical data +# Factors can be ordered (like childrens' grade levels) or unordered (like gender) +factor(c("female", "female", "male", NA, "female")) +# female female male female +# Levels: female male +# The "levels" are the values the categorical data can take +# Note that missing data does not enter the levels +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" +# If a factor vector has length 1, its levels will have length 1, too +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# Factors are commonly seen in data frames, a data structure we will cover later +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" is a weird one; use it to "blank out" a vector +class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + +# TYPE COERCION +# Type-coercion is when you force a value to take on a different type +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# If you put elements of different types into a vector, weird coercions happen: +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Warning message: +# NAs introduced by coercion + +# Also note: those were just the basic data types +# There are many more data types, such as for dates, time series, etc. + + + +################################################## +# Variables, loops, 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 +# Lots of way to assign stuff: +x = 5 # this is possible +y <- "1" # this is preferred +TRUE -> z # this works but is weird + +# LOOPS +# We've got for loops +for (i in 1:4) { + print(i) +} +# We've got while loops +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Keep in mind that for and while loops run slowly in R +# Operations on entire vectors (i.e. a whole row, a whole column) +# or apply()-type functions (we'll discuss later) are preferred + +# IF/ELSE +# Again, pretty standard +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + +# FUNCTIONS +# Defined like so: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + return(x) +} +# Called like any other R function: +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Data structures: Vectors, matrices, data frames, and arrays +########################################################################### + +# ONE-DIMENSIONAL + +# Let's start from the very beginning, and with something you already know: vectors. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# We ask for specific elements by subsetting with square brackets +# (Note that R starts counting from 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# We can also search for the indices of specific components, +which(vec %% 2 == 0) # 1 3 +# grab just the first or last few entries in the vector, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# or figure out if a certain value is in the vector +any(vec == 10) # TRUE +# If an index "goes over" you'll get NA: +vec[6] # NA +# You can find the length of your vector with length() +length(vec) # 4 +# You can perform operations on entire vectors or subsets of vectors +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# and R has many built-in functions to summarize vectors +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Some more nice built-ins: +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 + +# TWO-DIMENSIONAL (ALL ONE CLASS) + +# You can make a matrix out of entries all of the same type like so: +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 +# Unlike a vector, the class of a matrix is "matrix", no matter what's in it +class(mat) # => "matrix" +# Ask for the first row +mat[1,] # 1 4 +# Perform operation on the first column +3 * mat[,1] # 3 6 9 +# Ask for a specific cell +mat[3,2] # 6 + +# Transpose the whole matrix +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# Matrix multiplication +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() sticks vectors together column-wise to make a matrix +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 +# Again, note what happened! +# Because matrices must contain entries all of the same class, +# everything got converted to the character class +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() sticks vectors together row-wise to make a matrix +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, everything of the same class. No coercions. Much better. + +# TWO-DIMENSIONAL (DIFFERENT CLASSES) + +# For columns of different types, use a data frame +# This data structure is so useful for statistical programming, +# a version of it was added to Python in the package "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" +# find the dimensions +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# The data.frame() function converts character vectors to factor vectors +# by default; turn this off by setting stringsAsFactors = FALSE when +# you create the data.frame +?data.frame + +# There are many twisty ways to subset data frames, all subtly unalike +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# An augmented version of the data.frame structure is the data.table +# If you're working with huge or panel data, or need to merge a few data +# sets, data.table can be a good choice. Here's a whirlwind tour: +install.packages("data.table") # download the package from CRAN +require(data.table) # load it +students <- as.data.table(students) +students # note the slightly different print-out +# => +# 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"] # get rows with name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # get rows with year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table makes merging two data sets easy +# let's make another data.table to merge with students +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] # merge the two data sets by matching "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 makes summary tables easy +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# To drop a column from a data.frame or data.table, +# assign it the NULL value +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 + +# Drop a row by subsetting +# Using 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 +# Using 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 (ALL ELEMENTS OF ONE TYPE) + +# Arrays creates n-dimensional tables +# All elements must be of the same type +# You can make a two-dimensional table (sort of like a matrix) +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 +# You can use array to make three-dimensional matrices too +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 + +# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) + +# Finally, R has lists (of vectors) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1 +# You can get items in the list like so +list1$time # one way +list1[["time"]] # another way +list1[[1]] # yet another way +# => +# [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 +# You can subset list items like any other vector +list1$price[4] + +# Lists are not the most efficient data structure to work with in R; +# unless you have a very good reason, you should stick to data.frames +# Lists are often returned by functions that perform linear regressions + +################################################## +# The apply() family of functions +################################################## + +# Remember mat? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X +# over rows (MAR = 1) or columns (MAR = 2) +# That is, R does FUN to each row (or column) of X, much faster than a +# for or while loop would do +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Other functions: ?lapply, ?sapply + +# Don't feel too intimidated; everyone agrees they are rather confusing + +# The plyr package aims to replace (and improve upon!) the *apply() family. +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Loading data +######################### + +# "pets.csv" is a file on the internet +# (but it could just as easily be be a file on your own computer) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # first two rows +tail(pets, 1) # last row + +# To save a data frame or matrix as a .csv file +write.csv(pets, "pets2.csv") # to make a new .csv file +# set working directory with setwd(), look it up with getwd() + +# Try ?read.csv and ?write.csv for more information + + + +######################### +# Statistical Analysis +######################### + +# Linear regression! +linearModel <- lm(price ~ time, data = list1) +linearModel # outputs result of regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Coefficients: +# (Intercept) time +# 0.1453 0.4943 +summary(linearModel) # more verbose output from the regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Residuals: +# Min 1Q Median 3Q Max +# -8.3134 -3.0131 -0.3606 2.8016 10.3992 +# +# Coefficients: +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.14527 1.50084 0.097 0.923 +# time 0.49435 0.06379 7.749 2.44e-09 *** +# --- +# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 +# +# Residual standard error: 4.657 on 38 degrees of freedom +# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 +# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 +coef(linearModel) # extract estimated parameters +# => +# (Intercept) time +# 0.1452662 0.4943490 +summary(linearModel)$coefficients # another way to extract results +# => +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 +# time 0.4943490 0.06379348 7.74920901 2.440008e-09 +summary(linearModel)$coefficients[,4] # the p-values +# => +# (Intercept) time +# 9.234021e-01 2.440008e-09 + +# GENERAL LINEAR MODELS +# Logistic regression +set.seed(1) +list1$success = rbinom(length(list1$time), 1, .5) # random binary +glModel <- glm(success ~ time, data = list1, + family=binomial(link="logit")) +glModel # outputs result of logistic regression +# => +# Call: glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) +# +# Coefficients: +# (Intercept) time +# 0.17018 -0.01321 +# +# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual +# Null Deviance: 55.35 +# Residual Deviance: 55.12 AIC: 59.12 +summary(glModel) # more verbose output from the regression +# => +# Call: +# glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) + +# Deviance Residuals: +# Min 1Q Median 3Q Max +# -1.245 -1.118 -1.035 1.202 1.327 +# +# Coefficients: +# Estimate Std. Error z value Pr(>|z|) +# (Intercept) 0.17018 0.64621 0.263 0.792 +# time -0.01321 0.02757 -0.479 0.632 +# +# (Dispersion parameter for binomial family taken to be 1) +# +# Null deviance: 55.352 on 39 degrees of freedom +# Residual deviance: 55.121 on 38 degrees of freedom +# AIC: 59.121 +# +# Number of Fisher Scoring iterations: 3 + + +######################### +# Plots +######################### + +# BUILT-IN PLOTTING FUNCTIONS +# Scatterplots! +plot(list1$time, list1$price, main = "fake data") +# Plot regression line on existing plot +abline(linearModel, col = "red") +# Get a variety of nice diagnostics +plot(linearModel) +# Histograms! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Barplots! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# But these are not even the prettiest of R's plots +# Try the ggplot2 package for more and better graphics +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 has excellent documentation (available http://docs.ggplot2.org/current/) + + + +``` + +## How do I get R? + +* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) is another GUI 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 ">>" +# 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 inlocuite in interiorul altor comenzi folosind $( ): -# Urmatoarea comanda afiseaza numarul de fisiere -# si directoare din directorul curent -echo "Sunt $(ls | wc -l) fisiere aici." +# 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." -# 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." +# 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 foloseste o instructiune 'case' care functioneaza -# in mod similar cu instructiunea switch din Java si C++ +# 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 "," ``` diff --git a/ro-ro/coffeescript-ro.html.markdown b/ro-ro/coffeescript-ro.html.markdown new file mode 100644 index 00000000..695274d2 --- /dev/null +++ b/ro-ro/coffeescript-ro.html.markdown @@ -0,0 +1,102 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Bogdan Lazar", "http://twitter.com/tricinel"] +filename: coffeescript-ro.coffee +lang: ro-ro +--- + +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) diff --git a/ro-ro/json-ro.html.markdown b/ro-ro/json-ro.html.markdown new file mode 100644 index 00000000..e897059c --- /dev/null +++ b/ro-ro/json-ro.html.markdown @@ -0,0 +1,61 @@ +--- +language: 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 +--- + +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 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 +{ + "cheie": "valoare", + + "chei": "trebuie mereu inconjurate de ghilimele", + "numere": 0, + "stringuri": "Bunã. Tot setul unicode este permis, chiar si \"escaping\".", + "are booleane?": true, + "nimic": null, + + "numere mari": 1.2e+100, + + "obiecte": { + "comentariu": "Majoritatea structurii va veni din obiecte.", + + "vectori": [0, 1, 2, 3, "Vectorii pot avea orice in ei.", 5], + + "alt obiect": { + "comentariu": "Lucrurile pot fi subordonate. Foarte util." + } + }, + + "glumite": [ + { + "surse de potasiu": ["banane"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stil alternativ": { + "comentariu": "ia uite la asta!" + , "pozitia virgulei": "nu conteaza - daca e inaintea valorii atunci e valida" + , "alt comentariu": "ce dragut" + }, + + "a fost scurt": "Am terminat. Acum stii tot ce are JSON de oferit." +} +``` 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 diff --git a/ro-ro/xml-ro.html.markdown b/ro-ro/xml-ro.html.markdown new file mode 100644 index 00000000..269010c2 --- /dev/null +++ b/ro-ro/xml-ro.html.markdown @@ -0,0 +1,133 @@ +--- +language: xml +filename: learnxml-ro.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Serban Constantin", "https://github.com/fuzzmz"] +lang: ro-ro +--- + +XML este un limbaj de markup ce are ca scop stocarea si transportul de date. + +Spre deosebire de HTML, XML nu specifica cum sa fie afisata sau formatata +informatia, ci doar o transporta. + +* Sintaxa XML + +```xml + + + + + + Mancaruri italiene + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Invata XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* Document bine formatat x Validare + +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. + +Un document XML ce foloseste o definitie de document este numit valid in +contextul documentului. + +Cu acest tool poti verifica datele XML in afara codului aplicatiei. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 162ec4c8..bfa3f085 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: d +language: D filename: learnd-ru.d contributors: - ["Anton Pastukhov", "http://dprogramming.ru/"] diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index b24ad555..a1a5cdfc 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -9,7 +9,7 @@ filename: LearnJavaRu.java lang: ru-ru --- -Java - это объектно ориентированный язык программирования общего назначения, +Java - это объектно-ориентированный язык программирования общего назначения, основанный на классах и поддерживающий параллельное программирование. [Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) @@ -43,17 +43,41 @@ public class LearnJavaRu { " Double: " + 3.14 + " Boolean: " + true); - // Чтобы напечатать что-либо не заканчивая переводом строки - // используется System.out.print. + // Чтобы печатать что-либо, не заканчивая переводом строки, + // используйте System.out.print. System.out.print("Hello "); System.out.print("World"); + // Используйте System.out.printf() для печати с форматированием + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 /////////////////////////////////////// - // Типы и Переменные + // Переменные /////////////////////////////////////// + /* + * Объявление переменных + */ // Переменные объявляются с использованием <тип> <имя> + int fooInt; + // Одновременное объявление нескольких переменных одного типа + // , , + int fooInt1, fooInt2, fooInt3; + + /* + * Инициализация переменных + */ + + // объявление и инициализация переменной = + int fooInt = 1; + int fooInt1, fooInt2, fooInt3; + // инициализация нескольких переменных одного типа + // , , = + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Типы переменных + */ // Byte - 8-битное целое число. // (-128 <= byte <= 127) byte fooByte = 100; @@ -247,7 +271,7 @@ public class LearnJavaRu { // Switch Case // switch работает с типами byte, short, char и int. // Также он работает с перечислениями, - // классом String и с некоторыми классами-обертками над + // классом String (с Java 7) и с некоторыми классами-обертками над // примитивными типами: Character, Byte, Short и Integer. int month = 3; String monthString; @@ -319,7 +343,7 @@ public class LearnJavaRu { System.out.println("trek info: " + trek.toString()); } // Конец метода main. -} // Конец класса LearnJava. +} // Конец класса LearnJavaRu. // Вы можете включать другие, не публичные классы в .java файл. @@ -362,7 +386,7 @@ class Bicycle { // Классы в Java часто реализуют сеттеры и геттеры для своих полей. // Синтаксис определения метода: - // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) + // <модификатор доступа> <тип возвращаемого значения> <имя метода>(<аргументы>) public int getCadence() { return cadence; } @@ -424,10 +448,10 @@ class PennyFarthing extends Bicycle { // Интерфейсы // Синтаксис определения интерфейса: -// <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. -//} +// <модификатор доступа> interface <имя интерфейса> extends <базовый интерфейс> { +// // Константы +// // Определение методов +// } // Пример - Еда: public interface Edible { diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index eb8e4881..c41e9676 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -61,7 +61,7 @@ __И этот тоже.__ **_И тут!_** *__И даже здесь!__* - ~~Зачёркнутый текст.~~ @@ -157,7 +157,7 @@ __И этот тоже.__ Например, можно выделить имя функции `go_to()` прямо посреди текста. - \`\`\`ruby @@ -167,7 +167,7 @@ end \`\`\` <-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами, -поскольку Github сам в состоянии определить границы блока - по строкам "```" --> +поскольку GitHub сам в состоянии определить границы блока - по строкам "```" --> - diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 37b6a86e..d17f24fc 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -32,7 +32,7 @@ print('Hello '); // Напечатать "Hello " без перевода стр // () необязательно применять для print и echo echo "World\n"; // Напечатать "World" и перейти на новую строку. -// (все утверждения должны заканчиваться ;) +// (все утверждения должны заканчиваться точкой с запятой) // Любые символы за пределами закрывающего тега выводятся автоматически: ?> @@ -45,8 +45,8 @@ Hello World Again! */ // Переменные начинаются с символа $. -// Правильное имя переменной начинается с буквы или знака подчеркивания, -// и может содержать любые цифры, буквы, или знаки подчеркивания. +// Правильное имя переменной начинается с буквы или символа подчеркивания, +// за которым следует любое количество букв, цифр или символов подчеркивания. // Не рекомендуется использовать кириллические символы в именах (прим. пер.) // Логические значения нечувствительны к регистру @@ -55,7 +55,7 @@ $boolean = false; // или FALSE или False // Целые числа $int1 = 12; // => 12 -$int2 = -12; // => -12- +$int2 = -12; // => -12 $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) $int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) @@ -87,7 +87,7 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; -// Заключайте переменные в фигурные скобки если это необходимо +// Заключайте переменные в фигурные скобки, если это необходимо $money = "I have $${number} in the bank."; // Начиная с PHP 5.3, синтаксис nowdocs может использоваться для @@ -106,6 +106,9 @@ END; // Строки соединяются при помощи . echo 'This string ' . 'is concatenated'; +// echo можно передавать строки как параметры +echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersValid' + /******************************** * Константы @@ -114,18 +117,19 @@ echo 'This string ' . 'is concatenated'; // Константа определяется при помощи define() // и никогда не может быть изменена во время выполнения программы! -// Правильное имя константы начинается с буквы или символа подчеркивания, -// и содержит любое колличество букв, цифр и знаков подчеркивания. +// Правильное имя константы начинается с буквы или символа подчеркивания +// и содержит любое колличество букв, цифр или символов подчеркивания. define("FOO", "something"); -// Доступ к константе возможен через прямое указание её имени -echo 'This outputs '.FOO; +// Доступ к константе возможен через прямое указание её имени без знака $ +echo FOO; // печатает 'something' +echo 'This outputs ' . FOO; // печатает 'This ouputs something' /******************************** * Массивы */ -// Все массивы в PHP - это ассоциативные массивы или хеши, +// Все массивы в PHP - это ассоциативные массивы // Ассоциативные массивы, известные в других языках как HashMap. @@ -189,7 +193,7 @@ $b = '0'; $c = '1'; $d = '1'; -// Утверждение (assert) выдает предупреждение если аргумент не true +// Утверждение (assert) выдает предупреждение, если его аргумент не true // Эти сравнения всегда будут истинными, даже если типы будут различаться assert($a == $b); // "равно" @@ -284,35 +288,35 @@ This is displayed otherwise. // Использование switch. switch ($x) { case '0': - print 'Switch does type coercion'; - break; // You must include a break, or you will fall through - // to cases 'two' and 'three' + print 'Switch использует неточное сравнение'; + break; // вы должны использовать break, иначе PHP будет продолжать + // исполнять команды следующих секций case 'two' и 'three' case 'two': case 'three': - // Do something if $variable is either 'two' or 'three' + // делаем что-то, если $x == 'two' или $x == 'three' break; default: - // Do something by default + // делаем что-то по умолчанию } // Циклы: while, do...while и for $i = 0; while ($i < 5) { echo $i++; -}; // Prints "01234" +}; // печатает "01234" echo "\n"; $i = 0; do { echo $i++; -} while ($i < 5); // Prints "01234" +} while ($i < 5); // печатает "01234" echo "\n"; for ($x = 0; $x < 10; $x++) { echo $x; -} // Напечатает "0123456789" +} // печатает "0123456789" echo "\n"; @@ -335,17 +339,17 @@ echo "\n"; $i = 0; while ($i < 5) { if ($i === 3) { - break; // Exit out of the while loop + break; // выйти из цикла while } echo $i++; } // Напечатает "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { - continue; // Skip this iteration of the loop + continue; // пропустить текущую итерацию цикла } echo $i; -} // Напечатает "0124" +} // печатает "0124" /******************************** @@ -360,7 +364,7 @@ function my_function () { echo my_function(); // => "Hello" // Правильное имя функции начинается с буквы или символа подчеркивания -// и состоит из букв, цифр или знаков подчеркивания. +// и состоит из букв, цифр или символов подчеркивания. function add ($x, $y = 1) { // $y по умолчанию равно 1 $result = $x + $y; @@ -656,7 +660,10 @@ $cls = new SomeOtherNamespace\MyClass(); ``` ## Смотрите также: -Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки. +Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки. + Если вас интересуют полезные приемы использования PHP посетите [PHP The Right Way](http://www.phptherightway.com/). + Если вы раньше пользовались языком с хорошей организацией пакетов, посмотрите [Composer](http://getcomposer.org/). + Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards). diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown new file mode 100644 index 00000000..aa7545cc --- /dev/null +++ b/ru-ru/tmux-ru.html.markdown @@ -0,0 +1,252 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Davydov Anton", "https://github.com/davydovanton"] +filename: LearnTmux-ru.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 # Закрыть текущую панель + + Стрелки вверх, вниз # Переместиться на панель выше, ниже, левее + влево, вправо # или правее + + 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 % + +# Активировать центральную сессию (когда вложенный 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 + + +### Интерфейс +########################################################################### + +# Уведомления +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) diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown new file mode 100644 index 00000000..67b58a38 --- /dev/null +++ b/ru-ru/typescript-ru.html.markdown @@ -0,0 +1,173 @@ +--- +language: TypeScript +lang: ru-ru +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Fadil Mamedov", "https://github.com/fadilmamedov"] + - "Andre Polykanine", "https://github.com/Oire"] +filename: learntypescript-ru.ts +--- + +TypeScript — это язык программирования, целью которого является лёгкая разработка широкомасштабируемых JavaScript-приложений. +TypeScript добавляет в Javascript общие концепции, такие, как классы, модули, интерфейсы, обобщённое программирование и (опционально) статическую типизацию. +Это надмножество языка JavaScript: весь JavaScript-код является валидным TypeScript-кодом, следовательно, может быть добавлен бесшовно в любой проект. +Компилятор TypeScript генерирует JavaScript-код. + +Эта статья концентрируется только на синтаксисе TypeScript, в противовес статье о [JavaScript](javascript-ru/). + +Для тестирования компилятора TypeScript пройдите по ссылке в [песочницу](http://www.typescriptlang.org/Playground). +Там вы можете написать код (с поддержкой автодополнения) и сразу же увидеть сгенерированный JavaScript код. + +```js +// В TypeScript есть 3 базовых типа +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Андерс"; + +// Тип «any» для случаев, когда заранее неизвестен тип переменной +var notSure: any = 4; +notSure = "а может быть, строка"; +notSure = false; // а теперь логический тип + +// Для коллекций есть типизированные массивы и обобщённые массивы +var list: number[] = [1, 2, 3]; +// Как альтернатива, использование обобщённого массива +var list: Array = [1, 2, 3]; + +// Перечисления: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Наконец, «void» используется для обозначения того, что функция ничего не возвращает +function bigHorribleAlert(): void { + alert("Я маленькое надоедливое окошко!"); +} + +// Функции — это объекты первого класса. Они поддерживают лямбда-синтаксис (=>) +// и используют вывод типов (type inference) + +// Следующие строки кода являются эквивалентными, компилятором предполагается +// одинаковая сигнатура, на выходе генерируется одинаковый JavaScript-код +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; } +// Предполагается возвращаемый тип, в однострочной функции ключевое слово «return» не нужно +var f5 = (i: number) => i * i; + +// Интерфейсы являются структурными; всё, что имеет свойства, совместимо с интерфейсом +interface Person { + name: string; + // Опциональные свойства, помеченные символом «?» + age?: number; + // И, конечно, функции + move(): void; +} + +// Объект, который реализует интерфейс «Person» +// К нему можно обращаться, как к «Person», так как он имеет свойства «name» и «move» +var p: Person = { name: "Бобби", move: () => {} }; +// Объекты, которые могут иметь опциональные свойства: +var validPerson: Person = { name: "Бобби", age: 42, move: () => {} }; +// Это не «Person», поскольку «age» не является числовым значением +var invalidPerson: Person = { name: "Бобби", age: true }; + +// Интерфейсы могут также описывать функциональный тип +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Важны только типы параметров, имена — нет. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Классы. Члены класса по умолчанию являются публичными +class Point { + // Свойства + x: number; + + // Конструктор — ключевые слова public/private в данном контексте сгенерируют + // шаблонный код для свойства и для инициализации в конструкторе + // В данном примере «y» будет определён так же, как и «x», но меньшим количеством кода + // Значения по умолчанию также поддерживаются + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Функции + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Статические члены + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y будет равен 0 + +// Наследование +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Явный вызов конструктора базового класса обязателен + } + + // Перегрузка + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Модули, знак «.» может быть использован как разделитель для обозначения подмодулей +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Локальный псевдоним для ссылки на модуль +import G = Geometry; + +var s2 = new G.Square(10); + +// Обобщённое программирование +// Классы +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Интерфейсы +interface Pair { + item1: T; + item2: T; +} + +// И функции +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Включение ссылки на файл определения: +/// + +``` + +## Для дальнейшего чтения + * [Официальный веб-сайт TypeScript](http://www.typescriptlang.org/) + * [Спецификация языка TypeScript (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg — Introducing TypeScript на Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Исходный код на GitHub](https://github.com/Microsoft/TypeScript) + * [Definitely Typed — репозиторий определений типов](http://definitelytyped.org/) diff --git a/self.html.markdown b/self.html.markdown index 9290a0c9..fc7f69db 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -60,7 +60,7 @@ also sending the message 'true' to the lobby." # Sending messages to objects -Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. +Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separated from their destination by whitespace. ``` "unary message, sends 'printLine' to the object '23' diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 3b388505..2c17b753 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -37,7 +37,7 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j `"Comments are enclosed in quotes"` -`"Period (.) is the statement seperator"` +`"Period (.) is the statement separator"` ## Transcript: ``` @@ -305,7 +305,7 @@ result := (switch at: $B) value. x := 4. y := 1. [x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" [x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" -x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" +x timesRepeat: [y := y * 2]. "times repeat loop (i := 1 to x)" 1 to: x do: [:a | y := y * 2]. "for loop" 1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" @@ -320,7 +320,7 @@ y := x isUppercase. "test if upper case" y := x isLetter. "test if letter" y := x isDigit. "test if digit" y := x isAlphaNumeric. "test if alphanumeric" -y := x isSeparator. "test if seperator char" +y := x isSeparator. "test if separator char" y := x isVowel. "test if vowel" y := x digitValue. "convert to numeric digit value" y := x asLowercase. "convert to lower case" diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown new file mode 100644 index 00000000..c2ee36dd --- /dev/null +++ b/sv-se/json-sv.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +filename: learnjson-sv.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": "De 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." +} +``` diff --git a/swift.html.markdown b/swift.html.markdown index 46768375..e921e7ea 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -94,6 +94,8 @@ var unwrappedString: String! = "Value is expected." // same as above, but ! is a postfix operator (more syntax candy) var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." +// If let structure - +// If let is a special structure in Swift that allows you to check if an Optional rhs holds a value, and in case it does - unwraps and assigns it to the lhs. if let someOptionalStringConstant = someOptionalString { // has `Some` value, non-nil if !someOptionalStringConstant.hasPrefix("ok") { diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown index bac8f6fc..b8f11e39 100644 --- a/tr-tr/markdown-tr.html.markdown +++ b/tr-tr/markdown-tr.html.markdown @@ -52,7 +52,7 @@ __Bu yazı da kalın.__ **_Bu da öyle!_** *__Hatta bu bile!__* - + ~~Bu yazı üstü çizili olarak gözükecek.~~ @@ -151,7 +151,7 @@ kullanabilirsiniz --> Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor! - + \`\`\`ruby def foobar @@ -159,7 +159,7 @@ def foobar end \`\`\` - @@ -230,7 +230,7 @@ Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmama bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*. - | Sütun1 | Sütun 2 | Sütün 3 | diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown new file mode 100644 index 00000000..1ea30f3d --- /dev/null +++ b/uk-ua/java-ua.html.markdown @@ -0,0 +1,783 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +translators: + - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"] + - ["Andre Polykanine", "https://github.com/Oire"] +filename: LearnJavaUa.java +lang: uk-ua +--- + +Java є об’єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. +[Детальніше читайте тут, англ.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Однорядковий коментар починається з // +/* +Багаторядковий коментар виглядає так. +*/ +/** +JavaDoc-коментар виглядає так. Використовується для опису класу та членів класу. +*/ + +// Імпорт класу ArrayList з пакета java.util +import java.util.ArrayList; +// Імпорт усіх класів з пакета java.security +import java.security.*; + +// Кожний .java файл містить один зовнішній публічний клас, ім’я якого співпадає +// з іменем файлу. +public class LearnJava { + + // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main. + public static void main (String[] args) { + + // Використання System.out.println() для виводу на друк рядків. + System.out.println("Привіт, світе!"); + System.out.println( + " Ціле число: " + 10 + + " Число з рухомою комою подвійної точности: " + 3.14 + + " Булеве значення: " + true); + + // Для друку без переходу на новий рядок використовується System.out.print(). + System.out.print("Привіт, "); + System.out.print("світе"); + + // Використання System.out.printf() для простого форматованого виводу на друк. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Змінні + /////////////////////////////////////// + + /* + * Оголошення змінних + */ + // Для оголошення змінних використовується формат <тип> <змінна> + int fooInt; + // Оголошення декількох змінних одного типу <тип> <ім’я1>, <ім’я2>, <ім’я3> + int fooInt1, fooInt2, fooInt3; + + /* + * Ініціалізація змінних + */ + + // Ініціалізація змінної з використанням формату <тип> <ім’я> = <значення> + int fooInt = 1; + // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім’я1>, <ім’я2>, <ім’я3> = <значення> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Типи змінних + */ + // Байт — 8-бітне ціле число зі знаком + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short — 16-бітне ціле число зі знаком + // (-32 768 <= short <= 32 767) + short fooShort = 10000; + + // Integer — 32-бітне ціле число зі знаком + // (-2 147 483 648 <= int <= 2 147 483 647) + int fooInt = 1; + + // Long — 64-бітне ціле число зі знаком + // (-9 223 372 036 854 775 808 <= long <= 9 223 372 036 854 775 807) + long fooLong = 100000L; + // L використовується для позначення того, що число має тип Long; + // інакше число буде трактуватись як integer. + + // Примітка: Java не має беззнакових типів. + + // Float — 32-бітне число з рухомою комою одиничної точності за стандартом IEEE 754 + // 2^-149 <= float <= (2-2^-23) * 2^127 + float fooFloat = 234.5f; + // f або F використовується для позначення того, що змінна має тип float; + // інакше трактується як double. + + // Double — 64-бітне число з рухомою комою подвійної точності за стандартом IEEE 754 + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double fooDouble = 123.4; + + // Boolean — true & false (істина чи хиба) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char — 16-бітний символ Unicode + char fooChar = 'A'; + + // final - посилання на такі змінні не можуть бути присвоєні іншим об’єктам, + final int HOURS_I_WORK_PER_WEEK = 9001; + // але вони можуть мати відкладену ініціалізацію. + final double E; + E = 2.71828; + + + // BigInteger -Незмінні знакові цілі числа довільної точності + // + // BigInteger є типом даних, який дає можливість розробнику виконувати операції + // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві + // байтів, операції над ними виконуються функціями, які мають клас BigInteger + // + // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок. + + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + + // BigDecimal — Незмінні знакові дробові числа довільної точності + // + // BigDecimal складається з двох частин: цілого числа довільної точності + // з немасштабованим значенням та 32-бітного масштабованого цілого числа + // + // BigDecimal дозволяє розробникам контролювати десяткове округлення. + // Рекомендовано використовувати BigDecimal зі значеннями валют + // і там, де необхідна точність дробових обчислень. + // + // BigDecimal може бути ініціалізований типами даних int, long, double або String + // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Для дотримання заданої точності рекомендується використовувати + // конструктор, який приймає String + + BigDecimal tenCents = new BigDecimal("0.1"); + + + // Рядки + String fooString = "Це мій рядок!"; + + // \n є символом переходу на новий рядок + String barString = "Друк з нового рядка?\nНема питань!"; + // \t — це символ табуляції + String bazString = "Хочете додати табуляцію?\tТримайте!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Масиви + // Розмір масиву має бути визначений перед ініціалізацією + // Наведений формат ілюструє ініціалізацію масивів + // <тип даних>[] <ім’я змінної> = new <тип даних>[<розмір масиву>]; + // <тип даних> <ім’я змінної>[] = new <тип даних>[<розмір масиву>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Інший шлях оголошення та ініціалізації масиву + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Індексація масиву — доступ за елементами + System.out.println("intArray @ 0: " + intArray[0]); + + // Масиви є змінними та мають нульовий елемент. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Додатково + // ArrayLists — Схожі на масив, але мають більший функціонал та змінний розмір. + // LinkedLists — Реалізація двозв’язного списку. Всі операції + // виконуються так, як очікується від + // двозв’язного списку. + // Maps — Множина об’єктів, які пов’язують ключ зі значенням. Map є + // інтерфейсом, тому не може бути успадкований. + // Типи ключів і значень, які зберігаються в Map, мають + // вказуватись у класі, який його реалізує. + // Ключ не може повторюватись і пов’язаний лише з одним значенням + // HashMaps — Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. + // Це дозволяє виконувати певні операції, + // такі, як отримання та вставка елемента, + // залишаючись постійними навіть для великої кількості елементів. + + /////////////////////////////////////// + // Оператори + /////////////////////////////////////// + System.out.println("\n->Оператори"); + + int i1 = 1, i2 = 2; // Коротка форма присвоєння + + // Арифметичні операції виконуються очевидним способом + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int повертається як int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Ділення з остачею + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Оператори порівняння + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Логічні оператори + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Бітові оператори! + /* + ~ Унарне бітове доповнення + << Знаковий зсув уліво + >> Знаковий/Арифметичний зсув управо + >>> Беззнаковий/Логічний зсув управо + & Бітове І + ^ Бітови виключне АБО + | Бітове АБО + */ + + // Інкремент + int i = 0; + System.out.println("\n->Інкремент/Декремент"); + // Оператори ++ і -- здійснюють інкремент та декремент ретроспективно. + // Якщо вони розташовані перед змінною, операція виконається перед поверненням; + // якщо після неї — повернеться інкремент або декремент. + System.out.println(i++); // i = 1, друкує 0 (постінкремент) + System.out.println(++i); // i = 2, друкує 2 (преінкремент) + System.out.println(i--); // i = 1, друкує 2 (постдекремент) + System.out.println(--i); // i = 0, друкує 0 (предекремент) + + /////////////////////////////////////// + // Керуючі конструкції + /////////////////////////////////////// + System.out.println("\n->Керуючі конструкції"); + + // Оператор if використовується так само, як у мові C + int j = 10; + if (j == 10) { + System.out.println("Це надрукується"); + } else if (j > 10) { + System.out.println("А це — ні"); + } else { + System.out.println("Це — також ні"); + } + + // Цикл з передумовою While + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Інкремент лічильника + // Виконається 100 разів, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // Цикл з післяумовою Do While + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Інкремент лічильника + // Виконається 99 разів, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Значення fooDoWhile: " + fooDoWhile); + + // Цикл з параметром For + // структура циклу => for(<початковий стан>; <умова завершення>; <крок>) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Виконається 10 разів, fooFor 0->9 + } + System.out.println("Значення fooFor: " + fooFor); + + // Вихід із вкладеного циклу через мітку + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // вихід із зовнішнього циклу, а не лише внутрішнього + } + } + } + + // Цикл For Each + // Призначений для перебору масивів та колекцій + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + + for (int bar : fooList) { + System.out.println(bar); + // Повторюється 9 разів та друкує числа від 1 до 9 на нових рядках + } + + // Оператор вибору Switch Case + // Оператор вибору працює з типами даних byte, short, char, int. + // Також працює з переліками Enum, + // класом String та класами-обгортками примітивних типів: + // Character, Byte, Short та Integer. + int month = 3; + String monthString; + switch (month) { + case 1: monthString = "Січень"; + break; + case 2: monthString = "Лютий"; + break; + case 3: monthString = "Березень"; + break; + default: monthString = "Інший місяць"; + break; + } + System.out.println("Результат Switch Case: " + monthString); + + // Починаючи з Java 7 і далі, вибір рядкових змінних здійснюється так: + String myAnswer = "можливо"; + switch(myAnswer) { + case "так": + System.out.println("Ви відповіли «Так»."); + break; + case "ні": + System.out.println("Ви відповіли «ні»."); + break; + case "можливо": + System.out.println("Ви відповіли «Можливо»."); + break; + default: + System.out.println("Ви відповіли «" + myAnswer + "»"); + break; + } + + // Тернарний оператор вибору + // Можна використовувати оператор «?» (знак питання) для визначення умови. + // Читається так: «Якщо (умова) вірна, то <перше значення>, інакше + // <друге значення>» + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Надрукується А, бо умова вірна + + + //////////////////////////////////////// + // Перетворення типів + //////////////////////////////////////// + + // Перетворення String на Integer + Integer.parseInt("123");//поверне числову версію рядка "123" + + // Перетворення Integer на String + Integer.toString(123);//повертає рядкову версію 123 + + // Для інших перетворень є наступні класи: + // Double + // Long + // String + + // Приведення типів + // Тут можна прочитати про приведення об’єктів (англ.): + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Класи та функції + /////////////////////////////////////// + + System.out.println("\n->Класи та функції"); + + // (Клас Bicycle наведений нижче) + + // Новий об’єкт класу + Bicycle trek = new Bicycle(); + + // Виклик методу об’єкта + trek.speedUp(3); // Постійно використовуються методи з назвами set і get + trek.setCadence(100); + + // toString повертає рядкове представлення об’єкту. + System.out.println("Інформація про об’єкт trek: " + trek.toString()); + + // У Java немає синтаксису для явного створення статичних колекцій. + // Це можна зробити так: + + private static final Set COUNTRIES = new HashSet(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // Але є інший спосіб — ініціалізація з подвійними фігурними дужками. + + private static final Set COUNTRIES = new HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // Використовується анонімний внутрішній клас + + } // Кінець методу main +} // Кінець класу LearnJava + + +// У .java-файл можна додавати інші, не public класи зовнішнього рівня, +// але це не є хорошою практикою. Розміщуйте класи в окремих файлах. + + +// Синтаксис оголошення класу: +// class <ім’я класу> { +// // поля, конструктори, функції та ін. +// // у Java функції називаються методами. +// } + +class Bicycle { + + // Поля (змінні) класу Bicycle + public int cadence; // Public: доступно звідусіль + private int speed; // Private: доступно лише у межах класу + protected int gear; // Protected: доступно лише класові та його нащадкам + String name; // за замовчанням: доступно у даному пакеті + + static String className; // статична змінна класу + + // статичний блок + // Java не має статичних конструкторів, але + // має статичний блок ініціалізації змінних класу + // Цей блок виконується при завантаженні класу. + static { + className = "Bicycle"; + } + + // Конструктори є способом створення класу + // Оце — конструктор + public Bicycle() { + // Можна викликати інший конструктор: + // this(1, 50, 5, "Bontrager"); + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // Цей конструктор приймає аргументи + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Синтаксис методу: + // <тип повернутого значення> <ім’я методу>(<аргументи>) + + // Java-класи часто мають методи для отримання та встановлення змінних + + // Синтаксис оголошення методу: + // <модифікатор доступу> <тип повернутого значення> <ім’я методу>(<аргументи>) + public int getCadence() { + return cadence; + } + + // void-методи не повертають значень + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Метод показує значення змінних об’єкту. + @Override // Успадковано від класу Object. + public String toString() { + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; + } +} // кінець класу Bicycle + +// PennyFarthing є розширенням (нащадком) класу Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings мають велике переднє колесо. + // Вони не мають передач.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Виклик батьківського конструктора через super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Перевизначений метод має бути відмічений аннотацією, яка починається зі знака @. + // Для ознайомлення з аннотаціями перейдіть за посиланням + // http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } +} + +// Інтерфейси +// Синтаксис оголошення інтерфейсів +// <рівень доступу> interface <ім’я інтерфейсу> extends <батьківський інтерфейс> { +// // Константи +// // Оголошення методів +// } + +//Приклад — їжа (Food): +public interface Edible { + public void eat(); // Будь-які класи, що реалізують цей інтерфейс, + // повинні реалізувати цей метод. +} + +public interface Digestible { + public void digest(); +} + + +// Можна створити клас, що реалізує обидва інтерфейси. +public class Fruit implements Edible, Digestible { + + @Override + public void eat() { + // ... + } + + @Override + public void digest() { + // ... + } +} + +// В Java можна успадковувати лише один клас, але реалізовувати багато +// інтерфейсів. Наприклад: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { + + @Override + public void InterfaceOneMethod() { + } + + @Override + public void InterfaceTwoMethod() { + } + +} + +// Абстрактні класи + +// Синтаксис оголошення абстрактних класів: +// <рівень доступу> abstract <ім’я класу> extends <батьківський абстрактний клас> { +// // Константи і змінні +// // Оголошення методів +// } + +// Позначення класу як абстрактного означає, що оголошені у ньому методи мають +// бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри +// абстракних класів, але їх можна успадковувати. Нащадок зобов’язаний реалізувати всі абстрактні +// методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені, +// так і абстрактні методи. Методи в інтерфейсах не мають тіла, +// за винятком статичних методів, а змінні неявно мають модифікатор final, на відміну від +// абстрактного класу. Абстрактні класи МОЖУТЬ мати метод «main». + +public abstract class Animal +{ + public abstract void makeSound(); + + // Метод може мати тіло + public void eat() + { + System.out.println("Я тварина, і я їм."); + // Зауваження: є доступ до приватних змінних. + age = 30; + } + + // Ініціалізація не потрібна + protected int age; + + public void printAge() + { + System.out.println(age); + } + + // Абстрактні класи МОЖУТЬ мати метод «main». + public static void main(String[] args) + { + System.out.println("Я абстрактний"); + } +} + +class Dog extends Animal +{ + // Слід помічати перевизначення абстрактних методів + @Override + public void makeSound() + { + System.out.println("Гав!"); + // age = 30; ==> ПОМИЛКА! age є private для Animal + } + + // Зауваження: Буде помилка, якщо використати аннотацію + // @Override тут, так як у java не можна + // перевизначати статичні методи. + // Те, що тут відбувається, називається приховування методів. + // Більш детально: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Фінальні класи + +// Синтаксис оголошення фінальних класів +// <рівень доступу> final <ім’я класу> { +// // Константи і змінні +// // Оголошення методів +// } + +// Фінальні класи не можуть мати нащадків, також самі вони є останніми нащадками. +// Фінальні класи є протилежністю абстрактних у цьому плані. + +public final class SaberToothedCat extends Animal +{ + // Перевизначення методу + @Override + public void makeSound() + { + System.out.println("Гррр!"); + } +} + +// Фінальні методи +public abstract class Mammal() +{ + // Синтаксис фінальних методів: + // <модифікатор доступу> final <тип повернутого значення> <ім’я функції>(<аргументи>) + + // Фінальні методи не можуть бути перевизначені класом-нащадком, + // вони є остаточною реалізацією методу. + public final boolean isWarmBlooded() + { + return true; + } +} + + +// Тип Enum (перелік) +// +// Enum є спеціальним типом даних, який дозволяє змінним бути певною множиною +// визначених констант. Змінна має відповідати одному зі значень, що +// заздалегідь визначені для неї. Оскільки це константи, імена типів полів у enum +// задаються у верхньому регістрі. Тип «перелік» у Java задається за допомогою +// ключового слова enum. Наприклад, перелік днів тижня можна задати так: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// Перелік Day можна використовувати так: + +public class EnumTest { + + // Змінна того же типу, що й перелік + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Понеділкі важкі."); + break; + + case FRIDAY: + System.out.println("П’ятниці краще."); + break; + + case SATURDAY: + case SUNDAY: + System.out.println("Вихідні найліпші."); + break; + + default: + System.out.println("Середина тижня так собі."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => Понеділки важкі. + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => Середина тижня так собі. + } +} + +// Переліки набагато потужніші, ніж тут показано. +// Тіло переліків може містити методи та інші змінні. +// Дивіться більше тут: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Додатково для читання + +Посилання, наведені нижче, дозволяють тільки зрозуміти тему. Щоб знайти конкретні приклади, використовуйте Ґуґл. + +**Офіційні посібники Oracle**: + +* [Посібник Java від Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java — модифікатори доступу](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [ООП-концепції](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Наслідування](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Поліморфізм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Абстракція](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Виключення](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Інтерфейси](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [параметризація](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Стиль коду у Java](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Online-практика та посібники** + +* [Learneroo.com — Вивчаємо Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Книжки**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) 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. diff --git a/zfs.html.markdown b/zfs.html.markdown index 39ff84cd..3fe05896 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) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index b633714d..87ed46ad 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -53,7 +53,7 @@ __此文本也是__ **_或者这样。_** *__这个也是!__* - + ~~此文本为删除线效果。~~ @@ -142,7 +142,7 @@ __此文本也是__ John 甚至不知道 `go_to()` 方程是干嘛的! - + \`\`\`ruby def foobar @@ -150,7 +150,7 @@ def foobar end \`\`\` - + @@ -220,7 +220,7 @@ end 斜体化, 所以我就: \*这段置文字于星号之间\*。 - + | 第一列 | 第二列 | 第三列 | | :---------- | :------: | ----------: | diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 3efe4941..017a7812 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -31,7 +31,7 @@ import UIKit // Swift2.0 println() 及 print() 已经整合成 print()。 print("Hello, world") // 这是原本的 println(),会自动进入下一行 -print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false +print("Hello, world", terminator: "") // 如果不要自动进入下一行,需设定结束符为空串 // 变量 (var) 的值设置后可以随意改变 // 常量 (let) 的值设置后不能改变 @@ -171,8 +171,8 @@ while i < 1000 { i *= 2 } -// do-while 循环 -do { +// repeat-while 循环 +repeat { print("hello") } while 1 == 2 @@ -212,11 +212,11 @@ default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情 func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } -greet("Bob", "Tuesday") +greet("Bob", day: "Tuesday") -// 函数参数前带 `#` 表示外部参数名和内部参数名使用同一个名称。 +// 第一个参数表示外部参数名和内部参数名使用同一个名称。 // 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName` -func greet2(#requiredName: String, externalParamName localParamName: String) -> String { +func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值 @@ -235,8 +235,8 @@ print("Gas price: \(price)") // 可变参数 func setup(numbers: Int...) { // 可变参数是个数组 - let number = numbers[0] - let argCount = numbers.count + let _ = numbers[0] + let _ = numbers.count } // 函数变量以及函数作为返回值返回 @@ -257,7 +257,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { } var someIntA = 7 var someIntB = 3 -swapTwoInts(&someIntA, &someIntB) +swapTwoInts(&someIntA, b: &someIntB) print(someIntB) // 7 @@ -286,17 +286,10 @@ numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] // 简洁的闭包 -numbers = sorted(numbers) { $0 > $1 } -// 函数的最后一个参数可以放在括号之外,上面的语句是这个语句的简写形式 -// numbers = sorted(numbers, { $0 > $1 }) +numbers = numbers.sort { $0 > $1 } print(numbers) // [18, 6, 3] -// 超级简洁的闭包,因为 `<` 是个操作符函数 -numbers = sorted(numbers, < ) - -print(numbers) // [3, 6, 18] - // // MARK: 结构体 @@ -305,7 +298,7 @@ print(numbers) // [3, 6, 18] // 结构体和类非常类似,可以有属性和方法 struct NamesTable { - let names = [String]() + let names: [String] // 自定义下标运算符 subscript(index: Int) -> String { @@ -516,7 +509,7 @@ protocol ShapeGenerator { // 一个类实现一个带 optional 方法的协议时,可以实现或不实现这个方法 // optional 方法可以使用 optional 规则来调用 @objc protocol TransformShape { - optional func reshaped() + optional func reshape() optional func canReshape() -> Bool } @@ -528,9 +521,9 @@ class MyShape: Rect { // 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。 // 这样就不会引起运行时错误 (runtime error) - if let allow = self.delegate?.canReshape?() { + if let reshape = self.delegate?.canReshape?() where reshape { // 注意语句中的问号 - self.delegate?.reshaped?() + self.delegate?.reshape?() } } } @@ -542,8 +535,8 @@ class MyShape: Rect { // 扩展: 给一个已经存在的数据类型添加功能 -// 给 Square 类添加 `Printable` 协议的实现,现在其支持 `Printable` 协议 -extension Square: Printable { +// 给 Square 类添加 `CustomStringConvertible` 协议的实现,现在其支持 `CustomStringConvertible` 协议 +extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" } @@ -567,8 +560,8 @@ print(14.multiplyBy(3)) // 42 // 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。 // 如果只有一个类型限制,可以省略 `where` 关键字 -func findIndex(array: [T], valueToFind: T) -> Int? { - for (index, value) in enumerate(array) { +func findIndex(array: [T], _ valueToFind: T) -> Int? { + for (index, value) in array.enumerate() { if value == valueToFind { return index }