diff options
-rw-r--r-- | c.html.markdown | 10 | ||||
-rw-r--r-- | coldfusion.html.markdown | 321 | ||||
-rw-r--r-- | es-es/visualbasic-es.html.markdown | 286 | ||||
-rw-r--r-- | fr-fr/haml-fr.html.markdown | 156 | ||||
-rw-r--r-- | fr-fr/objective-c-fr.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/python3-fr.html.markdown | 723 | ||||
-rw-r--r-- | fr-fr/scala.html.markdown | 9 | ||||
-rw-r--r-- | hu-hu/ruby.html.markdown | 555 | ||||
-rw-r--r-- | java.html.markdown | 51 | ||||
-rw-r--r-- | julia.html.markdown | 26 | ||||
-rw-r--r-- | latex.html.markdown | 231 | ||||
-rw-r--r-- | objective-c.html.markdown | 2 | ||||
-rw-r--r-- | perl.html.markdown | 2 | ||||
-rw-r--r-- | perl6.html.markdown | 91 | ||||
-rw-r--r-- | pt-br/clojure-macros-pt.html.markdown | 154 | ||||
-rw-r--r-- | pt-pt/scala-pt.html.markdown | 651 | ||||
-rw-r--r-- | python3.html.markdown | 4 | ||||
-rw-r--r-- | ru-ru/objective-c-ru.html.markdown | 2 | ||||
-rw-r--r-- | ru-ru/php-ru.html.markdown | 61 | ||||
-rw-r--r-- | ruby.html.markdown | 10 | ||||
-rw-r--r-- | sass.html.markdown | 232 | ||||
-rw-r--r-- | scala.html.markdown | 12 | ||||
-rw-r--r-- | tr-tr/objective-c-tr.html.markdown | 2 | ||||
-rw-r--r-- | vi-vn/objective-c-vi.html.markdown | 2 | ||||
-rw-r--r-- | vi-vn/ruby-vi.html.markdown | 549 | ||||
-rw-r--r-- | xml.html.markdown | 7 |
26 files changed, 4038 insertions, 113 deletions
diff --git a/c.html.markdown b/c.html.markdown index db2ac930..345dca7f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -27,6 +27,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! // Constants: #define <keyword> +// Constants are written in all-caps out of convention, not requirement #define DAYS_IN_YEAR 365 // Enumeration constants are also ways to declare constants. @@ -56,6 +57,15 @@ int add_two_ints(int x1, int x2); // function prototype // Your program's entry point is a function called // main with an integer return type. int main(void) { + // your program +} + +// The command line arguments used to run your program are also passed to main +// argc being the number of arguments - your program's name counts as 1 +// argv is an array of character arrays - containing the arguments themselves +// argv[0] = name of your program, argv[1] = first argument, etc. +int main (int argc, char** argv) +{ // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown new file mode 100644 index 00000000..e2f0737d --- /dev/null +++ b/coldfusion.html.markdown @@ -0,0 +1,321 @@ +--- +language: ColdFusion +contributors: + - ["Wayne Boka", "http://wboka.github.io"] +filename: LearnColdFusion.cfm +--- + +ColdFusion is a scripting language for web development. +[Read more here.](http://www.adobe.com/products/coldfusion-family.html) + +```ColdFusion + +<em>HTML tags have been provided for output readability</em> + +<!--- Comments start with "<!---" and end with "--->" ---> +<!--- + Comments can + also + span + multiple lines +---> + +<!--- CFML tags have a similar format to HTML tags. ---> +<h1>Simple Variables</h1> +<!--- Variable Declaration: Variables are loosely typed, similar to javascript ---> +<p>Set <b>myVariable</b> to "myValue"</p> +<cfset myVariable = "myValue" /> +<p>Set <b>myNumber</b> to 3.14</p> +<cfset myNumber = 3.14 /> + +<!--- Displaying simple data ---> +<!--- Use <cfoutput> for simple values such as strings, numbers, and expressions ---> +<p>Display <b>myVariable</b>: <cfoutput>#myVariable#</cfoutput></p><!--- myValue ---> +<p>Display <b>myNumber</b>: <cfoutput>#myNumber#</cfoutput></p><!--- 3.14 ---> + +<hr /> + +<h1>Complex Variables</h1> +<!--- Declaring complex variables ---> +<!--- Declaring an array of 1 dimension: literal or bracket notation ---> +<p>Set <b>myArray1</b> to an array of 1 dimension using literal or bracket notation</p> +<cfset myArray1 = [] /> +<!--- Declaring an array of 1 dimension: function notation ---> +<p>Set <b>myArray2</b> to an array of 1 dimension using function notation</p> +<cfset myArray2 = ArrayNew(1) /> + +<!--- Outputting complex variables ---> +<p>Contents of <b>myArray1</b></p> +<cfdump var="#myArray1#" /> <!--- An empty array object ---> +<p>Contents of <b>myArray2</b></p> +<cfdump var="#myArray2#" /> <!--- An empty array object ---> + +<!--- Operators ---> +<!--- Arithmetic ---> +<h1>Operators</h1> +<h2>Arithmetic</h2> +<p>1 + 1 = <cfoutput>#1 + 1#</cfoutput></p> +<p>10 - 7 = <cfoutput>#10 - 7#<br /></cfoutput></p> +<p>15 * 10 = <cfoutput>#15 * 10#<br /></cfoutput></p> +<p>100 / 5 = <cfoutput>#100 / 5#<br /></cfoutput></p> +<p>120 % 5 = <cfoutput>#120 % 5#<br /></cfoutput></p> +<p>120 mod 5 = <cfoutput>#120 mod 5#<br /></cfoutput></p> + +<hr /> + +<!--- Comparison ---> +<h2>Comparison</h2> +<h3>Standard Notation</h3> +<p>Is 1 eq 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 neq 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 gt 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 lt 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 gte 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 lte 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<h3>Alternative Notation</h3> +<p>Is 1 == 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 != 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 > 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 < 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 >= 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 <= 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<hr /> + +<!--- Control Structures ---> +<h1>Control Structures</h1> + +<cfset myCondition = "Test" /> + +<p>Condition to test for: "<cfoutput>#myCondition#</cfoutput>"</p> + +<cfif myCondition eq "Test"> + <cfoutput>#myCondition#. We're testing.</cfoutput> +<cfelseif myCondition eq "Production"> + <cfoutput>#myCondition#. Proceed Carefully!!!</cfoutput> +<cfelse> + myCondition is unknown +</cfif> + +<hr /> + +<!--- Loops ---> +<h1>Loops</h1> +<h2>For Loop</h2> +<cfloop from="0" to="10" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<h2>For Each Loop (Complex Variables)</h2> + +<p>Set <b>myArray3</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray3 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray3#" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<p>Set <b>myArray4</b> to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]</p> + +<cfset myArray4 = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"] /> + +<cfloop array="#myArray4#" index="s"> + <p>Index equals <cfoutput>#s#</cfoutput></p> +</cfloop> + +<h2>Switch Statement</h2> + +<p>Set <b>myArray5</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray5 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray5#" index="i"> + <cfswitch expression="#i#"> + <cfcase value="5,15,45" delimiters=","> + <p><cfoutput>#i#</cfoutput> is a multiple of 5.</p> + </cfcase> + <cfcase value="99"> + <p><cfoutput>#i#</cfoutput> is ninety-nine.</p> + </cfcase> + <cfdefaultcase> + <p><cfoutput>#i#</cfoutput> is not 5, 15, 45, or 99.</p> + </cfdefaultcase> + </cfswitch> +</cfloop> + +<hr /> + +<h1>Converting types</h1> + +<style> + table.table th, table.table td { + border: 1px solid #000000; + padding: 2px; + } + + table.table th { + background-color: #CCCCCC; + } +</style> + +<table class="table" cellspacing="0"> + <thead> + <tr> + <th>Value</th> + <th>As Boolean</th> + <th>As number</th> + <th>As date-time</th> + <th>As string</th> + </tr> + </thead> + <tbody> + <tr> + <th>"Yes"</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>"No"</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>TRUE</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>FALSE</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>Number</th> + <td>True if Number is not 0; False otherwise.</td> + <td>Number</td> + <td>See "Date-time values" earlier in this chapter.</td> + <td>String representation of the number (for example, "8").</td> + </tr> + <tr> + <th>String</th> + <td>If "Yes", True <br>If "No", False <br>If it can be converted to 0, False <br>If it can be converted to any other number, True</td> + <td>If it represents a number (for example, "1,000" or "12.36E-12"), it is converted to the corresponding number.</td> + <td>If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. <br>If it is an ODBC date, time, or timestamp (for example "{ts '2001-06-14 11:30:13'}", or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. <br>Days of the week or unusual punctuation result in an error. <br>Dashes, forward-slashes, and spaces are generally allowed.</td> + <td>String</td> + </tr> + <tr> + <th>Date</th> + <td>Error</td> + <td>The numeric value of the date-time object.</td> + <td>Date</td> + <td>An ODBC timestamp.</td> + </tr> + </tbody> +</table> + +<hr /> + +<h1>Components</h1> + +<em>Code for reference (Functions must return something to support IE)</em> + +<pre> +<cfcomponent> + <cfset this.hello = "Hello" /> + <cfset this.world = "world" /> + + <cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> + </cffunction> + + <cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> + </cffunction> + + <cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> + </cffunction> + + <cffunction name="getHello"> + <cfreturn this.hello /> + </cffunction> + + <cffunction name="getWorld"> + <cfreturn this.world /> + </cffunction> +</cfcomponent> +</pre> + +<cfset this.hello = "Hello" /> +<cfset this.world = "world" /> + +<cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> +</cffunction> + +<cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> +</cffunction> + +<cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> +</cffunction> + +<cffunction name="getHello"> + <cfreturn this.hello /> +</cffunction> + +<cffunction name="getWorld"> + <cfreturn this.world /> +</cffunction> + + +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +<b>setHello("Hola")</b> +<cfoutput><p>#setHello("Hola")#</p></cfoutput> +<b>setWorld("mundo")</b> +<cfoutput><p>#setWorld("mundo")#</p></cfoutput> +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +``` + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown new file mode 100644 index 00000000..c7f581c0 --- /dev/null +++ b/es-es/visualbasic-es.html.markdown @@ -0,0 +1,286 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +translators: + - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"] +author: Brian Martin +author_url: https://github.com/fitojb +filename: learnvisualbasic-es.vb +lang: es-es +--- + +```vb +Module Module1 + + Sub Main() + ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes + ' de que profundicemos en el tema. + ' El apóstrofo inicia una línea de comentario. + ' Para explorar este tutorial dentro del Compilador de Visual Basic, + ' he creado un sistema de navegación. + ' Dicho sistema se explicará a medida que avancemos en este + ' tutorial; gradualmente entenderás lo que significa todo. + Console.Title = ("Aprende X en Y minutos") + Console.WriteLine("NAVEGACIÓN") 'Mostrar + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Salida «Hola, mundo»") + Console.WriteLine("2. Entrada «Hola, mundo»") + Console.WriteLine("3. Calcular números enteros") + Console.WriteLine("4. Calcular números decimales") + Console.WriteLine("5. Una calculadora funcional") + Console.WriteLine("6. Uso de bucles «Do While»") + Console.WriteLine("7. Uso de bucles «For While»") + Console.WriteLine("8. Declaraciones condicionales") + Console.WriteLine("9. Selecciona una bebida") + Console.WriteLine("50. Acerca de") + Console.WriteLine("Elige un número de la lista anterior") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" 'Salida «hola, mundo» + Console.Clear() 'Limpia la consola y abre la subrutina privada + SalidaHolaMundo() 'Abre la subrutina privada nombrada + Case "2" 'Entrada «hola, mundo» + Console.Clear() + EntradaHolaMundo() + Case "3" 'Calcular números enteros + Console.Clear() + CalcularNumerosEnteros() + Case "4" 'Calcular números decimales + Console.Clear() + CalcularNumerosDecimales() + Case "5" 'Una calculadora funcional + Console.Clear() + CalculadoraFuncional() + Case "6" 'Uso de bucles «Do While» + Console.Clear() + UsoBuclesDoWhile() + Case "7" 'Uso de bucles «For While» + Console.Clear() + UsoBuclesFor() + Case "8" 'Declaraciones condicionales + Console.Clear() + DeclaracionCondicional() + Case "9" 'Declaración «If/Else» + Console.Clear() + DeclaracionIfElse() 'Selecciona una bebida + Case "50" 'Cuadro de mensaje «Acerca de» + Console.Clear() + Console.Title = ("Aprende X en Y minutos :: Acerca de") + MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + 'Uno - He usado números para guiarme por el sistema de navegación anterior + 'cuando regrese posteriormente a implementarlo. + + 'Usamos subrutinas privadas para separar distintas secciones del programa. + Private Sub SalidaHolaMundo() + 'Título de la aplicación de consola + Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos" + 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas. + 'Seguido por Console.Read(), o bien, Console.Readline() + 'Console.ReadLine() muestra la salida en la consola. + Console.WriteLine("Hola, mundo") + Console.ReadLine() + End Sub + + 'Dos + Private Sub EntradaHolaMundo() + Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos" + ' Variables + ' Los datos que introduzca un usuario deben almacenarse. + ' Las variables también empiezan por Dim y terminan por As VariableType. + + ' En este tutorial queremos conocer tu nombre y hacer que el programa + ' responda a este. + Dim nombredeusuario As String + 'Usamos «string» porque es una variable basada en texto. + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario. + Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre + Console.ReadLine() 'Muestra lo anterior. + 'El código anterior te hará una pregunta y mostrará la respuesta. + 'Entre otras variables está Integer, la cual usaremos para números enteros. + End Sub + + 'Tres + Private Sub CalcularNumerosEnteros() + Console.Title = "Calcular números enteros | Aprende X en Y minutos" + Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc + Dim a As Integer = Console.ReadLine() + Console.Write("Segundo número: ") 'Escribe otro número entero. + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Lo anterior es una calculadora sencilla + End Sub + + 'Cuatro + Private Sub CalcularNumerosDecimales() + Console.Title = "Calcular con tipo doble | Aprende X en Y minutos" + 'Por supuesto, nos gustaría sumar decimales. + 'Por ello podríamos cambiar del tipo Integer al Double. + + 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") 'Escribe el segundo número. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Este programa puede sumar 1.1 y 2.2 + End Sub + + 'Cinco + Private Sub CalculadoraFuncional() + Console.Title = "La calculadora funcional | Aprende X en Y minutos" + 'Pero si quieres que la calculadora reste, divida, multiplique y + 'sume. + 'Copia y pega lo anterior. + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + 'Mediante las líneas siguientes podremos restar, + 'multiplicar y dividir los valores a y b + Console.Write(a.ToString() + " + " + b.ToString()) + 'Queremos dar un margen izquierdo de 3 espacios a los resultados. + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + + End Sub + + 'Seis + Private Sub UsoBuclesDoWhile() + 'Igual que la subrutina privada anterior + 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?) + 'Usamos el bucle Do While porque no sabemos si el usuario quiere + 'usar el programa más de una vez. + Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos" + Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto + Do 'Comenzamos el programa con + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + 'Preguntar si el usuario quiere continuar. Desafortunadamente, + 'distingue entre mayúsculas y minúsculas. + Console.Write("¿Quieres continuar? (s / n)") + 'El programa toma la variable, la muestra y comienza de nuevo. + respuesta = Console.ReadLine + 'La orden que hará funcionar esta variable es en este caso «s» + Loop While respuesta = "s" + + End Sub + + 'Siete + Private Sub UsoBuclesFor() + 'A veces el programa debe ejecutarse solo una vez. + 'En este programa contaremos a partir de 10. + + Console.Title = "Uso de bucles «For» | Aprende X en Y minutos" + 'Declarar Variable y desde qué número debe contar en Step -1, + 'Step -2, Step -3, etc. + For i As Integer = 10 To 0 Step -1 + Console.WriteLine(i.ToString) 'Muestra el valor del contador + Next i 'Calcular el valor nuevo + Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!! + Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :) + End Sub + + 'Ocho + Private Sub DeclaracionCondicional() + Console.Title = "Declaraciones condicionales | Aprende X en Y minutos" + Dim nombredeUsuario As String = Console.ReadLine + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario. + If nombredeUsuario = "Adam" Then + Console.WriteLine("Hola, Adam") + Console.WriteLine("Gracias por crear este útil sitio web") + Console.ReadLine() + Else + Console.WriteLine("Hola, " + nombredeUsuario) + Console.WriteLine("¿Has visitado www.learnxinyminutes.com?") + Console.ReadLine() 'Termina y muestra la declaración anterior. + End If + End Sub + + 'Nueve + Private Sub DeclaracionIfElse() + Console.Title = "Declaración «If / Else» | Aprende X en Y minutos" + 'A veces es importante considerar más de dos alternativas. + 'A veces, algunas de estas son mejores. + 'Cuando esto sucede, necesitaríamos más de una declaración «if». + 'Una declaración «if» es adecuada para máquinas expendedoras. + 'En las que el usuario escribe un código (A1, A2, A3) para elegir. + 'Pueden combinarse todas las elecciones en una sola declaración «if». + + Dim seleccion As String = Console.ReadLine 'Valor de la selección + Console.WriteLine("A1. para 7Up") + Console.WriteLine("A2. para Fanta") + Console.WriteLine("A3. para Dr. Pepper") + Console.WriteLine("A4. para Coca-Cola") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("coca-cola") + Console.ReadLine() + Else + Console.WriteLine("Selecciona un producto") + Console.ReadLine() + End If + + End Sub + +End Module + +``` + +## Referencias + +Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad. + +He creado un <a href="http://www.vbbootcamp.co.uk/" Title="Tutorial de Visual Basic">tutorial de Visual Basic</a> más exhaustivo para quienes quieran saber más. + +Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa. diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown new file mode 100644 index 00000000..0267a380 --- /dev/null +++ b/fr-fr/haml-fr.html.markdown @@ -0,0 +1,156 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Thibault", "https://github.com/iTech-"] +--- + +Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage. + +Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire. + +Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes. + +$ haml fichier_entree.haml fichier_sortie.html + + +```haml +/ ------------------------------------------- +/ Indentation +/ ------------------------------------------- + +/ + A cause de l'importance de l'indentation sur la manière dont votre code sera + converti, l'indentation doit être constante à travers votre document. Un + simple changement d'indentation entrainera une erreur. En général, on utilise + deux espaces, mais ce genre de décision sur l'indentation vous appartient, du + moment que vous vous y tenez. + +/ ------------------------------------------- +/ Commentaires +/ ------------------------------------------- + +/ Ceci est un commentaire en Haml. + +/ + Pour écrire un commentaire sur plusieurs lignes, indentez votre code + commenté en le commençant par un slash + +-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier + + +/ ------------------------------------------- +/ Eléments HTML +/ ------------------------------------------- + +/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise +%body + %header + %nav + +/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci + <body> + <header> + <nav></nav> + </header> + </body> + +/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci +.balise + +/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration +%h1 Titre contenu + +/ Pour écrire du contenu sur plusieurs lignes, imbriquez le +%p + Ce paragraphe contient beaucoup de contenu qui pourrait + probablement tenir sur deux lignes séparées. + +/ + Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va + convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple + +%p + &= "Oui & oui" + +/ Produira 'Oui & oui' + +/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant != +%p + != "Voici comment écrire une balise de paragraphe <p></p>" + +/ Cela produira 'Voici comment écrire une balise de paragraphe <p></p>' + +/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe +%div.truc.machin + +/ ou en utilisant un hash de Ruby +%div{:class => 'truc machin'} + +/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash +%a{:href => '#', :class => 'machin', :title => 'Titre machin'} + +/ Pour affecter une valeur à un booléen, utilisez 'true' +%input{:selected => true} + +/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash +%div{:data => {:attribute => 'machin'}} + + +/ ------------------------------------------- +/ Insérer du Ruby +/ ------------------------------------------- + +/ + Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le + signe égal suivi du code Ruby + +%h1= livre.titre + +%p + = livre.auteur + = livre.editeur + + +/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union +- livres = ['livre 1', 'livre 2', 'livre 3'] + +/ Ceci vous permet de faire des choses géniales comme des blocs Ruby +- livre.shuffle.each_with_index do |livre, index| + %h1= livre + + if livre do + %p Ceci est un livre + +/ + Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même + pour Ruby. + L'indentation le fera pour vous. + + +/ ------------------------------------------- +/ Ruby en-ligne / Interpolation en Ruby +/ ------------------------------------------- + +/ Inclure une variable Ruby dans une ligne en utilisant #{} +%p Votre meilleur score est #{record} + + +/ ------------------------------------------- +/ Filtres +/ ------------------------------------------- + +/ + Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple + utiliser un filtre :javascript pour écrire du contenu en-ligne js + +:javascript + console.log('Ceci est la balise en-ligne <script>'); + +``` + +## Lectures complémentaires + +- [Qu'est-ce que HAML ?](http://haml.info/) - Une bonne introduction qui explique très bien les avantages d'utiliser HAML. +- [Documentation officielle](http://haml.info/docs/yardoc/file.REFERENCE.html) - Si vous souhaitez en apprendre plus et aller plus loin. diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 69f4d8f9..4e31c4bf 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -14,7 +14,7 @@ lang: fr-fr L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. -```objective_c +```objective-c // Les commentaires sur une seule ligne commencent par // /* diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown new file mode 100644 index 00000000..04d0a55d --- /dev/null +++ b/fr-fr/python3-fr.html.markdown @@ -0,0 +1,723 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Gnomino", "https://github.com/Gnomino"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des +langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. +C'est tout simplement du pseudo-code exécutable. + +L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] + +Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 + +```python + +# Un commentaire d'une ligne commence par un dièse + +""" Les chaînes de caractères peuvent être écrites + avec 3 guillemets doubles ("), et sont souvent + utilisées comme des commentaires. +""" + +#################################################### +## 1. Types de données primaires et opérateurs +#################################################### + +# On a des nombres +3 # => 3 + +# Les calculs sont ce à quoi on s'attend +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Sauf pour la division qui retourne un float (nombre à virgule flottante) +35 / 5 # => 7.0 + +# Résultats de divisions entières tronqués pour les nombres positifs et négatifs +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quand on utilise un float, le résultat est un float +3 * 2.0 # => 6.0 + +# Modulo (reste de la division) +7 % 3 # => 1 + +# Exponentiation (x**y, x élevé à la puissance y) +2**4 # => 16 + +# Forcer la priorité de calcul avec des parenthèses +(1 + 3) * 2 # => 8 + +# Les valeurs booléennes sont primitives +True +False + +# Négation avec not +not True # => False +not False # => True + +# Opérateurs booléens +# On note que "and" et "or" sont sensibles à la casse +True and False #=> False +False or True #=> True + +# Utilisation des opérations booléennes avec des entiers : +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# On vérifie une égalité avec == +1 == 1 # => True +2 == 1 # => False + +# On vérifie une inégalité avec != +1 != 1 # => False +2 != 1 # => True + +# Autres opérateurs de comparaison +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# On peut enchaîner les comparaisons +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie +# si les objets ont la même valeur. +a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] +b = a # b pointe sur a +b is a # => True, a et b pointent sur le même objet +b == a # => True, les objets a et b sont égaux +b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] +b is a # => False, a et b ne pointent pas sur le même objet +b == a # => True, les objets a et b ne pointent pas sur le même objet + +# Les chaînes (ou strings) sont créées avec " ou ' +"Ceci est une chaine" +'Ceci est une chaine aussi.' + +# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. +"Hello " + "world!" # => "Hello world!" +# On peut aussi le faire sans utiliser '+' +"Hello " "world!" # => "Hello world!" + +# On peut traîter une chaîne comme une liste de caractères +"This is a string"[0] # => 'T' + +# .format peut être utilisé pour formatter des chaînes, comme ceci: +"{} peuvent etre {}".format("Les chaînes", "interpolées") + +# On peut aussi réutiliser le même argument pour gagner du temps. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# On peut aussi utiliser des mots clés pour éviter de devoir compter. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# Si votre code doit aussi être compatible avec Python 2.5 et moins, +# vous pouvez encore utiliser l'ancienne syntaxe : +"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") + + +# None est un objet +None # => None + +# N'utilisez pas "==" pour comparer des objets à None +# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. +"etc" is None # => False +None is None # => True + +# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. +# Toutes les autres valeurs valent True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Python a une fonction print pour afficher du texte +print("I'm Python. Nice to meet you!") + +# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. +# Utilisez l'argument optionnel end pour changer ce caractère de fin. +print("Hello, World", end="!") # => Hello, World! + +# Pas besoin de déclarer des variables avant de les définir. +# La convention est de nommer ses variables avec des minuscules_et_underscores +some_var = 5 +some_var # => 5 + +# Tenter d'accéder à une variable non définie lève une exception. +# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. +une_variable_inconnue # Lève une NameError + +# Les listes permettent de stocker des séquences +li = [] +# On peut initialiser une liste pré-remplie +other_li = [4, 5, 6] + +# On ajoute des objets à la fin d'une liste avec .append +li.append(1) # li vaut maintenant [1] +li.append(2) # li vaut maintenant [1, 2] +li.append(4) # li vaut maintenant [1, 2, 4] +li.append(3) # li vaut maintenant [1, 2, 4, 3] +# On enlève le dernier élément avec .pop +li.pop() # => 3 et li vaut maintenant [1, 2, 4] +# Et on le remet +li.append(3) # li vaut de nouveau [1, 2, 4, 3] + +# Accès à un élément d'une liste : +li[0] # => 1 +# Accès au dernier élément : +li[-1] # => 3 + +# Accéder à un élément en dehors des limites lève une IndexError +li[4] # Lève une IndexError + +# On peut accéder à une intervalle avec la syntaxe "slice" +# (c'est un rang du type "fermé/ouvert") +li[1:3] # => [2, 4] +# Omettre les deux premiers éléments +li[2:] # => [4, 3] +# Prendre les trois premiers +li[:3] # => [1, 2, 4] +# Sélectionner un élément sur deux +li[::2] # =>[1, 4] +# Avoir une copie de la liste à l'envers +li[::-1] # => [3, 4, 2, 1] +# Pour des "slices" plus élaborées : +# li[debut:fin:pas] + +# Faire une copie d'une profondeur de un avec les "slices" +li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. + +# Enlever des éléments arbitrairement d'une liste +del li[2] # li is now [1, 2, 3] + +# On peut additionner des listes +# Note: les valeurs de li et other_li ne sont pas modifiées. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concaténer des listes avec "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Vérifier la présence d'un objet dans une liste avec "in" +1 in li # => True + +# Examiner la longueur avec "len()" +len(li) # => 6 + + +# Les tuples sont comme des listes mais sont immuables. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Lève une TypeError + +# Note : un tuple de taille un doit avoir une virgule après le dernier élément, +# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> + +# On peut utiliser la plupart des opérations des listes sur des tuples. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Vous pouvez décomposer des tuples (ou des listes) dans des variables +a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 +# Les tuples sont créés par défaut sans parenthèses +d, e, f = 4, 5, 6 +# Voyez comme il est facile d'intervertir deux valeurs : +e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 + + +# Créer un dictionnaire : +empty_dict = {} +# Un dictionnaire pré-rempli : +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note : les clés des dictionnaires doivent être de types immuables. +# Elles doivent être convertibles en une valeur constante pour une recherche rapide. +# Les types immuables incluent les ints, floats, strings et tuples. +invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. + +# On trouve une valeur avec [] +filled_dict["one"] # => 1 + +# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer +# de list() pour avoir une liste Note: l'ordre n'est pas garanti. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# On obtient toutes les valeurs sous forme d'un itérable avec "values()". +# Là aussi, il faut utiliser list() pour avoir une liste. +# Note : l'ordre n'est toujours pas garanti. +list(filled_dict.values()) # => [3, 2, 1] + + +# On vérifie la présence d'une clé dans un dictionnaire avec "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# L'accès à une clé non-existente lève une KeyError +filled_dict["four"] # KeyError + +# On utilise "get()" pour éviter la KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. +filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 + +# Ajouter à un dictionnaire +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # une autre méthode + +# Enlever des clés d'un dictionnaire avec del +del filled_dict["one"] # Enlever la clé "one" de filled_dict. + + +# Les sets stockent des ensembles +empty_set = set() +# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. +some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} + +# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. +invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# On peut changer un set : +filled_set = some_set + +# Ajouter un objet au set : +filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} + +# Chercher les intersections de deux sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# On fait l'union de sets avec | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# On fait la différence de deux sets avec - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# On vérifie la présence d'un objet dans un set avec in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Structures de contrôle et Itérables +#################################################### + +# On crée juste une variable +some_var = 5 + +# Voici une condition "si". L'indentation est significative en Python! +# Affiche: "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # La clause elif ("sinon si") est optionelle + print("some_var is smaller than 10.") +else: # La clause else ("sinon") l'est aussi. + print("some_var is indeed 10.") + + +""" +Les boucles "for" itèrent sur une liste +Affiche: + chien est un mammifère + chat est un mammifère + souris est un mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser format() pour interpoler des chaînes formattées + print("{} est un mammifère".format(animal)) + +""" +"range(nombre)" retourne un itérable de nombres +de zéro au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(debut, fin)" retourne un itérable de nombre +de debut à fin. +Affiche: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(debut, fin, pas)" retourne un itérable de nombres +de début à fin en incrémentant de pas. +Si le pas n'est pas indiqué, la valeur par défaut est 1. +Affiche: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + +Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Raccourci pour x = x + 1 + +# On gère les exceptions avec un bloc try/except +try: + # On utilise "raise" pour lever une erreur + raise IndexError("Ceci est une erreur d'index") +except IndexError as e: + pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. +except (TypeError, NameError): + pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. +else: # Clause optionelle des blocs try/except. Doit être après tous les except. + print("Tout va bien!") # Uniquement si aucune exception n'est levée. +finally: # Éxécuté dans toutes les circonstances. + print("On nettoie les ressources ici") + +# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offre une abstraction fondamentale : l'Iterable. +# Un itérable est un objet pouvant être traîté comme une séquence. +# L'objet retourné par la fonction range() est un itérable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable + +# On peut boucler dessus +for i in our_iterable: + print(i) # Affiche one, two, three + +# Cependant, on ne peut pas accéder aux éléments par leur adresse. +our_iterable[1] # Lève une TypeError + +# Un itérable est un objet qui sait créer un itérateur. +our_iterator = iter(our_iterable) + +# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. +# On passe à l'élément suivant avec "next()". +next(our_iterator) #=> "one" + +# Il garde son état quand on itère. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator +next(our_iterator) # Lève une StopIteration + +# On peut mettre tous les éléments d'un itérateur dans une liste avec list() +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Fonctions +#################################################### + +# On utilise "def" pour créer des fonctions +def add(x, y): + print("x est {} et y est {}".format(x, y)) + return x + y # On retourne une valeur avec return + +# Appel d'une fonction avec des paramètres : +add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 + +# Une autre manière d'appeller une fonction : avec des arguments +add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. + +# Définir une fonction qui prend un nombre variable d'arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# On peut aussi définir une fonction qui prend un nombre variable de paramètres. +def keyword_args(**kwargs): + return kwargs + +# Appelons la pour voir ce qu'il se passe : +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# On peut aussi faire les deux à la fois : +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appelant des fonctions, on peut aussi faire l'inverse : +# utiliser * pour étendre un tuple de paramètres +# et ** pour étendre un dictionnaire d'arguments. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # équivalent à foo(1, 2, 3, 4) +all_the_args(**kwargs) # équivalent à foo(a=3, b=4) +all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) + +# Retourne plusieurs valeurs (avec un tuple) +def swap(x, y): + return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. + # (Note: on peut aussi utiliser des parenthèses) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses + +# Portée des fonctions : +x = 5 + +def setX(num): + # La variable locale x n'est pas la même que la variable globale x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # la variable globale x est maintenant 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Mais aussi des fonctions anonymes +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Il y a aussi des fonctions de base +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. +# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# On utilise l'opérateur "classe" pour définir une classe +class Human: + + # Un attribut de la classe. Il est partagé par toutes les instances de la classe. + species = "H. sapiens" + + # L'initialiseur de base. Il est appelé quand la classe est instanciée. + # Note : les doubles underscores au début et à la fin sont utilisés pour + # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. + # Les méthodes (ou objets ou attributs) comme: __init__, __str__, + # __repr__ etc. sont appelés méthodes magiques. + # Vous ne devriez pas inventer de noms de ce style. + def __init__(self, name): + # Assigner l'argument à l'attribut de l'instance + self.name = name + + # Une méthode de l'instance. Toutes prennent "self" comme premier argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Une méthode de classe est partagée avec entre les instances + # Ils sont appelés avec la classe comme premier argument + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appelée sans référence à une instance ni à une classe. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantier une classe +i = Human(name="Ian") +print(i.say("hi")) # affiche "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() # => "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print(math.sqrt(16)) # => 4 + +# On peut importer des fonctions spécifiques d'un module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# On peut importer toutes les fonctions d'un module +# Attention: ce n'est pas recommandé. +from math import * + +# On peut raccourcir un nom de module +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Les modules Python sont juste des fichiers Python. +# Vous pouvez écrire les vôtres et les importer. Le nom du module +# est le nom du fichier. + +# On peut voir quels fonctions et objets un module définit +import math +dir(math) + + +#################################################### +## 7. Avancé +#################################################### + +# Les générateurs aident à faire du code paresseux (lazy) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un générateur crée des valeurs à la volée. +# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque +# itération. Cela signifie que les valeurs supérieures à 15 ne seront pas traîtées par +# double_numbers. +# Note : range est un générateur aussi. +# Créer une liste 1-900000000 prendrait beaucoup de temps +# On met un underscore à la fin d'un nom de variable normalement réservé par Python. +range_ = range(1, 900000000) +# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorateurs +# Dans cet exemple, beg enveloppe say +# Beg appellera say. Si say_please vaut True le message retourné sera changé +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # affiche Can you buy me a beer? +print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( +``` + +## Prêt pour encore plus ? + +### En ligne et gratuit (en anglais) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Livres (en anglais) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index a43edf16..c6d06361 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -208,6 +208,7 @@ sSquared.reduce (_+_) // La fonction filter prend un prédicat (une fonction de type A -> Booléen) et // sélectionne tous les éléments qui satisfont ce prédicat List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -217,6 +218,7 @@ List( // Scala a une méthode foreach définie pour certaines collections // qui prend en argument une fonction renvoyant Unit (une méthode void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique. // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus // facile pour comprendre et pour faire la parallélisation +i = 0 // La boucle do while do { println("x is still less then 10"); - x += 1 -} while (x < 10) + i += 1 +} while (i < 10) // La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. @@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com" "Les chaînes de caractères Scala sont entourées de doubles guillements" 'a' // Un caractère de Scala -'Les simples guillemets n'existent pas en Scala // Erreur +// 'Les simples guillemets n'existent pas en Scala' // Erreur "Les chaînes de caractères possèdent les méthodes usuelles de Java".length "Il y a aussi quelques méthodes extra de Scala.".reverse diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby.html.markdown new file mode 100644 index 00000000..169f2b8e --- /dev/null +++ b/hu-hu/ruby.html.markdown @@ -0,0 +1,555 @@ +--- +language: ruby +lang: hu-hu +filenev: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + translators: + - ["Zsolt Prontvai", "https://github.com/prozsolt"] +--- + +```ruby +# Ez egy komment + +=begin +Ez egy többsoros komment +Senki sem használja +Neked sem kellene +=end + +# Először is: Minden objektum + +# A számok objektumok + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Néhány alapvető számtani művelet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# A számtani művelet csak szintaktikus cukor +# az objektumon történő függvény hívásra +1.+(3) #=> 4 +10.* 5 #=> 50 + +# A speciális értékek objektumok +nil # Nincs itt semmi látnivaló +true # igaz +false # hamis + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Egyenlőség +1 == 1 #=> true +2 == 1 #=> false + +# Egyenlőtlenség +1 != 1 #=> false +2 != 1 #=> true + +# A false-on kívül, nil az egyetlen hamis érték + +!nil #=> true +!false #=> true +!0 #=> false + +# Még több összehasonlítás +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Logikai operátorok +true && false #=> false +true || false #=> true +!true #=> false + +# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb +# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak +# amíg egyikük igaz vagy hamis értékkel nem tér vissza. + +# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel +# tért vissza. +csinalj_valamit() and csinalj_valami_mast() +# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel +# tért vissza. +csinalj_valamit() or log_error() + + +# A sztringek objektumok + +'Én egy sztring vagyok'.class #=> String +"Én is egy sztring vagyok".class #=> String + +helykitolto = 'interpolációt használhatok' +"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem" +#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem" + +# A szimpla idézőjelet preferáljuk, ahol csak lehet, +# mert a dupla idézőjel extra számításokat végez. + +# Kombinálhatunk sztringeket, de nem számokkal +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# kiírás a kimenetre +puts "Írok" + +# Változók +x = 25 #=> 25 +x #=> 25 + +# Értékadás az adott értékkel tér vissza +# Ez azt jelenti, hogy használhatunk többszörös értékadást: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Konvencióból, snake_case változó neveket használj +snake_case = true + +# Leíró változó neveket használj +ut_a_projekt_gyokerehez = '/jo/nev/' +ut = '/rossz/nev/' + +# A szimbólumok (objektumok) +# A szimbólumok megváltoztathatatlan, újra felhasználható konstans, +# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják, +# hogy effektíven közvetítsünk konkrét, értelmes értékeket + +:fuggoben.class #=> Symbol + +statusz = :fuggoben + +statusz == :fuggoben #=> true + +statusz == 'fuggoben' #=> false + +statusz == :jovahagyott #=> false + +# Tömbök + +# Ez egy tömb +tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# A tömmbök különböző tipusú dolgokat tartalmazhat + +[1, 'hello', false] #=> [1, "hello", false] + +# Tömbök indexelhetőek +# Az elejéről +tomb[0] #=> 1 +tomb[12] #=> nil + +# Akárcsak a számtani műveletek [var] hozzáférés +# is csak szintaktikus cukor +# a [] függvény hívására az objektumon +tomb.[] 0 #=> 1 +tomb.[] 12 #=> nil + +# A végéről +tomb[-1] #=> 5 + +# Kezdőértékkel és hosszal +tomb[2, 3] #=> [3, 4, 5] + +# Tömb megfordítása +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Vagy tartománnyal +tomb[1..3] #=> [2, 3, 4] + +# Így adhatunk a tömbhöz +tomb << 6 #=> [1, 2, 3, 4, 5, 6] +# Vagy így +tomb.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Ellenőrízük, hogy a tömb tartalmaz egy elemet +tomb.include?(1) #=> true + +# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal +# Hash-eket kapcsos zárójellel jelöljük +hash = { 'szin' => 'zold', 'szam' => 5 } + +hash.keys #=> ['szin', 'szam'] + +# Hash-ekben könnyen kreshetünk a kulcs segítségével: +hash['szin'] #=> 'zold' +hash['szam'] #=> 5 + +# Nem létező kulcsra keresve nil-t kapunk: +hash['nincs itt semmi'] #=> nil + +# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot +# használunk kulcsnak + +uj_hash = { defcon: 3, action: true } + +uj_hash.keys #=> [:defcon, :action] + +# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben +uj_hash.has_key?(:defcon) #=> true +uj_hash.has_value?(3) #=> true + +# Tip: A tömbök és hash-ek is felsorolhatóak +# Sok közös függvényük van, akár az each, map, count, és több + +# Kontroll Struktúrák + +if true + 'ha állítás' +elsif false + 'különben ha, opcionális' +else + 'különben, szintén opcionális' +end + +for szamlalo in 1..5 + puts "iteracio #{szamlalo}" +end +#=> iteracio 1 +#=> iteracio 2 +#=> iteracio 3 +#=> iteracio 4 +#=> iteracio 5 + +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# You can also surround blocks in curly brackets: +(1..5).each { |counter| puts "iteration #{counter}" } + +# The contents of data structures can also be iterated using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +jegy = '4' + +case jegy +when '5' + puts 'Kitünő' +when '4' + puts 'Jó' +when '3' + puts 'Közepes' +when '2' + puts 'Elégsége' +when '1' + puts 'Elégtelen' +else + puts 'Alternatív értékelés, hm?' +end +#=> "Jó" + +# case-ek tartományokat is használhatnak +jegy = 82 +case jegy +when 90..100 + puts 'Hurrá!' +when 80...90 + puts 'Jó munka' +else + puts 'Megbuktál!' +end +#=> "Jó munka" + +# kivétel kezelés: +begin + # kód ami kivételt dobhat + raise NoMemoryError, 'Megtelt a memória' +rescue NoMemoryError => kivetel_valtozo + puts 'NoMemoryError-t dobott', kivetel_valtozo +rescue RuntimeError => mas_kivetel_valtozo + puts 'RuntimeError dobott most' +else + puts 'Ez akkor fut ha nem dob kivételt' +ensure + puts 'Ez a kód mindenképpen lefut' +end + +# Függvények + +def ketszeres(x) + x * 2 +end + +# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel +ketszeres(2) #=> 4 + +# Zárójelezés opcionális, ha az eredmény félreérthetetlen +ketszeres 3 #=> 6 + +ketszeres ketszeres 3 #=> 12 + +def osszeg(x, y) + x + y +end + +# Függvény argumentumait vesszővel választjuk el. +osszeg 3, 4 #=> 7 + +osszeg osszeg(3, 4), 5 #=> 12 + +# yield +# Minden függvénynek van egy implicit, opcionális block paramétere +# 'yield' kulcsszóval hívhatjuk + +def korulvesz + puts '{' + yield + puts '}' +end + +korulvesz { puts 'hello world' } + +# { +# hello world +# } + + +# Fuggvénynek átadhatunk blokkot +# "&" jelöli az átadott blokk referenciáját +def vendegek(&block) + block.call 'valami_argumentum' +end + +# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva +# Erre való a splat operátor ("*") +def vendegek(*array) + array.each { |vendeg| puts vendeg } +end + +# Osztályt a class kulcsszóval definiálhatunk +class Ember + + # Az osztály változó. Az osztály minden példánnyával megvan osztva + @@faj = 'H. sapiens' + + # Alap inicializáló + def initialize(nev, kor = 0) + # Hozzárendeli az argumentumot a "nev" példány változóhoz + @nev = nev + # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni + @kor = kor + end + + # Alap setter függvény + def nev=(nev) + @nev = nev + end + + # Alap getter függvény + def nev + @nev + end + + # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük + attr_accessor :nev + + # Getter/setter függvények egyenként is kreálhatóak + attr_reader :nev + attr_writer :nev + + # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a + # példány függvényektől + # Az osztályn hívhatóak, nem a példányon + def self.mond(uzenet) + puts uzenet + end + + def faj + @@faj + end +end + + +# Példányosítsuk az osztályt +jim = Ember.new('Jim Halpert') + +dwight = Ember.new('Dwight K. Schrute') + +# Hívjunk meg pár függvényt +jim.faj #=> "H. sapiens" +jim.nev #=> "Jim Halpert" +jim.nev = "Jim Halpert II" #=> "Jim Halpert II" +jim.nev #=> "Jim Halpert II" +dwight.faj #=> "H. sapiens" +dwight.nev #=> "Dwight K. Schrute" + +# Hívjuk meg az osztály függvényt +Ember.mond('Hi') #=> "Hi" + +# Változók szókjait az elnevezésük definiálja +# $ kezdetű változók globálisak +$var = "Én egy globális változó vagyok" +defined? $var #=> "global-variable" + +# Változók amik @-al kezdődnek példány szkópjuk van +@var = "Én egy példány változó vagyok" +defined? @var #=> "instance-variable" + +# Változók amik @@-al kezdődnek példány szkópjuk van +@@var = "Én egy osztály változó vagyok" +defined? @@var #=> "class variable" + +# Változók amik nagy betűvel kezdődnek a konstansok +Var = "Konstans vagyok" +defined? Var #=> "constant" + +# Az osztály is objetum. Tehát az osztálynak lehet példány változója +# Az osztályváltozón osztozik minden pédány és leszármazott + +# Ős osztály +class Ember + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(ertek) + @@foo = ertek + end +end + +# Leszarmazott osztály +class Dolgozo < Ember +end + +Ember.foo # 0 +Dolgozo.foo # 0 + +Ember.foo = 2 # 2 +Dolgozo.foo # 2 + +# Az osztálynak példány változóját nem látja az osztály leszármazottja. + +class Ember + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(ertek) + @bar = ertek + end +end + +class Doctor < Ember +end + +Ember.bar # 0 +Doctor.bar # nil + +module ModulePelda + def foo + 'foo' + end +end + +# Modulok include-olása a fügvényeiket az osztály példányaihoz köti. +# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti. + +class Szemely + include ModulePelda +end + +class Konyv + extend ModulePelda +end + +Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class +Szemely.new.foo # => 'foo' +Konyv.foo # => 'foo' +Konyv.new.foo # => NoMethodError: undefined method `foo' + +# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult + +module ConcernPelda + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Valami + include ConcernPelda +end + +Valami.bar # => 'bar' +Valami.qux # => NoMethodError: undefined method `qux' +Valami.new.bar # => NoMethodError: undefined method `bar' +Valami.new.qux # => 'qux' +``` + +## Egyéb források + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) diff --git a/java.html.markdown b/java.html.markdown index ba602d2e..653cc97a 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] - ["Simon Morgan", "http://sjm.io/"] - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] filename: LearnJava.java --- @@ -114,7 +115,7 @@ public class LearnJava { // but they can be initialized later. final double E; E = 2.71828; - + // Strings String fooString = "My String Is Here!"; @@ -286,6 +287,23 @@ public class LearnJava { break; } System.out.println("Switch Case Result: " + monthString); + + // Starting in Java 7 and above, switching Strings works like this: + String myAnswer = "maybe"; + switch(myAnswer){ + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. @@ -348,7 +366,7 @@ public class LearnJava { validCodes.add("FINLAND"); } - // But there's a nifty way to achive the same thing in an + // But there's a nifty way to achieve the same thing in an // easier way, by using something that is called Double Brace // Initialization. @@ -358,9 +376,9 @@ public class LearnJava { add("FINLAND"); }} - // The first brace is creating an new AnonymousInnerClass and the - // second one declares and instance initializer block. This block - // is called with the anonymous inner class is created. + // The first brace is creating a new AnonymousInnerClass and the + // second one declares an instance initializer block. This block + // is called when the anonymous inner class is created. // This does not only work for Collections, it works for all // non-final classes. @@ -368,7 +386,7 @@ public class LearnJava { } // End LearnJava class -// You can include other, non-public outer-level classes in a .java file, +// You can include other, non-public outer-level classes in a .java file, // but it is good practice. Instead split classes into separate files. @@ -389,7 +407,7 @@ class Bicycle { // Constructors are a way of creating classes // This is a constructor public Bicycle() { - // You can also call another constructor: + // You can also call another constructor: // this(1, 50, 5, "Bontrager"); gear = 1; cadence = 50; @@ -489,6 +507,7 @@ public interface Digestible { // We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { + @Override public void eat() { // ... @@ -504,6 +523,7 @@ public class Fruit implements Edible, Digestible { // interfaces. For example: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { + @Override public void InterfaceOneMethod() { } @@ -511,6 +531,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, @Override public void InterfaceTwoMethod() { } + } // Abstract Classes @@ -522,10 +543,10 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // } // Marking a class as abstract means that it contains abstract methods that must -// be defined in a child class. Similar to interfaces, abstract classes cannot -// be instantiated, but instead must be extended and the abstract methods +// be defined in a child class. Similar to interfaces, abstract classes cannot +// be instantiated, but instead must be extended and the abstract methods // defined. Different from interfaces, abstract classes can contain a mixture of -// concrete and abstract methods. Methods in an interface cannot have a body, +// concrete and abstract methods. Methods in an interface cannot have a body, // unless the method is static, and variables are final by default, unlike an // abstract class. Also abstract classes CAN have the "main" method. @@ -541,7 +562,7 @@ public abstract class Animal age = 30; } - // No need to initialize, however in an interface + // No need to initialize, however in an interface // a variable is implicitly final and hence has // to be initialized. protected int age; @@ -569,7 +590,7 @@ class Dog extends Animal // age = 30; ==> ERROR! age is private to Animal } - // NOTE: You will get an error if you used the + // NOTE: You will get an error if you used the // @Override annotation here, since java doesn't allow // overriding of static methods. // What is happening here is called METHOD HIDING. @@ -583,7 +604,7 @@ class Dog extends Animal } } -// Final Classes +// Final Classes // Final Class declaration syntax // <access-level> final <final-class-name> { @@ -592,8 +613,8 @@ class Dog extends Animal // } // Final classes are classes that cannot be inherited from and are therefore a -// final child. In a way, final classes are the opposite of abstract classes -// because abstract classes must be extended, but final classes cannot be +// final child. In a way, final classes are the opposite of abstract classes +// because abstract classes must be extended, but final classes cannot be // extended. public final class SaberToothedCat extends Animal { diff --git a/julia.html.markdown b/julia.html.markdown index 66329feb..c5089dc3 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -81,10 +81,13 @@ false # Strings are created with " "This is a string." +# Julia has several types of strings, including ASCIIString and UTF8String. +# More on this in the Types section. + # Character literals are written with ' 'a' -# A string can be indexed like an array of characters +# Some strings can be indexed like an array of characters "This is a string"[1] # => 'T' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). @@ -314,7 +317,7 @@ end # For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. +# Iterable types include Range, Array, Set, Dict, and AbstractString. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings @@ -537,6 +540,17 @@ subtypes(Number) # => 6-element Array{Any,1}: # Real subtypes(Cat) # => 0-element Array{Any,1} +# AbstractString, as the name implies, is also an abstract type +subtypes(AbstractString) # 8-element Array{Any,1}: + # Base.SubstitutionString{T<:AbstractString} + # DirectIndexString + # RepString + # RevString{T<:AbstractString} + # RopeString + # SubString{T<:AbstractString} + # UTF16String + # UTF8String + # Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed @@ -546,17 +560,21 @@ super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any # All of these type, except for Int64, are abstract. +typeof("fire") # => ASCIIString +super(ASCIIString) # => DirectIndexString +super(DirectIndexString) # => AbstractString +# Likewise here with ASCIIString # <: is the subtyping operator type Lion <: Cat # Lion is a subtype of Cat mane_color - roar::String + roar::AbstractString end # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type -Lion(roar::String) = Lion("green",roar) +Lion(roar::AbstractString) = Lion("green",roar) # This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther is also a subtype of Cat diff --git a/latex.html.markdown b/latex.html.markdown new file mode 100644 index 00000000..146e8d45 --- /dev/null +++ b/latex.html.markdown @@ -0,0 +1,231 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +filename: learn-latex.tex +--- +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a "What You See Is What You Get" word processing software like +% MS Word, or OpenOffice Writer + +% Every Latex command starts with a backslash (\) + +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +% The options for the document appear in the [] brackets. In this case +% it specifies we want to use 12pt font. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% If you want to include graphics, colored text, or +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page for us. +\maketitle + +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in the document classes article and report. +\begin{abstract} + LaTex documentation written as LaTex! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. +\section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX! + +\section{Another section} +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} % Subsections are also intuitive. +I think we need another one + +\subsubsection{Pythagoras} +Much better now. +\label{subsec:pythagoras} + +% By using the asterisk we can suppress Latex's inbuilt numbering. +% This works for other Latex commands as well. +\section*{This is an unnumbered section} +However not all sections have to be numbered! + +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the source code. \\ + +\section{Lists} +Lists are one of the easiest things to create in Latex! I need to go shopping +tomorrow, so let's make a grocery list. +\begin{enumerate} % This creates an "enumerate" environment. + % \item tells the enumerate to increment + \item Salad. + \item 27 watermelon. + \item A single jackrabbit. + % we can even override the item number by using [] + \item[how many?] Medium sized squirt guns. + + Not a list item, but still part of the enumerate. + +\end{enumerate} % All environments must have an end. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic articles or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +Math has many symbols, far beyond what you can find on a keyboard; +Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. +% We can enter math-mode from text mode with the $ signs. +% The opposite also holds true. Variable can also be rendered in math-mode. + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +I haven't found a Greek letter that yet that Latex doesn't know about! + +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ \\ + +We can also insert equations in an "equation environment." + +% Display math with the equation 'environment' +\begin{equation} % enters math-mode + c^2 = a^2 + b^2. + \label{eq:pythagoras} % for referencing +\end{equation} % all \begin statements must have an end statement + +We can then reference our new equation! +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +figures, equations, sections, etc. + +Summations and Integrals are written with sum and int commands: + +% Some latex compilers will complain if there are blank lines +% In an equation environment. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definitely have to lookup the placement options each time. + +\begin{figure}[H] % H here denoted the placement option. + \centering % centers the figure on the page + % Inserts a figure scaled to 0.8 the width of the page. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Please use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Table} +We can also insert Tables in the same way as figures. + +\begin{table}[H] + \caption{Caption for the Table.} + % the {} arguments below describe how each row of the table is drawn. + % Again, I have to look these up. Each. And. Every. Time. + \begin{tabular}{c|cc} + Number & Last Name & First Name \\ % Column rows are separated by $ + \hline % a horizontal line + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Coming soon + +\section{Getting Latex to not compile something (i,e, Source Code)} +Let's say we want to include some code into our Latex document, +we would then need Latex to not try and interpret that text and +instead just print it to the document. We do this we a verbatim +environment. + +% There are other packages that exist (i.e. minty, lstlisting, etc.) +% but verbatim is the bare-bones basic one. +\begin{verbatim} + print("Hello World!") + a%b; % look! We can use % signs in verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +and look at the glorious glory that is a Latex pdf. +(yes, this document actually does compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} + \item Write the document in plain text (the "source code"). + \item Compile source code to produce a pdf. + The compilation step looks something like this (in Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +You write all your formatting information in plain text in Step 1. +The compilation part in Step 2 takes care of producing the document in the +format you defined in Step 1. + +\section{End} + +That's all for now! + +% end the document +\end{document} +``` +## More on LaTeX + +* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 89901308..cf6bf780 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -13,7 +13,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective_c +```objective-c // Single-line comments start with // /* diff --git a/perl.html.markdown b/perl.html.markdown index 4e172406..1b86f410 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -102,6 +102,8 @@ for (@elements) { print; } +# the Perlish post-condition way again +print for @elements; #### Regular expressions diff --git a/perl6.html.markdown b/perl6.html.markdown index 43327edb..0f015b45 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -75,7 +75,7 @@ say @array; #=> a 6 b # except they get "flattened" (hash context), removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys get auto-quoted +my %hash = foo => "bar", # keys get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = <key1 value1 key2 value2>; # you can also create a hash @@ -96,7 +96,6 @@ say %hash<key2>; # If it's a string, you can actually use <> # (`{key1}` doesn't work, as Perl6 doesn't have barewords) ## * Subs (subroutines, or functions in most other languages). -# Stored in variable, they use `&`. sub say-hello { say "Hello, world" } sub say-hello-to(Str $name) { # You can provide the type of an argument @@ -107,8 +106,8 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` if I don't have an argument passed, - or I'll return my argument"; + say "I might return `(Any)` (Perl's "null"-like value) if I don't have + an argument passed, or I'll return my argument"; $arg; } with-optional; # returns Any @@ -125,7 +124,7 @@ hello-to('You'); #=> Hello, You ! ## You can also, by using a syntax akin to the one of hashes (yay unified syntax !), ## pass *named* arguments to a `sub`. -# They're optional, and will default to "Any" (Perl's "null"-like value). +# They're optional, and will default to "Any". sub with-named($normal-arg, :$named) { say $normal-arg + $named; } @@ -162,7 +161,7 @@ named-def; #=> 5 named-def(def => 15); #=> 15 # Since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello`. +# you need "&" in the name to store `say-hello` in a variable. my &s = &say-hello; my &other-s = sub { say "Anonymous function !" } @@ -173,8 +172,8 @@ sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything els say @rest.join(' / ') ~ " !"; } say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume - # the parameter before. + # Note that the splat (the *) did not + # consume the parameter before. ## You can call a function with an array using the # "argument list flattening" operator `|` @@ -380,7 +379,9 @@ say join(' ', @array[-> $n { 15..$n }]); # You can use that in most places you'd expect, even assigning to an array my @numbers = ^20; -my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99 + +# Here numbers increase by "6"; more on `...` operator later. +my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99; @numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, # only the 15 needed values will be calculated. say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87 @@ -525,7 +526,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # The constructs for declaring types are "class", "role", # which you'll see later. -# For now, let us examinate "subset": +# For now, let us examine "subset": # a "subset" is a "sub-type" with additional checks. # For example: "a very big integer is an Int that's greater than 500" # You can specify the type you're subtyping (by default, Any), @@ -608,27 +609,26 @@ sub foo { bar(); # call `bar` in-place } sub bar { - say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, + say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s, # even though the blocks aren't nested (they're call-nested). #=> 1 } ### Object Model -## Perl 6 has a quite comprehensive object model # You declare a class with the keyword `class`, fields with `has`, -# methods with `method`. Every field to private, and is named `$!attr`, -# but you have `$.` to get a public (immutable) accessor along with it. -# (using `$.` is like using `$!` plus a `method` with the same name) +# methods with `method`. Every attribute that is private is named `$!attr`. +# Immutable public attributes are named `$.attr` +# (you can make them mutable with `is rw`) -# (Perl 6's object model ("SixModel") is very flexible, +# Perl 6's object model ("SixModel") is very flexible, # and allows you to dynamically add methods, change semantics, etc ... # (this will not be covered here, and you should refer to the Synopsis). class A { has $.field; # `$.field` is immutable. # From inside the class, use `$!field` to modify it. - has $.other-field is rw; # You can obviously mark a public field `rw`. + has $.other-field is rw; # You can mark a public attribute `rw`. has Int $!private-field = 10; method get-value { @@ -656,7 +656,6 @@ $a.other-field = 10; # This, however, works, because the public field # is mutable (`rw`). ## Perl 6 also has inheritance (along with multiple inheritance) -# (though considered a misfeature by many) class A { has $.val; @@ -751,7 +750,7 @@ fail "foo"; # We're not trying to access the value, so no problem. try { fail "foo"; CATCH { - default { say "It threw because we try to get the fail's value!" } + default { say "It threw because we tried to get the fail's value!" } } } @@ -763,7 +762,7 @@ try { ### Packages # Packages are a way to reuse code. Packages are like "namespaces", and any # element of the six model (`module`, `role`, `class`, `grammar`, `subset` -# and `enum`) are actually packages. (Packages are the lowest common denomitor) +# and `enum`) are actually packages. (Packages are the lowest common denominator) # Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. # You usually don't use packages directly: you use `class Package::Name::Here;`, @@ -773,7 +772,7 @@ module Hello::World { # Bracketed form # that can be redeclared as something else later. # ... declarations here ... } -module Parse::Text; # file-scoped form +unit module Parse::Text; # file-scoped form grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } @@ -797,10 +796,8 @@ my $actions = JSON::Tiny::Actions.new; # You've already seen `my` and `has`, we'll now explore the others. ## * `our` (happens at `INIT` time -- see "Phasers" below) -# Along with `my`, there are several others declarators you can use. -# The first one you'll want for the previous part is `our`. +# It's like `my`, but it also creates a package variable. # (All packagish things (`class`, `role`, etc) are `our` by default) -# it's like `my`, but it also creates a package variable: module Foo::Bar { our $n = 1; # note: you can't put a type constraint on an `our` variable our sub inc { @@ -829,7 +826,7 @@ constant why-not = 5, 15 ... *; say why-not[^5]; #=> 5 15 25 35 45 ## * `state` (happens at run time, but only once) -# State variables are only executed one time +# State variables are only initialized one time # (they exist in other langages such as C as `static`) sub fixed-rand { state $val = rand; @@ -862,7 +859,7 @@ for ^5 -> $a { ## * Compile-time phasers BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } -CHECK { say "[*] Runs at compile time, instead as late as possible, only once" } +CHECK { say "[*] Runs at compile time, as late as possible, only once" } ## * Run-time phasers INIT { say "[*] Runs at run time, as soon as possible, only once" } @@ -870,10 +867,13 @@ END { say "Runs at run time, as late as possible, only once" } ## * Block phasers ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } -LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." } +LEAVE { say "Runs everytime you leave a block, even when an exception + happened. Repeats on loop blocks." } -PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } -POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } +PRE { say "Asserts a precondition at every block entry, + before ENTER (especially useful for loops)" } +POST { say "Asserts a postcondition at every block exit, + after LEAVE (especially useful for loops)" } ## * Block/exceptions phasers sub { @@ -891,12 +891,12 @@ for ^5 { ## * Role/class phasers COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" } -# They allow for cute trick or clever code ...: -say "This code took " ~ (time - CHECK time) ~ "s to run"; +# They allow for cute tricks or clever code ...: +say "This code took " ~ (time - CHECK time) ~ "s to compile"; # ... or clever organization: sub do-db-stuff { - ENTER $db.start-transaction; # New transaction everytime we enter the sub + $db.start-transaction; # start a new transaction KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } @@ -1020,7 +1020,7 @@ sub circumfix:<[ ]>(Int $n) { $n ** $n } say [5]; #=> 3125 - # circumfix is around. Again, not whitespace. + # circumfix is around. Again, no whitespace. sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is @@ -1052,9 +1052,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # Basically, they're operators that apply another operator. ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and +# It's a prefix meta-operator that takes a binary function and # one or many lists. If it doesn't get passed any argument, -# it either return a "default value" for this operator +# it either returns a "default value" for this operator # (a meaningless value) or `Any` if there's none (examples below). # # Otherwise, it pops an element from the list(s) one at a time, and applies @@ -1089,7 +1089,7 @@ say [[&add]] 1, 2, 3; #=> 6 # This one is an infix meta-operator than also can be used as a "normal" operator. # It takes an optional binary function (by default, it just creates a pair), # and will pop one value off of each array and call its binary function on these -# until it runs out of elements. It runs the an array with all these new elements. +# until it runs out of elements. It returns an array with all of these new elements. (1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array 1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function @@ -1109,8 +1109,7 @@ say [[&add]] 1, 2, 3; #=> 6 # (and might include a closure), and on the right, a value or the predicate # that says when to stop (or Whatever for a lazy infinite list). my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, - # because Perl 6 can't figure out the end +#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element # (the iteration when the predicate matches). my @list = 1, 3, 9 ... * > 30; # you can use a predicate @@ -1222,7 +1221,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) # they use a more perl6-ish syntax: say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa' # You can use ranges: -say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou' +say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae' # Just like in normal regexes, if you want to use a special character, escape it # (the last one is escaping a space) say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !' @@ -1244,7 +1243,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # The previous line returns `True`. -# We match the "abc" 1 or more time (the `+` was applied to the group). +# We match the "ABC" 1 or more time (the `+` was applied to the group). # But this does not go far enough, because we can't actually get back what # we matched. @@ -1287,10 +1286,12 @@ say $/[0][0].Str; #=> ~ # This stems from a very simple fact: `$/` does not contain strings, integers or arrays, # it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods. -# (but you can also just use `match<key>` for hash access and `match[idx]` for array access) +# (but you can also just use `match<key>` for hash access +# and `match[idx]` for array access) say $/[0].list.perl; #=> (Match.new(...),).list - # We can see it's a list of Match objects. Those contain a bunch of infos: - # where the match started/ended, the "ast" (see actions later), etc. + # We can see it's a list of Match objects. Those contain + # a bunch of infos: where the match started/ended, + # the "ast" (see actions later), etc. # You'll see named capture below with grammars. ## Alternatives - the `or` of regexps @@ -1328,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. -# It's very powerful, because Perl 6 actually parses the argument +# It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) # and will even go as far as to autogenerate a `--help` sub MAIN($name) { say "Hello, $name !" } @@ -1346,7 +1347,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... } multi MAIN('remove', $key) { ... } multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # This produces: -# $ perl 6 cli.pl +# $ perl6 cli.pl # Usage: # t.pl [--replace] add <key> <value> # t.pl remove <key> diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown new file mode 100644 index 00000000..dbc0c25c --- /dev/null +++ b/pt-br/clojure-macros-pt.html.markdown @@ -0,0 +1,154 @@ +--- +language: clojure +filename: learnclojure-pt.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Raphael Bezerra do Nascimento"] +lang: pt-br +--- + +Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +do Clojure lhe dá acesso a toda a extensão da linguagem +para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem +às suas necessidades. + +Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas +quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado. + +Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em +[Clojure em Y Minutos](/docs/clojure/). + +```clojure +;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa +;; ser avaliada como codigo Clojure. +;; +;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1. +;; +;; Note que a chamada deve utilizar aspas simples. +(macroexpand '(my-first-macro)) +;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hello World") + +;; Você pode avaliar o resultad de macroexpand diretamente: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; mas você deve usar esse mais suscinto, sintax como de função: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta +;; para criar listas nas suas macros: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Note que reverse não é mais uma função objeto, mas um simbolo. + +;; Macros podem ter argumentos. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o +;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples +;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo. +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@ +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Lembrar o do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso. +;; caso contrario, retorna nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;;s Para evitar isso, use gensym para receber um identificador unico +(gensym 'x) ; -> x1281 (ou outra coisa) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente +(defmacro define-x-hygenically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygenically) ; -> (2) +(list x) ; -> (4) + +;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco +;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida) +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Podemos testar isso imediatamente, sem criar uma macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação +(defmacro inline-2 [form] + (inline-2-helper form))) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com / + +### Leitura adicional + +Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Documentos oficiais +[http://clojure.org/macros](http://clojure.org/macros) + +Quando utilizar macros? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown new file mode 100644 index 00000000..a4c1c02b --- /dev/null +++ b/pt-pt/scala-pt.html.markdown @@ -0,0 +1,651 @@ +--- +language: Scala +filename: learnscala-pt.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["João Costa", "http://joaocosta.eu"] +lang: pt-pt +--- + +Scala - a linguagem escalável + +```scala + +/* + Prepare tudo: + + 1) Faça Download do Scala - http://www.scala-lang.org/downloads + 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na + variável de ambiente `PATH` + 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer: + + scala> + + Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete). + Pode escrever qualquer expressão de Scala e o resultado será imprimido. + Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já, + vamos começar com os básicos. + +*/ + + +///////////////////////////////////////////////// +// 1. Basicos +///////////////////////////////////////////////// + +// Uma linha de comentários é marcada com duas barras + +/* + Comentários de multiplas linhas, como se pode ver neste exemplo, são assim. +*/ + +// Imprimir, forçando uma nova linha no final +println("Hello world!") +println(10) + +// Imprimir, sem forçar uma nova linha no final +print("Hello world") + +// Valores são declarados com var ou val. +// As declarações val são imutáveis, enquanto que vars são mutáveis. +// A immutabilidade é uma propriedade geralmente vantajosa. +val x = 10 // x é agora 10 +x = 20 // erro: reatribuição de um val +var y = 10 +y = 20 // y é agora 12 + +/* + Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima + não especificamos um tipo. Isto é devido a uma funcionalidade chamada + inferência de tipos. Na maior parte dos casos, o compilador de scala consegue + inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre. + Podemos declarar o tipo de uma variável da seguinte forma: +*/ +val z: Int = 10 +val a: Double = 1.0 + +// Note a conversão automática de Int para Double: o resultado é 10.0, não 10 +val b: Double = 10 + +// Valores booleanos +true +false + +// Operações booleanas +!true // false +!false // true +true == false // false +10 > 5 // true + +// A matemática funciona da maneira habitual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +// Avaliar expressões na REPL dá o tipo e valor do resultado + +1 + 7 + +/* A linha acima resulta em: + + scala> 1 + 7 + res29: Int = 8 + + Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com + o valor 8. + + Note que "res29" é um nome de uma variavel gerado sequencialmente para + armazenar os resultados das expressões que escreveu, por isso o resultado + pode ser ligeiramente diferente. +*/ + +"Strings em scala são rodeadas por aspas" +'a' // Um caracter de Scala +// 'Strings entre plicas não existem' <= Isto causa um erro + +// Strings tem os métodos de Java habituais definidos +"olá mundo".length +"olá mundo".substring(2, 6) +"olá mundo".replace("á", "é") + +// Para além disso, também possuem métodos de Scala. +// Ver: scala.collection.immutable.StringOps +"olá mundo".take(5) +"olá mundo".drop(5) + +// Interpolação de Strings: repare no prefixo "s" +val n = 45 +s"Temos $n maçãs" // => "Temos 45 maçãs" + +// Expressões dentro de Strings interpoladas também são possíveis +val a = Array(11, 9, 6) +s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos." +s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs." +s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4" + +// Strings interpoladas são formatadas com o prefixo "f" +f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25" +f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454" + +// Strings prefixadas com "raw" ignoram caracteres especiais +raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r." + +// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string: +"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown"" + +// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas +val html = """<form id="daform"> + <p>Carrega aqui, Zé</p> + <input type="submit"> + </form>""" + + +///////////////////////////////////////////////// +// 2. Funções +///////////////////////////////////////////////// + +// Funções são definidas como: +// +// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... } +// +// Se vem de linugagens mais tradicionais, repare na omissão da palavra +// return keyword. Em Scala, a ultima expressão de um bloco é o seu +// valor de retorno +def somaQuadrados(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// As { } podem ser omitidas se o corpo da função for apenas uma expressão: +def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y + +// A sintaxe para chamar funções deve ser familiar: +somaQuadrados(3, 4) // => 25 + +// Na maior parte dos casos (sendo funções recursivas a principal excepção), o +// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos +// é aplicada aos valores de retorno +def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int + +// Funções podem ter parâmetros por omissão: +def somaComOmissão(x: Int, y: Int = 5) = x + y +somaComOmissão(1, 2) // => 3 +somaComOmissão(1) // => 6 + + +// Funções anónimas são definidas da seguinte forma: +(x: Int) => x * x + +// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido +// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma +// funão que recebe Int e retorna Int. +val quadrado: Int => Int = x => x * x + +// Funcões anónimas são chamadas como funções normais: +quadrado(10) // => 100 + +// Se cada argumento de uma função anónima for usado apenas uma vez, existe +// uma forma ainda mais curta de os definir. Estas funções anónumas são +// extremamente comuns, como será visto na secção sobre estruturas de dados. +val somaUm: Int => Int = _ + 1 +val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3) + +somaUm(5) // => 6 +somaEstranha(2, 4) // => 16 + + +// O código return existe em Scala, mas apenas retorna do def mais interior +// que o rodeia. +// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros. +// Não tem qualquer efeito em funções anónimas, por exemplo: +def foo(x: Int): Int = { + val funcAnon: Int => Int = { z => + if (z > 5) + return z // Esta linha faz com que z seja o retorno de foo! + else + z + 2 // Esta linha define o retorno de funcAnon + } + funcAnon(x) // Esta linha define o valor de retorno de foo +} + + +///////////////////////////////////////////////// +// 3. Controlo de fluxo +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach(println) + +r foreach println +// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as +// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis + +(5 to 1 by -1) foreach (println) + +// Ciclos while +var i = 0 +while (i < 10) { println("i " + i); i += 1 } + +while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê? + +i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico - + // executa sequencialmente enquanto muda uma variável. Ciclos while são + // rápidos, por vezes até mais que ciclos de Java, mas combinadores e + // compreensões (usados anteriormente) são mais fáceis de entender e + // paralelizar + +// Um ciclo do while +i = 0 +do { + println("i ainda é menor que 10") + i += 1 +} while (i < 10) + +// A forma idiomática em Scala de definir acções recorrentes é através de +// recursão em cauda. +// Funções recursivas necessitam de um tipo de retorno definido explicitamente. +// Neste caso, é Unit. +def mostraNumerosEntre(a: Int, b: Int): Unit = { + print(a) + if (a < b) + mostraNumerosEntre(a + 1, b) +} +mostraNumerosEntre(1, 14) + + +// Condicionais + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. Estruturas de dados +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Lança uma excepção + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Lança uma excepção + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Veja a documentação de mapas de scala em - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * e verifique que a consegue aceder + */ + + +// Tuplos + +(1, 2) + +(4, 3, 2) + +(1, 2, "três") + +(a, 2, "três") + +// Porquê ter isto? +val divideInts = (x: Int, y: Int) => (x / y, x % y) + +divideInts(10, 3) // A função divideInts returna o resultado e o resto + +// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice +// (começado em 1) do elemento +val d = divideInts(10, 3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Programação Orientada a Objectos +///////////////////////////////////////////////// + +/* + Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples + (valores, funções, etc). Estas expressões são suficientes para executar no + interpretador da linha de comandos para testes rápidos, mas não podem existir + isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um + ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas + construções de topo permitidas são: + + - object + - class + - case class + - trait + + Vamos agora explicar o que são: +*/ + +// Classes são semelhantes a classes noutras linguagens. Os argumentos do +// construtor são declarados após o nome da classe, sendo a inicialização feita +// no corpo da classe. +class Cão(rc: String) { + // Código de construção + var raça: String = rc + + // Define um método chamado "ladra", que retorna uma String + def ladra = "Woof, woof!" + + // Valores e métodos são assumidos como públicos, mas é possivel usar + // os códigos "protected" and "private". + private def dormir(horas: Int) = + println(s"Vou dormir por $horas horas") + + // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima + // linha, a classe Cão é declarada como abstracta + // abstract class Cão(...) { ... } + // def persegue(oQue: String): String +} + +val oMeuCão = new Cão("greyhound") +println(oMeuCão.raça) // => "greyhound" +println(oMeuCão.ladra) // => "Woof, woof!" + + +// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum +// que classes de Scala possuam um "objecto companheiro", onde o comportamento +// por instância é capturado nas classes, equanto que o comportamento +// relacionado com todas as instancias dessa classe ficam no objecto. +// A diferença é semelhante a métodos de classes e métodos estáticos noutras +// linguagens. Note que objectos e classes podem ter o mesmo nome. +object Cão { + def raçasConhecidas = List("pitbull", "shepherd", "retriever") + def criarCão(raça: String) = new Cão(raça) +} + + +// Case classes são classes com funcionalidades extra incluidas. Uma questão +// comum de iniciantes de scala é quando devem usar classes e quando devem usar +// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se +// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes +// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal +// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos +// métods, sendo que estes raramente possuem efeitos secundários. +case class Pessoa(nome: String, telefone: String) + +// Cria uma nova instancia. De notar que case classes não precisam de "new" +val jorge = Pessoa("Jorge", "1234") +val cátia = Pessoa("Cátia", "4567") + +// Case classes trazem algumas vantagens de borla, como acessores: +jorge.telefone // => "1234" + +// Igualdade por campo (não é preciso fazer override do .equals) +Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false + +// Cópia simples +// outroJorge == Person("jorge", "9876") +val outroJorge = jorge.copy(telefone = "9876") + +// Entre outras. Case classes também suportam correspondência de padrões de +// borla, como pode ser visto de seguida. + + +// Traits em breve! + + +///////////////////////////////////////////////// +// 6. Correspondência de Padrões +///////////////////////////////////////////////// + +// A correspondência de padrões é uma funcionalidade poderosa e bastante +// utilizada em Scala. Eis como fazer correspondência de padrões numa case class: +// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de +// breaks, a computação termina no primeiro sucesso. + +def reconhecePessoa(pessoa: Pessoa): String = pessoa match { + // Agora, especifique os padrões: + case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel + case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel + case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel +} + +val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo. + +// A correspondência de padrões pode parecer familiar aos switches em linguagens +// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer +// correspondências com muito mais: +def correspondeTudo(obj: Any): String = obj match { + // Pode-se corresponder valores: + case "Olá mundo" => "Recebi uma string Olá mundo." + + // Corresponder por tipo: + case x: Double => "Recebi um Double: " + x + + // Corresponder tendo em conta condições especificas: + case x: Int if x > 10000 => "Recebi um número bem grande!" + + // Fazer correspondências com case classes (visto anteriormente): + case Pessoa(nome, tel) => s"Recebi o contacto para $nome!" + + // Fazer correspondência com expressões regulares: + case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio" + + // Corresponder tuplos: + case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c" + + // Corresponder estruturas de dados: + case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c" + + // Combinar padrões: + case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo" +} + +// Na realidade, é possível fazer correspondência com qualquer objecto que +// defina o método "unapply". Esta funcionalidade é tão poderosa que permite +// definir funções sob a forma de padrões: +val funcPaddrao: Pessoa => String = { + case Pessoa("Jorge", tel) => s"Número do Jorge: $tel" + case Pessoa(nome, tel) => s"Número de alguém: $tel" +} + + +///////////////////////////////////////////////// +// 7. Programação Funcional +///////////////////////////////////////////////// + +// Scala permite que funções e métodos retornem, ou recebam como parámetros, +// outras funções ou métodos + +val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int +List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento + +// Funções anónimas também podem ser usadas +List(1, 2, 3) map (x => x + 10) + +// Sendo que o símbolo _ também pode ser usado se a função anónima só receber +// um argumento. Este fica com o valor da variável +List(1, 2, 3) map (_ + 10) + +// Se tanto o bloco como a função apenas receberem um argumento, o próprio +// _ pode ser omitido +List("Dom", "Bob", "Natalia") foreach println + + +// Combinadores + +s.map(quadrado) + +val sQuadrado = s.map(quadrado) + +sQuadrado.filter(_ < 10) + +sQuadrado.reduce (_+_) + +// O método filter recebe um predicado (uma função de A => Boolean) e escolhe +// todos os elementos que satisfazem o predicado +List(1, 2, 3) filter (_ > 2) // List(3) +case class Pessoa(nome: String, idade: Int) +List( + Pessoa(nome = "Dom", idade = 23), + Pessoa(nome = "Bob", idade = 30) +).filter(_.idade > 25) // List(Pessoa("Bob", 30)) + + +// O método foreach recebe uma função de A => Unit, executando essa função em +// cada elemento da colecção +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// Compreensões For + +for { n <- s } yield quadrado(n) + +val nQuadrado2 = for { n <- s } yield quadrado(n) + +for { n <- nQuadrado2 if n < 10 } yield n + +for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado + +/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto + que uma compreensão define a relação entre dois conjuntos de dados. */ + + +///////////////////////////////////////////////// +// 8. Implicitos +///////////////////////////////////////////////// + +/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito + * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem + * resistir a tentação de usá-los até que compreendam não só como funcionam, + * mas também as melhores práticas. Apenas incluimos esta secção no tutorial + * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas + * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve + * para compreender como trabalhar com implicitos, não como declará-los. +*/ + +// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como +// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5 +// nestes exemplos + +implicit val oMeuIntImplicito = 100 +implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça) + +// Por si só, a palavra implicit não altera o comportamento de um valor, sendo +// que estes podem ser usados da forma habitual. +oMeuIntImplicito + 2 // => 102 +aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull" + +// A diferença é que estes valores podem ser utilizados quando outro pedaço de +// código "necessite" de uma valor implicito. Um exemplo são argumentos +// implicitos de funções: +def enviaCumprimentos(aQuem: String)(implicit quantos: Int) = + s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!" + +// Se dermos um valor a "quantos", a função comporta-se normalmente +enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!" + +// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é +// usado, neste caso, "oMeuInteiroImplicito" +enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!" + +// Parâmentros implicitos de funções permitem-nos simular classes de tipos de +// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação. +// As seguintes linhas representam a mesma coisa +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... + + +// Outra situação em que o compilador prouca um implicito é se encontrar uma +// expressão +// obj.método(...) +// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma +// conversão implicita A => B, onde A é o tipo de obj, e B possui um método +// chamado "método", a conversão é aplicada. Ou seja, tendo +// aMinhaFunçãoImplicita definida, podemos dizer +"Retriever".raça // => "Golden Retriever" +"Sheperd".ladra // => "Woof, woof!" + +// Neste caso, a String é primeiro convertida para Cão usando a nossa funão, +// sendo depois chamado o método apropriado. Esta é uma funcionalidade +// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade, +// ao definir a função implicita, o compilador deve lançar um aviso a insisitir +// que só deve definir a função se souber o que está a fazer. + + +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// + +// Importar coisas +import scala.collection.immutable.List + +// Importar todos os "sub pacotes" +import scala.collection.immutable._ + +// Importar multiplas classes numa linha +import scala.collection.immutable.{List, Map} + +// Renomear uma classe importada usando '=>' +import scala.collection.immutable.{List => ImmutableList} + +// Importar todas as classes excepto algumas. Set e Map são excluidos: +import scala.collection.immutable.{Map => _, Set => _, _} + +// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala +// com um método main: +object Aplicação { + def main(args: Array[String]): Unit = { + // código aqui. + } +} + +// Ficheiros podem conter várias classes o objectos. Compilar com scalac + + + + +// Input e output + +// Ler um ficheiro linha a linha +import scala.io.Source +for(linha <- Source.fromFile("ficheiro.txt").getLines()) + println(linha) + +// Escrever um ficheiro usando o PrintWriter de Java +val writer = new PrintWriter("ficheiro.txt") +writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator) +writer.write("Outra linha aqui" + util.Properties.lineSeparator) +writer.close() + +``` + +## Mais recursos + +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/python3.html.markdown b/python3.html.markdown index cd1a83cc..5a992b54 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -569,8 +569,8 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] #################################################### -# We subclass from object to get a class. -class Human(object): +# We use the "class" operator to get a class +class Human: # A class attribute. It is shared by all instances of this class species = "H. sapiens" diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index ddff2e5c..8eac4ddb 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -17,7 +17,7 @@ Cocoa Touch. Он является объектно-ориентированным языком программирования общего назначения, который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. -```objective_c +```objective-c // Однострочные комментарии начинаются с // /* diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 53b2f916..5672aa90 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["SlaF", "https://github.com/SlaF"] + - ["Corpsee", "https://github.com/corpsee"] lang: ru-ru filename: learnphp-ru.php --- @@ -14,8 +15,8 @@ filename: learnphp-ru.php ```php <?php // PHP код должен быть заключен в теги <?php -// Если ваш файл содержит только PHP код, то можно -// пропустить закрывающийся ?> +// Если ваш файл содержит только PHP-код, то можно +пропустить закрывающий ?> // А так начинаются комментарии @@ -30,10 +31,10 @@ filename: learnphp-ru.php print('Hello '); // Напечатать "Hello " без перевода строки // () необязательно применять для print и echo -echo "World\n"; // Печатать "World" и перейти на новую строку. +echo "World\n"; // Напечатать "World" и перейти на новую строку. // (все утверждения должны заканчиваться ;) -// Любые символы за пределами закрывающегося тега выводятся автоматически: +// Любые символы за пределами закрывающего тега выводятся автоматически: ?> Hello World Again! <?php @@ -46,7 +47,7 @@ Hello World Again! // Переменные начинаются с символа $. // Правильное имя переменной начинается с буквы или знака подчеркивания, // и может содержать любые цифры, буквы, или знаки подчеркивания. -// Не рекомендуется использовать кирилические символы в именах (прим. пер.) +// Не рекомендуется использовать кириллические символы в именах (прим. пер.) // Логические значения нечувствительны к регистру $boolean = true; // или TRUE или True @@ -56,7 +57,7 @@ $boolean = false; // или FALSE или False $int1 = 12; // => 12 $int2 = -12; // => -12- $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) -$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число) +$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) // Дробные числа $float = 1.234; @@ -126,7 +127,7 @@ echo 'This outputs '.FOO; // Все массивы в PHP - это ассоциативные массивы или хеши, -// Ассоциативные массивы, известные в других языках как хеш-карты. +// Ассоциативные массивы, известные в других языках как HashMap. // Работает во всех версиях РHP $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); @@ -199,13 +200,13 @@ assert($c > $b); // больше assert($a <= $b); // меньше или равно assert($c >= $d); // больше или равно -// Следующие утверждения истинны если переменные имеют одинаковый тип. +// Следующие утверждения истинны, если переменные имеют одинаковый тип. assert($c === $d); assert($a !== $d); assert(1 == '1'); assert(1 !== '1'); -// Переменные могут изменять тип, в зависимости от их использования. +// Переменные могут изменять тип в зависимости от их использования. $integer = 1; echo $integer + $integer; // => 2 @@ -235,7 +236,7 @@ $var = null; // Null $integer = 10; $boolen = settype($integer, "string") // теперь $integer имеет строковый тип -// settype возвращает true - если преобразование удалось и false в противном случае +// settype возвращает true, если преобразование удалось и false в противном случае /******************************** * Управляющие структуры @@ -311,7 +312,7 @@ echo "\n"; for ($x = 0; $x < 10; $x++) { echo $x; -} // Prints "0123456789" +} // Напечатает "0123456789" echo "\n"; @@ -320,7 +321,7 @@ $wheels = ['bicycle' => 2, 'car' => 4]; // Циклы foreach могут обходить массивы foreach ($wheels as $wheel_count) { echo $wheel_count; -} // Prints "24" +} // Напечатает "24" echo "\n"; @@ -337,14 +338,14 @@ while ($i < 5) { break; // Exit out of the while loop } echo $i++; -} // Prints "012" +} // Напечатает "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { continue; // Skip this iteration of the loop } echo $i; -} // Prints "0124" +} // Напечатает "0124" /******************************** @@ -369,7 +370,7 @@ function add ($x, $y = 1) { // $y по умолчанию равно 1 echo add(4); // => 5 echo add(4, 2); // => 6 -// $result недоступна за пределами функции +// $result недоступен за пределами функции // print $result; // Выдает предупреждение // Начиная с PHP 5.3 вы можете объявлять анонимные функции: @@ -402,19 +403,19 @@ echo $function_name(1, 2); // => 3 /******************************** - * Includes + * Включения */ <?php // PHP код внутри включаемого файла должен начинаться с тега PHP. include 'my-file.php'; -// Код в файле my-file.php теперь доступен в текущем в текущем пространстве имен. -// Если файл не удалось включить, будет выдано предупреждение. +// Код в файле my-file.php теперь доступен в текущем пространстве имен. +// Если файл не удалось подключить, то будет выдано предупреждение. include_once 'my-file.php'; -// Если код в файле my-file.php уже был включен, он не будет включен повторно. -// Это предотвращает ошибку повторного включения файла. +// Если код в файле my-file.php уже был подключен, он не будет подключен повторно. +// Это предотвращает ошибку повторного подключения файла. require 'my-file.php'; require_once 'my-file.php'; @@ -422,7 +423,7 @@ require_once 'my-file.php'; // Same as include(), except require() will cause a fatal error if the // file cannot be included. // Действует также как и include(), но если файл не удалось подключить, -// функция выдает неисправимую ошибку +// функция выдает фатальную ошибку // Содержимое файла my-include.php: <?php @@ -452,19 +453,19 @@ class MyClass static $staticVar = 'static'; - // Properties must declare their visibility + // Свойства объявляются с указанием их видимости public $property = 'public'; public $instanceProp; - protected $prot = 'protected'; // Accessible from the class and subclasses - private $priv = 'private'; // Accessible within the class only + protected $prot = 'protected'; // Свойство доступно только потомкам и самому классу + private $priv = 'private'; // Свойство доступно только самому классу - // Create a constructor with __construct + // Конструктор описывается с помощью __construct public function __construct($instanceProp) { - // Access instance variables with $this + // Доступ к эземпляру класса с помощью $this $this->instanceProp = $instanceProp; } - // Methods are declared as functions inside a class + // Методы объявляются как функции принадлежащие классу public function myMethod() { print 'MyClass'; @@ -502,7 +503,7 @@ class MyOtherClass extends MyClass echo $this->prot; } - // Override a method + // Переопределение родительского метода function myMethod() { parent::myMethod(); @@ -595,7 +596,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Трейты */ -// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait +// Трейты появились в PHP 5.4 и объявляются при помощи ключевого слова trait trait MyTrait { @@ -611,7 +612,7 @@ class MyTraitfulClass } $cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls->myTraitMethod(); // Напечатает "I have MyTrait" /******************************** diff --git a/ruby.html.markdown b/ruby.html.markdown index fe142365..c10255d8 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,6 +12,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", https://github.com/ghalley] --- @@ -39,6 +40,7 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 2**5 #=> 32 +5 % 3 #=> 2 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -160,6 +162,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can be indexed # From the front array[0] #=> 1 +array.first #=> 1 array[12] #=> nil # Like arithmetic, [var] access @@ -170,6 +173,7 @@ array.[] 12 #=> nil # From the end array[-1] #=> 5 +array.last #=> 5 # With a start index and length array[2, 3] #=> [3, 4, 5] @@ -264,6 +268,12 @@ hash.each do |key, value| puts "#{key} is #{value}" end +# If you still need and index you can use "each_with_index" and define an index +# variable +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" diff --git a/sass.html.markdown b/sass.html.markdown new file mode 100644 index 00000000..509aee9b --- /dev/null +++ b/sass.html.markdown @@ -0,0 +1,232 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] +--- + +Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. +Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code. + +Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. +This tutorial is written using SCSS. + + +```scss + + +//Single line comments are removed when Sass is compiled to CSS. + +/*Multi line comments are preserved. */ + + + +/*Variables +==============================*/ + + + +/* You can store a CSS value (such as a color) in a variable. +Use the '$' symbol to create a variable. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. +Now if you want to change a color, you only have to make the change once.*/ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* This would compile to: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* This is much more maintainable than having to change the color +each time it appears throughout your stylesheet. */ + + + +/*Mixins +==============================*/ + + + +/* If you find you are writing the same code for more than one +element, you might want to store that code in a mixin. + +Use the '@mixin' directive, plus a name for your mixin.*/ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* You can use the mixin with '@include' and the mixin name. */ + +div { + @include center; + background-color: $primary-color; +} + +/*Which would compile to: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* You can use mixins to create a shorthand property. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/*Which you can invoke by passing width and height arguments. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* This compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend is a way to share the properties of one selector with another. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + + + + +/*Nesting +==============================*/ + + + +/*Sass allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + + +``` + + + +## SASS or Sass? +Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym. +Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets". + + +## Practice Sass +If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/). +You can use either syntax, just go into the settings and select either Sass or SCSS. + + +## Further reading +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles. diff --git a/scala.html.markdown b/scala.html.markdown index 7189be10..7f545196 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] - ["Ha-Duong Nguyen", "http://reference-error.org"] -filename: learn.scala --- Scala - the scalable language @@ -244,10 +243,11 @@ i // Show the value of i. Note that while is a loop in the classical sense - // comprehensions above is easier to understand and parallelize // A do while loop +i = 0 do { - println("x is still less than 10") - x += 1 -} while (x < 10) + println("i is still less than 10") + i += 1 +} while (i < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. @@ -566,8 +566,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" // Implicit function parameters enable us to simulate type classes in other // functional languages. It is so often used that it gets its own shorthand. The // following two lines mean the same thing: -def foo[T](implicit c: C[T]) = ... -def foo[T : C] = ... +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... // Another situation in which the compiler looks for an implicit is if you have diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown index f27cbf08..727f973e 100644 --- a/tr-tr/objective-c-tr.html.markdown +++ b/tr-tr/objective-c-tr.html.markdown @@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C programlama diline Smalltalk stilinde mesajlaşma ekler. -```objective_c +```objective-c // Tek satır yorum // işaretleri ile başlar /* diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index c97bb560..38e418e9 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown new file mode 100644 index 00000000..73382100 --- /dev/null +++ b/vi-vn/ruby-vi.html.markdown @@ -0,0 +1,549 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn + +--- + +```ruby +# Đây là một comment + +=begin +Đây là một comment nhiều dòng +Không ai dùng cách này +Bạn không nên dùng +=end + +# Đầu tiên và quan trọng nhất: Mọi thứ là đối tượng. + +# Các con số là các đối tượng. + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Một vài bài toán số học căn bản +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# Số học vừa là các cú pháp thân thiện cho việc gọi +# một hàm trên một đối tượng +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Các giá trị đặc biệt là các đối tượng +nil # Ở đây không có gì để xem +true # luôn đúng +false # luôn sai + +nil.class #=> Lớp Nil +true.class #=> Lớp True +false.class #=> Lớp False + +# So sánh bằng +1 == 1 #=> true +2 == 1 #=> false + +# So sánh không bằng +1 != 1 #=> false +2 != 1 #=> true + +# Ngoài chính false, thì nil là một giá trị khác của false + +!nil #=> true +!false #=> true +!0 #=> false + +# Các loại so sánh khác +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Các toán tử logic +true && false #=> false +true || false #=> true +!true #=> false + + +# Có các cách khác của các toán tử logic với mức thấp hơn +# Chúng được sử dụng như các cấu trúc điều khiển luồng nối các mệnh đề +# với nhau cho đến khi một trong số chúng trả về đúng hoặc sai. + +# `do_something_else` chỉ được gọi nếu như hàm `do_something` thành công. +do_something() and do_something_else() +# `log_error` chỉ được gọi nếu hàm `do_something` không thành công. +do_something() or log_error() + + +# Các chuỗi là các đối tượng + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = 'use string interpolation' +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + +# Nên đưa các chuỗi vào trong dấu nháy đơn +# Ngoài ra dấu nháy kép được sử dụng trong tính toán. + +# Nối các chuỗi, nhưng không nối với các số. +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Xuất ra ngoài màn hình +puts "I'm printing!" + +# Các biến +x = 25 #=> 25 +x #=> 25 + +# Chú ý về việc gán các giá trị được trả về vào biến. +# Điều này có nghĩa là bạn có thể gán nhiều biến. + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Theo quy ước, dùng snake_case cho các tên của biến. +snake_case = true + +# Dùng để mô tả tên các biến +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Ký tự (là các đối tượng) +# Các ký tự là bất biến, như các biến hằng số chỉ đến các số nguyên. +# Chúng thường xuyên được sử dụng thay cho các chuỗi để chuyển đổi các giá +# trị hiệu quả. + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Các mảng + +# Đây là một mảng +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Các mảng có thể chứa nhiều phần tử khác nhau + +[1, 'hello', false] #=> [1, "hello", false] + +# Có thể truy cập các giá trị của mảng thông qua các chỉ mục +array[0] #=> 1 +array[12] #=> nil + +# Giống như số học, sử dụng [biến] là một cú pháp thông dụng +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Lấy phần tử cuối cùng +array[-1] #=> 5 + +# Bắt đầu từ chỉ mục và số phần tử cần lấy +array[2, 3] #=> [3, 4, 5] + +# Đảo ngược một mảng +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Lấy một khoảng +array[1..3] #=> [2, 3, 4] + +# Thêm phần tử vào mảng bằng cách này +array << 6 #=> [1, 2, 3, 4, 5, 6] +# Hoặc cách này +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Kiểm tra phần tử có tồn tại trong mảng +array.include?(1) #=> true + +# Băm là phần chính của Ruby với các cặp khoá/giá trị +# Băm được biểu thị bằng dấu ngoặc nhọn: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Băm có thể được truy cập nhanh chóng thông qua khoá +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Khoá không tồn tại sẽ trả về nil +hash['nothing here'] #=> nil + +# Kể từ Ruby bản 1.9, đây là một cú pháp đặc biệt, sử dụng symbol như khoá + +new_hash = { defcon: 3, action: true } + +new_hash.keys #=> [:defcon, :action] + +# Kiểm tra khoá hoặc giá trị có tồn tại hay không +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + +# Mẹo: Cả Mảng và Băm đều là Enumberable +# Chúng cùng chia sẻ rất nhiều phương thức hữu ích như each, map, count... + +# Cấu trúc điều khiển + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# TUY NHIÊN, không ai sử dụng vòng lặp for. +# Thay vào đó, ban nên dùng phương thức "each" và truyền vào đó một khối. +# Một khối là một loạt các mã mà bạn có thể truyền +# cho một phương thức giống như each. +# Nó tương tự với lambda, các hàm ẩn danh hoặc closures trong các ngôn ngữ +# lập trình khác. +# +# Phương thức "each" cho một khoản sẽ chạy qua từng phần tử của khoảng đó. +# Khối được truyền vào là một số đếm như là tham số. +# Gọi một method "each" với một khối sẽ trông như thế này: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Bạn cũng có thể bao khối trong các dấu ngoặc nhọn. +(1..5).each { |counter| puts "iteration #{counter}" } + +# Các nội dung của cấu trúc dữ liệu cũng có thể được lặp bằng each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Cases cũng được dùng cho các dãy +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Xử lý ngoại lệ: +begin + # Code ở đây có thể sẽ đưa ra một ngoại lệ. + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Hàm + +def double(x) + x * 2 +end + +# Hàm (và tất cả các khối) được mặc định giá trị trả về ở mệnh đề cuối. +double(2) #=> 4 + +# Dấu ngoặc là một tuỳ chọn cho một kết quả rõ ràng. +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Các đối số được chia cắt bởi dấu phẩy. +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Tất cả các hàm có thể có một tham số tuỳ chọn. +# Nó có thể được gọi với từ khóa "yield". +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# Bạn có thể truyền một khối đến một hàm +# Dấu "&" được đánh dấu đến một khối +def guests(&block) + block.call 'some_argument' +end + +# Bạn có thể truyền một danh sách các tham số, nó sẽ được chuyển thành mảng. +# Thông qua việc sử dụng dấu *. +def guests(*array) + array.each { |guest| puts guest } +end + +# Định nghĩ một lớp thông qua từ khoá class. +class Human + + # Một biến class. Nó được chia sẽ cho tất cả các instance của lớp này. + @@species = 'H. sapiens' + + # Các khởi tạo căn bản + def initialize(name, age = 0) + # Gán đối số đến biến instance "name" + @name = name + # Nếu không có age, sẽ lấy giá trị mặc định trong danh sách đối số. + @age = age + end + + # Hàm nhập giá trị căn bản + def name=(name) + @name = name + end + + # Hàm lấy giá trị căn bản + def name + @name + end + + # Các hàm trên có thể được gọn lại bằng cách dùng hàm attr_accessor + attr_accessor :name + + # Các hàm nhận/lấy cũng có thể được tạo riêng như sau: + attr_reader :name + attr_writer :name + + # Một hàm lớp dùng self để phân biệt với hàm instance. + # Nó chỉ có thể được gọi trên lớp. + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# Khởi tạo một lớp +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Hãy gọi một cặp các hàm. +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Gọi một hàm lớp +Human.say('Hi') #=> "Hi" + +# Phạm vi của biến được định nghĩa bởi cách chúng ta đặt tên cho chúng. +# Các biến bắt đầu với dấu $ là biến toàn cục. +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# Các biến bắt đầu với dấu @ là biến phạm vi. +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# Các biến bắt đầu với dấu @@ có pham vi là trong một lớp. +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Các biến bắt đầu với ký tự viết hoa là biến hằng. +Var = "I'm a constant" +defined? Var #=> "constant" + +# Lớp cũng là một đối tượng trong Ruby. Bởi vậy lớp có các biến instance. +# Biến lớp được chia sẽ trong lớp và các lớp kế thừa nó. + +# Lớp cơ sở +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Lớp kế thừa +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Các biến lớp instance không được chia sẽ trong lớp kế thừa. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# Include một module sẽ đưa các hàm của module thành instances của lớp. +# Extend một module sẽ đưa các hàm của module thành các biến của lớp. + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Hàm hồi quy được thực hiện khi include và extend một module. + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Các nguồn tham khảo thêm. + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/xml.html.markdown b/xml.html.markdown index d407512d..4d33e614 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -40,13 +40,14 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i It starts with a declaration, informing some metadata (optional). XML uses a tree structure. Above, the root node is 'bookstore', which has - three child nodes, all 'books'. Those nodes has more child nodes, and so on... + three child nodes, all 'books'. Those nodes have more child nodes (or + children), and so on... - Nodes are created using open/close tags, and childs are just nodes between + Nodes are created using open/close tags, and children are just nodes between the open and close tags.--> -<!-- XML carries two kind of data: +<!-- XML carries two kinds of data: 1 - Attributes -> That's metadata about a node. Usually, the XML parser uses this information to store the data properly. It is characterized by appearing with the format name="value" within the opening |