diff options
-rw-r--r-- | HTML-fr.html.markdown | 115 | ||||
-rw-r--r-- | binary-search.html.markdown | 2 | ||||
-rw-r--r-- | cmake.html.markdown | 2 | ||||
-rw-r--r-- | cs-cz/go.html.markdown | 431 | ||||
-rw-r--r-- | css.html.markdown | 52 | ||||
-rw-r--r-- | es-es/asymptotic-notation-es.html.markdown | 1 | ||||
-rw-r--r-- | es-es/ruby-ecosystem-es.html.markdown | 157 | ||||
-rw-r--r-- | fortran95.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/HTML-fr.html.markdown | 2 | ||||
-rw-r--r-- | html.html.markdown | 120 | ||||
-rw-r--r-- | id-id/markdown.html.markdown | 1 | ||||
-rw-r--r-- | it-it/rust-it.html.markdown | 1 | ||||
-rw-r--r-- | java.html.markdown | 2 | ||||
-rw-r--r-- | jquery.html.markdown | 138 | ||||
-rw-r--r-- | meteor.html.markdown | 567 | ||||
-rw-r--r-- | nl-nl/markdown-nl-html.markdown | 256 | ||||
-rw-r--r-- | pt-br/elixir.html.markdown | 1 | ||||
-rw-r--r-- | pt-br/python3-pt.html.markdown | 2 | ||||
-rw-r--r-- | python3.html.markdown | 10 | ||||
-rw-r--r-- | tmux.html.markdown | 10 | ||||
-rwxr-xr-x | toml.html.markdown | 274 | ||||
-rw-r--r-- | tr-tr/c-tr.html.markdown | 2 | ||||
-rw-r--r-- | vim.html.markdown | 16 | ||||
-rw-r--r-- | zh-cn/c++-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/vim-cn.html.markdown | 236 |
25 files changed, 1998 insertions, 404 deletions
diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown deleted file mode 100644 index fdde9107..00000000 --- a/HTML-fr.html.markdown +++ /dev/null @@ -1,115 +0,0 @@ ---- -language: html -filename: learnhtml-fr.html -contributors: - - ["Christophe THOMAS", "https://github.com/WinChris"] -lang: fr-fr ---- -HTML signifie HyperText Markup Language. -C'est un langage (format de fichiers) qui permet d'écrire des pages internet. -C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). -Les fichiers HTML sont en réalité de simple fichier texte. -Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. -Ce balisage sert à donner une signification au texte ainsi entouré. -Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. - -**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. -Cet article porte principalement sur la syntaxe et quelques astuces. - - -```HTML -<!-- Les commentaires sont entouré comme cette ligne! --> - -<!-- #################### Les balises #################### --> - -<!-- Voici un exemple de fichier HTML que nous allons analyser --> -<!-- Venez voir ce que ça donne --> - -<!doctype html> - <html> - <head> - <title>Mon Site</title> - </head> - <body> - <h1>Hello, world!</h1> - <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> - <p>Ceci est un paragraphe</p> - <p>Ceci est un autre paragraphe</p> - <ul> - <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> - <li>Ceci est un autre item</li> - <li>Et ceci est le dernier item de la liste</li> - </ul> - </body> - </html> - -<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML --> - -<!doctype html> - -<!-- Après ça on commence par ouvrir une balise <html> --> -<html> -</html> -<!-- Et puis on la referme à la fin du fichier avec </html> --> -<!-- après cette balise de fin, plus rien ne doit apparaître. --> - -<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : --> - -<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) --> -<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées --> - -<head> - <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre --> -</head> - -<!-- Après la balise <head>, on trouve la balise <body> --> -<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. --> -<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu --> - -<body> - <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre --> - <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) --> - <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" --> - <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html --> - <p>Ceci est un autre paragraphe</p> - <ul> <!-- La balise <ul> permet d'introduire une liste à puces --> - <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc --> - <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> - <li>Ceci est un autre item</li> - <li>Et ceci est le dernier item de la liste</li> - </ul> -</body> - -<!-- Voilà comment créer un fichier HTML simple --> - -<!-- Mais il est possible d'ajouter encore des balises plus spécifiques --> - -<!-- Pour insérer une image --> -<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" --> -<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur --> - -<!-- Il est possible de réaliser des tableaux également --> - -<table> <!-- On ouvre la balise <table> --> - <tr> <!-- <tr> permet de créer une ligne --> - <th>First Header</th> <!-- <th> permet de créer un titre au tableau --> - <th>Second Header</th> - </tr> - <tr> - <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule --> - <td>Première ligne, deuxième cellule</td> - </tr> - <tr> - <td>Deuxième ligne, première cellule</td> - <td>Deuxième ligne, deuxième cellule</td> - </tr> -</table> - -## Utilisation - -Le HTML s'écrit dans des fichiers `.html`. - -## En savoir plus - -* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) -* [W3School](http://www.w3schools.com/html/html_intro.asp) diff --git a/binary-search.html.markdown b/binary-search.html.markdown index 92df4875..ce436b44 100644 --- a/binary-search.html.markdown +++ b/binary-search.html.markdown @@ -9,7 +9,7 @@ contributors: ## Why Binary Search? -Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. +Searching is one of the prime problems in the domain of Computer Science. Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. ## Introduction diff --git a/cmake.html.markdown b/cmake.html.markdown index a2c8cc8a..45cf0585 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -45,7 +45,7 @@ cmake_minimum_required (VERSION 2.8) cmake_minimum_required (VERSION 2.8 FATAL_ERROR) # We setup the name for our project. After we do that, this will change some -# directories naming convention genearted by CMake. We can send the LANG of +# directories naming convention generated by CMake. We can send the LANG of # code as second param project (learncmake C) diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown new file mode 100644 index 00000000..36217414 --- /dev/null +++ b/cs-cz/go.html.markdown @@ -0,0 +1,431 @@ +--- +name: Go +category: language +language: Go +filename: learngo-cs.go +lang: cs-cz +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Ondra Linek", "https://github.com/defectus/"] +--- + +Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední +trend ve světě počítačové vědy, ale je to nejrychlejší a nejnovější způsob, +jak řešit realné problémy. + +Go používá známé koncepty imperativních jazyků se statickým typováním. +Rychle se kompiluje a také rychle běží. Přidává snadno pochopitelnou +podporu konkurenčnosti, což umožňuje využít výhody multi-core procesorů a +jazyk také obsahuje utility, které pomáhají se škálovatelným programováním. + +Go má již v základu vynikající knihovnu a je s ním spojená nadšená komunita. + +```go +// Jednořádkový komentář +/* Několika + řádkový komentář */ + +// Každý zdroják začíná deklarací balíčku (package) +// Main je vyhrazené jméno, které označuje spustitelný soubor, +// narozdíl od knihovny +package main + +// Importní deklarace říkají, které knihovny budou použity v tomto souboru. +import ( + "fmt" // Obsahuje formátovací funkce a tisk na konzolu + "io/ioutil" // Vstupně/výstupní funkce + m "math" // Odkaz na knihovnu math (matematické funkce) pod zkratkou m + "net/http" // Podpora http protokolu, klient i server. + "strconv" // Konverze řetězců, např. na čísla a zpět. +) + +// Definice funkce. Funkce main je zvláštní, je to vstupní bod do programu. +// Ať se vám to líbí, nebo ne, Go používá složené závorky +func main() { + // Println vypisuje na stdout. + // Musí být kvalifikováno jménem svého balíčko, ftm. + fmt.Println("Hello world!") + + // Zavoláme další funkci + svetPoHello() +} + +// Funkce mají své parametry v závorkách +// Pokud funkce nemá parametry, tak musíme stejně závorky uvést. +func svetPoHello() { + var x int // Deklarace proměnné. Proměnné musí být před použitím deklarované + x = 3 // Přiřazení hodnoty do proměnné + // Existuje "krátká" deklarace := kde se typ proměnné odvodí, + // proměnná vytvoří a přiřadí se jí hodnota + y := 4 + sum, prod := naucSeNasobit(x, y) // Funkce mohou vracet více hodnot + fmt.Println("sum:", sum, "prod:", prod) // Jednoduchý výstup + naucSeTypy() // < y minut je za námi, je čas učit se víc! +} + +/* <- začátek mnohořádkového komentáře +Funkce mohou mít parametry a (několik) návratových hodnot. +V tomto případě jsou `x`, `y` parametry a `sum`, `prod` jsou návratové hodnoty. +Všiměte si, že `x` a `sum` jsou typu `int`. +*/ +func naucSeNasobit(x, y int) (sum, prod int) { + return x + y, x * y // Vracíme dvě hodnoty +} + +// zabudované typy a literáty. +func naucSeTypy() { + // Krátká deklarace většinou funguje + str := "Learn Go!" // typ řetězec. + + s2 := `"surový" literát řetězce +může obsahovat nové řádky` // Opět typ řetězec. + + // Můžeme použít ne ASCII znaky, Go používá UTF-8. + g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8 + + f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou. + c := 3 + 4i // complex128, interně uložené jako dva float64. + + // takhle vypadá var s inicializací + var u uint = 7 // Číslo bez znaménka, jehož velikost záleží na implementaci, + // stejně jako int + var pi float32 = 22. / 7 + + // takto se převádí typy za pomoci krátké syntaxe + n := byte('\n') // byte je jiné jméno pro uint8. + + // Pole mají fixní délku, které se určuje v době kompilace. + var a4 [4]int // Pole 4 intů, všechny nastaveny na 0. + a3 := [...]int{3, 1, 5} // Pole nastaveno na tři hodnoty + // elementy mají hodntu 3, 1 a 5 + + // Slicy mají dynamickou velikost. Pole i slacy mají své výhody, + // ale většinou se používají slicy. + s3 := []int{4, 5, 9} // Podobně jako a3, ale není tu výpustka. + s4 := make([]int, 4) // Alokuj slice 4 intů, všechny nastaveny na 0. + var d2 [][]float64 // Deklarace slicu, nic se nealokuje. + bs := []byte("a slice") // Přetypování na slice + + // Protože jsou dynamické, můžeme ke slicům přidávat za běhu + // Přidat ke slicu můžeme pomocí zabudované funkce append(). + // Prvním parametrem je slice, návratová hodnota je aktualizovaný slice. + s := []int{1, 2, 3} // Výsledkem je slice se 3 elementy. + s = append(s, 4, 5, 6) // Přidány další 3 elementy. Slice má teď velikost 6. + fmt.Println(s) // Slice má hodnoty [1 2 3 4 5 6] + + // Pokud chceme k poli přičíst jiné pole, můžeme předat referenci na slice, + // nebo jeho literát a přidat výpustku, čímž se slicu "rozbalí" a přidá se k + // původnímu slicu. + s = append(s, []int{7, 8, 9}...) // druhým parametrem je literát slicu. + fmt.Println(s) // slice má teď hodnoty [1 2 3 4 5 6 7 8 9] + + p, q := naucSePraciSPameti() // Deklarujeme p a q jako typ pointer na int. + fmt.Println(*p, *q) // * dereferencuje pointer. Tím se vypíší dva inty. + + // Mapy jsou dynamické rostoucí asociativní pole, jako hashmapa, nebo slovník + // (dictionary) v jiných jazycích + m := map[string]int{"tri": 3, "ctyri": 4} + m["jedna"] = 1 + + // Napoužité proměnné jsou v Go chybou. + // Použijte podtržítko, abychom proměnno "použili". + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Výpis promenné se počítá jako použití. + fmt.Println(s, c, a4, s3, d2, m) + + naucSeVetveníProgramu() // Zpátky do běhu. +} + +// narozdíl od jiných jazyků, v Go je možné mít pojmenované návratové hodnoty. +// Tak můžeme vracet hodnoty z mnoha míst funkce, aniž bychom uváděli hodnoty v +// return. +func naucSePojmenovaneNavraty(x, y int) (z int) { + z = x * y + return // z je zde implicitní, jelikož bylo pojmenováno. +} + +// Go má garbage collector. Používá pointery, ale neumožňuje jejich aritmetiku. +// Můžete tedy udělat chybu použitím nil odkazu, ale ne jeho posunutím. +func naucSePraciSPameti() (p, q *int) { + // Pojmenované parametry p a q mají typ odkaz na int. + p = new(int) // Zabudované funkce new alokuje paměť. + // Alokované místo pro int má hodnotu 0 a p už není nil. + s := make([]int, 20) // Alokujeme paměť pro 20 intů. + s[3] = 7 // Jednu z nich nastavíme. + r := -2 // Deklarujeme další lokální proměnnou. + return &s[3], &r // a vezmeme si jejich odkaz pomocí &. +} + +func narocnyVypocet() float64 { + return m.Exp(10) +} + +func naucSeVetveníProgramu() { + // Výraz if vyžaduje složené závorky, ale podmínka nemusí být v závorkách. + if true { + fmt.Println("říkal jsme ti to") + } + // Formátování je standardizované pomocí utility "go fmt". + if false { + // posměšek. + } else { + // úšklebek. + } + // Použij switch, když chceš zřetězit if. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // jednotlivé case nepropadávají. není potřeba "break" + case 43: + // nedosažitelné, jelikož už bylo ošetřeno. + default: + // implicitní větev je nepovinná. + } + // Stejně jako if, for (smyčka) nepoužívá závorky. + // Proměnné definované ve for jsou lokální vůči smyčce. + for x := 0; x < 3; x++ { // ++ je výrazem. + fmt.Println("iterace", x) + } + // zde je x == 42. + + // For je jediná smyčka v Go, ale má několik tvarů. + for { // Nekonečná smyčka + break // Dělám si legraci + continue // Sem se nedostaneme + } + + // Můžete použít klíčové slovo range pro iteraci nad mapami, poli, slicy, + // řetězci a kanály. + // range vrací jednu (kanál) nebo dvě hodnoty (pole, slice, řetězec a mapa). + for key, value := range map[string]int{"jedna": 1, "dva": 2, "tri": 3} { + // pro každý pár (klíč a hodnota) je vypiš + fmt.Printf("klíč=%s, hodnota=%d\n", key, value) + } + + // stejně jako for, := v podmínce if přiřazuje hodnotu + // nejříve nastavíme y a pak otestujeme, jestli je y větší než x. + if y := narocnyVypocet(); y > x { + x = y + } + // Funkční literáty jsou tzv. uzávěry (closure) + xBig := func() bool { + return x > 10000 // odkazuje na x deklarované ve příkladu použití switch + } + x = 99999 + fmt.Println("xBig:", xBig()) // true + x = 1.3e3 // To udělá z x == 1300 + fmt.Println("xBig:", xBig()) // teď už false. + + // Dále je možné funkční literáty definovat a volat na místě jako parametr + // funkce, dokavaď: + // a) funkční literát je okamžitě volán pomocí (), + // b) výsledek se shoduje s očekávaným typem. + fmt.Println("Sečte + vynásobí dvě čísla: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Voláno s parametry 10 a 2 + // => Sečti a vynásob dvě čísla. 24 + + // Když to potřebujete, tak to milujete + goto miluji +miluji: + + naučteSeFunkčníFactory() // funkce vracející funkce je zábava(3)(3) + naučteSeDefer() // malá zajížďka k důležitému klíčovému slovu. + naučteSeInterfacy() // Přichází dobré věci! +} + +func naučteSeFunkčníFactory() { + // Následující dvě varianty jsou stejné, ale ta druhá je praktičtější + fmt.Println(větaFactory("létní")("Hezký", "den!")) + + d := větaFactory("letní") + fmt.Println(d("Hezký", "den!")) + fmt.Println(d("Líný", "odpoledne!")) +} + +// Dekorátory jsou běžné v jiných jazycích. To samé můžete udělat v Go +// pomocí parameterizovatelných funkčních literátů. +func větaFactory(můjŘetězec string) func(před, po string) string { + return func(před, po string) string { + return fmt.Sprintf("%s %s %s", před, můjŘetězec, po) // nový řetězec + } +} + +func naučteSeDefer() (ok bool) { + // Odloží (defer) příkazy na okamžik těsně před opuštěním funkce. + // tedy poslední se provede první + defer fmt.Println("odložené příkazy jsou zpravovaná v LIFO pořadí.") + defer fmt.Println("\nProto je tato řádka vytištěna první") + // Defer se běžně používá k zavírání souborů a tím se zajistí, že soubor + // bude po ukončení funkce zavřen. + return true +} + +// definuje typ interfacu s jednou metodou String() +type Stringer interface { + String() string +} + +// Definuje pár jako strukturu se dvěma poli typu int x a y. +type pár struct { + x, y int +} + +// Definuje method pár. Pár tedy implementuje interface Stringer. +func (p pár) String() string { // p je tu nazýváno "Receiver" - přijímač + // Sprintf je další veřejná funkce z balíčku fmt. + // Pomocí tečky přistupujeme k polím proměnné p + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func naučteSeInterfacy() { + // Složené závorky jsou "strukturální literáty. Vyhodnotí a inicializuje + // strukturu. Syntaxe := deklaruje a inicializuje strukturu. + p := pár{3, 4} + fmt.Println(p.String()) // Volá metodu String na p typu pár. + var i Stringer // Deklaruje i jako proměnné typu Stringer. + i = p // Toto je možné, jelikož oba implementují Stringer + // zavolá metodu String(( typu Stringer a vytiskne to samé jako předchozí. + fmt.Println(i.String()) + + // Funkce ve balíčku fmt volají metodu String, když zjišťují, jak se má typ + // vytisknout. + fmt.Println(p) // Vytiskne to samé, jelikož Println volá String(). + fmt.Println(i) // Ten samý výstup. + + naučSeVariabilníParametry("super", "učit se", "tady!") +} + +// Funcke mohou mít proměnlivé množství parametrů. +func naučSeVariabilníParametry(mojeŘetězce ...interface{}) { + // Iterujeme přes všechny parametry + // Potržítku tu slouží k ignorování indexu v poli. + for _, param := range mojeŘetězce { + fmt.Println("parameter:", param) + } + + // Použít variadický parametr jako variadický parametr, nikoliv pole. + fmt.Println("parametery:", fmt.Sprintln(mojeŘetězce...)) + + naučSeOšetřovatChyby() +} + +func naučSeOšetřovatChyby() { + // ", ok" je metodou na zjištění, jestli něco fungovalo, nebo ne. + m := map[int]string{3: "tri", 4: "ctyri"} + if x, ok := m[1]; !ok { // ok bude false, jelikož 1 není v mapě. + fmt.Println("není tu jedna") + } else { + fmt.Print(x) // x by bylo tou hodnotou, pokud by bylo v mapě. + } + // hodnota error není jen znamením OK, ale může říct více o chybě. + if _, err := strconv.Atoi("ne-int"); err != nil { // _ hodnotu zahodíme + // vytiskne 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Znovu si povíme o interfacech, zatím se podíváme na + naučSeKonkurenčnost() +} + +// c je kanál, způsob, jak bezpečně komunikovat v konkurenčním prostředí. +func zvyš(i int, c chan int) { + c <- i + 1 // <- znamená "pošli" a posílá data do kanálu na levé straně. +} + +// Použijeme funkci zvyš a konkurečně budeme zvyšovat čísla. +func naučSeKonkurenčnost() { + // funkci make jsme již použili na slicy. make alokuje a inicializuje slidy, + // mapy a kanály. + c := make(chan int) + // nastartuj tři konkurenční go-rutiny. Čísla se budou zvyšovat + // pravděpodobně paralelně pokud je počítač takto nakonfigurován. + // Všechny tři zapisují do toho samého kanálu. + go zvyš(0, c) // go je výraz pro start nové go-rutiny. + go zvyš(10, c) + go zvyš(-805, c) + // Přečteme si tři výsledky a vytiskeneme je.. + // Nemůžeme říct, v jakém pořadí výsledky přijdou! + fmt.Println(<-c, <-c, <-c) // pokud je kanál na pravo, jedná se o "přijmi". + + cs := make(chan string) // Další kanál, tentokrát pro řetězce. + ccs := make(chan chan string) // Kanál kanálu řetězců. + go func() { c <- 84 }() // Start nové go-rutiny na posílání hodnot. + go func() { cs <- "wordy" }() // To samé s cs. + // Select má syntaxi jako switch, ale vztahuje se k operacím nad kanály. + // Náhodně vybere jeden case, který je připraven na komunikaci. + select { + case i := <-c: // Přijatá hodnota může být přiřazena proměnné. + fmt.Printf("je to typ %T", i) + case <-cs: // nebo může být zahozena + fmt.Println("je to řetězec") + case <-ccs: // prázdný kanál, nepřipraven ke komunikaci. + fmt.Println("to se nestane.") + } + // V tomto okamžiku máme hodnotu buď z kanálu c nabo cs. Jedna nebo druhá + // nastartovaná go-rutina skončila a další zůstane blokovaná. + + naučSeProgramovatWeb() // Go to umí. A vy to chcete taky. +} + +// jen jedna funkce z balíčku http spustí web server. +func naučSeProgramovatWeb() { + + // První parametr ListenAndServe je TCP adresa, kde poslouchat. + // Druhý parametr je handler, implementující interace http.Handler. + go func() { + err := http.ListenAndServe(":8080", pár{}) + fmt.Println(err) // neignoruj chyby + }() + + requestServer() +} + +// Umožní typ pár stát se http tím, že implementuje její jedinou metodu +// ServeHTTP. +func (p pár) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Servíruj data metodou http.ResponseWriter + w.Write([]byte("Naučil ses Go za y minut!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver řekl: `%s`", string(body)) +} +``` + +## Kam dále + +Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/). +Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení. +Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go +popis balíčků (package), dokumentaci příkazové řádky a historii releasů. + +Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti +jiným současným jazyků. + +Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX). +Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako +[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go. + +Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/). +Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/) +tak se podíváte na dokumentaci. + +Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). + +Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou +spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile) +pro více informací. diff --git a/css.html.markdown b/css.html.markdown index fc07fce4..1c569d04 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -6,8 +6,8 @@ contributors: - ["Geoffrey Liu", "https://github.com/g-liu"] - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Brett Taylor", "https://github.com/glutnix"] - ["Tyler Mumford", "https://tylermumford.com"] - filename: learncss.css --- @@ -193,10 +193,10 @@ selector { Save a CSS stylesheet with the extension `.css`. -```xml +```html <!-- You need to include the css file in your page's <head>. This is the recommended method. Refer to http://stackoverflow.com/questions/8284365 --> -<link rel='stylesheet' type='text/css' href='path/to/style.css' /> +<link rel='stylesheet' type='text/css' href='path/to/style.css'> <!-- You can also include some CSS inline in your markup. --> <style> @@ -241,8 +241,8 @@ p { property: value !important; } and the following markup: -```xml -<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +```html +<p style='/*F*/ property:value;' class='class1 class2' attr='value'> ``` The precedence of style is as follows. Remember, the precedence is for each @@ -259,6 +259,48 @@ recommended that you avoid its usage. * `B` is next. * `D` is the last one. +## 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 +/* A rule that will be used on all devices */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* change the h1 to use less ink on a printer */ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* make the font bigger when shown on a screen at least 480px wide */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` + +Media queries can include these features: +`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Most of these features can be prefixed with `min-` or `max-`. + +The `resolution` feature is not supported by older devices, instead use `device-pixel-ratio`. + +Many smartphones and tablets will attempt to render the page as if it were on a desktop unless you provide a `viewport` meta-tag. + +```html +<head> + <meta name="viewport" content="width=device-width; initial-scale=1.0"> +</head> +``` + ## Compatibility Most of the features in CSS 2 (and many in CSS 3) are available across all diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown index f3fe1614..3507429c 100644 --- a/es-es/asymptotic-notation-es.html.markdown +++ b/es-es/asymptotic-notation-es.html.markdown @@ -168,3 +168,4 @@ definiciones y ejemplos. * [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) * [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) +* [Apuntes Facultad de Ingeniería](https://www.scribd.com/document/317979564/Apuntes-Sobre-Analisis-de-Algoritmos) diff --git a/es-es/ruby-ecosystem-es.html.markdown b/es-es/ruby-ecosystem-es.html.markdown new file mode 100644 index 00000000..9ce62ef5 --- /dev/null +++ b/es-es/ruby-ecosystem-es.html.markdown @@ -0,0 +1,157 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Ale Mohamad", "http://twitter.com/alemohamad"] +lang: es-es +--- + +Las personas que usan Ruby en general tienen una tendencia a instalar diferentes +versiones de Ruby, administrar sus paquetes (o gemas), y gestionar las +dependencias de sus gemas. + +## Gestores de Ruby + +Algunas plataformas ya tienen Ruby pre-instalado o disponible como un paquete +propio. Muchos rubystas no utilizan estas versiones, o si lo hacen, solo lo +utilizan para preparar otra instalación o implementación de Ruby. En lugar de +eso, los rubystas tienden a instalar un gestor de Ruby para poder instalar +diferentes versiones y poder cambiar dependiendo del entorno de cada proyecto. + +Los siguientes son gestores populares de entorno de Ruby: + +* [RVM](https://rvm.io/) - Instala y cambia versiones de Ruby. Además RVM tiene + el concepto de gemsets para aislar complemtante entornos de proyectos. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Solo instala + versiones de Ruby. Se utiliza para tener un control más fino sobre las + versiones instaladas de Ruby. +* [rbenv](https://github.com/sstephenson/rbenv) - Solo se utiliza para cambiar + la versión de Ruby. Se utiliza junto con ruby-build. Se utiliza para tener un + control más fino sobre cómo se carga Ruby en el sistema. +* [chruby](https://github.com/postmodern/chruby) - Solo se utiliza para cambiar + la versión de Ruby. En espíritu es similar a rbenv. No le es tan importante + como son instaladas las versiones de Ruby. + +## Versiones de Ruby + +Ruby fue creado por Yukihiro "Matz" Matsumoto, quien se mantiene como una +especie de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), +aunque recientemente está cambiando. Como resultado, la implementación de +referencia de Ruby es llamada MRI (Matz' Reference Implementation), y cuando se +habla de una versión de Ruby, se está haciendo referencia a la versión inicial +de MRI. + +Las tres versiones mayores en uso de Ruby son: + +* 2.0.0 - Lanzada en Febrero de 2013. La mayoría de las librerías importantes y + frameworks soportan 2.0.0. +* 1.9.3 - Lanzada en Octubre de 2011. Es la versión que actualmente usan más + rubystas. Además fue + [retirada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Ruby 1.8.7 fue + [retirada](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +El cambio de 1.8.7 a 1.9.x es un cambio mucho mayor que de 1.9.3 a 2.0.0. Por +ejemplo, la serie 1.9 presentó codificaciones (encodings) y un bytecode VM. +Todavía hay proyectos que utilizan 1.8.7, pero se están convirtiendo en una +pequeña minoría, debido a que la mayor parte de la comunidad está utilizando +como mínimo 1.9.2 o 1.9.3. + +## Implementaciones de Ruby + +El ecosistema de Ruby disfruta de muchas diferentes implementaciones de Ruby, +cada una con fortalezas únicas y estados de compatibilidad. Para ser claros, las +diferentes implementaciones están escritas en diferentes lenguajes, pero *todas +son Ruby*. Cada implementación tiene hooks especiales y características extra, +pero todas interpretan archivos Ruby de forma normal. Por ejemplo, JRuby está +escrito en Java, pero no necesitás saber de Java para poder utilizarla. + +Muy maduras/compatibles: + +* [MRI](https://github.com/ruby/ruby) - Escrita en C, es la implementación de + referencia de Ruby. Por definición es 100% compatible (consigo misma). Las + otras implementaciones de Ruby mantienen compatibilidad con MRI (ver + [RubySpec](#rubyspec) más abajo). +* [JRuby](http://jruby.org/) - Escrita en Java y Ruby, esta implementación es + robusta y bastante veloz. Más importante, la fortaleza de JRuby reside en la + interoperabilidad con JVM/Java, pudiendo utilizar herramientas, proyectos y + lenguajes ya existentes en JVM. +* [Rubinius](http://rubini.us/) - Escrita principalmente en Ruby junto con un + bytecode VM de C++. Además es bastante madura y veloz. Debido a que está + implementada de forma directa en Ruby, expone varias funcionalidades de VM en + rubyland. + +Medianamente maduras/compatibles: + +* [Maglev](http://maglev.github.io/) - Construida sobre Gemstone, una VM de + Smalltalk. Smalltalk tiene herramientas que son impresionantes, y este + proyecto intenta llevar eso dentro del desarrollo con Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Lleva Ruby al desarrollo en iOS. + +No tan maduras/compatibles: + +* [Topaz](http://topazruby.com/) - Escrito en RPython (usando el intérprete + PyPy), Topaz es bastante joven y no tan compatible. Se muestra prometedor para + ser una implementación de Ruby de alta performance. +* [IronRuby](http://ironruby.net/) - Escrita en C#, apuntando a la plataforma + .NET. El trabajo en IronRuby parece haberse detenido desde que Microsoft + retiró su soporte. + +Las implementaciones de Ruby pueden tener su propio número de versión de +release, pero siempre apuntan a una versión específica de MRI para poder tener +compatibilidad. Muchas implementaciones tienen la habilidad de trabajar en +diferentes modos (por ejemplo, modo 1.8 o 1.9) para especificar a qué versión de +MRI están apuntando. + +## RubySpec + +Muchas implementaciones de Ruby dependen en gran medida de +[RubySpec](http://rubyspec.org/). Ruby no tiene una especificación oficial, por +lo que la comunidad ha escrito especificaciones ejecutables en Ruby para poder +testear la compatibilidad de sus implementaciones con MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) es un manejador de paquetes/comunidad de Ruby. +RubyGems viene incluido con Ruby, por lo que no hay necesidad de instalarlo por +separado. + +Los paquetes de Ruby son llamados "gemas" ("gems"), y pueden ser alojados por la +comunidad en RubyGems.org. Cada gema contiene su código fuente y algo de +metadata, incluyendo cosas como la versión, dependencias, autor(es), y +licencia(s). + +## Bundler + +[Bundler](http://bundler.io/) es una herramienta para resolución de dependencias +de gemas. Utiliza un archivo llamado Gemfile en cada proyecto para poder +organizar sus dependencias, y luego poder agregar dichas dependencias y sus +dependencias de forma recursiva. Hace esta acción hasta que resuelve y descarga +todas las dependencias, o se detiene si es que un conflicto aparece. + +Bundler eleva un error si encuentra dependencias conflictivas. Por ejemplo, si +la gema A requiere la versión 3 o mayor de la gema Z, pero la gema B requiere la +versión 2, Bundler va a notificarte sobre dicho conflicto. Esto es +extremadamente útil ya que varias gemas hacen referencia a otras gemas (de las +cuales puede referenciar a otras gemas), lo cual puede formar un gran grafo de +dependencias para resolver. + +# Testing + +Testing es una parte grande dentro de la cultura de Ruby. Ruby incluye su propio +framework de testing llamado minitest (o TestUnit para la versión 1.8.x de +Ruby). Hay varias librerías de testing con diferentes objetivos. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Framework de testing de Ruby 1.8 +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Framework de testing de Ruby 1.9/2.0 +* [RSpec](http://rspec.info/) - Un framework de testing que se focaliza en expresividad +* [Cucumber](http://cukes.info/) - Un framework de testing que utiliza BDD, que parsea tests con formato Gherkin + +## Se Amable + +La comunidad de Ruby se enorgullece de ser una comunidad abierta, diversa y +acogedora. Matz mismo es extremadamente amigable, y en general la generosidad de +los rubystas es increíble. diff --git a/fortran95.html.markdown b/fortran95.html.markdown index 8479fef8..5d1424bf 100644 --- a/fortran95.html.markdown +++ b/fortran95.html.markdown @@ -17,7 +17,7 @@ This overview will discuss the features of Fortran 95 since it is the most widely implemented of the more recent specifications and the later versions are largely similar (by comparison FORTRAN 77 is a very different language). -```fortran +``` ! This is a comment. diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index 4d2da921..b52fd34a 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -106,6 +106,8 @@ Cet article porte principalement sur la syntaxe et quelques astuces. </tr> </table> +``` + ## Utilisation Le HTML s'écrit dans des fichiers `.html`. diff --git a/html.html.markdown b/html.html.markdown new file mode 100644 index 00000000..3e5e43c3 --- /dev/null +++ b/html.html.markdown @@ -0,0 +1,120 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] +--- + +HTML stands for HyperText Markup Language. +It is a language which 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. +This markup serves to give significance to the text that it encloses. +Like other computer languages, HTML has many versions. Here we will talk about HTML5. + +**NOTE :** You can test the different tags and elements as you progress through the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see their effects, understand how they work and familiarise yourself with the language. +This article is concerned principally with HTML syntax and some useful tips. + + +```html +<!-- Comments are enclosed like this line! --> + +<!-- #################### The Tags #################### --> + +<!-- Here is an example HTML file that we are going to analyse. --> + +<!doctype html> + <html> + <head> + <title>My Site</title> + </head> + <body> + <h1>Hello, world!</h1> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows/a> + <p>This is a paragraph.</p> + <p>This is another paragraph.</p> + <ul> + <li>This is an item in a non-enumerated list (bullet list)</li> + <li>This is another item</li> + <li>And this is the last item on the list</li> + </ul> + </body> + </html> + +<!-- An HTML file always starts by indicating to the browser that the page is HTML. --> +<!doctype html> + +<!-- After this, it starts by opening an <html> tag. --> +<html> + +<!-- that will be closed at the end of the file with </html>. --> +</html> + +<!-- Nothing should appear after this final tag. --> + +<!-- Inside (between the opening and closing tags <html></html>), we find: --> + +<!-- A header defined by <head> (it must be closed with </head>). --> +<!-- The header contains some description and additional information which are not displayed; this is metadata. --> + +<head> + <title>My Site</title><!-- The tag <title> indicates to the browser the title to show in browser window's title bar and tab name. --> +</head> + +<!-- After the <head> section, we find the tag - <body> --> +<!-- Until this point, nothing described will show up in the browser window. --> +<!-- We must fill the body with the content to be displayed. --> + +<body> + <h1>Hello, world!</h1> <!-- The h1 tag creates a title. --> + <!-- There are also subtitles to <h1> from the most important (h2) to the most precise (h6). --> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows</a> <!-- a hyperlink to the url given by the attribute href="" --> + <p>This is a paragraph.</p> <!-- The tag <p> lets us include text in the html page. --> + <p>This is another paragraph.</p> + <ul> <!-- The tag <ul> creates a bullet list. --> + <!-- To have a numbered list instead we would use <ol> giving 1. for the first element, 2. for the second, etc. --> + <li>This is an item in a non-enumerated list (bullet list)</li> + <li>This is another item</li> + <li>And this is the last item on the list</li> + </ul> +</body> + +<!-- And that's it, creating an HTML file can be simple. --> + +<!-- But it is possible to add many additional types of HTML tags. --> + +<!-- To insert an image. --> +<img src="http://i.imgur.com/XWG0O.gif"/> <!-- The source of the image is indicated using the attribute src="" --> +<!-- The source can be an URL or even path to a file on your computer. --> + +<!-- It is also possible to create a table. --> + +<table> <!-- We open a <table> element. --> + <tr> <!-- <tr> allows us to create a row. --> + <th>First Header</th> <!-- <th> allows us to give a title to a table column. --> + <th>Second Header</th> + </tr> + <tr> + <td>first row, first column</td> <!-- <td> allows us to create a table cell. --> + <td>first row, second column</td> + </tr> + <tr> + <td>second row, first column</td> + <td>second row, second column</td> + </tr> +</table> + +``` + +## Usage + +HTML is written in files ending with `.html`. + +## To Learn More + +* [wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 9a7c18cc..06ad1092 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +lang: id-id filename: markdown-id.md --- diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index dd5005f2..8ef09712 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -2,6 +2,7 @@ language: rust contributors: - ["Carlo Milanesi", "http://github.com/carlomilanesi"] +lang: it-it filename: rust-it.html.markdown --- diff --git a/java.html.markdown b/java.html.markdown index 56bffd88..57c10390 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -566,7 +566,7 @@ class PennyFarthing extends Bicycle { // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { - gear = 0; + this.gear = 0; } } diff --git a/jquery.html.markdown b/jquery.html.markdown new file mode 100644 index 00000000..013b75d7 --- /dev/null +++ b/jquery.html.markdown @@ -0,0 +1,138 @@ +--- +category: tool +tool: jquery +contributors: + - ["Sawyer Charles", "https://github.com/xssc"] +filename: jquery.js +--- + +jQuery is a JavaScript library that helps you "do more, write less". It makes many common JavaScript tasks and makes them easier to write. jQuery is used by many big companies and developers everywhere. It makes AJAX, event handling, document manipulation, and much more, easier and faster. + +Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/) + +```js + + +/////////////////////////////////// +// 1. Selectors + +// Selectors in jQuery are used to select an element +var page = $(window); // Selects the whole viewport + +// Selectors can also be CSS selector +var paragraph = $('p'); // Selects all paragraph elements +var table1 = $('#table1'); // Selects element with id 'table1' +var squares = $('.square'); // Selects all elements with the class 'square' +var square_p = $('p.square') // Selects paragraphs with the 'square' class + + +/////////////////////////////////// +// 2. Events and Effects + +// A very common event used is the ready event on the document +// You can use the 'ready' method to wait until the element has finished loading +$(document).ready(function(){ + // Code won't execute until the document is loaded +}); + +// jQuery is very good at triggering events +// and also handling what happens when an event is triggered +$('#button').click(); // Fires a click event on $('#button') +$('#button').click(function(){ + // Code here gets executed when the #button element is clicked +}); + +function onAction() { + // This is executed when the event is triggered +} + +// Some other common events are: +$('#btn').dblclick(onAction); // Double click +$('#btn').hover(onAction); // Hovering over +$('#btn').focus(onAction); // On focus +$('#btn').blur(onAction); // Losses focus +$('#btn').submit(onAction); // On submit +$('#btn').select(onAction); // When an element is selected +$('#btn').keydown(onAction); // When a key is pushed down +$('#btn').keyup(onAction); // When a key is released +$('#btn').keypress(onAction); // When a key is pressed +$('#btn').mousemove(onAction); // When the mouse is moved +$('#btn').mouseenter(onAction); // Mouse enters the element +$('#btn').mouseleave(onAction); // Mouse leaves the element + +// You can also use an anonymous function +$('#btn').hover(function(){ + // Executed on hover +}); + +// These can all also trigger the event instead of handling it +// by simply not giving any parameters +$('#btn').dblclick(); // Fires double click on the element + +// You can handle multiple events while only using the selector once +$('#btn').on( + {dblclick: myFunction1} // Triggered on double click + {blur: myFunction1} // Triggered on blur +); + +// You can move and hide elements with some effect methods +$('.table').hide(); # Hides the element(s) + +// Note: calling a function in these methods will still hide the element +$('.table').hide(function(){ + // Element hidden then function executed +}); + +// You can store selectors in variables +var tables = $('.table'); + +// Some basic document manipulation methods are: +tables.hide(); // Hides element(s) +tables.show(); // Shows (un-hides) element(s) +tables.toggle(); // Changes the hide/show state +tables.fadeOut(); // Fades out +tables.fadeIn(); // Fades in +tables.fadeToggle(); // Fades in or out +tables.fadeTo(0.5); // Fades to an opacity (between 0 and 1) +tables.slideUp(); // Slides up +tables.slideDown(); // Slides down +tables.slideToggle(); // Slides up or down + +// All of the above take a speed (milliseconds) and callback function +tables.hide(1000, myFunction); // 1 second hide animation then function + +// fadeTo has a required opacity as its second parameter +tables.fadeTo(2000, 0.1, myFunction); // 2 sec. fade to 0.1 opacity then function + +// You can get slightly more advanced with the animate method +tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); +// The animate method takes an object of css and values to end with, +// optional options parameter to tune the animation, +// and of course the callback function + +/////////////////////////////////// +// 3. Manipulation + +// These are similar to effects but can do more +$('div').addClass('div') // Adds class div to all div taming-slim-20 + +// Common manipulation methods +$('p').append('Hello world'); // Adds to end of element +$('p').attr('class'); // Gets attribute +$('p').attr('class', 'content'); // Sets attribute +$('p').hasClass('div'); // Returns true if it has the class +$('p').height(); // Gets height of element or sets height + + +// For many manipulation methods, getting info on an element +// will ONLY get the first matching element +$('p').height(); // Gets only the first 'p' tag's height + +// You can use each to loop through all the elements +var heights = []; +$('p').each(function() { + heights.push($(this.height)); // Adds all 'p' tag heights to array +}); + + +`` diff --git a/meteor.html.markdown b/meteor.html.markdown new file mode 100644 index 00000000..1685e0be --- /dev/null +++ b/meteor.html.markdown @@ -0,0 +1,567 @@ +--- +category: tool +tool: meteor.js +Filename: meteor.html.markdown +contributors: + - ["Mohammed Rafy", "https://github.com/IamRafy/"] +--- + + + +Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor. + +The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP. + +But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen. + +They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients. +Meteor Supports OS X, Windows, and Linux. // https://github.com/meteor/meteor/wiki/Supported-Platforms +On Windows? https://install.meteor.com/windows +On OS X or Linux? Install the latest official Meteor release from your terminal: +$ curl https://install.meteor.com/ | sh +The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures. + +Once you've installed Meteor, create a project: +meteor create myapp +Run it locally: + +cd myapp +meteor +# Meteor server running on: http://localhost:3000/ + +Then, open a new terminal tab and unleash it on the world (on a free server we provide): + +meteor deploy myapp.meteor.com + +Principles of Meteor + +* Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it. + +* One Language. Meteor lets you write both the client and the server parts of your application in JavaScript. + +* Database Everywhere. You can use the same methods to access your database from the client or the server. + +* Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly. + +* Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary. + +* Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and frameworks. + +* Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs. + +Developer Resources +------------------- + +If anything in Meteor catches your interest, we hope you'll get involved with the project! + +TUTORIAL +Get started fast with the official Meteor tutorial! https://www.meteor.com/install + +STACK OVERFLOW +The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the meteor tag to your question. +http://stackoverflow.com/questions/tagged/meteor + +FORUMS +Visit the Meteor discussion forumsto announce projects, get help, talk about the community, or discuss changes to core. +https://forums.meteor.com/ + +GITHUB +The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please read Contributing to Meteor for how to get started. https://github.com/meteor/meteor + +THE METEOR MANUAL +In-depth articles about the core components of Meteor can be found on the Meteor Manual. The first article is about Tracker, our transparent reactivity framework. More articles (covering topics like Blaze, Unibuild, and DDP) are coming soon! http://manual.meteor.com/ + +What is Meteor? +--------------- + +Meteor is two things: + +A library of packages: pre-written, self-contained modules that you might need in your app. + +There are about a dozen core Meteor packages that most any app will use. Two examples: webapp, which handles incoming HTTP connections, and templating, which lets you make HTML templates that automatically update live as data changes. Then there are optional packages like email, which lets your app send emails, or the Meteor Accounts series (accounts-password, accounts-facebook, accounts-ui, and others) which provide a full-featured user account system that you can drop right into your app. In addition to these "core" packages, there are thousands of community-written packages in Atmosphere, one of which might do just what you need. + +A command-line tool called meteor. + +meteor is a build tool analogous to make, rake, or the non-visual parts of Visual Studio. It gathers up all of the source files and assets in your application, carries out any necessary build steps (such as compiling CoffeeScript, minifying CSS, building npm modules, or generating source maps), fetches the packages used by your app, and outputs a standalone, ready-to-run application bundle. In development mode it can do all of this interactively, so that whenever you change a file you immediately see the changes in your browser. It's super easy to use out of the box, but it's also extensible: you can add support for new languages and compilers by adding build plugin packages to your app. + +The key idea in the Meteor package system is that everything should work identically in the browser and on the server (wherever it makes sense, of course: browsers can't send email and servers can't capture mouse events). Our whole ecosystem has been built from the ground up to support this. + +Structuring your application +---------------------------- + +A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree. + +Special Directories +------------------- + +By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor: + +client + +Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.) + +HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load. + +server +Any directory named server is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { ... }, except the client never even receives the code. Any sensitive code that you don't want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server directory. + +Meteor gathers all your JavaScript files, excluding anything under the client, public, and private subdirectories, and loads them into a Node.js server instance. In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node. We find the linear execution model a better fit for the typical server code in a Meteor application. + +public + +All files inside a top-level directory called public are served as-is to the client. When referencing these assets, do not include public/ in the URL, write the URL as if they were all in the top level. For example, reference public/bg.png as <img src='/bg.png' />. This is the best place for favicon.ico, robots.txt, and similar files. + +private + +All files inside a top-level directory called private are only accessible from server code and can be loaded via the Assets API. This can be used for private data files and any files that are in your project directory that you don't want to be accessible from the outside. + +client/compatibility + +This folder is for compatibility JavaScript libraries that rely on variables declared with var at the top level being exported as globals. Files in this directory are executed without being wrapped in a new variable scope. These files are executed before other client-side JavaScript files. +tests + +Any directory named tests is not loaded anywhere. Use this for any local test code. + +node_modules + +For compatibility with node.js tools used alongside Meteor, any directory named node_modules is not loaded anywhere. node.js packages installed into node_modules directories will not be available to your Meteor code. Use Npm.depends in your package package.js file for that. + +Files outside special directories +--------------------------------- + +All JavaScript files outside special directories are loaded on both the client and the server. That's the place for model definitions and other functions. Meteor provides the variables Meteor.isClient and Meteor.isServer (http://docs.meteor.com/#/full/meteor_isserver)so that your code can alter its behavior depending on whether it's running on the client or the server. + +CSS and HTML files outside special directories are loaded on the client only, and cannot be used from server code. + +Example File Structure + +The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above. + +lib/ # common code like collections and utilities +lib/methods.js # Meteor.methods definitions +lib/constants.js # constants used in the rest of the code + +client/compatibility # legacy libraries that expect to be global +client/lib/ # code for the client to be loaded first +client/lib/helpers.js # useful helpers for your client code +client/body.html # content that goes in the <body> of your HTML +client/head.html # content for <head> of your HTML: <meta> tags, etc +client/style.css # some CSS code +client/<feature>.html # HTML templates related to a certain feature +client/<feature>.js # JavaScript code related to a certain feature + +server/lib/permissions.js # sensitive permissions code used by your server +server/publications.js # Meteor.publish definitions + +public/favicon.ico # app icon +settings.json # configuration data to be passed to meteor --settings +mobile-config.js # define icons and metadata for Android/iOS + +You can also model your directory structure after the example apps. Run meteor create --example todos and explore the directories to see where all the files in a real app could go. + +File Load Order +--------------- + +It is best to write your application in such a way that it is insensitive to the order in which files are loaded, for example by using Meteor.startup (http://docs.meteor.com/#/full/meteor_startup) , or by moving load order sensitive code into packages (http://docs.meteor.com/#/full/usingpackages) , which can explicitly control both the load order of their contents and their load order with respect to other packages. However, sometimes load order dependencies in your application are unavoidable. + +There are several load ordering rules. They are applied sequentially to all applicable files in the application, in the priority given below: + +HTML template files are always loaded before everything else +Files beginning with main. are loaded last +Files inside any lib/ directory are loaded next +Files with deeper paths are loaded next +Files are then loaded in alphabetical order of the entire path +nav.html +main.html +client/lib/methods.js +client/lib/styles.js +lib/feature/styles.js +lib/collections.js +client/feature-y.js +feature-x.js +client/main.js +For example, the files above are arranged in the correct load order. main.html is loaded second because HTML templates are always loaded first, even if it begins with main., since rule 1 has priority over rule 2. However, it will be loaded after nav.html because rule 2 has priority over rule 5. + +client/lib/styles.js and lib/feature/styles.js have identical load order up to rule 4; however, since client comes before lib alphabetically, it will be loaded first. + +Organizing Your Project +----------------------- + +There are three main ways to organize your files into features or components. Let's say we have two types of objects in our project: apples and oranges. + +Method 1: Root-Level Folders +Since the special client, server, and lib directories work if they are anywhere in the path, you can use top-level folders to organize code into modules: + +apples/lib/ # code for apple-related features +apples/client/ +apples/server/ + +oranges/lib/ # code for orange-related features +oranges/client/ +oranges/server/ + +Method 2: Folders inside client/ and server/ + +lib/apples/ # common code for apples +lib/oranges/ # and oranges + +client/apples/ # client code for apples +client/oranges/ # and oranges + +server/apples/ # server code for apples +server/oranges/ # and oranges + +Method 3: Packages + +This is the ultimate in code separation, modularity, and reusability. If you put the code for each feature in a separate package, the code for one feature won't be able to access the code for the other feature except through exports, making every dependency explicit. This also allows for the easiest independent testing of features. You can also publish the packages and use them in multiple apps with meteor add. + +packages/apples/package.js # files, dependencies, exports for apple feature +packages/apples/<anything>.js # file loading is controlled by package.js + +packages/oranges/package.js # files, dependencies, exports for orange feature +packages/oranges/<anything>.js # file loading is controlled by package.js + +Data and security +----------------- + +Meteor makes writing distributed client code as simple as talking to a local database. It's a clean, simple, and secure approach that removes the need to implement individual RPC endpoints, manually cache data on the client to avoid slow roundtrips to the server, and carefully orchestrate invalidation messages to every client as data changes. + +In Meteor, the client and server share the same database API. The same exact application code — like validators and computed properties — can often run in both places. But while code running on the server has direct access to the database, code running on the client does not. This distinction is the basis for Meteor's data security model. + +By default, a new Meteor app includes the autopublish and insecure packages, which together mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools, but typically not appropriate for production applications. When you're ready, just remove the packages. + +Every Meteor client includes an in-memory database cache. To manage the client cache, the server publishes sets of JSON documents, and the client subscribes to those sets. As documents in a set change, the server patches each client's cache. + +Today most Meteor apps use MongoDB as their database because it is the best supported, though support for other databases is coming in the future. The Mongo.Collection class is used to declare Mongo collections and to manipulate them. Thanks to minimongo, Meteor's client-side Mongo emulator, Mongo.Collection can be used from both client and server code. + +// declare collections +// this code should be included in both the client and the server +Rooms = new Mongo.Collection("rooms"); +Messages = new Mongo.Collection("messages"); +Parties = new Mongo.Collection("parties"); + +// server: populate collections with some initial documents +Rooms.insert({name: "Conference Room A"}); +var myRooms = Rooms.find({}).fetch(); +Messages.insert({text: "Hello world", room: myRooms[0]._id}); +Parties.insert({name: "Super Bowl Party"}); +Each document set is defined by a publish function on the server. The publish function runs each time a new client subscribes to a document set. The data in a document set can come from anywhere, but the common case is to publish a database query. + +// server: publish all room documents +Meteor.publish("all-rooms", function () { + return Rooms.find(); // everything +}); + +// server: publish all messages for a given room +Meteor.publish("messages", function (roomId) { + check(roomId, String); + return Messages.find({room: roomId}); +}); + +// server: publish the set of parties the logged-in user can see. +Meteor.publish("parties", function () { + return Parties.find({$or: [{"public": true}, + {invited: this.userId}, + {owner: this.userId}]}); +}); +Publish functions can provide different results to each client. In the last example, a logged in user can only see Party documents that are public, that the user owns, or that the user has been invited to. + +Once subscribed, the client uses its cache as a fast local database, dramatically simplifying client code. Reads never require a costly round trip to the server. And they're limited to the contents of the cache: a query for every document in a collection on a client will only return documents the server is publishing to that client. + +// client: start a parties subscription +Meteor.subscribe("parties"); + +// client: return array of Parties this client can read +return Parties.find().fetch(); // synchronous! +Sophisticated clients can turn subscriptions on and off to control how much data is kept in the cache and manage network traffic. When a subscription is turned off, all its documents are removed from the cache unless the same document is also provided by another active subscription. + +When the client changes one or more documents, it sends a message to the server requesting the change. The server checks the proposed change against a set of allow/deny rules you write as JavaScript functions. The server only accepts the change if all the rules pass. + +// server: don't allow client to insert a party +Parties.allow({ + insert: function (userId, party) { + return false; + } +}); + +// client: this will fail +var party = { ... }; +Parties.insert(party); +If the server accepts the change, it applies the change to the database and automatically propagates the change to other clients subscribed to the affected documents. If not, the update fails, the server's database remains untouched, and no other client sees the update. + +Meteor has a cute trick, though. When a client issues a write to the server, it also updates its local cache immediately, without waiting for the server's response. This means the screen will redraw right away. If the server accepted the update — what ought to happen most of the time in a properly behaving client — then the client got a jump on the change and didn't have to wait for the round trip to update its own screen. If the server rejects the change, Meteor patches up the client's cache with the server's result. + +Putting it all together, these techniques accomplish latency compensation. Clients hold a fresh copy of the data they need, and never need to wait for a roundtrip to the server. And when clients modify data, those modifications can run locally without waiting for the confirmation from the server, while still giving the server final say over the requested change. + +The current release of Meteor supports MongoDB, the popular document database, and the examples in this section use the MongoDB API. Future releases will include support for other databases. + +Authentication and user accounts +-------------------------------- + +Meteor includes Meteor Accounts, a state-of-the-art authentication system. It features secure password login using the bcrypt algorithm, and integration with external services including Facebook, GitHub, Google, Meetup, Twitter, and Weibo. Meteor Accounts defines a Meteor.users collection where developers can store application-specific user data. + +Meteor also includes pre-built forms for common tasks like login, signup, password change, and password reset emails. You can add Accounts UI to your app with just one line of code. The accounts-ui package even provides a configuration wizard that walks you through the steps to set up the external login services you're using in your app. + +Input validation +---------------- + +Meteor allows your methods and publish functions to take arguments of any JSON type. (In fact, Meteor's wire protocol supports EJSON, an extension of JSON which also supports other common types like dates and binary buffers.) JavaScript's dynamic typing means you don't need to declare precise types of every variable in your app, but it's usually helpful to ensure that the arguments that clients are passing to your methods and publish functions are of the type that you expect. + +Meteor provides a lightweight library for checking that arguments and other values are the type you expect them to be. Simply start your functions with statements like check(username, String) or check(office, {building: String, room: Number}). The check call will throw an error if its argument is of an unexpected type. + +Meteor also provides an easy way to make sure that all of your methods and publish functions validate all of their arguments. Just run meteor add audit-argument-checks and any method or publish function which skips checking any of its arguments will fail with an exception. + +Reactivity +---------- + +Meteor embraces the concept of reactive programming (https://en.wikipedia.org/wiki/Reactive_programming). This means that you can write your code in a simple imperative style, and the result will be automatically recalculated whenever data changes that your code depends on. + +Tracker.autorun(function () { + Meteor.subscribe("messages", Session.get("currentRoomId")); +}); +This example (taken from a chat room client) sets up a data subscription based on the session variable currentRoomId. If the value of Session.get("currentRoomId") changes for any reason, the function will be automatically re-run, setting up a new subscription that replaces the old one. + +This automatic recomputation is achieved by a cooperation between Session and Tracker.autorun. Tracker.autorun performs an arbitrary "reactive computation" inside of which data dependencies are tracked, and it will re-run its function argument as necessary. Data providers like Session, on the other hand, make note of the computation they are called from and what data was requested, and they are prepared to send an invalidation signal to the computation when the data changes. + +This simple pattern (reactive computation + reactive data source) has wide applicability. Above, the programmer is saved from writing unsubscribe/resubscribe calls and making sure they are called at the right time. In general, Meteor can eliminate whole classes of data propagation code which would otherwise clog up your application with error-prone logic. + +These Meteor functions run your code as a reactive computation: + +Templates +Tracker.autorun +Template.autorun +Blaze.render and Blaze.renderWithData +And the reactive data sources that can trigger changes are: + +Session variables +Database queries on Collections +Meteor.status +The ready() method on a subscription handle +Meteor.user +Meteor.userId +Meteor.loggingIn +In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped: + +Tracker.autorun (nested) +Meteor.subscribe +observe() and observeChanges() on cursors +Meteor's implementation is a package called Tracker that is fairly short and straightforward. You can use it yourself to implement new reactive data sources. + +Live HTML templates +------------------- + +HTML templating is central to web applications. With Blaze, Meteor's live page update technology, you can render your HTML reactively, meaning that it will update automatically to track changes in the data used to generate it. + +Meteor makes it easy to use your favorite HTML templating language along with Meteor's live page update technology. Just write your template as you normally would, and Meteor will take care of making it update in realtime. + +Meteor ships with a templating language called Spacebars (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md), inspired by Handlebars (http://handlebarsjs.com/). It shares some of the spirit and syntax of Handlebars, but it has been tailored to produce reactive Meteor templates when compiled. + +Today, the only templating system that ships with Meteor is Spacebars, though our community has created packages for other languages such as Jade. + +To define templates, create a file in your project with the .html extension. In the file, make a <template> tag and give it a name attribute. Put the template contents inside the tag. Meteor will precompile the template, ship it down to the client, and make it available as on the global Template object. + +When your app is loaded, it automatically renders the special template called <body>, which is written using the <body> element instead of a <template>. You insert a template inside another template by using the {{> inclusion}} operator. + +The easiest way to get data into templates is by defining helper functions in JavaScript. Define helpers with the Template.templateName.helpers({ ... }) function. Putting it all together: + +<!-- in myapp.html --> +<body> + <h1>Today's weather!</h1> + {{> forecast}} +</body> + +<template name="forecast"> + <div>It'll be {{prediction}} tonight</div> +</template> +// in client/myapp.js: reactive helper function +Template.forecast.helpers({ + prediction: function () { + return Session.get("weather"); + } +}); +// in the JavaScript console +> Session.set("weather", "cloudy"); +> document.body.innerHTML + => "<h1>Today's weather!</h1> <div>It'll be cloudy tonight</div>" + +> Session.set("weather", "cool and dry"); +> document.body.innerHTML + => "<h1>Today's weather!</h1> <div>It'll be cool and dry tonight</div>" +To iterate over an array or database cursor, use {{#each}}: + +<!-- in myapp.html --> +<template name="players"> + {{#each topScorers}} + <div>{{name}}</div> + {{/each}} +</template> +// in myapp.js +Template.players.helpers({ + topScorers: function () { + return Users.find({score: {$gt: 100}}, {sort: {score: -1}}); + } +}); +In this case, the data is coming from a database query. When the database cursor is passed to {{#each}}, it will wire up all of the machinery to efficiently add and move DOM nodes as new results enter the query. + +Helpers can take arguments, and they receive the current template context data in this. Note that some block helpers change the current context (notably {{#each}} and {{#with}}): + +// in a JavaScript file +Template.players.helpers({ + leagueIs: function (league) { + return this.league === league; + } +}); +<!-- in a HTML file --> +<template name="players"> + {{#each topScorers}} + {{#if leagueIs "junior"}} + <div>Junior: {{name}}</div> + {{/if}} + {{#if leagueIs "senior"}} + <div>Senior: {{name}}</div> + {{/if}} + {{/each}} +</template> +Helpers can also be used to pass in constant data. + +// Works fine with {{#each sections}} +Template.report.helpers({ + sections: ["Situation", "Complication", "Resolution"] +}); +Finally, you can use the events function on a template to attach event handlers. The object passed into events is documented at Event Maps. The this argument to the event handler will be the data context of the element that triggered the event. + +<!-- myapp.html --> +<template name="scores"> + {{#each player}} + {{> playerScore}} + {{/each}} +</template> + +<template name="playerScore"> + <div>{{name}}: {{score}} + <span class="give-points">Give points</span> + </div> +</template> +// myapp.js +Template.playerScore.events({ + 'click .give-points': function () { + Users.update(this._id, {$inc: {score: 2}}); + } +}); +For more details about Spacebars, read the Spacebars README. (https://github.com/meteor/meteor/blob/master/packages/spacebars/README.md) + +Using packages +-------------- + +All of the functionality you've read about so far is implemented in standard Meteor packages. This is possible thanks to Meteor's unusually powerful isomorphic package and build system. Isomorphic means the same packages work in the web browser, in mobile apps, and on the server. Packages can also contain plugins that extend the build process, such as coffeescript (CoffeeScript compilation : http://coffeescript.org/) or templating (compiling HTML templates). + +Anyone can publish a Meteor package, and thousands of community-written packages have been published to date. The easiest way to browse these packages is Atmosphere, by Percolate Studio. You can also use the meteor search and meteor show commands. + +You can add packages to your project with meteor add and remove them with meteor remove. Additionally, meteor list will tell you what packages your project is using, and meteor update will update them to the newest versions when possible. + +By default all apps include the meteor-base package. This pulls in the packages that make up the core of the Meteor stack. Most apps will have this package. + +All new apps also start with a set of packages that allow a friendly development experience. For more information about these packages, check out the comments in the packages file. + +Meteor uses a single-loading packaging system, meaning that it loads just one version of every package. Before adding or upgrading to a particular version of a package, Meteor uses a constraint solver to check if doing so will cause other packages to break. By default, Meteor will choose conservatively. When adding transitive dependencies (packages that other packages, but not the application itself) depend on, Meteor will try to choose the earlier version. + +In addition to the packages in the official Meteor release being used by your app, meteor list and meteor add also search the packages directory at the top of your app. You can also use the packages directory to break your app into subpackages for your convenience, or to test packages that you might want to publish. See Writing Packages (http://docs.meteor.com/#/full/writingpackages) . If you wish to add packages outside of your app's folder structure, set the environment variable PACKAGE_DIRS to a colon-delimited list of paths. + +Namespacing +----------- + +Meteor's namespacing support makes it easy to write large applications in JavaScript. Each package that you use in your app exists in its own separate namespace, meaning that it sees only its own global variables and any variables provided by the packages that it specifically uses. Here's how it works. + +When you declare a top-level variable, you have a choice. You can make the variable File Scope or Package Scope. + +// File Scope. This variable will be visible only inside this +// one file. Other files in this app or package won't see it. +var alicePerson = {name: "alice"}; + +// Package Scope. This variable is visible to every file inside +// of this package or app. The difference is that 'var' is +// omitted. +bobPerson = {name: "bob"}; +Notice that this is just the normal JavaScript syntax for declaring a variable that is local or global. Meteor scans your source code for global variable assignments and generates a wrapper that makes sure that your globals don't escape their appropriate namespace. + +In addition to File Scope and Package Scope, there are also Exports. An export is a variable that a package makes available to you when you use it. For example, the email package exports the Email variable. If your app uses the email package (and only if it uses the email package!) then your app can see Email and you can call Email.send. Most packages have only one export, but some packages might have two or three (for example, a package that provides several classes that work together). + +You see only the exports of the packages that you use directly. If you use package A, and package A uses package B, then you only see package A's exports. Package B's exports don't "leak" into your namespace just because you used package A. This keeps each namespace nice and tidy. Each app or package only sees their own globals plus the APIs of the packages that they specifically asked for. + +When debugging your app, your browser's JavaScript console behaves as if it were attached to your app's namespace. You see your app's globals and the exports of the packages that your app uses directly. You don't see the variables from inside those packages, and you don't see the exports of your transitive dependencies (packages that aren't used directly by your app, but that are used by packages that are used by your app). + +If you want to look inside packages from inside your in-browser debugger, you've got two options: + +Set a breakpoint inside package code. While stopped on that breakpoint, the console will be in the package's namespace. You'll see the package's package-scope variables, imports, and also any file-scope variables for the file you're stopped in. + +If a package foo is included in your app, regardless of whether your app uses it directly, its exports are available in Package.foo. For example, if the email package is loaded, then you can access Package.email.Email.send even from namespaces that don't use the email package directly. + +When declaring functions, keep in mind that function x () {} is just shorthand for var x = function x () {} in JavaScript. Consider these examples: + +// This is the same as 'var x = function x () ...'. So x() is +// file-scope and can be called only from within this one file. +function x () { ... } + +// No 'var', so x() is package-scope and can be called from +// any file inside this app or package. +x = function () { ... } +Technically speaking, globals in an app (as opposed to in a package) are actually true globals. They can't be captured in a scope that is private to the app code, because that would mean that they wouldn't be visible in the console during debugging! This means that app globals actually end up being visible in packages. That should never be a problem for properly written package code (since the app globals will still be properly shadowed by declarations in the packages). You certainly shouldn't depend on this quirk, and in the future Meteor may check for it and throw an error if you do. + +Deploying +--------- + +Meteor is a full application server. We include everything you need to deploy your application on the internet: you just provide the JavaScript, HTML, and CSS. + +Running on Meteor's infrastructure +---------------------------------- + +The easiest way to deploy your application is to use meteor +deploy. We provide it because it's what, personally, we've always wanted: an easy way to take an app idea, flesh it out over a weekend, and put it out there for the world to use, with nothing getting in the way of creativity. + +meteor deploy myapp.meteor.com +Your application is now available at myapp.meteor.com. If this is the first time deploying to this hostname, Meteor creates a fresh empty database for your application. If you want to deploy an update, Meteor will preserve the existing data and just refresh the code. + +You can also deploy to your own domain. Just set up the hostname you want to use as a CNAME to origin.meteor.com, then deploy to that name. + +meteor deploy www.myapp.com +We provide this as a free service so you can try Meteor. It is also helpful for quickly putting up internal betas, demos, and so on. For more information, see meteor deploy. + +Running on your own infrastructure +---------------------------------- + +You can also run your application on your own infrastructure or any hosting provider that can run Node.js apps. + +To get started, run + +meteor build my_directory +This command will generate a fully-contained Node.js application in the form of a tarball. To run this application, you need to provide Node.js 0.10 and a MongoDB server. (The current release of Meteor has been tested with Node 0.10.40.) You can then run the application by invoking node, specifying the HTTP port for the application to listen on, and the MongoDB endpoint. + +cd my_directory +(cd programs/server && npm install) +env PORT=3000 MONGO_URL=mongodb://localhost:27017/myapp node main.js +Some packages might require other environment variables. For example, the email package requires a MAIL_URL environment variable. + +Writing packages +---------------- + +Writing Meteor packages is easy. To initialize a meteor package, run meteor create --package username:packagename, where username is your Meteor Developer username. This will create a package from scratch and prefill the directory with a package.js control file and some javascript. By default, Meteor will take the package name from the name of the directory that contains the package.js file. Don't forget to run meteor add [packagename], even if the package is internal to the app, in order to use it. + +Meteor promises repeatable builds for both packages and applications. This means that, if you built your package on a machine, then checked the code into a repository and checked it out elsewhere, you should get the same result. In your package directory, you will find an automatically generated .versions file. This file specifies the versions of all packages used to build your package and is part of the source. Check it into version control to ensure repeatable builds across machines. + +Sometimes, packages do not just stand on their own, but function in the context of an app (specifically, packages in the packages directory of an app). In that case, the app's context will take precedence. Rather than using the .versions file as a guide, we will build the package with the same dependencies as used by the app (we think that, in practice, it would be confusing to find your local packages built with different versions of things). + +Meteor uses extended semver versioning for its packages: that means that the version number has three parts separated by dots: major version, minor version and patch version (for example: 1.2.3) with an optional pre-release version. You can read more about it on semver.org. Additionally, because some meteor packages wrap external libraries, Meteor supports the convention of using _ to denote a wrap number. + +You can read more about package.js (http://docs.meteor.com/#/full/packagejs) files in the API section. + +A word on testing: since testing is an important part of the development process, there are two common ways to test a package: + +Integration tests (putting a package directly into an application, and writing tests against the application) is the most common way to test a package. After creating your package, add it to your app's /packages directory and run meteor add. This will add your package to your app as a local package. You can then test and run your app as usual. Meteor will detect and respond to changes to your local package, just as it does to your app files. + +Unit tests are run with the command meteor test-packages package-name. As described in the package.js section, you can use the package.js file to specify where your unit tests are located. If you have a repository that contains only the package source, you can test your package by specifying the path to the package directory (which must contain a slash), such as meteor test-packages ./. + +To publish a package, run meteor publish from the package directory. There are some extra restrictions on published packages: they must contain a version (Meteor packages are versioned using strict semver versioning) and their names must be prefixed with the username of the author and a colon, like so: iron:router. This namespacing allows for more descriptive and on-topic package names. + + + + diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown deleted file mode 100644 index 0f954715..00000000 --- a/nl-nl/markdown-nl-html.markdown +++ /dev/null @@ -1,256 +0,0 @@ ---- -language: markdown -contributors: - - ["Dan Turkel", "http://danturkel.com/"] -filename: learnmarkdown-nl.md -translators: - - ["Niels van Velzen", "https://nielsvanvelzen.me"] -lang: nl-nl ---- - -Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te -lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar -HTML (en tegenwoordig ook vele andere formaten). - -```markdown -<!-- Markdown is een superset van HTML, ofterwijl: een HTML bestand is -geldige Markdown code. Daardoor kunnen we dus HTML elementen in Markdown gebruiken. -Let wel op dat je geen markdown syntax in een HTML element kan gebruiken. --> - -<!-- Markdown verschilt ook in implementatie tussen verschillende parsers. In dit -artikel wordt aangegeven of iets overal werkt of alleen bij specifieke implementaties --> - -<!-- Koppen --> -<!-- Je kan HTML koppen (<h1 - 6>) makkelijk maken met markdown door -een aantal hekjes te gebruiken (#) --> -# Dit is een <h1> -## Dit is een <h2> -### Dit is een <h3> -#### Dit is een <h4> -##### Dit is een <h5> -###### Dit is een <h6> - -<!-- Voor h1 en h2 zijn er ook nog alternatieve methodes --> -Dit is een h1 -============= - -Dit is een h2 -------------- - -<!-- Simpele text stijlen --> -<!-- Tekst kan makkelijk vet of shuin gedrukt worden --> - -*Deze tekst staat schuin.* -_Net als deze tekst._ - -**Deze tekst is dikgedrukt.** -__Net als deze tekst.__ - -***En deze tekst is dik en schuin.*** -**_Net als dit!_** -*__En dit!__* - -<!-- In Github's markdown stijl is er ook een doorhaal mogelijkheid --> - -~~Deze tekst is doorgehaald.~~ - -<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or -multiple blank lines. --> -<!-- Paragrafen zijn een of meerdere aan elkaar lopende lijnen gescheiden door -een of meerdere lege lijnen --> - -Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? - -Nu ben ik in paragraaf 2. -Nog steeds in paragraaf 2! - -Dit is paragraaf drie! - -<!-- Wil je een nieuwe regel starten zonder de <br /> tag van HTML te gebruiken? -Je kunt een paragraaf eindigen met twee of meer spaties en dan een nieuwe paragraaf -beginnen --> - -Ik eindig met twee spaties (selecteer mij om het te zien). - -Er is een nieuwe regel boven mij! - -<!-- Citaten zijn makkelijk en worden gemaakt met het >. --> - -> Dit is een citaat. Je kan -> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. -> Het maakt niet uit zolang je maar begint met een `>`. - -> Je kunt ook meer dan 1 level ->> uitlijning gebruiken. -> Hoe handig is dat? - -<!-- Lijsten --> -<!-- Ongesorteerde lijsten kanje maken met sterretjes, plussen of koppeltekens --> - -* Item -* Item -* Nog een item - -of - -+ Item -+ Item -+ Nog een item - -of - -- Item -- Item -- Nog een item - -<!-- Geordende lijsten maak je met een nummer gevolgt door een punt --> - -1. Item een -2. Item twee -3. Item drie - -<!-- Je hoeft niet een correct getal te gebruiken en markdown zal nogsteeds werken, -ondanks dat het werkt is het niet aangeraden --> - -1. Item een -1. Item twee -1. Item drie - -<!-- (Dit is getzelfde als het voorbeeld hierboven) --> - -<!-- Je kan ook lijsten in lijsten gebruiken --> - -1. Item een -2. Item twee -3. Item drie - * Sub-item een - * Sub-item twee -4. Item vier - -<!-- Er zijn ook taken lijsten. Hier worden HTML checkboxes gebruikt --> - -Checkboxes hieronder zonder de 'x' zijn leeg. -- [ ] Eerste taak. -- [ ] Tweede taak -Checkboxes met een 'x' zijn klaar. -- [x] Deze taak is klaar. - -<!-- Code blokken --> -<!-- Je kunt een code blok maken door te inspringen met vier spaties fo een tab --> - - Dit is code - net als dit - -<!-- Je kan ook extra tabs (of spaties) gebruiken voor het inspringen in je code --> - - mijn_array.each do |item| - puts item - end - -<!-- Inline code kan worden gemaakt met het backtick karakter ` --> - -John wist niet eens wat de `go_to()` functie deed! - -<!-- In Github's markdown stijl is er een speciale syntax voor code --> - -\`\`\`ruby <!-- alleen moet je de backslashes weghalen als je dit doet, gewoon ```ruby dus! --> -def foobar - puts "Hallo wereld!" -end -\`\`\` <!-- hier ook, geen backslashes ``` --> - -<!-- Voor de bovenstaande syntax hoef je niet te inspringen. Daarnaast kan Github "syntax highlighting" geven. --> - -<!-- Horizontale regel (<hr />) --> -<!-- Horizontale regel zijn makkelijk toegevoegd met drie of meer sterretjes of -koppeltekens, met of zonder spaties. --> - -*** ---- -- - - -**************** - -<!-- Links --> -<!-- Een van de beste dingen van markdown is het maken van links. -De tekst om te weergeven plaats je tussen harde brackets [] gevolgd door de link tussen haakjes. --> - -[Klik op mij!](http://test.com/) - -<!-- Je kunt ook een titel aan de link defineren met quotes --> - -[Klik op mij!](http://test.com/ "Link naar Test.com") - -<!-- Relative paden werken ook. --> - -[Ga naar de muziek](/music/). - -<!-- Markdown support ook ankers --> - -[Klik op deze link][link1] vor meer informatie erover! -[Bekijk deze ook eens][foobar] als je wilt. - -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "In orde!" - -<!-- De titel kan ook in enkele quotes, tussen haakjes of gewoon zonder iets. -De refferentie kan overal in het document geplaats worden en zo lang als je wilt. -Zolang het maar uniek blijft --> - -<!-- Er is ook "impliciete naamgeving" wat de tekst en de link hetzelfde maakt --> - -[Dit][] is een link. - -[dit]: http://ditiseenlink.nl/ - -<!-- Dat is wel weinig gebruikt. --> - -<!-- Plaatjes --> -<!-- Plaatjes werken nar als links maar dan met een uitroepteken --> - -![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") - -<!-- En refferentie stijl werkt zoals verwacht --> - -![Dit is de alt attribuut.][mijnplaatje] - -[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" - -<!-- Diverse --> -<!-- Auto-links --> - -<http://testwebsite.com/> is hetzelfde als -[http://testwebsite.com/](http://testwebsite.com/) - -<!-- Auto-links voor emails --> - -<foo@bar.com> - -<!-- Escaping --> - -Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. - -<!-- Toetsenbord toetsen --> -<!-- In Github's markdown stijl kan je de <kbd> tag gebruiken --> - -Computer gecrashed? Gebruik eens -<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> - -<!-- Tabellen --> -<!-- Tabellen werken alleen in Github's stijl: --> - -| kolom1 | kolom2 |kolom3 | -| :--------------- | :---------: | ----------------: | -| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | -| blah | blah | blah | - -<!-- of, voor dezelfde resultaten --> - -Kolom 1 | Kolom 2 | Kolom 3 -:-- | :-: | --: -Dit is zo lelijk | stop | er mee - -<!-- Einde! --> - -``` - -Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown index b4ca8a52..f8c56101 100644 --- a/pt-br/elixir.html.markdown +++ b/pt-br/elixir.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] translators: - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br filename: learnelixir-pt.ex --- diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown index c5a3c020..9b6bd1b6 100644 --- a/pt-br/python3-pt.html.markdown +++ b/pt-br/python3-pt.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] translators: - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] -language: pt-br +lang: pt-br filename: learnpython3-pt.py --- diff --git a/python3.html.markdown b/python3.html.markdown index 6b3486a6..a56960a7 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -602,7 +602,7 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] # You can construct set and dict comprehensions as well. -{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} {x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} @@ -887,21 +887,19 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online * [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/) * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) * [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) ### Dead Tree * [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) +* [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) +* [Learn Python 3.0 VISUALLY](https://www.amazon.com/Learn-Python-3-0-VISUALLY-Interactive-ebook/dp/B00YI58B9U/) diff --git a/tmux.html.markdown b/tmux.html.markdown index ae73d912..1214a5ba 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -116,7 +116,7 @@ like how .vimrc or init.el are used. ``` # Example tmux.conf -# 2014.10 +# 2015.12 ### General @@ -129,7 +129,7 @@ set -g history-limit 2048 set -g base-index 1 # Mouse -set-option -g mouse-select-pane on +set-option -g -q mouse on # Force reload of config file unbind r @@ -204,8 +204,6 @@ setw -g window-status-bg black setw -g window-status-current-fg green setw -g window-status-bell-attr default setw -g window-status-bell-fg red -setw -g window-status-content-attr default -setw -g window-status-content-fg yellow setw -g window-status-activity-attr default setw -g window-status-activity-fg yellow @@ -246,6 +244,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) - - +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) diff --git a/toml.html.markdown b/toml.html.markdown new file mode 100755 index 00000000..980563f9 --- /dev/null +++ b/toml.html.markdown @@ -0,0 +1,274 @@ +--- +language: toml +filename: learntoml.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +--- + +TOML stands for Tom's Obvious, Minimal Language. It is a data serialisation language designed to be a minimal configuration file format that's easy to read due to obvious semantics. + +It is an alternative to YAML and JSON. It aims to be more human friendly than JSON and simpler that YAML. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages. + +Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you +should assume that it is unstable and act accordingly. This document follows TOML v0.4.0. + +```toml +# Comments in TOML look like this. + +################ +# SCALAR TYPES # +################ + +# Our root object (which continues for the entire document) will be a map, +# which is equivalent to a dictionary, hash or object in other languages. + +# The key, equals sign, and value must be on the same line +# (though some values can be broken over multiple lines). +key = "value" +string = "hello" +number = 42 +float = 3.14 +boolean = true +dateTime = 1979-05-27T07:32:00-08:00 +scientificNotation = 1e+12 +"key can be quoted" = true # Both " and ' are fine +"key may contains" = "letters, numbers, underscores, and dashes" + +# A bare key must be non-empty, but an empty quoted key is allowed +"" = "blank" # VALID but discouraged +'' = 'blank' # VALID but discouraged + +########## +# String # +########## + +# All strings must contain only valid UTF-8 characters. +# We can escape characters and some of them have a compact escape sequence. +# For example, \t add a tabulation. Refers to the spec to get all of them. +basicString = "are surrounded by quotation marks. \"I'm quotable\". Name\tJos" + +multiLineString = """ +are surrounded by three quotation marks +on each side and allow newlines.""" + +literalString = 'are surrounded by single quotes. Escaping are not allowed.' + +multiLineLiteralString = ''' +are surrounded by three single quotes on each side +and allow newlines. Still no escaping. +The first newline is trimmed in raw strings. + All other whitespace + is preserved. #! are preserved? +''' + +# For binary data it is recommended that you use Base64, another ASCII or UTF8 +# encoding. The handling of that encoding will be application specific. + +########### +# Integer # +########### + +## Integers can start with a +, a - or nothing. +## Leading zeros are not allowed. Hex, octal, and binary forms are not allowed. +## Values that cannot be expressed as a series of digits are not allowed. +int1 = +42 +int2 = 0 +int3 = -21 +integerRange = 64 + +## You can use underscores to enhance readability. Each +## underscore must be surrounded by at least one digit. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALID but discouraged + +######### +# Float # +######### + +# Floats are an integer followed by a fractional and/or an exponent part. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +bool1 = true +bool2 = false +boolMustBeLowercase = true + +############ +# Datetime # +############ + +date1 = 1979-05-27T07:32:00Z # follows the RFC 3339 spec +date2 = 1979-05-27T07:32:00 # without offset +date3 = 1979-05-27 # without offset nor time + +#################### +# COLLECTION TYPES # +#################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Commas", "are", "delimiters" ] +array3 = [ "Don't mixed", "different", "types" ] +array4 = [ [ 1.2, 2.4 ], ["all", 'strings', """are the same""", '''type'''] ] +array5 = [ + "Whitespace", "is", "ignored" +] + +######### +# Table # +######### + +# Tables (or hash tables or dictionaries) are collections of key/value +# pairs. They appear in square brackets on a line by themselves. +# Empty tables are allowed and simply have no key/value pairs within them. +[table] + +# Under that, and until the next table or EOF are the key/values of that table. +# Key/value pairs within tables are not guaranteed to be in any specific order. +[table-1] +key1 = "some string" +key2 = 123 + +[table-2] +key1 = "another string" +key2 = 456 + +# Dots are prohibited in bare keys because dots are used to signify nested tables. +# Naming rules for each dot separated part are the same as for keys. +[dog."tater.man"] +type = "pug" + +# In JSON land, that would give you the following structure: +# { "dog": { "tater.man": { "type": "pug" } } } + +# Whitespace around dot-separated parts is ignored, however, best practice is to +# not use any extraneous whitespace. +[a.b.c] # this is best practice +[ d.e.f ] # same as [d.e.f] +[ j . "ʞ" . 'l' ] # same as [j."ʞ".'l'] + +# You don't need to specify all the super-tables if you don't want to. TOML knows +# how to do it for you. +# [x] you +# [x.y] don't +# [x.y.z] need these +[x.y.z.w] # for this to work + +# As long as a super-table hasn't been directly defined and hasn't defined a +# specific key, you may still write to it. +[a.b] +c = 1 + +[a] +d = 2 + +# You cannot define any key or table more than once. Doing so is invalid. + +# DO NOT DO THIS +[a] +b = 1 + +[a] +c = 2 + +# DO NOT DO THIS EITHER +[a] +b = 1 + +[a.b] +c = 2 + +# All table names must be non-empty. +[] # INVALID +[a.] # INVALID +[a..b] # INVALID +[.b] # INVALID +[.] # INVALID + +################ +# Inline table # +################ + +inlineTables = { areEnclosedWith = "{ and }", mustBeInline = true } +point = { x = 1, y = 2 } + +################### +# Array of Tables # +################### + +# An array of tables can be expressed by using a table name in double brackets. +# Each table with the same double bracketed name will be an item in the array. +# The tables are inserted in the order encountered. + +[[products]] +name = "array of table" +sku = 738594937 +emptyTableAreAllowed = true + +[[products]] + +[[products]] +name = "Nail" +sku = 284758393 +color = "gray" + +# You can create nested arrays of tables as well. Each double-bracketed +# sub-table will belong to the nearest table element above it. + +[[fruit]] + name = "apple" + + [fruit.Geometry] + shape = "round" + note = "I am an fruit's property" + + [[fruit.color]] + name = "red" + note = "I am an array's item in apple" + + [[fruit.color]] + name = "green" + note = "I am in the same array than red" + +[[fruit]] + name = "banana" + + [[fruit.color]] + name = "yellow" + note = "I am an array's item too but banana's one" +``` + +In JSON land, this code will be: + +```json +{ + "fruit": [ + { + "name": "apple", + "geometry": { "shape": "round", "note": "..."}, + "color": [ + { "name": "red", "note": "..." }, + { "name": "green", "note": "..." } + ] + }, + { + "name": "banana", + "color": [ + { "name": "yellow", "note": "..." } + ] + } + ] +} +``` + +### More Resources + ++ [TOML official repository](https://github.com/toml-lang/toml) diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 2d4240ed..33544765 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -202,7 +202,7 @@ int main() { 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: - // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32) + // - isaretli sayinin isaret bitinde yap?ilan kaydirma (int a = 1 << 32) // - negatif sayilarda sol kaydirma (int a = -1 << 2) // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma: // int a = 1 << 32; // UB if int is 32 bits wide diff --git a/vim.html.markdown b/vim.html.markdown index cd61ca74..edbc3da7 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -19,7 +19,7 @@ specific points in the file, and for fast editing. vim <filename> # Open <filename> in vim :q # Quit vim :w # Save current file - :wq # Save file and quit vim + :wq # Save file and quit vim :q! # Quit vim without saving file # ! *forces* :q to execute, hence quiting vim without saving :x # Save file and quit vim, shorter version of :wq @@ -77,9 +77,9 @@ specific points in the file, and for fast editing. Vim is based on the concept on **modes**. -Command Mode - vim starts up in this mode, used to navigate and write commands -Insert Mode - used to make changes in your file -Visual Mode - used to highlight text and do operations to them +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` @@ -105,15 +105,15 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm Vim can be thought of as a set of commands in a 'Verb-Modifier-Noun' format, where: -Verb - your action -Modifier - how you're doing your action +Verb - your action +Modifier - how you're doing your action Noun - the object on which your action acts on -A few important examples of 'Verbs, 'Modifiers', and 'Nouns': +A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - + d # Delete c # Change y # Yank (copy) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index e1551e2b..5cf7e4c5 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -188,7 +188,7 @@ int main() cout << "Your favorite number is " << myInt << "\n";
// 显示“Your favorite number is <myInt>”
- cerr << "Used for error messages";
+ cerr << "Used for error messages";
}
/////////
diff --git a/zh-cn/vim-cn.html.markdown b/zh-cn/vim-cn.html.markdown new file mode 100644 index 00000000..0c3f6043 --- /dev/null +++ b/zh-cn/vim-cn.html.markdown @@ -0,0 +1,236 @@ +--- +category: tool +tool: vim +filename: LearnVim-cn.txt +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] +lang: zh-cn +--- + + +[Vim](www.vim.org) +(Vi IMproved) 是 Unix 上的流行编辑器 vi 的克隆版本。这个文本编辑器 +是为性能和提升效率而设计的,并且在大多数基于 unix 的系统上普遍存在。 +它有大量的快捷键可用来快速导航到文件的特定位置,以便进行快速编辑。 + +## Vim 导航基础 + +``` + vim <filename> # 在 Vim 中打开 <filename> + :q # 退出 Vim + :w # 保存当前文件 + :wq # 保存文件并退出 Vim + :q! # 退出 Vim 并且不保存文件 + # ! *强制* 执行 :q, 因此没有保存就退出 Vim + :x # 保存文件并且退出 Vim, 是 :wq 的简写版本 + + u # 撤销 + CTRL+R # 重做 + + h # 左移一个字符 + j # 下移一行 + k # 上移一行 + l # 右移一个字符 + + # 在行内移动 + + 0 # 移到行首 + $ # 移到行尾 + ^ # 移到行内的第一个非空白字符处 + + # 在文本中查找 + + /word # 光标之后的所有该词都高亮显示 + ?word # 光标之前的所有该词都高亮显示 + n # 查找后将光标移到该词的下一个出现位置 + N # 光标移到该词的上一个出现位置 + + :%s/foo/bar/g # 将文件每一行上的所有 'foo' 都改成 'bar' + :s/foo/bar/g # 将当前行上的所有 'foo' 都改成 'bar' + + # 跳到字符处 + + f<字符> # 向前跳移到 <字符> 上 + t<字符> # 向前跳移到 <字符> 的左侧 + + # 例如, + f< # 向前跣到 < 上 + t< # 向前跳移到 < 的左侧 + + # 按词移动 + + w # 前移一个词 + b # 后移一个词 + e # 移到当前词的末尾 + + # 移动的其它命令 + + gg # 移到文件顶部 + G # 移到文件末尾 + :NUM # 移到第 NUM 行 (NUM 是任意数字) + H # 移到屏幕顶部 + M # 移到屏幕中间位置 + L # 移到屏幕末尾 +``` + +## 模式: + +Vim 基于 **模式** 这个概念。 + +命令模式 - Vim 启动后就处于这个模式,用于导航和操作命令 +插入模式 - 用于在你的文件中进行修改 +可视模式 - 用于高亮文本并对它们进行操作 +Ex 模式 - 用于跳到底部的 ':' 提示行上输入命令 + +``` + i # 在光标位置前,将 Vim 切换到插入模式 + a # 在光标位置后,将 Vim 切换到插入模式 + v # 将 Vim 切换到可视模式 + : # 将 Vim 切换到 ex 模式 + <esc> # 无论你当前处于什么模式,都返回到命令模式 + + # 复制和粘贴文本 + + y # 复制所选的内容 + yy # 复制当前行 + d # 删除所选的内容 + dd # 删除当前行 + p # 在当前光标位置后粘贴复制的文本 + P # 在当前光标位置前粘贴复制的文本 + x # 删除当前光标位置处的字符 +``` + +## Vim 的 '语法' + +Vim 可以被认为是按 '动词-修饰词-名词' 格式编排的一组命令: + +动词 - 你的动作 +修饰词 - 你如何执行你的动作 +名词 - 你的动作所作用于的对象 + +关于 '动词','修饰词',和 '名词' 的几个重要例子: + +``` + # '动词' + + d # 删除 + c # 修改 + y # 复制 + v # 可视化选择 + + # '修饰词' + + i # 内部的 + a # 周围的 + NUM # 数字 (NUM 是任意数字) + f # 查找文本并位于其上 + t # 查找文本并停于其前面 + / # 从光标处开始查找字符串 + ? # 在光标前查找字符串 + + # '名词' + + w # 词 + s # 句子 + p # 段落 + b # 块 + + # 示例 '语句' 或命令 + + d2w # 删除 2 个词 + cis # 修改段落内的内容 + yip # 复制段落内的内容 (复制你所在的段落) + ct< # 修改直到括号开启处 + # 对你的当前位置直到下个括号开启处的内容进行修改 + d$ # 删除直到行尾 +``` + +## 一些快捷键和技巧 + + <!--TODO: Add more!--> +``` + > # 将所选内容缩进一级 + < # 将所选内容取消缩进一级 + :earlier 15m # 将文档还原到 15 分钟前的状态 + :later 15m # 逆转上述命令 + ddp # 相邻行交换位置,先 dd 再 p + . # 重复之前动作 +``` + +## 宏 + +宏基本上来说就是可录制的动作。 +当你开始录制宏时,它会记录你使用的 **每个** 动作和命令, +直到你停止录制。当调用宏时,它会将这个完全相同的动作和命令序列 +再次应用于所选文本之上。 + +``` + qa # 开始录制一个叫 'a' 的宏 + q # 停止录制 + @a # 重播宏 +``` + +### 配置 ~/.vimrc + +.vimrc 可用于在启动时对 Vim 进行配置。 + +这里是一个示例 ~/.vimrc 文件: + +``` +" 示例 ~/.vimrc +" 2015.10 + +" 需要 Vim iMproved 版本 +set nocompatible + +" 根据文件名检测文件类型,以便能进行智能自动缩进等操作。 +filetype indent plugin on + +" 开启语法高亮 +syntax on + +" 更好的命令行补全 +set wildmenu + +" 除了当使用大写字母时使用大小写无关查找 +set ignorecase +set smartcase + +" 当新开一行时,如果没有开启文件特定的缩进规则, +" 则缩进保持与你当前行一致 +set autoindent + +" 在左侧显示行号 +set number + +" 缩进选项,根据个人偏好进行修改 + +" 每个 TAB 的可视空格数 +set tabstop=4 + +" 编辑时 TAB 对应的空格数 +set softtabstop=4 + +" 当使用缩进操作 (>> 和 <<) 时缩进的空格数 +set shiftwidth=4 + +" 将 TAB 转换成空格 +set expandtab + +" 为缩进和对齐开启智能化的 TAB 和空格切换功能 +set smarttab +``` + +### 参考 + +[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) |