diff options
35 files changed, 1327 insertions, 127 deletions
diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..183b7cdb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,65 @@ +asciidoc*.html.markdown linguist-language=AsciiDoc +angularjs*.html.markdown linguist-language=JavaScript +bash*.html.markdown linguist-language=bash +bf.html.markdown linguist-language=Brainfuck +bf-*.html.markdown linguist-language=Brainfuck +c-*.html.markdown linguist-language=C +c.html.markdown linguist-language=C +c++*.html.markdown linguist-language=C++ +chapel*.html.markdown linguist-language=Chapel +clojure*.html.markdown linguist-language=Clojure +cmake*.html.markdown linguist-language=CMake +coffeescript*.html.markdown linguist-language=CoffeeScript +coldfusion*.html.markdown linguist-language=ColdFusion +common-lisp*.html.markdown linguist-language=lisp +compojure*.html.markdown linguist-language=Clojure +csharp*.html.markdown linguist-language=C# +css*.html.markdown linguist-language=CSS +d.html.markdown linguist-language=D +d-*.html.markdown linguist-language=D +dart*.html.markdown linguist-language=Dart +edn*.html.markdown linguist-language=edn +elisp*.html.markdown linguist-language=elisp +elixir*.html.markdown linguist-language=Elixir +elm*.html.markdown linguist-language=Elm +erlang*.html.markdown linguist-language=Erlang +factor*.html.markdown linguist-language=Factor +forth*.html.markdown linguist-language=Forth +fortran*.html.markdown linguist-language=FORTRAN +fsharp*.html.markdown linguist-language=fsharp +go.html.markdown linguist-language=Go +go-*.html.markdown linguist-language=Go +groovy*.html.markdown linguist-language=Groovy +hack*.html.markdown linguist-language=Hack +haml*.html.markdown linguist-language=Haml +haskell*.html.markdown linguist-language=Haskell +haxe*.html.markdown linguist-language=Haxe +html*.html.markdown linguist-language=HTML +hy.html.markdown linguist-language=Hy +hy-*.html.markdown linguist-language=Hy +inform7*.html.markdown linguist-language=inform7 +java.html.markdown linguist-language=Java +java-*.html.markdown linguist-language=Java +javascript*.html.markdown linguist-language=JavaScript +jquery*.html.markdown linguist-language=JavaScript +json*.html.markdown linguist-language=JSON +julia*.html.markdown linguist-language=Julia +kotlin*.html.markdown linguist-language=Kotlin +latex*.html.markdown linguist-language=latex +less*.html.markdown linguist-language=less +livescript*.html.markdown linguist-language=LiveScript +logtalk*.html.markdown linguist-language=Logtalk +lua*.html.markdown linguist-language=Lua +make*.html.markdown linguist-language=Makefile +markdown*.html.markdown linguist-language=Markdown +matlab*.html.markdown linguist-language=Matlab +nim*.html.markdown linguist-language=Nimrod +nix*.html.markdown linguist-language=Nix +objective-c*.html.markdown linguist-language=Objective-C +ocaml*.html.markdown linguist-language=OCaml +paren*.html.markdown linguist-language=lisp +pcre*.html.markdown linguist-language=Perl +perl.html.markdown linguist-language=Perl +perl-*.html.markdown linguist-language=Perl +perl6*.html.markdown linguist-language=Perl6 +ruby*.html.markdown linguist-language=Ruby diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..ab89cb23 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: ruby +rvm: + - 2.2 diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown index c6a3a914..080527a9 100644 --- a/CHICKEN.html.markdown +++ b/CHICKEN.html.markdown @@ -479,7 +479,7 @@ sqr ;; => #<procedure (sqr x)> ;; Functors ;; Functors are high level modules that can be parameterized by other modules -;; Following functor requires another module named 'M' that provides a funtion called 'multiply' +;; Following functor requires another module named 'M' that provides a function called 'multiply' ;; The functor itself exports a generic function 'square' (functor (squaring-functor (M (multiply))) (square) (import scheme M) diff --git a/Gemfile b/Gemfile new file mode 100644 index 00000000..c30a6497 --- /dev/null +++ b/Gemfile @@ -0,0 +1,5 @@ +source 'http://rubygems.org' +group :test do + gem 'rake' + gem 'charlock_holmes' +end diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 3f55e3fb..6f1f000d 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,4 +1,5 @@ -- [ ] PR touches only one file (or a set of logically related files with similar changes made) +- [ ] Pull request title is prepended with `[language/lang-code]` +- [ ] Pull request touches only one file (or a set of logically related files with similar changes made) - [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts) -- [ ] YAML Frontmatter formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown) - - [ ] Seriously, look at it now. Watch for quotes and double-check field names. +- [ ] If you've changed any part of the YAML Frontmatter, make sure it is formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown) + - [ ] Yes, I have double-checked quotes and field names! diff --git a/README.markdown b/README.markdown index a71e85bd..9a8a3752 100644 --- a/README.markdown +++ b/README.markdown @@ -1,5 +1,7 @@ # [Learn X in Y minutes][1] +[![Build Status](https://travis-ci.org/adambard/learnxinyminutes-docs.svg?branch=master)](https://travis-ci.org/adambard/learnxinyminutes-docs) + Whirlwind tours of (several, hopefully many someday) popular and ought-to-be-more-popular programming languages, presented as valid, commented code and explained as they go. diff --git a/Rakefile b/Rakefile new file mode 100644 index 00000000..6a31bd72 --- /dev/null +++ b/Rakefile @@ -0,0 +1,23 @@ +task default: %w[encoding yaml return_code] +$failure = 0 +task :encoding do + begin + ruby 'tests/encoding.rb' + rescue Exception => msg + puts msg + $failure += 1 + end +end +task :yaml do + begin + ruby 'tests/yaml.rb' + rescue Exception => msg + puts msg + $failure += 1 + end +end +task :return_code do + if $failure != 0 + raise "Failed #{$failure} tests!!" + end +end diff --git a/angularjs.html.markdown b/angularjs.html.markdown index f4f6375f..89afa291 100644 --- a/angularjs.html.markdown +++ b/angularjs.html.markdown @@ -18,9 +18,10 @@ AngularJS extends HTML attributes with Directives, and binds data to HTML with E ##What You Should Already Know Before you study AngularJS, you should have a basic understanding of: -* HTML -* CSS -* JavaScript + +- HTML +- CSS +- JavaScript ```html // AngularJS is a JavaScript framework. It is a library written in JavaScript. @@ -279,11 +280,11 @@ angular.module('myApp', []).controller('namesCtrl', function($scope) { // Filters can be added to expressions and directives using a pipe character. // AngularJS filters can be used to transform data: -**currency: Format a number to a currency format. -**filter: Select a subset of items from an array. -**lowercase: Format a string to lower case. -**orderBy: Orders an array by an expression. -**uppercase: Format a string to upper case. +- **currency**: Format a number to a currency format. +- **filter**: Select a subset of items from an array. +- **lowercase**: Format a string to lower case. +- **orderBy**: Orders an array by an expression. +- **uppercase**: Format a string to upper case. //A filter can be added to an expression with a pipe character (|) and a filter. //(For the next two examples we will use the person controller from the previous chapter) @@ -696,13 +697,15 @@ app.controller('myCtrl', function($scope) { ## Source & References -**Examples -* http://www.w3schools.com/angular/angular_examples.asp +**Examples** + +- http://www.w3schools.com/angular/angular_examples.asp + +**References** -**References -* http://www.w3schools.com/angular/angular_ref_directives.asp -* http://www.w3schools.com/angular/default.asp -* https://teamtreehouse.com/library/angular-basics/ +- http://www.w3schools.com/angular/angular_ref_directives.asp +- http://www.w3schools.com/angular/default.asp +- https://teamtreehouse.com/library/angular-basics/ Feedback is welcome! You can find me in: [@WalterC_87](https://twitter.com/WalterC_87), or diff --git a/c++.html.markdown b/c++.html.markdown index 7dc9afbe..24d38df7 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -981,7 +981,7 @@ cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat(first, second, third); -// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) +// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 @@ -1057,7 +1057,7 @@ cout << ST.size(); // will print the size of set ST // and a mapped value, following a specific order. #include<map> -map<char, int> mymap; // Will initalize the map with key as char and value as int +map<char, int> mymap; // Will initialize the map with key as char and value as int mymap.insert(pair<char,int>('A',1)); // Will insert value 1 for key A @@ -1072,7 +1072,7 @@ for (it=mymap.begin(); it!=mymap.end(); ++it) // A->1 // Z->26 -// To find the value correponsing to a key +// To find the value corresponding to a key it = mymap.find('Z'); cout << it->second; diff --git a/c.html.markdown b/c.html.markdown index ae87ca08..57ce72d2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -202,7 +202,7 @@ int main (int argc, char** argv) 11 % 3; // => 2 // Comparison operators are probably familiar, but - // there is no Boolean type in c. We use ints instead. + // there is no Boolean type in C. We use ints instead. // (Or _Bool or bool in C99.) // 0 is false, anything else is true. (The comparison // operators always yield 0 or 1.) @@ -715,14 +715,14 @@ typedef void (*my_fnp_type)(char *); /******************************* Header Files ********************************** -Header files are an important part of c as they allow for the connection of c +Header files are an important part of C as they allow for the connection of C source files and can simplify code and definitions by separating them into separate files. -Header files are syntactically similar to c source files but reside in ".h" -files. They can be included in your c source file by using the precompiler +Header files are syntactically similar to C source files but reside in ".h" +files. They can be included in your C source file by using the precompiler command #include "example.h", given that example.h exists in the same directory -as the c file. +as the C file. */ /* A safe guard to prevent the header from being defined too many times. This */ @@ -753,12 +753,12 @@ enum traffic_light_state {GREEN, YELLOW, RED}; /* Function prototypes can also be defined here for use in multiple files, */ /* but it is bad practice to define the function in the header. Definitions */ -/* should instead be put in a c file. */ +/* should instead be put in a C file. */ Node createLinkedList(int *vals, int len); -/* Beyond the above elements, other definitions should be left to a c source */ +/* Beyond the above elements, other definitions should be left to a C source */ /* file. Excessive includes or definitions should, also not be contained in */ -/* a header file but instead put into separate headers or a c file. */ +/* a header file but instead put into separate headers or a C file. */ #endif /* End of the if precompiler directive. */ diff --git a/css.html.markdown b/css.html.markdown index 1c569d04..3b378d44 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -169,9 +169,9 @@ selector { color: transparent; /* equivalent to setting the alpha to 0 */ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ - + /* Borders */ - border-width:5px; + border-width:5px; border-style:solid; border-color:red; /* similar to how background-color is set */ border: 5px solid red; /* this is a short hand approach for the same */ @@ -261,7 +261,7 @@ recommended that you avoid its usage. ## Media Queries -CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specifity. +CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specificity. ```css /* A rule that will be used on all devices */ diff --git a/es-es/wolfram-es.html.markdown b/es-es/wolfram-es.html.markdown new file mode 100644 index 00000000..44ec9e09 --- /dev/null +++ b/es-es/wolfram-es.html.markdown @@ -0,0 +1,138 @@ +--- +language: wolfram +lang: es-es +contributors: + - ["Daniel Caballero", "http://github.com/danielcaballero796/"] +filename: learnwolfram-es.md +--- + +Wolfram es un lenguaje subyacente originalmente utilizado en Mathematica, pero ahora esta disponible para su uso en múltiples contextos. + +El lenguaje de Wolfram tiene varias interfaces: +* La interfaz de línea de comandos kernel de Raspberry Pi (recién llamada _The Wolfram Language_) que se ejecuta interactivamente y no puede producir entrada gráfica. +* _Mathematica_ que es un texto rico / editor de matemáticas con Wolfram interactivo construido: presionando shift + Return en una "celda de código" crea una celda de salida con el resultado, que no es dinámica +* _Wolfram Workbench_ la cual es la interfaz de Eclipse del lenguaje Wolfram + +El código de este ejemplo se puede escribir en cualquier interfaz y editarlo con Wolfram Workbench. Cargar directamente en Matematica puede resultar incómodo porque el archivo no contiene información de formato de celda (lo que haría que el archivo sea un desastre enorme para ser leído como texto) - puede ser visto / editado pero tal vez requerira algún ajuste. + +``` +(* Esto es un comentario *) + +(* En Mathematica en lugar de utilizar estos comentarios, puede crear una celda de texto + Y anotar su código con texto e imágenes bien escritas *) + +(* Escribe una expresión devuelve el resultado *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Llamada de función *) +(* Nota, los nombres de funciones (y todo lo demás) distingue entre mayúsculas y minúsculas *) +Sin[Pi/2] (* 1 *) + +(* Sintaxis alternativa para la Llamada de una función con un parámetro *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Cada sintaxis en WL tiene algún equivalente como una llamada de función *) +Veces[2, 2] (* 4 *) +Mas[5, 8] (* 13 *) + +(* El uso de una variable por primera vez lo define y lo hace global *) +x = 5 (* 5 *) +x == 5 (* verdadero, Estilo-C asignación y pruebas de igualdad *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Modifique[x, 20] (* No estaba bromeando cuando dije que TODO tiene una función equivalente *) +x (* 20 *) + +(* Debido a que WL se basa en un sistema de álgebra computacional, *) +(* El uso de variables indefinidas está bien, simplemente obstruyen la evaluación *) +cow + 5 (* 5 + cow, cow es indefinido por lo que no puede evaluar más *) +cow + 5 + 10 (* 15 + cow, Va a evaluar lo que puede *) +% (* 15 + cow, % Busca el último retorno *) +% - cow (* 15, cow variable indefinida cancelada *) +moo = cow + 5 (* Cuidado, moo ahora tiene una expresión, no un número! *) + +(* Definición de una función *) +Double[x_] := x * 2 (* Nota: = para evitar la evaluación inmediata del RHS + y después de x para indicar que no hay restricciones de concordancia de patrones *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-Sintaxis evita colas de paréntesis *) +(Pi/2) // Sin // Double(* 2, //-Sintaxis lista las funciones en orden de ejecución *) + +(* Para un uso de programación de estilo imperativo; Para separar declaraciones *) +(* Descarta cualquier salida de LHS y ejecuta RHS *) +miPrimero[] := (Print@"Hola"; Print@"Mundo") (* Tenga en cuenta que los padres externos son críticos + ; La precedencia es menor que := *) +miPrimero[] (* Hola Mundo *) + +(* Estilo-C para bucle *) +PrintTo[x_] := For[y=0, y<x, y++, (Print[y])] (* Start, test, incr, body *) +PrintTo[5] (* 0 1 2 3 4 *) + +(* bucle *) +x = 0; While[x < 2, (Print@x; x++)] (* Ciclo con prueba y cuerpo *) + +(* Si y condicionales *) +x = 8; If[x==8, Print@"Yes", Print@"No"] (* Condición, Caso verdadero, Caso distinto*) +Switch[x, 2, Print@"Two", 8, Print@"Yes"] (* Interruptor de estilo de coincidencia de valor *) +Which[x==2, Print@"No", x==8, Print@"Yes"] (* estilo de caso distinto *) + +(* Las variables distintas de los parámetros son globales por defecto, incluso dentro de las funciones *) +y = 10 (* 10, Variable global y *) +PrintTo[5] (* 0 1 2 3 4 *) +y (* 5, Global por contador de bucle dentro de PrintTo *) +x = 20 (* 20, Variable global x *) +PrintTo[5] (* 0 1 2 3 4 *) +x (* 20, x en PrintTo Es un parámetro y automáticamente local *) + +(* Las variables locales se declaran utilizando la metafunción del módulo *) +(* Version con variable local*) +BetterPrintTo[x_] := Module[{y}, (For[y=0, y<x, y++, (Print@y)])] +y = 20 (* Variable global y *) +BetterPrintTo[5] (* 0 1 2 3 4 *) +y (* 20, eso es mejor *) + +(* El módulo realmente nos permite declarar cualquier ámbito que nos guste *) +Module[{count}, count=0; (* Declare el alcance de este recuento de variables *) + (IncCount[] := ++count); (* Estas funciones están dentro de ese ámbito *) + (DecCount[] := --count)] +count (* count - Variable global count no esta definida *) +IncCount[] (* 1, usando count variable dentro del alcance *) +IncCount[] (* 2, incCount lo actualiza *) +DecCount[] (* 1, decCount tambien lo hace *) +count (* count - Aún ninguna variable global con ese nombre*) + +(* listas *) +miLista = {1, 2, 3, 4} (* {1, 2, 3, 4} *) +miLista[[1]] (* 1 - Los índices de la lista de notas comienzan en 1, no 0 *) +Map[Double, miLista] (* {2, 4, 6, 8} - Lista de estilo funcional mapa función *) +Double /@ miLista (* {2, 4, 6, 8} - Sintaxis abreviada para arriba *) +Scan[Print, miLista] (* 1 2 3 4 - Lista de bucle sobre estilo imperativo *) +Fold[Plus, 0, miLista] (* 10 (0+1+2+3+4) *) +FoldList[Plus, 0, miLista] (* {0, 1, 3, 6, 10} - Guardar los resultados intermedios *) +Append[miLista, 5] (* {1, 2, 3, 4, 5} - Note que miLista no está actualizada *) +Prepend[miLista, 5] (* {5, 1, 2, 3, 4} - añada "miLista = " Si quieres que lo sea *) +Join[miLista, {3, 4}] (* {1, 2, 3, 4, 3, 4} *) +miLista[[2]] = 5 (* {1, 5, 3, 4} - Esto actualiza miLista *) + +(* Asociaciones, aka Diccionarios /Hashes *) +miHash = <|"Green" -> 2, "Red" -> 1|> (* crea una asociación *) +miHash[["Green"]] (* 2, uselo *) +miHash[["Green"]] := 5 (* 5, actualizalo *) +miHash[["Puce"]] := 3.5 (* 3.5, extiendalo *) +KeyDropFrom[miHash, "Verde"] (* Limpia la llave Verde *) +Claves[miHash] (* {Rojo} *) +Valores[miHash] (* {1} *) + +(* Y no puedes hacer ninguna demo de Wolfram sin mostrar esto *) +Manipular[y^2, {y, 0, 20}] (* Devuelve una interfaz de usuario reactiva que muestra y ^ 2 + Y permite ajustar y entre 0-20 con un deslizador. + Sólo funciona en interfaces gráficas *) +``` + +##Listo para mas? + +* [Centro de Documentación](http://reference.wolfram.com/language/) diff --git a/fr-fr/vim.html.markdown b/fr-fr/vim.html.markdown new file mode 100644 index 00000000..8e84bf33 --- /dev/null +++ b/fr-fr/vim.html.markdown @@ -0,0 +1,239 @@ +--- +category: tool +tool: vim +filename: LearnVim.txt +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Thibault", "https://github.com/napnac"] +lang: fr-fr +--- + + +[Vim](www.vim.org) +(Vi IMproved) est le clone le plus populaire de l'éditeur de texte vi sous Unix. +Vim est un éditeur de texte omniprésent sur les systèmes de type Unix, et a pour +objectif la rapidité ainsi que l'augmentation de la productivité. Il a de +nombreux raccourcis claviers pour une navigation et une édition plus rapide. + +## Navigation basique avec Vim + +``` + vim <ficher> # Ouvre <fichier> avec vim + :q # Quitte vim + :w # Sauvegarde le fichier actuel + :wq # Sauvegarde le fichier actuel et quitte vim + :q! # Quitte vim sans sauvegarder + # ! *force* l'exécution de :q, ce qui par conséquent + # oblige vim à quitter sans sauvegarder + :x # Sauvegarde le fichier et quitte vim (raccourcis de :wq) + + u # Annuler + CTRL+R # Rétablir + + h # Déplace le curseur vers la gauche + j # Déplace le curseur vers le bas + k # Déplace le curseur vers le haut + l # Déplace le curseur vers la droite + + # Mouvements au sein d'une ligne + + 0 # Va au début de la ligne + $ # Va à la fin de la ligne + ^ # Va au premier caractère non blanc de la ligne + + # Rechercher dans un texte + + /mot # Surligne toutes les occurrences du mot après le curseur + ?mot # Surligne toutes les occurrences du mot avant le curseur + n # Déplace le curseur sur la prochaine occurrence du mot recherché + N # Déplace le curseur sur la précédente occurrence du mot recherché + + :%s/abc/def/g # Transforme les 'abc' en 'def' sur chaque ligne du texte + :s/abc/def/g # Transforme les 'abc' en 'def' sur la ligne actuelle + + # Se déplacer vers un caractère + + f<caractère> # Se déplace en avant jusqu'à <caractère> + t<caractère> # Se déplace en avant juste avant <caractère> + + # Par exemple + f< # Se déplace en avant jusqu'à < + t< # Se déplace en avant juste avant < + + # Se déplacer dans un mot + + w # Avance d'un mot + b # Recule d'un mot + e # Se déplace jusqu'à la fin du mot actuel + + # D'autres raccourcis pour se déplacer + + gg # Va au début du fichier + G # Va à la fin du fichier + :NB # Va à la ligne numéro NB (où NB est un nombre) + H # Se déplace jusqu'en haut de l'écran + M # Se déplace jusqu'au milieu de l'écran + L # Se déplace jusqu'en bas de l'écran +``` + +## Modes + +Vim est basé sur le concept de **modes**. + +Mode Commande - pour se déplacer et exécuter des commandes (vim démarre dans ce mode) +Mode Insertion - pour éditer le fichier +Mode Visuel - pour sélectionner du texte et réaliser des opérations dessus +Mode Ex - pour entrer des commandes avec ':' + +``` + i # Mode insertion, avant le curseur + a # Mode insertion, après le curseur + v # Mode visuel + : # Mode ex + <esc> # 'Echap' permet de revenir dans le mode commande + + # Copier/Coller du texte + + y # Copie le texte sélectionné + yy # Copie la ligne actuelle + d # Supprime ce qui est sélectionné + dd # Supprime la ligne actuelle + p # Colle après le curseur + P # Colle avant le curseur + x # Supprime le caractère sous le curseur +``` + +## La "Grammaire" de Vim + +Vim peut être vu comme un ensemble de commande sous la forme +'Verbe-Modificateur-Nom' : + +Verbe - notre action +Modificateur - la manière de faire l'action +Nom - l'objet désigné par l'action + +Quelques exemples importants de 'Verbes', 'Modificateurs', et de 'Noms' : + +``` + # 'Verbes' + + d # Supprime + c # Transforme + y # Copie + v # Sélectionne + + # 'Modificateurs' + + i # A l'intérieur + a # Autour + NB # Nombre + f # Cherche quelque chose et se déplace dessus + t # Cherche quelque chose et se déplace juste avant + / # Cherche une chaîne de caractères après le curseur + ? # Cherche une chaîne de caractères avant le curseur + + # 'Noms' + + w # Mot + s # Phrase + p # Paragraphe + b # Bloc + + # Exemple de 'phrases' ou commandes + + d2w # Supprime 2 mots + cis # Transforme l'intérieur de la phrase + yip # Copie l'intérieur du paragraphe + ct< # Transforme le texte du curseur jusqu'au caractère avant le < + d$ # Supprime jusqu'à la fin de la ligne +``` + +## Quelques raccourcis et astuces + +``` + > # Indente la sélection d'un bloc + < # Dé-indente la sélection d'un bloc + :earlier 15m # Retrouve le document comme il était il y a 15 minutes + :later 15m # Inverse la commande précédente + ddp # Echange la position de deux lignes consécutives (dd puis p) + . # Répète la dernière action effectuée +``` + +## Macros + +Les macros sont des actions enregistrables. +Quand on commence à enregistrer une macro, Vim enregistre **toutes** les actions +et les commandes que vous utilisez, jusqu'à ce que vous arrêtiez d'enregistrer. +Lorsque vous appelez une macro, elle applique exactement les mêmes actions et +commandes sur le texte sélectionné. + +``` + qa # Commence l'enregistrement de la macro 'a' + q # Arrête l'enregistrement + @a # Appelle la macro 'a' +``` + +### Configuration de ~/.vimrc + +Le fichier .vimrc est utilisé pour configurer Vim lors du démarrage. + +Voici un exemple de fichier ~/.vimrc : + +``` +" Exemple de ~/.vimrc +" 2015.10 + +" Nécessaire à Vim pour être 'iMproved' +set nocompatible + +" Détermine l'extension du fichier à partir du nom pour permettre une indentation +" automatique intelligente, etc. +filetype indent plugin on + +" Active la coloration syntaxique +syntax on + +" Une meilleure complétion de la ligne de commande +set wildmenu + +" Utilise une recherche insensible à la case sauf quand on utilise des majuscules +set ignorecase +set smartcase + +" Quand on commence une nouvelle ligne et qu'aucun type d'indentation n'est activé +" on utilise la même indentation que sur la ligne précédente +set autoindent + +" Affiche le numéro de la ligne sur la gauche de l'écran +set number + +" Options d'indentation, à changer en fonction des préférences personnelles + +" Nombre d'espaces visuels par tabulation +set tabstop=4 + +" Nombre d'espaces par tabulation +set softtabstop=4 + +" Nombre d'espaces indentés avec les opérations d'indentations (>> et <<) +set shiftwidth=4 + +" Convertis les tabulations en espaces +set expandtab + +" Active des tabulations et des espaces intelligents pour l'indentation et l'alignement +set smarttab +``` + +### Références + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) diff --git a/go.html.markdown b/go.html.markdown index 7b007bab..f097caeb 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Leonid Shevtsov", "https://github.com/leonid-shevtsov"] --- Go was created out of the need to get work done. It's not the latest trend @@ -39,6 +40,7 @@ import ( "io/ioutil" // Implements some I/O utility functions. m "math" // Math library with local alias m. "net/http" // Yes, a web server! + "os" // OS functions like working with the file system "strconv" // String conversions. ) @@ -133,6 +135,14 @@ can include line breaks.` // Same string type. // Unused variables are an error in Go. // The underscore lets you "use" a variable but discard its value. _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Usually you use it to ignore one of the return values of a function + // For example, in a quick and dirty script you might ignore the + // error value returned from os.Create, and expect that the file + // will always be created. + file, _ := os.Create("output.txt") + fmt.Fprint(file, "This is how you write to a file, by the way") + file.Close() + // Output of course counts as using a variable. fmt.Println(s, c, a4, s3, d2, m) @@ -211,6 +221,10 @@ func learnFlowControl() { // for each pair in the map, print key and value fmt.Printf("key=%s, value=%d\n", key, value) } + // If you only need the value, use the underscore as the key + for _, name := range []string{"Bob", "Bill", "Joe"} { + fmt.Printf("Hello, %s\n", name) + } // As with for, := in an if statement means to declare and assign // y first, then test y > x. diff --git a/html.html.markdown b/html.html.markdown index 904fa5c2..b64cec33 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -8,7 +8,7 @@ translators: --- HTML stands for HyperText Markup Language. -It is a language which use to write pages for the world wide web. +It is a language which allows us to write pages for the world wide web. It is a markup language, it enables us to write to write webpages using code to indicate how text and data should be displayed. In fact, html files are simple text files. What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags. diff --git a/java.html.markdown b/java.html.markdown index 13c75ffe..12de0c73 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -198,7 +198,20 @@ public class LearnJava { builderConcatenated.append("the StringBuilder class."); System.out.println(builderConcatenated.toString()); // only now is the string built // Output: You can use the StringBuilder class. - + + // StringBuilder is efficient when the fully constructed String is not required until the end of some processing. + StringBuilder stringBuilder = new StringBuilder(); + String inefficientString = ""; + for(int i = 0 ; i < 10; i++){ + stringBuilder.append(i).append(" "); + inefficientString += i + " "; + } + System.out.println(inefficientString); + System.out.println(stringBuilder.toString()); + // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration. + // Simple concatenation with + is compiled to a StringBuilder and toString() + // Avoid string concatenation in loops. + // #3 - with String formatter // Another alternative way to create strings. Fast and readable. String.format("%s may prefer %s.", "Or you", "String.format()"); @@ -835,6 +848,10 @@ The links provided here below are just to get an understanding of the topic, fee * [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html) +* New features in Java 8: + * [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) + * [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) + **Online Practice and Tutorials** * [Learneroo.com - Learn Java](http://www.learneroo.com) diff --git a/javascript.html.markdown b/javascript.html.markdown index 98261334..38119864 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -230,6 +230,17 @@ for (var i = 0; i < 5; i++){ // will run 5 times } +// Breaking out of labeled loops is similar to Java +outer: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } +} + // The for/in statement iterates over every property across the entire prototype chain. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; diff --git a/kdb+.html.markdown b/kdb+.html.markdown index ae132451..772c8a47 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -6,9 +6,8 @@ contributors: filename: learnkdb.q --- -The q langauge and its database component kdb+ were developed by Arthur -Whitney and released by Kx systems in 2003. q is a descendant of -[APL](https://en.wikipedia.org/wiki/APL_(programming_language)) and as such is +The q langauge and its database component kdb+ were developed by Arthur Whitney +and released by Kx systems in 2003. q is a descendant of APL and as such is very terse and a little strange looking for anyone from a "C heritage" language background. Its expressiveness and vector oriented nature make it well suited to performing complex calculations on large amounts of data (while also @@ -69,7 +68,7 @@ at jonny.press@aquaq.co.uk / And exponentiation... 2 xexp 4 / => 16 -/ ...and rounding... +/ ...and truncating... floor 3.14159 / => 3 / ...getting the absolute value... @@ -257,7 +256,7 @@ l / => 5 2 3 4 / Lists can also be used for indexing and indexed assignment l[1 3] / => 2 4 l[1 3]: 1 3 -l / => 1 1 3 3 +l / => 5 1 3 3 / Lists can be untyped/mixed type l:(1;2;`hi) @@ -291,6 +290,7 @@ last 1 2 3 / => 3 / Take (#), drop (_) and find (?) are also useful working with lists l:1 2 3 4 5 6 7 8 9 +l:1+til 9 / til is a useful shortcut for generating ranges / take the first 5 elements 5#l / => 1 2 3 4 5 / drop the first 5 @@ -298,7 +298,7 @@ l:1 2 3 4 5 6 7 8 9 / take the last 5 -5#l / => 5 6 7 8 9 / drop the last 5 --5_l / => 1 2 3 4 5 +-5_l / => 1 2 3 4 / find the first occurance of 4 l?4 / => 3 l[3] / => 4 @@ -312,7 +312,7 @@ d:`a`b`c!1 2 3 / the keyword key returns the first list key d / => `a`b`c / and value the second -value / => 1 2 3 +value d / => 1 2 3 / Indexing is indentical to lists / with the first list as a key instead of the position @@ -398,7 +398,7 @@ k!t / => id| c1 c2 c3 / => --| -------- / => 1 | 1 4 7 -/ => 2 | 2 5 8 +/ => 2 | 3 5 8 / => 3 | 3 6 9 / We can also use this shortcut for defining keyed tables @@ -456,7 +456,7 @@ f[2] / => 4 / however using a dictionary as a single argument can overcome this / allows for optional arguments or differing functionality d:`arg1`arg2`arg3!(1.0;2;"my function argument") -{x[`arg1]+x[`arg2]}[d] / => 3.0 +{x[`arg1]+x[`arg2]}[d] / => 3f / Functions in q see the global scope a:1 @@ -465,6 +465,7 @@ a:1 / However local scope obscures this a:1 {a:2;:a}[] / => 2 +a / => 1 / Functions cannot see nested scopes (only local and global) {local:1;{:local}[]}[] / throws error as local is not defined in inner function @@ -495,11 +496,11 @@ t:([]name:`Arthur`Thomas`Polly;age:35 32 52;height:180 175 160;sex:`m`m`f) / equivalent of SELECT * FROM t select from t / (must be lower case, and the wildcard is not necessary) -/ => name age height -/ => ----------------- -/ => Arthur 35 180 -/ => Thomas 32 175 -/ => Polly 52 160 +/ => name age height sex +/ => --------------------- +/ => Arthur 35 180 m +/ => Thomas 32 175 m +/ => Polly 52 160 f / Select specific columns select name,age from t @@ -524,6 +525,7 @@ select name, feet:floor height*0.032, inches:12*(height*0.032) mod 1 from t / => ------------------ / => Arthur 5 9.12 / => Thomas 5 7.2 +/ => Polly 5 1.44 / Including custom functions select name, growth:{[h;a]h%a}[height;age] from t @@ -535,18 +537,18 @@ select name, growth:{[h;a]h%a}[height;age] from t / The where clause can contain multiple statements separated by commas select from t where age>33,height>175 -/ => name age height -/ => ----------------- -/ => Arthur 35 180 +/ => name age height sex +/ => --------------------- +/ => Arthur 35 180 m / The where statements are executed sequentially (not the same as logical AND) select from t where age<40,height=min height -/ => name age height -/ => ----------------- -/ => Thomas 32 175 +/ => name age height sex +/ => --------------------- +/ => Thomas 32 175 m select from t where (age<40)&(height=min height) -/ => name age height -/ => --------------- +/ => name age height sex +/ => ------------------- / The by clause falls between select and from / and is equivalent to SQL's GROUP BY @@ -586,7 +588,7 @@ t / => Polly 52 160 f / Insert however is in place, it takes a table name, and new data -`t insert (`John;25;178;`m) +`t insert (`John;25;178;`m) / => ,3 t / => name age height sex / => --------------------- @@ -698,7 +700,7 @@ first each (1 2 3;4 5 6;7 8 9) / their behaviour differs based on the number of arguments the function they / are modifying receives. Here I'll summarise some of the most useful cases / a single argument function modified by scan given 2 args behaves like "do" -{x * 2}\[5;1] / => 1 2 4 8 16 3 (i.e. multiply by 2, 5 times) +{x * 2}\[5;1] / => 1 2 4 8 16 32 (i.e. multiply by 2, 5 times) {x * 2}/[5;1] / => 32 (using over only the final result is shown) / If the first argument is a function, we have the equivalent of "while" diff --git a/matlab.html.markdown b/matlab.html.markdown index 51b7bd4e..86b116c6 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -557,6 +557,8 @@ c = a + b ## More on Matlab -* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) +* [The official website](http://www.mathworks.com/products/matlab/) +* [The official MATLAB Answers forum](http://www.mathworks.com/matlabcentral/answers/) +* [Loren on the Art of MATLAB](http://blogs.mathworks.com/loren/) +* [Cleve's Corner](http://blogs.mathworks.com/cleve/) diff --git a/perl6.html.markdown b/perl6.html.markdown index 8fcf9a02..34ad70b7 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -4,6 +4,7 @@ language: perl6 filename: learnperl6.p6 contributors: - ["vendethiel", "http://github.com/vendethiel"] + - ["Samantha McVey", "https://cry.nu"] --- Perl 6 is a highly capable, feature-rich programming language made for at diff --git a/pl-pl/vim-pl.html.markdown b/pl-pl/vim-pl.html.markdown new file mode 100644 index 00000000..21c8c152 --- /dev/null +++ b/pl-pl/vim-pl.html.markdown @@ -0,0 +1,236 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Adam Bobowski", "https://github.com/Bobowski"] +lang: pl-pl +filename: LearnVim-pl.txt +--- + + +[Vim](www.vim.org) +(Vi IMproved) jest klonem popularnego edytora vi dla systemów Unix. +Zaprojektowany z myślą o prędkości edycji i zwiększeniu produktywności jest +wszechobecny na systemach UNIXopodobnych. Posiada wiele skrótów klawiszowych +do szybkiej nawigacji do wybranych miejsc w plikach oraz szybkiej edycji +danych fragmentów. + +## Podstawy nawigacji w Vim + +``` + vim <nazwapliku> # Otwórz <nazwapliku> w vim + :q # Zamknij vim + :w # Zapisz aktualny plik + :wq # Zapisz i wyjdź z vim + :q! # Wyjdź bez zapisywania + # ! *wymusza* wykonanie :q, dlatego nie wykonuje zapisu + :x # Zapisz i wyjdź, krótszy odpowiednik :wq + + u # Cofnij operację + CTRL+R # Powtórz operację + + h # Przesuń kursor w lewo + j # Przesuń kursor w dół + k # Przesuń kursor w górę + l # Przesuń kursor w prawo + + # Poruszanie w obrębie jednej lini + + 0 # Skocz do początku linii + $ # Skocz do końca linii + ^ # Skocz do pierwszego niebiałego znaku + + # Wyszukiwanie w tekście + + /slowo # Zaznacza wszystkie wystąpienia słowa za kursorem + ?slowo # Zaznacza wszystkie wystąpienia słowa przed kursorem + n # Przemieszcza kursor do następnego wystąpienia słowa + N # Przemieszcza kursor do poprzedniego wystąpenia słowa + + :%s/foo/bar/g # Zamień 'foo' na 'bar' w każdej linii tekstu + :s/foo/bar/g # Zamień 'foo' na 'bar' w aktualnej linii + + # Skoki do znaków + + f<znak> # Skocz do przodu i zatrzymaj się na <znak> + t<znak> # Skocz do przodu i zatrzymaj się przed <znak> + + # Na przykład, + f< # Skocz do przodu i zatrzymaj się na < + t< # Skocz do przodu i zatrzymaj się przed < + + # Moving by word + + w # Przesuń kursor do przodu o jedno słowo + b # Przesuń kursor do tyłu o jedno słowo + e # Przesuń kursor do końca aktualnego słowa + + # Inne znaki do przemieszczania się + + gg # Skocz na początek pliku + G # Skocz na koniec pliku + :NUM # Skocz do linii o numerze NUM + H # Skocz na górę ekranu + M # Skocz na środek ekranu + L # Skocz na dół ekranu +``` + +## Tryby: + +Vim oparty jest na koncepcji **trybów**. + +Command Mode - (Tryb komend) vim zaczyna w tym trybie, używany do nawigacji i wpisywania komend +Insert Mode - (Tryb wprowadzania) używany do wprowadzania zmian w pliku +Visual Mode - (Tryb wizualny) używany do zaznaczania tekstu i wykonywania komend na nim +Ex Mode - (Tryb Ex) + +``` + i # Przechodzi to trybu wprowadzania, przed pozycją kursora + a # Przechodzi do trybu wprowadzania, za pozycją kursora + v # Przechodzi do trybu wizualnego + : # Przechodzi do trybu ex + <esc> # Wychodzi z dowolnego aktywnego trybu do trybu komend + + # Kopiowanie i wklejanie tekstu + + y # Skopiuj zaznaczony tekst + yy # Skopiuj aktualną linię + d # Usuń zaznaczony tekst + dd # Usuń aktualną linię + p # Wklej skopiowany tekst za kursorem + P # Wklej skopiowany tekst przed kursorem + x # Usuń znak pod kursorem +``` + +## 'Gramatyka' vim'a + +Vim można traktować jako zbiór komend w formacie 'Akcja-Modyfikator-Obiekt', gdzie: + +Akcja - jedna z dostępnych akcji +Modyfikator - w jaki sposób wykonywana jest akcja +Obiekt - obiekt na którym wykonywana jest akcja + +Kilka ważnych przykładów Akcji, Modyfikatorów i Obiektów: + +``` + # 'Akcje' + + d # Usuń + c # Zmień + y # Skopiuj + v # Zaznacz + + # 'Modyfikatory' + + i # W środku + a # Dookoła + NUM # Liczba + f # Szuka czegoś i zatrzymuje się na tym + t # Szuka czegoś i zatrzymuje się przed tym + / # Znajduje napis od kursora naprzód + ? # Znajduje napis przed kursorem + + # 'Obiekty' + + w # Słowo + s # Zdanie + p # Paragraf + b # Blok + + # Przykładowe 'zdania' + + d2w # Usuń 2 słowa + cis # Zmień w zdaniu + yip # Skopiuj paragraf w którym jest kursor + ct< # Zamień na < + d$ # Usuń tekst do końca linii +``` + +## Pewne skróty i triki + + <!--TODO: Dodać więcej!--> +``` + > # Zrób wcięcie zaznaczonego bloku + < # Usuń wcięcie zaznaczonego bloku + :earlier 15m # Przywróć dokument do stanu z przed 15 minut + :later 15m # Odwróć efekt poprzedniej komendy + ddp # Zamień kolejnością kolejne linie, dd potem p + . # Powtórz poprzednią komendę +``` + +## Makra + +Makra są właściwie nagrywanymi akcjami. Gdy zaczynasz nagrywać makro, nagrywa ono +**każdą** akcję i komendę jaką wykonasz do momentu przerwania nagrywania. +Wywołanie makra wykonuje dokładnie te same operacje w tej samej kolejności. + +``` + qa # Zacznij nagrywać makro 'a' + q # Przerwij nagrywanie + @a # Odtwórz makro 'a' +``` + +### Konfiguracja ~/.vimrc + +Plik .vimrc może być użyty do skonfigurowania Vim'a przy jego starcie + +Poniżej zamieszczono przykładowy plik ~/.vimrc: + +``` +" Przykładowy ~/.vimrc +" 2016.10 + +" Wymagane aby korzystać z opcji iMproved +set nocompatible + +" Na podstawie typu pliku włącza inteligentne wcięcia i inne. +filetype indent plugin on + +" Włącz podkreślanie składni +syntax on + +" Lepsze uzupełnianie składni komend +set wildmenu + +" Wyszukiwanie będzie ignorować wielkość liter poza przypadkami gdy użyjemy wielkich liter +set ignorecase +set smartcase + +" Po otwarciu pliku gdzie nie jest zdefiniowane zachowanie wcięć +" zostanie zachowane wcięcie takie samo jak w aktualnej linii +set autoindent + +" Wyświetlaj numer lini +set number + +" Opcje wcięć, zmień w zależności od osobistych upodobań + +" Szerokość TAB w spacjach +set tabstop=4 + +" Liczba spacji w TAB podczas edycji +set softtabstop=4 + +" Liczba spacji gdy wykonywane są operacje wcięcia (>> i <<) +set shiftwidth=4 + +" Zamieniaj tabulatory na spacje +set expandtab + +" Aktywuj inteligentne tabulatory i spacje do wcięć i wyrównań +set smarttab +``` + +### Odniesienia [ENG] + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) diff --git a/powershell.html.markdown b/powershell.html.markdown index 492e7153..f34d5b4e 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -113,7 +113,7 @@ if ($Age -is [string]) { echo 'Adult' } -# Switch statements are more powerfull compared to most languages +# Switch statements are more powerful compared to most languages $val = "20" switch($val) { { $_ -eq 42 } { "The answer equals 42"; break } @@ -204,7 +204,7 @@ function foo([string]$name) { # Calling your function foo "Say my name" -# Functions with named parameters, parameter attributes, parsable documention +# Functions with named parameters, parameter attributes, parsable documentation <# .SYNOPSIS Setup a new website @@ -308,7 +308,7 @@ if (-not (Test-Path $Profile)) { notepad $Profile } # More info: `help about_profiles` -# For a more usefull shell, be sure to check the project PSReadLine below +# For a more useful shell, be sure to check the project PSReadLine below ``` Interesting Projects diff --git a/pt-br/jquery-pt.html.markdown b/pt-br/jquery-pt.html.markdown new file mode 100644 index 00000000..d49bea0f --- /dev/null +++ b/pt-br/jquery-pt.html.markdown @@ -0,0 +1,131 @@ +--- +category: tool +tool: jquery +contributors: + - ["Sawyer Charles", "https://github.com/xssc"] +translators: + - ["Nikolas Silva", "https://github.com/nikolassilva"] +filename: jquery-pt.js +lang: pt-br +--- + +jQuery é uma biblioteca JavaScript que te ajuda a "fazer mais, escrevendo menos". Ela faz com que muitas tarefas comuns em JavaScript sejam mais simples de escrever. jQuery é usado por grandes empresas e desenvolvedores do mundo todo. Ela torna o AJAX, manipulação de eventos, manipulação do DOM, entre outros, mais fácil e rápido. + +Pelo jQuery ser uma biblioteca JavaScript você deve [aprende-lo primeiro](https://learnxinyminutes.com/docs/pt-br/javascript-pt/) + +```js + + +/////////////////////////////////// +// 1. Seletores + +// Seletores no jQuery são usados para selecionar um elemento +var page = $(window); // Seleciona toda a viewport + +// Seletores também podem ser na forma do CSS +var paragraph = $('p'); // Seleciona todos elementos de parágrafo +var table1 = $('#table1'); // Seleciona o elemento com id 'table1' +var squares = $('.square'); // Seleciona todos elementos com classe 'square' +var square_p = $('p.square') // Seleciona todos elementos de parágrafo com a classe 'square' + + +/////////////////////////////////// +// 2. Eventos e Efeitos +// jQuery é muito bom em manipular o que acontece quando um evento é disparado +// Um evento muito usado é o 'ready' +// Você pode usar o método ready para esperar até que um elemento tenha terminado de carregar +$(document).ready(function(){ + // O código não será executado até que o documento carregue +}); +// Você também pode usar funções declaradas +function onAction() { + // Isso será executado quando um evento for disparado +} +$('#btn').click(onAction); // Chama 'onAction' quando o elemento receber um clique + +// Outros eventos comuns são: +$('#btn').dblclick(onAction); // Clique duplo +$('#btn').hover(onAction); // Mouse sobre elemento +$('#btn').focus(onAction); // Elemento recebe foco +$('#btn').blur(onAction); // Elemento perde foco +$('#btn').submit(onAction); // Envio de formulário +$('#btn').select(onAction); // Quando o elemento é selecionado +$('#btn').keydown(onAction); // Quando uma tecla é segurada +$('#btn').keyup(onAction); // Quando uma tecla é solta +$('#btn').keypress(onAction); // Quando uma tecla é pressionada +$('#btn').mousemove(onAction); // Quando o mouse é movido +$('#btn').mouseenter(onAction); // Quando o mouse entra no elemento +$('#btn').mouseleave(onAction); // Quando o mouse sai do elemento + + +// Eles também podem disparar os eventos em vez de manipulá-los, +// simplesmente deixando de passar os parâmetros +$('#btn').dblclick(); // Dispara um clique duplo no elemento + +// Você pode manipular múltiplos eventos usando o seletor apenas uma vez +$('#btn').on( + {dblclick: myFunction1} // Disparado num clique duplo + {blur: myFunction1} // Disparado quando perder o foco +); + +// Você pode mover e esconder elementos com alguns métodos de efeito +$('.table').hide(); // Esconde o elemento + +// Nota: chamar uma função nesse método ainda irá esconder o elemento +$('.table').hide(function(){ + // Elemento é escondido e a função é executada +}); + +// Você pode guardar seletores em variáveis +var tables = $('.table'); + +// Alguns métodos básicos de manipulação do DOM: +tables.hide(); // Esconde elemento(s) +tables.show(); // Exibe elemento(s) +tables.toggle(); // Alterna entre esconder/exibir +tables.fadeOut(); // Efeito fade out +tables.fadeIn(); // Efeito fade in +tables.fadeToggle(); // Alterna entre fade out/in +tables.fadeTo(0.5); // Efeito fade com opacidade específica (entre 0 e 1) +tables.slideUp(); // Efeito de deslize pra cima +tables.slideDown(); // Efeito de deslize pra baixo +tables.slideToggle(); // Alterna entre deslizar pra cima/baixo + +// Todos os métodos acima levam velocidade (em milissegundos) e uma função callback +tables.hide(1000, myFunction); // Esconde o elemento em 1 segundo e chama a função + +// No fadeTo é obrigatório definir a opacidade como segundo parâmetro +tables.fadeTo(2000, 0.1, myFunction); // 2 segundos de fade para 0.1 de opacidade e chama a função + +// Você pode fazer animações mais avançadas com o método animate +tables.animate({'margin-top':"+=50", height: "100px"}, 500, myFunction); +// O método animate leva um objeto com valores CSS, +// um parâmetro de opções para melhorar a animação +// e uma função callback, como de costume + +/////////////////////////////////// +// 3. Manipulação + +// São similares aos efeitos, mas podem fazer mais +$('div').addClass('taming-slim-20'); // Adiciona a classe taming-slim-20 em todas as divs + +// Métodos comuns de manipulação +$('p').append('Hello world'); // Adiciona ao final do elemento +$('p').attr('class'); // Obtém o valor de um atributo +$('p').attr('class', 'content'); // Define o valor de um atributo +$('p').hasClass('taming-slim-20'); // Retorna true se tiver a classe +$('p').height(); // Obtém/define a altura do elemento + + +// Pra maioria dos métodos de manipulação, pegar o valor de um +// elemento só afetará o primeiro deles +$('p').height(); // Obtém a altura da primeira tag 'p' + +// Você pode usar o método each pra percorrer os elementos +var heights = []; +$('p').each(function() { + heights.push($(this).height()); // Adiciona a altura das tags 'p' na array +}); + + +``` diff --git a/python3.html.markdown b/python3.html.markdown index 9ce7790b..839d66fd 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -37,8 +37,6 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 - -# Except division which defaults to rounding down 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -47,13 +45,9 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# When one of the inputs is a float, result is a float +# The result of division is always a float 10.0 / 3 # => 3.3333333333333335 -# to force this behavior on integers, use -from __future__ import division -10 / 3 # => 3.3333333333333335 - # Modulo operation 7 % 3 # => 1 diff --git a/red.html.markdown b/red.html.markdown index 05da3c3f..6d10fe8f 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -23,17 +23,17 @@ from any platform to any other platform. And it will do this all from a binary e Ready to learn your first Red? ``` -All text before the header will be treated as comment, as long as you avoid using the -word "red" starting with a capital "R" in this pre-header text. This is a temporary -shortcoming of the used lexer but most of the time you start your script or program -with the header itself. +All text before the header will be treated as comment, as long as you avoid +using the word "red" starting with a capital "R" in this pre-header text. +This is a temporary shortcoming of the used lexer but most of the time you +start your script or program with the header itself. + The header of a red script is the capitalized word "red" followed by a -whitespace character followed by a block of square brackets []. -The block of brackets can be filled with useful information about this script or -program: the author's name, the filename, the version, the license, a summary of -what the program does or any other files it needs. -The red/System header is just like the red header, only saying "red/System" and -not "red". +whitespace character followed by a block of square brackets []. The block of +brackets can be filled with useful information about this script or program: +the author's name, the filename, the version, the license, a summary of what +the program does or any other files it needs. The red/System header is just +like the red header, only saying "red/System" and not "red". Red [] @@ -50,9 +50,9 @@ comment { ; no need to restrict this to a 'main' function. ; Valid variable names start with a letter and can contain numbers, -; variables containing only capital A thru F and numbers and ending with 'h' are -; forbidden, because that is how hexadecimal numbers are expressed in Red and -; Red/System. +; variables containing only capital A thru F and numbers and ending with 'h' +; are forbidden, because that is how hexadecimal numbers are expressed in Red +; and Red/System. ; assign a value to a variable using a colon ":" my-name: "Red" @@ -63,8 +63,8 @@ reason-for-using-the-colon: {Assigning values using the colon makes } is-this-name-valid?: true -; print output using print, or prin for printing without a newline or linefeed at the -; end of the printed text. +; print output using print, or prin for printing without a newline or linefeed +; at the end of the printed text. prin " My name is " print my-name My name is Red @@ -72,7 +72,7 @@ My name is Red print ["My name is " my-name lf] My name is Red -; In case you haven't already noticed: statements do NOT end with a semicolon ;-) +; If you haven't already noticed: statements do NOT end with a semicolon ;-) ; ; Datatypes @@ -85,13 +85,13 @@ My name is Red ; Some of the available types are integer! string! block! ; Declaring variables before using them? -; Red knows by itself what variable is best to use for the data you want to use it -; for. +; Red knows by itself what variable is best to use for the data you want to +; use it for. ; A variable declaration is not always necessary. ; It is considered good coding practise to declare your variables, ; but it is not forced upon you by Red. -; You can declare a variable and specify its type. a variable's type determines its -; size in bytes. +; You can declare a variable and specify its type. a variable's type +; determines its size in bytes. ; Variables of integer! type are usually 4 bytes or 32 bits my-integer: 0 @@ -111,10 +111,10 @@ i2 - i1 ; result 1 i2 * i1 ; result 2 i1 / i2 ; result 0 (0.5, but truncated towards 0) -; Comparison operators are probably familiar, and unlike in other languages you -; only need a single '=' sign for comparison. -; There is a boolean like type in Red. It has values true and false, but also the -; values on/off or yes/no can be used +; Comparison operators are probably familiar, and unlike in other languages +; you only need a single '=' sign for comparison. +; There is a boolean like type in Red. It has values true and false, but also +; the values on/off or yes/no can be used 3 = 2 ; result false 3 != 2 ; result true @@ -127,14 +127,14 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; Control Structures ; ; if -; Evaluate a block of code if a given condition is true. IF does not return any value, -; so cannot be used in an expression. +; Evaluate a block of code if a given condition is true. IF does not return +; any value, so cannot be used in an expression. if a < 0 [print "a is negative"] ; either -; Evaluate a block of code if a given condition is true, else evaluate an alternative -; block of code. If the last expressions in both blocks have the same type, EITHER can -; be used inside an expression. +; Evaluate a block of code if a given condition is true, else evaluate an +; alternative block of code. If the last expressions in both blocks have the +; same type, EITHER can be used inside an expression. either a < 0 [ either a = 0 [ msg: "zero" @@ -172,8 +172,8 @@ until [ ] ; will output: ooooo -; Note that the loop will always be evaluated at least once, even if the condition is -; not met from the beginning. +; Note that the loop will always be evaluated at least once, even if the +; condition is not met from the beginning. ; while ; While a given condition is met, evaluate a block of code. diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown new file mode 100644 index 00000000..5cf95fc4 --- /dev/null +++ b/ru-ru/html-ru.html.markdown @@ -0,0 +1,128 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Lana Tim", "https://github.com/LanaTim"] +--- + +HTML расшифровывается как Hypertext Markup Language(гипертекстовый язык разметки). +Это язык используют для написания страниц для World Wide Web(всемирной паутины). +Это язык разметки позволяет писать веб-страниц с помощью кода, чтобы определять, +как должны быть отображены текст и данные. +На самом деле, HTML файлы представляют собой простые текстовые файлы. +Что такое разметка? Это способ организации данных страницы, +путем открытия и закрытия тегов(помещая данные внутрь этих тегов). +Эта разметка служит, чтобы придать значение тексту, который он окружает. +Как и в других языках программирования, HTML имеет много версий. Здесь мы будем говорить о HTML5. + + +**Примечание:** Вы можете тестировать различные теги и элементы по мере продвижения +через учебник на сайте, как [codepen](http://codepen.io/pen/) для того, чтобы увидеть +их влияние, понять, как они работают и ознакомиться с языком. +В данной статье рассматривается в основном HTML синтаксис и некоторые полезные советы. + +```html +<!-- Комментарии заключаются как эта лини\! --> + +<!-- #################### Теги #################### --> + +<!-- Ниже приведен пример HTML-файл, который мы будем анализировать. --> + +<!doctype html> + <html> + <head> + <title>Мой сайт</title> + </head> + <body> + <h1>Привет, мир!</h1> + <a href = "http://codepen.io/anon/pen/xwjLbZ"> + Переходите сюда, чтоб посмотреть как это выглядит. + </a> + <p>Это параграф.</p> + <p>Это другой параграф.</p> + <ul> + <li>Это элемент не нумерованного списка (маркированный список)</li> + <li>Это другой элемент</li> + <li>Это последний элемент в списке</li> + </ul> + </body> + </html> + +<!-- HTML-файл всегда начинается с указанием браузеру, что страница это HTML. --> +<!doctype html> + +<!-- После этого, страница начинается с <html> тега. --> +<html> + +<!-- страница будет закрыта в конце с помощью тега </html>. --> +</html> + +<!-- Ничто не должно появиться после этого заключительного тега. --> + +<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>), мы находим: --> + +<!-- Заголовок определяется <head> (it он должен быть закрыт </head>). --> +<!-- Заголовок содержит описание и дополнительную информацию, которая не отображается; это метаданные. --> + +<head> + <title>Мой сайт</title><!-- Тег <title> указывает браузеру заголовок, чтобы показать в строке заголовка названия и вкладки браузера окна. --> +</head> + +<!-- После секция <head>, находится секция - <body> --> +<!-- До этого момента, ничего описаное не будет отображаться в окне браузера. --> +<!-- Мы должны наполнить <body> содержанием, которое будет отображаться. --> + +<body> + <h1>Hello, world!</h1> <!-- Тег h1 создает заголовок. --> + <!-- Так же существуют другие заголовки от имеющего большее значение <h1> по убыванию к <h6>. --> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите сюда, чтоб посмотреть как это выглядит.</a> + <!--гиперссылка на URL, заданнf атрибутом href="" --> + <p>Это параграф.</p> <!-- Тег <p> позволяет нам добавдять текст на странице HTML. --> + <p>Это другой параграф.</p> + <ul> <!-- Тег <ul> создает маркированный список. --> + <!-- Для того, чтобы иметь пронумерованный список лучше использовать <ol> + тогда первый элемент будет иметь значение 1. для второго элемента, 2. и так далее. --> + <li>Это элемент в не нумерованном списке (маркированный список)</li> + <li>Это еще один элемент</li> + <li>И это последний пункт в списке</li> + </ul> +</body> + +<!-- Вот так просто можно создать HTML страницу. --> + +<!--Но можно добавить множество дополнительных типов HTML тегов. --> + +<!-- Для вставки картинки --> +<img src="http://i.imgur.com/XWG0O.gif"/> <!-- Источник изображения указывается с помощью атрибута src="" --> +<!-- Источником может быть URL или даже путь к файлу на вашем компьютере. --> + +<!-- Кроме того, можно создать таблицу. --> + +<table> <!-- Мы открыли <table> элемент. --> + <tr> <!-- <tr> позволяет создать ряд. --> + <th>Первый заголовок</th> <!-- <th> позволяет дать название для столбца таблицы. --> + <th>Второй заголовок</th> + </tr> + <tr> + <td>Первый ряд, первая колонка</td> <!-- <td> позволяет нам создать ячейку таблицы. --> + <td>Первый ряд, вторая колонка</td> + </tr> + <tr> + <td>Второй ряв, первая колонка</td> + <td>Второй ряд, вторая колонка</td> + </tr> +</table> + +``` + +## Применение + +HTML файлы имеют окончание(расширение) `.html`. + +## Узнать больше + +* [википедиа](https://ru.wikipedia.org/wiki/HTML) +* [HTML учебник](https://developer.mozilla.org/ru/docs/Web/HTML) +* [htmlbook](http://htmlbook.ru/) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 76b3777c..181368de 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -58,8 +58,10 @@ $int1 = 12; // => 12 $int2 = -12; // => -12 $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) $int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) + // Двоичная запись integer доступна начиная с PHP 5.4.0. $int5 = 0b11111111; // 255 (0b в начале означает двоичное число) + // Дробные числа $float = 1.234; $float = 1.2e3; @@ -87,6 +89,7 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' // Специальные (escape) символы работают только в двойных кавычках $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; + // Заключайте переменные в фигурные скобки, если это необходимо $apples = "I have {$number} apples to eat."; $oranges = "I have ${number} oranges to eat."; @@ -723,8 +726,121 @@ ChildClass::test(); /* I'm a ParentClass But I'm ChildClass + +/********************** +* Позднее статическое связывание. +* +*/ + +class ParentClass +{ + public static function who() + { + echo "I'm a " . __CLASS__ . "\n"; + } + + public static function test() + { + // self ссылается на класс в котором определен метод. + self::who(); + // static ссылается на класс в котором метод вызван. + static::who(); + } +} + +ParentClass::test(); +/* +I'm a ParentClass +I'm a ParentClass +*/ + +class ChildClass extends ParentClass +{ + public static function who() + { + echo "But I'm " . __CLASS__ . "\n"; + } +} + +ChildClass::test(); +/* +I'm a ParentClass +But I'm ChildClass +*/ + + +/********************** +* Магические константы +* +*/ + +// Возвращает имя текущего класса. Должно быть использовано внутри класса. +echo "Current class name is " . __CLASS__; + +// Возвращает полный путь текущей папки из которой вызван файл. +echo "Current directory is " . __DIR__; + + // Обычно используют в таких случаях: + require __DIR__ . '/vendor/autoload.php'; + +// Возвращает полный путь к текущему файлу. +echo "Current file path is " . __FILE__; + +// Возвращает имя текущей функции. +echo "Current function name is " . __FUNCTION__; + +// Возвращает номер текущей линии. +echo "Current line number is " . __LINE__; + +// Возвращает имя текущего метода. Возвращает только если вызван внутри метода. +echo "Current method is " . __METHOD__; + +// Возвращает имя текущего пространства имен. +echo "Current namespace is " . __NAMESPACE__; + +// Возвращает имя текущего трейта. +// Возвращает только если испольщуется внутри трейта. +echo "Current namespace is " . __TRAIT__; + + +/********************** +* Обработка ошибок +* */ +// Простую обработку ошибок можно произвести спомощью try catch блока. + +try { + // Выполняем что-то +} catch (Exception $e) { + // Обработка исключения +} + +// При использовании try catch блока в области вилимости, стоит использовать +// следующий подход: + +try { + // Do something +} catch (\Exception $e) { + // Обработка исключения +} + +// Специальное(кастомное) исключение - exceptions + +class MyException extends Exception {} + +try { + + $condition = true; + + if ($condition) { + throw new MyException('Something just happend'); + } + +} catch (MyException $e) { + // Обработка исключения +} + ``` ## Смотрите также: @@ -734,4 +850,4 @@ But I'm ChildClass Если вы раньше пользовались языком с хорошей организацией пакетов, посмотрите [Composer](http://getcomposer.org/). -Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards). +Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards). diff --git a/ru-ru/xml-ru.html.markdown b/ru-ru/xml-ru.html.markdown index b0096b75..bf3f22b0 100644 --- a/ru-ru/xml-ru.html.markdown +++ b/ru-ru/xml-ru.html.markdown @@ -128,3 +128,18 @@ XML-документ, который следует описанию докум </book> </bookstore> ``` + +## DTD совместимость и определение XML Schema(схем/структуры) + +Поддержка DTDs является повсеместным, потому что это довольно старая технология. К сожалению, современные функции XML как пространств имен(namespaces) не поддерживаются DTDs. Определения XML-схемы (XSDs) предназначены для замены DTDs которая в свою очередь предназначена для определения грамматики XML-документа. + +## Ресурсы + +* [Валидатор XML (ссылка на английском языке)](http://www.xmlvalidation.com) + +## Для будущего прочтения + +* [XML Schema Definitions Tutorial (ссылка на английском языке)](http://www.w3schools.com/schema/) +* [DTD руководство (ссылка на английском языке)](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML руководство (ссылка на английском языке)](http://www.w3schools.com/xml/default.asp) +* [использование XPath запросов для парсинга XML (ссылка на английском языке)](http://www.w3schools.com/xml/xml_xpath.asp) diff --git a/scala.html.markdown b/scala.html.markdown index 5e3ece2d..d33b6234 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -19,20 +19,20 @@ Scala - the scalable language Setup Scala: 1) Download Scala - http://www.scala-lang.org/downloads - 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable + 2) Unzip/untar to your favorite location and put the bin subdir in your `PATH` environment variable */ /* Try the REPL - - Scala has a tool called the REPL (Read-Eval-Print Loop) that is anologus to + + Scala has a tool called the REPL (Read-Eval-Print Loop) that is anologus to commandline interpreters in many other languages. You may type any Scala expression, and the result will be evaluated and printed. - - The REPL is a very handy tool to test and verify code. Use it as you read + + The REPL is a very handy tool to test and verify code. Use it as you read this tutorial to quickly explore concepts on your own. */ - + // Start a Scala REPL by running `scala`. You should see the prompt: $ scala scala> @@ -50,7 +50,7 @@ res1: Int = 6 scala> :type (true, 2.0) (Boolean, Double) -// REPL sessions can be saved +// REPL sessions can be saved scala> :save /sites/repl-test.scala // Files can be loaded into the REPL @@ -59,7 +59,7 @@ Loading /sites/repl-test.scala... res2: Int = 4 res3: Int = 6 -// You can search your recent history +// You can search your recent history scala> :h? 1 2 + 2 2 res0 + 2 @@ -594,7 +594,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared * best practices around them. We only include this section in the tutorial * because they are so commonplace in Scala libraries that it is impossible to * do anything meaningful without using a library that has implicits. This is - * meant for you to understand and work with implicts, not declare your own. + * meant for you to understand and work with implicits, not declare your own. */ // Any value (vals, functions, objects, etc) can be declared to be implicit by diff --git a/sk-sk/elixir.html.markdown b/sk-sk/elixir.html.markdown index baadbc0f..2401f92e 100644 --- a/sk-sk/elixir.html.markdown +++ b/sk-sk/elixir.html.markdown @@ -7,7 +7,7 @@ contributors: translators: - ["Peter Szatmary", "https://github.com/peterszatmary"] lang: sk-sk -filename: learnelixir.ex +filename: learnelixir-sk.ex --- Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym @@ -215,7 +215,7 @@ cond do end # Je bežné nastaviť poslednú podmienku rovnajúcu sa `true` , ktorá bude vždy -zodpovedať. +# zodpovedať. cond do 1 + 1 == 3 -> "Nebudem nikdy videný" @@ -310,12 +310,12 @@ defmodule Geometria do end Geometria.oblast({:obdlznik, 2, 3}) #=> 6 -Geometry.oblast({:kruh, 3}) #=> 28.25999999999999801048 +Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048 # Geometria.oblast({:kruh, "nie_je_cislo"}) #=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1 # Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru -defmodule Recurzia do +defmodule Rekurzia do def sumuj_zoznam([hlavicka | schvost], acc) do sumuj_zoznam(chvost, acc + hlavicka) end @@ -325,7 +325,7 @@ defmodule Recurzia do end end -Recurzia.sumuj_zoznam([1,2,3], 0) #=> 6 +Rekurzia.sumuj_zoznam([1,2,3], 0) #=> 6 # Elixir moduly podporujú atribúty, existujú vstavané atribúty a takisto # môžte pridávať vlastné. @@ -422,7 +422,7 @@ end # Kompiluj modul a vytvor proces, ktorý vyhodnotí `slucka_oblasti` v shelli -pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +pid = spawn(fn -> Geometria.slucka_oblasti() end) #=> #PID<0.40.0> # Alternatívne pid = spawn(Geometria, :slucka_oblasti, []) @@ -458,13 +458,13 @@ Agent.update(moj_agent, fn farby -> ["modra" | farby] end) ## Referencie -* [Začíname](http://elixir-lang.org/getting-started/introduction.html) from the +* [Začíname](http://elixir-lang.org/getting-started/introduction.html) z [Elixir stránky](http://elixir-lang.org) * [Elixir dokumentácia](http://elixir-lang.org/docs/master/) -* ["Elixir programovanie"](https://pragprog.com/book/elixir/programming-elixir) - by Dave Thomas +* [Elixir programovanie](https://pragprog.com/book/elixir/programming-elixir) + od Dave Thomasa * [Elixir ťahák](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) -* ["Nauč sa kúsok Erlangu pre veľké dobro!"](http://learnyousomeerlang.com/) by -Fred Hebert -* ["Erlang programovanie: Softvér pre konkurentný svet"](https://pragprog -.com/book/jaerlang2/programming-erlang) by Joe Armstrong +* [Nauč sa kúsok Erlangu pre veľké dobro!](http://learnyousomeerlang.com/) od +Freda Heberta +* [Erlang programovanie: Softvér pre konkurentný svet](https://pragprog +.com/book/jaerlang2/programming-erlang) od Joe Armstronga diff --git a/tests/encoding.rb b/tests/encoding.rb new file mode 100644 index 00000000..a0b3b184 --- /dev/null +++ b/tests/encoding.rb @@ -0,0 +1,32 @@ +#!/usr/bin/env ruby +require 'charlock_holmes' +$file_count = 0; +markdown_files = Dir["./**/*.html.markdown"] +markdown_files.each do |file| + begin + contents = File.read(file) + detection = CharlockHolmes::EncodingDetector.detect(contents) + case detection[:encoding] + when 'UTF-8' + $file_count = $file_count + 1 + when 'ISO-8859-1' + $file_count = $file_count + 1 + when /ISO-8859/ + puts "Notice: #{file} was detected as #{detection[:encoding]} encoding. Everything is probably fine." + $file_count = $file_count + 1 + else + puts "WARNING #{file} was detected as #{detection[:encoding]} encoding. Please save the file in UTF-8!" + end + rescue Exception => msg + puts msg + end +end +files_failed = markdown_files.length - $file_count +if files_failed != 0 + puts "FAILURE!!! #{files_failed} files were unable to be validated as UTF-8!" + puts "Please resave the file as UTF-8." + exit 1 +else + puts "Success. All #{$file_count} files passed UTF-8 validity checks." + exit 0 +end diff --git a/tests/yaml.rb b/tests/yaml.rb new file mode 100644 index 00000000..0ed918e0 --- /dev/null +++ b/tests/yaml.rb @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby +require 'yaml'; +$file_count = 0; +markdown_files = Dir["./**/*.html.markdown"] +markdown_files.each do |file| + begin + YAML.load_file(file) + $file_count = $file_count + 1 + rescue Exception => msg + puts msg + end +end +files_failed = markdown_files.length - $file_count +if files_failed != 0 + puts "FAILURE!!! #{files_failed} files were unable to be parsed!" + puts "Please check the YAML headers for the documents that failed!" + exit 1 +else + puts "All #{$file_count} files were verified valid YAML" + exit 0 +end diff --git a/vim.html.markdown b/vim.html.markdown index edbc3da7..96cc20cb 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -156,6 +156,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': :later 15m # Reverse above command ddp # Swap position of consecutive lines, dd then p . # Repeat previous action + :w !sudo tee % # Save the current file as root ``` ## Macros diff --git a/yaml.html.markdown b/yaml.html.markdown index a1ef0d38..95adbd83 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -25,9 +25,9 @@ YAML doesn't allow literal tab characters at all. key: value another_key: Another value goes here. a_number_value: 100 -# If you want to use number 1 as a value, you have to enclose it in quotes, -# otherwise, YAML parser will assume that it is a boolean value of true. scientific_notation: 1e+12 +# The number 1 will be interpreted as a number, not a boolean. if you want +# it to be intepreted as a boolean, use true boolean: true null_value: null key with spaces: value diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 2d181de0..657a913d 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -214,7 +214,7 @@ hash.keys #=> ['color', 'number'] hash['color'] #=> 'green' hash['number'] #=> 5 -# 查询一个不存在地键将会返回nil +# 查询一个不存在的键将会返回nil hash['nothing here'] #=> nil # 从Ruby 1.9开始,用符号作为键的时候有特别的记号表示: |