summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitattributes4
-rw-r--r--.github/CODEOWNERS2
-rw-r--r--ATS.html.markdown607
-rw-r--r--CONTRIBUTING.markdown100
-rw-r--r--LICENSE.txt359
-rw-r--r--ada.html.markdown416
-rw-r--r--ansible.html.markdown5
-rw-r--r--ar-ar/sql-ar.html.markdown135
-rw-r--r--arturo.html.markdown432
-rw-r--r--asciidoc.html.markdown2
-rw-r--r--assemblyscript.html.markdown202
-rw-r--r--asymptotic-notation.html.markdown2
-rw-r--r--awk.html.markdown53
-rw-r--r--ballerina.html.markdown432
-rw-r--r--bash.html.markdown208
-rw-r--r--bf.html.markdown8
-rw-r--r--c++.html.markdown12
-rw-r--r--c.html.markdown65
-rw-r--r--ca-es/asciidoc-ca.html.markdown2
-rw-r--r--ca-es/go-ca.html.markdown14
-rw-r--r--cairo.html.markdown864
-rw-r--r--citron.html.markdown4
-rw-r--r--clojure.html.markdown2
-rw-r--r--cobol.html.markdown2
-rw-r--r--cs-cz/go.html.markdown16
-rw-r--r--cs-cz/markdown.html.markdown10
-rw-r--r--csharp.html.markdown42
-rw-r--r--css.html.markdown17
-rw-r--r--cue.html.markdown551
-rw-r--r--dart.html.markdown5
-rw-r--r--de-de/asciidoc-de.html.markdown13
-rw-r--r--de-de/brainfuck-de.html.markdown4
-rw-r--r--de-de/c++-de.html.markdown2
-rw-r--r--de-de/c-de.html.markdown2
-rw-r--r--de-de/crystal-de.html.markdown561
-rw-r--r--de-de/csharp-de.html.markdown2
-rw-r--r--de-de/elixir-de.html.markdown2
-rw-r--r--de-de/git-de.html.markdown2
-rw-r--r--de-de/go-de.html.markdown8
-rw-r--r--de-de/pug-de.html.markdown4
-rw-r--r--de-de/pyqt-de.html.markdown8
-rw-r--r--de-de/qt-de.html.markdown2
-rw-r--r--de-de/rust-de.html.markdown2
-rw-r--r--de-de/vim-de.html.markdown309
-rw-r--r--de-de/visualbasic-de.html.markdown290
-rw-r--r--de-de/yaml-de.html.markdown2
-rw-r--r--directx9.html.markdown18
-rw-r--r--docker.html.markdown412
-rw-r--r--dynamic-programming.html.markdown2
-rw-r--r--el-gr/rust-gr.html.markdown37
-rw-r--r--elisp.html.markdown17
-rw-r--r--elixir.html.markdown19
-rw-r--r--elm.html.markdown20
-rw-r--r--erlang.html.markdown2
-rw-r--r--es-es/asciidoc-es.html.markdown2
-rw-r--r--es-es/awk-es.html.markdown46
-rw-r--r--es-es/c++-es.html.markdown2
-rw-r--r--es-es/c-es.html.markdown2
-rw-r--r--es-es/chapel-es.html.markdown1219
-rw-r--r--es-es/clojure-es.html.markdown2
-rw-r--r--es-es/css-es.html327
-rw-r--r--es-es/css-es.html.markdown402
-rw-r--r--es-es/elixir-es.html.markdown18
-rw-r--r--es-es/forth-es.html.markdown2
-rw-r--r--es-es/git-es.html.markdown2
-rw-r--r--es-es/go-es.html.markdown12
-rw-r--r--es-es/julia-es.html.markdown2
-rw-r--r--es-es/matlab-es.html.markdown16
-rw-r--r--es-es/powershell-es.html.markdown6
-rw-r--r--es-es/pyqt-es.html.markdown6
-rw-r--r--es-es/python-es.html.markdown12
-rw-r--r--es-es/r-es.html.markdown2
-rw-r--r--es-es/raku-es.html.markdown2
-rw-r--r--es-es/ruby-es.html.markdown8
-rw-r--r--es-es/rust-es.html.markdown2
-rw-r--r--es-es/visualbasic-es.html.markdown2
-rw-r--r--es-es/wolfram-es.html.markdown2
-rw-r--r--fa-ir/css-fa.html.markdown50
-rw-r--r--fa-ir/vim-fa.html.markdown469
-rw-r--r--fi-fi/go-fi.html.markdown16
-rw-r--r--fish.html.markdown109
-rw-r--r--forth.html.markdown17
-rw-r--r--fortran.html.markdown457
-rw-r--r--fortran95.html.markdown453
-rw-r--r--fr-fr/awk-fr.html.markdown210
-rw-r--r--fr-fr/c++-fr.html.markdown2
-rw-r--r--fr-fr/clojure-fr.html.markdown2
-rw-r--r--fr-fr/csharp-fr.html.markdown2
-rw-r--r--fr-fr/elixir-fr.html.markdown2
-rw-r--r--fr-fr/git-fr.html.markdown2
-rw-r--r--fr-fr/go-fr.html.markdown12
-rw-r--r--fr-fr/javascript-fr.html.markdown2
-rw-r--r--fr-fr/markdown-fr.html.markdown55
-rw-r--r--fr-fr/pyqt-fr.html.markdown10
-rw-r--r--fr-fr/rust-fr.html.markdown4
-rw-r--r--fr-fr/set-theory-fr.html.markdown30
-rw-r--r--fr-fr/wolfram-fr.html.markdown2
-rw-r--r--fr-fr/yaml-fr.html.markdown1
-rw-r--r--fsharp.html.markdown15
-rw-r--r--func.html.markdown338
-rw-r--r--gdscript.html.markdown7
-rw-r--r--git.html.markdown20
-rw-r--r--go.html.markdown20
-rw-r--r--groovy.html.markdown5
-rw-r--r--hack.html.markdown630
-rw-r--r--haskell.html.markdown3
-rw-r--r--hdl.html.markdown4
-rw-r--r--hjson.html.markdown94
-rw-r--r--hocon.html.markdown574
-rw-r--r--httpie.html.markdown120
-rw-r--r--hu-hu/go-hu.html.markdown4
-rw-r--r--hu-hu/pythonlegacy-hu.html.markdown2
-rw-r--r--hy.html.markdown9
-rw-r--r--id-id/asciidoc-id.html.markdown2
-rw-r--r--id-id/coffeescript-id.html.markdown2
-rw-r--r--id-id/pyqt-id.html.markdown6
-rw-r--r--images/cairo/build.pngbin0 -> 20768 bytes
-rw-r--r--images/cairo/connect.pngbin0 -> 62073 bytes
-rw-r--r--images/cairo/connect2.pngbin0 -> 66962 bytes
-rw-r--r--images/cairo/declare.pngbin0 -> 74011 bytes
-rw-r--r--images/cairo/deploy.pngbin0 -> 99481 bytes
-rw-r--r--it-it/asciidoc-it.html.markdown2
-rw-r--r--it-it/c++-it.html.markdown2
-rw-r--r--it-it/elixir-it.html.markdown18
-rw-r--r--it-it/go-it.html.markdown16
-rw-r--r--it-it/markdown.html.markdown17
-rw-r--r--it-it/matlab-it.html.markdown16
-rw-r--r--it-it/php-composer-it.html.markdown193
-rw-r--r--it-it/pyqt-it.html.markdown8
-rw-r--r--it-it/qt-it.html.markdown2
-rw-r--r--it-it/rust-it.html.markdown2
-rw-r--r--it-it/solidity.html.markdown1069
-rw-r--r--ja-jp/asciidoc.html.markdown2
-rw-r--r--ja-jp/yaml-jp.html.markdown193
-rw-r--r--janet.html.markdown51
-rw-r--r--java.html.markdown18
-rw-r--r--javascript.html.markdown15
-rw-r--r--jinja.html.markdown270
-rw-r--r--jq.html.markdown910
-rw-r--r--jquery.html.markdown2
-rw-r--r--json.html.markdown2
-rw-r--r--jsonnet.html.markdown2
-rw-r--r--julia.html.markdown14
-rw-r--r--kdb+.html.markdown2
-rw-r--r--ko-kr/clojure-kr.html.markdown2
-rw-r--r--ko-kr/go-kr.html.markdown8
-rw-r--r--ko-kr/markdown-kr.html.markdown53
-rw-r--r--kotlin.html.markdown4
-rw-r--r--lambda-calculus.html.markdown2
-rw-r--r--latex.html.markdown2
-rw-r--r--lbstanza.html.markdown10
-rw-r--r--ldpl.html.markdown7
-rw-r--r--lua.html.markdown15
-rw-r--r--m.html.markdown103
-rw-r--r--markdown.html.markdown60
-rw-r--r--matlab.html.markdown16
-rw-r--r--mercurial.html.markdown14
-rw-r--r--mips.html.markdown8
-rw-r--r--mongodb.html.markdown23
-rw-r--r--montilang.html.markdown2
-rw-r--r--ms-my/clojure-my.html.markdown2
-rw-r--r--neat.html.markdown297
-rw-r--r--nim.html.markdown4
-rw-r--r--nix.html.markdown5
-rw-r--r--objective-c.html.markdown2
-rw-r--r--ocaml.html.markdown205
-rw-r--r--opencv.html.markdown4
-rw-r--r--opengl.html.markdown14
-rw-r--r--openscad.html.markdown117
-rw-r--r--osl.html.markdown751
-rw-r--r--p5.html.markdown136
-rw-r--r--pascal.html.markdown2
-rw-r--r--php.html.markdown11
-rw-r--r--powershell.html.markdown26
-rw-r--r--processing.html.markdown6
-rw-r--r--pt-br/asciidoc-pt.html.markdown2
-rw-r--r--pt-br/awk-pt.html.markdown6
-rw-r--r--pt-br/bc-pt.html.markdown104
-rw-r--r--pt-br/c++-pt.html.markdown4
-rw-r--r--pt-br/c-pt.html.markdown6
-rw-r--r--pt-br/clojure-pt.html.markdown2
-rw-r--r--pt-br/csharp-pt.html.markdown4
-rw-r--r--pt-br/d-pt.html.markdown262
-rw-r--r--pt-br/dart-pt.html.markdown5
-rw-r--r--pt-br/elixir-pt.html.markdown20
-rw-r--r--pt-br/emacs-pt.html.markdown60
-rw-r--r--pt-br/git-pt.html.markdown340
-rw-r--r--pt-br/go-pt.html.markdown10
-rw-r--r--pt-br/groovy-pt.html.markdown15
-rw-r--r--pt-br/latex-pt.html.markdown101
-rw-r--r--pt-br/lua-pt.html.markdown2
-rw-r--r--pt-br/make-pt.html.markdown4
-rw-r--r--pt-br/markdown-pt.html.markdown264
-rw-r--r--pt-br/matlab-pt.html.markdown16
-rw-r--r--pt-br/php-pt.html.markdown2
-rw-r--r--pt-br/processing-pt.html.markdown480
-rw-r--r--pt-br/pug-pt.html.markdown211
-rw-r--r--pt-br/pyqt-pt.html.markdown6
-rw-r--r--pt-br/pythonstatcomp-pt.html.markdown249
-rw-r--r--pt-br/qt-pt.html.markdown2
-rw-r--r--pt-br/r-pt.html.markdown786
-rw-r--r--pt-br/rust-pt.html.markdown2
-rw-r--r--pt-br/sass-pt.html.markdown7
-rw-r--r--pt-br/set-theory-pt.html.markdown129
-rw-r--r--pt-br/sql-pt.html.markdown119
-rw-r--r--pt-br/tmux-pt.html.markdown48
-rw-r--r--pt-br/toml-pt.html.markdown232
-rw-r--r--pt-br/visualbasic-pt.html.markdown42
-rw-r--r--pt-br/yaml-pt.html.markdown157
-rw-r--r--pt-pt/git-pt.html.markdown2
-rw-r--r--pt-pt/kotlin-pt.html.markdown473
-rw-r--r--pug.html.markdown4
-rw-r--r--purescript.html.markdown4
-rw-r--r--pyqt.html.markdown20
-rw-r--r--python.html.markdown217
-rw-r--r--qsharp.html.markdown2
-rw-r--r--r.html.markdown291
-rw-r--r--raku-pod.html.markdown2
-rw-r--r--raku.html.markdown6
-rw-r--r--rdf.html.markdown160
-rw-r--r--ro-ro/clojure-ro.html.markdown2
-rw-r--r--ro-ro/elixir-ro.html.markdown4
-rw-r--r--rst.html.markdown8
-rw-r--r--ru-ru/asymptotic-notation-ru.html.markdown6
-rw-r--r--ru-ru/binary-search-ru.html.markdown2
-rw-r--r--ru-ru/c++-ru.html.markdown4
-rw-r--r--ru-ru/c-ru.html.markdown4
-rw-r--r--ru-ru/clojure-ru.html.markdown2
-rw-r--r--ru-ru/common-lisp-ru.html.markdown7
-rw-r--r--ru-ru/css-ru.html.markdown6
-rw-r--r--ru-ru/elixir-ru.html.markdown2
-rw-r--r--ru-ru/forth-ru.html.markdown4
-rw-r--r--ru-ru/go-ru.html.markdown10
-rw-r--r--ru-ru/haml-ru.html.markdown10
-rw-r--r--ru-ru/haskell-ru.html.markdown6
-rw-r--r--ru-ru/html-ru.html.markdown58
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/learnvisualbasic-ru.html.markdown2
-rw-r--r--ru-ru/linker-ru.html.markdown24
-rw-r--r--ru-ru/markdown-ru.html.markdown41
-rw-r--r--ru-ru/nim-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown22
-rw-r--r--ru-ru/pyqt-ru.html.markdown16
-rw-r--r--ru-ru/python-ru.html.markdown1
-rw-r--r--ru-ru/qt-ru.html.markdown4
-rw-r--r--ru-ru/rust-ru.html.markdown2
-rw-r--r--ru-ru/sql-ru.html.markdown4
-rw-r--r--ru-ru/tmux-ru.html.markdown2
-rw-r--r--ru-ru/typescript-ru.html.markdown4
-rw-r--r--ru-ru/vim-ru.html.markdown6
-rw-r--r--ru-ru/xml-ru.html.markdown2
-rw-r--r--ru-ru/yaml-ru.html.markdown10
-rw-r--r--ru-ru/zfs-ru.html.markdown406
-rw-r--r--rust.html.markdown5
-rw-r--r--scala.html.markdown2
-rw-r--r--sed.html.markdown285
-rw-r--r--set-theory.html.markdown6
-rw-r--r--sing.html.markdown2
-rw-r--r--sk-sk/elixir-sk.html.markdown16
-rw-r--r--sk-sk/git-sk.html.markdown2
-rw-r--r--sk-sk/latex-sk.html.markdown (renamed from sk-sk/latex-sk.html.markdown.tex)0
-rw-r--r--sk-sk/learn-latex-sk.tex209
-rw-r--r--sl-si/asciidoc-sl.html.markdown2
-rw-r--r--smalltalk.html.markdown9
-rw-r--r--solidity.html.markdown28
-rw-r--r--sorbet.html.markdown1040
-rw-r--r--sql.html.markdown2
-rw-r--r--swift.html.markdown3
-rw-r--r--tact.html.markdown603
-rw-r--r--tailspin.html.markdown383
-rw-r--r--tcsh.html.markdown374
-rw-r--r--textile.html.markdown6
-rw-r--r--tmux.html.markdown2
-rwxr-xr-xtoml.html.markdown6
-rw-r--r--tr-tr/bf-tr.html.markdown2
-rw-r--r--tr-tr/c++-tr.html.markdown2
-rw-r--r--tr-tr/c-tr.html.markdown4
-rw-r--r--tr-tr/clojure-tr.html.markdown2
-rw-r--r--tr-tr/csharp-tr.html.markdown2
-rw-r--r--tr-tr/git-tr.html.markdown2
-rw-r--r--typescript.html.markdown6
-rw-r--r--uk-ua/c-ua.html.markdown2
-rw-r--r--uk-ua/go-ua.html.markdown10
-rw-r--r--uk-ua/rust-ua.html.markdown2
-rw-r--r--v.html.markdown229
-rwxr-xr-xvala.html.markdown2
-rw-r--r--vi-vn/git-vi.html.markdown2
-rw-r--r--vi-vn/json-vi.html.markdown2
-rw-r--r--vi-vn/markdown-vi.html.markdown40
-rw-r--r--vi-vn/xml-vi.html.markdown170
-rw-r--r--vim.html.markdown225
-rw-r--r--vimscript.html.markdown14
-rw-r--r--visualbasic.html.markdown2
-rw-r--r--vyper.html.markdown20
-rw-r--r--wolfram.html.markdown2
-rw-r--r--xml.html.markdown2
-rw-r--r--yaml.html.markdown113
-rw-r--r--zfs.html.markdown72
-rw-r--r--zh-cn/asciidoc-cn.html.markdown2
-rw-r--r--zh-cn/awk-cn.html.markdown2
-rw-r--r--zh-cn/c++-cn.html.markdown2
-rw-r--r--zh-cn/c-cn.html.markdown4
-rw-r--r--zh-cn/clojure-cn.html.markdown2
-rw-r--r--zh-cn/clojure-macro-cn.html.markdown2
-rw-r--r--zh-cn/cobol-cn.html.markdown192
-rw-r--r--zh-cn/csharp-cn.html.markdown822
-rw-r--r--zh-cn/docker-cn.html.markdown3
-rw-r--r--zh-cn/elixir-cn.html.markdown2
-rw-r--r--zh-cn/fortran-cn.html.markdown444
-rw-r--r--zh-cn/fortran95-cn.html.markdown435
-rw-r--r--zh-cn/gdscript-cn.html.markdown317
-rw-r--r--zh-cn/git-cn.html.markdown2
-rw-r--r--zh-cn/go-cn.html.markdown12
-rw-r--r--zh-cn/java-cn.html.markdown4
-rw-r--r--zh-cn/json-cn.html.markdown43
-rw-r--r--zh-cn/lua-cn.html.markdown3
-rw-r--r--zh-cn/markdown-cn.html.markdown16
-rw-r--r--zh-cn/matlab-cn.html.markdown2
-rw-r--r--zh-cn/nim-cn.html.markdown2
-rw-r--r--zh-cn/powershell-cn.html.markdown6
-rw-r--r--zh-cn/pyqt-cn.html.markdown6
-rw-r--r--zh-cn/python-cn.html.markdown6
-rw-r--r--zh-cn/qt-cn.html.markdown2
-rw-r--r--zh-cn/ruby-cn.html.markdown4
-rw-r--r--zh-cn/rust-cn.html.markdown2
-rw-r--r--zh-cn/visualbasic-cn.html.markdown2
-rw-r--r--zh-cn/wolfram-cn.html.markdown2
-rw-r--r--zh-tw/elixir-tw.html.markdown16
-rw-r--r--zig.html.markdown981
329 files changed, 24926 insertions, 4801 deletions
diff --git a/.gitattributes b/.gitattributes
index 96d2bb5a..da8c9d63 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -46,13 +46,13 @@ json*.html.markdown linguist-language=JSON
julia*.html.markdown linguist-language=Julia
kotlin*.html.markdown linguist-language=Kotlin
latex*.html.markdown linguist-language=latex
-less*.html.markdown linguist-language=less
+less*.html.markdown linguist-language=Less
livescript*.html.markdown linguist-language=LiveScript
logtalk*.html.markdown linguist-language=Logtalk
lua*.html.markdown linguist-language=Lua
make*.html.markdown linguist-language=Makefile
markdown*.html.markdown linguist-language=Markdown
-matlab*.html.markdown linguist-language=Matlab
+matlab*.html.markdown linguist-language=MATLAB
nim*.html.markdown linguist-language=Nimrod
nix*.html.markdown linguist-language=Nix
objective-c*.html.markdown linguist-language=Objective-C
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6c1efe0d..7bc421a7 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -4,3 +4,5 @@
/zh-cn/ @geoffliu @imba-tjd
/zh-tw/ @geoffliu @imba-tjd
/ko-kr/ @justin-themedium
+/pt-pt/ @mribeirodantas
+/pt-br/ @mribeirodantas
diff --git a/ATS.html.markdown b/ATS.html.markdown
new file mode 100644
index 00000000..f290ac0f
--- /dev/null
+++ b/ATS.html.markdown
@@ -0,0 +1,607 @@
+---
+language: ATS
+contributors:
+ - ["Mark Barbone", "https://github.com/mb64"]
+filename: learnats.dats
+---
+
+ATS is a low-level functional programming language. It has a powerful type
+system which lets you write programs with the same level of control and
+efficiency as C, but in a memory safe and type safe way.
+
+The ATS type system supports:
+
+* Full type erasure: ATS compiles to efficient C
+* Dependent types, including [LF](http://twelf.org/wiki/LF) and proving
+ metatheorems
+* Refinement types
+* Linearity for resource tracking
+* An effect system that tracks exceptions, mutation, termination, and other
+ side effects
+
+This tutorial is not an introduction to functional programming, dependent types,
+or linear types, but rather to how they all fit together in ATS. That said, ATS
+is a very complex language, and this tutorial doesn't cover it all. Not only
+does ATS's type system boast a wide array of confusing features, its
+idiosyncratic syntax can make even "simple" examples hard to understand. In the
+interest of keeping it a reasonable length, this document is meant to give a
+taste of ATS, giving a high-level overview of what's possible and how, rather
+than attempting to fully explain how everything works.
+
+You can [try ATS in your browser](http://www.ats-lang.org/SERVER/MYCODE/Patsoptaas_serve.php),
+or install it from [http://www.ats-lang.org/](http://www.ats-lang.org/).
+
+
+```ocaml
+// Include the standard library
+#include "share/atspre_define.hats"
+#include "share/atspre_staload.hats"
+
+// To compile, either use
+// $ patscc -DATS_MEMALLOC_LIBC program.dats -o program
+// or install the ats-acc wrapper https://github.com/sparverius/ats-acc and use
+// $ acc pc program.dats
+
+// C-style line comments
+/* and C-style block comments */
+(* as well as ML-style block comments *)
+
+/*************** Part 1: the ML fragment ****************/
+
+val () = print "Hello, World!\n"
+
+// No currying
+fn add (x: int, y: int) = x + y
+
+// fn vs fun is like the difference between let and let rec in OCaml/F#
+fun fact (n: int): int = if n = 0 then 1 else n * fact (n-1)
+
+// Multi-argument functions need parentheses when you call them; single-argument
+// functions can omit parentheses
+val forty_three = add (fact 4, 19)
+
+// let is like let in SML
+fn sum_and_prod (x: int, y: int): (int, int) =
+ let
+ val sum = x + y
+ val prod = x * y
+ in (sum, prod) end
+
+// 'type' is the type of all heap-allocated, non-linear types
+// Polymorphic parameters go in {} after the function name
+fn id {a:type} (x: a) = x
+
+// ints aren't heap-allocated, so we can't pass them to 'id'
+// val y: int = id 7 // doesn't compile
+
+// 't@ype' is the type of all non-linear potentially unboxed types. It is a
+// supertype of 'type'.
+// Templated parameters go in {} before the function name
+fn {a:t@ype} id2 (x: a) = x
+
+val y: int = id2 7 // works
+
+// can't have polymorphic t@ype parameters
+// fn id3 {a:t@ype} (x: a) = x // doesn't compile
+
+// explicity specifying type parameters:
+fn id4 {a:type} (x: a) = id {a} x // {} for non-template parameters
+fn id5 {a:type} (x: a) = id2<a> x // <> for template parameters
+fn id6 {a:type} (x: a) = id {..} x // {..} to explicitly infer it
+
+// Heap allocated shareable datatypes
+// using datatypes leaks memory
+datatype These (a:t@ype, b:t@ype) = This of a
+ | That of b
+ | These of (a, b)
+
+// Pattern matching using 'case'
+fn {a,b: t@ype} from_these (x: a, y: b, these: These(a,b)): (a, b) =
+ case these of
+ | This(x) => (x, y) // Shadowing of variable names is fine; here, x shadows
+ // the parameter x
+ | That(y) => (x, y)
+ | These(x, y) => (x, y)
+
+// Partial pattern match using 'case-'
+// Will throw an exception if passed This
+fn {a,b:t@ype} unwrap_that (these: These(a,b)): b =
+ case- these of
+ | That(y) => y
+ | These(_, y) => y
+
+
+/*************** Part 2: refinements ****************/
+
+// Parameterize functions by what values they take and return
+fn cool_add {n:int} {m:int} (x: int n, y: int m): int (n+m) = x + y
+
+// list(a, n) is a list of n a's
+fun square_all {n:int} (xs: list(int, n)): list(int, n) =
+ case xs of
+ | list_nil() => list_nil()
+ | list_cons(x, rest) => list_cons(x * x, square_all rest)
+
+fn {a:t@ype} get_first {n:int | n >= 1} (xs: list(a, n)): a =
+ case+ xs of // '+' asks ATS to prove it's total
+ | list_cons(x, _) => x
+
+// Can't run get_first on lists of length 0
+// val x: int = get_first (list_nil()) // doesn't compile
+
+// in the stdlib:
+// sortdef nat = {n:int | n >= 0}
+// sortdef pos = {n:int | n >= 1}
+
+fn {a:t@ype} also_get_first {n:pos} (xs: list(a, n)): a =
+ let
+ val+ list_cons(x, _) = xs // val+ also works
+ in x end
+
+// tail-recursive reverse
+fun {a:t@ype} reverse {n:int} (xs: list(a, n)): list(a, n) =
+ let
+ // local functions can use type variables from their enclosing scope
+ // this one uses both 'a' and 'n'
+ fun rev_helper {i:nat} (xs: list(a, n-i), acc: list(a, i)): list(a, n) =
+ case xs of
+ | list_nil() => acc
+ | list_cons(x, rest) => rev_helper(rest, list_cons(x, acc))
+ in rev_helper(xs, list_nil) end
+
+// ATS has three context-dependent namespaces
+// the two 'int's mean different things in this example, as do the two 'n's
+fn namespace_example {n:int} (n: int n): int n = n
+// ^^^ sort namespace
+// ^ ^^^ ^ ^^^ ^ statics namespace
+// ^^^^^^^^^^^^^^^^^ ^ ^ value namespace
+
+// a termination metric can go in .< >.
+// it must decrease on each recursive call
+// then ATS will prove it doesn't infinitely recurse
+fun terminating_factorial {n:nat} .<n>. (n: int n): int =
+ if n = 0 then 1 else n * terminating_factorial (n-1)
+
+
+/*************** Part 3: the LF fragment ****************/
+
+// ATS supports proving theorems in LF (http://twelf.org/wiki/LF)
+
+// Relations are represented by inductive types
+
+// Proofs that the nth fibonacci number is f
+dataprop Fib(n:int, m:int) =
+ | FibZero(0, 0)
+ | FibOne(1, 1)
+ | {n, f1, f2: int} FibInd(n, f1 + f2) of (Fib(n-1,f1), Fib(n-2,f2))
+
+// Proved-correct fibonacci implementation
+// [A] B is an existential type: "there exists A such that B"
+// (proof | value)
+fun fib {n:nat} .<n>. (n: int n): [f:int] (Fib(n,f) | int f) =
+ if n = 0 then (FibZero | 0) else
+ if n = 1 then (FibOne | 1) else
+ let
+ val (proof1 | val1) = fib (n-1)
+ val (proof2 | val2) = fib (n-2)
+ // the existential type is inferred
+ in (FibInd(proof1, proof2) | val1 + val2) end
+
+// Faster proved-correct fibonacci implementation
+fn fib_tail {n:nat} (n: int n): [f:int] (Fib(n,f) | int f) =
+ let
+ fun loop {i:int | i < n} {f1, f2: int} .<n - i>.
+ (p1: Fib(i,f1), p2: Fib(i+1,f2)
+ | i: int i, f1: int f1, f2: int f2, n: int n
+ ): [f:int] (Fib(n,f) | int f) =
+ if i = n - 1
+ then (p2 | f2)
+ else loop (p2, FibInd(p2,p1) | i+1, f2, f1+f2, n)
+ in if n = 0 then (FibZero | 0) else loop (FibZero, FibOne | 0, 0, 1, n) end
+
+// Proof-level lists of ints, of type 'sort'
+datasort IntList = ILNil of ()
+ | ILCons of (int, IntList)
+
+// ILAppend(x,y,z) iff x ++ y = z
+dataprop ILAppend(IntList, IntList, IntList) =
+ | {y:IntList} AppendNil(ILNil, y, y)
+ | {a:int} {x,y,z: IntList}
+ AppendCons(ILCons(a,x), y, ILCons(a,z)) of ILAppend(x,y,z)
+
+// prfuns/prfns are compile-time functions acting on proofs
+
+// metatheorem: append is total
+prfun append_total {x,y: IntList} .<x>. (): [z:IntList] ILAppend(x,y,z)
+ = scase x of // scase lets you inspect static arguments (only in prfuns)
+ | ILNil() => AppendNil
+ | ILCons(a,rest) => AppendCons(append_total())
+
+
+/*************** Part 4: views ****************/
+
+// views are like props, but linear; ie they must be consumed exactly once
+// prop is a subtype of view
+
+// 'type @ address' is the most basic view
+
+fn {a:t@ype} read_ptr {l:addr} (pf: a@l | p: ptr l): (a@l | a) =
+ let
+ // !p searches for usable proofs that say something is at that address
+ val x = !p
+ in (pf | x) end
+
+// oops, tried to dereference a potentially invalid pointer
+// fn {a:t@ype} bad {l:addr} (p: ptr l): a = !p // doesn't compile
+
+// oops, dropped the proof (leaked the memory)
+// fn {a:t@ype} bad {l:addr} (pf: a@l | p: ptr l): a = !p // doesn't compile
+
+fn inc_at_ptr {l:addr} (pf: int@l | p: ptr l): (int@l | void) =
+ let
+ // !p := value writes value to the location at p
+ // like !p, it implicitly searches for usable proofs that are in scope
+ val () = !p := !p + 1
+ in (pf | ()) end
+
+// threading proofs through gets annoying
+fn inc_three_times {l:addr} (pf: int@l | p: ptr l): (int@l | void) =
+ let
+ val (pf2 | ()) = inc_at_ptr (pf | p)
+ val (pf3 | ()) = inc_at_ptr (pf2 | p)
+ val (pf4 | ()) = inc_at_ptr (pf3 | p)
+ in (pf4 | ()) end
+
+// so there's special syntactic sugar for when you don't consume a proof
+fn dec_at_ptr {l:addr} (pf: !int@l | p: ptr l): void =
+ !p := !p - 1 // ^ note the exclamation point
+
+fn dec_three_times {l:addr} (pf: !int@l | p: ptr l): void =
+ let
+ val () = dec_at_ptr (pf | p)
+ val () = dec_at_ptr (pf | p)
+ val () = dec_at_ptr (pf | p)
+ in () end
+
+// dataview is like dataprop, but linear
+// A proof that either the address is null, or there is a value there
+dataview MaybeNull(a:t@ype, addr) =
+ | NullPtr(a, null)
+ | {l:addr | l > null} NonNullPtr(a, l) of (a @ l)
+
+fn maybe_inc {l:addr} (pf: !MaybeNull(int, l) | p: ptr l): void =
+ if ptr1_is_null p
+ then ()
+ else let
+ // Deconstruct the proof to access the proof of a @ l
+ prval NonNullPtr(value_exists) = pf
+ val () = !p := !p + 1
+ // Reconstruct it again for the caller
+ prval () = pf := NonNullPtr(value_exists)
+ in () end
+
+// array_v(a,l,n) represents and array of n a's at location l
+// this gets compiled into an efficient for loop, since all proofs are erased
+fn sum_array {l:addr}{n:nat} (pf: !array_v(int,l,n) | p: ptr l, n: int n): int =
+ let
+ fun loop {l:addr}{n:nat} .<n>. (
+ pf: !array_v(int,l,n)
+ | ptr: ptr l,
+ length: int n,
+ acc: int
+ ): int = if length = 0
+ then acc
+ else let
+ prval (head, rest) = array_v_uncons(pf)
+ val result = loop(rest | ptr_add<int>(ptr, 1), length - 1, acc + !ptr)
+ prval () = pf := array_v_cons(head, rest)
+ in result end
+ in loop (pf | p, n, 0) end
+
+// 'var' is used to create stack-allocated (lvalue) variables
+val seven: int = let
+ var res: int = 3
+ // they can be modified
+ val () = res := res + 1
+ // addr@ res is a pointer to it, and view@ res is the associated proof
+ val (pf | ()) = inc_three_times(view@ res | addr@ res)
+ // need to give back the view before the variable goes out of scope
+ prval () = view@ res := pf
+ in res end
+
+// References let you pass lvalues, like in C++
+fn square (x: &int): void =
+ x := x * x // they can be modified
+
+val sixteen: int = let
+ var res: int = 4
+ val () = square res
+ in res end
+
+fn inc_at_ref (x: &int): void =
+ let
+ // like vars, references have views and addresses
+ val (pf | ()) = inc_at_ptr(view@ x | addr@ x)
+ prval () = view@ x := pf
+ in () end
+
+// Like ! for views, & references are only legal as argument types
+// fn bad (x: &int): &int = x // doesn't compile
+
+// this takes a proof int n @ l, but returns a proof int (n+1) @ l
+// since they're different types, we can't use !int @ l like before
+fn refined_inc_at_ptr {n:int}{l:addr} (
+ pf: int n @ l | p: ptr l
+): (int (n+1) @ l | void) =
+ let
+ val () = !p := !p + 1
+ in (pf | ()) end
+
+// special syntactic sugar for returning a proof at a different type
+fn refined_dec_at_ptr {n:int}{l:addr} (
+ pf: !int n @ l >> int (n-1) @ l | p: ptr l
+): void =
+ !p := !p - 1
+
+// legal but very bad code
+prfn swap_proofs {v1,v2:view} (a: !v1 >> v2, b: !v2 >> v1): void =
+ let
+ prval tmp = a
+ prval () = a := b
+ prval () = b := tmp
+ in () end
+
+// also works with references
+fn refined_square {n:int} (x: &int n >> int (n*n)): void =
+ x := x * x
+
+fn replace {a,b:vtype} (dest: &a >> b, src: b): a =
+ let
+ val old = dest
+ val () = dest := src
+ in old end
+
+// values can be uninitialized
+fn {a:vt@ype} write (place: &a? >> a, value: a): void =
+ place := value
+
+val forty: int = let
+ var res: int
+ val () = write (res, 40)
+ in res end
+
+// viewtype: a view and a type
+viewtypedef MaybeNullPtr(a:t@ype) = [l:addr] (MaybeNull(a, l) | ptr l)
+// MaybeNullPtr has type 'viewtype' (aka 'vtype')
+// type is a subtype of vtype and t@ype is a subtype of vt@ype
+
+// The most general identity function:
+fn {a:vt@ype} id7 (x: a) = x
+
+// since they contain views, viewtypes must be used linearly
+// fn {a:vt@ype} duplicate (x: a) = (x, x) // doesn't compile
+// fn {a:vt@ype} ignore (x: a) = () // doesn't compile
+
+// arrayptr(a,l,n) is a convenient built-in viewtype
+fn easier_sum_array {l:addr}{n:nat} (p: !arrayptr(int,l,n), n: int n): int =
+ let
+ fun loop {i:nat | i <= n} (
+ p: !arrayptr(int,l,n), n: int n, i: int i, acc: int
+ ): int =
+ if i = n
+ then acc
+ else loop(p, n, i+1, acc + p[i])
+ in loop(p, n, 0, 0) end
+
+
+/*************** Part 5: dataviewtypes ****************/
+
+// a dataviewtype is a heap-allocated non-shared inductive type
+
+// in the stdlib:
+// dataviewtype list_vt(a:vt@ype, int) =
+// | list_vt_nil(a, 0)
+// | {n:nat} list_vt_cons(a, n+1) of (a, list_vt(a, n))
+
+fn {a:vt@ype} length {n:int} (l: !list_vt(a, n)): int n =
+ let // ^ since we're not consuming it
+ fun loop {acc:int} (l: !list_vt(a, n-acc), acc: int acc): int n =
+ case l of
+ | list_vt_nil() => acc
+ | list_vt_cons(head, tail) => loop(tail, acc + 1)
+ in loop (l, 0) end
+
+// vvvvv not vt@ype, because you can't easily get rid of a vt@ype
+fun {a:t@ype} destroy_list {n:nat} (l: list_vt(a,n)): void =
+ case l of
+ // ~ pattern match consumes and frees that node
+ | ~list_vt_nil() => ()
+ | ~list_vt_cons(_, tail) => destroy_list tail
+
+// unlike a datatype, a dataviewtype can be modified:
+fun {a:vt@ype} push_back {n:nat} (
+ x: a,
+ l: &list_vt(a,n) >> list_vt(a,n+1)
+): void =
+ case l of
+ | ~list_vt_nil() => l := list_vt_cons(x, list_vt_nil)
+ // @ pattern match disassembles/"unfolds" the datavtype's view, so you can
+ // modify its components
+ | @list_vt_cons(head, tail) => let
+ val () = push_back (x, tail)
+ // reassemble it with fold@
+ prval () = fold@ l
+ in () end
+
+fun {a:vt@ype} pop_last {n:pos} (l: &list_vt(a,n) >> list_vt(a,n-1)): a =
+ let
+ val+ @list_vt_cons(head, tail) = l
+ in case tail of
+ | list_vt_cons _ => let
+ val res = pop_last tail
+ prval () = fold@ l
+ in res end
+ | ~list_vt_nil() => let
+ val head = head
+ // Deallocate empty datavtype nodes with free@
+ val () = free@{..}{0} l
+ val () = l := list_vt_nil()
+ in head end
+ /** Equivalently:
+ * | ~list_vt_nil() => let
+ * prval () = fold@ l
+ * val+ ~list_vt_cons(head, ~list_vt_nil()) = l
+ * val () = l := list_vt_nil()
+ * in head end
+ */
+ end
+
+// "holes" (ie uninitialized memory) can be created with _ on the RHS
+// This function uses destination-passing-style to copy the list in a single
+// tail-recursive pass.
+fn {a:t@ype} copy_list {n:nat} (l: !list_vt(a, n)): list_vt(a, n) =
+ let
+ var res: ptr
+ fun loop {k:nat} (l: !list_vt(a, k), hole: &ptr? >> list_vt(a, k)): void =
+ case l of
+ | list_vt_nil() => hole := list_vt_nil
+ | list_vt_cons(first, rest) => let
+ val () = hole := list_vt_cons{..}{k-1}(first, _)
+ // ^ on RHS: a hole
+ val+list_vt_cons(_, new_hole) = hole
+ // ^ on LHS: wildcard pattern (not a hole)
+ val () = loop (rest, new_hole)
+ prval () = fold@ hole
+ in () end
+ val () = loop (l, res)
+ in res end
+
+// Reverse a linked-list *in place* -- no allocations or frees
+fn {a:vt@ype} in_place_reverse {n:nat} (l: list_vt(a, n)): list_vt(a, n) =
+ let
+ fun loop {k:nat} (l: list_vt(a, n-k), acc: list_vt(a, k)): list_vt(a, n) =
+ case l of
+ | ~list_vt_nil() => acc
+ | @list_vt_cons(x, tail) => let
+ val rest = replace(tail, acc)
+ // the node 'l' is now part of acc instead of the original list
+ prval () = fold@ l
+ in loop (rest, l) end
+ in loop (l, list_vt_nil) end
+
+
+/*************** Part 6: miscellaneous extras ****************/
+
+// a record
+// Point has type 't@ype'
+typedef Point = @{ x= int, y= int }
+val origin: Point = @{ x= 0, y= 0 }
+
+// tuples and records are normally unboxed, but there are boxed variants
+// BoxedPoint has type 'type'
+typedef BoxedPoint = '{ x= int, y= int }
+val boxed_pair: '(int,int) = '(5, 3)
+
+// When passing a pair as the single argument to a function, it needs to be
+// written @(a,b) to avoid ambiguity with multi-argument functions
+val six_plus_seven = let
+ fun sum_of_pair (pair: (int,int)) = pair.0 + pair.1
+ in sum_of_pair @(6, 7) end
+
+// When a constructor has no associated data, such as None(), the parentheses
+// are optional in expressions. However, they are mandatory in patterns
+fn inc_option (opt: Option int) =
+ case opt of
+ | Some(x) => Some(x+1)
+ | None() => None
+
+// ATS has a simple FFI, since it compiles to C and (mostly) uses the C ABI
+%{
+// Inline C code
+int scanf_wrapper(void *format, void *value) {
+ return scanf((char *) format, (int *) value);
+}
+%}
+// If you wanted to, you could define a custom dataviewtype more accurately
+// describing the result of scanf
+extern fn scanf (format: string, value: &int): int = "scanf_wrapper"
+
+fn get_input_number (): Option int =
+ let
+ var x: int = 0
+ in
+ if scanf("%d\n", x) = 1
+ then Some(x)
+ else None
+ end
+
+// extern is also used for separate declarations and definitions
+extern fn say_hi (): void
+// later on, or in another file:
+implement say_hi () = print "hi\n"
+
+// if you implement main0, it will run as the main function
+// implmnt is an alias for implement
+implmnt main0 () = ()
+
+// as well as for axioms:
+extern praxi view_id {a:view} (x: a): a
+// you don't need to actually implement the axioms, but you could
+primplmnt view_id x = x
+// primplmnt is an alias for primplement
+
+// Some standard aliases are:
+// List0(a) = [n:nat] list(a,n) and List0_vt(a) = [n:nat] list_vt(a,n)
+// t0p = t@ype and vt0p = vt@ype
+fun {a:t0p} append (xs: List0 a, ys: List0 a): List0 a =
+ case xs of
+ | list_nil() => ys
+ | list_cons(x, xs) => list_cons(x, append(xs, ys))
+
+// there are many ways of doing things after one another
+val let_in_example = let
+ val () = print "thing one\n"
+ val () = print "thing two\n"
+ in () end
+
+val parens_example = (print "thing one\n"; print "thing two\n")
+
+val begin_end_example = begin
+ print "thing one\n";
+ print "thing two\n"; // optional trailing semicolon
+ end
+
+// and many ways to use local variables
+fun times_four_let x =
+ let
+ fun times_two (x: int) = x * 2
+ in times_two (times_two x) end
+
+local
+ fun times_two (x: int) = x * 2
+in
+ fun times_four_local x = times_two (times_two x)
+end
+
+fun times_four_where x = times_two (times_two x)
+ where {
+ fun times_two (x: int) = x * 2
+ }
+
+//// The last kind of comment in ATS is an end-of-file comment.
+
+Anything between the four slashes and the end of the file is ignored.
+
+Have fun with ATS!
+```
+
+## Learn more
+
+This isn't all there is to ATS -- notably, some core features like closures and
+the effect system are left out, as well as other less type-y stuff like modules
+and the build system. If you'd like to write these sections yourself,
+contributions would be welcome!
+
+To learn more about ATS, visit the [ATS website](http://www.ats-lang.org/), in
+particular the [documentation page](http://www.ats-lang.org/Documents.html).
+
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown
index 8d2a8320..f3556efa 100644
--- a/CONTRIBUTING.markdown
+++ b/CONTRIBUTING.markdown
@@ -16,27 +16,29 @@ review them more effectively and/or individually.
## Style Guidelines
-- **Keep lines under 80 chars**
- + Try to keep **line length in code blocks to 80 characters or fewer**.
- + Otherwise, the text will overflow and look odd.
-- **Prefer example to exposition**
- + Try to use as few words as possible.
- + Code examples are preferred over exposition in all cases.
-- **Eschew surplusage**
- + We welcome newcomers, but the target audience for this site is programmers
- with some experience.
- + Try to avoid explaining basic concepts except for those specific to the
- language in question.
- + Keep articles succinct and scannable. We all know how to use Google here.
-- **Use UTF-8**
- + For translations (or EN articles with non-ASCII characters) please make sure
- your file is UTF-8 encoded.
- + Try to leave out the byte-order-mark at the start of the file. (`:set nobomb`
- in Vim)
- + You can check if the file contains a BOM on Linux/Unix systems by running
+* **Keep lines under 80 chars**
+ * Try to keep **line length in code blocks to 80 characters or fewer**.
+ * Otherwise, the text will overflow and look odd.
+ * This and other potential pitfalls to format the content consistently are
+ identified by the freely available
+ [markdownlint](https://github.com/markdownlint/markdownlint).
+* **Prefer example to exposition**
+ * Try to use as few words as possible.
+ * Code examples are preferred over exposition in all cases.
+* **Eschew surplusage**
+ * We welcome newcomers, but the target audience for this site is programmers
+ with some experience.
+ * Try to avoid explaining basic concepts except for those specific to the
+ language in question.
+ * Keep articles succinct and scannable. We all know how to use Google here.
+* **Use UTF-8**
+ * For translations (or EN articles with non-ASCII characters) please ensure
+ your file is UTF-8 encoded.
+ * Leave out the byte-order-mark (BOM) at the start of the file (in Vim, use
+ `:set nobomb`).
+ * You can check if the file contains a BOM on Linux/Unix systems by running
`file language.html.markdown` You will see this if it uses a BOM:
- `UTF-8 Unicode (with BOM) text`.
-
+ `UTF-8 Unicode (with BOM) text`.
### Header configuration
@@ -47,34 +49,38 @@ some key information be defined in the header.
The following fields are necessary for English articles about programming
languages:
-- **language** The *programming language* in question
-- **contributors** A list of [author, URL] lists to credit
+* **language** The *programming language* in question
+* **contributors** A list of [author, URL] lists to credit
Other fields:
-- **category**: The category of the article. So far, can be one of *language*,
+* **category**: The category of the article. So far, can be one of *language*,
*tool* or *Algorithms & Data Structures*. Defaults to *language* if omitted.
-- **filename**: The filename for this article's code. It will be fetched, mashed
+* **filename**: The filename for this article's code. It will be fetched, mashed
together, and made downloadable.
- + For non-English articles, *filename* should have a language-specific
- suffix.
-- **lang**: For translations, the human language this article is in. For
+ * For non-English articles, *filename* should have a language-specific
+ suffix.
+* **lang**: For translations, the human language this article is in. For
categorization, mostly.
Here's an example header for an Esperanto translation of Ruby:
```yaml
----
+*--
language: ruby
filename: learnruby-epo.ruby
contributors:
- ["Doktor Esperanto", "http://example.com/"]
- ["Someone else", "http://someoneelseswebsite.com/"]
lang: ep-ep
----
+*--
```
-### Should I add myself as a Contributor?
+### Syntax highlighter
+
+[Rouge](https://github.com/rouge-ruby/rouge/wiki/List-of-supported-languages-and-lexers) is used for syntax highlighting.
+
+### Should I add myself as a contributor?
If you want to add yourself to contributors, keep in mind that contributors get
equal billing, and the first contributor usually wrote the whole article. Please
@@ -85,21 +91,25 @@ addition or not.
You can build the site locally to test your changes. Follow the steps below.
-* Install Ruby language runtime and RubyGems. See [here](https://middlemanapp.com/basics/install/) for more details.
-* Clone or zip download the [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) repo.
- * `git clone https://github.com/adambard/learnxinyminutes-site`
+* Install Ruby language runtime and RubyGems. See
+ [here](https://middlemanapp.com/basics/install/)
+ for more details.
+* Clone or zip download the
+ [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site)
+ repository.
+ * `git clone https://github.com/adambard/learnxinyminutes-site`
* Install Middleman and other required dependencies using Bundler.
- * `cd learnxinyminutes-site/`
- * `bundle install`
+ * `cd learnxinyminutes-site/`
+ * `bundle install`
* Get the source in place
- * Copy the contents of your clone of the fork of learnxinyminutes-docs repo
- into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs`
- folder inside the `docs` folder, it should just contain all the repo
- contents.
- * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`.
- * `cd source/docs/`
- * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/`
+ * Copy the contents of your clone of the fork of learnxinyminutes-docs repo
+ into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs`
+ folder inside the `docs` folder, it should just contain all the repo
+ contents.
+ * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`.
+ * `cd source/docs/`
+ * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/`
* Build the site or run a development server to test your changes (NOTE: run
-these commands at `learnxinyminutes-site/`).
- * Build - `bundle exec middleman build`
- * Dev server - `bundle exec middleman --force-polling --verbose`
+ these commands at `learnxinyminutes-site/`).
+ * Build - `bundle exec middleman build`
+ * Dev server - `bundle exec middleman --force-polling --verbose`
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 00000000..604209a8
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,359 @@
+Creative Commons Legal Code
+
+Attribution-ShareAlike 3.0 Unported
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
+ DAMAGES RESULTING FROM ITS USE.
+
+License
+
+THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
+COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
+COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
+AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
+
+BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
+TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
+BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
+CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
+CONDITIONS.
+
+1. Definitions
+
+ a. "Adaptation" means a work based upon the Work, or upon the Work and
+ other pre-existing works, such as a translation, adaptation,
+ derivative work, arrangement of music or other alterations of a
+ literary or artistic work, or phonogram or performance and includes
+ cinematographic adaptations or any other form in which the Work may be
+ recast, transformed, or adapted including in any form recognizably
+ derived from the original, except that a work that constitutes a
+ Collection will not be considered an Adaptation for the purpose of
+ this License. For the avoidance of doubt, where the Work is a musical
+ work, performance or phonogram, the synchronization of the Work in
+ timed-relation with a moving image ("synching") will be considered an
+ Adaptation for the purpose of this License.
+ b. "Collection" means a collection of literary or artistic works, such as
+ encyclopedias and anthologies, or performances, phonograms or
+ broadcasts, or other works or subject matter other than works listed
+ in Section 1(f) below, which, by reason of the selection and
+ arrangement of their contents, constitute intellectual creations, in
+ which the Work is included in its entirety in unmodified form along
+ with one or more other contributions, each constituting separate and
+ independent works in themselves, which together are assembled into a
+ collective whole. A work that constitutes a Collection will not be
+ considered an Adaptation (as defined below) for the purposes of this
+ License.
+ c. "Creative Commons Compatible License" means a license that is listed
+ at https://creativecommons.org/compatiblelicenses that has been
+ approved by Creative Commons as being essentially equivalent to this
+ License, including, at a minimum, because that license: (i) contains
+ terms that have the same purpose, meaning and effect as the License
+ Elements of this License; and, (ii) explicitly permits the relicensing
+ of adaptations of works made available under that license under this
+ License or a Creative Commons jurisdiction license with the same
+ License Elements as this License.
+ d. "Distribute" means to make available to the public the original and
+ copies of the Work or Adaptation, as appropriate, through sale or
+ other transfer of ownership.
+ e. "License Elements" means the following high-level license attributes
+ as selected by Licensor and indicated in the title of this License:
+ Attribution, ShareAlike.
+ f. "Licensor" means the individual, individuals, entity or entities that
+ offer(s) the Work under the terms of this License.
+ g. "Original Author" means, in the case of a literary or artistic work,
+ the individual, individuals, entity or entities who created the Work
+ or if no individual or entity can be identified, the publisher; and in
+ addition (i) in the case of a performance the actors, singers,
+ musicians, dancers, and other persons who act, sing, deliver, declaim,
+ play in, interpret or otherwise perform literary or artistic works or
+ expressions of folklore; (ii) in the case of a phonogram the producer
+ being the person or legal entity who first fixes the sounds of a
+ performance or other sounds; and, (iii) in the case of broadcasts, the
+ organization that transmits the broadcast.
+ h. "Work" means the literary and/or artistic work offered under the terms
+ of this License including without limitation any production in the
+ literary, scientific and artistic domain, whatever may be the mode or
+ form of its expression including digital form, such as a book,
+ pamphlet and other writing; a lecture, address, sermon or other work
+ of the same nature; a dramatic or dramatico-musical work; a
+ choreographic work or entertainment in dumb show; a musical
+ composition with or without words; a cinematographic work to which are
+ assimilated works expressed by a process analogous to cinematography;
+ a work of drawing, painting, architecture, sculpture, engraving or
+ lithography; a photographic work to which are assimilated works
+ expressed by a process analogous to photography; a work of applied
+ art; an illustration, map, plan, sketch or three-dimensional work
+ relative to geography, topography, architecture or science; a
+ performance; a broadcast; a phonogram; a compilation of data to the
+ extent it is protected as a copyrightable work; or a work performed by
+ a variety or circus performer to the extent it is not otherwise
+ considered a literary or artistic work.
+ i. "You" means an individual or entity exercising rights under this
+ License who has not previously violated the terms of this License with
+ respect to the Work, or who has received express permission from the
+ Licensor to exercise rights under this License despite a previous
+ violation.
+ j. "Publicly Perform" means to perform public recitations of the Work and
+ to communicate to the public those public recitations, by any means or
+ process, including by wire or wireless means or public digital
+ performances; to make available to the public Works in such a way that
+ members of the public may access these Works from a place and at a
+ place individually chosen by them; to perform the Work to the public
+ by any means or process and the communication to the public of the
+ performances of the Work, including by public digital performance; to
+ broadcast and rebroadcast the Work by any means including signs,
+ sounds or images.
+ k. "Reproduce" means to make copies of the Work by any means including
+ without limitation by sound or visual recordings and the right of
+ fixation and reproducing fixations of the Work, including storage of a
+ protected performance or phonogram in digital form or other electronic
+ medium.
+
+2. Fair Dealing Rights. Nothing in this License is intended to reduce,
+limit, or restrict any uses free from copyright or rights arising from
+limitations or exceptions that are provided for in connection with the
+copyright protection under copyright law or other applicable laws.
+
+3. License Grant. Subject to the terms and conditions of this License,
+Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
+perpetual (for the duration of the applicable copyright) license to
+exercise the rights in the Work as stated below:
+
+ a. to Reproduce the Work, to incorporate the Work into one or more
+ Collections, and to Reproduce the Work as incorporated in the
+ Collections;
+ b. to create and Reproduce Adaptations provided that any such Adaptation,
+ including any translation in any medium, takes reasonable steps to
+ clearly label, demarcate or otherwise identify that changes were made
+ to the original Work. For example, a translation could be marked "The
+ original work was translated from English to Spanish," or a
+ modification could indicate "The original work has been modified.";
+ c. to Distribute and Publicly Perform the Work including as incorporated
+ in Collections; and,
+ d. to Distribute and Publicly Perform Adaptations.
+ e. For the avoidance of doubt:
+
+ i. Non-waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme cannot be waived, the Licensor
+ reserves the exclusive right to collect such royalties for any
+ exercise by You of the rights granted under this License;
+ ii. Waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme can be waived, the Licensor waives the
+ exclusive right to collect such royalties for any exercise by You
+ of the rights granted under this License; and,
+ iii. Voluntary License Schemes. The Licensor waives the right to
+ collect royalties, whether individually or, in the event that the
+ Licensor is a member of a collecting society that administers
+ voluntary licensing schemes, via that society, from any exercise
+ by You of the rights granted under this License.
+
+The above rights may be exercised in all media and formats whether now
+known or hereafter devised. The above rights include the right to make
+such modifications as are technically necessary to exercise the rights in
+other media and formats. Subject to Section 8(f), all rights not expressly
+granted by Licensor are hereby reserved.
+
+4. Restrictions. The license granted in Section 3 above is expressly made
+subject to and limited by the following restrictions:
+
+ a. You may Distribute or Publicly Perform the Work only under the terms
+ of this License. You must include a copy of, or the Uniform Resource
+ Identifier (URI) for, this License with every copy of the Work You
+ Distribute or Publicly Perform. You may not offer or impose any terms
+ on the Work that restrict the terms of this License or the ability of
+ the recipient of the Work to exercise the rights granted to that
+ recipient under the terms of the License. You may not sublicense the
+ Work. You must keep intact all notices that refer to this License and
+ to the disclaimer of warranties with every copy of the Work You
+ Distribute or Publicly Perform. When You Distribute or Publicly
+ Perform the Work, You may not impose any effective technological
+ measures on the Work that restrict the ability of a recipient of the
+ Work from You to exercise the rights granted to that recipient under
+ the terms of the License. This Section 4(a) applies to the Work as
+ incorporated in a Collection, but this does not require the Collection
+ apart from the Work itself to be made subject to the terms of this
+ License. If You create a Collection, upon notice from any Licensor You
+ must, to the extent practicable, remove from the Collection any credit
+ as required by Section 4(c), as requested. If You create an
+ Adaptation, upon notice from any Licensor You must, to the extent
+ practicable, remove from the Adaptation any credit as required by
+ Section 4(c), as requested.
+ b. You may Distribute or Publicly Perform an Adaptation only under the
+ terms of: (i) this License; (ii) a later version of this License with
+ the same License Elements as this License; (iii) a Creative Commons
+ jurisdiction license (either this or a later license version) that
+ contains the same License Elements as this License (e.g.,
+ Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible
+ License. If you license the Adaptation under one of the licenses
+ mentioned in (iv), you must comply with the terms of that license. If
+ you license the Adaptation under the terms of any of the licenses
+ mentioned in (i), (ii) or (iii) (the "Applicable License"), you must
+ comply with the terms of the Applicable License generally and the
+ following provisions: (I) You must include a copy of, or the URI for,
+ the Applicable License with every copy of each Adaptation You
+ Distribute or Publicly Perform; (II) You may not offer or impose any
+ terms on the Adaptation that restrict the terms of the Applicable
+ License or the ability of the recipient of the Adaptation to exercise
+ the rights granted to that recipient under the terms of the Applicable
+ License; (III) You must keep intact all notices that refer to the
+ Applicable License and to the disclaimer of warranties with every copy
+ of the Work as included in the Adaptation You Distribute or Publicly
+ Perform; (IV) when You Distribute or Publicly Perform the Adaptation,
+ You may not impose any effective technological measures on the
+ Adaptation that restrict the ability of a recipient of the Adaptation
+ from You to exercise the rights granted to that recipient under the
+ terms of the Applicable License. This Section 4(b) applies to the
+ Adaptation as incorporated in a Collection, but this does not require
+ the Collection apart from the Adaptation itself to be made subject to
+ the terms of the Applicable License.
+ c. If You Distribute, or Publicly Perform the Work or any Adaptations or
+ Collections, You must, unless a request has been made pursuant to
+ Section 4(a), keep intact all copyright notices for the Work and
+ provide, reasonable to the medium or means You are utilizing: (i) the
+ name of the Original Author (or pseudonym, if applicable) if supplied,
+ and/or if the Original Author and/or Licensor designate another party
+ or parties (e.g., a sponsor institute, publishing entity, journal) for
+ attribution ("Attribution Parties") in Licensor's copyright notice,
+ terms of service or by other reasonable means, the name of such party
+ or parties; (ii) the title of the Work if supplied; (iii) to the
+ extent reasonably practicable, the URI, if any, that Licensor
+ specifies to be associated with the Work, unless such URI does not
+ refer to the copyright notice or licensing information for the Work;
+ and (iv) , consistent with Ssection 3(b), in the case of an
+ Adaptation, a credit identifying the use of the Work in the Adaptation
+ (e.g., "French translation of the Work by Original Author," or
+ "Screenplay based on original Work by Original Author"). The credit
+ required by this Section 4(c) may be implemented in any reasonable
+ manner; provided, however, that in the case of a Adaptation or
+ Collection, at a minimum such credit will appear, if a credit for all
+ contributing authors of the Adaptation or Collection appears, then as
+ part of these credits and in a manner at least as prominent as the
+ credits for the other contributing authors. For the avoidance of
+ doubt, You may only use the credit required by this Section for the
+ purpose of attribution in the manner set out above and, by exercising
+ Your rights under this License, You may not implicitly or explicitly
+ assert or imply any connection with, sponsorship or endorsement by the
+ Original Author, Licensor and/or Attribution Parties, as appropriate,
+ of You or Your use of the Work, without the separate, express prior
+ written permission of the Original Author, Licensor and/or Attribution
+ Parties.
+ d. Except as otherwise agreed in writing by the Licensor or as may be
+ otherwise permitted by applicable law, if You Reproduce, Distribute or
+ Publicly Perform the Work either by itself or as part of any
+ Adaptations or Collections, You must not distort, mutilate, modify or
+ take other derogatory action in relation to the Work which would be
+ prejudicial to the Original Author's honor or reputation. Licensor
+ agrees that in those jurisdictions (e.g. Japan), in which any exercise
+ of the right granted in Section 3(b) of this License (the right to
+ make Adaptations) would be deemed to be a distortion, mutilation,
+ modification or other derogatory action prejudicial to the Original
+ Author's honor and reputation, the Licensor will waive or not assert,
+ as appropriate, this Section, to the fullest extent permitted by the
+ applicable national law, to enable You to reasonably exercise Your
+ right under Section 3(b) of this License (right to make Adaptations)
+ but not otherwise.
+
+5. Representations, Warranties and Disclaimer
+
+UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
+OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
+KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
+INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
+FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
+LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
+WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
+OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
+
+6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
+LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
+ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
+ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
+BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. Termination
+
+ a. This License and the rights granted hereunder will terminate
+ automatically upon any breach by You of the terms of this License.
+ Individuals or entities who have received Adaptations or Collections
+ from You under this License, however, will not have their licenses
+ terminated provided such individuals or entities remain in full
+ compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
+ survive any termination of this License.
+ b. Subject to the above terms and conditions, the license granted here is
+ perpetual (for the duration of the applicable copyright in the Work).
+ Notwithstanding the above, Licensor reserves the right to release the
+ Work under different license terms or to stop distributing the Work at
+ any time; provided, however that any such election will not serve to
+ withdraw this License (or any other license that has been, or is
+ required to be, granted under the terms of this License), and this
+ License will continue in full force and effect unless terminated as
+ stated above.
+
+8. Miscellaneous
+
+ a. Each time You Distribute or Publicly Perform the Work or a Collection,
+ the Licensor offers to the recipient a license to the Work on the same
+ terms and conditions as the license granted to You under this License.
+ b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
+ offers to the recipient a license to the original Work on the same
+ terms and conditions as the license granted to You under this License.
+ c. If any provision of this License is invalid or unenforceable under
+ applicable law, it shall not affect the validity or enforceability of
+ the remainder of the terms of this License, and without further action
+ by the parties to this agreement, such provision shall be reformed to
+ the minimum extent necessary to make such provision valid and
+ enforceable.
+ d. No term or provision of this License shall be deemed waived and no
+ breach consented to unless such waiver or consent shall be in writing
+ and signed by the party to be charged with such waiver or consent.
+ e. This License constitutes the entire agreement between the parties with
+ respect to the Work licensed here. There are no understandings,
+ agreements or representations with respect to the Work not specified
+ here. Licensor shall not be bound by any additional provisions that
+ may appear in any communication from You. This License may not be
+ modified without the mutual written agreement of the Licensor and You.
+ f. The rights granted under, and the subject matter referenced, in this
+ License were drafted utilizing the terminology of the Berne Convention
+ for the Protection of Literary and Artistic Works (as amended on
+ September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
+ Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
+ and the Universal Copyright Convention (as revised on July 24, 1971).
+ These rights and subject matter take effect in the relevant
+ jurisdiction in which the License terms are sought to be enforced
+ according to the corresponding provisions of the implementation of
+ those treaty provisions in the applicable national law. If the
+ standard suite of rights granted under applicable copyright law
+ includes additional rights not granted under this License, such
+ additional rights are deemed to be included in the License; this
+ License is not intended to restrict the license of any rights under
+ applicable law.
+
+
+Creative Commons Notice
+
+ Creative Commons is not a party to this License, and makes no warranty
+ whatsoever in connection with the Work. Creative Commons will not be
+ liable to You or any party on any legal theory for any damages
+ whatsoever, including without limitation any general, special,
+ incidental or consequential damages arising in connection to this
+ license. Notwithstanding the foregoing two (2) sentences, if Creative
+ Commons has expressly identified itself as the Licensor hereunder, it
+ shall have all rights and obligations of Licensor.
+
+ Except for the limited purpose of indicating to the public that the
+ Work is licensed under the CCPL, Creative Commons does not authorize
+ the use by either party of the trademark "Creative Commons" or any
+ related trademark or logo of Creative Commons without the prior
+ written consent of Creative Commons. Any permitted use will be in
+ compliance with Creative Commons' then-current trademark usage
+ guidelines, as may be published on its website or otherwise made
+ available upon request from time to time. For the avoidance of doubt,
+ this trademark restriction does not form part of the License.
+
+ Creative Commons may be contacted at https://creativecommons.org/.
diff --git a/ada.html.markdown b/ada.html.markdown
new file mode 100644
index 00000000..7191c5dc
--- /dev/null
+++ b/ada.html.markdown
@@ -0,0 +1,416 @@
+---
+language: Ada
+filename: learn.ada
+contributors:
+ - ["Luke A. Guest", "https://github.com/Lucretia"]
+ - ["Fernando Oleo Blanco", "https://github.com/Irvise"]
+ - ["Fabien Chouteau", "https://github.com/Fabien-Chouteau"]
+ - ["Manuel", "https://github.com/mgrojo"]
+---
+
+Ada is a strong statically typed imperative, [object-oriented](https://ada-lang.io/docs/arm/AA-3/AA-3.9), [real-time](https://ada-lang.io/docs/arm/AA-D), [parallel](https://ada-lang.io/docs/arm/AA-9) and [distributed](https://ada-lang.io/docs/arm/AA-9) programming language from the Pascal/Algol family of languages, but nowadays, it only has a passing resemblance to Pascal, with the only remnants left being the ```begin/end``` keyword pair, the ```:=``` assignment symbol, records and ```if/case``` control statement structures.
+
+Ada was originally designed to be an [object-based](https://ada-lang.io/docs/arm/AA-3/AA-3.3) language and to replace 100's of languages in use by the US government. This means that all entities are objects, not in the object-oriented sense. The language became [Object-Oriented](https://ada-lang.io/docs/arm/AA-3/AA-3.9) in 1995, and added [interfaces](https://ada-lang.io/docs/arm/AA-3/AA-3.9#Subclause_3.9.4) derived from Java in 2005. [Contract based](https://ada-lang.io/docs/arm/AA-13/AA-13.1#Subclause_13.1.1) programming was introduced with Ada 2012.
+
+Ada was designed to be easy to read and learn, even for non-programmers, e.g. management within an organisation, therefore programs written in the language tend to be a bit more verbose.
+
+Ada is a modern programming language, and now has a package manager like other modern languages, Alire, see below.
+
+```ada
+-- Comments are written with a double hyphen and exist until the end of
+-- the line.
+
+-- You do not need to call the entry point "Main" or "main," you should
+-- name it based on what the program does.
+procedure Empty is
+ -- This is a declarative part.
+begin
+ -- Statements go here.
+ null; -- Do nothing here.
+end Empty;
+
+-- Ada compilers accept compilation units which can be library packages,
+-- tasks, sub-programs, generics, etc.
+
+-- This is where "context clauses" go, these can be pragmas or "with"
+-- statements. "with" is equivalent to "include" or "import" in other
+-- languages.
+with Ada.Text_IO; -- Get access to a library package.
+
+procedure Hello is
+begin
+ Ada.Text_IO.Put_Line ("Hello, world");
+
+ Ada.Text_IO.Put ("Hello again, world");
+ Ada.Text_IO.New_Line;
+end Hello;
+
+
+-- Ada has a real module system. Modules are called packages and are split into
+-- two component parts, the specification and a body.
+-- It is important to introduce packages early, as you will be using them from
+-- the start.
+package Stuff is
+ -- We could add the following line in order to tell the compiler that this
+ -- package does not have to run any code before the "main" procedure starts.
+ -- pragma Preelaborate;
+
+ -- Packages can be nested within the same file or externally.
+ -- Nested packages are accessed via dot notation, e.g. Stuff.Things.My.
+ package Things is
+ My : constant Integer := 100;
+ end Things;
+
+ -- If there are sub-programs declared within the specification, the body
+ -- of the sub-program must be declared within the package body.
+ procedure Do_Something; -- If a subprogram takes no parameters, empty
+ -- parentheses are not required, unlike other
+ -- languages.
+
+ -- We can also make generic sub-programs.
+ generic
+ type Element is (<>); -- The "(<>)" notation specifies that only
+ -- discrete types can be passed into the generic.
+ procedure Swap (Left, Right : in out Element);
+
+ -- Sometimes we want to hide how a type is defined from the outside world
+ -- so that nobody can mess with it directly. The full type must be defined
+ -- within the private section below.
+ type Blobs is private;
+
+ -- We can also make types "limited" by putting this keyword after the "is"
+ -- keyword, this means that the user cannot copy objects of that type
+ -- around, like they normally could.
+private
+ type Blobs is new Integer range -25 .. 25;
+end Stuff;
+
+
+package body Stuff is
+ -- Sub-program body.
+ procedure Do_Something is
+ -- We can nest sub-programs too.
+ -- Parameters are defined with the direction of travel, in, in out, out.
+ -- If the direction of travel is not specified, they are in by default.
+ function Times_4 (Value : in Integer) return Integer is
+ begin
+ return Value * 4;
+ end Times_4;
+
+ I : Integer := 4;
+ begin
+ I := Times_4 (I);
+ end Do_Something;
+
+
+ -- Generic procedure body.
+ procedure Swap (Left, Right : in out Element) is
+ Temp : Element := Left;
+ begin
+ Left := Right;
+ Right := Temp;
+ end Swap;
+begin
+ -- If we need to initialise something within the package, we can do it
+ -- here.
+ Do_Something;
+end Stuff;
+
+
+with Ada.Unchecked_Conversion;
+with Ada.Text_IO;
+with Stuff;
+
+procedure LearnAdaInY is
+ -- Indentation is 3 spaces.
+
+ -- The most important feature in Ada is the type. Objects have types and an
+ -- object of one type cannot be assigned to an object of another type.
+
+ -- You can, and should, define your own types for the domain you are
+ -- modelling. But you can use the standard types to start with and then
+ -- replace them later with your own types, this could be called a form of
+ -- gradual typing.
+
+ -- The standard types would only really be a good starting point for binding
+ -- to other languages, like C. Ada is the only language with a standardised
+ -- way to bind with C, Fortran and COBOL! See the links in the References
+ -- section with more information on binding to these languages.
+
+ type Degrees is range 0 .. 360; -- This is a type. Its underlying
+ -- representation is an Integer.
+
+ type Hues is (Red, Green, Blue, Purple, Yellow); -- So is this. Here, we
+ -- are declaring an
+ -- Enumeration.
+
+ -- This is a modular type. They behave like Integers that automatically
+ -- wrap around. In this specific case, the range would be 0 .. 359.
+ -- If we added 1 to a variable containing the value 359, we would receive
+ -- back 0. They are very useful for arrays.
+ type Degrees_Wrap is mod 360;
+
+ -- You can restrict a type's range using a subtype, this makes them
+ -- compatible with each other, i.e. the subtype can be assigned to an
+ -- object of the type, as can be seen below.
+ subtype Primaries is Hues range Red .. Blue; -- This is a range.
+
+ -- You can define variables or constants like this:
+ -- Var_Name : Type := Value;
+
+ -- 10 is a universal integer. These universal numerics can be used with
+ -- any type which matches the base type.
+ Angle : Degrees := 10;
+ Value : Integer := 20;
+ -- New_Angle : Degrees := Value; -- Incompatible types won't compile.
+ -- New_Value : Integer := Angle;
+
+ Blue_Hue : Primaries := Blue; -- A variable.
+ Red_Hue : constant Primaries := Red; -- A constant.
+ Yellow_Hue : constant Hues := Yellow;
+ Colour_1 : constant Hues := Red_Hue;
+ -- Colour_2 : constant Primaries := Yellow_Hue; -- uncomment to compile.
+
+ -- You can force conversions, but then you are warned by the name of the
+ -- package that you may be doing something unsafe.
+ function Degrees_To_Int is new Ada.Unchecked_Conversion
+ (Source => Degrees, -- Line continuations are indented by 2 spaces.
+ Target => Integer);
+
+ New_Value_2 : Integer := Degrees_To_Int (Angle); -- Note, space before (.
+
+ -- GNAT is the GNU Ada Translator (compiler).
+ -- Ada has a style guide and GNAT will warn you to adhere to it, and has
+ -- option to check your style so that you can correct it so that all Ada
+ -- source looks consistent. However, the style can be customized.
+
+ -- Yes, you can even define your own floating and fixed point types, this
+ -- is a very rare and unique ability. "digits" refers to the minimum
+ -- digit precision that the type should support. "delta" is for fixed
+ -- point types and refers to the smallest change that the type will support.
+ type Real_Angles is digits 3 range 0.0 .. 360.0;
+ type Fixed_Angles is delta 0.01 digits 5 range 0.0 .. 360.0;
+
+ RA : constant Real_Angles := 36.45;
+ FA : constant Fixed_Angles := 360.0; -- ".0" in order to make it a Float.
+
+ -- You can have normal Latin 1 based strings by default.
+ Str : constant String := "This is a constant string";
+ -- When initialising from a string literal, the compiler knows the bounds,
+ -- so we don't have to define them.
+
+ -- Strings are arrays. Note how parentheses are used to access elements of
+ -- an array? This is mathematical notation and was used because square
+ -- brackets were not available on all keyboards at the time Ada was
+ -- created. Also, because an array can be seen as a function from a
+ -- mathematical perspective, so it made converting between arrays and
+ -- functions easier.
+ Char : constant Character := Str (Str'First); -- "'First" is a type
+ -- attribute.
+
+ -- Ada 2022 includes the use of [] for array initialisation when using
+ -- containers, which were added in Ada 2012.
+
+ -- Arrays are usually always defined as a type.
+ -- They can be any dimension.
+ type My_Array_1 is array (1 .. 4, 3 .. 7, -20 .. 20) of Integer;
+
+ -- Yes, unlike other languages, you can index arrays with other discrete
+ -- types such as enumerations and modular types or arbitrary ranges.
+ type Axes is (X, Y, Z);
+
+ -- You can define the array's range using the 'Range attribute from
+ -- another type.
+ type Vector is array (Axes'Range) of Float;
+
+ V1 : constant Vector := (0.0, 0.0, 1.0);
+
+ -- A record is the same as a structure in C, C++.
+ type Entities is record
+ Name : String (1 .. 10); -- Always starts at a positive value,
+ -- inclusive range.
+ Position : Vector;
+ end record;
+
+ -- In Ada, array bounds are immutable. You therefore have to provide a
+ -- string literal with a value for every character.
+ E1 : constant Entities := ("Blob ", (0.0, 0.0, 0.0));
+
+ -- An alternative is to use an array aggregate and assign a default value
+ -- to every element that wasn't previously assigned in this aggregate.
+ -- "others" is used to indicate anything else that has not been
+ -- explicitly initialized.
+ E2 : constant Entities := (('B', 'l', 'o', 'b', others => ' '),
+ (0.0, 0.0, 0.0));
+
+ -- There are dynamic length strings (see references section) available in
+ -- the standard library.
+
+ -- We can make an object be initialised to its default values with the box
+ -- notation, "<>". "others" is used to indicate anything else that has not
+ -- been explicitly initialized.
+ Null_Entity : constant Entities := (others => <>);
+
+ -- Object-orientation is accomplished via an extension of record syntax,
+ -- tagged records, see link above in first paragraph.
+
+ -- We can rename objects (aliases) to make readability a bit better.
+ package IO renames Ada.Text_IO;
+begin
+ -- We can output enumerations as names.
+ IO.Put_Line ("Blue_Hue = " & -- & is the string concatenation operator.
+ Blue'Image); -- ' accesses attributes on objects.
+ -- The Image attribute converts a value to a string.
+ -- Ada 2022 has extended Image to custom types too.
+ -- Access this with -gnat2022 compiler flag.
+ IO.Put_Line ("Yellow_Hue = " &
+ -- We can use the type's attribute.
+ Primaries'Image (Yellow_Hue));
+
+ -- We can define local variables within a declare block, this can be made
+ -- more readable by giving it a label.
+ Enum_IO : declare
+ package Hue_IO is new IO.Enumeration_IO (Hues);
+
+ -- Using a package makes everything inside that package visible within
+ -- this block, it is good practice to only do this locally and not on
+ -- a whole package within the context clause.
+ use Hue_IO;
+ begin
+ -- We can print out the enumeration values too.
+ Put (Purple); -- Note we don't have to prefix the Put procedure with
+ -- Hue_IO.
+ IO.New_Line; -- We still need to prefix with IO here.
+ Put (Red_Hue);
+ IO.New_Line;
+ end Enum_IO;
+
+ -- Loops have a consistent form. "<form> loop ... end loop".
+ -- Where "form" can be "while" or "for" or missing as below, if
+ -- you place the "loop ... end loop;" construct on their own lines,
+ -- you can comment out or experiment with different loop constructs more
+ -- easily.
+ declare
+ Counter : Positive := Positive'First; -- This is 1.
+ begin
+ -- We can label loops so we can exit from them more easily if we need to.
+ Infinite :
+ loop
+ IO.Put_Line ("[Infinite loop] Counter = " & Counter'Image);
+
+ Counter := Counter + 1;
+
+ -- This next line implements a repeat ... until or do ... while loop construct.
+ -- Comment it out for an infinite loop.
+ exit Infinite when Counter = 5; -- Equality tests use a single "=".
+ end loop Infinite; -- Useful when implementing state machines.
+ end;
+
+ declare -- We don't have to have a label.
+ Counter : Positive := Positive'First; -- This is 1.
+ begin
+ while Counter < 10
+ loop
+ IO.Put_Line ("Counter = " & Counter'Image);
+
+ Counter := Counter + 1; -- There is no explicit inc/decrement.
+
+ -- Ada 2022 introduced @ for LHS, so the above would be written as
+ -- Counter := @ + 1; -- Try it, -gnat2022.
+ end loop;
+ end;
+
+ declare
+ package Hue_IO is new IO.Enumeration_IO (Hues);
+
+ -- We can have multiple packages on one line, but I tend to use one
+ -- package per line for readability.
+ use IO, Hue_IO;
+ begin
+ Put ("Hues : "); -- Note, no prefix.
+
+ -- Because we are using the 'Range attribute, the compiler knows it is
+ -- safe and can omit run-time checks here.
+ for Hue in Hues'Range
+ loop
+ Put (Hue);
+
+ -- Types and objects know about their bounds, their First .. Last
+ -- values. These can be specified as range types.
+ if Hue /= Hues'Last then -- The /= means "not equal to" like the
+ -- maths symbol ≠.
+ Put (", ");
+ end if;
+ end loop;
+
+ IO.New_Line;
+ end;
+
+ -- All objects know their bounds, including strings.
+ declare
+ C : Character := Str (50); -- Warning caused and exception raised at
+ -- runtime.
+ -- The exception raised above can only be handled by an outer scope,
+ -- see wikibook link below.
+ begin
+ null; -- We will never get to this point because of the above.
+ end;
+exception
+ when Constraint_Error =>
+ IO.Put_Line ("Caught the exception");
+end LearnAdaInY;
+```
+
+Now, that's a lot of information for a basic intro to Ada, and I've only touched the surface, there's much more to look at in the references section below. I haven't even touched on dynamic memory allocation which includes [pools](https://ada-lang.io/docs/arm/AA-13/AA-13.11), this is because for the most part, Ada programs don't need it, you can do a lot without it.
+
+As I stated above, Ada barely looks like Pascal and if you look at the original [Green specification](https://apps.dtic.mil/sti/trecms/pdf/ADB950587.pdf) (Warning: Huge 4575 page scanned PDF - starting on page 460), it looks nothing like it at all (page 505 of that PDF).
+
+The above source code will compile, but also will give warnings showing the power of the strong static type system.
+
+## Download this source
+
+If you already have the GNAT toolchain installed, you can cut and paste the above into a new file, e.g. ```learn-ada-in-y.ada``` and then run the following:
+
+```bash
+$ gnatchop learn-ada-in-y.ada # This breaks the program into its specification ".ads" and body ".adb".
+$ gnatmake empty.adb # gnatmake takes care of compilation of all units and linking.
+$ gnatmake hello.adb
+$ gnatmake learnadainy.adb
+```
+
+Or, download [Alire](https://alire.ada.dev), copy it to somewhere in your PATH and then do the following:
+
+**N.B.** Alire will automatically install the toolchain for you if you don't have one installed and will ask you to select which you want to use.
+
+```bash
+$ alr search learnadainy
+$ alr get learnadainy
+$ cd learnadainy
+$ alr run empty
+$ alr run hello
+$ alr run learnadainy
+```
+
+## Further Reading
+
+* [Ada Programming Language](https://ada-lang.io)
+* [Ada 2022 Reference Manual](https://ada-lang.io/docs/arm)
+* [Ada Style Guide](https://ada-lang.io/docs/style-guide/Ada_Style_Guide)
+* [Learn more Ada/Spark at AdaCore's site](https://learn.adacore.com)
+
+## References from the source above
+
+1. [wikibook](https://en.wikibooks.org/wiki/Ada_Programming/Exceptions#Exception_handlers)
+2. [C](https://ada-lang.io/docs/arm/AA-B/AA-B.3)
+3. [Fortran](https://ada-lang.io/docs/arm/AA-B/AA-B.5/)
+4. [COBOL](https://ada-lang.io/docs/arm/AA-B/AA-B.4/)
+5. [dynamic length strings](https://ada-lang.io/docs/arm/AA-A/AA-A.4#Subclause_A.4.5)
+
+### Multi-line comments
+
+Multi-line comments are not allowed as they are error prone.
+
+> Such comments would require a closing comment delimiter and this would again raise the dangers associated with the (unintentional) omission of the closing delimiter: entire sections of a program could be ignored by the compiler without the programmer realizing it
+>
+> [Ada 83 Rationale](http://archive.adaic.com/standards/83rat/html/ratl-02-01.html#2.1)
+
diff --git a/ansible.html.markdown b/ansible.html.markdown
index 30dfba13..847505c1 100644
--- a/ansible.html.markdown
+++ b/ansible.html.markdown
@@ -44,7 +44,7 @@ for, which provides an excellent UI.
#### Cons
* It is an agent-less tool - every agent consumes up to 16MB ram - in some
-environments, it may be noticable amount.
+environments, it may be noticeable amount.
* It is agent-less - you have to verify your environment consistency
'on-demand' - there is no built-in mechanism that would warn you about some
change automatically (this can be achieved with reasonable effort)
@@ -691,7 +691,7 @@ to specify the username.
Note: You may like to execute Ansible with `--ask-sudo-pass` or add the user to
sudoers file in order to allow non-supervised execution if you require 'admin'
-privilages.
+privileges.
[Read more](http://docs.ansible.com/ansible/latest/become.html)
@@ -753,3 +753,4 @@ the `register` command.
* [A system administrator's guide to getting started with Ansible - FAST!](https://www.redhat.com/en/blog/system-administrators-guide-getting-started-ansible-fast)
* [Ansible Tower](https://www.ansible.com/products/tower) - Ansible Tower provides a web UI, dashboard and rest interface to ansible.
* [Ansible AWX](https://github.com/ansible/awx) - The Open Source version of Ansible Tower.
+* [Ansible Tutorial for Beginners: Ultimate Playbook & Examples](https://spacelift.io/blog/ansible-tutorial)
diff --git a/ar-ar/sql-ar.html.markdown b/ar-ar/sql-ar.html.markdown
new file mode 100644
index 00000000..dea20c1f
--- /dev/null
+++ b/ar-ar/sql-ar.html.markdown
@@ -0,0 +1,135 @@
+---
+language: SQL
+filename: learnsql-ar.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["Ahmed Omar Eissa", "https://twitter.com/AhmedOmarEissa"]
+lang: ar-ar
+---
+<div dir="rtl">
+
+لغة الاستعلام الهيكلية
+(SQL)
+هي لغة قياسية
+[ISO/IEC 9075](https://www.iso.org/standard/63555.html)
+لإنشاء قواعد البيانات المخزنة ÙÙŠ مجموعة من الجداول التعامل معها. عادةً ما تضي٠التطبيقات
+امتدادات خاصة بها إلى اللغة ؛ تعد
+[مقارنة نسخ SQL المختلÙØ©](http://troels.arvin.dk/db/rdbms/)
+مرجعًا جيدًا لاختلاÙات النسخ.
+
+توÙر النسخ عادةً موجه سطر أوامر
+command line prompt
+حيث يمكنك إدخال الأوامر المعروضة هنا بشكل تÙاعلي، كما أنها توÙر طريقة لتنÙيذ سلسلة من هذه الأوامر المخزنة ÙÙŠ مل٠نصي. إظهار رسالة الانتهاء من العمل مع الموجه التÙاعلي مثال جيد على امكانية اضاÙØ© أوامر غير قياسية، معظم النسخ تدعم أحد أوامر
+QUIT , EXIT
+.أو كليهما
+
+ÙÙŠ الامثلة بالأسÙÙ„ تعتمدالعديد من الأوامرأن قاعدة بيانات الموظÙين
+[MySQL employee sample database](https://dev.mysql.com/doc/employee/en/)
+الموجودة على
+[github](https://github.com/datacharmer/test_db)
+قد تم تحميلها مسبقا. الملÙات على
+github
+هي مجموعة من الاوامر تشبه الموجودة بالاسÙÙ„ Ùˆ تقوم الأوامر بإنشاء الجدوال وإدخال بيانات مجموعة من الموظÙين المتخيلين ÙÙŠ شركة. تعتمد الأوامر المستخدمة ÙÙŠ هذا البرنامج على نسخة
+SQL
+التي تستخدمها،
+</div>
+
+
+
+
+```sql
+-- تبدأ التعليقات بشرطتين. قم بإنهاء كل أمر بÙاصلة منقوطة
+
+-- حساسة لحالة الاحر٠SQL لا تعتبر
+-- Ùقط ليسهل تمييزها عن أسماه الأعمدة والجداول وقواعد البيانات UPPER-CASE الاوامر الموجودة هنا تستخدم الحالة العليا للاحرÙ
+
+-- إنشاء ومسح قاعدة بيانات، أسماء قواعد البيانات والجداول حساسة لحالة الأحرÙ
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- عرض قواعد البيانات الموجودة
+SHOW DATABASES;
+
+--استخدام قاعدة بيانات محددة
+USE employees;
+
+-- ÙÙŠ قاعدة البيانات المستخدمة departments ارجاع كل السطور والاعمدة ÙÙŠ جدول
+-- ستظهر النتائج على الشاشة بشكل تلقائي لتتصÙحها.
+SELECT * FROM departments;
+
+-- Ùقط dept_name Ùˆ dept_no لكن سنسترجع عمودي departments استرجاع كل أسطر من جدول
+-- لا مانع من تقسيم الاوامر بين السطور
+
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- لكن هذه المرة سنسترجع Ù¥ أسطر Ùقط departments استرجاع كل الاعمدة من جدول
+SELECT * FROM departments LIMIT 5;
+
+--en يحتوي علي dept_name ÙÙŠ حالة أن عمود departments من جدول dept_name استرجاع عمود
+
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- S استرجاع كل أعمدة جدول الاقسام ÙÙŠ حالة أن اسم القسم يبدأ بحرÙ
+-- متبوعا بأربعة حروÙ
+
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- استرجاع قيم العناوين من جدول العناوين بدون تكرار
+SELECT DISTINCT title FROM titles;
+
+-- Ù†Ùس المثال السابق مع ترتيب العناوين أبجديا
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- اظهار عدد السطور ÙÙŠ جدول الأقسام
+SELECT COUNT(*) FROM departments;
+
+
+-- en اظهار عدد السطور ÙÙŠ جدول الأقسام التي تحتوي ÙÙŠ عمود اسم القسم علي
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+
+-- ربط المعلومات بين الجداول، جدول العناوين يظهر رقم كل موظ٠ومسماه الوظيÙÙŠ
+-- ومتي حصل على هذا المسمى وإلي متى ولكن بدلا من اظهار رقم الموظ٠سنستخدم هذا الرقم
+-- للحصول على اسم الموظ٠الاول والأخير من جدول الموظÙين مع إظهار ١٠ سطور Ùقط
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- إظهار كل الجدوال ÙÙŠ كل قواعد البيانات
+-- النسخ المختلÙØ© تقدم اختصارات لمثل هذا الأمر لقاعدة البيانات المستخدمة
+
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- يحتوى على عمودان ÙÙŠ قاعدة البيانات المستخدمة tablename1 أنشاء جدول يسمى
+-- يوجد العديد من الطرق لتعري٠الاعمدة وأنواع البيانات ÙÙŠ العمود
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- هذا باÙتراض ان الجدول يمكن اضاÙØ© الاسطر له .tablename1 اضاÙØ© سطر ÙÙŠ جدول
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+--John إلى fname سنغير قيمة عمود tablename1 ÙÙŠ
+-- Mutt هي lname ÙÙŠ حالة أن قيمة العمود
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+
+-- 'M' تبدأ ب lname ÙÙŠ حالة أن قيمة عمود tablename1 مسح السطور من جدول
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- مع ترك الجدول Ùارغ tablename1 مسح جميع السطور من جدول
+DELETE FROM tablename1;
+
+-- تماما tablename1 إزالة جدول
+DROP TABLE tablename1;
+```
+<div dir="rtl">
+
+## اقرأ أكثر
+
+* [Codecademy - SQL](https://www.codecademy.com/learn/learn-sql)مقدمة جيدة للتعلم عن طريق التطبيق.
+* [Database System Concepts](https://www.db-book.com) الÙصل رقم Ù£ من الكتاب مقدمة ÙÙŠ (SQL) تحتوى علي شرح Ù…Ùصل لمÙاهيم (SQL)
+
+</div>
diff --git a/arturo.html.markdown b/arturo.html.markdown
new file mode 100644
index 00000000..c3c4dc43
--- /dev/null
+++ b/arturo.html.markdown
@@ -0,0 +1,432 @@
+---
+language: arturo
+filename: learnarturo.art
+contributors:
+ - ["Dr.Kameleon", "https://github.com/drkameleon"]
+---
+
+```red
+; this is a comment
+; this is another comment
+
+;---------------------------------
+; VARIABLES & VALUES
+;---------------------------------
+
+; numbers
+a1: 2
+a2: 3.14
+a3: to :complex [1 2.0] ; 1.0+2.0i
+
+; strings
+c1: "this is a string"
+c2: {
+ this is a multiline string
+ that is indentation-agnostic
+}
+c3: {:
+ this is
+ a verbatim
+ multiline string
+ which will remain exactly
+ as the original
+:}
+
+; characters
+ch: `c`
+
+; blocks/arrays
+d: [1 2 3]
+
+; dictionaries
+e: #[
+ name: "John"
+ surname: "Doe"
+ age: 34
+ likes: [pizza spaghetti]
+]
+
+; yes, functions are values too
+f: function [x][
+ 2 * x
+]
+
+; dates
+g: now ; 2021-05-03T17:10:48+02:00
+
+; booleans
+h1: true
+h2: false
+
+;---------------------------------
+; BASIC OPERATORS
+;---------------------------------
+
+; simple arithmetic
+1 + 1 ; => 2
+8 - 1 ; => 7
+4.2 - 1.1 ; => 3.1
+10 * 2 ; => 20
+35 / 4 ; => 8
+35 // 4 ; => 8.75
+2 ^ 5 ; => 32
+5 % 3 ; => 2
+
+; bitwise operators
+and 3 5 ; => 1
+or 3 5 ; => 7
+xor 3 5 ; => 6
+
+; pre-defined constants
+pi ; => 3.141592653589793
+epsilon ; => 2.718281828459045
+null ; => null
+true ; => true
+false ; => false
+
+;---------------------------------
+; COMPARISON OPERATORS
+;---------------------------------
+
+; equality
+1 = 1 ; => true
+2 = 1 ; => false
+
+; inequality
+1 <> 1 ; => false
+2 <> 1 ; => true
+
+; more comparisons
+1 < 10 ; => true
+1 =< 10 ; => true
+10 =< 10 ; => true
+1 > 10 ; => false
+1 >= 10 ; => false
+11 >= 10 ; => true
+
+;---------------------------------
+; CONDITIONALS
+;---------------------------------
+
+; logical operators
+and? true true ; => true
+and? true false ; => false
+or? true false ; => true
+or? false false ; => false
+
+and? [1=2][2<3] ; => false
+ ; (the second block will not be evaluated)
+
+; simple if statements
+if 2 > 1 [ print "yes!"] ; yes!
+if 3 <> 2 -> print "true!" ; true!
+
+; if/else statements
+if? 2 > 3 -> print "2 is greater than 3"
+else -> print "2 is not greater than 3" ; 2 is not greater than 3
+
+; switch statements
+switch 2 > 3 -> print "2 is greater than 3"
+ -> print "2 is not greater than 3" ; 2 is not greater than 3
+
+a: (2 > 3)["yes"]["no"] ; a: "no"
+a: (2 > 3)? -> "yes" -> "no" ; a: "no" (exactly the same as above)
+
+; case/when statements
+case [1]
+ when? [>2] -> print "1 is greater than 2. what?!"
+ when? [<0] -> print "1 is less than 0. nope..."
+ else -> print "here we are!" ; here we are!
+
+;---------------------------------
+; LOOPS
+;---------------------------------
+
+; with `loop`
+arr: [1 4 5 3]
+loop arr 'x [
+ print ["x =" x]
+]
+; x = 1
+; x = 4
+; x = 5
+; x = 3
+
+; with loop and custom index
+loop.with:'i arr 'x [
+ print ["item at position" i "=>" x]
+]
+; item at position 0 => 1
+; item at position 1 => 4
+; item at position 2 => 5
+; item at position 3 => 3
+
+; using ranges
+loop 1..3 'x -> ; since it's a single statement
+ print x ; there's no need for [block] notation
+ ; we can wrap it up using the `->` syntactic sugar
+
+loop `a`..`c` 'ch ->
+ print ch
+; a
+; b
+; c
+
+; picking multiple items
+loop 1..10 [x y] ->
+ print ["x =" x ", y =" y]
+; x = 1 , y = 2
+; x = 3 , y = 4
+; x = 5 , y = 6
+; x = 7 , y = 8
+; x = 9 , y = 10
+
+; looping through a dictionary
+dict: #[name: "John", surname: "Doe", age: 34]
+loop dict [key value][
+ print [key "->" value]
+]
+; name -> John
+; surname -> Doe
+; age -> 34
+
+; while loops
+i: new 0
+while [i<3][
+ print ["i =" i]
+ inc 'i
+]
+; i = 0
+; i = 1
+; i = 2
+
+;---------------------------------
+; STRINGS
+;---------------------------------
+
+; case
+a: "tHis Is a stRinG"
+print upper a ; THIS IS A STRING
+print lower a ; this is a string
+print capitalize a ; tHis Is a stRinG
+
+; concatenation
+a: "Hello " ++ "World!" ; a: "Hello World!"
+
+; strings as an array
+split "hello" ; => [h e l l o]
+split.words "hello world" ; => [hello world]
+
+print first "hello" ; h
+print last "hello" ; o
+
+; conversion
+to :string 123 ; => "123"
+to :integer "123" ; => 123
+
+; joining strings together
+join ["hello" "world"] ; => "helloworld"
+join.with:"-" ["hello" "world"] ; => "hello-world"
+
+; string interpolation
+x: 2
+print ~"x = |x|" ; x = 2
+
+; interpolation with `print`
+print ["x =" x] ; x = 2
+ ; (`print` works by calculating the given block
+ ; and joining the different values as strings
+ ; with a single space between them)
+
+; templates
+print render.template {
+ <||= switch x=2 [ ||>
+ Yes, x = 2
+ <||][||>
+ No, x is not 2
+ <||]||>
+} ; Yes, x = 2
+
+; matching
+prefix? "hello" "he" ; => true
+suffix? "hello" "he" ; => false
+
+contains? "hello" "ll" ; => true
+contains? "hello" "he" ; => true
+contains? "hello" "x" ; => false
+
+in? "ll" "hello" ; => true
+in? "x" "hello" ; => false
+
+;---------------------------------
+; BLOCKS
+;---------------------------------
+
+; calculate a block
+arr: [1 1+1 1+1+1]
+@arr ; => [1 2 3]
+
+; execute a block
+sth: [print "Hello world"] ; this is perfectly valid,
+ ; could contain *anything*
+ ; and will not be executed...
+
+do sth ; Hello world
+ ; (...until we tell it to)
+
+; array indexing
+arr: ["zero" "one" "two" "three"]
+print first arr ; zero
+print arr\0 ; zero
+print last arr ; three
+print arr\3 ; three
+
+x: 2
+print get arr x ; two
+print arr \ 2 ; two
+ ; (using the `\` infix alias for get -
+ ; notice space between the operands!
+ ; otherwise, it'll be parsed as a path)
+
+; setting an array element
+arr\0: "nada"
+set arr 2 "dos"
+print arr ; nada one dos three
+
+; adding elements to an array
+arr: new []
+'arr ++ "one"
+'arr ++ "two"
+print arr ; one two
+
+; remove elements from an array
+arr: new ["one" "two" "three" "four"]
+'arr -- "two" ; arr: ["one" "three" "four"]
+remove 'arr .index 0 ; arr: ["three" "four"]
+
+; getting the size of an array
+arr: ["one" 2 "three" 4]
+print size arr ; 4
+
+; getting a slice of an array
+print slice ["one" "two" "three" "four"] 0 1 ; one two
+
+; check if array contains a specific element
+print contains? arr "one" ; true
+print contains? arr "five" ; false
+
+; sorting array
+arr: [1 5 3 2 4]
+sort arr ; => [1 2 3 4 5]
+sort.descending arr ; => [5 4 3 2 1]
+
+; mapping values
+map 1..10 [x][2*x] ; => [2 4 6 8 10 12 14 16 18 20]
+map 1..10 'x -> 2*x ; same as above
+map 1..10 => [2*&] ; same as above
+map 1..10 => [2*] ; same as above
+
+; selecting/filtering array values
+select 1..10 [x][odd? x] ; => [1 3 5 7 9]
+select 1..10 => odd? ; same as above
+
+filter 1..10 => odd? ; => [2 4 6 8 10]
+ ; (now, we leave out all odd numbers -
+ ; while select keeps them)
+
+; misc operations
+arr: ["one" 2 "three" 4]
+reverse arr ; => [4 "three" 2 "one"]
+shuffle arr ; => [2 4 "three" "one"]
+unique [1 2 3 2 3 1] ; => [1 2 3]
+permutate [1 2 3] ; => [[1 2 3] [1 3 2] [3 1 2] [2 1 3] [2 3 1] [3 2 1]]
+take 1..10 3 ; => [1 2 3]
+repeat [1 2] 3 ; => [1 2 1 2 1 2]
+
+;---------------------------------
+; FUNCTIONS
+;---------------------------------
+
+; declaring a function
+f: function [x][ 2*x ]
+f: function [x]-> 2*x ; same as above
+f: $[x]->2*x ; same as above (only using the `$` alias
+ ; for the `function`... function)
+
+; calling a function
+f 10 ; => 20
+
+; returning a value
+g: function [x][
+ if x < 2 -> return 0
+
+ res: 0
+ loop 0..x 'z [
+ res: res + z
+ ]
+ return res
+]
+
+;---------------------------------
+; CUSTOM TYPES
+;---------------------------------
+
+; defining a custom type
+define :person [ ; define a new custom type "Person"
+ name ; with fields: name, surname, age
+ surname
+ age
+][
+ ; with custom post-construction initializer
+ init: [
+ this\name: capitalize this\name
+ ]
+
+ ; custom print function
+ print: [
+ render "NAME: |this\name|, SURNAME: |this\surname|, AGE: |this\age|"
+ ]
+
+ ; custom comparison operator
+ compare: 'age
+]
+
+; create a method for our custom type
+sayHello: function [this][
+ ensure -> is? :person this
+
+ print ["Hello" this\name]
+]
+
+; create new objects of our custom type
+a: to :person ["John" "Doe" 34] ; let's create 2 "Person"s
+b: to :person ["jane" "Doe" 33] ; and another one
+
+; call pseudo-inner method
+sayHello a ; Hello John
+sayHello b ; Hello Jane
+
+; access object fields
+print ["The first person's name is:" a\name] ; The first person's name is: John
+print ["The second person's name is:" b\name] ; The second person's name is: Jane
+
+; changing object fields
+a\name: "Bob"
+sayHello a ; Hello Bob
+
+; verifying object type
+print type a ; :person
+print is? :person a ; true
+
+; printing objects
+print a ; NAME: John, SURNAME: Doe, AGE: 34
+
+; sorting user objects (using custom comparator)
+sort @[a b] ; Jane..., John...
+sort.descending @[a b] ; John..., Jane...
+```
+
+## Additional resources
+
+- [Official documentation](https://arturo-lang.io/documentation/) - Arturo official documentation & reference.
+- [Online playground](https://arturo-lang.io/playground/) - Online REPL for the Arturo programming language.
diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown
index 51d0d7c9..557ed294 100644
--- a/asciidoc.html.markdown
+++ b/asciidoc.html.markdown
@@ -3,7 +3,7 @@ language: asciidoc
contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
-filename: asciidoc.md
+filename: asciidoc.adoc
---
AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization.
diff --git a/assemblyscript.html.markdown b/assemblyscript.html.markdown
new file mode 100644
index 00000000..4433b41e
--- /dev/null
+++ b/assemblyscript.html.markdown
@@ -0,0 +1,202 @@
+---
+language: Assemblyscript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+ - ["Steve Huguenin-Elie", "https://github.com/StEvUgnIn"]
+ - ["Sebastian Speitel", "https://github.com/SebastianSpeitel"]
+ - ["Max Graey", "https://github.com/MaxGraey"]
+filename: learnassemblyscript.ts
+---
+
+__AssemblyScript__ compiles a variant of __TypeScript__ (basically JavaScript with types) to __WebAssembly__ using __Binaryen__. It generates lean and mean WebAssembly modules while being just an `npm install` away.
+
+This article will focus only on AssemblyScript extra syntax, as opposed to [TypeScript](/docs/typescript) and [JavaScript](/docs/javascript).
+
+To test AssemblyScript's compiler, head to the
+[Playground](https://bit.ly/asplayground) where you will be able
+to type code, have auto completion and directly see the emitted WebAssembly.
+
+```ts
+// There are many basic types in AssemblyScript,
+let isDone: boolean = false;
+let name: string = "Anders";
+
+// but integer type come as signed (sized from 8 to 64 bits)
+let lines8: i8 = 42;
+let lines16: i16 = 42;
+let lines32: i32 = 42;
+let lines64: i64 = 42;
+
+// and unsigned (sized from 8 to 64 bits),
+let ulines8: u8 = 42;
+let ulines16: u16 = 42;
+let ulines32: u32 = 42;
+let ulines64: u64 = 42;
+
+// and float has two sizes possible (32/64).
+let rate32: f32 = 1.0
+let rate64: f64 = 1.0
+
+// But you can omit the type annotation if the variables are derived
+// from explicit literals
+let _isDone = false;
+let _lines = 42;
+let _name = "Anders";
+
+// Use const keyword for constants
+const numLivesForCat = 9;
+numLivesForCat = 1; // Error
+
+// For collections, there are typed arrays and generic arrays
+let list1: i8[] = [1, 2, 3];
+// Alternatively, using the generic array type
+let list2: Array<i8> = [1, 2, 3];
+
+// For enumerations:
+enum Color { Red, Green, Blue };
+let c: Color = Color.Green;
+
+// Functions imported from JavaScript need to be declared as external
+// @ts-ignore decorator
+@external("alert")
+declare function alert(message: string): void;
+
+// and you can also import JS functions in a namespace
+declare namespace window {
+ // @ts-ignore decorator
+ @external("window", "alert")
+ function alert(message: string): void;
+}
+
+// Lastly, "void" is used in the special case of a function returning nothing
+export function bigHorribleAlert(): void {
+ alert("I'm a little annoying box!"); // calling JS function here
+}
+
+// Functions are first class citizens, support the lambda "fat arrow" syntax
+
+// The following are equivalent, the compiler does not offer any type
+// inference for functions yet, and same WebAssembly will be emitted.
+export function f1 (i: i32): i32 { return i * i; }
+// "Fat arrow" syntax
+let f2 = (i: i32): i32 => { return i * i; }
+// "Fat arrow" syntax, braceless means no return keyword needed
+let f3 = (i: i32): i32 => i * i;
+
+// Classes - members are public by default
+export class Point {
+ // Properties
+ x: f64;
+
+ // Constructor - the public/private keywords in this context will generate
+ // the boiler plate code for the property and the initialization in the
+ // constructor.
+ // In this example, "y" will be defined just like "x" is, but with less code
+ // Default values are also supported
+
+ constructor(x: f64, public y: f64 = 0) {
+ this.x = x;
+ }
+
+ // Functions
+ dist(): f64 { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Static members
+ static origin: Point = new Point(0, 0);
+}
+
+// Classes can be explicitly marked as extending a parent class.
+// Any missing properties will then cause an error at compile-time.
+export class PointPerson extends Point {
+ constructor(x: f64, y: f64, public name: string) {
+ super(x, y);
+ }
+ move(): void {}
+}
+
+let p1 = new Point(10, 20);
+let p2 = new Point(25); //y will be 0
+
+// Inheritance
+export class Point3D extends Point {
+ constructor(x: f64, y: f64, public z: f64 = 0) {
+ super(x, y); // Explicit call to the super class constructor is mandatory
+ }
+
+ // Overwrite
+ dist(): f64 {
+ let d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// Namespaces, "." can be used as separator for sub namespaces
+export namespace Geometry {
+ class Square {
+ constructor(public sideLength: f64 = 0) {
+ }
+ area(): f64 {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+let s1 = new Geometry.Square(5);
+
+// Generics
+// AssemblyScript compiles generics to one concrete method or function per set
+// of unique contextual type arguments, also known as [monomorphisation].
+// Implications are that a module only includes and exports concrete functions
+// for sets of type arguments actually used and that concrete functions can be
+// shortcutted with [static type checks] at compile time, which turned out to
+// be quite useful.
+// Classes
+export class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+export class Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// And functions
+export function pairToTuple <T>(p: Pair<T>): Tuple<T, T> {
+ return new Tuple(p.item1, p.item2);
+};
+
+let tuple = pairToTuple<string>({ item1: "hello", item2: "world" });
+
+// Including references to a TypeScript-only definition file:
+/// <reference path="jquery.d.ts" />
+
+// Template Strings (strings that use backticks)
+// String Interpolation with Template Strings
+let name = 'Tyrone';
+let greeting = `Hi ${name}, how are you?`
+// Multiline Strings with Template Strings
+let multiline = `This is an example
+of a multiline string`;
+
+let numbers: Array<i8> = [0, 1, 2, 3, 4];
+let moreNumbers: Array<i8> = numbers;
+moreNumbers[5] = 5; // Error, elements are read-only
+moreNumbers.push(5); // Error, no push method (because it mutates array)
+moreNumbers.length = 3; // Error, length is read-only
+numbers = moreNumbers; // Error, mutating methods are missing
+
+// Type inference in Arrays
+let ints = [0, 1, 2, 3, 4] // will infer as Array<i32>
+let floats: f32[] = [0, 1, 2, 3, 4] // will infer as Array<f32>
+let doubles = [0.0, 1.0, 2, 3, 4] // will infer as Array<f64>
+let bytes1 = [0 as u8, 1, 2, 3, 4] // will infer as Array<u8>
+let bytes2 = [0, 1, 2, 3, 4] as u8[] // will infer as Array<u8>
+let bytes3: u8[] = [0, 1, 2, 3, 4] // will infer as Array<u8>
+
+```
+
+## Further Reading
+ * [AssemblyScript Official website] (https://www.assemblyscript.org/)
+ * [AssemblyScript source documentation] https://github.com/AssemblyScript/website/tree/main/src)
+ * [Source Code on GitHub] (https://github.com/AssemblyScript/assemblyscript)
diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown
index a6acf54e..0739c02d 100644
--- a/asymptotic-notation.html.markdown
+++ b/asymptotic-notation.html.markdown
@@ -135,7 +135,7 @@ Let's look at the definition of Big-O.
3 * n^2 <= c * n
```
-Is there some pair of constants c, n<sub>0</sub> that satisfies this for all n > <sub>0</sub>?
+Is there some pair of constants c, n<sub>0</sub> that satisfies this for all n > n<sub>0</sub>?
No, there isn't. `f(n)` is NOT O(g(n)).
### Big-Omega
diff --git a/awk.html.markdown b/awk.html.markdown
index 3ff3f937..e1d4a0a3 100644
--- a/awk.html.markdown
+++ b/awk.html.markdown
@@ -48,7 +48,7 @@ BEGIN {
# the preliminary set-up code, before you process any text files. If you
# have no text files, then think of BEGIN as the main entry point.
- # Variables are global. Just set them or use them, no need to declare..
+ # Variables are global. Just set them or use them, no need to declare.
count = 0;
# Operators just like in C and friends
@@ -118,12 +118,12 @@ BEGIN {
# Arrays
arr[0] = "foo";
arr[1] = "bar";
-
+
# You can also initialize an array with the built-in function split()
-
+
n = split("foo:bar:baz", arr, ":");
-
- # You also have associative arrays (actually, they're all associative arrays)
+
+ # You also have associative arrays (indeed, they're all associative arrays)
assoc["foo"] = "bar";
assoc["bar"] = "baz";
@@ -178,26 +178,26 @@ function arithmetic_functions(a, b, c, d) {
# Now, to demonstrate the arithmetic functions
# Most AWK implementations have some standard trig functions
- localvar = sin(a);
- localvar = cos(a);
- localvar = atan2(b, a); # arc tangent of b / a
+ d = sin(a);
+ d = cos(a);
+ d = atan2(b, a); # arc tangent of b / a
# And logarithmic stuff
- localvar = exp(a);
- localvar = log(a);
+ d = exp(a);
+ d = log(a);
# Square root
- localvar = sqrt(a);
+ d = sqrt(a);
# Truncate floating point to integer
- localvar = int(5.34); # localvar => 5
+ d = int(5.34); # d => 5
# Random numbers
srand(); # Supply a seed as an argument. By default, it uses the time of day
- localvar = rand(); # Random number between 0 and 1.
+ d = rand(); # Random number between 0 and 1.
# Here's how to return a value
- return localvar;
+ return d;
}
function string_functions( localvar, arr) {
@@ -209,14 +209,15 @@ function string_functions( localvar, arr) {
# Both return number of matches replaced
localvar = "fooooobar";
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar); # localvar => "M..t m. at th. bar"
# Search for a string that matches a regular expression
# index() does the same thing, but doesn't allow a regular expression
match(localvar, "t"); # => 4, since the 't' is the fourth character
# Split on a delimiter
- n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
+ n = split("foo-bar-baz", arr, "-");
+ # result: a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
# Other useful stuff
sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3"
@@ -238,9 +239,9 @@ function io_functions( localvar) {
# AWK doesn't have file handles, per se. It will automatically open a file
# handle for you when you use something that needs one. The string you used
# for this can be treated as a file handle, for purposes of I/O. This makes
- # it feel sort of like shell scripting, but to get the same output, the string
- # must match exactly, so use a variable:
-
+ # it feel sort of like shell scripting, but to get the same output, the
+ # string must match exactly, so use a variable:
+
outfile = "/tmp/foobar.txt";
print "foobar" > outfile;
@@ -261,7 +262,7 @@ function io_functions( localvar) {
# Reads a line from a file and stores in localvar
infile = "/tmp/foobar.txt";
- getline localvar < infile;
+ getline localvar < infile;
close(infile);
}
@@ -273,10 +274,10 @@ function io_functions( localvar) {
# When you pass arguments to AWK, they are treated as file names to process.
# It will process them all, in order. Think of it like an implicit for loop,
# iterating over the lines in these files. these patterns and actions are like
-# switch statements inside the loop.
+# switch statements inside the loop.
/^fo+bar$/ {
-
+
# This action will execute for every line that matches the regular
# expression, /^fo+bar$/, and will be skipped for any line that fails to
# match it. Let's just print the line:
@@ -376,11 +377,15 @@ END {
}
```
+
Further Reading:
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
* [Awk man page](https://linux.die.net/man/1/awk)
-* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems.
+* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
+ GNU Awk is found on most Linux systems.
* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html)
-* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical summary and list of "gotchas" (places where different implementations may behave in different or unexpected ways).
+* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical
+ summary and list of "gotchas" (places where different implementations may
+ behave in different or unexpected ways).
* [basic libraries for awk](https://github.com/dubiousjim/awkenough)
diff --git a/ballerina.html.markdown b/ballerina.html.markdown
new file mode 100644
index 00000000..7f055343
--- /dev/null
+++ b/ballerina.html.markdown
@@ -0,0 +1,432 @@
+---
+language: Ballerina
+contributors:
+ - ["Anjana Fernando", "https://github.com/lafernando"]
+filename: learn_ballerina.bal
+---
+
+[Ballerina](https://ballerina.io/) is a statically-typed programming language for making development for the cloud an enjoyable experience.
+
+```java
+// Single-line comment
+
+// Import modules into the current source file
+import ballerina/io;
+import ballerina/time;
+import ballerina/http;
+import ballerinax/java.jdbc;
+import ballerina/lang.'int as ints;
+import ballerinax/awslambda;
+// Module alias "af" used in code in place of the full module name
+import ballerinax/azure.functions as af;
+
+http:Client clientEP = new ("https://freegeoip.app/");
+jdbc:Client accountsDB = new ({url: "jdbc:mysql://localhost:3306/AccountsDB",
+ username: "test", password: "test"});
+
+// A service is a first-class concept in Ballerina, and is one of the
+// entrypoints to a Ballerina program.
+// The Ballerina platform also provides support for easy deployment to
+// environments such as Kubernetes (https://ballerina.io/learn/deployment/kubernetes/).
+service geoservice on new http:Listener(8080) {
+
+ @http:ResourceConfig {
+ path: "/geoip/{ip}"
+ }
+ resource function geoip(http:Caller caller, http:Request request,
+ string ip) returns @tainted error? {
+ http:Response resp = check clientEP->get("/json/" + <@untainted>ip);
+ check caller->respond(<@untainted> check resp.getTextPayload());
+ }
+
+}
+
+// Serverless Function-as-a-Service support with AWS Lambda.
+// The Ballerina compiler automatically generates the final deployment
+// artifact to be deployed.
+@awslambda:Function
+public function echo(awslambda:Context ctx, json input) returns json {
+ return input;
+}
+
+@awslambda:Function
+public function notifyS3(awslambda:Context ctx,
+ awslambda:S3Event event) returns json {
+ return event.Records[0].s3.'object.key;
+}
+
+// Serverless Function-as-a-Service support with Azure Functions.
+// Similar to AWS Lambda, the compiler generates the deployment artifacts.
+@af:Function
+public function fromQueueToQueue(af:Context ctx,
+ @af:QueueTrigger { queueName: "queue1" } string inMsg,
+ @af:QueueOutput { queueName: "queue2" } af:StringOutputBinding outMsg) {
+ outMsg.value = inMsg;
+}
+
+// A custom record type
+public type Person record {
+ string id; // required field
+ string name;
+ int age?; // optional field
+ string country = "N/A"; // default value
+};
+
+@af:Function
+public function fromHttpTriggerCosmosDBInput(
+ @af:HTTPTrigger { route: "c1/{country}" } af:HTTPRequest httpReq,
+ @af:CosmosDBInput { connectionStringSetting: "CosmosDBConnection",
+ databaseName: "db1", collectionName: "c1",
+ sqlQuery: "select * from c1 where c1.country = {country}" }
+ Person[] dbReq)
+ returns @af:HTTPOutput string|error {
+ return dbReq.toString();
+}
+
+public function main() returns @tainted error? {
+ int a = 10; // 64-bit signed integer
+ float b = 1.56; // 64-bit IEEE 754-2008 binary floating point number
+ string c = "hello"; // a unicode string
+ boolean d = true; // true, false
+ decimal e = 15.335; // decimal floating point number
+
+ var f = 20; // type inference with 'var' - 'f' is an int
+
+ int[] intArray = [1, 2, 3, 4, 5, 6];
+ int x = intArray.shift(); // similar to a dequeue operation
+ x = intArray.pop(); // removes the last element
+ intArray.push(10); // add to the end
+
+ // Tuples - similar to a fixed length array with a distinct type for each slot
+ [string, int] p1 = ["Jack", 1990];
+ [string, int] p2 = ["Tom", 1986];
+ io:println("Name: ", p1[0], " Birth Year: ", p1[1]);
+
+ string name1;
+ int birthYear1;
+ [name1, birthYear1] = p1; // tuple destructuring
+
+ var [name2, birthYear2] = p2; // declare and assign values in the same statement
+
+ // If statements
+ int ix = 10;
+ if ix < 10 {
+ io:println("value is less than 10");
+ } else if ix == 10 {
+ io:println("value equals to 10");
+ } else {
+ io:println("value is greater than 10");
+ }
+
+ // Loops
+ int count = 10;
+ int i = 0;
+ while i < 10 {
+ io:println(i);
+ }
+ // Loop from 0 to count (inclusive)
+ foreach var j in 0...count {
+ io:println(j);
+ }
+ // Loop from 0 to count (non-inclusive)
+ foreach var j in 0..<count {
+ io:println(j);
+ }
+ // Loop a list
+ foreach var j in intArray {
+ io:println(j);
+ }
+
+ json j1 = { "name" : name1, "birthYear" : birthYear1, "zipcode" : 90210 };
+ io:println(j1.name, " - ", j1.zipcode);
+ // New fields are added to a JSON value through "mergeJson"
+ var j2 = j1.mergeJson({ "id" : "90400593053"});
+
+ // XML namespace declaration
+ xmlns "http://example.com/ns1" as ns1;
+ xmlns "http://example.com/default";
+
+ // XML variable from a literal value
+ xml x1 = xml `<ns1:entry><name>{{name1}}</name><birthYear>{{birthYear1}}</birthYear></ns1:entry>`;
+ io:println(x1);
+ // Access specific elements in the XML value
+ io:println(x1/<name>);
+ // List all child items in the XML value
+ io:println(x1/*);
+
+ // Function invocations
+ x = add(1, 2);
+ io:println(multiply(2, 4));
+ // Invocation providing value for the defaultable parameter
+ io:println(multiply(3, 4, true));
+ // Invocation with values to a rest parameter (multi-valued)
+ io:println(addAll(1, 2, 3));
+ io:println(addAll(1, 2, 3, 4, 5));
+
+ // Function pointers
+ (function (int, int) returns int) op1 = getOperation("add");
+ (function (int, int) returns int) op2 = getOperation("mod");
+ io:println(op1(5, 10));
+ io:println(op2(13, 10));
+
+ // Closures
+ (function (int x) returns int) add5 = getAdder(5);
+ (function (int x) returns int) add10 = getAdder(10);
+ io:println(add5(10));
+ io:println(add10(10));
+
+ int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8];
+ // Functional iteration
+ int[] evenNumbers = numbers.filter(function (int x) returns boolean { return x % 2 == 0; });
+
+ // Union types - "input" is of type either string or byte[]
+ string|byte[] uval = "XXX";
+
+ // A type test expression ("uval is string") can be used to check the
+ // runtime type of a variable.
+ if uval is string {
+ // In the current scope, "uval" is a string value
+ string data = "data:" + uval;
+ } else {
+ // Since the expression in the "if" statement ruled out that it's not a string,
+ // the only type left is "byte[]"; so in the current scope, "uval" will always
+ // be a "byte[]".
+ int inputLength = uval.length();
+ }
+
+ // Error handling
+ string input = io:readln("Enter number: ");
+ int|error result = ints:fromString(input);
+ if result is int {
+ io:println("Number: ", result);
+ } else {
+ io:println("Invalid number: ", input);
+ }
+
+ // A check expression can be used to directly return the error from
+ // the current function if its subexpression evaluated to an error
+ // value in the runtime.
+ int number = check ints:fromString(input);
+
+ // Concurrent execution using workers in a function
+ doWorkers();
+
+ // Asynchronous execution with futures
+ future<int> f10 = start fib(10);
+ var webresult = clientEP->get("/");
+ int fresult = wait f10;
+ if webresult is http:Response {
+ io:println(webresult.getTextPayload());
+ io:println(fresult);
+ }
+
+ // Mapping types
+ map<int> ageMap = {};
+ ageMap["Peter"] = 25;
+ ageMap["John"] = 30;
+
+ int? agePeter = ageMap["Peter"]; // int? is the union type int|() - int or nill
+ if agePeter is int {
+ io:println("Peter's age is ", agePeter);
+ } else {
+ io:println("Peter's age is not found");
+ }
+
+ Person person1 = { id: "p1", name : "Anne", age: 28, country: "Sri Lanka" };
+ Scores score1 = { physics : 80, mathematics: 95 };
+ score1["chemistry"] = 75;
+ io:println(score1["chemistry"]);
+
+ Student student1 = { id: "s1", name: "Jack", age: 25, country: "Japan" };
+ student1.college = "Stanford";
+ string? jacksCollege = student1?.college; // optional field access
+ if jacksCollege is string {
+ io:println("Jack's college is ", jacksCollege);
+ }
+
+ // Due to the structural type system, "student1" can be assigned to "person2",
+ // since the student1's structure is compatible with person2's,
+ // where we can say, a "Student" is a "Person" as well.
+ Person person2 = student1;
+
+ map<int> grades = {"Jack": 95, "Anne": 90, "John": 80, "Bill": 55};
+ Person px1 = {id: "px1", name: "Jack", age: 30, country: "Canada"};
+ Person px2 = {id: "px2", name: "John", age: 25};
+ Person px3 = {id: "px3", name: "Anne", age: 17, country: "UK"};
+ Person px4 = {id: "px4", name: "Bill", age: 15, country: "USA"};
+ Person[] persons = [];
+ persons.push(px1);
+ persons.push(px2);
+ persons.push(px3);
+ persons.push(px4);
+
+ // Query expressions used to execute complex queries for list data
+ Result[] results = from var person in persons
+ let int lgrade = (grades[person.name] ?: 0)
+ where lgrade > 75
+ let string targetCollege = "Stanford"
+ select {
+ name: person.name,
+ college: targetCollege,
+ grade: lgrade
+ };
+
+ // Compile-time taint checking for handling untrusted data
+ string s1 = "abc";
+ mySecureFunction(s1);
+ // Explicitely make "s2" a tainted value. External input to a Ballerina
+ // program such as command-line arguments and network input are by-default
+ // marked as tainted data.
+ string s2 = <@tainted> s1;
+ // "s2x" is now a tainted value, since its value is derived using a
+ // tainted value (s1).
+ string s2x = s2 + "abc";
+ // The following line uncommented will result in a compilation error,
+ // since we are passing a tainted value (s2x) to a function which
+ // exepects an untainted value.
+ // mySecureFunction(s2x);
+
+ // Instantiating objects
+ Employee emp1 = new("E0001", "Jack Smith", "Sales", 2009);
+ io:println("The company service duration of ", emp1.name,
+ " is ", emp1.serviceDuration());
+
+ // Supported operations can be executed in a transaction by enclosing the actions
+ // in a "transaction" block.
+ transaction {
+ // Executes the below database operations in a single local transactions
+ var r1 = accountsDB->update("UPDATE Employee SET balance = balance + ? WHERE id = ?", 5500.0, "ID001");
+ var r2 = accountsDB->update("UPDATE Employee SET balance = balance + ? WHERE id = ?", 5500.0, "ID001");
+ }
+}
+
+// An object is a behavioural type, which encapsulates both data and functionality.
+type Employee object {
+
+ // Private fields are only visible within the object and its methods
+ private string empId;
+ // Public fields can be accessed by anyone
+ public string name;
+ public string department;
+ // The default qualifier is a "protected" field,
+ // which are accessible only within the module.
+ int yearJoined;
+
+ // The object initialization function; automatically called when an object is instantiated.
+ public function __init(string empId, string name, string department, int yearJoined) {
+ self.empId = empId;
+ self.name = name;
+ self.department = department;
+ self.yearJoined = yearJoined;
+ }
+
+ // An object method
+ public function serviceDuration() returns int {
+ time:Time ct = time:currentTime();
+ return time:getYear(ct) - self.yearJoined;
+ }
+
+};
+
+// Student is a subtype of Person
+type Student record {
+ string id;
+ string name;
+ int age;
+ string college?;
+ string country;
+};
+
+type Scores record {
+ int physics;
+ int mathematics;
+};
+
+type Result record {
+ string name;
+ string college;
+ int grade;
+};
+
+public function getOperation(string op) returns (function (int, int) returns int) {
+ if op == "add" {
+ return add;
+ } else if op == "mod" {
+ return function (int a, int b) returns int { // anonymous function
+ return a % b;
+ };
+ } else {
+ return (x, y) => 0; // single expression anonymous no-op function
+ }
+}
+
+// Two required parameters
+public function add(int a, int b) returns int {
+ return a + b;
+}
+
+// 'log' is a defaultable parameter
+public function multiply(int a, int b, boolean log = false) returns int {
+ if log {
+ io:println("Multiplying ", a, " with ", b);
+ }
+ return a * b;
+}
+
+// 'numbers' is a rest parameter - it can have multiple values,
+// similar to an array.
+public function addAll(int... numbers) returns int {
+ int result = 0;
+ foreach int number in numbers {
+ result += number;
+ }
+ return result;
+}
+
+public function getAdder(int n) returns (function (int x) returns int) {
+ return function (int x) returns int { // returns closure
+ return x + n;
+ };
+}
+
+function fib(int n) returns int {
+ if n <= 2 {
+ return 1;
+ } else {
+ return fib(n - 1) + fib(n - 2);
+ }
+}
+
+// The code in worker blocks "w1" and "w2" are executed concurrency
+// when this function is invoked. The "wait" expressions waits for
+// the given workers to finish to retrieve their results.
+public function doWorkers() {
+ worker w1 returns int {
+ int j = 10;
+ j -> w2;
+ int b;
+ b = <- w2;
+ return b * b;
+ }
+ worker w2 returns int {
+ int a;
+ a = <- w1;
+ a * 2 -> w1;
+ return a + 2;
+ }
+ record {int w1; int w2;} x = wait {w1, w2};
+ io:println(x);
+}
+
+// A function which takes in only an untainted string value.
+public function mySecureFunction(@untainted string input) {
+ io:println(input);
+}
+```
+
+### Further Reading
+
+* [Ballerina by Example](https://ballerina.io/learn/by-example/)
+* [User Guide](https://ballerina.io/learn/installing-ballerina/)
+* [API Documentation](https://ballerina.io/learn/api-docs/ballerina/)
+* [Language Specification](https://ballerina.io/spec/)
diff --git a/bash.html.markdown b/bash.html.markdown
index 8fdfdf08..e0e4f88a 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -18,6 +18,7 @@ contributors:
- ["Harry Mumford-Turner", "https://github.com/harrymt"]
- ["Martin Nicholson", "https://github.com/mn113"]
- ["Mark Grimwood", "https://github.com/MarkGrimwood"]
+ - ["Emily Grace Seville", "https://github.com/EmilySeville7cfg"]
filename: LearnBash.sh
translators:
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
@@ -37,104 +38,107 @@ or executed directly in the shell.
# As you already figured, comments start with #. Shebang is also a comment.
# Simple hello world example:
-echo Hello world! # => Hello world!
+echo "Hello world!" # => Hello world!
# Each command starts on a new line, or after a semicolon:
-echo 'This is the first line'; echo 'This is the second line'
-# => This is the first line
-# => This is the second line
+echo "This is the first command"; echo "This is the second command"
+# => This is the first command
+# => This is the second command
# Declaring a variable looks like this:
-Variable="Some string"
+variable="Some string"
# But not like this:
-Variable = "Some string" # => returns error "Variable: command not found"
-# Bash will decide that Variable is a command it must execute and give an error
+variable = "Some string" # => returns error "variable: command not found"
+# Bash will decide that `variable` is a command it must execute and give an error
# because it can't be found.
# Nor like this:
-Variable= 'Some string' # => returns error: "Some string: command not found"
-# Bash will decide that 'Some string' is a command it must execute and give an
-# error because it can't be found. (In this case the 'Variable=' part is seen
-# as a variable assignment valid only for the scope of the 'Some string'
-# command.)
+variable= "Some string" # => returns error: "Some string: command not found"
+# Bash will decide that "Some string" is a command it must execute and give an
+# error because it can't be found. In this case the "variable=" part is seen
+# as a variable assignment valid only for the scope of the "Some string"
+# command.
# Using the variable:
-echo $Variable # => Some string
-echo "$Variable" # => Some string
-echo '$Variable' # => $Variable
-# When you use the variable itself — assign it, export it, or else — you write
+echo "$variable" # => Some string
+echo '$variable' # => $variable
+# When you use a variable itself — assign it, export it, or else — you write
# its name without $. If you want to use the variable's value, you should use $.
# Note that ' (single quote) won't expand the variables!
-
-# Parameter expansion ${ }:
-echo ${Variable} # => Some string
-# This is a simple usage of parameter expansion
-# Parameter Expansion gets a value from a variable.
-# It "expands" or prints the value
-# During the expansion time the value or parameter can be modified
-# Below are other modifications that add onto this expansion
-
-# String substitution in variables
-echo ${Variable/Some/A} # => A string
-# This will substitute the first occurrence of "Some" with "A"
-
-# Substring from a variable
-Length=7
-echo ${Variable:0:Length} # => Some st
+# You can write variable without surrounding quotes but it's not recommended.
+
+# Parameter expansion ${...}:
+echo "${variable}" # => Some string
+# This is a simple usage of parameter expansion such as two examples above.
+# Parameter expansion gets a value from a variable.
+# It "expands" or prints the value.
+# During the expansion time the value or parameter can be modified.
+# Below are other modifications that add onto this expansion.
+
+# String substitution in variables:
+echo "${variable/Some/A}" # => A string
+# This will substitute the first occurrence of "Some" with "A".
+
+# Substring from a variable:
+length=7
+echo "${variable:0:length}" # => Some st
# This will return only the first 7 characters of the value
-echo ${Variable: -5} # => tring
-# This will return the last 5 characters (note the space before -5)
+echo "${variable: -5}" # => tring
+# This will return the last 5 characters (note the space before -5).
+# The space before minus is mandatory here.
-# String length
-echo ${#Variable} # => 11
+# String length:
+echo "${#variable}" # => 11
-# Indirect expansion
-OtherVariable="Variable"
-echo ${!OtherVariable} # => Some String
-# This will expand the value of OtherVariable
+# Indirect expansion:
+other_variable="variable"
+echo ${!other_variable} # => Some string
+# This will expand the value of `other_variable`.
-# Default value for variable
-echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
+# The default value for variable:
+echo "${foo:-"DefaultValueIfFooIsMissingOrEmpty"}"
# => DefaultValueIfFooIsMissingOrEmpty
-# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
+# This works for null (foo=) and empty string (foo=""); zero (foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.
-# Declare an array with 6 elements
-array0=(one two three four five six)
-# Print first element
-echo $array0 # => "one"
-# Print first element
-echo ${array0[0]} # => "one"
-# Print all elements
-echo ${array0[@]} # => "one two three four five six"
-# Print number of elements
-echo ${#array0[@]} # => "6"
-# Print number of characters in third element
-echo ${#array0[2]} # => "5"
-# Print 2 elements starting from forth
-echo ${array0[@]:3:2} # => "four five"
-# Print all elements. Each of them on new line.
-for i in "${array0[@]}"; do
- echo "$i"
+# Declare an array with 6 elements:
+array=(one two three four five six)
+# Print the first element:
+echo "${array[0]}" # => "one"
+# Print all elements:
+echo "${array[@]}" # => "one two three four five six"
+# Print the number of elements:
+echo "${#array[@]}" # => "6"
+# Print the number of characters in third element
+echo "${#array[2]}" # => "5"
+# Print 2 elements starting from fourth:
+echo "${array[@]:3:2}" # => "four five"
+# Print all elements each of them on new line.
+for item in "${array[@]}"; do
+ echo "$item"
done
-# Brace Expansion { }
-# Used to generate arbitrary strings
-echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
-echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z
-# This will output the range from the start value to the end value
-
# Built-in variables:
-# There are some useful built-in variables, like
+# There are some useful built-in variables, like:
echo "Last program's return value: $?"
echo "Script's PID: $$"
echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "Script's arguments separated into different variables: $1 $2..."
+# Brace Expansion {...}
+# used to generate arbitrary strings:
+echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
+echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z
+# This will output the range from the start value to the end value.
+# Note that you can't use variables here:
+from=1
+to=10
+echo {$from..$to} # => {$from..$to}
+
# Now that we know how to echo and use variables,
-# let's learn some of the other basics of bash!
+# let's learn some of the other basics of Bash!
# Our current directory is available through the command `pwd`.
# `pwd` stands for "print working directory".
@@ -144,33 +148,46 @@ echo "I'm in $(pwd)" # execs `pwd` and interpolates output
echo "I'm in $PWD" # interpolates the variable
# If you get too much output in your terminal, or from a script, the command
-# `clear` clears your screen
+# `clear` clears your screen:
clear
-# Ctrl-L also works for clearing output
+# Ctrl-L also works for clearing output.
# Reading a value from input:
echo "What's your name?"
-read Name # Note that we didn't need to declare a new variable
-echo Hello, $Name!
+read name
+# Note that we didn't need to declare a new variable.
+echo "Hello, $name!"
-# We have the usual if structure:
-# use `man test` for more info about conditionals
-if [ $Name != $USER ]
-then
+# We have the usual if structure.
+# Condition is true if the value of $name is not equal to the current user's login username:
+if [[ "$name" != "$USER" ]]; then
echo "Your name isn't your username"
else
echo "Your name is your username"
fi
-# True if the value of $Name is not equal to the current user's login username
-# NOTE: if $Name is empty, bash sees the above condition as:
-if [ != $USER ]
-# which is invalid syntax
-# so the "safe" way to use potentially empty variables in bash is:
-if [ "$Name" != $USER ] ...
-# which, when $Name is empty, is seen by bash as:
-if [ "" != $USER ] ...
-# which works as expected
+# To use && and || with if statements, you need multiple pairs of square brackets:
+read age
+if [[ "$name" == "Steve" ]] && [[ "$age" -eq 15 ]]; then
+ echo "This will run if $name is Steve AND $age is 15."
+fi
+
+if [[ "$name" == "Daniya" ]] || [[ "$name" == "Zach" ]]; then
+ echo "This will run if $name is Daniya OR Zach."
+fi
+# There are other comparison operators for numbers listed below:
+# -ne - not equal
+# -lt - less than
+# -gt - greater than
+# -le - less than or equal to
+# -ge - greater than or equal to
+
+# There is also the `=~` operator, which tests a string against the Regex pattern:
+email=me@example.com
+if [[ "$email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
+then
+ echo "Valid email!"
+fi
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
@@ -193,27 +210,6 @@ bg
kill %2
# %1, %2, etc. can be used for fg and bg as well
-# To use && and || with if statements, you need multiple pairs of square brackets:
-if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
-then
- echo "This will run if $Name is Steve AND $Age is 15."
-fi
-
-if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
-then
- echo "This will run if $Name is Daniya OR Zach."
-fi
-
-# There is also the `=~` operator, which tests a string against a Regex pattern:
-Email=me@example.com
-if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
-then
- echo "Valid email!"
-fi
-# Note that =~ only works within double [[ ]] square brackets,
-# which are subtly different from single [ ].
-# See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
-
# Redefine command `ping` as alias to send only 5 packets
alias ping='ping -c 5'
# Escape the alias and use command with this name instead
diff --git a/bf.html.markdown b/bf.html.markdown
index 1e415a4d..adc58f02 100644
--- a/bf.html.markdown
+++ b/bf.html.markdown
@@ -4,12 +4,13 @@ filename: bf.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
+ - ["rilysh", "https://github.com/rilysh"]
---
Brainfuck (not capitalized except at the start of a sentence) is an extremely
minimal Turing-complete programming language with just 8 commands.
-You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+You can try brainfuck on your browser with [brainfuck-online](https://copy.sh/brainfuck/).
```bf
Any character not "><+-.,[]" (excluding quotation marks) is ignored.
@@ -80,3 +81,8 @@ And that's brainfuck. Not that hard, eh? For fun, you can write your own
brainfuck programs, or you can write a brainfuck interpreter in another
language. The interpreter is fairly simple to implement, but if you're a
masochist, try writing a brainfuck interpreter… in brainfuck.
+
+## Further Reading
+ * [esolang-wiki](https://esolangs.org/wiki/Brainfuck)
+ * [learn brainfuck](http://cydathria.com/bf/brainfuck.html)
+ * [other resources](http://www.muppetlabs.com/~breadbox/bf/)
diff --git a/c++.html.markdown b/c++.html.markdown
index 038c3900..499eb669 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp.cpp
contributors:
- ["Steven Basart", "https://github.com/xksteven"]
@@ -158,6 +158,10 @@ namespace Second {
{
printf("This is Second::foo\n");
}
+ void bar()
+ {
+ printf("This is Second::bar\n");
+ }
}
void foo()
@@ -168,10 +172,12 @@ void foo()
int main()
{
// Includes all symbols from namespace Second into the current scope. Note
- // that simply foo() no longer works, since it is now ambiguous whether
- // we're calling the foo in namespace Second or the top level.
+ // that while bar() works, simply using foo() no longer works, since it is
+ // now ambiguous whether we're calling the foo in namespace Second or the
+ // top level.
using namespace Second;
+ bar(); // prints "This is Second::bar"
Second::foo(); // prints "This is Second::foo"
First::Nested::foo(); // prints "This is First::Nested::foo"
::foo(); // prints "This is global foo"
diff --git a/c.html.markdown b/c.html.markdown
index 90b5ed2d..ef341abf 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -1,16 +1,16 @@
---
-language: c
+language: C
filename: learnc.c
contributors:
- - ["Adam Bard", "http://adambard.com/"]
- - ["Ãrpád Goretity", "http://twitter.com/H2CO3_iOS"]
- - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- - ["Marco Scannadinari", "https://marcoms.github.io"]
- - ["Zachary Ferguson", "https://github.io/zfergus2"]
- - ["himanshu", "https://github.com/himanshu81494"]
- - ["Joshua Li", "https://github.com/JoshuaRLi"]
- - ["Dragos B. Chirila", "https://github.com/dchirila"]
- - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
+ - ["Adam Bard", "http://adambard.com/"]
+ - ["Ãrpád Goretity", "http://twitter.com/H2CO3_iOS"]
+ - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
+ - ["Marco Scannadinari", "https://marcoms.github.io"]
+ - ["Zachary Ferguson", "https://github.io/zfergus2"]
+ - ["himanshu", "https://github.com/himanshu81494"]
+ - ["Joshua Li", "https://github.com/JoshuaRLi"]
+ - ["Dragos B. Chirila", "https://github.com/dchirila"]
+ - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -101,6 +101,12 @@ int main (int argc, char** argv)
// %d is an integer, \n is a newline
printf("%d\n", 0); // => Prints 0
+ // take input using scanf
+ // '&' is used to define the location
+ // where we want to store the input value
+ int input;
+ scanf("%d", &input);
+
///////////////////////////////////////
// Types
///////////////////////////////////////
@@ -118,7 +124,7 @@ int main (int argc, char** argv)
// shorts are usually 2 bytes (use the `sizeof` operator to check)
short x_short = 0;
- // chars are defined as the smallest addressable unit for a processor.
+ // chars are defined as the smallest addressable unit for a processor.
// This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
char x_char = 0;
char y_char = 'y'; // Char literals are quoted with ''
@@ -167,19 +173,19 @@ int main (int argc, char** argv)
// where the "{0}" part is called an "array initializer".
// All elements (if any) past the ones in the initializer are initialized to 0:
int my_array[5] = {1, 2};
- // So my_array now has five elements, all but the first two of which are 0:
+ // So my_array now has five elements, all but the first two of which are 0:
// [1, 2, 0, 0, 0]
- // NOTE that you get away without explicitly declaring the size
+ // NOTE that you get away without explicitly declaring the size
// of the array IF you initialize the array on the same line:
int my_array[] = {0};
- // NOTE that, when not declaring the size, the size of the array is the number
+ // NOTE that, when not declaring the size, the size of the array is the number
// of elements in the initializer. With "{0}", my_array is now of size one: [0]
// To evaluate the size of the array at run-time, divide its byte size by the
// byte size of its element type:
size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
- // WARNING You should evaluate the size *before* you begin passing the array
- // to functions (see later discussion) because arrays get "downgraded" to
- // raw pointers when they are passed to functions (so the statement above
+ // WARNING You should evaluate the size *before* you begin passing the array
+ // to functions (see later discussion) because arrays get "downgraded" to
+ // raw pointers when they are passed to functions (so the statement above
// will produce the wrong result inside the function).
// Indexing an array is like other languages -- or,
@@ -247,11 +253,11 @@ int main (int argc, char** argv)
(float)i1 / i2; // => 0.5f
i1 / (double)i2; // => 0.5 // Same with double
f1 / f2; // => 0.5, plus or minus epsilon
-
+
// Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
- // exact values. For instance, the following does not produce expected results
- // because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
- // might be stored as 0.300000000001.
+ // exact values. For instance, the following does not produce expected results
+ // because 0.1 might actually be 0.099999999999 inside the computer, and 0.3
+ // might be stored as 0.300000000001.
(0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
// and it is NOT associative due to reasons mentioned above.
1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
@@ -262,7 +268,7 @@ int main (int argc, char** argv)
// eventually calls C which uses IEEE 754. It is mentioned this way not to
// indicate that this is a poor implementation, but instead as a warning
// that when doing floating point comparisons, a little bit of error (epsilon)
- // needs to be considered.
+ // needs to be considered.
// Modulo is there as well, but be careful if arguments are negative
11 % 3; // => 2 as 11 = 2 + 3*x (x=3)
@@ -411,7 +417,7 @@ int main (int argc, char** argv)
*/
/*
it is generally considered bad practice to do so, except if
- you really know what you are doing. See
+ you really know what you are doing. See
https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
*/
@@ -424,7 +430,7 @@ int main (int argc, char** argv)
int x_hex = 0x01; // You can assign vars with hex literals
// binary is not in the standard, but allowed by some
- // compilers (x_bin = 0b0010010110)
+ // compilers (x_bin = 0b0010010110)
// Casting between types will attempt to preserve their numeric values
printf("%d\n", x_hex); // => Prints 1
@@ -626,7 +632,7 @@ printf("first: %d\nsecond: %d\n", first, second);
// values will be swapped
*/
-// Return multiple values.
+// Return multiple values.
// C does not allow for returning multiple values with the return statement. If
// you would like to return multiple values, then the caller must pass in the
// variables where they would like the returned values to go. These variables must
@@ -637,9 +643,9 @@ int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
return 0; //return error code (false)
//de-reference the pointer so we modify its value
- *ret1 = array_of_3[0];
- *ret2 = array_of_3[1];
- *ret3 = array_of_3[2];
+ *ret1 = array_of_3[0];
+ *ret2 = array_of_3[1];
+ *ret3 = array_of_3[2];
return 1; //return error code (true)
}
@@ -901,10 +907,11 @@ Node createLinkedList(int *vals, int len);
#endif /* End of the if precompiler directive. */
```
+
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
-It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
+It is _the_ book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free).
diff --git a/ca-es/asciidoc-ca.html.markdown b/ca-es/asciidoc-ca.html.markdown
index a88aba52..6d387213 100644
--- a/ca-es/asciidoc-ca.html.markdown
+++ b/ca-es/asciidoc-ca.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
lang: ca-es
-filename: asciidoc-ca.md
+filename: asciidoc-ca.adoc
---
AsciiDoc és un llenguatge de marques similar a Markdown i que pot ser usat per qualsevol ús, des de llibres fins a blogs.
diff --git a/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown
index 99f0d393..7bec4ba4 100644
--- a/ca-es/go-ca.html.markdown
+++ b/ca-es/go-ca.html.markdown
@@ -95,7 +95,7 @@ salts de línia.` // El mateix tipus
// literals Non-ASCII literal. El tipus de Go és UTF-8.
g := 'Σ' // El tipus rune, és un àlies de int32 conté un caràcter unicode.
- f := 3.14195 // float64, un número de 64 bits amb coma flotant IEEE-754.
+ f := 3.14159 // float64, un número de 64 bits amb coma flotant IEEE-754.
c := 3 + 4i // complex128, representat internament amb dos float64.
// Sintaxi amb var i inicialitzadors.
@@ -433,25 +433,25 @@ func requestServer() {
## Més informació
L'arrel de tot en Go és la web oficial [official Go web site]
-(http://golang.org/). Allà es pot seguir el tutorial, jugar interactivament
+(https://go.dev/). Allà es pot seguir el tutorial, jugar interactivament
i llegir molt més del que hem vist aquí.En el "tour",
-[the docs](https://golang.org/doc/) conté informació sobre com escriure codi
+[the docs](https://go.dev/doc/) conté informació sobre com escriure codi
net i efectiu en Go, comandes per empaquetar i generar documentació, i
història de les versions.
És altament recomanable llegir La definició del llenguatge. És fàcil de llegir
i sorprenentment curta (com la definició del llenguatge en aquests dies).
-Es pot jugar amb codi a [Go playground](https://play.golang.org/p/tnWMjr16Mm).
+Es pot jugar amb codi a [Go playground](https://go.dev/play/p/tnWMjr16Mm).
Prova de fer canvis en el codi i executar-lo des del navegador! Es pot fer
-servir [https://play.golang.org](https://play.golang.org) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi
+servir [https://go.dev/play/](https://go.dev/play/) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi
en el navegador sense haver d'instal·lar Go.
En la llista de lectures pels estudiants de Go hi ha
-[el codi font de la llibreria estàndard](http://golang.org/src/pkg/).
+[el codi font de la llibreria estàndard](https://go.dev/src/).
Ampliament comentada, que demostra el fàcil que és de llegir i entendre els
programes en Go, l'estil de programació, i les formes de treballar-hi. O es
-pot clicar en un nom de funció en [la documentació](http://golang.org/pkg/)
+pot clicar en un nom de funció en [la documentació](https://go.dev/pkg/)
i veure'n el codi!
Un altre gran recurs per aprendre Go és
diff --git a/cairo.html.markdown b/cairo.html.markdown
new file mode 100644
index 00000000..dd3ca036
--- /dev/null
+++ b/cairo.html.markdown
@@ -0,0 +1,864 @@
+---
+language: Cairo
+filename: learnCairo.sol
+contributors:
+ - ["Darlington Nnam", "https://github.com/Darlington02"]
+---
+
+# Cairo
+
+Cairo is a Turing-complete language that allows you write provable programs
+(where one party can prove to another that a certain computation was executed
+correctly) on StarkNet.
+
+## StarkNet
+
+StarkNet is a decentralized ZK-rollup that operates as an Ethereum layer 2
+chain.
+
+In this document, we are going to be going in-depth into understanding Cairo's
+syntax and how you could create and deploy a Cairo smart contract on StarkNet.
+
+**NB: As at the time of this writing, StarkNet is still at v0.10.3, with Cairo
+1.0 coming soon. The ecosystem is young and evolving very fast, so you might
+want to check the [official docs](https://www.cairo-lang.org/docs) to confirm
+this document is still up-to-date. Pull requests are welcome!**
+
+## Setting Up A Development Environment
+
+Before we get started writing codes, we will need to setup a Cairo development
+environment, for writing, compiling and deploying our contracts to StarkNet.
+For the purpose of this tutorial we are going to be using the
+[Protostar Framework](https://github.com/software-mansion/protostar).
+Installation steps can be found in the docs
+[here](https://docs.swmansion.com/protostar/docs/tutorials/installation).
+Note that Protostar supports just Mac and Linux OS, Windows users might need to
+use WSL, or go for other alternatives such as the Official
+[StarkNet CLI](https://www.cairo-lang.org/docs/quickstart.html) or
+[Nile from Openzeppelin](https://github.com/OpenZeppelin/nile)
+
+Once you're done with the installations, run the command `protostar -v` to
+confirm your installation was successful. If successful, you should see your
+Protostar version displayed on the screen.
+
+## Initializing a new project
+
+Protostar similar to Truffle for solidity development can be installed once and
+used for multiple projects. To initialize a new Protostar project, run the
+following command:
+
+```
+protostar init
+```
+
+It would then request the project's name and the library's directory name,
+you'd need to fill in this, and a new project will be initialized successfully.
+
+## Compiling, Declaring, Deploying and Interacting with StarkNet Contracts
+
+Within the `src` folder you'll find a boilerplate contract that comes with
+initializing a new Protostar project, `main.cairo`. We are going to be
+compiling, declaring and deploying this contract.
+
+### Compiling Contracts
+
+To compile a Cairo contract using Protostar, ensure a path to the contract is
+specified in the `[contracts]` section of the `protostar.toml` file. Once
+you've done that, open your terminal and run the command:
+
+```
+protostar build
+```
+
+And you should get an output similar to what you see below, with a `main.json`
+and `main_abi.json` files created in the `build` folder.
+<img src="./images/cairo/build.png" alt="building your contract">
+
+### Declaring Contracts
+
+With the recent StarkNet update to 0.10.3, the DEPLOY transaction was
+deprecated and no longer works. To deploy a transaction, you must first declare
+a Contract to obtain the class hash, then deploy the declared contract using the
+[Universal Deployer Contract](https://community.starknet.io/t/universal-deployer-contract-proposal/1864).
+
+Before declaring or deploying your contract using Protostar, you should set the
+private key associated with the specified account address in a file, or in the
+terminal. To set your private key in the terminal, run the command:
+
+```
+export PROTOSTAR_ACCOUNT_PRIVATE_KEY=[YOUR PRIVATE KEY HERE]
+```
+
+Then to declare our contract using Protostar run the following command (for
+visual clarity, the backslash sign symbolizes the continuing line):
+
+```
+protostar declare ./build/main.json \
+ --network testnet \
+ --account 0x0691622bBFD29e835bA4004e7425A4e9630840EbD11c5269DE51C16774585b16 \
+ --max-fee auto
+```
+
+where `network` specifies the network we are deploying to, `account` specifies
+account whose private key we are using, `max-fee` specifies the maximum fee to
+be paid for the transaction. You should get the class hash outputted as seen
+below:
+<img src="./images/cairo/declare.png" alt="declaring your contract">
+
+### Deploying Contracts
+
+After obtaining our class hash from declaring, we can now deploy using the
+command below:
+
+```
+protostar \
+ deploy 0x02a5de1b145e18dfeb31c7cd7ff403714ededf5f3fdf75f8b0ac96f2017541bc \
+ --network testnet \
+ --account 0x0691622bBFD29e835bA4004e7425A4e9630840EbD11c5269DE51C16774585b16 \
+ --max-fee auto
+```
+
+where `0x02a5de1b145e18dfeb31c7cd7ff403714ededf5f3fdf75f8b0ac96f2017541bc` is
+the class hash of our contract.
+<img src="./images/cairo/deploy.png" alt="deploying your contract">
+
+### Interacting with Contracts
+
+To interact with your deployed contract, we will be using `Argent X`
+(alternative: `Braavos`), and `Starkscan` (alternative: `Voyager`). To install
+and setup `Argent X`, see this
+[guide](https://www.argent.xyz/learn/how-to-create-an-argent-x-wallet/).
+
+Copy your contract address, displayed on screen from the previous step, and
+head over to [Starkscan](https://testnet.starkscan.co/) to search for the
+contract. Once found, you can make write calls to the contract in the following
+sequence:
+
++ click on the "connect wallet" button,
+ <img src="./images/cairo/connect.png" alt="connect wallet">
++ select `Argent X` and approve the connection
+ <img src="./images/cairo/connect2.png" alt="connect to argentX">
++ you can now make read and write calls easily.
+
+## Let's learn Cairo
+
+First let's look at a default contract that comes with Protostar which allows
+you to set balance on deployment, increase, and get the balance.
+
+```
+// Language directive - instructs compiler its a StarkNet contract
+%lang starknet
+
+// Library imports from the Cairo-lang library
+from starkware.cairo.common.math import assert_nn
+from starkware.cairo.common.cairo_builtins import HashBuiltin
+
+// @dev Storage variable that stores the balance of a user.
+// @storage_var is a decorator that instructs the compiler the function
+// below it is a storage variable.
+@storage_var
+func balance() -> (res: felt) {}
+
+// @dev Constructor writes the balance variable to 0 on deployment
+// Constructors sets storage variables on deployment. Can accept arguments too.
+@constructor
+func constructor{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}() {
+ balance.write(0);
+ return();
+}
+
+// @dev increase_balance updates the balance variable
+// @param amount the amount you want to add to balance
+// @external is a decorator that specifies the func below it is an external
+// function.
+@external
+func increase_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(amount: felt){
+ with_attr error_message("Amount must be positive. Got: {amount}.") {
+ assert_nn(amount);
+ }
+
+ let (res) = balance.read();
+ balance.write(res + amount);
+ return ();
+}
+
+// @dev returns the balance variable
+// @view is a decorator that specifies the func below it is a view function.
+@view
+func get_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}() -> (res: felt) {
+ let (res) = balance.read();
+ return (res,);
+}
+```
+
+Before proceeding to the main lessons, try to build, deploy and interact with
+this contract.
+NB: You should be at `main.cairo` if you are using Protostar.
+
+### 1. The Felt data type
+
+Unlike solidity, where you have access to various data types, Cairo comes with
+just a single data type `..felts`. Felts stands for Field elements, and are a
+252 bit integer in the range `0<=x<=P` where `P` is a prime number. You can
+create a `Uint256` in Cairo by utlizing a struct of two 128 bits felts.
+
+```
+struct Uint256 {
+ low: felt, // The low 128 bits of the value.
+ high: felt, // The high 128 bits of the value.
+}
+```
+
+To avoid running into issues with divisions, it's safer to work with the
+`unsigned_div_rem` method from Cairo-lang's library.
+
+### 2. Lang Directive and Imports
+
+To get started with writing a StarkNet contract, you must specify the directive:
+
+```
+%lang starknet
+```
+
+This directive informs the compiler you are writing a contract and not a
+program. The difference between both is contracts have access to StarkNet's
+storage, programs don't and as such are stateless.
+
+There are important functions you might need to import from the official
+Cairo-lang library or Openzeppelin's, e.g.
+
+```
+from starkware.cairo.common.cairo_builtins import HashBuiltin
+from cairo_contracts.src.openzeppelin.token.erc20.library import ERC20
+from starkware.cairo.common.uint256 import Uint256
+from starkware.cairo.common.bool import TRUE
+```
+
+### 3. Data Structures
+
++ Storage variables: Cairo's storage is a map with `2^251` slots, where each
+ slot is a felt which is initialized to `0`. You create one using the
+ `@storage_var` decorator.
+
+ ```
+ @storage_var
+ func names() -> (name: felt) {}
+ ```
+
++ Storage mappings: Unlike Solidity where mappings have a separate keyword, in
+ Cairo you create mappings using storage variables.
+
+ ```
+ @storage_var
+ func names(address: felt) -> (name: felt) {}
+ ```
+
++ Structs: are a means to create custom data types in Cairo. A `struct` has a
+ size, which is the sum of the sizes of its members. The size can be
+ retrieved using `MyStruct.SIZE`. You create a struct in Cairo using the
+ `struct` keyword.
+
+ ```
+ struct Person {
+ name: felt,
+ age: felt,
+ address: felt,
+ }
+ ```
+
++ Constants: Constants are fixed and as such can't be altered after being set.
+ They evaluate to an integer (field element) at compile time. To create a
+ constant in Cairo, you use the `const` keyword. It's proper practice to
+ capitalize constant names.
+
+ ```
+ const USER = 0x01C6cfC1DB2ae90dACEA243F0a8C2F4e32560F7cDD398e4dA2Cc56B733774E9b
+ ```
+
++ Arrays: Arrays can be defined as a `pointer(felt*)` to the first element of
+ the array. As an array is populated, its elements take up contigous memory
+ cells. The `alloc` keyword can be used to dynamically allocate a new memory
+ segment, which can be used to store an array:
+
+ ```
+ let (myArray: felt*) = alloc ();
+ assert myArray[0] = 1;
+ assert myArray[1] = 2;
+ assert myArray[3] = 3;
+ ```
+
+ You can also use the `new` operator to create fixed-size arrays using
+ tuples. The new operator is useful as it enables you allocate memory and
+ initialize the object in one instruction
+
+ ```
+ func foo() {
+ tempvar arr: felt* = new (1, 1, 2, 3, 5);
+ assert arr[4] = 5;
+ return ();
+ }
+ ```
+
++ Tuples: A tuple is a finite, ordered, unchangeable list of elements. It is
+ represented as a comma-separated list of elements enclosed by parentheses.
+ Their elements may be of any combination of valid types.
+
+ ```
+ local tuple0: (felt, felt, felt) = (7, 9, 13);
+ ```
+
++ Events: Events allows a contract emit information during the course of its
+ execution, that can be used outside of StarkNet. An event can be created,
+ subsequently emitted:
+
+ ```
+ @event
+ func name_stored(address, name) {}
+
+ name_stored.emit(address, name);
+ ```
+
+### 4. Constructors, External and View functions
+
++ Constructors: Constructors are a way to intialize state variables on
+ contract deployment. You create a constructor using the `@constructor`
+ decorator.
+
+ ```
+ @constructor
+ func constructor{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+ range_check_ptr}(_name: felt) {
+ let (caller) = get_caller_address();
+ names.write(caller, _name);
+ return ();
+ }
+ ```
+
++ External functions: External functions are functions that modifies the state
+ of the network. You create an external function using the `@external`
+ decorator:
+
+ ```
+ @external
+ func store_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+ range_check_ptr}(_name: felt){
+ let (caller) = get_caller_address();
+ names.write(caller, _name);
+ stored_name.emit(caller, _name);
+ return ();
+ }
+ ```
+
++ View functions: View functions do not modify the state of the blockchain.
+ You can create a view function using the `@view` decorator.
+
+ ```
+ @view
+ func get_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+ range_check_ptr}(_address: felt) -> (name: felt){
+ let (name) = names.read(_address);
+ return (name,);
+ }
+ ```
+
+ NB: Unlike Solidity, Cairo supports just External and View function types.
+ You can alternatively also create an internal function by not adding any
+ decorator to the function.
+
+### 5. Decorators
+
+All functions in Cairo are specified by the `func` keyword, which can be
+confusing. Decorators are used by the compiler to distinguish between these
+functions.
+
+Here are the most common decorators you'll encounter in Cairo:
+
++ `@storage_var` — used for specifying state variables.
++ `@constructor` — used for specifying constructors.
++ `@external` — used for specifying functions that write to a state variable.
++ `@event` — used for specifying events
++ `@view` — used to specify functions reading from a state variable
++ `@contract_interface` — used for specifying function interfaces.
++ `@l1_handler` — used for specifying functions that processes message sent from
+ an L1 contract in a messaging bridge.
+
+### 6. BUILTINS, HINTS & IMPLICIT Arguments
+
++ `BUILTINS` are predefined optimized low-level execution units, which are
+ added to Cairo’s CPU board. They help perform predefined computations like
+ pedersen hashing, bitwise operations etc, which are expensive to perform in
+ Vanilla Cairo. Each builtin in Cairo is assigned a separate memory location,
+ accessible through regular Cairo memory calls using implicit parameters. You
+ specify them using the `%builtins` directive
+
+ Here is a list of available builtins in Cairo:
+
+ + `output` — the output builtin is used for writing program outputs
+ + `pedersen` — the pedersen builtin is used for pedersen hashing
+ computations
+ + `range_check` — This builtin is mostly used for integer comparisons,
+ and facilitates check to confirm that a field element is within a range
+ `[0, 2^128)`
+ + `ecdsa` — the ecdsa builtin is used for verifying ECDSA signatures
+ + `bitwise` — the bitwise builtin is used for carrying out bitwise
+ operations on felts
+
++ `HINTS` are pieces of Python codes, which contains instructions that only
+ the prover sees and executes. From the point of view of the verifier these
+ hints do not exist. To specify a hint in Cairo, you need to encapsulate it
+ within `%{` and `%}`. It is good practice to avoid using hints as much as
+ you can in your contracts, as hints are not added to the bytecode, and thus
+ do not count in the total number of execution steps.
+
+ ```
+ %{
+ # Python hint goes here
+ %}
+ ```
+
++ `IMPLICIT ARGUMENTS` are not restricted to the function body, but can be
+ inherited by other functions calls that require them. Implicit arguments are
+ passed in between curly bracelets, like you can see below:
+
+ ```
+ func store_name{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+ range_check_ptr}(_name: felt){
+ let (caller) = get_caller_address();
+ names.write(caller, _name);
+ stored_name.emit(caller, _name);
+ return ();
+ }
+ ```
+
+### 7. Error Messages and Access Controls
+
+You can create custom errors in Cairo which is outputted to the user upon failed
+execution. This can be very useful for implementing checks and proper access
+control mechanisms. An example is preventing a user to call a function except
+user is `admin`.
+
+```
+// imports
+from starkware.starknet.common.syscalls import get_caller_address
+
+// create an admin constant
+const ADMIN = 0x01C6cfC1DB2ae90dACEA243F0a8C2F4e32560F7cDD398e4dA2Cc56B733774E9b
+
+// implement access control
+with_attr error_message("You do not have access to make this action!"){
+ let (caller) = get_caller_address();
+ assert ADMIN = caller;
+}
+
+// using an assert statement throws if condition is not true, thus
+// returning the specified error.
+```
+
+### 8. Contract Interfaces
+
+Contract interfaces provide a means for one contract to invoke or call the
+external function of another contract. To create a contract interface, you use
+the `@contract_interface` keyword:
+
+```
+@contract_interface
+ namespace IENS {
+ func store_name(_name: felt) {
+ }
+
+ func get_name(_address: felt) -> (name: felt) {
+ }
+ }
+```
+
+Once a contract interface is specified, any contract can make calls to that
+contract passing in the contract address as the first parameter like this:
+
+```
+IENS.store_name(contract_address, _name);
+```
+
+Note that Interfaces exclude the function body/logic and the implicit
+arguments.
+
+### 9. Recursions
+
+Due to the unavailability of loops, Recursion is the go-to for similar
+operations. In simple terms, a recursive function is one which calls itself
+repeatedly.
+
+A good example to demonstrate this is writing a function for getting the nth
+fibonacci number:
+
+```
+@external
+func fibonacci{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(n : felt) -> (result : felt){
+ alloc_locals;
+ if (n == 0){
+ return (0);
+ }
+ if (n == 1){
+ return (1);
+ }
+ let (local x) = fibonacci(n - 1);
+ let (local y) = fibonacci(n - 2);
+ return (result=(x + y));
+}
+```
+
+The nth fibonacci term is the sum of the `nth - 1` and the `nth - 2` numbers,
+that's why we get these two as `(x,y)` using recursion.
+
+NB: when implementing recursive functions, always remember to implement a base
+case (`n==0`, `n==1` in our case), to prevent stack overflows.
+
+### 10. Registers
+
+Registers holds values that may change over time. There are 3 major types of
+registers:
+
++ `ap` (allocation pointer) points to a yet unused memory. Temporary variables
+ created using `let`, `tempvar` are held here, and thus susceptible to being
+ revoked.
++ `fp` (frame pointer) points to the frame of the current function. The address
+ of all the function arguments and local variables are relative to this
+ register and as such can never be revoked.
++ `pc` (program counter) points to the current instruction.
+
+### 11. Revoked References
+
+Revoked references occur when there is a call instruction to another function,
+between the definition of a reference variable that depends on `ap` (temp
+variables) and its usage. This occurs as the compiler may not be able to compute
+the change of `ap` (as one may jump to the label from another place in the
+program, or call a function that might change ap in an unknown way).
+
+Here is an example to demonstrate what I mean:
+
+```
+@external
+func get_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}() -> (res: felt) {
+ return (res=100);
+}
+
+@external
+func double_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}() -> (res: felt) {
+ let multiplier = 2;
+ let (balance) = get_balance();
+ let new_balance = balance * multiplier;
+ return (res=new_balance);
+}
+```
+
+If you run that code, you'll run into the revoked reference error as we are
+trying to access the `multiplier` variable after calling the `get_balance`
+function.
+
+In simple cases you can resolve revoked references by adding the keyword
+`alloc_locals` within function scopes. In more complex cases you might need to
+create a local variable to resolve it.
+
+```
+// resolving the `double_balance` function:
+@external
+func double_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}() -> (res: felt) {
+ alloc_locals;
+ let multiplier = 2;
+ let (balance) = get_balance();
+ let new_balance = balance * multiplier;
+ return (res=new_balance);
+}
+```
+
+### 12. Understanding Cairo's Punctuations
+
++ `;` (semicolon). Used at the end of each instruction
++ `()` (parentheses). Used in a function declaration, if statements, and in a
+ tuple declaration
++ `{}` (curly braces). Used in a declaration of implicit arguments and to define
+ code blocks.
++ `[]` (square brackets). Standalone brackets represent the value at a
+ particular address location (such as the allocation pointer, `[ap]`). Brackets
+ following a pointer or a tuple act as a subscript operator, where `x[2]`
+ represents the element with index `2` in `x`.
++ `*` (single asterisk). Refers to the pointer of an expression.
++ `%` (percent sign). Appears at the start of a directive, such as `%builtins`
+ or `%lang`.
++ `%{` and `%}` represent Python hints.
++ `_` (underscore). A placeholder to handle values that are not used, such as an
+ unused function return value.
+
+## Full Contract Example
+
+Below is a simple automated market maker contract example that implements most
+of what we just learnt! Re-write, deploy, have fun!
+
+```
+%lang starknet
+
+from starkware.cairo.common.cairo_builtins import HashBuiltin
+from starkware.cairo.common.hash import hash2
+from starkware.cairo.common.alloc import alloc
+from starkware.cairo.common.math import (assert_le, assert_nn_le,
+ unsigned_div_rem)
+from starkware.starknet.common.syscalls import (get_caller_address,
+ storage_read, storage_write)
+
+
+// CONSTANTS
+//
+// @dev the maximum amount of each token that belongs to the AMM
+const BALANCE_UPPER_BOUND = 2 ** 64;
+
+const TOKEN_TYPE_A = 1;
+const TOKEN_TYPE_B = 2;
+
+// @dev Ensure the user's balances are much smaller than the pool's balance
+const POOL_UPPER_BOUND = 2 ** 30;
+const ACCOUNT_BALANCE_BOUND = 1073741; // (2 ** 30 / 1000)
+
+
+// STORAGE VARIABLES
+//
+// @dev A map from account and token type to corresponding balance
+@storage_var
+func account_balance(account_id: felt, token_type: felt) -> (balance: felt) {}
+
+// @dev a map from token type to corresponding pool balance
+@storage_var
+func pool_balance(token_type: felt) -> (balance: felt) {}
+
+
+// GETTERS
+//
+// @dev returns account balance for a given token
+// @param account_id Account to be queried
+// @param token_type Token to be queried
+@view
+func get_account_token_balance{syscall_ptr: felt*, pedersen_ptr:
+HashBuiltin*, range_check_ptr}(
+ account_id: felt, token_type: felt
+ ) -> (balance: felt) {
+ return account_balance.read(account_id, token_type);
+}
+
+// @dev return the pool's balance
+// @param token_type Token type to get pool balance
+@view
+func get_pool_token_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ token_type: felt
+ ) -> (balance: felt) {
+ return pool_balance.read(token_type);
+}
+
+
+// EXTERNALS
+//
+// @dev set pool balance for a given token
+// @param token_type Token whose balance is to be set
+// @param balance Amount to be set as balance
+@external
+func set_pool_token_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ token_type: felt, balance: felt
+ ) {
+ with_attr error_message("exceeds maximum allowed tokens!"){
+ assert_nn_le(balance, BALANCE_UPPER_BOUND - 1);
+ }
+
+ pool_balance.write(token_type, balance);
+ return ();
+}
+
+// @dev add demo token to the given account
+// @param token_a_amount amount of token a to be added
+// @param token_b_amount amount of token b to be added
+@external
+func add_demo_token{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ token_a_amount: felt, token_b_amount: felt
+ ) {
+ alloc_locals;
+ let (account_id) = get_caller_address();
+
+ modify_account_balance(account_id=account_id, token_type=TOKEN_TYPE_A,
+ amount=token_a_amount);
+ modify_account_balance(account_id=account_id, token_type=TOKEN_TYPE_B,
+ amount=token_b_amount);
+
+ return ();
+}
+
+// @dev intialize AMM
+// @param token_a amount of token a to be set in pool
+// @param token_b amount of token b to be set in pool
+@external
+func init_pool{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ token_a: felt, token_b: felt
+ ) {
+ with_attr error_message("exceeds maximum allowed tokens!"){
+ assert_nn_le(token_a, POOL_UPPER_BOUND - 1);
+ assert_nn_le(token_b, POOL_UPPER_BOUND - 1);
+ }
+
+ set_pool_token_balance(token_type=TOKEN_TYPE_A, balance=token_a);
+ set_pool_token_balance(token_type=TOKEN_TYPE_B, balance=token_b);
+
+ return ();
+}
+
+
+// @dev swaps token between the given account and the pool
+// @param token_from token to be swapped
+// @param amount_from amount of token to be swapped
+// @return amount_to the token swapped to
+@external
+func swap{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr}(
+ token_from: felt, amount_from: felt
+ ) -> (amount_to: felt) {
+ alloc_locals;
+ let (account_id) = get_caller_address();
+
+ // verify token_from is TOKEN_TYPE_A or TOKEN_TYPE_B
+ with_attr error_message("token not allowed in pool!"){
+ assert (token_from - TOKEN_TYPE_A) * (token_from - TOKEN_TYPE_B) = 0;
+ }
+
+ // check requested amount_from is valid
+ with_attr error_message("exceeds maximum allowed tokens!"){
+ assert_nn_le(amount_from, BALANCE_UPPER_BOUND - 1);
+ }
+
+ // check user has enough funds
+ let (account_from_balance) =
+ get_account_token_balance(account_id=account_id, token_type=token_from);
+ with_attr error_message("insufficient balance!"){
+ assert_le(amount_from, account_from_balance);
+ }
+
+ let (token_to) = get_opposite_token(token_type=token_from);
+ let (amount_to) = do_swap(account_id=account_id, token_from=token_from,
+ token_to=token_to, amount_from=amount_from);
+
+ return (amount_to=amount_to);
+}
+
+
+// INTERNALS
+//
+// @dev internal function that updates account balance for a given token
+// @param account_id Account whose balance is to be modified
+// @param token_type Token type to be modified
+// @param amount Amount Amount to be added
+func modify_account_balance{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ account_id: felt, token_type: felt, amount: felt
+ ) {
+ let (current_balance) = account_balance.read(account_id, token_type);
+ tempvar new_balance = current_balance + amount;
+
+ with_attr error_message("exceeds maximum allowed tokens!"){
+ assert_nn_le(new_balance, BALANCE_UPPER_BOUND - 1);
+ }
+
+ account_balance.write(account_id=account_id, token_type=token_type,
+ value=new_balance);
+ return ();
+}
+
+// @dev internal function that swaps tokens between the given account and
+// the pool
+// @param account_id Account whose tokens are to be swapped
+// @param token_from Token type to be swapped from
+// @param token_to Token type to be swapped to
+// @param amount_from Amount to be swapped
+func do_swap{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*,
+range_check_ptr}(
+ account_id: felt, token_from: felt, token_to: felt, amount_from: felt
+ ) -> (amount_to: felt) {
+ alloc_locals;
+
+ // get pool balance
+ let (local amm_from_balance) = get_pool_token_balance(token_type =
+ token_from);
+ let (local amm_to_balance) = get_pool_token_balance(token_type=token_to);
+
+ // calculate swap amount
+ let (local amount_to, _) = unsigned_div_rem((amm_to_balance *
+ amount_from), (amm_from_balance + amount_from));
+
+ // update token_from balances
+ modify_account_balance(account_id=account_id, token_type=token_from,
+ amount=-amount_from);
+ set_pool_token_balance(token_type=token_from, balance=(amm_from_balance
+ + amount_from));
+
+ // update token_to balances
+ modify_account_balance(account_id=account_id, token_type=token_to,
+ amount=amount_to);
+ set_pool_token_balance(token_type=token_to, balance=(amm_to_balance -
+ amount_to));
+
+ return (amount_to=amount_to);
+}
+
+
+// @dev internal function to get the opposite token type
+// @param token_type Token whose opposite pair needs to be gotten
+func get_opposite_token(token_type: felt) -> (t: felt) {
+ if(token_type == TOKEN_TYPE_A) {
+ return (t=TOKEN_TYPE_B);
+ } else {
+ return (t=TOKEN_TYPE_A);
+ }
+}
+```
+
+## Additional Resources
+
++ [Official documentation](https://www.cairo-lang.org/docs/)
++ [Starknet EDU](https://medium.com/starknet-edu)
++ [Journey through Cairo](https://medium.com/@darlingtonnnam/journey-through-cairo-i-setting-up-protostar-and-argentx-for-local-development-ba40ae6c5524)
++ [Demystifying Cairo whitepaper](https://medium.com/@pban/demystifying-cairo-white-paper-part-i-b71976ad0108)
++ [Learn about StarkNet with Argent](https://www.argent.xyz/learn/tag/starknet/)
+
+## Development Frameworks
+
++ [Protostar](https://docs.swmansion.com/protostar/docs/tutorials/installation)
++ [Nile](https://github.com/OpenZeppelin/nile)
++ [StarkNet CLI](https://www.cairo-lang.org/docs/quickstart.html)
+
+## Helpful Libraries
+
++ [Cairo-lang](https://github.com/starkware-libs/cairo-lang)
++ [Openzeppelin](https://github.com/OpenZeppelin/cairo-contracts)
+
+## Educational Repos
+
++ [StarkNet Cairo 101](https://github.com/starknet-edu/starknet-cairo-101)
++ [StarkNet ERC721](https://github.com/starknet-edu/starknet-erc721)
++ [StarkNet ERC20](https://github.com/starknet-edu/starknet-erc20)
++ [L1 -> L2 Messaging](https://github.com/starknet-edu/starknet-messaging-bridge)
++ [StarkNet Debug](https://github.com/starknet-edu/starknet-debug)
++ [StarkNet Accounts](https://github.com/starknet-edu/starknet-accounts)
++ [Min-Starknet](https://github.com/Darlington02/min-starknet)
+
+## Security
+
++ [Amarna static analysis for Cairo programs](https://blog.trailofbits.com/2022/04/20/amarna-static-analysis-for-cairo-programs/)
++ [Cairo and StarkNet security by Ctrl03](https://ctrlc03.github.io/)
++ [How to hack almost any Cairo smart contract](https://medium.com/ginger-security/how-to-hack-almost-any-starknet-cairo-smart-contract-67b4681ac0f6)
++ [Analyzing Cairo code using Armana](https://dic0de.substack.com/p/analyzing-cairo-code-using-amarna?sd=pf)
+
+## Future TO-DOs
+
+Update tutorial to fit Cairo 1.0
diff --git a/citron.html.markdown b/citron.html.markdown
index bd3c398c..ce607ca1 100644
--- a/citron.html.markdown
+++ b/citron.html.markdown
@@ -68,7 +68,7 @@ False not. # True
###########################################
# You may assign values to the current scope:
-var name is value. # assignes `value` into `name`
+var name is value. # assigns `value` into `name`
# You may also assign values into the current object's namespace
my name is value. # assigns `value` into the current object's `name` property
@@ -146,7 +146,7 @@ add(3, 5). # 8
3 `add` 5. # 8
# This call binds as such: add[(3), 5]
-# because the default fixity is left, and the default precedance is 1
+# because the default fixity is left, and the default precedence is 1
# You may change the precedence/fixity of this operator with a pragma
#:declare infixr 1 add
diff --git a/clojure.html.markdown b/clojure.html.markdown
index 20812a9b..21d5a088 100644
--- a/clojure.html.markdown
+++ b/clojure.html.markdown
@@ -412,7 +412,7 @@ Clojuredocs.org has documentation with examples for most core functions:
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure is a great way to build your clojure/FP skills:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org (yes, really) has a number of getting started articles:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/cobol.html.markdown b/cobol.html.markdown
index 1c858396..1350c66f 100644
--- a/cobol.html.markdown
+++ b/cobol.html.markdown
@@ -132,7 +132,7 @@ organizations.
*Now it is time to learn about two related COBOL verbs: string and unstring.
- *The string verb is used to concatenate, or put together, two or more stings.
+ *The string verb is used to concatenate, or put together, two or more strings.
*Unstring is used, not surprisingly, to separate a
*string into two or more smaller strings.
*It is important that you remember to use ‘delimited by’ when you
diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown
index 36217414..18880a3b 100644
--- a/cs-cz/go.html.markdown
+++ b/cs-cz/go.html.markdown
@@ -33,7 +33,7 @@ Go má již v základu vynikající knihovnu a je s ním spojená nadšená komu
řádkový komentář */
// Každý zdroják zaÄíná deklarací balíÄku (package)
-// Main je vyhrazené jméno, které oznaÄuje spustitelný soubor,
+// main je vyhrazené jméno, které oznaÄuje spustitelný soubor,
// narozdíl od knihovny
package main
@@ -90,7 +90,7 @@ 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.
+ f := 3.14159 // 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í
@@ -408,20 +408,20 @@ func requestServer() {
## Kam dále
-Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/).
+Vše hlavní o Go se nachází na [oficiálních stránkách go](https://go.dev/).
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
+KromÄ› úvodu, [dokumenty](https://go.dev/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
+Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://go.dev/play/p/r46YvCu-XX).
+Můžete tam spouÅ¡tÄ›t programy s prohlížeÄe. Také můžete [https://go.dev/play/](https://go.dev/play/) 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/)
+Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](https://go.dev/src/).
+Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](https://go.dev/pkg/)
tak se podíváte na dokumentaci.
Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/).
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
index 50a69107..e1a96f32 100644
--- a/cs-cz/markdown.html.markdown
+++ b/cs-cz/markdown.html.markdown
@@ -215,7 +215,7 @@ Pro ještě hlubší odsazení můžete přidat další 4 mezery nebo další ta
```md
moje_pole.each do |i|
- puts i
+ puts i
end
```
@@ -228,11 +228,13 @@ Honza neměl tušení, co dělá funkce `go_to()`!
V Markdownu od GitHubu, můžete použít speciální syntaxi pro kód:
-<pre><code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def neco
- puts "Ahoj světe!"
+ puts "Ahoj světe!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
Text výše nepotÅ™ebuje ÄtyÅ™mezerové odsazení a parser navíc použije zvýraznÄ›ní
syntaxe pro zvolený jazyk.
diff --git a/csharp.html.markdown b/csharp.html.markdown
index c85acb1b..1d7d0881 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
@@ -158,7 +158,7 @@ on a new line! ""Wow!"", the masses cried";
// Arrays - zero indexed
// The array size must be decided upon declaration
- // The format for declaring an array is follows:
+ // The format for declaring an array is
// <datatype>[] <var name> = new <datatype>[<array size>];
int[] intArray = new int[10];
@@ -172,7 +172,7 @@ on a new line! ""Wow!"", the masses cried";
// Lists
// Lists are used more frequently than arrays as they are more flexible
- // The format for declaring a list is follows:
+ // The format for declaring a list is
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
@@ -182,14 +182,14 @@ on a new line! ""Wow!"", the masses cried";
// Lists don't default to a value;
// A value must be added before accessing the index
intList.Add(1);
- Console.WriteLine("intList @ 0: " + intList[0]);
+ Console.WriteLine("intList at 0: " + intList[0]);
- // Others data structures to check out:
+ // Other data structures to check out:
// Stack/Queue
// Dictionary (an implementation of a hash map)
// HashSet
// Read-only Collections
- // Tuple (.Net 4+)
+ // Tuple (.NET 4+)
///////////////////////////////////////
// Operators
@@ -222,20 +222,20 @@ on a new line! ""Wow!"", the masses cried";
| Bitwise inclusive OR
*/
- // Incrementations
+ // Incrementing
int i = 0;
- Console.WriteLine("\n->Inc/Dec-rementation");
- Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation
- Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation
- Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation
- Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation
+ Console.WriteLine("\n->Inc/Dec-rement");
+ Console.WriteLine(i++); //Prints "0", i = 1. Post-Increment
+ Console.WriteLine(++i); //Prints "2", i = 2. Pre-Increment
+ Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrement
+ Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrement
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
Console.WriteLine("\n->Control Structures");
- // If statements are c-like
+ // If statements are C-like
int j = 10;
if (j == 10)
{
@@ -288,7 +288,7 @@ on a new line! ""Wow!"", the masses cried";
// For Each Loop
// foreach loop structure => foreach(<iteratorType> <iteratorName> in <enumerable>)
// The foreach loop loops over any object implementing IEnumerable or IEnumerable<T>
- // All the collection types (Array, List, Dictionary...) in the .Net framework
+ // All the collection types (Array, List, Dictionary...) in the .NET framework
// implement one or both of these interfaces.
// (The ToCharArray() could be removed, because a string also implements IEnumerable)
foreach (char character in "Hello World".ToCharArray())
@@ -297,7 +297,7 @@ on a new line! ""Wow!"", the masses cried";
}
// Switch Case
- // A switch works with the byte, short, char, and int data types.
+ // A switch works with byte, short, char, and int data types.
// It also works with enumerated types (discussed in Enum Types),
// the String class, and a few special classes that wrap
// primitive types: Character, Byte, Short, and Integer.
@@ -316,7 +316,7 @@ on a new line! ""Wow!"", the masses cried";
break;
// You can assign more than one case to an action
// But you can't add an action without a break before another case
- // (if you want to do this, you would have to explicitly add a goto case x
+ // (if you want to do this, you would have to explicitly add a goto case x)
case 6:
case 7:
case 8:
@@ -337,14 +337,14 @@ on a new line! ""Wow!"", the masses cried";
// this will throw a FormatException on failure
int.Parse("123"); // returns an integer version of "123"
- // try parse will default to type default on failure
- // in this case: 0
+ // TryParse will default to the type's default value on failure
+ // in this case 0
int tryInt;
if (int.TryParse("123", out tryInt)) // Function is boolean
Console.WriteLine(tryInt); // 123
// Convert Integer To String
- // Convert class has a number of methods to facilitate conversions
+ // The Convert class has a number of methods to facilitate conversions
// String to int
@@ -388,7 +388,7 @@ on a new line! ""Wow!"", the masses cried";
Console.Read();
} // End main method
- // Available in C# 9 and later, this is basically a syntactic sugar for a class. Records are immutable*.
+ // Available in C# 9 and later, this is basically syntactic sugar for a class. Records are immutable*.
public record ARecord(string Csharp);
// CONSOLE ENTRY - A console application must have a main method as an entry point
@@ -428,7 +428,7 @@ on a new line! ""Wow!"", the masses cried";
// GENERICS
// The classes for TKey and TValue is specified by the user calling this function.
- // This method emulates the SetDefault of Python
+ // This method emulates Python's dict.setdefault()
public static TValue SetDefault<TKey, TValue>(
IDictionary<TKey, TValue> dictionary,
TKey key,
diff --git a/css.html.markdown b/css.html.markdown
index b8adc886..948b70ac 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -102,19 +102,24 @@ div.some-parent.class-name { }
/* There are some selectors called pseudo classes that can be used to select an
element only when it is in a particular state */
-/* for example, when the cursor hovers over an element */
-selector:hover { }
+/* for example, when a link hasn't been visited */
+selected:link { }
/* or a link has been visited */
selector:visited { }
-/* or hasn't been visited */
-selected:link { }
-
/* or an element is in focus */
selected:focus { }
-/* any element that is the first child of its parent */
+/* or when the cursor hovers over an element */
+selector:hover { }
+
+/* or when a link is clicked on */
+selector:active { }
+
+/* These pseudo classes regarding links should always be written in the above order or the code might not work as expected */
+
+/* Any element that is the first child of its parent */
selector:first-child {}
/* any element that is the last child of its parent */
diff --git a/cue.html.markdown b/cue.html.markdown
new file mode 100644
index 00000000..a1ff0822
--- /dev/null
+++ b/cue.html.markdown
@@ -0,0 +1,551 @@
+---
+name: CUE
+category: language
+language: CUE
+filename: learncue.cue
+contributors:
+ - ["Daniel Cox", "https://github.com/danielpcox"]
+ - ["Coleman McFarland", "https://github.com/dontlaugh"]
+---
+
+CUE is an expressive (but not Turing-complete) JSON superset, exportable to JSON or YAML. It supports optional types and many other conveniences for working with large configuration sets. The unification engine has roots in logic programming, and as such it provides a ready solution to modern configuration management problems.
+
+When CUE is exported to JSON, values from every processed file are unified into one giant object. Consider these two files:
+
+```yaml
+//name.cue
+name: "Daniel"
+```
+
+```yaml
+//disposition.cue
+disposition: "oblivious"
+```
+
+Now we can unify and export to JSON:
+```bash
+% cue export name.cue disposition.cue
+{
+ "name": "Daniel",
+ "disposition": "oblivious"
+}
+```
+
+Or YAML:
+```bash
+% cue export --out yaml name.cue disposition.cue
+name: Daniel
+disposition: oblivious
+```
+
+Notice the C-style comments are not in the output. Also notice that the keys in CUE syntax did not require quotes. Some special characters do require quotes:
+
+```yaml
+works_fine: true
+"needs-quotes": true
+```
+
+Unification doesn't just unify across files, it is also a *global merge* of all types and values. The following fails, because the *types* are different.
+
+```yaml
+//string_value.cue
+foo: "baz"
+```
+
+```yaml
+//integer_value.cue
+foo: 100
+```
+
+```bash
+% cue export string_value.cue integer_value.cue
+foo: conflicting values "baz" and 100 (mismatched types string and int):
+ integer_value.cue:1:6
+ string_value.cue:1:6
+```
+
+But even if we quote the integer, it still fails, because the *values* conflict and there is no way to unify everything into a top-level object.
+
+```yaml
+//string_value.cue
+foo: "baz"
+```
+
+```yaml
+//integer_value.cue
+foo: "100" // a string now
+```
+
+```bash
+% cue export string_value.cue integer_value.cue
+foo: conflicting values "100" and "baz":
+ integer_value.cue:1:6
+ string_value.cue:1:6
+```
+
+Types in CUE *are* values; special ones that the unification engine knows have certain behavior relative to other values. During unification it requires that values match the specified types, and when concrete values are required, you will get an error if there's only a type. So this is fine:
+
+```yaml
+street: "1 Infinite Loop"
+street: string
+```
+
+While `cue export` produces YAML or JSON, `cue eval` produces CUE. This is useful for converting YAML or JSON to CUE, or for inspecting the unified output in CUE itself. It's fine to be missing concrete values in CUE (though it prefers concrete values when emitting CUE when both are available and match),
+
+```yaml
+//type-only.cue
+amount: float
+```
+
+```bash
+% cue eval type-only.cue
+amount: float
+```
+
+but you *need* concrete values if you want to export (or if you tell `eval` to require them with `-c`):
+
+```bash
+% cue export type-only.cue
+amount: incomplete value float
+```
+
+Give it a value that unifies with the type, and all is well.
+
+```yaml
+//concrete-value.cue
+amount: 3.14
+```
+
+```bash
+% cue export type-only.cue concrete-value.cue
+{
+ "amount": 3.14
+}
+```
+
+The method of unifying concrete values with types that share a common syntax is very powerful, and much more compact than, e.g., JSON Schema. This way, schema, defaults, and data are all expressible in CUE.
+
+Default values may be supplied with a type using an asterisk:
+
+```yaml
+// default-port.cue
+port: int | *8080
+```
+
+```bash
+% cue eval default-port.cue
+port: 8080
+```
+
+Enum-style options ("disjunctions" in CUE) may be specified with an `|` separator:
+
+```yaml
+//severity-enum.cue
+severity: "high" | "medium" | "low"
+severity: "unknown"
+```
+
+```bash
+% cue eval severity-enum.cue
+severity: 3 errors in empty disjunction:
+severity: conflicting values "high" and "unknown":
+ ./severity-enum.cue:1:11
+ ./severity-enum.cue:1:48
+severity: conflicting values "low" and "unknown":
+ ./severity-enum.cue:1:31
+ ./severity-enum.cue:1:48
+severity: conflicting values "medium" and "unknown":
+ ./severity-enum.cue:1:20
+ ./severity-enum.cue:1:48
+```
+
+You can even have disjunctions of structs (not shown, but it works like you'd expect).
+
+CUE has "definitions", and you can use them like you would variable declarations in other languages. They are also for defining struct types. You can apply a struct of type definitions to some concrete value(s) with `&`. Also notice you can say "a list with type #Whatever" using `[...#Whatever]`.
+
+```yaml
+// definitions.cue
+
+#DashboardPort: 1337
+
+configs: {
+ host: "localhost"
+ port: #DashboardPort
+}
+
+#Address: {
+ street: string
+ city: string
+ zip?: int // ? makes zip optional
+}
+
+some_address: #Address & {
+ street: "1 Rocket Rd"
+ city: "Hawthorne"
+}
+
+more_addresses: [...#Address] & [
+ {street: "1600 Amphitheatre Parkway", city: "Mountain View", zip: "94043"},
+ {street: "1 Hacker Way", city: "Menlo Park"}
+]
+```
+
+```bash
+% cue export --out yaml definitions.cue
+configs:
+ host: localhost
+ port: 1337
+some_address:
+ street: 1 Rocket Rd
+ city: Hawthorne
+more_addresses:
+ - street: 1600 Amphitheatre Parkway
+ city: Mountain View
+ zip: "94043"
+ - street: 1 Hacker Way
+ city: Menlo Park
+```
+
+CUE supports more complex values and validation:
+
+```yaml
+#Country: {
+ name: =~"^\\p{Lu}" // Must start with an upper-case letter
+ pop: >800 & <9_000_000_000 // More than 800, fewer than 9 billion
+}
+
+vatican_city: #Country & {
+ name: "Vatican City"
+ pop: 825
+}
+```
+
+CUE may save you quite a bit of time with all the sugar it provides on top of mere JSON. Here we're defining, "modifying", and validating a nested structure in three lines: (Notice the `[]` syntax used around `string` to signal to the engine that `string` is a constraint, not a string in this case.)
+
+```yaml
+//paths.cue
+
+// path-value pairs
+outer: middle1: inner: 3
+outer: middle2: inner: 7
+
+// collection-constraint pair
+outer: [string]: inner: int
+```
+
+```bash
+% cue export paths.cue
+{
+ "outer": {
+ "middle1": {
+ "inner": 3
+ },
+ "middle2": {
+ "inner": 7
+ }
+ }
+}
+```
+
+In the same vein, CUE supports "templates", which are a bit like functions of a single argument. Here `Name` is bound to each string key immediately under `container` while the struct underneath *that* is evaluated.
+
+```yaml
+//templates.cue
+
+container: [Name=_]: {
+ name: Name
+ replicas: uint | *1
+ command: string
+}
+
+container: sidecar: command: "envoy"
+
+container: service: {
+ command: "fibonacci"
+ replicas: 2
+}
+```
+
+```bash
+% cue eval templates.cue
+container: {
+ sidecar: {
+ name: "sidecar"
+ replicas: 1
+ command: "envoy"
+ }
+ service: {
+ name: "service"
+ command: "fibonacci"
+ replicas: 2
+ }
+}
+```
+
+And while we're talking about references like that, CUE supports scoped references.
+
+```yaml
+//scopes-and-references.cue
+v: "top-level v"
+b: v // a reference
+a: {
+ b: v // matches the top-level v
+}
+
+let V = v
+a: {
+ v: "a's inner v"
+ c: v // matches the inner v
+ d: V // matches the top-level v now shadowed by a.v
+}
+av: a.v // matches a's v
+```
+
+```bash
+% cue eval --out yaml scopes-and-references.cue
+```
+
+```yaml
+v: top-level v
+b: top-level v
+a:
+ b: top-level v
+ v: a's inner v
+ c: a's inner v
+ d: top-level v
+av: a's inner v
+```
+
+I changed the order of the keys in the output for clarity. Order doesn't actually matter, and notice that duplicate keys at a given level are *all* unified.
+
+You can hide fields be prefixing them with `_` (quote the field if you need a `_` prefix in an emitted field)
+
+```yaml
+//hiddens.cue
+"_foo": 2
+_foo: 3
+foo: 4
+_#foo: 5
+#foo : 6
+```
+
+```bash
+% cue eval hiddens.cue
+"_foo": 2
+foo: 4
+#foo: 6
+
+% cue export hiddens.cue
+{
+ "_foo": 2,
+ "foo": 4
+}
+```
+
+Notice the difference between `eval` and `export` with respect to definitions. If you want to hide a definition in CUE, you can prefix *that* with `_`.
+
+Interpolation of values and fields:
+
+```yaml
+//interpolation.cue
+
+#expense: 90
+#revenue: 100
+message: "Your profit was $\( #revenue - #expense)"
+
+cat: {
+ type: "Cuddly"
+ "is\(type)": true
+}
+```
+
+```bash
+% cue export interpolation.cue
+{
+ "message": "Your profit was $10",
+ "cat": {
+ "type": "Cuddly",
+ "isCuddly": true
+ }
+}
+```
+
+Operators, list comprehensions, conditionals, imports...:
+
+```yaml
+//getting-out-of-hand-now.cue
+import "strings" // we'll come back to this
+
+// operators are nice
+g: 5 / 3 // CUE can do math
+h: 3 * "blah" // and Python-like string repetition
+i: 3 * [1, 2, 3] // with lists too
+j: 8 < 10 // and supports boolean ops
+
+// conditionals are also nice
+price: number
+// Require a justification if price is too high
+if price > 100 {
+ justification: string
+}
+price: 200
+justification: "impulse buy"
+
+// list comprehensions are powerful and compact
+#items: [ 1, 2, 3, 4, 5, 6, 7, 8, 9]
+comp: [ for x in #items if x rem 2 == 0 {x*x}]
+
+// and... well you can do this too
+#a: [ "Apple", "Google", "SpaceX"]
+for k, v in #a {
+ "\( strings.ToLower(v) )": {
+ pos: k + 1
+ name: v
+ nameLen: len(v)
+ }
+}
+```
+
+```bash
+% cue export getting-out-of-hand-now.cue
+```
+
+```json
+{
+ "g": 1.66666666666666666666667,
+ "h": "blahblahblah",
+ "i": [1, 2, 3, 1, 2, 3, 1, 2, 3],
+ "j": true,
+ "apple": {
+ "pos": 1,
+ "name": "Apple",
+ "nameLen": 5
+ },
+ "google": {
+ "pos": 2,
+ "name": "Google",
+ "nameLen": 6
+ },
+ "price": 200,
+ "justification": "impulse buy",
+ "comp": [
+ 4,
+ 16,
+ 36,
+ 64
+ ],
+ "spacex": {
+ "pos": 3,
+ "name": "SpaceX",
+ "nameLen": 6
+ }
+}
+```
+
+At this point it's worth mentioning that CUE may not be Turing-complete, but it *is* powerful enough for you to shoot yourself in the foot, so do try to keep it clear. It's easy to go off the deep end and make your config *harder* to work with if you're not careful. Make use of those comments, at least, and/or...
+
+To that end, CUE supports packages and modules. CUE files are standalone by default, but if you put a package clause at the top, you're saying that file is unifiable with other files "in" the same package.
+
+```yaml
+//a.cue
+package config
+
+foo: 100
+bar: int
+```
+
+```yaml
+//b.cue
+package config
+
+bar: 200
+```
+
+If you create these two files in a new directory and run `cue eval` (no arguments), it will unify them like you'd expect. It searches the current directory for .cue files, and if they all have the same package, they will be unified.
+
+Packages are more clear in the context of "modules". Modules are the *largest* unit of organization. Basically every time you have a project that spans multiple files, you should create a module and name it with something that looks like the domain and path of a URL, e.g., `example.com/something`. When you import anything from this module, even from *within* the module, you must do so using the fully-qualified module path which will be prefixed with this module name.
+
+You can create a new module like so:
+
+```bash
+mkdir mymodule && cd mymodule
+cue mod init example.com/mymodule
+```
+
+This creates a `cue.mod/` subdirectory within that `mymodule` directory, and `cue.mod/` contains the following file and subdirectories:
+
+- `module.cue` (which defines your module name, in this case with `module: "example.com/mymodule"`)
+- pkg/
+- gen/
+- usr/
+
+For a different perspective on this and details about what's in there, see https://cuelang.org/docs/concepts/packages/. For my purposes here, I'll say you don't need to think about the contents of this directory *at all*, except that your module name will be the prefix for all imports within your module.
+
+Where will your module file hierarchy go? All files and directories for your module are rooted in `mymodule/`, the directory that also contains `cue.mod/`. If you want to import a package, you'll prefix it with `example.com/mymodule`, followed by a relative path rooted in `mymodule/`.
+
+To make it concrete, consider the following:
+
+```
+mymodule
+├── config
+│   ├── a.cue
+│   └── b.cue
+├── cue.mod
+│   ├── module.cue
+│   ├── pkg
+│   └── usr
+└── main.cue
+```
+
+`cue.mod/` and the files underneath it were created by `cue mod init example.com/mymodule`. I then created the `config/` subdirectory with `a.cue` and `b.cue` inside. Then I created `main.cue` to act as my top-level file to rule them all.
+
+Running `eval` (no arguments) checks to see if there's only one package in all .cue files in the current directory, and if so, it unifies them and outputs the result. In this case, there's only main.cue with package `main` (nothing special about "main" there, it just seemed appropriate), so that's the one.
+
+```bash
+% cue eval
+configuredBar: 200
+```
+
+The contents of `main.cue` is:
+
+```yaml
+//main.cue
+
+package main
+import "example.com/mymodule/config"
+
+configuredBar: config.bar
+```
+
+`config/a.cue` and `config/b.cue` are files from earlier, except now they've both got `package config` at the top:
+
+```yaml
+//a.cue
+package config
+
+foo: 100
+bar: int
+```
+
+```yaml
+//b.cue
+package config
+
+bar: 200
+```
+
+So there you go. If you want to verify that it's actually unifying both files under `config/`, you can change `bar: int` to `bar: string` in `a.cue` and re-run `cue eval` to get a nice type error:
+
+```
+cue eval 2022-01-06 17:51:24
+configuredBar: conflicting values string and 200 (mismatched types string and int):
+ ./config/a.cue:4:6
+ ./config/b.cue:3:6
+ ./main.cue:5:16
+```
+
+That's it for now. I understand there are more package management features coming in the future and the design decisions around `cue.mod` are looking ahead to that.
+
+Finally, CUE has built-in modules with powerful functionality. We saw one of these earlier, when we imported "strings" and used `strings.ToLower`. Imports without fully-qualified module names are assumed to be built-ins. The full list and documentation for each is here: https://pkg.go.dev/cuelang.org/go/pkg
+
+This has been a condensation of the official docs and tutorials, so go give the source material some love: https://cuelang.org/docs/tutorials/
diff --git a/dart.html.markdown b/dart.html.markdown
index 69e1623d..ab3c07d2 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -45,7 +45,7 @@ const CONSTANT_VALUE = "I CANNOT CHANGE";
CONSTANT_VALUE = "DID I?"; //Error
/// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions
/// `final` can be declared in pascalCase.
-final finalValue = "value cannot be change once instantiated";
+final finalValue = "value cannot be changed once instantiated";
finalValue = "Seems not"; //Error
/// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type
@@ -79,7 +79,8 @@ example1() {
/// Anonymous functions don't include a name
example2() {
- nested1(fn) {
+ //// Explicit return type.
+ nested1(void Function() fn) {
fn();
}
nested1(() => print("Example2 nested 1"));
diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown
index e3f64a00..d0a62c66 100644
--- a/de-de/asciidoc-de.html.markdown
+++ b/de-de/asciidoc-de.html.markdown
@@ -4,15 +4,19 @@ contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
-filename: asciidoc-de.md
+filename: asciidoc-de.adoc
lang: de-de
---
-AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an Anpassungen.
+AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles
+verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart
+Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an
+Anpassungen.
Kopfzeile des Dokuments
-Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen mindestens eine Leerzeile vom Inhalt versetzt sein.
+Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen
+mindestens eine Leerzeile vom Inhalt versetzt sein.
Nur Titel
@@ -104,7 +108,8 @@ Um eine nummerierte Liste zu erstellen, verwendest du Punkte.
. item 3
```
-Um Listen zu verschachteln, musst du zusätzliche Sternchen beziehungsweise Punkte hinzufügen. Dies ist bis zu fünf Mal möglich.
+Um Listen zu verschachteln, musst du zusätzliche Sternchen beziehungsweise
+Punkte hinzufügen. Dies ist bis zu fünf Mal möglich.
```
* foo 1
diff --git a/de-de/brainfuck-de.html.markdown b/de-de/brainfuck-de.html.markdown
index dd62dd67..09f01cd2 100644
--- a/de-de/brainfuck-de.html.markdown
+++ b/de-de/brainfuck-de.html.markdown
@@ -1,11 +1,11 @@
---
-language: brainfuck
+language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["urfuchs", "https://github.com/urfuchs"]
-filename: brainfuck-de
+filename: brainfuck-de.bf
lang: de-de
---
diff --git a/de-de/c++-de.html.markdown b/de-de/c++-de.html.markdown
index 87e75ad6..cca54c30 100644
--- a/de-de/c++-de.html.markdown
+++ b/de-de/c++-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-de.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown
index f9090518..3a726b83 100644
--- a/de-de/c-de.html.markdown
+++ b/de-de/c-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: c
+language: C
filename: learnc-de.c
contributors:
- ["caminsha", "https://github.com/caminsha"]
diff --git a/de-de/crystal-de.html.markdown b/de-de/crystal-de.html.markdown
new file mode 100644
index 00000000..535267ee
--- /dev/null
+++ b/de-de/crystal-de.html.markdown
@@ -0,0 +1,561 @@
+---
+language: crystal
+contributors:
+ - ["Vitalii Elenhaupt", "http://veelenga.com"]
+ - ["Arnaud Fernandés", "https://github.com/TechMagister/"]
+translators:
+ - ["caminsha", "https://github.com/caminsha"]
+filename: learncrystal-de.cr
+lang: de-de
+---
+
+```crystal
+
+# Das ist ein Kommentar
+
+# Alles ist ein Objekt
+nil.class # => Nil
+100.class # => Int32
+true.class # => Bool
+
+# Falschwerte sind: nil, false und Nullpointer
+!nil # => true : Bool
+!false # => true : Bool
+!0 # => false : Bool
+
+# Integer
+
+1.class # => Int32
+
+# Fünf vorzeichenbehaftete Ganzzahlen
+1_i8.class # => Int8
+1_i16.class # => Int16
+1_i32.class # => Int32
+1_i64.class # => Int64
+1_i128.class # => Int128
+
+# Fünf vorzeichenlose Ganzzahlen
+1_u8.class # => UInt8
+1_u16.class # => UInt16
+1_u32.class # => UInt32
+1_u64.class # => UInt64
+1_u128.class # => UInt128
+
+
+2147483648.class # => Int64
+9223372036854775808.class # => UInt64
+
+# Binäre Zahlen
+0b1101 # => 13 : Int32
+
+# Oktalzahlen
+0o123 # => 83 : Int32
+
+# Hexadezimalzahlen
+0xFE012D # => 16646445 : Int32
+0xfe012d # => 16646445 : Int32
+
+# Gleitkommazahlen (floats)
+
+1.0.class # => Float64
+
+# Es gibt zwei Typen von Gleitkommazahlen
+
+1.0_f32.class # => Float32
+1_f32.class # => Float32
+
+1e10.class # => Float64
+1.5e10.class # => Float64
+1.5e-7.class # => Float64
+
+
+# Chars (einzelne Zeichen)
+
+'a'.class # => Char
+
+# Oktale Schreibweise
+'\101' # => 'A' : Char
+
+# Unicode Schreibweise
+'\u0041' # => 'A' : Char
+
+# Strings (Zeichenketten)
+"s".class # => String
+
+# Strings sind unveränderlich
+s = 'hello, " # => "hello, " : String
+s.object_id # => 1234667712 : UInt64
+s += "Crystal" # => "hello, Crystal" : String
+s.object_id # => 142528472 : UInt64
+
+# Interpolation wird unterstützt
+"sum = #{1 + 2}" # => "sum = 3" : String
+
+# Mehrzeilige Strings
+" Dies ist ein
+ mehrzeiliger String."
+
+# String mit doppeltem Anführungszeichen
+%(hello "world") # => "hello \"world\""
+
+# Symbole
+# Unveränderbare, wiederverwendbare Konstanten, welche intern als Int32 Integer
+# Werte repräsentiert werden.
+# Symbole werden oft anstelle von Strings verwendet, um bestimmte Werte zu bestimmen.
+
+:symbol.class # => Symbol
+
+sentence = :question? # :"question?" : Symbol
+
+sentence = :question? # => true : Bool
+sentence = :exclamation! # => false : Bool
+sentence = "question?" # => false : Bool
+
+# Arrays
+[1, 2, 3].class # => Array(Int32)
+[1, "hello", 'x'].class # => Array(Int32 | String | Char)
+
+# Leere Arrays sollten einen Typen definieren
+[] # => Syntaxfehler: für leere Arrays,
+ # verwende `[] of ElementType`
+[] of Int32 # => [] : Array(Int32)
+Array(Int32).new # => [] : Array(Int32)
+
+# Arrays können indiziert werden
+array = [1, 2, 3, 4, 5] # => [1, 2, 3, 4, 5] : Array(Int32)
+array[0] # => 1 : Int32
+array[10] # führt zu einem IndexError
+array[-6] # führt zu einem IndexError
+array[10]? # => nil : (Int32 | Nil)
+array[-6]? # => nil : (Int32 | Nil)
+
+# Starte am Ende des Arrays
+array[-1] # => 5
+
+# Mit einem Startindex und einer Länge
+array[2, 4] # => [3, 4, 5]
+
+# oder mit einem Bereich
+array[1..3] # => [2, 3, 4]
+
+# Füge etwas zu einem Array hinzu
+array << 6 # => [1, 2, 3, 4, 5, 6]
+
+# Entferne Einträge am Ende des Arrays
+array.pop # => 6
+array # => [1, 2, 3, 4, 5]
+
+# Entferne ersten Eintrag im Array
+array.shift # => 1
+array # => [2, 3, 4, 5]
+
+# Überprüfe, ob ein Element in einem Array existiert
+array.includes? 3 # => true
+
+# Spezielle Syntax für String-Arrays und Symbol-Arrays
+%w(one two three) # => ["one", "two", "three"] : Array(String)
+%i(one two three) # 0> [:one, :two, :three] : Array(Symbol)
+
+# Es gibt auch für andere Arrays eine spezielle Syntax, wenn die Methoden
+# `.new` und `#<<` definiert werden.
+set = Set{1, 2, 3} # => [1, 2, 3]
+set.class # => Set(Int32)
+
+# Das obere ist äquivalent zu:
+set = Set(typeof(1, 2, 3)).new
+set << 1
+set << 2
+set << 3
+
+# Hashes
+{1 => 2, 3 => 4}.class # => Hash(Int32, Int32)
+{1 => 2, 'a' => 3}.class # => Hash (Int32 | Char, Int32)
+
+# Leere Hashes sollten einen Typen spezifieren
+{} # Syntaxfehler
+{} of Int32 => Int32 # {}
+Hash(Int32, Int32).new # {}
+
+# Hashes können schnell mit dem Key nachgeschaut werden
+hash = {"color" => "green", "number" => 5}
+hash["color"] # => "green"
+hash["no_such_key"] # => Fehlender hash key: "no_such_key" (KeyError)
+hash["no_such_key"]? # => nil
+
+# Überprüfe die Existenz eines Hashkeys
+hash.has_key? "color" # => true
+
+# Spezielle Schreibweise für Symbol- und Stringkeys
+{key1: 'a', key2: 'b'} # {:key1 => 'a', :key2 => 'b'}
+{"key1": 'a', "key2": 'b'} # {"key1" => 'a', "key2" => 'b'}
+
+# Die spezielle Syntax für Hash-Literale gibt es auch für andere Typen, sofern
+# diese die Methoden `.new` und `#[]=` Methoden definieren.
+class MyType
+ def []=(key, value)
+ puts "do stuff"
+ end
+end
+
+MyType{"foo" => "bar"}
+
+# Das obere ist äquivalent zu:
+tmp = MyType.new
+tmp["foo"] = "bar"
+tmp
+
+# Ranges (Bereiche)
+1..10 # => Range(Int32, Int32)
+Range.new(1,10).class # => Range(Int32, Int32)
+
+# Ranges können inklusiv oder exklusiv sein.
+(3..5).to_a # => [3, 4, 5]
+(3...5).to_a # => [3, 4]
+
+# Überprüfe, ob ein Range einen Wert enthält oder nicht.
+(1..8).includes? 2 # => true
+
+# Tupel sind unveränderliche, Stack-zugewiese Folgen von Werten mit fester
+# Größe und möglicherweise unterschiedlichen Typen
+{1, "hello", 'x'}.class # => Tuple(Int32, String, Char)
+
+# Erhalte den Wert eines Tupels über den Index
+tuple = {:key1, :key2}
+tuple[1] # => :key2
+tuple[2] # syntax error: Index out of bound
+
+# Können auf mehrere Variablen erweitert werden
+a, b, c = {:a, 'b', "c"}
+a # => :a
+b # => 'b'
+c # => "c"
+
+# Procs repräsentieren ein Funktionspointer mit einem optionalen Kontext.
+# Normalerweise wird ein Proc mit einem proc-Literal erstellt.
+proc = ->(x : Int32) { x.to_s }
+proc.class # => Print(Int32, String)
+# Außerdem kann man auch mit der Methode `new` ein Proc erstellen.
+Proc(Int32, String).new { |x| x.to_s }
+
+# Rufe ein Proc auf mit der Methode `call`
+proc.call 10 # => "10"
+
+# Kontrollstatements
+
+if true
+ "if statement"
+elsif false
+ "else-f, optional"
+else
+ "else, auch optional"
+end
+
+puts "if as a suffix" if true # => if as a suffix
+
+# If als Ausdruck
+a = if 2 > 1
+ 3
+ else
+ 4
+ end
+
+a # => 3
+
+# Bedingter ternärer Ausdruck
+a = 1 > 2 ? 3 : 4 # => 4
+
+# Case-Statement
+cmd = "move"
+
+action = case cmd
+ when "create"
+ "Creating..."
+ when "copy"
+ "Copying..."
+ when "move"
+ "Moving..."
+ when "delete"
+ "Deleting..."
+end
+
+action # => "Moving..."
+
+# Schleifen
+index = 0
+while index <= 3
+ puts "Index: #{index}"
+ index += 1
+end
+# Index: 0
+# Index: 1
+# Index: 2
+# Index: 3
+
+index = 0
+until index > 3
+ puts "Index: #{index}"
+ index += 1
+end
+# Index: 0
+# Index: 1
+# Index: 2
+# Index: 3
+
+# Der bevorzugte Weg, ist `each` zu verwenden.
+(1..3).each do |index|
+ puts "Index: #{index}"
+end
+# Index: 1
+# Index: 2
+# Index: 3
+
+# Der Typ der Variablen hängt vom Typen innerhalb der Kontrollanweisung ab
+if a < 3
+ a = "hello"
+else
+ a = true
+end
+typeof a # => (Bool | String)
+
+if a && b
+ # Hier wird garantiert, dass weder a noch b vom Typ Nil sind
+end
+
+if a.is_a? String
+ a.class # => String
+end
+
+# Funktionen
+def double(x)
+ x * 2
+end
+
+# Funktionen geben implizit den Wert der letzten Anweisung zurück
+# Dies ist auch bei anderen Blöcken der Fall.
+double(2) # => 4
+
+# Klammern müssen nicht gesetzt werden, wenn der Aufruf eindeutig ist
+double 3 # => 6
+double double 3 # => 12
+
+def sum(x, y)
+ x + y
+end
+
+# Funktionsargumente werden mit einem Komma separiert.
+sum 3, 4 # => 7
+
+sum sum(3, 4), 5 # => 12
+
+# yield
+# Alle Methoden haben einen impliziten, optionalen Blockparameter.
+# Dieser kann mit dem Schlüsselwort `yield` aufgerufen werden.
+
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+
+surround { puts "Hallo Welt" }
+
+# {
+# Hallo Welt
+# }
+
+# Du kannst ein Block einer Funktion übergeben.
+# "&" kennzeichnet eine Referenz zu einem übergebenen Block
+def guests(&block)
+ block.call "some_argument"
+end
+
+# Du kannst eine Liste von Argumenten mitgeben, welche zu einem Array
+# umgewandelt werden.
+# Hierfür ist der Splat-Operator ("*")
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+
+# Wenn eine Methode ein Array zurückgibt, kann destrukturiende Zuordnung
+# verwendet werden.
+def foods
+ ["pancake", "sandwich", "quesadilla"]
+end
+breakfast, lunch, dinner = foods
+breakfast # => "pancake"
+dinner # => "quesadilla"
+
+# Gemäß der Konvention enden alle Methoden, welchen einen Boolean zurückgeben
+# mit einem Fragezeichen.
+5.even? # false
+5.odd? # true
+
+# Und wenn eine Methode mit einem Ausrufezeichen endet, macht sie etwas
+# destruktives. Zum Beispiel wird der Aufrufer verändert. Einige Methoden haben
+# eine !-Version, um eine Änderung zu machen und eine Nicht-!-Version, welche
+# lediglich eine neue veränderte Version zurückgibt.
+
+company_name = "Dunder Mifflin"
+company_name.gsub "Dunder", "Donald" # => "Donald Mifflin"
+company_name # => "Dunder Mifflin"
+company_name.gsub! "Dunder", "Donald"
+company_name # => "Donald Mifflin"
+
+# definiere eine Klasse mit dem Schlüsselwort `class`.
+class Human
+
+# eine Klassenvariable. Diese wird mit allen Instanzen dieser Klasse geteilt.
+ @@species = "H. sapiens"
+
+ # type of name is String
+ @name: String
+
+ # Grundlegender Intialisierer
+ # Weise das Argument der Instanz-Variable "name" zu
+ # Wenn kein Alter angegeben wird, wird der Default (hier 0) genommen.
+ def initialize(@name, @age = 0)
+ end
+
+ # Einfache Setter-Methode
+ def name=(name)
+ @name = name
+ end
+
+ # einfache Getter-Methode
+ def name
+ @name
+ end
+
+ # Die obere Funktionalität kann mit der property-Methode gekapselt werden:
+ property :name
+
+ # Getter/Setter-Methoden können auch individuell erstellt werden:
+ getter :name
+ setter :name
+
+ # eine Klassenmethode verwendet `self` um sich von Instanzmethoden zu
+ # unterscheiden. Diese kann lediglich von einer Klasse aufgerufen werden,
+ # nicht von einer Instanz.
+ def self.say(msg)
+ puts msg
+ end
+
+ def species
+ @@species
+ end
+end
+
+
+# Eine Klasse instanzieren
+jim = Human.new("Jim Halpert")
+
+dwight = Human.new("Dwight K. Schrute")
+
+# Lass uns ein paar Methoden aufrufen
+jim.species # => "H. sapiens"
+jim.name # => "Jim Halpert"
+jim.name = "Jim Halpert II" # => "Jim Halpert II"
+jim.name # => "Jim Halpert II"
+dwight.species # => "H. sapiens"
+dwight.name # => "Dwight K. Schrute"
+
+# Rufe die Klassenmethode auf
+Human.say("Hi") # => gibt Hi aus und gibt `nil` zurück
+
+# Variablen, welche mit @ starten, sind im Scope der Instanz
+class TestClass
+ @var = "Ich bin eine Instanzvariable"
+end
+
+# Variablen, welche mit @@ starten, sind im Scope der Klasse
+class TestClass
+ @@var = "Ich bin eine Klassenvariable"
+end
+
+# Variablen, welche mit einem Großbuchstaben starten, sind Konstanten.
+Var = "Ich bin eine Konstante"
+Var = "Ich kann nicht aktualisiert werden." # Die Konstante Var wurde bereits
+ # initialisiert.
+
+# In Crystal ist Class auch ein Objekt. Dadurch können Klassen Instanzvariablen
+# haben. Klassenvariablen werden mit der Klasse und allen Subklassen geteilt.
+
+# Basisklasse
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# abgeleitete Klasse
+class Worker < Human
+end
+
+Human.foo # => 0
+Worker.foo # => 0
+
+Human.foo = 2 # => 2
+Worker.foo # => 0
+
+Worker.foo = 3 # => 3
+Human.foo # => 2
+Worker.foo # => 3
+
+module ModuleExample
+ def foo
+ "foo"
+ end
+end
+
+# Wenn ein Modul mit include eingeschlossen wird, so werden die Methoden an die
+# Instanzen gebunden.
+# Wenn eine Klasse mit einem Modul erweitert wird, so werden die Methoden an die
+# Klasse selbst gebunden.
+
+class Person
+ include ModuleExample
+end
+
+class Book
+ extend ModuleExample
+end
+
+Person.foo # => undefinierte Methode 'foo' für Person:Class
+Person.new.foo # => 'foo'
+Book.foo # => 'foo'
+Book.new.foo # => undefinierte Methode für Book
+
+# Ausnahmebehandlung
+
+# Definiere eine neue Ausnahme
+class MyException < Exception
+end
+
+# Definiere eine weitere Ausnahme
+class MyAnotherException < Exception; end
+
+ex = begin
+ raise MyException.new
+rescue ex1 : IndexError
+ "ex1"
+rescue ex2 : MyException | MyAnotherException
+ "ex2"
+rescue ex3 : Exception
+ "ex3"
+rescue ex4 # fange alle Ausnahmen ab
+ "ex4"
+end
+
+ex # => "ex2"
+```
+
+
+## Weitere Unterlagen
+
+- [offizielle Dokumentation, englisch](https://crystal-lang.org/)
diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
index 78bb0a6b..18a23017 100644
--- a/de-de/csharp-de.html.markdown
+++ b/de-de/csharp-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown
index 254cca51..ec933696 100644
--- a/de-de/elixir-de.html.markdown
+++ b/de-de/elixir-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
translators:
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index 0896f513..3065a033 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -385,6 +385,4 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/)
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index 9409e181..1b09a1e1 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -82,7 +82,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
// nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel.
g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points.
- f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl
+ f := 3.14159 // float64, eine IEEE-754 64-bit Dezimalzahl
c := 3 + 4i // complex128, besteht intern aus zwei float64-er
// "var"-Syntax mit Initalwert
@@ -308,13 +308,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
```
## Weitere Resourcen
-Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/).
+Informationen zu Go findet man auf der [offiziellen Go Webseite](https://go.dev/).
Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor
allem aber Dokumentation zur Sprache und den Paketen.
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
-ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/)
+ist außerdem der Quelltext der [Go standard Bibliothek](https://go.dev/src/)
einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil
verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
-in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
+in der [offiziellen Dokumentation von Go](https://go.dev/pkg/).
diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown
index c86494ce..10172d6b 100644
--- a/de-de/pug-de.html.markdown
+++ b/de-de/pug-de.html.markdown
@@ -162,13 +162,13 @@ case bestellungsStatus
//- <p class="warn">Deine Bestellung steht noch aus</p>
//- --INCLUDE--
-//- File path -> "includes/nav.png"
+//- File path -> "includes/nav.pug"
h1 Firmenname
nav
a(href="index.html") Home
a(href="about.html") Ãœber uns
-//- Dateipfad -> "index.png"
+//- Dateipfad -> "index.pug"
html
body
include includes/nav.pug
diff --git a/de-de/pyqt-de.html.markdown b/de-de/pyqt-de.html.markdown
index 93ee20d4..3b9b6ebb 100644
--- a/de-de/pyqt-de.html.markdown
+++ b/de-de/pyqt-de.html.markdown
@@ -21,7 +21,7 @@ Diese Version wurde in pyqt erstellt.
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Erschafft ein Anwendungsobjekt.
app = QtGui.QApplication(sys.argv)
@@ -48,10 +48,10 @@ if __name__ == '__main__':
Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können,
müssen wir anfangen zusätzliche Elemente zu bauen.
-Hier zeigen wir wie man eine Dialog Popup Box einführt.
+Hier zeigen wir wie man eine Dialog Popup Box einführt.
Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -70,7 +70,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen.
# Der Knopf wartet bis er geklickt wird und beendet das Programm
def showdialog():
diff --git a/de-de/qt-de.html.markdown b/de-de/qt-de.html.markdown
index 480030fe..7d287cab 100644
--- a/de-de/qt-de.html.markdown
+++ b/de-de/qt-de.html.markdown
@@ -1,7 +1,7 @@
---
category: tool
tool: Qt Framework
-language: c++
+language: C++
filename: learnqt-de.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown
index 02bb460a..6208db68 100644
--- a/de-de/rust-de.html.markdown
+++ b/de-de/rust-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown
index 8abf9a14..d0b4eb9d 100644
--- a/de-de/vim-de.html.markdown
+++ b/de-de/vim-de.html.markdown
@@ -3,95 +3,92 @@ category: tool
tool: vim
lang: de-de
contributors:
- - ["RadhikaG", "https://github.com/RadhikaG"]
+- ["RadhikaG", "https://github.com/RadhikaG"]
translators:
- - ["caminsha", "https://github.com/caminsha"]
+- ["caminsha", "https://github.com/caminsha"]
filename: LearnVim-de.txt
---
-
[Vim](http://www.vim.org)
(Vi IMproved) ist ein Klon von vi, dem bekannten Editor für Unix. Es ist ein
-Texteditor, welcher mit Fokus auf Geschwindigkeit und Prouktivität entwickelt
-wurde.
-Vim hat viele Keybindings für ein schnelles navigieren und schnelles bearbeiten
-einer Datei.
+Texteditor, welcher mit Fokus auf Geschwindigkeit und Produktivität entwickelt
+wurde. Vim hat viele Keybindings für ein schnelles navigieren und schnelles
+bearbeiten einer Datei.
## Grundlagen, um in Vim zu navigieren
```
- vim <filename> # Öffne <filename> in Vim
- :help <topic> # Open up built-in help docs about <topic> if any exists
- :help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
- # es existiert
- :q # Schließe vim
- :w # Speichere diese Datei
- :wq # Speichere diese Datei und schließe vim
- ZZ # Speichere diese Datei und schließe vim
- :q! # Schließe vim ohne die Datei zu speichern
- # ! *zwingt* die Ausführung von :q,
- # daher wird die Datei nicht gespeichert.
- ZQ # Beende vim ohne die Datei zu speichern
- :x # Speichere die Datei und beende vim
- # Dies ist eine kürzere Version von :wq
-
- u # Änderung rückgängig machen
- CTRL+R # Änderung wiederherstellen
-
- h # Den Cursor um ein Zeichen nach links bewegen
- j # Den Cursor eine Zeile nach unten bewegen
- k # Den Cursor eine Zeile nach oben bewegen
- l # Den Cursor um ein Zeichen nach rechts bewegen
-
- Ctrl+B # Gehe eine Bildschirmanzeige zurück
- Ctrl+F # Gehe eine Bildschirmanzeige vorwärts
- Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts
- Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück
-
- # Navigieren innerhalb einer Zeile
-
- 0 # Navigiere zum Anfang der Zeile
- $ # Navigiere zum Ende der Zeile
- ^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist
-
- # Im Text suchen
-
- /word # Hebt alle Ergebnisse nach dem Cursor hervor
- ?word # Hebt alle Ergebnisse vor dem Cursor hervor
- n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche
- N # Bewegt den Cursor zum vorherigen Ergebnis der Suche
-
- :%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen
- :s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile
- :%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch
- # ein carriage return
-
- # Zu einzelnen Zeichen springen
-
- f<character> # Springe vorwärts und auf dem Zeichen <character>
- t<character> # Springe vorwärts und lande vor dem Zeichen <character>
-
- # Zum Beispiel,
- f< # Springe vorwärts und lande auf <
- t< # Springe vorwärts und lande vor <
-
- # Wortweise navigieren
-
- w # Springe um ein Wort vorwärts
- b # Gehe ein Wort zurück
- e # Springe zum Ende des aktuellen Wortes
-
- # Weitere Befehle, um zu navigieren
-
- gg # Gehe an den Start der Datei
- G # Gehe an das Ende der Datei
- :NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein)
- H # Navigiere zum Start der aktuellen Bildschirmanzeige
- M # Navigiere in die Mitte der aktuellen Bildschirmanzeige
- L # Navigiere an das Ende der aktuellen Bildschirmanzeige
+vim <filename> # Öffne <filename> in Vim
+:help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
+ # es existiert
+:q # Schließe vim
+:w # Speichere diese Datei
+:wq # Speichere diese Datei und schließe vim
+ZZ # Speichere diese Datei und schließe vim
+:q! # Schließe vim ohne die Datei zu speichern
+ # ! *zwingt* die Ausführung von :q,
+ # daher wird die Datei nicht gespeichert.
+ZQ # Beende vim ohne die Datei zu speichern
+:x # Speichere die Datei und beende vim
+ # Dies ist eine kürzere Version von :wq
+
+u # Änderung rückgängig machen
+CTRL+R # Änderung wiederherstellen
+
+h # Den Cursor um ein Zeichen nach links bewegen
+j # Den Cursor eine Zeile nach unten bewegen
+k # Den Cursor eine Zeile nach oben bewegen
+l # Den Cursor um ein Zeichen nach rechts bewegen
+
+Ctrl+B # Gehe eine Bildschirmanzeige zurück
+Ctrl+F # Gehe eine Bildschirmanzeige vorwärts
+Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts
+Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück
+
+# Navigieren innerhalb einer Zeile
+
+0 # Navigiere zum Anfang der Zeile
+$ # Navigiere zum Ende der Zeile
+^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist
+
+# Im Text suchen
+
+/word # Hebt alle Ergebnisse nach dem Cursor hervor
+?word # Hebt alle Ergebnisse vor dem Cursor hervor
+n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche
+N # Bewegt den Cursor zum vorherigen Ergebnis der Suche
+
+:%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen
+:s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile
+:%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch
+ # ein carriage return
+
+# Zu einzelnen Zeichen springen
+
+f<character> # Springe vorwärts und auf dem Zeichen <character>
+t<character> # Springe vorwärts und lande vor dem Zeichen <character>
+
+# Zum Beispiel,
+f< # Springe vorwärts und lande auf <
+t< # Springe vorwärts und lande vor <
+
+# Wortweise navigieren
+
+w # Springe um ein Wort vorwärts
+b # Gehe ein Wort zurück
+e # Springe zum Ende des aktuellen Wortes
+
+# Weitere Befehle, um zu navigieren
+
+gg # Gehe an den Start der Datei
+G # Gehe an das Ende der Datei
+:NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein)
+H # Navigiere zum Start der aktuellen Bildschirmanzeige
+M # Navigiere in die Mitte der aktuellen Bildschirmanzeige
+L # Navigiere an das Ende der aktuellen Bildschirmanzeige
```
-## Hilfsdokumente:
+## Hilfsdokumente
Vim hat eine eingebaute Dokumentation, welche mit `:help <topic>` aufgerufen
werden kann.
@@ -99,34 +96,33 @@ Zum Beispiel öffnet `:help navigation` die Dokumentation über das Navigieren
`:help` kann auch ohne ein Argument verwendet werden. Dies zeigt den Standard-
Hilfsdialog an, welcher den Start mit vim einfacher macht.
-that aims to make getting started with vim more approachable!
-## Modi:
+## Modi
Vim basiert auf dem Konzept von **modes**.
-- Command Mode - Vim startet in diesem Modus, hier kann man navigieren und Befehle eingeben
+- Command Mode - Vims erster Modus, hier kann man navigieren und Befehle eingeben
- Insert Mode - Wird verwendet, um Änderungen in der Datei zu machen.
-- Visual Mode - Wird verwendet, um Text zu markieren und Operationen durchzuführen
+- Visual Mode - Wird verwendet, um Text zu markieren und diesen zu verändern
- Ex Mode - Wird verwendet, um im ':'-Prompt Befehle einzugeben
```
- i # Führt vim in den Insert Mode, vor der Cursorposition
- a # Führt vim in den Insert Mode, nach der Cursorposition
- v # Führt vim in den Visual Mode
- : # Führt vim in den Ex Mode
- <esc> # Führt zurück in den Command Mode, egal in welchem Mode
- # man sich gerade befindet.
-
- # Kopieren und einfügen von Text
-
- y # Kopiere alles, was im Moment ausgewählt ist
- yy # Kopiert die aktuelle Zeile
- d # Löscht alles, was im Moment ausgewählt ist
- dd # Löscht die aktuelle Zeile
- p # Fügt den kopierten Text nach dem Cursor ein
- P # Fügt den kopierten Text vor dem Cursor ein
- x # Löscht das Zeichen unter dem Cursor
+i # Führt vim in den Insert Mode, vor der Cursorposition
+a # Führt vim in den Insert Mode, nach der Cursorposition
+v # Führt vim in den Visual Mode
+: # Führt vim in den Ex Mode
+<esc> # Führt zurück in den Command Mode, egal in welchem Mode
+ # man sich gerade befindet.
+
+# Kopieren und einfügen von Text
+
+y # Kopiere alles, was im Moment ausgewählt ist
+yy # Kopiert die aktuelle Zeile
+d # Löscht alles, was im Moment ausgewählt ist
+dd # Löscht die aktuelle Zeile
+p # Fügt den kopierten Text nach dem Cursor ein
+P # Fügt den kopierten Text vor dem Cursor ein
+x # Löscht das Zeichen unter dem Cursor
```
## Die 'Grammatik' von Vim
@@ -141,68 +137,67 @@ Vim kann als Satz von Kommandos angesehen werden, welche im Format
Einige wichtige Beispiele von 'Verb', 'Modifier' und 'Nouns':
```
- # 'Verb'
-
- d # löschen
- c # ändern
- y # kopieren
- v # visuelles auswählen
-
- # 'Modifiers'
-
- i # innerhalb
- a # außerhalb
- NUM # Nummer (NUM kann irgendeine Zahl sein)
- f # Sucht nach etwas und landet darauf
- t # Sucht nach etwas und stoppt davor
- / # Suche eine Zeichenfolge ab dem Cursor
- ? # Suche eine Zeichenfolge vor dem Cursor
-
- # 'Nouns'
-
- w # Wort
- s # Satz
- p # Abschnitt
- b # Block
-
- # Beispielsätze resp. Kommandos
-
- d2w # lösche zwei Wörter
- cis # Ändere innerhalb des Satzes.
- yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt,
- # in welchem du bist)
- ct< # Ändere bis zur spitzen Klammer
- # Ändere den Text von deiner aktuellen Cursorposition bis
- # zur nächsten spitzen Klammer
- d$ # Lösche bis zum Ende der Zeile
+# 'Verb'
+
+d # löschen
+c # ändern
+y # kopieren
+v # visuelles auswählen
+
+# 'Modifiers'
+
+i # innerhalb
+a # außerhalb
+NUM # Nummer (NUM kann irgendeine Zahl sein)
+f # Sucht nach etwas und landet darauf
+t # Sucht nach etwas und stoppt davor
+/ # Suche eine Zeichenfolge ab dem Cursor
+? # Suche eine Zeichenfolge vor dem Cursor
+
+# 'Nouns'
+
+w # Wort
+s # Satz
+p # Abschnitt
+b # Block
+
+# Beispielsätze resp. Kommandos
+
+d2w # lösche zwei Wörter
+cis # Ändere innerhalb des Satzes.
+yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt,
+ # in welchem du bist)
+ct< # Ändere bis zur spitzen Klammer
+ # Ändere den Text von deiner aktuellen Cursorposition bis
+ # zur nächsten spitzen Klammer
+d$ # Lösche bis zum Ende der Zeile
```
## Einige Shortcuts und Tricks
```
- > # Rücke die Auswahl um einen Block ein
- < # Lösche eine Einrückung der Auswahl
- :earlier 15m # Stellt das Dokument so wieder her, wie es vor 15
- # Minuten war
- :later 15m # den oberen Befehl rückgängig machen
- ddp # Vertauschen zweier aufeinanderfolgenden Zeilen
- # Zuerst dd, dann p
- . # Wiederhole die vorherige Aktion
- :w !sudo tee % # Speichere die Datei als Root
- :set syntax=c # Stelle das Syntax-Highlighting für 'C' ein
- :sort # Alle Zeilen sortieren
- :sort! # Alle Zeilen rückwärts sortieren
- :sort u # Alle Zeilen sortieren und Duplikate entfernen
- ~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes
- u # Ausgewählten Text zu Kleinschreibung ändern
- U # Ausgewählten Text zu Großschreibung ändern
-
- # Text-Folding (Textfaltung)
- zf # Erstelle eine Faltung des ausgewählten Textes
- zo # Öffne die aktuelle Faltung
- zc # Schließe die aktuelle Faltung
- zR # Öffne alle Faltungen
- zM # Schließe alle Faltungen
+> # Rücke die Auswahl um einen Block ein
+< # Lösche eine Einrückung der Auswahl
+:earlier 15m # Stellt das Dokument so wieder her, wie es vor 15 Minuten war
+:later 15m # den oberen Befehl rückgängig machen
+ddp # Vertauschen zweier aufeinanderfolgenden Zeilen
+ # Zuerst dd, dann p
+. # Wiederhole die vorherige Aktion
+:w !sudo tee % # Speichere die Datei als Root
+:set syntax=c # Stelle das Syntax-Highlighting für 'C' ein
+:sort # Alle Zeilen sortieren
+:sort! # Alle Zeilen rückwärts sortieren
+:sort u # Alle Zeilen sortieren und Duplikate entfernen
+~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes
+u # Ausgewählten Text zu Kleinschreibung ändern
+U # Ausgewählten Text zu Großschreibung ändern
+
+# Text-Folding (Textfaltung)
+zf # Erstelle eine Faltung des ausgewählten Textes
+zo # Öffne die aktuelle Faltung
+zc # Schließe die aktuelle Faltung
+zR # Öffne alle Faltungen
+zM # Schließe alle Faltungen
```
## Makros
@@ -213,9 +208,9 @@ Kommandos, welche du braucht, aufgenommen bis die Aufnahme gestoppt wird.
Wenn du ein Makro ausführst, werden exakt die gleichen Schritte gemacht.
```
- qa # Starte das Aufnehmen des Makros 'a'
- q # Beende das Aufnehmen
- @a # Führe das Makro 'a' aus
+qa # Starte das Aufnehmen des Makros 'a'
+q # Beende das Aufnehmen
+@a # Führe das Makro 'a' aus
```
### Konfigurieren mit ~/.vimrc
diff --git a/de-de/visualbasic-de.html.markdown b/de-de/visualbasic-de.html.markdown
new file mode 100644
index 00000000..6194e906
--- /dev/null
+++ b/de-de/visualbasic-de.html.markdown
@@ -0,0 +1,290 @@
+---
+language: Visual Basic
+contributors:
+ - ["Brian Martin", "http://brianmartin.biz"]
+translators:
+ - ["Enno Nagel", "https://github.com/konfekt"]
+filename: learnvisualbasic-de.vb
+lang: de-de
+---
+
+```visualbasic
+Module Modul1
+
+Sub Main()
+ ' Ein kurzer Blick auf Visual Basic-Konsolenanwendungen
+ ' bevor wir tiefer in das Thema eintauchen.
+ ' Das Hochkomma leitet eine Kommentarzeile ein.
+ ' Um dieses Tutorial innerhalb des Visual Basic Compilers zu erkunden,
+ ' habe ich ein Navigationssystem erstellt.
+ ' Dieses System wird im weiteren Verlauf des Tutorials erklärt;
+ ' Sie werden nach und nach verstehen, was das alles bedeutet.
+ Console.Title = ("Lerne X in Y Minuten")
+ Console.WriteLine ("NAVIGATION") 'Anzeige
+ Console.WriteLine ("")
+ Console.ForegroundColor = ConsoleColor.Green
+ Console.WriteLine ("1. Ausgabe von 'Hallo, Welt'")
+ Console.WriteLine ("2. Eingabe 'Hallo, Welt'")
+ Console.WriteLine ("3. ganze Zahlen berechnen")
+ Console.WriteLine ("4. Berechne Dezimalzahlen")
+ Console.WriteLine ("5. ein funktionaler Taschenrechner")
+ Console.WriteLine ("6. 'Do While'-Schleifen verwenden")
+ Console.WriteLine ("7. Verwendung von 'For While'-Schleifen")
+ Console.WriteLine ("8. Bedingte Anweisungen")
+ Console.WriteLine ("9. Ein Getränk auswählen")
+ Console.WriteLine ("50. Ãœber")
+ Console.WriteLine ("Wählen Sie eine Zahl aus der obigen Liste")
+ Dim selection As String = Console.Readline()
+ Select Case auswahl
+ Case "1" 'Ausgabe "Hallo, Welt"
+ Console.Clear() 'Löscht die Konsole und öffnet die private Subroutine
+ AusgabeHalloWelt() 'Öffnet die genannte private Subroutine
+ Case "2" 'Eingabe "hallo, Welt"
+ Console.Clear()
+ EingabeHalloWelt()
+ Case "3" 'Berechne ganze Zahlen
+ Console.Clear()
+ BerechneGanzeZahlen()
+ Case "4" 'Dezimalzahlen berechnen
+ Console.Clear()
+ BerechneDezimalZahlen()
+ Case "5" 'Ein funktionaler Taschenrechner
+ Console.Clear()
+ Taschenrechner()
+ Case "6" 'Verwendung von "Do While"-Schleifen
+ Console.Clear()
+ WhileSchleife()
+ Case "7" 'Verwendung von "For While"-Schleifen
+ Console.Clear()
+ ForSchleife()
+ Case "8" 'Bedingte Anweisungen
+ Console.Clear()
+ BedingteAnweisung()
+ Case "9" 'If/Else-Anweisung
+ Console.Clear()
+ IfElseAnweisung() 'Ein Getränk auswählen
+ Case "50" '"Ãœber" Infobox
+ Console.Clear()
+ Console.Title = ("Lernen Sie X in Y Minuten :: Ãœber")
+ MsgBox ("Tutorial geschrieben von Brian Martin (@BrianMartinn)")
+ Console.Clear()
+ Main()
+ Console.ReadLine()
+
+ End Select
+End Sub
+
+'Eins - Ich habe Zahlen verwendet, um mich durch das obige Navigationssystem zu
+'führen auf das ich später zurückkomme, um es zu implementieren.
+
+'wir verwenden private Unterprogramme, um verschiedene Abschnitte des Programms
+'zu trennen.
+Private Sub AusgabeHalloWelt()
+ 'Titel der Konsolenanwendung
+ Console.Title = "Ausgabe 'Hallo, Welt' | Lerne X in Y Minuten"
+ 'Verwenden Sie Console.Write("") oder Console.WriteLine(""), um die Ausgabe
+ 'anzuzeigen, gefolgt von Console.Read(), oder Console.Readline()
+ 'Console.ReadLine() zeigt die Ausgabe auf der Konsole an.
+ Console.WriteLine ("Hallo, Welt")
+ Console.ReadLine()
+End Sub
+
+'Zwei
+Private Sub EingabeHalloWelt()
+ Console.Title = "Hallo, Welt, ich bin.. | Lerne X in Y Minuten"
+ 'Variablen
+ 'Vom Benutzer eingegebene Daten müssen gespeichert werden.
+ 'Variablen beginnen ebenfalls mit Dim und enden mit As VariableType.
+
+ 'In diesem Lernprogramm wollen wir Ihren Namen wissen und das Programm
+ 'auf ihn antworten.
+ Dim nutzername As String
+ ' Wir verwenden "String", weil es sich um eine textbasierte Variable handelt.
+ Console.WriteLine ("Hallo, wie ist Ihr Name?") 'Frage nach dem Benutzernamen.
+ nutzername = Console.ReadLine() 'Benutzernamen speichern.
+ Console.WriteLine ("Hallo, " + nutzername) 'Ausgabe ist Hallo, Name
+ Console.ReadLine() 'Die obige Ausgabe anzeigen.
+ 'Der obige Code stellt Ihnen eine Frage und zeigt die Antwort an.
+ 'Neben anderen Variablentypen gibt es Integer, den wir für ganze Zahlen
+ 'verwenden werden.
+End Sub
+
+'Drei
+Private Sub BerechneGanzeZahlen()
+ Console.Title = "Berechne ganze Zahlen | Lerne X in Y Minuten"
+ Console.Write ("Erste Zahl: ") 'Schreiben Sie eine ganze Zahl, 1, 2, 104, usw
+ Dim a As Integer = Console.ReadLine()
+ Console.Write ("Zweite Zahl: ") 'Schreiben Sie eine weitere ganze Zahl.
+ Dim b As Integer = Console.ReadLine()
+ Dim c As Integer = a + b
+ Console.WriteLine (c)
+ Console.ReadLine()
+ 'Dies ist ein einfacher Taschenrechner
+End Sub
+
+'Vier
+Private Sub BerechneDezimalZahlen()
+ Console.Title = "Berechne mit dem Typ Double | Lerne X in Y Minuten"
+ 'Natürlich würden wir gerne Dezimalzahlen addieren.
+ 'Also könnten wir von Integer auf Double umstellen.
+
+ 'Schreiben Sie eine Bruchzahl, 1.2, 2.4, 50.1, 104.9 usw
+ Console.Write ("Erste Zahl: ")
+ Dim a As Double = Console.Readline()
+ Console.Write ("Zweite Zahl: ") 'Schreiben Sie die zweite Zahl.
+ Dim b As Double = Console.Readline()
+ Dim c As Double = a + b
+ Console.WriteLine (c)
+ Console.ReadLine()
+ 'Dieses Programm kann 1.1 und 2.2 addieren
+End Sub
+
+'Fünf
+Private Sub Taschenrechner()
+ Console.Title = "Der Funktionsrechner | Lerne X in Y Minuten"
+ 'Wenn Sie aber wollen, dass der Rechner subtrahiert, dividiert,
+ 'multipliziert und addiert.
+ 'Kopieren Sie den obigen Text und fügen Sie ihn ein.
+ Console.Write ("Erste Zahl: ")
+ Dim a As Double = Console.Readline()
+ Console.Write ("Zweite Zahl: ")
+ Dim b As Integer = Console.Readline()
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ 'Mit den folgenden Zeilen können wir die Werte a und b
+ 'subtrahieren, multiplizieren und dividieren
+ Console.Write (a.ToString() + " + " + b.ToString())
+ 'Wir wollen den Ergebnissen einen linken Rand von 3 Leerzeichen geben.
+ Console.WriteLine (" = " + c.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " * " + b.ToString())
+ Console.WriteLine (" = " + d.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " - " + b.ToString())
+ Console.WriteLine (" = " + e.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " / " + b.ToString())
+ Console.WriteLine (" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+
+End Sub
+
+'Sechs
+Private Sub WhileSchleife()
+ 'Gleich zur vorherigen privaten Subroutine.
+ 'Diesmal fragen wir den Benutzer, ob er fortfahren möchte (ja oder nein?).
+ 'Wir verwenden die Do While-Schleife, weil wir nicht wissen, ob der Benutzer
+ 'das Programm mehr als einmal verwenden möchte.
+ Console.Title = "Do While-Schleifen verwenden | X in Y Minuten lernen"
+ Dim antwort As String 'Wir verwenden "String", weil die Antwort ein Text ist
+ Do 'Wir beginnen das Programm mit
+ Console.Write ("Erste Zahl: ")
+ Dim a As Double = Console.Readline()
+ Console.Write ("Zweite Zahl: ")
+ Dim b As Integer = Console.Readline()
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ Console.Write (a.ToString() + " + " + b.ToString())
+ Console.WriteLine (" = " + c.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " * " + b.ToString())
+ Console.WriteLine (" = " + d.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " - " + b.ToString())
+ Console.WriteLine (" = " + e.ToString.PadLeft(3))
+ Console.Write (a.ToString() + " / " + b.ToString())
+ Console.WriteLine (" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+ 'Fragen Sie den Benutzer, ob er fortfahren möchte. Unglücklicherweise
+ 'werden Groß- und Kleinschreibung unterschieden.
+ Console.Write ("Möchten Sie fortfahren? (j / n)")
+ 'Das Programm nimmt die Variable, zeigt sie an und beginnt von vorne.
+ antwort = Console.Readline()
+ 'Der Befehl, der diese Variable zum Laufen bringt, ist in diesem Fall "j"
+ Loop While antwort = "j"
+
+End Sub
+
+'Sieben
+Private Sub ForSchleife()
+ 'Manchmal muss das Programm nur einmal ausgeführt werden.
+ 'In diesem Programm werden wir von 10 loszählen.
+
+ Console.Title = "Mit "For"-Schleifen | X in Y Minuten lernen"
+ 'Deklarieren Sie die Variable und ab welcher Zahl in Schritt -1 gezählt
+ 'werden soll, Schritt -2, Schritt -3, usw.
+ For i As Integer = 10 To 0 Schritt -1
+ Console.WriteLine (i.ToString) 'Zählerwert anzeigen
+ Next i 'Berechne den neuen Wert
+ Console.WriteLine ("Start") 'Starten wir das Programm, baby!!!!
+ Console.ReadLine() 'BANG!!!! - Vielleicht war ich zu aufgeregt :)
+End Sub
+
+'Acht
+Private Sub BedingteAnweisung()
+ Console.Title = "Bedingte Anweisungen | X in Y Minuten lernen"
+ Dim username As String = Console.Readline()
+ 'Aufforderung zur Eingabe des Benutzernamens.
+ Console.WriteLine ("Hallo, wie ist Ihr Name?")
+ username = Console.ReadLine() 'Benutzernamen speichern.
+ If username = "Adam" Then
+ Console.WriteLine ("Hallo, Adam")
+ Console.WriteLine ("Danke, dass Sie diese nützliche Website erstellt haben")
+ Console.ReadLine()
+ Else
+ Console.WriteLine ("Hallo, " + Benutzername)
+ Console.WriteLine ("Haben Sie www.learnxinyminutes.com besucht?")
+ Console.ReadLine() 'Beendet und zeigt die obige Anweisung an.
+ End If
+End Sub
+
+ 'Neun
+Private Sub IfElseAnweisung()
+ Console.Title = "If / Else-Anweisung | X in Y Minuten lernen"
+ 'Manchmal ist es wichtig, mehr als zwei Alternativen in Betracht zu ziehen.
+ 'Manchmal sind einige von ihnen besser.
+ 'In diesem Fall brauchen wir mehr als eine "if"-Anweisung.
+ 'Eine "if"-Anweisung ist für Verkaufsautomaten geeignet.
+ 'Der Benutzer gibt einen Code ein (A1, A2, A3), aus dem er wählen kann.
+ 'Alle Auswahlmöglichkeiten können in einer einzigen "if"-Anweisung
+ 'kombiniert werden.
+
+ Dim auswahl As String = Console.ReadLine 'Der Wert der Auswahl
+ Console.WriteLine ("A1. für 7Up")
+ Console.WriteLine ("A2. für Fanta")
+ Console.WriteLine ("A3. für Dr. Pepper")
+ Console.WriteLine ("A4. für Coca-Cola")
+ Console.ReadLine()
+ If auswahl = "A1" Dann
+ Console.WriteLine ("7up")
+ Console.ReadLine()
+ ElseIf auswahl = "A2" Then
+ Console.WriteLine ("fanta")
+ Console.ReadLine()
+ ElseIf auswahl = "A3" Then
+ Console.WriteLine ("Dr. Pfeffer")
+ Console.ReadLine()
+ ElseIf auswahl = "A4" Then
+ Console.WriteLine ("Coca-Cola")
+ Console.ReadLine()
+ Else
+ Console.WriteLine ("Ein Produkt auswählen")
+ Console.ReadLine()
+ End If
+
+End Sub
+
+End Module
+```
+
+## Referenzen
+
+Für diejenigen, die mehr wissen wollen, hat Brian Martin ein umfassenderes
+[Visual Basic Tutorial](http://www.vbbootcamp.co.uk/ "Visual Basic Tutorial")
+erstellt.
+
+Die gesamte Syntax sollte gültig sein.
+Kopieren Sie den Code und fügen Sie ihn in den Visual Basic Compiler ein und
+führen Sie das Programm aus (F5).
+
diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown
index 0332c912..00e4fd94 100644
--- a/de-de/yaml-de.html.markdown
+++ b/de-de/yaml-de.html.markdown
@@ -112,7 +112,7 @@ python_komplexe_Zahlen: !!python/komplex 1+2j
####################
# Strings und Zahlen sind nicht die einzigen Skalare, welche YAML versteht.
-# ISO-formatierte Datumsangaben and Zeiangaben können ebenso geparsed werden.
+# ISO-formatierte Datumsangaben and Zeitangaben können ebenso geparsed werden.
DatumZeit: 2001-12-15T02:59:43.1Z
DatumZeit_mit_Leerzeichen: 2001-12-14 21:59:43.10 -5
Datum: 2002-12-14
diff --git a/directx9.html.markdown b/directx9.html.markdown
index b51f418d..586865c8 100644
--- a/directx9.html.markdown
+++ b/directx9.html.markdown
@@ -12,7 +12,7 @@ all began with Direct, such as Direct3D, DirectDraw, DirectMusic, DirectPlay, Di
Direct3D (the 3D graphics API within DirectX) is widely used in the development of video games for Microsoft
Windows and the Xbox line of consoles.<sup>[1]</sup>
-In this tutorial we will be focusing on DirectX 9, which is not as low-level as it's sucessors, which are aimed at programmers very familiar with how graphics hardware works. It makes a great starting point for learning Direct3D. In this tutorial I will be using the Win32-API for window handling and the DirectX 2010 SDK.
+In this tutorial we will be focusing on DirectX 9, which is not as low-level as it's successors, which are aimed at programmers very familiar with how graphics hardware works. It makes a great starting point for learning Direct3D. In this tutorial I will be using the Win32-API for window handling and the DirectX 2010 SDK.
## Window creation
@@ -125,7 +125,7 @@ bool InitD3D(HWND hWnd) {
pp.hDeviceWindow = hWnd; // associated window handle
pp.Windowed = true; // display in window mode
pp.Flags = 0; // no special flags
- // Variable to store results of methods to check if everything succeded.
+ // Variable to store results of methods to check if everything succeeded.
HRESULT result{ };
result = _d3d->CreateDevice(D3DADAPTER_DEFAULT, // use default graphics card
D3DDEVTYPE_HAL, // use hardware acceleration
@@ -144,7 +144,7 @@ bool InitD3D(HWND hWnd) {
viewport.Y = 0; // ..
viewport.Width = clientRect.right; // use the entire window
viewport.Height = clientRect.bottom; // ..
- viewport.MinZ = 0.0f; // minimun view distance
+ viewport.MinZ = 0.0f; // minimum view distance
viewport.MaxZ = 100.0f; // maximum view distance
// Apply the created viewport.
result = _device->SetViewport(&viewport);
@@ -157,7 +157,7 @@ bool InitD3D(HWND hWnd) {
// ...
// Back in our WinMain function we call our initialization function.
// ...
-// Check if Direct3D initialization succeded, else exit the application.
+// Check if Direct3D initialization succeeded, else exit the application.
if (!InitD3D(hWnd))
return -1;
@@ -197,7 +197,7 @@ Let's create a vertex buffer to store the vertices for our triangle
#include <vector>
// First we declare a new ComPtr holding a vertex buffer.
ComPtr<IDirect3DVertexBuffer9> _vertexBuffer{ };
-// Lets define a funtion to calculate the byte size of a std::vector
+// Lets define a function to calculate the byte size of a std::vector
template <typename T>
unsigned int GetByteSize(const std::vector<T>& vec) {
return sizeof(vec[0]) * vec.size();
@@ -253,7 +253,7 @@ if (!InitD3D(hWnd))
return -1;
// Define the vertices we need to draw a triangle.
// Values are declared in a clockwise direction else Direct3D would cull them.
-// If you want to diable culling just call:
+// If you want to disable culling just call:
// _device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
std::vector<VStruct> vertices {
// Bottom left
@@ -274,7 +274,7 @@ if (!(_vertexBuffer = CreateBuffer(vertices)))
Before we can use the vertex buffer to draw our primitives, we first need to set up the matrices.
```cpp
-// Lets create a new funtions for the matrix transformations.
+// Lets create a new functions for the matrix transformations.
bool SetupTransform() {
// Create a view matrix that transforms world space to
// view space.
@@ -338,7 +338,7 @@ if (FAILED(result))
// Create a world transformation matrix and set it to an identity matrix.
D3DXMATRIX world{ };
D3DXMatrixIdentity(&world);
-// Create a scalation matrix scaling our primitve by 10 in the x,
+// Create a scalation matrix scaling our primitive by 10 in the x,
// 10 in the y and keeping the z direction.
D3DXMATRIX scaling{ };
D3DXMatrixScaling(&scaling, // matrix to scale
@@ -499,7 +499,7 @@ std::vector<D3DVERTEXELEMENT9> vertexDeclDesc {
0, // byte offset from the struct beginning
D3DDECLTYPE_FLOAT3, // data type (3d float vector)
D3DDECLMETHOD_DEFAULT, // tessellator operation
- D3DDECLUSAGE_POSTION, // usage of the data
+ D3DDECLUSAGE_POSITION, // usage of the data
0 }, // index (multiples usage of the same type)
{ 0,
12, // byte offset (3 * sizeof(float) bytes)
diff --git a/docker.html.markdown b/docker.html.markdown
index 1dad267a..17f803f4 100644
--- a/docker.html.markdown
+++ b/docker.html.markdown
@@ -1,147 +1,281 @@
---
-language: docker
+category: tool
+tool: docker
filename: docker.bat
contributors:
- ["Ruslan López", "http://javapro.org/"]
- ["Michael Chen", "https://github.com/ML-Chen"]
+ - ["Akshita Dixit", "https://github.com/akshitadixit"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
---
-```bat
-:: download, install and run hello-world image
-docker run hello-world
-
-:: if this is the first time you should be able to see the message
-:: Unable to find image 'hello-world:latest' locally
-:: latest: Pulling from library/hello-world
-:: 1b930d010525: Pull complete
-:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
-:: Status: Downloaded newer image for hello-world:latest
-::
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-:: now let's see currently running images
-docker ps
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: let's see the images we have ran previously
-docker ps -a
-
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
-:: happy_poincare
-:: the name part is generated automatically so it probably will be different for you
-
-:: let's remove our previously generated image
-docker rm happy_poincare
-
-:: let's test if it was really deleted
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: specify a custom name for the container
-docker run --name test_container hello-world
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
-:: test_container
-:: as you can see the name is now what we have specified
-
-:: retrieve logs from a named container
-docker logs test_container
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker rm test_container
-
-docker run ubuntu
-:: Unable to find image 'ubuntu:latest' locally
-:: latest: Pulling from library/ubuntu
-:: 2746a4a261c9: Pull complete
-:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
-:: Status: Downloaded newer image for ubuntu:latest
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
-:: relaxed_nobel
-
-:: running a container in an interactive mode
-docker run -it ubuntu
-:: root@e2cac48323d2:/# uname
-:: Linux
-:: root@e2cac48323d2:/# exit
-:: exit
-
-docker rm relaxed_nobel
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
-:: nifty_goldwasser
-
-docker rm nifty_goldwasser
+Docker is a tool that helps you build, test, ship and run applications
+seamlessly across various machines. It replicates the environment our software
+needs on any machine. You can get Docker for your machine from
+https://docs.docker.com/get-docker/
+
+It has grown in popularity over the last decade due to being lightweight and
+fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker
+does not need a full blown OS of its own to be loaded to start and does not
+compete for resources other than what the application it is running will use.
+VMs on the other hand are pretty resource intensive on our processors, disks and
+memory hence running multiple VMs for various applications becomes a challenge
+in a limited capacity architecture.
+
+<pre>
+┌────────────────────────┠┌───────────────────────â”
+│ ┌───────────┠│ │ ┌───────────┠│
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┠┌────────┠│ │ ┌────────┠┌───────┠│
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ ┌───────────────────┠│ │ ┌──────────────────┠│
+│ │ Guest OS │ │ │ │ Guest OS │ │
+│ └───────────────────┘ │ │ └──────────────────┘ │
+│ VM1 │ │ VM2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ Hypervisor │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ Host OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (VM based architecture)
+
+┌────────────────────────┠┌───────────────────────â”
+│ ┌───────────┠│ │ ┌───────────┠│
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┠┌────────┠│ │ ┌────────┠┌───────┠│
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ Container1 │ │ Container2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ Docker │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────â”
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (Docker based architecture)
+
+</pre>
+
+Couple of terms we will encounter frequently are Docker Images and Docker
+Containers. Images are packages or templates of containers all stored in a
+container registry such as [Docker Hub](https://hub.docker.com/). Containers
+are standalone, executable instances of these images which include code,
+runtime, system tools, system libraries and settings - everything required to
+get the software up and running. Coming to Docker, it follows a client-server
+architecture wherein the CLI client communicates with the server component,
+which here is, the Docker Engine using RESTful API to issue commands.
+
+## The Docker CLI
+```bash
+# after installing Docker from https://docs.docker.com/get-docker/
+# To list available commands, either run `docker` with no parameters or execute
+# `docker help`
+$ docker
+
+>>> docker [OPTIONS] COMMAND [ARG...]
+ docker [ --help | -v | --version ]
+
+ A self-sufficient runtime for containers.
+
+ Options:
+ --config string Location of client config files (default "/root/.docker")
+ -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
+ -D, --debug Enable debug mode
+ --help Print usage
+ -H, --host value Daemon socket(s) to connect to (default [])
+ -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
+ --tls Use TLS; implied by --tlsverify
+ --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
+ --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
+ --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
+ --tlsverify Use TLS and verify the remote
+ -v, --version Print version information and quit
+
+ Commands:
+ attach Attach to a running container
+ # […]
+
+$ docker run hello-world
+# `docker run <container-name>` is used to run a container, it will pull the
+# images from Docker Hub if they don't already exist in your system. Here the
+# docker client connects to the daemon which in turn pulls the "hello-world"
+# image from the Docker Hub. The daemon then builds a new container from the
+# image which runs the executable that produces the output streamed back to the
+# client that we see on our terminals.
+
+$ docker run -d ubuntu sleep 60s
+# The -d (or --detach) flag is when we want to run a container in the background
+# and return back to the terminal. Here we detach an ubuntu container from the
+# terminal, the output should be the id and the command exits. If we check
+# running containers, we should still see ours there:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould
+
+$ docker run <container-id> -p 3000:8000
+# The -p (or --publish) flag is used to expose port 8000 inside the container to
+# port 3000 outside the container. This is because the app inside the container
+# runs in isolation, hence the port 8000 where the app runs is private to the
+# container.
+
+$ docker run -i
+# or
+$ docker run -it
+# Docker runs our containers in a non-interactive mode i.e. they do not accept
+# inputs or work dynamically while running. The -i flag keeps input open to the
+# container, and the -t flag creates a pseudo-terminal that the shell can attach
+# to (can be combined as -it)
+
+$ docker ps -a
+# The `docker ps` command only shows running containers by default. To see all
+# containers, use the -a (or --all) flag
+# Running the above command should output something similar in the terminal:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet
+
+
+$ docker stop hello-world
+# or
+$ docker start hello-world
+# The stop command simply stops one or more containers, and the start command
+# starts the container(s) up again! `docker start -a ubuntu` will attach our
+# detached container back to the terminal i.e. runs in the foreground
+
+$ docker create alpine
+# `docker create` creates a new container for us with the image specified (here,
+# alpine), the container does not auto-start unlike `docker run`. This command
+# is used to set up a container configuration and then `docker start` to shoot
+# it up when required. Note that the status is "Created":
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie
+
+$ docker rm 82f84
+# Removes one or more containers using their container ID.
+# P.S.: we can use only the first few characters of the entire ID to identify
+# containers
+
+$ docker images
+# Displays all images and their information, created here means the latest image
+# tag updated on Docker Hub:
+# REPOSITORY TAG IMAGE ID CREATED SIZE
+# ubuntu latest a8780b506fa4 9 days ago 77.8MB
+# alpine latest 9c6f07244728 3 months ago 5.54MB
+# hello-world latest feb5d9fea6a5 13 months ago 13.3kB
+
+$ docker rmi
+# Removes one or more images from your system which do not have their instances
+# (or containers as we know them) running. If the image has an attached
+# container, either delete the container first or use the -f (or --force) flag
+# to forcefully delete both the container and image.
+
+$ docker pull busybox
+# The pull command downloads the specified image on our system from Docker Hub.
+
+$ docker exec -it 7b272 bash
+# This command is used to run a command in the running container's default
+# directory. Here 7b272 was our ubuntu container and the above command would
+# help us interact with the container by opening a bash session.
+
+$ docker logs <container-id>
+# Displays the information logged by the specified container
+# root@7b27222e4bb7:/# whoami
+# root
+# root@7b27222e4bb7:/# pwd
+# /
+# root@7b27222e4bb7:/# ls
+# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var
+# root@7b27222e4bb7:/# exit
+# exit
+
+# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/
+```
+## The Dockerfile
+The Dockerfile is a blueprint of a Docker image. We can mention the artifacts
+from our application along with their configurations into this file in the
+specific syntax to let anyone create a Docker image of our application.
+
+### A few things to keep in mind:
+* It is always strictly named `Dockerfile` without any extensions
+* We have to build our custom image on top of some already available Docker base
+image. (there is an empty image called `scratch` which literally lets you build
+an image from scratch)
+* All capitalised commands are part of the syntax, they are not case-sensitive
+but used like a convention
+* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/).
+
+```Dockerfile
+FROM <base-image>
+# define base image
+
+ENV USERNAME='admin'\
+ PWD='****'
+# optionally define environmental variables
+
+RUN apt-get update
+# run linux commands inside container env, does not affect host env
+# This executes during the time of image creation
+
+COPY <src> <target>
+# executes on the host, copies files from src (usually on the host) to target
+# on the container
+
+ENTRYPOINT ["some-script.sh"]
+# executes an entire script as an entrypoint
+
+CMD [<args>,...]
+# always part of dockerfile, introduces entry point linux command e.g.
+# `CMD node server.js`
+# This executes after image creation only when the container from the image
+# is running.
+```
+### Build your images
+Use the `docker build` command after wrapping your application into a Docker
+image to run ( or build) it.
+
+```bash
+
+$ docker build <path-to-dockerfile>
+# used to build an image from the specified Dockerfile
+# instead of path we could also specify a URL
+# -t tag is optional and used to name and tag your images for e.g.
+# `$ docker build -t my-image:0.1 ./home/app`
+# rebuild images everytime you make changes in the dockerfile
+```
+
+## Push your image to DockerHub
+If you want your application's Docker image to be made publicly available for
+any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a
+registry of Docker images. Make sure you have an account with a username and
+password on Docker Hub.
+
+When pushing an image to Docker Hub, we must specify our Docker Hub username
+as part of the source image name. We need to create the target image with the
+tag name of username/image-name much like GitHub repositories.
+
+```bash
+$ docker login
+# to login to Docker Hub using your username and password
+
+$ docker tag <src-image>[:<src-tag>] <target-image>[:<target-tag>]
+# this tags a local src-image to a public target-image
+# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app`
+# if tags are not specified, they're defaulted to `latest`
+
+$ docker push <target-image>[:<target-tag>]
+# uploads our image to Docker Hub
+# e.g. `docker push akshitadixit/my-sample-app`
+# this image will be accessible under your profile's repositories as
+# `https://hub.docker.com/r/username/image-name`
+
```
diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown
index 3e3c0413..ff053384 100644
--- a/dynamic-programming.html.markdown
+++ b/dynamic-programming.html.markdown
@@ -59,5 +59,3 @@ for i=0 to n-1
* [Optimal Substructure Property](https://www.geeksforgeeks.org/dynamic-programming-set-2-optimal-substructure-property/)
* [How to solve a DP problem](https://www.geeksforgeeks.org/solve-dynamic-programming-problem/)
* [How to write DP solutions](https://www.quora.com/Are-there-any-good-resources-or-tutorials-for-dynamic-programming-DP-besides-the-TopCoder-tutorial/answer/Michal-Danilák)
-
-And a [quiz](https://www.commonlounge.com/discussion/cdbbfe83bcd64281964b788969247253) to test your knowledge.
diff --git a/el-gr/rust-gr.html.markdown b/el-gr/rust-gr.html.markdown
index 4da75b1d..d28e3c2c 100644
--- a/el-gr/rust-gr.html.markdown
+++ b/el-gr/rust-gr.html.markdown
@@ -62,7 +62,7 @@ fn add2(x: i32, y: i32) -> i32 {
fn main() {
// ΑÏιθμοί //
- // Αμετάβλητη σÏνδεση
+ // Αμετάβλητη δέσμευση (η τιμή που αντιστοιχεί στο όνομα "x" δεν μποÏεί να αλλάξει)
let x: i32 = 1;
// Καταλήξεις integer/float
@@ -80,7 +80,8 @@ fn main() {
// ΠÏάξεις
let sum = x + y + 13;
- // Μη-αμετάβλητη αξία (με την έννοια ότι μποÏεί να αλλάξει)
+ // Μεταβλητές (με την έννοια των Ï€Ïοστακτικών γλωσσών Ï€ÏογÏαμματισμοÏ).
+ // Στη Rust η αμετάβλητη δέσμευση είναι στάνταÏ. Το mut δηλώνει μεταβλητότητα.
let mut mutable = 1;
mutable = 4;
mutable += 2;
@@ -96,7 +97,7 @@ fn main() {
// A `String` – a heap-allocated string
let s: String = "καλημέÏα κόσμε".to_string();
- // Ένα κομμάτι αλφαÏÎ¹Î¸Î¼Î·Ï„Î¹ÎºÎ¿Ï (string slice) – μια μη-μεταβλητή οπτική γωνία Ï€Ïος ένα άλλο αλφαÏιθμητικό
+ // Ένα κομμάτι αλφαÏÎ¹Î¸Î¼Î·Ï„Î¹ÎºÎ¿Ï (string slice) – μια αμετάβλητη οπτική γωνία Ï€Ïος ένα άλλο αλφαÏιθμητικό
// Το αλφαÏιθμητικό μποÏεί να είναι στατικό όπως τα σταθεÏά αλφαÏιθμητικά, ή να πεÏιλαμβάνεται σε ένα άλλο,
// δυναμικό αντικείμενο (σε αυτή την πεÏίπτωση τη μεταβλητή `s`)
let s_slice: &str = &s;
@@ -112,7 +113,7 @@ fn main() {
let mut vector: Vec<i32> = vec![1, 2, 3, 4];
vector.push(5);
- // Ένα κομμάτι – μια μη-μεταβλητή οπτική γωνία Ï€Ïος ένα διάνυσμα ή πίνακα
+ // Ένα κομμάτι – μια αμετάβλητη οπτική γωνία Ï€Ïος ένα διάνυσμα ή πίνακα
// Είναι παÏόμοιο με το κομμάτι αλφαÏÎ¹Î¸Î¼Î·Ï„Î¹ÎºÎ¿Ï Ï€Î¿Ï… είδαμε Ï€Ïοηγουμένως
let slice: &[i32] = &vector;
@@ -121,10 +122,10 @@ fn main() {
// Tuples (πλειάδες) //
- // Ένα tuple είναι μια σταθεÏÎ¿Ï Î¼ÎµÎ³Î­Î¸Î¿Ï…Ï‚ σειÏά από αξίες (πιθανά διαφοÏÎµÏ„Î¹ÎºÎ¿Ï Ï„Ïπου)
+ // Ένα tuple είναι μια σταθεÏÎ¿Ï Î¼ÎµÎ³Î­Î¸Î¿Ï…Ï‚ σειÏά από τιμές (πιθανά διαφοÏÎµÏ„Î¹ÎºÎ¿Ï Ï„Ïπου)
let x: (i32, &str, f64) = (1, "καλημέÏα", 3.4);
- // ΜποÏοÏμε να χÏησιμοποιήσουμε το `let` και ένα tuple για να δώσουμε πολλές αξίες σε πολλές μεταβλητές ταυτόχÏονα
+ // ΜποÏοÏμε να χÏησιμοποιήσουμε το `let` και ένα tuple για να δώσουμε πολλές τιμές σε πολλές μεταβλητές ταυτόχÏονα
// (destructuring `let`)
let (a, b, c) = x;
println!("{} {} {}", a, b, c); // 1 καλημέÏα 3.4
@@ -185,7 +186,7 @@ fn main() {
fn bar(&self) -> &T { // Δανειζόμαστε το self
&self.bar
}
- fn bar_mut(&mut self) -> &mut T { // Δανειζόμαστε το self ως μη-αμετάβλητη αξία
+ fn bar_mut(&mut self) -> &mut T { // Γίνεται "μεταβλητός δανεισμός" του self (μποÏοÏμε να το Ï„Ïοποποιήσουμε)
&mut self.bar
}
fn into_bar(self) -> T { // Εδώ το self καταναλώνεται
@@ -240,7 +241,7 @@ fn main() {
// 4. Έλεγχος Ïοής //
/////////////////////
- // Î’Ïόγχοι `for`
+ // Î’Ïόχοι `for`
let array = [1, 2, 3];
for i in array {
println!("{}", i);
@@ -253,7 +254,7 @@ fn main() {
println!("");
// Τυπώνει `0 1 2 3 4 5 6 7 8 9 `
- // Î’Ïόγχοι `if`
+ // `if` (υπό συνθήκη διακλάδωση)
if 1 == 1 {
println!("Τα μαθηματικά δουλεÏουν!");
} else {
@@ -267,17 +268,17 @@ fn main() {
"κακό"
};
- // Î’Ïόγχοι `while`
+ // Î’Ïόχοι `while`
while 1 == 1 {
println!("Το σÏμπαν λειτουÏγεί κανονικά.");
- // ΜποÏοÏμε να βγοÏμε από το βÏόγχο με το `break`
+ // ΜποÏοÏμε να βγοÏμε από το βÏόχο με το `break`
break
}
- // ΑτέÏμονος βÏόχγος
+ // ΑτέÏμονος βÏόχος
loop {
println!("ΚαλημέÏα!");
- // ΜποÏοÏμε να βγοÏμε από το βÏόγχο με το `break`
+ // ΜποÏοÏμε να βγοÏμε από το βÏόχο με το `break`
break
}
@@ -294,11 +295,11 @@ fn main() {
*now_its_mine += 2;
println!("{}", now_its_mine); // 7
- // println!("{}", mine); // Αυτό παÏάγει λάθος κατά τη μεταγλώττιση διότι Ï„ÏŽÏα ο δείκτης ανοίκει στο `now_its_mine`
+ // println!("{}", mine); // Αυτό παÏάγει λάθος κατά τη μεταγλώττιση διότι Ï„ÏŽÏα ο δείκτης ανήκει στο `now_its_mine`
// Reference (αναφοÏά) – ένας αμετάβλητος δείκτης που αναφέÏεται σε άλλα δεδομένα
- // Όταν μια αναφοÏά δίνεται σε μια αξία, λέμε πως η αξία έχει "δανειστεί".
- // Όταν μια αξία δανείζεται αμετάβλητα, δεν μποÏεί να είναι mutated (να μεταβληθεί) ή να μετακινηθεί.
+ // Όταν μια αναφοÏά δίνεται σε μια τιμή, λέμε πως η τιμή έχει "δανειστεί".
+ // Όταν μια τιμή δανείζεται αμετάβλητα, δεν μποÏεί να είναι mutated (να μεταβληθεί) ή να μετακινηθεί.
// Ένας "δανεισμός" παÏαμένει ενεÏγός μέχÏι την τελευταία χÏήση της μεταβλητής που δανείζεται.
let mut var = 4;
var = 3;
@@ -313,13 +314,13 @@ fn main() {
var = 2; // Η `ref_var` δεν χÏησιμοποιείται από εδώ και στο εξής, άÏα ο "δανεισμός" τελειώνει
// Μεταβλητή αναφοÏά
- // Όσο μια αξία είναι μεταβλητά δανεισμένη, παÏαμένει τελείως απÏοσβάσιμη.
+ // Όσο μια τιμή είναι μεταβλητά δανεισμένη, παÏαμένει τελείως απÏοσβάσιμη.
let mut var2 = 4;
let ref_var2: &mut i32 = &mut var2;
*ref_var2 += 2; // Ο αστεÏίσκος (*) χÏησιμοποιείται ως δείκτης Ï€Ïος την μεταβλητά δανεισμένη `var2`
println!("{}", *ref_var2); // 6 , // Αν είχαμε `var2` εδώ θα Ï€ÏοκαλοÏνταν λάθος μεταγλώττισης.
- // O Ï„Ïπος της `ref_var2` είναι &mut i32, άÏα αποθηκεÏει μια αναφοÏά Ï€Ïος μια αξία i32, όχι την αξία την ίδια.
+ // O Ï„Ïπος της `ref_var2` είναι &mut i32, άÏα αποθηκεÏει μια αναφοÏά Ï€Ïος μια τιμή i32, όχι την τιμή την ίδια.
// var2 = 2; // Λάθος μεταγλώττισης, γιατί η `var2` είναι δανεισμένη.
ref_var2; // Εντολή no-op (τίποτα δεν εκτελείται από τον επεξεÏγαστή), η οποία όμως μετÏάει ως χÏήση και κÏατά τον
// "δανεισμό" ενεÏγό
diff --git a/elisp.html.markdown b/elisp.html.markdown
index f839dac0..5d98ceff 100644
--- a/elisp.html.markdown
+++ b/elisp.html.markdown
@@ -3,6 +3,7 @@ language: elisp
contributors:
- ["Bastien Guerry", "https://bzg.fr"]
- ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
+ - ["rilysh", "https://github.com/rilysh"]
filename: learn-emacs-lisp.el
---
@@ -12,11 +13,11 @@ filename: learn-emacs-lisp.el
;; First make sure you read this text by Peter Norvig:
;; http://norvig.com/21-days.html
;;
-;; Then install GNU Emacs 24.3:
+;; Then install latest version of GNU Emacs:
;;
;; Debian: apt-get install emacs (or see your distro instructions)
-;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg
-;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip
+;; OSX: https://emacsformacosx.com/
+;; Windows: https://ftp.gnu.org/gnu/emacs/windows/
;;
;; More general information can be found at:
;; http://www.gnu.org/software/emacs/#Obtaining
@@ -76,12 +77,12 @@ filename: learn-emacs-lisp.el
;; `C-j' inserts the result of the evaluation in the buffer.
;; `C-xC-e' displays the same result in Emacs bottom line,
-;; called the "minibuffer". We will generally use `C-xC-e',
+;; called the "echo area". We will generally use `C-xC-e',
;; as we don't want to clutter the buffer with useless text.
;; `setq' stores a value into a variable:
(setq my-name "Bastien")
-;; `C-xC-e' => "Bastien" (displayed in the mini-buffer)
+;; `C-xC-e' => "Bastien" (displayed in the echo area)
;; `insert' will insert "Hello!" where the cursor is:
(insert "Hello!")
@@ -343,3 +344,9 @@ filename: learn-emacs-lisp.el
;; To read an online introduction to Emacs Lisp:
;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
```
+
+### Further Reading
+- [GNU Elisp Manual](https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html)
+- [Emacs Wiki](https://www.emacswiki.org/emacs/LearningEmacs)
+- [Emacs Docs](https://emacsdocs.org/docs/elisp/Emacs-Lisp)
+- [Mpre Elisp Docs](https://www.math.utah.edu/docs/info/elisp_22.html)
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 9f96be49..2748a983 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "https://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -13,16 +13,15 @@ It's fully compatible with Erlang, but features a more standard syntax
and many more features.
```elixir
-
# Single line comments start with a number symbol.
# There's no multi-line comment,
# but you can stack multiple comments.
-# To use the elixir shell use the `iex` command.
+# To use the Elixir shell use the `iex` command.
# Compile your modules with the `elixirc` command.
-# Both should be in your path if you installed elixir correctly.
+# Both should be in your path if you installed Elixir correctly.
## ---------------------------
## -- Basic types
@@ -50,7 +49,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# In elixir, just like in Erlang, the `=` denotes pattern matching and
+# In Elixir, just like in Erlang, the `=` denotes pattern matching and
# not an assignment.
#
# This means that the left-hand side (pattern) is matched against a
@@ -83,7 +82,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` in elixir returns the ASCII integer for the letter `a`
+# `?a` in Elixir returns the ASCII integer for the letter `a`
?a #=> 97
# To concatenate lists use `++`, for binaries use `<>`
@@ -116,7 +115,7 @@ genders.gillian #=> "female"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# In elixir the operator `/` always returns a float.
+# In Elixir the operator `/` always returns a float.
# To do integer division use `div`
div(10, 2) #=> 5
@@ -174,7 +173,7 @@ else
"This will"
end
-# Remember pattern matching? Many control-flow structures in elixir rely on it.
+# Remember pattern matching? Many control-flow structures in Elixir rely on it.
# `case` allows us to compare a value against many patterns:
case {:one, :two} do
@@ -307,7 +306,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Due to immutability, recursion is a big part of elixir
+# Due to immutability, recursion is a big part of Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -382,7 +381,7 @@ end
## ---------------------------
# Elixir relies on the actor model for concurrency. All we need to write
-# concurrent programs in elixir are three primitives: spawning processes,
+# concurrent programs in Elixir are three primitives: spawning processes,
# sending messages and receiving messages.
# To start a new process we use the `spawn` function, which takes a function
diff --git a/elm.html.markdown b/elm.html.markdown
index ad80adc9..bc7ba4cc 100644
--- a/elm.html.markdown
+++ b/elm.html.markdown
@@ -224,7 +224,7 @@ List.map : (a -> b) -> List a -> List b
-- Comparable allows you to order numbers and strings, like a < b.
-- Appendable things can be combined with a ++ b.
-{-- Type Aliases and Union Types --}
+{-- Type Aliases and Custom Types --}
-- When you write a record or tuple, its type already exists.
-- (Notice that record types use colon and record values use equals.)
@@ -244,28 +244,28 @@ otherOrigin =
-- But it's still the same type, so you can equate them.
origin == otherOrigin -- True
--- By contrast, defining a union type creates a type that didn't exist before.
--- A union type is so called because it can be one of many possibilities.
--- Each of the possibilities is represented as a "tag".
+-- By contrast, defining a custom type creates a type that didn't exist before.
+-- A custom type is so called because it can be one of many possibilities.
+-- Each of the possibilities is represented as a "type variant".
type Direction =
North | South | East | West
--- Tags can carry other values of known type. This can work recursively.
+-- Type variants can carry other values of known type. This can work recursively.
type IntTree =
Leaf | Node Int IntTree IntTree
--- "Leaf" and "Node" are the tags. Everything following a tag is a type.
+-- "Leaf" and "Node" are the type variants. Everything following a type variant is a type.
--- Tags can be used as values or functions.
+-- Type variants can be used as values or functions.
root : IntTree
root =
Node 7 Leaf Leaf
--- Union types (and type aliases) can use type variables.
+-- Custom types (and type aliases) can use type variables.
type Tree a =
Leaf | Node a (Tree a) (Tree a)
-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a."
--- Pattern match union tags. The uppercase tags will be matched exactly. The
+-- Pattern match variants in a custom type. The uppercase variants will be matched exactly. The
-- lowercase variables will match anything. Underscore also matches anything,
-- but signifies that you aren't using it.
leftmostElement : Tree a -> Maybe a
@@ -289,7 +289,7 @@ module Name where
-- By default, everything is exported. You can specify exports explicitly.
module Name (MyType, myValue) where
--- One common pattern is to export a union type but not its tags. This is known
+-- One common pattern is to export a custom type but not its type variants. This is known
-- as an "opaque type", and is frequently used in libraries.
-- Import code from other modules to use it in this one.
diff --git a/erlang.html.markdown b/erlang.html.markdown
index a9d280d7..62666c3a 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -1,7 +1,7 @@
---
language: erlang
contributors:
- - ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
+ - ["Giovanni Cappellotto", "http://giovanni.curlybrackets.it/"]
filename: learnerlang.erl
---
diff --git a/es-es/asciidoc-es.html.markdown b/es-es/asciidoc-es.html.markdown
index 6e357915..31406ee1 100644
--- a/es-es/asciidoc-es.html.markdown
+++ b/es-es/asciidoc-es.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
lang: es-es
-filename: asciidoc-es.md
+filename: asciidoc-es.adoc
---
AsciiDoc es un lenguaje de marcas similar a Markdown que puede ser usado para cualquier uso, desde libros a blogs.
diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown
index 8da8f024..1ee12956 100644
--- a/es-es/awk-es.html.markdown
+++ b/es-es/awk-es.html.markdown
@@ -11,8 +11,8 @@ lang: es-es
AWK es una herramienta estándar en cada sistema UNIX compatible con POSIX.
Es como un Perl restringido, perfecto para tareas de procesamiento de texto y
-otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin
-puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo
+otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin
+puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo
desde un script de shell o usarlo como un lenguaje stand-alone para scripting.
¿Por qué elegir AWK sobre Perl? Principalmente, porque AWK es parte de UNIX.
@@ -74,8 +74,8 @@ BEGIN {
# Bloques formados por múltiples líneas usan llaves
while (a < 10) {
- print "La concatenación de strings se hace " " con series "
- print " de" " strings separados por espacios"
+ print "La concatenación de strings se hace " " con series "
+ print " de" " strings separados por espacios"
print a
a++
@@ -153,13 +153,13 @@ function arithmetic_functions(a, b, c, localvar) {
# Todo es global. No es problema en scripts pequeños, pero sí para
# scripts más grandes.
- # Hay un work-around (mmm... hack). Los argumentos de las funciones son
+ # Hay un work-around (mmm... hack). Los argumentos de las funciones son
# locales para la función, y AWK permite definir más argumentos de función
- # de los que necesita, por lo que define las variables locales en la
+ # de los que necesita, por lo que define las variables locales en la
# declaración como en la función de arriba. Como convención, agrega
- # espacios en blanco para distinguir los parámetros de la función de las
- # variables locales. En este ejemplo, a, b y c son parámetros y localvar es una
- # variable local.
+ # espacios en blanco para distinguir los parámetros de la función de las
+ # variables locales. En este ejemplo, a, b y c son parámetros y localvar es
+ # una variable local.
# Ahora, a demostrar las funciones aritméticas
@@ -196,7 +196,7 @@ function string_functions( localvar, arr) {
# Ambas regresan el número de matches remplazados.
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "M..t m. at th. bar"
# Buscar una cadena que haga match con una expresión regular
# index() hace lo mismo, pero no permite expresiones regulares
@@ -222,10 +222,10 @@ function io_functions( localvar) {
# También hay printf
printf("%s %d %d %d\n", "Testing", 1, 2, 3)
- # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un
- # handle de archivo cuando use algo que necesite uno. El string que usaste
- # para esto puede ser tratada como un handle de archivo para propósitos de I/O.
- # Esto lo hace similar al scripting de shell:
+ # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un
+ # handle de archivo cuando use algo que necesite uno. El string que usaste
+ # para esto puede ser tratada como un handle de archivo para propósitos
+ # de I/O. Esto lo hace similar al scripting de shell:
print "foobar" >"/tmp/foobar.txt"
@@ -247,17 +247,17 @@ function io_functions( localvar) {
close("/tmp/foobar.txt")
}
-# Como dije al inicio, los programas en AWK son una colección de patrones y
+# Como dije al inicio, los programas en AWK son una colección de patrones y
# acciones. Ya conociste el patrón BEGIN. otros patrones sólo se usan si estás
# procesando líneas desde archivos o stdin.
-# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a
-# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for
+# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a
+# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for
# implícito, iterando sobre las líneas de estos archivos. Estos patrones y
# acciones son como instrucciones switch dentro del ciclo.
/^fo+bar$/ {
-
+
# Esta acción se ejecutará por cada línea que haga match con la expresión
# regular /^fo+bar$/, y será saltada por cualquier línea que no haga match.
# Vamos a sólo mostrar la línea:
@@ -268,7 +268,7 @@ function io_functions( localvar) {
# $0 es el nombre de la línea actual que se está procesando.
# Se crea automáticamente para ti.
- # Probablemente puedas adivinar que hay otras variables $. Cada línea es
+ # Probablemente puedas adivinar que hay otras variables $. Cada línea es
# separada implícitamente antes de que se llame cada acción, justo como lo
# hace shell. Y, como shell, cada campo puede ser accesado con $.
@@ -301,7 +301,7 @@ a > 0 {
# Y ya te das una idea. Procesar archivos de texto, leyendo una línea a la vez,
# y haciendo algo con ella, particularmente separando en un deliminator, es tan
# común en UNIX que AWK es un lenguaje de scripting que hace todo eso por ti
-# sin que tengas que pedirlo. Basta con escribir los patrones y acciones
+# sin que tengas que pedirlo. Basta con escribir los patrones y acciones
# basados en lo que esperas de la entrada y lo quieras quieras hacer con ella.
# Aquí está un ejemplo de un script simple, para lo que AWK es perfecto.
@@ -343,7 +343,7 @@ $1 == name {
nlines++
}
-# Otro patrón especial es END. Va a ejecutarse después de procesar todos los
+# Otro patrón especial es END. Va a ejecutarse después de procesar todos los
# archivos de texto. A diferencia de BEGIN, sólo se ejecuta si le das dado una
# entrada a procesar. Se ejecutará después de que todos los archivos hayan sido
# leídos y procesados según las reglas y acciones que programaste. El propósito
@@ -356,8 +356,10 @@ END {
}
```
+
Más información:
* [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html)
* [Página man de AWK](https://linux.die.net/man/1/awk)
-* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): GNU Awk se encuentra en la mayoría de los sistemas Linux.
+* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html):
+ GNU Awk se encuentra en la mayoría de los sistemas Linux.
diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown
index 9db2c802..f624d3c7 100644
--- a/es-es/c++-es.html.markdown
+++ b/es-es/c++-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-es.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown
index cae4349e..ae357d91 100644
--- a/es-es/c-es.html.markdown
+++ b/es-es/c-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: c
+language: C
filename: learnc-es.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
diff --git a/es-es/chapel-es.html.markdown b/es-es/chapel-es.html.markdown
new file mode 100644
index 00000000..732ee298
--- /dev/null
+++ b/es-es/chapel-es.html.markdown
@@ -0,0 +1,1219 @@
+---
+language: chapel
+filename: learnchapel.chpl
+contributors:
+ - ["Ian J. Bertolacci", "https://www.cs.arizona.edu/~ianbertolacci/"]
+ - ["Ben Harshbarger", "https://github.com/benharsh/"]
+translators:
+ - ["Ivan Alburquerque", "https://github.com/AlburIvan"]
+lang: es-es
+---
+
+Puede leer todo sobre Chapel en [el sitio web oficial de Chapel de Cray](https://chapel-lang.org).
+En resumen, Chapel es un lenguaje de programación paralela, código abierto, de alta productividad
+desarrolladp en Cray Inc. y está diseñado para ejecutarse en PC multi-nucleos,
+así como en supercomputadoras multi-kilocore.
+
+
+Puede encontrar más información y asistencia al final de este documento.
+
+```chapel
+// Los comentarios son de estilo de la familia C
+
+// comentario de una línea
+/*
+ comentario de múltiples lineas
+*/
+
+// Impresión básica
+
+write("Hola, ");
+writeln("Mundo!");
+
+// write y writeln pueden tomar una lista de cosas para imprimir.
+// Cada cosa está impresa justo al lado de las demás, ¡así que incluye espacios!
+writeln("hay ", 3, " comas (\",\") en esta línea de código");
+
+// Diferentes canales de salida:
+stdout.writeln("Esto va a la salida estándar, al igual que lo hace writeln()");
+stderr.writeln("Esto va al error estándar");
+
+
+// Las variables no tienen que escribirse explícitamente
+// mientras el compilador pueda determinar el tipo que contendrá.
+
+// 10 es un entero, asi que myVar es explícitamente un entero
+var myVar = 10;
+myVar = -10;
+var mySecondVar = myVar;
+// var anError; sería un error en tiempo de compilación
+
+// Podemos (y debemos) escribir cosas explícitamente.
+var myThirdVar: real;
+var myFourthVar: real = -1.234;
+myThirdVar = myFourthVar;
+
+// Tipos
+
+// Hay varios tipos básicos.
+var myInt: int = -1000; // Enteros firmados
+var myUint: uint = 1234; // Enteros sin-firmar
+var myReal: real = 9.876; // Números de punto flotante
+var myImag: imag = 5.0i; // Números imaginarios
+var myCplx: complex = 10 + 9i; // Números complejos
+myCplx = myInt + myImag; // Otra manera de formar números complejos
+var myBool: bool = false; // Booleanos
+var myStr: string = "Una cadena..."; // Cadenas
+var singleQuoteStr = 'Otra cadena...'; // Cadena literal con comillas simples
+
+// Algunos tipos pueden tener tamaños.
+var my8Int: int(8) = 10; // Entero de 8 bit (one byte);
+var my64Real: real(64) = 1.516; // Real de 64 bit (8 bytes)
+
+// Conversion de tipos.
+var intFromReal = myReal : int;
+var intFromReal2: int = myReal : int;
+
+// Alias de tipo.
+type chroma = int; // Tipo de un solo tono
+type RGBColor = 3*chroma; // Tipo que representa un color completo
+var black: RGBColor = (0,0,0);
+var white: RGBColor = (255, 255, 255);
+
+// Constantes y Parámetros
+
+// una variable const es una constante y no se puede cambiar después de
+// establecerla en tiempo de ejecución.
+const almostPi: real = 22.0/7.0;
+
+// Un parámetro es una constante cuyo valor debe conocerse estáticamente
+// en tiempo de compilación.
+
+param compileTimeConst: int = 16;
+
+// El modificador de configuración permite establecer valores en la línea de comando.
+// Establece valores con --varCmdLineArg=Value o --varCmdLineArg Value en tiempo de ejecución.
+config var varCmdLineArg: int = -123;
+config const constCmdLineArg: int = 777;
+
+// config param se puede configurar en tiempo de compilación.
+// Establece valores con --set paramCmdLineArg=value en tiempo de compilación.
+config param paramCmdLineArg: bool = false;
+writeln(varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg);
+
+// Referencias
+
+// ref funciona de manera muy similar a una referencia en C ++. En Chapel,
+// no se puede hacer una referencia como alias a una variable distinta
+// de la variable con la que se inicializa.
+
+// Aquí, refToActual se refiere a actual.
+var actual = 10;
+ref refToActual = actual;
+writeln(actual, " == ", refToActual); // imprime el mismo valor
+actual = -123; // modificar actual (a lo que refToActual se refiere)
+writeln(actual, " == ", refToActual); // imprime el mismo valor
+refToActual = 99999999; // modificar a qué se refiere refToActual (que es actual)
+writeln(actual, " == ", refToActual); // imprime el mismo valor
+
+// Operadores
+
+// Operadores matemáticos:
+var a: int, thisInt = 1234, thatInt = 5678;
+a = thisInt + thatInt; // Adicción
+a = thisInt * thatInt; // Multiplicación
+a = thisInt - thatInt; // Substracción
+a = thisInt / thatInt; // División
+a = thisInt ** thatInt; // Exponenciación
+a = thisInt % thatInt; // residuo (módulo)
+
+// Operadores logicos:
+var b: bool, thisBool = false, thatBool = true;
+b = thisBool && thatBool; // Lógico y
+b = thisBool || thatBool; // Lógico o
+b = !thisBool; // Lógico negación
+
+// Operadores relacionales:
+b = thisInt > thatInt; // Mas grande que
+b = thisInt >= thatInt; // Mas grande o igual que
+b = thisInt < a && a <= thatInt; // Menor que, y, Menor o igual que
+b = thisInt != thatInt; // No es igual a
+b = thisInt == thatInt; // es igual a
+
+// Operadores bit a bit:
+a = thisInt << 10; // Desplazamiento de bit izquierdo por 10 bits;
+a = thatInt >> 5; // Desplazamiento de bit derecho por 5 bits;
+a = ~thisInt; // Negación bit a bit
+a = thisInt ^ thatInt; // bit a bit exclusivo o
+
+// Operadores de asignación compuesta:
+a += thisInt; // Adición-igual (a = a + thisInt;)
+a *= thatInt; // Multiplicación-igual (a = a * thatInt;)
+b &&= thatBool; // Lógico e igual (b = b && thatBool;)
+a <<= 3; // Desplazamiento a la izquierda igual (a = a << 10;)
+
+// A diferencia de otros lenguajes de familia C, no hay operadores de
+// pre / post-incremento / decremento, tales como:
+//
+// ++j, --j, j++, j--
+
+// Operador de intercambio:
+var old_this = thisInt;
+var old_that = thatInt;
+thisInt <=> thatInt; // Intercambia los valores de thisInt y thatInt
+writeln((old_this == thatInt) && (old_that == thisInt));
+
+// También se pueden definir sobrecargas del operador, como veremos con los procedimientos.
+
+// Tuplas
+
+// Las tuplas pueden ser del mismo tipo o de diferentes tipos.
+var sameTup: 2*int = (10, -1);
+var sameTup2 = (11, -6);
+var diffTup: (int,real,complex) = (5, 1.928, myCplx);
+var diffTupe2 = (7, 5.64, 6.0+1.5i);
+
+// Se puede acceder a las tuplas usando corchetes o paréntesis,
+// y están indexadas en base 1.
+writeln("(", sameTup[1], ",", sameTup(2), ")");
+writeln(diffTup);
+
+// Las tuplas también se pueden escribir.
+diffTup(1) = -1;
+
+// Los valores de tupla se pueden expandir a sus propias variables.
+var (tupInt, tupReal, tupCplx) = diffTup;
+writeln(diffTup == (tupInt, tupReal, tupCplx));
+
+// También son útiles para imprimit una lista de variables,
+// como es común en la depuración.
+writeln((a,b,thisInt,thatInt,thisBool,thatBool));
+
+// Flujo de control
+
+// if - then - else funciona como cualquier otro lenguaje de la familia C.
+if 10 < 100 then
+ writeln("All is well");
+
+if -1 < 1 then
+ writeln("Continuando creyendo en la realidad");
+else
+ writeln("¡Envia un matemático!, algo está mal");
+
+// Puedes usar paréntesis si lo prefieres.
+if (10 > 100) {
+ writeln("El Universo está roto, Por favor reinicie el universo.");
+}
+
+if a % 2 == 0 {
+ writeln(a, " es par.");
+} else {
+ writeln(a, " es impar.");
+}
+
+if a % 3 == 0 {
+ writeln(a, " es divisible entre 3.");
+} else if a % 3 == 1 {
+ writeln(a, " es divisible entre 3 con un residuo de 1.");
+} else {
+ writeln(b, " es divisible entre 3 con un residuo de 2.");
+}
+
+// Ternario: if - then - else en una declaración.
+var maximum = if thisInt < thatInt then thatInt else thisInt;
+
+// las declaraciones select son muy parecidas a las declaraciones switch
+// en otros idiomas. Sin embargo, las declaraciones select no caen
+// en cascada como en C o Java.
+var inputOption = "anOption";
+select inputOption {
+ when "anOption" do writeln("Escoge 'anOption'");
+ when "otherOption" {
+ writeln("Escoge 'otherOption'");
+ writeln("Que tiene un cuerpo");
+ }
+ otherwise {
+ writeln("Cualquier otra entrada");
+ writeln("El caso otherwise no necesita hacerse si el cuerpo es de una línea");
+ }
+}
+
+// Los bucles while y do-while también se comportan como sus contrapartes en C.
+var j: int = 1;
+var jSum: int = 0;
+while (j <= 1000) {
+ jSum += j;
+ j += 1;
+}
+writeln(jSum);
+
+do {
+ jSum += j;
+ j += 1;
+} while (j <= 10000);
+writeln(jSum);
+
+// Los bucles for son muy parecidos a los de Python porque iteran en un rango.
+// Los rangos (como la expresión 1..10 a continuación) son un objeto de primera clase
+// en Chapel, y como tal pueden almacenarse en variables.
+for i in 1..10 do write(i, ", ");
+writeln();
+
+var iSum: int = 0;
+for i in 1..1000 {
+ iSum += i;
+}
+writeln(iSum);
+
+for x in 1..10 {
+ for y in 1..10 {
+ write((x,y), "\t");
+ }
+ writeln();
+}
+
+// Rangos y Dominios
+
+// Los bucles y matrices utilizan rangos y dominios para definir un conjunto de índices
+// que se pueden iterar. Los rangos son índices enteros unidimensionales, mientras
+// que los dominios pueden ser multidimensionales y representan índices
+// de diferentes tipos.
+
+// Son tipos ciudadanos de primera clase y pueden asignarse a variables.
+var range1to10: range = 1..10; // 1, 2, 3, ..., 10
+var range2to11 = 2..11; // 2, 3, 4, ..., 11
+var rangeThisToThat: range = thisInt..thatInt; // usando variables
+var rangeEmpty: range = 100..-100; // esto es válido pero no contiene índices
+
+// Los rangos pueden ser ilimitados.
+var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ...
+var rangeNegInfTo1 = ..1; // ..., -4, -3, -2, -1, 0, 1
+
+// Los rangos se pueden andar (y revertir) utilizando el operador by.
+var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10
+var reverse2to10by2 = 2..10 by -2; // 10, 8, 6, 4, 2
+
+var trapRange = 10..1 by -1; // No te dejes engañar, esto sigue siendo un rango vacío
+writeln("Size of range ", trapRange, " = ", trapRange.length);
+
+// Note: range(boundedType= ...) and range(stridable= ...) solo son necesarios
+// si escribimos explícitamente la variable.
+
+// El punto final de un rango se puede determinar utilizando el operador de conteo (#).
+var rangeCount: range = -5..#12; // intervalo de -5 to 6
+
+// Los operadores pueden ser mixtos.
+var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5
+writeln(rangeCountBy);
+
+// Se pueden consultar las propiedades del rango.
+// En este ejemplo, imprime el primer índice, el último índice, el número de índices,
+// el paso y si 2 se incluye en el rango.
+writeln((rangeCountBy.first, rangeCountBy.last, rangeCountBy.length,
+ rangeCountBy.stride, rangeCountBy.member(2)));
+
+for i in rangeCountBy {
+ write(i, if i == rangeCountBy.last then "\n" else ", ");
+}
+
+// Los dominios rectangulares se definen usando la misma sintaxis de rango,
+// pero se requiere que estén delimitados (a diferencia de los rangos).
+var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10;
+var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges
+var thirdDim: range = 1..16;
+var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable
+
+// Los dominios también pueden ser redimensionados
+var resizedDom = {1..10};
+writeln("antes, resizedDom = ", resizedDom);
+resizedDom = {-10..#10};
+writeln("despues, resizedDom = ", resizedDom);
+
+// Los índices pueden iterarse como tuplas.
+for idx in twoDimensions do
+ write(idx, ", ");
+writeln();
+
+// Estas tuplas también pueden ser deconstruidas.
+for (x,y) in twoDimensions {
+ write("(", x, ", ", y, ")", ", ");
+}
+writeln();
+
+// Los dominios asociativos actúan como conjuntos.
+var stringSet: domain(string); // empty set of strings
+stringSet += "a";
+stringSet += "b";
+stringSet += "c";
+stringSet += "a"; // Redundant add "a"
+stringSet -= "c"; // Remove "c"
+writeln(stringSet.sorted());
+
+// Los dominios asociativos también pueden tener una sintaxis literal
+var intSet = {1, 2, 4, 5, 100};
+
+// Tanto los rangos como los dominios se pueden dividir para producir un rango
+// o dominio con la intersección de los índices.
+var rangeA = 1.. ; // range from 1 to infinity
+var rangeB = ..5; // range from negative infinity to 5
+var rangeC = rangeA[rangeB]; // resulting range is 1..5
+writeln((rangeA, rangeB, rangeC));
+
+var domainA = {1..10, 5..20};
+var domainB = {-5..5, 1..10};
+var domainC = domainA[domainB];
+writeln((domainA, domainB, domainC));
+
+// Matrices
+
+// Las matrices son similares a otros lenguajes.
+// Sus tamaños son definidos usndo dominions que repretsenten sus indices.
+var intArray: [1..10] int;
+var intArray2: [{1..10}] int; // equivalent
+
+// Pueden ser accedidos usando brackets o paréntesis
+for i in 1..10 do
+ intArray[i] = -i;
+writeln(intArray);
+
+// No podemos acceder a intArray[0] porque existe fuera del conjunto de índices,
+// {1..10}, que definimos al principio.
+// intArray [11] es ilegal por la misma razón.
+var realDomain: domain(2) = {1..5,1..7};
+var realArray: [realDomain] real;
+var realArray2: [1..5,1..7] real; // equivalent
+var realArray3: [{1..5,1..7}] real; // equivalent
+
+for i in 1..5 {
+ for j in realDomain.dim(2) { // Solo use la segunda dimensión del dominio
+ realArray[i,j] = -1.61803 * i + 0.5 * j; // Acceso usando la lista de índice
+ var idx: 2*int = (i,j); // Nota: 'índice' es una palabra reservada
+ realArray[idx] = - realArray[(i,j)]; // Indice usando tuplas
+ }
+}
+
+// Las matrices tienen dominios como miembros y pueden ser iterados de manera normal.
+for idx in realArray.domain { // De nuevo, idx es una tupla 2*int
+ realArray[idx] = 1 / realArray[idx[1], idx[2]]; // Acceso por tupla y lista
+}
+
+writeln(realArray);
+
+// Los valores de una matriz también se pueden iterar directamente.
+var rSum: real = 0;
+for value in realArray {
+ rSum += value; // Read a value
+ value = rSum; // Write a value
+}
+writeln(rSum, "\n", realArray);
+
+// Las matrices asociativas (diccionarios) se pueden crear utilizando dominios asociativos.
+var dictDomain: domain(string) = { "one", "two" };
+var dict: [dictDomain] int = ["one" => 1, "two" => 2];
+dict["three"] = 3; // Adiciona 'three' a 'dictDomain' implícitamente
+for key in dictDomain.sorted() do
+ writeln(dict[key]);
+
+// Las matrices se pueden asignar entre sí de diferentes maneras.
+// Estos arreglos se usarán en el ejemplo.
+
+var thisArray : [0..5] int = [0,1,2,3,4,5];
+var thatArray : [0..5] int;
+
+// Primero, simplemente asigna uno al otro. Esto copia esta matriz en
+// thatArray, en lugar de simplemente crear una referencia. Por lo tanto, modificando
+// thisArray tampoco modifica thatArray.
+thatArray = thisArray;
+thatArray[1] = -1;
+writeln((thisArray, thatArray));
+
+// Asigna un segmento de una matriz a un segmento (del mismo tamaño) en el otro.
+thatArray[4..5] = thisArray[1..2];
+writeln((thisArray, thatArray));
+
+// Las operaciones también se pueden promover para trabajar en arreglos.
+// 'thisPlusThat' también es una matriz.
+var thisPlusThat = thisArray + thatArray;
+writeln(thisPlusThat);
+
+// Continuando, las matrices y los bucles también pueden ser expresiones, donde
+// la expresión del cuerpo del bucle es el resultado de cada iteración.
+var arrayFromLoop = for i in 1..10 do i;
+writeln(arrayFromLoop);
+
+// Una expresión puede resultar en nada, como cuando se filtra con una expresión if.
+var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i;
+
+writeln(arrayFromLoop);
+
+// Las expresiones de matriz también se pueden escribir con una notación de paréntesis.
+// Nota: esta sintaxis utiliza el concepto paralelo forall discutido más adelante.
+var evensOrFivesAgain = [i in 1..10] if (i % 2 == 0 || i % 5 == 0) then i;
+
+// They can also be written over the values of the array.
+arrayFromLoop = [value in arrayFromLoop] value + 1;
+
+
+// Procedimientos
+
+// Los procedimientos de Chapel tienen funciones de sintaxis similares en otros idiomas.
+proc fibonacci(n : int) : int {
+ if n <= 1 then return n;
+ return fibonacci(n-1) + fibonacci(n-2);
+}
+
+// Los parámetros de entrada pueden estar sin tipo para crear un procedimiento genérico.
+proc doublePrint(thing): void {
+ write(thing, " ", thing, "\n");
+}
+
+// Se puede inferir el tipo de retorno, siempre que el compilador pueda resolverlo.
+proc addThree(n) {
+ return n + 3;
+}
+
+doublePrint(addThree(fibonacci(20)));
+
+// También es posible tomar un número variable de parámetros.
+proc maxOf(x ...?k) {
+ // x se refiere a una tupla de un tipo, con k elementos
+ var maximum = x[1];
+ for i in 2..k do maximum = if maximum < x[i] then x[i] else maximum;
+ return maximum;
+}
+writeln(maxOf(1, -10, 189, -9071982, 5, 17, 20001, 42));
+
+// Los procedimientos pueden tener valores de parámetros predeterminados, y
+// los parámetros pueden nombrarse en la llamada, incluso fuera de orden.
+proc defaultsProc(x: int, y: real = 1.2634): (int,real) {
+ return (x,y);
+}
+
+writeln(defaultsProc(10));
+writeln(defaultsProc(x=11));
+writeln(defaultsProc(x=12, y=5.432));
+writeln(defaultsProc(y=9.876, x=13));
+
+// El operador ? se llama operador de consulta y se usa para tomar valores
+// indeterminados como tuplas o tamaños de matriz y tipos genéricos.
+// Por ejemplo, tomar matrices como parámetros.
+
+// El operador de consulta se utiliza para determinar el dominio de A.
+// Esto es útil para definir el tipo de retorno, aunque no es obligatorio.
+proc invertArray(A: [?D] int): [D] int{
+ for a in A do a = -a;
+ return A;
+}
+
+writeln(invertArray(intArray));
+
+// Podemos consultar el tipo de argumentos a los procedimientos genéricos.
+// Aquí definimos un procedimiento que toma dos argumentos del mismo tipo,
+// pero no definimos cuál es ese tipo.
+proc genericProc(arg1 : ?valueType, arg2 : valueType): void {
+ select(valueType) {
+ when int do writeln(arg1, " and ", arg2, " are ints");
+ when real do writeln(arg1, " and ", arg2, " are reals");
+ otherwise writeln(arg1, " and ", arg2, " are somethings!");
+ }
+}
+
+genericProc(1, 2);
+genericProc(1.2, 2.3);
+genericProc(1.0+2.0i, 3.0+4.0i);
+
+// También podemos imponer una forma de polimorfismo con la cláusula where
+// Esto permite que el compilador decida qué función usar.
+
+// Nota: Eso significa que toda la información debe conocerse en tiempo de compilación.
+// El modificador param en el argumento se usa para imponer esta restricción.
+proc whereProc(param N : int): void
+ where (N > 0) {
+ writeln("N is greater than 0");
+}
+
+proc whereProc(param N : int): void
+ where (N < 0) {
+ writeln("N is less than 0");
+}
+
+whereProc(10);
+whereProc(-1);
+
+// whereProc(0) daría lugar a un error del compilador porque no hay funciones
+// que satisfagan la condición de la cláusula where.
+// Podríamos haber definido un whereProc sin una cláusula where que
+// hubiera servido como captura para todos los demás casos (de los cuales solo hay uno).
+
+// Las cláusulas where también se pueden usar para restringir según el tipo de argumento.
+proc whereType(x: ?t) where t == int {
+ writeln("Inside 'int' version of 'whereType': ", x);
+}
+
+proc whereType(x: ?t) {
+ writeln("Inside general version of 'whereType': ", x);
+}
+
+whereType(42);
+whereType("hello");
+
+// Intenciones
+
+/* Los modificadores de intención en los argumentos transmiten cómo esos argumentos se pasan al procedimiento.
+
+ * in: copia arg adentro, pero no afuera
+ * out: copia arg, pero no dentro
+ * inout: copia arg adentro, copia arg afuera
+ * ref: pasa arg por referencia
+*/
+proc intentsProc(in inarg, out outarg, inout inoutarg, ref refarg) {
+ writeln("Adentro antes: ", (inarg, outarg, inoutarg, refarg));
+ inarg = inarg + 100;
+ outarg = outarg + 100;
+ inoutarg = inoutarg + 100;
+ refarg = refarg + 100;
+ writeln("Adentro después: ", (inarg, outarg, inoutarg, refarg));
+}
+
+var inVar: int = 1;
+var outVar: int = 2;
+var inoutVar: int = 3;
+var refVar: int = 4;
+writeln("Afuera antes: ", (inVar, outVar, inoutVar, refVar));
+intentsProc(inVar, outVar, inoutVar, refVar);
+writeln("Afuera después: ", (inVar, outVar, inoutVar, refVar));
+
+// Del mismo modo, podemos definir intentos en el tipo de retorno.
+// refElement devuelve una referencia a un elemento de la matriz. Esto tiene más sentido
+// práctico para los métodos de clase donde las referencias a elementos en una estructura
+// de datos se devuelven a través de un método o iterador.
+proc refElement(array : [?D] ?T, idx) ref : T {
+ return array[idx];
+}
+
+var myChangingArray : [1..5] int = [1,2,3,4,5];
+writeln(myChangingArray);
+ref refToElem = refElement(myChangingArray, 5); // Almacena una referencia al elemento en variable de referencia
+writeln(refToElem);
+refToElem = -2; // modifica referencia que, a su vez, modifica el valor real en la matriz
+writeln(refToElem);
+writeln(myChangingArray);
+
+// Definiciones del operador
+
+// Chapel permite que los operadores se sobrecarguen.
+// Podemos definir los operadores unarios:
+// + - ! ~
+// y los operadores binarios:
+// + - * / % ** == <= >= < > << >> & | ˆ by
+// += -= *= /= %= **= &= |= ˆ= <<= >>= <=>
+
+// Exclusivo u operador booleano.
+proc ^(left : bool, right : bool): bool {
+ return (left || right) && !(left && right);
+}
+
+writeln(true ^ true);
+writeln(false ^ true);
+writeln(true ^ false);
+writeln(false ^ false);
+
+// Define un operador * en cualquiera de los dos tipos que devuelve una tupla de esos tipos.
+proc *(left : ?ltype, right : ?rtype): (ltype, rtype) {
+ writeln("\tIn our '*' overload!");
+ return (left, right);
+}
+
+writeln(1 * "a"); // Utiliza nuestro * operador.
+writeln(1 * 2); // Utiliza el operador predeterminado *.
+
+// Note: Podrías romper todo si te descuidas con tus sobrecargas.
+// Esto aquí lo romperá todo. No lo hagas
+
+/*
+ proc +(left: int, right: int): int {
+ return left - right;
+ }
+*/
+
+// Iteradores
+
+// Los iteradores son hermanas del procedimiento, y casi todo lo relacionado
+// con los procedimientos también se aplica a los iteradores. Sin embargo, en lugar de
+// devolver un solo valor, los iteradores pueden generar múltiples valores en un bucle.
+
+// Esto es útil cuando se necesita un conjunto u orden complicado de iteraciones,
+// ya que permite que el código que define las iteraciones
+// se separe del cuerpo del bucle.
+iter oddsThenEvens(N: int): int {
+ for i in 1..N by 2 do
+ yield i; // yield values instead of returning.
+ for i in 2..N by 2 do
+ yield i;
+}
+
+for i in oddsThenEvens(10) do write(i, ", ");
+writeln();
+
+// Los iteradores también pueden ceder condicionalmente, cuyo resultado puede ser nada
+iter absolutelyNothing(N): int {
+ for i in 1..N {
+ if N < i { // Always false
+ yield i; // Yield statement never happens
+ }
+ }
+}
+
+for i in absolutelyNothing(10) {
+ writeln("Woa there! absolutelyNothing yielded ", i);
+}
+
+// Podemos comprimir dos o más iteradores (que tienen el mismo número de iteraciones)
+// usando zip () para crear un solo iterador comprimido, donde cada iteración
+// del iterador comprimido produce una tupla de un valor de cada iterador.
+for (positive, negative) in zip(1..5, -5..-1) do
+ writeln((positive, negative));
+
+// La iteración de la cremallera es bastante importante en la asignación de matrices,
+// segmentos de matrices y expresiones de matriz / bucle.
+var fromThatArray : [1..#5] int = [1,2,3,4,5];
+var toThisArray : [100..#5] int;
+
+// Algunas operaciones de cierre implementan otras operaciones.
+// La primera declaración y el bucle son equivalentes.
+toThisArray = fromThatArray;
+for (i,j) in zip(toThisArray.domain, fromThatArray.domain) {
+ toThisArray[i] = fromThatArray[j];
+}
+
+// Estos dos pedazos también son equivalentes.
+toThisArray = [j in -100..#5] j;
+writeln(toThisArray);
+
+for (i, j) in zip(toThisArray.domain, -100..#5) {
+ toThisArray[i] = j;
+}
+writeln(toThisArray);
+
+/*
+ Esto es muy importante para entender por qué esta declaración
+ exhibe un error de tiempo de ejecución.
+*/
+
+/*
+ var iterArray : [1..10] int = [i in 1..10] if (i % 2 == 1) then i;
+*/
+
+// Aunque el dominio de la matriz y la expresión de bucle son del mismo tamaño,
+// el cuerpo de la expresión puede considerarse como un iterador.
+// Debido a que los iteradores pueden producir nada, ese iterador produce un número
+// diferente de cosas que el dominio de la matriz o bucle, que no está permitido.
+
+// Clases
+
+// Las clases son similares a las de C ++ y Java, asignadas en el montón.
+class MyClass {
+
+// Variables miembro
+ var memberInt : int;
+ var memberBool : bool = true;
+
+// Inicializador definido explícitamente.
+// También obtenemos el inicializador generado por el compilador, con un argumento por campo.
+// Tenga en cuenta que pronto no habrá un inicializador generado por el compilador
+// cuando definamos los inicializadores explícitamente.
+ proc init(val : real) {
+ this.memberInt = ceil(val): int;
+ }
+
+// Desinicializador explícitamente definido.
+// Si no escribiéramos uno, obtendríamos el desinicializador generado por el compilador,
+// que tiene un cuerpo vacío.
+ proc deinit() {
+ writeln("MyClass deinitializer called ", (this.memberInt, this.memberBool));
+ }
+
+// Métodos de clase.
+ proc setMemberInt(val: int) {
+ this.memberInt = val;
+ }
+
+ proc setMemberBool(val: bool) {
+ this.memberBool = val;
+ }
+
+ proc getMemberInt(): int{
+ return this.memberInt;
+ }
+
+ proc getMemberBool(): bool {
+ return this.memberBool;
+ }
+} // termina MyClass
+
+// Llame al inicializador generado por el compilador,
+// utilizando el valor predeterminado para memberBool.
+var myObject = new MyClass(10);
+ myObject = new MyClass(memberInt = 10); // Equivalente
+writeln(myObject.getMemberInt());
+
+// Same, but provide a memberBool value explicitly.
+var myDiffObject = new MyClass(-1, true);
+ myDiffObject = new MyClass(memberInt = -1, memberBool = true); // Equivalente
+writeln(myDiffObject);
+
+// Llame al inicializador que escribimos.
+var myOtherObject = new MyClass(1.95);
+ myOtherObject = new MyClass(val = 1.95); // Equivalente
+writeln(myOtherObject.getMemberInt());
+
+// También podemos definir un operador en nuestra clase,
+// pero la definición tiene que estar fuera de la definición de la clase.
+proc +(A : MyClass, B : MyClass) : MyClass {
+ return new MyClass(memberInt = A.getMemberInt() + B.getMemberInt(),
+ memberBool = A.getMemberBool() || B.getMemberBool());
+}
+
+var plusObject = myObject + myDiffObject;
+writeln(plusObject);
+
+// Destrucción.
+delete myObject;
+delete myDiffObject;
+delete myOtherObject;
+delete plusObject;
+
+// Las clases pueden heredar de una o más clases primarias
+class MyChildClass : MyClass {
+ var memberComplex: complex;
+}
+
+// Aquí hay un ejemplo de clases genéricas.
+class GenericClass {
+ type classType;
+ var classDomain: domain(1);
+ var classArray: [classDomain] classType;
+
+// Constructor explícito.
+ proc GenericClass(type classType, elements : int) {
+ this.classDomain = {1..#elements};
+ }
+
+// Copiar constructor.
+// Nota: Todavía tenemos que poner el tipo como argumento, pero podemos usar
+// el operador de consulta (?) como predeterminado para el tipo del otro objeto.
+// Además, podemos aprovechar esto para permitir a nuestro constructor de copias
+// copiar clases de diferentes tipos y emitir sobre la marcha.
+ proc GenericClass(other : GenericClass(?otherType),
+ type classType = otherType) {
+ this.classDomain = other.classDomain;
+ // Copiar y Convertir
+ for idx in this.classDomain do this[idx] = other[idx] : classType;
+ }
+
+// Defina la notación de corchetes en un objeto GenericClass
+// para que pueda comportarse como una matriz normal
+// i.e. objVar[i] or objVar(i)
+ proc this(i : int) ref : classType {
+ return this.classArray[i];
+ }
+
+// Definir un iterador implícito para que la clase produzca
+// valores de la matriz a un bucle
+// i.e. for i in objVar do ...
+ iter these() ref : classType {
+ for i in this.classDomain do
+ yield this[i];
+ }
+} // end GenericClass
+
+// Podemos asignar a la matriz de miembros del objeto usando la notación de
+// corchete que definimos.
+var realList = new GenericClass(real, 10);
+for i in realList.classDomain do realList[i] = i + 1.0;
+
+// Podemos iterar sobre los valores en nuestra lista con el iterador
+// que definimos.
+for value in realList do write(value, ", ");
+writeln();
+
+// Haga una copia de realList usando el constructor de copias.
+var copyList = new GenericClass(realList);
+for value in copyList do write(value, ", ");
+writeln();
+
+// Haga una copia de realList y cambie el tipo, también utilizando el constructor de copias.
+var copyNewTypeList = new GenericClass(realList, int);
+for value in copyNewTypeList do write(value, ", ");
+writeln();
+
+
+// Módulos
+
+// Los módulos son la forma en que Chapel administra los espacios de nombres.
+// Los archivos que contienen estos módulos no necesitan ser nombrados después
+// de los módulos (como en Java), pero los archivos implícitamente nombran módulos.
+// Por ejemplo, este archivo nombra implícitamente el módulo learnChapelInYMinutes
+
+module OurModule {
+
+// Podemos usar módulos dentro de otros módulos.
+// Time es uno de los módulos estándar.
+ use Time;
+
+// Usaremos este procedimiento en la sección de paralelismo.
+ proc countdown(seconds: int) {
+ for i in 1..seconds by -1 {
+ writeln(i);
+ sleep(1);
+ }
+ }
+
+// Es posible crear nidos de módulos arbitrariamente profundos.
+// i.e. submódulos de OurModule
+ module ChildModule {
+ proc foo() {
+ writeln("ChildModule.foo()");
+ }
+ }
+
+ module SiblingModule {
+ proc foo() {
+ writeln("SiblingModule.foo()");
+ }
+ }
+} // end OurModule
+
+// Usando OurModule también usa todos los módulos que usa.
+// Como OurModule usa Time, nosotros también usamos Time.
+use OurModule;
+
+// En este punto no hemos usado ChildModule o SiblingModule, por lo que sus símbolos
+// (es decir, foo) no están disponibles para nosotros. Sin embargo, los nombres de
+// los módulos están disponibles y podemos llamar explícitamente a foo () a través de ellos.
+SiblingModule.foo();
+OurModule.ChildModule.foo();
+
+// Ahora usamos ChildModule, que permite llamadas no calificadas.
+use ChildModule;
+foo();
+
+// Paralelismo
+
+// En otros idiomas, el paralelismo generalmente se realiza con librerias complicadas
+// y extrañas jerarquías de estructura de clases.
+// Chapel lo tiene directamente en el idioma.
+
+// Podemos declarar un procedimiento principal, pero todo el código anterior
+// a main todavía se ejecuta.
+proc main() {
+
+// Una declaración de inicio hará girar el cuerpo de esa declaración en una nueva tarea.
+// Una declaración de sincronización garantizará que el progreso de la tarea principal
+// no avance hasta que los hijos hayan sincronizado nuevamente.
+
+ sync {
+ begin { // Inicio del cuerpo de la nueva tarea.
+ var a = 0;
+ for i in 1..1000 do a += 1;
+ writeln("Done: ", a);
+ } // Fin del nuevo cuerpo de tareas
+ writeln("escindió una tarea!");
+ }
+ writeln("De nuevo juntos");
+
+ proc printFibb(n: int) {
+ writeln("fibonacci(",n,") = ", fibonacci(n));
+ }
+
+// Una declaración de cobegin girará cada declaración del cuerpo en una nueva tarea.
+// Observe aquí que las impresiones de cada declaración pueden ocurrir en
+// cualquier orden.
+ cobegin {
+ printFibb(20); // nueva tarea
+ printFibb(10); // nueva tarea
+ printFibb(5); // nueva tarea
+ {
+ // Este es un cuerpo de declaración anidado y, por lo tanto, es una
+ // declaración única para la declaración principal, ejecutada
+ // por una sola tarea.
+ writeln("esto se ");
+ writeln("ejecuta");
+ writeln("como un todo");
+ }
+ }
+
+// Un bucle coforall creará una nueva tarea para CADA iteración.
+// Nuevamente vemos que las impresiones suceden en cualquier orden.
+// NOTA: ¡coforall debe usarse solo para crear tareas!
+// ¡Usarlo para iterar sobre una estructura es una muy mala idea!
+ var num_tasks = 10; // Number of tasks we want
+ coforall taskID in 1..#num_tasks {
+ writeln("Hola de tarea# ", taskID);
+ }
+
+// los bucles forall son otro bucle paralelo, pero solo crean un número
+// menor de tareas, específicamente --dataParTasksPerLocale = número de tareas.
+ forall i in 1..100 {
+ write(i, ", ");
+ }
+ writeln();
+
+// Aquí vemos que hay secciones que están en orden, seguidas de una sección
+// que no seguiría (por ejemplo, 1, 2, 3, 7, 8, 9, 4, 5, 6,).
+// Esto se debe a que cada tarea está asumiendo un fragmento del rango 1..10
+// (1..3, 4..6 o 7..9) haciendo ese fragmento en serie, pero cada tarea ocurre en paralelo.
+// Sus resultados pueden depender de su máquina y configuración
+
+// Para los bucles forall y coforall, la ejecución de la tarea principal
+// no continuará hasta que todos los hijos se sincronicen.
+
+// los bucles forall son particularmente útiles para la iteración paralela sobre matrices.
+// Hagamos un experimento para ver qué tan rápido es un ciclo paralelo.
+
+ use Time; // Importe el módulo Time para usar objetos de Timer
+ var timer: Timer;
+ var myBigArray: [{1..4000,1..4000}] real; // Gran matriz en la que escribiremos
+
+// Experimento en serie:
+ timer.start(); // Iniciar temporizador
+ for (x,y) in myBigArray.domain { // Iteración en serie
+ myBigArray[x,y] = (x:real) / (y:real);
+ }
+ timer.stop(); // Detener temporizador
+ writeln("Serial: ", timer.elapsed()); // Imprimir tiempo transcurrido
+ timer.clear(); // Limpia el temporizador para bucle paralelo
+
+// Experimento Paralelo:
+ timer.start(); // Iniciar temporizador
+ forall (x,y) in myBigArray.domain { // Iteración paralela
+ myBigArray[x,y] = (x:real) / (y:real);
+ }
+ timer.stop(); // Detener temporizador
+ writeln("Parallel: ", timer.elapsed()); // Imprimir tiempo transcurrido
+ timer.clear();
+
+// Puede que hayas notado que (dependiendo de cuántos núcleos tengas)
+// el ciclo paralelo fue más rápido que el ciclo serial.
+
+// La expresión de bucle estilo corchete descrita mucho antes utiliza
+// implícitamente un bucle forall.
+ [val in myBigArray] val = 1 / val; // Operación paralela
+
+// Las variables atómicas, comunes a muchos idiomas, son aquellas cuyas operaciones
+// ocurren sin interrupciones. Por lo tanto, varios subprocesos pueden modificar
+// las variables atómicas y pueden saber que sus valores son seguros.
+// Las variables atómicas de la capilla pueden ser de tipo bool, int, uint y real.
+ var uranium: atomic int;
+ uranium.write(238); // escribir atómicamente una variable
+ writeln(uranium.read()); // leer atómicamente una variable
+
+// Las operaciones atómicas se describen como funciones, por lo que puede definir
+// las suyas propias.
+ uranium.sub(3); // restar atómicamente una variable
+ writeln(uranium.read());
+
+ var replaceWith = 239;
+ var was = uranium.exchange(replaceWith);
+ writeln("El uranio era", was, ", pero ahora es ", replaceWith);
+
+ var isEqualTo = 235;
+ if uranium.compareExchange(isEqualTo, replaceWith) {
+ writeln("El uranio era igual a ", isEqualTo,
+ " pero valor reemplazado por", replaceWith);
+ } else {
+ writeln("uranio no era igual a ", isEqualTo,
+ " así que el valor permanece igual... sea lo que sea");
+ }
+
+ sync {
+ begin { // Tarea del lector
+ writeln("Lector: esperando que el uranio sea ", isEqualTo);
+ uranium.waitFor(isEqualTo);
+ writeln("Lector: el uranio fue configurado (por alguien) para ", isEqualTo);
+ }
+
+ begin { // Tarea de escritor
+ writeln("Escritor: establecerá uranio en el valor ", isEqualTo, " en...");
+ countdown(3);
+ uranium.write(isEqualTo);
+ }
+ }
+
+// las variables de sincronización tienen dos estados: vacío y lleno.
+// Si lee una variable vacía o escribe una variable completa,
+// se espera hasta que la variable esté llena o vacía nuevamente.
+ var someSyncVar$: sync int; // varName$ Es una convención, no una ley.
+ sync {
+ begin { // Tarea del lector
+ writeln("Lector: esperando leer.");
+ var read_sync = someSyncVar$;
+ writeln("Lector: el valor es ", read_sync);
+ }
+
+ begin { // Tarea de escritor
+ writeln("Escritor: escribirá en...");
+ countdown(3);
+ someSyncVar$ = 123;
+ }
+ }
+
+// las variales individuales solo se pueden escribir una vez.
+// Una lectura en un solo no escrito da como resultado una espera,
+// pero cuando la variable tiene un valor, puede leerse indefinidamente.
+ var someSingleVar$: single int; // varName$ Es una convención, no una ley.
+ sync {
+ begin { // Tarea del lector
+ writeln("Lector: esperando leer.");
+ for i in 1..5 {
+ var read_single = someSingleVar$;
+ writeln("Lector: iteración ", i,", y el valor es ", read_single);
+ }
+ }
+
+ begin { // Tarea de escritor
+ writeln("Escritor: escribirá en ...");
+ countdown(3);
+ someSingleVar$ = 5; // primero y único escrito.
+ }
+ }
+
+// Aquí hay un ejemplo usando atómica y una variable de sincronización
+// para crear un mutex de cuenta regresiva
+// (también conocido como multiplexor).
+ var count: atomic int; // nuestro mostrador
+ var lock$: sync bool; // la cerradura mutex
+
+ count.write(2); // Solo deje dos tareas a la vez.
+ lock$.writeXF(true); // Establezca lock$ en completo (desbloqueado)
+ // Nota: el valor en realidad no importa, solo el estado
+ // (completo: desbloqueado / vacio: bloqueado)
+ // Además, writeXF() llena (F) la variable de sincronización independientemente de su estado (X)
+
+ coforall task in 1..#5 { // Generar tareas
+ // Create a barrier
+ do {
+ lock$; // Leer lock$ (espera)
+ } while (count.read() < 1); // Sigue esperando hasta que se abra un lugar
+
+ count.sub(1); //disminuir el contador
+ lock$.writeXF(true); // Establezca lock$ en completo (señal)
+
+ // 'Trabajo' actual
+ writeln("Tarea #", task, " trabajando");
+ sleep(2);
+
+ count.add(1); // Incrementa el contador
+ lock$.writeXF(true); // Establezca lock$ en completo (señal)
+ }
+
+// Podemos definir las operaciones + * & | ^ && || min max minloc maxloc
+// sobre una matriz completa usando escaneos y reducciones.
+// Las reducciones aplican la operación en toda la matriz
+// y dan como resultado un valor escalar.
+
+ var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2];
+ var sumOfValues = + reduce listOfValues;
+ var maxValue = max reduce listOfValues; // 'max' da solo el valor máximo
+
+// maxloc proporciona el valor máximo y el índice del valor máximo.
+// Nota: Tenemos que comprimir la matriz y el dominio junto con el iterador zip.
+ var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues,
+ listOfValues.domain);
+
+ writeln((sumOfValues, maxValue, idxOfMax, listOfValues[idxOfMax]));
+
+// Los escaneos aplican la operación de forma incremental y devuelven una matriz
+// con los valores de la operación en ese índice a medida que avanza a través
+// de la matriz desde array.domain.low hasta array.domain.high.
+ var runningSumOfValues = + scan listOfValues;
+ var maxScan = max scan listOfValues;
+ writeln(runningSumOfValues);
+ writeln(maxScan);
+} // end main()
+```
+
+¿Para quién es este tutorial?
+-------------------------
+
+Este tutorial es para personas que desean aprender las cuerdas de chapel sin tener
+que escuchar sobre qué mezcla de fibras son las cuerdas, o cómo fueron trenzadas,
+o cómo las configuraciones de trenzas difieren entre sí. No le enseñará cómo
+desarrollar código increíblemente eficaz, y no es exhaustivo.
+Referirse a [especificación de idioma](https://chapel-lang.org/docs/latest/language/spec.html)(en) y
+a [documentación del módulo](https://chapel-lang.org/docs/latest/)(en) para más detalles.
+
+Ocasionalmente, vuelva aquí en el [website de Chapel](https://chapel-lang.org)
+para ver si se han agregado más temas o se han creado más tutoriales.
+
+### Lo que le falta a este tutorial:
+
+ * Exposición de los [módulos estándar](https://chapel-lang.org/docs/latest/modules/standard.html)
+ * Múltiples configuraciones regionales (sistema de memoria distribuida)
+ * Registros
+ * Iteradores paralelos
+
+¡Sus comentarios, preguntas y descubrimientos son importantes para los desarrolladores!
+-----------------------------------------------------------------------
+
+El lenguaje Chapel todavía está en desarrollo activo, por lo que
+ocasionalmente hay problemas con el rendimiento y
+las características del lenguaje.
+
+Cuanta más información brinde al equipo de desarrollo de Chapel
+sobre los problemas que encuentre o las características que le gustaría ver,
+mejor será el lenguaje.
+
+
+Hay varias formas de interactuar con los desarrolladores:
++ [Chat de Gitter](https://gitter.im/chapel-lang/chapel)
++ [lista de emails de Sourceforge](https://sourceforge.net/p/chapel/mailman)
+
+Si está realmente interesado en el desarrollo del compilador o en contribuir al proyecto,
+[consulte el repositorio maestro de GitHub](https://github.com/chapel-lang/chapel).
+Está bajo el [La licencia Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0).
+
+Instalar el compilador
+-----------------------
+
+[La documentación oficial de Chapel detalla cómo descargar y compilar el compilador de Chapel.](https://chapel-lang.org/docs/usingchapel/QUICKSTART.html)
+
+Chapel se puede construir e instalar en su máquina promedio 'nix (y cygwin).
+[Descargue la última versión de lanzamiento](https://github.com/chapel-lang/chapel/releases/)
+y es tan fácil como
+
+ 1. `tar -xvf chapel-<VERSION>.tar.gz`
+ 2. `cd chapel-<VERSION>`
+ 3. `source util/setchplenv.bash # or .sh or .csh or .fish`
+ 4. `make`
+ 5. `make check # optional`
+
+You will need to `source util/setchplenv.EXT` from within the Chapel directory
+(`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop
+that command in a script that will get executed on startup (like .bashrc).
+
+Necesitará `source util/setchplenv.EXT` desde el directorio de Chapel (`$CHPL_HOME`)
+cada vez que se inicie su terminal, por lo que se sugiere que suelte ese comando
+en un script que se ejecutará al inicio (como .bashrc).
+
+Chapel se instala fácilmente con Brew para OS X
+
+ 1. `brew update`
+ 2. `brew install chapel`
+
+Compilando Código
+--------------
+
+Construye como otros compiladores:
+
+`chpl myFile.chpl -o myExe`
+
+Argumentos notables:
+
+ * `--fast`: habilita varias optimizaciones y deshabilita las comprobaciones
+ de los límites de la matriz Solo debe habilitarse cuando la aplicación es estable.
+ * `--set <Nombre del Symbolo>=<Valor>`: establece el param de configuracion
+ `<Nombre del Symbolo>` a `<Valor>`en tiempo de compilación.
+ * `--main-module <Nombre del módulo>`: use el procedimiento main() que se encuentra en el módulo
+    `<Nombre del módulo>` como principal del ejecutable.
+ * `--module-dir <Directorio>`: incluye `<Directorio>` en la ruta de búsqueda del módulo.
diff --git a/es-es/clojure-es.html.markdown b/es-es/clojure-es.html.markdown
index 62935ebe..9f25425c 100644
--- a/es-es/clojure-es.html.markdown
+++ b/es-es/clojure-es.html.markdown
@@ -431,7 +431,7 @@ funciones principales (pertenecientes al core):
[http://clojuredocs.org/quickref](http://clojuredocs.org/quickref)
4Clojure es una genial forma de mejorar tus habilidades con clojure/FP:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org (sí, de verdad) tiene un buen número de artículos con los que
iniciarse en Clojure: [http://clojure-doc.org](http://clojure-doc.org)
diff --git a/es-es/css-es.html b/es-es/css-es.html
deleted file mode 100644
index 506a9467..00000000
--- a/es-es/css-es.html
+++ /dev/null
@@ -1,327 +0,0 @@
----
-language: css
-contributors:
- - ["Mohammad Valipour", "https://github.com/mvalipour"]
- - ["Marco Scannadinari", "https://github.com/marcoms"]
- - ["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"]
-translators:
- - ["miky ackerman", "https://github.com/mikyackerman"]
-lang: es-es
-filename: learncss-es.css
----
-
-Paginas web estan contruidas en HTML, lo cual especifica el contenido de una pagina
-CSS(Hoja de Estilos en Cascada) es un lenguaje separado el cual especifica
-la **apariencia** de una pagina.
-
-codigo CSS esta hecho de *reglas* estaticas. Cada regla toma uno o mas *selectores* y da *valores* especificos a un numero de *propiedades* visuales. Esas propiedades estan entonces aplicadas a los elementos indicados en una pagina por los selectores
-
-Esta guia ha sido escrita con CSS 2 en mente, la cual es extendida por una nueva caracterica de CSS 3.
-
-**NOTA:** Debido a que CSS produce resultados visuales, para aprenderlo, necesitas
-Probar todo en un patio de juegos CSS como [dabblet] (http://dabblet.com/).
-El objetivo principal de este artículo es la sintaxis y algunos consejos generales.
-
-## Sintaxis
-
-```css
-/* Los comentarios aparecen dentro de un diagonal-asterisco, justo como esta linea
- no hay "comentarios en una linea"; este es el unico estilo de comentario.*/
-
-
-/* ####################
- ## SELECTORS
- #################### */
-
-/* el selector es usado para apuntar a un elemento de la pagina. */
-selector { property: value; /* more properties...*/ }
-
-/*
-Here is an example element:
-
-<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
-*/
-
-/* You can target it using one of its CSS classes */
-.class1 { }
-
-/* or both classes! */
-.class1.class2 { }
-
-/* or its name */
-div { }
-
-/* or its id */
-#anID { }
-
-/* or using the fact that it has an attribute! */
-[attr] { font-size:smaller; }
-
-/* or that the attribute has a specific value */
-[attr='value'] { font-size:smaller; }
-
-/* starts with a value (CSS 3) */
-[attr^='val'] { font-size:smaller; }
-
-/* or ends with a value (CSS 3) */
-[attr$='ue'] { font-size:smaller; }
-
-/* or contains a value in a space-separated list */
-[otherAttr~='foo'] { }
-[otherAttr~='bar'] { }
-
-/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
-[otherAttr|='en'] { font-size:smaller; }
-
-
-/* You can combine different selectors to create a more focused selector. Don't
- put spaces between them. */
-div.some-class[attr$='ue'] { }
-
-/* You can select an element which is a child of another element */
-div.some-parent > .class-name { }
-
-/* or a descendant of another element. Children are the direct descendants of
- their parent element, only one level down the tree. Descendants can be any
- level down the tree. */
-div.some-parent .class-name { }
-
-/* Warning: the same selector without a space has another meaning.
- Can you guess what? */
-div.some-parent.class-name { }
-
-/* You may also select an element based on its adjacent sibling */
-.i-am-just-before + .this-element { }
-
-/* or any sibling preceding it */
-.i-am-any-element-before ~ .this-element { }
-
-/* There are some selectors called pseudo classes that can be used to select an
- element only when it is in a particular state */
-
-/* for example, when the cursor hovers over an element */
-selector:hover { }
-
-/* or a link has been visited */
-selector:visited { }
-
-/* or hasn't been visited */
-selected:link { }
-
-/* or an element is in focus */
-selected:focus { }
-
-/* any element that is the first child of its parent */
-selector:first-child {}
-
-/* any element that is the last child of its parent */
-selector:last-child {}
-
-/* Just like pseudo classes, pseudo elements allow you to style certain parts of
- a document */
-
-/* matches a virtual first child of the selected element */
-selector::before {}
-
-/* matches a virtual last child of the selected element */
-selector::after {}
-
-/* At appropriate places, an asterisk may be used as a wildcard to select every
- element */
-* { } /* all elements */
-.parent * { } /* all descendants */
-.parent > * { } /* all children */
-
-/* ####################
- ## PROPERTIES
- #################### */
-
-selector {
-
- /* Units of length can be absolute or relative. */
-
- /* Relative units */
- width: 50%; /* percentage of parent element width */
- font-size: 2em; /* multiples of element's original font-size */
- font-size: 2rem; /* or the root element's font-size */
- font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
- font-size: 2vh; /* or its height */
- font-size: 2vmin; /* whichever of a vh or a vw is smaller */
- font-size: 2vmax; /* or greater */
-
- /* Absolute units */
- width: 200px; /* pixels */
- font-size: 20pt; /* points */
- width: 5cm; /* centimeters */
- min-width: 50mm; /* millimeters */
- max-width: 5in; /* inches */
-
- /* Colors */
- color: #F6E; /* short hex format */
- color: #FF66EE; /* long hex format */
- color: tomato; /* a named color */
- color: rgb(255, 255, 255); /* as rgb values */
- color: rgb(10%, 20%, 50%); /* as rgb percentages */
- color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
- color: transparent; /* equivalent to setting the alpha to 0 */
- color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
- color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
-
- /* Borders */
- border-width:5px;
- border-style:solid;
- border-color:red; /* similar to how background-color is set */
- border: 5px solid red; /* this is a short hand approach for the same */
- border-radius:20px; /* this is a CSS3 property */
-
- /* Images as backgrounds of elements */
- background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
-
- /* Fonts */
- font-family: Arial;
- /* if the font family name has a space, it must be quoted */
- font-family: "Courier New";
- /* if the first one is not found, the browser uses the next, and so on */
- font-family: "Courier New", Trebuchet, Arial, sans-serif;
-}
-```
-
-## Usage
-
-Save a CSS stylesheet with the extension `.css`.
-
-```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'>
-
-<!-- You can also include some CSS inline in your markup. -->
-<style>
- a { color: purple; }
-</style>
-
-<!-- Or directly set CSS properties on the element. -->
-<div style="border: 1px solid red;">
-</div>
-```
-
-## Precedence or Cascade
-
-An element may be targeted by multiple selectors and may have a property set on
-it in more than once. In these cases, one of the rules takes precedence over
-others. Rules with a more specific selector take precedence over a less specific
-one, and a rule occurring later in the stylesheet overwrites a previous one
-(which also means that if two different linked stylesheets contain rules for an
-element and if the rules are of the same specificity, then order of linking
-would take precedence and the sheet linked latest would govern styling) .
-
-This process is called cascading, hence the name Cascading Style Sheets.
-
-Given the following CSS:
-
-```css
-/* A */
-p.class1[attr='value']
-
-/* B */
-p.class1 { }
-
-/* C */
-p.class2 { }
-
-/* D */
-p { }
-
-/* E */
-p { property: value !important; }
-```
-
-and the following markup:
-
-```html
-<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
-```
-
-The precedence of style is as follows. Remember, the precedence is for each
-**property**, not for the entire block.
-
-* `E` has the highest precedence because of the keyword `!important`. It is
-recommended that you avoid its usage.
-* `F` is next, because it is an inline style.
-* `A` is next, because it is more "specific" than anything else. It has 3
- specifiers: The name of the element `p`, its class `class1`, an attribute
- `attr='value'`.
-* `C` is next, even though it has the same specificity as `B`.
- This is because it appears after `B`.
-* `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 specificity.
-
-```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
-browsers and devices. But it's always good practice to check before using
-a new feature.
-
-## Resources
-
-* [CanIUse](http://caniuse.com) (Detailed compatibility info)
-* [Dabblet](http://dabblet.com/) (CSS playground)
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
-
-## Further Reading
-
-* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
-* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
-* [QuirksMode CSS](http://www.quirksmode.org/css/)
-* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
-* [CSS-Tricks](https://css-tricks.com)
-
-
diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown
index 6395f5fd..506a9467 100644
--- a/es-es/css-es.html.markdown
+++ b/es-es/css-es.html.markdown
@@ -1,253 +1,327 @@
---
language: css
-filename: learncss-es.css
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["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"]
translators:
- - ["Daniel Zendejas","https://github.com/DanielZendejas"]
+ - ["miky ackerman", "https://github.com/mikyackerman"]
lang: es-es
+filename: learncss-es.css
---
-Tutorial de CSS en español
+Paginas web estan contruidas en HTML, lo cual especifica el contenido de una pagina
+CSS(Hoja de Estilos en Cascada) es un lenguaje separado el cual especifica
+la **apariencia** de una pagina.
-En los primeros días de la web no había elementos visuales, todo
-era texto plano. Pero después, con el desarrollo de los navegadores,
-las páginas con contenido visual empezaron a ser más comunes.
-CSS es el lenguaje estándar que existe para separar el contenido
-(HTML) y el aspecto visual de las páginas web.
+codigo CSS esta hecho de *reglas* estaticas. Cada regla toma uno o mas *selectores* y da *valores* especificos a un numero de *propiedades* visuales. Esas propiedades estan entonces aplicadas a los elementos indicados en una pagina por los selectores
-Lo que CSS hace es proveer con una sintaxis que te permite apuntar a distintos
-elementos HTML y asignarles diferentes propiedades visuales.
+Esta guia ha sido escrita con CSS 2 en mente, la cual es extendida por una nueva caracterica de CSS 3.
-CSS, como cualquier otro lenguaje, tiene múltiples versiones. Aquí nos enfocamos
-en CSS 2.0. No es la versión más reciente pero sí la más soportada y compatible.
+**NOTA:** Debido a que CSS produce resultados visuales, para aprenderlo, necesitas
+Probar todo en un patio de juegos CSS como [dabblet] (http://dabblet.com/).
+El objetivo principal de este artículo es la sintaxis y algunos consejos generales.
-**NOTA:** Como los resultados de CSS son efectos visuales, para aprenderlo,
-necesitarás probar todo tipo de cosas en ambientes como
-[dabblet](http://dabblet.com/). Este artículo se enfoca, principalmente, en
-la sintaxis y consejos generales.
+## Sintaxis
```css
-/* ¡Los comentarios aparecen dentro de diagonal-asterisco, justo como esta línea! */
+/* Los comentarios aparecen dentro de un diagonal-asterisco, justo como esta linea
+ no hay "comentarios en una linea"; este es el unico estilo de comentario.*/
+
/* ####################
- ## SELECTORES
- ####################*/
-
-/* Generalmente, la sentencia principal en CSS es muy simple. */
-selector { propiedad: valor; /* más propiedades separados por punto y coma...*/ }
-
-/* El selector es usado para apuntar a (seleccionar) un elemento en la página.
+ ## SELECTORS
+ #################### */
-¡Puedes apuntar a todos los elementos en la página con el asterisco! */
-* { color:red; }
+/* el selector es usado para apuntar a un elemento de la pagina. */
+selector { property: value; /* more properties...*/ }
/*
-Dado un elemento como este en la página:
+Here is an example element:
-<div class='una-clase clase2' id='unaId' attr='valor' />
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
*/
-/* puedes seleccionar el <div> por el nombre de su clase */
-.una-clase { }
+/* You can target it using one of its CSS classes */
+.class1 { }
-/*¡O por sus dos clases! */
-.una-clase.clase2 { }
+/* or both classes! */
+.class1.class2 { }
-/* O por el nombre de su elemento */
+/* or its name */
div { }
-/* O por su Id */
-#unaId { }
+/* or its id */
+#anID { }
-/* ¡O por el hecho de que tiene un atributo! */
+/* or using the fact that it has an attribute! */
[attr] { font-size:smaller; }
-/* O por el hecho de que el atributo tiene un valor determinado */
-[attr='valor'] { font-size:smaller; }
+/* or that the attribute has a specific value */
+[attr='value'] { font-size:smaller; }
-/* Empieza con un valor ('val' en este caso)*/
+/* starts with a value (CSS 3) */
[attr^='val'] { font-size:smaller; }
-/* O termina con un valor ('or' en este caso) */
-[attr$='or'] { font-size:smaller; }
+/* or ends with a value (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* or contains a value in a space-separated list */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
+
+/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
-/* O incluso contiene un valor ('lo' en este caso) */
-[attr~='lo'] { font-size:smaller; }
+/* You can combine different selectors to create a more focused selector. Don't
+ put spaces between them. */
+div.some-class[attr$='ue'] { }
-/*Más importante, puedes combinar estos criterios de búsqueda entre sí.
-No debe existir ningún espacio entre estas partes porque hace que el
-significado cambie.*/
-div.una-clase[attr$='or'] { }
+/* You can select an element which is a child of another element */
+div.some-parent > .class-name { }
-/* También puedes seleccionar un elemento HTML basándote en sus padres*/
+/* or a descendant of another element. Children are the direct descendants of
+ their parent element, only one level down the tree. Descendants can be any
+ level down the tree. */
+div.some-parent .class-name { }
-/* Un elemento que es hijo directo de otro elemento (Seleccionado de la forma que
-vimos anteriormente) */
+/* Warning: the same selector without a space has another meaning.
+ Can you guess what? */
+div.some-parent.class-name { }
-div.un-padre > .nombre-clase {}
+/* You may also select an element based on its adjacent sibling */
+.i-am-just-before + .this-element { }
-/* O cualquiera de sus ancestros en la jerarquía*/
-/* La siguiente sentencia selecciona a cualquier elemento que tenga una clase
-"nombre-clase" y sea hijo de un div con clase "un-padre" EN CUALQUIER PROFUNDIDAD*/
-div.un-padre .nombre-clase {}
+/* or any sibling preceding it */
+.i-am-any-element-before ~ .this-element { }
-/* advertencia: el mismo selector sin espacio tiene otro significado. ¿Puedes
-identificar la diferencia?*/
+/* There are some selectors called pseudo classes that can be used to select an
+ element only when it is in a particular state */
-/* También puedes seleccionar un elemento basado en su hermano inmediato previo*/
-.yo-estoy-antes + .este-elemento { }
+/* for example, when the cursor hovers over an element */
+selector:hover { }
-/*o cualquier hermano previo */
-.yo-soy-cualquiera-antes ~ .estes-elemento {}
+/* or a link has been visited */
+selector:visited { }
-/* Existen algunas pseudo-clases que permiten seleccionar un elemento
-basado en el comportamiendo de la página (a diferencia de la estructura de
-la página) */
+/* or hasn't been visited */
+selected:link { }
-/* Por ejemplo, para cuando pasas el mouse por encima de un elemento */
-:hover {}
+/* or an element is in focus */
+selected:focus { }
-/* o una liga visitada*/
-:visited {}
+/* any element that is the first child of its parent */
+selector:first-child {}
-/* o una liga no visitada aún*/
-:link {}
+/* any element that is the last child of its parent */
+selector:last-child {}
-/* o un elemento de un formulario que esté seleccionado */
-:focus {}
+/* Just like pseudo classes, pseudo elements allow you to style certain parts of
+ a document */
+/* matches a virtual first child of the selected element */
+selector::before {}
+
+/* matches a virtual last child of the selected element */
+selector::after {}
+
+/* At appropriate places, an asterisk may be used as a wildcard to select every
+ element */
+* { } /* all elements */
+.parent * { } /* all descendants */
+.parent > * { } /* all children */
/* ####################
- ## PROPIEDADES
- ####################*/
+ ## PROPERTIES
+ #################### */
selector {
-
- /* Unidades */
- width: 50%; /* en porcentaje */
- font-size: 2em; /* dos veces el tamaño de la fuente actual */
- width: 200px; /* en pixeles */
- font-size: 20pt; /* en puntos */
- width: 5cm; /* en centimetros */
- width: 50mm; /* en milimetros */
- width: 5in; /* en pulgadas */
-
- /* Colores */
- background-color: #F6E; /* en hexadecimal corto */
- background-color: #F262E2; /* en hexadecimal largo */
- background-color: tomato; /* puede ser un color con nombre */
- background-color: rgb(255, 255, 255); /* en rgb */
- background-color: rgb(10%, 20%, 50%); /* en rgb percent */
- background-color: rgba(255, 0, 0, 0.3); /* en rgb semi-transparente (con valor alfa)*/
-
- /* Imagenes */
- background-image: url(/ruta-a-la-imagen/imagen.jpg);
-
- /* Fuentes */
+
+ /* Units of length can be absolute or relative. */
+
+ /* Relative units */
+ width: 50%; /* percentage of parent element width */
+ font-size: 2em; /* multiples of element's original font-size */
+ font-size: 2rem; /* or the root element's font-size */
+ font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
+ font-size: 2vh; /* or its height */
+ font-size: 2vmin; /* whichever of a vh or a vw is smaller */
+ font-size: 2vmax; /* or greater */
+
+ /* Absolute units */
+ width: 200px; /* pixels */
+ font-size: 20pt; /* points */
+ width: 5cm; /* centimeters */
+ min-width: 50mm; /* millimeters */
+ max-width: 5in; /* inches */
+
+ /* Colors */
+ color: #F6E; /* short hex format */
+ color: #FF66EE; /* long hex format */
+ color: tomato; /* a named color */
+ color: rgb(255, 255, 255); /* as rgb values */
+ color: rgb(10%, 20%, 50%); /* as rgb percentages */
+ color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
+ color: transparent; /* equivalent to setting the alpha to 0 */
+ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
+ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
+
+ /* Borders */
+ border-width:5px;
+ border-style:solid;
+ border-color:red; /* similar to how background-color is set */
+ border: 5px solid red; /* this is a short hand approach for the same */
+ border-radius:20px; /* this is a CSS3 property */
+
+ /* Images as backgrounds of elements */
+ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
+
+ /* Fonts */
font-family: Arial;
- font-family: "Courier New"; /* si el nombre contiene espacios, debe ir entre comillas */
- font-family: "Courier New", Trebuchet, Arial; /* si la primera fuente no se encontró
- entonces se busca la seguna, o la tercera, así recursivamente*/
+ /* if the font family name has a space, it must be quoted */
+ font-family: "Courier New";
+ /* if the first one is not found, the browser uses the next, and so on */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
-
```
-## Uso
+## Usage
-Guarda cualquier CSS que quieras en un archivo con extensión `.css`.
+Save a CSS stylesheet with the extension `.css`.
-```xml
-<!-- Necesitas incluir tu archivo CSS en el elemento <head> de tu HTML: -->
-<link rel='stylesheet' type='text/css' href='ruta/archivoDeEstilos.css' />
+```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'>
-<!--
-también puedes incluir CSS dentro del archivo HTML. Esta no es una buena práctica
-y debe ser evitada.
--->
+<!-- You can also include some CSS inline in your markup. -->
<style>
- selector { propiedad:valor; }
+ a { color: purple; }
</style>
-<!--
-También se pueden aplicar propiedades al elemento directamente.
-Esta práctica también debe ser evitada a toda costa
--->
-<div style='propiedad:valor;'>
+<!-- Or directly set CSS properties on the element. -->
+<div style="border: 1px solid red;">
</div>
-
```
-## Preferencia y orden
+## Precedence or Cascade
+
+An element may be targeted by multiple selectors and may have a property set on
+it in more than once. In these cases, one of the rules takes precedence over
+others. Rules with a more specific selector take precedence over a less specific
+one, and a rule occurring later in the stylesheet overwrites a previous one
+(which also means that if two different linked stylesheets contain rules for an
+element and if the rules are of the same specificity, then order of linking
+would take precedence and the sheet linked latest would govern styling) .
-Como te habrás dado cuenta un elemento puede ser seleccionado por más
-de un selector. En este caso alguna de las reglas cobra preferencia
-sobre las otras:
+This process is called cascading, hence the name Cascading Style Sheets.
-Dado el siguiente CSS:
+Given the following CSS:
```css
-/*A*/
-p.clase1[attr='valor']
+/* A */
+p.class1[attr='value']
-/*B*/
-p.clase1 {}
+/* B */
+p.class1 { }
-/*C*/
-p.clase2 {}
+/* C */
+p.class2 { }
-/*D*/
-p {}
+/* D */
+p { }
-/*E*/
-p { propiedad: valor !important; }
+/* E */
+p { property: value !important; }
+```
+and the following markup:
+
+```html
+<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
```
-Y el siguiente HTML:
+The precedence of style is as follows. Remember, the precedence is for each
+**property**, not for the entire block.
+
+* `E` has the highest precedence because of the keyword `!important`. It is
+recommended that you avoid its usage.
+* `F` is next, because it is an inline style.
+* `A` is next, because it is more "specific" than anything else. It has 3
+ specifiers: The name of the element `p`, its class `class1`, an attribute
+ `attr='value'`.
+* `C` is next, even though it has the same specificity as `B`.
+ This is because it appears after `B`.
+* `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 specificity.
+
+```css
+/* A rule that will be used on all devices */
+h1 {
+ font-size: 2em;
+ color: white;
+ background-color: black;
+}
-```xml
-<p style='/*F*/ propiedad:valor;' class='clase1 clase2' attr='valor'>
-</p>
+/* 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;
+ }
+}
```
-El orden respetado es el siguiente:
-Recuerda, la preferencia es por cada **property**, no para el bloque completo.
+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-`.
-* `E` tiene la preferencia más elevada gracias a la palabra `!important`.
- Es recomendado evitar esto a menos que sea estrictamente necesario incluirlo.
-* `F` le sigue, porque es estilo incrustado directamente en el HTML.
-* `A` le sigue, porque es más específico que cualquier otra opción.
- más específico = más especificadores. Aquí hay tres especificadores: elemento `p` +
- nombre de la clase `clase1` + un atributo `attr='valor'`
-* `C` le sigue. Aunque tiene el mismo número de especificadores como `B`
- pero aparece después.
-* Luego va `B`
-* y al final `D`.
+The `resolution` feature is not supported by older devices, instead use `device-pixel-ratio`.
-## Compatibilidad
+Many smartphones and tablets will attempt to render the page as if it were on a desktop unless you provide a `viewport` meta-tag.
-La mayoría de las funcionalidades de CSS2 (y gradualmente de CSS3) son compatibles
-en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la
-compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores
-y dispositivos para los que desarrolles.
+```html
+<head>
+ <meta name="viewport" content="width=device-width; initial-scale=1.0">
+</head>
+```
+
+## Compatibility
-[QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto.
+Most of the features in CSS 2 (and many in CSS 3) are available across all
+browsers and devices. But it's always good practice to check before using
+a new feature.
-## Recursos
+## Resources
-* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com).
-* CSS Playground [Dabblet](http://dabblet.com/).
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS).
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/).
+* [CanIUse](http://caniuse.com) (Detailed compatibility info)
+* [Dabblet](http://dabblet.com/) (CSS playground)
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
-## Otras lecturas
+## Further Reading
-* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/).
-* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/).
-* [QuirksMode CSS](http://www.quirksmode.org/css/).
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS.
-* [CSS-Tricks](https://css-tricks.com).
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
+
diff --git a/es-es/elixir-es.html.markdown b/es-es/elixir-es.html.markdown
index 885165a6..37acf6ad 100644
--- a/es-es/elixir-es.html.markdown
+++ b/es-es/elixir-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -23,10 +23,10 @@ y otras características más.
# No hay comentarios multilinea,
# pero se pueden apilar varios comentarios.
-# Para usar el shell de elixir se usa el comando `iex`.
+# Para usar el shell de Elixir se usa el comando `iex`.
# Los módulos se compilan con el comando `elixirc`.
-# Ambos deberían estar en la ruta si elixir se instaló correctamente.
+# Ambos deberían estar en la ruta si Elixir se instaló correctamente.
## ---------------------------
## -- Tipos básicos
@@ -55,7 +55,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# En elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
+# En Elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
# no una asignación.
#
# This is how the above example of accessing the head and tail of a list works.
@@ -87,7 +87,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` en elixir devuelve el valor ASCII para el caracter `a`
+# `?a` en Elixir devuelve el valor ASCII para el caracter `a`
?a #=> 97
# Para concatenar listas se usa `++`, para binarios `<>`
@@ -120,7 +120,7 @@ genders.gillian #=> "female"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# En elixir el operador `/` siempre devuelve un número flotante
+# En Elixir el operador `/` siempre devuelve un número flotante
# Para hacer la división de número entero se debe usar `div`
div(10, 2) #=> 5
@@ -175,7 +175,7 @@ else
end
# Se acuerda de la coincidencia de patrones?
-# Muchas estructuras de control de flujo en elixir confían en ella.
+# Muchas estructuras de control de flujo en Elixir confían en ella.
# `case` permite comparar un valor con muchos patrones:
case {:one, :two} do
@@ -305,7 +305,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Debido a la inmutabilidad, la recursión es una gran parte de elixir
+# Debido a la inmutabilidad, la recursión es una gran parte de Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -380,7 +380,7 @@ end
## ---------------------------
# Elixir confía en el modelo actor para la concurrencia. Todo lo que se necesita para escribir
-# programas concurrentes en elixir son tres primitivas: procesos de desove,
+# programas concurrentes en Elixir son tres primitivas: procesos de desove,
# envío de mensajes y recepción de mensajes.
# Para empezar un nuevo proceso se usa la función `spawn`,
diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown
index edc5d38c..61123151 100644
--- a/es-es/forth-es.html.markdown
+++ b/es-es/forth-es.html.markdown
@@ -13,7 +13,7 @@ Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativ
Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo
de lo que esta escrito aquí debe funcionar en otro sitio.
-```
+```forth
\ Este es un comentario
( Este es un comentario también pero solo esta usado cuando definiendo palabras. )
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 749365d1..dc0dda30 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -410,8 +410,6 @@ $ git rm /directorio/del/archivo/FooBar.c
* [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown
index 78267695..17bf4a22 100644
--- a/es-es/go-es.html.markdown
+++ b/es-es/go-es.html.markdown
@@ -88,7 +88,7 @@ saltos de línea.` // mismo tipo cadena
// Literal no ASCII. Los ficheros fuente de Go son UTF-8.
g := 'Σ' // Tipo rune, un alias de int32, alberga un carácter unicode.
- f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit.
+ f := 3.14159 // float64, el estándar IEEE-754 de coma flotante 64-bit.
c := 3 + 4i // complex128, representado internamente por dos float64.
// Sintaxis var con iniciadores.
var u uint = 7 // Sin signo, pero la implementación depende del tamaño
@@ -425,7 +425,7 @@ func consultaAlServidor() {
## Más información
La raíz de todas las cosas sobre Go es el
-[sitio web oficial de Go](http://golang.org/).
+[sitio web oficial de Go](https://go.dev/).
Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más.
La definición del lenguaje es altamente recomendada. Es fácil de leer y
@@ -433,17 +433,17 @@ sorprendentemente corta (como la definición del lenguaje Go en estos
días).
Puedes jugar con el código en el
-[parque de diversiones Go](https://play.golang.org/p/ncRC2Zevag). ¡Trata
+[parque de diversiones Go](https://go.dev/play/p/ncRC2Zevag). ¡Trata
de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes
-utilizar [https://play.golang.org]( https://play.golang.org) como un
+utilizar [https://go.dev/play/]( https://go.dev/play/) como un
[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar
cosas y el código en el navegador, sin ni siquiera instalar Go.
En la lista de lecturas para estudiantes de Go está el
-[código fuente de la biblioteca estándar](http://golang.org/src/pkg/).
+[código fuente de la biblioteca estándar](https://go.dev/src/).
Ampliamente documentado, que demuestra lo mejor del legible y comprensible
Go, con su característico estilo y modismos. ¡O puedes hacer clic en un
-nombre de función en [la documentación](http://golang.org/pkg/) y
+nombre de función en [la documentación](https://go.dev/pkg/) y
aparecerá el código fuente!
Otro gran recurso para aprender Go está en
diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown
index e4181609..355c7f29 100644
--- a/es-es/julia-es.html.markdown
+++ b/es-es/julia-es.html.markdown
@@ -28,7 +28,7 @@ En Julia los programas están organizados entorno al [despacho múltiple](http:/
* [Buen desempeño](http://julialang.org/benchmarks), comparado al de lenguajes **estáticamente compilados** como C.
* [Gestor de paquetes](http://docs.julialang.org/en/release-0.3/stdlib/pkg) integrado.
* [Macros tipo Lisp](http://docs.julialang.org/en/release-0.3/manual/metaprogramming/#macros) y otras comodidades para la [meta programación](http://docs.julialang.org/en/release-0.3/manual/metaprogramming).
-* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **Matlab** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)).
+* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **MATLAB** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)).
* [Llamar funciones de C y Fortran](http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code) **directamente**: sin necesidad de usar envoltorios u APIs especiales.
* Poderosas características de **línea de comandos** para [gestionar otros procesos](http://docs.julialang.org/en/release-0.3/manual/running-external-programs).
* Diseñado para la [computación paralela y distribuida](http://docs.julialang.org/en/release-0.3/manual/parallel-computing) **desde el principio**.
diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown
index faa3dead..9290e505 100644
--- a/es-es/matlab-es.html.markdown
+++ b/es-es/matlab-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: Matlab
+language: MATLAB
filename: learnmatlab-es.mat
contributors:
- ["mendozao", "http://github.com/mendozao"]
@@ -139,7 +139,7 @@ A.d.e = false;
% Vectores
x = [4 32 53 7 1]
-x(2) % ans = 32, los índices en Matlab comienzan 1, no 0
+x(2) % ans = 32, los índices en MATLAB comienzan 1, no 0
x(2:3) % ans = 32 53
x(2:end) % ans = 32 53 7 1
@@ -506,7 +506,7 @@ find(x) % Encuentra todos los elementos distintos de cero de x y devuelve sus í
% Clases
-% Matlab puede soportar programación orientada a objetos.
+% MATLAB puede soportar programación orientada a objetos.
% Las clases deben colocarse en un archivo del nombre de la clase con la extensión .m.
% Para comenzar, creamos una clase simple para almacenar puntos de referencia de GPS.
% Comience WaypointClass.m
@@ -528,7 +528,7 @@ classdef WaypointClass % El nombre de la clase.
end
% Si queremos agregar dos objetos Waypoint juntos sin llamar
- % a una función especial, podemos sobrecargar la aritmética de Matlab así:
+ % a una función especial, podemos sobrecargar la aritmética de MATLAB así:
function r = plus(o1,o2)
r = WaypointClass([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]);
@@ -540,7 +540,7 @@ end
% Podemos crear un objeto de la clase usando el constructor
a = WaypointClass(45.0, 45.0)
-% Las propiedades de clase se comportan exactamente como estructuras de Matlab.
+% Las propiedades de clase se comportan exactamente como estructuras de MATLAB.
a.latitude = 70.0
a.longitude = 25.0
@@ -551,15 +551,15 @@ ans = multiplyLatBy(a,3)
% no necesita ser pasado al método.
ans = a.multiplyLatBy(a,1/3)
-% Las funciones de Matlab pueden sobrecargarse para manejar objetos.
-% En el método anterior, hemos sobrecargado cómo maneja Matlab
+% Las funciones de MATLAB pueden sobrecargarse para manejar objetos.
+% En el método anterior, hemos sobrecargado cómo maneja MATLAB
% la adición de dos objetos Waypoint.
b = WaypointClass(15.0, 32.0)
c = a + b
```
-## Más sobre Matlab
+## Más sobre MATLAB
* [The official website (EN)](http://www.mathworks.com/products/matlab/)
* [The official MATLAB Answers forum (EN)](http://www.mathworks.com/matlabcentral/answers/)
diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown
index 9eb35967..5b12b961 100644
--- a/es-es/powershell-es.html.markdown
+++ b/es-es/powershell-es.html.markdown
@@ -34,7 +34,7 @@ $PSVersionTable
Para obtener ayuda:
-```
+```powershell
# Si necesita encontrar algún comando
Get-Command about_* # tiene por abreviación (o alias): gcm
Get-Command -Verb Add # lista todos los comandos que tienen por verbo 'Add'
@@ -51,7 +51,7 @@ Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como
Acá inicia el tutorial:
-```
+```powershell
# Como ya lo notó, los comentarios empiezan con #
# Ejemplo de un simple hola mundo:
@@ -299,7 +299,7 @@ $Shortcut.Save()
Configurando el shell
-```
+```powershell
# $Profile es la ruta completa para su `Microsoft.PowerShell_profile.ps1`
# Todo el código alojado allí será ejecutado cuando se ejecuta una nueva sesión de PS
if (-not (Test-Path $Profile)) {
diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown
index 6d4fdde7..9a5eab8c 100644
--- a/es-es/pyqt-es.html.markdown
+++ b/es-es/pyqt-es.html.markdown
@@ -16,7 +16,7 @@ Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Crear el objeto de la aplicación
app = QtGui.QApplication(sys.argv)
@@ -44,7 +44,7 @@ if __name__ == '__main__':
Para poder hacer uso de las funciones más avanzades en **pyqt** necesitamos agregar elementos adicionales.
Aquí mostramos cómo introducir una caja de diálogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -63,7 +63,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Esta función debería crear una ventana de diálogo con un botón
# que espera a recibir un click y luego sale del programa
def showdialog():
diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
index 7deec286..0b21e479 100644
--- a/es-es/python-es.html.markdown
+++ b/es-es/python-es.html.markdown
@@ -328,7 +328,7 @@ dicc_lleno = {"uno": 1, "dos": 2, "tres": 3}
nuestro_iterable = dicc_lleno.keys()
print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable
-Podemos recorrerla.
+# Podemos recorrerla.
for i in nuestro_iterable:
print(i) # Imprime uno, dos, tres
@@ -388,8 +388,8 @@ keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
todos_los_argumentos(1, 2, a=3, b=4) imprime:
(1, 2)
@@ -462,10 +462,10 @@ class Humano(object):
# Instancia una clase
i = Humano(nombre="Ian")
-print i.decir("hi") # imprime "Ian: hi"
+print(i.decir("hi")) # imprime "Ian: hi"
j = Humano("Joel")
-print j.decir("hello") #imprime "Joel: hello"
+print(j.decir("hello")) #imprime "Joel: hello"
# Llama nuestro método de clase
i.get_especie() #=> "H. sapiens"
@@ -548,7 +548,7 @@ def pedir(_decir):
@pedir
-def say(decir_por_favor=False):
+def decir(decir_por_favor=False):
mensaje = "¿Puedes comprarme una cerveza?"
return mensaje, decir_por_favor
diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown
index 2b710b27..850952fa 100644
--- a/es-es/r-es.html.markdown
+++ b/es-es/r-es.html.markdown
@@ -16,7 +16,7 @@ LaTeX.
```r
-# Los comentariso inician con símbolos numéricos.
+# Los comentarios inician con símbolos numéricos.
# No puedes hacer comentarios de múltiples líneas
# pero puedes agrupar múltiples comentarios de esta manera.
diff --git a/es-es/raku-es.html.markdown b/es-es/raku-es.html.markdown
index e916d0fd..09341056 100644
--- a/es-es/raku-es.html.markdown
+++ b/es-es/raku-es.html.markdown
@@ -1,5 +1,5 @@
---
-name: perl6
+name: Raku
category: language
language: Raku
filename: learnraku-es.raku
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
index 63a47e89..8b703df1 100644
--- a/es-es/ruby-es.html.markdown
+++ b/es-es/ruby-es.html.markdown
@@ -89,10 +89,10 @@ true || false #=> true
# Estos son usados como constructores controladores de flujo que encadenan
# sentencias hasta que una de ellas retorne verdadero o falso
-# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero.
-has_algo() and has_otra_cosa()
-# `registra_error` solo se llama si `has_algo` falla
-has_algo() or registra_error()
+# `haz_otra_cosa` solo se llama si `haz_algo` retorna verdadero.
+haz_algo() and haz_otra_cosa()
+# `registra_error` solo se llama si `haz_algo` falla
+haz_algo() or registra_error()
# Los strings son objetos
diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown
index dc48abf5..b0a3873c 100644
--- a/es-es/rust-es.html.markdown
+++ b/es-es/rust-es.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
index c677c20f..fb0b1d27 100644
--- a/es-es/visualbasic-es.html.markdown
+++ b/es-es/visualbasic-es.html.markdown
@@ -8,7 +8,7 @@ filename: learnvisualbasic-es.vb
lang: es-es
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/es-es/wolfram-es.html.markdown b/es-es/wolfram-es.html.markdown
index 44ec9e09..6858c286 100644
--- a/es-es/wolfram-es.html.markdown
+++ b/es-es/wolfram-es.html.markdown
@@ -15,7 +15,7 @@ El lenguaje de Wolfram tiene varias interfaces:
El código de este ejemplo se puede escribir en cualquier interfaz y editarlo con Wolfram Workbench. Cargar directamente en Matematica puede resultar incómodo porque el archivo no contiene información de formato de celda (lo que haría que el archivo sea un desastre enorme para ser leído como texto) - puede ser visto / editado pero tal vez requerira algún ajuste.
-```
+```mathematica
(* Esto es un comentario *)
(* En Mathematica en lugar de utilizar estos comentarios, puede crear una celda de texto
diff --git a/fa-ir/css-fa.html.markdown b/fa-ir/css-fa.html.markdown
index 4e222eb2..93af9132 100644
--- a/fa-ir/css-fa.html.markdown
+++ b/fa-ir/css-fa.html.markdown
@@ -29,21 +29,21 @@ filename: learncss-fa.css
<p dir='rtl'>در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد</p>
-```CSS
+```css
/* comments appear inside slash-asterisk, just like this line!
there are no "one-line comments"; this is the only comment style */
```
<p dir='rtl'>به طور Ú©Ù„ÛŒ دستورات CSS بسیار ساده هستند Ú©Ù‡ در آن یک انتخابگر (selector) عنصری را در روی صÙحه هد٠قرار میدهد.</p>
-```CSS
+```css
selector { property: value; /* more properties...*/ }
```
<p dir='rtl'>با استÙاده از ستاره Ù…ÛŒ توان برای همه عناصر روی صÙحه استایل تعری٠کرد</p>
-```CSS
+```css
* { color:red; }
```
@@ -55,129 +55,129 @@ selector { property: value; /* more properties...*/ }
<p dir='rtl'>شما میتوانید با استÙاده از نام کلاس آنرا انتخاب کنید</p>
-```CSS
+```css
.some-class { }
```
<p dir='rtl'>یا با استÙاده از نام دو کلاس</p>
-```CSS
+```css
.some-class.class2 { }
```
<p dir='rtl'>یا با استÙاده از نام id</p>
-```CSS
+```css
#someId { }
```
<p dir='rtl'>یا با استÙاده از نام خود عنصر</p>
-```CSS
+```css
div { }
```
<p dir='rtl'>یا با استÙاده از `attr`</p>
-```CSS
+```css
[attr] { font-size:smaller; }
```
<p dir='rtl'>یا با استÙاده از ارزشی Ú©Ù‡ برای `attr` مشخص شده</p>
-```CSS
+```css
[attr='value'] { font-size:smaller; }
```
<p dir='rtl'>با استÙاده از ارزشی Ú©Ù‡ برای `attr` مشخص شده Ùˆ آن ارزش با `val` شروع میشود در CSS3</p>
-```CSS
+```css
[attr^='val'] { font-size:smaller; }
```
<p dir='rtl'>با استÙاده از ارزشی Ú©Ù‡ برای `attr` مشخص شده Ùˆ آن ارزش با `ue` به پایان میرسد در CSS3</p>
-```CSS
+```css
[attr$='ue'] { font-size:smaller; }
```
<p dir='rtl'>یا با انتخاب بوسیله یکی از ارزشهایی Ú©Ù‡ در لیست `otherAttr` بوسیله Ùاصله از هم جدا شده اند در CSS3</p>
-```CSS
+```css
[attr$='ue'] { font-size:smaller; }
```
<p dir='rtl'>یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حر٠بعدی جدا شود</p>
-```CSS
+```css
[otherAttr|='en'] { font-size:smaller; }
```
<p dir='rtl'>Ùˆ مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی Ú©Ù‡ در اینجا باید مد نظر داشته باشید این است Ú©Ù‡ هنگام ترکیب نباید هیچگونه Ùاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند</p>
-```CSS
+```css
div.some-class[attr$='ue'] { }
```
<p dir='rtl'>CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید</p>
<p dir='rtl'>برای مثال دستور زیر همه عناصری را که نام کلاس آنها <span dir="ltr">`.class-name`</span> و دارای پدر و مادری با این مشخصه <span dir="ltr">`div.some-parent`</span> هستند را انتخاب میکند.</p>
-```CSS
+```css
div.some-parent > .class-name {}
```
<p dir='rtl'>یا دستور زیر Ú©Ù‡ همه عناصری را Ú©Ù‡ نام کلاس آنها <span dir="ltr">`.class-name`</span> Ùˆ داخل عنصری با مشخصه <span dir="ltr">`div.some-parent`</span> هستند را در هر عمقی Ú©Ù‡ باشند (یعنی Ùرزندی از Ùرزندان <span dir="ltr">`div.some-parent`</span><span dir="ltr"> باشند) انتخاب میکند.</p>
-```CSS
+```css
div.some-parent .class-name {}
```
<p dir='rtl'>نکته ای Ú©Ù‡ در اینجا باید به آن توجه کنید این است Ú©Ù‡ این رستور با Ùاصله ای بین نام دو کلاس همراه است Ùˆ با مثال زیر Ú©Ù‡ در بالا هم ذکر شد تÙاوت دارد.</p>
-```CSS
+```css
div.some-parent.class-name {}
```
<p dir='rtl'>دستور زیر همه عناصری را Ú©Ù‡ نام کلاس آنها <span dir="ltr">`.this-element`</span> Ùˆ بلاÙاصله بعد از عنصری با مشخصه <span dir="ltr">`.i-am-before`</span> قرار دارد را انتخاب میکند.</p>
-```CSS
+```css
.i-am-before + .this-element { }
```
<p dir='rtl'>هر خواهر یا برادری Ú©Ù‡ بعد از <span dir="ltr">`.i-am-before`</span> بیاید در اینجا لازم نیست بلاÙاصله بعد از هم قرار بگیرند ولی باید دارای پدر Ùˆ مادری یکسان باشند.</p>
-```CSS
+```css
.i-am-any-before ~ .this-element {}
```
<p dir='rtl'>در زیر چند نمونه از شبه کلاسها را معرÙÛŒ میکنیم Ú©Ù‡ به شما اجازه میدهد عناصر را بر اساس رÙتار آنها در صÙحه انتخاب کنید.</p>
<p dir='rtl'>برای مثال زمانی Ú©Ù‡ اشاره گر ماوس روی عنصری بر روی صÙحه قرار دارد.</p>
-```CSS
+```css
selector:hover {}
```
<p dir='rtl'>یا زمانی از یک لینک بازید کردید.</p>
-```CSS
+```css
selected:visited {}
```
<p dir='rtl'>یا زمانی از لینکی بازید نشده است.</p>
-```CSS
+```css
selected:link {}
```
<p dir='rtl'>یا زمانی که روی یک عنصر ورودی متمرکز شده.</p>
-```CSS
+```css
selected:focus {}
```
<h3 dir='rtl'>واحدها</h3>
-```CSS
+```css
selector {
/* واحدها اندازه */
@@ -247,7 +247,7 @@ selector {
<p dir='rtl'>به مثال زیر توجه کنید:</p>
-```CSS
+```css
/*A*/
p.class1[attr='value']
diff --git a/fa-ir/vim-fa.html.markdown b/fa-ir/vim-fa.html.markdown
new file mode 100644
index 00000000..f1864619
--- /dev/null
+++ b/fa-ir/vim-fa.html.markdown
@@ -0,0 +1,469 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+translators:
+ - ["Moein Halvaei", "https://github.com/mo1ein"]
+lang: fa-ir
+filename: LearnVim-fa.txt
+---
+
+<p dir="rtl">
+[Vim](http://www.vim.org) (Vi رشدیاÙته) یک کلون از ادیتور مشهور vi است برای unix. ادیتورمتنی‌ست Ú©Ù‡ برای سرعت Ùˆ اÙزایش بهره‌وری طراحی شده‌ Ùˆ در همه جا به ویژه در سیستم های unix-based دیده می‌شود. شورتکات کلید های بی‌شماری برای سرعت جهت‌یابی به نقاط ویژه‌ي Ùایل ها Ùˆ تغییر سریع، دارد.
+<br />
+`vimtutor` یک برنامه‌ي عالیست Ú©Ù‡ به شما چگونگی استÙاده از `vim` را آموزش می‌دهد.
+این به همراه پکیج های vim هنگام نصب کردن، نصب می‌شود. شما باید بتوانید با ران کردن `vimtutor` در کامندلاین از آموزش ها استÙاده کنید. این همه‌ی ویژگی های عمده‌ی `vim` را به شما راهنمایی می‌کند.
+</p>
+<h3>
+ <p dir="rtl">
+مکان‌یابی اولیه vim
+ </p>
+</h3>
+
+
+<p dir="rtl">
+باز کردن `<filename>` در ویم
+</p>
+
+```
+vim <filename> # Open <filename> in vim
+```
+<p dir="rtl">
+باز کردن help docs های `<topic>` اگر وجود داشته باشد
+</p>
+
+```
+:help <topic> # Open up built-in help docs about <topic> if any exists
+```
+```
+:q # خروج از ویم
+
+:w # ذخیره کردن Ùایل Ùعلی
+
+:wq # ذخیره کردن و خارج شدن از ویم
+
+ZZ # ذخیره کردن و خارج شدن از ویم
+
+:q! # خارج شدن بدون ذخیره کردن Ùایل
+
+! *forces* :q to execute, hence quiting vim without saving
+
+ZQ # خارج شدن بدون ذخیره کردن Ùایل
+```
+
+<p dir="rtl">ذخیره کردن و خارج شدن از vim ورژن خلاصه شده‌ی wq:</p>
+
+```
+:x # Save file and quit vim, shorter version of :wq
+```
+
+<p dir="rtl">برگشت به عقب</p>
+
+```
+ u # Undo
+```
+
+<p dir="rtl">رÙتن به جلو</p>
+
+```
+CTRL+R # Redo
+```
+
+<p dir="rtl">راه رÙتن در صÙحه</p>
+
+```
+h # رÙتن یک کاراکتر به Ú†Ù¾
+
+j # رÙتن یک کاراکتر به پایین
+
+k # رÙتن یک کاراکتر به بالا
+
+l # رÙتن یک کاراکتر به راست
+
+Ctrl+B # جابه‌جا شدن به عقب به اندازه یک صÙحه
+
+Ctrl+F # جابه‌جا شدن به جلو به اندازه یک صÙحه
+
+Ctrl+D # جابه‌جا شدن به جلو به اندازه نص٠صÙحه
+
+Ctrl+U # جابه‌جا شدن به عقب به اندازه نص٠صÙحه
+```
+
+<p dir="rtl"><strong>جابه‌جا شدن در خط</strong></p>
+
+```
+0 # رÙتن به اول خط
+$ # رÙتن به آخر خط
+^ # رÙتن به اولین کاراکتر غیرخالی در خط
+```
+
+<p dir="rtl"><strong>جست و جو در متن</strong></p>
+
+```
+/word # هایلایت کردن همه‌ی کلمه های بعد Ú©Ùرسر
+
+?word # هایلایت کردن همه‌ی کلمه های قبل Ú©Ùرسر
+
+n # جابه‌جایی Ú©Ùرسر به کلمه های بعدی پیدا شده
+
+N # جابه‌جایی Ú©Ùرسر به کلمه های قبلی پیدا شده
+```
+
+<p dir="rtl">عوض کردن 'foo' به 'bar' در هر خط از Ùایل</p>
+
+```
+:%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file
+```
+
+<p dir="rtl">عوض کردن 'foo' به 'bar' در خط Ùعلی</p>
+
+```
+:s/foo/bar/g # Change 'foo' to 'bar' on the current line
+```
+
+<p dir="rtl">جایگزینی کاراکتر های خط جدید با کاراکتر های خط جدید</p>
+
+```
+:%s/\n/\r/g # Replace new line characters with new line characters
+```
+
+<p dir="rtl"><strong>پرش به کاراکتر ها</strong></p>
+<p dir="rtl">پرش به جلو Ùˆ قرار گرÙتن روی کاراکتر مورد نظر</p>
+
+```
+f<character> # Jump forward and land on <character>
+```
+
+<p dir="rtl">پرش به جلو Ùˆ قرار گرÙتن قبل کاراکتر مورد نظر</p>
+
+```
+t<character> # Jump forward and land right before <character>
+```
+
+<p dir="rtl"><strong>برای مثال:</strong></p>
+
+<p dir="rtl">پرش به جلو Ùˆ قرار گرÙتن روی ></p>
+
+```
+f< # Jump forward and land on <
+```
+
+<p dir="rtl">پرش به جلو Ùˆ قرار گرÙتن قبل از ></p>
+
+```
+t< # Jump forward and land right before <
+```
+<p dir="rtl"><strong>جابه‌جا شدن با کلمه ها</strong></p>
+
+```
+w # رÙتن به جلو به اندازه‌ی یک کلمه
+b # رÙتن به عقب به اندازه‌ی یک کلم
+e # رÙتن به آخر کلمه‌ی Ùعلی
+```
+<p dir="rtl"><strong>سایر کاراکتر ها برای جابه‌جایی</strong></p>
+<p dir="rtl">رÙتن به اول Ùایل</p>
+
+```
+gg # Go to the top of the file
+```
+<p dir="rtl">رÙتن به آخر Ùایل</p>
+
+```
+G # Go to the bottom of the file
+```
+<p dir="rtl">رÙتن به شماره‌ی خط مورد نظر (NUM شماره است)</p>
+
+```
+:NUM # Go to line number NUM (NUM is any number)
+```
+<p dir="rtl">رÙتن به اول صÙحه</p>
+
+```
+H # Move to the top of the screen
+```
+<p dir="rtl">رÙتن به وسط صÙحه</p>
+
+```
+M # Move to the middle of the screen
+```
+<p dir="rtl">رÙتن به آخر صÙحه</p>
+
+```
+L # Move to the bottom of the screen
+```
+
+<h3>
+<p dir="rtl"><strong>
+داک های help
+</strong></p>
+</h3>
+
+<p dir="rtl">
+Vim دارای یک help doc داخلی است Ú©Ù‡ می‌توان با help: <topic> به آن دسترسی داشت. برای مثال help navigation: داک مربوط به مکان‌یابی در Ùضای کار را به شما نشان می‌دهد! <br /><br />
+help: همچنین می‌تواند بدون option مورد استÙاده قرار گیرد.
+این یه صورت یک help پیش‌Ùرض بالا می‌آید Ú©Ù‡ شروع vim را قابل دسترس تر می‌کند!
+</p>
+
+<h3>
+ <p dir="rtl"><strong>Modes:</strong></p>
+</h3>
+
+<div dir="rtl">
+Vim بر پایه‌ی Ù…Ùهومی‌ست به نام <strong>modes</strong>
+<br /><br />
+<ul>
+ <li>
+ Command Mode - ویم در این حالت بالا می‌آید،‌ برای مکان‌یابی Ùˆ نوشتن دستورات استÙاده می‌شود
+</li>
+<li>
+ Insert Mode - برای ایجاد تغییر در Ùایل شما استÙاده می‌شود
+</li>
+<li>
+ Visual Mode - برای هایلایت کردن متن Ùˆ انجام عملی روی آن ها استÙاده می‌شود
+</li>
+<li>
+ Ex Mode - برای وارد کردن دستورات توسط ":" در قسمت پایین استÙاده می‌شود
+</li>
+</ul>
+<br />
+</div>
+
+<p dir="rtl">رÙتن به حالت insert, پیش از جایگاه cursor</p>
+
+```
+i # Puts vim into insert mode, before the cursor position
+```
+<p dir="rtl">رÙتن به حالت insert, پس از جایگاه cursor</p>
+
+```
+a # Puts vim into insert mode, after the cursor position
+```
+
+<p dir="rtl">رÙتن به حالت visual</p>
+
+```
+v # Puts vim into visual mode
+```
+<p dir="rtl">رÙتن به حالت ex</p>
+
+```
+: # Puts vim into ex mode
+```
+<p dir="rtl">خروج از همه‌ی حالت ها Ùˆ رÙتن به حالت command</p>
+
+```
+<esc> # 'Escapes' from whichever mode you're in, into Command mode
+```
+<p dir="rtl">کپی و پیست در متن</p>
+
+```
+y # کپی کردن متن انتخاب شده
+
+yy # Ú©Ù¾ÛŒ کردن خط Ùعلی
+
+d # حذ٠کردن متن انتخاب شده
+
+dd # حذ٠کردن خط Ùعلی
+
+p # پیست کردن متن Ú©Ù¾ÛŒ شده پس از جایگاه Ùعلی Ú©Ùرسر
+
+P # پیست کردن متن Ú©Ù¾ÛŒ شده پیش از جایگاه Ùعلی Ú©Ùرسر
+
+x # حذ٠کردن یک کاراکتر از جایگاه Ú©Ùرسر
+```
+
+<h3>
+<p dir="rtl"><strong>گرامر (Grammer) </strong></p>
+</h3>
+
+<div dir="rtl">
+Vim را می توان به عنوان مجموعه ای از دستورات در قالب (Verb - Modifier - Noun) تصور کرد ، جایی که:
+<br /><br />
+<ul>
+<li>
+ Verb - عمل شما
+</li>
+<li>
+ Modifier - چگونگی انجام عمل شما
+</li>
+<li>
+ Noun - شیئی که عمل شما بر اساس آن عمل می کند
+</li>
+</ul>
+اندکی از مثال های مهم Verbs ,Modifiers, Nouns:
+<br /><br />
+</div>
+
+<p dir="rtl"><strong>Ùعل ها (Verbs)</strong></p>
+
+```
+d # حذÙ
+c # تغییر
+y # کپی
+v # انتخاب
+```
+<p dir="rtl"><strong>تغییردهنده ها (Modifiers)</strong></p>
+
+```
+i # داخل
+a # اطراÙ
+NUM # شماره (NUM هر شماره‌ای است)
+f # جست و جو کردن چیزی و متوق٠شدن روی آن
+t # جست و جو کردن چیزی و متوق٠شدن قبل از آن
+/ # جست Ùˆ جو کردن رشته‌ای پس از Ú©Ùرسر
+? # جست Ùˆ جو کردن رشته‌ای پیش از Ú©Ùرسر
+```
+<p dir="rtl"><strong>اسم ها (Nouns)</strong></p>
+
+```
+w # کلمه
+s # جمله
+p # پاراگراÙ
+b # بلوک
+```
+<p dir="rtl"><strong>جمله ها و کامند های نمونه</strong></p>
+
+```
+d2w # حذ٠دو کلمه
+cis # تغییر داخل جمله
+yip # Ú©Ù¾ÛŒ داخل پاراگرا٠(از پاراگراÙÛŒ Ú©Ù‡ داخل آن هستید Ú©Ù¾ÛŒ کنید)
+ct< # متن را از جایی که قرار دارید به براکت باز بعدی تغییر دهید
+d$ # حذ٠تا پایان
+```
+
+<h3>
+ <p dir="rtl">بعضی از شورتکات ها Ùˆ ترÙند ها</p>
+</h3>
+
+```
+<!--TODO: Add more!-->
+
+> # ایجاد دندانه به اندازه یک بلوک
+
+< # حذ٠دندانه به اندازه یک بلوک
+
+:earlier 15m # برگرداندن همه چیز به ۱۵ دقیقه قبل
+
+:later 15m # برعکس کامند قبلی
+
+ddp # تغییر مکان خطوط متوالی(dd, then p)
+
+. # تکرار دستور قبلی
+
+:w !sudo tee % # ذخیره کردن Ùایل Ùعلی به عنوان روت
+
+:set syntax=c # تنظیم سینتکس هایلایتینگ روی 'c'
+
+:sort # مرتب کردن همه‌ی خطوط
+
+:sort! # مرتب کردن همه‌ی خطوط به صورت برعکس
+
+:sort u # مرتب کردن همه‌ی خطوط و پاک کردن تکراری ها
+
+~ # تبدیل متن انتخاب شده به حرو٠(اگر بزرگ است، کوچک و اگر کوچک است، بزرگ)
+
+u # تبدیل متن انتخاب شده به حرو٠کوچک
+
+U # تبدیل متن انتخاب شده به حرو٠بزرگ
+
+J # اتصال خط Ùعلی به خط بعدی
+```
+<h4>
+<p dir="rtl">
+Ùولد (Fold)
+</p>
+</h4>
+
+```
+zf # ایجاد Ùولد برای متن انتخاب شده
+zo # باز کردن Ùولد Ùعلی
+zc # بستن Ùولد Ùعلی
+zR # باز کردن همه‌ی Ùولد ها
+zM # بستن همه‌ی Ùولد ها
+```
+
+<h3>
+<p dir="rtl">
+ماکرو ها (Macros)
+</p>
+</h3>
+
+<p dir="rtl">
+ماکرو ها اساسا عمل های قابل ضبط هستند. زمانی Ú©Ù‡ شما شروع می‌کنید به ضبط ماکرو، هر عمل Ùˆ دستوری را Ú©Ù‡ استÙاده می‌کنید، تا زمانی Ú©Ù‡ ضبط را متوق٠کنید، ضبط می‌شود. با Ùراخوانی ماکرو، دقیقاً همان توالی اعمال Ùˆ دستورات، دوباره روی متن انتخاب شده اعمال می‌شود.
+</p>
+
+```
+qa # Start recording a macro named 'a'
+q # Stop recording
+@a # Play back the macro
+```
+<h3>
+<p dir="rtl">
+کانÙیگ vimrc./~
+<p>
+</h3>
+
+<p dir="rtl">
+vimrc. Ùایلی‌ست Ú©Ù‡ استÙاده می‌شود برای کانÙیگ vim هنگام بالا آمدن
+<br />
+این‌جا یک نمونه‌ Ùایل vimrc. آورده شده:
+</p>
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" Determines filetype from name to allow intelligent auto-indenting, etc.
+filetype indent plugin on
+
+" Enable syntax highlighting
+syntax on
+
+" Better command-line completion
+set wildmenu
+
+" Use case insensitive search except when using capital letters
+set ignorecase
+set smartcase
+
+" When opening a new line and no file-specific indenting is enabled,
+" keep same indent as the line you're currently on
+set autoindent
+
+" Display line numbers on the left
+set number
+
+" Indentation options, change according to personal preference
+
+" Number of visual spaces per TAB
+set tabstop=4
+
+" Number of spaces in TAB when editing
+set softtabstop=4
+
+" Number of spaces indented when reindent operations (>> and <<) are used
+set shiftwidth=4
+" Convert TABs to spaces
+set expandtab
+
+" Enable intelligent tabbing and spacing for indentation and alignment
+set smarttab
+```
+
+<h3>
+<p dir="rtl">رÙرنس ها</p>
+</h3>
+
+[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? (St
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown
index af304099..ef88a96e 100644
--- a/fi-fi/go-fi.html.markdown
+++ b/fi-fi/go-fi.html.markdown
@@ -33,7 +33,7 @@ Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön.
rivin kommentti */
// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto.
-// Main on erityinen nimi joka ilmoittaa
+// main on erityinen nimi joka ilmoittaa
// suoritettavan tiedoston kirjaston sijasta.
package main
@@ -90,7 +90,7 @@ voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi.
// Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8.
g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen.
- f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku.
+ f := 3.14159 //float64, IEEE-754 64-bittinen liukuluku.
c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla.
// var -syntaksi alkuarvoilla.
@@ -418,21 +418,21 @@ func requestServer() {
## Lisää luettavaa
-Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/).
+Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(https://go.dev/).
Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon.
-Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa
+Kierroksen lisäksi [dokumentaatio](https://go.dev/doc/) pitää sisällään tietoa
siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta.
Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja
yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.)
-Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm).
-Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org)
+Voit askarrella parissa kanssa [Go playgroundissa](https://go.dev/play/p/tnWMjr16Mm).
+Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://go.dev/play/](https://go.dev/play/)
[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista.
-Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/).
+Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](https://go.dev/src/).
Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista,
--tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja
+-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](https://go.dev/pkg/) ja
lähdekoodi tulee esille!
Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/).
diff --git a/fish.html.markdown b/fish.html.markdown
index edbd8909..4b70f883 100644
--- a/fish.html.markdown
+++ b/fish.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: fish
contributors:
- ["MySurmise", "https://github.com/MySurmise"]
+ - ["Geo Maciolek", "https://github.com/GeoffMaciolek"]
filename: learn.fish
---
@@ -14,45 +15,64 @@ Examples of these features are autosuggestions, 24-bit colors, Man Page Completi
It was released in February 2005.
-[Read more](https://fishshell.com/docs/current/language.html)
+- [Read more](https://fishshell.com/docs/current/language.html)
+- [Installation guide](https://github.com/fish-shell/fish-shell#getting-fish)
-[Installation guide](https://github.com/fish-shell/fish-shell#getting-fish)
-
-# Guide
+## Guide
Be sure you have the newest fish shell. This was made with version 3.3.0. To test, type:
+
+```
> fish -v
+```
To start the fish shell, type:
+
+```
> fish
+```
to exit, type:
+
+```
> exit
+```
or press <kbd>Ctrl + D</kbd>
Now, right out of the gate, there's one annoying thing in fish. It's the welcome message. Who needs that, right? When your shell is started, just type:
-> set -U fish_greeting ""
-
-To set that to the wanted value,  .
+```
+> set -U fish_greeting ""
+```
If you want to execute a single command written in bash, without switching to that shell, you can type:
+
+```
> bash -c 'echo "fish is better than bash"'
+```
In fish, you can use single or double quotes.
The escape character is a `\`
You can change your configuration of fish either by editing the config file
+
+```
> vim ~/.config/fish/config.fish
+```
or by opening the aforementioned web settings:
->fish_config
+```
+> fish_config
+```
Adding something to your fish PATH Variable is easy:
+
+```
> fish_path_add ~/cowsay
+```
Can you do that with bash, huh? No, you always have to look it up... It's just that easy!
@@ -60,21 +80,28 @@ But there's more. Most fish-specific commands start, you guessed it, with 'fish'
Now you can navigate with <kbd>TAB</kbd>, <kbd>Shift + TAB</kbd> and your Arrow-Keys <kbd>â†</kbd><kbd>↑</kbd><kbd>→</kbd><kbd>↓</kbd>.
To get help, contact your local psychiatrist or type `man`. That will bring up the manual for that command, for example:
+
+```
> man set
+```
If you finally tried fish, you can see something other in fish that's really cool. Everything has cool colors, if you type in something wrong, it is red, without even executing, if you put something in quotes, you see where it ends and why that quote doesn't work, because there's another qoutation mark in the quote at position 26.
fish has even more cool things, like wildcards.
For example, type
+
+```
> ls *.fish
+```
That will list all fish files in your current directory.
You can have multiple wildcards per command or even a recursive wildcard, `**`, which basically means it includes files and directories, that fit.
For example the following command would return (in your case):
-> ls ~/images/**.jpg
```
+> ls ~/images/**.jpg
+
~/images/nudes/pewdiepie.jpg
~/images/nudes/peppa.jpg
~/images/screenshots/2020-42-69.jpg
@@ -83,72 +110,77 @@ For example the following command would return (in your case):
Of course, you can also pipe the output of a command to another command
+```
>echo sick egg, nadia. no u do really goofy shit. | grep [udense]
+```
write to a file:
+```
>echo This\ is\ text > file.txt
+```
(noticed the escape character?)
Add to a file:
+```
>echo This\ is\ a\ line >> file.txt
-
>echo This\ is\ a\ second\ line >> file.txt
+```
For Autocompletion, just always press <kbd>TAB</kbd>. You will be surprised how many things fish knows.
To use variables, just type `$VAR`, like in bash.
+```
> echo "My home is $HOME"
-
-> My home is /home/myuser
+My home is /home/myuser
+```
Here comes a difference between single and double quotes. If you use a variable in single quotes, it will not substitute it.
+```
> echo 'My home is $HOME'
-
-> My home is $HOME
+My home is $HOME
+```
More on variables later.
To execute two commands, separate them with `;`
+
+```
> echo Lol; echo this is fun
+```
The status code of the last command is stored in `$status`
You can use && for two commands that depend on each other.
+```
> set var lol && echo $var
+```
-You can also use and,
-which executes if the previous command was successful
-
-or
-which executes if the previous command was not successful
-
-and not
+You can also use `and` which executes if the previous command was successful,
+`or` which executes if the previous command was not successful, and `not`
which inverts the exit status of a command.
For example:
-
-> if not echo It's very late I should not waste my time with this
-
->> echo Nobody heard you
-
->end
+```
+> if not echo It's very late I should not waste my time with this
+ echo Nobody heard you
+ end
+```
(You can of course do all of that in the shell)
-
---
-Now let's start with the scripting part of fish.
+Now let's start with the scripting part of fish.
As with every shell, you can not only execute commands in the shell, but also as files, saved as a `.fish` file.
(You can also execute `.sh` files with fish syntax, but I always use `.fish` for fish-syntax scripts to distinguish them from bash script files)
-```bash
+```fish
# This is a comment in fish.
#
# If you execute a file without specifying an interpreter,
@@ -165,10 +197,9 @@ As with every shell, you can not only execute commands in the shell, but also as
# for use inside a program, you can use the syntax
set name = 'My Variable'
-
-# use
+# Use...
set -x name value
-# to eXport
+# to eXport, or
set -e name
# to Erase
@@ -188,20 +219,21 @@ count $PATH
# So $PWD for example is a list of length 1.
# To make a list, just give the set command multiple arguments:
set list entry1 entry2 entry3
+
# that way you can also append something to an existing variable:
set PATH $PATH ~/cowsay/
# But, as previously mentioned, we also have a simpler way to do that specifically in fish.
# As with every Array/List, you can access it with
$listvar[2]
+
# there's also ranges with
-$listvar[1..5]
+$listvar[1..5]
+
# and you can use negative numbers like
$listvar[-1]
# e.g to access the last element.
-
-
# You can also do fancy cartesian products when you combine two list variables:
set a 1 2 3
set 1 a b c
@@ -239,7 +271,7 @@ else
echo Got nothing
end
-# A little weird is that you compare stuff with one = sign , of course because we don't need it to set variables, but still... and the keyword "test":
+# A little weird is that you compare stuff with one = sign, of course because we don't need it to set variables, but still... and the keyword "test":
if test $var = "test"
echo yes
else
@@ -304,10 +336,7 @@ end
# Cool!
# The bashrc equivalent is not fishrc, but the previously mentioned config.fish file in ~/.config/fish/
-
# To add a function to fish, though, you should create a simple .fish file in that directory. Don't just paste that function in the config.fish. That's ugly.
-
# If you have more, just add it, but those are the most important basics.
```
-
diff --git a/forth.html.markdown b/forth.html.markdown
index ff094017..4e2f7599 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -93,8 +93,8 @@ see square \ : square dup * ; ok
\ ------------------------------------ Loops -----------------------------------
-\ `do` is also a compile-only word.
-: myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok
+\ `?do` is also a compile-only word.
+: myloop ( -- ) 5 0 ?do cr ." Hello!" loop ; \ ok
myloop
\ Hello!
\ Hello!
@@ -102,16 +102,17 @@ myloop
\ Hello!
\ Hello! ok
-\ `do` expects two numbers on the stack: the end number and the start number.
+\ `?do` expects two numbers on the stack: the end number (exclusive) and the
+\ start number (inclusive).
\ We can get the value of the index as we loop with `i`:
: one-to-12 ( -- ) 12 0 do i . loop ; \ ok
-one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
+one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 ok
-\ `?do` works similarly, except it will skip the loop if the end and start
-\ numbers are equal.
-: squares ( n -- ) 0 ?do i square . loop ; \ ok
-10 squares \ 0 1 4 9 16 25 36 49 64 81 ok
+\ `do` works similarly, except if start and end are exactly the same it will
+\ loop forever (until arithmetic underflow).
+: loop-forever 1 1 do i square . loop ; \ ok
+loop-forever \ 1 4 9 16 25 36 49 64 81 100 ...
\ Change the "step" with `+loop`:
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
diff --git a/fortran.html.markdown b/fortran.html.markdown
new file mode 100644
index 00000000..316f8c87
--- /dev/null
+++ b/fortran.html.markdown
@@ -0,0 +1,457 @@
+---
+language: Fortran
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+filename: learnfortran.f90
+---
+
+Fortran is one of the oldest computer languages. It was developed in the 1950s
+by IBM for numeric calculations (Fortran is an abbreviation of "Formula
+Translation"). Despite its age, it is still used for high-performance computing
+such as weather prediction. However, the language has changed considerably over
+the years, although mostly maintaining backwards compatibility; well known
+versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008,
+Fortran 2018 and Fortran 2023.
+
+This overview will discuss the features of Fortran 2008 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.
+
+program example ! declare a program called example.
+
+ ! Code can only exist inside programs, functions, subroutines or modules.
+ ! Using indentation is not required but it is recommended.
+
+ ! Declaring Variables
+ ! ===================
+
+ ! All declarations must come before statements and expressions.
+
+ implicit none ! prevents dynamic declaration of variables (recommended!)
+ ! Implicit none must be redeclared in every function/program/module...
+
+ ! IMPORTANT - Fortran is case insensitive.
+ real z
+ REAL Z2
+
+ real :: v, x ! WARNING: default initial values are compiler dependent!
+ real :: a = 3, b = 2E12, c = 0.01
+ integer :: i, j, k = 1, m
+ real, parameter :: PI = 3.1415926535897931 ! declare a constant.
+ logical :: y = .TRUE., n = .FALSE. ! boolean type.
+ complex :: w = (0, 1) ! sqrt(-1)
+ character(len=3) :: month ! string of 3 characters.
+
+ real :: array(6) ! declare an array of 6 reals.
+ real, dimension(4) :: arrayb ! another way to declare an array.
+ integer :: arrayc(-10:10) ! an array with a custom index.
+ real :: array2d(3, 2) ! multidimensional array.
+
+ ! The '::' separators are not always necessary but are recommended.
+
+ ! many other variable attributes also exist:
+ real, pointer :: p ! declare a pointer.
+
+ integer, parameter :: LP = selected_real_kind(20)
+ real(kind=LP) :: d ! long precision variable.
+
+ ! WARNING: initialising variables during declaration causes problems
+ ! in functions since this automatically implies the 'save' attribute
+ ! whereby values are saved between function calls. In general, separate
+ ! declaration and initialisation code except for constants!
+
+ ! Strings
+ ! =======
+
+ character :: a_char = 'i'
+ character(len=6) :: a_str = "qwerty"
+ character(len=30) :: str_b
+ character(len=*), parameter :: a_long_str = "This is a long string."
+ !can have automatic counting of length using (len=*) but only for constants.
+
+ str_b = a_str//" keyboard" ! concatenate strings using // operator.
+
+ ! Assignment & Arithmetic
+ ! =======================
+
+ Z = 1 ! assign to variable z declared above (case insensitive).
+ j = 10 + 2 - 3
+ a = 11.54/(2.3*3.1)
+ b = 2**3 ! exponentiation
+
+ ! Control Flow Statements & Operators
+ ! ===================================
+
+ ! Single-line if statement
+ if (z == a) b = 4 ! condition always need surrounding parentheses.
+
+ if (z /= a) then ! z not equal to a
+ ! Other symbolic comparisons are < > <= >= == /=
+ b = 4
+ else if (z .GT. a) then ! z greater than a
+ ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE.
+ b = 6
+ else if (z < a) then ! 'then' must be on this line.
+ b = 5 ! execution block must be on a new line.
+ else
+ b = 10
+ end if ! end statement needs the 'if' (or can use 'endif').
+
+ if (.NOT. (x < c .AND. v >= a .OR. z == z)) then ! boolean operators.
+ inner: if (.TRUE.) then ! can name if-construct.
+ b = 1
+ end if inner ! then must name endif statement.
+ end if
+
+ i = 20
+ select case (i)
+ case (0, 1) ! cases i == 0 or i == 1
+ j = 0
+ case (2:10) ! cases i is 2 to 10 inclusive.
+ j = 1
+ case (11:) ! all cases where i>=11
+ j = 2
+ case default
+ j = 3
+ end select
+
+ month = 'jan'
+ ! Condition can be integer, logical or character type.
+ ! Select constructions can also be named.
+ monthly:select case(month)
+ case ("jan")
+ j = 0
+ case default
+ j = -1
+ end select monthly
+
+ do i = 2, 10, 2 ! loops from 2 to 10 (inclusive) in increments of 2.
+ innerloop: do j = 1, 3 ! loops can be named too.
+ exit ! quits the loop.
+ end do innerloop
+ cycle ! jump to next loop iteration.
+ end do
+
+ ! Goto statement exists but it is heavily discouraged though.
+ goto 10
+ stop 1 ! stops code immediately (returning specified condition code).
+10 j = 201 ! this line is labeled as line 10
+
+ ! Arrays
+ ! ======
+ array = (/1, 2, 3, 4, 5, 6/)
+ array = [1, 2, 3, 4, 5, 6] ! using Fortran 2003 notation.
+ arrayb = [10.2, 3e3, 0.41, 4e-5]
+ array2d = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [3, 2])
+
+ ! Fortran array indexing starts from 1.
+ ! (by default but can be defined differently for specific arrays).
+ v = array(1) ! take first element of array.
+ v = array2d(2, 2)
+
+ print *, array(3:5) ! print all elements from 3rd to 5th (inclusive).
+ print *, array2d(1, :) ! print first column of 2d array.
+
+ array = array*3 + 2 ! can apply mathematical expressions to arrays.
+ array = array*array ! array operations occur element-wise.
+ ! array = array*array2d ! these arrays would not be compatible.
+
+ ! There are many built-in functions that operate on arrays.
+ c = dot_product(array, array) ! this is the dot product.
+ ! Use matmul() for matrix maths.
+ c = sum(array)
+ c = maxval(array)
+ print *, minloc(array)
+ c = size(array)
+ print *, shape(array)
+ m = count(array > 0)
+
+ ! Loop over an array (could have used Product() function normally).
+ v = 1
+ do i = 1, size(array)
+ v = v*array(i)
+ end do
+
+ ! Conditionally execute element-wise assignments.
+ array = [1, 2, 3, 4, 5, 6]
+ where (array > 3)
+ array = array + 1
+ elsewhere(array == 2)
+ array = 1
+ elsewhere
+ array = 0
+ end where
+
+ ! Implied-DO loops are a compact way to create arrays.
+ array = [(i, i=1, 6)] ! creates an array of [1,2,3,4,5,6]
+ array = [(i, i=1, 12, 2)] ! creates an array of [1,3,5,7,9,11]
+ array = [(i**2, i=1, 6)] ! creates an array of [1,4,9,16,25,36]
+ array = [(4, 5, i=1, 3)] ! creates an array of [4,5,4,5,4,5]
+
+ ! Input/Output
+ ! ============
+
+ print *, b ! print the variable 'b' to the command line
+
+ ! We can format our printed output.
+ print "(I6)", 320 ! prints ' 320'
+ print "(I6.4)", 3 ! prints ' 0003'
+ print "(F6.3)", 4.32 ! prints ' 4.320'
+
+ ! The letter indicates the expected type and the number afterwards gives
+ ! the number of characters to use for printing the value.
+ ! Letters can be I (integer), F (real), E (engineering format),
+ ! L (logical), A (characters) ...
+ print "(I3)", 3200 ! print '***' since the number doesn't fit.
+
+ ! we can have multiple format specifications.
+ print "(I5,F6.2,E6.2)", 120, 43.41, 43.41
+ print "(3I5)", 10, 20, 30 ! 3 repeats of integers (field width = 5).
+ print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 ! repeated grouping of formats.
+
+ ! We can also read input from the terminal.
+ read (*, *) v
+ read (*, "(2F6.2)") v, x ! read two numbers
+
+ ! To write a file.
+ open (unit=12, file="records.txt", status="replace")
+ ! The file is referred to by a 'unit number', an integer that you pick in
+ ! the range 9:99. Status can be one of {'old','replace','new'}.
+ write (12, "(F10.2,F10.2,F10.2)") c, b, a
+ close (12)
+
+ ! To read a file.
+ open (newunit=m, file="records.txt", status="old")
+ ! The file is referred to by a 'new unit number', an integer that the compiler
+ ! picks for you.
+ read (unit=m, fmt="(3F10.2)") a, b, c
+ close (m)
+
+ ! There are more features available than discussed here and alternative
+ ! variants due to backwards compatibility with older Fortran versions.
+
+ ! Built-in Functions
+ ! ==================
+
+ ! Fortran has around 200 functions/subroutines intrinsic to the language.
+ ! Examples -
+ call cpu_time(v) ! sets 'v' to a time in seconds.
+ k = ior(i, j) ! bitwise OR of 2 integers.
+ v = log10(x) ! log base 10.
+ i = floor(b) ! returns the closest integer less than or equal to x.
+ v = aimag(w) ! imaginary part of a complex number.
+
+ ! Functions & Subroutines
+ ! =======================
+
+ ! A subroutine runs some code on some input values and can cause
+ ! side-effects or modify the input values.
+
+ call routine(a, c, v) ! subroutine call.
+
+ ! A function takes a list of input parameters and returns a single value.
+ ! However the input parameters may still be modified and side effects
+ ! executed.
+
+ m = func(3, 2, k) ! function call.
+
+ ! Function calls can also be evoked within expressions.
+ print *, func2(3, 2, k)
+
+ ! A pure function is a function that doesn't modify its input parameters
+ ! or cause any side-effects.
+ m = func3(3, 2, k)
+
+contains ! Zone for defining sub-programs internal to the program.
+
+ ! Fortran has a couple of slightly different ways to define functions.
+
+ integer function func(a, b, c) ! a function returning an integer value.
+ ! implicit none ! subvariable fields can no longer declare implicit none
+ integer, intent(in) :: a, b, c ! type of input parameters defined inside the function.
+
+ if (a >= 2) then
+ func = a + b + c ! the return variable defaults to the function name.
+ return ! can return the current value from the function at any time.
+ end if
+ func = a + c
+
+ ! Don't need a return statement at the end of a function.
+ end function func
+
+ function func2(a, b, c) result(f) ! return variable declared to be 'f'.
+ integer, intent(in) :: a, b ! can declare and enforce that variables
+ !are not modified by the function.
+ integer, intent(inout) :: c
+ integer :: f ! function return type declared inside the function.
+ integer :: cnt = 0 ! GOTCHA - initialisation implies variable is
+ !saved between function calls.
+
+ f = a + b - c
+ c = 4 ! altering the value of an input variable.
+ cnt = cnt + 1 ! count number of function calls.
+
+ end function func2
+
+ pure function func3(a, b, c) ! a pure function can have no side-effects.
+ integer, intent(in) :: a, b, c
+ integer :: func3
+
+ func3 = a*b*c
+
+ end function func3
+
+ subroutine routine(d, e, f)
+ real, intent(inout) :: f
+ real, intent(in) :: d, e
+
+ f = 2*d + 3*e + f
+
+ end subroutine routine
+
+end program example ! End of Program Definition -----------------------
+
+! Functions and Subroutines declared externally to the program listing need
+! to be declared to the program using an Interface declaration (even if they
+! are in the same source file!) (see below). It is easier to define them within
+! the 'contains' section of a module or program.
+
+elemental real function func4(a) result(res)
+! An elemental function is a Pure function that takes a scalar input variable
+! but can also be used on an array where it will be separately applied to all
+! of the elements of an array and return a new array.
+ real, intent(in) :: a
+
+ res = a**2 + 1.0
+
+end function func4
+
+! Modules
+! =======
+
+! A module is a useful way to collect related declarations, functions and
+! subroutines together for reusability.
+
+module fruit
+
+ real :: apple
+ real :: pear
+ real :: orange
+
+end module fruit
+
+module fruity
+ ! Declarations must be in the order: modules, interfaces, variables.
+ ! (can declare modules and interfaces in programs too).
+
+ use fruit, only: apple, pear ! use apple and pear from fruit module.
+ implicit none ! comes after module imports.
+
+ private ! make things private to the module (default is public).
+ ! Declare some variables/functions explicitly public.
+ public :: apple, mycar, create_mycar
+ ! Declare some variables/functions private to the module (redundant here).
+ private :: func4
+
+ ! Interfaces
+ ! ==========
+ ! Explicitly declare an external function/procedure within the module
+ ! (better in general to put functions/procedures in the 'contains' section).
+ interface
+ elemental real function func4(a) result(res)
+ real, intent(in) :: a
+ end function func4
+ end interface
+
+ ! Overloaded functions can be defined using named interfaces.
+ interface myabs
+ ! Can use 'module procedure' keyword to include functions already
+ ! defined within the module.
+ module procedure real_abs, complex_abs
+ end interface
+
+ ! Derived Data Types
+ ! ==================
+ ! Can create custom structured data collections.
+ type car
+ character(len=100) :: model
+ real :: weight ! (kg)
+ real :: dimensions(3) ! i.e. length-width-height (metres).
+ character :: colour
+ contains
+ procedure :: info ! bind a procedure to a type.
+ end type car
+
+ type(car) :: mycar ! declare a variable of your custom type.
+ ! See create_mycar() routine for usage.
+
+ ! Note: There are no executable statements in modules.
+
+contains
+
+ subroutine create_mycar(mycar)
+ ! Demonstrates usage of a derived data type.
+ type(car), intent(out) :: mycar
+
+ ! Access type elements using '%' operator.
+ mycar%model = "Ford Prefect"
+ mycar%colour = 'r'
+ mycar%weight = 1400
+ mycar%dimensions(1) = 5.0 ! default indexing starts from 1!
+ mycar%dimensions(2) = 3.0
+ mycar%dimensions(3) = 1.5
+
+ end subroutine create_mycar
+
+ subroutine info(self)
+ class(car), intent(in) :: self
+ ! 'class' keyword used to bind a procedure to a type here.
+
+ print *, "Model : ", self%model
+ print *, "Colour : ", self%colour
+ print *, "Weight : ", self%weight
+ print *, "Dimensions: ", self%dimensions
+
+ end subroutine info
+
+ real pure function real_abs(x)
+ real, intent(in) :: x
+
+ if (x < 0) then
+ real_abs = -x
+ else
+ real_abs = x
+ end if
+
+ end function real_abs
+
+ real pure function complex_abs(z)
+ complex, intent(in) :: z
+ ! long lines can be continued using the continuation character '&'
+
+ complex_abs = sqrt(real(z)**2 + &
+ aimag(z)**2)
+
+ end function complex_abs
+
+end module fruity
+
+```
+
+### More Resources
+
+For more information on Fortran:
+
++ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
++ [Fortran-lang Organization](https://fortran-lang.org/)
++ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
++ [fortranwiki.org](http://fortranwiki.org)
++ [www.fortran90.org/](http://www.fortran90.org)
++ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/)
++ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran)
++ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf)
++ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html)
diff --git a/fortran95.html.markdown b/fortran95.html.markdown
deleted file mode 100644
index 5fa8ca88..00000000
--- a/fortran95.html.markdown
+++ /dev/null
@@ -1,453 +0,0 @@
----
-language: Fortran
-contributors:
- - ["Robert Steed", "https://github.com/robochat"]
-filename: learnfortran.f95
----
-
-Fortran is one of the oldest computer languages. It was developed in the 1950s
-by IBM for numeric calculations (Fortran is an abbreviation of "Formula
-Translation"). Despite its age, it is still used for high-performance computing
-such as weather prediction. However, the language has changed considerably over
-the years, although mostly maintaining backwards compatibility; well known
-versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and
-Fortran 2015.
-
-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.
-
-
-program example !declare a program called example.
-
- ! Code can only exist inside programs, functions, subroutines or modules.
- ! Using indentation is not required but it is recommended.
-
-
- ! Declaring Variables
- ! ===================
-
- ! All declarations must come before statements and expressions.
-
- implicit none !prevents dynamic declaration of variables (recommended!)
- ! Implicit none must be redeclared in every function/program/module...
-
- ! IMPORTANT - Fortran is case insensitive.
- real z
- REAL Z2
-
- real :: v,x ! WARNING: default initial values are compiler dependent!
- real :: a = 3, b=2E12, c = 0.01
- integer :: i, j, k=1, m
- real, parameter :: PI = 3.1415926535897931 !declare a constant.
- logical :: y = .TRUE. , n = .FALSE. !boolean type.
- complex :: w = (0,1) !sqrt(-1)
- character (len=3) :: month !string of 3 characters.
-
- real :: array(6) !declare an array of 6 reals.
- real, dimension(4) :: arrayb !another way to declare an array.
- integer :: arrayc(-10:10) !an array with a custom index.
- real :: array2d(3,2) !multidimensional array.
-
- ! The '::' separators are not always necessary but are recommended.
-
- ! many other variable attributes also exist:
- real, pointer :: p !declare a pointer.
-
- integer, parameter :: LP = selected_real_kind(20)
- real (kind = LP) :: d !long precision variable.
-
- ! WARNING: initialising variables during declaration causes problems
- ! in functions since this automatically implies the 'save' attribute
- ! whereby values are saved between function calls. In general, separate
- ! declaration and initialisation code except for constants!
-
-
- ! Strings
- ! =======
-
- character :: a_char = 'i'
- character (len = 6) :: a_str = "qwerty"
- character (len = 30) :: str_b
- character (len = *), parameter :: a_long_str = "This is a long string."
- !can have automatic counting of length using (len=*) but only for constants.
-
- str_b = a_str // " keyboard" !concatenate strings using // operator.
-
-
- ! Assignment & Arithmetic
- ! =======================
-
- Z = 1 !assign to variable z declared above (case insensitive).
- j = 10 + 2 - 3
- a = 11.54 / (2.3 * 3.1)
- b = 2**3 !exponentiation
-
-
- ! Control Flow Statements & Operators
- ! ===================================
-
- ! Single-line if statement
- if (z == a) b = 4 !condition always need surrounding parentheses.
-
- if (z /= a) then !z not equal to a
- ! Other symbolic comparisons are < > <= >= == /=
- b = 4
- else if (z .GT. a) then !z greater than a
- ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE.
- b = 6
- else if (z < a) then !'then' must be on this line.
- b = 5 !execution block must be on a new line.
- else
- b = 10
- end if !end statement needs the 'if' (or can use 'endif').
-
-
- if (.NOT. (x < c .AND. v >= a .OR. z == z)) then !boolean operators.
- inner: if (.TRUE.) then !can name if-construct.
- b = 1
- endif inner !then must name endif statement.
- endif
-
-
- i = 20
- select case (i)
- case (0) !case i == 0
- j=0
- case (1:10) !cases i is 1 to 10 inclusive.
- j=1
- case (11:) !all cases where i>=11
- j=2
- case default
- j=3
- end select
-
-
- month = 'jan'
- ! Condition can be integer, logical or character type.
- ! Select constructions can also be named.
- monthly: select case (month)
- case ("jan")
- j = 0
- case default
- j = -1
- end select monthly
-
-
- do i=2,10,2 !loops from 2 to 10 (inclusive) in increments of 2.
- innerloop: do j=1,3 !loops can be named too.
- exit !quits the loop.
- end do innerloop
- cycle !jump to next loop iteration.
- enddo
-
-
- ! Goto statement exists but it is heavily discouraged though.
- goto 10
- stop 1 !stops code immediately (returning specified condition code).
-10 j = 201 !this line is labeled as line 10
-
-
- ! Arrays
- ! ======
- array = (/1,2,3,4,5,6/)
- array = [1,2,3,4,5,6] !using Fortran 2003 notation.
- arrayb = [10.2,3e3,0.41,4e-5]
- array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2])
-
- ! Fortran array indexing starts from 1.
- ! (by default but can be defined differently for specific arrays).
- v = array(1) !take first element of array.
- v = array2d(2,2)
-
- print *, array(3:5) !print all elements from 3rd to 5th (inclusive).
- print *, array2d(1,:) !print first column of 2d array.
-
- array = array*3 + 2 !can apply mathematical expressions to arrays.
- array = array*array !array operations occur element-wise.
- !array = array*array2d !these arrays would not be compatible.
-
- ! There are many built-in functions that operate on arrays.
- c = dot_product(array,array) !this is the dot product.
- ! Use matmul() for matrix maths.
- c = sum(array)
- c = maxval(array)
- print *, minloc(array)
- c = size(array)
- print *, shape(array)
- m = count(array > 0)
-
- ! Loop over an array (could have used Product() function normally).
- v = 1
- do i = 1, size(array)
- v = v*array(i)
- end do
-
- ! Conditionally execute element-wise assignments.
- array = [1,2,3,4,5,6]
- where (array > 3)
- array = array + 1
- elsewhere (array == 2)
- array = 1
- elsewhere
- array = 0
- end where
-
- ! Implied-DO loops are a compact way to create arrays.
- array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6]
- array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11]
- array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36]
- array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5]
-
-
- ! Input/Output
- ! ============
-
- print *, b !print the variable 'b' to the command line
-
- ! We can format our printed output.
- print "(I6)", 320 !prints ' 320'
- print "(I6.4)", 3 !prints ' 0003'
- print "(F6.3)", 4.32 !prints ' 4.320'
-
- ! The letter indicates the expected type and the number afterwards gives
- ! the number of characters to use for printing the value.
- ! Letters can be I (integer), F (real), E (engineering format),
- ! L (logical), A (characters) ...
- print "(I3)", 3200 !print '***' since the number doesn't fit.
-
- ! we can have multiple format specifications.
- print "(I5,F6.2,E6.2)", 120, 43.41, 43.41
- print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5).
- print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 !repeated grouping of formats.
-
- ! We can also read input from the terminal.
- read *, v
- read "(2F6.2)", v, x !read two numbers
-
- ! To read a file.
- open(unit=11, file="records.txt", status="old")
- ! The file is referred to by a 'unit number', an integer that you pick in
- ! the range 9:99. Status can be one of {'old','replace','new'}.
- read(unit=11, fmt="(3F10.2)") a, b, c
- close(11)
-
- ! To write a file.
- open(unit=12, file="records.txt", status="replace")
- write(12, "(F10.2,F10.2,F10.2)") c, b, a
- close(12)
-
- ! There are more features available than discussed here and alternative
- ! variants due to backwards compatibility with older Fortran versions.
-
-
- ! Built-in Functions
- ! ==================
-
- ! Fortran has around 200 functions/subroutines intrinsic to the language.
- ! Examples -
- call cpu_time(v) !sets 'v' to a time in seconds.
- k = ior(i,j) !bitwise OR of 2 integers.
- v = log10(x) !log base 10.
- i = floor(b) !returns the closest integer less than or equal to x.
- v = aimag(w) !imaginary part of a complex number.
-
-
- ! Functions & Subroutines
- ! =======================
-
- ! A subroutine runs some code on some input values and can cause
- ! side-effects or modify the input values.
-
- call routine(a,c,v) !subroutine call.
-
- ! A function takes a list of input parameters and returns a single value.
- ! However the input parameters may still be modified and side effects
- ! executed.
-
- m = func(3,2,k) !function call.
-
- ! Function calls can also be evoked within expressions.
- Print *, func2(3,2,k)
-
- ! A pure function is a function that doesn't modify its input parameters
- ! or cause any side-effects.
- m = func3(3,2,k)
-
-
-contains ! Zone for defining sub-programs internal to the program.
-
- ! Fortran has a couple of slightly different ways to define functions.
-
- integer function func(a,b,c) !a function returning an integer value.
- implicit none !best to use implicit none in function definitions too.
- integer :: a,b,c !type of input parameters defined inside the function.
- if (a >= 2) then
- func = a + b + c !the return variable defaults to the function name.
- return !can return the current value from the function at any time.
- endif
- func = a + c
- ! Don't need a return statement at the end of a function.
- end function func
-
-
- function func2(a,b,c) result(f) !return variable declared to be 'f'.
- implicit none
- integer, intent(in) :: a,b !can declare and enforce that variables
- !are not modified by the function.
- integer, intent(inout) :: c
- integer :: f !function return type declared inside the function.
- integer :: cnt = 0 !GOTCHA - initialisation implies variable is
- !saved between function calls.
- f = a + b - c
- c = 4 !altering the value of an input variable.
- cnt = cnt + 1 !count number of function calls.
- end function func2
-
-
- pure function func3(a,b,c) !a pure function can have no side-effects.
- implicit none
- integer, intent(in) :: a,b,c
- integer :: func3
- func3 = a*b*c
- end function func3
-
-
- subroutine routine(d,e,f)
- implicit none
- real, intent(inout) :: f
- real, intent(in) :: d,e
- f = 2*d + 3*e + f
- end subroutine routine
-
-
-end program example ! End of Program Definition -----------------------
-
-
-! Functions and Subroutines declared externally to the program listing need
-! to be declared to the program using an Interface declaration (even if they
-! are in the same source file!) (see below). It is easier to define them within
-! the 'contains' section of a module or program.
-
-elemental real function func4(a) result(res)
-! An elemental function is a Pure function that takes a scalar input variable
-! but can also be used on an array where it will be separately applied to all
-! of the elements of an array and return a new array.
- real, intent(in) :: a
- res = a**2 + 1.0
-end function func4
-
-
-! Modules
-! =======
-
-! A module is a useful way to collect related declarations, functions and
-! subroutines together for reusability.
-
-module fruit
- real :: apple
- real :: pear
- real :: orange
-end module fruit
-
-
-module fruity
- ! Declarations must be in the order: modules, interfaces, variables.
- ! (can declare modules and interfaces in programs too).
-
- use fruit, only: apple, pear ! use apple and pear from fruit module.
- implicit none !comes after module imports.
-
- private !make things private to the module (default is public).
- ! Declare some variables/functions explicitly public.
- public :: apple,mycar,create_mycar
- ! Declare some variables/functions private to the module (redundant here).
- private :: func4
-
- ! Interfaces
- ! ==========
- ! Explicitly declare an external function/procedure within the module
- ! (better in general to put functions/procedures in the 'contains' section).
- interface
- elemental real function func4(a) result(res)
- real, intent(in) :: a
- end function func4
- end interface
-
- ! Overloaded functions can be defined using named interfaces.
- interface myabs
- ! Can use 'module procedure' keyword to include functions already
- ! defined within the module.
- module procedure real_abs, complex_abs
- end interface
-
- ! Derived Data Types
- ! ==================
- ! Can create custom structured data collections.
- type car
- character (len=100) :: model
- real :: weight !(kg)
- real :: dimensions(3) !i.e. length-width-height (metres).
- character :: colour
- end type car
-
- type(car) :: mycar !declare a variable of your custom type.
- ! See create_mycar() routine for usage.
-
- ! Note: There are no executable statements in modules.
-
-contains
-
- subroutine create_mycar(mycar)
- ! Demonstrates usage of a derived data type.
- implicit none
- type(car),intent(out) :: mycar
-
- ! Access type elements using '%' operator.
- mycar%model = "Ford Prefect"
- mycar%colour = 'r'
- mycar%weight = 1400
- mycar%dimensions(1) = 5.0 !default indexing starts from 1!
- mycar%dimensions(2) = 3.0
- mycar%dimensions(3) = 1.5
-
- end subroutine
-
- real function real_abs(x)
- real :: x
- if (x<0) then
- real_abs = -x
- else
- real_abs = x
- end if
- end function real_abs
-
- real function complex_abs(z)
- complex :: z
- ! long lines can be continued using the continuation character '&'
- complex_abs = sqrt(real(z)**2 + &
- aimag(z)**2)
- end function complex_abs
-
-
-end module fruity
-
-```
-
-### More Resources
-
-For more information on Fortran:
-
-+ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
-+ [Fortran-lang Organization](https://fortran-lang.org/)
-+ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
-+ [fortranwiki.org](http://fortranwiki.org)
-+ [www.fortran90.org/](http://www.fortran90.org)
-+ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/)
-+ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran)
-+ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf)
-+ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html)
diff --git a/fr-fr/awk-fr.html.markdown b/fr-fr/awk-fr.html.markdown
index 75c48811..bd4e1312 100644
--- a/fr-fr/awk-fr.html.markdown
+++ b/fr-fr/awk-fr.html.markdown
@@ -10,37 +10,49 @@ lang: fr-fr
---
-AWK est un outil standard présent dans chaque système UNIX conforme aux normes POSIX.
-C’est un outil en ligne de commande qui ressemble au Perl et qui est excellent dans les tâches de traitement de fichiers texte.
-Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage de script autonome.
+AWK est un outil standard présent dans chaque système UNIX conforme aux normes
+POSIX. C’est un outil en ligne de commande qui ressemble au Perl et qui est
+excellent dans les tâches de traitement de fichiers texte.
+Vous pouvez l’appeler à partir d’un script shell, ou l’utiliser comme un langage
+de script autonome.
Pourquoi utiliser AWK au lieu du langage Perl ?
-Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur une très grande partie des systèmes d'exploitation UNIX et Linux.
-AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour ce qui concerne le traitement de texte simple. Notamment le traitement de ceux qui necéssitent de lire des fichiers ligne par ligne ; chaque ligne comportant des champs séparés par des délimiteur.
-
+Principalement, car AWK fait partie d'UNIX et est donc présent par défaut sur
+une très grande partie des systèmes d'exploitation UNIX et Linux.
+AWK est aussi plus facile à lire que le langage Perl ; et est l'outil idéal pour
+ce qui concerne le traitement de texte simple. Notamment le traitement de ceux
+qui nécessitent de lire des fichiers ligne par ligne ; chaque ligne comportant
+des champs séparés par des délimiteur.
```awk
#!/usr/bin/awk -f
# Les commentaires commencent par un #
-
-# les programmes AWK consistent en une collection de règles et d'actions
+# Les programmes AWK consistent en une collection de règles et d'actions.
règle1 { action; }
règle2 { action; }
# AWK lit et analyse automatiquement chaque ligne de chaque fichier fourni.
-# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur peut être changer grâce à l'option -F ou être renseigné au début d'un bloc (exemple: FS = " ").
-
-# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le point d’entrée principal du script.
-# A l'opposé de BEGIN, il existe la règle END. Cette règle est présente après chaque fin de fichier (EOF : End Of File).
+# Chaque ligne est divisée par un délimiteur FS qui est par défaut l'espace
+# (plusieurs espaces ou une tabulation comptent pour un espace). Ce délimiteur
+# peut être changé grâce à l'option -F ou être renseigné au début d'un bloc
+# (exemple: FS = " ").
+
+# BEGIN est une règle spécifique exécutée au début du programme. C'est à cet
+# endroit que vous mettrez tout le code à exécuter avant de traiter les fichiers
+# texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le
+# point d’entrée principal du script.
+# À l'opposé de BEGIN, il existe la règle END. Cette règle est présente après
+# chaque fin de fichier (EOF : End Of File).
BEGIN {
# Les variables sont globales. Pas besoin de les déclarer.
count = 0;
- # les opérateurs sont identiques au langage C et aux langages similaires (exemple: C#, C++)
+ # Les opérateurs sont identiques au langage C et aux langages similaires
+ # (tels que C#, C++, etc.)
a = count + 1; # addition
b = count - 1; # soustraction
c = count * 1; # multiplication
@@ -59,7 +71,8 @@ BEGIN {
a++;
b--;
- # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui est retournée
+ # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui
+ # est retournée
++a;
--b;
@@ -74,7 +87,8 @@ BEGIN {
# Les blocs sont composés d'une multitude de lignes entre accolades
while (a < 10) {
- print "La concaténation de chaînes de caractères" " se fait avec des séries de chaînes " " séparées par des espaces";
+ print "La concaténation de chaînes de caractères" " se fait avec"
+ "des séries de chaînes " "séparées par des espaces";
print a;
a++;
@@ -106,14 +120,14 @@ BEGIN {
arr[1] = "bar";
# Vous pouvez aussi initialiser un tableau avec la fonction split()
-
n = split("foo:bar:baz", arr, ":");
# Il y a aussi les tableaux associatifs
assoc["foo"] = "bar";
assoc["bar"] = "baz";
- # et les tableaux multi-dimentions, avec certaines limitations que l'on ne mentionnera pas ici
+ # et les tableaux multi-dimensions, avec certaines limitations que l'on ne
+ # mentionnera pas ici
multidim[0,0] = "foo";
multidim[0,1] = "bar";
multidim[1,0] = "baz";
@@ -123,7 +137,8 @@ BEGIN {
if ("foo" in assoc)
print "Fooey!";
- # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés d'un tableau
+ # Vous pouvez aussi utilisez l'opérateur 'in' pour parcourir les clés
+ # d'un tableau
for (key in assoc)
print assoc[key];
@@ -131,16 +146,16 @@ BEGIN {
for (argnum in ARGV)
print ARGV[argnum];
- # Vous pouvez supprimer des éléments d'un tableau
- # C'est utile pour empêcher AWK de supposer que certains arguments soient des fichiers à traiter.
+ # Vous pouvez supprimer des éléments d'un tableau.
+ # C'est utile pour empêcher AWK de supposer que certains arguments soient
+ # des fichiers à traiter.
delete ARGV[1];
- # Le nombre d'arguments de la ligne de commande est dans une variable appellée ARGC
+ # Le nombre d'arguments de la ligne de commande est assigné à
+ # la variable ARGC
print ARGC;
- # AWK inclue trois catégories de fonction.
- # On les examinera plus tard
-
+ # AWK inclue trois catégories de fonction. On les examinera plus tard.
return_value = arithmetic_functions(a, b, c);
string_functions();
io_functions();
@@ -149,22 +164,24 @@ BEGIN {
# Voici comment définir une fonction
function arithmetic_functions(a, b, c, d) {
- # La partie la plus ennuieuse de AWK est probablement l’absence de variables locales.
- # Tout est global. Pour les scripts courts, c'est très utile, mais pour les scripts plus longs,
- # cela peut poser problème.
+ # La partie la plus ennuyeuse de AWK est probablement l’absence de variables
+ # locales. Tout est global. Pour les scripts courts, c'est très utile, mais
+ # pour les scripts plus longs, cela peut poser un problème.
- # Il y a cepandant une solution de contournement (enfin ... une bidouille).
+ # Il y a cependant une solution de contournement (enfin ... une bidouille).
# Les arguments d'une fonction sont locaux à cette fonction.
- # Et AWK vous permet de définir plus d'arguments à la fonction que nécessaire.
- # Il suffit donc de mettre une variable locale dans la déclaration de fonction,
- # comme ci-dessus. La convention veut que vous mettiez quelques espaces supplémentaires
- # pour faire la distinction entre les paramètres réels et les variables locales.
- # Dans cet exemple, a, b et c sont des paramètres réels,
- # alors que d est simplement une variable locale.
+ # Et AWK vous permet de définir plus d'arguments à la fonction que
+ # nécessaire. Il suffit donc de mettre une variable locale dans la
+ # déclaration de fonction, comme ci-dessus. La convention veut que vous
+ # mettiez quelques espaces supplémentaires pour faire la distinction entre
+ # les paramètres réels et les variables locales.
+ # Dans cet exemple, a, b et c sont des paramètres réels, alors que d est
+ # simplement une variable locale.
# Maintenant, les fonctions arithmétiques
- # La plupart des implémentations de AWK ont des fonctions trigonométriques standards
+ # La plupart des implémentations de AWK ont des fonctions trigonométriques
+ # standards
localvar = sin(a);
localvar = cos(a);
localvar = atan2(b, a); # arc tangente de b / a
@@ -180,10 +197,10 @@ function arithmetic_functions(a, b, c, d) {
localvar = int(5.34); # localvar => 5
# Les nombres aléatoires
- srand();
+ srand();
# L'argument de la fonction srand() est la valeur de départ pour générer
# les nombres aléatoires . Par défaut, il utilise l'heure du système
-
+
localvar = rand(); # Nombre aléatoire entre 0 et 1.
# Maintenant on retourne la valeur
@@ -195,18 +212,21 @@ function string_functions( localvar, arr) {
# AWK a plusieurs fonctions pour le traitement des chaînes de caractères,
# dont beaucoup reposent sur des expressions régulières.
- # Chercher et remplacer, la première occurence (sub) ou toutes les occurences (gsub)
+ # Chercher et remplacer, la première occurrence (sub), ou toutes les
+ # occurrences (gsub).
# Les deux renvoient le nombre de correspondances remplacées
localvar = "fooooobar";
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar); # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar); # localvar => "M..t m. at th. bar"
- # Rechercher une chaîne de caractères qui correspond à une expression régulière
- # index() fait la même chose, mais n'autorise pas les expressions régulières
+ # Rechercher une chaîne de caractères qui correspond à une expression
+ # régulière index() fait la même chose, mais n'autorise pas les expressions
+ # régulières.
match(localvar, "t"); # => 4, puisque 't' est le quatrième caractère
# Séparer par un délimiteur
- n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
+ n = split("foo-bar-baz", arr, "-");
+ # résultat : a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
# Autre astuces utiles
sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3"
@@ -226,26 +246,25 @@ function io_functions( localvar) {
printf("%s %d %d %d\n", "Testing", 1, 2, 3);
# AWK n'a pas de descripteur de fichier en soi. Il ouvrira automatiquement
- # un descripteur de fichier lorsque vous utilisez quelque chose qui en a besoin.
- # La chaîne de caractères que vous avez utilisée pour cela peut être traitée
- # comme un descripteur de fichier à des fins d'entrée / sortie.
-
+ # un descripteur de fichier lorsque vous utilisez quelque chose qui en a
+ # besoin. La chaîne de caractères que vous avez utilisée pour cela peut être
+ # traitée comme un descripteur de fichier à des fins d'entrée / sortie.
outfile = "/tmp/foobar.txt";
-
print "foobar" > outfile;
- # Maintenant, la chaîne de caractères "outfile" est un descripteur de fichier.
- # Vous pouvez le fermer
+ # Maintenant, la chaîne de caractères "outfile" est un descripteur de
+ # fichier. Vous pouvez le fermer.
close(outfile);
# Voici comment exécuter quelque chose dans le shell
system("echo foobar"); # => affiche foobar
- # Lire quelque chose depuis l'entrée standard et la stocker dans une variable locale
+ # Lire quelque chose depuis l'entrée standard et la stocker dans une
+ # variable locale
getline localvar;
- # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une chaine de caractère
- # que vous fermerez proprement)
+ # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une
+ # chaîne de caractère que vous fermerez proprement)
"echo foobar" | getline localvar # localvar => "foobar"
close("echo foobar")
@@ -256,33 +275,36 @@ function io_functions( localvar) {
}
# Comme dit au début, AWK consiste en une collection de règles et d'actions.
-# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont utilisées que si vous traitez
-# des lignes à partir de fichiers ou l'entrée standard (stdin).
-# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de fichiers à traiter.
-# AWK les traitera tous dans l'ordre. Voyez les comme dans à une boucle implicite,
-# parcourant les lignes de ces fichiers.
-# Ces règles et ces actions ressemblent à des instructions switch dans la boucle.
+# Vous connaissez déjà les règles BEGIN et END. Les autres règles ne sont
+# utilisées que si vous traitez des lignes à partir de fichiers ou l'entrée
+# standard (stdin).
+# Quand vous passez des arguments à AWK, ils sont considérés comme des noms de
+# fichiers à traiter. AWK les traitera tous dans l'ordre. Voyez les comme dans
+# une boucle implicite, parcourant les lignes de ces fichiers. Ces règles et ces
+# actions ressemblent à des instructions switch dans la boucle.
/^fo+bar$/ {
- # Cette action sera exécutée pour chaque ligne qui correspond à l'expression régulière,
- # /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond pas.
- # Imprimons simplement la ligne:
+ # Cette action sera exécutée pour chaque ligne qui correspond à l'expression
+ # régulière, /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond
+ # pas. Imprimons simplement la ligne :
print;
# Pas d'argument ! C'est parce que print a un défaut : $0.
- # $0 est le nom de la ligne en cours de traitement. Il est créé automatiquement.
+ # $0 est le nom de la ligne en cours de traitement. Il est créé
+ # automatiquement.
# Vous devinez probablement qu'il existe d'autres variables $.
- # Chaque ligne est divisée implicitement avant que chaque action soit exécutée, comme
- # le fait le shell. Et, comme le shell, chaque champ est accessible avec un signe dollar
+ # Chaque ligne est divisée implicitement avant que chaque action soit
+ # exécutée, comme le fait le shell. Et, comme le shell, chaque champ est
+ # accessible avec un signe dollar.
- # Ceci affichera les deuxième et quatrième champs de la ligne.
+ # Ceci affichera les deuxième et quatrième champs de la ligne.
print $2, $4;
- # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous aider
- # à inspecter et traiter chaque ligne. La plus importante est NF
+ # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous
+ # aider à inspecter et traiter chaque ligne. La plus importante est NF.
# Affiche le nombre de champs de la ligne
print NF;
@@ -291,33 +313,33 @@ function io_functions( localvar) {
print $NF;
}
-# Chaque règle est en réalité un test conditionel.
-
+# Chaque règle est en réalité un test conditionnel.
a > 0 {
# Ceci s’exécutera une fois pour chaque ligne, tant que le test est positif
}
-# Les expressions régulières sont également des tests conditionels.
-#Si le test de l'expression régulières n'est pas vrais alors le bloc n'est pas executé
-$0 /^fobar/ {
- print "la ligne commance par fobar"
+# Les expressions régulières sont également des tests conditionnels.
+# Si le test de l'expression régulières n'est pas vrais alors le bloc
+# n'est pas exécuté.
+$0 /^fobar/ {
+ print "la ligne commence par foobar"
}
-# Dans le cas où vous voulez tester votre chaine de caractères sur la ligne en cours de traitement
-# $0 est optionnelle.
-
+# Dans le cas où vous voulez tester votre chaîne de caractères sur la ligne
+# en cours de traitement $0 est optionnelle.
/^[a-zA-Z0-9]$/ {
print "La ligne courante ne contient que des caractères alphanumériques.";
}
+# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en
+# fonction de règles établies. Cela est si courant sous UNIX qu'AWK est un
+# langage de script.
-# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en fonction de règles établies
-# Cela est si courant sous UNIX qu'AWK est un langage de script.
-
-# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est parfait.
-# Le script lit un nom à partir de l'entrée standard, puis affiche l'âge moyen de toutes les
-# personnes portant ce prénom.
-# Supposons que vous fournissiez comme argument le nom d'un fichier comportant ces données:
+# Ce qui suit est un exemple rapide d'un petit script, pour lequel AWK est
+# parfait. Le script lit un nom à partir de l'entrée standard, puis affiche
+# l'âge moyen de toutes les personnes portant ce prénom.
+# Supposons que vous fournissiez comme argument le nom d'un fichier comportant
+# ces données :
#
# Bob Jones 32
# Jane Doe 22
@@ -330,24 +352,26 @@ $0 /^fobar/ {
BEGIN {
# Premièrement, on demande à l'utilisateur le prénom voulu
- print "Pour quel prénom vouldriez vous savoir l'age moyen ?";
+ print "Pour quel prénom voudriez vous savoir l'age moyen ?";
- # On récupère la ligne à partir de l'entrée standard, pas de la ligne de commande
+ # On récupère la ligne à partir de l'entrée standard, pas de la ligne
+ # de commande :
getline name < "/dev/stdin";
}
# Maintenant, pour chaque ligne dont le premier champ est le prénom donné
$1 == name {
- # Ici, nous avons accès à un certain nombre de variables utiles déjà préchargées :
+ # Ici, nous avons accès à un certain nombre de variables utiles déjà
+ # préchargées :
# $0 est la ligne entière
# $3 est le troisième champ. Ici il correspond à l'age qui nous intéresse
# NF est le nombre de champs et vaut 3
# NR est le nombre d'enregistrements (lignes) vus jusqu'à présent
# FILENAME est le nom du fichier en cours de traitement
# FS est séparateur de champs, ici c'est " " (un espace)
- # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de man.
- # Pour cela exécutez "man awk" dans votre terminal
+ # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de
+ # man. Pour cela exécutez "man awk" dans votre terminal.
# Garder une trace du total accumulé et du nombre de lignes correspondant.
sum += $3;
@@ -358,9 +382,9 @@ $1 == name {
# les fichiers texte. Contrairement à BEGIN, il ne fonctionne que si vous lui
# donnez une entrée à traiter. Il sera exécuté une fois que tous les fichiers
# auront été lus et traités conformément aux règles et aux actions que vous
-# avez fournies. Le but est généralement de produire un rapport final
-# ou de faire quelque chose avec l'ensemble des données que vous avez
-# accumulées au cours du script.
+# avez fournies. Le but est généralement de produire un rapport final, ou de
+# faire quelque chose avec l'ensemble des données que vous avez accumulées
+# au cours du script.
END {
@@ -369,9 +393,11 @@ END {
}
```
+
Pour plus d'informations :
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
* [Awk man page](https://linux.die.net/man/1/awk)
-* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk est dans la majorité des systèmes Linux.
+* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
+ GNU Awk est dans la majorité des systèmes Linux.
* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html)
diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown
index c8603756..b96d0ad0 100644
--- a/fr-fr/c++-fr.html.markdown
+++ b/fr-fr/c++-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-fr.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown
index 65747c0d..6215e0cf 100644
--- a/fr-fr/clojure-fr.html.markdown
+++ b/fr-fr/clojure-fr.html.markdown
@@ -427,7 +427,7 @@ plupart des fonctions principales :
4Clojure est une super manière d'augmenter vos compétences en Clojure et
en programmation fonctionnelle :
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org a pas mal d'article pour débuter :
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown
index 58b3f386..b3bf9c3b 100644
--- a/fr-fr/csharp-fr.html.markdown
+++ b/fr-fr/csharp-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
diff --git a/fr-fr/elixir-fr.html.markdown b/fr-fr/elixir-fr.html.markdown
index 90cdad7c..f8250e16 100644
--- a/fr-fr/elixir-fr.html.markdown
+++ b/fr-fr/elixir-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown
index 510459fe..00b6b6e1 100644
--- a/fr-fr/git-fr.html.markdown
+++ b/fr-fr/git-fr.html.markdown
@@ -574,8 +574,6 @@ $ git rm /chemin/vers/le/fichier/HelloWorld.c
* [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys (EN)](http://www.gitguys.com/)
-
* [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html)
* [Livre Pro Git](http://www.git-scm.com/book/fr/v1)
diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown
index 9d8bef70..5468096a 100644
--- a/fr-fr/go-fr.html.markdown
+++ b/fr-fr/go-fr.html.markdown
@@ -32,7 +32,7 @@ communauté active.
multiligne */
// Un paquet débute avec une clause "package"
-// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt
+// "main" est un nom spécial déclarant un paquet de type exécutable plutôt
// qu'une bibliothèque
package main
@@ -87,7 +87,7 @@ sauts de ligne.` // Chaîne de caractère.
g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère
// unicode.
- f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit.
+ f := 3.14159 // float64, un nombre flottant IEEE-754 de 64-bit.
c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur.
// Syntaxe "var" avec une valeur d'initialisation.
@@ -422,18 +422,18 @@ func requestServer() {
## En savoir plus
-La référence Go se trouve sur [le site officiel de Go](http://golang.org/).
+La référence Go se trouve sur [le site officiel de Go](https://go.dev/).
Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus.
Une lecture de la documentation du langage est grandement conseillée. C'est
facile à lire et très court (comparé aux autres langages).
-Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go.
+Vous pouvez exécuter et modifier le code sur [Go playground](https://go.dev/play/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://go.dev/play/](https://go.dev/play/) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go.
Sur la liste de lecteur des étudiants de Go se trouve le [code source de la
-librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre
+librairie standard](https://go.dev/src/). Bien documentée, elle démontre
le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous
pouvez cliquer sur le nom d'une fonction dans [la
-documentation](http://golang.org/pkg/) et le code source apparaît!
+documentation](https://go.dev/pkg/) et le code source apparaît!
Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/).
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
index 186859ab..308f1ca8 100644
--- a/fr-fr/javascript-fr.html.markdown
+++ b/fr-fr/javascript-fr.html.markdown
@@ -94,7 +94,7 @@ let banta = "Harry", santa = "Hermione";
// L'égalité est === ou ==
// === compare la valeur exacte 2 === '2' // = false
-// == convertit la valeur pour comparer 2 === '2' // = true
+// == convertit la valeur pour comparer 2 == '2' // = true
// En général, il vaut mieux utiliser === pour ne pas faire d'erreur.
1 === 1; // = true
2 === 1; // = false
diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown
index 1fd22883..91894787 100644
--- a/fr-fr/markdown-fr.html.markdown
+++ b/fr-fr/markdown-fr.html.markdown
@@ -178,7 +178,7 @@ Vous pouvez également utiliser des sous-listes.
1. Item un
2. Item deux
3. Item trois
- * Sub-item
+ * Sub-item
* Sub-item
4. Item quatre
```
@@ -210,7 +210,7 @@ l'intérieur du bloc de code.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -223,13 +223,15 @@ La fonction `run()` ne vous oblige pas à aller courir!
En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques.
- ```ruby
- def foobar
- puts "Hello world!"
- end
- ```
+````md
+```ruby
+def foobar
+ puts "Hello world!"
+end
+```
+````
-Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
+Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub
va utiliser une coloration syntaxique pour le langage indiqué après les <code>```</code>.
## Ligne Horizontale
@@ -267,13 +269,13 @@ Markdown supporte aussi les liens relatifs.
Les liens de références sont eux aussi disponibles en Markdown.
-<div class="highlight"><code><pre>
-[<span class="nv">Cliquez ici</span>][<span class="ss">link1</span>] pour plus d'information!
-[<span class="nv">Regardez aussi par ici</span>][<span class="ss">foobar</span>] si vous voulez.
+```md
+[Cliquez ici][link1] pour plus d'information!
+[Regardez aussi par ici][foobar] si vous voulez.
-[<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
-[<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Génial!"</span>
-</pre></code></div>
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Génial!"
+```
Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou
absent. Les références peuvent être placées où vous voulez dans le document et
@@ -282,11 +284,11 @@ les identifiants peuvent être n'importe quoi tant qu'ils sont uniques.
Il y a également le nommage implicite qui transforme le texte du lien en
identifiant.
-<div class="highlight"><code><pre>
-[<span class="nv">Ceci</span>][] est un lien.
+```md
+[Ceci][] est un lien.
-[<span class="nv">Ceci</span>]:<span class="sx">http://ceciestunlien.com/</span>
-</pre></code></div>
+[Ceci]:http://ceciestunlien.com/
+```
Mais ce n'est pas beaucoup utilisé.
@@ -301,12 +303,11 @@ d'un point d'exclamation!
Là aussi, on peut utiliser le mode "références".
+```md
+![Ceci est l'attribut ALT de l'image][monimage]
-<div class="highlight"><code><pre>
-![<span class="nv">Ceci est l'attribut ALT de l'image</span>][<span class="ss">monimage</span>]
-
-[<span class="nv">monimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"si vous voulez un titre, c'est ici."</span>
-</pre></code></div>
+[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
+```
## Divers
@@ -348,10 +349,10 @@ Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et
ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin :
```md
-| Col1 | Col2 | Col3 |
-| :----------- | :------: | ------------: |
-| Alignement Gauche | Centré | Alignement Droite |
-| bla | bla | bla |
+| Col1 | Col2 | Col3 |
+| :---------------- | :------: | ----------------: |
+| Alignement Gauche | Centré | Alignement Droite |
+| bla | bla | bla |
```
ou bien, pour un résultat équivalent :
diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown
index 6da9a380..7f0f018b 100644
--- a/fr-fr/pyqt-fr.html.markdown
+++ b/fr-fr/pyqt-fr.html.markdown
@@ -14,14 +14,14 @@ lang: fr-fr
Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192
), certains exemples du code doivent avoir la même fonctionnalité,
-cette version ayant juste été faite en utilisant pyqt!
+cette version ayant juste été faite en utilisant pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
- # Création de l'objet application
+ # Création de l'objet application
app = QtGui.QApplication(sys.argv)
# Création d'un widget où notre label sera placé
w = QtGui.QWidget()
@@ -47,7 +47,7 @@ if __name__ == '__main__':
Pour obtenir certaines des fonctionnalités les plus avancées de **pyqt** nous devons commencer par chercher à construire des éléments supplémentaires.
Ici nous voyons comment introduire une boîte de dialogue popup, utile pour demander une confirmation à un utilisateur ou fournir des informations.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -66,7 +66,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Cette fonction devrait créer une fenêtre de dialogue avec un bouton
# qui attend d'être cliqué puis quitte le programme
def showdialog():
diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown
index a61f78be..6fc0d07d 100644
--- a/fr-fr/rust-fr.html.markdown
+++ b/fr-fr/rust-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
@@ -309,7 +309,7 @@ fn main() {
Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre
les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust
-Langue](http://doc.rust-lang.org/book/index.html) et etudier la
+Langue](http://doc.rust-lang.org/book/index.html) et étudier la
[/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur
irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants.
diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown
index 50a4ea30..d1ac2711 100644
--- a/fr-fr/set-theory-fr.html.markdown
+++ b/fr-fr/set-theory-fr.html.markdown
@@ -1,11 +1,11 @@
-```
---
-category: tool
-lang: fr-fr
+category: Algorithms & Data Structures
name: Set theory
+lang: fr-fr
contributors:
- - ["kieutrang", "https://github.com/kieutrang1729"]
+ - ["kieutrang", "https://github.com/kieutrang1729"]
---
+
La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés.
* Un ensemble est une collection d'éléments disjoints.
@@ -32,9 +32,9 @@ La théorie des ensembles est une branche des mathématiques qui étudie les ens
* `â„š`, l'ensemble des nombres rationnels ;
* `â„`, l'ensemble des nombres réels.
-Quelques mise en gardes sur les ensembles definis ci-dessus:
+Quelques mise en gardes sur les ensembles définis ci-dessus:
1. Même si l'ensemble vide ne contient aucun élément, il est lui-même un sous-ensemble de n'importe quel ensemble.
-2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitment si l'auteur considère le zéro comme nombre naturel ou pas.
+2. Il n'y a pas d'accord général sur l'appartenance de zéro dans l'ensemble des nombres naturels, et les livres indiquent explicitement si l'auteur considère le zéro comme nombre naturel ou pas.
### Cardinalité
@@ -43,7 +43,7 @@ La cardinalité, ou taille, d'un ensemble est déterminée par le nombre d'élé
Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
### L'ensemble vide
-* L'ensemble vide peut se définir en comprehension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
+* L'ensemble vide peut se définir en compréhension à l'aide d'une propriété qui n'est satisfaite par nul élément, e.g. `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`.
* il n'y a qu'un seul ensemble vide.
* l'ensemble vide est sous-ensemble de tout ensemble.
* la cardinalité de l'ensemble vide est 0, ou `|∅| = 0`.
@@ -54,9 +54,9 @@ Par exemple, si `S = { 1, 2, 4 }`, alors `|S| = 3`.
Un ensemble peut être defini en extension par une liste de tous les éléments qui sont contenus dans l'ensemble. Par exemple, `S = { a, b, c, d }`.
-Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatres premiers.
+Quand le contexte est clair, on peut raccourcir la liste en utilisant des points de suspension. Par exemple, `E = { 2, 4, 6, 8, ... }` est clairement l'ensemble de tous les nombres pairs, contenant un nombre infini des éléments, même si on a explicitement écrit seulement les quatre premiers.
-### Définition par comprehension
+### Définition par compréhension
C'est une notation plus descriptif qui permet de définir un ensemble à l'aide d'un sujet et d'une propriété, et il est noté `S = { sujet : propriété }`. Par exemple,
@@ -76,18 +76,18 @@ D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
### Appartenance
-* Si l'élement `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
-* Si l'élement `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
+* Si l'élément `a` est dans l'ensemble `A`, on dit que `a` appartient à `A` et on le note `a ∈ A`.
+* Si l'élément `a` n'est pas dans l'ensemble `A`, on dit que `a` n'appartient pas à `A` et on le note `a ∉ A`.
### Égalité
* On dit que deux ensembles `A` et `B` sont égaux s'ils contiennent les mêmes éléments, et on le note `A = B`.
* Les ensembles n'ont pas de notion d'ordre, par exemple `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`.
* Un élément ne peut apparaître qu'au plus une seule fois - il n'y a jamais de répétition, e.g. `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`.
-* Deux ensembles `A` and `B` sont égaux si et seulement si `A ⊆ B` and `B ⊆ A`.
+* Deux ensembles `A` et `B` sont égaux si et seulement si `A ⊆ B` et `B ⊆ A`.
## Ensemble puissance
-* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité d'`A` est `n`, la cardinalité de `P(A)` est `2^n`.
+* L'ensemble puissance d'un ensemble `A` est l'ensemble contenant tous les sous-ensembles de `A`. Il est noté `P(A)`. Si la cardinalité de `A` est `n`, la cardinalité de `P(A)` est `2^n`.
```
P(A) = { x : x ⊆ A }
@@ -125,10 +125,8 @@ A △ B = (A \ B) ∪ (B \ A)
```
### Produit cartésien
-Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont la première élément appartient à `A` et la deuxième à `B`.
+Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous les couples dont le premier élément appartient à `A` et le deuxième à `B`.
```
A × B = { (x, y) | x ∈ A, y ∈ B }
```
-
-```
diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown
index 7b446259..10a37994 100644
--- a/fr-fr/wolfram-fr.html.markdown
+++ b/fr-fr/wolfram-fr.html.markdown
@@ -21,7 +21,7 @@ Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant,
copier-coller directement dans Mathematica peut causer des problèmes de
formatage, car il ne contient aucune information de mise en page.
-```
+```mathematica
(* Ceci est un commentaire *)
(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des
diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
index c7cb9421..36c33bd1 100644
--- a/fr-fr/yaml-fr.html.markdown
+++ b/fr-fr/yaml-fr.html.markdown
@@ -36,6 +36,7 @@ valeur_numérique: 100
notation_scientifique: 1e+12
booléen: true
valeur_null: null
+une_autre_valeur_null: ~
clé avec espaces: valeur
# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères
# entre guillemets, cela reste possible, et parfois utile.
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index c140d6b1..f1f8e95d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -33,6 +33,21 @@ let myInt = 5
let myFloat = 3.14
let myString = "hello" // note that no types needed
+// Mutable variables
+let mutable a=3
+a <- 4 // a is now 4.
+
+// Somewhat mutable variables
+// Reference cells are storage locations that enable you to create mutable values with reference semantics.
+// See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/reference-cells
+let xRef = ref 10
+printfn "%d" xRef.Value // 10
+xRef.Value <- 11
+printfn "%d" xRef.Value // 11
+
+let a=[ref 0; ref 1] // somewhat mutable list
+a[0].Value <- 2
+
// ------ Lists ------
let twoToFive = [2; 3; 4; 5] // Square brackets create a list with
// semicolon delimiters.
diff --git a/func.html.markdown b/func.html.markdown
new file mode 100644
index 00000000..da1b2214
--- /dev/null
+++ b/func.html.markdown
@@ -0,0 +1,338 @@
+---
+language: FunC
+filename: learnFunC.fc
+contributors:
+ - ["Ivan Romanovich", "https://t.me/ton_learn"]
+ - ["Kirill Malev", "https://fslabs.io"]
+---
+
+The FunC language is used to program smart contracts on the [The Open Network](https://ton.org) blockchain. Contract logic is executed in TVM, the stack-based TON Virtual Machine.
+
+FunC is a statically typed, which is similar to C.
+
+# Basic syntax, the first Smart Contract — Data Types, Storage, Functions
+
+```c
+;; Single line comment
+
+ {- This is a multi-line comment
+ {- this is a comment in the comment -}
+ -}
+
+ (int) sum(int a, int b) {
+ ;; This is a function that gets two integer parameters
+ ;; and return integer result
+ return a + b;
+ ;; All integers are signed and are 257 bit long. Overflow throws exception
+ ;; expressions must end with a semicolon
+ }
+
+ () f(int i, cell c, slice s, builder b, cont c, tuple t) {
+ ;; FunC has 7 atomic types:
+ ;; int - 257 bit signed integers,
+ ;; cell - basic for TON opaque data structure,
+ ;; which contains up to 1,023 bits and up to 4 references to other cells,
+ ;; slice and builder - special objects to read from and write to cells,
+ ;; continuation - another flavor of cell that contains
+ ;; ready-to-execute TVM byte-code.
+ ;; tuple is an ordered collection of up to 255 components,
+ ;; having arbitrary value types, possibly distinct.
+ ;; Finally tensor type (A,B, ...) is an ordered collection ready for
+ ;; mass assigning like: (int, int) a = (3, 5);
+ ;; Special case of tensor type is the unit type ().
+ ;; It represents that a function doesn’t return any value,
+ ;; or has no arguments.
+ }
+
+ ;; During execution, the contract has read access to local context:
+ ;; its storage, balance, time, network config, etc.
+ ;; Contract may change its storage and code,
+ ;; and also may send messages to other contracts
+
+ ;; Let’s write a counter smart contract that gets a number
+ ;; from an incoming message,
+ ;; adds to already stored numbers and stores result in “storageâ€
+
+ ;; For handling special events, smart contracts have reserved methods:
+ ;; recv_internal() handles internal messages from other smart contracts
+ ;; recv_external() handles external messages from the outside world —
+ ;; e.g., from a user.
+
+ () recv_internal(slice in_msg_body) {
+ ;; Cells play the role of memory in the stack-based TVM.
+ ;; A cell can be transformed into a slice,
+ ;; and then the data bits and references to
+ ;; other cells from the cell can be obtained
+ ;; by loading them from the slice.
+ ;; Data bits and references to other cells can be stored
+ ;; into a builder, and then the builder can be finalized into a new cell.
+ ;; recv_internal gets the slice
+ ;; with incoming message data as an argument.
+
+ ;; As everything else on TON, permanent storage data is stored as a cell.
+ ;; It can be retrieved via the get_data() method
+ ;; begin_parse - converts a cell with data into a readable slice
+
+ slice ds = get_data().begin_parse();
+ ;; `.` is a syntax sugar: a.b() is equivalent to b(a)
+
+ ;; load_uint is a function from the FunC standard library;
+ ;; it loads an unsigned n-bit integer from a slice
+ int total = ds~load_uint(64); ;; `~` is a "modifying" method:
+ ;; essentially, it is a syntax sugar: `r = a~b(x)`
+ ;; is equivalent to (a,r) = b(a,x)
+
+ ;; Now let’s read the incoming value from the message body slice
+ int n = in_msg_body~load_uint(32);
+
+ total += n;
+ ;; integers support usual +-*/ operations as well as (+-*/)= syntax sugar
+
+ ;; In order to keep a store integer value, we need to do four things:
+ ;; create a Builder for the future cell - begin_cell()
+ ;; write a value to total - store_uint(value, bit_size)
+ ;; create a Cell from the Builder - end_cell()
+ ;; write the resulting cell into permanent storage - set_data()
+
+ set_data(begin_cell().store_uint(total, 64).end_cell());
+ }
+
+
+
+ ;; The FunC program is essentially a list of
+ function declarations/definitions and global variable declarations.
+
+ ;; Any function in FunC matches the following pattern:
+ ;; [<forall declarator>] <return_type> <function_name>(<comma_separated_function_args>) <specifiers>
+
+
+ ;; Specifiers:
+ ;; The impure specifier indicates that
+ ;; function calls should not be optimized
+ ;; (whether its result is used or not)
+ ;; it is important for methods that change the smart contract data
+ ;; or send messages
+
+ ;; The method_id specifier allows you to call a GET function by name
+
+ ;; For instance, we can create a get method for the contract above
+ ;; to allow outside viewers to read counter
+
+ int get_total() method_id {
+ slice ds = get_data().begin_parse();
+ int total = ds~load_uint(64);
+
+ ;; Note that (int) and int is the same,
+ ;; thus brackets in the function declaration
+ ;; and in the return statement are omitted.
+ return total;
+ }
+ ;; Now any observer can read get_total value via lite-client or explorer
+```
+
+# Messages
+
+The actor model is a model of concurrent computation and is at the heart of TON smart contracts. Each smart contract can process one message at a time, change its own state, or send one or several messages. Processing of the message occurs in one transaction, that is, it cannot be interrupted. Messages to one contract are processed consequently one by one. As a result, the execution of each transaction is local and can be parallelized at the blockchain level, which allows for on-demand throughput horizontal scaling and hosting an unlimited number of users and transactions.
+
+```c
+;; For normal internal message-triggered transactions,
+;; before passing control to recv_internal TVM puts the following
+;; elements on stack.
+;;;; Smart contract balance (in nanoTons)
+;;;; Incoming message balance (in nanoTons)
+;;;; Cell with an incoming message
+;;;; Incoming message body, slice type
+;; In turn, recv_internal may use only
+;; the required number of fields (like 1 in the example above or 4 below)
+
+;; Let’s dive into message sending
+
+() recv_internal (
+ int balance, int msg_value, cell in_msg_full, slice in_msg_body) {
+ ;;
+ ;; Every message has a strict layout, thus by parsing it,
+ ;; we can get the sender’s address
+ ;; first, we need to read some tech flags and
+ ;; then take the address using load_msg_addr
+ ;; function from FunC standard library - ()
+ var cs = in_msg_full.begin_parse();
+ var flags = cs~load_uint(4);
+ slice sender_address = cs~load_msg_addr();
+
+ ;; if we want to send a message, we first need to construct it
+ ;; message serialization in most cases may be reduced to
+ var msg = begin_cell()
+ .store_uint(0x18, 6) ;; tech flags
+ .store_slice(addr) ;; destination address
+ .store_coins(amount) ;; attached value
+ .store_uint(0, 107) ;; more tech flags :)
+ .store_slice(in_msg_body) ;; just put some payload here
+ .end_cell();
+
+ ;; to send messages, use send_raw_message from the standard library.
+ ;; it accepts two arguments message and mode
+ send_raw_message(msg, 64);
+
+ ;; mode parameter specifies how to process the funds passed into
+ ;; the smart contract with the message and the smart contract funds
+ ;; 64 means send everything from the incoming message —
+ ;; what’s left after the commission is deducted
+
+ ;; Exceptions can be thrown by conditional primitives throw_if and
+ ;; throw_unless and by unconditional throw
+ ;; by default, it will automatically cause a bounce message with 64 mode
+
+ var some = 7;
+ throw_if(102, some == 10);
+ ;; Throw exception with code 102 conditionally
+ throw_unless(103, some != 10);
+ ;; Throw exception with code 103 conditionally
+ throw(101); ;; Throw exception with code 101 unconditionally
+}
+```
+
+# Flow control: Conditional Statements and Loops; Dictionaries
+
+```c
+;; FunC, of course, supports if statements
+
+;;;; usual if-else
+if (flag) {
+ ;;do_something();
+}
+else {
+ ;;do_alternative();
+}
+
+;; If statements are often used as an operation identifier
+;; for a smart contract, for example:
+
+() recv_internal (
+ int balance, int msg_value, cell in_msg_full, slice in_msg_body) {
+ int op = in_msg_body~load_int(32);
+ if (op == 1) {
+ ;; smth here
+ } else {
+ if (op == 2) {
+ ;; smth here
+ } else {
+ ;; smth here
+ }
+ }
+}
+
+;; Loops
+;; FunC supports repeat, while and do { ... } until loops.
+;; for loop is not supported.
+
+;; repeat
+int x = 1;
+repeat(10) {
+ x *= 2;
+}
+;; x = 1024
+
+;; while
+int x = 2;
+while (x < 100) {
+ x = x * x;
+}
+;; x = 256
+
+;; until loops
+int x = 0;
+do {
+ x += 3;
+} until (x % 17 == 0);
+;; x = 51
+
+;; In practice, loops in TON smart contracts are often used to work with
+;; dictionaries, or as they are also called in TON hashmaps
+
+;; A hashmap is a data structure represented by a tree.
+;; Hashmap maps keys to values ​​of arbitrary type so that
+;; quick lookup and modification are possible.
+
+;; udict_get_next? from FunC standard library in combination with
+;; the loop will help, go through the dictionary
+
+int key = -1;
+do {
+ (key, slice cs, int f) = dic.udict_get_next?(256, key);
+
+} until (~ f);
+
+;; udict_get_next? - Calculates the minimum key k in the dictionary dict
+;; that is greater than some given value and returns k,
+;; the associated value, and a flag indicating success.
+;; If the dictionary is empty, returns (null, null, 0).
+```
+
+# Functions
+
+```c
+;; Most useful functions are slice reader and builder writer primitives,
+;; storage handlers and sending messages
+
+;; slice begin_parse(cell c) - Converts a cell into a slice
+;; (slice, int) load_int(slice s, int len) -
+;; Loads a signed len-bit integer from a slice.
+;; (slice, int) load_uint(slice s, int len) -
+;; Loads a unsigned len-bit integer from a slice.
+;; (slice, slice) load_bits(slice s, int len) -
+;; Loads the first 0 ≤ len ≤ 1023 bits from slice into a separate slice.
+;; (slice, cell) load_ref(slice s) - Loads the reference cell from the slice.
+
+;; builder begin_cell() - Creates a new empty builder.
+;; cell end_cell(builder b) - Converts a builder into an ordinary cell.
+;; builder store_int(builder b, int x, int len) -
+;; Stores a signed len-bit integer x into b for 0 ≤ len ≤ 257.
+;; builder store_uint(builder b, int x, int len) -
+;; Stores an unsigned len-bit integer x into b for 0 ≤ len ≤ 256.
+;; builder store_slice(builder b, slice s) - Stores slice s into builder b.
+;; builder store_ref(builder b, cell c) -
+;; Stores a reference to cell c into builder b.
+
+;; cell get_data() - Returns the persistent contract storage cell.
+;; () set_data(cell c) - Sets cell c as persistent contract data.
+
+;; () send_raw_message(cell msg, int mode) -
+;; put message msg into sending queue with mode.
+;; Note, that message will be sent after a successful execution
+;; of the whole transaction
+
+;; Detailed descriptions of all standard functions can be found
+;; in docs https://ton.org/docs/#/func/stdlib
+;;
+```
+
+## Additional resources
+- [FunC Lessons](https://github.com/romanovichim/TonFunClessons_Eng)
+- [TON Development Onboarding](https://www.tonspace.co)
+- [TON Documentation](https://ton.org/docs/#/)
+- [FunC Documentation](https://ton.org/docs/#/func/overview)
+- [TON Smart Contracts examples](https://github.com/ton-blockchain/ton/tree/master/crypto/smartcont)
+- [Community portal](https://society.ton.org)
+- [Blockchain portal](https://ton.org)
+- [Stackoverflow](https://stackoverflow.com/questions/tagged/ton)
+
+## Social
+- [Developer community](https://t.me/tondev_eng)
+- [TON Learn](https://t.me/ton_learn)
+- [FunC Lessons Channel](https://github.com/romanovichim/TonFunClessons_Eng)
+- [FunC onboarding](https://t.me/func_guide)
+- [Tondev News](https://t.me/tondevnews)
+
+## Useful blogposts
+- [Setting up a TON Development Environment](https://society.ton.org/setting-up-a-ton-development-environment)
+- [Hello World on TON](https://society.ton.org/ton-hello-world-step-by-step-guide-for-writing-your-first-smart-contract-in-func)
+
+
+## Future To Dos
+- Add smart contracts examples
+- Add more posts
+
+
+This file is mostly copied from [TonFunClessons 15 minutes intro](https://github.com/romanovichim/TonFunClessons_Eng/blob/main/13lesson/15min.md).
+
+P.S. If by any chance you're familiar with [Forth](https://learnxinyminutes.com/docs/forth/), you can also take a look at [Fift](https://ton-blockchain.github.io/docs/fiftbase.pdf). \ No newline at end of file
diff --git a/gdscript.html.markdown b/gdscript.html.markdown
index 25af0974..0bfac26a 100644
--- a/gdscript.html.markdown
+++ b/gdscript.html.markdown
@@ -95,7 +95,7 @@ func doing_math():
func control_flow():
x = 8
y = 2 # y was originally a float,
- # but we can change it's type to int
+ # but we can change its type to int
# using the power of dynamic typing!
if x < y:
@@ -114,6 +114,9 @@ func control_flow():
for i in range(20): # GDScript's range is similar to Python's
print(i) # so this will print numbers from 0 to 19
+ for i in 20: # unlike Python, you can loop over an int directly
+ print(i) # so this will also print numbers from 0 to 19
+
for i in ["two", 3, 1.0]: # iterating over an array
print(i)
@@ -319,4 +322,4 @@ signal example(arg: int) # ERROR! Signals can't take typed arguments!
* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html)
* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html)
* [GDQuest](https://www.gdquest.com/)
-* [GDScript.com](https://gdscript.com/) \ No newline at end of file
+* [GDScript.com](https://gdscript.com/)
diff --git a/git.html.markdown b/git.html.markdown
index a40ef01b..9d33225f 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -124,9 +124,12 @@ To configure settings. Whether it be for the repository, the system itself,
or global configurations ( global config file is `~/.gitconfig` ).
```bash
-# Print & Set Some Basic Config Variables (Global)
+# Set & Print Some Basic Config Variables (Global)
$ git config --global user.email "MyEmail@Zoho.com"
$ git config --global user.name "My Name"
+
+$ git config --global user.email
+$ git config --global user.name
```
[Learn More About git config.](http://git-scm.com/docs/git-config)
@@ -579,6 +582,19 @@ $ git rm HelloWorld.c
$ git rm /pather/to/the/file/HelloWorld.c
```
+### blame
+Examine specific parts of the code's history and find out who was the last author to modify that line.
+
+```bash
+# find the authors on the latest modified lines
+$ git blame google_python_style.vim
+b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 12) " See the License for the specific language governing permissions and
+b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 13) " limitations under the License.
+b88c6a1b (Google Python team 2019-12-30 13:45:23 -0800 14)
+222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 15) " Indent Python in the Google way.
+222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 16)
+222e6da8 (mshields@google.com 2010-11-29 20:32:06 +0000 17) setlocal indentexpr=GetGooglePythonIndent(v:lnum)
+```
## Further Information
* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
@@ -597,8 +613,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/go.html.markdown b/go.html.markdown
index 39c8ac74..59ba2e4f 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -39,7 +39,7 @@ Go comes with a good standard library and a sizeable community.
// +build prod, dev, test
// A package clause starts every source file.
-// Main is a special name declaring an executable rather than a library.
+// main is a special name declaring an executable rather than a library.
package main
// Import declaration declares library packages referenced in this file.
@@ -95,7 +95,7 @@ can include line breaks.` // Same string type.
// Non-ASCII literal. Go source is UTF-8.
g := 'Σ' // rune type, an alias for int32, holds a unicode code point.
- f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
+ f := 3.14159 // float64, an IEEE-754 64-bit floating point number.
c := 3 + 4i // complex128, represented internally with two float64's.
// var syntax with initializers.
@@ -130,7 +130,7 @@ can include line breaks.` // Same string type.
// Because they are dynamic, slices can be appended to on-demand.
// To append elements to a slice, the built-in append() function is used.
// First argument is a slice to which we are appending. Commonly,
- // the array variable is updated in place, as in example below.
+ // the slice variable is updated in place, as in example below.
s := []int{1, 2, 3} // Result is a slice of length 3.
s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
@@ -357,7 +357,7 @@ func learnInterfaces() {
// Functions can have variadic parameters.
func learnVariadicParams(myStrings ...interface{}) {
// Iterate each value of the variadic.
- // The underbar here is ignoring the index argument of the array.
+ // The underscore here is ignoring the index argument of the array.
for _, param := range myStrings {
fmt.Println("param:", param)
}
@@ -456,21 +456,21 @@ func requestServer() {
## Further Reading
-The root of all things Go is the [official Go web site](http://golang.org/).
+The root of all things Go is the [official Go web site](https://go.dev/).
There you can follow the tutorial, play interactively, and read lots.
-Aside from a tour, [the docs](https://golang.org/doc/) contain information on
+Aside from a tour, [the docs](https://go.dev/doc/) contain information on
how to write clean and effective Go code, package and command docs, and release history.
-The [Go language specification](https://golang.org/ref/spec) itself is highly recommended. It's easy to read
+The [Go language specification](https://go.dev/ref/spec) itself is highly recommended. It's easy to read
and amazingly short (as language definitions go these days.)
-You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go.
+You can play around with the code on [Go playground](https://go.dev/play/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://go.dev/play/](https://go.dev/play/) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go.
On the reading list for students of Go is the [source code to the standard
-library](http://golang.org/src/pkg/). Comprehensively documented, it
+library](https://go.dev/src/). Comprehensively documented, it
demonstrates the best of readable and understandable Go, Go style, and Go
idioms. Or you can click on a function name in [the
-documentation](http://golang.org/pkg/) and the source code comes up!
+documentation](https://go.dev/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 0d589c10..89eee3dd 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -55,6 +55,9 @@ println x
//Creating an empty list
def technologies = []
+// or create a list with data
+technologies = ["Kotlin", "Swift"]
+
/*** Adding a elements to the list ***/
// As with Java
@@ -193,7 +196,7 @@ def say(msg = 'Hello', name = 'world') {
assert 'Hello world!' == say()
// Right most parameter with default value is eliminated first.
assert 'Hi world!' == say('Hi')
-assert 'learn groovy' == say('learn', 'groovy')
+assert 'learn groovy!' == say('learn', 'groovy')
/*
Logical Branching and Looping
diff --git a/hack.html.markdown b/hack.html.markdown
index fb6af8e1..24055503 100644
--- a/hack.html.markdown
+++ b/hack.html.markdown
@@ -1,308 +1,420 @@
---
language: Hack
contributors:
+ - ["Andrew DiMola", "https://github.com/AndrewDiMola"]
- ["Stephen Holdaway", "https://github.com/stecman"]
- ["David Lima", "https://github.com/davelima"]
filename: learnhack.hh
---
-Hack is a superset of PHP that runs under a virtual machine called HHVM. Hack
-is almost completely interoperable with existing PHP code and adds a bunch of
-useful features from statically typed languages.
+[Hack](https://hacklang.org/) lets you write code quickly, while also having safety features built in, like static typechecking.
-
-Only Hack-specific features are covered here. Details about PHP's syntax are
-available in the [PHP article](http://learnxinyminutes.com/docs/php/) on this site.
+To run Hack code, [install HHVM](https://docs.hhvm.com/hhvm/installation/introduction), the open-source virtual machine.
```php
-<?hh
-
-// Hack syntax is only enabled for files starting with an <?hh marker
-// <?hh markers cannot be interspersed with HTML the way <?php can be.
-// Using the marker "<?hh //strict" puts the type checker in strict mode.
-
-
-// Scalar parameter type hints
-function repeat(string $word, int $count)
-{
- $word = trim($word);
- return str_repeat($word . ' ', $count);
-}
-
-// Type hints for return values
-function add(...$numbers) : int
-{
- return array_sum($numbers);
-}
-
-// Functions that return nothing are hinted as "void"
-function truncate(resource $handle) : void
-{
- // ...
-}
-
-// Type hints must explicitly allow being nullable
-function identity(?string $stringOrNull) : ?string
-{
- return $stringOrNull;
-}
-
-// Type hints can be specified on class properties
-class TypeHintedProperties
-{
- public ?string $name;
-
- protected int $id;
-
- private float $score = 100.0;
-
- // Hack's type checker enforces that typed properties either have a
- // default value or are set in the constructor.
- public function __construct(int $id)
- {
- $this->id = $id;
- }
-}
-
-
-// Concise anonymous functions (lambdas)
-$multiplier = 5;
-array_map($y ==> $y * $multiplier, [1, 2, 3]);
-
-
-// Generics
-class Box<T>
-{
- protected T $data;
-
- public function __construct(T $data) {
- $this->data = $data;
- }
-
- public function getData(): T {
- return $this->data;
- }
-}
-
-function openBox(Box<int> $box) : int
-{
- return $box->getData();
-}
-
-
-// Shapes
-//
-// Hack adds the concept of shapes for defining struct-like arrays with a
-// guaranteed, type-checked set of keys
-type Point2D = shape('x' => int, 'y' => int);
+/* ==================================
+ * READ THE DOCS!
+ * ==================================
+ */
+
+/* For more information on the Hack language:
+ * - About Hack: https://hacklang.org/
+ * - Documentation: https://docs.hhvm.com/hack/
+ */
+
+/* ==================================
+ * A NOTE ON PHP
+ * ==================================
+ */
+
+// The Hack language began as a superset of PHP.
+// Since then, the languages have (largely) diverged.
+// You may encounter the .php extension, which is no longer recommended.
+
+/* ==================================
+ * COMMENTS
+ * ==================================
+ */
+
+// Hack has single-line comments...
+
+/* Multi-line comments...
+ *
+ */
+
+/**
+ * ... and a special syntax for doc comments.
+ *
+ * Use doc comments to summarize the purpose of a definition, function, class or method.
+ */
+
+/* ==================================
+ * NAMESPACES
+ * ==================================
+ */
+
+// Namespaces contain definitions of classes, interfaces, traits, functions, and constants.
+
+namespace LearnHackinYMinutes {
+
+ /* ==================================
+ * TYPES
+ * ==================================
+ */
+
+ function demo_hack_types(): void {
+
+ // Hack has five primitive types: bool, int, float, string, and null.
+ $is_helpful = true; // bool
+ $int_value = 10; // int
+ $precise_value = 2.0; // float
+ $hello_world = "Hello World!"; // string
+ $null_string = null; // null
-function distance(Point2D $a, Point2D $b) : float
-{
- return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
-}
+ // Create a `shape` with the shape keyword, with a series of field names and values.
+ $my_point = shape('x' => -3, 'y' => 6, 'visible' => true);
-distance(
- shape('x' => -1, 'y' => 5),
- shape('x' => 2, 'y' => 50)
-);
+ // Create a `tuple` with the tuple keyword, with a series of two or more types as values.
+ $apple_basket = tuple("apples", 25); // different types are OK
+
+ // Use `arraykey` to represent either an integer or string.
+ $the_answer = 42;
+ $is_answer = process_key($the_answer);
+
+ // Similarly, `num` represents either an int or float.
+ $lucky_number = 7;
+ $lucky_square = calculate_square($lucky_number);
+ }
+ function process_key(arraykey $the_answer): bool {
+ if ($the_answer is int) {
+ return true;
+ } else {
+ return false;
+ } // true
+ }
+
+ function calculate_square(num $arg)[]: float {
+ return ((float)$arg * $arg);
+ }
+
+ // Enums are limited to int or string (as an Arraykey), or other enum values.
+ enum Permission: string {
+ Read = 'R';
+ Write = 'W';
+ Execute = 'E';
+ Delete = 'D';
+ }
+
+ // In contrast, an enum class can be of any value type!
+ enum class Random: mixed {
+ int X = 42;
+ string S = 'foo';
+ }
+
+ /* ==================================
+ * HACK ARRAYS
+ * ==================================
+ */
+
+ // The following line lets us use functions in the `C\` namespace.
+ use namespace HH\Lib\C; // the `C` library operates on containers
+
+ function demo_hack_arrays(): void {
-// Type aliasing
-//
-// Hack adds a bunch of type aliasing features for making complex types readable
-newtype VectorArray = array<int, Vector<int>>;
+ // vec: ordered
+ $v = vec[1, 2, 3];
+ $letters = vec['a', 'b', 'c'];
-// A tuple containing two integers
-newtype Point = (int, int);
+ $letters[0]; // returns 'a'
+ $letters[] = 'd'; // appends 'd'
+
+ // `inout` provides pass-by-reference behavior
+ C\pop_back(inout $letters); // removes 'd'
+ C\pop_front(inout $letters); // removes 'a'
+
+ // keyset: ordered, without duplicates
+ $k = keyset[1, 2, 3]; // values must be int or string
+ $colors = keyset['red', 'blue', 'green'];
+
+ // keyset keys are identical to their values
+ $colors['blue']; // returns 'blue'.
+
+ $colors[] = 'yellow'; // appends 'yellow'
+ unset($colors['red']); // removes 'red'
+
+ // dict: ordered, by key-value
+ $d = dict['a' => 1, 'b' => 3]; // keys must be int or string
+ $alphabet = dict['a' => 1, 'b' => 2];
-function addPoints(Point $p1, Point $p2) : Point
-{
- return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
-}
+ $alphabet['a']; // indexing at 'a' returns `1`
+ $alphabet['c'] = 3; // adds a new key-value pair of `c => 3`
-addPoints(
- tuple(1, 2),
- tuple(5, 6)
-);
+ unset($alphabet['b']); // removes 'b'
+ }
+ /* ==================================
+ * THE HACK STANDARD LIBRARY (HSL)
+ * ==================================
+ */
+
+ // The Hack Standard Library is a set of functions and classes for the Hack language.
+ // Namespace use declarations are ideally at the top of your file but are placed here for instruction purposes.
+
+ use namespace HH\Lib\Str; // The `Str` library operates on strings
+
+ function demo_hack_standard_library(): void {
+
+ $letters = vec['a', 'b', 'c'];
+ $colors = keyset['red', 'blue', 'green'];
+ $alphabet = dict['a' => 1, 'b' => 2];
+
+ C\contains($letters, 'c'); // checks for a value; returns 'true'
+ C\contains($colors, 'purple'); // checks for a value; returns 'false'
+ C\contains_key($alphabet, 'a'); // checks for a key; returns 'true'
+ C\contains($alphabet, 'd'); // checks for a value; returns 'false'
-// First-class enums
-enum RoadType : int
-{
- Road = 0;
- Street = 1;
- Avenue = 2;
- Boulevard = 3;
-}
+ Str\length("foo"); // returns `3`
+ Str\join(vec['foo', 'bar', 'baz'], '!'); // returns `foo!bar!baz`
+ }
+
+ /* ==================================
+ * HELLO WORLD!
+ * ==================================
+ */
+
+ use namespace HH\Lib\IO; // the `IO` library is a standard API for input / output
+
+ <<__EntryPoint>> // required attribute for the typical entry/main function
+ async function main(): Awaitable<
+ void,
+ > { // does not need to be named 'main' / is an asynchronous function
+ await IO\request_output()->writeAllAsync(
+ "Hello World!\n",
+ ); // prints 'Hello World'!
+ }
-function getRoadType() : RoadType
-{
- return RoadType::Avenue;
-}
+ /* ==================================
+ * FUNCTIONS
+ * ==================================
+ */
+ // Functions are defined globally.
+ // When a function is defined in a class, we refer to the function as a method.
-// Constructor argument promotion
-//
-// To avoid boilerplate property and constructor definitions that only set
-// properties, Hack adds a concise syntax for defining properties and a
-// constructor at the same time.
-class ArgumentPromotion
-{
- public function __construct(public string $name,
- protected int $age,
- private bool $isAwesome) {}
-}
+ // Functions have return types (here: `int`) and must return a value of
+ // that type or return no value when a void return type annotation was used.
-class WithoutArgumentPromotion
-{
- public string $name;
+ function add_one(int $x): int {
+ return $x + 1;
+ }
- protected int $age;
+ // Functions can also have defined, default values.
+ function add_value(int $x, int $y = 1): int {
+ return $x + $y;
+ }
- private bool $isAwesome;
+ // Functions can be variadic (unspecified length of arguments).
+ function sum_ints(int $val, int ...$vals): int {
+ $result = $val;
- public function __construct(string $name, int $age, bool $isAwesome)
- {
- $this->name = $name;
- $this->age = $age;
- $this->isAwesome = $isAwesome;
+ foreach ($vals as $v) {
+ $result += $v;
}
-}
-
-
-// Co-operative multi-tasking
-//
-// Two new keywords "async" and "await" can be used to perform multi-tasking
-// Note that this does not involve threads - it just allows transfer of control
-async function cooperativePrint(int $start, int $end) : Awaitable<void>
-{
- for ($i = $start; $i <= $end; $i++) {
- echo "$i ";
-
- // Give other tasks a chance to do something
- await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
+ return $result;
+ }
+
+ // Functions can also be anonymous (defined with the `==>` arrow).
+ // $f = (int $x): int ==> $x + 1;
+
+ /* ==================================
+ * PIPE OPERATOR
+ * ==================================
+ */
+
+ // The pipe operator, `|>`, evaluates the result of a left-hand expression
+ // and stores the result in `$$`, the predefined pipe variable.
+
+ use namespace HH\Lib\Vec;
+
+ function demo_pipe_operator(): void {
+
+ Vec\sort(Vec\map(vec[2, 1, 3], $a ==> $a * $a)); // vec[1,4,9]
+
+ // the same result, but using the pipe operator and pipe variable:
+ $x = vec[2, 1, 3]
+ |> Vec\map($$, $a ==> $a * $a) // $$ with value vec[2,1,3]
+ |> Vec\sort($$); // $$ with value vec[4,1,9]
+ }
+
+ /* ==================================
+ * ATTRIBUTES
+ * ==================================
+ */
+
+ // Hack provides built-in attributes that can change runtime or static type checking behavior.
+ // For example, we used the `__EntryPoint` attribute earlier in the "Hello World!" example.
+
+ // As another example, `__Memoize` caches the result of a function.
+ <<__Memoize>>
+ async function do_expensive_task(): Awaitable<string> {
+ $site_contents = await \HH\Asio\curl_exec("http://hacklang.org");
+ return $site_contents;
+ }
+
+ /* ==================================
+ * CONTEXTS
+ * ==================================
+ */
+
+ // Hack functions are attached to different contexts and capabilities.
+ // A context is a grouping of capabilities; that is, a grouping of permissions.
+
+ // To declare allowed contexts (and capabilities), use the Context List `[]`.
+ // If contexts are not defined, your function includes permissions defined in Hack's `defaults` context.
+
+ // Because the context list is NOT defined, the `defaults` context is implicitly declared.
+ async function implicit_defaults_context(): Awaitable<void> {
+ await IO\request_output()->writeAllAsync(
+ "Hello World!\n",
+ ); // prints 'Hello World'!
+ }
+
+ // In the function below, the context list is defined to have the `defaults` context.
+ // A function can have multiple contexts [context1, context2, ...].
+ // `defaults` includes most of the capabilities defined by the Hack language.
+ async function explicit_defaults_context()[defaults]: Awaitable<void> {
+ await IO\request_output()->writeAllAsync("Hello World!\n");
+ }
+
+ // You can also specify zero contexts to create a pure function (no capabilities).
+ async function empty_context()[]: Awaitable<void> {
+ // The following line is an error, as the function does not have IO capabilities.
+ // await IO\request_output()->writeAllAsync("Hello World!\n");
+ }
+
+ /* ==================================
+ * GENERICS
+ * ==================================
+ */
+
+ // Generics allow classes or methods to be parameterized to any set of types.
+ // That's pretty cool!
+
+ // Hack typically passes by value: use `inout` to pass by reference.
+ function swap<T>(inout T $input1, inout T $input2): void {
+ $temp = $input1;
+ $input1 = $input2;
+ $input2 = $temp;
+ }
+
+ /* ==================================
+ * CLASSES
+ * ==================================
+ */
+
+ // Classes provide a way to group functionality and state together.
+ // To define a class, use the `class` keyword. To instantiate, use `new`.
+ // Like other languages, you can use `$this` to refer to the current instance.
+
+ class Counter {
+ private int $i = 0;
+
+ public function increment(): void {
+ $this->i += 1;
}
-}
-
-// This prints "1 4 7 2 5 8 3 6 9"
-AwaitAllWaitHandle::fromArray([
- cooperativePrint(1, 3),
- cooperativePrint(4, 6),
- cooperativePrint(7, 9)
-])->getWaitHandle()->join();
-
-
-// Attributes
-//
-// Attributes are a form of metadata for functions. Hack provides some
-// special built-in attributes that introduce useful behaviour.
-
-// The __Memoize special attribute causes the result of a function to be cached
-<<__Memoize>>
-function doExpensiveTask() : ?string
-{
- return file_get_contents('http://example.com');
-}
-// The function's body is only executed once here:
-doExpensiveTask();
-doExpensiveTask();
-
-
-// The __ConsistentConstruct special attribute signals the Hack type checker to
-// ensure that the signature of __construct is the same for all subclasses.
-<<__ConsistentConstruct>>
-class ConsistentFoo
-{
- public function __construct(int $x, float $y)
- {
- // ...
+ public function get(): int {
+ return $this->i;
}
+ }
- public function someMethod()
- {
- // ...
+ // Properties and Methods can be static (not requiring instantiation).
+ class Person {
+ public static function favoriteProgrammingLanguage(): string {
+ return "Hack";
}
-}
+ }
-class ConsistentBar extends ConsistentFoo
-{
- public function __construct(int $x, float $y)
- {
- // Hack's type checker enforces that parent constructors are called
- parent::__construct($x, $y);
+ function demo_hack_classes(): void {
+ // Use `new` to instantiate a class.
+ $c1 = new Counter();
- // ...
- }
+ // To call a static property or method, use `::`
+ $typical_person = tuple("Andrew", Person::favoriteProgrammingLanguage());
+ }
- // The __Override annotation is an optional signal for the Hack type
- // checker to enforce that this method is overriding a method in a parent
- // or trait. If not, this will error.
- <<__Override>>
- public function someMethod()
- {
- // ...
+ // Abstract class can be defined, but not instantiated directly.
+ abstract class Machine {
+ public function openDoors(): void {
+ return;
}
-}
-
-class InvalidFooSubclass extends ConsistentFoo
-{
- // Not matching the parent constructor will cause a type checker error:
- //
- // "This object is of type ConsistentBaz. It is incompatible with this object
- // of type ConsistentFoo because some of their methods are incompatible"
- //
- public function __construct(float $x)
- {
- // ...
+ public function closeDoors(): void {
+ return;
}
-
- // Using the __Override annotation on a non-overridden method will cause a
- // type checker error:
- //
- // "InvalidFooSubclass::otherMethod() is marked as override; no non-private
- // parent definition found or overridden parent is defined in non-<?hh code"
- //
- <<__Override>>
- public function otherMethod()
- {
- // ...
+ }
+
+ /* ==================================
+ * INTERFACES
+ * ==================================
+ */
+
+ // A class can implement a set of requirements via an interface.
+ // An interface is a set of method declarations and constants.
+
+ interface Plane {
+ // A constant is a named value. Once defined, the value cannot be changed.
+ const MAX_SPEED = 300;
+ public function fly(): void;
+ }
+
+ /* ==================================
+ * TRAITS
+ * ==================================
+ */
+
+ // A trait defines properties and method declarations.
+ // Traits are recommended when abstracting code for reuse.
+ // Traits are included in code via the `use` keyword.
+
+ trait Airplane {
+ // Introduce a class or interface requirement with the following syntax:
+ require extends Machine; // abstract class
+ require implements Plane; // interface
+
+ public function takeOff(): void {
+ $this->openDoors();
+ $this->closeDoors();
+ $this->fly();
}
-}
+ }
+ class Spaceship extends Machine implements Plane {
+ use Airplane;
-// Traits can implement interfaces (standard PHP does not support this)
-interface KittenInterface
-{
- public function play() : void;
-}
-
-trait CatTrait implements KittenInterface
-{
- public function play() : void
- {
- // ...
+ public function fly(): void {
+ // fly like the wind
}
+ }
+
+ /* ==================================
+ * KEEP READING!
+ * ==================================
+ */
+
+ /* This is a simplified guide!
+ * There's much more to learn, including:
+ * - Asynchronous Operations: https://docs.hhvm.com/hack/asynchronous-operations/introduction
+ * - Reified Generics: https://docs.hhvm.com/hack/reified-generics/reified-generics
+ * - XHP: https://docs.hhvm.com/hack/XHP/setup
+ * - ... and more!
+ */
}
-class Samuel
-{
- use CatTrait;
-}
-
-
-$cat = new Samuel();
-$cat instanceof KittenInterface === true; // True
-
```
## More Information
-Visit the [Hack language reference](http://docs.hhvm.com/manual/en/hacklangref.php)
-for detailed explanations of the features Hack adds to PHP, or the [official Hack website](http://hacklang.org/)
-for more general information.
-
-Visit the [official HHVM website](http://hhvm.com/) for HHVM installation instructions.
+Visit the [Hack language reference](http://docs.hhvm.com/hack/) to learn more about the Hack language.
-Visit [Hack's unsupported PHP features article](http://docs.hhvm.com/manual/en/hack.unsupported.php)
-for details on the backwards incompatibility between Hack and PHP.
+For more information on HHVM, including installation instructions, visit the [official HHVM website](http://hhvm.com/).
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 29712570..edb4121d 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -3,6 +3,7 @@ language: Haskell
filename: learnhaskell.hs
contributors:
- ["Adit Bhargava", "http://adit.io"]
+ - ["Stanislav Modrak", "https://stanislav.gq"]
---
Haskell was designed as a practical, purely functional programming
@@ -602,6 +603,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install).
You can find a much gentler introduction from the excellent
-[Learn you a Haskell](http://learnyouahaskell.com/),
+[Learn you a Haskell](http://learnyouahaskell.com/) (or [up-to-date community version](https://learnyouahaskell.github.io/)),
[Happy Learn Haskell Tutorial](http://www.happylearnhaskelltutorial.com/) or
[Real World Haskell](http://book.realworldhaskell.org/).
diff --git a/hdl.html.markdown b/hdl.html.markdown
index 3c3aff66..6b9a2d80 100644
--- a/hdl.html.markdown
+++ b/hdl.html.markdown
@@ -12,7 +12,7 @@ It is used by circuit designers to simulate circuits and logic prior to wiring a
HDL allows circuit designers to simulate circuits at a high level without being connected to specific components.
## Basic building blocks & introduction to the language---
-This programming language is built by simulating hardware chips and wiring. Normal programming functions are replaced with specialized chips that are added to the current wiring desing. Every base chip must be written as it's own file and imported to be used in the current chip, though they may be reused as often as desired.
+This programming language is built by simulating hardware chips and wiring. Normal programming functions are replaced with specialized chips that are added to the current wiring design. Every base chip must be written as it's own file and imported to be used in the current chip, though they may be reused as often as desired.
```verilog
// Single line comments start with two forward slashes.
@@ -79,7 +79,7 @@ foo(in=a[0..7], out=c); // C is now a 2 bit internal bus
// Note that internally defined busses cannot be subbussed!
-// To access these elements, output or input them seperately:
+// To access these elements, output or input them separately:
foo(in[0]=false, in[1..7]=a[0..6], out[0]=out1, out[1]=out2);
// out1 and out2 can then be passed into other circuits within the design.
diff --git a/hjson.html.markdown b/hjson.html.markdown
new file mode 100644
index 00000000..6b3cc3ed
--- /dev/null
+++ b/hjson.html.markdown
@@ -0,0 +1,94 @@
+---
+language: Hjson
+filename: learnhjson.hjson
+contributors:
+ - ["MrTeferi", "https://github.com/MrTeferi"]
+lang: en
+---
+
+Hjson is an attempt to make [JSON](https://learnxinyminutes.com/docs/json/) more human readable.
+
+Hjson is a syntax extension to JSON.
+It's NOT a proposal to replace JSON or to incorporate it into the JSON spec itself.
+It's intended to be used like a user interface for humans,
+to read and edit before passing the JSON data to the machine.
+
+Let's take a look at examples to see the key syntax differences!
+
+```
+{
+ # Comments are totally supported!
+
+ // With forward slashes too!
+
+ /*
+ Even block style comments, neat!
+ /*
+
+ # Strings do not require quotes!
+ # Just keep it to a single line
+ human: readable
+ quotes: "are fine too"
+
+ # Notice that commas are also not required!
+ # If using commas, strings DO require quotes!
+ object: {
+ name: Hjson
+ properties: [
+ readable
+ exciting
+ fun
+ ]
+ with_commas: [
+ "quoted",
+ "quoty",
+ "quote"
+ ]
+ details: ["this", "is", "fine", "too"]
+ }
+
+ # Multiline quotes with proper whitespace handling are supported!
+ diary:
+ '''
+ I wish JSON was more human readable.
+ If only there was a JSON for my needs!
+ Oh wait.. there is! It's called Hjson.
+ '''
+
+ # Backslashes are interpreted as an escape character ONLY in quoted strings
+ slash: This will not have a new line\n
+ slash-quoted: "This will definitely have a new line\n"
+
+ # Make sure to use quotes when mixing whitespace with important punctuation
+ example1: "If, you're, going, to, comma in a string, use, quotes!"
+ example2: "Also if you want to use {} or [] or any JSON relevant punctuation!"
+ example3: [because, this, is, totally, BROKEN!]
+ example4: this is technically OK though: {}[],:
+
+ # Enjoy working with Hjson!
+ party-time: {
+ Hjson-lovers: [
+ me
+ my mom
+ "my dad"
+ ]
+ Hjson-power-level: 9000
+ supported: {
+ python: yes
+ java: yes
+ javascript: yes
+ c++: yes
+ Go: yes
+ C#: yes
+ Rust: yes
+ }
+ partial-support: ["C", "Kotlin", "Ruby", "Rust"]
+ }
+
+}
+```
+
+## Further Reading
+
+* [Hjson.github.io](https://hjson.github.io/) Main Hjson site including editor support, how-to, etc.
+* [Hjson Packages](https://github.com/hjson/) Various Hjson packages for different applications.
diff --git a/hocon.html.markdown b/hocon.html.markdown
new file mode 100644
index 00000000..67ea30a2
--- /dev/null
+++ b/hocon.html.markdown
@@ -0,0 +1,574 @@
+---
+language: hocon
+filename: learnhocon.conf
+contributors:
+- [TehBrian, 'https://tehbrian.xyz']
+---
+
+Human-Optimized Configuration Object Notation, or HOCON, is a configuration and
+data serialization format designed to be easily editable by humans.
+
+It's a superset of JSON, meaning that any valid JSON is valid HOCON, but it
+differs in being much less pedantic and opinionated. With its flexible yet
+easily determinable syntax, resulting configuration files are often much less
+noisy than some other formats.
+
+Additionally, its support for comments makes it much better suited for
+user-facing configurations than JSON.
+
+```hocon
+// Comments can either look like this,
+# or they can look like this.
+// Anything after // or # is a comment.
+
+##################
+### THE BASICS ###
+##################
+
+# Everything in HOCON is either a key, a value, or a separator.
+# : and = are separators. They separate the key from the value.
+key: value
+another_key = another_value
+
+# You can use either separator with or without whitespace on either side.
+colon1:value
+colon2: value
+colon3 : value
+equals1=value
+equals2= value
+equals3 = value
+# As you'll see, HOCON is very nonrestrictive regarding its syntax style.
+
+# HOCON also isn't opinionated on how keys look.
+THIS_IS_A_VALID_KEY: value
+this-is-also-a-valid-key: value
+keys can have spaces too: value
+or even numbers like 12345: value
+"you can even quote keys if you'd like!": value
+
+# A key, followed by any separator, and then finally a value, is called a field.
+this_entire_line_is: a field
+
+###################
+### VALUE TYPES ###
+###################
+
+# The types that a value can be are string, number, object, array, boolean, and
+# null. Every value type except for array and object are called simple values.
+
+## SIMPLE VALUES ##
+
+quoted_string: "I like quoting my strings."
+unquoted_string: I don't like quoting my strings.
+# Special characters that cannot be used in unquoted strings are:
+# $ " { } [ ] : = , + # ` ^ ? ! @ * &
+# Unquoted strings do not support any kind of escaping. If using one of those
+# special characters is desired, use a quoted string.
+multi-line_string: """
+ This entire thing is a string!
+ One giant, multi-line string.
+ You can put 'single' and "double" quotes without it being invalid.
+"""
+
+number: 123
+negative: -123
+fraction: 3.1415926536
+scientific_notation: 1.2e6 // same as 1.2 * (10^6)
+
+boolean: true # or false
+empty: null
+
+## ARRAYS ##
+
+# Arrays hold lists of values.
+# Values in arrays can be separated with commas..
+array: [ 1, 2, 3, 4, 5 ]
+fibonacci: [1,1,2,3,5,8,13]
+multiples_of_5: [5, 10, 15, 20,] # Notice the trailing comma. That's okay here.
+# or newlines..
+friends: [
+ "Brian"
+ "Sophie"
+ "Maya"
+ "Sabina"
+]
+# or both!
+ingredients: [
+ "Egg",
+ "Sugar",
+ "Oil",
+ "Flour", # Notice the trailing comma. That's okay here too.
+]
+# Once again, HOCON has a very loose syntax. Use whichever style you prefer.
+no newline before or after bracket: ["This"
+ "is"
+ "an"
+ "array!"]
+
+# Just like any other value, arrays can hold other arrays.
+array in array: [ [1, 2, 3], ["a", "b", "c"] ]
+array in array in array: [ [ [1, 2], [8, 9] ], [ ["a", "b" ], ["y", "z"] ] ]
+
+## OBJECTS ##
+
+# Objects hold fields.
+# Just like arrays, fields in objects can be separated with commas..
+object: { key: value, another_key: another_value }
+server_connection: {ip: "127.0.0.1", port: 80}
+first: {letter: a, number: 1,} # Notice the trailing comma.
+# or newlines..
+power_grid: {
+ max_capacity: 15000
+ current_power: 1200
+}
+# or both!
+food_colors: {
+ carrot: orange,
+ pear: green,
+ apple: red,
+ plum: purple,
+ banana: yellow, # Trailing commas are okay here too!
+}
+
+# Arrays can hold objects just like any other value type.
+coworkers: [
+ {
+ name: Jeff
+ age: 27
+ },
+ {
+ name: Henry
+ age: 35
+ },
+ {
+ name: Timmy
+ age: 12
+ }
+]
+
+# The field separator may be omitted if the key is followed by {
+no_separator {
+ key: value
+ speed_of_light: very fast
+ ten: 10
+
+ # Objects can go inside other objects just like any other value.
+ another_object {
+ twenty: 20
+ speed_of_sound: also pretty fast
+ }
+}
+
+# In fact, the entirety of any HOCON document is an actually just an object.
+# That object is called the root object. The only difference between it and any
+# other object is that the curly brackets at the top and bottom of the document
+# may be omitted.
+
+# This means that HOCON documents can be formatted in the same way that
+# regular objects can be formatted, including separating fields with commas
+# rather than with newlines.
+
+# Additionally, while the entirety of a HOCON document can be and is usually an
+# object, it can also be an array. If it is an array, the opening and closing
+# brackets at the top and bottom of the document must be explicitly written.
+
+######################
+### DUPLICATE KEYS ###
+######################
+
+is_happy: false
+# If there is a duplicate key, the new value overrides the previous value.
+is_happy: true
+online_users: [Jacob, Mike]
+# Same with arrays.
+online_users: [Jacob, Mike, Henry]
+
+# For objects, it's a bit different.
+my_car: {
+ color: blue
+ speed: 9001
+ passengers: null
+
+ engine: {
+ running: true
+ temperature: 137
+ }
+}
+# If there is a duplicate key and both values are objects,
+# then the objects are merged.
+my_car: {
+ // These fields are added to the old, previous object.
+ nickname: "My Favorite Car"
+ type: 2-door sedan
+
+ // Since the value of this duplicate key is NOT an object,
+ // it simply overrides the previous value.
+ speed: 60
+ // Same with arrays. They override, not merge.
+ passengers: ["Nate", "Ty"]
+
+ // This object is recursively merged with the other object.
+ engine: {
+ // These two fields are added to the previous object.
+ type: gas
+ oil_level: 10
+ // This field overrides the previous value.
+ temperature: 179
+ }
+}
+
+# Object merging is done two at a time. That is to say, the first two objects
+# merge into one, then that object merges with the next object, and so on.
+
+# Because of this, if you set a field with an object value to a non-object value
+# and then back to an object value, the new object will completely override any
+# previous value.
+
+// Null, a non-object value, completely overrides the object value.
+my_car: null
+
+// Then, this object completely overrides null.
+my_car: {
+ nickname: "My New Car"
+ type: 4-door minivan
+ color: gray
+ speed: 90
+ passengers: ["Ayden", "Liz"]
+}
+
+###########################
+### VALUE CONCATENATION ###
+###########################
+
+## SIMPLE VALUE CONCATENATION ##
+
+# Simple values (all value types except objects and arrays) separated by
+# whitespace are concatenated into a single string. The whitespace between
+# values is preserved.
+number_concatenation: 1 2 3 12.5 -3 2e5 // same as: "1 2 3 12.5 -3 2e5"
+boolean_concat: true false true // "true false true"
+null_concat: null null null // "null null null"
+mixed_concat: 1 true null // "1 true null"
+
+# String value concatenation can appear anywhere that a quoted string can.
+number_concat_in_array: [1 2, 3 4, 5 6] // same as: ["1 2", "3 4", "5 6"]
+
+# In fact, unquoted strings are actually just string value concatenations.
+unquoted_string_concat: his name is jeff // same as: "his name is jeff"
+
+# Going further, even keys that are unquoted strings are actually just string
+# value concatenations.
+this is a key: value // the KEY is the same as: "this is a key"
+# The following field is identical to the field above.
+"this is a key": value
+
+# Quoted strings can also be concatenated. This will be useful later,
+# when we cover substitutions.
+quoted_string_concat: "her"" name" "is ""jenna" // same as: "her name is jenna"
+# Notice that the whitespace (or lack thereof) between values is preserved.
+
+## ARRAY CONCATENATION ##
+
+# Arrays separated by whitespace are merged into a single array.
+array_concat: [1, 2, 3] [4, 5, 6] // same as: [1, 2, 3, 4, 5, 6]
+
+# Arrays cannot be concatenated with a non-array value.
+//array_concat: true [false] results in an error
+//array_concat: 1 [2] results in an error
+
+## OBJECT CONCATENATION ##
+
+# Objects separated by whitespace are merged into a single object.
+# The merge functionality is identical to that of duplicate key object merging.
+lamp: {on: true} {color: tan} // same as: {on: true, color: tan}
+
+# Similarly to arrays, objects cannot be concatenated with a non-object value.
+//object_concat: true {on: false} results in an error
+//object_concat: 1 {number: 2} results in an error
+
+########################
+### PATH EXPRESSIONS ###
+########################
+
+# Path expressions are used to write out a path through the object graph.
+# Think of it as navigating through objects to a specific field.
+# Each object to traverse through is called an element, and each element is
+# separated with a period.
+
+country: {
+ city: {
+ neighborhood: {
+ house: {
+ name: "My House"
+ address: 123 Example Dr.
+ }
+ }
+ }
+}
+# For example, the path to the address of the house could be written as:
+# country.city.neighborhood.house.address
+# Country, city, neighborhood, house, and address are all elements.
+
+# Path expressions are used in two places: substitutions (which will be
+# covered in a moment), and as keys.
+# That's right: keys themselves can also be path expressions.
+foo: {
+ bar: {
+ baz: {
+ number: 12
+ }
+ }
+}
+# Rather than tediously specifying each object, a path expression can be used.
+# The following field represents the same object found above.
+foo.bar.baz.number: 12
+
+# Fields and objects specified with path expressions are merged in the same way
+# that any object is usually merged.
+foo.bar.baz.bool: true
+// the object foo's value is: foo { bar { baz { number: 12, bool: true } } }
+
+#####################
+### SUBSTITUTIONS ###
+#####################
+
+# Substitutions refer to a specific value from some path expression.
+# They're only allowed in values, not keys or nested inside other substitutions.
+
+me: {
+ favorite_animal: parrots
+ favorite_food: cookies
+}
+# The syntax for a substitution is either ${path_expression} or
+# ${?path_expression}. The latter syntax will be discussed in a moment.
+my_fav_animal: ${me.favorite_animal}
+my_fav_food: ${me.favorite_food}
+
+# Substitutions are not parsed inside quoted strings. To get around this,
+# either use an unquoted string or value concatenation.
+animal_announcement: My favorite animal is ${my_fav_animal}
+// the value is: My favorite animal is parrots
+food_announcement: "My favorite food is "${my_fav_food}"!"
+// the value is: "My favorite food is cookies!"
+
+# Substitutions are parsed last in the document. Because of this, you can
+# reference a key that hasn't been defined yet.
+color_announcement: "My favorite color is" ${my_fav_color}"!"
+// the value is: "My favorite color is blue!"
+my_fav_color: blue
+
+# Another effect of substitutions being parsed last is that substitutions will
+# always use the latest, as in last, value assigned in the entire document,
+# which includes merged objects.
+color: green
+their_favorite_color: ${color} // the value is: orange
+color: orange
+
+random_object: {
+ number: 12
+}
+the_number: ${random_object.number} // the value is: 15
+random_object: {
+ number: 15
+}
+
+###############################
+### UNDEFINED SUBSTITUTIONS ###
+###############################
+
+# A substitution using the ${path_expression} syntax with an undefined path
+# expression, meaning a path expression that does not point to a defined value,
+# is invalid and will therefore generate an error.
+//${does.not.exist} will throw an error
+
+# However, an undefined substitution using the ${?path_expression} syntax
+# has different behavior depending on what it is the value of.
+request: {
+ # If it is the value of a field, then the field will not be created.
+ response: ${?does.not.exist} // this field won't be created and does not exist
+ type: HTTP
+}
+
+request: {
+ # Additionally, if it would have overridden a previous value, then the
+ # previous value remains unchanged.
+ type: ${?does.not.exist} // request.type is still HTTP
+}
+
+# If it is a value in an array, then it is simply not added.
+values: [ 172, "Brian", ${?does.not.exist}, null, true, ]
+// the value is: [ 172, "Brian", null, true ]
+
+# If it is part of simple value concatenation, it acts as an empty string.
+final_string: "String One"${?does.not.exist}"String Two"
+// the value is: "String OneString Two"
+
+# If it is part of array concatenation, it acts as an empty array.
+final_array: [ 1, 2, 3 ] ${?does.not.exist} [ 7, 8, 9 ]
+// the value is: [ 1, 2, 3, 7, 8, 9 ]
+
+# If it is part of object concatenation, it acts as an empty object.
+final_array: { a: 1 } ${?does.not.exist} { c: 3 }
+// the value is: { a: 1, c: 3 }
+
+######################################
+### SELF-REFERENTIAL SUBSTITUTIONS ###
+######################################
+
+# Substitutions normally "look forward" and use the final value defined in the
+# document. However, in cases when this would create a cycle, the substitution
+# looks only backwards.
+
+# A field which contains a substitution that points to itself or points to
+# other fields that eventually point back to itself is called a
+# self-referential field.
+letters: "a b c" // the value is: "a b c"
+letters: ${letters}" d" // "a b c d"
+letters: ${letters}" e" // "a b c d e"
+
+PATH: [/bin] // the value is: [/bin]
+PATH: ${PATH} [/usr/bin] // [/bin, /usr/bin]
+PATH: ${PATH} [/usr/local/bin] // [/bin, /usr/bin, /usr/local/bin]
+
+x: "x" // the value is: "x"
+y: ${x}"y" // "xy"
+x: ${y}"z" // "xyz"
+
+##########################
+### += FIELD SEPARATOR ###
+##########################
+
+# In addition to : and =, there actually exists another separator: +=
+# A field separated with += acts as a self-referential array concatenation.
+# In short, it appends an element to a previously defined array.
+
+a: [1]
+b: [1]
+# This field:
+a += 2 // the value is: [1, 2]
+# functions the same as:
+b: ${?b} [2] // the value is: [1, 2]
+
+USERS: [/usr/luke] // the value is: [/usr/luke]
+USERS += /usr/devon // [/usr/luke, /usr/devon]
+USERS += /usr/michael // [/usr/luke, /usr/devon, /usr/michael]
+
+# Since += only appends elements to a previously existing array, if the previous
+# value was not an array, an error will be generated.
+OTHER_USERS: /usr/luke
+//OTHER_USERS += /usr/devon results in an error
+
+# Notice that the underlying substitution syntax used is ${?path}, not ${path}.
+# Recall that, using the ${?} syntax, an undefined substitution in array
+# concatenation acts as an empty array. Because of this, it is perfectly
+# acceptable if the field that is being set is initially undefined.
+//z: [] not necessary
+z += 3 // the value is: [3]
+z += 4 // the value is: [3, 4]
+
+NEW_USERS += /usr/sandra // the value is: [/usr/sandra]
+NEW_USERS += /usr/kennedy // [/usr/sandra, /usr/kennedy]
+NEW_USERS += /usr/robin // [/usr/sandra, /usr/kennedy, /usr/robin]
+
+################
+### INCLUDES ###
+################
+
+# Includes allow you to "import" one HOCON document into another.
+
+# An include statement consists of the unquoted string "include" followed by
+# whitespace and then a resource name, which is one of the following:
+# - a single quoted string which is heuristically interpreted as a URL,
+# filename, or a Java classpath resource.
+# - url(), file(), or classpath(), with the parentheses surrounding a quoted
+# string which is either a URL, filename, or classpath resource respectively.
+# - required(), with the parentheses surrounding one of the above.
+include "https://example.com/config.conf"
+include "/foo/bar/config.conf"
+include "config.conf"
+
+include url("https://example.com/config.conf")
+include file("/foo/bar/config.conf")
+include classpath("config.conf")
+
+# If the included file does not exist, it will be silently ignored and act as if
+# it were an empty object. However, if it is wrapped around required(), then
+# parsing will explicitly error if the file cannot be resolved.
+//include required("doesnt_exist.conf") will error
+//include required(url("https://example.com/doesnt_exist.conf")) will error
+//include required(file("doesnt_exist.conf")) will error
+//include required(classpath("doesnt_exist.conf")) will error
+
+# The file specified by the include statement is called the included file, and
+# the file which contains the include statement is called the including file.
+
+# Including a file functions as if you directly replaced the include statement,
+# wherever it may be, with the contents of the included file's root object.
+
+# An included file must have an object as its root value and not an array.
+# If the included file has an array as its root value, then it is invalid and
+# an error will be generated.
+
+# Pretend that the following is in a file called user_config.conf:
+username: RandomUser1337
+auto_login: true
+color_theme: dark
+screensaver: {
+ image: usr/images/screensaver.jpg
+ turn_on_after: 1m
+}
+
+# And then we include that file.
+include file("user_config.conf")
+
+# We can now reference values from that file!
+path_to_user_screensaver: ${screensaver.image} //
+greeting: "Welcome, "${username}"!" // the value is: "Welcome, RandomUser1337!"
+
+# Duplicate keys override as they normally do.
+status: "Auto Login: "${auto_login} // the value is: "Auto Login: true"
+auto_login: false
+status: "Auto Login: "${auto_login} // the value is: "Auto Login: false"
+
+# Object merging is also the same as usual.
+screensaver: {
+ // This gets added to the screensaver object.
+ enable_during_day: false
+ // This overrides the previous value.
+ turn_on_after: 30s
+}
+
+# Include statements can appear in place of a field. Anywhere that a field
+# could appear, an include statement could appear as well.
+
+# Pretend that the following is in a file called server_settings.conf:
+max_connections: 10
+url: example.com
+port: 80
+admin_page: {
+ username: admin
+ password: pass12345
+}
+
+# And then we include that file nested inside another object.
+websites: {
+ my_epic_website: {
+ include file("server_settings.conf")
+ }
+}
+
+# Now, we can reference the contents of server_settings.conf as if they
+# had been written directly into the object my_epic_website.
+server_port: ${websites.my_epic_website.port}
+
+the_password: "The password is: "${websites.my_epic_website.admin_page.password}
+// the value is: The password is: pass12345
+
+max_conn: "Max Connections: "${websites.my_epic_website.max_connections}
+// the value is: Max Connections: 10
+```
+
+### More Resources
+
++ [Official HOCON Specification](https://github.com/lightbend/config/blob/master/HOCON.md)
++ [HOCON Playground](https://hocon-playground.herokuapp.com)
diff --git a/httpie.html.markdown b/httpie.html.markdown
new file mode 100644
index 00000000..390e7b35
--- /dev/null
+++ b/httpie.html.markdown
@@ -0,0 +1,120 @@
+---
+category: tool
+tool: httpie
+contributors:
+ - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"]
+filename: learn-httpie.sh
+---
+
+HTTPie is a powerful command-line HTTP client designed for easy interaction
+with HTTP servers. It provides a simple and intuitive interface, making it an
+excellent tool for developers, testers, and system administrators.
+
+## Basic Usage
+
+HTTPie follows a simple syntax: http [flags] [METHOD] URL [items].
+
+```bash
+http GET https://api.example.com/posts
+```
+
+You can print the request without sending it by using the `--offline` flag.
+
+```bash
+http --offline https://api.example.com/posts
+```
+
+### URL shortcuts for `localhost`
+
+HTTPie supports a curl-like shorthand for localhost. For instance, ":3000"
+expands to "http://localhost:3000". If the port is omitted, it assumes port 80.
+
+```bash
+http :/users # http://localhost/users
+http :5000/rss # http://localhost:5000/rss
+```
+
+### Optional GET and POST
+
+If you don't specify the METHOD, the HTTPie will use:
+
+- GET for requests without body
+- POST for requests with body
+
+```bash
+http https://api.example.com/tags # GET tags
+http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST a new tag
+```
+
+## Querystring Parameters
+
+
+If you're manually adding query string parameters in the terminal, try the
+`param==value` syntax. It avoids shell escaping for & separators and
+automatically URL-escapes special characters in parameter names and values.
+This differs from parameters in the full URL, which HTTPie doesn't modify.
+
+```bash
+http https://api.example.com/search q==httpie per_page==20
+```
+
+## Sending Data
+
+You can send data in various formats such as JSON, form data, or files.
+
+### JSON Data
+
+```bash
+http POST https://api.example.com/posts title="Hello" body="World"
+```
+
+### Form Data
+
+```bash
+http -f POST https://api.example.com/submit name=John email=john@example.com
+```
+
+### Files
+
+```bash
+http --form POST https://api.example.com/upload file@/path/to/file.txt
+```
+
+## Headers and Authentication
+
+HTTPie allows you to set headers and handle authentication easily.
+
+### Headers
+
+```bash
+http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie"
+```
+
+### Basic Authentication
+
+```bash
+http -a username:password GET https://api.example.com/protected
+```
+
+### Bearer Authentication
+
+```bash
+https -A bearer -a token https://api.example.com/admin
+```
+
+## Response Handling
+
+HTTPie provides various options for handling responses.
+
+```bash
+http GET https://api.example.com/data Accept:application/json # Pretty Print JSON
+
+http GET https://api.example.com/image --output image.png # Save Response to File
+
+http --follow GET https://example.com # Follow Redirects
+```
+
+## Further Reading
+
+- [Official Documentation](https://httpie.io/docs/cli).
+- [Github](https://github.com/httpie).
diff --git a/hu-hu/go-hu.html.markdown b/hu-hu/go-hu.html.markdown
index 638c9489..451f9147 100644
--- a/hu-hu/go-hu.html.markdown
+++ b/hu-hu/go-hu.html.markdown
@@ -89,7 +89,7 @@ func learnTypes() {
g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert
// tárol
- f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites
+ f := 3.14159 // float64, az IEEE-754 szabványnak megfelelő 64-bites
// lebegőpontos szám
c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva
@@ -325,7 +325,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
## További olvasmányok
-Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/).
+Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](https://go.dev/).
Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz.
A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember.
diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown
index b5922766..483784ba 100644
--- a/hu-hu/pythonlegacy-hu.html.markdown
+++ b/hu-hu/pythonlegacy-hu.html.markdown
@@ -20,7 +20,7 @@ bele. Tulajdonképpen futtatható pszeudokód.
Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
-Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
+Figyelem: ez a leírás a Python 2.7 verziójára vonatkozik, illetve
általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python/)
diff --git a/hy.html.markdown b/hy.html.markdown
index 1287095f..5eddbf55 100644
--- a/hy.html.markdown
+++ b/hy.html.markdown
@@ -13,8 +13,7 @@ hy to call native python code or python to call native hy code as well
This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11.
```clojure
-;; this gives an gentle introduction to hy for a quick trial head to
-;; http://try-hy.appspot.com
+;; this gives an gentle introduction to hy
;;
; Semicolon comments, like other LISPS
@@ -175,10 +174,10 @@ True ; => True
; create lexical bindings with `let', all variables defined thusly
; have local scope
-(let [[nemesis {"superman" "lex luther"
+(let [nemesis {"superman" "lex luther"
"sherlock" "moriarty"
- "seinfeld" "newman"}]]
- (for [(, h v) (.items nemesis)]
+ "seinfeld" "newman"}]
+ (for [[h v] (.items nemesis)]
(print (.format "{0}'s nemesis was {1}" h v))))
;; classes
diff --git a/id-id/asciidoc-id.html.markdown b/id-id/asciidoc-id.html.markdown
index ceb56b92..2843b8be 100644
--- a/id-id/asciidoc-id.html.markdown
+++ b/id-id/asciidoc-id.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
translators:
- ["Rizky Luthfianto", "http://github.com/rilut"]
-filename: asciidoc-id.md
+filename: asciidoc-id.adoc
lang: id-id
---
diff --git a/id-id/coffeescript-id.html.markdown b/id-id/coffeescript-id.html.markdown
index 7fa40bb6..fc876184 100644
--- a/id-id/coffeescript-id.html.markdown
+++ b/id-id/coffeescript-id.html.markdown
@@ -16,7 +16,7 @@ dan kompatibel dengan semua *runtime* JavaScript.
Lihat juga [website CoffeeScript](http://coffeescript.org/) yang memiliki tutorial lengkap tentang CoffeeScript.
-```CoffeeScript
+```coffeescript
# CoffeeScript adalah bahasa hipster.
# Mengikuti tren bahasa modern lainnya.
# Sehingga, seperti Ruby dan Python, untuk komentar digunakan tanda pagar.
diff --git a/id-id/pyqt-id.html.markdown b/id-id/pyqt-id.html.markdown
index c4833d06..a9163326 100644
--- a/id-id/pyqt-id.html.markdown
+++ b/id-id/pyqt-id.html.markdown
@@ -15,10 +15,10 @@ lang: id-id
Tulisan ini diadaptasi dari **Intro Qt untuk C++** oleh [Aleksey Kholovchuk](https://github.com/vortexxx192). Kode-kode yang tertulis di sini akan menghasilkan fungsionalitas yang sama. Bedanya, versi ini dibangun menggunakan **PyQt**!
-```Python
+```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Buat objek aplikasi
app = QtGui.QApplication(sys.argv)
@@ -45,7 +45,7 @@ if __name__ == '__main__':
Untuk menunjukkan beberapa fitur yang lebih canggih di **PyQt**, kita akan membangun elemen tambahan.
Di sini, kita akan membuat Kotak Popup Dialog, yang berguna untuk meminta pengguna untuk mengkonfirmasi keputusan atau untuk menampilkan informasi.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
diff --git a/images/cairo/build.png b/images/cairo/build.png
new file mode 100644
index 00000000..7cadb9ad
--- /dev/null
+++ b/images/cairo/build.png
Binary files differ
diff --git a/images/cairo/connect.png b/images/cairo/connect.png
new file mode 100644
index 00000000..86146353
--- /dev/null
+++ b/images/cairo/connect.png
Binary files differ
diff --git a/images/cairo/connect2.png b/images/cairo/connect2.png
new file mode 100644
index 00000000..08b00a81
--- /dev/null
+++ b/images/cairo/connect2.png
Binary files differ
diff --git a/images/cairo/declare.png b/images/cairo/declare.png
new file mode 100644
index 00000000..5b5196ce
--- /dev/null
+++ b/images/cairo/declare.png
Binary files differ
diff --git a/images/cairo/deploy.png b/images/cairo/deploy.png
new file mode 100644
index 00000000..bdb7e53c
--- /dev/null
+++ b/images/cairo/deploy.png
Binary files differ
diff --git a/it-it/asciidoc-it.html.markdown b/it-it/asciidoc-it.html.markdown
index 47a57349..eaa2372b 100644
--- a/it-it/asciidoc-it.html.markdown
+++ b/it-it/asciidoc-it.html.markdown
@@ -6,7 +6,7 @@ contributors:
translators:
- ["Ale46", "https://github.com/ale46"]
lang: it-it
-filename: asciidoc-it.md
+filename: asciidoc-it.adoc
---
AsciiDoc è un linguaggio di markup simile a Markdown e può essere usato per qualsiasi cosa, dai libri ai blog. Creato nel 2002 da Stuart Rackman, questo linguaggio è semplice ma permette un buon numero di personalizzazioni.
diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown
index 449aebfb..a8e0c7b5 100644
--- a/it-it/c++-it.html.markdown
+++ b/it-it/c++-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-it.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown
index 48afe0c8..ce3e4535 100644
--- a/it-it/elixir-it.html.markdown
+++ b/it-it/elixir-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Luca 'Kino' Maroni", "https://github.com/kino90"]
- ["Joao Marques", "http://github.com/mrshankly"]
@@ -21,11 +21,11 @@ e molte altre funzionalità.
# Non esistono commenti multilinea,
# ma puoi concatenare più commenti.
-# Per usare la shell di elixir usa il comando `iex`.
+# Per usare la shell di Elixir usa il comando `iex`.
# Compila i tuoi moduli con il comando `elixirc`.
# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato
-# elixir correttamente.
+# Elixir correttamente.
## ---------------------------
## -- Tipi di base
@@ -87,7 +87,7 @@ multi-linea.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` in elixir restituisce il valore ASCII della lettera `a`
+# `?a` in Elixir restituisce il valore ASCII della lettera `a`
?a #=> 97
# Per concatenare liste si usa `++`, per binari si usa `<>`
@@ -112,7 +112,7 @@ minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli
5 * 2 #=> 10
10 / 2 #=> 5.0
-# In elixir l'operatore `/` restituisce sempre un decimale.
+# In Elixir l'operatore `/` restituisce sempre un decimale.
# Per fare una divisione intera si usa `div`
div(10, 2) #=> 5
@@ -173,7 +173,7 @@ else
end
# Ti ricordi il pattern matching?
-# Moltre strutture di controllo di flusso in elixir si basano su di esso.
+# Moltre strutture di controllo di flusso in Elixir si basano su di esso.
# `case` ci permette di confrontare un valore a diversi pattern:
case {:uno, :due} do
@@ -307,7 +307,7 @@ Geometria.area({:cerchio, 3}) #=> 28.25999999999999801048
# Geometria.area({:cerchio, "non_un_numero"})
#=> ** (FunctionClauseError) no function clause matching in Geometria.area/1
-# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir
+# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in Elixir
defmodule Ricorsione do
def somma_lista([testa | coda], accumulatore) do
somma_lista(coda, accumulatore + testa)
@@ -382,7 +382,7 @@ end
## ---------------------------
# Elixir si basa sul modello degli attori per la concorrenza.
-# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir
+# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in Elixir
# sono tre primitive: creare processi, inviare messaggi e ricevere messaggi.
# Per creare un nuovo processo si usa la funzione `spawn`, che riceve una
@@ -434,7 +434,7 @@ self() #=> #PID<0.27.0>
## Referenze
-* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org)
+* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di Elixir](http://elixir-lang.org)
* [Documentazione Elixir](https://elixir-lang.org/docs.html)
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown
index 797f6b0b..6f974c91 100644
--- a/it-it/go-it.html.markdown
+++ b/it-it/go-it.html.markdown
@@ -34,7 +34,7 @@ Go include un'ottima libreria standard e ha una community entusiasta.
su riga multipla */
// In cima ad ogni file è necessario specificare il package.
-// Main è un package speciale che identifica un eseguibile anziché una libreria.
+// main è un package speciale che identifica un eseguibile anziché una libreria.
package main
// Con import sono dichiarate tutte le librerie a cui si fa riferimento
@@ -91,7 +91,7 @@ può includere andata a capo.` // Sempre di tipo stringa.
// Stringa letterale non ASCII. I sorgenti Go sono in UTF-8.
g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode.
- f := 3.14195 // float64, un numero in virgola mobile a 64-bit (IEEE-754)
+ f := 3.14159 // float64, un numero in virgola mobile a 64-bit (IEEE-754)
c := 3 + 4i // complex128, rappresentato internamente con due float64.
@@ -422,9 +422,9 @@ func richiediServer() {
## Letture consigliate
-La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/).
+La risorsa più importante per imparare il Go è il [sito ufficiale di Go](https://go.dev/).
Qui puoi seguire i tutorial, scrivere codice in modo interattivo, e leggere tutti i dettagli.
-Oltre al tour, [la documentazione](https://golang.org/doc/) contiene informazioni su
+Oltre al tour, [la documentazione](https://go.dev/doc/) contiene informazioni su
come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e
la cronologia delle release.
@@ -432,17 +432,17 @@ Anche il documento che definisce il linguaggio è un'ottima lettura. E' semplice
da leggere e incredibilmente corto (rispetto ad altri documenti riguardanti
la creazione di linguaggi).
-Puoi giocare con il codice visto finora nel [Go playground](https://play.golang.org/p/Am120Xe7qf).
+Puoi giocare con il codice visto finora nel [Go playground](https://go.dev/play/p/Am120Xe7qf).
Prova a cambiarlo e ad eseguirlo dal browser!
-Osserva che puoi usare [https://play.golang.org](https://play.golang.org) come
+Osserva che puoi usare [https://go.dev/play/](https://go.dev/play/) come
una [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per scrivere
codice all'interno del browser, senza neanche installare Go!
Una lettura importante per capire Go in modo più profondo è il [codice
-sorgente della libreria standard](http://golang.org/src/pkg/). Infatti è
+sorgente della libreria standard](https://go.dev/src/). Infatti è
molto ben documentato e costituisce quanto più chiaro e conciso ci sia riguardo
gli idiomi e le buone pratiche del Go. Inoltre, clickando sul nome di una
-funzione [nella documentazione](http://golang.org/pkg/) compare il relativo
+funzione [nella documentazione](https://go.dev/pkg/) compare il relativo
codice sorgente!
Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/).
diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown
index b0a123f1..ff6f0aed 100644
--- a/it-it/markdown.html.markdown
+++ b/it-it/markdown.html.markdown
@@ -183,7 +183,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -194,12 +194,15 @@ Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`!
```
In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
+
Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali
## Linea orizzontale
@@ -253,7 +256,7 @@ Ma non è comunemente usato.
Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre!
```md
-![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale")
+![Questo è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale")
```
E la modalità a riferimento funziona esattamente come ci si aspetta
@@ -307,4 +310,4 @@ Col 1 | Col2 | Col3
```
---
-Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
+Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](https://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown
index 38be8848..2668815f 100644
--- a/it-it/matlab-it.html.markdown
+++ b/it-it/matlab-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: Matlab
+language: MATLAB
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
@@ -114,7 +114,7 @@ A.d.e = false;
% Vettori
x = [4 32 53 7 1]
-x(2) % ans = 32, gli indici in Matlab iniziano da 1, non da 0
+x(2) % ans = 32, gli indici in MATLAB iniziano da 1, non da 0
x(2:3) % ans = 32 53
x(2:end) % ans = 32 53 7 1
@@ -466,7 +466,7 @@ perms(x) % lista tutte le permutazioni di elementi di x
% Classi
-% Matlab supporta la programmazione orientata agli oggetti.
+% MATLAB supporta la programmazione orientata agli oggetti.
% La classe deve essere messa in un file con lo stesso nome della classe e estensione .m
% Per iniziare, creiamo una semplice classe per memorizzare waypoint GPS
% Inizio WaypointClass.m
@@ -488,7 +488,7 @@ classdef WaypointClass % Il nome della classe.
end
% Se si vuole aggiungere due oggetti Waypoint insieme senza chiamare
- % una funzione speciale si può sovradefinire una funzione aritmetica di Matlab come questa:
+ % una funzione speciale si può sovradefinire una funzione aritmetica di MATLAB come questa:
function r = plus(o1,o2)
r = WaypointClass([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]);
@@ -500,7 +500,7 @@ end
% Si può creare un oggetto della classe usando un costruttore
a = WaypointClass(45.0, 45.0)
-% Le proprietà della classe si comportano esattamente come una Struttura Matlab.
+% Le proprietà della classe si comportano esattamente come una Struttura MATLAB.
a.latitude = 70.0
a.longitude = 25.0
@@ -511,15 +511,15 @@ ans = multiplyLatBy(a,3)
% non necessita di essere passato al metodo.
ans = a.multiplyLatBy(a,1/3)
-% Le funzioni Matlab possono essere sovradefinite per gestire oggetti.
-% Nel metodo sopra, è stato sovradefinito come Matlab gestisce
+% Le funzioni MATLAB possono essere sovradefinite per gestire oggetti.
+% Nel metodo sopra, è stato sovradefinito come MATLAB gestisce
% l'addizione di due oggetti Waypoint.
b = WaypointClass(15.0, 32.0)
c = a + b
```
-## Di più su Matlab
+## Di più su MATLAB
* Sito ufficiale [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
* Forum ufficiale di MATLAB: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
diff --git a/it-it/php-composer-it.html.markdown b/it-it/php-composer-it.html.markdown
new file mode 100644
index 00000000..509ec336
--- /dev/null
+++ b/it-it/php-composer-it.html.markdown
@@ -0,0 +1,193 @@
+---
+category: tool
+tool: composer
+contributors:
+ - ["Brett Taylor", "https://github.com/glutnix"]
+translator:
+ - ["Agostino Fiscale", "https://github.com/agostinofiscale"]
+lang: it-it
+filename: LearnComposer-it.sh
+---
+
+[Composer](https://getcomposer.org/) è uno strumento che ti aiuta a gestire le
+dipendenze in PHP. Ti permette di dichiarare le librerie utilizzate dal tuo
+progetto e di installarle/aggiornarle per te.
+
+# Installazione
+
+```sh
+# Se installi l'eseguibile in una cartella...
+curl -sS https://getcomposer.org/installer | php
+# ...dovrai utilizzare questo approccio, invocando Composer in questo modo:
+php composer.phar about
+
+# Se installi l'eseguibile nella directory ~/bin/composer
+# Nota: assicurati che ~/bin si trovi nella variabile di ambiente PATH
+curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer
+```
+
+Gli utenti Windows possono seguire le istruzioni per [installarlo su Windows](https://getcomposer.org/doc/00-intro.md#installation-windows).
+
+## Assicuriamoci che il tutto abbia funzionato correttamente
+
+```sh
+# Controlla la versione e la lista delle opzioni disponibili
+composer
+
+# Ottieni ulteriori informazioni riguardanti le opzioni
+composer help require
+
+# Controlla se Composer ha tutto il necessario per funzionare come si deve
+# e se è aggiornato correttamente all'ultima versione disponibile.
+composer diagnose
+composer diag # alias
+
+# Aggiorna Composer all'ultima versione disponibile
+composer self-update
+composer self # alias
+```
+
+# Cominciamo ad usare Composer
+
+Composer memorizza le dipendenze necessarie nel file `composer.json`.
+Puoi editare questo file manualmente, ma è meglio che lasci che Composer se ne
+occupi per te.
+
+```sh
+# Crea un nuovo progetto nella cartella attuale
+composer init
+# ti verranno chieste delle domande interrative riguardanti il tuo progetto.
+# Puoi evitare di rispondere almeno che tu non stia sviluppando altri progetti
+# che che possano dipendere da questo.
+
+# Se il file composer.json esiste già, scarichera' le dipendenze necessarie
+composer install
+
+# Scarica le dipendenze necessarie per l'ambiente di produzione
+composer install --no-dev
+
+# Aggiunge una dipendenza per l'ambiente di produzione
+composer require guzzlehttp/guzzle
+# automaticamente selezionera' l'ultima versione, la scarichera' e la aggiungera'
+# come dipendenza nell'apposito campo del file composer.json.
+
+composer require guzzlehttp/guzzle:6.0.*
+# scarichera' l'ultima versione disponibile corrispondente al pattern (es. 6.0.2)
+# e lo aggiungera' come dipendenza nell'apposito campo del file composer.json.
+
+composer require --dev phpunit/phpunit:~4.5.0
+# aggiungera' la dipendenza nell'ambiente di sviluppo utilizzando l'ultima versione
+# disponibile nel range >=4.5.0 e < 4.6.0.
+
+composer require-dev phpunit/phpunit:^4.5.0
+# aggiungera' la dipendenza nell'ambiente di sviluppo utilizzando l'ultima versione
+# disponibile nel range >=4.5.0 and < 5.0.
+
+# Per ulteriori dettagli riguardo le versioni, vedi [la documentazione di Composer sulle versioni](https://getcomposer.org/doc/articles/versions.md) per ulteriori dettagli
+
+# Per vedere quali pacchetti sono installabili e quali sono gia' stati installati
+composer show
+
+# Per vedere solo quali pacchetti sono gia' stati installati
+composer show --installed
+
+# Per trovare una dipendenza con 'mailgun' nel suo nome o nella descrizione.
+composer search mailgun
+```
+
+[Packagist.org](https://packagist.org/) è il repository principale per i pacchetti
+di Composer. Cerca qui pacchetti di terze-parti utili per il tuo progetto.
+
+## `composer.json` vs `composer.lock`
+
+Il file `composer.json` memorizza la versione che si preferisce per ogni dipendenza,
+insieme ad altre informazioni.
+
+Il file `composer.lock` memorizza quale versione è stata scaricata per ogni
+dipendenza. Non editare mai questo file.
+
+Se includi il file `composer.lock` nella tua repository git, ogni sviluppatore
+andra' a installare la versione attualmente utilizzata dal tuo progetto per
+ogni dipendenza. Anche quando una nuova versione è stata rilasciata, Composer
+andra' a installare la versione registrata nel file lock.
+
+```sh
+# Se vuoi aggiornare tutte le dipendenze all'ultima versione che corrisponde al pattern descritto
+composer update
+
+# Se vuoi scaricare l'ultima versione di una particolare dipendenza:
+composer update phpunit/phpunit
+
+# Se vuoi cambiare la versione di una una dipendenza, potresti dover rimuovere
+# quello attualmente selezionato, per poi richiedere quello corretto successivamente,
+# attraverso i seguenti comandi:
+composer remove --dev phpunit/phpunit
+composer require --dev phpunit/phpunit:^5.0
+
+```
+
+## Autoloader
+
+Composer crea una classe autoloader che puoi richiamare nella tua applicazione.
+Puoi creare instanze delle classi tramite il loro namespace.
+
+```php
+require __DIR__ . '/vendor/autoload.php';
+
+$mailgun = new Mailgun\Mailgun("key");
+```
+
+### PSR-4 Autoloader
+
+Puoi aggiungere i tuoi namespace all'autoloader.
+
+Nel file `composer.json`, aggiungi il campo "autoload":
+
+```json
+{
+ "autoload": {
+ "psr-4": {"Acme\\": "src/"}
+ }
+}
+```
+Questo dira' all'autoloader di controllare ogni risorsa che corrisponde al
+namespace `\Acme\` all'interno della cartella `src`.
+
+In alternativa puoi usare [PSR-0, una Classmap o una lista di file da includere](https://getcomposer.org/doc/04-schema.md#autoload).
+Inoltre e' possibile anche utilizzare `autoload-dev` dedicato all'ambiente di sviluppo.
+
+Quando aggiungi o modifichi una chiave, dovrai ricompilare l'autoload attraverso:
+
+```sh
+composer dump-autoload
+composer dump # alias
+
+# Ottimizza i pacchetti PSR0 e PSR4 per essere caricati anche con le classmap.
+# Sara' lento, ma migliorera' le performance in produzione.
+composer dump-autoload --optimize --no-dev
+```
+
+# La cache di Composer
+
+```sh
+# Composer utilizzera i pacchetti scaricati anche per i progetti futuri. Per evitare che accada:
+composer clear-cache
+```
+
+# Problemi?
+
+```sh
+composer diagnose
+composer self-update
+composer clear-cache
+```
+
+## Argomenti che non sono stati (ancora) discussi in questo tutorial
+
+* Creare e distribuire pacchetti personali su Packagist.org o altrove
+* Pre- e post- script hooks: eseguire operazioni quando vengono eseguiti degli eventi
+
+### References
+
+* [Composer - Dependency Manager for PHP](https://getcomposer.org/)
+* [Packagist.org](https://packagist.org/)
diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown
index 7238dd7b..7b5a98c2 100644
--- a/it-it/pyqt-it.html.markdown
+++ b/it-it/pyqt-it.html.markdown
@@ -14,12 +14,12 @@ lang: it-it
Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192
), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità
-che avrebbero se fossero fatte usando pyqt!
+che avrebbero se fossero fatte usando pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Crea un oggetto applicazione
app = QtGui.QApplication(sys.argv)
@@ -47,7 +47,7 @@ if __name__ == '__main__':
Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi.
Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -66,7 +66,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante
# che aspetta di essere cliccato e quindi esce dal programma
def showdialog():
diff --git a/it-it/qt-it.html.markdown b/it-it/qt-it.html.markdown
index d7469f67..ef829493 100644
--- a/it-it/qt-it.html.markdown
+++ b/it-it/qt-it.html.markdown
@@ -1,7 +1,7 @@
---
category: tool
tool: Qt Framework
-language: c++
+language: C++
filename: learnqt-it.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown
index df4d6279..acb8b8ba 100644
--- a/it-it/rust-it.html.markdown
+++ b/it-it/rust-it.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["Carlo Milanesi", "http://github.com/carlomilanesi"]
lang: it-it
diff --git a/it-it/solidity.html.markdown b/it-it/solidity.html.markdown
new file mode 100644
index 00000000..be747e68
--- /dev/null
+++ b/it-it/solidity.html.markdown
@@ -0,0 +1,1069 @@
+---
+language: Solidity
+filename: learnSolidity-it.sol
+contributors:
+ - ["Nemil Dalal", "https://www.nemil.com"]
+ - ["Joseph Chow", ""]
+ - ["Bhoomtawath Plinsut", "https://github.com/varshard"]
+ - ["Shooter", "https://github.com/liushooter"]
+ - ["Patrick Collins", "https://gist.github.com/PatrickAlphaC"]
+translators:
+ - ["Al", "http://github.com/al-ias"]
+lang: it-it
+---
+
+Solidity permette di programmare su [Ethereum](https://www.ethereum.org/), una
+macchina virtuale basata sulla blockchain che consente la creazione e
+l'esecuzione degli smart contract senza che sia richiesta centralizzazione o
+fiducia negli attori coinvolti.
+
+Solidity è un linguaggio di programmazione di contratti tipizzato staticamente e
+ha molte cose in comune con Javascript e C. Come per gli oggetti nella
+programmazione ad oggetti, ogni contratto contiene variabili di stato, funzioni
+e tipi di dato semplici. Tra le funzionalità specifiche dei contratti troviamo
+le clausole (guardie) dei modifier, gli event notifier per i listener, e le
+variabili globali custom.
+
+Come esempi di contratti su Ethereum troviamo sistemi di crowdfunding, voto,
+[finanza decentralizzata](https://defipulse.com/) e aste al buio.
+
+Compiere errori nel codice Solidity può portare a rischi e costi alti, quindi
+bisogna fare attenzione a testare e rilasciare le modifiche lentamente. A
+CAUSA DEI CONTINUI CAMBIAMENTI DI ETHEREUM È IMPROBABILE CHE QUESTO DOCUMENTO
+RESTI AGGIORNATO, QUINDI COSNIGLIAMO DI SEGUIRE LA CHAT ROOM DI SOLIDITY E IL
+BLOG DI ETHEREUM PER TENERSI AGGIORNATI. TUTTO IL CODICE QUI PRESENTE E' FORNITO
+COSÌ COM'È, CON ANNESSI RISCHI SOSTANZIALI DI ERRORI O PATTERN DI PROGRAMMAZIONE
+DEPRECATI.
+
+A differenza di altri linguaggi, potresti aver bisogno di usare pattern di
+pausing, deprecation e throttling usage per ridurre il rischio. Questo documento
+tratta principalmene la sintassi e quindi esclude molti design pattern in voga.
+
+Visto che Solidity e Ethereum sono in continuo sviluppo, le funzionalità
+sperimentali o beta sono evidenziate e soggette a cambiamenti. Ogni Pull Request
+è ben accetta.
+
+
+# Lavorare con Remix e Metamask
+
+Uno dei modi più semplici di scrivere, distribuire e testare il codice Solidity
+è usare :
+
+1. [L'ambiente di sviluppo online Remix](https://remix.ethereum.org/)
+2. [Il wallet Metamask](https://metamask.io/).
+
+Per cominciare, [scarichiamo l'estesione per browser di Metamask](https://metamask.io/).
+
+Una volta installata, potremo iniziare ad usare Remix. Il codice seguente è
+pre-inizializzato, ma prima di addentrarci, diamo un'occhiata a qualche
+trucchetto per iniziare ad usare Remix. Carica tutto il necessario [clickando su questo link](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=f490c0d51141dd0515244db40bbd0c17&runs=200).
+
+1. Scegli il compilatore per Solidity
+
+![Solidity-in-remix](../images/solidity/remix-solidity.png)
+
+2. Apri il file che si caricherà su quel link
+
+![Solidity-choose-file](../images/solidity/remix-choose-file.png)
+
+3. Compila il file
+
+![Solidity-compile](../images/solidity/remix-compile.png)
+
+4. Fai il deploy
+
+![Solidity-deploy](../images/solidity/remix-deploy.png)
+
+5. Smanetta con i contratti
+
+![Solidity-deploy](../images/solidity/remix-interact.png)
+
+Hai distribuito il tuo primo contratto! Congratulazioni!
+
+Potrai testarlo e smanettare con le funzioni già definite. Dai un'occhiata ai
+commenti per scoprire cosa fanno.
+
+
+## Lavorare su una testnet
+
+Distribuire e testare su una testnet è il modo più accurato per mettere alla
+prova i tuoi smart contract in Solidity. Per farlo procuriamoci prima degli ETH
+di test dalla testnet Kovan.
+
+[Entra in questo Gitter Channel](https://gitter.im/kovan-testnet/faucet) e
+scrivici l'indirizzo del tuo wallet Metamask.
+
+Sul tuo Metamask, dovrai cambiare la testnet in `Kovan`.
+
+![Solidity-in-remix](../images/solidity/metamask-kovan.png)
+
+Riceverai degli Ethereum di test gratuiti. Abbiamo bisogno di Ethereum per
+distribuire degli smart contract su una testnet.
+
+Nell'esempio precedente non avevamo usato una testnet, ma avevamo distribuito
+su un ambiente virtuale fittizio. Quando si lavora su una testnet, possiamo
+davvero monitorare e interagire con i nostri contratti in maniera persistente.
+
+Per distribuire su una testnet, allo step `#4 Fai il deploy`, cambia
+l'`environment` selezionato in `injected web3`. In questo modo verrà usato
+come network su cui fare il deploy qualsiasi network selezionato sul tuo
+Metamask.
+
+![Solidity-in-remix](../images/solidity/remix-testnet.png)
+
+Per ora continua a usare la `Javascript VM` a meno che non ti sia detto di
+cambiarla. Quando distribuisci su una testnet, Metamask aprirà un pop up che
+ti chiederà di "confermare" la transazione. Premi `yes` e dopo un certo lasso
+di tempo, ti apparirà la stessa interfaccia per il contratto nella parte
+inferiore dello schermo.
+
+
+```javascript
+// Iniziamo con un semplice contratto su una Banca
+// Permette di depositare, prelevare e fare l'estratto conto
+
+// simple_bank.sol (nota l'estensione .sol)
+/* **** INIZIO DELL'ESEMPIO **** */
+
+// Dichiara la versione del compilatore per il file sorgente
+pragma solidity ^0.6.6;
+
+// Inizia con il commento Natspec (i tre slash)
+// viene usato per la documentazione - e per i dati descrittivi per gli elementi
+// dell'interfaccia utente / azioni
+
+/// @title SimpleBank
+/// @author nemild
+
+/* 'contract' somiglia a 'class' in altri linguaggi (ha variabili di classe,
+ereditarietà, etc.) */
+contract SimpleBank { // CapWords
+ // Dichiariamo le variabili di stato fuori dalle funzioni, persisteranno
+ // durante tutta la vita del contratto
+
+ // i dizionari mappano gli indirizzi con i saldi
+ // fai sempre attenzione agli overflow attack che sfruttano i numeri
+ mapping (address => uint) private balances;
+
+ // "private" significa che che altri contratti non possono leggere i
+ // saldi ma le informazioni restano visibili ad altri attori sulla blockchain
+
+ address public owner;
+ // 'public' lo rende leggibile dall'esterno (ma non modificabile) dagli
+ // utenti e dai contratti
+
+ // Gli 'event' pubblicano le azioni in modo che siano ascoltabili da
+ // listener esterni
+ event LogDepositMade(address accountAddress, uint amount);
+
+ // I 'constructor' possono ricevere uno o più parametri; Si può
+ // dichiarare un solo costruttore
+ constructor() public {
+ // 'msg' fornisce i dettagli sul messaggio che è stato mandato al contratto
+ // 'msg.sender' è chi invoca il contratto (l'indirizzo di chi lo crea)
+ owner = msg.sender;
+ }
+
+ /// @notice Deposita ether nella banca
+ /// @return Il saldo dell'utente dopo che è stato effettualto il deposito
+ function deposit() public payable returns (uint) {
+ // Usiamo 'require' per testare gli input dell'utente, 'assert' per gli
+ // invarianti interni. Qui ci assicuriamo di non avere a che fare con
+ // un overflow
+ require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
+
+ balances[msg.sender] += msg.value;
+ // Non servono "this." o "self." con le variabili di stato
+ // Tutti i valori iniziali delle variabili sono impostati automaticamente
+ // al valore di default per quel tipo di dato
+
+ emit LogDepositMade(msg.sender, msg.value); // Fa scattare l'evento
+
+ return balances[msg.sender];
+ }
+
+ /// @notice Preleva ether dalla banca
+ /// @dev Non restituisce gli ether inviati in eccesso
+ /// @param withdrawAmount L'importo che si vuole ritirare
+ /// @return remainingBal
+ function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
+ require(withdrawAmount <= balances[msg.sender]);
+
+ // Notiamo come per prima cosa scaliamo i soldi dal saldo, prima di
+ // invarli. Ogni .transfer/.send in questo contratto può chiamare una
+ // funzione esterna. Questa cosa potrebbe permettere a chi invoca la
+ // funzione di richiedere un importo maggiore del suo saldo usando
+ // una chiamata ricorsiva. Miriamo ad aggiornare lo stato prima che sia
+ // chiamata una funzione esterna, incluse .transfer/.send
+ balances[msg.sender] -= withdrawAmount;
+
+ // Qui lancia automaticamente un errore se fallisce, il che implica
+ // che il saldo (non più aggiornato) viene ripristinato a prima della
+ // transazione
+ msg.sender.transfer(withdrawAmount);
+
+ return balances[msg.sender];
+ }
+
+ /// @notice Recupera il saldo
+ /// @return Il saldo dell'utente
+ // 'view' (ex: constant) impedisce alle funzioni di modificare lo stato
+ // delle variabili; consente alle le funzioni di essere disponibili in
+ // locale/fuori dalla blockchain
+ function balance() view public returns (uint) {
+ return balances[msg.sender];
+ }
+}
+// ** FINE DELL'ESEMPIO **
+
+
+// Passiamo alle basi di Solidity
+
+// 1. TIPI DI DATO E I LORO METODI
+// uint viene usato per gli importi in valuta (non ci sono double o float)
+// e per le date (in unix time)
+uint x;
+
+// int di 256 bit, non possono essere modificati dopo l'istanziazione
+int constant a = 8;
+int256 constant a = 8; // stesso effetto della riga prima, qui viene
+// dichiarato esplicitamente che è di 256 bit
+uint constant VERSION_ID = 0x123A1; // Una costante esadecimale
+// con 'constant', il compilatore rimpiazza ogni occorrenza con il valore
+
+// Tutte le variabili di stato (quelle fuori da una funzione)
+// sono 'interne' di default e accessibili SOLO dall'interno del contratto
+// e da tutti contratti che le ereditano
+// Bisogna usare esplicitamente 'public' per consentire l'accesso dai contratti
+// esterni
+int256 public a = 8;
+
+// Per int e uint possiamo esplicitamente assegnare una dimensione tra 8 e 256
+// es. int8, int16, int24
+uint8 b;
+int64 c;
+uint248 e;
+
+// Attenzione a non andare in overflow e a proteggersi dagli attacchi che lo fanno
+// Ad esempio per quanto rigrada l'addizione, conviene fare:
+uint256 c = a + b;
+assert(c >= a); // 'assert' testa gli invarianti interni; require viene usato
+// per gli input
+// Per altri esempi di problemi comuni con le operazioni aritmentiche, dai una
+// occhiata alla Zeppelin's SafeMath library
+// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
+
+
+// Non ci sono funzioni random built-in, puoi ottenere un numero pseudo-casuale
+// hashando l'ultimo blockhash, o ottenere un numero realmente casuale usando
+// qualcosa come Chainlink VRF.
+// https://docs.chain.link/docs/get-a-random-number
+
+// Conversione di tipo
+int x = int(b);
+
+bool b = true; // oppure 'var b = true;' per l'inferenza di tipo
+
+// Indirizzi - contengono indirizzi Ethereum di 20 byte/160 bit
+// Non sono consentite operazioni aritmetiche
+address public owner;
+
+// Tipi di account:
+// Contract account: l'indirizzo viene impostato quando lo si crea (funzione con
+// l'indirzzo di chi lo crea, il numero della transazione inviata)
+// External Account: (persona/enitità esterna): l'indirizzo viene creato dalla
+// chiave pubblica
+
+// Aggiungi il campo 'public' per indicare che è pubblico/accessibile dall'esterno
+// un getter viene creato automaticamente, ma NON un setter
+
+// Si possono mandare ether a tutti gli indirizzi
+owner.transfer(SOME_BALANCE); // fallisce e, in tal caso, ripristina
+// lo stato precedente
+
+// Possiamo anche usare la funzione di livello più basso .send, che restituisce
+// false se fallisce
+if (owner.send) {} // RICORDA: metti la send in un 'if' dato che gli indirizzi
+// usati nei contratti hanno delle funzioni, che vengono eseguite quando viene
+// fatta una send, che possono fallire.
+// Inoltre fai attenzione a scalare i saldi PRIMA di provare a fare una send,
+// dato il rischio di chiamate riscorsive che potrebbero prosciugare il contratto
+
+// Possiamo controllare il saldo
+owner.balance; // il saldo del propietario (utente o contratto)
+
+
+// I Byte sono disposibili in dimensioni da 1 a 32
+byte a; // 'byte' è la stessa cosa di 'bytes1'
+bytes2 b;
+bytes32 c;
+
+// Byte con dimensione dinamica
+bytes m; // Un array particolare, la stessa cosa dell'array 'byte[]' (ma scritto stringato)
+// È più dispendioso di byte1-byte32, che di solito sono preferibili
+
+// come bytes, ma non permette di accedere alla lunghezza o all'indice (per ora)
+string n = "hello"; // salvato in UTF8, nota i doppi apici, non singoli
+// le utility function per le stringhe saranno aggiunte in futuro
+// sono preferibili bytes32/bytes, dato che UTF8 occupa più memoria
+
+// Inferenza di tipo
+// 'var' fa inferenza di tipo a seconda del primo assegnamento,
+// non può essere usata tra i parametri di una funzione
+var a = true;
+// da usare con cautela, può inferire un tipo errato
+// es. un int8 quando un contatore dev'essere un int16
+
+// var può essere usata per assegnare una funzione ad una variabile
+function a(uint x) returns (uint) {
+ return x * 2;
+}
+var f = a;
+f(22); // chiamata
+
+// di default, tutte le variabili sono impostate a 0 durante l'istanziazione
+
+
+// Delete può essere chiamato sulla maggior parte dei valori
+// (NON distrugge il valore, ma lo setta a 0, il valore did default)
+uint x = 5;
+
+
+// Destructuring/Tuple
+(x, y) = (2, 7); // assegna/scambia più valori
+
+
+// 2. STRUTTURE DATI
+// Array
+bytes32[5] nicknames; // array statico
+bytes32[] names; // array dinamico
+uint newLength = names.push("John"); // aggiungere un elemento restituisce
+// la nuova dimensione dell'array
+// Dimesione
+names.length; // ottenere la dimensione
+names.length = 1; // la dimensione può essere assegnata (solo per gli array nello storage)
+
+// array multidimensionali
+uint[][5] x; // array con 5 array dinamici (ordine opposto rispetto ad
+// altri linguaggi)
+
+// Dizionari (da un tipo qualsiasi a un tipo qualsiasi)
+mapping (string => uint) public balances;
+balances["charles"] = 1;
+// il risultato balances["ada"] è 0, tutte le chiavi non settate
+// restituiscono zero
+// 'public' permette che si possa fare questo da un altro contratto:
+contractName.balances("charles"); // restituisce 1
+// 'public' ha creato getter (ma non un setter), come il seguente:
+function balances(string _account) returns (uint balance) {
+ return balances[_account];
+}
+
+// Mapping annidati
+mapping (address => mapping (address => uint)) public custodians;
+
+// Fare una delete
+delete balances["John"];
+delete balances; // assegna 0 a tutti gli elementi
+
+// Diversamente da altri linguaggi NON si può iterare tra gli elementi di un
+// mapping senza conoscere le chiavi - ma si può costruire una struttura dati a monte
+// che lo faccia
+
+// Strutture dati
+struct Bank {
+ address owner;
+ uint balance;
+}
+Bank b = Bank({
+ owner: msg.sender,
+ balance: 5
+});
+// oppure
+Bank c = Bank(msg.sender, 5);
+
+c.balance = 5; // imposta ad un nuovo valore
+delete b;
+// reimposta, imposta tutte le variabili della struttura a 0, tranne i mapping
+
+// Enumerazioni
+enum State { Created, Locked, Inactive }; // di solito si usano per gli automi a stati finiti
+State public state; // Dichiara una variabile da un enum
+state = State.Created;
+// Le enum possono essere convertite esplicitamente in int
+uint createdState = uint(State.Created); // 0
+
+// Data location: Memory vs. storage vs. calldata - tutti i tipi complessi
+// (array, struct) hanno una data location
+// 'memory' non è persistente, 'storage' sì
+// Il default è 'storage' per varibili locali e di stato;
+// 'memory' per i parametri delle funzioni
+// Lo stack può contenere poche varaibili locali
+
+// Per la maggior parte dei tipi, si può impostare esplicitamente
+// quale data location usare
+
+
+// 3. Operatori semplici
+// Ci sono operatori logici, a bit e aritmetici
+// Potenza: **
+// Or esclusivo: ^
+// Negazione bitwise: ~
+
+
+// 4. Variabili globali degne di nota
+// ** this **
+this; // indirizzo del contratto
+// di solito si usa per trasferire altrove il saldo rimanente
+// al termine della vita del contratto
+this.balance;
+this.someFunction(); // invoca una funzione esterna tramite chiamata,
+// non attraverso un salto interno
+
+// ** msg - Il messaggio corrente ricevuto dal contratto **
+msg.sender; // indirizzo di chi ha inviato msg
+msg.value; // l'importo di ether forniti a questo contratto espresso in "wei",
+// la funzione dovrebbe essere marcata come "payable"
+msg.data; // in bytes, tutti gli argomenti del messaggio
+msg.gas; // 'gas' restante
+
+// ** tx - Questa transazione **
+tx.origin; // l'indirizzo di chi ha avviato questa transazione
+tx.gasprice; // il prezzo del "gas" per la transazione
+
+// ** block - Informazioni sul blocco attuale **
+now; // ora corrente (approssimatamente), alias di block.timestamp (in Unix time)
+// Da notare come può essere manipolata dai miner, quindi da usare con cautela
+
+block.number; // numero del blocco attuale
+block.difficulty; // difficulty del blocco attuale
+block.blockhash(1); // restituisce un bytes32, funziona solo per i 256 blocchi
+// più recenti
+block.gasLimit();
+
+// ** storage - Memoria persistente (in hash) **
+storage['abc'] = 'def'; // mappa da parole di 256 bit a parole di 256 bit
+
+
+// 4. FUNZIONI E ALTRO
+// A. Funzioni
+// Una semplice funzione
+function increment(uint x) returns (uint) {
+ x += 1;
+ return x;
+}
+
+// Le funzioni possono restituire molti valori,
+// e visto che i valori di ritorno vengono dichiarati prima
+// non è richiesta un'instruzione return esplicita
+function increment(uint x, uint y) returns (uint x, uint y) {
+ x += 1;
+ y += 1;
+}
+// Chiama la funzione di cui sopra
+uint (a,b) = increment(1,1);
+
+// 'view' (un alias di 'constant')
+// indica che la funzione non cambia / non può cambiare le variabili persistenti
+// Le funzioni definite con view vengono eseguite localmente, non sulla blockchain
+// N.B. la keyword constant sarà presto deprecata
+uint y = 1;
+
+function increment(uint x) view returns (uint x) {
+ x += 1;
+ y += 1; // questa riga fallirebbe
+ // y è una variabile di stato, e non può essere cambiata in una funzione di view
+}
+
+// 'pure' è più restrittivo di 'view' o 'constant', e non
+// permette nemmeno di leggere le varaibili di stato
+// In realtà è più complicato, per approfondire su
+// view/pure:
+// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions
+
+// Modificatori di visibilità per le funzioni
+// Possono essere messi vicino a 'view' e includono:
+// public - visibile esternamente e internamente (di default per function)
+// external - visible solo esternamente (comprese le chiamate fatte con this.)
+// private - visibile solo dal contratto attuale
+// internal - visibile solo dal contratto attuale, e da quelli che ne derivano
+
+// Di solito è una buona idea marcare esplicitamente ogni funzione
+
+// Le funzioni sono hoisted e si può assegnare una funzione ad una variabile
+function a() {
+ var z = b;
+ b();
+}
+
+function b() {
+
+}
+
+// Tutte le funzioni che ricevono ether devono essere dichiarate come 'payable'
+function depositEther() public payable {
+ balances[msg.sender] += msg.value;
+}
+
+
+// I cicli sono da preferire alla ricorsione
+// (la profondità massima dello stack è 1024)
+// Inoltre, non impostare dei loop senza limiti,
+// perchè potresti raggiungere il limite per il gas
+
+// B. Eventi
+// Gli eventi notificano a terze parti; è facile ispezionare e
+// accedere agli eventi al di fuori della blockchain (con client leggeri);
+// Tipicamente si dichiarano dopo i parametri del contratto
+
+// Tipicamente, sono capitalized - si usa Log come prefisso per esplicitarli
+// meglio ed evitare che si confondano con una chiamata a funzione
+
+// Dichiarazione
+event LogSent(address indexed from, address indexed to, uint amount);
+// Da notare le prime lettere maiuscole
+
+// Chiamata
+LogSent(from, to, amount);
+
+/**
+
+Una terza parte esterna (entità o contratto), può osservare usando
+la libreria Javascript Web3:
+
+// Quel che se segue è codice Javascript, non Solidity
+Coin.LogSent().watch({}, '', function(error, result) {
+ if (!error) {
+ console.log("Trasferimento valuta: " + result.args.amount +
+ " la valuta è stata mandata da " + result.args.from +
+ " a " + result.args.to + ".");
+ console.log("I saldi ora sono:\n" +
+ "Mittente: " + Coin.balances.call(result.args.from) +
+ "Destinatario: " + Coin.balances.call(result.args.to));
+ }
+}
+**/
+
+// È prassi che un contratto dipenda da un altro (es. che dipenda
+// dai tassi di cambio forniti da un altro contratto)
+
+// C. Modifier
+// I modifier validano gli input per conto dele funzioni verificando ad esempio
+// il saldo minimo o l'autenticazione dell'utente;
+// sono simili alle calusole di guardia di altri linguaggi
+
+// '_' (underscore) viene spesso posizionato nell'ultima riga del body, e indica
+// che la funzione chiamata dev'essere posizionata lì
+modifier onlyAfter(uint _time) { require (now >= _time); _; }
+modifier onlyOwner { require(msg.sender == owner) _; }
+// usate comunemente negli automi a stati finiti
+modifier onlyIfStateA (State currState) { require(currState == State.A) _; }
+
+// Si dichiarano appena dopo la definizione di una funzione
+function changeOwner(newOwner)
+onlyAfter(someTime)
+onlyOwner()
+onlyIfState(State.A)
+{
+ owner = newOwner;
+}
+
+// L'underscore può essere messo prima della fine del body,
+// ma un'istruzione di ritorno esplicita lo salterebbe,
+// quindi è da usare con cautela
+modifier checkValue(uint amount) {
+ _;
+ if (msg.value > amount) {
+ uint amountToRefund = amount - msg.value;
+ msg.sender.transfer(amountToRefund);
+ }
+}
+
+
+// 6. ISTRUZIONI CONDIZIONALI E CICLI
+
+// Troviamo tutte le istruzioni condizionali di base - incluse if/else, for,
+// while, break, continue e return - ma non c'è lo switch
+
+// La sintassi è la stessa di javascript, ma non esiste la conversione di tipo
+// in booleano dai non booleani (bisogna usare gli operatori logici per
+// ottenere il valore boolean)
+
+// Bisogna stare attenti i loop che iterano in base al comportamento
+// dell'utente, dato che i contratti hanno un tetto massimo di gas
+// per blocco di codice e falliranno se lo superano
+// Ad esempio:
+for(uint x = 0; x < refundAddressList.length; x++) {
+ refundAddressList[x].transfer(SOME_AMOUNT);
+}
+
+// Ci sono due errori nel codice precedente:
+// 1. Un fallimento su una transfer impedisce al loop di completare tutti
+// i cicli, bloccando dei soldi;
+// 2. Questo loop potrebbe essere arbitrariamente lungo (si basa sul numero
+// degli utenti che hanno diritto al rimborso), quindi potrebbe fallire sempre
+// se supera il tetto massimo di gas per blocco;
+// Come soluzione, si permette agli utenti di prelevare
+// individualmente dal loro subaccount e segnare il rimborso come riscosso
+// Ad es. preferire pull payments ai push payment
+
+
+// 7. OGGETTI/CONTRATTI
+
+// A. Invocare un contratto esterno
+contract InfoFeed {
+ function info() payable returns (uint ret) { return 42; }
+}
+
+contract Consumer {
+ InfoFeed feed; // punta ad un contratto sulla blockchain
+
+ // Imposta il feed sull'istanza del contratto esistente
+ function setFeed(address addr) {
+ // fare attenzione alla conversione di tipo automatica;
+ // il costruttore non viene invocato
+ feed = InfoFeed(addr);
+ }
+
+ // Imposta il feed ad una nuova istanza del contratto
+ function createNewFeed() {
+ feed = new InfoFeed(); // viene creata una nuova istanza;
+ // viene invocato il costruttore
+ }
+
+ function callFeed() {
+ // le parentesi finali invocano il contratto, opzionalmente si può
+ // specificare un importo custom di ether o di gas
+ feed.info.value(10).gas(800)();
+ }
+}
+
+// B. ereditarietà
+
+// Conta l'ordine, l'ultimo contratto ereditato (es. 'def') può andare
+// in overriding su parti dei contratti precedentemente ereditati
+contract MyContract is abc, def("a custom argument to def") {
+
+// Funzione in overriding
+ function z() {
+ if (msg.sender == owner) {
+ def.z(); // invoca la funzione overridden da def
+ super.z(); // chiama la funzione overridden del padre
+ }
+ }
+}
+
+// Funzioni astratte
+function someAbstractFunction(uint x);
+// non possono essere compilate, vengono usate nei contratti base/astratti
+// e poi verranno implementate
+
+// C. Import
+
+import "filename";
+import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
+
+
+// 8. ALTRE KEYWORD
+
+// A. Selfdestruct
+// autodistrugge il contratto corrente, inviando i fondi ad un indirizzo
+// (di solito il creatore)
+selfdestruct(SOME_ADDRESS);
+
+// rimuove il codice e quanto in memoria dal blocco corrente e da tutti i blocchi futuri
+// aiuta ad alleggerire i client, ma le informazioni precedenti continueranno
+// a persistere sulla blockchain
+
+// È un pattern comune, permette al proprietario di terminare il contratto
+// e ricevere i fondi rimasti
+function remove() {
+ if(msg.sender == creator) { // Solo il creatore del contratto può farlo
+ selfdestruct(creator); // Cessa l'attività del contratto, trasferisce i fondi
+ }
+}
+
+// Si potrebbe voler disattivare il contratto manualmente, anzichè usare una
+// selfdestruct (gli ether inviati ad un contratto dopo una selfdestruct
+// vengono persi)
+
+
+// 9. NOTE SUL DESIGN DEI CONTRATTI
+
+// A. Offruscamento
+// Tutte le variabili sono pubblicamente visibili sulla blockchain, quindi
+// qualsiasi informazione privata ha bisogno di essere offruscata (es. hash con una
+// chiave segreta)
+
+// Passi: 1. Impegnarsi pagare una certa cifra, 2. Rivelare l'impegno preso
+keccak256("una_puntata_d_asta", "un segreto"); // impegno
+
+// in futuro, l'invocazione della funzione rivelatrice del contratto
+// mostrerà la puntata con il segreto che produce lo SHA3
+reveal(100, "ilMioSegreto");
+
+// B. Ottimizzazione della memoria (storage)
+// Scrivere dati sulla blockchain può essere costoso visto che vengono
+// conservati per sempre; siamo incoraggati ad usare la memoria in maniera
+// scaltra (un giorno la compilazione migliorerà, ma per ora è vantaggioso
+// pianificare le strutture dati da usare - e conservarne il minimo possibile
+// sulla blockchain)
+
+// I costi per conservare cose come array multidimensionali sono spesso alti
+// (costa conservare dati - non dichiarare variabili parzialmente vuote)
+
+// C. Accesso ai dati sulla blockchain
+// Non si può impedire alle persone o ai computer di leggere il contenuto
+// o lo stato delle transazioni
+
+// Anche se 'private' non permette agli altri *contratti* di leggere alcune
+// informazioni direttamente, qualsiasi altro attore può leggerle
+// sulla blockchain
+
+// Tutti i dati, dall'inizio, vegono conservati sulla blockchain e
+// tutti possono accedere alle informazioni passate e ai cambiamenti futuri
+
+// D. Oracle e dati esterni
+// Gli oracle consentono di interagire con i tuoi smart contract
+// al di fuori della blockchain.
+// Vengono usati per ricevere informazioni dal mondo reale, mandare
+// richieste post al mondo reale o vice versa.
+
+// Anche le implementazioni che sfruttano l'ora vengono fatte attraverso
+// gli oracle, visto che i contratti devono essere chiamati direttamente e
+// non possono fare una "subscribe" a un certo orario.
+// Data la decentralizzazione degli smart contract, vorrai ricevere informazioni
+// in maniera decentralizzata, altrimenti rischi di ricreare l'accentramento
+// che la progettazione degli smart contract si prefigge di prevenire.
+
+// Il modo migliore di ottenere e usare dati decentralizzati già pronti
+// è attraverso i Chainlink Data Feeds
+// https://docs.chain.link/docs/get-the-latest-price
+// Possiamo fare riferimento a certe informazioni della blockchain
+// che sono già state aggregate da più fonti e ridistribuite on-chain,
+// usandole come "banche dati" di fonti di informazione.
+
+// Puoi vedere altri esempi che effettuano chiamate alle API qui:
+// https://docs.chain.link/docs/make-a-http-get-request
+
+// E ovviamente puoi costruire la tua rete di orace, ma assicurati di sapere
+// quant'è accentrata o decentralizzata la tua applicazione.
+
+// Mettere su una rete di oracle per conto tuo
+
+// E. Cron Job
+// I contratti devono essere chiamati manualmente per gestire lo scheduling
+// in base all'orario; si può creare un codice esterno che li pinghi reglarmente
+// oppure fornire degli incentivi (ether) a qualcun'altro che lo faccia
+
+// F. Pattern Observer
+// Un pattern observer permette di iscriversi come osservatore e
+// registrare una funzione che verrà chiamata dall'oracle
+// (N.B. l'oracolo paga perchè sia eseguita quest'azione)
+// Ci sono alcune somoglianze nella registrazione con Pub/sub
+
+// Questo è un contratto astratto che importano sia il client che il server
+// Il client dovrebbe implementarlo
+contract SomeOracleCallback {
+ function oracleCallback(int _value, uint _time, bytes32 info) external;
+}
+
+contract SomeOracle {
+ SomeOracleCallback[] callbacks; // array di tutti gli osservatori iscritti
+
+ // Osservatori iscritti
+ function addSubscriber(SomeOracleCallback a) {
+ callbacks.push(a);
+ }
+
+ function notify(value, time, info) private {
+ for(uint i = 0;i < callbacks.length; i++) {
+ // tutti gli osservatori iscritti dovranno implementare la oracleCallback
+ callbacks[i].oracleCallback(value, time, info);
+ }
+ }
+
+ function doSomething() public {
+ // Codice che fa qualcosa
+
+ // Notifica a tutti gli iscritti
+ notify(_value, _time, _info);
+ }
+}
+
+// Il contratto client può aggiungersi agli iscritti (con addSubscriber)
+// del contratto SomeOracle, importando SomeOracleCallback
+
+// G. Automi a stati finiti
+// vedi l'esempio sotto che usa enum per lo stato e il modifier inState
+```
+
+Prova l'esempio completo qui sotto [usando remix e la `Javascript VM`](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200)
+
+```javascript
+// *** ESEMPIO: Un esempio di crowdfunding (molto simile a Kickstarter) ***
+// ** START EXAMPLE **
+
+// CrowdFunder.sol
+pragma solidity ^0.6.6;
+
+/// @title CrowdFunder
+/// @author nemild
+contract CrowdFunder {
+ // Variabili impostate alla creazione dal creatore
+ address public creator;
+ address payable public fundRecipient; // il creatore può essere diverso
+ // da chi riceve i fondi, che dev'essere payable
+ uint public minimumToRaise; // è richiesto per chiedere il finanziamento,
+ // altrimenti tutti ricevono un rimborso
+ string campaignUrl;
+ byte version = "1";
+
+ // Strutture dati
+ enum State {
+ Fundraising,
+ ExpiredRefund,
+ Successful
+ }
+ struct Contribution {
+ uint amount;
+ address payable contributor;
+ }
+
+ // Variabili di stato
+ State public state = State.Fundraising; // inizializzato alla creazione
+ uint public totalRaised;
+ uint public raiseBy;
+ uint public completeAt;
+ Contribution[] contributions;
+
+ event LogFundingReceived(address addr, uint amount, uint currentTotal);
+ event LogWinnerPaid(address winnerAddress);
+
+ modifier inState(State _state) {
+ require(state == _state);
+ _;
+ }
+
+ modifier isCreator() {
+ require(msg.sender == creator);
+ _;
+ }
+
+ // Aspetta 24 settimane dopo l'ultimo cambio di stato prima di consentire
+ // che in contratto venga distrutto
+ modifier atEndOfLifecycle() {
+ require(((state == State.ExpiredRefund || state == State.Successful) &&
+ completeAt + 24 weeks < now));
+ _;
+ }
+
+ function crowdFund(
+ uint timeInHoursForFundraising,
+ string memory _campaignUrl,
+ address payable _fundRecipient,
+ uint _minimumToRaise)
+ public
+ {
+ creator = msg.sender;
+ fundRecipient = _fundRecipient;
+ campaignUrl = _campaignUrl;
+ minimumToRaise = _minimumToRaise;
+ raiseBy = now + (timeInHoursForFundraising * 1 hours);
+ }
+
+ function contribute()
+ public
+ payable
+ inState(State.Fundraising)
+ returns(uint256 id)
+ {
+ contributions.push(
+ Contribution({
+ amount: msg.value,
+ contributor: msg.sender
+ }) // usiamo un array per iterare
+ );
+ totalRaised += msg.value;
+
+ emit LogFundingReceived(msg.sender, msg.value, totalRaised);
+
+ checkIfFundingCompleteOrExpired();
+ return contributions.length - 1; // restituisce l'id
+ }
+
+ function checkIfFundingCompleteOrExpired()
+ public
+ {
+ if (totalRaised > minimumToRaise) {
+ state = State.Successful;
+ payOut();
+
+ // qui si può incentivare chi ha provocato il cambiamento di stato
+ } else if ( now > raiseBy ) {
+ state = State.ExpiredRefund; // ora i finanziatori possono avere
+ // il rimborso chiamando getRefund(id)
+ }
+ completeAt = now;
+ }
+
+ function payOut()
+ public
+ inState(State.Successful)
+ {
+ fundRecipient.transfer(address(this).balance);
+ LogWinnerPaid(fundRecipient);
+ }
+
+ function getRefund(uint256 id)
+ inState(State.ExpiredRefund)
+ public
+ returns(bool)
+ {
+ require(contributions.length > id && id >= 0 && contributions[id].amount != 0 );
+
+ uint256 amountToRefund = contributions[id].amount;
+ contributions[id].amount = 0;
+
+ contributions[id].contributor.transfer(amountToRefund);
+
+ return true;
+ }
+
+ function removeContract()
+ public
+ isCreator()
+ atEndOfLifecycle()
+ {
+ selfdestruct(msg.sender);
+ // il creatore riceve tutti i fondi che non sono stati riscossi
+ }
+}
+// ** END EXAMPLE **
+
+```
+
+Qualche altra funzionalità.
+
+```javascript
+// 10. ATRE FUNZIONALITA' NATIVE
+
+// Unità di valuta
+// La valuta viene definita partendo dai wei, l'unità più piccola di Ether
+uint minAmount = 1 wei;
+uint a = 1 finney; // 1 ether == 1000 finney
+// Per altre unità, vedi: http://ether.fund/tool/converter
+
+// Unità temporali
+1 == 1 second
+1 minutes == 60 seconds
+
+// Le unità temporali si possono moltiplicare, visto che non vegono salvate
+// nelle variabili
+uint x = 5;
+(x * 1 days); // 5 giorni
+
+// Attenzione ad usare l'operatore di uguaglianza con i secondi/anni bisestili
+// (sono da preferire maggiore/minore di)
+
+// Crittografia
+// Tutte le stringhe che vengono passate vengono concatenate prima di
+// calcolare l'hash
+sha3("ab", "cd");
+ripemd160("abc");
+sha256("def");
+
+
+// 11.SICUREZZA
+
+// I bug possono essere disastrosi per i contratti Ethereum e anche
+// i pattern comuni di Solidity potrebbero riverlarsi degli antipattern
+
+// Dai un'occhiata ai link sulla sicurezza alla fine di questo documento
+
+
+// 12. FUNZIONI DI BASSO LIVELLO
+// call - è di basso livello, non viene usata spesso, perchè non è type safe
+successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2');
+
+// callcode - Il codice all'indirizzo target viene eseguito *contestualmente*
+// alla chiamata del contratto
+// fornisce le stesse funzionalità di una libreria
+someContractAddress.callcode('function_name');
+
+
+// 13. NOTE SULLO STILE
+// Basate sulla guida allo stile PEP8 di Python
+// Guida completa allo stile: http://solidity.readthedocs.io/en/develop/style-guide.html
+
+// Riassunto veloce:
+// 4 spazi per l'indentazione
+// Due righe per separare la dichiarazione dei contratti
+// (e altre dichirazioni top level)
+// Evitare spazi ai lati interni delle parentesi tonde
+// Si possono omettere le parentesi graffe per statement monolinea (if, for, etc)
+// L'else dovrebbe essere posizionato su una riga a se
+
+// 14. COMMENTI NATSPEC
+// usati per la documentazione, commenti e UI esterne
+
+// Natspec dei contratti - sempre sopra la definizione del contratto
+/// @title Titolo del contratto
+/// @author Nome dell'autore
+
+// Natspec delle funzioni
+/// @notice informazioni su quel che fa la funzione; mostrate quando la funzione viene eseguita
+/// @dev Documentazione della funzione per sviluppatori
+
+// Natspec dei parametri/valori di ritorno delle funzioni
+/// @param someParam Una descrizione di quel che fa il parametro
+/// @return Descrizione del valore di ritorno
+```
+
+## Risorse Aggiuntive
+- [Documentazione di Solidity](https://solidity.readthedocs.org/en/latest/)
+- [Tutorial Chainlink per Principianti](https://docs.chain.link/docs/beginners-tutorial)
+- [Best Practice per Smart Contract](https://github.com/ConsenSys/smart-contract-best-practices)
+- [Superblocks Lab - Ambiente di sviluppo su browser per Solidity](https://lab.superblocks.com/)
+- [EthFiddle - Il JsFiddle di Solidity](https://ethfiddle.com/)
+- [Solidity Editor su Browser](https://remix.ethereum.org/)
+- [Chat Room Gitter su Solidity](https://gitter.im/ethereum/solidity)
+- [Stategie di Progettazione Modulare per Contratti Ethereum](https://docs.erisindustries.com/tutorials/solidity/)
+- [Documentazione Chainlink](https://docs.chain.link/docs/getting-started)
+
+## Framework di Sviluppo per Smart Contract
+- [Hardhat](https://hardhat.org/)
+- [Brownie](https://github.com/eth-brownie/brownie)
+- [Truffle](https://www.trufflesuite.com/)
+
+## Librerie importanti
+- [Zeppelin](https://github.com/OpenZeppelin/openzeppelin-contracts): Librerie che offrono pattern comuni (crowdfuding, safemath, ecc)
+- [Chainlink](https://github.com/smartcontractkit/chainlink): Codice che permette di interagire con dati esterni
+
+## Contratti di esempio
+- [Dapp Bin](https://github.com/ethereum/dapp-bin)
+- [Esempi Defi](https://github.com/PatrickAlphaC/chainlink_defi)
+- [Solidity per Contratti a Piccoli Passi](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
+- [Contratti ConsenSys](https://github.com/ConsenSys/dapp-store-contracts)
+- [Lo stato delle Dapp](http://dapps.ethercasts.com/)
+
+## Sicurezza
+- [Pensando Alla Sicurezza Degli Smart Contract](https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/)
+- [Sicurezza Degli Smart Contract](https://blog.ethereum.org/2016/06/10/smart-contract-security/)
+- [Blog Distribuito di Hacking](http://hackingdistributed.com/)
+
+## Stile
+- [Guida allo Stile di Solidity](http://solidity.readthedocs.io/en/latest/style-guide.html): La guida allo stile di Ethereum deriva in gran parte dalla guida allo stile [PEP 8](https://www.python.org/dev/peps/pep-0008/) di Python.
+
+## Editor
+- [Remix](https://remix.ethereum.org/)
+- [Emacs Modalità Solidity](https://github.com/ethereum/emacs-solidity)
+- [Vim Solidity](https://github.com/tomlion/vim-solidity)
+- Snippet per gli Editor ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc))
+
+## Cose da fare in futuro
+- Nuove keyword: protected, inheritable
+- Lista dei design pattern comuni (throttling, RNG, upgrade di versione)
+-Anti patterns comuni sulla sicurezza
+
+Sentiti libero di mandare una pull request con qualsiasi modifica - o scrivi una mail a nemild -/at-/ gmail
diff --git a/ja-jp/asciidoc.html.markdown b/ja-jp/asciidoc.html.markdown
index 7347589a..af19850a 100644
--- a/ja-jp/asciidoc.html.markdown
+++ b/ja-jp/asciidoc.html.markdown
@@ -5,7 +5,7 @@ contributors:
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
translators:
- ["Ryota Kayanuma", "https://github.com/PicoSushi"]
-filename: asciidoc-ja.md
+filename: asciidoc-ja.adoc
lang: ja-jp
---
diff --git a/ja-jp/yaml-jp.html.markdown b/ja-jp/yaml-jp.html.markdown
new file mode 100644
index 00000000..28a5d870
--- /dev/null
+++ b/ja-jp/yaml-jp.html.markdown
@@ -0,0 +1,193 @@
+---
+language: yaml
+filename: learnyaml-jp.yaml
+contributors:
+- [Leigh Brenecki, 'https://leigh.net.au']
+- [Suhas SG, 'https://github.com/jargnar']
+translators:
+- [haru, 'https://haru52.com/']
+lang: ja-jp
+---
+
+YAMLã¯ãƒ‡ãƒ¼ã‚¿ã®ã‚·ãƒªã‚¢ãƒ©ã‚¤ã‚ºç”¨è¨€èªžã§ã€
+人間ãŒç›´æŽ¥èª­ã¿æ›¸ãã—ã‚„ã™ã„よã†ã«ãƒ‡ã‚¶ã‚¤ãƒ³ã•ã‚Œã¦ã„ã¾ã™ã€‚
+
+YAMLã¯JSONã®åŽ³æ ¼ãªã‚¹ãƒ¼ãƒ‘ーセットã§ã€
+改行ã¨ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆãŒæ§‹æ–‡çš„ã«æ„味をæŒã¤ã¨ã„ã†Pythonã«ä¼¼ãŸä»•æ§˜ã‚’追加ã—ã¦ã„ã¾ã™ã€‚
+ã—ã‹ã—Pythonã¨ã¯ç•°ãªã‚ŠYAMLã§ã¯ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆã«ã‚¿ãƒ–文字を使ã†ã“ã¨ã¯ã§ãã¾ã›ã‚“。
+
+```yaml
+--- # ドキュメント開始
+
+# YAMLã®ã‚³ãƒ¡ãƒ³ãƒˆã¯ã“ã‚“ãªæ„Ÿã˜ã§ã™ã€‚
+
+##############
+# スカラー型 #
+##############
+
+# (ドキュメント全体をå«ã‚€ï¼‰ãƒ«ãƒ¼ãƒˆã‚ªãƒ–ジェクトã¯ãƒžãƒƒãƒ—ã«ãªã‚Šã¾ã™ã€‚
+# ã“ã‚Œã¯ä»–言語ã«ãŠã‘る辞書型ã€ãƒãƒƒã‚·ãƒ¥ã€ã‚ªãƒ–ジェクトãªã©ã¨ç­‰ä¾¡ã§ã™ã€‚
+キー: 値
+別ã®ã‚­ãƒ¼: 別ã®å€¤ã€‚
+数値: 100
+指数表記: 1e+12
+# 1 ã¯booleanã§ãªã数値ã¨ã—ã¦è§£é‡ˆã•ã‚Œã¾ã™ã€‚
+# ã‚‚ã—booleanã¨ã—ã¦è§£é‡ˆã—ã¦ã»ã—ã„å ´åˆã¯trueを使ã„ã¾ã™
+boolean: true
+null値: null
+スペースを å«ã‚€ キー: 値
+# 文字列をクォートã§å›²ã†å¿…è¦ãŒãªã„ã“ã¨ã«æ³¨æ„ã—ã¦ãã ã•ã„。
+# ã—ã‹ã—囲ã†ã“ã¨ã‚‚ã§ãã¾ã™ã€‚
+ã—ã‹ã—: 'クォートã§å›²ã¾ã‚ŒãŸæ–‡å­—列。'
+'キーもクォートã§å›²ãˆã¾ã™ã€‚': "keyã®ä¸­ã§ ':' を使ã„ãŸã„ã¨ãã«æœ‰ç”¨ã§ã™ã€‚"
+シングルクォート: 'ã«ã¯ ''1ã¤ã®'' エスケープパターンãŒã‚ã‚Šã¾ã™'
+ダブルクォート: "ã«ã¯å¤šãã®ã‚¨ã‚¹ã‚±ãƒ¼ãƒ—パターンãŒã‚ã‚Šã¾ã™ï¼š\", \0, \t, \u263A,
+\x0d\x0a == \r\n, ãªã©ã€ä»–ã«ã‚‚ã‚ã‚Šã¾ã™ã€‚"
+# UTF-8/16/32文字ã¯ã‚¨ãƒ³ã‚³ãƒ¼ãƒ‰ã•ã‚Œã¦ã„ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™
+上付ã2: \u00B2
+
+# 複数行ã®æ–‡å­—列ã¯ï¼ˆ| を使ã†ï¼‰ã€Œãƒªãƒ†ãƒ©ãƒ«ãƒ–ロックã€ã€
+# ã¾ãŸã¯ã€ï¼ˆ'>' を使ã†ï¼‰ã€ŒæŠ˜ã‚Šç•³ã¿ãƒ–ロックã€ã¨ã—ã¦æ›¸ãã“ã¨ãŒã§ãã¾ã™
+リテラルブロック: |
+ ã“ã®æ–‡ç« ã®ãƒ–ロック全体ãŒã€Œãƒªãƒ†ãƒ©ãƒ«ãƒ–ロックã€ã‚­ãƒ¼ã®å€¤ã«ãªã‚Šã€
+ 改行ã¯ä¿æŒã•ã‚Œã¾ã™ã€‚
+
+ リテラルã¯ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆã‚’解除ã™ã‚‹ã¾ã§ç¶šãã€å…ˆé ­è¡Œã®ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆæ–‡å­—数分を
+ å„è¡Œã®ãƒ†ã‚­ã‚¹ãƒˆã®å…ˆé ­ã‹ã‚‰å–り除ãã¾ã™ã€‚
+
+ 「よりインデントã®æ·±ã„ã€è¡Œã¯ãã®åˆ†ã®ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆã‚’ä¿æŒã—ã¾ã™ -
+ ã“ã®2è¡Œã¯ã‚¹ãƒšãƒ¼ã‚¹4個分インデントã•ã‚Œã¾ã™ã€‚
+折り畳ã¿ã‚¹ã‚¿ã‚¤ãƒ«: >
+ ã“ã®æ–‡ç« ã®ãƒ–ロック全体ãŒã€ŒæŠ˜ã‚Šç•³ã¿ã‚¹ã‚¿ã‚¤ãƒ«ã€ã®å€¤ã«ãªã‚Šã¾ã™ã€‚
+ ã—ã‹ã—ã“ã¡ã‚‰ã®å ´åˆã€å…¨ã¦ã®æ”¹è¡ŒãŒã‚¹ãƒšãƒ¼ã‚¹1個ã«ç½®ãæ›ã‚ã‚Šã¾ã™ã€‚
+
+ ç›´å‰ã®ã‚ˆã†ãªç©ºè¡Œã¯æ”¹è¡Œæ–‡å­—ã«å¤‰æ›ã•ã‚Œã¾ã™ã€‚
+
+ 「よりインデントã®æ·±ã„ã€è¡Œã‚‚改行をä¿æŒã—ã¾ã™ -
+ ã“ã®ãƒ†ã‚­ã‚¹ãƒˆã¯2è¡Œã«ã‚ãŸã£ã¦è¡¨ç¤ºã•ã‚Œã¾ã™ã€‚
+
+##################
+# コレクション型 #
+##################
+
+# 入れå­ã‚’表ç¾ã™ã‚‹ã«ã¯ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆã‚’使ã„ã¾ã™ã€‚
+# スペース2個ã®ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆãŒå¥½ã¾ã‚Œã¾ã™ï¼ˆãŒå¿…é ˆã§ã¯ã‚ã‚Šã¾ã›ã‚“)。
+入れå­ã®ãƒžãƒƒãƒ—:
+ キー: 値
+ 別ã®ã‚­ãƒ¼: 別ã®å€¤
+ 別ã®å…¥ã‚Œå­ã®ãƒžãƒƒãƒ—:
+ ã“ã‚“ã«ã¡ã¯: ã“ã‚“ã«ã¡ã¯
+
+# マップã®ã‚­ãƒ¼ã¯æ–‡å­—列ã§ã‚ã‚‹å¿…è¦ã¯ã‚ã‚Šã¾ã›ã‚“。
+0.25: å°æ•°ã®ã‚­ãƒ¼
+
+# 複数行オブジェクトã®ã‚ˆã†ãªè¤‡é›‘ãªã‚­ãƒ¼ã‚‚使用å¯èƒ½ã§ã™ã€‚
+# ? ã®å¾Œã«ã‚¹ãƒšãƒ¼ã‚¹ã‚’入れるã“ã¨ã§è¤‡é›‘ãªã‚­ãƒ¼ã®é–‹å§‹ã‚’宣言ã§ãã¾ã™ã€‚
+? |
+ ã“ã‚Œã¯ã‚­ãƒ¼ã§ã™
+ 複数行ã‚ã‚Šã¾ã™
+: ãã—ã¦ã“ã‚ŒãŒãã®å€¤ã§ã™
+
+# YAMLã§ã¯ã‚·ãƒ¼ã‚±ãƒ³ã‚¹ã‚’複雑ãªã‚­ãƒ¼æ§‹æ–‡ã§ä½¿ã†ã“ã¨ã‚‚ã§ãã¾ã™
+# ã—ã‹ã—ã€è¨€èªžãƒ‘ーサーã«ã‚ˆã£ã¦ã¯ã‚¨ãƒ©ãƒ¼ã«ãªã‚‹ã‹ã‚‚ã—ã‚Œã¾ã›ã‚“
+# 例
+? - マンãƒã‚§ã‚¹ã‚¿ãƒ¼ãƒ»ãƒ¦ãƒŠã‚¤ãƒ†ãƒƒãƒ‰
+ - レアル・マドリード
+: [2001-01-01, 2002-02-02]
+
+# シーケンス(リストやé…列ã¨ç­‰ä¾¡ï¼‰ã¯ã“ã‚“ãªæ„Ÿã˜ã§ã™
+# ('-' ã¯ã‚¤ãƒ³ãƒ‡ãƒ³ãƒˆã¨ã—ã¦ã‚«ã‚¦ãƒ³ãƒˆã—ã¦ãã ã•ã„):
+シーケンス:
+ - アイテム1
+ - アイテム2
+ - 0.5 # シーケンスã«ã¯ç•°ãªã‚‹åž‹ã®å€¤ã‚’混在ã•ã›ã‚‰ã‚Œã¾ã™
+ - アイテム4
+ - キー: 値
+ 別ã®ã‚­ãƒ¼: 別ã®å€¤
+ -
+ - ã“ã‚Œã¯ã‚·ãƒ¼ã‚±ãƒ³ã‚¹ã§ã™
+ - 別ã®ã‚·ãƒ¼ã‚±ãƒ³ã‚¹å†…部
+ - - - 入れå­ã®ã‚·ãƒ¼ã‚±ãƒ³ã‚¹è¡¨è¨˜ã¯
+ - 折り畳ã‚ã¾ã™
+
+# YAMLã¯JSONã®ã‚¹ãƒ¼ãƒ‘ーセットãªã®ã§ã€
+# JSONå½¢å¼ã®ãƒžãƒƒãƒ—ã¨ã‚·ãƒ¼ã‚±ãƒ³ã‚¹ã‚’書ãã“ã¨ã‚‚ã§ãã¾ã™ï¼š
+jsonマップ: {"キー": "値"}
+jsonシーケンス: [3, 2, 1, "発進"]
+クォートã¯ä»»æ„: {キー: [3, 2, 1, 発進]}
+
+######################
+# ãã®ä»–ã®YAMLã®æ©Ÿèƒ½ #
+######################
+
+# YAMLã«ã¯ã€Œã‚¢ãƒ³ã‚«ãƒ¼ã€ã¨å‘¼ã°ã‚Œã‚‹ä¾¿åˆ©ãªæ©Ÿèƒ½ã‚‚ã‚ã‚Šã¾ã™ã€‚ã“ã‚Œã«ã‚ˆã‚Šã‚³ãƒ³ãƒ†ãƒ³ãƒ„ã‚’
+# ドキュメント内ã§ç°¡å˜ã«è¤‡è£½ã§ãã¾ã™ã€‚ã“れらã®ã‚­ãƒ¼ã¯ã©ã¡ã‚‰ã‚‚åŒã˜å€¤ã‚’æŒã¡ã¾ã™ï¼š
+アンカーã•ã‚ŒãŸã‚³ãƒ³ãƒ†ãƒ³ãƒ„: &anchor_name ã“ã®æ–‡å­—列ã¯2ã¤ã®ã‚­ãƒ¼ã®å€¤ã«ãªã‚Šã¾ã™ã€‚
+ä»–ã®ã‚¢ãƒ³ã‚«ãƒ¼: *anchor_name
+
+# アンカーã¯è¤‡è£½ï¼ç¶™æ‰¿ãƒ—ロパティã¨ã—ã¦ä½¿ãˆã¾ã™
+ベース: &base
+ åå‰: ã¿ã‚“ãªåŒã˜åå‰ã‚’æŒã¡ã¾ã™
+
+# è¨˜å· << ã¯ãƒžãƒ¼ã‚¸ã‚­ãƒ¼è¨€èªžéžä¾å­˜åž‹ï¼ˆMerge Key Language-Independent Type)
+# ã¨å‘¼ã°ã‚Œã¾ã™ã€‚ã“ã‚Œã¯æŒ‡å®šã•ã‚ŒãŸ1ã¤ä»¥ä¸Šã®ãƒžãƒƒãƒ—ã®å…¨ã¦ã®ã‚­ãƒ¼ã‚’ç¾åœ¨ã®ãƒžãƒƒãƒ—ã«
+# 挿入ã™ã‚‹ã“ã¨ã‚’示ã™ãŸã‚ã«ä½¿ã‚ã‚Œã¾ã™ã€‚
+
+foo:
+ <<: *base
+ å¹´é½¢: 10
+
+bar:
+ <<: *base
+ å¹´é½¢: 20
+
+# fooã¨barも「åå‰ï¼š ã¿ã‚“ãªåŒã˜åå‰ã‚’æŒã¡ã¾ã™ã€ã‚’æŒã¡ã¾ã™
+
+# YAMLã«ã¯ã‚¿ã‚°ã‚‚ã‚ã‚Šã€æ˜Žç¤ºçš„ã«åž‹ã‚’宣言ã§ãã¾ã™ã€‚
+明示的ãªæ–‡å­—列: !!str 0.5
+# 言語特有ã®ã‚¿ã‚°ã‚’実装ã—ãŸãƒ‘ーサーもã‚ã‚Šã€ä¾‹ãˆã°Pythonã®è¤‡ç´ æ•°åž‹ãŒä½¿ãˆã¾ã™ã€‚
+pythonã®è¤‡ç´ æ•°åž‹: !!python/complex 1+2j
+
+# YAMLã®è¤‡é›‘ãªã‚­ãƒ¼ã§ã¯è¨€èªžç‰¹æœ‰ã®ã‚¿ã‚°ã‚‚使ãˆã¾ã™
+? !!python/tuple [5, 7]
+: 五å七
+# Python上㧠{(5, 7): '五å七'} ã¨ã—ã¦æ‰±ã‚ã‚Œã¾ã™
+
+####################
+# ãã®ä»–ã®YAMLã®åž‹ #
+####################
+
+# 文字列ã¨æ•°å€¤ãŒYAMLã®ç†è§£ã§ãる唯一ã®ã‚¹ã‚«ãƒ©ãƒ¼ã§ã¯ã‚ã‚Šã¾ã›ã‚“。
+# ISOå½¢å¼ã®æ—¥ä»˜ã‚„日時リテラルもパースã•ã‚Œã¾ã™ã€‚
+日時: 2001-12-15T02:59:43.1Z
+スペースをå«ã‚€æ—¥æ™‚: 2001-12-14 21:59:43.10 -5
+日付: 2002-12-14
+
+# !!binaryã‚¿ã‚°ã¯æ–‡å­—列ã®å®Ÿä½“ãŒãƒã‚¤ãƒŠãƒªblobã®base64エンコード表ç¾ã§ã‚ã‚‹ã“ã¨ã‚’
+# 示ã—ã¾ã™ã€‚
+gifファイル: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAMLã«ã¯ã‚»ãƒƒãƒˆåž‹ã‚‚ã‚ã‚Šã€ãã‚Œã¯ã“ã‚“ãªæ„Ÿã˜ã§ã™ï¼š
+セット:
+ ? アイテム1
+ ? アイテム2
+ ? アイテム3
+ã¾ãŸã¯: {アイテム1, アイテム2, アイテム3}
+
+# セットã¯å€¤ãŒnullã®ãŸã ã®ãƒžãƒƒãƒ—ã§ã€ç›´å‰ã®ã‚»ãƒƒãƒˆã¯ä»¥ä¸‹ã¨ç­‰ä¾¡ã§ã™ï¼š
+セット2:
+ アイテム1: null
+ アイテム2: null
+ アイテム3: null
+
+... # ドキュメント終了
+```
+
+### 補足資料
+
++ [YAMLå…¬å¼ã‚¦ã‚§ãƒ–サイト](https://yaml.org/)
++ [オンラインYAMLãƒãƒªãƒ‡ãƒ¼ã‚¿ãƒ¼](http://www.yamllint.com/)
diff --git a/janet.html.markdown b/janet.html.markdown
index 7b2912c2..62ed7331 100644
--- a/janet.html.markdown
+++ b/janet.html.markdown
@@ -29,9 +29,9 @@ nil
# Typical style for symbols (identifiers-for / names-of things).
do-stuff
pants-on-fire!
-foo->bar # Evidently for converting foos to bars.
+foo->bar # Evidently for converting foos to bars.
fully-charged?
-_ # Usually used as a dummy variable.
+_ # Usually used as a dummy variable.
# Keywords are like symbols that start with a colon, are treated like
# constants, and are typically used as map keys or pieces of syntax in
@@ -58,10 +58,11 @@ math/e # => 2.71828
"hello"
"hey\tthere" # contains a tab
-# For multi-line strings, use one or more backticks. No escapes allowed.
+# For multi-line strings, use one or more backticks. Backslash-escapes not
+# recognized in these (bytes will be parsed literally).
``a long
multi-line
-string`` # => "a long\nmulti-line\nstring"
+string`` # => "a long\nmulti-line\nstring"
# Strings and data structures in Janet come in two varieties: mutable and
# immutable. The literal for the mutable variety is written with a `@` in
@@ -72,7 +73,7 @@ string`` # => "a long\nmulti-line\nstring"
@`a multi-line
one here`
-(string "con" "cat" "enate") # => "concatenate"
+(string "con" "cat" "enate") # => "concatenate"
# To get a substring:
(string/slice "abcdefgh" 2 5) # => "cde"
@@ -81,7 +82,8 @@ one here`
# See the string library for more (splitting, replacement, etc.)
-# Arrays and Tuples ###########################################################
+# Data Structures #############################################################
+# Arrays and Tuples
# Arrays are mutable, tuples are immutable.
# Arrays (mutable)
@@ -91,18 +93,19 @@ one here`
# Tuples (immutable)
# Note that an open paren usually indicates a function call, so if you want a
# literal tuple with parens, you need to "quote" it (with a starting single
-# quote mark).
+# quote mark)...
'(4 5 6)
[4 5 6] # ... or just use square brackets.
-# Tables and Structs (AKA: "maps", "hashmaps", "dictionaries")
+# Tables and Structs (associative data structures)
@{:a 1 :b 2 :c 3} # table (mutable)
{:a 1 :b 2 :c 3} # struct (immutable)
+# To "pretty-print" these out, use `pp` instead of `print`.
# More about how to work with arrays/tuples and tables/structs below.
# Bindings ####################################################################
-# ... or "Name Some Things!" (that is, bind a value to a symbol)
+# Bind a value to a symbol.
(def x 4.7) # Define a constant, `x`.
x # => 4.7
(quote x) # => x (the symbol x)
@@ -113,7 +116,7 @@ x # => 4.7
(set x 5.6) # Error, `x` is a constant.
(var y 10)
-(set y 12) # Works, since `y` was made var.
+(set y 12) # Works, since `y` was defined using `var`.
# Note that bindings are local to the scope they're called in. `let`
# creates a local scope and makes some bindings all in one shot:
@@ -151,29 +154,29 @@ insect-friend # => bee
(% 5 3) # => 2 (remainder)
(- 5) # => -5 (or you can just write `-5`)
-(++ i) # increments
+(++ i) # increments (modifies `i`)
(-- i) # decrements
(+= i 3) # add 3 to `i`
(*= i 3) # triple `i`
# ... and so on for the other operations on numbers.
+# If you don't want to mutate `i`, use `(inc i)` and `(dec i)`.
+
# Comparison
# = < > not= <= >=
(< 2 7 12) # => true
# Functions ###################################################################
# Call them:
-(- 5 3) # => 2 (Yes, operators and functions work the same.)
+(- 5 3) # => 2 (Operators and functions work the same way.)
(math/sin (/ math/pi 2)) # => 1
-(range 5) # => @[0 1 2 3 4]
+(range 5) # => @[0 1 2 3 4]
# Create them:
(defn mult-by-2
``First line of docstring.
- Some more of the docstring.
-
- Possibly more!``
+ Some more of the docstring.``
[x]
(print "Hi.")
(print "Will compute using: " x)
@@ -206,7 +209,7 @@ n # => 3
# You might say that function bodies provide an "implicit do".
# Operations on data structures ###############################################
-# (Making all these mutable so we can ... mutate them.)
+# (Making all of these mutable so we can ... mutate them.)
(def s @"Hello, World!")
(def a @[:a :b :c :d :e])
(def t @{:a 1 :b 2})
@@ -216,9 +219,9 @@ n # => 3
(length t) # => 2
# Getting values:
-(s 7) # => 87 (which is the code point for "W")
-(a 1) # => :b
-(t :a) # => 1
+(s 7) # => 87 (which is the code point for "W")
+(a 1) # => :b
+(t :a) # => 1
(keys t) # => @[:a :b]
(values t) # => @[1 2]
@@ -227,14 +230,14 @@ n # => 3
(put a 2 :x) # @[:a :b :x :d :e]
(put t :b 42) # @{:a 1 :b 42}
-# Adding & removing values (again, for mutable data structures):
+# Adding and removing values (again, for mutable data structures):
(buffer/push-string s "??") # @"HeWlo, World!??"
(array/push a :f) # @[:a :b :x :d :e :f]
(array/pop a) # => :f, and it's also removed from `a`.
(put t :x 88) # @{:a 1 :b 42 :x 88}
# See the manual for a wide variety of functions for working with
-# buffers/strings, arrays/tuples, and tables/struct.
+# buffers/strings, arrays/tuples, and tables/structs.
# Flow control ################################################################
(if some-condition
@@ -282,7 +285,7 @@ n # => 3
{:yar v} (print "matches key :yar! " v)
{:moo v} (print "matches key :moo! " v)
{:c v} (print "matches key :c! " v)
- _ (print "no match")) # => prints "matches key :c! 3"
+ _ (print "no match")) # => prints "matches key :c! 3"
# Iterating ###################################################################
# Iterate over an integer range:
@@ -312,7 +315,7 @@ n # => 3
(* x x))
(range 10))) # => @[0 4 16 36 64]
-(reduce + 0 (range 5)) # => 10
+(reduce + 0 (range 5)) # => 10
# ...and lots more (see the API docs).
diff --git a/java.html.markdown b/java.html.markdown
index 4be940be..7bf3fa0a 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -91,6 +91,9 @@ public class LearnJava {
int numInt = scanner.nextInt();
// read long input
+ long numLong = scanner.nextLong();
+
+ // read float input
float numFloat = scanner.nextFloat();
// read double input
@@ -123,6 +126,9 @@ public class LearnJava {
// <name1> = <name2> = <name3> = <val>
int barInt1, barInt2, barInt3;
barInt1 = barInt2 = barInt3 = 1;
+ // Shorthand for multiple declarations
+ int barInt4 = 1, barInt5 = 2;
+
/*
* Variable types
@@ -182,7 +188,7 @@ public class LearnJava {
//
// BigInteger is a data type that allows programmers to manipulate
// integers longer than 64-bits. Integers are stored as an array of
- // of bytes and are manipulated using functions built into BigInteger
+ // bytes and are manipulated using functions built into BigInteger
//
// BigInteger can be initialized using an array of bytes or a string.
BigInteger fooBigInteger = new BigInteger(fooByteArray);
@@ -304,8 +310,8 @@ public class LearnJava {
///////////////////////////////////////
System.out.println("\n->Operators");
- int i1 = 1, i2 = 2; // Shorthand for multiple declarations
-
+ int i1 = 1, i2 = 2;
+
// Arithmetic is straightforward
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
@@ -314,7 +320,7 @@ public class LearnJava {
System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5
// Modulo
- System.out.println("11%3 = "+(11 % 3)); // => 2
+ System.out.println("11%3 = " + (11 % 3)); // => 2
// Comparison operators
System.out.println("3 == 2? " + (3 == 2)); // => false
@@ -368,7 +374,7 @@ public class LearnJava {
// While loop
int fooWhile = 0;
- while(fooWhile < 100) {
+ while (fooWhile < 100) {
System.out.println(fooWhile);
// Increment the counter
// Iterated 100 times, fooWhile 0,1,2...99
@@ -383,7 +389,7 @@ public class LearnJava {
// Increment the counter
// Iterated 100 times, fooDoWhile 0->99
fooDoWhile++;
- } while(fooDoWhile < 100);
+ } while (fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
// For Loop
diff --git a/javascript.html.markdown b/javascript.html.markdown
index b290b553..4e7c5c09 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -105,6 +105,10 @@ false;
"1, 2, " + 3; // = "1, 2, 3"
"Hello " + ["world", "!"]; // = "Hello world,!"
+// ...which can result in some weird behaviour...
+13 + !0; // 14
+"13" + !0; // '13true'
+
// and are compared with < and >
"a" < "b"; // = true
@@ -116,10 +120,6 @@ null == undefined; // = true
"5" === 5; // = false
null === undefined; // = false
-// ...which can result in some weird behaviour...
-13 + !0; // 14
-"13" + !0; // '13true'
-
// You can access characters in a string with `charAt`
"This is a string".charAt(0); // = 'T'
@@ -405,7 +405,7 @@ myObj = {
};
myObj.myFunc(); // = "Hello world!"
-// What this is set to has to do with how the function is called, not where
+// What `this` is set to has to do with how the function is called, not where
// it's defined. So, our function doesn't work if it isn't called in the
// context of the object.
var myFunc = myObj.myFunc;
@@ -620,7 +620,7 @@ function isEven(number) {
};
// I put the word "equivalent" in double quotes because a function defined
-// using the lambda syntax cannnot be called before the definition.
+// using the lambda syntax cannot be called before the definition.
// The following is an example of invalid usage:
add(1, 8);
@@ -655,7 +655,7 @@ attached terminal
[Javascript: The Right Way][10] is a guide intended to introduce new developers
to JavaScript and help experienced developers learn more about its best practices.
-[Javascript:Info][11] is a modern javascript tutorial covering the basics (core language and working with a browser)
+[javascript.info][11] is a modern javascript tutorial covering the basics (core language and working with a browser)
as well as advanced topics with concise explanations.
@@ -671,6 +671,7 @@ Mozilla Developer Network.
[5]: http://bonsaiden.github.io/JavaScript-Garden/
[6]: http://www.amazon.com/gp/product/0596805527/
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[8]: https://www.javascripttutorial.net/
[8]: http://eloquentjavascript.net/
[10]: http://jstherightway.org/
[11]: https://javascript.info/
diff --git a/jinja.html.markdown b/jinja.html.markdown
new file mode 100644
index 00000000..7e5b8e96
--- /dev/null
+++ b/jinja.html.markdown
@@ -0,0 +1,270 @@
+---
+language: Jinja
+contributors:
+ - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"]
+filename: learn-jinja.j2
+---
+
+## Getting Started with Jinja
+
+Jinja is a fast, expressive, and extensible templating engine for Python
+applications.
+
+Jinja includes a lot of functionalities, such as:
+- Template inheritance and inclusion;
+- Defining and importing macros within templates;
+- Security mechanisms to prevent XSS attacks;
+- A sandboxed environment that can safely render untrusted templates;
+- Extensible filters, tests, functions, and even syntax.
+
+A Jinja template is simply a text file. Jinja doesn't require a specific
+extension, but it's common to use `.j2` or `.jinja` to make it easier for
+some IDEs.
+
+There are a few kinds of delimiters. The default Jinja delimiters are configured
+as follows:
+
+- `{% ... %}` for Statements
+- `{{ ... }}` for Expressions to print to the template output
+- `{# ... #}` for Comments not included in the template output
+
+```jinja
+{# This is an example of a comment. #}
+
+{#
+ You can use this syntax
+ to write multiline comments
+ as well.
+#}
+```
+
+
+## VARIABLES
+
+```jinja
+{# You have the option to access variables from the context passed to the template #}
+
+{{ foo }}
+
+{#
+ Additionally, you can use a dot (.) to access attributes of a variable or
+ use Python syntax, using []
+#}
+
+{{ foo.bar }}
+{{ foo['bar'] }}
+
+{# Within the template, you can define variables as well #}
+
+{% set name = "Magdiel" %}
+{{ name }}
+```
+
+## Loops
+
+```html
+<h1>Members</h1>
+<ul>
+{% for user in users %}
+ <li>{{ user.username }}</li>
+{% endfor %}
+</ul>
+
+
+<div>
+{% for key, value in my_dict.items() %}
+ <p>{{ key }}</p> - <p>{{ value }}</p>
+{% endfor %}
+</div>
+
+
+<div>
+{% for idx, url in enumerate(urls) %}
+ <a href="{{ url }}">Go to url {{ idx + 1 }}</a>
+{% endfor %}
+</div>
+```
+
+## Conditionals
+
+The if statement in Jinja is similar to the if statement in Python. It is
+commonly used to check if a variable is defined, not empty, and not false in
+its most basic form.
+
+```html
+{% if users %}
+<ul>
+{% for user in users %}
+ <li>{{ user.username }}</li>
+{% endfor %}
+</ul>
+{% endif %}
+
+
+{# For multiple branches, elif and else can be used like in Python. #}
+
+
+{% if message.status == "error" %}
+ <p class="text-red-400">{{ message.content }}</p>
+{% elif message.status == "success" %}
+ <p class="text-green-400">{{ message.content }}</p>
+{% else %}
+ <p class="text-blue-400">{{ message.content }}</p>
+{% endif %}
+```
+
+## Template Inheritance
+
+One of the most powerful features of Jinja is template inheritance. You can
+create a base layout with predefined blocks that you can extend in another file
+and override with your own content.
+
+```html
+{# file: base.html.j2 #}
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ {% block head %}
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>{% block title %}{% endblock title %} - Learning Jinja</title>
+ {% endblock head %}
+</head>
+<body>
+ <main>
+ {% block content %}{% endblock %}
+ {# the endblock tag doesn't need the name of the block #}
+ </main>
+</body>
+</html>
+
+
+
+{# file: child.html.j2 #}
+
+{% extends "base.html.j2" %}
+
+{% block head %}
+ {{ super() }}
+ <script>
+ console.log("There's a console.log here")
+ </script>
+{% endblock %}
+
+{% block title %}Home{% endblock %}
+
+{% block content %}
+ <h1>Index</h1>
+ <p>Welcome to my home homepage.</p>
+{% endblock %}
+
+
+
+{# RESULT #}
+
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Home - Learning Jinja</title>
+ <script>
+ console.log("There's a console.log here")
+ </script>
+</head>
+<body>
+ <main>
+ <h1>Index</h1>
+ <p>Welcome to my home homepage.</p>
+ </main>
+</body>
+</html>
+
+```
+
+### Including Content
+
+You can include content from another template on your current template using
+the `{% include "template/path" %}` tag.
+
+```html
+
+{# file: footer.html.j2 #}
+
+<footer>
+ <p>&copy; 2024 - John Doe</p>
+</footer>
+
+
+
+{# file: index.html.j2 #}
+...
+<body>
+ <main>
+ <h1>Hi! I'm John Doe!</h1>
+ </main>
+ {% include "footer.html.j2" %}
+</body>
+...
+
+
+
+{# RESULT #}
+
+...
+<body>
+ <main>
+ <h1>Hi! I'm John Doe!</h1>
+ </main>
+ <footer>
+ <p>&copy; 2024 - John Doe</p>
+ </footer>
+</body>
+...
+```
+
+Variables passed to the main template can also be used in the include, as the
+included template has access to the context of the main template.
+
+```html
+{# file: greetings.html.j2 #}
+
+<p>I'm the {{ name }} and i like to {{ hobby }}.</p>
+
+
+
+{# file: index.html.j2 #}
+
+{% set name = "Captain Nemo" %}
+{% set hobby = "navigate through the depths of the ocean" %}
+
+<div>
+ {% include "greetings.html.j2" %}
+</div>
+
+
+
+{# RESULT #}
+
+<div>
+ <p>I'm the Captain Nemo and i like to navigate through the depths of the ocean.</p>
+</div>
+```
+
+## Macros
+
+Macros are basically like functions in another languages. You can define macros with or without arguments and reuse them in various parts of your template.
+
+```html
+{% macro input(value="", type="text", placeholder="") -%}
+ <input type="{{ type }}" value="{{ value }}" placeholder="{{ placeholder }}">
+{%- endmacro %}
+
+<p>{{ input(placeholder="Your username") }}</p>
+<p>{{ input(type="password") }}</p>
+```
+
+## Official Documentation
+
+To learn more, access the [official documentation](https://jinja.palletsprojects.com/en/).
diff --git a/jq.html.markdown b/jq.html.markdown
new file mode 100644
index 00000000..dded34cb
--- /dev/null
+++ b/jq.html.markdown
@@ -0,0 +1,910 @@
+---
+category: tool
+tool: jq
+contributors:
+ - ["Jack Kuan", "https://github.com/kjkuan"]
+filename: learnjq.sh
+---
+
+`jq` is a tool for transforming JSON inputs and generating JSON outputs. As a
+programming language, jq supports boolean and arithmetic expressions, object
+and array indexing; it has conditionals, functions, and even exception
+handling... etc. Knowing jq enables you to easily write small programs that
+can perform complex queries on JSON documents to find answers, make reports, or
+to produce another JSON document for further processing by other programs.
+
+> **NOTE**: This guide demonstrates the use of jq from the command line,
+> specifically, under an environment running the Bash shell.
+
+```bash
+# When running jq from the command line, jq program code can be specified as the
+# first argument after any options to `jq`. We often quote such jq program with
+# single quotes (`'`) to prevent any special interpretation from the command line
+# shell.
+#
+jq -n '# Comments start with # until the end of line.
+ # The -n option sets the input to the value, `null`, and prevents `jq`
+ # from reading inputs from external sources.
+'
+
+# Output:
+# null
+
+
+# By default jq reads from *STDIN* a stream of JSON inputs (values). It
+# processes each input with the jq program (filters) specified at the command
+# line, and prints the outputs of processing each input with the program to
+# *STDOUT*.
+#
+echo '
+ "hello" 123 [
+ "one",
+ "two",
+ "three"
+ ]
+ { "name": "jq" }
+' |
+ jq '. # <-- the jq program here is the single dot (.), called the identity
+ # operator, which stands for the current input.
+'
+
+# Output:
+# "hello"
+# 123
+# [
+# "one",
+# "two",
+# "three"
+# ]
+# {
+# "name": "jq"
+# }
+
+
+# Notice that jq pretty-prints the outputs by default, therefore, piping
+# to `jq` is a simple way to format a response from some REST API endpoint
+# that returns JSON. E.g., `curl -s https://freegeoip.app/json/ | jq`
+
+
+# Instead of processing each JSON input with a jq program, you can also
+# ask jq to slurp them up as an array.
+#
+echo '1 "two" 3' | jq -s .
+
+# Output:
+# [
+# 1,
+# "two",
+# 3
+# ]
+
+
+# Or, treat each line as a string.
+#
+(echo line 1; echo line 2) | jq -R .
+
+# Output:
+# "line 1"
+# "line 2"
+
+
+# Or, combine -s and -R to slurp the input lines into a single string.
+#
+(echo line 1; echo line 2) | jq -sR .
+
+# Output:
+# "line 1\nline2\n"
+
+
+# Inputs can also come from a JSON file specified at the command line:
+#
+echo '"hello"' > hello.json
+jq . hello.json
+
+# Output:
+# "hello"
+
+
+# Passing a value into a jq program can be done with the `--arg` option.
+# Below, `val` is the variable name to bind the value, `123`, to.
+# The variable is then referenced as `$val`.
+#
+jq -n --arg val 123 '$val' # $val is the string "123" here
+
+# Output:
+# "123"
+
+
+# If you need to pass a JSON value, use `--argjson`
+#
+jq -n --argjson val 123 '$val' # $val is a number
+
+# Output:
+# 123
+
+
+# Using `--arg` or `--argjson` is an useful way of building JSON output from
+# existing input.
+#
+jq --arg text "$(date; echo "Have a nice day!")" -n '{ "today": $text }'
+
+# Output:
+# {
+# "today": "Sun Apr 10 09:53:07 PM EDT 2022\nHave a nice day!"
+# }
+
+
+# Instead of outputting values as JSON, you can use the `-r` option to print
+# string values unquoted / unescaped. Non-string values are still printed as
+# JSON.
+#
+echo '"hello" 2 [1, "two", null] {}' | jq -r .
+
+# Output:
+# hello
+# 2
+# [
+# 1,
+# "two",
+# null
+# ]
+# {}
+
+
+# Inside a string in jq, `\(expr)` can be used to substitute the output of
+# `expr` into the surrounding string context.
+#
+jq -rn '"1 + 2 = \(1+2)"'
+
+# Output:
+# 1 + 2 = 3
+
+
+# The `-r` option is most useful for generating text outputs to be processed
+# down in a shell pipeline, especially when combined with an intepolated
+# string that is prefixed the `@sh` prefix operator.
+#
+# The `@sh` operator escapes the outputs of `\(...)` inside a string with
+# single quotes so that each resulting string of `\(...)` can be evaluated
+# by the shell as a single word / token / argument without special
+# interpretations.
+#
+env_vars=$(
+ echo '{"var1": "value one", "var2": "value\ntwo"}' \
+ |
+ jq -r '
+ "export " + @sh "var1=\(.var1) var2=\(.var2)"
+ # ^^^^^^^^ ^^^^^^^^
+ # "'value one'" "'value\ntwo'"
+ #
+ # NOTE: The + (plus) operator here concatenates strings.
+ '
+)
+echo "$env_vars"
+eval "$env_vars"
+declare -p var1 var2
+
+# Output:
+# export var1='value one' var2='value
+# two'
+# declare -- var1="value one"
+# declare -- var2="value
+# two"
+
+# There are other string `@prefix` operators (e.g., @base64, @uri, @csv, ...)
+# that might be useful to you. See `man jq` for details.
+
+
+# The comma (`,`) operator in jq evaluates each operand and generates multiple
+# outputs:
+#
+jq -n '"one", 2, ["three"], {"four": 4}'
+
+# Output:
+# "one"
+# 2
+# [
+# "three"
+# ]
+# {
+# "four": 4
+# }
+
+
+# Any JSON value is a valid jq expression that evaluates to the JSON value
+# itself.
+#
+jq -n '1, "one", [1, 2], {"one": 1}, null, true, false'
+
+# Output:
+# 1
+# "one"
+# [
+# 1,
+# 2
+# ]
+# {
+# "one": 1
+# }
+# null
+# true
+# false
+
+
+# Any jq expression can be used where a JSON value is expected, even as object
+# keys. (though parenthesis might be required for object keys or values)
+#
+jq -n '[2*3, 8-1, 16/2], {("tw" + "o"): (1 + 1)}'
+
+# Output:
+# [
+# 6,
+# 7,
+# 8
+# ]
+# {
+# "two": 2
+# }
+
+
+# As a shortcut, if a JSON object key looks like a valid identifier (matching
+# the regex `^[a-zA-Z_][a-zA-Z_0-9]*$`), quotes can be omitted.
+#
+jq -n '{ key_1: "value1" }'
+
+# If a JSON object's key's value is ommited, it is looked up in the current
+# input using the key: (see next example for the meaning of `... | ...`)
+#
+jq -n '{c: 3} | {a: 1, "b", c}'
+
+# Output:
+# {
+# "a": 1,
+# "b": null,
+# "c": 3
+# }
+
+
+# jq programs are more commonly written as a series of expressions (filters)
+# connected by the pipe (`|`) operator, which makes the output of its left
+# filter the input to its right filter.
+#
+jq -n '1 | . + 2 | . + 3' # first dot is 1; second dot is 3
+
+# Output:
+# 6
+
+# If an expression evaluates to multiple outputs, then jq will iterate through
+# them and propagate each output down the pipeline, and generate multiple
+# outputs in the end.
+#
+jq -n '1, 2, 3 | ., 4 | .'
+
+# Output:
+# 1
+# 4
+# 2
+# 4
+# 3
+# 4
+
+# The flows of the data in the last example can be visualized like this:
+# (number prefixed with `*` indicates the current output)
+#
+# *1, 2, 3 | *1, 4 | *1
+# 1, 2, 3 | 1, *4 | *4
+# 1, *2, 3 | *2, 4 | *2
+# 1, 2, 3 | 2, *4 | *4
+# 1, 2, *3 | *3, 4 | *3
+# 1, 2, 3 | 3, *4 | *4
+#
+#
+# To put it another way, the evaluation of the above example is very similar
+# to the following pieces of code in other programming languages:
+#
+# In Python:
+#
+# for first_dot in 1, 2, 3:
+# for second_dot in first_dot, 4:
+# print(second_dot)
+#
+# In Ruby:
+#
+# [1, 2, 3].each do |dot|
+# [dot, 4].each { |dot| puts dot }
+# end
+#
+# In Javascript:
+#
+# [1, 2, 3].forEach(dot => {
+# [dot, 4].forEach(dot => console.log(dot))
+# })
+#
+
+
+# Below are some examples of array index and object attribute lookups using
+# the `[expr]` operator after an expression. If `expr` is a number then it's
+# an array index lookup; otherwise, it should be a string, in which case it's
+# an object attribute lookup:
+
+# Array index lookup
+#
+jq -n '[2, {"four": 4}, 6][1 - 1]' # => 2
+jq -n '[2, {"four": 4}, 6][0]' # => 2
+jq -n '[2, {"four": 4}, 6] | .[0]' # => 2
+
+# You can chain the lookups since they are just expressions.
+#
+jq -n '[2, {"four": 4}, 6][1]["fo" + "ur"]' # => 4
+
+# For object attributes, you can also use the `.key` shortcut.
+#
+jq -n '[2, {"four": 4}, 6][1].four' # => 4
+
+# Use `."key"` if the key is not a valid identifier.
+#
+jq -n '[2, {"f o u r": 4}, 6][1]."f o u r"' # => 4
+
+# Array index lookup returns null if the index is not found.
+#
+jq -n '[2, {"four": 4}, 6][99]' # => null
+
+# Object attribute lookup returns null if the key is not found.
+#
+jq -n '[2, {"four": 4}, 6][1].whatever' # => null
+
+# The alternative operator `//` can be used to provide a default
+# value when the result of the left operand is either `null` or `false`.
+#
+jq -n '.unknown_key // 7' # => 7
+
+# If the thing before the lookup operator (`[expr]`) is neither an array
+# or an object, then you will get an error:
+#
+jq -n '123 | .[0]' # => jq: error (at <unknown>): Cannot index number with number
+jq -n '"abc" | .name' # => jq: error (at <unknown>): Cannot index string with string "name"
+jq -n '{"a": 97} | .[0]' # => jq: error (at <unknown>): Cannot index object with number
+jq -n '[89, 64] | .["key"]' # => jq: error (at <unknown>): Cannot index array with string "key"
+
+# You can, however, append a `?` to a lookup to make jq return `empty`
+# instead when such error happens.
+#
+jq -n '123 | .[0]?' # no output since it's empty.
+jq -n '"abc" | .name?' # no output since it's empty.
+
+# The alternative operator (`//`) also works with `empty`:
+#
+jq -n '123 | .[0]? // 99' # => 99
+jq -n '"abc" | .name? // "unknown"' # => "unknown"
+
+# NOTE: `empty` is actually a built-in function in jq.
+# With the nested loop explanation we illustrated earlier before,
+# `empty` is like the `continue` or the `next` keyword that skips
+# the current iteration of the loop in some programming languages.
+
+
+# Strings and arrays can be sliced with the same syntax (`[i:j]`, but no
+# steppings) and semantic as found in the Python programming language:
+#
+# 0 1 2 3 4 5 ... infinite
+# array = ["a", "b", "c", "d"]
+# -infinite ... -4 -3 -2 -1
+#
+jq -n '["Peter", "Jerry"][1]' # => "Jerry"
+jq -n '["Peter", "Jerry"][-1]' # => "Jerry"
+jq -n '["Peter", "Jerry", "Tom"][1:]' # => ["Jerry", "Tom"]
+jq -n '["Peter", "Jerry", "Tom"][:1+1]' # => ["Peter", "Jerry"]
+jq -n '["Peter", "Jerry", "Tom"][1:99]' # => ["Jerry", "Tom"]
+
+
+# If the lookup index or key is ommited then jq iterates through
+# the collection, generating one output value from each iteration.
+#
+# These examples produce the same outputs.
+#
+echo 1 2 3 | jq .
+jq -n '1, 2, 3'
+jq -n '[1, 2, 3][]'
+jq -n '{a: 1, b: 2, c: 3}[]'
+
+# Output:
+# 1
+# 2
+# 3
+
+
+# You can build an array out of multiple outputs.
+#
+jq -n '{values: [{a: 1, b: 2, c: 3}[] | . * 2]}'
+
+# Output:
+# {
+# "values": [
+# 2,
+# 4,
+# 6
+# ]
+# }
+
+
+# If multiple outputs are not contained, then we'd get multiple outputs
+# in the end.
+#
+jq -n '{values: ({a: 1, b: 2, c: 3}[] | . * 2)}'
+
+# Output:
+# {
+# "values": 2
+# }
+# {
+# "values": 4
+# }
+# {
+# "values": 6
+# }
+
+
+# Conditional `if ... then ... else ... end` in jq is an expression, so
+# both the `then` part and the `else` part are required. In jq, only
+# two values, `null` and `false`, are false; all other values are true.
+#
+jq -n 'if 1 > 2 | not and 1 <= 2 then "Makes sense" else "WAT?!" end'
+
+# Output
+# "Makes sense"
+
+# Notice that `not` is a built-in function that takes zero arguments,
+# that's why it's used as a filter to negate its input value.
+# We'll talk about functions soon.
+
+# Another example using a conditional:
+#
+jq -n '1, 2, 3, 4, 5 | if . % 2 != 0 then . else empty end'
+
+# Output
+# 1
+# 3
+# 5
+
+# The `empty` above is a built-in function that takes 0 arguments and
+# generates no outputs. Let's see more examples of built-in functions.
+
+# The above conditional example can be written using the `select/1` built-in
+# function (`/1` indicates the number of arguments expected by the function).
+#
+jq -n '1, 2, 3, 4, 5 | select(. % 2 != 0)' # NOTE: % gives the remainder.
+
+# Output
+# 1
+# 3
+# 5
+
+
+# Function arguments in jq are passed with call-by-name semantic, which
+# means, an argument is not evaulated at call site, but instead, is
+# treated as a lambda expression with the calling context of the call
+# site as its scope for variable and function references used in the
+# expression.
+#
+# In the above example, the expression `. % 2 != 0` is what's passed to
+# `select/1` as the argument, not `true` or `false`, which is what would
+# have been the case had the (boolean) expression was evaluated before it's
+# passed to the function.
+
+
+# The `range/1`, `range/2`, and `range/3` built-in functions generate
+# integers within a given range.
+#
+jq -n '[range(3)]' # => [0, 1, 2]
+jq -n '[range(0; 4)]' # => [0, 1, 2, 3]
+jq -n '[range(2; 10; 2)]' # => [2, 4, 6, 8]
+
+# Notice that `;` (semicolon) is used to separate function arguments.
+
+
+# The `map/1` function applies a given expression to each element of
+# the current input (array) and outputs a new array.
+#
+jq -n '[range(1; 6) | select(. % 2 != 0)] | map(. * 2)'
+
+# Output:
+# [
+# 2,
+# 6,
+# 10
+# ]
+
+# Without using `select/1` and `map/1`, we could have also written the
+# above example like this:
+#
+jq -n '[range(1; 6) | if . % 2 != 0 then . else empty end | . * 2]'
+
+
+# `keys/0` returns an array of keys of the current input. For an object,
+# these are the object's attribute names; for an array, these are the
+# array indices.
+#
+jq -n '[range(2; 10; 2)] | keys' # => [0, 1, 2, 3]
+jq -n '{a: 1, b: 2, c: 3} | keys' # => ["a", "b", "c"]
+
+# `values/0` returns an array of values of the current input. For an object,
+# these are the object's attribute values; for an array, these are the
+# elements of the array.
+#
+jq -n '[range(2; 10; 2)] | values' # => [2, 4, 6, 8]
+jq -n '{a: 1, b: 2, c: 3} | values' # => [1, 2, 3]
+
+
+# `to_entries/0` returns an array of key-value objects of the current input
+# object.
+#
+jq -n '{a: 1, b: 2, c: 3} | to_entries'
+
+# Output:
+# [
+# {
+# "key": "a",
+# "value": 1
+# },
+# {
+# "key": "b",
+# "value": 2
+# },
+# {
+# "key": "c",
+# "value": 3
+# }
+# ]
+
+
+# Here's how you can turn an object's attribute into environment variables
+# using what we have learned so far.
+#
+env_vars=$(
+ jq -rn '{var1: "1 2 3 4", var2: "line1\nline2\n"}
+ | to_entries[]
+ | "export " + @sh "\(.key)=\(.value)"
+ '
+)
+eval "$env_vars"
+declare -p var1 var2
+
+# Output:
+# declare -x var1="1 2 3 4"
+# declare -x var2="line1
+# line2
+# "
+
+
+# `from_entries/0` is the opposite of `to_entries/0` in that it takes an
+# an array of key-value objects and turn that into an object with keys
+# and values from the `key` and `value` attributes of the objects.
+#
+# It's useful together with `to_entries/0` when you need to iterate and
+# do something to each attribute of an object.
+#
+jq -n '{a: 1, b: 2, c: 3} | to_entries | map(.value *= 2) | from_entries'
+
+# Output:
+# {
+# "a": 2,
+# "b": 4,
+# "c": 6
+# }
+
+
+# The example above can be further shortened with the `with_entries/1` built-in:
+#
+jq -n '{a: 1, b: 2, c: 3} | with_entries(.value *= 2)'
+
+
+# The `group_by/1` generates an array of groups (arrays) from the current
+# input (array). The classification is done by applying the expression argument
+# to each member of the input array.
+#
+# Let's look at a contrived example (Note that `tostring`, `tonumber`,
+# `length` and `max` are all built-in jq functions. Feel free to look
+# them up in the jq manual):
+#
+# Generate some random numbers.
+numbers=$(echo $RANDOM{,,,,,,,,,,,,,,,,,,,,})
+#
+# Feed the numbers to jq, classifying them into groups and calculating their
+# averages, and finally generate a report.
+#
+echo $numbers | jq -rs ' # Slurp the numbers into an array.
+[
+ [ map(tostring) # Turn it into an array of strings.
+ | group_by(.[0:1]) # Group the numbers by their first digits.
+ | .[] # Iterate through the array of arrays (groups).
+ | map(tonumber) # Turn each group back to an array of numbers.
+ ] # Finally, contain all groups in an array.
+
+ | sort_by([length, max]) # Sort the groups by their sizes.
+ # If two groups have the same size then the one with the largest
+ # number wins (is bigger).
+
+ | to_entries[] # Enumerate the array, generating key-value objects.
+ | # For each object, generate two lines:
+ "Group \(.key): \(.value | sort | join(" "))" + "\n" +
+ "Average: \( .value | (add / length) )"
+
+] # Contain the group+average lines in an array.
+ # Join the array elements by separator lines (dashes) to produce the report.
+| join("\n" + "-"*78 + "\n")
+'
+
+# Output:
+#
+# Group 0: 3267
+# Average: 3267
+# ------------------------------------------------------------------------------
+# Group 1: 7854
+# Average: 7854
+# ------------------------------------------------------------------------------
+# Group 2: 4415 4447
+# Average: 4431
+# ------------------------------------------------------------------------------
+# Group 3: 681 6426
+# Average: 3553.5
+# ------------------------------------------------------------------------------
+# Group 4: 21263 21361 21801 21832 22947 23523 29174
+# Average: 23128.714285714286
+# ------------------------------------------------------------------------------
+# Group 5: 10373 12698 13132 13924 17444 17963 18934 18979
+# Average: 15430.875
+
+
+# The `add/1` built-in "reduces" an array of values to a single value.
+# You can think of it as sticking the `+` operator in between each value of
+# the collection. Here are some examples:
+#
+jq -n '[1, 2, 3, 4, 5] | add' # => 15
+jq -n '["a", "b", "c"] | add' # => "abc"
+
+# `+` concatenates arrays
+jq -n '[["a"], ["b"], ["c"]] | add'
+
+# Output:
+# [
+# "a",
+# "b",
+# "c"
+# ]
+
+# `+` merges objects non-recursively.
+jq -n '[{a: 1, b: {c: 3}}, {b: 2, c: 4}] | add'
+
+# Output:
+# {
+# "a": 1,
+# "b": 2,
+# "c": 4
+# }
+
+
+# jq provides a special syntax for writing an expression that reduces
+# the outputs generated by a given expresion to a single value.
+# It has this form:
+#
+# reduce outputs_expr as $var (initial_value; reduction_expr)
+#
+# Examples:
+#
+jq -n 'reduce range(1; 6) as $i (0; . + $i)' # => 15
+jq -n 'reduce (1, 2, 3, 4, 5) as $i (0; . + $i)' # => 15
+jq -n '[1, 2, 3, 4, 5] | reduce .[] as $i (0; . + $i)' # => 15
+jq -n '["a", "b", "c"] | reduce .[] as $i (""; . + $i)' # => "abc"
+
+# Notice the `.` in the `reduction_expr` is the `initial_value` at first,
+# and then it becomes the result of applying the `reduction_expr` as
+# we iterate through the values of `outputs_expr`. The expression:
+#
+# reduce (1, 2, 3, 4, 5) as $i (0; . + $i)
+#
+# can be thought of as doing:
+#
+# 0 + 1 | . + 2 | . + 3 | . + 4 | . + 5
+#
+
+
+# The `*` operator when used on two objects, merges both recursively.
+# Therefore, to merge JSON objects recursively, you can use `reduce`
+# with the `*` operator. For example:
+#
+echo '
+ {"a": 1, "b": {"c": 3}}
+ { "b": {"d": 4}}
+ {"a": 99, "e": 5 }
+' | jq -s 'reduce .[] as $m ({}; . * $m)'
+
+# Output:
+# {
+# "a": 99,
+# "b": {
+# "c": 3,
+# "d": 4
+# },
+# "e": 5
+# }
+
+
+# jq has variable assignment in the form of `expr as $var`, which binds
+# the value of `expr` to `$var`, and `$var` is immutable. Further more,
+# `... as ...` doesn't change the input of the next filter; its introduction
+# in a filter pipeline is only for establishing the binding of a value to a
+# variable, and its scope extends to the filters following its definition.
+# (i.e., to look up a variable's definition, scan to the left of the filter
+# chain from the expression using it until you find the definition)
+#
+jq -rn '[1, 2, 3, 4, 5]
+ | (.[0] + .[-1]) as $sum # Always put ( ) around the binding `expr` to avoid surprises.
+ | ($sum * length / 2) as $result # The current input at this step is still the initial array.
+ | "The result is: \($result)" # Same.
+'
+
+# Output:
+# The result is: 15
+
+
+# With the `expr as $var` form, if multiple values are generated by `expr`
+# then jq will iterate through them and bind each value to `$var` in turn
+# for the rest of the pipeline.
+#
+jq -rn 'range(2; 4) as $i
+ | range(1; 6) as $j
+ | "\($i) * \($j) = \($i * $j)"
+'
+
+# Output:
+# 2 * 1 = 2
+# 2 * 2 = 4
+# 2 * 3 = 6
+# 2 * 4 = 8
+# 2 * 5 = 10
+# 3 * 1 = 3
+# 3 * 2 = 6
+# 3 * 3 = 9
+# 3 * 4 = 12
+# 3 * 5 = 15
+
+
+# It's sometimes useful to bind the initial input to a variable at the
+# start of a program, so that you can refer to it later down the pipeline.
+#
+jq -rn "$(cat <<'EOF'
+ {lookup: {a: 1, b: 2, c: 3},
+ bonuses: {a: 5, b: 2, c: 9}
+ }
+ | . as $doc
+ | .bonuses
+ | to_entries[]
+ | "\(.key)'s total is \($doc.lookup[.key] + .value)"
+EOF
+)"
+
+# Output:
+# a's total is 6
+# b's total is 4
+# c's total is 12
+
+
+# jq supports destructing during varible binding. This lets you extract values
+# from an array or an object and bind them to variables.
+#
+jq -n '[range(5)] | . as [$first, $second] | $second'
+
+# Output:
+# 1
+
+jq -n '{ name: "Tom", numbers: [1, 2, 3], age: 32}
+ | . as {
+ name: $who, # bind .name to $who
+ $name, # shorthand for `name: $name`
+ numbers: [$first, $second],
+ }
+ | $name, $second, $first, $who
+'
+
+# Output:
+# "Tom"
+# 2
+# 1
+# "Tom"
+
+
+# In jq, values can be assigned to an array index or object key via the
+# assignment operator, `=`. The same current input is given to both sides
+# of the assignment operator, and the assignment itself evaluates to the
+# current input. In other words, the assignment expression is evaluated
+# for its side effect, and doesn't generate a new output.
+#
+jq -n '.a = 1 | .b = .a + 1' # => {"a": 1, "b": 2}
+
+# Note that input is `null` due to `jq -n`, so `.` is `null` in the first
+# filter, and assiging to a key under `null` turns it into an object with
+# the key. The same input (now an object) then gets piped to the next filter,
+# which then sets the `b` key to the value of the `a` key plus `1`, which is `2`.
+#
+
+# Another example:
+#
+jq -n '.a=1, .a.b=2' # => {"a": 1} {"a": {"b": 2}}
+
+# In the above example, two objects are generated because both assignments
+# received `null` as their inputs, and each operand of the comma operator
+# is evaluated independently. Notice also how you can easily generate
+# nested objects.
+
+
+# In addition to the assignment operator, jq also has operators like:
+# `+=`, `-=`, `*=`, and '/=', ... etc. Basically, `a op= b` is a shorthand
+# for `a = a op b`, and they are handy for updating an object attribute or
+# an item in an array based on its current value. Examples:
+#
+jq -n '.a.b.c = 3 | .a.b.c = .a.b.c + 1' # => {"a": {"b": {"c": 4}}}
+jq -n '.a.b.c = 3 | .a.b.c += 1' # => {"a": {"b": {"c": 4}}}
+
+
+# To delete a value, use `del/1`, which takes a path expression that specifies
+# the locations of the things to be deleted. Example:
+#
+jq -n '{a: 1, b: {c: 2}, d: [3, 4, 5]} | del(.b.c, .d[1]) | .b.x = 6'
+
+# Output:
+# {
+# "a": 1,
+# "b": {
+# "x": 6
+# },
+# "d": [
+# 3,
+# 5
+# ]
+# }
+
+
+# Other than using jq's built-in functions, you can define your own.
+# In fact, many built-in functions are defined using jq (see the link
+# to jq's built-in functions at the end of the doc).
+#
+jq -n '
+ def my_select(expr): if expr then . else empty end;
+ def my_map(expr): [.[] | expr];
+ def sum: reduce .[] as $x (0; . + $x);
+ def my_range($from; $to):
+ if $from >= $to then
+ empty
+ else
+ $from, my_range($from + 1; $to)
+ end
+ ;
+ [my_range(1; 6)] | my_map(my_select(. % 2 != 0)) | sum
+'
+
+# Output:
+# 9
+
+# Some notes about function definitons:
+#
+# - Functions are usually defined at the beginning, so that they are available
+# to the rest of the jq program.
+#
+# - Each function definion should end with a `;` (semicolon).
+#
+# - It's also possible to define a function within another, though it's not shown here.
+#
+# - Function parameters are separated by `;` (semicolor). This is consistent with
+# passing multiple arguments when calling a function.
+#
+# - A function can call itself; in fact, jq has TCO (Tail Call Optimization).
+#
+# - `def f($a; $b): ...;` is a shorthand for: `def f(a; b): a as $a | b as $b | ...`
+```
+
+
+## Further Reading
+- https://stedolan.github.io/jq/manual/
+- https://github.com/stedolan/jq/wiki/jq-Language-Description
+- https://github.com/stedolan/jq/wiki/Cookbook
+- https://github.com/stedolan/jq/blob/master/src/builtin.jq
diff --git a/jquery.html.markdown b/jquery.html.markdown
index 18077dca..cdcb89d9 100644
--- a/jquery.html.markdown
+++ b/jquery.html.markdown
@@ -12,8 +12,8 @@ jQuery is a JavaScript library that helps you "do more, write less". It makes ma
Because jQuery is a JavaScript library you should [learn JavaScript first](https://learnxinyminutes.com/docs/javascript/)
**NOTE**: jQuery has fallen out of the limelight in recent years, since you can achieve the same thing with the vanilla DOM (Document Object Model) API. So the only thing it is used for is a couple of handy features, such as the [jQuery date picker](https://api.jqueryui.com/datepicker) (which actually has a standard, unlike the `<input type="date">` HTML element), and the obvious decrease in the code length.
-```js
+```js
///////////////////////////////////
// 1. Selectors
diff --git a/json.html.markdown b/json.html.markdown
index 1ccdb5cf..27f6bbe0 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -11,7 +11,7 @@ contributors:
JSON is an extremely simple data-interchange format. As [json.org](https://json.org) says, it is easy for humans to read and write and for machines to parse and generate.
-A piece of JSON must represent either:
+A piece of JSON can be any value of the types listed later, but in practice almost always represents either:
* A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence.
diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown
index 241caf5f..f077c35b 100644
--- a/jsonnet.html.markdown
+++ b/jsonnet.html.markdown
@@ -131,7 +131,7 @@ assert obj5 == {};
```
## Further Reading
-There are a few but important concepts that are not touched in this exmaple, including:
+There are a few but important concepts that are not touched in this example, including:
- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config)
- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports)
diff --git a/julia.html.markdown b/julia.html.markdown
index 4d8eb497..336cd2b8 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -356,6 +356,20 @@ intersect(filledSet, otherSet) # => Set([4, 3, 5])
union(filledSet, otherSet) # => Set([4, 2, 3, 5, 6, 1])
setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1])
+# Assignment with `=` attaches a new label to the same value without copying
+a = [1, 2, 3]
+b = a
+# Now `b` and `a` point to the same value, so changing one affects the other:
+a[3] = 5
+b[3] # => 5
+
+# The `copy()` function can create a shallow copy of an array, dictionary,
+# or other container
+a = [1, 2, 3]
+c = copy(a)
+a[3] = 5
+c[3] # => 3
+
####################################################
## 3. Control Flow
####################################################
diff --git a/kdb+.html.markdown b/kdb+.html.markdown
index 680c01c1..db842726 100644
--- a/kdb+.html.markdown
+++ b/kdb+.html.markdown
@@ -560,7 +560,7 @@ select avg height by sex from t
/ => f | 160
/ => m | 177.5
-/ If no aggreation function is specified, last is assumed
+/ If no aggregation function is specified, last is assumed
select by sex from t
/ => sex| name age height
/ => ---| -----------------
diff --git a/ko-kr/clojure-kr.html.markdown b/ko-kr/clojure-kr.html.markdown
index 1d9e53cd..32a5baf3 100644
--- a/ko-kr/clojure-kr.html.markdown
+++ b/ko-kr/clojure-kr.html.markdown
@@ -377,7 +377,7 @@ Clojuredocs.org는 core í•¨ìˆ˜ë“¤ì— ëŒ€í•´ 다양한 예제와 문서를 보유
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure는 clojure/FP ìŠ¤í‚¬ì„ ì˜¬ë¦´ 수 있는 ì¢‹ì€ ê¸¸ìž…ë‹ˆë‹¤:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org는 많고 ë§Žì€ ë¬¸ì„œë“¤ì„ ë³´ìœ í•˜ê³  있습니다:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown
index 3012c04f..aed0918e 100644
--- a/ko-kr/go-kr.html.markdown
+++ b/ko-kr/go-kr.html.markdown
@@ -81,7 +81,7 @@ func learnTypes() {
// non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다.
g := 'Σ' // 유니코드 코드 í¬ì¸íŠ¸ë¥¼ ë‹´ê³  있고, int32 íƒ€ìž…ì˜ ê°€ì¹­(alias)ì¸ rune 타입
- f := 3.14195 // float64, an IEEE-754 64-bit 부ë™ì†Œìˆ˜ 타입
+ f := 3.14159 // float64, an IEEE-754 64-bit 부ë™ì†Œìˆ˜ 타입
c := 3 + 4i // complex128, 내부ì ìœ¼ë¡œëŠ” ë‘ ê°œì˜ float64 타입으로 표현ë¨
// 초기값과 함께 사용하는 var 키워드.
@@ -332,15 +332,15 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
## ë” ì½ì–´ë³¼ 것들
-Goì— ëŒ€í•œ 모든 ê²ƒë“¤ì€ [Go ê³µì‹ ì›¹ 사ì´íŠ¸](http://golang.org/)를 참고하ìž.
+Goì— ëŒ€í•œ 모든 ê²ƒë“¤ì€ [Go ê³µì‹ ì›¹ 사ì´íŠ¸](https://go.dev/)를 참고하ìž.
여기ì—는 ë”°ë¼í•´ë³¼ 튜토리얼, 웹 ê¸°ë°˜ì˜ ì¸í„°ëž™í‹°ë¸Œ 실행환경과 ë§Žì€ ì½ì„ê±°ë¦¬ë“¤ì´ ìžˆë‹¤.
Go 언어 ìžì²´ì— 대한 ìŠ¤íŽ™ë„ ì½ì–´ë³´ê¸°ë¥¼ ì ê·¹ 추천한다. ì½ê¸° 쉽게 ë˜ì–´ìžˆê³ 
그리 길지는 않다.
-Go ì†ŒìŠ¤ì½”ë“œì— ëŒ€í•´ ì¢€ë” ì•Œì•„ë³´ê³  싶다면 [Go 표준 ë¼ì´ë¸ŒëŸ¬ë¦¬](http://golang.org/src/pkg/)를
+Go ì†ŒìŠ¤ì½”ë“œì— ëŒ€í•´ ì¢€ë” ì•Œì•„ë³´ê³  싶다면 [Go 표준 ë¼ì´ë¸ŒëŸ¬ë¦¬](https://go.dev/src/)를
분ì„해보기 바란다. ì´í•´í•˜ê¸° 쉽게 문서화ë˜ì–´ 있고, Go ìŠ¤íƒ€ì¼ ê·¸ë¦¬ê³  Goì—ì„œì˜
-관례 ë°°ìš°ê¸°ì— ê°€ìž¥ ì¢‹ì€ ë°©ë²•ì¼ ê²ƒì´ë‹¤. ë˜ëŠ” [문서](http://golang.org/pkg/) 안ì—ì„œ
+관례 ë°°ìš°ê¸°ì— ê°€ìž¥ ì¢‹ì€ ë°©ë²•ì¼ ê²ƒì´ë‹¤. ë˜ëŠ” [문서](https://go.dev/pkg/) 안ì—ì„œ
함수 ì´ë¦„ 하나를 í´ë¦­í•´ë³´ë©´ 소스코드를 브ë¼ìš°ì €ì—ì„œ 살펴볼 ìˆ˜ë„ ìžˆë‹¤.
Go를 배울수 있는 ë˜í•˜ë‚˜ì˜ ì¢‹ì€ ë°©ë²•ì€ [Go by example](https://gobyexample.com/).
diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown
index 397e9f30..0167f0ff 100644
--- a/ko-kr/markdown-kr.html.markdown
+++ b/ko-kr/markdown-kr.html.markdown
@@ -25,15 +25,18 @@ lang: ko-kr
## HTML 요소
HTMLì€ ë§ˆí¬ë‹¤ìš´ì˜ 수í¼ì…‹ìž…니다. 모든 HTML 파ì¼ì€ 유효한 마í¬ë‹¤ìš´ì´ë¼ëŠ” 것입니다.
+
```md
<!--ë”°ë¼ì„œ 주ì„ê³¼ ê°™ì€ HTML ìš”ì†Œë“¤ì„ ë§ˆí¬ë‹¤ìš´ì— 사용할 수 있으며, 마í¬ë‹¤ìš´ íŒŒì„œì— ì˜í–¥ì„
받지 ì•Šì„ ê²ƒìž…ë‹ˆë‹¤. 하지만 마í¬ë‹¤ìš´ 파ì¼ì—ì„œ HTML 요소를 만든다면 ê·¸ ìš”ì†Œì˜ ì•ˆì—서는
마í¬ë‹¤ìš´ ë¬¸ë²•ì„ ì‚¬ìš©í•  수 없습니다.-->
```
+
## 제목
í…스트 ì•žì— ë¶™ì´ëŠ” 우물 ì • 기호(#)ì˜ ê°¯ìˆ˜ì— ë”°ë¼ `<h1>`부터 `<h6>`ê¹Œì§€ì˜ HTML 요소를
ì†ì‰½ê²Œ 작성할 수 있습니다.
+
```md
# <h1>입니다.
## <h2>입니다.
@@ -42,7 +45,9 @@ HTMLì€ ë§ˆí¬ë‹¤ìš´ì˜ 수í¼ì…‹ìž…니다. 모든 HTML 파ì¼ì€ 유효한 마í
##### <h5>입니다.
###### <h6>입니다.
```
+
ë˜í•œ h1ê³¼ h2를 나타내는 다른 ë°©ë²•ì´ ìžˆìŠµë‹ˆë‹¤.
+
```md
h1입니다.
=============
@@ -50,9 +55,11 @@ h1입니다.
h2입니다.
-------------
```
+
## 간단한 í…스트 꾸미기
마í¬ë‹¤ìš´ìœ¼ë¡œ 쉽게 í…스트를 기울ì´ê±°ë‚˜ 굵게 í•  수 있습니다.
+
```md
*ê¸°ìš¸ì¸ í…스트입니다.*
_ì´ í…ìŠ¤íŠ¸ë„ ê°™ìŠµë‹ˆë‹¤._
@@ -64,10 +71,13 @@ __ì´ í…ìŠ¤íŠ¸ë„ ê°™ìŠµë‹ˆë‹¤.__
**_ì´ í…ìŠ¤íŠ¸ë„ ê°™ìŠµë‹ˆë‹¤._**
*__ì´ê²ƒë„ 같습니다.__*
```
+
깃헙 ì „ìš© 마í¬ë‹¤ìš´ì—는 ì·¨ì†Œì„ ë„ ìžˆìŠµë‹ˆë‹¤.
+
```md
~~ì´ í…스트ì—는 ì·¨ì†Œì„ ì´ ê·¸ë ¤ì§‘ë‹ˆë‹¤.~~
```
+
## 문단
ë¬¸ë‹¨ì€ í•˜ë‚˜ ì´ìƒì˜ 빈 줄로 구분ë˜ëŠ”, í•œ 줄 ì´ìƒì˜ ì¸ì ‘í•œ í…스트입니다.
@@ -103,6 +113,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, ë‘ ê°œ ì´ìƒì˜ ë„ì–´ì“
## 목ë¡
순서가 없는 목ë¡ì€ 별표, ë”하기, 하ì´í”ˆì„ ì´ìš©í•´ 만들 수 있습니다.
+
```md
* ì´ê±°
* 저거
@@ -140,6 +151,7 @@ HTML `<br />` 태그를 삽입하고 싶으시다면, ë‘ ê°œ ì´ìƒì˜ ë„ì–´ì“
1. 둘
1. ì…‹
```
+
(ìœ„ì˜ ì˜ˆì‹œì™€ ë˜‘ê°™ì´ ë‚˜íƒ€ë‚©ë‹ˆë‹¤.)
ëª©ë¡ ì•ˆì— ëª©ë¡ì´ 올 ìˆ˜ë„ ìžˆìŠµë‹ˆë‹¤.
@@ -176,7 +188,7 @@ xê°€ 없는 ë°•ìŠ¤ë“¤ì€ ì²´í¬ë˜ì§€ ì•Šì€ HTML ì²´í¬ë°•ìŠ¤ìž…니다.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -188,12 +200,13 @@ xê°€ 없는 ë°•ìŠ¤ë“¤ì€ ì²´í¬ë˜ì§€ ì•Šì€ HTML ì²´í¬ë°•ìŠ¤ìž…니다.
깃헙 ì „ìš© 마í¬ë‹¤ìš´ì—서는 코드를 나타내기 위해 특별한 ë¬¸ë²•ì„ ì“¸ 수 있습니다.
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
ìœ„ì˜ ê²½ìš°ì— ë“¤ì—¬ì“°ê¸°ê°€ í•„ìš”ì—†ì„ ë¿ ì•„ë‹ˆë¼ \`\`\` ë’¤ì— íŠ¹ì •í•´ 준 ì–¸ì–´ì˜ ë¬¸ë²•ì— ë”°ë¼
ìƒ‰ì„ ìž…í˜€ì¤„ 것입니다.
@@ -202,12 +215,14 @@ end
수í‰ì„ (`<hr/>`)ì€ ì…‹ ì´ìƒì˜ 별표나 하ì´í”ˆì„ ì´ìš©í•´ 쉽게 나타낼 수 있습니다.
ë„어쓰기가 í¬í•¨ë  수 있습니다.
+
```md
***
---
- - -
****************
```
+
## ë§í¬
마í¬ë‹¤ìš´ì˜ ìž¥ì  ì¤‘ 하나는 ë§í¬ë¥¼ 만들기 쉽다는 것입니다. 대괄호 ì•ˆì— ë‚˜íƒ€ë‚¼ í…스트를 ì“°ê³ 
@@ -231,20 +246,24 @@ end
참조하는 ì‹ìœ¼ë¡œ ë§í¬ë¥¼ 걸 ìˆ˜ë„ ìžˆìŠµë‹ˆë‹¤.
-<pre><code class="highlight">&#x5b;<span class="nv">ì´ </span>][<span class="ss">ë§í¬</span>]ì—ì„œ ë” ì•Œì•„ë³´ì„¸ìš”!
-&#x5b;<span class="nv">ì›í•˜ì‹ ë‹¤ë©´ </span>][<span class="ss">foobar</span>]ë„ ì°¸ê³ í•˜ì„¸ìš”.
+```md
+[ì´ ][ë§í¬]ì—ì„œ ë” ì•Œì•„ë³´ì„¸ìš”!
+[ì›í•˜ì‹ ë‹¤ë©´ ][foobar]ë„ ì°¸ê³ í•˜ì„¸ìš”.
-&#x5b;<span class="nv">ë§í¬</span>]: <span class="sx">http://test.com/</span> <span class="nn">"좋아!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"ë다!"</span></code></pre>
+[ë§í¬]: http://test.com/ "좋아!"
+[foobar]: http://foobar.biz/ "ë다!"
+```
ì œëª©ì€ ìž‘ì€ ë”°ì˜´í‘œë‚˜ ê´„í˜¸ì— ë“¤ì–´ê°ˆ ìˆ˜ë„ ìžˆê³ , 완전히 ìƒëžµí•  ìˆ˜ë„ ìžˆìŠµë‹ˆë‹¤. 참조는 문서ì˜
ì–´ëŠ ê³³ì—ë“  올 수 있고 참조 ID는 유ì¼í•˜ë‹¤ë©´ 무엇ì´ë“  ë  ìˆ˜ 있습니다.
ë§í¬ í…스트를 IDë¡œ 사용하는 "ë¬µì‹œì  ì´ë¦„"ë„ ìžˆìŠµë‹ˆë‹¤.
-<pre><code class="highlight">&#x5b;<span class="nv">ì´ê²ƒ</span>][]ì€ ë§í¬ìž…니다.
+```md
+[ì´ê²ƒ][]ì€ ë§í¬ìž…니다.
-&#x5b;<span class="nv">ì´ê²ƒ</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[ì´ê²ƒ]: http://thisisalink.com/
+```
하지만 보통 그렇게 추천하지는 않습니다.
@@ -257,9 +276,11 @@ end
참조 ë°©ì‹ë„ 가능합니다.
-<pre><code class="highlight">!&#x5b;<span class="nv">alt ì†ì„±</span>][<span class="ss">ì´ë¯¸ì§€</span>]
+```md
+![alt ì†ì„±][ì´ë¯¸ì§€]
-&#x5b;<span class="nv">ì´ë¯¸ì§€</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"ì œëª©ì´ í•„ìš”í•˜ë‹¤ë©´ 여기ì—"</span></code></pre>
+[ì´ë¯¸ì§€]: relative/urls/cool/image.jpg "ì œëª©ì´ í•„ìš”í•˜ë‹¤ë©´ 여기ì—"
+```
## 기타
### ìžë™ ë§í¬
@@ -270,9 +291,11 @@ end
```
### ì´ë©”ì¼ ìžë™ ë§í¬
+
```md
<foo@bar.com>
```
+
### 탈출 문ìž
```md
@@ -292,17 +315,21 @@ end
### 표
표는 깃헙 ì „ìš© 마í¬ë‹¤ìš´ì—서만 쓸 수 있고 다소 복잡하지만, ì •ë§ ì“°ê³  싶으시다면
+
```md
| 1ì—´ | 2ì—´ | 3ì—´ |
| :--------| :-------: | --------: |
| 왼쪽 ì •ë ¬ | ê°€ìš´ë° ì •ë ¬ | 오른쪽 ì •ë ¬ |
| 머시기 | 머시기 | 머시기 |
```
+
혹ì€
+
```md
1ì—´ | 2ì—´ | 3ì—´
:-- | :-: | --:
으악 너무 못ìƒê²¼ì–´ | 그만 | 둬
```
+
---
추가 정보를 위해, ì¡´ ê·¸ë£¨ë²„ì˜ ê³µì‹ ë¬¸ë²• [(ì˜ì–´) 문서](http://daringfireball.net/projects/markdown/syntax)와 ì• ë¤ í”„ë¦¿ì°¨ë“œì˜ í›Œë¥­í•œ [(ì˜ì–´) 치트싯](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)ì„ í™•ì¸í•˜ì„¸ìš”.
diff --git a/kotlin.html.markdown b/kotlin.html.markdown
index 12008074..a6fac518 100644
--- a/kotlin.html.markdown
+++ b/kotlin.html.markdown
@@ -26,7 +26,7 @@ any parameters.
*/
fun main(args: Array<String>) {
/*
- Declaring values is done using either "var" or "val".
+ Declaring variables is done using either "var" or "val".
"val" declarations cannot be reassigned, whereas "vars" can.
*/
val fooVal = 10 // we cannot later reassign fooVal to something else
@@ -297,7 +297,7 @@ fun helloWorld(val name : String) {
else -> println("none of the above")
}
- // "when" can be used as a function that returns a value.
+ // "when" can be used as an expression that returns a value.
var result = when (i) {
0, 21 -> "0 or 21"
in 1..20 -> "in the range 1 to 20"
diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown
index 958dd746..775907c2 100644
--- a/lambda-calculus.html.markdown
+++ b/lambda-calculus.html.markdown
@@ -41,7 +41,7 @@ Evaluation is done via
which is essentially lexically-scoped substitution.
When evaluating the
-expression `(λx.x)a`, we replace all occurences of "x" in the function's body
+expression `(λx.x)a`, we replace all occurrences of "x" in the function's body
with "a".
- `(λx.x)a` evaluates to: `a`
diff --git a/latex.html.markdown b/latex.html.markdown
index 34c4b78d..9edc057e 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -320,3 +320,5 @@ That's all for now!
* The amazing LaTeX Wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
+* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/)
+* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/)
diff --git a/lbstanza.html.markdown b/lbstanza.html.markdown
index 19dc7db7..90e7b7e5 100644
--- a/lbstanza.html.markdown
+++ b/lbstanza.html.markdown
@@ -8,7 +8,7 @@ contributors:
LB Stanza (or Stanza for short) is a new optionally-typed general purpose programming language from the University of California, Berkeley. Stanza was designed to help programmers tackle the complexity of architecting large programs and significantly increase the productivity of application programmers across the entire software development life cycle.
-```stanza
+```
; this is a comment
;<A>
This is a block comment
@@ -193,7 +193,7 @@ while condition[0]:
for i in 0 to 10 do:
vector[i] = i
-; stanza also supports named labels which can functin as break or return
+; stanza also supports named labels which can function as break or return
; statements
defn another-fn ():
label<False> return:
@@ -218,7 +218,7 @@ for (x in xs, y in ys, z in zs) do :
println("x:%_, y:%_, z:%_" % [x, y, z])
-;xs, ys, and zs are all "Seqable" meaing they are Seq types (sequences).
+;xs, ys, and zs are all "Seqable" meaning they are Seq types (sequences).
; the `do` identifier is a special function that just applies the body of
; the for loop to each element of the sequence.
;
@@ -268,7 +268,7 @@ is-there = any?({_ == 2.0}, numbers)
doc: \<doc>
# Document Strings
- ```stanza
+ ```
val you-can = "include code snippets, too"
```
@@ -279,4 +279,4 @@ doc: \<doc>
```
\<doc>
defn docfn () : false
-``` \ No newline at end of file
+```
diff --git a/ldpl.html.markdown b/ldpl.html.markdown
index 86603d94..449c8670 100644
--- a/ldpl.html.markdown
+++ b/ldpl.html.markdown
@@ -3,6 +3,7 @@ language: LDPL
filename: learnLDPL.ldpl
contributors:
- ["Martín del Río", "https://github.com/lartu"]
+ - ["John Paul Wohlscheid", "https://github.com/JohnBlood"]
---
**LDPL** is a powerful, C++ transpiled, open-source programming language designed
@@ -68,7 +69,7 @@ else if myMap:"someIndex" is not equal to 45 then
else
display "Else!" crlf
end if
-# Valid LDPL comparisson operators are
+# Valid LDPL comparison operators are
# - IS EQUAL TO
# - IS NOT EQUAL TO
# - IS LESS THAN
@@ -123,8 +124,8 @@ get random in myNumber # get a random number between 0 and 1
# files, are divided in sections. The sections found in sub-procedures are
# the PARAMETERS section, the LOCAL DATA section and the PROCEDURE section.
# All sections except the PROCEDURE section can be skipped if they aren't
-# used. If no PARAMTERS nor LOCAL DATA sections are used, the PROCEDURE
-# keyword may be omited.
+# used. If no PARAMETERS nor LOCAL DATA sections are used, the PROCEDURE
+# keyword may be omitted.
sub myFunction
parameters:
a is number # LDPL is pass by reference
diff --git a/lua.html.markdown b/lua.html.markdown
index ac7883b2..f11d67a8 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -17,10 +17,7 @@ filename: learnlua.lua
-- 1. Variables and flow control.
----------------------------------------------------
-num = 42 -- All numbers are doubles.
--- Don't freak out, 64-bit doubles have 52 bits for
--- storing exact int values; machine precision is
--- not a problem for ints that need < 52 bits.
+num = 42 -- Numbers can be integer or floating point.
s = 'walternate' -- Immutable strings like Python.
t = "double-quotes are also fine"
@@ -58,7 +55,7 @@ foo = anUnknownVariable -- Now foo = nil.
aBoolValue = false
-- Only nil and false are falsy; 0 and '' are true!
-if not aBoolValue then print('twas false') end
+if not aBoolValue then print('it was false') end
-- 'or' and 'and' are short-circuited.
-- This is similar to the a?b:c operator in C/js:
@@ -193,7 +190,7 @@ end
-- A table can have a metatable that gives the table
-- operator-overloadish behavior. Later we'll see
--- how metatables support js-prototypey behavior.
+-- how metatables support js-prototype behavior.
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
f2 = {a = 2, b = 3}
@@ -364,7 +361,7 @@ end)()
-- locals inside mod.lua are invisible outside it.
-- This works because mod here = M in mod.lua:
-mod.sayHello() -- Says hello to Hrunkner.
+mod.sayHello() -- Prints: Why hello there Hrunkner
-- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName() -- error
@@ -402,11 +399,11 @@ If you need support join the official Lua [mailing list](https://www.lua.org/lua
I was excited to learn Lua so I could make games
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why.
-I started with <a href="https://ebens.me/post/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
+I started with <a href="https://ebens.me/posts/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book.
That's the how.
-It might be helpful to check out the <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short
+It might be helpful to check out the <a href="http://lua-users.org/wiki/LuaShortReference">Lua short
reference</a> on lua-users.org.
The main topics not covered are standard libraries:
diff --git a/m.html.markdown b/m.html.markdown
index 96828ae5..46e7313b 100644
--- a/m.html.markdown
+++ b/m.html.markdown
@@ -17,8 +17,8 @@ more fits on one screen without scrolling.
The M database is a hierarchical key-value store designed for high-throughput
transaction processing. The database is organized into tree structures called
-"globals", which are sparse data structures with parallels to modern formats
-like JSON.
+"globals", (for global variables) which are sparse data structures with parallels
+to modern formats like JSON.
Originally designed in 1966 for the healthcare applications, M continues to be
used widely by healthcare systems and financial institutions for high-throughput
@@ -26,7 +26,7 @@ real-time applications.
### Example
-Here's an example M program to calculate the Fibonacci series:
+Here's an example M program using expanded syntax to calculate the Fibonacci series:
```
fib ; compute the first few Fibonacci terms
@@ -39,28 +39,38 @@ fib ; compute the first few Fibonacci terms
```
### Comments
+Comments in M need at least one space before the comment marker of semicolon.
+Comments that start with at least two semicolons (;;) are guaranteed to be accessible
+within a running program.
```
-; Comments start with a semicolon (;)
+ ; Comments start with a semicolon (;)
```
### Data Types
-M has two data types:
+M has one data type (String) and three interpretations of that string.:
```
-; Numbers - no commas, leading and trailing 0 removed.
-; Scientific notation with 'E'.
-; Floats with IEEE 754 double-precision values (15 digits of precision)
-; Examples: 20, 1e3 (stored as 1000), 0500.20 (stored as 500.2)
; Strings - Characters enclosed in double quotes.
; "" is the null string. Use "" within a string for "
; Examples: "hello", "Scrooge said, ""Bah, Humbug!"""
+;
+; Numbers - no commas, leading and trailing 0 removed.
+; Scientific notation with 'E'. (not 'e')
+; Numbers with at least with IEEE 754 double-precision values (guaranteed 15 digits of precision)
+; Examples: 20 (stored as 20) , 1e3 (stored as 1000), 0500.20 (stored as 500.2),
+; the US National Debt AT sometime on 12-OCT-2020 retrieved from http://www.usdebt.org is 27041423576201.15)
+; (required to be stored as at least 27041422576201.10 but most implementations store as 27041432576201.15)
+;
+; Truthvalues - String interpreted as 0 is used for false and any string interpreted as non-zero (such as 1) for true.
```
### Commands
-Commands are case insensitive, and have a shortened abbreviation, often the first letter. Commands have zero or more arguments,depending on the command. M is whitespace-aware. Spaces are treated as a delimiter between commands and arguments. Each command is separated from its arguments by 1 space. Commands with zero arguments are followed by 2 spaces.
+Commands are case insensitive, and have full form, and a shortened abbreviation, often the first letter. Commands have zero or more arguments,depending on the command. This page includes programs written in this terse syntax. M is whitespace-aware. Spaces are treated as a delimiter between commands and arguments. Each command is separated from its arguments by 1 space. Commands with zero arguments are followed by 2 spaces. (technically these are called argumentless commands)
+
+#### Common Commands from all National and International Standards of M
-#### W(rite)
+#### Write (abbreviated as W)
Print data to the current device.
@@ -68,13 +78,19 @@ Print data to the current device.
WRITE !,"hello world"
```
-! is syntax for a new line. Multiple statements can be provided as additional arguments:
+Output Formatting characters:
+
+ The ! character is syntax for a new line.
+ The # character is syntax for a new page.
+ The sequence of the ? character and then a numeric expression is syntax for output of spaces until the number'th colum is printed.
+
+Multiple statements can be provided as additional arguments before the space separators to the next command:
```
w !,"foo bar"," ","baz"
```
-#### R(ead)
+#### Read (abbreviated as R)
Retrieve input from the user
@@ -82,13 +98,13 @@ Retrieve input from the user
READ var
r !,"Wherefore art thou Romeo? ",why
```
-Multiple arguments can be passed to a read command. Constants are outputted. Variables are retrieved from the user. The terminal waits for the user to enter the first variable before displaying the second prompt.
+As with all M commands, multiple arguments can be passed to a read command. Constants like quoted strings, numbers, and formatting characters are output directly. Values for both global variables and local variables are retrieved from the user. The terminal waits for the user to enter the first variable before displaying the second prompt.
```
r !,"Better one, or two? ",lorem," Better two, or three? ",ipsum
```
-#### S(et)
+#### Set (abbreviated as S)
Assign a value to a variable
@@ -100,19 +116,21 @@ w !,centi,!,micro
;.01
;.00001
```
-#### K(ill)
+#### Kill (abbreviated as K)
Remove a variable from memory or remove a database entry from disk.
-
+A database node (global variable) is killed depending on the variable name being prefixed by the caret character (^).
+If it is not, then the local variable is removed from memory.
+If KILLed, automatic garbage collection occurs.
```
KILL centi
k micro
```
### Globals and Arrays
-In addition to local variables, M has persistent variables stored to disk called _globals_. Global names must start with a __caret__ (__^__). Globals are the built-in database of M.
+In addition to local variables, M has persistent, shared variables that are the built-in database of M. They are stored to disk and called _globals_. Global names must start with a __caret__ (__^__).
-Any variable can be an array with the assignment of a _subscript_. Arrays are sparse and do not have a predefined size. Arrays should be visualized like trees, where subscripts are branches and assigned values are leaves. Not all nodes in an array need to have a value.
+Any variable (local or global) can be an array with the assignment of a _subscript_. Arrays are sparse and do not have a predefined size. Only if data is stored will a value use memory. Arrays should be visualized like trees, where subscripts are branches and assigned values are leaves. Not all nodes in an array need to have a value.
```
s ^cars=20
@@ -128,7 +146,7 @@ w !,^cars("Tesla",1,"Name")
; Model 3
```
-Arrays are automatically sorted in order. Take advantage of the built-in sorting by setting your value of interest as the last child subscript of an array rather than its value.
+The index values of Arrays are automatically sorted in order. There is a catchphrase of "MUMPS means never having to say you are sorting". Take advantage of the built-in sorting by setting your value of interest as the last child subscript of an array rather than its value, and then storing an empty string for that node.
```
; A log of temperatures by date and time
@@ -171,13 +189,14 @@ s ^TEMPS("11/12","1700",43)=""
#### Order of operations
Operations in M are _strictly_ evaluated left to right. No operator has precedence over any other.
-You should use parentheses to group expressions.
+For example, there is NO order of operations where multiply is evaluated before addition.
+To change this order, just use parentheses to group expressions to be evaluated first.
```
w 5+3*20
;160
;You probably wanted 65
-w 5+(3*20)
+write 5+(3*20)
```
### Flow Control, Blocks, & Code Structure
@@ -193,12 +212,12 @@ w !,$$tag^routine(a,b)
M has an execution stack. When all levels of the stack have returned, the program ends. Levels are added to the stack with _do_ commands and removed with _quit_ commands.
-#### D(o)
+#### Do (abbreviated as D)
With an argument: execute a block of code & add a level to the stack.
```
-d ^routine ;run a routine from the begining.
+d ^routine ;run a routine from the beginning.
; ;routines are identified by a caret.
d tag ;run a tag in the current routine
d tag^routine ;run a tag in different routine
@@ -216,12 +235,14 @@ if a=1 do
w "hello"
```
-#### Q(uit)
+#### Quit (abbreviated as Q)
Stop executing this block and return to the previous stack level.
-Quit can return a value.
+Quit can return a value, following the comamnd with a single space.
+Quit can stop a loop. remember to follow with two spaces.
+Quit outside a loop will return from the current subroutine followed by two spaces or a linefeed
-#### N(ew)
-Clear a given variable's value _for just this stack level_. Useful for preventing side effects.
+#### New (abbreviated as N)
+Hide with a cleared value a given variable's value _for just this stack level_. Useful for preventing side effects.
Putting all this together, we can create a full example of an M routine:
@@ -233,20 +254,22 @@ main
n length,width ; New length and width so any previous value doesn't persist
w !,"Welcome to RECTANGLE. Enter the dimensions of your rectangle."
r !,"Length? ",length,!,"Width? ",width
- d area(length,width) ;Do a tag
- s per=$$perimeter(length,width) ;Get the value of a function
+ d area(length,width) ;Do/Call subroutine using a tag
+ s per=$$perimeter(length,width) ;Get the value of a function
w !,"Perimeter: ",per
- q
+ quit
area(length,width) ; This is a tag that accepts parameters.
; It's not a function since it quits with no value.
w !, "Area: ",length*width
- q ; Quit: return to the previous level of the stack.
+ q ; Quit: return to the previous level of the stack.
perimeter(length,width)
- q 2*(length+width) ; Quits with a value; thus a function
+ q 2*(length+width) ; Returns a value using Quit ; this is a function
```
+
+
### Conditionals, Looping and $Order()
F(or) loops can follow a few different patterns:
@@ -255,13 +278,15 @@ F(or) loops can follow a few different patterns:
;Finite loop with counter
;f var=start:increment:stop
-f i=0:5:25 w i," " ;0 5 10 15 20 25
+f i=0:5:25 w i," "
+;0 5 10 15 20 25
; Infinite loop with counter
; The counter will keep incrementing forever. Use a conditional with Quit to get out of the loop.
;f var=start:increment
-f j=1:1 w j," " i j>1E3 q ; Print 1-1000 separated by a space
+f j=1:1 w j," " i j>1E3 q
+; Print 1-1000 separated by a space
;Argumentless for - infinite loop. Use a conditional with Quit.
; Also read as "forever" - f or for followed by two spaces.
@@ -355,7 +380,11 @@ f s date=$ORDER(^TEMPS(date)) q:date="" d
## Further Reading
-There's lots more to learn about M. A great short tutorial comes from the University of Northern Iowa and Professor Kevin O'Kane's [Introduction to the MUMPS Language][1] presentation.
+There's lots more to learn about M. A great short tutorial comes from the University of Northern Iowa and Professor Kevin O'Kane's [Introduction to the MUMPS Language][1] presentation. More about M using VistA is at
+
+Intersystems has some products which are a super-set of the M programming language.
+* [Iris Description Page][5]
+* [Cache Description Page][6]
To install an M interpreter / database on your computer, try a [YottaDB Docker image][2].
@@ -368,3 +397,5 @@ YottaDB and its precursor, GT.M, have thorough documentation on all the language
[2]: https://yottadb.com/product/get-started/
[3]: https://docs.yottadb.com/ProgrammersGuide/langfeat.html
[4]: http://tinco.pair.com/bhaskar/gtm/doc/books/pg/UNIX_manual/index.html
+[5]: https://www.intersystems.com/products/intersystems-iris/
+[6]: https://en.wikipedia.org/wiki/InterSystems_Caché
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 60ca1323..ee213083 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -40,9 +40,9 @@ specific to a certain parser.
Markdown is a superset of HTML, so any HTML file is valid Markdown.
```md
-<!--This means we can use HTML elements in Markdown, such as the comment
-element, and they won't be affected by a markdown parser. However, if you
-create an HTML element in your markdown file, you cannot use markdown syntax
+<!--This means we can use HTML elements in Markdown, such as the comment
+element, and they won't be affected by a markdown parser. However, if you
+create an HTML element in your markdown file, you cannot use markdown syntax
within that element's contents.-->
```
@@ -169,9 +169,9 @@ render the numbers in order, but this may not be a good idea.
1. Item three
```
-(This renders the same as the above example)
+(This renders the same as the example above.)
-You can also use sublists
+You can also use sublists.
```md
1. Item one
@@ -203,31 +203,32 @@ a line with four spaces or a tab.
```
You can also re-tab (or add an additional four spaces) for indentation
-inside your code
+inside your code.
```md
my_array.each do |item|
- puts item
+ puts item
end
```
-Inline code can be created using the backtick character `` ` ``
+Inline code can be created using the backtick character `` ` ``.
```md
John didn't even know what the `go_to()` function did!
```
-In GitHub Flavored Markdown, you can use a special syntax for code
+In GitHub Flavored Markdown, you can use a special syntax for code.
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
The above text doesn't require indenting, plus GitHub will use syntax
-highlighting of the language you specify after the \`\`\`
+highlighting of the language you specify after the opening <code>```</code>.
## Horizontal rule
@@ -264,11 +265,13 @@ Relative paths work too.
Markdown also supports reference style links.
-<pre><code class="highlight">&#x5b;<span class="nv">Click this link</span>][<span class="ss">link1</span>] for more info about it!
-&#x5b;<span class="nv">Also check out this link</span>][<span class="ss">foobar</span>] if you want to.
+```md
+[Click this link][link1] for more info about it!
+[Also check out this link][foobar] if you want to.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Cool!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Alright!"</span></code></pre>
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+```
The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
@@ -276,9 +279,11 @@ can be anything so long as they are unique.
There is also "implicit naming" which lets you use the link text as the id.
-<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+```md
+[This][] is a link.
-&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[This]: http://thisisalink.com/
+```
But it's not that commonly used.
@@ -298,7 +303,7 @@ omitted though.)
- [Subchapter <h3 />](#subchapter-h3-)
```
-Nontheless, this is a feature that might not be working in all Markdown
+Nonetheless, this is a feature that might not be working in all Markdown
implementations the same way.
## Images
@@ -311,9 +316,11 @@ Images are done the same way as links but with an exclamation point in front!
And reference style works as expected.
-<pre><code class="highlight">!&#x5b;<span class="nv">This is the alt-attribute.</span>][<span class="ss">myimage</span>]
+```md
+![This is the alt-attribute.][myimage]
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"if you need a title, it's here"</span></code></pre>
+[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
+```
## Miscellany
@@ -370,9 +377,10 @@ Ugh this is so ugly | make it | stop
## Markdownlint
In order to simplify work with Markdown and to unify its coding style,
-`Markdownlint` has been created. This tool is available also as a plugin for
-some IDEs and can be used as an utility to ensure validity and readability of
-Markdown.
+`Markdownlint` has been created. Available as a
+[separate tool](https://github.com/markdownlint/markdownlint)
+as well as a plugin for some IDEs, it can be used to ensure validity and
+readability of Markdown.
---
diff --git a/matlab.html.markdown b/matlab.html.markdown
index ecf2fc96..b0482d0b 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -1,5 +1,5 @@
---
-language: Matlab
+language: MATLAB
filename: learnmatlab.mat
contributors:
- ["mendozao", "http://github.com/mendozao"]
@@ -134,7 +134,7 @@ A.d.e = false;
% Vectors
x = [4 32 53 7 1]
-x(2) % ans = 32, indices in Matlab start 1, not 0
+x(2) % ans = 32, indices in MATLAB start 1, not 0
x(2:3) % ans = 32 53
x(2:end) % ans = 32 53 7 1
@@ -502,7 +502,7 @@ find(x) % Finds all non-zero elements of x and returns their indexes, can use co
% Classes
-% Matlab can support object-oriented programming.
+% MATLAB can support object-oriented programming.
% Classes must be put in a file of the class name with a .m extension.
% To begin, we create a simple class to store GPS waypoints.
% Begin WaypointClass.m
@@ -524,7 +524,7 @@ classdef WaypointClass % The class name.
end
% If we want to add two Waypoint objects together without calling
- % a special function we can overload Matlab's arithmetic like so:
+ % a special function we can overload MATLAB's arithmetic like so:
function r = plus(o1,o2)
r = WaypointClass([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]);
@@ -536,7 +536,7 @@ end
% We can create an object of the class using the constructor
a = WaypointClass(45.0, 45.0)
-% Class properties behave exactly like Matlab Structures.
+% Class properties behave exactly like MATLAB Structures.
a.latitude = 70.0
a.longitude = 25.0
@@ -547,15 +547,15 @@ ans = multiplyLatBy(a,3)
% does not need to be passed to the method.
ans = a.multiplyLatBy(1/3)
-% Matlab functions can be overloaded to handle objects.
-% In the method above, we have overloaded how Matlab handles
+% MATLAB functions can be overloaded to handle objects.
+% In the method above, we have overloaded how MATLAB handles
% the addition of two Waypoint objects.
b = WaypointClass(15.0, 32.0)
c = a + b
```
-## More on Matlab
+## More on MATLAB
* [The official website](http://www.mathworks.com/products/matlab/)
* [The official MATLAB Answers forum](http://www.mathworks.com/matlabcentral/answers/)
diff --git a/mercurial.html.markdown b/mercurial.html.markdown
index 98658f83..2c06ca77 100644
--- a/mercurial.html.markdown
+++ b/mercurial.html.markdown
@@ -22,13 +22,13 @@ and/or directorie(s) over time.
* Distributed Architecture - Traditionally version control systems such as CVS
and Subversion are a client server architecture with a central server to
-store the revsion history of a project. Mercurial however is a truly
-distributed architecture, giving each devloper a full local copy of the
+store the revision history of a project. Mercurial however is a truly
+distributed architecture, giving each developer a full local copy of the
entire development history. It works independently of a central server.
* Fast - Traditionally version control systems such as CVS and Subversion are a
-client server architecture with a central server to store the revsion history
+client server architecture with a central server to store the revision history
of a project. Mercurial however is a truly distributed architecture, giving
-each devloper a full local copy of the entire development history. It works
+each developer a full local copy of the entire development history. It works
independently of a central server.
* Platform Independent - Mercurial was written to be highly platform
independent. Much of Mercurial is written in Python, with small performance
@@ -56,7 +56,7 @@ any later version.
| changeset | Set of changes saved as diffs |
| diff | Changes between file(s) |
| tag | A named named revision |
-| parent(s) | Immediate ancestor(s) of a revison |
+| parent(s) | Immediate ancestor(s) of a revision |
| branch | A child of a revision |
| head | A head is a changeset with no child changesets |
| merge | The process of merging two HEADS |
@@ -184,7 +184,7 @@ Commit changes to the given files into the repository.
# Commit with a message
$ hg commit -m 'This is a commit message'
-# Commit all added / removed files in the currrent tree
+# Commit all added / removed files in the current tree
$ hg commit -A 'Adding and removing all existing files in the tree'
# amend the parent of the working directory with a new commit that contains the
@@ -341,7 +341,7 @@ $ hg revert -a
Remove the specified files on the next commit.
```bash
-# Remove a spcific file
+# Remove a specific file
$ hg remove go_away.txt
# Remove a group of files by pattern
diff --git a/mips.html.markdown b/mips.html.markdown
index 0e7a7d0c..3add0c5b 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -111,7 +111,7 @@ gateways and routers.
sub $t2, $t0, $t1 # $t2 = $t0 - $t1
mul $t2, $t0, $t1 # $t2 = $t0 * $t1
div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be
- # supported in some versons of MARS)
+ # supported in some versions of MARS)
div $t0, $t1 # Performs $t0 / $t1. Get the
# quotient using 'mflo' and
# remainder using 'mfhi'
@@ -162,7 +162,7 @@ gateways and routers.
blt $t0, $t1, t0_gt_t1 # Branches when $t0 < $t1
ble $t0, $t1, t0_gte_t1 # Branches when $t0 <= $t1
bltz $t0, t0_lt0 # Branches when $t0 < 0
- slt $s0, $t0, $t1 # Instruction that sends a signal
+ slt $s0, $t0, $t1 # "Set on Less Than"
# when $t0 < $t1 with result in $s0
# (1 for true)
@@ -186,6 +186,7 @@ gateways and routers.
# else
# max = c;
# else
+ # if (b > c)
# max = b;
# else
# max = c;
@@ -212,8 +213,9 @@ gateways and routers.
# instruction to continue its execution
li $t0, 0
while:
- bgt $t0, 10, end_while # While $t0 is less than 10,
+ bgt $t0, 9, end_while # While $t0 is less than 10,
# keep iterating
+ #actual loop content would go here
addi $t0, $t0, 1 # Increment the value
j while # Jump back to the beginning of
# the loop
diff --git a/mongodb.html.markdown b/mongodb.html.markdown
index 959b57d0..f4e7d709 100644
--- a/mongodb.html.markdown
+++ b/mongodb.html.markdown
@@ -228,7 +228,7 @@ db.engineers.update({ name: 'Foo Baz' },
)
/////////////////////// Delete /////////////////////////
-// Queries are in the form of db.collectionName.find(<filter>)
+// Queries are in the form of db.collectionName.delete(<filter>)
// Delete first document matching query, always returns deletedCount
db.engineers.deleteOne({ name: 'Foo Baz' })
@@ -252,20 +252,21 @@ db.engineers.deleteMany({ gender: 'Male' })
//////////////// Comparison Operators ///////////////////
// Find all greater than or greater than equal to some condition
-db.engineers.find({ $gt: { age: 25 }})
-db.engineers.find({ $gte: { age: 25 }})
+db.engineers.find({ age: { $gt: 25 }})
+db.engineers.find({ age: { $gte: 25 }})
// Find all less than or less than equal to some condition
-db.engineers.find({ $lte: { age: 25 }})
-db.engineers.find({ $lte: { age: 25 }})
+db.engineers.find({ age: { $lt: 25 }})
+db.engineers.find({ age: { $lte: 25 }})
// Find all equal or not equal to
// Note: the $eq operator is added implicitly in most queries
-db.engineers.find({ $eq: { age: 25 }})
-db.engineers.find({ $ne: { age: 25 }})
+db.engineers.find({ age: { $eq: 25 }})
+db.engineers.find({ age: { $ne: 25 }})
-// Find all that match any element in the array
-db.engineers.find({ age: ${ in: [ 20, 23, 24, 25 ]}})
+// Find all that match any element in the array, or not in the array
+db.engineers.find({ age: { $in: [ 20, 23, 24, 25 ]}})
+db.engineers.find({ age: { $nin: [ 20, 23, 24, 25 ]}})
//////////////// Logical Operators ///////////////////
@@ -293,7 +294,7 @@ db.engineers.find({ $not: {
// Must match none of the query conditions
db.engineers.find({ $nor [
- gender: 'Female,
+ gender: 'Female',
age: {
$gte: 18
}
@@ -400,6 +401,6 @@ features, I would look at
- Aggregation - useful for creating advanced queries to be executed by the
database
-- Idexing allows for caching, which allows for much faster execution of queries
+- Indexing allows for caching, which allows for much faster execution of queries
- Sharding allows for horizontal data scaling and distribution between multiple
machines.
diff --git a/montilang.html.markdown b/montilang.html.markdown
index cceb7aa1..483dc5a5 100644
--- a/montilang.html.markdown
+++ b/montilang.html.markdown
@@ -170,7 +170,7 @@ printseven
/# currently, preprocessor statements can be used to make c++-style constants #/
&DEFINE LOOPSTR 20&
-/# must have & on either side with no spaces, 'DEFINE' is case sensative. #/
+/# must have & on either side with no spaces, 'DEFINE' is case sensitive. #/
/# All statements are scanned and replaced before the program is run, regardless of where the statements are placed #/
FOR LOOPSTR 7 PRINT . ENDFOR /# Prints '7' 20 times. At run, 'LOOPSTR' in source code is replaced with '20' #/
diff --git a/ms-my/clojure-my.html.markdown b/ms-my/clojure-my.html.markdown
index e199c8f4..cfcdeb40 100644
--- a/ms-my/clojure-my.html.markdown
+++ b/ms-my/clojure-my.html.markdown
@@ -413,7 +413,7 @@ Clojuredocs.org mempunyai dokumentasi berserta contoh untuk menggunakan kebanyak
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure ialah cara yang baik untuk mengasah skill Clojure dan functional programming:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org (yup, serius) juga mengandungi beberapa artikel sebagai permulaan:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/neat.html.markdown b/neat.html.markdown
deleted file mode 100644
index f02461ee..00000000
--- a/neat.html.markdown
+++ /dev/null
@@ -1,297 +0,0 @@
----
-language: neat
-contributors:
- - ["Feep", "https://github.com/FeepingCreature"]
-filename: LearnNeat.nt
----
-
-Neat is basically a smaller version of D1 with some experimental syntax and a focus on terseness without losing the basic C-like syntax.
-
-[Read more here.](https://github.com/FeepingCreature/fcc/wiki)
-
-```c
-// single line comments start with //
-/*
- multiline comments look like this
-*/
-/+
- or this
- /+ these can be nested too, same as D +/
-+/
-
-// Module name. This has to match the filename/directory.
-module LearnNeat;
-
-// Make names from another module visible in this one.
-import std.file;
-// You can import multiple things at once.
-import std.math, std.util;
-// You can even group up imports!
-import std.(process, socket);
-
-// Global functions!
-void foo() { }
-
-// Main function, same as in C.
-// string[] == "array of strings".
-// "string" is just an alias for char[],
-void main(string[] args) {
- // Call functions with "function expression".
- writeln "Hello World";
- // You can do it like in C too... if you really want.
- writeln ("Hello World");
- // Declare a variable with "type identifier"
- string arg = ("Hello World");
- writeln arg;
- // (expression, expression) forms a tuple.
- // There are no one-value tuples though.
- // So you can always use () in the mathematical sense.
- // (string) arg; <- is an error
-
- /*
- byte: 8 bit signed integer
- char: 8 bit UTF-8 byte component.
- short: 16 bit signed integer
- int: 32 bit signed integer
- long: 64 bit signed integer
-
- float: 32 bit floating point
- double: 64 bit floating point
- real: biggest native size floating point (80 bit on x86).
-
- bool: true or false
- */
- int a = 5;
- bool b = true;
- // as in C, && and || are short-circuit evaluating.
- b = b && false;
- assert(b == false);
- // "" are "format strings". So $variable will be substituted at runtime
- // with a formatted version of the variable.
- writeln "$a";
- // This will just print $a.
- writeln `$a`;
- // you can format expressions with $()
- writeln "$(2+2)";
- // Note: there is no special syntax for characters.
- char c = "a";
- // Cast values by using type: expression.
- // There are three kinds of casts:
- // casts that just specify conversions that would be happening automatically
- // (implicit casts)
- float f = float:5;
- float f2 = 5; // would also work
- // casts that require throwing away information or complicated computation -
- // those must always be done explicitly
- // (conversion casts)
- int i = int:f;
- // int i = f; // would not work!
- // and, as a last attempt, casts that just reinterpret the raw data.
- // Those only work if the types have the same size.
- string s = "Hello World";
- // Arrays are (length, pointer) pairs.
- // This is a tuple type. Tuple types are (type, type, type).
- // The type of a tuple expression is a tuple type. (duh)
- (int, char*) array = (int, char*): s;
- // You can index arrays and tuples using the expression[index] syntax.
- writeln "pointer is $(array[1]) and length is $(array[0])";
- // You can slice them using the expression[from .. to] syntax.
- // Slicing an array makes another array.
- writeln "$(s[0..5]) World";
- // Alias name = expression gives the expression a name.
- // As opposed to a variable, aliases do not have an address
- // and can not be assigned to. (Unless the expression is assignable)
- alias range = 0 .. 5;
- writeln "$(s[range]) World";
- // You can iterate over ranges.
- for int i <- range {
- write "$(s[i])";
- }
- writeln " World";
- // Note that if "range" had been a variable, it would be 'empty' now!
- // Range variables can only be iterated once.
- // The syntax for iteration is "expression <- iterable".
- // Lots of things are iterable.
- for char c <- "Hello" { write "$c"; }
- writeln " World";
- // For loops are "for test statement";
- alias test = char d <- "Hello";
- for test write "$d";
- writeln " World\t\x05"; // note: escapes work
- // Pointers: function the same as in C, btw. The usual.
- // Do note: the pointer star sticks with the TYPE, not the VARIABLE!
- string* p;
- assert(p == null); // default initializer
- p = &s;
- writeln "$(*p)";
- // Math operators are (almost) standard.
- int x = 2 + 3 * 4 << 5;
- // Note: XOR is "xor". ^ is reserved for exponentiation (once I implement that).
- int y = 3 xor 5;
- int z = 5;
- assert(z++ == 5);
- assert(++z == 7);
- writeln "x $x y $y z $z";
- // As in D, ~ concatenates.
- string hewo = "Hello " ~ "World";
- // == tests for equality, "is" tests for identity.
- assert (hewo == s);
- assert !(hewo is s);
- // same as
- assert (hewo !is s);
-
- // Allocate arrays using "new array length"
- int[] integers = new int[] 10;
- assert(integers.length == 10);
- assert(integers[0] == 0); // zero is default initializer
- integers = integers ~ 5; // This allocates a new array!
- assert(integers.length == 11);
-
- // This is an appender array.
- // Instead of (length, pointer), it tracks (capacity, length, pointer).
- // When you append to it, it will use the free capacity if it can.
- // If it runs out of space, it reallocates - but it will free the old array automatically.
- // This makes it convenient for building arrays.
- int[auto~] appender;
- appender ~= 2;
- appender ~= 3;
- appender.free(); // same as {mem.free(appender.ptr); appender = null;}
-
- // Scope variables are automatically freed at the end of the current scope.
- scope int[auto~] someOtherAppender;
- // This is the same as:
- int[auto~] someOtherAppender2;
- onExit { someOtherAppender2.free; }
-
- // You can do a C for loop too
- // - but why would you want to?
- for (int i = 0; i < 5; ++i) { }
- // Otherwise, for and while are the same.
- while int i <- 0..4 {
- assert(i == 0);
- break; // continue works too
- } then assert(false); // if we hadn't break'd, this would run at the end
- // This is the height of loopdom - the produce-test-consume loop.
- do {
- int i = 5;
- } while (i == 5) {
- assert(i == 5);
- break; // otherwise we'd go back up to do {
- }
-
- // This is a nested function.
- // Nested functions can access the surrounding function.
- string returnS() { return s; }
- writeln returnS();
-
- // Take the address of a function using &
- // The type of a global function is ReturnType function(ParameterTypeTuple).
- void function() foop = &foo;
-
- // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
- string delegate() returnSp = &returnS;
- writeln returnSp();
- // Class member functions and struct member functions also fit into delegate variables.
- // In general, delegates are functions that carry an additional context pointer.
- // ("fat pointers" in C)
-
- // Allocate a "snapshot" with "new delegate".
- // Snapshots are not closures! I used to call them closures too,
- // but then my Haskell-using friends yelled at me so I had to stop.
- // The difference is that snapshots "capture" their surrounding context
- // when "new" is used.
- // This allows things like this
- int delegate(int) add(int a) {
- int add_a(int b) { return a + b; }
- // This does not work - the context of add_a becomes invalid
- // when add returns.
- // return &add_a;
- // Instead:
- return new &add_a;
- }
- int delegate(int) dg = add 2;
- assert (dg(3) == 5);
- // or
- assert (((add 2) 3) == 5);
- // or
- assert (add 2 3 == 5);
- // add can also be written as
- int delegate(int) add2(int a) {
- // this is an implicit, nameless nested function.
- return new λ(int b) { return a + b; }
- }
- // or even
- auto add3(int a) { return new λ(int b) -> a + b; }
- // hahahaaa
- auto add4 = λ(int a) -> new λ(int b) -> a + b;
- assert(add4 2 3 == 5);
- // If your keyboard doesn't have a λ (you poor sod)
- // you can use \ too.
- auto add5 = \(int a) -> new \(int b) -> a + b;
- // Note!
- auto nestfun = λ() { } // There is NO semicolon needed here!
- // "}" can always substitute for "};".
- // This provides syntactic consistency with built-in statements.
-
-
- // This is a class.
- // Note: almost all elements of Neat can be used on the module level
- // or just as well inside a function.
- class C {
- int a;
- void writeA() { writeln "$a"; }
- // It's a nested class - it exists in the context of main().
- // so if you leave main(), any instances of C become invalid.
- void writeS() { writeln "$s"; }
- }
- C cc = new C;
- // cc is a *reference* to C. Classes are always references.
- cc.a = 5; // Always used for property access.
- auto ccp = &cc;
- (*ccp).a = 6;
- // or just
- ccp.a = 7;
- cc.writeA();
- cc.writeS(); // to prove I'm not making things up
- // Interfaces work same as in D, basically. Or Java.
- interface E { void doE(); }
- // Inheritance works same as in D, basically. Or Java.
- class D : C, E {
- override void writeA() { writeln "hahahahaha no"; }
- override void doE() { writeln "eeeee"; }
- // all classes inherit from Object. (toString is defined in Object)
- override string toString() { return "I am a D"; }
- }
- C cd = new D;
- // all methods are always virtual.
- cd.writeA();
- E e = E:cd; // dynamic class cast!
- e.doE();
- writeln "$e"; // all interfaces convert to Object implicitly.
-
- // Templates!
- // Templates are parameterized namespaces, taking a type as a parameter.
- template Templ(T) {
- alias hi = 5, hii = 8;
- // Templates always have to include something with the same name as the template
- // - this will become the template's _value_.
- // Static ifs are evaluated statically, at compile-time.
- // Because of this, the test has to be a constant expression,
- // or something that can be optimized to a constant.
- static if (types-equal (T, int)) {
- alias Templ = hi;
- } else {
- alias Templ = hii;
- }
- }
- assert(Templ!int == 5);
- assert(Templ!float == 8);
-}
-```
-
-## Topics Not Covered
-
- * Extended iterator types and expressions
- * Standard library
- * Conditions (error handling)
- * Macros
diff --git a/nim.html.markdown b/nim.html.markdown
index 9730e579..81662630 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -3,7 +3,7 @@ language: Nim
filename: learnNim.nim
contributors:
- ["Jason J. Ayala P.", "http://JasonAyala.com"]
- - ["Dennis Felsing", "http://felsin9.de/nnis/"]
+ - ["Dennis Felsing", "https://dennis.felsing.org"]
---
Nim (formerly Nimrod) is a statically typed, imperative programming language
@@ -142,7 +142,7 @@ when compileBadCode:
# Arrays
type
- RollCounter = array[DieFaces, int] # Array's are fixed length and
+ RollCounter = array[DieFaces, int] # Arrays are fixed length and
DirNames = array[Direction, string] # indexed by any ordinal type.
Truths = array[42..44, bool]
var
diff --git a/nix.html.markdown b/nix.html.markdown
index 1d5a7778..c2a2c074 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -305,6 +305,9 @@ with builtins; [
({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; }
#=> "a-b"
+ # The entire set can be bound to a variable using `@`
+ (args@{x, y}: args.x + "-" + args.y) { x = "a"; y = "b"; }
+ #=> "a-b"
# Errors
#=========================================
@@ -355,7 +358,7 @@ with builtins; [
# its contents. You can read files from anywhere. In this example,
# we write a file into the store, and then read it back out.
(let filename = toFile "foo.txt" "hello!"; in
- [filename (builtins.readFile filename)])
+ [filename (readFile filename)])
#=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ]
# We can also download files into the Nix store.
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index c029c5fb..c179c295 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -387,7 +387,7 @@ if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains meth
// Implement the methods in an implementation (MyClass.m) file:
@implementation MyClass {
long distance; // Private access instance variable
- NSNumber height;
+ NSNumber *height;
}
// To access a public variable from the interface file, use '_' followed by variable name:
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index 70668611..2c5e13d5 100644
--- a/ocaml.html.markdown
+++ b/ocaml.html.markdown
@@ -3,26 +3,31 @@ language: OCaml
filename: learnocaml.ml
contributors:
- ["Daniil Baturin", "http://baturin.org/"]
+ - ["Stanislav Modrak", "https://stanislav.gq/"]
+ - ["Luke Tong", "https://lukert.me/"]
---
-
OCaml is a strictly evaluated functional language with some imperative
features.
-Along with StandardML and its dialects it belongs to ML language family.
+Along with Standard ML and its dialects it belongs to ML language family.
F# is also heavily influenced by OCaml.
-Just like StandardML, OCaml features both an interpreter, that can be
+Just like Standard ML, OCaml features both an interpreter, that can be
used interactively, and a compiler.
-The interpreter binary is normally called "ocaml" and the compiler is "ocamlopt".
-There is also a bytecode compiler, "ocamlc", but there are few reasons to use it.
+The interpreter binary is normally called `ocaml` and the compiler is `ocamlopt`.
+There is also a bytecode compiler, `ocamlc`, but there are few reasons to use it.
+
+It also includes a package manager, `opam`, and a build system, `dune`.
It is strongly and statically typed, but instead of using manually written
-type annotations, it infers types of expressions using Hindley-Milner algorithm.
+type annotations, it infers types of expressions using the
+[Hindley-Milner](https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system)
+algorithm.
It makes type annotations unnecessary in most cases, but can be a major
source of confusion for beginners.
When you are in the top level loop, OCaml will print the inferred type
-after you enter an expression.
+after you enter an expression
```
# let inc x = x + 1 ;;
@@ -31,8 +36,8 @@ val inc : int -> int = <fun>
val a : int = 99
```
-For a source file you can use "ocamlc -i /path/to/file.ml" command
-to print all names and type signatures.
+For a source file you can use the `ocamlc -i /path/to/file.ml` command
+to print all names and type signatures
```
$ cat sigtest.ml
@@ -48,12 +53,12 @@ val a : int
```
Note that type signatures of functions of multiple arguments are
-written in curried form. A function that takes multiple arguments can be
+written in [curried](https://en.wikipedia.org/wiki/Currying) form.
+A function that takes multiple arguments can be
represented as a composition of functions that take only one argument.
-The "f(x,y) = x + y" function from the example above applied to
-arguments 2 and 3 is equivalent to the "f0(y) = 2 + y" function applied to 3.
-Hence the "int -> int -> int" signature.
-
+The `f(x,y) = x + y` function from the example above applied to
+arguments 2 and 3 is equivalent to the `f0(y) = 2 + y` function applied to 3.
+Hence the `int -> int -> int` signature.
```ocaml
(*** Comments ***)
@@ -65,13 +70,14 @@ Hence the "int -> int -> int" signature.
(*** Variables and functions ***)
-(* Expressions can be separated by a double semicolon symbol, ";;".
+(* Expressions can be separated by a double semicolon ";;".
In many cases it's redundant, but in this tutorial we use it after
every expression for easy pasting into the interpreter shell.
Unnecessary use of expression separators in source code files
is often considered to be a bad style. *)
-(* Variable and function declarations use "let" keyword. *)
+(* Variable and function declarations use the "let" keyword. *)
+(* Variables are immutable by default in OCaml *)
let x = 10 ;;
(* OCaml allows single quote characters in identifiers.
@@ -109,42 +115,42 @@ let sqr2 = sqr (-2) ;;
"unit" type for it that has the only one value written as "()" *)
let print_hello () = print_endline "hello world" ;;
-(* Note that you must specify "()" as argument when calling it. *)
+(* Note that you must specify "()" as the argument when calling it. *)
print_hello () ;;
-(* Calling a function with insufficient number of arguments
+(* Calling a function with an insufficient number of arguments
does not cause an error, it produces a new function. *)
let make_inc x y = x + y ;; (* make_inc is int -> int -> int *)
let inc_2 = make_inc 2 ;; (* inc_2 is int -> int *)
inc_2 3 ;; (* Evaluates to 5 *)
-(* You can use multiple expressions in function body.
+(* You can use multiple expressions in the function body.
The last expression becomes the return value. All other
expressions must be of the "unit" type.
This is useful when writing in imperative style, the simplest
- form of it is inserting a debug print. *)
+ form of which is inserting a debug print. *)
let print_and_return x =
print_endline (string_of_int x);
x
;;
(* Since OCaml is a functional language, it lacks "procedures".
- Every function must return something. So functions that
- do not really return anything and are called solely for their
- side effects, like print_endline, return value of "unit" type. *)
+ Every function must return something. So functions that do not
+ really return anything and are called solely for their side
+ effects, like print_endline, return a value of "unit" type. *)
-(* Definitions can be chained with "let ... in" construct.
- This is roughly the same to assigning values to multiple
+(* Definitions can be chained with the "let ... in" construct.
+ This is roughly the same as assigning values to multiple
variables before using them in expressions in imperative
languages. *)
let x = 10 in
let y = 20 in
x + y ;;
-(* Alternatively you can use "let ... and ... in" construct.
+(* Alternatively you can use the "let ... and ... in" construct.
This is especially useful for mutually recursive functions,
- with ordinary "let .. in" the compiler will complain about
+ with ordinary "let ... in" the compiler will complain about
unbound values. *)
let rec
is_even = function
@@ -186,9 +192,9 @@ let my_lambda = fun x -> x * x ;;
~-. 3.4 (* Float only *)
(* You can define your own operators or redefine existing ones.
- Unlike SML or Haskell, only selected symbols can be used
- for operator names and first symbol defines associativity
- and precedence rules. *)
+ Unlike Standard ML or Haskell, only certain symbols can be
+ used for operator names and the operator's first symbol determines
+ its associativity and precedence rules. *)
let (+) a b = a - b ;; (* Surprise maintenance programmers. *)
(* More useful: a reciprocal operator for floats.
@@ -223,6 +229,10 @@ List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;;
often referred to as "cons". *)
1 :: [2; 3] ;; (* Gives [1; 2; 3] *)
+(* Remember that the cons :: constructor can only cons a single item to the front
+ of a list. To combine two lists use the append @ operator *)
+[1; 2] @ [3; 4] ;; (* Gives [1; 2; 3; 4] *)
+
(* Arrays are enclosed in [| |] *)
let my_array = [| 1; 2; 3 |] ;;
@@ -258,7 +268,7 @@ let ocaml = (String.make 1 'O') ^ "Caml" ;;
(* There is a printf function. *)
Printf.printf "%d %s" 99 "bottles of beer" ;;
-(* Unformatted read and write functions are there too. *)
+(* There's also unformatted read and write functions. *)
print_string "hello world\n" ;;
print_endline "hello world" ;;
let line = read_line () ;;
@@ -291,15 +301,59 @@ let my_point = Point (2.0, 3.0) ;;
type 'a list_of_lists = 'a list list ;;
type int_list_list = int list_of_lists ;;
+(* These features allow for useful optional types *)
+type 'a option = Some of 'a | None ;;
+let x = Some x ;;
+let y = None ;;
+
(* Types can also be recursive. Like in this type analogous to
- built-in list of integers. *)
+ a built-in list of integers. *)
type my_int_list = EmptyList | IntList of int * my_int_list ;;
let l = IntList (1, EmptyList) ;;
+(* or Trees *)
+type 'a tree =
+ | Empty
+ | Node of 'a tree * 'a * 'a tree
+
+let example_tree: int tree =
+ Node (
+ Node (Empty, 7, Empty),
+ 5,
+ Node (Empty, 9, Empty)
+ )
+(*
+ 5
+ / \
+ 7 9
+*)
+
+(*** Records ***)
+
+(* A collection of values with named fields *)
+
+type animal =
+ {
+ name: string;
+ color: string;
+ legs: int;
+ }
+;;
+
+let cow =
+ { name: "cow";
+ color: "black and white";
+ legs: 4;
+ }
+;;
+val cow : animal
+
+cow.name ;;
+- : string = "cow"
(*** Pattern matching ***)
-(* Pattern matching is somewhat similar to switch statement in imperative
+(* Pattern matching is somewhat similar to the switch statement in imperative
languages, but offers a lot more expressive power.
Even though it may look complicated, it really boils down to matching
@@ -311,7 +365,7 @@ let l = IntList (1, EmptyList) ;;
let is_zero x =
match x with
| 0 -> true
- | _ -> false (* The "_" pattern means "anything else". *)
+ | _ -> false (* The "_" means "anything else". *)
;;
(* Alternatively, you can use the "function" keyword. *)
@@ -342,6 +396,19 @@ let say x =
say (Cat "Fluffy") ;; (* "Fluffy says meow". *)
+(* However, pattern matching must be exhaustive *)
+type color = Red | Blue | Green ;;
+let what_color x =
+ match x with
+ | Red -> "color is red"
+ | Blue -> "color is blue"
+ (* Won't compile! You have to add a _ case or a Green case
+ to ensure all possibilities are accounted for *)
+;;
+(* Also, the match statement checks each case in order.
+ So, if a _ case appears first, none of the
+ following cases will be reached! *)
+
(** Traversing data structures with pattern matching **)
(* Recursive types can be traversed with pattern matching easily.
@@ -369,9 +436,75 @@ let rec sum_int_list l =
let t = Cons (1, Cons (2, Cons (3, Nil))) ;;
sum_int_list t ;;
+(* Heres a function to tell if a list is sorted *)
+let rec is_sorted l =
+ match l with
+ | x :: y :: tail -> x <= y && is_sorted (y :: tail)
+ | _ -> true
+;;
+
+is_sorted [1; 2; 3] ;; (* True *)
+(* OCaml's powerful type inference guesses that l is of type int list
+ since the <= operator is used on elements of l *)
+
+(* And another to reverse a list *)
+let rec rev (l: 'a list) : 'a list =
+ match l with
+ | [] -> []
+ | x::tl -> (rev tl) @ [x]
+;;
+
+rev [1; 2; 3] ;; (* Gives [3; 2; 1] *)
+(* This function works on lists of any element type *)
+
+(*** Higher Order Functions ***)
+
+(* Functions are first class in OCaml *)
+
+let rec transform (f: 'a -> 'b) (l: 'a list) : 'b list =
+ match l with
+ | [] -> []
+ | head :: tail -> (f head) :: transform f tail
+;;
+
+transform (fun x -> x + 1) [1; 2; 3] ;; (* Gives [2; 3; 4] *)
+
+(** Lets combine everything we learned! **)
+let rec filter (pred: 'a -> bool) (l: 'a list) : 'a list =
+ begin match l with
+ | [] -> []
+ | x :: xs ->
+ let rest = filter pred xs in
+ if pred x then x :: rest else rest
+ end
+;;
+
+filter (fun x -> x < 4) [3; 1; 4; 1; 5] ;; (* Gives [3; 1; 1]) *)
+
+(*** Mutability ***)
+
+(* Records and variables are immutable: you cannot change where a variable points to *)
+
+(* However, you can create mutable polymorphic fields *)
+type counter = { mutable num : int } ;;
+
+let c = { num: 0 } ;;
+c.num ;; (* Gives 0 *)
+c.num <- 1 ;; (* <- operator can set mutable record fields *)
+c.num ;; (* Gives 1 *)
+
+(* OCaml's standard library provides a ref type to make single field mutability easier *)
+type 'a ref = { mutable contents : 'a } ;;
+let counter = ref 0 ;;
+!counter ;; (* ! operator returns x.contents *)
+counter := !counter + 1 ;; (* := can be used to set contents *)
```
## Further reading
-* Visit the official website to get the compiler and read the docs: <http://ocaml.org/>
-* Try interactive tutorials and a web-based interpreter by OCaml Pro: <http://try.ocamlpro.com/>
+* Visit the official website to get the compiler and read the docs: [http://ocaml.org/](http://ocaml.org/)
+* Quick tutorial on OCaml: [https://ocaml.org/docs/up-and-running](https://ocaml.org/docs/up-and-running)
+* Complete online OCaml v5 playground: [https://ocaml.org/play](https://ocaml.org/play)
+* An up-to-date (2022) book (with free online version) "Real World OCaml": [https://www.cambridge.org/core/books/real-world-ocaml-functional-programming-for-the-masses/052E4BCCB09D56A0FE875DD81B1ED571](https://www.cambridge.org/core/books/real-world-ocaml-functional-programming-for-the-masses/052E4BCCB09D56A0FE875DD81B1ED571)
+* Online interactive textbook "OCaml Programming: Correct + Efficient + Beautiful" from Cornell University: [https://cs3110.github.io/textbook/cover.html](https://cs3110.github.io/textbook/cover.html)
+* Try interactive tutorials and a web-based interpreter by OCaml Pro: [http://try.ocamlpro.com/](http://try.ocamlpro.com/)
diff --git a/opencv.html.markdown b/opencv.html.markdown
index 5d860eca..b083feb8 100644
--- a/opencv.html.markdown
+++ b/opencv.html.markdown
@@ -114,13 +114,15 @@ eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('human.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
-aces = face_cascade.detectMultiScale(gray, 1.3, 5)
+faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
+ # Draw a rectangle around detected face
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
+ # Draw a rectangle around detected eyes
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
diff --git a/opengl.html.markdown b/opengl.html.markdown
index 83ace3e8..993402f7 100644
--- a/opengl.html.markdown
+++ b/opengl.html.markdown
@@ -35,7 +35,7 @@ int main() {
context };
window.setVerticalSyncEnabled(true);
window.setActive(true);
- // After that we initialise GLEW and check if an error occured.
+ // After that we initialise GLEW and check if an error occurred.
GLenum error;
glewExperimental = GL_TRUE;
if ((err = glewInit()) != GLEW_OK)
@@ -140,7 +140,7 @@ if (logSize > 0) {
}
```
-The same is possibile after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
+The same is possible after <code>glLinkProgram()</code>, just replace <code>glGetShaderiv()</code> with <code>glGetProgramiv()</code>
and <code>glGetShaderInfoLog()</code> with <code>glGetProgramInfoLog()</code>.
```cpp
@@ -194,7 +194,7 @@ void main() {
out vec4 outColor;
void main() {
- // We simply set the ouput color to red.
+ // We simply set the output color to red.
// The parameters are red, green, blue and alpha.
outColor = vec4(1.0, 0.0, 0.0, 1.0);
}
@@ -233,7 +233,7 @@ glBufferData(GL_ARRAY_BUFFER, // target buffer
// After filling the VBO link it to the location 0 in our vertex shader,
// which holds the vertex position.
// ...
-// To ask for the attibute location, if you haven't set it:
+// To ask for the attribute location, if you haven't set it:
GLint posLocation = glGetAttribLocation(program, "position");
// ..
glEnableVertexAttribArray(0);
@@ -463,7 +463,7 @@ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(),
iboData.data(), GL_STATIC_DRAW);
// Next in our render loop, we replace glDrawArrays() with:
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSINGED_INT, nullptr);
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
// Remember to delete the allocated memory for the IBO.
```
@@ -535,7 +535,7 @@ glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// ...
glBindVertexArray(vao);
glBindTexture(GL_TEXTURE_2D, texture);
-glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSINGED_INT, nullptr);
+glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
// ...
```
@@ -673,7 +673,7 @@ glUniformMatrix4fv(modelLocation, 1, GL_FALSE,
## Geometry Shader
-Gemoetry shaders were introduced in OpenGL 3.2, they can produce vertices
+Geometry shaders were introduced in OpenGL 3.2, they can produce vertices
that are send to the rasterizer. They can also change the primitive type e.g.
they can take a point as an input and output other primitives.
Geometry shaders are inbetween the vertex and the fragment shader.
diff --git a/openscad.html.markdown b/openscad.html.markdown
new file mode 100644
index 00000000..63570cbe
--- /dev/null
+++ b/openscad.html.markdown
@@ -0,0 +1,117 @@
+---
+language: openscad
+filename: learnopenscad.scad
+contributors:
+ - ["Tom Preston", "https://github.com/tompreston/"]
+---
+
+Draw 3D models with code using [OpenSCAD](https://openscad.org/).
+
+```
+// Comments look like this
+
+// 3D Primitives
+cube(10);
+cube([5, 10, 20]);
+sphere(10);
+
+// Transformations
+translate([20, 0, 0]) cube(10);
+rotate([0, 20, 30]) cube(10);
+
+translate([20, 0, 0]) rotate([0, 20, 30]) cube(10);
+rotate([0, 20, 30]) translate([20, 0, 0]) cube(10);
+
+// Modifiers
+//
+// * disable
+// ! show only
+// # highlight / debug
+// % transparent / background
+//
+// For example, show only the rotated cube at the origin, before we translate it.
+translate([20, 0, 0]) !rotate([0, 20, 30]) cube(10);
+
+// Formatting
+// The following models are the same. The official docs prefer the second.
+rotate([0, 20, 30]) translate([20, 0, 0]) cube(10);
+
+rotate([0, 20, 30])
+ translate([20, 0, 0])
+ cube(10);
+
+rotate([0, 20, 30]) {
+ translate([20, 0, 0]) {
+ cube(10);
+ }
+}
+
+// Loops
+num_cubes = 5;
+r = 20;
+cube_len = 5;
+
+for (i = [0:num_cubes]) {
+ echo(str("Plot cube ", i));
+ rotate([0, i * 360 / num_cubes, 0])
+ translate([r, 0, 0])
+ cube(cube_len, center=true);
+}
+
+// Boolean operations
+//
+// union() - the sum of both shapes
+// difference() - the first shape, minus the second shape
+// intersection() - only parts of both shapes which intersect
+//
+cube_l = 20;
+cube_w = 10;
+cube_h = 10;
+
+hole_pos_l = 10;
+hole_pos_h = 5;
+hole_r = 3;
+
+difference() {
+ cube([cube_l, cube_w, cube_h]);
+ translate([hole_pos_l, 0, hole_pos_h])
+ rotate([-90, 0, 0])
+ cylinder(cube_w, r=hole_r);
+}
+
+// Functions calculate values
+function inch2mm(i) = i * 25.4;
+
+cube(inch2mm(2));
+
+// Modules create objects you want to use later
+module house(roof="flat", paint=[1,0,0]) {
+ color(paint)
+ if (roof=="flat") {
+ translate([0,-1,0]) cube();
+ } else if (roof=="pitched") {
+ rotate([90,0,0])
+ linear_extrude(height=1)
+ polygon(points=[[0,0],[0,1],[0.5,1.5],[1,1],[1,0]]);
+ }
+ else if (roof=="domical") {
+ translate([0,-1,0]) {
+ translate([0.5,0.5,1])
+ sphere(r=0.5,$fn=20);
+ cube();
+ }
+ }
+}
+
+house("pitched");
+translate([2, 0, 0]) house("domical");
+
+// Import modules and function from other files
+include <filename> // Import the content of the file as if they were written in this file
+use <filename> // Import modules and functions, but do not execute any commands
+```
+
+## Further Reading
+* Official docs https://openscad.org/documentation.html
+* Cheat sheet https://openscad.org/cheatsheet/index.html
+* Vim bindings https://github.com/sirtaj/vim-openscad
diff --git a/osl.html.markdown b/osl.html.markdown
new file mode 100644
index 00000000..af5f83bc
--- /dev/null
+++ b/osl.html.markdown
@@ -0,0 +1,751 @@
+---
+language: osl
+filename: learnosl.osl
+contributors:
+ - ["Preetham Pemmasani", "https://github.com/Preetham-ai"]
+---
+
+OSL (Open Shading Language) is a programming language designed by Sony for Arnold Renderer used for creating shaders.
+
+[Read more here.](https://raw.githubusercontent.com/imageworks/OpenShadingLanguage/master/src/doc/osl-languagespec.pdf)
+
+```c
+
+
+// Single-line comments start with //
+
+/* Multi line comments are preserved. */
+
+// Statements can be terminated by ;
+divide(1,2);
+
+///////////////
+// 1. Basics //
+///////////////
+
+// Declating variables
+color Blue; // Initializing a variable
+int _num = 3;
+float Num = 3.00;
+float c[3] = {0.1, 0.2, 3.14}; // Array
+
+// Math works as you would expect
+3 + 1; // 4
+74 - 3; // 71
+20 * 2; // 40
+75/3; // 25.0
+
+// And modulo division only works with integers
+10 % 2; // 0
+31 % 4; // 1
+
+// Bitwise operations only works with integers
+- 0 // 1 (Unary Negation)
+~ 00100011 // 11011100 (bitwise Compliment)
+1 << 2; // 4 (shift Left)
+12 >> 1; // 3 (shift Right)
+1 & 0; // 0 (bitwise AND)
+1 | 0; // 1 (bitwise OR)
+1 ^ 1; // 0 (bitwise XOR)
+
+// We also have booleans
+true;
+false;
+
+// Booleans can't be compared to integers
+true == 1 // Error
+false == 0 // Error
+
+// Negation uses the ! symbol
+!0; // 1
+!1; // 0
+!2; // 0
+//... and so on
+
+// Relation Operators are defined like:
+0 == 0 // true (equal to)
+0 != 1 // true (not equal to)
+5 < 3 // false (less then)
+3 <= 3 // true (less than or equal to)
+69 > 69 // false (greater than)
+99 >= 52 // true (greater than or equal)
+
+
+// Functions are same as C and C++
+float sum(float a, float b){
+ return a+b;
+}
+
+int subtract(int a, int b){
+ return a-b;
+}
+
+sum(2,3); // 5
+
+////////////////
+// 2. Shaders //
+////////////////
+
+// Shaders explain the custom behavior of materials and light
+// Shader's syntax is similar to the main function in C
+// The inputs and the outputs should be initialized to default types
+shader multiply(float a = 0.0,
+ float b = 0.0,
+ output float c = 0.0){
+ c = a*b;
+}
+
+// Double brackets[[ ]] is used to classify metadata of a shader
+surface plastic
+ [[ string help = "Realistic wood shader" ]]
+(
+ color Plastic = color (0.7, 0.5, 0.3) [[ string help = "Base color" ]],
+ float Reflectivity = 0.5 [[ float min = 0, float max = 1 ]],
+){...}
+
+///////////////////////////////////////
+// Metadata Types
+///////////////////////////////////////
+
+[[ string label = "IOR" ]] // Display-name in UI of the parameter
+[[ string help = "Change Refractive Index" ]] // Info about the parameter
+[[ string help = "widget" // Gives widgets to input the parameter
+ string widget = "number" ]] // input float or int
+ string widget = "string" ]] // String input
+ string widget = "boolean" ]] // yes/no (or) 1/0
+ string widget = "popup", options = "smooth|rough" ]] // Drop-down list
+ // enum Drop-down list can also be made
+ string widget = "mapper", options = "smooth:0|rough:1" ]]
+ string widget = "filename" ]] // Input files externally
+ string widget = "null" ]] // null input
+
+[[ float min = 0.0 ]] // Minimum value of parameter
+[[ float max = 0.5 ]] // Maximum value of parameter
+[[ int slider = 3.0 // Adds a slider as an input
+ int slidermin = -1]] // minimum value of the slider
+ int slidermax = 3]] // maximum value of the slider
+ int slidercenter = 2]] // origin value of the slider
+
+[[ float sensitivity = 0.5 ]] // step size for incrementing the parameter
+[[ string URL = www.example.com/ ]] // URL of shader's documentation
+
+
+
+// There are different types of shaders
+
+/* Surface shaders determine the basic material properties of a surface and
+how it reacts to light */
+// Light shaders are a type of SURFACE shaders used for emissive objects.
+// Displacement shaders alter the geometry using position and normals.
+// Volume shaders adds a medium like air/smoke/dust into the scene.
+
+volume multiply(float a = 0.0, float b = 0.0, output float c = 0.0){
+ c = 2*a+b;
+}
+
+////////////////////////////////////////
+// 3. Data Types and Global Variables //
+////////////////////////////////////////
+
+// Data Types
+
+// 1. The void type indicates a function that doesn't return any value
+
+// 2. int (Integer)
+ int x = -12; // Minimum size of 32-bits
+ int new2 = 0x01cf; // Hexadecimal can also be specified
+
+ ///////////////////////////////////////
+ // Order of Evaluation
+ ///////////////////////////////////////
+
+ // From top to bottom, top has higher precedence
+ //--------------------------//
+ // Operators //
+ //--------------------------//
+ // int++, int-- //
+ // ++ int --int - ~ ! //
+ // * / % //
+ // + - //
+ // << >> //
+ // < <= > >= //
+ // == != //
+ // & //
+ // ^ //
+ // | //
+ // && //
+ // || //
+ // ?: //
+ // = += -= *= /= //
+ //--------------------------//
+
+// 3. float (Floating-point number)
+ float A = 2.3; // minimum IEEE 32-bit float
+ float Z = -4.1e2; // Z = -4.1 * 10^2
+
+ // Order of evaluation is similar to int.
+ // Operations like ( ~ ! % << >> ^ | & && || ) aren't available in float
+
+// 4. string
+ // The syntax is similar to C
+ string new = "Hello World";
+ // some Special characters:
+ /*
+ '\"'; // double quote
+ '\n'; // newline character
+ '\t'; // tab character (left justifies text)
+ '\v'; // vertical tab
+ '\\'; // back slash
+ '\r'; // carriage return
+ '\b'; // backspace character
+ */
+
+ // Strings are concatenated with whitespace
+ "Hello " "world!"; // "Hello world!"
+ // concat function can also be used
+ string concat ("Hello ","World!"); // "Hello world!"
+
+ // printf function is same as C
+ int i = 18;
+ printf("I am %d years old",i); // I am 18 years old
+
+ // String functions can alse be used
+ int strlen (string s); // gives the length of the string
+ int len = strlen("Hello, World!"); // len = 13
+
+ // startswith returns 1 if string starts with prefix, else returns 0
+ int starts = startswith("The quick brown fox", "The"); // starts = 1
+
+ // endswith returns 1 if string starts with suffix, else returns 0
+ int ends = endswith("The quick brown fox", "fox"); // ends will be 1
+
+// 5. color (Red, Green, Blue)
+ color p = color(0,1,2); // black
+ color q = color(1); // white ( same as color(1,1,1) )
+ color r = color("rgb", 0.23, 0.1, 0.8); // explicitly specify in RGB
+ color s = color("hsv", 0.23, 0.1, 0.8); // specify in HSV
+ // HSV stands for (Hue, Saturation, Luminance)
+ // HSL stands for (Hue, Saturation, Lightness)
+ // YIQ, XYZ and xyY formats can also be used
+ // We can also access the indivudual values of (R,G,B)
+ float Red = p[0]; // 0 (access the red component)
+ float Green = p[1]; // 1 (access the green component)
+ float Blue = p[2]; // 2 (access the blue component)
+
+ // They can also be accessed like this
+ float Red = p.r; // 0 (access the red component)
+ float Green = p.g; // 1 (access the green component)
+ float Blue = p.b; // 2 (access the blue component)
+
+ // Math operators work like this with decreasing precedence
+ color C = (3,2,3) * (1,0,0); // (3, 0, 0)
+ color D = (1,1,1) * 255; // (255, 255, 255)
+ color E = (25,5,125) / 5; // (5, 1, 25)
+ color F = (30,40,50) / (3,4,5); // (10, 10, 10)
+ color A = (1,2,3) + (1,0,0); // (2, 2, 3)
+ color B = (1,2,3) - (1,0,0); // (0, 2, 3)
+ // Operators like ( - == != ) are also used
+
+ // Color Functions
+ color blackbody (1500) // Gives color based on temperature (in Kelvin)
+ float luminance (0.5, 0.3, 0.8) // 0.37 gives luminance cd/m^2
+ // Luminance is calculated by 0.2126R+0.7152G+0.0722B
+ color wavelength color (700) // (1, 0, 0) Gives color based on wavelength
+ color transformc ("hsl", "rgb") // converts one system to another
+
+// 6. point (x,y,z) is position of a point in the 3D space
+// 7. vector (x,y,z) has length and direction but no position
+// 8. normal (x,y,z) is a special vector perpendicular to a surface
+ // These Operators are the same as color and have the same precedence
+ L = point(0.5, 0.6, 0.7);
+ M = vector(30, 100, 70);
+ N = normal(0, 0, 1);
+
+ // These 3 types can be assigned to a coordinate system
+ L = point("object", 0.5, 0.6, 0.7); // relative to local space
+ M = vector("common", 30, 100, 70); // relative to world space
+ // There's also ("shader", "world", "camera", "screen", "raster", "NDC")
+
+ float x = L[0]; // 0.5 (access the x-component)
+ float y = L[1]; // 0.6 (access the y-component)
+ float z = L[2]; // 0.7 (access the z-component)
+
+ // They can also be accessed like this
+ float x = M.x; // 30 (access the x-component)
+ float y = M.y; // 100 (access the y-component)
+ float z = M.z; // 70 (access the z-component)
+
+ float a = dot ((1,2,3), (1,2,3)); // 14 (Dot Product)
+ vector b = cross ((1,2,3), (1,2,3)); // (0,0,0) (Cross Product)
+ float l = length(L); // 1.085 (length of vector)
+ vector normalize (vector L); // (0.460, 0.552, 0.644) Normalizes the vector
+
+ point p0 = point(1, 2, 3);
+ point p1 = point(4, 5, 6);
+ point Q = point(0, 0, 0);
+
+ // Finding distance between two points
+ float len = distance(point(1, 2, 3), point(4, 5, 6)); // 5.196
+ // Perpendicular distance from Q to line joining P0 and P1
+ float distance (point P0, point P1, point Q); // 2.45
+
+
+// 9. matrix
+ // Used for transforming vectors between different coordinate systems.
+ // They are usually 4x4 (or) 16 floats
+ matrix zero = 0; // makes a 4x4 zero matrix
+ /* 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0 */
+
+ matrix ident = 1; // makes a 4x4 identity matrix
+ /* 1.0, 0.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0, 0.0,
+ 0.0, 0.0, 1.0, 0.0,
+ 0.0, 0.0, 0.0, 1.0 */
+
+ matrix m = 7; // Maked a 4x4 scalar matrix with scaling factor of 7
+ /* 7.0, 0.0, 0.0, 0.0,
+ 0.0, 7.0, 0.0, 0.0,
+ 0.0, 0.0, 7.0, 0.0,
+ 0.0, 0.0, 0.0, 7.0 */
+
+ float x = m[1][1]; // 7
+
+ // matrices can be constructed using floats in row-major order
+ // matrices are usually 4x4 with 16 elements
+ matrix myMatrix = matrix(1.0, 0.0, 0.0, 0.0, // Row 1
+ 0.0, 2.0, 0.0, 0.0, // Row 2
+ 0.0, 0.0, 3.0, 0.0, // Row 3
+ 0.0, 0.0, 0.0, 4.0); // Row 4
+
+ // matrix transformations are easy to implement
+ matrix a = matrix ("shader", 1); // converted shader to common
+ matrix m = matrix ("object", "world"); // converted object to world
+
+ // Operations that can be used with decreasing precedence are:
+ // ( - * / == !=)
+
+ float determinant (matrix M) // 24 (returns the determinant of the matrix)
+ float transpose (matrix M) // returns the transpose of the matrix
+ /* 1.0, 0.0, 0.0, 0.0,
+ 0.0, 2.0, 0.0, 0.0,
+ 0.0, 0.0, 3.0, 0.0,
+ 0.0, 0.0, 0.0, 4.0 */
+
+// 10. array
+ // Arrays in OSL are similar to C
+ float a[5]; // initialize array a with size 5
+ int b[3] = {90,80,70}; // declare array with size 3
+ int len = arraylength(b); // 3
+ int f = b[1]; // 80
+ float anotherarray[3] = b; // arrays can be copied if same type
+
+// 11. struct (Structures)
+ // Structures in OSL are similar to C and C++.
+ struct RGBA { // Defining a structure
+ color rgb;
+ float alpha;
+ };
+
+
+ RGBA col; // Declaring a structure
+ RGBA b = { color(0.1, 0.2, 0.3), 1 }; // Can also be declared like this
+
+ r.rgb = color (1, 0, 0); // Assign to one field
+ color c = r.rgb; // Read from a structure field
+
+// 12. closure
+ // Closure is used to store data that aren't considered when it executes.
+ // It cannot be manipulated or read.
+ // A null closure can always be assigned.
+ // OSL currently only supports color as their closure.
+
+ // A few examples of closures are:
+
+ // Diffuse BSDF closures:
+ closure color oren_nayar_diffuse_bsdf(normal N, color alb, float roughness)
+ closure color burley_diffuse_bsdf(normal N, color alb, float roughness);
+
+ // Dielectric BSDF closure:
+ closure color dielectric_bsdf(normal N, vector U, color reflection_tint,
+ color transmission_tint, float roughness_x, float roughness_y,
+ float ior, string distribution);
+
+ // Conductor BSDF closure:
+ closure color conductor_bsdf(normal N, vector U, float roughness_x,
+ float roughness_y, color ior, color extinction, string distribution);
+
+ // Generalized Schlick BSDF closure:
+ closure color generalized_schlick_bsdf(normal N, vector U,
+ color reflection_tint, color transmission_tint,
+ float roughness_x, float roughness_y, color f0, color f90,
+ float exponent, string distribution);
+
+ // Translucent BSDF closure:
+ closure color translucent_bsdf(normal N, color albedo);
+
+ // Transparent BSDF closure:
+ closure color transparent_bsdf();
+
+ // Subsurface BSSRDF closure:
+ closure color subsurface_bssrdf();
+
+ // Sheen BSDF closure:
+ closure color sheen_bsdf(normal N, color albedo, float roughness);
+
+ // Anisotropic VDF closure: (Volumetric)
+ closure color anisotropic_vdf(color albedo, color extinction,
+ float anisotropy);
+
+ // Medium VDF closure: (Volumetric)
+ closure color medium_vdf(color albedo, float transmission_depth,
+ color transmission_color, float anisotropy, float ior, int priority);
+
+ closure color uniform edf(color emittance); // Emission closure
+ closure color holdout(); // Holdout Hides objects beneath it
+
+ // BSDFs can be layered using this closure
+ closure color layer (closure color top, closure color base);
+
+
+
+// Global Variables
+// Contains info that the renderer knows
+// These variables need not be declared
+
+point P // Position of the point you are shading
+vector I // Incident ray direction from viewing position to shading position
+normal N // Normal of the surface at P
+normal Ng // Normal of the surface at P irrespective of bump mapping
+float u // UV 2D x - parametric coordinate of geometry
+float v // UV 2D y - parametric coordinate of geometry
+vector dPdu // change of P with respect to u tangent to the surface
+vector dPdv // change of P with respect to v tangent to the surface
+float time // Current time
+float dtime // Time covered
+vector dPdtime // change of P with respect to time
+
+/////////////////////
+// 4. Control flow //
+/////////////////////
+
+// Conditionals in OSL are just like in C or C++.
+
+// If/Else
+if (5>2){
+ int x = s;
+ int l = x;
+}
+else{
+ int x = s + l;
+}
+
+// 'while' loop
+int i = 0;
+while (i < 5) {
+ i += 1;
+ printf("Current value of i: %d\n", i);
+}
+
+// 'do-while' loop is where test happens after the body of the loop
+int i = 0;
+do {
+ printf("Current value of i: %d\n", i);
+ i += 1;
+} while (i < 5);
+
+// 'for' loop
+for (int i = 0; i < 5; i += 1) {
+ printf("Current value of i: %d\n", i);
+}
+
+/////////////////////
+// 5. Functions //
+/////////////////////
+
+// Math Constants
+ M_PI // π
+ M_PI_35 // π/35
+ m_E // e
+ M_LN2 // ln 2
+ M_SQRT2 // √2
+ M_SQRT1_2 // √(1/2)
+
+// Geometry Functions
+ vector N = vector(0.1, 1, 0.2); // Normal vector
+ vector I = vector(-0.5, 0.2, 0.8); // Incident vector
+
+ // Faceforward tells the direction of vector
+ vector facing_dir = faceforward(N, I); // facing_dir = (-0.5, 0.2, 0.8)
+
+ // faceforward with three arguments
+ vector ref = vector(0.3, -0.7, 0.6); // Reference normal
+ facing_dir = faceforward(N, I, ref); // facing_dir = (0.5, -0.2, -0.8)
+
+ // reflect gives the reflected vector along normal
+ vector refl = reflect(I, N); // refl = (-0.7, -0.4, 1.4)\
+
+ // refract gives the refracted vector along normal
+ float ior = 1.5; // Index of refraction
+ vector refr = refract(I, N, ior); // refr = (-0.25861, 0.32814, 0.96143)
+
+ /* Fresnel computes the Reflection (R) and Transmission (T) vectors, along
+ with the scaling factors for reflected (Kr) and transmitted (Kt) light. */
+ float Kr, Kt;
+ vector R, T;
+ fresnel(I, N, ior, Kr, Kt, R, T);
+/* Kr = 0.03958, Kt = 0.96042
+ R = (-0.19278, -0.07711, 0.33854)
+ T = (-0.25861, 0.32814, 0.96143) */
+
+ // Rotating a point along a given axis
+ point Q = point(1, 0, 0);
+ float angle = radians(90); // 90 degrees
+ vector axis = vector(0, 0, 1);
+ point rotated_point = rotate(Q, angle, axis);
+ // rotated_point = point(0, 1, 0)
+
+ // Rotating a point along a line made by 2 points
+ point P0 = point(0, 0, 0);
+ point P1 = point(1, 1, 0);
+ angle = radians(45); // 45 degrees
+ Q = point(1, 0, 0);
+ rotated_point = rotate(Q, angle, P0, P1);
+ // rotated_point = point(0.707107, 0.707107, 0)
+
+ // Calculating normal of surface at point p
+ point p1 = point(1, 0, 0); // Point on the sphere of radius 1
+ vector normal1 = calculatenormal(p1);
+ // normal1 = vector(1, 0, 0)
+
+ // Transforming units is easy
+ float transformu ("cm", float x) // converts to cm
+ float transformu ("cm", "m", float y) // converts cm to m
+
+// Displacement Functions
+ void displace (float 5); // Displace by 5 amp units
+ void bump (float 10); // Bump by 10 amp units
+
+
+// Noise Generation
+
+ type noise (type noise (string noisetype, float u, float v, ...)); // noise
+ type noise (string noisetype, point p,...); // point instead of coordinates
+ /* some noises are ("perlin", "snoise", "uperlin", "noise", "cell", "hash"
+ "simplex", "usimplex", "gabor", etc) */
+
+ // Noise Names
+
+ // 1. Perlin Noise (perlin, snoise):
+ // Creates smooth, swirling noise often used for textures.
+ // Range: [-1, 1] (signed)
+ color cloud_texture = noise("perlin", P);
+
+ // 2. Simplex Noise (simplex, usimplex):
+ // Similar to Perlin noise but faster.
+ // Range: [-1, 1] (signed) for simplex, [0, 1] (unsigned) for usimplex
+ float bump_amount = 0.2 * noise("simplex", P * 5.0);
+
+ // 3. UPerlin Noise (uperlin, noise):
+ // Similar to peril
+ // Range: [0, 1] (unsigned)
+ color new_texture = noise("uperlin", P);
+
+ // 4. Cell Noise (cell):
+ // Creates a blocky, cellular and constant values within each unit block
+ // Range: [0, 1] (unsigned)
+ color new_texture = noise("cell", P);
+
+ // 5. Hash Noise (hash):
+ // Generates random, uncorrelated values at each point.
+ // Range: [0, 1] (unsigned)
+ color new_texture = noise("hash", P);
+
+ // Gabor Noise (gabor)
+ // Gabor Noise is advanced version of Perin noies and gives more control
+ // Range: [-1, 1] (signed)
+ // Gabor Noise Parameters
+
+ // Anisotropic (default: 0)
+ // Controls anisotropy:
+ // 0: Isotropic (equal frequency in all directions)
+ // 1: Anisotropic with user-defined direction vector (defaults to (1,0,0))
+ /* 2: Hybrid mode,anisotropic along direction vector but radially isotropic
+ perpendicularly. */
+
+ // Direction (default: (1,0,0))
+ // Specifies the direction of anisotropy (used only if anisotropic is 1).
+
+ // bandwidth (default: 1.0)
+ // Controls the frequency range of the noise.
+
+ // impulses (default: 16)
+ // Controls the number of impulses used per cell, affecting detail level.
+
+ // do_filter (default: 1)
+ // Enables/disables antialiasing (filtering).
+
+ result = noise(
+ "gabor",
+ P,
+ "anisotropic", anisotropic,
+ "direction", direction,
+ "bandwidth", bandwidth,
+ "impulses", impulses,
+ "do_filter", do_filter
+ );
+
+ // Specific noises can also be used instead of passing them as types
+ // pnoise is periodic noise
+ float n1 = pnoise("perlin", 0.5, 1.0);
+ // 2D periodic noise with Gabor type
+ float n2 = pnoise("gabor", 0.2, 0.3, 2.0, 3.0);
+ // 2D non-periodic simplex noise
+ float n3 = snoise(0.1, 0.7);
+ // 2D periodic simplex noise
+ type psnoise (float u, float v, float uperiod, float vperiod);
+ float n4 = psnoise(0.4, 0.6, 0.5, 0.25);
+ // 2D cellular noise
+ float n5 = cellnoise(0.2, 0.8);
+ // 2D hash noise
+ int n6 = hash(0.7, 0.3);
+
+// Step Function
+ // Step Functions are used to compare input and threshold
+
+ // The type may be of float, color, point, vector, or normal.
+ type step (type edge, type x); // Returns 1 if x ≥ edge, else 0
+ color checker = step(0.5, P); // P is a point on the surface
+ /* Pixels with P values below 0.5 will be black, those above or equal will
+ be white */
+ float visibility = step(10, distance(P, light_position));
+ // Light is fully visible within 10 units, completely invisible beyond
+
+ type linearstep (type edge0, type edge1, type x); /* Linearstep Returns 0
+ if x ≤ edge0, and 1 if x ≥ edge1, with linear interpolation */
+ color gradient = linearstep(0, 1, P);
+ // P is a point on the surface between 0 and 1
+ // Color will graduate smoothly from black to white as P moves from 0 to 1
+ float fade = linearstep(0.85, 1, N.z); // N.z is the z-component
+ // Object edges with normals close to vertical (N.z near 1) will fade out
+
+ type smoothstep (type edge0, type edge1, type x); /* smoothstep Returns 0
+ if x ≤ edge0, and 1 if x ≥ edge1, with Hermite interpolation */
+ float soft_mask = smoothstep(0.2, 0.8, noise(P)); /* noise(P) is a noisy
+ value between 0 and 1. soft_mask will vary smoothly between 0 and 1 based
+ on noise(P), with a smoother curve than linearstep */
+
+// Splines
+ // Splines are smooth curves based on a set of control points
+
+ /* The type of interpolation ranges from "catmull-rom", "bezier",
+ "bspline", "hermite", "linear", or "constant" */
+
+ // Spline with knot vector
+ float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1};
+ point[] controls = {point(0),point(1, 2, 1),point(2, 1, 2),point(3, 3, 1)};
+ spline curve1 = spline("bezier", 0.5, len(knots), controls);
+ // curve1 is a Bezier spline evaluated at u = 0.5
+
+ // Spline with control points
+ spline curve2 = spline("catmull-rom", 0.25, point(0, 0, 0), point(1, 2, 1),
+ point(2, 1, 2), point(3, 3, 1));
+ // curve2 is a Catmull-Rom spline evaluated at u = 0.25
+
+ // Constant spline with a single float value
+ float value = 10;
+ u = 0.1;
+ spline curve5 = spline("constant", u, value);
+ // curve5 is a constant spline with value 10 evaluated at u = 0.1
+
+ // Hermite spline with point and vector controls
+ point q0 = point(0, 0, 0), q1 = point(3, 3, 3);
+ vector t0 = vector(1, 0, 0), t1 = vector(-1, 1, 1);
+ u = 0.75;
+ spline curve3 = spline("hermite", u, q0, t0, q1, t1);
+ // curve3 is a Hermite spline evaluated at u = 0.75
+
+ // Linear spline with float controls
+ float f0 = 0, f1 = 1, f2 = 2, f3 = 3;
+ u = 0.4;
+ spline curve4 = spline("linear", u, f0, f1, f2, f3);
+ // curve4 is a linear spline evaluated at u = 0.4
+
+ // InverseSplines also exist
+
+ // Inverse spline with control values
+ float y0 = 0, y1 = 1, y2 = 2, y3 = 3;
+ float v = 1.5;
+ float u1 = splineinverse("linear", v, y0, y1, y2, y3);
+ // u1 = 0.5 (linear interpolation between y1 and y2)
+
+ // Inverse spline with knot vector
+ float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1};
+ float[] values = {0, 1, 4, 9};
+ v = 6;
+ float u2 = splineinverse("bezier", v, len(knots), values);
+ // u2 = 0.75 (Bezier spline inverse evaluated at v = 6)
+
+ // Inverse spline with constant value
+ v = 10;
+ float u3 = splineinverse("constant", v, 10);
+ // u3 = 0 (since the constant spline always returns 10)
+
+ // Inverse spline with periodic values
+ float y4 = 0, y5 = 1, y6 = 0;
+ v = 0.5;
+ float u4 = splineinverse("periodic", v, y4, y5, y6);
+ // u4 = 0.75 (periodic spline inverse evaluated at v = 0.5)
+
+
+
+// Calculus Operators
+ // Partial derivative of f with respect to x, y and z using Dx, Dy, Dz
+ float a = 3.14;
+ float dx = Dx(a); // partial derivative of a with respect to x
+
+ point p = point(1.0, 2.0, 3.0);
+ vector dp_dx = Dx(p); // partial derivative of p with respect to x
+
+ vector dv_dy = Dy(N); // partial derivative of normal with respect to y
+
+ color c = color(0.5, 0.2, 0.8);
+ color dc_dz = Dz(c); // partial derivative of c with respect to z
+
+
+ float area (point p) // gives the surface area at the position p
+
+ float filterwidth (float x) // gives the changes of x in adjacent samples
+
+// Texture Functions
+ // lookup for a texture at coordinates (x,y)
+ color col1 = texture("texture.png", 0.5, 0.2);
+ // Lookup color at (0.5, 0.2) in texture.png
+
+ // 3D lookup for a texture at coordinates (x,y)
+ color col3 = texture3d("texture3d.vdb", point(0.25, 0.5, 0.75));
+
+ // parameters are ("blur","width","wrap","fill","alpha","interp", ...)
+ color col2 = texture("texture.png",1.0,0.75,"blur",0.1,"wrap", "periodic");
+ // Lookup color at (1.0, 0.75) with blur 0.1 and periodic wrap mode
+
+// Light Functions
+
+ float surfacearea (); // Returns the surface area of area light covers
+ int backfacing (); // Outputs 1 if the normals are backfaced, else 0
+ int raytype (string name); // returns 1 if the ray is a particular raytype
+
+ // Tracing a ray from a position in a direction
+ point pos = point(0, 0, 0); // Starting position of the ray
+ vector dir = vector(0, 0, 1); // Direction of the ray
+ int hit = trace(pos, dir); // returns 1 if it hits, else 0
+
+```
+### Further reading
+
+* [Blender Docs for OSL](https://docs.blender.org/manual/en/latest/render/shader_nodes/osl.html)
+* [C4D Docs for OSL](https://docs.otoy.com/cinema4d//OpenShadingLanguageOSL.html)
+* Open Shading Language on [Github](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage)
+* [Official OSL Documentation](https://open-shading-language.readthedocs.io/en/main/) \ No newline at end of file
diff --git a/p5.html.markdown b/p5.html.markdown
index f6084b98..2588ffc6 100644
--- a/p5.html.markdown
+++ b/p5.html.markdown
@@ -10,40 +10,142 @@ filename: p5.js
p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.
+To run p5.js code, you can go to [the online editor](https://editor.p5js.org/).
+
```js
///////////////////////////////////
// p5.js has two important functions to work with.
function setup() {
- // the setup function gets executed just once when the window is loaded
+ // the setup function gets executed just once when the window is loaded
}
function draw() {
- // the draw function gets called every single frame. This means that for a frameRate(30) it would get called 30 times per second.
+ // the draw function gets called every single frame
+ // if the framerate is set to 30, it would get called 30 times every second
}
// the following code explains all features
function setup() {
- createCanvas(640, 480); // creates a new canvas element with 640px as width as 480px as height
- background(128); // changes the background color of the canvas, can accept rgb values like background(100,200,20) else grayscale values like background(0) = black or background(255) = white
+ createCanvas(640, 480); // creates a new canvas element with 640px as width as 480px as height
+ background(128); // sets the background color to rgb(128, 128, 128)
+ // background('#aaf') // you can use hex codes and color names too
}
function draw() {
- ellipse(10, 10, 50, 50); // creates a ellipse at the 10px from the left and 10px from the top with width adn height as 50 each, so its basically a circle.
- //remember in p5.js the origin is at the top-left corner of the canvas
+ background('#f2f2fc'); // usually, you call `background` in draw to clear the screen
+ // creates an ellipse at 10px from the top and 10px from the left, with width and height 37
+ ellipse(10, 10, 37, 37);
+ // remember in p5.js the origin is at the top-left corner of the canvas
+
+ if (mouseIsPressed) {
+ // mouseIsPressed is a boolean variable that is true when the mouse is down, and false otherwise
+
+ fill(0); // fill sets the fill color, which will stay until it is changed
+ } else {
+ fill(255, 255, 255, 240); // fill(a, b, c, d) sets the fill color to rgba(a, b, c, d)
+ }
+
+ ellipse(mouseX, mouseY, 80, 80);
+ // mouseX and mouseY are the x and y position of the mouse, respectively
+ // the above code creates and ellipse under the mouse, and fills it with white or black
+
+
+ // some other 2d primitives (shapes) you can draw:
+ rect(9, 3, 23, 26); // x, y, width, height
+ noFill(); // sets the fill color to transparent
+ triangle(100, 400, 130, 200, 200, 300); // x1, y1, x2, y2, x3, y3
+ point(100, 300); // create a point at x, y
+ // there are more, but they are more complex.
+}
- if (mouseIsPressed) {
- // mouseIsPressed is a boolean variable that changes to true if the mouse buttton is pressed down at that instant
+/** Bouncing balls animation
+ * You can copy-paste this code into the online editor at
+ * https://editor.p5js.org/
+ */
+class Ball {
+ constructor(x, y, xvel, yvel, radius, col) {
+ this.position = createVector(x, y); // create a p5.Vector object which stores the x and y
+ this.velocity = createVector(xvel, yvel); // make a p5.Vector storing the velocity
+ this.radius = radius;
+ this.col = col; // p5 already uses the word color, so we use col instead
+ }
- fill(0); // fill refers to the innner color or filling color of whatever shape you are going to draw next
- } else {
- fill(255); // you can give in rgb values like fill(72, 240, 80) to get colors, else a single values determines the grayscale where fill(255) stands for #FFF(white) and fill(0) stands for #000(black)
+ update() {
+ this.position.add(this.velocity); // you can add vectors with p5.Vector.add(p5.Vector)
+ if (this.position.x + this.radius > width) {
+ // flip the direction the ball is going in if it touches the edge
+ this.velocity.x *= -1;
}
+ if (this.position.x - this.radius < 0) {
+ this.velocity.x *= -1;
+ }
+ if (this.position.y + this.radius > height) {
+ this.velocity.y *= -1;
+ }
+ if (this.position.y - this.radius < 0) {
+ this.velocity.y *= -1;
+ }
+ }
+
+ render() {
+ // you can figure out what this does by now
+ fill(this.col);
+ ellipse(this.position.x, this.position.y, this.radius);
+ }
+}
+
+let numBalls = 23;
+let balls = [];
+
+function setup() {
+ createCanvas(400, 400); // width, height
+ for (let i = 0; i < numBalls; i++) {
+ let r = random(255); // random number between 0 and 255
+ let g = random(255);
+ let b = random(255);
+
+ balls.push(
+ new Ball(
+ random(30, width), // x position
+ random(height), // y position
+ random(-4, 4), // x velocity
+ random(-4, 4), // y velocity
+ random(4, 10), // radius
+ color(r, g, b) // fill color for the ball
+ )
+ );
+ }
+}
+
+function draw() {
+ background(255);
+ for (let ball of balls) {
+ ball.update();
+ ball.render();
+ }
+}
+
+// So far, we have only seen the default rendering mode.
+// This time, we will use the 'webgl' renderer
- ellipse(mouseX, mouseY, 80, 80);
- // mouseX is the x-coordinate of the mouse's current position and mouseY is the y-coordinate of the mouse's current position
+function setup() {
+ createCanvas(400, 400, WEBGL); // width, height, rendering mode
+}
+
+function draw() {
+ background(0);
- // the above code creates a circle wherever mouse's current position and fills it either black or white based on the mouseIsPressed
+ stroke('#000');
+ fill('#aaf');
+
+ // rotate around the x, y, and z axes by the frame count divided by 50
+ rotateX(frameCount / 50);
+ rotateY(frameCount / 50);
+ rotateZ(frameCount / 50);
+ // frameCount is a p5.js variable that stores the amount of frames that have passed
+
+ box(50, 50, 50); // width, height, depth
}
```
@@ -51,3 +153,9 @@ function draw() {
- [p5.js | get started](http://p5js.org/get-started/) The official documentation
- [Code! Programming for Beginners with p5.js - YouTube](https://www.youtube.com/watch?v=yPWkPOfnGsw&vl=en) Introduction and Coding challenges using Processing and p5.js by Coding Train
+- [The Coding Train](https://codingtra.in/) A website with sketches made in p5 and processing
+
+## Source
+
+- [p5's source code](https://github.com/processing/p5.js)
+- [p5.sound.js source](https://github.com/processing/p5.js-sound)
diff --git a/pascal.html.markdown b/pascal.html.markdown
index 9c73c456..fe00791a 100644
--- a/pascal.html.markdown
+++ b/pascal.html.markdown
@@ -131,7 +131,7 @@ Begin
str := 'apple';
bool := true;
//pascal is not a case-sensitive language
- //arithmethic operation
+ //arithmetic operation
int := 1 + 1; // int = 2 overwriting the previous assignment
int := int + 1; // int = 2 + 1 = 3;
int := 4 div 2; //int = 2 division operation where result will be floored
diff --git a/php.html.markdown b/php.html.markdown
index 821bde8f..1ef52f68 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -92,9 +92,10 @@ $escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
// Enclose a variable in curly braces if needed
-$apples = "I have {$number} apples to eat.";
-$oranges = "I have ${number} oranges to eat.";
-$money = "I have $${number} in the bank.";
+$number = 23;
+$apples = "I have {$number} apples to eat."; // => I have 23 apples to eat.
+$oranges = "I have ${number} oranges to eat."; // => I have 23 oranges to eat.
+$money = "I have $${number} in the bank."; // => I have $23 in the bank.
// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners
$nowdoc = <<<'END'
@@ -109,7 +110,7 @@ $sgl_quotes
END;
// String concatenation is done with .
-echo 'This string ' . 'is concatenated';
+echo 'This string ' . 'is concatenated'; // Returns 'This string is concatenated'
// Strings can be passed in as parameters to echo
echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid'
@@ -443,7 +444,7 @@ $bar('C'); // Prints "A - B - C"
// You can call named functions using strings
$function_name = 'add';
echo $function_name(1, 2); // => 3
-// Useful for programatically determining which function to run.
+// Useful for programmatically determining which function to run.
// Or, use call_user_func(callable $callback [, $parameter [, ... ]]);
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 318bf043..50e1e27e 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -118,14 +118,15 @@ $False - 5 # => -5
2 -lt 3 -and 3 -lt 2 # => False
# (-is vs. -eq) -is checks if two objects are the same type.
-# -eq checks if the objects have the same values.
+# -eq checks if the objects have the same values, but sometimes doesn't work
+# as expected.
# Note: we called '[Math]' from .NET previously without the preceeding
# namespaces. We can do the same with [Collections.ArrayList] if preferred.
[System.Collections.ArrayList]$a = @() # Point a at a new list
$a = (1,2,3,4)
$b = $a # => Point b at what a is pointing to
$b -is $a.GetType() # => True, a and b equal same type
-$b -eq $a # => True, a and b values are equal
+$b -eq $a # => None! See below
[System.Collections.Hashtable]$b = @{} # => Point a at a new hash table
$b = @{'one' = 1
'two' = 2}
@@ -154,6 +155,13 @@ $age = 22
"$name's name is $($name.Length) characters long."
# => "Steve's name is 5 characters long."
+# Strings can be compared with -eq, but are case insensitive. We can
+# force with -ceq or -ieq.
+"ab" -eq "ab" # => True
+"ab" -eq "AB" # => True!
+"ab" -ceq "AB" # => False
+"ab" -ieq "AB" # => True
+
# Escape Characters in Powershell
# Many languages use the '\', but Windows uses this character for
# file paths. Powershell thus uses '`' to escape characters
@@ -274,6 +282,10 @@ $array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6]
# Examine length with "Count" (Note: "Length" on arrayList = each items length)
$array.Count # => 6
+# -eq doesn't compare array but extract the matching elements
+$array = 1,2,3,1,1
+$array -eq 1 # => 1,1,1
+($array -eq 1).Count # => 3
# Tuples are like arrays but are immutable.
# To use Tuples in powershell, you must use the .NET tuple class.
@@ -574,7 +586,7 @@ Get-Process | Foreach-Object ProcessName | Group-Object
1..10 | ForEach-Object { "Loop number $PSITEM" }
1..10 | Where-Object { $PSITEM -gt 5 } | ConvertTo-Json
-# A notable pitfall of the pipeline is it's performance when
+# A notable pitfall of the pipeline is its performance when
# compared with other options.
# Additionally, raw bytes are not passed through the pipeline,
# so passing an image causes some issues.
@@ -665,7 +677,7 @@ Powershell as a Tool:
Getting Help:
-```Powershell
+```powershell
# Find commands
Get-Command about_* # alias: gcm
Get-Command -Verb Add
@@ -682,7 +694,7 @@ Update-Help # Run as admin
If you are uncertain about your environment:
-```Powershell
+```powershell
Get-ExecutionPolicy -List
Set-ExecutionPolicy AllSigned
# Execution policies include:
@@ -696,7 +708,7 @@ help about_Execution_Policies # for more info
$PSVersionTable
```
-```Powershell
+```powershell
# Calling external commands, executables,
# and functions with the call operator.
# Exe paths with arguments passed or containing spaces can create issues.
@@ -802,6 +814,6 @@ Interesting Projects
* [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac
* [PSake](https://github.com/psake/psake) Build automation tool
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
-* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
+* [ZLocation](https://github.com/vors/ZLocation) Powershell `cd` that reads your mind
* [PowerShell Community Extensions](https://github.com/Pscx/Pscx)
* [More on the Powershell Pipeline Issue](https://github.com/PowerShell/PowerShell/issues/1908)
diff --git a/processing.html.markdown b/processing.html.markdown
index 777c6981..63f10e88 100644
--- a/processing.html.markdown
+++ b/processing.html.markdown
@@ -2,7 +2,7 @@
language: processing
filename: learnprocessing.pde
contributors:
- - ["Phone Thant Ko", "http://github.com/phonethantko"]
+ - ["Phone Than Ko", "http://github.com/phonethantko"]
- ["Divay Prakash", "https://github.com/divayprakash"]
---
@@ -256,7 +256,7 @@ line(x1, y1, z1, x2, y2, z2); // In 3D space
// Triangle
triangle(x1, y1, x2, y2, x3, y3);
-// Draws a triangle connecting three points defined by coordinate paramters.
+// Draws a triangle connecting three points defined by coordinate parameters.
// Rectangle
rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners
@@ -375,7 +375,7 @@ texture(image); // PImage can be passed into arguments for texture-mapping the s
If you want to take things further, there are more things Processing is powered
for. Rendering models, shaders and whatnot. There's too much to cover in a
-short documentation, so I will leave them out here. Shoud you be interested,
+short documentation, so I will leave them out here. Should you be interested,
please check out the references.
```
diff --git a/pt-br/asciidoc-pt.html.markdown b/pt-br/asciidoc-pt.html.markdown
index b12c0693..9fca5af0 100644
--- a/pt-br/asciidoc-pt.html.markdown
+++ b/pt-br/asciidoc-pt.html.markdown
@@ -5,7 +5,7 @@ contributors:
translators:
- ["David Lima", "https://github.com/davelima"]
lang: pt-br
-filename: asciidoc-pt.md
+filename: asciidoc-pt.adoc
---
AsciiDoc é uma linguagem de marcação similar ao Markdown e pode ser
diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown
index 70d0a01c..02bffc41 100644
--- a/pt-br/awk-pt.html.markdown
+++ b/pt-br/awk-pt.html.markdown
@@ -202,7 +202,7 @@ function string_functions( localvar, arr) {
# Ambas retornam o número de instâncias substituídas
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "M..t m. at th. bar"
# Localiza um texto que casa com uma expressão regular
# index() faz a mesma coisa, mas não permite uma expressão regular
@@ -370,8 +370,10 @@ END {
}
```
+
Leituras adicionais (em inglês):
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
* [Awk man page](https://linux.die.net/man/1/awk)
-* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux.
+* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
+ GNU AWK é encontrado na maioria dos sistemas GNU/Linux.
diff --git a/pt-br/bc-pt.html.markdown b/pt-br/bc-pt.html.markdown
new file mode 100644
index 00000000..2a412806
--- /dev/null
+++ b/pt-br/bc-pt.html.markdown
@@ -0,0 +1,104 @@
+---
+language: bc
+contributors:
+ - ["Btup"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: learnbc-pt.bc
+---
+```c
+/*Este é um comentário
+multi-linhas*/
+# Este é um comentário de uma única linha! (em bc GNU).
+
+ /*1. Variáveis e estruturas de controle*/
+num = 45 /*Todas as variáveis apenas salvam dados do tipo double, e
+ você não pode salvar strings diretamente em constantes.*/
+num 45; /*Você pode adicionar ponto-e-vírgula após cada linha.
+ Isto é opcional*/
+/*Blocos são denotados usando os operadores {} (similar ao C):*/
+while(num < 50) {
+ num += 1 /*equivalente a num=num+1.
+ a = a op b é equivalente a a op= b.*/
+}
+/*E existem os operadores ++ (incrementar) e -- (decrementar).*/
+/* Existem 3 tipos especiais de variáveis:
+scale: define a escala de números double.
+ibase: define a base de da entrada.
+obase: define a base da saída.
+*/
+/*Cláusulas If:*/
+hora = read() /*Lê a entrada de um número*/
+
+if(hora < 12) { /*Os operadores são idênticos ao C.*/
+ print "Bom dia\n" /*"print" imprime strings ou variáveis
+ separados por vírgula (,).*/
+} else if(hora == 12) {
+ print "Olá\n"
+ /*Para escapar strings, inicie a string com \.
+ Para deixar o escape de strings mais claros,
+ aqui está uma lista simplificada das strings escapadas
+ que funcionarão com bc:
+ \b: backspace
+ \c: carriage return (enter)
+ \n: newline (nova linha)
+ \t: tab
+ \\: backslash (barra inertida)*/
+} else {
+ /*Variáveis são globais por padrão.*/
+ istoEGlobal = 5
+ /*Para tornar uma variável local, use a palavra-chave "auto" em uma função.*/
+}
+
+/*Todas as variáveis por padrão tem o valor 0*/
+num = variavelEmBranco /*num é igual a 0.*/
+
+/*Assim como no C, "0" é considerado "false"*/
+if(!num) {print "false\n"}
+
+/*Diferente do C, bc não tem o operador ?:. Por exemplo,
+este bloco de código causaria um erro:
+a = (num) ? 1 : 0
+Entretanto, você pode simular da seguinte forma:
+a = (num) && (1) || (0) /*&& é "E", || é "OU"*/
+*/
+
+/*Loops For*/
+num = 0
+for(i = 1; i <= 100; i++) {/*Similar ao loop For do C.*/
+ num += i
+}
+
+ /*2.Funções e arrays*/
+define fac(n) { /*para definir uma função, use "define".*/
+ if(n == 1 || n == 0) {
+ return 1 /*retorna um valor*/
+ }
+ return n * fac(n - 1) /*recursão é permitido*/
+}
+
+/*Closures e funções anônimas não são permitidas*/
+
+num = fac(4) /*24*/
+
+/*Exemplo de variáveis locais:*/
+define x(n) {
+ auto x
+ x = 1
+ return n + x
+}
+x(3) /*4*/
+print x /*A variável "x" não será acessível de fora da função*/
+/*Arrays são equivalentes aos arrays em C.*/
+for(i = 0; i <= 3; i++) {
+ a[i] = 1
+}
+/*Para acessar um array, faça assim:*/
+print a[0], " ", a[1], " ", a[2], " ", a[3], "\n"
+quit /*Adicione essa linha no final do código
+para garantir que o programa encerre. Essa linha é opcional.*/
+```
+Aproveite bem essa simples calculadora! (Ou essa linguagem de programação, para ser exato.)
+
+Este programa inteiro foi escrito em GNU bc. Para rodá-lo, use ```bc learnbc-pt.bc```
diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown
index 42a29991..ca289001 100644
--- a/pt-br/c++-pt.html.markdown
+++ b/pt-br/c++-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-pt.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
@@ -363,7 +363,7 @@ void OwnedDog::print() const
{
Dog::print(); // Chame a função de impressão na classe Dog base de
std::cout << "Dog is owned by " << owner << "\n";
- // Prints "Dog is <name> and weights <weight>"
+ // Imprime "Dog is <name> and weights <weight>"
// "Dog is owned by <owner>"
}
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 4e55f068..22a86376 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -1,6 +1,6 @@
---
-language: c
-filename: learnc.c
+language: C
+filename: learnc-pt.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Ãrpád Goretity", "http://twitter.com/H2CO3_iOS"]
@@ -10,7 +10,6 @@ translators:
- ["Cássio Böck", "https://github.com/cassiobsilva"]
- ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
lang: pt-br
-filename: c-pt.el
---
Ah, C. Ainda é **a** linguagem de computação de alta performance.
@@ -385,7 +384,6 @@ int main() {
// Por exemplo, quando um array é passado para uma função ou é atribuído a um
// ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro.
// Exceções: quando o array é o argumento de um operador `&` (endereço-de):
- // Exceptions: when the array is the argument of the `&` (address-of) operator:
int arr[10];
int (*ptr_to_arr)[10] = &arr; // &arr não é do tipo `int *`!
// É do tipo "ponteiro para array" (de `int`s).
diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown
index e40b8fe7..15ad930a 100644
--- a/pt-br/clojure-pt.html.markdown
+++ b/pt-br/clojure-pt.html.markdown
@@ -561,7 +561,7 @@ Caso queira aprender mais:
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
* 4clojure possui alguns problemas e desafios interessantes para quem quiser treinar clojure ou programação funcional:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
* clojure-doc.org tem um bom número de artigos para iniciantes:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown
index 384ca325..87e5b3a4 100644
--- a/pt-br/csharp-pt.html.markdown
+++ b/pt-br/csharp-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
filename: csharp-pt.cs
contributors:
- ["Robson Alves", "http://robsonalves.net/"]
@@ -153,7 +153,7 @@ on a new line! ""Wow!"", the masses cried";
intArray[1] = 1;
// Listas
- // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis
+ // Listas são usadas frequentemente tanto quanto matriz por serem mais flexíveis
// O formato de declarar uma lista é o seguinte:
// List<tipodado> <var nome> = new List<tipodado>();
List<int> intList = new List<int>();
diff --git a/pt-br/d-pt.html.markdown b/pt-br/d-pt.html.markdown
new file mode 100644
index 00000000..ae4bab22
--- /dev/null
+++ b/pt-br/d-pt.html.markdown
@@ -0,0 +1,262 @@
+---
+language: D
+filename: learnd-pt.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Julio Vanzelli", "https://github.com/JulioVanzelli"]
+lang: pt-br
+---
+
+```d
+// Você sabe o que está por vir...
+module hello;
+
+import std.stdio;
+
+// args é opcional
+void main(string[] args) {
+ writeln("Hello, World!");
+}
+```
+
+Se você é como eu e passa muito tempo na Internet, é provável que tenha ouvido
+sobre [D] (http://dlang.org/). A linguagem de programação D é moderna, de uso geral,
+linguagem multiparadigma com suporte para tudo, desde recursos de baixo nível até
+abstrações expressivas de alto nível.
+
+D é desenvolvido ativamente por um grande grupo de pessoas super-inteligentes e é liderado por
+[Walter Bright] (https://en.wikipedia.org/wiki/Walter_Bright) e
+[Andrei Alexandrescu] (https://en.wikipedia.org/wiki/Andrei_Alexandrescu).
+Com tudo isso fora do caminho, vamos dar uma olhada em alguns exemplos!
+
+```d
+import std.stdio;
+
+void main() {
+
+ // Condicionais e loops funcionam como esperado.
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ // 'auto' pode ser usado para inferir tipos.
+ auto n = 1;
+
+ // literais numéricos podem usar '_' como um separador de dígitos para maior clareza.
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // Por e enquanto são bons, mas em D-land preferimos loops 'foreach'.
+ // O '..' cria um intervalo contínuo, incluindo o primeiro valor
+ // mas excluindo o último.
+ foreach(n; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(n);
+ }
+
+ // Há também 'foreach_reverse' quando você deseja fazer um loop para trás.
+ foreach_reverse(n; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(n);
+ } else {
+ writeln("No!");
+ }
+ }
+}
+```
+
+Podemos definir novos tipos com `struct`,` class`, `union` e` enum`. Estruturas e uniões
+são passados para funções por valor(ou seja, copiados) e as classes são passadas por referência. Além disso,
+podemos usar modelos para parametrizar tudo isso em tipos e valores!
+
+```d
+// Aqui, 'T' é um parâmetro de tipo. Pense '<T>' em C++/C#/Java.
+struct LinkedList(T) {
+ T data = null;
+
+ // Usar '!' para instanciar um tipo parametrizado. Mais uma vez, pense '<T>'.
+ LinkedList!(T)* next;
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Se houver apenas um parâmetro de modelo, podemos omitir os parênteses.
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Use o alias para criar abreviações para tipos.
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// Também podemos criar modelos de funções!
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// Use a palavra-chave ref para garantir a passagem por referência. Ou seja, mesmo que 'a'
+// e 'b' sejam tipos de valor, eles sempre serão passados por referência a 'swap ()'.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Com os modelos, também podemos parametrizar valores, não apenas tipos.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // O tipo 'T' foi padronizado como 'int'.
+
+```
+
+Falando em aulas, vamos falar sobre propriedades por um segundo. Uma propriedade
+é aproximadamente uma função que pode agir como um valor I, para que possamos
+ter a sintaxe das estruturas POD (`structure.x = 7`) com a semântica de
+métodos getter e setter (`object.setX (7)`)!
+
+```d
+// Considere uma classe parametrizada nos tipos 'T' e 'U'.
+class MyClass(T, U) {
+ T _data;
+ U _other;
+}
+
+// E os métodos "getter" e "setter", assim:
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Os construtores sempre são chamados de 'this'.
+ this(T t, U u) {
+ // This will call the setter methods below.
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ @property void data(T t) {
+ _data = t;
+ }
+
+ @property void other(U u) {
+ _other = u;
+ }
+}
+
+// E nós os usamos desta maneira:
+void main() {
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Importe o módulo 'stdio' da biblioteca padrão para gravar no
+ // console (as importações podem ser locais para um escopo).
+ import std.stdio;
+
+ // Ligue para os getters para buscar os valores.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // Ligue para os setters para atribuir novos valores.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // Ligue para os getters novamente para buscar os novos valores.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
+}
+```
+
+Com propriedades, podemos adicionar qualquer quantidade de lógica para
+nossos métodos getter e setter, e mantenha a sintaxe limpa de
+acessando membros diretamente!
+
+Outras guloseimas orientadas a objetos à nossa disposição,
+incluem interfaces, classes abstratas,
+e métodos de substituição. D faz herança como Java:
+Estenda uma classe, implemente quantas interfaces você desejar.
+
+Vimos as instalações OOP de D, mas vamos mudar de marcha. D oferece
+programação funcional com funções de primeira classe, `pura`
+funções e dados imutáveis. Além disso, todos os seus favoritos
+algoritmos funcionais (mapear, filtrar, reduzir e amigos) podem ser
+encontrado no maravilhoso módulo `std.algorithm`!
+
+```d
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // cria uma gama exclusiva de final
+
+void main() {
+ // Queremos imprimir a soma de uma lista de quadrados de ints pares
+ // de 1 a 100. Fácil!
+
+ // Basta passar expressões lambda como parâmetros de modelo!
+ // Você pode passar qualquer função que desejar, mas as lambdas são convenientes aqui.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Observe como conseguimos construir um bom pipeline haskelliano para calcular num?
+Isso se deve a uma inovação em D, conhecida como Uniform Function Call Syntax (UFCS).
+Com o UFCS, podemos optar por escrever uma chamada de função como método
+ou chamada de função grátis! Walter escreveu um bom artigo sobre isso
+[aqui.] (http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Em resumo, você pode chamar funções cujo primeiro parâmetro
+é de algum tipo A em qualquer expressão do tipo A como método.
+
+Eu gosto de paralelismo. Alguém mais gosta de paralelismo? Com certeza. Vamos fazer um pouco!
+
+```d
+// Digamos que queremos preencher uma matriz grande com a raiz quadrada de todos
+// os números inteiros consecutivos começando de 1 (até o tamanho da matriz), e queremos
+// fazer isso simultaneamente, aproveitando o número de núcleos que temos
+// disponível.
+
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // Crie sua grande variedade
+ auto arr = new double[1_000_000];
+
+ // Use um índice, acesse todos os elementos da matriz por referência (porque vamos
+ // mudar cada elemento) e apenas chame paralelo na matriz!
+ foreach(i, ref elem; parallel(arr)) {
+ elem = sqrt(i + 1.0);
+ }
+}
+```
diff --git a/pt-br/dart-pt.html.markdown b/pt-br/dart-pt.html.markdown
index e9d72850..6aff1ac3 100644
--- a/pt-br/dart-pt.html.markdown
+++ b/pt-br/dart-pt.html.markdown
@@ -3,15 +3,16 @@ language: dart
filename: learndart-pt.dart
contributors:
- ["Joao Pedrosa", "https://github.com/jpedrosa/"]
+ - ["Hélio Oliveira", "https://github.com/insign/"]
translators:
- ["Junior Damacena", "https://github.com/jdamacena/"]
lang: pt-br
---
Dart é uma novata no reino das linguagens de programação.
-Ela empresta muito de outras linguagens mais conhecidas, e tem a meta de não se diferenciar muito de seu irmão, JavaScript. Assim como JavaScript, Dart foi pensada para oferecer grande integração com o Browser.
+Ela absorve muitas teorias de outras linguagens mais conhecidas, e tem a meta de não se diferenciar muito de seu irmão, JavaScript. Assim como JavaScript, Dart foi pensada para oferecer grande integração com o navegador.
-A característica mais controversa da Dart é a sua Tipagem Opcional, ou seja, não é obrigatório declarar tipos.
+As variáveis em Dart tem tipos, mas não é obrigatório declarar devido à função de [detecção automática](https://dart.dev/guides/language/type-system#type-inference).
```dart
import "dart:collection";
diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown
index 4ba78f52..18441ff7 100644
--- a/pt-br/elixir-pt.html.markdown
+++ b/pt-br/elixir-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -20,7 +20,7 @@ e muitos outros recursos.
# Não há comentários de múltiplas linhas,
# mas você pode empilhar os comentários.
-# Para usar o shell do elixir use o comando `iex`.
+# Para usar o shell do Elixir use o comando `iex`.
# Compile seus módulos com o comando `elixirc`.
# Ambos devem estar em seu path se você instalou o Elixir corretamente.
@@ -51,7 +51,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# Em elixir, bem como em Erlang, o sinal `=` denota pattern match,
+# Em Elixir, bem como em Erlang, o sinal `=` denota pattern match,
# e não uma atribuição.
#
# Isto significa que o que estiver à esquerda (pattern) é comparado com o que
@@ -85,7 +85,7 @@ linhas.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` em elixir retorna o valor ASCII para a letra `a`
+# `?a` em Elixir retorna o valor ASCII para a letra `a`
?a #=> 97
# Para concatenar listas use `++`, para binários use `<>`
@@ -98,7 +98,7 @@ linhas.
# Ranges são representados como `início..fim` (ambos inclusivos)
1..10 #=> 1..10
menor..maior = 1..10 # Pattern matching pode ser usada em ranges também
-[lower, upper] #=> [1, 10]
+[menor, maior] #=> [1, 10]
## ---------------------------
## -- Operadores
@@ -110,7 +110,7 @@ menor..maior = 1..10 # Pattern matching pode ser usada em ranges também
5 * 2 #=> 10
10 / 2 #=> 5.0
-# Em elixir o operador `/` sempre retorna um float.
+# Em Elixir o operador `/` sempre retorna um float.
# Para divisão de inteiros use `div`
div(10, 2) #=> 5
@@ -167,7 +167,7 @@ else
"Isso será"
end
-# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela.
+# Lembra do pattern matching? Muitas estruturas de fluxo de controle em Elixir contam com ela.
# `case` nos permite comparar um valor com muitos patterns:
case {:um, :dois} do
@@ -296,7 +296,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# Devido à imutabilidade, recursão é uma grande parte do elixir
+# Devido à imutabilidade, recursão é uma grande parte do Elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -309,7 +309,7 @@ end
Recursion.sum_list([1,2,3], 0) #=> 6
-# Módulos do elixir suportam atributos, hpa atributos embutidos e você
+# Módulos do Elixir suportam atributos, hpa atributos embutidos e você
# pode também adicionar os seus próprios.
defmodule MyMod do
@moduledoc """
@@ -361,7 +361,7 @@ end
## ---------------------------
# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para
-# escrever programas concorrentes em elixir são três primitivos: spawning processes,
+# escrever programas concorrentes em Elixir são três primitivos: spawning processes,
# sending messages e receiving messages.
# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função
diff --git a/pt-br/emacs-pt.html.markdown b/pt-br/emacs-pt.html.markdown
new file mode 100644
index 00000000..7a86a119
--- /dev/null
+++ b/pt-br/emacs-pt.html.markdown
@@ -0,0 +1,60 @@
+---
+category: tool
+tool: emacs
+filename: emacs.txt
+contributors:
+ - ["Joseph Riad", "https://github.com/Joseph-Riad"]
+translators:
+ - ["André de Santa Gabriel", "https://github.com/andredesanta"]
+lang: pt-br
+---
+
+O Emacs começou sua vida como (https://www.gnu.org/software/emacs/emacs-paper.html) e cresceu
+ao longo dos anos em um ecossistema completo. Muitas tarefas, geralmente
+relegado a um conjunto diversificado de ferramentas pode ser realizado de dentro
+Emacs em uma interface consistente e familiar. Exemplos incluem
+gerenciamento de diretório, visualização de documentos PDF, edição de arquivos via SSH, gerenciamento de
+repos git. Em suma, o Emacs é seu para fazer
+o que você quiser: o espectro de usuários varia daqueles que o usam para
+editar arquivos de texto para puristas extremos que o usam para substituir virtualmente seu
+sistema operacional.
+
+O Emacs é extensível através de um dialeto especializado do Lisp conhecido como Emacs
+Lisp (Elisp), que possui muitas macros voltadas para a edição de texto e
+gerenciamento de buffers de texto. Qualquer tecla (combinação) usada no Emacs está vinculada
+para uma função Emacs Lisp e pode ser remapeado para qualquer outra função,
+incluindo aqueles que você escreve
+você mesmo.
+
+# Conceitos básicos de Emacs
+
+Aqui, discuto alguns conceitos e terminologia básicos do Emacs que podem ser
+confusos para os recém-chegados (especialmente para as pessoas acostumadas à terminologia do Vim):
+
+ - O texto que o Emacs está editando é conhecido como **buffer**
+
+ - Um buffer não corresponde necessariamente a um arquivo real no disco. Pode ser apenas texto na memória.
+
+ - Quando um buffer corresponde a um arquivo no disco, dizemos que o buffer está **visitando** esse arquivo.
+
+ - O Emacs normalmente possui muitos buffers abertos ao mesmo tempo.
+
+ - A exibição do Emacs pode ser dividida em diferentes **windows**.
+
+ - Uma janela do sistema operacional para o Emacs é chamada de **frame**. Assim, quando o manual do Emacs fala sobre a abertura de um novo frame, esse essencialmente significa abrir uma nova janela do SO contendo uma (outra) instância do Emacs.
+  
+ - Os conceitos convencionalmente conhecidos como recortar e colar são referido como **killing** e **yanking**, respectivamente no Emacs.
+  
+ - A posição atual do cursor é chamada de **point** no Emacs. Tecnicamente, **point** é definido como a posição imediatamente antes do caractere onde o cursor está atualmente.
+  
+ - Finalmente, cada buffer pode ter vários **modes** associados: o **major mode** e possivelmente vários **minor modes**.
+  
+ - O **major mode** define o principal comportamento do Emacs no buffer atualmente selecionado. Isso pode ser pensado como o tipo de arquivo. Por exemplo, se você estiver editando um arquivo Python, os principais modes é (por padrão) `python-mode`, que faz com que o Emacs destaque a sintaxe Python e idente automaticamente seus blocos de código conforme exigido sintaticamente pelo seu código Python.
+  
+ - **Minor modes** definem mudanças sutis no comportamento e várias alterações menores Os modos podem estar ativos ao mesmo tempo no mesmo buffer. Um exemplo menor modo é o modo flyspell, que destaca automaticamente os erros de ortografia no seu buffer.
+
+# Recursos adicionais
+
+ - [The GNU Emacs Manual](https://www.gnu.org/software/emacs/manual/emacs.html)
+ - [Emacs Stack Exchange](https://emacs.stackexchange.com/)
+ - [Emacs Wiki](https://www.emacswiki.org/emacs/EmacsWiki)
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
index e59ba901..2cc1c337 100644
--- a/pt-br/git-pt.html.markdown
+++ b/pt-br/git-pt.html.markdown
@@ -11,6 +11,7 @@ contributors:
translators:
- ["Suzane Sant Ana", "http://github.com/suuuzi"]
- ["Bruno Volcov", "http://github.com/volcov"]
+ - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"]
---
Git é um sistema distribuido de gestão para código fonte e controle de versões.
@@ -67,7 +68,8 @@ referências e outros.
### *Working Tree* (componente do repositório)
-A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto.
+A *Working Tree* é basicamente a listagem dos diretórios e arquivos do
+repositório. É chamada também de diretório do projeto.
### *Index* (componente do diretório .git)
@@ -77,28 +79,37 @@ maior controle sobre o que é registado no repositório git.
### *Commit*
-Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto.
-Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações
-serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado
-para outros repositórios ou não!
+Um *commit** de git é um registo de um conjunto de alterações ou manipulações
+nos arquivos do projeto. Por exemplo, ao adicionar cinco arquivos e remover
+outros 2, estas alterações serão gravadas em um *commit* (ou registro). Este
+*commit* pode então ser enviado para outros repositórios, caso você queira.
### *Branch*
-Um *branch* é essencialmente uma referência que aponta para o último *commit*
+Uma *branch* é essencialmente uma referência que aponta para o último *commit*
efetuado. Na medida que são feitos novos commits, esta referência é atualizada
automaticamente e passa a apontar para o commit mais recente.
### *Tag*
Uma tag é uma marcação em um ponto específico da história. Geralmente as
-pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí vai)
+pessoas usam esta funcionalidade para marcar pontos de release (v2.0, e por aí
+vai)
### *HEAD* e *head* (componentes do diretório .git)
-*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem
-uma *HEAD* activa.
-*head* é uma referência que aponta para qualquer *commit*. Um repositório pode
-ter um número indefinido de *heads*
+*HEAD* é a referência que aponta para a *branch* em uso. Um repositório só tem
+uma *HEAD* activa. *head* é uma referência que aponta para qualquer *commit*. Um
+repositório pode ter um número indefinido de *heads*.
+
+### Estados no Git
+
+* Modificado (Modified): Ocorreram mudanças em ao menos um arquivo mas essas
+mudanças ainda não foram registradas na base de dados do Git
+* Preparado (Staged): Marca o arquivo como preparado para ser adicionado ao
+próximo commit
+* Consolidado (Committed): As mudanças foram registradas na base de dados do
+Git
### Recursos conceituais (EN)
@@ -109,8 +120,8 @@ ter um número indefinido de *heads*
### *init*
-Cria um repositório Git vazio. As definições, informação guardada e outros do
-repositório git são guardados em uma pasta chamada ".git".
+Cria um repositório Git vazio. As configurações do repositório, e outras
+informações são guardadas em uma pasta dentro do repositório com o nome ".git".
```bash
$ git init
@@ -118,23 +129,24 @@ $ git init
### *config*
-Permite configurar as definições, sejam as definições do repositório, sistema
-ou configurações globais.
+Permite configurar o git, seja com respeito a definições deste repositório,
+do sistema ou configurações globais para todos os repositórios.
```bash
-# Imprime e define algumas variáveis de configuração básicas (global)
-$ git config --global user.email
-$ git config --global user.name
-
+# Define e imprime algumas variáveis de configuração básicas (global)
$ git config --global user.email "MyEmail@Zoho.com"
$ git config --global user.name "My Name"
+
+$ git config --global user.email
+$ git config --global user.name
```
[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config)
### help
-Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica.
+Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da
+semântica.
```bash
# Ver rapidamente os comandos disponiveis
@@ -148,16 +160,32 @@ $ git help -a
$ git help add
$ git help commit
$ git help init
+# ou git <comando_aqui> --help
+$ git add --help
+$ git commit --help
+$ git init --help
+```
+
+### Ignorando arquivos
+
+É possível intencionalmente ignorar arquivos e pastas. Costuma-se utilizar o
+arquivo .gitignore para fazer o git ignorar a existência de arquivos e pastas
+geralmente utilizados para arquivos privados ou temporários que, de outro modo,
+seriam compartilhados com todos que tem acesso ao repositório.
+
+```bash
+$ echo "temp/" >> .gitignore
+$ echo "chave_privada" >> .gitignore
```
### status
-Apresenta as diferenças entre o arquivo *index* (a versão corrente
-do repositório) e o *commit* da *HEAD* atual.
+Apresenta as diferenças entre o arquivo *index* (a versão corrente do
+repositório) e o *commit* da *HEAD* atual.
```bash
-# Apresenta o *branch*, arquivos não monitorados, alterações e outras
+# Apresenta a *branch*, arquivos não monitorados, alterações e outras
# diferenças
$ git status
@@ -173,35 +201,42 @@ incluidos nos commits!
```bash
# adiciona um arquivo no diretório do projeto atual
-$ git add HelloWorld.java
+$ git add OlaMundo.java
-# adiciona um arquivo num sub-diretório
-$ git add /path/to/file/HelloWorld.c
+# adiciona um arquivo em um sub-diretório
+$ git add /caminho/para/arquivo/OlaMundo.java
# permite usar expressões regulares!
$ git add ./*.java
+
+# Você também pode adicionar tudo no seu diretório de trabalho como alterações
+prontas para o próximo commit.
+$ git add -A
```
+Esse comando apenas adiciona os arquivos no estado de preparados para o próximo
+commit, mas não realiza o commit de fato.
+
### branch
-Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este
+Gerencia as *branches*. É possível ver, editar, criar e apagar branches com este
comando.
```bash
# listar *branches* existentes e remotos
$ git branch -a
-# criar um novo *branch*
+# criar uma nova *branch*
$ git branch myNewBranch
-# apagar um *branch*
+# apagar uma *branch*
$ git branch -d myBranch
-# alterar o nome de um *branch*
+# alterar o nome de uma *branch*
# git branch -m <oldname> <newname>
$ git branch -m myBranchName myNewBranchName
-# editar a descrição de um *branch*
+# editar a descrição de uma *branch*
$ git branch myBranchName --edit-description
```
@@ -212,18 +247,22 @@ Gerencia as *tags*
```bash
# Listar tags
$ git tag
+
# Criar uma tag anotada.
# O parâmetro -m define uma mensagem, que é armazenada com a tag.
# Se você não especificar uma mensagem para uma tag anotada,
# o Git vai rodar seu editor de texto para você digitar alguma coisa.
$ git tag -a v2.0 -m 'minha versão 2.0'
+
# Mostrar informações sobre a tag
# O comando mostra a informação da pessoa que criou a tag,
# a data de quando o commit foi taggeado,
# e a mensagem antes de mostrar a informação do commit.
$ git show v2.0
+
# Enviar uma tag para o repositório remoto
$ git push origin v2.0
+
# Enviar várias tags para o repositório remoto
$ git push origin --tags
```
@@ -231,14 +270,16 @@ $ git push origin --tags
### checkout
Atualiza todos os arquivos no diretório do projeto para que fiquem iguais
-à versão do index ou do *branch* especificado.
+à versão do index ou da *branch* especificado.
```bash
-# Checkout de um repositório - por padrão para o branch master
+# Checkout de um repositório - por padrão para a branch master
$ git checkout
-# Checkout de um branch especifico
+
+# Checkout de uma branch especifica
$ git checkout branchName
-# Cria um novo branch e faz checkout para ele.
+
+# Cria uma nova branch e faz checkout para ela.
# Equivalente a: "git branch <name>; git checkout <name>"
$ git checkout -b newBranch
```
@@ -246,22 +287,41 @@ $ git checkout -b newBranch
### clone
Clona ou copia um repositório existente para um novo diretório. Também
-adiciona *branches* de monitoramento remoto para cada *branch* no repositório
-clonado o que permite enviar alterações para um *branch* remoto.
+adiciona *branches* no repositório clonado para cada *branch* no repositório
+remoto o que permite enviar alterações para uma *branch* no repositório remoto.
```bash
# Clona learnxinyminutes-docs
$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+
+# Clone superficial - É mais rápido, mas puxa apenas o último commit
+$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git
+
+# Clona apenas uma branch em específica
+$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch
```
### commit
-Guarda o conteudo atual do index num novo *commit*. Este *commit* contém
+Guarda o conteúdo atual do index em um novo *commit*. Este *commit* contém
as alterações feitas e a mensagem criada pelo usuário.
```bash
-# commit com uma mensagem
-$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+# Realiza um commit com uma mensagem
+$ git commit -m "Adicione a função multipliqueNumeros() em OlaMundo.c"
+
+# Assine um commit com sua chave GPG. Antes disso, você precisa ter
+# configurado a opção user.signkey do git com o comando:
+# git config --global user.signinkey ID_CHAVE_AQUI
+$ git commit -S -m "mensagem do commit aqui"
+
+# Automaticamente adicione como preparados arquivos modificados ou apagados e
+# então realize um commit:
+$ git commit -a -m "Modified foo.php and removed bar.php"
+
+# Altere o último commit (Esse comando cria um novo commit com o conteúdo do
+# commit anterior mais suas novas alterações e sobrescreve o último commit)
+$ git commit --amend -m "Correct message"
```
### diff
@@ -282,7 +342,7 @@ $ git diff HEAD
### grep
-Permite procurar facilmente num repositório
+Permite procurar facilmente em um repositório.
Configurações opcionais:
@@ -313,74 +373,158 @@ Apresenta commits do repositório.
# Apresenta todos os commits
$ git log
-# Apresenta X commits
-$ git log -n 10
+# Apresenta apenas mensagem do commit e referência
+$ git log --oneline
# Apresenta apenas commits de merge
$ git log --merges
+
+# Apresenta todos os commits representados por um gráfico em ASCII
+$ git log --graph
```
### merge
-"Merge" junta as alterações de commits externos com o *branch* atual.
+"Merge" junta as alterações de commits externos com a *branch* atual.
```bash
-# Junta o branch especificado com o atual
+# Junta a branch especificada com o atual
$ git merge branchName
-# Para gerar sempre um commit ao juntar os branches
+# Para gerar sempre um commit ao juntar as branches
$ git merge --no-ff branchName
```
### mv
-Alterar o nome ou mover um arquivo.
+Altera o nome ou move um arquivo.
```bash
# Alterar o nome de um arquivo
-$ git mv HelloWorld.c HelloNewWorld.c
+$ git mv OlaMundo.c OlaNovoMundo.c
# Mover um arquivo
-$ git mv HelloWorld.c ./new/path/HelloWorld.c
+$ git mv OlaMundo.c ./novo/caminho/OlaMundo.c
-# Forçar a alteração de nome ou mudança local
-# "existingFile" já existe no directório, será sobrescrito.
+# Forçar a alteração de nome ou mudança de local
+# Se o arquivo já existir no diretório, será sobrescrito.
$ git mv -f myFile existingFile
```
### pull
-Puxa alterações de um repositório e as junta com outro branch
+Puxa alterações de um repositório e as junta com outra branch
```bash
# Atualiza o repositório local, juntando as novas alterações
# do repositório remoto 'origin' e branch 'master'
# git pull <remote> <branch>
-# git pull => aplica a predefinição => git pull origin master
$ git pull origin master
-# Juntar alterações do branch remote e fazer rebase commits do branch
+# Por padrão, o git irá realizar o pull na branch atual fazendo um merge
+# com as alterações novas na branch remota
+$ git pull
+
+# Juntar alterações da branch remote e fazer rebase commits da branch
# no repositório local, como: "git pull <remote> <branch>, git rebase <branch>"
$ git pull origin master --rebase
```
### push
-Enviar e juntar alterações de um branch para o seu branch correspondente
-num repositório remoto.
+Enviar e juntar alterações de uma branch para a sua branch correspondente
+em um repositório remoto.
```bash
# Envia e junta as alterações de um repositório local
-# para um remoto denominado "origin" no branch "master".
+# para um remoto denominado "origin" na branch "master".
# git push <remote> <branch>
-# git push => aplica a predefinição => git push origin master
$ git push origin master
+
+# Por padrão, o git push irá enviar e realizar merge das mudanças da sua branch
+# local com a branch remota
+$ git push
+
+# Para associar a branch local com uma branch específica remota, adicione a
+# flag -u
+$ git push -u origin master
+
+# Agora, sempre que você realizar um push daquela branch local, use o atalho:
+$ git push
```
+### stash
+
+O objetivo desse comando do git é pegar o estado "sujo" do seu diretório de
+trabalho, que não está pronto (staged), e salvá-lo em um outro lugar para que
+você possa trabalhar no seu repositório do zero, mas sem perder as mudanças que
+fez. Em qualquer outro momento que você quiser, você pode trazer de volta as
+alterações que você tirou dali com o comando stash.
+
+Digamos que você tem feito algumas alterações no seu repositório, mas agora
+você quer realizar um pull do repositório remoto. Como você tem alterações não
+commitadas no seu diretório (ele está "sujo"), você não irá conseguir realizar
+o `git pull` com sucesso. Mas você pode executar o `git stash` para salvar
+essas alterações e conseguir realizar o pull. Depois, você traz de volta.
+
+```bash
+$ git stash
+Saved working directory and index state \
+ "WIP on master: 049d078 added the index file"
+ HEAD is now at 049d078 added the index file
+ (To restore them type "git stash apply")
+```
+
+Agora você irá conseguir realizar o pull!
+
+```bash
+git pull
+```
+`...changes apply...`
+
+Verifique se está tudo OK com o `git status`
+
+```bash
+$ git status
+# On branch master
+nothing to commit, working directory clean
+```
+
+É possível verificar as alterações que você guardou com cada uso do comando
+`git stash` com o `git stash list`. Como os usos desse comando são guardados
+como em uma pilha, os usos mais recentes estarão no topo.
+
+```bash
+$ git stash list
+stash@{0}: WIP on master: 049d078 added the index file
+stash@{1}: WIP on master: c264051 Revert "added file_size"
+stash@{2}: WIP on master: 21d80a5 added number to log
+```
+
+Agora vamos trazer o que havíamos salvado com o `git stash` de volta para o
+diretório de trabalho.
+
+```bash
+$ git stash pop
+# On branch master
+# Changes not staged for commit:
+# (use "git add <file>..." to update what will be committed)
+#
+# modified: index.html
+# modified: lib/simplegit.rb
+#
+```
+
+`git stash apply` faz a mesma coisa
+
+Agora podemos voltar a trabalhar no que havíamos deixado de lado!
+
+[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing)
+
### rebase (cautela!)
-Pega em todas as alterações que foram registadas num branch e volta a
-aplicá-las em outro branch.
+Pega em todas as alterações que foram registadas em uma branch e volta a
+aplicá-las em outra branch.
*Não deve ser feito rebase de commits que foram enviados para um repositório
público*
@@ -407,31 +551,79 @@ $ git reset
# sobrescreve o projeto atual
$ git reset --hard
-# Move a head do branch atual para o commit especificado, sem alterar o projeto.
+# Move a head da branch atual para o commit especificado, sem alterar o projeto.
# todas as alterações ainda existem no projeto
$ git reset 31f2bb1
-# Inverte a head do branch atual para o commit especificado
+# Inverte a head da branch atual para o commit especificado
# fazendo com que este esteja em sintonia com o diretório do projeto
-# Remove alterações não registadas e todos os commits após o commit especificado
+# Remove alterações não registradas e todos os commits após o commit
+# especificado
$ git reset --hard 31f2bb1
```
+### reflog (cuidado!)
+
+O reflog irá listar a maior parte dos comandos que você realizou no git em um
+determinado intervalo de tempo. O intervalo padrão é de 90 dias.
+
+Isso te dá a oportunidade de reverter qualquer comando que você realizou no git
+e que tenha tido consequências indesejadas (por exemplo, se um rebase quebrou
+sua aplicação).
+
+Você pode fazer assim:
+
+1. `git reflog` para listar todos os comandos utilizados no git para o rebase
+
+```
+38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog
+38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators
+4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown
+34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666)
+ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748)
+2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d
+```
+2. Selecione para onde você quer resetar. No nosso exemplo, seria o commit
+`2e6c386`, ou `HEAD@{5}`
+3. 'git reset --hard HEAD@{5}' esse comando irá resetar o seu repositório para
+aquele ponto (5 commits atrás).
+4. Agora você pode recomeçar o rebase ou apenas deixar como está.
+
+[Leitura complementar](https://git-scm.com/docs/git-reflog)
+
+### revert
+
+O comando revert pode ser utilizado para desfazer um commit. Não deve ser
+confundido com o comando reset que restabelece o estado do repositório para um
+momento anterior. O revert irá criar um novo commit com alterações inversas a
+de um outro commit especificado, portanto revertendo aquelas alterações.
+
+```bash
+# Revertendo um commit específico
+$ git revert <commit>
+```
+
### rm
-O oposto de git add, git rm remove arquivos do branch atual.
+O oposto de git add, git rm remove arquivos da branch atual.
```bash
-# remove HelloWorld.c
-$ git rm HelloWorld.c
+# remove OlaMundo.c
+$ git rm OlaMundo.c
-# Remove um arquivo de um sub-directório
-$ git rm /pather/to/the/file/HelloWorld.c
+# Remove um arquivo de um sub-diretório
+$ git rm /caminho/para/o/arquivo/OlaMundo.c
```
-## Informação complementar (EN)
+## Leitura complementar
+
+* [Configurar o Git (GitHub Docs)](https://docs.github.com/pt/get-started/quickstart/set-up-git)
+
+* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/)
-* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
+* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+
+* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
* [git-scm - Video Tutorials](http://git-scm.com/videos)
@@ -441,4 +633,10 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
+* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
+
+* [Pro Git (em Português)](https://www.git-scm.com/book/pt-br/v2)
+
+* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)
+
+* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx)
diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown
index 31473ee1..ce10e079 100644
--- a/pt-br/go-pt.html.markdown
+++ b/pt-br/go-pt.html.markdown
@@ -28,7 +28,7 @@ Go vem com uma biblioteca padrão exaustiva e uma comunidade entusiasta.
várias linhas */
// A cláusula package aparece no início de cada arquivo.
-// Main é um nome especial declarando um executável ao invés de uma biblioteca.
+// main é um nome especial declarando um executável ao invés de uma biblioteca.
package main
// A cláusula Import declara os pacotes referenciados neste arquivo.
@@ -77,7 +77,7 @@ pode incluir quebras de linha.` // mesmo tipo string
// literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8.
g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode
- f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754)
+ f := 3.14159 // float64, número de vírgula flutuante de 64bit (IEEE-754)
c := 3 + 4i // complex128, representado internamente com dois float64s
// Declaração de variáveis, com inicialização.
@@ -295,17 +295,17 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
## Leitura Recomendada
-A principal fonte de informação é o [web site oficial Go](http://golang.org/).
+A principal fonte de informação é o [web site oficial Go](https://go.dev/).
Lá é possível seguir o tutorial, experimentar de forma iterativa, e ler muito.
A própria especificação da linguagem é altamente recomendada. É fácil de ler e
incrivelmente curta (em relação ao que é habitual hoje em dia).
Na lista de leitura para os aprendizes de Go deve constar o [código fonte da
-biblioteca padrão](http://golang.org/src/pkg/). Exaustivamente documentado, é
+biblioteca padrão](https://go.dev/src/). Exaustivamente documentado, é
a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e da
sua escrita idiomática. Ou então clique no nome de uma função na [documentação]
-(http://golang.org/pkg/) e veja o código fonte aparecer!
+(https://go.dev/pkg/) e veja o código fonte aparecer!
Outra ótima fonte para aprender Go é o [Go by example](https://gobyexample.com/).
Apesar de ser em inglês, é possível recodificar os exemplos para aprender sobre
diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
index 3acfce21..dff3f2e1 100644
--- a/pt-br/groovy-pt.html.markdown
+++ b/pt-br/groovy-pt.html.markdown
@@ -5,7 +5,8 @@ filename: learngroovy-pt.groovy
contributors:
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
translators:
- - ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["João Farias", "https://github.com/joaogfarias"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
lang: pt-br
---
@@ -201,8 +202,16 @@ if(x==1) {
//Groovy também suporta o operador ternário
def y = 10
-def x = (y > 1) ? "functionou" : "falhou"
-assert x == "functionou"
+def x = (y > 1) ? "funcionou" : "falhou"
+assert x == "funcionou"
+
+//E suporta o 'The Elvis Operator' também!
+//Em vez de usar o operador ternário:
+
+displayName = nome.name ? nome.name : 'Anonimo'
+
+//Podemos escrever:
+displayName = nome.name ?: 'Anonimo'
//Loop 'for'
//Itera sobre um intervalo (range)
diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown
index 58586522..919c0f4f 100644
--- a/pt-br/latex-pt.html.markdown
+++ b/pt-br/latex-pt.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Svetlana Golubeva", "https://attillax.github.io/"]
translators:
- ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
lang: pt-br
filename: learn-latex-pt.tex
---
@@ -16,10 +17,10 @@ filename: learn-latex-pt.tex
% Todas as linhas de comentários começam com %
% Não existem comentários multilinhas
-$ LaTeX não é um programa processador de textos "Visual" como
+% LaTeX não é um programa processador de textos "Visual" como
% MS Word ou OpenOffice Writer
-$ Todo comando LaTeX começa com uma barra invertida (\)
+% Todo comando LaTeX começa com uma barra invertida (\)
% Documentos LaTeX começam com a definição do tipo que será % compilado
% Os tipos de documento podem ser livro, relatório, apresentação, etc.
@@ -37,14 +38,11 @@ $ Todo comando LaTeX começa com uma barra invertida (\)
\usepackage{float}
\usepackage{hyperref}
-% Para poder usar caracteres acentuados, use o seguinte pacote:
-\usepackage[utf8]{inputenc}
-
% Podemos definir algumas outras propriedades do documento também!
\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\
Svetlana Golubeva}
\date{\today}
-\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!}
+\title{Aprenda \LaTeX{} em Y Minutos!}
% Agora estamos prontos para começar o documento
% Tudo antes dessa linha é chamado "preâmbulo".
@@ -52,6 +50,7 @@ Svetlana Golubeva}
% Se informarmos os campos author (autores), date (data), "title" (título),
% LaTeX poderá cria uma página inicial para nós.
\maketitle
+
% Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso,
% o documento deve ser compilado duas vezes, para que tudo apareça na ordem
% correta.
@@ -69,7 +68,7 @@ Svetlana Golubeva}
% Esse comando está disponível para os documentos do tipo artigo (article)
% e relatório (report).
\begin{abstract}
- Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original!
+ Documentação do \LaTeX{} escrita em \LaTeX! Nada original!
\end{abstract}
% Comandos para seções são intuitivos.
@@ -93,11 +92,17 @@ Muito melhor agora.
Afinal nem todas as seções precisam ser numeradas!
\section{Algumas notas sobre texto}
-%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço.
-\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve
+%\section{Espaçamento} % É necessário mais informação sobre intervalos de espaço.
+\LaTeX{} geralmente é muito bom sobre colocar texto onde ele deve
ser posto. Se
uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash
-\hspace{1pt} ao código de seu documento. \\
+\hspace{1pt} ao código de seu documento.
+
+Separe parágrafos por linhas vazias.
+
+Você precisa adicionar um til após abreviações (se não forem seguidas de vírgula)
+para um espaço sem quebra, senão o espaçamento após o ponto será muito largo:
+E.g., i.e., etc.~são exemplos de abreviações.
\section{Listas}
Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras
@@ -112,21 +117,21 @@ amanhã, então façamos uma lista de compras.
Não é um item da lista, mas faz parte do bloco enumerate.
- \end{enumerate} % Todos os blocos devem ter um final (end{}).
+\end{enumerate} % Todos os blocos devem ter um final (end{}).
\section{Matemática}
-Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos
+Um dos usos iniciais para \LaTeX{} foi a produção de artigos
acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é
-necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\
+necessários que consigamos incluir alguns símbolos especiais em nosso texto!
A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado;
símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas
-para mencionar alguns.\\
+para mencionar alguns.
Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática.
Aqui está como você pode indicar como todo x que pertence
-a X, $\forall$ x $\in$ X. \\
+a X, $\forall$ x $\in$ X.
% Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos.
% Isso é porque quando escrevendo, estamos em modo texto.
% Mas os símbolos de matemática só existem no modo matemática.
@@ -138,15 +143,14 @@ a X, $\forall$ x $\in$ X. \\
\[a^2 + b^2 = c^2 \]
Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$.
-Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\
+Eu ainda não encontrei uma letra grega que o \LaTeX{} não tenha!\\
Operadores são parte essencial de um documento sobre matemática:
funções trigonométricas ($\sin$, $\cos$, $\tan$),
logaritmo e exponencial ($\log$, $\exp$),
-limites ($\lim$), etc.
-possuem comandos pré-definidos em LaTex.
+limites ($\lim$), etc.~possuem comandos pré-definidos em LaTex.
Vamos escrever uma equação para ver como se faz:
-$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
Frações (numerador/denominador) podem ser escritas dessa forma:
@@ -183,8 +187,10 @@ Somatórios e Integrais são escritas com os comandos sum e int:
\section{Figuras}
-Insiramos uma Figura. O local para colocar a figura pode ser difícil
-de determinar. Eu tenho sempre que verificar as opções toda vez.
+Insiramos uma Figura. O local para colocar a figura pode ser difícil de determinar.
+Operações básicas são [t] para o topo, [b] para base, [h] para aqui (aproximadamente).
+Eu tenho sempre que verificar as opções toda vez.
+% Veja https://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions para mais detalhes
\begin{figure}[H] % H aqui é uma opção para o local da figura.
\centering % centra a figura na página
@@ -201,36 +207,45 @@ Também podemos incluir tabelas da mesma forma que figuras.
\begin{table}[H]
\caption{Título para a Tabela.}
% os argumentos {} abaixo descrevem como cada linha da tabela é desenhada.
- % Aqui também, Preciso ver isso. Toda. E. Cada. Vez.
+ % O básico é simples: uma letra para cada coluna, para controlar o alinhamento:
+ % Operações básicas são: c, l, r e p para centro, esquerda, direita e parágrafo
+ % opcionalmente, você pode adicionar um | para linha vertical
+ % Veja https://en.wikibooks.org/wiki/LaTeX/Tables para mais detalhes
\begin{tabular}{c|cc}
- Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por &
+ Número & Primeiro Nome & Sobrenome \\ % Colunas são separadas por &
\hline % uma linha horizontal
1 & Biggus & Dickus \\
2 & Monty & Python
\end{tabular}
+ % Vai ficar mais ou menos assim:
+ % Número | Primeiro Nome Sobrenome
+ % -------|--------------------------- % por causa do \hline
+ % 1 | Biggus Dickus
+ % 2 | Monty Python
\end{table}
-\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)}
+\section{Fazendo o \LaTeX{} não compilar algo (o código fonte)}
Digamos que precisamos incluir algum código dentro do nosso
-documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt}
+documento \LaTeX{}, para isso precisamos com o \LaTeX{}
não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos
isso com o bloco verbatim.
% Existem outros pacotes (por exemplo, minty, lstlisting, etc.)
% mas verbatim é o básico
\begin{verbatim}
- print("Hello World!")
+ print("Olá mundo!")
a%b; % olha só! Podemos usar os sinais % no bloco verbatim.
- random = 4; #decided by fair random dice roll
+ random = 4; #decidido por um lançamento honesto de dado
+ Veja https://www.explainxkcd.com/wiki/index.php/221:_Random_Number
\end{verbatim}
\section{Compilando}
Imagino que agora você esteja pensando como compilar esse fantástico documento
-e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf.
+e visualizar a gloriosa glória que é um pdf gerado por \LaTeX{} pdf.
(sim, esse documento é compilável). \\
-Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos:
+Finalizando o documento usando \LaTeX{} consiste nos seguintes passos:
\begin{enumerate}
\item Escrever o documento em texto puro (o ``código fonte'').
\item Compilar o código fonte para gerar um pdf.
@@ -240,7 +255,7 @@ Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos
\end{verbatim}
\end{enumerate}
-Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo
+Existem editores de \LaTeX{} que combinam os passos 1 e 2 no mesmo
sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por
completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar
referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o
@@ -267,6 +282,27 @@ Existem dois tipos principais de links: URL visíveis \\
Esse pacote também produz uma lista de thumbnails no documento pdf gerado e
ativa os links na tabela de conteúdo.
+\section{Escrevendo em ASCII ou outras codificações}
+
+Por padrão, historicamente LaTeX aceita entradas que são puro ASCII (128),
+mas não ASCII extendido, o que significa sem acentos (à, è etc.) e símbolos não latinos.
+
+É fácil inserir acentos e símbolos latinos básicos através de atalhos de barra invertida
+como \,c, \'e, \`A, \ae e \oe etc. % Para ç, é, À, etc
+% Veja https://en.wikibooks.org/wiki/LaTeX/Special_Characters#Escaped_codes para mais detalhes
+
+Para escrever diretamente em UTF-8 quando compilando com pdflatex, use
+\begin{verbatim}
+ \usepackage[utf8]{inputenc}
+\end{verbatim}
+A fonte selecionada precisa suportar os glifos usados em seu documento. Você precisa adicionar
+\begin{verbatim}
+ \usepackage[T1]{fontenc}
+\end{verbatim}
+
+Desde LuaTeX e XeLaTeX, suporte para UTF-8 vem embutido por padrão, tornando a vida muito
+mais fácil para escrever em alfabetos não latinos.
+
\section{End}
Por enquanto é isso!
@@ -276,7 +312,7 @@ Por enquanto é isso!
\begin{thebibliography}{1}
% como em outras listas, o comando \bibitem pode ser usado para itens da lista
% cada entrada pode ser citada diretamente no corpo do texto
- \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em
+ \bibitem{latexwiki} The amazing \LaTeX{} wikibook: {\em
https://en.wikibooks.org/wiki/LaTeX}
\bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com}
\end{thebibliography}
@@ -289,3 +325,6 @@ https://en.wikibooks.org/wiki/LaTeX}
* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
+* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes)
+* An interactive platform to learn LaTeX (installationfree) [learnlatex.org/](https://www.learnlatex.org/)
+* Stack Exchange's question and answer site about TeX, LaTeX, ConTeXt, etc. [tex.stackexchange.com](https://tex.stackexchange.com/)
diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown
index 0c75da26..4aaf3a1e 100644
--- a/pt-br/lua-pt.html.markdown
+++ b/pt-br/lua-pt.html.markdown
@@ -2,7 +2,7 @@
language: Lua
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
-filename: learnlua.lua
+filename: learnlua-pt.lua
translators:
- ["Iaan Mesquita", "https://github.com/ianitow"]
lang: pt-br
diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown
index cbdebde7..40ac733a 100644
--- a/pt-br/make-pt.html.markdown
+++ b/pt-br/make-pt.html.markdown
@@ -4,7 +4,9 @@ tool: make
contributors:
- ["Robert Steed", "https://github.com/robochat"]
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
-filename: Makefile
+translators:
+ - ["Rogério Gomes Rio", "https://github.com/rogerlista"]
+filename: Makefile-pt
lang: pt-br
---
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown
index dc50cac1..fca864bb 100644
--- a/pt-br/markdown-pt.html.markdown
+++ b/pt-br/markdown-pt.html.markdown
@@ -6,36 +6,56 @@ translators:
- ["Miguel Araújo", "https://github.com/miguelarauj1o"]
- ["Gabriele Luz", "https://github.com/gabrieleluz"]
- ["Monique Baptista", "https://github.com/bfmonique"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
-lang: pt-br
+lang: pt-br
filename: learnmarkdown-pt.md
---
-Markdown foi criado por John Gruber in 2004. Originado para ser fácil de ler e
-escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos também).
-
-Dê-me feedback tanto quanto você quiser! / Sinta-se livre para fazer uma bifurcação (fork) e
-puxar o projeto (pull request)
+O Markdown foi lançado por John Gruber em 2004. Criado para ser uma sintaxe
+fácil de ler e escrever e que é facilmente convertida em HTML (hoje, suporta
+outros formatos também).
+
+O Markdown varia em termos de implementação de um parser para outro. Esse guia
+irá tentar deixar explícito quando os recursos são universais ou quando são
+específicos para um parser em específico.
+
+- [Elementos HTML](#elementos-html)
+- [Cabeçalhos](#cabeçalhos)
+- [Estilos de texto simples](#estilos-de-texto-simples)
+- [Parágrafos](#parágrafos)
+- [Listas](#listas)
+- [Blocos de código](#blocos-de-código)
+- [Linha Horizontal](#linha-horizontal)
+- [Links](#links)
+ - [Tabela de conteúdo](#tabela-de-conteúdo)
+- [Imagens](#imagens)
+- [Miscelânea](#miscelânea)
+ - [Auto-links](#auto-links)
+ - [Auto-links para e-mails](#auto-links-com-e-mails)
+ - [Escapando caracteres](#escapando-caracteres)
+ - [Teclas do teclado](#teclas-do-teclado)
+ - [Tabelas](#tabelas)
+- [Markdownlint](#markdownlint)
+- [Leitura complementar](#leitura-complementar)
## Elementos HTML
-Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é
+O Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é
um arquivo Markdown válido.
-```md
-<!-- Markdown é um superconjunto do HTML, de modo que qualquer arquivo HTML é
-um arquivo Markdown válido. Isso significa que nós podemos usar elementos HTML
-em Markdown, como o elemento de comentário, e eles não serão afetados pelo analisador
-de remarcação. No entanto, se você criar um elemento HTML em seu arquivo Markdown, você
-não pode usar sintaxe de remarcação dentro desse conteúdo do elemento.-->
-
-<!--A maneira como o Markdown é analisado varia de software para software.
-Este guia vai tentar esclarecer quando as características são universais, ou quando eles são específicos para um determinado interpretador -->
+```md
+<!--Isso significa que nós podemos usar elementos HTML em Markdown, como o
+elemento de comentário, e eles não serão afetados pelo analisador de
+remarcação. No entanto, se você criar um elemento HTML em seu arquivo Markdown,
+você não pode usar sintaxe de remarcação dentro do conteúdo desse elemento.-->
+```
## Cabeçalhos
Você pode criar elementos HTML `<h1>` até `<h6>` facilmente antecedendo o texto
-que deseja estar nesse elemento por um número de hashes (#)
+que deseja estar nesse elemento por um número de cerquilhas (#).
+```md
# Isto é um cabeçalho <h1>
## Isto é um cabeçalho <h2>
### Isto é um cabeçalho <h3>
@@ -44,7 +64,7 @@ que deseja estar nesse elemento por um número de hashes (#)
###### Isto é um cabeçalho <h6>
```
-Markdown também nos fornece duas maneiras alternativas de indicar h1 e h2
+Markdown também nos fornece duas maneiras alternativas de indicar h1 e h2.
```md
Isto é um cabeçalho h1
@@ -55,21 +75,22 @@ Isto é um cabeçalho h2
```
## Estilos de texto simples
-O texto pode ser facilmente denominado como marcação itálico, negrito ou tachado usando:
+
+O texto pode ser facilmente estilizado como itálico ou negrito usando Markdown.
```md
*Este texto está em itálico*
_E este também está._
**Este texto está em negrito**
-__E este também está._
+__E este também está.__
***Este texto está em negrito e itálico.***
**_E este também está_**
-*--Danouse! Este também__*
+*__Danou-se! Este também__*
```
-Em GitHub Flavored Markdown, que é usado para processar arquivos Markdown
+No GitHub Flavored Markdown, que é usado para processar arquivos Markdown
GitHub, nós também temos:
```md
@@ -77,43 +98,46 @@ GitHub, nós também temos:
```
## Parágrafos
-Os parágrafos estão uma ou várias linhas adjacentes de texto separadas por
+Os parágrafos estão em uma ou várias linhas adjacentes de texto separadas por
uma ou múltiplas linhas em branco.
```md
Este é um parágrafo. Eu estou digitando em um parágrafo, não é legal?
Agora, eu estou no parágrafo 2.
-... Ainda continuo no parágrafo 2! :)
+Ainda continuo no parágrafo 2!
+
-Eu estou no parágrafo três.
+Eu estou no parágrafo três!
```
Se você quiser inserir uma tag HTML `<br />`, você pode acabar com um parágrafo
-com dois ou mais espaços e, em seguida, começar um novo parágrafo
+com dois ou mais espaços e, em seguida, começar um novo parágrafo.
```md
-Termino com dois espaços (destacar-me para vê-los).
+Termino com dois espaços (selecione essa linha para vê-los).
Há um <br /> acima de mim!
```
-
-Bloco de citações são fáceis e feito com o caractere >.
+Blocos de citações são fáceis e feitos com o caractere >.
```md
> Este é um bloco de citação. Você pode
-> Quebrar manualmente suas linhas e colocar um `>` antes de cada linha ou você pode
-> deixar suas linhas ficarem muito longas e quebrarem por conta própria. Não faz diferença,
-> desde que eles começam com um `>`.
-
+> Quebrar manualmente suas linhas e colocar um `>` antes de cada linha ou você
+> pode deixar suas linhas ficarem muito longas e quebrarem por conta própria.
+> Não faz diferença, desde que elas comecem com um `>`.
> Você também pode usar mais de um nível
>> De recuo?
+> O quão legal é isso?
+
```
## Listas
-As listas não ordenadas podem ser feitas usando asteriscos, positivos ou hífens
+
+As listas não ordenadas podem ser feitas usando asteriscos, sinais de positivo
+ou hífens.
```md
* Item
@@ -141,18 +165,18 @@ Listas ordenadas são feitas com um número seguido por um ponto.
3. Item três
```
-<!-- Você não tem poder para rotular os itens corretamente e a remarcação ainda deixará os
-itens em ordem, mas isso pode não ser uma boa idéia -->
-
+Você não precisa sequer rotular os itens corretamente e o Markdown ainda
+assim deixará os itens em ordem, mas isso pode não ser uma boa idéia.
```md
1. Item um
1. Item dois
1. Item três
```
+
(Isto é processado da mesma forma que o exemplo acima)
-Você também pode usar sublistas
+Você também pode usar sublistas.
```md
1. Item um
@@ -163,63 +187,59 @@ Você também pode usar sublistas
4. Item quatro
```
-Existem também listas de tarefas. Isso cria checkboxes (caixas de seleção) de HTML
+Existem também listas de tarefas. Isso cria checkboxes (caixas de seleção) do
+HTML.
```md
-As caixas abaixo sem o 'x' são checkboxes HTML desmarcadas
-- [ ] Primeira tarefa a completar
+As caixas abaixo sem o 'x' são checkboxes HTML desmarcadas.
+- [ ] Primeira tarefa a completar.
- [ ] Segunda tarefa a completar
-A caixa de seleção abaixo será exibida como uma checkbox HTML marcada
+A caixa de seleção abaixo será exibida como uma checkbox HTML marcada.
- [x] Essa tarefa foi completa
-
```
-
## Blocos de código
-Você pode indicar um bloco de código (que utiliza o elemento `<code>`) pelo recuo
-uma linha com quatro espaços ou uma guia
-```md
- Isto é código
- É assim, sacou?
-
-```
-Você pode também re-guia (ou adicionar mais quatro espaços adicionais) para o recuo
-dentro do seu código
+Você pode indicar um bloco de código (que utiliza o elemento `<code>`) através
+de indentação com quatro espaços ou uma tabulação.
```md
- my_array.each do |item|
- puts item
- end
- ```
+ Isto é código
+ É assim, sacou?
+```
-Código embutido pode ser criada usando o caractere de crase `` ` ``
+Você pode também adicionar mais tabulações (ou adicionar mais quatro espaços
+adicionais) para indentação no seu código.
```md
-John não sabia nem o que o função `goto()` fazia!
+ my_array.each do |item|
+ puts item
+ end
```
-Em GitHub Flavored Markdown, você pode usar uma sintaxe especial para o código
+Código embutido pode ser criado usando o caractere de crase `` ` ``.
+
```md
- ``` ruby
- def foobar
- puts "Hello world!"
- end
- ```
+John não sabia nem o que a função `go_to()` fazia!
```
-=======
-\`\`\`ruby <!-- exceto remover essas barras invertidas quando você faz isso, apenas ```
-ruby! -->
+
+No GitHub Flavored Markdown, você pode usar uma sintaxe especial para código.
+
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Olá mundo!"
end
-\`\`\` <!-- Aqui também, não use barras invertidas, apenas ``` -->
+```
+````
-O texto acima não requer recuo, além disso o GitHub vai usar a sintaxe highlight da linguagem que você especificar após a \`\`\`.
+O texto acima não requer indentação, além disso o GitHub vai usar o destaque
+de sintaxe da linguagem qeu você especificar após a tag <code>```</code>.
## Linha Horizontal
-Linhas horizontais são facilmente adicionados com três ou mais asteriscos ou hífens,
-com ou sem espaços.
+
+Linhas horizontais são facilmente adicionadas com três ou mais asteriscos ou
+hífens, com ou sem espaços.
```md
***
@@ -229,17 +249,19 @@ com ou sem espaços.
```
## Links
-Uma das melhores coisas sobre a marcação é o quão fácil é fazer ligações. Colocar
-o texto a ser exibido entre parênteses rígidos [] seguido pela url em parênteses ()
+
+Uma das melhores coisas sobre o Mardkwon é o quão fácil é criar links.
+Coloque o texto a ser exibido entre colchetes [] seguido pela url entre
+parênteses ()
```md
-[Click aqui!](http://test.com/)
+[Clique aqui!](http://test.com/)
```
-Você também pode adicionar um título link usando aspas dentro dos parênteses
+Você também pode adicionar um título ao link usando aspas dentro dos parênteses.
```md
-[Click aqui!](http://test.com/ "Link para Test.com")
+[Cliqueaqui!](http://test.com/ "Link para Test.com")
```
Caminhos relativos funcionam também.
@@ -248,46 +270,69 @@ Caminhos relativos funcionam também.
[Ir para música](/música/).
```
-Markdown também suporta ligações de estilo de referência
+O Markdown também suporta links para referências no texto.
```md
-[Clique neste link] [link1] para mais informações sobre isso!
-[Além disso, verifique este link] [foobar] se você quiser.
+[Clique nesse link][link1] para mais informações!
+[Também cheque esse link][foobar] se você quiser.
[link1]: http://test.com/ "Legal!"
-[foobar]: http://foobar.biz/ "OK!"
+[link2r]: http://foobar.biz/ "Certo!"
```
O título também pode estar entre aspas simples ou entre parênteses, ou omitido
-inteiramente. As referências podem estar em qualquer lugar no documento e os IDs de referência
-pode ser qualquer um, desde que eles são únicos.
+inteiramente. As referências podem estar em qualquer lugar no documento e os
+IDs de referência podem ser qualquer um, desde que eles sejam únicos.
-Existe também a "nomeação implicita", que permite que você use o texto do link como o id
+Existe também a "nomeação implícita", que permite que você use o texto do link
+como o id:
```md
-[Este] [] é um link.
+[Isso][] é um link.
-[este]: http://thisisalink.com/
+[Isso]: http://thisisalink.com/
```
-Mas não são usados normalmente
+Mas geralmente não são usados.
+
+### Tabela de conteúdo
+
+Alguns sabores de Markdown fazem inclusive uso de combinação de listas, links e
+cabeçalhos de modo a criar uma tabela de conteúdo. Nesse caso, títulos em
+cabeçalhos são precedidos de (`#`) e são usados como ids para links. Se o
+cabeçalho consistir de várias palavras, elas serão conectadas por hífens (`-`),
+que também substitui alguns caracteres especiais. (Embora alguns outros
+carácteres especiais sejam omitidos.)
+
+```md
+- [Cabeçalho](#cabecalho)
+- [Um outro cabeçalho](#outro-cabecalho)
+- [Capítulo](#capitulo)
+ - [Subcapítulo <h3 />](#subcapitulo-h3-)
+```
+
+De qualquer modo, esse é um recurso que talvez não funcione em todas as
+implementações do Markdown da mesma forma.
## Imagens
-As imagens são feitas da mesma forma que as ligações, mas com um ponto de exclamação na frente!
+
+As imagens são feitas da mesma forma que os links, mas com um ponto de
+exclamação na frente!
```md
-![Este é pairar-texto (texto alternativo) para minha imagem](http://imgur.com/myimage.jpg "Um título opcional")
+![Este é alt-text (texto alternativo) para minha imagem](http://imgur.com/myimage.jpg "Um título opcional")
```
E estilo de referência funciona como esperado
```md
-![Este é o pairar-texto.][Myimage]
+![Esse é o alt-attribute.][myimage]
-[myimage]: relative/urls/legal/image.jpg "se você precisa de um título, é aqui"
+[Minha imagem]: relative/urls/cool/image.jpg "se precisar de um título, está aqui"
```
## Miscelânea
+
### Auto-links
```md
@@ -303,14 +348,25 @@ E estilo de referência funciona como esperado
### Escapando caracteres
-Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja
+Quero digitar *Este texto entre asteriscos*, mas eu não quero que ele seja
em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*.
+### Teclas do teclado
+
+No GitHub Flavored Markdown, você pode usar a tag `<kbd>` para representar uma
+tecla do teclado.
+
+```md
+Seu computador travou? Tente apertar
+<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+
### Tabelas
+
Tabelas estão disponíveis apenas no GitHub Flavored Markdown e são ligeiramente
complicadas, mas se você realmente quer:
-```md
+```md
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| esquerda-alin| Centrado | direita-alinh |
@@ -325,8 +381,22 @@ Col 1 | Col2 | Col3
Ugh isso é tão feio | faça isto | parar
```
-Fim!
+## Markdownlint
+
+De modo a simplificar o trabalho com Markdown e padronizar estilo de código, o
+`Markdownlint` foi criado. Essa ferramenta está disponível como plugin para
+algumas interfaces de desenvolvimento (IDEs) e pode ser utilizada como um
+utilitário para garantir validade e legibilidade do Markdown.
---
-Para mais informações, confira o post oficial de John Gruber de sintaxe [aqui](http://daringfireball.net/projects/markdown/syntax)
-e de Adam Pritchard grande cheatsheet [aqui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
+
+## Leitura complementar
+
+Para mais informações, confira o post oficial de John Gruber sobre sintaxe [aqui](http://daringfireball.net/projects/markdown/syntax)
+e o do cheatsheet do Adam Pritchard [aqui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
+
+Se você quiser aprender mais sobre recursos de alguns sabores específicos de
+Markdown, veja:
+
+- [GitHub flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)
+- [GitLab flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html)
diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown
index fae17bca..947e0699 100644
--- a/pt-br/matlab-pt.html.markdown
+++ b/pt-br/matlab-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: Matlab
+language: MATLAB
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
@@ -120,7 +120,7 @@ A.d.e = false;
% Vetores
x = [4 32 53 7 1]
-x(2) % Resposta = 32, índices no Matlab começam por 1, não 0
+x(2) % Resposta = 32, índices no MATLAB começam por 1, não 0
x(2:3) % Resposta = 32 53
x(2:end) % Resposta = 32 53 7 1
@@ -479,7 +479,7 @@ perms(x) % Lista todas as permutações de elementos de x
% Classes
-% Matlab pode suportar programação orientada a objetos.
+% MATLAB pode suportar programação orientada a objetos.
% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m
% Para começar, criamos uma simples classe que armazena posições de GPS
% Início ClassePosicoesGPS.m
@@ -501,7 +501,7 @@ classdef ClassePosicoesGPS % O nome da classe.
end
% Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar
- % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira:
+ % uma função especial nós podemos sobrepor a aritmética do MATLAB, desta maneira:
function r = plus(o1,o2)
r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]);
@@ -513,7 +513,7 @@ end
% Podemos criar um objeto da classe usando o construtor
a = ClassePosicoesGPS(45.0, 45.0)
-% Propriedades da classe se comportam exatamente como estruturas Matlab
+% Propriedades da classe se comportam exatamente como estruturas MATLAB
a.latitude = 70.0
a.longitude = 25.0
@@ -524,15 +524,15 @@ ans = multiplicarLatPor(a,3)
% o objeto não precisa ser passado para o método.
ans = a.multiplicarLatPor(a,1/3)
-% Funções do Matlab podem ser sobrepostas para lidar com objetos.
-% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de
+% Funções do MATLAB podem ser sobrepostas para lidar com objetos.
+% No método abaixo, nós sobrepomos a forma como o MATLAB lida com a soma de
% dois objetos PosicoesGPS.
b = ClassePosicoesGPS(15.0, 32.0)
c = a + b
```
-## Mais sobre Matlab
+## Mais sobre MATLAB
* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown
index e55f1100..7db6a671 100644
--- a/pt-br/php-pt.html.markdown
+++ b/pt-br/php-pt.html.markdown
@@ -7,7 +7,7 @@ translators:
- ["Abdala Cerqueira", "http://abda.la"]
- ["Raquel Diniz", "http://twitter.com/raquelrdiniz"]
lang: pt-br
-filename: php-pt.html.markdown
+filename: learnphp-pt.php
---
Este documento descreve PHP 5+.
diff --git a/pt-br/processing-pt.html.markdown b/pt-br/processing-pt.html.markdown
new file mode 100644
index 00000000..5ed2950a
--- /dev/null
+++ b/pt-br/processing-pt.html.markdown
@@ -0,0 +1,480 @@
+---
+language: processing
+filename: learnprocessing.pde
+contributors:
+ - ["Phone Thant Ko", "http://github.com/phonethantko"]
+ - ["Divay Prakash", "https://github.com/divayprakash"]
+translators:
+ - ["Kemel Zaidan", "https://github.com/kemelzaidan"]
+lang: pt-br
+---
+
+## Introdução
+
+Processing é uma linguagem de programação para criação de artes digitais e
+conteúdo multimídia, permitindo que não programadores aprendam os fundamentos
+da programação computacional em um contexto visual.
+
+Embora a linguagem seja baseada na linguagem Java, sua sintaxe foi amplamente
+influenciado por ambas as sintaxes Java e Javascript.
+[Veja mais aqui](https://processing.org/reference/)
+
+A linguagem é tipada estaticamente e também vem com o seu Ambiente de Desenvolvimento
+Integrado (do inglês Integrated Development Environment - IDE) oficial para
+compilar e executar os scripts.
+
+```
+/* ---------
+ Comentários
+ ---------
+*/
+
+// Comentário de linha única começa com //
+
+/*
+ Como o Processing é baseado em Java,
+ a sintaxe para seus comentários é a mesma do Java (como você deve ter notado
+ acima)!
+ Comentários de várias linhas são agrupados como visto aqui.
+*/
+
+/* ---------------------------------------
+ Escrevendo e executando programas em Processing
+ ---------------------------------------
+*/
+
+// No Processing, o ponto de entrada do programa é uma função chamada setup()
+// com um tipo de retorno void.
+// Observação! A sintaxe é muito semelhante à do C++.
+void setup() {
+ // Isso imprime a saída clássica "Hello World!" no console quando executado.
+ println("Olá Mundo!"); // Mais uma linguagem com esse maldito ponto e vírgula, não é?
+}
+
+// Normalmente, colocamos todos os códigos estáticos dentro do método setup()
+// como o próprio nome sugere, uma vez que é executado apenas uma vez.
+// Pode variar da definição das cores de fundo, ou o tamanho da tela.
+background(color); //define a cor do fundo
+size(largura,altura,[renderizador]); // define o tamanho da tela com parâmetro
+// opcional para definir o renderizador
+// Você verá mais sobre isso ao longo deste documento.
+
+// Se você deseja executar os códigos indefinidamente, eles devem ser colocados
+// dentro do método draw()
+// draw() deve existir caso você queira que o código seja executado
+// continuamente e, obviamente, só pode haver um método draw().
+int = 0;
+void draw(){
+ // Este bloco de código faz um loop para sempre até parar
+ imprima(i);
+ i++; // Operador de incremento!
+}
+
+// Agora que sabemos como escrever o script de trabalho e como executá-lo,
+// continuaremos a explorar quais tipos de dados e coleções são suportados no
+// Processing.
+
+/* ------------------------
+ Tipos de dados e coleções
+ ------------------------
+*/
+
+// De acordo com as Referências do Processing, ele suporta 8 tipos primitivos
+// de dados da seguinte forma.
+
+boolean valorBoleano = true; // Boleano
+byte valorByteDeA = 23; // Byte
+char valorCharDeA = 'A'; // Caractere
+color valorDeCorBrancoM = color(255, 255, 255); // Cor (especificada usando
+// método color())
+color valorDeCorBrancoH = #FFFFFF; // Cor (especificada usando valor de hash)
+int valor = 5; // Inteiro (Número sem decimais)
+long valorLongo = 2147483648L; // "L" é adicionado ao número para marcá-lo como um longo
+float valorFloat = 1,12345; // Float (números de ponto flutuante de 32 bits)
+double valorDouble = 1,12345D; // Double (números de ponto flutuante de 64 bits)
+
+// NOTA!
+// Embora os tipos de dados "long" e "double" funcionem na linguagem,
+// funções do Processing não usam esses tipos de dados, portanto
+// eles precisam ser convertidos em tipos de dados "int" e "float",
+// respectivamente, usando a sintaxe (int) e (float) antes de passar para uma
+// função.
+
+// Existem vários tipos de dados compostos que estão disponíveis por padrão para
+// uso no Processing.
+// Primeiramente, farei um resumo dos mais usados ​​para economizar tempo.
+
+// String
+// Enquanto o tipo de dados char usa '', o tipo de dados String usa "" - aspas
+// duplas.
+string stringExemplo = "Olá, Processing!";
+// String também pode ser criada a partir de um array de tipos de dados char.
+// Nós vamos discutir array muito em breve.
+char fonte = {'H', 'E', 'L', 'L', 'O'};
+String stringDeFonte = new String(source); // HELLO
+// Como em Java, strings podem ser concatenadas usando o operador "+".
+print("Olá " + "Mundo!"); // Olá Mundo!
+
+// Array
+// Arrays em Processing podem conter quaisquer tipos de dados, incluindo os
+// próprios objetos. Como os arrays são semelhantes aos objetos, eles devem
+// ser criados com a palavra-chave "new".
+int[] arrayInt = new int[5];
+int[] arrayIntComValores ​​= {1, 2, 3}; // Você também pode preencher com dados.
+
+// Lista de Arrays
+// As funções são semelhantes às do array; arraylists podem conter qualquer
+// tipo de dados. A única diferença é que as listas de matrizes são
+// redimensionadas dinamicamente, pois é uma forma de implementação de matriz
+// redimensionável da interface "List" do Java .
+ArrayList<Integer> intArrayList = new ArrayList<Integer>();
+
+// Objeto
+// Como é baseado em Java, o Processing suporta programação orientada a objetos.
+// Isso significa que você pode basicamente definir quaisquer tipos de dados de
+// sua preferência e manipulá-los para suas necessidades.
+// Claro, uma classe tem que ser definida antes para o objeto que você quer.
+// Formato --> NomeClasse NameInstancia
+UmaClasseQualquer meuObjeto // então instancia mais tarde
+//ou
+UmaClasseQualquer meuObjetoInstanciado = new UmaClasseQualquer();
+
+// O Processing surge com mais coleções (ex. - Dicionários e Listas) por
+// padrão, por uma questão de simplicidade, vou deixá-los fora da discussão aqui.
+
+/* ------------
+ Matemática
+ ------------
+*/
+
+// Aritmética
+1 + 1 // 2
+2 - 1 // 1
+2 * 3 // 6
+3/2 // 1
+3.0 / 2 // 1.5
+3.0% 2 // 1.0
+
+// O Processing também vem com um conjunto de funções que simplificam operações
+// matemáticas.
+float f = sq(3); // f = 9.0
+float p = pow(3, 3); // p = 27.0
+int a = abs(-13); // a = 13
+int r1 = round(3.1); // r1 = 3
+int r2 = round(3.7); // r2 = 4
+float sr = sqrt(25); // sr = 5.0
+
+// Vetores
+// O Processing fornece uma maneira fácil de implementar vetores em seu ambiente
+// usando a classe PVector. Ela pode descrever um vetor bi ou tridimensional e
+// vem com um conjunto de métodos que são úteis para operações com matrizes.
+// Você pode encontrar mais informações sobre a classe PVector e suas funções
+// aqui. (https://processing.org/reference/PVector.html)
+
+// Trigonometria
+// O Processing também suporta operações trigonométricas fornecendo um
+// conjunto de funções. sin(), cos(), tan(), asin(), acos(), atan() e também
+// degrees() e radians() para conversão conveniente.
+// No entanto, essas funções usam o ângulo em radianos como parâmetro, então é
+// necessário converter previamente.
+float um = sin(PI/2); // um = 1.0
+// Como você deve ter notado, existe um conjunto de constantes para usos
+// trigonométricos; PI, HALF_PI, QUARTER_PI e assim por diante...
+
+/* -------------
+ Controle de fluxo
+ -------------
+*/
+
+// Declarações Condicionais
+// Instruções If - A mesma sintaxe das instruções if em Java.
+if (author.getAppearance().equals("quente")) {
+ print("Narcisismo no máximo!");
+} else {
+ // Você pode verificar outras condições aqui.
+ print("Algo está realmente errado aqui!");
+}
+// Um ​​atalho para instruções if-else também pode ser usado.
+int = 3;
+String valor = (i > 5) ? "Grande" : "Pequena"; // "Pequena"
+
+// A estrutura switch-case pode ser usada para verificar várias condições de
+// forma concisa. É importante usar a instrução break. Se a instrução `break`
+// não existe o programa executa todos os casos a seguir após um caso ser
+// verdadeiro.
+int valor = 2;
+switch(valor) {
+ case 0:
+ print("Nada!"); // Isso não é executado.
+ break; // Salta para a próxima instrução
+ case 1:
+ print("Chegando lá..."); // Isso novamente não é executado.
+ break;
+ case 2:
+ print("Bravo!"); // Esta linha é executada.
+ break;
+ default:
+ print("Não encontrado!"); // Esta linha é executada se nosso valor for algum outro valor.
+ break;
+}
+
+// Declarações iterativas
+// Declarações For - Novamente, a mesma sintaxe que em Java
+for(int i = 0; i < 5; i++){
+ print(i); // imprime de 0 a 4
+}
+
+// Declarações While - Novamente, nada de novo se você estiver familiarizado com
+// a sintaxe Java.
+int j = 3;
+while(j > 0) {
+ print(j);
+ j--; // Isso é importante para evitar que o código seja executado indefinidamente.
+}
+
+// loop()| noLoop() | redraw() | exit()
+// Estas são mais funções específicas do Processing para configurar o fluxo do
+// programa.
+loop(); // permite que o método draw() seja executado para sempre enquanto
+noLoop(); // só permite que ele seja executado uma vez.
+redraw(); // executa o método draw() mais uma vez.
+exit(); // Isso para o programa. É útil para programas com draw()
+// rodando continuamente.
+```
+
+## Desenho com Processing
+
+Como você já deve ter entendido o básico da linguagem, vamos agora
+ver a melhor parte do Processing - DESENHAR.
+
+```
+/* ------
+ Formas
+ ------
+*/
+
+// Formas 2D
+
+// Ponto
+point(x, y); // No espaço 2D
+point(x, y, z); // No espaço 3D
+// Desenha um ponto no espaço de coordenadas.
+
+// Linha
+line(x1, y1, x2, y2); // No espaço 2D
+line(x1, y1, z1, x2, y2, z2); // No espaço 3D
+// Desenha uma linha conectando dois pontos definidos por (x1, y1) e (x2, y2).
+
+// Triângulo
+triangle(x1, y1, x2, y2, x3, y3);
+// Desenha um triângulo conectando três pontos definidos por parâmetros de coordenadas.
+
+// Retângulo
+rect(a, b, c, d, [r]); // Com parâmetro opcional definindo o raio de todos os cantos
+rect(a, b, c, d, [te, td, bd, be]); // Com conjunto opcional de parâmetros definindo
+// raio de cada canto
+// Desenha um retângulo com {a, b} como coordenada superior esquerda e c e d como largura
+// e altura respectivamente.
+
+// Quad
+quad(x, y, x2, y2, x3, y3, x4, y4);
+// Desenha um quadrilátero com parâmetros que definem as coordenadas de cada canto
+// ponto.
+
+// Elipse
+ellipse(x, y, largura, altura);
+// Desenha um eclipse no ponto {x, y} com largura e altura especificadas.
+
+// Arco
+arc(x, y, largura, altura, inicio, fim, [modo]);
+// Enquanto os primeiros quatro parâmetros são autoexplicativos,
+// início e fim definem os ângulos que o arco começa e termina (em radianos).
+// O parâmetro opcional [mode] define o preenchimento;
+// PIE dá o contorno de torta, CHORD dá o contorno reto e OPEN é como
+// CHORD porém sem contorno
+
+// Curvas
+// O Processing fornece duas implementações de curvas; usando curve() e
+// bezier(). Como pretendo manter isso simples, não vou discutir mais detalhes.
+// No entanto, se você quiser implementá-lo em seu sketch, aqui estão as
+// referências: (https://processing.org/reference/curve_.html)
+// (https://processing.org/reference/bezier_.html)
+
+// Formas 3D
+
+// espaço 3D
+pode ser configurado definindo "P3D" para o parâmetro do renderizador no
+// método size().
+size(largura, altura, P3D);
+// No espaço 3D, você terá que traduzir para a coordenada específica para
+// renderiza as formas 3D.
+
+// Caixa
+box(tamanho); // Cubo com o mesmo comprimento definido pelo tamanho
+box(w, h, d); // Caixa com largura, altura e profundidade definidas separadamente
+
+// Esfera
+sphere(raio); // Seu tamanho é definido usando o parâmetro raio
+// O mecanismo por trás da renderização das esferas é implementado por
+// triângulos em mosaico. Dito isso, o nível de detalhe sendo renderizado é
+// controlado pela função sphereDetail(res)
+// Mais informações aqui: (https://processing.org/reference/sphereDetail_.html)
+
+// Formas irregulares
+// E se você quiser desenhar algo que não foi disponibilizado pelo Processing
+// funções?
+// Você pode usar beginShape(), endShape(), vertex(x,y) para definir formas por
+// especificando cada ponto. Mais informações aqui:
+// (https://processing.org/reference/beginShape_.html)
+// Você também pode usar formas personalizadas usando a classe PShape:
+// (https://processing.org/reference/PShape.html)
+
+/* ---------------
+ Transformações
+ ---------------
+*/
+
+// As transformações são particularmente úteis para acompanhar o espaço de
+// coordenadas e os vértices das formas que você desenhou. Particularmente;
+// métodos de pilha de matrizes; pushMatrix(), popMatrix() e translate(x,y)
+pushMatriz(); // Salva o sistema de coordenadas atual na pilha
+// ... aplique todas as transformações aqui ...
+popMatriz(); // Restaura o sistema de coordenadas salvo
+// Usando-os, o sistema de coordenadas pode ser preservado e visualizado sem
+// causar qualquer conflito.
+
+// Traduzir
+translate(x,y); // Traduz para o ponto{x, y} ou seja - configurando a origem para esse ponto
+translate(x, y, z); // Contraparte 3D da função
+
+// Rotacionar
+rotate(ângulo); // Gira a quantidade especificada pelo parâmetro ângulo
+// Possui 3 contrapartes 3D para realizar a rotação, uma para cada dimensão:
+// rotateX(ângulo), rotateY(ângulo), rotateZ(ângulo)
+
+// Escala
+scale(s); // Dimensiona o sistema de coordenadas expandindo ou contraindo-o.
+
+/* --------------------
+ Estilo e texturas
+ --------------------
+*/
+
+// Cores
+// Como discuti anteriormente, a cor de fundo pode ser configurada usando a
+// função background(). Você pode definir a cor de um objeto de antemão e depois
+// passar para a função como um argumento.
+color c = cor(255, 255, 255); // BRANCO!
+// Por padrão, o Processing usa o esquema de cores RGB, mas pode ser configurado
+// para HSB usando colorMode(). Leia mais aqui:
+// (https://processing.org/reference/colorMode_.html)
+background(c); // Até agora, a cor de fundo deve ser branca.
+// Você pode usar a função fill() para selecionar a cor para preencher as formas.
+// Tem que ser configurado antes de você começar a desenhar formas para que as
+// cores fiquem aplicadas.
+fill(color(0, 0, 0));
+// Se você quiser apenas colorir os contornos das formas, você pode usar
+// função stroke().
+stroke(255, 255, 0, 200); // cor do traço definida para amarelo com transparência
+// definido para um valor menor.
+
+// Imagens
+// O Processing pode renderizar imagens e usá-las de várias maneiras.
+// Principalmente armazenado como Tipo de dados PImage.
+filter(sombreador); // O Processing suporta várias funções de filtro para manipulação de imagens.
+texture(imagem); // PImage pode ser passado em argumentos para mapeamento de textura das formas.
+```
+
+Se você quiser levar as coisas adiante, há mais coisas que o Processing tem o poder de fazer. Renderizar modelos, shaders e outros efeitos. Há muito para se cobrir em uma
+documentação curta, então vou deixá-los aqui. Se você se interessar, por favor verifique as referências.
+
+```
+// Antes de prosseguirmos, vou falar um pouco mais sobre como importar bibliotecas
+// para que você possa estender a funcionalidade do Processing para outros horizontes.
+
+/* -------
+ Importações
+ -------
+*/
+
+// As possibilidades do Processing pode ser estendidas ainda mais quando
+// importamos bibliotecas e pacotes em nossos esboços.
+// A instrução de importação pode ser escrita como abaixo na parte superior
+// do código-fonte.
+import processing.algumacoisa.*;
+```
+
+## VAC?
+
+Vamos ao código? Vamos sujar as mãos!
+
+Vamos ver um exemplo do openprocessing para visualizar o quanto o Processing é
+capaz de fazer com poucas linhas de código.
+
+Copie o código abaixo em seu IDE do Processing e veja a mágica.
+
+```
+// Isenção de responsabilidade: eu não escrevi este programa porque atualmente
+// estou ocupado com meu estágio e este sketch é adaptado do openprocessing pois
+// mostra algo legal com um código simples.
+// Recuperado de: (https://www.openprocessing.org/sketch/559769)
+
+float theta;
+float a;
+float col;
+float num;
+
+void setup() {
+ size(600,600);
+}
+
+void draw() {
+ background(#F2F2F2);
+ translate(width/2, height/2);
+ theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6);
+
+ float num=6;
+ for (int i=0; i<num; i++) {
+ a =350;
+ rotate(TWO_PI/num);
+ branch(a);
+ }
+
+}
+
+void branch(float len) {
+ col=map(len, 0, 90, 150, 255);
+ fill(col, 0, 74);
+ stroke (col, 0, 74);
+ line(0, 0, 0, -len);
+ ellipse(0, -len, 3, 3);
+ len *= 0.7;
+
+ if (len>30) {
+ pushMatrix();
+ translate(0, -30);
+ rotate(theta);
+ branch(len);
+ popMatrix();
+
+ pushMatrix();
+ translate(0, -30);
+ rotate(-theta);
+ branch(len);
+ popMatrix();
+
+ }
+}
+```
+
+A linguagem Processing é fácil de aprender e é particularmente útil para criar
+conteúdo (mesmo em 3D) sem ter que digitar muitos códigos. É tão simples
+que você pode ler o código e ter uma ideia aproximada do fluxo do programa.
+
+No entanto, isso não se aplica quando você introduz bibliotecas externas, pacotes
+e até mesmo suas próprias aulas. (Confie em mim! Projetos em processing podem ficar realmente monstruosos...)
+
+## Alguns recursos úteis
+
+ - [Site do Processing](http://processing.org)
+ - [Sketches em Processing](http://openprocessing.org)
diff --git a/pt-br/pug-pt.html.markdown b/pt-br/pug-pt.html.markdown
new file mode 100644
index 00000000..a74666fb
--- /dev/null
+++ b/pt-br/pug-pt.html.markdown
@@ -0,0 +1,211 @@
+---
+language: Pug
+contributors:
+ - ["Michael Warner", "https://github.com/MichaelJGW"]
+filename: index-pt.pug
+translators:
+ - ["Adaías Magdiel", "https://adaiasmagdiel.com/"]
+lang: pt-br
+---
+
+## Começando com Pug
+
+Pug é uma pequena linguagem que compila para HTML. Possui uma sintaxe limpa
+com algumas funcionalidades adicionais, como declarações if e loops. Também pode ser utilizada
+como uma linguagem de templates no lado do servidor para tecnologias como o Node.js.
+
+### The Language
+```pug
+
+//- Comentário de uma linha
+
+//- Comentário de
+ várias linhas
+
+//- ---TAGS---
+//- Básico
+div
+//- <div></div>
+h1
+//- <h1></h1>
+minha-propriaTag
+//- <minha-propriaTag></minha-propriaTag>
+
+//- Tags irmãs
+div
+div
+//- <div></div>
+ <div></div>
+
+//- Tags aninhadas
+div
+ div
+//- <div>
+ <div></div>
+ </div>
+
+//- Textos
+h1 Olá, pessoas
+//- <h1>Olá, pessoas</h1>
+
+//- Texto de várias linhas
+div.
+ Oi,
+ tudo bem?
+//- <div>
+ Oi,
+ tudo bem?
+ </div>
+
+//- ---ATRIBUTOS---
+div(class="minha-class" id="meu-id" meu-proprio-atributo="data" enabled)
+//- <div class="minha-class" id="meu-id" meu-proprio-atributo="data" enabled></div>
+
+//- Abreviações
+span.minha-class
+//- <span class="minha-class"></span>
+.minha-class
+//- <div class="minha-class"></div>
+div#meu-id
+//- <div id="meu-id"></div>
+div#meu-id.minha-class
+//- <div class="minha-class" id="meu-id"></div>
+
+
+//- ---JAVASCRIPT---
+- const lang = "pug";
+
+//- Javascript em várias linhas
+-
+ const lang = "pug";
+ const awesome = true;
+
+//- Classes com Javascript
+- const myClass = ['class1', 'class2', 'class3']
+div(class=myClass)
+//- <div class="class1 class2 class3"></div>
+
+//- Estilos com Javascript
+- const myStyles = {'color':'white', 'background-color':'blue'}
+div(styles=myStyles)
+//- <div styles="{&quot;color&quot;:&quot;white&quot;,&quot;background-color&quot;:&quot;blue&quot;}"></div>
+
+//- Atributos com Javascript
+- const myAttributes = {"src": "photo.png", "alt": "My Photo"}
+img&attributes(myAttributes)
+//- <img src="photo.png" alt="My Photo">
+- let disabled = false
+input(type="text" disabled=disabled)
+//- <input type="text">
+- disabled = true
+input(type="text" disabled=disabled)
+//- <input type="text" disabled>
+
+//- Templates com Javascript
+- const name = "Bob";
+h1 Olá, #{name}
+h1= name
+//- <h1>Olá, Bob</h1>
+//- <h1>Bob</h1>
+
+//- ---LOOPS---
+
+//- 'each' e 'for' tem a mesma função, aqui nós usaremos apenas 'each'.
+
+each value, i in [1,2,3]
+ p=value
+//-
+ <p>1</p>
+ <p>2</p>
+ <p>3</p>
+
+each value, index in [1,2,3]
+ p=value + '-' + index
+//-
+ <p>1-0</p>
+ <p>2-1</p>
+ <p>3-2</p>
+
+each value in []
+ p=value
+//-
+
+each value in []
+ p=value
+else
+ p Sem valores
+
+//- <p>Sem valores</p>
+
+//- ---CONDICIONAIS---
+
+- const number = 5
+if number < 5
+ p o número é menor do que 5
+else if number > 5
+ p o número é maior do que 5
+else
+ p o número é 5
+//- <p>o número é 5</p>
+
+- const orderStatus = "Aguardando";
+case orderStatus
+ when "Aguardando"
+ p.warn Seu pedido está em espera
+ when "Completado"
+ p.success Seu pedido foi completado.
+ when -1
+ p.error Ocorreu algum erro
+ default
+ p Nenhum registro de pedido encontrado
+//- <p class="warn">Seu pedido está em espera</p>
+
+//- --INCLUINDO CONTEÚDOS--
+//- Caminho do arquivo -> "includes/nav.pug"
+h1 Indústrias ACME
+nav
+ a(href="index.html") Início
+ a(href="about.html") Sobre Nós
+
+//- Caminho do arquivo -> "index.pug"
+html
+ body
+ include includes/nav.pug
+//-
+ <html>
+ <body>
+ <h1>Indústrias ACME</h1>
+ <nav><a href="index.html">Início</a><a href="about.html">Sobre Nós</a></nav>
+ </body>
+ </html>
+
+//- Importando Javascript e CSS
+script
+ include scripts/index.js
+style
+ include styles/theme.css
+
+//- ---MIXIN---
+mixin basic
+ div Olá
++basic
+//- <div>Olá</div>
+
+mixin comment(nome, comentario)
+ div
+ span.comment-name= nome
+ div.comment-text= comentario
++comment("Gil", "Tudo é divino, tudo é maravilhoso")
+//-
+ <div>
+ <span class="comment-name">Gil</span>
+ <div class="comment-text">Tudo é divino, tudo é maravilhoso</div>
+ </div>
+
+```
+
+
+### Saiba Mais
+- [Site Oficial](https://pugjs.org/)
+- [Documentação](https://pugjs.org/api/getting-started.html)
+- [Repositório no Github](https://github.com/pugjs/pug)
diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown
index 40fe82d5..42f744e2 100644
--- a/pt-br/pyqt-pt.html.markdown
+++ b/pt-br/pyqt-pt.html.markdown
@@ -24,7 +24,7 @@ o pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# Cria um objeto para a aplicação
app = QtGui.QApplication(sys.argv)
@@ -54,7 +54,7 @@ outros elementos.
Aqui mostraremos como criar uma janela popup, muito útil para perguntar ao
usuário qual decisão tomar ou exibir alguma informação.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -73,7 +73,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# Essa função deve criar uma janela de diálogo com um botão,
# aguarda ser clicado e encerra o programa
def showdialog():
diff --git a/pt-br/pythonstatcomp-pt.html.markdown b/pt-br/pythonstatcomp-pt.html.markdown
new file mode 100644
index 00000000..aa532eb4
--- /dev/null
+++ b/pt-br/pythonstatcomp-pt.html.markdown
@@ -0,0 +1,249 @@
+---
+category: tool
+tool: Statistical Computing with Python
+contributors:
+ - ["e99n09", "https://github.com/e99n09"]
+translators:
+ - ["waltercjunior", "https://github.com/waltercjunior"]
+filename: pythonstatcomp-pt.py
+lang: pt-br
+---
+
+Este é um tutorial sobre como fazer algumas tarefas típicas de programação estatística usando Python.
+É destinado basicamente à pessoas familizarizadas com Python e experientes com programação estatística em linguagens como R,
+Stata, SAS, SPSS ou MATLAB.
+
+```python
+
+
+
+# 0. Preparando-se ====
+
+""" Para começar, instale o seguinte : jupyther, numpy, scipy, pandas,
+ matplotlib, seaborn, requests.
+ Certifique-se de executar este tutorial utilizando o Jupyther notebook para
+ que você utilize os gráficos embarcados e ter uma fácil consulta à
+ documentação.
+ O comando para abrir é simplesmente '`jupyter notebook`, quando abrir então
+ clique em 'New -> Python'.
+"""
+
+# 1. Aquisição de dados ====
+
+""" A única razão das pessoas optarem por Python no lugar de R é que pretendem
+ interagir com o ambiente web, copiando páginas diretamente ou solicitando
+ dados utilizando uma API. Você pode fazer estas coisas em R, mas no
+ contexto de um projeto já usando Python, há uma vantagem em se ater uma
+ linguágem única.
+"""
+
+import requests # para requisições HTTP (web scraping, APIs)
+import os
+
+# web scraping
+r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
+r.status_code # se retornou código 200, a requisição foi bem sucedida
+r.text # código fonte bruto da página
+print(r.text) # formatado bonitinho
+# salve a o código fonte d apágina em um arquivo:
+os.getcwd() # verifique qual é o diretório de trabalho
+with open("learnxinyminutes.html", "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+# Baixar um arquivo csv
+fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/"
+fn = "pets.csv"
+r = requests.get(fp + fn)
+print(r.text)
+with open(fn, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+""" para mais informações sobre o módulo de solicitações, incluindo API's, veja em
+ http://docs.python-requests.org/en/latest/user/quickstart/
+"""
+
+# 2. Lendo um arquivo formato CSV ====
+
+""" Um pacote de pandas da Wes McKinney lhe dá um objeto 'DataFrame' em Python.
+ Se você já usou R, já deve estar familiarizado com a ideia de "data.frame".
+"""
+
+import pandas as pd
+import numpy as np
+import scipy as sp
+pets = pd.read_csv(fn)
+pets
+# name age weight species
+# 0 fluffy 3 14 cat
+# 1 vesuvius 6 23 fish
+# 2 rex 5 34 dog
+
+""" Usuários R: observe que o Python, como a maioria das linguagens de programação
+ influenciada pelo C, a indexação começa de 0. Em R, começa a indexar em 1
+ devido à influência do Fortran.
+"""
+
+# duas maneiras diferentes de imprimir uma coluna
+pets.age
+pets["age"]
+
+pets.head(2) # imprima as 2 primeiras linhas
+pets.tail(1) # imprima a última linha
+
+pets.name[1] # 'vesuvius'
+pets.species[0] # 'cat'
+pets["weight"][2] # 34
+
+# Em R, você esperaria obter 3 linhas fazendo isso, mas aqui você obtem 2:
+pets.age[0:2]
+# 0 3
+# 1 6
+
+sum(pets.age) * 2 # 28
+max(pets.weight) - min(pets.weight) # 20
+
+""" Se você está fazendo alguma álgebra linear séria e processamento de
+ números você pode desejar apenas arrays, não DataFrames. DataFrames são
+ ideais para combinar colunas de diferentes tipos de dados.
+"""
+
+# 3. Gráficos ====
+
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+%matplotlib inline
+
+# Para fazer a visualiação de dados em Python, use matplotlib
+
+plt.hist(pets.age);
+
+plt.boxplot(pets.weight);
+
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
+
+# seaborn utiliza a biblioteca do matplotlib e torna os enredos mais bonitos
+
+import seaborn as sns
+
+plt.scatter(pets.age, pets.weight)
+plt.xlabel("age")
+plt.ylabel("weight");
+
+# também existem algumas funções de plotagem específicas do seaborn
+# observe como o seaborn automaticamenteo o eixto x neste gráfico de barras
+sns.barplot(pets["age"])
+
+# Veteranos em R ainda podem usar o ggplot
+from ggplot import *
+ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
+# fonte: https://pypi.python.org/pypi/ggplot
+
+# há até um d3.js veja em: https://github.com/mikedewar/d3py
+
+# 4. Limpeza de dados simples e análise exploratória ====
+
+""" Aqui está um exemplo mais complicado que demonstra dados básicos
+ fluxo de trabalho de limpeza levando à criação de algumas parcelas
+ e a execução de uma regressão linear.
+ O conjunto de dados foi transcrito da Wikipedia à mão. Contém
+ todos os sagrados imperadores romanos e os marcos importantes em suas vidas
+ (birth, death, coronation, etc.).
+ O objetivo da análise será explorar se um relacionamento existe
+ entre o ano de nascimento (birth year) e a expectativa de vida (lifespam)
+ do imperador.
+ Fonte de dados: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
+"""
+
+# carregue alguns dados dos sagrados imperadores romanos
+url = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/hre.csv"
+r = requests.get(url)
+fp = "hre.csv"
+with open(fp, "wb") as f:
+ f.write(r.text.encode("UTF-8"))
+
+hre = pd.read_csv(fp)
+
+hre.head()
+"""
+ Ix Dynasty Name Birth Death
+0 NaN Carolingian Charles I 2 April 742 28 January 814
+1 NaN Carolingian Louis I 778 20 June 840
+2 NaN Carolingian Lothair I 795 29 September 855
+3 NaN Carolingian Louis II 825 12 August 875
+4 NaN Carolingian Charles II 13 June 823 6 October 877
+
+ Coronation 1 Coronation 2 Ceased to be Emperor
+0 25 December 800 NaN 28 January 814
+1 11 September 813 5 October 816 20 June 840
+2 5 April 823 NaN 29 September 855
+3 Easter 850 18 May 872 12 August 875
+4 29 December 875 NaN 6 October 877
+"""
+
+# limpar as colunas Birth e Death
+
+import re # módulo para expressões regulares
+
+rx = re.compile(r'\d+$') # conincidir com os códigos finais
+
+""" Esta função aplia a expressão reguar a uma coluna de entrada (here Birth,
+ Death), nivela a lista resultante, converte-a em uma lista de objetos, e
+ finalmente converte o tipo do objeto da lista de String para inteiro. para
+ mais informações sobre o que as diferentes partes do código fazer, veja em:
+ - https://docs.python.org/2/howto/regex.html
+ - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list
+ - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html
+"""
+
+from functools import reduce
+
+def extractYear(v):
+ return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int))
+
+hre["BirthY"] = extractYear(hre.Birth)
+hre["DeathY"] = extractYear(hre.Death)
+
+# faça uma coluna infomrnado a idade estimada ("EstAge")
+hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
+
+# gráfico de dispersão simples, sem linha de tendência, cor representa dinastia
+sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False)
+
+# use o scipy para executar uma regrassão linear
+from scipy import stats
+(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge)
+# código fonte: http://wiki.scipy.org/Cookbook/LinearRegression
+
+# varifique o declive (slope)
+slope # 0.0057672618839073328
+
+# varifique o valor R^2:
+rval**2 # 0.020363950027333586
+
+# varifique o valor p-value
+pval # 0.34971812581498452
+
+# use o seaborn para fazer um gráfico de dispersão e traçar a linha de tendência de regrassão linear
+sns.lmplot("BirthY", "EstAge", data=hre)
+
+""" Para mais informações sobre o seaborn, veja
+ - http://web.stanford.edu/~mwaskom/software/seaborn/
+ - https://github.com/mwaskom/seaborn
+ Para mais informações sobre o SciPy, veja
+ - http://wiki.scipy.org/SciPy
+ - http://wiki.scipy.org/Cookbook/
+ Para ver uma versão da análise dos sagrados imperadores romanos usando R, consulte
+ - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
+"""
+
+```
+
+Se você quiser saber mais, obtenha o Python para análise de dados de Wes McKinney. É um excelente recurso e usei-o como referência ao escrever este tutorial.
+
+Você também pode encontrar muitos tutoriais interativos de IPython sobre assuntos específicos de seus interesses, como Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Programação Probabilística e Métodos Bayesianos para Hackers">Programação Probabilística e Métodos Bayesianos para Hackers</a>.
+
+Mais alguns módulos para pesquisar:
+ - análise de texto e processamento de linguagem natural: nltk, http://www.nltk.org
+ - análise de rede social: igraph, http://igraph.org/python/
diff --git a/pt-br/qt-pt.html.markdown b/pt-br/qt-pt.html.markdown
index 99579c35..f4211e09 100644
--- a/pt-br/qt-pt.html.markdown
+++ b/pt-br/qt-pt.html.markdown
@@ -1,7 +1,7 @@
---
category: tool
tool: Qt Framework
-language: c++
+language: C++
filename: learnqt-pt.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
diff --git a/pt-br/r-pt.html.markdown b/pt-br/r-pt.html.markdown
new file mode 100644
index 00000000..5c9304ec
--- /dev/null
+++ b/pt-br/r-pt.html.markdown
@@ -0,0 +1,786 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+ - ["kalinn", "http://github.com/kalinn"]
+translators:
+ - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"]
+lang: pt-br
+filename: learnr-pt.r
+---
+
+R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX.
+
+```r
+
+# Comentários começam com o símbolo de Cerquilha, também conhecido como
+# jogo da velha
+
+# Não existe um símbolo especial para comentários em várias linhas
+# mas você pode escrever várias linhas de comentários adicionando a
+# cerquilha (#) ao início de cada uma delas.
+
+# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha.
+# No MacOS, o equivalente é COMMAND-ENTER
+
+
+
+#############################################################################
+# Coisas que você pode fazer sem entender nada sobre programação
+#############################################################################
+
+# Nesta seção, mostramos algumas das coisas legais que você pode fazer em
+# R sem entender nada de programação. Não se preocupe em entender tudo o
+# que o código faz. Apenas aproveite!
+
+data() # navegue pelos conjuntos de dados pré-carregados
+data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos"
+ls() # observe que "rivers" apareceu na área de trabalho (workspace)
+head(rivers) # dê uma espiada no conjunto de dados
+# 735 320 325 392 524 450
+
+length(rivers) # quantos rios foram medidos?
+# 141
+summary(rivers) # consulte um sumário de estatísticas básicas
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma)
+stem(rivers)
+
+# A vírgula está 2 dígito(s) à direita do símbolo |
+#
+# 0 | 4
+# 2 | 011223334555566667778888899900001111223333344455555666688888999
+# 4 | 111222333445566779001233344567
+# 6 | 000112233578012234468
+# 8 | 045790018
+# 10 | 04507
+# 12 | 1471
+# 14 | 56
+# 16 | 7
+# 18 | 9
+# 20 |
+# 22 | 25
+# 24 | 3
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
+# 36 | 1
+
+stem(log(rivers)) # Observe que os dados não são normais nem log-normais!
+# Tome isso, fundamentalistas da curva normal!
+
+# O ponto decimal está 1 dígito(s) à esquerda do símbolo |
+#
+# 48 | 1
+# 50 |
+# 52 | 15578
+# 54 | 44571222466689
+# 56 | 023334677000124455789
+# 58 | 00122366666999933445777
+# 60 | 122445567800133459
+# 62 | 112666799035
+# 64 | 00011334581257889
+# 66 | 003683579
+# 68 | 0019156
+# 70 | 079357
+# 72 | 89
+# 74 | 84
+# 76 | 56
+# 78 | 4
+# 80 |
+# 82 | 2
+
+# faça um histograma:
+hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros
+hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde
+
+# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles.
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Ano",
+ main="Número de descobertas importantes por ano")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano",
+ main="Número de descobertas importantes por ano")
+
+# Em vez de deixar a ordenação padrão (por ano),
+# também podemos ordenar para ver o que é mais comum:
+sort(discoveries)
+# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
+# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
+# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
+# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
+
+stem(discoveries, scale=2)
+#
+# O ponto decimal está no símbolo |
+#
+# 0 | 000000000
+# 1 | 000000000000
+# 2 | 00000000000000000000000000
+# 3 | 00000000000000000000
+# 4 | 000000000000
+# 5 | 0000000
+# 6 | 000000
+# 7 | 0000
+# 8 | 0
+# 9 | 0
+# 10 | 0
+# 11 |
+# 12 | 0
+
+max(discoveries)
+# 12
+summary(discoveries)
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
+
+# Role um dado algumas vezes
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed
+
+# Obtenha 9 números de forma aleatória a partir de uma distribuição normal
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+##################################################
+# Tipos de dados e aritmética básica
+##################################################
+
+# Agora para a parte orientada a programação do tutorial.
+# Nesta seção você conhecerá os tipos de dados importantes do R:
+# integers, numerics, characters, logicals, e factors.
+# Existem outros, mas estes são o mínimo que você precisa para
+# iniciar.
+
+# INTEGERS
+# Os inteiros de armazenamento longo são escritos com L
+5L # 5
+class(5L) # "integer"
+# (Experimente ?class para obter mais informações sobre a função class().)
+# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1
+length(5L) # 1
+# Você pode ter um vetor inteiro com comprimento > 1 também:
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+# NUMERICS
+# Um "numeric" é um número de ponto flutuante de precisão dupla
+5 # 5
+class(5) # "numeric"
+# De novo, tudo em R é um vetor;
+# você pode fazer um vetor numérico com mais de um elemento
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# Você também pode usar a notação científica
+5e4 # 50000
+6.02e23 # Número de Avogadro
+1.6e-35 # Comprimento de Planck
+# Você também pode ter números infinitamente grandes ou pequenos
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf)
+# isso evita as tabelas de escores-Z.
+
+# ARITMÉTICA BÃSICA
+# Você pode fazer aritmética com números
+# Fazer aritmética com uma mistura de números inteiros (integers) e com
+# ponto flutuante (numeric) resulta em um numeric
+10L + 66L # 76 # integer mais integer resulta em integer
+53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric
+2.0 * 2L # 4 # numeric vezes integer resulta em numeric
+3L / 4 # 0.75 # integer dividido por numeric resulta em numeric
+3 %% 2 # 1 # o resto de dois numeric é um outro numeric
+# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number):
+0 / 0 # NaN
+class(NaN) # "numeric"
+# Você pode fazer aritmética em dois vetores com comprimento maior que 1,
+# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor
+c(1,2,3) + c(1,2,3) # 2 4 6
+# Como um único número é um vetor de comprimento um, escalares são aplicados
+# elemento a elemento com relação a vetores
+(4 * c(1,2,3) - 2) / 2 # 1 3 5
+# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com
+# comprimentos diferentes. Embora possa ser feito,
+c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
+# ter comprimentos iguais é uma prática melhor e mais fácil de ler
+c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+
+# CHARACTERS
+# Não há diferença entre strings e caracteres em R
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# São ambos vetores de caracteres de comprimento 1
+# Aqui está um mais longo:
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# Você pode utilizar expressões regulares (regex) em vetores de caracteres:
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
+# R tem vários vetores de caracteres embutidos:
+letters
+# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
+# [20] "t" "u" "v" "w" "x" "y" "z"
+month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
+
+# LOGICALS
+# Em R, um "logical" é um booleano
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# O comportamento deles é normal
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# Dados ausentes (NA) são logical, também
+class(NA) # "logical"
+# Use | e & para operações lógicas.
+# OR
+TRUE | FALSE # TRUE
+# AND
+TRUE & FALSE # FALSE
+# Aplicar | e & a vetores retorna operações lógicas elemento a elemento
+c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
+c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+# Você pode testar se x é TRUE
+isTRUE(TRUE) # TRUE
+# Aqui obtemos um vetor logical com muitos elementos:
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+# FACTORS
+# A classe factor é para dados categóricos
+# Os fatores podem ser ordenados (como as avaliações de crianças) ou
+# não ordenados (como as cores)
+factor(c("azul", "azul", "verde", NA, "azul"))
+# azul azul verde <NA> azul
+# Levels: azul verde
+# Os "levels" são os valores que os dados categóricos podem assumir
+# Observe que os dados ausentes não entram nos levels
+levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde"
+# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1
+length(factor("green")) # 1
+length(levels(factor("green"))) # 1
+# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos
+# mais tarde
+data(infert) # "Infertilidade após aborto espontâneo e induzido"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+# NULL
+# "NULL" é um valor estranho; use-o para "apagar" um vetor
+class(NULL) # NULL
+parakeet = c("bico", "penas", "asas", "olhos")
+parakeet
+# [1] "bico" "penas" "asas" "olhos"
+parakeet <- NULL
+parakeet
+# NULL
+
+# COERÇÃO DE TIPO
+# Coerção de tipo é quando você força um valor a assumir um tipo diferente
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem:
+c(TRUE, 4) # 1 4
+c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4"
+as.numeric("Bilbo")
+# [1] NA
+# Warning message:
+# NAs introduced by coercion
+
+# Observe também: esses são apenas os tipos de dados básicos
+# Existem muitos outros tipos de dados, como datas, séries temporais, etc.
+
+
+
+##################################################
+# Variáveis, laços, expressões condicionais
+##################################################
+
+# Uma variável é como uma caixa na qual você armazena um valor para uso posterior.
+# Chamamos isso de "atribuir" o valor à variável.
+# Ter variáveis nos permite escrever laços, funções e instruções com condição
+
+# VARIÃVEIS
+# Existem muitas maneiras de atribuir valores:
+x = 5 # é possível fazer assim
+y <- "1" # mas é preferível fazer assim
+TRUE -> z # isso funciona, mas é estranho
+
+# LAÇOS
+# Nós temos laços com for
+for (i in 1:4) {
+ print(i)
+}
+# [1] 1
+# [1] 2
+# [1] 3
+# [1] 4
+# Nós temos laços com while
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# 10...9...8...7...6...5...
+# Tenha em mente que os laços for e while são executados lentamente em R
+# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira)
+# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas
+
+# IF/ELSE
+# Novamente, bastante padrão
+if (4 > 3) {
+ print("4 é maior que 3")
+} else {
+ print("4 não é maior que 3")
+}
+# [1] "4 é maior que 3"
+
+# FUNÇÕES
+# Definidas assim:
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado)
+ return(x)
+}
+# Chamada como qualquer outra função R:
+jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043
+
+
+
+###########################################################################
+# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays)
+###########################################################################
+
+# UNIDIMENSIONAL
+
+# Vamos começar do início, e com algo que você já sabe: vetores.
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# Consultamos elementos específicos utilizando colchetes
+# (Observe que R começa a contar a partir de 1)
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+# Também podemos pesquisar os índices de componentes específicos,
+which(vec %% 2 == 0) # 1 3
+# pegue apenas as primeiras ou últimas entradas no vetor,
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# ou descubra se um determinado valor está no vetor
+any(vec == 10) # TRUE
+# Se um índice for além do comprimento de um vetor, você obterá NA:
+vec[6] # NA
+# Você pode encontrar o comprimento do seu vetor com length()
+length(vec) # 4
+# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
+# e R tem muitas funções internas para sumarizar vetores
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# Mais alguns recursos embutidos:
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from=0, to=31337, by=1337)
+# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
+# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
+
+# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE)
+
+# Você pode fazer uma matriz com entradas do mesmo tipo assim:
+mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém
+class(mat) # "matrix"
+# Consulte a primeira linha
+mat[1,] # 1 4
+# Execute uma operação na primeira coluna
+3 * mat[,1] # 3 6 9
+# Consulte uma célula específica
+mat[3,2] # 6
+
+# Transponha toda a matriz
+t(mat)
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+# Multiplicação de matrizes
+mat %*% t(mat)
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+# cbind() une vetores em colunas para formar uma matriz
+mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro"))
+mat2
+# [,1] [,2]
+# [1,] "1" "cachorro"
+# [2,] "2" "gato"
+# [3,] "3" "passaro"
+# [4,] "4" "cachorro"
+class(mat2) # matrix
+# Mais uma vez, observe o que aconteceu!
+# Como as matrizes devem conter todas as entradas da mesma classe,
+# tudo foi convertido para a classe character
+c(class(mat2[,1]), class(mat2[,2]))
+
+# rbind() une vetores linha a linha para fazer uma matriz
+mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3
+# [,1] [,2] [,3] [,4]
+# [1,] 1 2 4 5
+# [2,] 6 7 0 4
+# Ah, tudo da mesma classe. Sem coerções. Muito melhor.
+
+# BIDIMENSIONAL (CLASSES DIFERENTES)
+
+# Para colunas de tipos diferentes, use um data frame
+# Esta estrutura de dados é tão útil para programação estatística,
+# que uma versão dela foi adicionada ao Python através do pacote "pandas".
+
+estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas
+class(estudantes) # "data.frame"
+estudantes
+# nome ano casa
+# 1 Cedric 3 H
+# 2 Fred 2 G
+# 3 George 2 G
+# 4 Cho 1 R
+# 5 Draco 0 S
+# 6 Ginny -1 G
+class(estudantes$ano) # "numeric"
+class(estudantes[,3]) # "factor"
+# encontre as dimensões
+nrow(estudantes) # 6
+ncol(estudantes) # 3
+dim(estudantes) # 6 3
+# A função data.frame() converte vetores de caracteres em vetores de fator
+# por padrão; desligue isso definindo stringsAsFactors = FALSE quando
+# você criar um data frame
+?data.frame
+
+# Existem muitas maneiras particulares de consultar partes de um data frame,
+# todas sutilmente diferentes
+estudantes$ano # 3 2 2 1 0 -1
+estudantes[,2] # 3 2 2 1 0 -1
+estudantes[,"ano"] # 3 2 2 1 0 -1
+
+# Uma versão extendida da estrutura data.frame é a data.table
+# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar
+# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour
+# relâmpago:
+install.packages("data.table") # baixe o pacote a partir do CRAN
+require(data.table) # carregue ele
+estudantes <- as.data.table(estudantes)
+estudantes # observe a saída ligeiramente diferente
+# nome ano casa
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny"
+# nome ano casa
+# 1: Ginny -1 G
+estudantes[ano==2] # Consulte estudantes com o ano == 2
+# nome ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# data.table facilita a fusão de dois conjuntos de dados
+# vamos fazer outro data.table para mesclar com os alunos
+fundadores <- data.table(casa=c("G","H","R","S"),
+ fundador=c("Godric","Helga","Rowena","Salazar"))
+fundadores
+# casa fundador
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(estudantes, casa)
+setkey(fundadores, casa)
+estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa"
+setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano"))
+estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F]
+# nomeEstudante ano casa nomeFundadorCasa
+# 1: Fred 2 G Godric
+# 2: George 2 G Godric
+# 3: Ginny -1 G Godric
+# 4: Cedric 3 H Helga
+# 5: Cho 1 R Rowena
+# 6: Draco 0 S Salazar
+
+# O data.table torna as tabelas de sumário fáceis
+estudantes[,sum(ano),by=casa]
+# casa V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+# Para remover uma coluna de um data.frame ou data.table,
+# atribua a ela o valor NULL
+estudantes$nomeFundadorCasa <- NULL
+estudantes
+# nomeEstudante ano casa
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+# Remova uma linha consultando parte dos dados
+# Usando data.table:
+estudantes[nomeEstudante != "Draco"]
+# casa estudanteNome ano
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# Usando data.frame:
+estudantes <- as.data.frame(estudantes)
+estudantes[estudantes$casa != "G",]
+# casa nomeFundadorCasa nomeEstudante ano
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO)
+
+# Arranjos (arrays) criam tabelas n-dimensionais
+# Todos os elementos devem ser do mesmo tipo
+# Você pode fazer uma tabela bidimensional (como uma matriz)
+array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+# [,1] [,2] [,3] [,4]
+# [1,] 1 4 8 3
+# [2,] 2 5 9 6
+# Você pode usar array para fazer matrizes tridimensionais também
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+# , , 1
+#
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
+#
+# , , 2
+#
+# [,1] [,2]
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
+
+# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS)
+
+# Finalmente, R tem listas (de vetores)
+lista1 <- list(tempo = 1:40)
+lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória
+lista1
+# Você pode obter itens na lista assim
+lista1$tempo # um modo
+lista1[["tempo"]] # um outro modo
+lista1[[1]] # e ainda um outro modo
+# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+# [34] 34 35 36 37 38 39 40
+# Você pode obter itens de uma lista como qualquer outro vetor
+lista1$preco[4]
+
+# Listas não são a estrutura de dados mais eficiente para se trabalhar em R;
+# a menos que você tenha um bom motivo, você deve se ater a data.frames
+# As listas geralmente são retornadas por funções que realizam regressões lineares
+
+##################################################
+# A família de funções apply()
+##################################################
+
+# Lembra de mat?
+mat
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X
+# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2)
+# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um
+# laço for ou while faria
+apply(mat, MAR = 2, jiggle)
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# Outras funções: ?lappy, ?sapply
+
+# Não as deixe te intimidar; todos concordam que essas funções são bem confusas
+
+# O pacote plyr visa substituir (e melhorar!) a família *apply().
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+#########################
+# Carregando dados
+#########################
+
+# "pets.csv" é um arquivo hospedado na internet
+# (mas também poderia tranquilamente ser um arquivo no seu computador)
+require(RCurl)
+pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv")))
+pets
+head(pets, 2) # primeiras duas linhas
+tail(pets, 1) # última linha
+
+# Para salvar um data frame ou matriz como um arquivo .csv:
+write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv
+# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd()
+
+# Experimente ?read.csv e ?write.csv para obter mais informações
+
+
+
+#########################
+# Análise estatística
+#########################
+
+# Regressão linear!
+modeloLinear <- lm(preco ~ tempo, data = lista1)
+modeloLinear # imprime na tela o resultado da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.1453 0.4943
+summary(modeloLinear) # saída mais detalhada da regressão
+# Call:
+# lm(formula = preco ~ tempo, data = lista1)
+#
+# Residuals:
+# Min 1Q Median 3Q Max
+# -8.3134 -3.0131 -0.3606 2.8016 10.3992
+#
+# Coefficients:
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.14527 1.50084 0.097 0.923
+# tempo 0.49435 0.06379 7.749 2.44e-09 ***
+# ---
+# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
+#
+# Residual standard error: 4.657 on 38 degrees of freedom
+# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022
+# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09
+coef(modeloLinear) # extrai os parâmetros estimados
+# (Intercept) tempo
+# 0.1452662 0.4943490
+summary(modeloLinear)$coefficients # um outro meio de extrair os resultados
+# Estimate Std. Error t value Pr(>|t|)
+# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
+# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09
+summary(modeloLinear)$coefficients[,4] # the p-values
+# (Intercept) tempo
+# 9.234021e-01 2.440008e-09
+
+# MODELOS LINEARES GERAIS
+# Regressão logística
+set.seed(1)
+lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório
+modeloLg <- glm(sucesso ~ tempo, data = lista1,
+ family=binomial(link="logit"))
+modeloLg # imprime na tela o resultado da regressão logística
+# Call: glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+#
+# Coefficients:
+# (Intercept) tempo
+# 0.17018 -0.01321
+#
+# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual
+# Null Deviance: 55.35
+# Residual Deviance: 55.12 AIC: 59.12
+summary(modeloLg) # saída mais detalhada da regressão
+# Call:
+# glm(formula = sucesso ~ tempo,
+# family = binomial(link = "logit"), data = lista1)
+
+# Deviance Residuals:
+# Min 1Q Median 3Q Max
+# -1.245 -1.118 -1.035 1.202 1.327
+#
+# Coefficients:
+# Estimate Std. Error z value Pr(>|z|)
+# (Intercept) 0.17018 0.64621 0.263 0.792
+# tempo -0.01321 0.02757 -0.479 0.632
+#
+# (Dispersion parameter for binomial family taken to be 1)
+#
+# Null deviance: 55.352 on 39 degrees of freedom
+# Residual deviance: 55.121 on 38 degrees of freedom
+# AIC: 59.121
+#
+# Number of Fisher Scoring iterations: 3
+
+
+#########################
+# Gráficos
+#########################
+
+# FUNÇÕES DE PLOTAGEM INTEGRADAS
+# Gráficos de dispersão!
+plot(lista1$tempo, lista1$preco, main = "dados falsos")
+# Trace a linha de regressão em um gráfico existente!
+abline(modeloLinear, col = "red")
+# Obtenha uma variedade de diagnósticos legais
+plot(modeloLinear)
+# Histogramas!
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# Gráficos de barras!
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+# GGPLOT2
+# Mas estes não são nem os mais bonitos dos gráficos no R
+# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(estudantes, aes(x=casa))
+pp + geom_bar()
+ll <- as.data.table(lista1)
+pp <- ggplot(ll, aes(x=tempo,preco))
+pp + geom_point()
+# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/)
+
+
+
+```
+
+## Como faço para obter R?
+
+* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica
diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown
index 3dd4a8d5..1080baa4 100644
--- a/pt-br/rust-pt.html.markdown
+++ b/pt-br/rust-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
filename: rust-pt.rs
contributors:
- ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"]
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
index 28df3c59..e5175857 100644
--- a/pt-br/sass-pt.html.markdown
+++ b/pt-br/sass-pt.html.markdown
@@ -4,6 +4,7 @@ filename: learnsass-pt.scss
contributors:
- ["Laura Kyle", "https://github.com/LauraNK"]
- ["Sean Corrales", "https://github.com/droidenator"]
+ - ["Thalles Augusto", "https://github.com/Theslladev"]
translators:
- ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
- ["Cássio Böck", "https://github.com/cassiobsilva"]
@@ -16,7 +17,7 @@ Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os d
Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula.
Este tutorial é escrito usando SCSS.
-Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente.
+Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais facilmente.
```scss
@@ -249,7 +250,7 @@ ul {
/* '&' será substituído pelo selector pai (parent). */
/* Você também pode aninhar pseudo-classes. */
/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável.
-Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação.
+Essas práticas também recomendam não mais de 3 níveis de profundidade quando nidificação.
Por exemplo: */
@@ -379,7 +380,7 @@ body {
/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
   ser úteis para calcular os valores diretamente no seu arquivos Sass em vez
- de usar valores que você já calculados manualmente. O exemplo abaixo é
+ de usar valores que você já calcula manualmente. O exemplo abaixo é
de um projeto simples de duas colunas. */
$content-area: 960px;
diff --git a/pt-br/set-theory-pt.html.markdown b/pt-br/set-theory-pt.html.markdown
new file mode 100644
index 00000000..58fd7979
--- /dev/null
+++ b/pt-br/set-theory-pt.html.markdown
@@ -0,0 +1,129 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+lang: pt-br
+contributors:
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
+translators:
+ - ["Bárbara Luz", "https://github.com/barbluz"]
+---
+
+Teoria de conjuntos é uma área da matemática que estuda conjuntos, suas operações e propriedades.
+- Um conjunto é uma coleção de itens disjuntos.
+
+## Símbolos básicos
+
+### Operações
+- a operação de união `∪`, significa "ou"
+- a operação de interseção `∩`, que significa "e"
+- a operação de exclusão `\`, significa "sem" ou "menos"
+- a operação de conjunto complementar `'`, que significa "o inverso de"
+- a operação de produto cartesiano `×`,que significa "o produto cartesiano de"
+
+### Outros símbolos
+- `:` ou `|`, símbolos que significam "tal que"
+- o símbolo de pertencimento `∈`, que significa "pertence a"
+- o símbolo `⊆`, que significa "subconjunto de" (neste caso, o subconjunto pode ser igual ao conjunto)
+- o símbolo `⊂`, que significa "subconjunto próprio" (neste caso, o subconjunto não pode ser igual ao conjunto)
+
+### Conjuntos canônicos
+- `∅`, o conjunto vazio, isto é, o conjunto que não possui itens
+- `ℕ`, o conjunto de todos os números naturais
+- `ℤ`, o conjunto de todos os números inteiros
+- `ℚ`, o conjunto de todos os números racionais
+- `â„`, o conjunto de todos os números reais
+
+Existem algumas ressalvas sobre os conjuntos canônicos:
+- Apesar de o conjunto vazio não conter itens, o conjunto vazio é subconjunto de si mesmo (e portanto de todos os outros conjuntos)
+- Matemáticos geralmente não concordam sobre o zero ser um número natural e os livros tipicamente explicitam se o autor considera ou não o zero como um número natural
+
+
+### Cardinalidade
+A cardinalidade (ou tamanho) de um conjunto é determinado pela quantidade de itens no conjunto. O operador de cardinalidade é `|...|`
+
+Por exemplo, se `S = {1, 2, 4}`, então `|S| = 3`.
+
+### O Conjunto Vazio
+- o conjunto vazio pode ser contruído em notação de conjuntos utilizando condições impossíveis, como por exemplo: `∅ = { x : x ≠ x }`, ou `∅ = { x : x ∈ N, x < 0 }`
+- o conjunto vazio é sempre único (ou seja, existe um e apenas um conjunto vazio)
+- o conjunto vazio é subconjunto de todos os conjuntos
+- a cardinalidade do conjunto vazio é `0`, ou seja, `|∅| = 0`.
+
+## Representando conjuntos
+
+### Definição Literal
+Um conjunto pode ser contruído literalmente fornecendo uma lista completa dos itens contigos no conjunto. Por exemplo `S = { a, b, c, d }`
+
+Listas longas podem ser encurtadas com reticências, desde que o contexto seja claro. Por exemplo, `E = { 2, 4, 6, 8, ... }` é claramente o conjunto de todos os números pares, contendo um número infinito de objetos, embora só tenhamos escrito explicitamente quatro deles.
+
+### Definição por compreensão
+Conjuntos também podem ser descritos de uma maneira mais descritiva, baseando-se em sujeito e predicado, de forma tal que `S = {sujeito : predicado}`. Por exemplo:
+
+```
+A = { x : x é uma vogal } = { a, e, i, o, u } (lê-se x, tal que x é uma vogal)
+B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
+C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+Ou pode-se também aplicar uma função ao sujeito, ex:
+```
+D = { 2x : x ∈ N } = { 0, 2, 4, 6, 8, ... }
+```
+
+## Relações
+
+### Pertencimento
+- Se um valor `a` está contido num conjunto `A`, então dizemos que `a` pertence a `A` e denotamos por `a ∈ A`
+- Se o valor `a` não está contido no conjunto `A`, então dizemos que `a` não pertence a `A` e denotamos por `a ∉ A`
+
+### Igualdade
+- Se dois conjuntos contém os mesmos itens, então dizemos que os conjuntos são iguals, ex. `A = B`
+- A ordenação não importa quando vamos avaliar a igualdade, ex: `{ 1, 2, 3, 4 } = { 2, 3, 1, 4 }`
+- Conjuntos são disjuntos, o que significa que os elementos não podem ser repetidos, ex: `{ 1, 2, 2, 3, 4, 3, 4, 2 } = { 1, 2, 3, 4 }`
+- Dois conjuntos `A` e `B` são iguais se, e somente se, `A ⊆ B` e `B ⊆ A`
+
+### Conjuntos especiais
+O Conjunto das Partes
+- Seja `A` um conjunto qualquer. O conjunto que contém todos os possíveis subconjuntos de `A` é chamado "conjunto das partes" e é denotado como `P(A)`. Se o conjunto `A` contém `n` elementos, então o conjunto das partes conterá `2^n` elementos.
+```
+P(A) = { x : x ⊆ A }
+```
+
+## Operações entre dois conjuntos
+
+### União
+Dados dois conjuntos `A` e `B`, a união entre esses dois conjuntos são os itens que aparecem em `A` ou em `B`, denotado por `A ∪ B`.
+
+```
+A ∪ B = { x : x ∈ A ∪ x ∈ B }
+```
+
+### Interseção
+Dados dois conjuntos `A` e `B`, a interseção entre esses dois conjuntos são os itens que aparecem em `A` e em `B`, denotado por `A ∩ B`.
+
+```
+A ∩ B = { x : x ∈ A, x ∈ B }
+```
+
+### Diferença
+Dados dois conjuntos `A` e `B`, o conjunto da diferença entre `A` e `B` são todos os itens de `A` que não pertencem a `B`.
+```
+A \ B = { x : x ∈ A, x ∉ B }
+```
+
+### Diferença simétrica
+Dados dois conjuntos `A` e `B`, a diferença simétrica são todos os itens entre `A` e `B` que não aparecem na interseção desses dois conjuntos.
+
+```
+A △ B = { x : ((x ∈ A) ∩ (x ∉ B)) ∪ ((x ∈ B) ∩ (x ∉ A)) }
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Produto Cartesiano
+Dados dois conjuntos `A` e `B`, o produto cartesiano de `A` e `B` consiste no conjunto contendo todas as combinações dos itens de `A` e `B`.
+```
+A × B = { (x, y) | x ∈ A, y ∈ B }
+```
+
+
diff --git a/pt-br/sql-pt.html.markdown b/pt-br/sql-pt.html.markdown
new file mode 100644
index 00000000..0e4631a6
--- /dev/null
+++ b/pt-br/sql-pt.html.markdown
@@ -0,0 +1,119 @@
+---
+language: SQL
+filename: learnsql-pt.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["jovinoguerrero", "https://github.com/jovinoguerrero"]
+lang: pt-br
+---
+
+A linguagem de consulta estruturada (SQL em inglês) é uma linguagem padrão ISO para criar e trabalhar com bancos de dados armazenados num conjunto de tabelas. As implementações geralmente adicionam suas próprias extensões à linguagem; [Comparação entre diferentes implementações de SQL](http://troels.arvin.dk/db/rdbms/) é uma boa referência sobre as diferenças entre os diferentes produtos.
+
+As implementações normalmente fornecem uma linha de comando onde se pode digitar os comandos mostrados aqui de forma interativa, e também oferecem uma maneira de executar uma série desses comandos armazenados em um arquivo de script (mostrar que é feito com o prompt interativo é um bom exemplo de algo que não é padronizado - a maioria das implementações SQL suporta as palavras-chave QUIT, EXIT ou ambas).
+
+Vários desses comandos de exemplo assumem que o [banco de dados de funcionários de exemplo MySQL](https://dev.mysql.com/doc/employee/en/) disponível em [github](https://github.com/datacharmer/test_db) já foi carregado. Os arquivos do GitHub são scripts de comandos, semelhantes aos comandos abaixo, que criam e carregam tabelas de dados sobre os funcionários de uma empresa fictícia. A sintaxe para executar esses scripts dependerá da implementação SQL que você está usando. Um aplicativo executado a partir do prompt do sistema operacional geralmente é o normal.
+
+
+```sql
+-- Os comentários começam com dois hífens. Cada comando é encerrado com um
+-- ponto e vírgula.
+
+-- SQL não diferencia maiúsculas de minúsculas em palavras-chave. Os
+-- comandos de exemplo mostrados aqui seguem a convenção de serem escritos
+-- em maiúsculas porque torna mais fácil distingui-los dos nomes dos bancos
+-- de dados, tabelas e colunas.
+
+-- Em seguida, um banco de dados é criado e excluído. Os nomes do banco de
+-- dados e da tabela são sensíveis a maiúsculas de minúsculas.
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- Mostra numa lista todos os bancos de dados disponíveis.
+SHOW DATABASES;
+
+-- Usa um determinado banco de dados existente.
+USE employees;
+
+-- Seleciona todas as filas e colunas da tabela de departamentos no banco
+-- de dados atual. A atividade padrão é o intérprete rolar os resultados
+-- na tela.
+SELECT * FROM departments;
+
+-- Recupera todas as filas da tabela de departamentos, mas apenas as colunas
+-- dept_no e dept_name.
+-- A separação de comandos em várias linhas é permitida.
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- Obtém todas as colunas de departments, mas é limitado a 5 filas.
+SELECT * FROM departments LIMIT 5;
+
+-- Obtém os valores da coluna dept_name da tabela de departments quando
+-- dept_name tem como valor a substring 'en'.
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- Recupera todas as colunas da tabela de departments onde a coluna
+-- dept_name começa com um 'S' e tem exatamente 4 caracteres depois dele.
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- Seleciona os valores dos títulos da tabela de titles, mas não mostra
+-- duplicatas.
+SELECT DISTINCT title FROM titles;
+
+-- Igual ao anterior, mas ordenado por valores de da coluna title (diferencia
+-- maiúsculas de minúsculas).
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- Mostra o número de filas da tabela departments.
+SELECT COUNT(*) FROM departments;
+
+-- Mostra o número de filas da tabela departments que contém 'en' como
+-- substring na coluna dept_name.
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+-- Uma união (JOIN) de informações de várias tabelas: a tabela titles mostra
+-- quem tem quais cargos laborais, de acordo com seu número de funcionários,
+-- e desde que data até que data. Esta informação é obtida, mas em vez do
+-- número do funcionário é usada como referência cruzada a tabela employee
+-- para obter o nome e sobrenome de cada funcionário (e limita os resultados
+-- a 10 filas).
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- São listadas todas as tabelas de todas os bancos de dados. As implementações
+-- normalmente fornecem seus próprios comandos para fazer isso com o banco de
+-- dados atualmente em uso.
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- Cria uma tabela chamada tablename1, com as duas colunas mostradas, a partir
+-- do banco de dados em uso. Há muitas outras opções dísponiveis para a forma
+-- em que se especificam as colunas, por ex. seus tipos de dados.
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- Insere uma fila de dados na tabela tablename1. É assumido que a tabela foi
+-- definida para aceitar esses valores como adequados.
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+-- Em tablename1, se altera o valor de fname para 'John' em todas as filas que
+-- contenham um valor em lname igual a 'Mutt'.
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+-- Se excluem as filas da tabela tablename1 em que o valor de lname começa
+-- com 'M'.
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- Se excluem as filas da tabela tablename1, deixando a tabla vazia.
+DELETE FROM tablename1;
+
+-- A tabela tablename1, é excluída completamente.
+DROP TABLE tablename1;
+```
+
+# Leitura adicional
+
+* [Codecademy - SQL](https://www.codecademy.com/learn/learn-sql) A good introduction to SQL in a “learn by doing it†format.
+* [Database System Concepts](https://www.db-book.com/) book’s Chapter 3 - Introduction to SQL has an in depth explanation of SQL concepts.
diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown
index ce3be407..e2130e0a 100644
--- a/pt-br/tmux-pt.html.markdown
+++ b/pt-br/tmux-pt.html.markdown
@@ -59,47 +59,49 @@ As seções tmux acopladas são controladas através de teclas de atalho. (prefi
----------------------------------------------------------------------
(C-b) = Ctrl + b # Abre a opção de receber comandos(atalhos).
- (M-1) = Meta + 1 -or- Alt + 1
+ (M-1) = Meta + 1 -ou- Alt + 1
----------------------------------------------------------------------
- ? # Lista todos os comandos.
- : # Acessa o prompt command do tmux
- r # Força a reinicialização do cliente acoplado.
- c # Cria uma nova janela.
+ ? # Lista todos os comandos.
+ : # Acessa o prompt command do tmux
+ r # Força a reinicialização do cliente acoplado.
+ c # Cria uma nova janela.
- ! # Retira o painel atual da janela.
- % # Divide o painel atual em dois. Esquerda e direita.
- " # Divide o painel atual em dois. Para cima e para baixo.
+ ! # Retira o painel atual da janela.
+ % # Divide o painel atual em dois. Esquerda e direita.
+ " # Divide o painel atual em dois. Para cima e para baixo.
- n # Muda para a próxima janela.
- p # Muda para a janela anterior.
- { # Troca o painel atual pelo anterior.
- } # Troca o painel corrent pelo posterior.
+ n # Muda para a próxima janela.
+ p # Muda para a janela anterior.
+ { # Troca o painel atual pelo anterior.
+ } # Troca o painel corrent pelo posterior.
+ [ # Entra no modo cópia (Copy Mode) para copiar texto ou ver o histórico.
- s # Seleciona uma nova seção para o cliente acoplado iterativamente.
- w # Seleciona a janela atual iterativamente.
- 0 to 9 # Seleciona a janela de 0 à 9.
- d # Separa o cliente atual.
- D # Seleciona um cliente a ser separado.
+ s # Seleciona uma nova seção para o cliente acoplado iterativamente.
+ w # Seleciona a janela atual iterativamente.
+ 0 to 9 # Seleciona a janela de 0 à 9.
- & # Encerra a janela atual.
- x # Encerra o painel atual.
+ d # Separa o cliente atual.
+ D # Seleciona um cliente a ser separado.
- Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita.
+ & # Encerra a janela atual.
+ x # Encerra o painel atual.
+
+ Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita.
Left, Right
- M-1 to M-5 # Organiza os paines:
+ M-1 to M-5 # Organiza os paines:
# 1) Horizontalmente de maneira igual
# 2) Verticalmente de maineira igual.
# 3) Principal horizontalmente
# 4) Principal verticamente.
# 5) Mosaico
- C-Up, C-Down # Altera o tamanho do painel atual em uma célula.
+ C-Up, C-Down # Altera o tamanho do painel atual em uma célula.
C-Left, C-Right
- M-Up, M-Down # Altera o tamanho do painel atual em cinco células.
+ M-Up, M-Down # Altera o tamanho do painel atual em cinco células.
M-Left, M-Right
```
diff --git a/pt-br/toml-pt.html.markdown b/pt-br/toml-pt.html.markdown
new file mode 100644
index 00000000..bdb1decf
--- /dev/null
+++ b/pt-br/toml-pt.html.markdown
@@ -0,0 +1,232 @@
+---
+language: toml
+filename: learntoml-pt.toml
+contributors:
+ - ["Alois de Gouvello", "https://github.com/aloisdg"]
+translators:
+ - ["Adaías Magdiel", "https://adaiasmagdiel.com/"]
+lang: pt-br
+---
+
+TOML significa Tom's Obvious, Minimal Language. É uma linguagem de serialização de dados projetada para ser um formato de arquivo de configuração mínimo que é fácil de ler devido à semântica óbvia.
+
+É uma alternativa ao YAML e JSON. Tem como objetivo ser mais amigável para humanos do que JSON e mais simples que YAML. TOML é projetado para mapear de forma inequívoca para uma tabela de hash e deve ser fácil de converter em estruturas de dados em uma ampla variedade de linguagens.
+
+Cuidado, a especificação do TOML ainda passa por muitas mudanças. Até que seja marcado como 1.0, você deve assumir que é instável e agir de acordo. Este documento segue o TOML v0.4.0.
+
+```toml
+# Comentários em TOML são feitos desta forma.
+
+###################
+# TIPOS ESCALARES #
+###################
+
+# Nosso objeto raiz (que continuará por todo o documento) será um mapa,
+# que é equivalente a um dicionário, hash ou objeto em outras linguagens.
+
+# A chave, o sinal de igual e o valor precisam estar na mesma linha
+# (embora alguns valores possam ser quebrados em várias linhas).
+chave = "valor"
+string = "Olá"
+number = 42
+float = 3.14
+boolean = true
+dateTime = 2002-07-16T20:32:00-03:00
+scientificNotation = 1e+12
+"chaves podem estar entre aspas" = true # Tanto " quanto ' são aceitáveis
+"chaves podem conter" = "letras, números, underscores e hífens"
+
+# Uma chave não pode ser vazia, mas uma chave vazia entre aspas é permitido
+"" = "blank" # VÃLIDO mas não é recomendado
+'' = 'blank' # VÃLIDO mas não é recomendado
+
+##########
+# String #
+##########
+
+# Todas as strings precisam ter apenas caracteres UTF-8 válidos.
+# Podemos escapar caracteres e alguns deles têm uma sequência de escape compacta.
+# Por exemplo: \t adiciona uma tabulação. Leia a spec para conhecer todos.
+basicString = "São cercadas por aspas. \"Sou digno de citação\". Nome\tJosé."
+
+multiLineString = """
+são cercadas por três aspas
+em cada lado e permitem novas linhas."""
+
+literalString = 'são cercadas por aspas simples. Escape de caracteres não é permitido.'
+
+multiLineString = '''
+são cercadas por três aspas simples em cada lado
+e permitem novas linhas. Escape de caracteres também não é permitido.
+A primeira quebra de linha é removida em strings brutas
+ Todo outro espaço em branco
+ é preservado. #! foi preservado?
+'''
+
+# Para dados binários é recomendado que você use Base64, outra codificação ASCII ou UTF8.
+# A manipulação dessa codificação será específico da aplicação.
+
+############
+# Inteiros #
+############
+
+## Inteiros podem começar com um +, um -, ou nada.
+## Zeros à frente não são permitidos.
+## Formatos em hexadecimal, octal e binário são permitidos.
+## Não são permitidos valores que não podem ser expressados como uma série de dígitos.
+int1 = +42
+int2 = 0
+int3 = -21
+int4 = 0xcafebabe
+int5 = 0o755
+int6 = 0b11011100
+integerRange = 64
+
+## Você pode usar underscores para melhorar a legibilidade.
+## Cada underscore precisa estar entre, pelo menos, um dígito.
+int7 = 5_349_221
+int8 = 1_2_3_4_5 # VÃLIDO, mas não é recomendado
+
+#########
+# Float #
+#########
+
+# Floats são inteiros seguidos por uma fração e/ou de um expoente.
+flt1 = 3.1415
+flt2 = -5e6
+flt3 = 6.626E-34
+
+#############
+# Booleanos #
+#############
+
+bool1 = true
+bool2 = false
+booleanosPrecisamEstarEmMinusculo = true
+
+############
+# Datetime #
+############
+
+date1 = 1979-05-27T07:32:00Z # Tempo UTC, seguindo especificação RFC 3339/ISO 8601
+date2 = 1979-05-26T15:32:00+08:00 # com um deslocamento segundo a RFC 3339/ISO 8601
+date3 = 1979-05-27T07:32:00 # sem deslocamento
+date4 = 1979-05-27 # sem as horas e sem deslocamento
+
+####################
+# TIPOS DE COLEÇÃO #
+####################
+
+#########
+# Array #
+#########
+
+array1 = [ 1, 2, 3 ]
+array2 = [ "Vírgulas", "são", "delimitadores" ]
+array3 = [ "Não misture", "tipos", "diferentes" ]
+array4 = [ [ 1.2, 2.4 ], ["todas as", 'strings', """são do mesmo""", '''tipo'''] ]
+array5 = [
+ "Espaços em branco", "são", "ignorados"
+]
+
+##########
+# Tabela #
+##########
+
+# Tabelas (ou tabelas de hash, ou dicionários) é uma coleção de pares chave/valor.
+# Eles aparecem entre colchetes em uma linha separada.
+# Tabelas vazias são permitidas e simplesmente não possuem chave/valor associado.
+[tabela]
+
+# Abaixo disso, e até a próxima tabela ou final do arquivo, estão as chaves/valores dessa tabela.
+# Os pares de chave/valor dentro das tabelas não têm garantia de estar em nenhuma ordem específica.
+[table-1]
+chave1 = "algum texto"
+chave2 = 123
+
+[table-2]
+chave1 = "outro texto"
+chave2 = 456
+
+# Pontos são proibidos em chaves simples porque são usados para indicar tabelas aninhadas.
+# As regras de nomenclatura para cada parte separada por ponto são as mesmas que para chaves.
+[dog."tater.man"]
+type = "pug"
+
+# Na terra do JSON, você teria a seguinte estrutura:
+# { "dog": { "tater.man": { "type": "pug" } } }
+
+# Espaços em branco em torno das partes separadas por pontos são ignorados, de qualquer forma,
+# é sempre recomendado não utilizar espaços em branco desnecessários.
+[a.b.c] # isso é o recomendado
+[ d.e.f ] # mesmo que [d.e.f]
+[ j . "Êž" . 'l' ] # mesmo que [j."Êž".'l']
+
+# Você não precisa especificar todas as super-tabelas se não quiser. TOML sabe
+# como lidar com isso para você.
+# [x] você
+# [x.y] não precisa
+# [x.y.z] disso
+[x.y.z.w] # para isso funcionar
+
+# Mesmo que uma super-tabela não tenha sido definida diretamente e não tenha definido uma
+# chave específica, ainda é possível escrever nela.
+[a.b]
+c = 1
+
+[a]
+d = 2
+
+# Irá gerar o seguinte JSON:
+# { "a": {"b": {"c": 1}, "d": 2 } }
+
+# Você não pode definir uma chave ou tabela mais de uma vez. É inválido fazer isso.
+
+# NÃO FAÇA ISSO
+[a]
+b = 1
+
+[a]
+c = 2
+
+# NEM MESMO ISSO
+[a]
+b = 1
+
+[a.b]
+c = 2
+
+# O nome de todas as tabelas não pode ser vazio.
+[] # INVÃLIDO
+[a.] # INVÃLIDO
+[a..b] # INVÃLIDO
+[.b] # INVÃLIDO
+[.] # INVÃLIDO
+
+####################
+# Tabelas em linha #
+####################
+
+tabelasEmLinha = { sãoFechadasCom = "{ e }", precisamEstarEmUmaLinha = true }
+ponto = { x = 1, y = 2 }
+
+####################
+# Array de Tabelas #
+####################
+
+# Um array de tabelas pode ser expresso usando um nome de tabela entre colchetes duplos.
+# Cada tabela com o mesmo nome entre colchetes duplos será um item no array.
+# As tabelas são inseridas na ordem em que são encontradas.
+
+[[produtos]]
+nome = "array de tabelas"
+sku = 738594937
+tabelasVaziasSaoPermitidas = true
+
+[[produtos]]
+
+[[produtos]]
+nome = "Unhas"
+sku = 284758393
+color = "cinza"
+```
diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown
index 2a7205cd..dcc72c04 100644
--- a/pt-br/visualbasic-pt.html.markdown
+++ b/pt-br/visualbasic-pt.html.markdown
@@ -8,7 +8,7 @@ lang: pt-br
filename: learnvisualbasic-pt.vb
---
-```
+```visualbasic
Module Module1
module Module1
@@ -28,12 +28,12 @@ module Module1
Console.WriteLine ("2. Entrada Olá Mundo" )
Console.WriteLine ("3. Cálculando números inteiros " )
Console.WriteLine ("4. Calculando números decimais " )
- Console.WriteLine ("5 . Calculadora de Trabalho " )
+ Console.WriteLine ("5. Calculadora de Trabalho " )
Console.WriteLine ("6. Usando Do While Loops " )
Console.WriteLine ("7. Usando Para While Loops " )
- Console.WriteLine ("8 . Declarações condicionais " )
+ Console.WriteLine ("8. Declarações condicionais " )
Console.WriteLine ("9. Selecione uma bebida" )
- Console.WriteLine ("50 . About" )
+ Console.WriteLine ("50. About" )
Console.WriteLine ("Por favor, escolha um número da lista acima " )
Seleção Dim As String = Console.ReadLine
Select A seleção dos casos
@@ -76,7 +76,7 @@ module Module1
End Sub
' Um - Eu estou usando números para ajudar com a navegação acima quando eu voltar
- ' depois de construí-lo .
+ ' depois de construí-lo.
" Nós usamos subs privadas para separar diferentes seções do programa.
Private Sub HelloWorldOutput ()
@@ -94,12 +94,12 @@ module Module1
Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes"
' Variáveis
'Os dados inseridos por um usuário precisam ser armazenados.
- ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType .
+ ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType.
' Neste tutorial, nós queremos saber qual é o seu nome, e faça o programa
' Responder ao que é dito.
Nome de usuário Dim As String
- " Nós usamos string como string é uma variável de texto baseado .
+ " Nós usamos string como string é uma variável de texto baseado.
Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome.
username = Console.ReadLine () ' armazena o nome do usuário.
Console.WriteLine (" Olá " + username) ' A saída é "Olá < seu nome >".
@@ -124,10 +124,10 @@ module Module1
'Quatro
Sub CalculatingDecimalNumbers particulares ()
Console.Title = " Calculando com duplo | Saiba X em Y Minutes"
- ' Claro que gostaria de ser capaz de somar decimais .
+ ' Claro que gostaria de ser capaz de somar decimais.
" Por isso, poderia mudar o acima de Integer para Double.
- " Digite um número inteiro , 1,2 , 2,4 , 50,1 , 104,9 ect
+ " Digite um número inteiro como 1, 2, 50, 104, etc
Console.Write ("Primeiro número:")
Dim a As Double = Console.ReadLine
Console.Write ("Segundo número:") 'Enter segundo número inteiro.
@@ -141,9 +141,9 @@ module Module1
' Cinco
Private Sub WorkingCalculator ()
Console.Title = " A Calculadora de Trabalho | Saiba X em Y Minutes"
- " No entanto, se você gostaria que a calculadora para subtrair, dividir , múltiplos e
+ " No entanto, se você gostaria que a calculadora para subtrair, dividir, múltiplos e
' somar.
- ' Copie e cole o código acima novamente .
+ ' Copie e cole o código acima novamente.
Console.Write ("Primeiro número:")
Dim a As Double = Console.ReadLine
Console.Write ("Segundo número:") 'Enter segundo número inteiro.
@@ -153,7 +153,7 @@ module Module1
Dim e As Integer = a - b
Dim f As Integer = a / b
- " Ao adicionar as linhas abaixo , somos capazes de calcular a subtração ,
+ " Ao adicionar as linhas abaixo, somos capazes de calcular a subtração,
' multply bem como dividir os valores de a e b
Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) )
'Queremos pad as respostas para a esquerda por três espaços.
@@ -172,8 +172,8 @@ module Module1
Sub UsingDoWhileLoops particulares ()
' Assim como o sub privado anterior
' Desta vez, perguntar se o usuário deseja continuar ( Sim ou Não ? )
- ' Estamos usando Do While Loop , como não temos certeza se o usuário quer usar o
- 'programa mais de uma vez .
+ ' Estamos usando Do While Loop, como não temos certeza se o usuário quer usar o
+ 'programa mais de uma vez.
Console.Title = " UsingDoWhileLoops | Saiba X em Y Minutes"
Dim resposta As String ' Nós usamos a variável " String" como a resposta é um texto
Do ' Começamos o programa com
@@ -195,12 +195,12 @@ module Module1
Console.Write ( a.ToString () + "/" + b.ToString ())
Console.WriteLine (" =" + e.ToString.PadLeft (3) )
Console.ReadLine ()
- ' Faça a pergunta , se o usuário deseja continuar? Infelizmente,
+ ' Faça a pergunta, se o usuário deseja continuar? Infelizmente,
"é sensível a maiúsculas.
Console.Write ( "Deseja continuar? (Sim / não )")
" O programa pega a variável e imprime e começa de novo.
answer = Console.ReadLine
- " O comando para a variável para trabalhar seria , neste caso, " sim "
+ " O comando para a variável para trabalhar seria, neste caso, " sim "
Loop While resposta = "yes"
End Sub
@@ -233,7 +233,7 @@ module Module1
outro
Console.WriteLine (" Olá " + nome do usuário)
Console.WriteLine (" Você check-out www.learnxinyminutes.com " )
- Console.ReadLine () ' Fins e imprime a declaração acima .
+ Console.ReadLine () ' Fins e imprime a declaração acima.
End If
End Sub
@@ -242,15 +242,15 @@ module Module1
Console.Title = "Se Declaração / Else | Saiba X em Y Minutes"
'Às vezes é importante ter em conta mais de duas alternativas.
'Às vezes, há um bom número de outros.
- 'Quando este for o caso , mais do que uma if seria necessária .
- 'Uma instrução if é ótimo para máquinas de venda automática . Quando o usuário digita um código.
- ' A1 , A2, A3 , ect para selecionar um item.
+ 'Quando este for o caso, mais do que uma if seria necessária.
+ 'Uma instrução if é ótimo para máquinas de venda automática. Quando o usuário digita um código.
+ ' A1, A2, A3, etc para selecionar um item.
'Todas as opções podem ser combinadas em uma única if.
Seleção Dim Valor String = Console.ReadLine ' para a seleção
Console.WriteLine (" A1. Para Soda " )
Console.WriteLine (" A2. Para Fanta " )
- Console.WriteLine (" A3 . Para Guaraná" )
+ Console.WriteLine (" A3. Para Guaraná" )
Console.WriteLine (" A4. Para Coca Diet" )
Console.ReadLine ()
Se a seleção = "A1" Então
diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown
index 21e9b4bb..b2fb2a7d 100644
--- a/pt-br/yaml-pt.html.markdown
+++ b/pt-br/yaml-pt.html.markdown
@@ -2,6 +2,7 @@
language: yaml
contributors:
- ["Leigh Brenecki", "https://github.com/adambrenecki"]
+ - [Suhas SG, 'https://github.com/jargnar']
translators:
- ["Rodrigo Russo", "https://github.com/rodrigozrusso"]
filename: learnyaml-pt.yaml
@@ -14,6 +15,8 @@ legível por seres humanos.
É um superconjunto de JSON, com a adição de identação e quebras de linhas sintaticamente significativas, como Python. Ao contrário de Python, entretanto, YAML não permite o caracter literal tab para identação.
```yaml
+--- # início do documento
+
# Comentários em YAML são como este.
###################
@@ -30,28 +33,32 @@ boleano: true
valor_nulo: null
chave com espaco: valor
# Observe que strings não precisam de aspas. Porém, elas podem ter.
-porem: "Uma string, entre aspas."
-"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave."
+porem: 'Uma string, entre aspas.'
+'Chaves podem estar entre aspas tambem.': "É útil se você quiser colocar um ':' na sua chave."
+aspas simples: 'possuem ''um'' padrão de escape'
+aspas duplas: "possuem vários: \", \0, \t, \u263A, \x0d\x0a == \r\n, e mais."
+# Caracteres UTF-8/16/32 precisam ser codificados
+Superscript dois: \u00B2
# Seqüências de várias linhas podem ser escritas como um 'bloco literal' (utilizando |),
# ou em um 'bloco compacto' (utilizando '>').
bloco_literal: |
- Todo esse bloco de texto será o valor da chave 'bloco_literal',
- preservando a quebra de com linhas.
+ Todo esse bloco de texto será o valor da chave 'bloco_literal',
+ preservando a quebra de com linhas.
- O literal continua até de-dented, e a primeira identação é
- removida.
+ O literal continua até 'des-indentar', e a primeira identação é
+ removida.
- Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações -
- estas linhas serão identadas com 4 espaços.
+ Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações -
+ estas linhas serão identadas com 4 espaços.
estilo_compacto: >
- Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta
- vez, todas as novas linhas serão substituídas com espaço simples.
+ Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta
+ vez, todas as novas linhas serão substituídas com espaço simples.
- Linhas em branco, como acima, são convertidas em um carater de nova linha.
+ Linhas em branco, como acima, são convertidas em um carater de nova linha.
- Linhas 'mais-indentadas' mantém suas novas linhas também -
- este texto irá aparecer em duas linhas.
+ Linhas 'mais-indentadas' mantém suas novas linhas também -
+ este texto irá aparecer em duas linhas.
####################
# TIPOS DE COLEÇÃO #
@@ -59,54 +66,85 @@ estilo_compacto: >
# Texto aninhado é conseguido através de identação.
um_mapa_aninhado:
- chave: valor
- outra_chave: Outro valor
- outro_mapa_aninhado:
- ola: ola
+ chave: valor
+ outra_chave: Outro valor
+ outro_mapa_aninhado:
+ ola: ola
# Mapas não tem que ter chaves com string.
0.25: uma chave com valor flutuante
-# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave.
+# As chaves podem ser complexas, como sequência de várias linhas
+# Utilizando ? seguido por espaço para indicar o começo de uma chave complexa.
? |
- Esta é uma chave
- que tem várias linhas
+ Esta é uma chave
+ que tem várias linhas
: e este é o seu valor
-# também permite tipos de coleção de chaves, mas muitas linguagens de programação
-# vão reclamar.
+# YAML também permite o mapeamento entre sequências com a sintaxe chave complexa
+# Alguns analisadores de linguagem de programação podem reclamar
+# Um exemplo
+? - Manchester United
+ - Real Madrid
+: [2001-01-01, 2002-02-02]
# Sequências (equivalente a listas ou arrays) semelhante a isso:
uma_sequencia:
- - Item 1
- - Item 2
- - 0.5 # sequencias podem conter tipos diferentes.
- - Item 4
- - chave: valor
- outra_chave: outro_valor
- -
- - Esta é uma sequencia
- - dentro de outra sequencia
+ - Item 1
+ - Item 2
+ - 0.5 # sequências podem conter tipos diferentes.
+ - Item 4
+ - chave: valor
+ outra_chave: outro_valor
+ -
+ - Esta é uma sequência
+ - dentro de outra sequência
+ - - - Indicadores de sequência aninhadas
+ - podem ser recolhidas
# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e
-# sequencias:
+# sequências:
mapa_json: {"chave": "valor"}
json_seq: [3, 2, 1, "decolar"]
+e aspas são opcionais: {chave: [3, 2, 1, decolar]}
-##########################
-# RECURSOS EXTRA DO YAML #
-##########################
+###########################
+# RECURSOS EXTRAS DO YAML #
+###########################
# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique
# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor:
-conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves.
-outra_ancora: * nome_ancora
+conteudo_ancora: &nome_ancora Essa string irá aparecer como o valor de duas chaves.
+outra_ancora: *nome_ancora
+
+# Âncoras podem ser usadas para dubplicar/herdar propriedades
+base: &base
+ name: Todos possuem o mesmo nome
+
+# O regexp << é chamado Mesclar o Tipo Chave Independente-de-Idioma. É usado para
+# indicar que todas as chaves de um ou mais mapas específicos devam ser inseridos
+# no mapa atual.
+
+foo:
+ <<: *base
+ idade: 10
+
+bar:
+ <<: *base
+ idade: 20
+
+# foo e bar terão o mesmo nome: Todos possuem o mesmo nome
# YAML também tem tags, que você pode usar para declarar explicitamente os tipos.
-string_explicita: !! str 0,5
+string_explicita: !!str 0.5
# Alguns analisadores implementam tags específicas de linguagem, como este para Python de
# Tipo de número complexo.
-numero_complexo_em_python: !! python / complex 1 + 2j
+numero_complexo_em_python: !!python/complex 1+2j
+
+# Podemos utilizar chaves YAML complexas com tags específicas de linguagem
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Seria {(5, 7): 'Fifty Seven'} em Python
####################
# YAML TIPOS EXTRA #
@@ -114,27 +152,34 @@ numero_complexo_em_python: !! python / complex 1 + 2j
# Strings e números não são os únicos que escalares YAML pode entender.
# Data e 'data e hora' literais no formato ISO também são analisados.
-datetime: 2001-12-15T02: 59: 43.1Z
-datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5
-Data: 2002/12/14
+datetime: 2001-12-15T02:59:43.1Z
+datetime_com_espaços: 2001-12-14 21:59:43.10 -5
+date: 2002-12-14
# A tag !!binary indica que a string é na verdade um base64-encoded (codificado)
# representação de um blob binário.
gif_file: !!binary |
- R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
- OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
- +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
- AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# YAML também tem um tipo de conjunto, o que se parece com isso:
-set:
- ? item1
- ? item2
- ? item3
-
-# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a:
-set2:
- item1: nulo
- item2: nulo
- item3: nulo
+conjunto:
+ ? item1
+ ? item2
+ ? item3
+ou: {item1, item2, item3}
+
+# Como Python, são apenas conjuntos de mapas com valores nulos; o acima é equivalente a:
+conjunto2:
+ item1: null
+ item2: null
+ item3: null
+
+... # fim do documento
```
+### Mais Recursos
+
++ [Site Oficial do YAML](https://yaml.org/)
++ [Validador YAML Online](http://www.yamllint.com/)
diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown
index bd0f0fc5..86710a13 100644
--- a/pt-pt/git-pt.html.markdown
+++ b/pt-pt/git-pt.html.markdown
@@ -411,5 +411,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
-* [GitGuys](http://www.gitguys.com/)
diff --git a/pt-pt/kotlin-pt.html.markdown b/pt-pt/kotlin-pt.html.markdown
new file mode 100644
index 00000000..47dbb44d
--- /dev/null
+++ b/pt-pt/kotlin-pt.html.markdown
@@ -0,0 +1,473 @@
+---
+language: kotlin
+filename: LearnKotlin-pt.kt
+lang: pt-pt
+contributors:
+ - ["S Webber", "https://github.com/s-webber"]
+translators:
+ - ["André Martins", "https://github.com/chriptus13"]
+---
+
+Kotlin é uma linguagem de programação de tipificação estática para a JVM, Android e browser. Ela é 100% interoperável com Java.
+[Lê mais aqui.](https://kotlinlang.org/)
+
+```kotlin
+// Comentários de linha começam com //
+/*
+Comentários de múltiplas linhas são assim.
+*/
+
+// A palavra-chave "package" funciona da mesma forma que em Java.
+package com.learnxinyminutes.kotlin
+
+/*
+O ponto de entrada de um programa em Kotlin é a função chamada "main".
+Esta função tem como único parâmetro um array contendo todos os argumentos passados na linha de comandos.
+Desde a versão 1.3 que esta pode também ser definida sem parâmetros.
+*/
+fun main(args: Array<String>) {
+ /*
+ A declaração de variáveis é feita usando "var" ou "val".
+ Variáveis declaradas com "val" não podem ser redefinidas, já as declaradas com "var" podem.
+ */
+ val fooVal = 10 // não podemos redefinir mais tarde o valor de fooVal para algo diferente
+ var fooVar = 10
+ fooVar = 20 // fooVar pode ser redefinida
+
+ /*
+ Na maioria dos casos, o Kotlin pode determinar (inferir) o tipo de uma variável,
+ assim não precisamos de o dizer explicitamente sempre.
+ Para especificar o tipo explicitamente fazemos assim:
+ */
+ val foo: Int = 7
+
+ /*
+ As Strings são representadas de uma forma semelhante ao Java.
+ O escape é feito com barras invertidas.
+ */
+ val fooString = "A minha String está aqui!"
+ val barString = "Imprimir numa nova linha?\nSem problemas!"
+ val bazString = "Adicionar um tab?\tSem problemas!"
+ println(fooString)
+ println(barString)
+ println(bazString)
+
+ /*
+ Uma raw string é delimitada por aspas triplas (""").
+ Raw strings podem conter caracteres de nova linha ou qualquer outro.
+ */
+ val fooRawString = """
+fun helloWorld(val name : String) {
+ println("Hello, world!")
+}
+"""
+ println(fooRawString)
+
+ /*
+ As strings podem também conter template expressions.
+ Uma template expression começa com o símbolo do dollar ($).
+ */
+ val fooTemplateString = "$fooString tem ${fooString.length} caracteres"
+ println(fooTemplateString) // => A minha String está aqui! tem 25 caracteres
+
+ /*
+ Para que uma variável possa ter o valor de null esta tem de ser
+ especificada explicitamente como nullable.
+ Uma variável pode ser marcada como nullable adicionando um ? ao seu tipo.
+ A variable can be specified as nullable by appending a ? to its type.
+ Usando o operador ?. podemos facilmente aceder a propriedades de
+ uma variável nullable, se esta for null o resultado da expressão será também ele null.
+ Podemos também usar o operador ?: para especificar um valor alternativo
+ no caso da variavél ser null.
+ */
+ var fooNullable: String? = "abc"
+ println(fooNullable?.length) // => 3
+ println(fooNullable?.length ?: -1) // => 3
+ fooNullable = null
+ println(fooNullable?.length) // => null
+ println(fooNullable?.length ?: -1) // => -1
+
+ /*
+ As funções são declaradas usando a palavra-chave "fun".
+ Os parâmetros da função são especificados entre parênteses a seguir ao nome da função.
+ Estes parâmetros podem opcionalmente ter um valor por omissão.
+ O tipo de retorno da função, se necessário, é especificado após os parâmetros.
+ */
+ fun hello(name: String = "world"): String {
+ return "Hello, $name!"
+ }
+ println(hello("foo")) // => Hello, foo!
+ println(hello(name = "bar")) // => Hello, bar!
+ println(hello()) // => Hello, world!
+
+ /*
+ Para que uma função receba um número variável de parâmetros podemos
+ marcar um, e apenas um, parâmetro com a palavra-chave "vararg".
+ */
+ fun varargExample(vararg names: Int) {
+ println("Argument has ${names.size} elements")
+ }
+ varargExample() // => A chamada à função tem 0 argumentos
+ varargExample(1) // => A chamada à função tem 1 argumentos
+ varargExample(1, 2, 3) // => A chamada à função tem 3 argumentos
+
+ /*
+ Quando uma função consiste em apenas uma expressão as chavetas podem ser omitidas
+ O corpo da mesma é especificado após o símbolo de igual (=).
+ */
+ fun odd(x: Int): Boolean = x % 2 == 1
+ println(odd(6)) // => false
+ println(odd(7)) // => true
+
+ // Se o tipo de retorno da função pode ser inferido então não é necessário especificá-lo.
+ fun even(x: Int) = x % 2 == 0
+ println(even(6)) // => true
+ println(even(7)) // => false
+
+ // As funções podem ter outras funções como parâmetros e/ou como retorno.
+ fun not(f: (Int) -> Boolean): (Int) -> Boolean {
+ return {n -> !f.invoke(n)}
+ }
+ // O operador :: pode ser usado para referênciar funções existentes.
+ val notOdd = not(::odd)
+ val notEven = not(::even)
+ /*
+ Expressões lambda podem ser usadas da seguinte forma.
+ Os lambdas quando passados a outras funções podem estar
+ fora dos parênteses da chamada, caso sejam o último parâmetro.
+ */
+ val notZero = not {n -> n == 0}
+ /*
+ Se o lambda apenas tiver um parâmetro então a sua
+ declaração pode ser omitida (em conjunto com "->").
+ O nome por omissão do parâmetro será "it".
+ */
+ val notPositive = not {it > 0}
+ for (i in 0..4) {
+ println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
+ }
+
+ // Para declararmos classes usa-se a palavra-chave "class".
+ class ExampleClass(val x: Int) {
+ fun aMethod(y: Int): Int {
+ return x + y
+ }
+
+ infix fun infixMemberFunction(y: Int): Int {
+ return x * y
+ }
+ }
+ /*
+ Para se instanciar uma classe usamos o constructor.
+ De notar que em Kotlin não existe a palavra-chave "new" como no Java.
+ */
+ val fooExampleClass = ExampleClass(7)
+ // Os métodos da classe podem então ser chamados usando o ponto.
+ println(fooExampleClass.aMethod(4)) // => 11
+ /*
+ Uma função marcada com a palavra-chave "infix" pode ser chamada
+ usando a notação infixa.
+ */
+ println(fooExampleClass infixMemberFunction 4) // => 28
+
+ /*
+ Data classes são uma forma concisa de criar classes que apenas contêm dados.
+ Neste tipo de classes os métodos "hashCode"/"equals" e "toString" são gerados
+ automáticamente.
+ */
+ data class DataClassExample (val x: Int, val y: Int, val z: Int)
+ val fooData = DataClassExample(1, 2, 4)
+ println(fooData) // => DataClassExample(x=1, y=2, z=4)
+
+ // Instâncias deste tipo de classes têm acesso ao método "copy".
+ val fooCopy = fooData.copy(y = 100)
+ println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
+
+ // Os objectos podem ser desconstruídos para variáveis.
+ val (a, b, c) = fooCopy
+ println("$a $b $c") // => 1 100 4
+
+ // desconstrucção dentro de um ciclo "for"
+ for ((a, b, c) in listOf(fooData)) {
+ println("$a $b $c") // => 1 2 4
+ }
+
+ val mapData = mapOf("a" to 1, "b" to 2)
+ // Instâncias de Map.Entry podem também ser desconstruídas.
+ for ((key, value) in mapData) {
+ println("$key -> $value")
+ }
+
+ // A função "with" é semelhante ao bloco "with" do JavaScript.
+ data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
+ val fooMutableData = MutableDataClassExample(7, 4, 9)
+ with (fooMutableData) {
+ x -= 2
+ y += 2
+ z--
+ }
+ println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
+
+ /*
+ Podemos criar listas usando a função "listOf".
+ No Kotlin, por padrão, as listas são imútaveis - não podendo
+ assim adicionar ou remover elementos das mesmas.
+ */
+ val fooList = listOf("a", "b", "c")
+ println(fooList.size) // => 3
+ println(fooList.first()) // => a
+ println(fooList.last()) // => c
+ // Os elementos de uma lista podem ser acedidos usando o seu índice.
+ println(fooList[1]) // => b
+
+ // Listas mútaveis podem ser criadas usando a função "mutableListOf".
+ val fooMutableList = mutableListOf("a", "b", "c")
+ fooMutableList.add("d")
+ println(fooMutableList.last()) // => d
+ println(fooMutableList.size) // => 4
+
+ // Podemos criar conjuntos usando a função "setOf".
+ val fooSet = setOf("a", "b", "c")
+ println(fooSet.contains("a")) // => true
+ println(fooSet.contains("z")) // => false
+
+ // Podemos criar mapas usando a função "mapOf" e através da função infixa "to".
+ val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
+ // Os valores do mapa podem ser acedidos usando a sua chave.
+ println(fooMap["a"]) // => 8
+
+ /*
+ No Kotlin as sequências representam collecções de dados avaliadas de forma lazy.
+ Podemos cirar uma sequência usando a função "generateSequence".
+ */
+ val fooSequence = generateSequence(1, { it + 1 })
+ val x = fooSequence.take(10).toList()
+ println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+
+ // Um exemplo de uso das sequências para gerar os números de Fibonacci:
+ fun fibonacciSequence(): Sequence<Long> {
+ var a = 0L
+ var b = 1L
+
+ fun next(): Long {
+ val result = a + b
+ a = b
+ b = result
+ return a
+ }
+
+ return generateSequence(::next)
+ }
+ val y = fibonacciSequence().take(10).toList()
+ println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
+
+ // O Kotlin fornece funções de ordem superior convenientes para a manipulação de colecções.
+ val z = (1..9).map {it * 3}
+ .filter {it < 20}
+ .groupBy {it % 2 == 0}
+ .mapKeys {if (it.key) "even" else "odd"}
+ println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
+
+ // Um ciclo "for" pode ser usado com qualquer coisa que forneça um iterador.
+ for (c in "hello") {
+ println(c)
+ }
+
+ // Um ciclo "while" funciona da mesma forma que em outras linguagens.
+ var ctr = 0
+ while (ctr < 5) {
+ println(ctr)
+ ctr++
+ }
+ do {
+ println(ctr)
+ ctr++
+ } while (ctr < 10)
+
+ /*
+ Um "if" pode ser usado como uma expressão que produz um valor.
+ Por esta razão o operador ternário não é necessário no Kotlin.
+ */
+ val num = 5
+ val message = if (num % 2 == 0) "even" else "odd"
+ println("$num is $message") // => 5 is odd
+
+ // O bloco "when" pode ser usado como alternativa para cadeias de "if-else if".
+ val i = 10
+ when {
+ i < 7 -> println("first block")
+ fooString.startsWith("hello") -> println("second block")
+ else -> println("else block")
+ }
+
+ // O "when" pode ser usado como um "switch" do Java.
+ when (i) {
+ 0, 21 -> println("0 or 21")
+ in 1..20 -> println("in the range 1 to 20")
+ else -> println("none of the above")
+ }
+
+ // O "when" pode também ser usado como expressão para produzir um valor.
+ var result = when (i) {
+ 0, 21 -> "0 or 21"
+ in 1..20 -> "in the range 1 to 20"
+ else -> "none of the above"
+ }
+ println(result)
+
+ /*
+ Podemos utilizar o operador "is" para verificar se um objecto é de um certo tipo.
+ Se um objecto passar a verificação do tipo pode ser usado como sendo desse tipo
+ sem conversão explicita, sendo isto chamado de smart cast.
+ */
+ fun smartCastExample(x: Any) : Boolean {
+ if (x is Boolean) {
+ // x is automatically cast to Boolean
+ return x
+ } else if (x is Int) {
+ // x is automatically cast to Int
+ return x > 0
+ } else if (x is String) {
+ // x is automatically cast to String
+ return x.isNotEmpty()
+ } else {
+ return false
+ }
+ }
+ println(smartCastExample("Hello, world!")) // => true
+ println(smartCastExample("")) // => false
+ println(smartCastExample(5)) // => true
+ println(smartCastExample(0)) // => false
+ println(smartCastExample(true)) // => true
+
+ // Os smart casts funcionam também com o bloco "when".
+ fun smartCastWhenExample(x: Any) = when (x) {
+ is Boolean -> x
+ is Int -> x > 0
+ is String -> x.isNotEmpty()
+ else -> false
+ }
+
+ /*
+ Extensões são uma forma de adicionar funcionalidade a classes existentes.
+ Isto é semelhante aos métodos de extensão do C#.
+ */
+ fun String.remove(c: Char): String {
+ return this.filter {it != c}
+ }
+ println("Hello, world!".remove('l')) // => Hello, world!
+}
+
+// Enum classes são o equivalente aos tipos enum do Java.
+enum class EnumExample {
+ A, B, C // As constantes da enumeração são separadas por vírgula.
+}
+fun printEnum() = println(EnumExample.A) // => A
+
+/*
+Como cada constante é uma instância da classe enum,
+estas podem ser inicializadas da seguinte forma:
+*/
+enum class EnumExample(val value: Int) {
+ A(value = 1),
+ B(value = 2),
+ C(value = 3)
+}
+fun printProperty() = println(EnumExample.A.value) // => 1
+
+/*
+Cada constante de enumerações tem propriedades para
+obter o nome e o ordinal (posição) na respectiva classe.
+*/
+fun printName() = println(EnumExample.A.name) // => A
+fun printPosition() = println(EnumExample.A.ordinal) // => 0
+
+/*
+A palavra-chave "object" pode ser usada para criar objectos singleton.
+Estes não podem ser instânciados, porém podem ser referênciados como uma
+única instância através do seu nome.
+São semelhantes aos objectos singleton do Scala.
+*/
+object ObjectExample {
+ fun hello(): String {
+ return "hello"
+ }
+
+ override fun toString(): String {
+ return "Hello, it's me, ${ObjectExample::class.simpleName}"
+ }
+}
+
+
+fun useSingletonObject() {
+ println(ObjectExample.hello()) // => hello
+ // Em Kotlin o tipo "Any" é a raíz da hierárquia de classes, tal como o tipo "Object" em Java.
+ val someRef: Any = ObjectExample
+ println(someRef) // => Hello, it's me, ObjectExample
+}
+
+
+/*
+O operador !! serve para realizar um assert de not-null. Este converte qualquer
+valor nullable para non-null ou lança exceção se o mesmo for null.
+*/
+var b: String? = "abc"
+val l = b!!.length // lançaria exceção caso "b" fosse null
+
+// O modificador "operator" permite fazer overload dos operadores
+// [Ver lista de operadores](https://kotlinlang.org/docs/operator-overloading.html)
+data class Counter(var value: Int) {
+ // overload para Counter += Int
+ operator fun plusAssign(increment: Int) {
+ this.value += increment
+ }
+
+ // overload para Counter++ e ++Counter
+ operator fun inc() = Counter(value + 1)
+
+ // overload para Counter + Counter
+ operator fun plus(other: Counter) = Counter(this.value + other.value)
+
+ // overload para Counter * Counter
+ operator fun times(other: Counter) = Counter(this.value * other.value)
+
+ // overload para Counter * Int
+ operator fun times(value: Int) = Counter(this.value * value)
+
+ // overload para Counter in Counter
+ operator fun contains(other: Counter) = other.value == this.value
+
+ // overload para Counter[Int] = Int
+ operator fun set(index: Int, value: Int) {
+ this.value = index + value
+ }
+
+ // overload para invocação da instância Counter
+ operator fun invoke() = println("The value of the counter is $value")
+}
+/* Podemos também dar overload dos operadores através de métodos de extensão */
+// overload para -Counter
+operator fun Counter.unaryMinus() = Counter(-this.value)
+
+fun operatorOverloadingDemo() {
+ var counter1 = Counter(0)
+ var counter2 = Counter(5)
+ counter1 += 7
+ println(counter1) // => Counter(value=7)
+ println(counter1 + counter2) // => Counter(value=12)
+ println(counter1 * counter2) // => Counter(value=35)
+ println(counter2 * 2) // => Counter(value=10)
+ println(counter1 in Counter(5)) // => false
+ println(counter1 in Counter(7)) // => true
+ counter1[26] = 10
+ println(counter1) // => Counter(value=36)
+ counter1() // => The value of the counter is 36
+ println(-counter2) // => Counter(value=-5)
+}
+```
+
+### Leituras Adicionais
+
+* [Tutoriais de Kotlin](https://kotlinlang.org/docs/tutorials/)
+* [Experimenta Kotlin no browser](https://play.kotlinlang.org/)
+* [Recursos adicionais](http://kotlin.link/) \ No newline at end of file
diff --git a/pug.html.markdown b/pug.html.markdown
index 1bc49f64..9badee92 100644
--- a/pug.html.markdown
+++ b/pug.html.markdown
@@ -158,13 +158,13 @@ case orderStatus
//- <p class="warn">Your order is pending</p>
//- --INCLUDE--
-//- File path -> "includes/nav.png"
+//- File path -> "includes/nav.pug"
h1 Company Name
nav
a(href="index.html") Home
a(href="about.html") About Us
-//- File path -> "index.png"
+//- File path -> "index.pug"
html
body
include includes/nav.pug
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 8cf1c1dd..1ceaecf9 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -59,9 +59,9 @@ compare 3 2 -- GT
true && (9 >= 19 || 1 < 2) -- true
-- Strings
-"Hellow" :: String -- "Hellow"
+"Hello" :: String -- "Hello"
-- Multiline string without newlines, to run in PSCi use "paste" mode.
-"Hellow\
+"Hello\
\orld" -- "Helloworld"
-- Multiline string with newlines
"""Hello
diff --git a/pyqt.html.markdown b/pyqt.html.markdown
index 6bdb6488..2b331874 100644
--- a/pyqt.html.markdown
+++ b/pyqt.html.markdown
@@ -11,25 +11,25 @@ contributors:
This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192
), some of the code examples should result in the same functionality
-this version just having been done using pyqt!
+this version just having been done using pyqt!
```python
import sys
from PyQt4 import QtGui
-
+
def window():
- # Create an application object
+ # Create an application object
app = QtGui.QApplication(sys.argv)
# Create a widget where our label will be placed in
w = QtGui.QWidget()
- # Add a label to the widget
+ # Add a label to the widget
b = QtGui.QLabel(w)
- # Set some text for the label
+ # Set some text for the label
b.setText("Hello World!")
- # Give some size and placement information
+ # Give some size and placement information
w.setGeometry(100, 100, 200, 50)
b.move(50, 20)
- # Give our window a nice title
+ # Give our window a nice title
w.setWindowTitle("PyQt")
# Have everything display
w.show()
@@ -41,10 +41,10 @@ if __name__ == '__main__':
```
-In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements.
+In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements.
Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -63,7 +63,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# This function should create a dialog window with a button
# that waits to be clicked and then exits the program
def showdialog():
diff --git a/python.html.markdown b/python.html.markdown
index e46d726e..9d97e64d 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -9,14 +9,18 @@ contributors:
- ["Rommel Martinez", "https://ebzzry.io"]
- ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"]
- ["caminsha", "https://github.com/caminsha"]
+ - ["Stanislav Modrak", "https://stanislav.gq"]
+ - ["John Paul Wohlscheid", "https://gitpi.us"]
filename: learnpython.py
---
-Python was created by Guido van Rossum in the early 90s. It is now one of the most popular
-languages in existence. I fell in love with Python for its syntactic clarity. It's basically
-executable pseudocode.
+Python was created by Guido van Rossum in the early 90s. It is now one of the
+most popular languages in existence. I fell in love with Python for its
+syntactic clarity. It's basically executable pseudocode.
-Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the old Python 2.7
+Note: This article applies to Python 3 specifically. Check out
+[here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the
+old Python 2.7
```python
@@ -81,16 +85,29 @@ False - 5 # => -5
# Comparison operators look at the numerical value of True and False
0 == False # => True
-1 == True # => True
+2 > True # => True
2 == True # => False
-5 != False # => True
-# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned
-# Don't mix up with bool(ints) and bitwise and/or (&,|)
+# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False.
+# All other values are True
bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
+bool(set()) # => False
bool(4) # => True
bool(-6) # => True
+
+# Using boolean logical operators on ints casts them to booleans for evaluation,
+# but their non-cast value is returned. Don't mix up with bool(ints) and bitwise
+# and/or (&,|)
+bool(0) # => False
+bool(2) # => True
0 and 2 # => 0
+bool(-5) # => True
+bool(2) # => True
-5 or 0 # => -5
# Equality is ==
@@ -139,10 +156,10 @@ b == a # => True, a's and b's objects are equal
# You can find the length of a string
len("This is a string") # => 16
-# You can also format using f-strings or formatted string literals (in Python 3.6+)
+# Since Python 3.6, you can use f-strings or formatted string literals.
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
-# You can basically put any Python expression inside the braces and it will be output in the string.
+# Any valid Python expression inside these braces is returned to the string.
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
# None is an object
@@ -153,14 +170,6 @@ None # => None
"etc" is None # => False
None is None # => True
-# None, 0, and empty strings/lists/dicts/tuples all evaluate to False.
-# All other values are True
-bool(0) # => False
-bool("") # => False
-bool([]) # => False
-bool({}) # => False
-bool(()) # => False
-
####################################################
## 2. Variables and Collections
####################################################
@@ -176,7 +185,7 @@ print("Hello, World", end="!") # => Hello, World!
input_string_var = input("Enter some data: ") # Returns the data as a string
# There are no declarations, only assignments.
-# Convention is to use lower_case_with_underscores
+# Convention in naming variables is snake_case style
some_var = 5
some_var # => 5
@@ -217,7 +226,7 @@ li[4] # Raises an IndexError
li[1:3] # Return list from index 1 to 3 => [2, 4]
li[2:] # Return list starting from index 2 => [4, 3]
li[:3] # Return list from beginning until index 3 => [1, 2, 4]
-li[::2] # Return list selecting every second entry => [1, 4]
+li[::2] # Return list selecting elements with a step size of 2 => [1, 4]
li[::-1] # Return list in reverse order => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
@@ -289,7 +298,7 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Note keys for dictionaries have to be immutable types. This is to ensure that
# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
-invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+invalid_dict = {[1,2,3]: "123"} # => Yield a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
# Look up values with []
@@ -343,7 +352,7 @@ del filled_dict["one"] # Removes the key "one" from filled dict
# Sets store ... well sets
empty_set = set()
-# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
+# Initialize a set with a bunch of values.
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
@@ -415,7 +424,7 @@ for animal in ["dog", "cat", "mouse"]:
"""
"range(number)" returns an iterable of numbers
-from zero to the given number
+from zero up to (but excluding) the given number
prints:
0
1
@@ -449,8 +458,7 @@ for i in range(4, 8, 2):
print(i)
"""
-To loop over a list, and retrieve both the index and the value of each item in the list
-prints:
+Loop over a list to retrieve both the index and the value of each list item:
0 dog
1 cat
2 mouse
@@ -477,10 +485,11 @@ try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Refrain from this, provide a recovery (next example).
except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
+ pass # Multiple exceptions can be processed jointly.
+else: # Optional clause to the try/except block. Must follow
+ # all except blocks.
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
@@ -495,6 +504,7 @@ contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w") as file:
file.write(str(contents)) # writes a string to a file
+import json
with open("myfile2.txt", "w") as file:
file.write(json.dumps(contents)) # writes an object to a file
@@ -516,7 +526,8 @@ print(contents)
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object
+ # that implements our Iterable interface.
# We can loop over it.
for i in our_iterable:
@@ -528,15 +539,16 @@ our_iterable[1] # Raises a TypeError
# An iterable is an object that knows how to create an iterator.
our_iterator = iter(our_iterable)
-# Our iterator is an object that can remember the state as we traverse through it.
-# We get the next object with "next()".
+# Our iterator is an object that can remember the state as we traverse through
+# it. We get the next object with "next()".
next(our_iterator) # => "one"
# It maintains state as we iterate.
next(our_iterator) # => "two"
next(our_iterator) # => "three"
-# After the iterator has returned all of its data, it raises a StopIteration exception
+# After the iterator has returned all of its data, it raises a
+# StopIteration exception
next(our_iterator) # Raises StopIteration
# We can also loop over it, in fact, "for" does this implicitly!
@@ -544,7 +556,7 @@ our_iterator = iter(our_iterable)
for i in our_iterator:
print(i) # Prints one, two, three
-# You can grab all the elements of an iterable or iterator by calling list() on it.
+# You can grab all the elements of an iterable or iterator by call of list().
list(our_iterable) # => Returns ["one", "two", "three"]
list(our_iterator) # => Returns [] because state is saved
@@ -591,12 +603,12 @@ all_the_args(1, 2, a=3, b=4) prints:
"""
# When calling functions, you can do the opposite of args/kwargs!
-# Use * to expand tuples and use ** to expand kwargs.
+# Use * to expand args (tuples) and use ** to expand kwargs (dictionaries).
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent: all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent: all_the_args(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
@@ -606,17 +618,19 @@ def swap(x, y):
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
+# (x, y) = swap(x,y) # Again the use of parenthesis is optional.
-# Function Scope
+# global scope
x = 5
def set_x(num):
- # Local var x not the same as global variable x
+ # local scope begins here
+ # local var x not the same as global var x
x = num # => 43
print(x) # => 43
def set_global_x(num):
+ # global indicates that particular var lives in the global scope
global x
print(x) # => 5
x = num # global var x is now set to 6
@@ -624,6 +638,12 @@ def set_global_x(num):
set_x(43)
set_global_x(6)
+"""
+prints:
+ 43
+ 5
+ 6
+"""
# Python has first class functions
@@ -635,6 +655,22 @@ def create_adder(x):
add_10 = create_adder(10)
add_10(3) # => 13
+# Closures in nested functions:
+# We can use the nonlocal keyword to work with variables in nested scope which shouldn't be declared in the inner functions.
+def create_avg():
+ total = 0
+ count = 0
+ def avg(n):
+ nonlocal total, count
+ total += n
+ count += 1
+ return total/count
+ return avg
+avg = create_avg()
+avg(3) # => 3.0
+avg(5) # (3+5)/2 => 4.0
+avg(7) # (8+7)/3 => 5.0
+
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
@@ -646,7 +682,7 @@ list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
# We can use list comprehensions for nice maps and filters
-# List comprehension stores the output as a list which can itself be a nested list
+# List comprehension stores the output as a list (which itself may be nested).
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
@@ -665,8 +701,8 @@ print(math.sqrt(16)) # => 4.0
# You can get specific functions from a module
from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+print(ceil(3.7)) # => 4
+print(floor(3.7)) # => 3
# You can import all functions from a module.
# Warning: this is not recommended
@@ -706,14 +742,16 @@ class Human:
# Note that the double leading and trailing underscores denote objects
# or attributes that are used by Python but that live in user-controlled
# namespaces. Methods(or objects or attributes) like: __init__, __str__,
- # __repr__ etc. are called special methods (or sometimes called dunder methods)
- # You should not invent such names on your own.
+ # __repr__ etc. are called special methods (or sometimes called dunder
+ # methods). You should not invent such names on your own.
def __init__(self, name):
# Assign the argument to the instance's name attribute
self.name = name
# Initialize property
- self._age = 0
+ self._age = 0 # the leading underscore indicates the "age" property is
+ # intended to be used internally
+ # do not rely on this to be enforced: it's a hint to other devs
# An instance method. All methods take "self" as the first argument
def say(self, msg):
@@ -761,7 +799,7 @@ if __name__ == '__main__':
i.say("hi") # "Ian: hi"
j = Human("Joel")
j.say("hello") # "Joel: hello"
- # i and j are instances of type Human, or in other words: they are Human objects
+ # i and j are instances of type Human; i.e., they are Human objects.
# Call our class method
i.say(i.get_species()) # "Ian: H. sapiens"
@@ -798,8 +836,8 @@ if __name__ == '__main__':
# "species", "name", and "age", as well as methods, like "sing" and "grunt"
# from the Human class, but can also have its own unique properties.
-# To take advantage of modularization by file you could place the classes above in their own files,
-# say, human.py
+# To take advantage of modularization by file you could place the classes above
+# in their own files, say, human.py
# To import functions from other files use the following format
# from "filename-without-extension" import "function-or-class"
@@ -856,7 +894,8 @@ if __name__ == '__main__':
if type(sup) is Superhero:
print('I am a superhero')
- # Get the Method Resolution search Order used by both getattr() and super()
+ # Get the "Method Resolution Order" used by both getattr() and super()
+ # (the order in which classes are searched for an attribute or method)
# This attribute is dynamic and can be updated
print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
# => <class 'human.Human'>, <class 'object'>)
@@ -923,8 +962,8 @@ class Batman(Superhero, Bat):
# However we are dealing with multiple inheritance here, and super()
# only works with the next base class in the MRO list.
# So instead we explicitly call __init__ for all ancestors.
- # The use of *args and **kwargs allows for a clean way to pass arguments,
- # with each parent "peeling a layer of the onion".
+ # The use of *args and **kwargs allows for a clean way to pass
+ # arguments, with each parent "peeling a layer of the onion".
Superhero.__init__(self, 'anonymous', movie=True,
superpowers=['Wealthy'], *args, **kwargs)
Bat.__init__(self, *args, can_fly=False, **kwargs)
@@ -938,8 +977,7 @@ class Batman(Superhero, Bat):
if __name__ == '__main__':
sup = Batman()
- # Get the Method Resolution search Order used by both getattr() and super().
- # This attribute is dynamic and can be updated
+ # The Method Resolution Order
print(Batman.__mro__) # => (<class '__main__.Batman'>,
# => <class 'superhero.Superhero'>,
# => <class 'human.Human'>,
@@ -996,39 +1034,72 @@ gen_to_list = list(values)
print(gen_to_list) # => [-1, -2, -3, -4, -5]
-# Decorators
-# In this example `beg` wraps `say`. If say_please is True then it
-# will change the returned message.
-from functools import wraps
+# Decorators are a form of syntactic sugar.
+# They make code easier to read while accomplishing clunky syntax.
+# Wrappers are one type of decorator.
+# They're really useful for adding logging to existing functions without needing to modify them.
-def beg(target_function):
- @wraps(target_function)
+def log_function(func):
def wrapper(*args, **kwargs):
- msg, say_please = target_function(*args, **kwargs)
- if say_please:
- return "{} {}".format(msg, "Please! I am poor :(")
- return msg
-
+ print("Entering function", func.__name__)
+ result = func(*args, **kwargs)
+ print("Exiting function", func.__name__)
+ return result
return wrapper
+@log_function # equivalent:
+def my_function(x,y): # def my_function(x,y):
+ return x+y # return x+y
+ # my_function = log_function(my_function)
+# The decorator @log_function tells us as we begin reading the function definition
+# for my_function that this function will be wrapped with log_function.
+# When function definitions are long, it can be hard to parse the non-decorated
+# assignment at the end of the definition.
-@beg
-def say(say_please=False):
- msg = "Can you buy me a beer?"
- return msg, say_please
+my_function(1,2) # => "Entering function my_function"
+ # => "3"
+ # => "Exiting function my_function"
+# But there's a problem.
+# What happens if we try to get some information about my_function?
-print(say()) # Can you buy me a beer?
-print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
-```
+print(my_function.__name__) # => 'wrapper'
+print(my_function.__code__.co_argcount) # => 0. The argcount is 0 because both arguments in wrapper()'s signature are optional.
+
+# Because our decorator is equivalent to my_function = log_function(my_function)
+# we've replaced information about my_function with information from wrapper
+
+# Fix this using functools
+
+from functools import wraps
-## Ready For More?
+def log_function(func):
+ @wraps(func) # this ensures docstring, function name, arguments list, etc. are all copied
+ # to the wrapped function - instead of being replaced with wrapper's info
+ def wrapper(*args, **kwargs):
+ print("Entering function", func.__name__)
+ result = func(*args, **kwargs)
+ print("Exiting function", func.__name__)
+ return result
+ return wrapper
+
+@log_function
+def my_function(x,y):
+ return x+y
+
+my_function(1,2) # => "Entering function my_function"
+ # => "3"
+ # => "Exiting function my_function"
+
+print(my_function.__name__) # => 'my_function'
+print(my_function.__code__.co_argcount) # => 2
+
+```
### Free Online
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
-* [Ideas for Python Projects](http://pythonpracticeprojects.com)
* [The Official Docs](https://docs.python.org/3/)
* [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/)
* [Python Course](https://www.python-course.eu)
diff --git a/qsharp.html.markdown b/qsharp.html.markdown
index 10015d7f..04e697a4 100644
--- a/qsharp.html.markdown
+++ b/qsharp.html.markdown
@@ -9,7 +9,7 @@ filename: LearnQSharp.qs
Q# is a high-level domain-specific language which enables developers to write quantum algorithms. Q# programs can be executed on a quantum simulator running on a classical computer and (in future) on quantum computers.
-```C#
+```c#
// Single-line comments start with //
diff --git a/r.html.markdown b/r.html.markdown
index e90d5a97..a063cc2f 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["e99n09", "http://github.com/e99n09"]
- ["isomorphismes", "http://twitter.com/isomorphisms"]
- ["kalinn", "http://github.com/kalinn"]
+ - ["mribeirodantas", "http://github.com/mribeirodantas"]
filename: learnr.r
---
@@ -11,7 +12,7 @@ R is a statistical computing language. It has lots of libraries for uploading an
```r
-# Comments start with number symbols.
+# Comments start with hash signs, also known as number symbols (#).
# You can't make multi-line comments,
# but you can stack multiple comments like so.
@@ -29,13 +30,13 @@ R is a statistical computing language. It has lots of libraries for uploading an
# R without understanding anything about programming. Do not worry
# about understanding everything the code does. Just enjoy!
-data() # browse pre-loaded data sets
-data(rivers) # get this one: "Lengths of Major North American Rivers"
-ls() # notice that "rivers" now appears in the workspace
-head(rivers) # peek at the data set
+data() # browse pre-loaded data sets
+data(rivers) # get this one: "Lengths of Major North American Rivers"
+ls() # notice that "rivers" now appears in the workspace
+head(rivers) # peek at the data set
# 735 320 325 392 524 450
-length(rivers) # how many rivers were measured?
+length(rivers) # how many rivers were measured?
# 141
summary(rivers) # what are some summary statistics?
# Min. 1st Qu. Median Mean 3rd Qu. Max.
@@ -91,14 +92,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 82 | 2
# make a histogram:
-hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters
-hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later
+hist(rivers, col = "#333333", border = "white", breaks = 25)
+hist(log(rivers), col = "#333333", border = "white", breaks = 25)
+# play around with these parameters, you'll do more plotting later
# Here's another neat data set that comes pre-loaded. R has tons of these.
data(discoveries)
-plot(discoveries, col="#333333", lwd=3, xlab="Year",
+plot(discoveries, col = "#333333", lwd = 3, xlab = "Year",
main="Number of important discoveries per year")
-plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
+plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year",
main="Number of important discoveries per year")
# Rather than leaving the default ordering (by year),
@@ -109,7 +111,7 @@ sort(discoveries)
# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
-stem(discoveries, scale=2)
+stem(discoveries, scale = 2)
#
# The decimal point is at the |
#
@@ -134,7 +136,7 @@ summary(discoveries)
# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
-round(runif(7, min=.5, max=6.5))
+round(runif(7, min = .5, max = 6.5))
# 1 4 6 1 4 6 4
# Your numbers will differ from mine unless we set the same random.seed(31337)
@@ -157,69 +159,68 @@ rnorm(9)
# INTEGERS
# Long-storage integers are written with L
-5L # 5
-class(5L) # "integer"
+5L # 5
+class(5L) # "integer"
# (Try ?class for more information on the class() function.)
# In R, every single value, like 5L, is considered a vector of length 1
-length(5L) # 1
+length(5L) # 1
# You can have an integer vector with length > 1 too:
-c(4L, 5L, 8L, 3L) # 4 5 8 3
-length(c(4L, 5L, 8L, 3L)) # 4
-class(c(4L, 5L, 8L, 3L)) # "integer"
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
# NUMERICS
# A "numeric" is a double-precision floating-point number
-5 # 5
-class(5) # "numeric"
+5 # 5
+class(5) # "numeric"
# Again, everything in R is a vector;
# you can make a numeric vector with more than one element
-c(3,3,3,2,2,1) # 3 3 3 2 2 1
+c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1
# You can use scientific notation too
-5e4 # 50000
-6.02e23 # Avogadro's number
-1.6e-35 # Planck length
+5e4 # 50000
+6.02e23 # Avogadro's number
+1.6e-35 # Planck length
# You can also have infinitely large or small numbers
-class(Inf) # "numeric"
-class(-Inf) # "numeric"
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
# this obviates Z-score tables.
# BASIC ARITHMETIC
# You can do arithmetic with numbers
# Doing arithmetic on a mix of integers and numerics gives you another numeric
-10L + 66L # 76 # integer plus integer gives integer
-53.2 - 4 # 49.2 # numeric minus numeric gives numeric
-2.0 * 2L # 4 # numeric times integer gives numeric
-3L / 4 # 0.75 # integer over numeric gives numeric
-3 %% 2 # 1 # the remainder of two numerics is another numeric
+10L + 66L # 76 # integer plus integer gives integer
+53.2 - 4 # 49.2 # numeric minus numeric gives numeric
+2.0 * 2L # 4 # numeric times integer gives numeric
+3L / 4 # 0.75 # integer over numeric gives numeric
+3 %% 2 # 1 # the remainder of two numerics is another numeric
# Illegal arithmetic yields you a "not-a-number":
-0 / 0 # NaN
-class(NaN) # "numeric"
+0 / 0 # NaN
+class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
-c(1,2,3) + c(1,2,3) # 2 4 6
+c(1, 2, 3) + c(1, 2, 3) # 2 4 6
# Since a single number is a vector of length one, scalars are applied
# elementwise to vectors
-(4 * c(1,2,3) - 2) / 2 # 1 3 5
+(4 * c(1, 2, 3) - 2) / 2 # 1 3 5
# Except for scalars, use caution when performing arithmetic on vectors with
# different lengths. Although it can be done,
-c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
-# Matching lengths is better practice and easier to read
-c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
+c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6
+# Matching lengths is better practice and easier to read most times
+c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6
# CHARACTERS
# There's no difference between strings and characters in R
-"Horatio" # "Horatio"
-class("Horatio") # "character"
-class('H') # "character"
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class("H") # "character"
# Those were both character vectors of length 1
# Here is a longer one:
-c('alef', 'bet', 'gimmel', 'dalet', 'he')
-# =>
-# "alef" "bet" "gimmel" "dalet" "he"
+c("alef", "bet", "gimmel", "dalet", "he")
+# => "alef" "bet" "gimmel" "dalet" "he"
length(c("Call","me","Ishmael")) # 3
# You can do regex operations on character vectors:
-substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
# R has several built-in character vectors:
letters
@@ -230,32 +231,33 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D
# LOGICALS
# In R, a "logical" is a boolean
-class(TRUE) # "logical"
-class(FALSE) # "logical"
+
+class(TRUE) # "logical"
+class(FALSE) # "logical"
# Their behavior is normal
-TRUE == TRUE # TRUE
-TRUE == FALSE # FALSE
-FALSE != FALSE # FALSE
-FALSE != TRUE # TRUE
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
# Missing data (NA) is logical, too
-class(NA) # "logical"
+class(NA) # "logical"
# Use | and & for logic operations.
# OR
-TRUE | FALSE # TRUE
+TRUE | FALSE # TRUE
# AND
-TRUE & FALSE # FALSE
+TRUE & FALSE # FALSE
# Applying | and & to vectors returns elementwise logic operations
-c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
-c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
+c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE
+c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
-isTRUE(TRUE) # TRUE
+isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
-c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
-c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
-# Factors can be ordered (like childrens' grade levels) or unordered (like colors)
+# Factors can be ordered (like grade levels) or unordered (like colors)
factor(c("blue", "blue", "green", NA, "blue"))
# blue blue green <NA> blue
# Levels: blue green
@@ -263,31 +265,27 @@ factor(c("blue", "blue", "green", NA, "blue"))
# Note that missing data does not enter the levels
levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green"
# If a factor vector has length 1, its levels will have length 1, too
-length(factor("green")) # 1
+length(factor("green")) # 1
length(levels(factor("green"))) # 1
# Factors are commonly seen in data frames, a data structure we will cover later
-data(infert) # "Infertility after Spontaneous and Induced Abortion"
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
# NULL
# "NULL" is a weird one; use it to "blank out" a vector
-class(NULL) # NULL
+class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
-parakeet
-# =>
-# [1] "beak" "feathers" "wings" "eyes"
+parakeet # "beak" "feathers" "wings" "eyes"
parakeet <- NULL
-parakeet
-# =>
-# NULL
+parakeet # NULL
# TYPE COERCION
# Type-coercion is when you force a value to take on a different type
-as.character(c(6, 8)) # "6" "8"
-as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
# If you put elements of different types into a vector, weird coercions happen:
-c(TRUE, 4) # 1 4
-c("dog", TRUE, 4) # "dog" "TRUE" "4"
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
as.numeric("Bilbo")
# =>
# [1] NA
@@ -309,14 +307,15 @@ as.numeric("Bilbo")
# VARIABLES
# Lots of way to assign stuff:
-x = 5 # this is possible
-y <- "1" # this is preferred
-TRUE -> z # this works but is weird
+x = 5 # this is possible
+y <- "1" # this is preferred traditionally
+TRUE -> z # this works but is weird
+# Refer to the Internet for the behaviors and preferences about them.
# LOOPS
# We've got for loops
for (i in 1:4) {
- print(i)
+ print(i)
}
# We've got while loops
a <- 10
@@ -341,11 +340,11 @@ if (4 > 3) {
# FUNCTIONS
# Defined like so:
jiggle <- function(x) {
- x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise
+ x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise
return(x)
}
# Called like any other R function:
-jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
+jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
@@ -357,39 +356,39 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
# Let's start from the very beginning, and with something you already know: vectors.
vec <- c(8, 9, 10, 11)
-vec # 8 9 10 11
+vec # 8 9 10 11
# We ask for specific elements by subsetting with square brackets
# (Note that R starts counting from 1)
-vec[1] # 8
-letters[18] # "r"
-LETTERS[13] # "M"
-month.name[9] # "September"
-c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
# We can also search for the indices of specific components,
-which(vec %% 2 == 0) # 1 3
+which(vec %% 2 == 0) # 1 3
# grab just the first or last few entries in the vector,
-head(vec, 1) # 8
-tail(vec, 2) # 10 11
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
# or figure out if a certain value is in the vector
-any(vec == 10) # TRUE
+any(vec == 10) # TRUE
# If an index "goes over" you'll get NA:
-vec[6] # NA
+vec[6] # NA
# You can find the length of your vector with length()
-length(vec) # 4
+length(vec) # 4
# You can perform operations on entire vectors or subsets of vectors
-vec * 4 # 32 36 40 44
-vec[2:3] * 5 # 45 50
-any(vec[2:3] == 8) # FALSE
+vec * 4 # 32 36 40 44
+vec[2:3] * 5 # 45 50
+any(vec[2:3] == 8) # FALSE
# and R has many built-in functions to summarize vectors
-mean(vec) # 9.5
-var(vec) # 1.666667
-sd(vec) # 1.290994
-max(vec) # 11
-min(vec) # 8
-sum(vec) # 38
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
# Some more nice built-ins:
-5:15 # 5 6 7 8 9 10 11 12 13 14 15
-seq(from=0, to=31337, by=1337)
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from = 0, to = 31337, by = 1337)
# =>
# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
@@ -397,7 +396,7 @@ seq(from=0, to=31337, by=1337)
# TWO-DIMENSIONAL (ALL ONE CLASS)
# You can make a matrix out of entries all of the same type like so:
-mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6))
mat
# =>
# [,1] [,2]
@@ -405,13 +404,13 @@ mat
# [2,] 2 5
# [3,] 3 6
# Unlike a vector, the class of a matrix is "matrix", no matter what's in it
-class(mat) # => "matrix"
+class(mat) # "matrix" "array"
# Ask for the first row
-mat[1,] # 1 4
+mat[1, ] # 1 4
# Perform operation on the first column
-3 * mat[,1] # 3 6 9
+3 * mat[, 1] # 3 6 9
# Ask for a specific cell
-mat[3,2] # 6
+mat[3, 2] # 6
# Transpose the whole matrix
t(mat)
@@ -437,14 +436,14 @@ mat2
# [2,] "2" "cat"
# [3,] "3" "bird"
# [4,] "4" "dog"
-class(mat2) # matrix
+class(mat2) # matrix
# Again, note what happened!
# Because matrices must contain entries all of the same class,
# everything got converted to the character class
-c(class(mat2[,1]), class(mat2[,2]))
+c(class(mat2[, 1]), class(mat2[, 2]))
# rbind() sticks vectors together row-wise to make a matrix
-mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4))
mat3
# =>
# [,1] [,2] [,3] [,4]
@@ -458,11 +457,11 @@ mat3
# This data structure is so useful for statistical programming,
# a version of it was added to Python in the package "pandas".
-students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
- c(3,2,2,1,0,-1),
- c("H", "G", "G", "R", "S", "G"))
+students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"),
+ c( 3, 2, 2, 1, 0, -1),
+ c( "H", "G", "G", "R", "S", "G"))
names(students) <- c("name", "year", "house") # name the columns
-class(students) # "data.frame"
+class(students) # "data.frame"
students
# =>
# name year house
@@ -472,21 +471,22 @@ students
# 4 Cho 1 R
# 5 Draco 0 S
# 6 Ginny -1 G
-class(students$year) # "numeric"
-class(students[,3]) # "factor"
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
# find the dimensions
-nrow(students) # 6
-ncol(students) # 3
-dim(students) # 6 3
-# The data.frame() function converts character vectors to factor vectors
-# by default; turn this off by setting stringsAsFactors = FALSE when
-# you create the data.frame
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# The data.frame() function used to convert character vectors to factor
+# vectors by default; This has changed in R 4.0.0. If your R version is
+# older, turn this off by setting stringsAsFactors = FALSE when you
+# create the data.frame
?data.frame
# There are many twisty ways to subset data frames, all subtly unalike
-students$year # 3 2 2 1 0 -1
-students[,2] # 3 2 2 1 0 -1
-students[,"year"] # 3 2 2 1 0 -1
+students$year # 3 2 2 1 0 -1
+students[, 2] # 3 2 2 1 0 -1
+students[, "year"] # 3 2 2 1 0 -1
# An augmented version of the data.frame structure is the data.table
# If you're working with huge or panel data, or need to merge a few data
@@ -503,19 +503,19 @@ students # note the slightly different print-out
# 4: Cho 1 R
# 5: Draco 0 S
# 6: Ginny -1 G
-students[name=="Ginny"] # get rows with name == "Ginny"
+students[name == "Ginny"] # get rows with name == "Ginny"
# =>
# name year house
# 1: Ginny -1 G
-students[year==2] # get rows with year == 2
+students[year == 2] # get rows with year == 2
# =>
# name year house
# 1: Fred 2 G
# 2: George 2 G
# data.table makes merging two data sets easy
# let's make another data.table to merge with students
-founders <- data.table(house=c("G","H","R","S"),
- founder=c("Godric","Helga","Rowena","Salazar"))
+founders <- data.table(house = c("G" , "H" , "R" , "S"),
+ founder = c("Godric", "Helga", "Rowena", "Salazar"))
founders
# =>
# house founder
@@ -526,8 +526,8 @@ founders
setkey(students, house)
setkey(founders, house)
students <- founders[students] # merge the two data sets by matching "house"
-setnames(students, c("house","houseFounderName","studentName","year"))
-students[,order(c("name","year","house","houseFounderName")), with=F]
+setnames(students, c("house", "houseFounderName", "studentName", "year"))
+students[, order(c("name", "year", "house", "houseFounderName")), with = F]
# =>
# studentName year house houseFounderName
# 1: Fred 2 G Godric
@@ -538,7 +538,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F]
# 6: Draco 0 S Salazar
# data.table makes summary tables easy
-students[,sum(year),by=house]
+students[, sum(year), by = house]
# =>
# house V1
# 1: G 3
@@ -571,7 +571,7 @@ students[studentName != "Draco"]
# 5: R Cho 1
# Using data.frame:
students <- as.data.frame(students)
-students[students$house != "G",]
+students[students$house != "G", ]
# =>
# house houseFounderName studentName year
# 4 H Helga Cedric 3
@@ -583,13 +583,13 @@ students[students$house != "G",]
# Arrays creates n-dimensional tables
# All elements must be of the same type
# You can make a two-dimensional table (sort of like a matrix)
-array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4))
# =>
# [,1] [,2] [,3] [,4]
# [1,] 1 4 8 3
# [2,] 2 5 9 6
# You can use array to make three-dimensional matrices too
-array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2))
# =>
# , , 1
#
@@ -609,7 +609,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
# Finally, R has lists (of vectors)
list1 <- list(time = 1:40)
-list1$price = c(rnorm(40,.5*list1$time,4)) # random
+list1$price = c(rnorm(40, .5*list1$time, 4)) # random
list1
# You can get items in the list like so
list1$time # one way
@@ -682,7 +682,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file
#########################
# Linear regression!
-linearModel <- lm(price ~ time, data = list1)
+linearModel <- lm(price ~ time, data = list1)
linearModel # outputs result of regression
# =>
# Call:
@@ -719,7 +719,7 @@ summary(linearModel)$coefficients # another way to extract results
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
# time 0.4943490 0.06379348 7.74920901 2.440008e-09
-summary(linearModel)$coefficients[,4] # the p-values
+summary(linearModel)$coefficients[, 4] # the p-values
# =>
# (Intercept) time
# 9.234021e-01 2.440008e-09
@@ -728,8 +728,7 @@ summary(linearModel)$coefficients[,4] # the p-values
# Logistic regression
set.seed(1)
list1$success = rbinom(length(list1$time), 1, .5) # random binary
-glModel <- glm(success ~ time, data = list1,
- family=binomial(link="logit"))
+glModel <- glm(success ~ time, data = list1, family=binomial(link="logit"))
glModel # outputs result of logistic regression
# =>
# Call: glm(formula = success ~ time,
@@ -745,8 +744,10 @@ glModel # outputs result of logistic regression
summary(glModel) # more verbose output from the regression
# =>
# Call:
-# glm(formula = success ~ time,
-# family = binomial(link = "logit"), data = list1)
+# glm(
+# formula = success ~ time,
+# family = binomial(link = "logit"),
+# data = list1)
# Deviance Residuals:
# Min 1Q Median 3Q Max
@@ -780,7 +781,7 @@ plot(linearModel)
# Histograms!
hist(rpois(n = 10000, lambda = 5), col = "thistle")
# Barplots!
-barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow"))
# GGPLOT2
# But these are not even the prettiest of R's plots
@@ -788,10 +789,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
install.packages("ggplot2")
require(ggplot2)
?ggplot2
-pp <- ggplot(students, aes(x=house))
+pp <- ggplot(students, aes(x = house))
pp + geom_bar()
ll <- as.data.table(list1)
-pp <- ggplot(ll, aes(x=time,price))
+pp <- ggplot(ll, aes(x = time, price))
pp + geom_point()
# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)
diff --git a/raku-pod.html.markdown b/raku-pod.html.markdown
index 7e9b6fc3..b008beab 100644
--- a/raku-pod.html.markdown
+++ b/raku-pod.html.markdown
@@ -193,7 +193,7 @@ are C<print>, C<put> and C<say>.
### Comments
Although Pod blocks are ignored by the Rakudo Raku compiler, everything
-indentified as a Pod block will be read and interpreted by Pod renderers. In
+identified as a Pod block will be read and interpreted by Pod renderers. In
order to prevent Pod blocks from being rendered by any renderer, use the
`=comment` directive.
diff --git a/raku.html.markdown b/raku.html.markdown
index a8059791..39bc0e51 100644
--- a/raku.html.markdown
+++ b/raku.html.markdown
@@ -122,7 +122,7 @@ say @array; # OUTPUT: «a 6 bâ¤Â»
# context, and any duplicated keys are deduplicated.
my %hash = 'a' => 1, 'b' => 2;
-# Keys get auto-quoted when the fat comman (`=>`) is used. Trailing commas are
+# Keys get auto-quoted when the fat comma (`=>`) is used. Trailing commas are
# okay.
%hash = a => 1, b => 2, ;
@@ -688,7 +688,7 @@ say (0 or False); # OUTPUT: «Falseâ¤Â».
my ($a, $b, $c, $d, $e) = 1, 0, False, True, 'pi';
say $a && $b && $c; # OUTPUT: «0â¤Â», the first falsey value
say $a && $b && $c; # OUTPUT: «Falseâ¤Â», the first falsey value
-say $a && $d && $e; # OUTPUT: «piâ¤Â», last operand since everthing before is truthy
+say $a && $d && $e; # OUTPUT: «piâ¤Â», last operand since everything before is truthy
# `||` returns the first argument that evaluates to `True`.
say $b || $a || $d; # OUTPUT: «1â¤Â»
@@ -1965,7 +1965,7 @@ say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «Trueâ¤Â»
say so 'aec' ~~ / a b* c /; # OUTPUT: «Falseâ¤Â», "b"(s) are optional, not replaceable.
# `**` - (Unbound) Quantifier
-# If you squint hard enough, you might understand why exponentation is used
+# If you squint hard enough, you might understand why exponentiation is used
# for quantity.
say so 'abc' ~~ / a b**1 c /; # OUTPUT: «Trueâ¤Â», exactly one time
say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «Trueâ¤Â», one to three times
diff --git a/rdf.html.markdown b/rdf.html.markdown
new file mode 100644
index 00000000..5b2105b8
--- /dev/null
+++ b/rdf.html.markdown
@@ -0,0 +1,160 @@
+---
+language: RDF
+filename: learnrdf.ttl
+contributors:
+- ["Bob DuCharme", "http://bobdc.com/"]
+---
+
+RDF (Resource Description Framework) is a [W3C
+standard](https://www.w3.org/TR/2014/REC-rdf11-concepts-20140225/) data
+model. The W3C has standardized several RDF syntaxes; examples below use the
+most popular one, [Turtle](https://www.w3.org/TR/turtle/).
+
+One nice advantage of Turtle files is that if you concatenate any two
+syntactically valid Turtle files, you will have another syntactically valid
+Turtle file. This is one of many things about RDF that ease data integration.
+
+The W3C standard query language for RDF datasets is
+[SPARQL](https://www.w3.org/TR/sparql11-query/).
+
+RDF expresses all facts as three-part {subject, predicate, object} statements
+known as triples. Because the same entity can be the subject of some triples
+and the object of others, a set of triples can represent a graph data
+structure. A large-scale storage system for triples is called a triplestore,
+and falls into the graph database category of NoSQL databases.
+
+RDF subjects and predicates must be URIs (Uniform Resource Identifiers), which
+usually look like URLs but function as identifiers, not locators. The use of
+URIs provides context for resource identifiers to make them unambiguous—for
+example, to tell a book title from a job title.
+
+```
+# The hash symbol is the comment delimiter.
+
+# Turtle triple statements end with periods like natural language sentences.
+
+# These two triples tell us that the mythical Example Company's
+# employee 134 has a hire date of 2022-11-12 and a family name of Smith:
+
+<http://example.com/emp134> <http://example.com/hireDate> "2022-11-12" .
+<http://example.com/emp134> <http://example.com/familyName> "Smith" .
+
+# Declaring prefixes to stand in for namespaces reduces verbosity. These
+# declarations typically go at the beginning of the file, but the only
+# requirement is that they come before the first use of the prefix they declare.
+
+@prefix ex: <http://example.com/> .
+ex:emp134 ex:hireDate "2022-11-12" .
+ex:emp134 ex:familyName "Smith" .
+
+# A semicolon means that the next triple uses the same subject as the last
+# one. This is handy for listing data about a single resource. The following
+# example means the same thing as the previous one.
+
+@prefix ex: <http://example.com/> .
+ex:emp134 ex:hireDate "2022-11-12" ;
+ ex:familyName "Smith" .
+
+# A comma means that the next triple has the same subject and predicate as
+# the previous one.
+
+ex:emp134 ex:nickname "Smithy", "Skipper", "Big J".
+
+# Three single or double quote marks at the beginning and end of a value let
+# you define a multi-line string value.
+
+ex:emp134 ex:description """
+Skipper joined the company in November.
+
+He always has a joke for everyone.""" .
+
+# Using URIs from existing standard vocabulary namespaces eases both data
+# integration and interoperability with the large amount of RDF that already
+# exists. Mixing and matching of standard and local custom namespaces is
+# common.
+
+@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .
+ex:emp134 ex:hireDate "2022-11-12" ;
+ vcard:family-name "Smith" .
+
+# Related RDF standards provide vocabularies that are popular for basic
+# facts. The rdfs:label predicate from the RDF Schema standard is a common
+# way to indicate a human-readable name.
+
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ex:hireDate rdfs:label "hire date" .
+
+# String object values can include language codes, making
+# multi-lingual representation of entities easier for applications
+# reading the data (for example, when generating a user interface).
+
+ex:hireDate rdfs:label "hire date"@en, "date d'embauche"@fr .
+
+# Representing a triple's object with a URI (or prefixed name) is not required
+# but lets you connect up triples into a graph.
+
+ex:emp134 vcard:family-name "Smith" .
+ex:emp113 vcard:family-name "Jones" ;
+ ex:reportsTo ex:emp134 .
+
+# Objects can be datatypes from the XML Schema part 2 standard or your own
+# custom datatypes.
+
+@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
+ex:emp134 vcard:family-name "Smith"^^xsd:string ; # default data type
+ ex:hireDate "2022-11-12"^^xsd:date ;
+ ex:rating "3.5"^^ex:someCustomType .
+
+# The use of schemas with RDF is optional. Schemas may describe all or a
+# subset of a dataset. They use a vocabulary described by the W3C RDF Schema
+# (RDFS) standard, usually with a prefix of rdfs.
+
+# These schemas are descriptive, to ease the accommodation of new
+# datasets, not proscriptive rules about how new data should be
+# created. The following declares a class. (Note that RDFS is itself
+# expressed in triples.)
+
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+ex:Person rdf:type rdfs:Class .
+
+# The following triple means the same as the preceding one but
+# uses a Turtle shortcut for terseness and more readability.
+
+ex:Person a rdfs:Class .
+
+# That last triple declares that ex:Person is an instance of a class, and the
+# following declares that employee 113 is an instance of the class Employee.
+
+ex:emp113 a ex:Employee .
+
+# The first triple below is actually unnecessary because a typical
+# RDFS processor will infer from the second one that ex:Employee is a
+# class. (Only a subset of RDF parsers perform RDFS inferencing.)
+
+ex:Employee a rdfs:Class .
+ex:Employee rdfs:subClassOf ex:Person .
+
+# An RDF parser that reads the last four triples shown and understands
+# RDFS will infer that ex:emp113 is an instance of ex:Person, because
+# it's an instance of ex:Employee, a subclass of ex:Person.
+
+# RDFS lets you declare properties and associate them with classes.
+# Properties are first class resources and don't "belong" to classes
+# in the object-oriented sense. rdfs:domain means "the following object
+# class uses the property named by this triple's subject". rdfs:range
+# means "the property named by this triple's subject will have a value of
+# the following class or type".
+
+ex:birthday rdf:type rdf:Property ;
+ rdfs:domain ex:Person ;
+ rdfs:range xsd:date .
+
+```
+
+## Further Reading
+
+* [RDF Primer — Turtle version](https://www.w3.org/2007/02/turtle/primer/) from the W3C
+* [What is RDF?](https://www.bobdc.com/blog/whatisrdf/) on bobdc.com
+* [What is RDFS?](https://www.bobdc.com/blog/whatisrdfs/) on bobdc.com
+* [Introduction to RDF and SPARQL](https://data.europa.eu/sites/default/files/d2.1.2_training_module_1.3_introduction_to_rdf_sparql_en_edp.pdf) at data.europa.eu
+
diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown
index 32ba9620..77052379 100644
--- a/ro-ro/clojure-ro.html.markdown
+++ b/ro-ro/clojure-ro.html.markdown
@@ -380,7 +380,7 @@ Clojuredocs.org contine documentatie cu exemple pentru majoritatea functiilor de
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure este o metoda excelenta pentru a exersa Clojure/FP (Programarea Functionala):
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org are un numar de article pentru incepatori:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown
index 10fec3c5..60500d64 100644
--- a/ro-ro/elixir-ro.html.markdown
+++ b/ro-ro/elixir-ro.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -22,7 +22,7 @@ posibilități.
# Pentru comentarii pe mai multe linii nu există sintaxă separată,
# de aceea folosiți mai multe linii cu comentarii.
-# Pentru a folosi shell-ul elixir utilizați comanda `iex`.
+# Pentru a folosi shell-ul Elixir utilizați comanda `iex`.
# Compilați modulele cu comanda `elixirc`.
# Ambele comenzi vor lucra în terminal, dacă ați instalat Elixir corect.
diff --git a/rst.html.markdown b/rst.html.markdown
index 56d54501..8a730c7a 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -8,7 +8,7 @@ filename: restructuredtext.rst
RST, Restructured Text, is a file format created by the Python community to write documentation. It is part of [Docutils](https://docutils.sourceforge.io/rst.html).
-RST is a markdown language like HTML but is much more lightweight and easier to read.
+RST is a markup language like HTML but is much more lightweight and easier to read.
## Installation
@@ -33,7 +33,7 @@ $ pip install docutils
A simple example of the file syntax:
```
-.. Lines starting with two dots are special commands. But if no command can be found, the line is considered as a comment
+.. Lines starting with two dots are special commands. But if no command can be found, the line is considered as a comment.
=========================================================
Main titles are written using equals signs over and under
@@ -80,12 +80,12 @@ France Paris
Japan Tokyo
=========== ========
-More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :)
+More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this. :)
There are multiple ways to make links:
- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text).
-- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)
+- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link).
- By making a more Markdown-like link: `Github <https://github.com/>`_ .
.. _Github: https://github.com/
diff --git a/ru-ru/asymptotic-notation-ru.html.markdown b/ru-ru/asymptotic-notation-ru.html.markdown
index 7fd02c47..cb276ec1 100644
--- a/ru-ru/asymptotic-notation-ru.html.markdown
+++ b/ru-ru/asymptotic-notation-ru.html.markdown
@@ -48,7 +48,7 @@ f(n) — Ð²Ñ€ÐµÐ¼Ñ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ. Тогда Ð´Ð»Ñ Ð´Ð°Ð½Ð½Ð¾Ð³Ð¾ алÐ
С помощью О-Ñимволики можно оценить функцию или алгоритм
неÑколькими различными ÑпоÑобами. Ðапример, можно оценить алгоритм иÑходÑ
из нижней оценки, верхней оценки, тождеÑтвенной оценки. Чаще вÑего вÑтречаетÑÑ
-анализ на оÑнове верхней оценки. Как правило не иÑпользуетÑÑ Ð½Ð¸Ð¶Ð½ÑÑ Ð¾Ñ†ÐµÐ½ÐºÐ°,
+анализ на оÑнове верхней оценки. Как правило, не иÑпользуетÑÑ Ð½Ð¸Ð¶Ð½ÑÑ Ð¾Ñ†ÐµÐ½ÐºÐ°,
потому что она не подходит под планируемые уÑловиÑ. Отличный пример — алгоритмы
Ñортировки, оÑобенно добавление Ñлементов в древовидную Ñтруктуру. ÐижнÑÑ Ð¾Ñ†ÐµÐ½ÐºÐ°
большинÑтва таких алгоритмов может быть дана как одна операциÑ. Ð’ то Ð²Ñ€ÐµÐ¼Ñ ÐºÐ°Ðº в
@@ -155,8 +155,8 @@ c (c > 0) и n<sub>0</sub> (n<sub>0</sub> > 0), такие, что `f(n)` >= `c
### Примечание
-ÐÑимптотичеÑкие оценки, Ñделаные при помощи О Большого и Омега Большого, могут
-как ÑвлÑÑ‚ÑŒÑÑ, так и не ÑвлÑÑ‚ÑŒÑÑ Ñ‚Ð¾Ñ‡Ð½Ñ‹Ð¼Ð¸. Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы обозначить, что границы не
+ÐÑимптотичеÑкие оценки, Ñделанные при помощи О Большого и Омега Большого, могут
+как ÑвлÑÑ‚ÑŒÑÑ, так и не ÑвлÑÑ‚ÑŒÑÑ Ñ‚Ð¾Ñ‡Ð½Ñ‹Ð¼Ð¸. Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾ чтобы обозначить, что границы не
ÑвлÑÑŽÑ‚ÑÑ Ð°ÑимптотичеÑки точными, иÑпользуютÑÑ Ð·Ð°Ð¿Ð¸Ñи О Малое и Омега Малое.
### О Малое
diff --git a/ru-ru/binary-search-ru.html.markdown b/ru-ru/binary-search-ru.html.markdown
index 9ed62cb8..ab1a1585 100644
--- a/ru-ru/binary-search-ru.html.markdown
+++ b/ru-ru/binary-search-ru.html.markdown
@@ -55,7 +55,7 @@ def search(arr, x):
### Ðа заметку
-СущеÑтвует и Ð´Ñ€ÑƒÐ³Ð°Ñ Ñ„Ð¾Ñ€Ð¼Ð° двоичного поиÑка, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¼Ð¾Ð¶ÐµÑ‚ÑŒ быть полезна.
+СущеÑтвует и Ð´Ñ€ÑƒÐ³Ð°Ñ Ñ„Ð¾Ñ€Ð¼Ð° двоичного поиÑка, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¼Ð¾Ð¶ÐµÑ‚ быть полезна.
## Ðа почитать
diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown
index 3acfafa3..43e9e6a3 100644
--- a/ru-ru/c++-ru.html.markdown
+++ b/ru-ru/c++-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-ru.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
@@ -17,7 +17,7 @@ C++ - компилируемый, ÑтатичеÑки типизированнÑ
- "Ð»ÑƒÑ‡ÑˆÐ°Ñ Ð·Ð°Ð¼ÐµÐ½Ð° C"
- Ñзык Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ¾Ð¹ абÑтракции данных
-- Ñзык Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ¾Ð¹ объектно-ориентированого программированиÑ
+- Ñзык Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ¾Ð¹ объектно-ориентированного программированиÑ
- Ñзык Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ¾Ð¹ обобщенного программированиÑ
Ð¥Ð¾Ñ‚Ñ ÐµÐ³Ð¾ ÑинтакÑÐ¸Ñ Ð¼Ð¾Ð¶ÐµÑ‚ показатьÑÑ Ð±Ð¾Ð»ÐµÐµ трудным или Ñложным Ð´Ð»Ñ Ð¿Ð¾Ð½Ð¸Ð¼Ð°Ð½Ð¸Ñ, чем в более Ñовременных Ñзыках,
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index cc68d620..a146a76b 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: c
+language: C
filename: learnc-ru.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
@@ -476,7 +476,7 @@ void str_reverse_through_pointer(char *str_in) {
ЕÑли у Ð²Ð°Ñ Ð¿Ð¾ÑвилÑÑ Ð²Ð¾Ð¿Ñ€Ð¾Ñ, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com).
Очень важно иÑпользовать правильные отÑтупы и Ñтавить пробелы в нужных меÑтах.
-Читаемый код лучше чем краÑивый или быÑтрый код.
+Читаемый код лучше, чем краÑивый или быÑтрый код.
Чтобы научитьÑÑ Ð¿Ð¸Ñать хороший код, почитайте [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
Также не забывайте, что [Google](http://google.com) и [ЯндекÑ](http://yandex.ru) – ваши хорошие друзьÑ.
diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown
index 19233d23..66986fa0 100644
--- a/ru-ru/clojure-ru.html.markdown
+++ b/ru-ru/clojure-ru.html.markdown
@@ -421,7 +421,7 @@ Clojuredocs.org — Ñайт документации Ñзыка Ñ Ð¿Ñ€Ð¸Ð¼ÐµÑ€
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure — отличный ÑпоÑоб закрепить навыки Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð½Ð° clojure, Ñ€ÐµÑˆÐ°Ñ Ð·Ð°Ð´Ð°Ñ‡Ð¸ вмеÑте Ñ ÐºÐ¾Ð»Ð»ÐµÐ³Ð°Ð¼Ð¸ Ñо вÑего мира:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org (да, именно) неплохой перечень Ñтатей Ð´Ð»Ñ Ð½Ð°Ñ‡Ð¸Ð½Ð°ÑŽÑ‰Ð¸Ñ…:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/ru-ru/common-lisp-ru.html.markdown b/ru-ru/common-lisp-ru.html.markdown
index d5f9bf0e..0490ee30 100644
--- a/ru-ru/common-lisp-ru.html.markdown
+++ b/ru-ru/common-lisp-ru.html.markdown
@@ -14,7 +14,8 @@ Common Lisp - мультипарадигменный Ñзык программи
Ñпектра задач.
Его чаÑтенько называют программируемым Ñзыком программированиÑ.
-Ð˜Ð´ÐµÐ°Ð»ÑŒÐ½Ð°Ñ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²Ð½Ð°Ñ Ñ‚Ð¾Ñ‡ÐºÐ° - книга [Common Lisp на практике (перевод)](http://lisper.ru/pcl/).
+Ð˜Ð´ÐµÐ°Ð»ÑŒÐ½Ð°Ñ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²Ð½Ð°Ñ Ñ‚Ð¾Ñ‡ÐºÐ° - книга
+[Common Lisp на практике (перевод)](https://github.com/pcl-ru/pcl-ru/releases/download/v1.1/pcl-ru.pdf).
Ещё одна популÑÑ€Ð½Ð°Ñ ÐºÐ½Ð¸Ð³Ð° [Land of Lisp](http://landoflisp.com/).
И одна из поÑледних книг [Common Lisp Recipes](http://weitz.de/cl-recipes/) вобрала в ÑÐµÐ±Ñ Ð»ÑƒÑ‡ÑˆÐ¸Ðµ
архитектурные Ñ€ÐµÑˆÐµÐ½Ð¸Ñ Ð½Ð° оÑнове опыта коммерчеÑкой работки автора.
@@ -674,7 +675,7 @@ nil ; ложь; а ещё пуÑтой ÑпиÑок () тож
## Ð”Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ
Ðа руÑÑком
-- [Practical Common Lisp](http://www.gigamonkeys.com/book/)
+- [Practical Common Lisp](https://github.com/pcl-ru/pcl-ru/releases/download/v1.1/pcl-ru.pdf)
Ðа английÑком
- [Practical Common Lisp](http://www.gigamonkeys.com/book/)
@@ -685,7 +686,7 @@ nil ; ложь; а ещё пуÑтой ÑпиÑок () тож
Ðа руÑÑком
-- [Lisper.ru](http://lisper.ru/)
+- [СообщеÑтво в Telegram](https://t.me/lisp_forever)
Ðа английÑком
diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown
index e0e5e30b..b543bfeb 100644
--- a/ru-ru/css-ru.html.markdown
+++ b/ru-ru/css-ru.html.markdown
@@ -20,12 +20,12 @@ HTML Ñлементы и определÑÑ‚ÑŒ их внешний вид.
**Ð’ÐЖÐО:** Так как результатом Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ CSS ÑвлÑетÑÑ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ внешнего вида
Ñлементов, поÑтарайтеÑÑŒ иÑпользовать CSS-пеÑочницы при изучении Ñзыка.
-Ðапример [dabblet](http://dabblet.com/).
+Ðапример, [dabblet](http://dabblet.com/).
Ð’ данной Ñтатье раÑÑматриваютÑÑ Ð² первую очередь ÑинтакÑÐ¸Ñ Ð¸ общие рекомендации.
```css
-/* Ð”Ð»Ñ ÐºÐ¾Ð¼Ð¼ÐµÐ½Ñ‚Ð°Ñ€Ð¸ÐµÐ² иÑпользуетÑÑ Ñлеш-аÑтериÑк, как на Ñтой Ñтрочке.
+/* Ð”Ð»Ñ ÐºÐ¾Ð¼Ð¼ÐµÐ½Ñ‚Ð°Ñ€Ð¸ÐµÐ² иÑпользуетÑÑ ÑлÑш-аÑтериÑк, как на Ñтой Ñтрочке.
Ð’ CSS нет одноÑтрочных комментариев; вÑе комментарии запиÑываютÑÑ Ñ‚Ð°ÐºÐ¸Ð¼ ÑпоÑобом */
/* ####################
@@ -104,7 +104,7 @@ div.some-parent.class-name {}
.i-am-any-before ~ .this-element {}
-/* СущеÑтвуют пÑевдо-клаÑÑÑ‹, позволÑющие изменÑÑ‚ÑŒ внешний вид Ñлемента
+/* СущеÑтвуют пÑевдоклаÑÑÑ‹, позволÑющие изменÑÑ‚ÑŒ внешний вид Ñлемента
в завиÑимоÑти от Ñобытий, произошедших Ñ Ñлементом */
/* например, когда курÑор наведен на Ñлемент */
diff --git a/ru-ru/elixir-ru.html.markdown b/ru-ru/elixir-ru.html.markdown
index c8c2c060..8dd48ba7 100644
--- a/ru-ru/elixir-ru.html.markdown
+++ b/ru-ru/elixir-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown
index 2fc4ad7c..96fa0941 100644
--- a/ru-ru/forth-ru.html.markdown
+++ b/ru-ru/forth-ru.html.markdown
@@ -10,10 +10,10 @@ lang: ru-ru
Форт Ñоздан Чарлзом Муром в 70-е годы. Это императивный, Ñтековый Ñзык Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¸ Ñреда иÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼. ИÑпользовалÑÑ Ð² таких проектах как Open Firmware. Продолжает применÑÑ‚ÑÑ Ð² проектах. ПрименÑетÑÑ Ð² ÐÐСÐ.
-Внимание: Ñта материал иÑпользует реализацию Форта - Gforth, но Ð±Ð¾Ð»ÑŒÑˆÐ°Ñ Ñ‡Ð°ÑÑ‚ÑŒ напиÑанного будет работать в других Ñредах.
+Внимание: Ñтот материал иÑпользует реализацию Форта - Gforth, но Ð±Ð¾Ð»ÑŒÑˆÐ°Ñ Ñ‡Ð°ÑÑ‚ÑŒ напиÑанного будет работать в других Ñредах.
-```
+```forth
\ Это комментарий
( Это тоже комментарий, но иÑпользуетÑÑ Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ€ÐµÐ´ÐµÐ»Ñ‘Ð½Ð½Ñ‹Ñ… Ñлов )
diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown
index 37592258..22249a6e 100644
--- a/ru-ru/go-ru.html.markdown
+++ b/ru-ru/go-ru.html.markdown
@@ -29,7 +29,7 @@ Go - Ñто Ñзык общего назначениÑ, целью котороÐ
комментарий */
// Ключевое Ñлово package приÑутÑтвует в начале каждого файла.
-// Main Ñто Ñпециальное имÑ, обозначающее иÑполнÑемый файл, нежели библиотеку.
+// main Ñто Ñпециальное имÑ, обозначающее иÑполнÑемый файл, нежели библиотеку.
package main
// Import предназначен Ð´Ð»Ñ ÑƒÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð°Ð²Ð¸ÑимоÑтей Ñтого файла.
@@ -82,7 +82,7 @@ func learnTypes() {
// Символ не из ASCII. ИÑходный код Go в кодировке UTF-8.
g := 'Σ' // тип rune, Ñто Ð°Ð»Ð¸Ð°Ñ Ð´Ð»Ñ Ñ‚Ð¸Ð¿Ð° int32, Ñодержит Ñимвол юникода.
- f := 3.14195 // float64, 64-Ñ… битное чиÑло Ñ Ð¿Ð»Ð°Ð²Ð°ÑŽÑ‰ÐµÐ¹ точкой (IEEE-754).
+ f := 3.14159 // float64, 64-Ñ… битное чиÑло Ñ Ð¿Ð»Ð°Ð²Ð°ÑŽÑ‰ÐµÐ¹ точкой (IEEE-754).
c := 3 + 4i // complex128, внутри ÑÐµÐ±Ñ Ñодержит два float64.
// СинтакÑÐ¸Ñ var Ñ Ð¸Ð½Ð¸Ñ†Ð¸Ð°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ñми.
@@ -334,12 +334,12 @@ func requestServer() {
## Что дальше
-ОÑнова вÑех оÑнов в Go Ñто [официальный веб Ñайт](http://golang.org/).
+ОÑнова вÑех оÑнов в Go Ñто [официальный веб Ñайт](https://go.dev/).
Там можно пройти туториал, поигратьÑÑ Ñ Ð¸Ð½Ñ‚ÐµÑ€Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¾Ð¹ Ñредой Go и почитать
объёмную документацию.
Ð”Ð»Ñ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¾Ð·Ð½Ð°ÐºÐ¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ñ€ÐµÐºÐ¾Ð¼ÐµÐ½Ð´ÑƒÐµÑ‚ÑÑ Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð°Ñ‚ÑŒ иÑходные коды [Ñтандартной
-библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированнаÑ, она
+библиотеки Go](https://go.dev/src/). Отлично задокументированнаÑ, она
ÑвлÑетÑÑ Ð»ÑƒÑ‡ÑˆÐ¸Ð¼ иÑточником Ð´Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ Ð¸ Ð¿Ð¾Ð½Ð¸Ð¼Ð°Ð½Ð¸Ñ Go, его ÑÑ‚Ð¸Ð»Ñ Ð¸ идиом. Либо
-можно, кликнув на имени функции в [документации](http://golang.org/pkg/),
+можно, кликнув на имени функции в [документации](https://go.dev/pkg/),
перейти к ее иÑходным кодам.
diff --git a/ru-ru/haml-ru.html.markdown b/ru-ru/haml-ru.html.markdown
index c2f8852e..ed823496 100644
--- a/ru-ru/haml-ru.html.markdown
+++ b/ru-ru/haml-ru.html.markdown
@@ -39,7 +39,7 @@ $ haml input_file.haml output_file.html
/ Комментарии
/ -------------------------------------------
-/ Комментари начинаетÑÑ Ñ Ñимвола коÑой черты.
+/ Комментарии начинаетÑÑ Ñ Ñимвола коÑой черты.
/
Ð”Ð»Ñ Ð½Ð°Ð¿Ð¸ÑÐ°Ð½Ð¸Ñ Ð¼Ð½Ð¾Ð³Ð¾Ñтрочного ÐºÐ¾Ð¼Ð¼ÐµÐ½Ñ‚Ð°Ñ€Ð¸Ñ Ñ€Ð°Ñположите ваш комментарий
@@ -94,7 +94,7 @@ $ haml input_file.haml output_file.html
/ выведет 'Да &amp; да'
/
- Чтобы выполнÑÑ‚ÑŒ Ruby-код без ÑкранрованиÑ, можно иÑпользовать
+ Чтобы выполнÑÑ‚ÑŒ Ruby-код без ÑкранированиÑ, можно иÑпользовать
"воÑклицательный знак" и "равно" (!=)
%p
@@ -196,13 +196,13 @@ $ haml input_file.haml output_file.html
/ -------------------------------------------
/
- Фильтры передают ÑвÑзанный блок текÑта в ÑоотвеÑтвующую
+ Фильтры передают ÑвÑзанный блок текÑта в ÑоответÑтвующую
фильтрующую программу и возвращают результат в Haml
Фильтр обозначаетÑÑ Ð´Ð²Ð¾ÐµÑ‚Ð¾Ñ‡Ð¸ÐµÐ¼ и названием фильтра:
/ Markdown filter
:markdown
- # Заголовк
+ # Заголовок
ТекÑÑ‚ **внутри** *блока*
@@ -221,7 +221,7 @@ $ haml input_file.haml output_file.html
</script>
/
- СущеÑтвует множеÑтво типов фильров (:markdown, :javascript, :coffee,
+ СущеÑтвует множеÑтво типов фильтров (:markdown, :javascript, :coffee,
:css, :ruby и так далее). Ð’Ñ‹ можете определить ÑобÑтвенный фильтр c
помощью Haml::Filters.
diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown
index b1b8eb79..aada30c1 100644
--- a/ru-ru/haskell-ru.html.markdown
+++ b/ru-ru/haskell-ru.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: ru-ru
---
-Haskell разрабатывалÑÑ, как чиÑтый функциональный Ñзык программированиÑ, применимый на практике. Язык извеÑтен Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ñвоей ÑиÑтеме типов, и "знаменит" Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð¼Ð¾Ð½Ð°Ð´Ð°Ð¼. [МенÑ][autor] же Haskell заÑтавлÑет возвращатьÑÑ Ðº Ñебе Ñнова и Ñнова именно Ñвоей ÑлегантноÑтью и [Ñ][autor] получаю иÑтинное удовольÑтвие, Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð¸Ñ€ÑƒÑ Ð½Ð° Haskell.
+Haskell разрабатывалÑÑ, как чиÑтый функциональный Ñзык программированиÑ, применимый на практике. Язык извеÑтен Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ñвоей ÑиÑтеме типов, и "знаменит" Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð¼Ð¾Ð½Ð°Ð´Ð°Ð¼. [МенÑ][author] же Haskell заÑтавлÑет возвращатьÑÑ Ðº Ñебе Ñнова и Ñнова именно Ñвоей ÑлегантноÑтью и [Ñ][author] получаю иÑтинное удовольÑтвие, Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð¸Ñ€ÑƒÑ Ð½Ð° Haskell.
```haskell
-- ОдноÑтрочные комментарии начинаютÑÑ Ñ Ð´Ð²ÑƒÑ… дефиÑов
@@ -172,7 +172,7 @@ fib x
первое определение, к образцу которого
"подойдет" набор аргументов -}
fib 1 = 1
-fib 2 = 2
+fib 2 = 1
fib x = fib (x - 1) + fib (x - 2)
-- Pattern matching Ð´Ð»Ñ ÐºÐ¾Ñ€Ñ‚ÐµÐ¶ÐµÐ¹ выглÑдит так
@@ -544,4 +544,4 @@ Haskell проÑÑ‚ в уÑтановке, забирайте [здеÑÑŒ](http:/
[Learn you a Haskell](http://learnyouahaskell.com/) и
[Real World Haskell](http://book.realworldhaskell.org/).
-[autor]: http://adit.io имеетÑÑ Ð² виду автор оригинального текÑта Adit Bhargava *(примечание переводчика)*
+[author]: http://adit.io имеетÑÑ Ð² виду автор оригинального текÑта Adit Bhargava *(примечание переводчика)*
diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown
index 120981b9..e18fb8a0 100644
--- a/ru-ru/html-ru.html.markdown
+++ b/ru-ru/html-ru.html.markdown
@@ -8,28 +8,28 @@ translators:
lang: ru-ru
---
-HTML раÑшифровываетÑÑ ÐºÐ°Ðº Hypertext Markup Language(гипертекÑтовый Ñзык разметки).
-Это Ñзык иÑпользуют Ð´Ð»Ñ Ð½Ð°Ð¿Ð¸ÑÐ°Ð½Ð¸Ñ Ñтраниц Ð´Ð»Ñ World Wide Web(вÑемирной паутины).
-Это Ñзык разметки позволÑет пиÑать веб-Ñтраниц Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ кода, чтобы определÑÑ‚ÑŒ,
-как должны быть отображены текÑÑ‚ и данные.
+HTML раÑшифровываетÑÑ ÐºÐ°Ðº Hypertext Markup Language (гипертекÑтовый Ñзык разметки).
+Этот Ñзык иÑпользуют Ð´Ð»Ñ Ð½Ð°Ð¿Ð¸ÑÐ°Ð½Ð¸Ñ Ñтраниц Ð´Ð»Ñ World Wide Web (вÑемирной паутины).
+Этот Ñзык разметки позволÑет опиÑать веб-Ñтраницу Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ кода, чтобы определить,
+как на ней должны быть отображены текÑÑ‚ и данные.
Ðа Ñамом деле, HTML файлы предÑтавлÑÑŽÑ‚ Ñобой проÑтые текÑтовые файлы.
-Что такое разметка? Это ÑпоÑоб организации данных Ñтраницы,
-путем Ð¾Ñ‚ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ð¸ Ð·Ð°ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ñ‚ÐµÐ³Ð¾Ð²(Ð¿Ð¾Ð¼ÐµÑ‰Ð°Ñ Ð´Ð°Ð½Ð½Ñ‹Ðµ внутрь Ñтих тегов).
-Эта разметка Ñлужит, чтобы придать значение текÑту, который он окружает.
+Что такое разметка? Это ÑпоÑоб организации данных Ñтраницы
+путем Ð¾Ñ‚ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ð¸ Ð·Ð°ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ñ‚ÐµÐ³Ð¾Ð² и Ð¿Ð¾Ð¼ÐµÑ‰ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ… внутрь Ñтих тегов.
+Эта разметка Ñлужит, чтобы придать значение текÑту, который она окружает.
Как и в других Ñзыках программированиÑ, HTML имеет много верÑий. ЗдеÑÑŒ мы будем говорить о HTML5.
**Примечание:** Ð’Ñ‹ можете теÑтировать различные теги и Ñлементы по мере продвижениÑ
-через учебник на Ñайте, как [codepen](http://codepen.io/pen/) Ð´Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы увидеть
+через учебник на Ñайте [codepen](http://codepen.io/pen/) Ð´Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы увидеть
их влиÑние, понÑÑ‚ÑŒ, как они работают и ознакомитьÑÑ Ñ Ñзыком.
-Ð’ данной Ñтатье раÑÑматриваетÑÑ Ð² оÑновном HTML ÑинтакÑÐ¸Ñ Ð¸ некоторые полезные Ñоветы.
+Ð’ данной Ñтатье раÑÑматриваетÑÑ Ð² оÑновном HTML-ÑинтакÑÐ¸Ñ Ð¸ некоторые полезные Ñоветы.
```html
-<!-- Комментарии заключаютÑÑ ÐºÐ°Ðº Ñта лини\! -->
+<!-- Это комментарий. -->
<!-- #################### Теги #################### -->
-<!-- Ðиже приведен пример HTML-файл, который мы будем анализировать. -->
+<!-- Ðиже приведен пример HTML-файла, который мы будем анализировать. -->
<!doctype html>
<html>
@@ -39,7 +39,7 @@ HTML раÑшифровываетÑÑ ÐºÐ°Ðº Hypertext Markup Language(гипеÑ
<body>
<h1>Привет, мир!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">
- Переходите Ñюда, чтоб поÑмотреть как Ñто выглÑдит.
+ Переходите Ñюда, чтобы поÑмотреть, как Ñто выглÑдит.
</a>
<p>Это параграф.</p>
<p>Это другой параграф.</p>
@@ -51,41 +51,41 @@ HTML раÑшифровываетÑÑ ÐºÐ°Ðº Hypertext Markup Language(гипеÑ
</body>
</html>
-<!-- HTML-файл вÑегда начинаетÑÑ Ñ ÑƒÐºÐ°Ð·Ð°Ð½Ð¸ÐµÐ¼ браузеру, что Ñтраница Ñто HTML. -->
+<!-- HTML-файл вÑегда начинаетÑÑ Ñ ÑƒÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð±Ñ€Ð°ÑƒÐ·ÐµÑ€Ñƒ, что Ñтраница — Ñто HTML. -->
<!doctype html>
-<!-- ПоÑле Ñтого, Ñтраница начинаетÑÑ Ñ <html> тега. -->
+<!-- ПоÑле Ñтого Ñтраница начинаетÑÑ Ñ <html> тега. -->
<html>
-<!-- Ñтраница будет закрыта в конце Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ тега </html>. -->
+<!-- Страница будет закрыта в конце Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ тега </html>. -->
</html>
<!-- Ðичто не должно поÑвитьÑÑ Ð¿Ð¾Ñле Ñтого заключительного тега. -->
-<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>), мы находим: -->
+<!-- Внутри (между открывающим и закрывающим тегами <html> </ html>) мы находим: -->
-<!-- Заголовок определÑетÑÑ <head> (it он должен быть закрыт </head>). -->
+<!-- Заголовок определÑетÑÑ <head> (и он должен быть закрыт </head>). -->
<!-- Заголовок Ñодержит опиÑание и дополнительную информацию, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð½Ðµ отображаетÑÑ; Ñто метаданные. -->
<head>
- <title>Мой Ñайт</title><!-- Тег <title> указывает браузеру заголовок, чтобы показать в Ñтроке заголовка Ð½Ð°Ð·Ð²Ð°Ð½Ð¸Ñ Ð¸ вкладки браузера окна. -->
+ <title>Мой Ñайт</title><!-- Тег <title> указывает браузеру заголовок, который Ñледует показать в Ñтроке заголовка Ð½Ð°Ð·Ð²Ð°Ð½Ð¸Ñ Ð¸ вкладки браузера окна. -->
</head>
-<!-- ПоÑле ÑÐµÐºÑ†Ð¸Ñ <head>, находитÑÑ ÑÐµÐºÑ†Ð¸Ñ - <body> -->
-<!-- До Ñтого момента, ничего опиÑаное не будет отображатьÑÑ Ð² окне браузера. -->
-<!-- Мы должны наполнить <body> Ñодержанием, которое будет отображатьÑÑ. -->
+<!-- ПоÑле Ñекции <head>, находитÑÑ ÑÐµÐºÑ†Ð¸Ñ - <body> -->
+<!-- До Ñтого момента, ничего из опиÑанного не будет отображатьÑÑ Ð² окне браузера. -->
+<!-- Мы должны наполнить <body> Ñодержанием, которое будет отображатьÑÑ. -->
<body>
<h1>Hello, world!</h1> <!-- Тег h1 Ñоздает заголовок. -->
- <!-- Так же ÑущеÑтвуют другие заголовки от имеющего большее значение <h1> по убыванию к <h6>. -->
- <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите Ñюда, чтоб поÑмотреть как Ñто выглÑдит.</a>
- <!--гиперÑÑылка на URL, заданнf атрибутом href="" -->
- <p>Это параграф.</p> <!-- Тег <p> позволÑет нам добавдÑÑ‚ÑŒ текÑÑ‚ на Ñтранице HTML. -->
+ <!-- Также ÑущеÑтвуют другие заголовки от имеющего большее значение <h1> до меньшего <h6>. -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Переходите Ñюда, чтобы поÑмотреть, как Ñто выглÑдит.</a>
+ <!--гиперÑÑылка на URL, Ð·Ð°Ð´Ð°Ð½Ð½Ð°Ñ Ð°Ñ‚Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ð¼ href="" -->
+ <p>Это параграф.</p> <!-- Тег <p> позволÑет нам добавлÑÑ‚ÑŒ текÑÑ‚ на Ñтранице HTML. -->
<p>Это другой параграф.</p>
<ul> <!-- Тег <ul> Ñоздает маркированный ÑпиÑок. -->
- <!-- Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы иметь пронумерованный ÑпиÑок лучше иÑпользовать <ol>
- тогда первый Ñлемент будет иметь значение 1. Ð´Ð»Ñ Ð²Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ Ñлемента, 2. и так далее. -->
- <li>Это Ñлемент в не нумерованном ÑпиÑке (маркированный ÑпиÑок)</li>
+ <!-- Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы иметь пронумерованный ÑпиÑок, лучше иÑпользовать <ol>
+ тогда первый Ñлемент будет иметь значение 1., Ð´Ð»Ñ Ð²Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ Ñлемента 2. и так далее. -->
+ <li>Это Ñлемент в ненумерованном ÑпиÑке (маркированный ÑпиÑок)</li>
<li>Это еще один Ñлемент</li>
<li>И Ñто поÑледний пункт в ÑпиÑке</li>
</ul>
@@ -124,6 +124,6 @@ HTML файлы имеют окончание(раÑширение) `.html`.
## Узнать больше
-* [википедиа](https://ru.wikipedia.org/wiki/HTML)
+* [википедиÑ](https://ru.wikipedia.org/wiki/HTML)
* [HTML учебник](https://developer.mozilla.org/ru/docs/Web/HTML)
* [htmlbook](http://htmlbook.ru/)
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 4556b425..4c4fa503 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -504,7 +504,7 @@ if (Object.create === undefined) { // не перезапиÑываем мето
[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) —
предоÑтавлÑет отличную документацию Ð´Ð»Ñ JavaScript, как он иÑпользуетÑÑ Ð² браузерах.
-Кроме того, Ñто вики, поÑтому, еÑли вы знаете больше, вы можете помочь другим,
+Кроме того, Ñто вики. ПоÑтому, еÑли вы знаете больше, вы можете помочь другим,
делÑÑÑŒ Ñвоими знаниÑми.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — Ñто
diff --git a/ru-ru/learnvisualbasic-ru.html.markdown b/ru-ru/learnvisualbasic-ru.html.markdown
index 72e1358c..6242fc42 100644
--- a/ru-ru/learnvisualbasic-ru.html.markdown
+++ b/ru-ru/learnvisualbasic-ru.html.markdown
@@ -8,7 +8,7 @@ filename: learnvisualbasic-ru.vb
lang: ru-ru
---
-```vbnet
+```visualbasic
Module Module1
Sub Main()
diff --git a/ru-ru/linker-ru.html.markdown b/ru-ru/linker-ru.html.markdown
index 7df29c23..14cfd229 100644
--- a/ru-ru/linker-ru.html.markdown
+++ b/ru-ru/linker-ru.html.markdown
@@ -34,11 +34,11 @@ lang: ru-ru
# ОпределÑем точку входа в программу
ENTRY(Reset_Handler)
-# ОпределÑем перемнную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит Ð°Ð´Ñ€ÐµÑ Ð²ÐµÑ€ÑˆÐ¸Ð½Ñ‹ Ñтека
+# ОпределÑем переменную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит Ð°Ð´Ñ€ÐµÑ Ð²ÐµÑ€ÑˆÐ¸Ð½Ñ‹ Ñтека
_estack = 0x20020000;
-# ОпределÑем перемнную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит значение размера кучи
+# ОпределÑем переменную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит значение размера кучи
_Min_Heap_Size = 0x200;
-# ОпределÑем перемнную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит значение размера Ñтека
+# ОпределÑем переменную ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит значение размера Ñтека
_Min_Stack_Size = 0x400;
# ОпиÑание карты памÑти доÑтупной Ð´Ð»Ñ Ð´Ð°Ð½Ð½Ð¾Ð³Ð¾ процеÑÑора
@@ -50,7 +50,7 @@ _Min_Stack_Size = 0x400;
# RAM - начинаетÑÑ Ñ Ð°Ð´Ñ€ÐµÑа 0x20000000 и занимает 128 Кбайт;
# CCMRAM - начинаетÑÑ Ñ Ð°Ð´Ñ€ÐµÑа 0x10000000и занимает 64 Кбайт;
# FLASH - начинаетÑÑ Ñ Ð°Ð´Ñ€ÐµÑа 0x8000000 занимает 1024 Кбайт;
-# Причем RAM памÑÑ‚ÑŒ доÑтупка Ð´Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ, запиÑи и иÑполнениÑ.
+# Причем RAM памÑÑ‚ÑŒ доÑтупна Ð´Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ, запиÑи и иÑполнениÑ.
# CCMRAM памÑÑ‚ÑŒ доÑтупна только на чтение и запиÑÑŒ.
# FLASH памÑÑ‚ÑŒ доÑтупна на чтение и иÑполнение.
MEMORY
@@ -70,7 +70,7 @@ SECTIONS
. = ALIGN(4);
# СущеÑтвует Ð¾Ð¿Ñ†Ð¸Ñ --gc-sections, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ñет Ñобирать муÑор из неиÑпользуемых
- # входных разделов. И еÑли еÑÑ‚ÑŒ разделы, которые Ñборщик муÑÑора не должен трогать,
+ # входных разделов. И еÑли еÑÑ‚ÑŒ разделы, которые Ñборщик муÑора не должен трогать,
# то их необходимо указать в качеÑтве аргумента функции KEEP() (аналог ключевого Ñлова
# volatile).
# ЗапиÑÑŒ (*(.isr_vector)) означает разделы .isr_vector во вÑех объектных файлах. Т.к.
@@ -80,8 +80,8 @@ SECTIONS
# Выравниваем текущую позицию на границу 4-х байт.
. = ALIGN(4);
- # Выражение ">ОБЛÐСТЬ_ПÐМЯТИ" указывает в какую именно облаÑÑ‚ÑŒ памÑти будет помещенна
- # Ð´Ð°Ð½Ð½Ð°Ñ ÑекциÑ. Ð’ нашем Ñлущае ÑÐµÐºÑ†Ð¸Ñ .isr_vector будет размещена во FLASH памÑти.
+ # Выражение ">ОБЛÐСТЬ_ПÐМЯТИ" указывает в какую именно облаÑÑ‚ÑŒ памÑти будет помещена
+ # Ð´Ð°Ð½Ð½Ð°Ñ ÑекциÑ. Ð’ нашем Ñлучае ÑÐµÐºÑ†Ð¸Ñ .isr_vector будет размещена во FLASH памÑти.
} >FLASH
# ИТОГО: Ð¡ÐµÐºÑ†Ð¸Ñ .isr_vector, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ñодержит таблицу векторов прерываний выравниваетÑÑ
@@ -125,7 +125,7 @@ SECTIONS
# Выравниваем текущую позицию на границу 4-х байт.
. = ALIGN(4);
- # Указываем, что в данной Ñекции будут хранитÑÑ Ð¾Ð±Ð»Ð°Ñти .rodataвÑех
+ # Указываем, что в данной Ñекции будут хранитÑÑ Ð¾Ð±Ð»Ð°Ñти .rodata вÑех
# объектных файлов
*(.rodata)
*(.rodata*)
@@ -158,13 +158,13 @@ SECTIONS
_edata = .;
# Ð¤ÑƒÐ½ÐºÑ†Ð¸Ñ AT указывает на то, что данный Ñектор хранитÑÑ Ð² одной облаÑти памÑти
- # (в нашем Ñлучае FLASH), а иÑполнÑÑ‚ÑŒÑÑ Ð±ÑƒÐ´ÐµÑ‚ из другой обаÑти памÑти (в нашем Ñлучае RAM).
- # ЕÑÑ‚ÑŒ два типа адреÑÑов:
- # * VMA (Virtual memory address) - Ñто run-time Ð°Ð´Ñ€ÐµÑ Ð¿Ð¾ которому уомпилÑтор ожидает
+ # (в нашем Ñлучае FLASH), а иÑполнÑÑ‚ÑŒÑÑ Ð±ÑƒÐ´ÐµÑ‚ из другой облаÑти памÑти (в нашем Ñлучае RAM).
+ # ЕÑÑ‚ÑŒ два типа адреÑов:
+ # * VMA (Virtual memory address) - Ñто run-time Ð°Ð´Ñ€ÐµÑ Ð¿Ð¾ которому компилÑтор ожидает
# видеть данные.
# * LMA (Load memory address) - Ñто Ð°Ð´Ñ€ÐµÑ Ð¿Ð¾ которому линкер хранит данные.
- #Startup должен код Ñкопировать Ñекцию .data из адреÑÑов LMA в адреÑÑа VMA.
+ #Startup должен код Ñкопировать Ñекцию .data из адреÑов LMA в адреÑа VMA.
} >RAM AT> FLASH
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index 579a9a20..4692e628 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -45,7 +45,7 @@ Markdown ÑвлÑетÑÑ Ð½Ð°Ð´Ð¼Ð½Ð¾Ð¶ÐµÑтвом HTML, поÑтому люб
HTML-Ñлементов -->
```
-## Заголовки
+## Заголовки
HTML-Ñлементы от <h1> до <h6> размечаютÑÑ Ð¾Ñ‡ÐµÐ½ÑŒ проÑто:
текÑÑ‚, который должен Ñтать заголовком, предварÑетÑÑ
@@ -110,7 +110,7 @@ __И Ñтот тоже.__
Ð”Ð»Ñ Ð²Ñтавки принудительных переноÑов можно завершить абзац Ð´Ð²ÑƒÐ¼Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¼Ð¸ пробелами:
```md
-Эта Ñтрока завершаетÑÑ Ð´Ð²ÑƒÐ¼Ñ Ð¿Ñ€Ð¾Ð±ÐµÐ»Ð°Ð¼Ð¸ (выделите, чтобы увидеть!).
+Эта Ñтрока завершаетÑÑ Ð´Ð²ÑƒÐ¼Ñ Ð¿Ñ€Ð¾Ð±ÐµÐ»Ð°Ð¼Ð¸ (выделите, чтобы увидеть!).
Ðад Ñтой Ñтрокой еÑÑ‚ÑŒ <br />!
```
@@ -208,7 +208,7 @@ __И Ñтот тоже.__
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -223,12 +223,11 @@ __И Ñтот тоже.__
Ð’ Github Flavored Markdown Ð´Ð»Ñ Ð±Ð»Ð¾ÐºÐ¾Ð² кода можно иÑпользовать
Ñпециальный ÑинтакÑиÑ:
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+```ruby
def foobar
- puts "Привет, мир!"
+ puts "Привет, мир!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
Во фрагменте, приведённом выше, отÑтуп не требуетÑÑ.
Кроме того, Github подÑветит ÑинтакÑÐ¸Ñ Ñзыка, указанного поÑле \`\`\`
@@ -255,6 +254,7 @@ end
```md
[СÑылка!](http://test.com/)
```
+
Также Ð´Ð»Ñ ÑÑылки можно указать вÑплывающую подÑказку (`title`), иÑпользуÑ
кавычки внутри круглых Ñкобок:
@@ -269,11 +269,13 @@ end
Markdown также позволÑет размечать ÑÑылку в виде ÑноÑки:
-<pre><code class="highlight">&#x5b;<span class="nv">Щёлкните Ñту ÑÑылку</span>][<span class="ss">link1</span>] Ð´Ð»Ñ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾Ð¹ информации!
-&#x5b;<span class="nv">Также поÑмотрите Ñту ÑÑылку,</span>][<span class="ss">foobar</span>] еÑли хотите.
+```md
+[Щёлкните Ñту ÑÑылку][link1] Ð´Ð»Ñ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾Ð¹ информации!
+[Также поÑмотрите Ñту ÑÑылку,][foobar] еÑли хотите.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Круто!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Ðормально!"</span></code></pre>
+[link1]: http://test.com/ "Круто!"
+[foobar]: http://foobar.biz/ "Ðормально!"
+```
`Title` также может быть в одинарных кавычках или круглых Ñкобках, а также
отÑутÑтвовать вовÑе. СÑылки на ÑноÑки могут быть в любом меÑте документа,
@@ -281,9 +283,11 @@ Markdown также позволÑет размечать ÑÑылку в вид
СущеÑтвует также неÑвное именование, когда ÑÑылка ÑвлÑетÑÑ Ð¸Ð´ÐµÐ½Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ‚Ð¾Ñ€Ð¾Ð¼.
-<pre><code class="highlight">&#x5b;<span class="nv">Это</span>][] ÑÑылка.
+```md
+[Это][] ÑÑылка.
-&#x5b;<span class="nv">Ñто</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[Ñто]: http://thisisalink.com/
+```
Правда, Ñта возможноÑÑ‚ÑŒ не очень раÑпроÑтранена.
@@ -294,11 +298,15 @@ Markdown также позволÑет размечать ÑÑылку в вид
```md
![Ðльтернативный текÑÑ‚ Ð´Ð»Ñ Ð¸Ð·Ð¾Ð±Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ](http://imgur.com/myimage.jpg "ПодÑказка")
```
-Ð˜Ð·Ð¾Ð±Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ Ñ‚Ð¾Ð¶Ðµ могут быть оформлены, как ÑноÑки.
-<pre><code class="highlight">!&#x5b;<span class="nv">Это альтернативный текÑÑ‚.</span>][<span class="ss">myimage</span>]
+Ð˜Ð·Ð¾Ð±Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ Ñ‚Ð¾Ð¶Ðµ могут быть оформлены как ÑноÑки.
+
+```md
+![Это альтернативный текÑÑ‚.][myimage]
+
+[myimage]: relative/urls/cool/image.jpg "ЕÑли нужна подÑказка, её можно добавить"
+```
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"ЕÑли нужна подÑказка, её можно добавить"</span></code></pre>
## Разное
### ÐвтоÑÑылки
@@ -341,6 +349,7 @@ Markdown также позволÑет размечать ÑÑылку в вид
| Выравнивание | Выравнивание | Выравнивание |
| влево | по центру | вправо |
```
+
Или более компактно
```md
diff --git a/ru-ru/nim-ru.html.markdown b/ru-ru/nim-ru.html.markdown
index 0e08f1bf..09784792 100644
--- a/ru-ru/nim-ru.html.markdown
+++ b/ru-ru/nim-ru.html.markdown
@@ -3,7 +3,7 @@ language: Nim
filename: learnNim-ru.nim
contributors:
- ["Jason J. Ayala P.", "http://JasonAyala.com"]
- - ["Dennis Felsing", "http://felsin9.de/nnis/"]
+ - ["Dennis Felsing", "https://dennis.felsing.org"]
translators:
- ["Nomadic", "https://github.com/n0madic"]
- ["dvska", "https://github.com/dvska"]
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index af77a9ca..4a508cfc 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -125,7 +125,7 @@ echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersV
// и никогда не может быть изменена во Ð²Ñ€ÐµÐ¼Ñ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ñ‹!
// Правильное Ð¸Ð¼Ñ ÐºÐ¾Ð½Ñтанты начинаетÑÑ Ñ Ð±ÑƒÐºÐ²Ñ‹ или Ñимвола подчеркиваниÑ
-// и Ñодержит любое колличеÑтво букв, цифр или Ñимволов подчеркиваниÑ.
+// и Ñодержит любое количеÑтво букв, цифр или Ñимволов подчеркиваниÑ.
define("FOO", "something");
// ДоÑтуп к конÑтанте возможен через прÑмое указание её имени без знака $
@@ -224,7 +224,7 @@ assert($c > $b); // больше
assert($a <= $b); // меньше или равно
assert($c >= $d); // больше или равно
-// Следующие ÑƒÑ‚Ð²ÐµÑ€Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¸Ñтинны, еÑли переменные имеют одинаковые тип.
+// Следующие ÑƒÑ‚Ð²ÐµÑ€Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¸Ñтинны, еÑли переменные имеют одинаковый тип.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
@@ -251,7 +251,7 @@ echo $string + $string; // => 2 (Ñтрока превращаетÑÑ Ð² чиÑ
$string = 'one';
echo $string + $string; // => 0
-// Приведение типов (type casting) может быть иÑпользовано Ð´Ð»Ñ Ð¿Ñ€ÐµÐ¾Ð±Ñ€Ð°Ð·Ð¾Ð²Ð°Ð½Ð¸Ðµ
+// Приведение типов (type casting) может быть иÑпользовано Ð´Ð»Ñ Ð¿Ñ€ÐµÐ¾Ð±Ñ€Ð°Ð·Ð¾Ð²Ð°Ð½Ð¸Ñ
// переменной в другой тип
$boolean = (boolean) 1; // => true
@@ -458,7 +458,7 @@ include_once 'my-file.php';
require 'my-file.php';
require_once 'my-file.php';
-// ДейÑтвует также как и include(), но еÑли файл не удалоÑÑŒ подключить,
+// ДейÑтвует так же как и include(), но еÑли файл не удалоÑÑŒ подключить,
// Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð²Ñ‹Ð´Ð°ÐµÑ‚ фатальную ошибку
// Содержимое файла my-include.php:
@@ -497,7 +497,7 @@ class MyClass
// КонÑтруктор опиÑываетÑÑ Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ __construct
public function __construct($instanceProp) {
- // ДоÑтуп к ÑземплÑру клаÑÑа Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ $this
+ // ДоÑтуп к ÑкземплÑру клаÑÑа Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ $this
$this->instanceProp = $instanceProp;
}
@@ -661,7 +661,7 @@ $cls->myTraitMethod(); // Ðапечатает "I have MyTrait"
<?php
// По умолчанию, клаÑÑÑ‹ ÑущеÑтвуют в глобальном проÑтранÑтве имен и могут быть
-// вызваны Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ñ‹Ð¼ Ñлешем.
+// вызваны Ñ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ñ‹Ð¼ ÑлÑшем.
$cls = new \MyClass();
@@ -762,7 +762,7 @@ echo "Current method is " . __METHOD__;
echo "Current namespace is " . __NAMESPACE__;
// Возвращает Ð¸Ð¼Ñ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ трейта.
-// Возвращает только еÑли иÑпольщуетÑÑ Ð²Ð½ÑƒÑ‚Ñ€Ð¸ трейта.
+// Возвращает только еÑли иÑпользуетÑÑ Ð²Ð½ÑƒÑ‚Ñ€Ð¸ трейта.
echo "Current namespace is " . __TRAIT__;
@@ -771,7 +771,7 @@ echo "Current namespace is " . __TRAIT__;
*
*/
-// ПроÑтую обработку ошибок можно произвеÑти Ñпомощью try catch блока.
+// ПроÑтую обработку ошибок можно произвеÑти Ñ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒÑŽ try catch блока.
try {
// ВыполнÑем что-то
@@ -779,7 +779,7 @@ try {
// Обработка иÑключениÑ
}
-// При иÑпользовании try catch блока в облаÑти вилимоÑти, Ñтоит иÑпользовать
+// При иÑпользовании try catch блока в облаÑти видимоÑти, Ñтоит иÑпользовать
// Ñледующий подход:
try {
@@ -788,7 +788,7 @@ try {
// Обработка иÑключениÑ
}
-// Специальное(каÑтомное) иÑключение - exceptions
+// Специальное (каÑтомное) иÑключение - exceptions
class MyException extends Exception {}
@@ -797,7 +797,7 @@ try {
$condition = true;
if ($condition) {
- throw new MyException('Something just happend');
+ throw new MyException('Something just happened');
}
} catch (MyException $e) {
diff --git a/ru-ru/pyqt-ru.html.markdown b/ru-ru/pyqt-ru.html.markdown
index 24afc03d..a7e14c02 100644
--- a/ru-ru/pyqt-ru.html.markdown
+++ b/ru-ru/pyqt-ru.html.markdown
@@ -11,7 +11,7 @@ translators:
**Qt** - широко извеÑтный кроÑÑ-платформенный фреймворк Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ программного обеÑпечениÑ,
который может быть иÑпользован на различных Ñофтварных и хардварных платформах без какого-либо
-Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð² коде. Данный фреймворк при Ñтом обладает мощью и ÑкороÑтью нативных приложений.
+Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð² коде. Данный фреймворк при Ñтом обладает мощью и ÑкороÑтью нативных приложений.
Qt и был изначально напиÑан на *C++*.
Данный текÑÑ‚ ÑвлÑетÑÑ Ð°Ð´Ð°Ð¿Ñ‚Ð°Ñ†Ð¸ÐµÐ¹ Ð²Ð²ÐµÐ´ÐµÐ½Ð¸Ñ Ð² Qt на C++ под авторÑтвом ÐлекÑÐµÑ ÐšÐ¾Ð²Ð°Ð»ÑŒÑ‡ÑƒÐºÐ° Ð´Ð»Ñ pyqt.
@@ -20,7 +20,7 @@ Qt и был изначально напиÑан на *C++*.
```python
def window():
- # Создайте объект приложениÑ
+ # Создайте объект приложениÑ
app = QtGui.QApplication(sys.argv)
# Создайте виджет, где будет находитьÑÑ Ð½Ð°Ñˆ лейбл
w = QtGui.QWidget()
@@ -28,10 +28,10 @@ def window():
b = QtGui.QLabel(w)
# Задайте текÑÑ‚ Ð´Ð»Ñ Ð»ÐµÐ¹Ð±Ð»Ð°
b.setText("Hello World!")
- # Задайте Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ размере и раÑположении
+ # Задайте Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ размере и раÑположении
w.setGeometry(100, 100, 200, 50)
b.move(50, 20)
- # Задайте заголовок окна
+ # Задайте заголовок окна
w.setWindowTitle("PyQt")
# Ð’Ñе ранее напиÑанное выводитÑÑ Ð½Ð° Ñкран
w.show()
@@ -43,11 +43,11 @@ if __name__ == '__main__':
```
-Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾, чтобы получить более продвинутые функции Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð² pyqt, нам необходимо
-обратить внимание на Ñоздание дополнительных Ñлементов. Ðиже предÑтавлено Ñоздание вÑплывающего диалогового окна, которое проÑит Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ñ‚ÑŒ его решение или предоÑтавить какую-либо
+Ð”Ð»Ñ Ñ‚Ð¾Ð³Ð¾ чтобы получить более продвинутые функции Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð² pyqt, нам необходимо
+обратить внимание на Ñоздание дополнительных Ñлементов. Ðиже предÑтавлено Ñоздание вÑплывающего диалогового окна, которое проÑит Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ñ‚ÑŒ его решение или предоÑтавить какую-либо
информацию.
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -67,7 +67,7 @@ def window():
w.show()
sys.exit(app.exec_())
-Ð”Ð°Ð½Ð½Ð°Ñ Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð´Ð¾Ð»Ð¶Ð½Ð° Ñоздавать диалоговое окно Ñ ÐºÐ½Ð¾Ð¿ÐºÐ¾Ð¹, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¶Ð´ÐµÑ‚ клика по Ñебе
+Ð”Ð°Ð½Ð½Ð°Ñ Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð´Ð¾Ð»Ð¶Ð½Ð° Ñоздавать диалоговое окно Ñ ÐºÐ½Ð¾Ð¿ÐºÐ¾Ð¹, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¶Ð´ÐµÑ‚ клика по Ñебе
и затем завершает программу.
def showdialog():
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index e0e53b9c..e088593e 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -353,7 +353,6 @@ empty_set = set()
# Да, оно выглÑдит примерно как Ñловарь. Ðу извините, так уж вышло.
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
-# Similar to keys of a dictionary, elements of a set have to be immutable.
# Как и ключи ÑловарÑ, Ñлементы множеÑтва должны быть неизменÑемыми.
invalid_set = {[1], 1} # => ВыбраÑывает ошибку TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
diff --git a/ru-ru/qt-ru.html.markdown b/ru-ru/qt-ru.html.markdown
index d0a70c9d..15e2c775 100644
--- a/ru-ru/qt-ru.html.markdown
+++ b/ru-ru/qt-ru.html.markdown
@@ -1,7 +1,7 @@
---
category: tool
tool: Qt Framework
-language: c++
+language: C++
filename: learnqt-ru.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
@@ -80,7 +80,7 @@ int main(int argc, char *argv[]) {
```
Обратите внимание на метод *QObject::connect*. Этот метод ÑоединÑет *СИГÐÐЛЫ* одного объекта Ñо *СЛОТÐМИ* другого.
-**Сигналы** отправлÑÑŽÑ‚ÑÑ ÐºÐ¾Ð³Ð´Ð° Ñ Ð¾Ð±ÑŠÐµÐºÑ‚Ð°Ð¼Ð¸ проиÑходÑÑ‚ отпределённые ÑобытиÑ, например, Ñигнал *нажатие* отправлÑетÑÑ ÐºÐ¾Ð³Ð´Ð° пользователь нажимает на объект типа QPushButton.
+**Сигналы** отправлÑÑŽÑ‚ÑÑ ÐºÐ¾Ð³Ð´Ð° Ñ Ð¾Ð±ÑŠÐµÐºÑ‚Ð°Ð¼Ð¸ проиÑходÑÑ‚ определённые ÑобытиÑ, например, Ñигнал *нажатие* отправлÑетÑÑ, когда пользователь нажимает на объект типа QPushButton.
**Слоты** Ñто *дейÑтвиÑ*, которые могут быть выполнены в ответ на полученные Ñигналы.
diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown
index d46d301c..a568ac37 100644
--- a/ru-ru/rust-ru.html.markdown
+++ b/ru-ru/rust-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
filename: learnrust-ru.rs
contributors:
diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown
index 7353a175..c7ba0edb 100644
--- a/ru-ru/sql-ru.html.markdown
+++ b/ru-ru/sql-ru.html.markdown
@@ -24,7 +24,7 @@ lang: ru-ru
Ðекоторые команды ниже предполагают иÑпользование
[демонÑтрационного образца базы данных Ñотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доÑтупного на [Github](https://github.com/datacharmer/test_db).
Следовательно, Ð´Ð»Ñ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½Ð¸Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´ в локальном окружении он должен быть загружен.
-Файлы на github — Ñто Ñкрипты Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð°Ð¼Ð¸, которые Ñхожи Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð°Ð¼Ð¸ ниже,
+Файлы на github — Ñто Ñкрипты Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð°Ð¼Ð¸, Ñхожие Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð°Ð¼Ð¸ ниже,
которые Ñоздают и манипулируют таблицами и данными о Ñотрудниках вымышленной
компании. СинтакÑÐ¸Ñ Ð´Ð»Ñ Ð·Ð°Ð¿ÑƒÑка Ñтих Ñкриптов будет завиÑеть от иÑпользуемой
вами реализации SQL. Обычно иÑпользуетÑÑ ÑƒÑ‚Ð¸Ð»Ð¸Ñ‚Ð°, запуÑÐºÐ°ÐµÐ¼Ð°Ñ Ð¸Ð· командной
@@ -50,7 +50,7 @@ SHOW DATABASES;
USE employees;
-- Выбрать вÑе Ñтроки и колонки из таблицы «departments» (отделы) текущей базы.
--- Ð’ интерактивном режиме обыч но результат будет выведен на Ñкран.
+-- Ð’ интерактивном режиме обычно результат будет выведен на Ñкран.
SELECT * FROM departments;
-- Тот же запроÑ, что и выше, но выбор только колонок «dept_no» и «dept_name».
diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown
index aa7545cc..643c48b0 100644
--- a/ru-ru/tmux-ru.html.markdown
+++ b/ru-ru/tmux-ru.html.markdown
@@ -249,4 +249,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] |
[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux)
-[Отображение CPU/MEM % в ÑтатуÑбаре](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
+[Отображение CPU/MEM % в ÑÑ‚Ð°Ñ‚ÑƒÑ Ð±Ð°Ñ€Ðµ](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux)
diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown
index 09bbb2d1..ad931599 100644
--- a/ru-ru/typescript-ru.html.markdown
+++ b/ru-ru/typescript-ru.html.markdown
@@ -9,8 +9,8 @@ translators:
filename: learntypescript-ru.ts
---
-TypeScript — Ñто Ñзык программированиÑ, целью которого ÑвлÑетÑÑ Ð»Ñ‘Ð³ÐºÐ°Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° широкомаÑштабируемых JavaScript-приложений.
-TypeScript добавлÑет в Javascript общие концепции, такие, как клаÑÑÑ‹, модули, интерфейÑÑ‹, обобщённое программирование и (опционально) ÑтатичеÑкую типизацию.
+TypeScript — Ñто Ñзык программированиÑ, целью которого ÑвлÑетÑÑ Ð»Ñ‘Ð³ÐºÐ°Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° широко маÑштабируемых JavaScript-приложений.
+TypeScript добавлÑет в Javascript общие концепции, такие как клаÑÑÑ‹, модули, интерфейÑÑ‹, обобщённое программирование и (опционально) ÑтатичеÑкую типизацию.
Это надмножеÑтво Ñзыка JavaScript: веÑÑŒ JavaScript-код ÑвлÑетÑÑ Ð²Ð°Ð»Ð¸Ð´Ð½Ñ‹Ð¼ TypeScript-кодом, Ñледовательно, может быть добавлен беÑшовно в любой проект.
КомпилÑтор TypeScript генерирует JavaScript-код.
diff --git a/ru-ru/vim-ru.html.markdown b/ru-ru/vim-ru.html.markdown
index f43f99eb..60b381e7 100644
--- a/ru-ru/vim-ru.html.markdown
+++ b/ru-ru/vim-ru.html.markdown
@@ -10,7 +10,7 @@ lang: ru-ru
---
[Vim](http://www.vim.org)
-(Vi IMproved) Ñто клон полулÑрного текÑтового редактора Ð´Ð»Ñ Unix. Он разработан
+(Vi IMproved) Ñто клон популÑрного текÑтового редактора Ð´Ð»Ñ Unix. Он разработан
Ñ Ñ†ÐµÐ»ÑŒÑŽ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ñ ÑкороÑти и продуктивноÑти и повÑемеÑтно иÑпользуетÑÑ Ð²
большинÑтво ЮникÑ-подобных ÑиÑтем. Ð’ нем имеетÑÑ Ð¼Ð½Ð¾Ð¶ÐµÑтво клавиатурных
Ñочетаний Ð´Ð»Ñ Ð±Ñ‹Ñтрой навигации к определенным точкам в файле и быÑтрого
@@ -167,8 +167,8 @@ Vim можно раÑÑматривать как набор команд в фо
## МакроÑÑ‹
МакроÑÑ‹ Ñто проÑто запиÑываемые дейÑтвиÑ.
-Во Ð²Ñ€ÐµÐ¼Ñ Ð·Ð°Ð¿Ð¸Ñи макроÑÑ‹ запоминают **вÑе** дейÑÑ‚Ð²Ð¸Ñ Ð¸ команды до тех пор пока
-запиÑÑŒ не будет оÑтановлена.При вызове Ð¼Ð°ÐºÑ€Ð¾Ñ Ð¿Ñ€Ð¸Ð¼ÐµÐ½Ñет ту же Ñамую поÑледовательноÑÑ‚ÑŒ
+Во Ð²Ñ€ÐµÐ¼Ñ Ð·Ð°Ð¿Ð¸Ñи макроÑÑ‹ запоминают **вÑе** дейÑÑ‚Ð²Ð¸Ñ Ð¸ команды до тех пор, пока
+запиÑÑŒ не будет оÑтановлена. При вызове Ð¼Ð°ÐºÑ€Ð¾Ñ Ð¿Ñ€Ð¸Ð¼ÐµÐ½Ñет ту же Ñамую поÑледовательноÑÑ‚ÑŒ
дейÑтвий и команд на выделенном текÑте.
```
diff --git a/ru-ru/xml-ru.html.markdown b/ru-ru/xml-ru.html.markdown
index bf3f22b0..34e17b9b 100644
--- a/ru-ru/xml-ru.html.markdown
+++ b/ru-ru/xml-ru.html.markdown
@@ -15,7 +15,7 @@ XML - Ñто Ñзык разметки, предназначенный Ð´Ð»Ñ Ñ…
* XML-СинтакÑиÑ
```xml
-<!-- Комментарии в XML выглÑдÑÑ‚ вот так -->
+<!-- Это комментарий. -->
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
diff --git a/ru-ru/yaml-ru.html.markdown b/ru-ru/yaml-ru.html.markdown
index ddaed2b6..693848fc 100644
--- a/ru-ru/yaml-ru.html.markdown
+++ b/ru-ru/yaml-ru.html.markdown
@@ -12,7 +12,7 @@ lang: ru-ru
YAML как Ñзык Ñериализации данных предназначен прежде вÑего Ð´Ð»Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð»ÑŽÐ´ÑŒÐ¼Ð¸.
Это Ñтрогое надмножеÑтво JSON Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸ÐµÐ¼ ÑинтакÑичеÑки значимых переноÑов Ñтрок и
-отÑтупов как в Python. Тем не менее, в отличие от Python, YAML запрещает
+отÑтупов как в Python. Тем не менее в отличие от Python, YAML запрещает
иÑпользование табов Ð´Ð»Ñ Ð¾Ñ‚Ñтупов.
```yaml
@@ -53,7 +53,7 @@ literal_block: |
Любые Ñтроки Ñ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ð¼ отÑтупом ÑохранÑÑŽÑ‚ оÑтатки Ñвоего отÑтупа -
Ñта Ñтрока будет Ñодержать дополнительно 4 пробела.
folded_style: >
- ВеÑÑŒ блок Ñтого тектÑа будет значением 'folded_style', но в данном Ñлучае
+ ВеÑÑŒ блок Ñтого текÑта будет значением 'folded_style', но в данном Ñлучае
вÑе Ñимволы новой Ñтроки будут заменены пробелами.
ПуÑтые Ñтроки будут преобразованы в Ð¿ÐµÑ€ÐµÐ½Ð¾Ñ Ñтроки.
@@ -76,7 +76,7 @@ a_nested_map:
0.25: a float key
# Ключи также могут быть Ñложными, например многоÑтрочными.
-# Мы иÑпользуем ? Ñ Ð¿Ð¾Ñледующим пробелом чтобы обозначить начало Ñложного ключа.
+# Мы иÑпользуем ? Ñ Ð¿Ð¾Ñледующим пробелом, чтобы обозначить начало Ñложного ключа.
? |
Этот ключ
который Ñодержит неÑколько Ñтрок
@@ -124,7 +124,7 @@ base: &base
name: Каждый будет иметь одинаковое имÑ
# РегулÑрное выражение << называетÑÑ ÐºÐ»ÑŽÑ‡Ð¾Ð¼ Ð¾Ð±ÑŠÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ Ð½ÐµÐ·Ð°Ð²Ð¸Ñимо от типа Ñзыка.
-# Он иÑпользуетÑÑ Ñ‡Ñ‚Ð¾Ð±Ñ‹ показать что вÑе ключи одного или более Ñловарей должны быть
+# Он иÑпользуетÑÑ, чтобы показать что вÑе ключи одного или более Ñловарей должны быть
# добавлены в текущий Ñловарь.
foo: &foo
@@ -185,5 +185,5 @@ set2:
### Больше информации
-+ [YAML оффициальный вебÑайт](http://yaml.org/)
++ [YAML официальный вебÑайт](http://yaml.org/)
+ [YAML онлайн валидатор](http://www.yamllint.com/)
diff --git a/ru-ru/zfs-ru.html.markdown b/ru-ru/zfs-ru.html.markdown
new file mode 100644
index 00000000..46a3fbb5
--- /dev/null
+++ b/ru-ru/zfs-ru.html.markdown
@@ -0,0 +1,406 @@
+---
+category: tool
+tool: zfs
+contributors:
+ - ["sarlalian", "http://github.com/sarlalian"]
+ - ["A1EF", "https://github.com/A1EF"]
+filename: LearnZfs-ru.txt
+translators:
+ - ["A1EF", "https://github.com/A1EF"]
+lang: ru-ru
+---
+
+
+[ZFS](http://open-zfs.org/wiki/Main_Page)
+предÑтавлÑет Ñобой переоÑмыÑление ÑиÑтемы Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ…, комбинирующее в едином инÑтрументе
+традиционные файловые ÑиÑтемы и ÑиÑтемы ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ñ‚Ð¾Ð¼Ð°Ð¼Ð¸. ZFS обладает некоторой Ñпецифичной
+терминологией, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¾Ñ‚Ð»Ð¸Ñ‡Ð°ÐµÑ‚ её от более традиционных ÑиÑтем Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ…, однако имеет
+отличный набор возможноÑтей, акцентированных на удобÑтве иÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ ÑиÑтемными админиÑтраторами.
+
+
+## Концепции ZFS
+
+### Виртуальные уÑтройÑтва
+
+Виртуальное уÑтройÑтво (VDEV) подобно уÑтройÑтву RAID, предÑтавлÑемого RAID-контроллером.
+ЕÑÑ‚ÑŒ неÑколько типов виртуальных уÑтройÑтв (VDEV), которые предлагают различные преимущеÑтва,
+Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ Ð¾Ñ‚ÐºÐ°Ð·Ð¾ÑƒÑтойчивоÑÑ‚ÑŒ и ÑкороÑÑ‚ÑŒ доÑтупа. Ð’ оÑновном виртуальные уÑтройÑтва (VDEV)
+предоÑтавлÑÑŽÑ‚ лучшую отказоуÑтойчивоÑÑ‚ÑŒ и безопаÑноÑÑ‚ÑŒ, нежели RAID-контроллеры. Ðе рекомендуетÑÑ
+иÑпользовать уÑтановку RAID Ñ ZFS, поÑкольку ZFS раÑÑчитывает непоÑредÑтвенно управлÑÑ‚ÑŒ диÑками.
+
+Типы виртуальных уÑтройÑтв (VDEV)
+
+* mirror (поддерживаетÑÑ n-кратное зеркалирование)
+* raidz
+ * raidz1 (1-диÑк четноÑти, аналог RAID 5)
+ * raidz2 (2-диÑка четноÑти, аналог RAID 6)
+ * raidz3 (3-диÑка четноÑти, нет имеет аналогичного RAID-маÑÑива)
+* disk
+* file (не рекомендовано Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð¼Ñ‹ÑˆÐ»ÐµÐ½Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð¸Ð·-за Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½ÐµÐ¶ÐµÐ»Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ промежуточного ÑÐ»Ð¾Ñ Ð¸Ð½Ð¾Ð¹ файловой ÑиÑтемы)
+
+Ваши данные раÑпределÑÑŽÑ‚ÑÑ Ñреди вÑех виртуальных уÑтройÑтв (VDEV), предÑтавленных в пуле хранениÑ,
+так что увеличив чиÑло виртуальных уÑтройÑтв (VDEV), вы увеличите количеÑтво IOPS.
+
+### Пулы хранениÑ
+
+ZFS иÑпользует пулы Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ ÐºÐ°Ðº абÑтракцию над нижним уровнем провайдера Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ (VDEV), позволÑÑ Ð²Ð°Ð¼ отделить видимые пользователю
+файловые ÑиÑтемы от физичеÑкого их размещениÑ.
+
+### ZFS датаÑеты
+
+ZFS датаÑеты подобны традиционным файловым ÑиÑтемам, но имеют гораздо больше возможноÑтей, обеÑпечивающих обилие преимущеÑтв ZFS.
+ДатаÑеты поддерживают [Copy on Write](https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BF%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BF%D1%80%D0%B8_%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8), Ñнапшоты, квоты, Ñжатие и дедубликацию.
+
+
+### ОграничениÑ
+
+Один каталог может Ñодержать до 2^48 файлов, каждый до 16 ÑкÑабайт. Один пул Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ð¼Ð¾Ð¶ÐµÑ‚ Ñодержать до 256 зеттабайт (2^78) данных
+и может быть раÑпределён по 2^64 уÑтройÑтвам. Родин хоÑÑ‚ может иметь 2^64 пула хранениÑ. Лимиты огромны.
+
+
+## Команды
+
+### Пулы хранениÑ
+
+ДейÑтвиÑ:
+
+* ПроÑмотр
+* СтатуÑ
+* Удаление
+* Получение/уÑтановка ÑвойÑтв
+
+ПроÑмотр пулов
+
+```bash
+# Создание пула типа raidz
+$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+
+# ПроÑмотр пулов
+$ zpool list
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+
+# ПроÑмотр детализованной информации о конкретном пуле
+$ zpool list -v zroot
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75%
+```
+
+Ð¡Ñ‚Ð°Ñ‚ÑƒÑ Ð¿ÑƒÐ»Ð¾Ð²
+
+```bash
+# Получение информации о ÑтатуÑе пулов
+$ zpool status
+ pool: zroot
+ state: ONLINE
+ scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+
+# Скрабинг пула Ð´Ð»Ñ Ð¸ÑÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð»ÑŽÐ±Ñ‹Ñ… ошибок
+$ zpool scrub zroot
+$ zpool status -v zroot
+ pool: zroot
+ state: ONLINE
+ scan: scrub in progress since Thu Oct 15 16:59:14 2015
+ 39.1M scanned out of 106G at 1.45M/s, 20h47m to go
+ 0 repaired, 0.04% done
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+```
+
+СвойÑтва пулов
+
+```bash
+
+# Получение ÑвойÑтв пула, ÑвойÑтва могут быть заданы пользователем или ÑиÑтемой.
+$ zpool get all zroot
+NAME PROPERTY VALUE SOURCE
+zroot size 141G -
+zroot capacity 75% -
+zroot altroot - default
+zroot health ONLINE -
+...
+
+# УÑтановка Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑвойÑтва пула
+$ zpool set comment="Storage of mah stuff" zroot
+$ zpool get comment
+NAME PROPERTY VALUE SOURCE
+tank comment - default
+zroot comment Storage of mah stuff local
+```
+
+Удаление пула
+
+```bash
+$ zpool destroy test
+```
+
+
+### ДатаÑеты
+
+ДейÑтвиÑ:
+
+* Создание
+* ПроÑмотр
+* Переименование
+* Удаление
+* Получение/уÑтановка ÑвойÑтв
+
+Создание датаÑетов
+
+```bash
+# Создание датаÑета
+$ zfs create zroot/root/data
+$ mount | grep data
+zroot/root/data on /data (zfs, local, nfsv4acls)
+
+# Создание дочернего датаÑета
+$ zfs create zroot/root/data/stuff
+$ mount | grep data
+zroot/root/data on /data (zfs, local, nfsv4acls)
+zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+
+
+# Создание тома
+$ zfs create -V zroot/win_vm
+$ zfs list zroot/win_vm
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/win_vm 4.13G 17.9G 64K -
+```
+
+ПроÑмотр датаÑетов
+
+```bash
+# ПроÑмотр вÑех датаÑетов
+$ zfs list
+NAME USED AVAIL REFER MOUNTPOINT
+zroot 106G 30.8G 144K none
+zroot/ROOT 18.5G 30.8G 144K none
+zroot/ROOT/10.1 8K 30.8G 9.63G /
+zroot/ROOT/default 18.5G 30.8G 11.2G /
+zroot/backup 5.23G 30.8G 144K none
+zroot/home 288K 30.8G 144K none
+...
+
+# ПроÑмотр конкретного датаÑета
+$ zfs list zroot/home
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home 288K 30.8G 144K none
+
+# ПроÑмотр Ñнапшотов
+$ zfs list -t snapshot
+zroot@daily-2015-10-15 0 - 144K -
+zroot/ROOT@daily-2015-10-15 0 - 144K -
+zroot/ROOT/default@daily-2015-10-15 0 - 24.2G -
+zroot/tmp@daily-2015-10-15 124K - 708M -
+zroot/usr@daily-2015-10-15 0 - 144K -
+zroot/home@daily-2015-10-15 0 - 11.9G -
+zroot/var@daily-2015-10-15 704K - 1.42G -
+zroot/var/log@daily-2015-10-15 192K - 828K -
+zroot/var/tmp@daily-2015-10-15 0 - 152K -
+```
+
+Переименование датаÑетов
+
+```bash
+$ zfs rename zroot/root/home zroot/root/old_home
+$ zfs rename zroot/root/new_home zroot/root/home
+```
+
+Удаление датаÑета
+
+```bash
+# ДатаÑеты не могут быть удалены, еÑли у них имеютÑÑ ÐºÐ°ÐºÐ¸Ðµ-то Ñнапшоты
+$ zfs destroy zroot/root/home
+```
+
+Получение / уÑтановка ÑвойÑтв датаÑета
+
+```bash
+# Получение вÑех ÑвойÑтв
+$ zfs get all zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home type filesystem -
+zroot/home creation Mon Oct 20 14:44 2014 -
+zroot/home used 11.9G -
+zroot/home available 94.1G -
+zroot/home referenced 11.9G -
+zroot/home mounted yes -
+...
+
+# ÐŸÐ¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ ÑвойÑтва Ð´Ð»Ñ Ð´Ð°Ñ‚Ð°Ñета
+$ zfs get compression zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home compression off default
+
+# УÑтановка Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑвойÑтва на датаÑете
+$ zfs set compression=lz4 zroot/lamb
+
+# Получение значений выбранных ÑвойÑтв вÑех датаÑетов
+$ zfs list -o name,quota,reservation
+NAME QUOTA RESERV
+zroot none none
+zroot/ROOT none none
+zroot/ROOT/default none none
+zroot/tmp none none
+zroot/usr none none
+zroot/home none none
+zroot/var none none
+...
+```
+
+
+### Снапшоты
+
+ZFS Ñнапшоты -- одна из очень важных оÑобенноÑтей zfs
+
+* МеÑто, которое они занимают, равно разнице данных между файловой ÑиÑтемой и её Ñнапшотом
+* Ð’Ñ€ÐµÐ¼Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð·Ð°Ð½Ð¸Ð¼Ð°ÐµÑ‚ Ñчитанные Ñекунды
+* ВоÑÑтановление наÑтолько быÑтро, наÑколько позволÑет вам запиÑÑŒ данных
+* Они очень проÑÑ‚Ñ‹ в автоматизации
+
+ДейÑтвиÑ:
+
+* Создание
+* Удаление
+* Переименование
+* Получение доÑтупа к Ñнапшотам
+* Отправка / Получение
+* Клонирование
+
+
+Создание Ñнапшотов
+
+```bash
+# Создание Ñнапшота единÑтвенного датаÑета
+zfs snapshot zroot/home/sarlalian@now
+
+# Создание Ñнапшота Ð´Ð»Ñ Ñ€Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÑкого и дочерних датаÑетов
+$ zfs snapshot -r zroot/home@now
+$ zfs list -t snapshot
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home@now 0 - 26K -
+zroot/home/sarlalian@now 0 - 259M -
+zroot/home/alice@now 0 - 156M -
+zroot/home/bob@now 0 - 156M -
+...
+```
+
+Удаление Ñнапшотов
+
+```bash
+# Как удалить Ñнапшот
+$ zfs destroy zroot/home/sarlalian@now
+
+# Удаление Ñнапшота в родительÑком и дочерних датаÑетах
+$ zfs destroy -r zroot/home/sarlalian@now
+
+```
+
+Переименование Ñнапшотов
+
+```bash
+# Переименование Ñнапшота
+$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today
+$ zfs rename zroot/home/sarlalian@now today
+
+$ zfs rename -r zroot/home@now @yesterday
+```
+
+Получение доÑтупа к Ñпапшотам
+
+```bash
+# CD в каталог Ñнапшота
+$ cd /home/.zfs/snapshot/
+```
+
+Отправка и получение
+
+```bash
+# Сохранение Ñнапшота в файл
+$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz
+
+# Отправка Ñнапшота в другой датаÑет
+$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian
+
+# Отправка Ñнапшота на удаленный хоÑÑ‚
+$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian'
+
+# Отправка полного датаÑета Ñо Ñнапшотами на новый хоÑÑ‚
+$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home'
+```
+
+Клонирование Ñнапшотов
+
+```bash
+# Клонирование Ñнапшота
+$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new
+
+# Повышение клона, чтобы он больше не завиÑел от Ñнапшота
+$ zfs promote zroot/home/sarlalian_new
+```
+
+### Собираем вÑÑ‘ вмеÑте
+
+ÐижеÑледующий Ñкрипт иÑпользует FreeBSD, jails и ZFS Ð´Ð»Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ð·Ð°Ñ†Ð¸Ð¸
+подготовки чиÑтой копии Ñтейджинговой базы mysql Ñ Ð¶Ð¸Ð²Ð¾Ð¹ реплики Ñлейв-ноды.
+
+```bash
+#!/bin/sh
+
+echo "==== ОÑтановка Ñтейджингового Ñервера баз данных ===="
+jail -r staging
+
+echo "==== ОчиÑтка ÑущеÑтвующих Ñтейджингового Ñервера и Ñнапшота ===="
+zfs destroy -r zroot/jails/staging
+zfs destroy zroot/jails/slave@staging
+
+echo "==== ФикÑÐ°Ñ†Ð¸Ñ Ð±Ð°Ð·Ñ‹ на Ñлейве ===="
+echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave
+
+echo "==== Сохранение Ñнапшота файлов базы Ñлейва как zroot/jails/slave@staging ===="
+zfs snapshot zroot/jails/slave@staging
+
+echo "==== ЗапуÑк Ñлейв-ноды Ñервера баз данных ===="
+jail -c slave
+
+echo "==== Клонирование Ñнапшота Ñлейва на Ñтейджинговый Ñервер ===="
+zfs clone zroot/jails/slave@staging zroot/jails/staging
+
+echo "==== УÑтановка конфига Ñтейджингово mysql ===="
+mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave
+cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf
+
+echo "==== ÐаÑтройка Ñтейджингового файла rc.conf ===="
+mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave
+mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local
+
+echo "==== ЗапуÑк Ñтейджингово Ñервера баз данных ===="
+jail -c staging
+
+echo "==== Отключение Ñинхронизации Ñтейджинговой базы Ñ Ð¼Ð°Ñтером ===="
+echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging
+echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging
+```
+
+
+### Почитать дополнительно
+
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html)
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html)
+* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning)
+* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide)
diff --git a/rust.html.markdown b/rust.html.markdown
index 9e07e005..526d20d5 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -30,6 +30,9 @@ Rust not only fast, but also easy and efficient to code in.
// This is a comment. Line comments look like this...
// and extend multiple lines like this.
+/* Block comments
+ /* can be nested. */ */
+
/// Documentation comments look like this and support markdown notation.
/// # Examples
///
@@ -223,7 +226,7 @@ fn main() {
type FunctionPointer = fn(u32) -> u32;
let fib : FunctionPointer = fibonacci;
- println!("Fib: {}", fib(4));
+ println!("Fib: {}", fib(4)); // 5
/////////////////////////
// 3. Pattern matching //
diff --git a/scala.html.markdown b/scala.html.markdown
index d2d45dc9..bb20f624 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -302,7 +302,7 @@ do {
// Recursion is the idiomatic way of repeating an action in Scala (as in most
// other functional languages).
// Recursive functions need an explicit return type, the compiler can't infer it.
-// Here it's Unit, which is analagous to a `void` return type in Java
+// Here it's Unit, which is analogous to a `void` return type in Java
def showNumbersInRange(a: Int, b: Int): Unit = {
print(a)
if (a < b)
diff --git a/sed.html.markdown b/sed.html.markdown
new file mode 100644
index 00000000..3e6d8fc8
--- /dev/null
+++ b/sed.html.markdown
@@ -0,0 +1,285 @@
+---
+category: tool
+tool: sed
+filename: learnsed.sed
+contributors:
+ - ["Diomidis Spinellis", "https://www.spinellis.gr"]
+
+---
+
+__Sed__ is a standard tool on every POSIX-compliant UNIX system.
+It's like an editor, such as Vim, Visual Studio Code, Atom, or Sublime.
+However, rather than typing the commands interactively, you
+provide them on the command line or in a file.
+
+_Sed_'s advantages over an interactive editor is that it can be easily
+used to automate text processing tasks, and that it can process
+efficiently huge (terabyte-sized) files.
+It can perform more complex tasks than _grep_ and for many text
+processing tasks its commands are much shorter than what you would
+write in _awk_, _Perl_, or _Python_.
+
+_Sed_ works by reading a line of text (by default from its standard
+input, unless some files are specified as arguments), processing
+it with the specified commands, and then outputting the result
+on its standard output.
+You can suppress the default output by specifying the `-n` command-line
+argument.
+
+```perl
+#!/usr/bin/sed -f
+# Files that begin with the above line and are given execute permission
+# can be run as regular scripts.
+
+# Comments are like this.
+
+# Commands consist of a single letter and many can be preceded
+# by a specification of the lines to which they apply.
+
+# Delete the input's third line.
+3d
+
+# The same command specified the command line as an argument to sed:
+# sed 3d
+
+# For many commands the specification can consist of two addresses,
+# which select an inclusive range.
+# Addresses can be specified numerically ($ is the last line) or through
+# regular expressions delimited by /.
+
+# Delete lines 1-10
+1,10d
+
+# Lines can also be specified as regular expressions, delimited by /.
+
+# Delete empty lines.
+/^$/d
+
+# Delete blocks starting with SPOILER-BEGIN and ending with SPOILER-END.
+/SPOILER-BEGIN/,/SPOILER-END/d
+
+# A command without an address is applied to all lines.
+
+# List lines in in a visually unambiguous form (e.g. tab appears as \t).
+l
+
+# A command prefixed by ! will apply to non-matching lines.
+# Keep only lines starting with a #.
+/^#/!d
+
+# Below are examples of the most often-used commands.
+
+# Substitute the first occurence in a line of John with Mary.
+s/John/Mary/
+
+# Remove all underscore characters (global substitution).
+s/_//g
+
+# Remove all HTML tags.
+s/<[^>]*>//g
+
+# In the replacement string & is the regular expression matched.
+
+# Put each line inside double quotes.
+s/.*/"&"/
+
+# In the matched regular expression \(pattern\) is used to store
+# a pattern into a buffer.
+# In the replacement string \1 refers to the first pattern, \2 to the second
+# and so on. \u converts the following character to uppercase \l to lowercase.
+
+# Convert snake_case_identifiers into camelCaseIdentifiers.
+s/_\(.\)/\u\1/g
+
+
+# The p (print) command is typically used together with the -n
+# command-line option, which disables the print by default functionality.
+# Output all lines between ``` and ```.
+/```/,/```/p
+
+
+# The y command maps characters from one set to another.
+# Swap decimal and thousand separators (1,234,343.55 becomes 1.234.343,55).
+y/.,/,./
+
+# Quit after printing the line starting with END.
+/^END/q
+
+# You can stop reading here, and still get 80% of sed's benefits.
+# Below are examples of how you can specify multiple sed commands.
+
+# You can apply multiple commands by separating them with a newline or
+# a semicolon.
+
+# Delete the first and the last line.
+1d
+$d
+
+# Delete the first and the last line.
+1d;$d
+
+
+# You can group commands in { } blocks.
+
+# Convert first line to uppercase and print it.
+1 {
+ s/./\u&/g
+ p
+}
+
+# Convert first line to uppercase and print it (less readable one-liner).
+1{s/./\u&/g;p;}
+
+
+# You can also stop reading here, if you're not interested in creating
+# sed script files.
+
+# Below are more advanced commands. You typically put these in a file
+# rather than specify them on a command line. If you have to use
+# many of these commands in a script, consider using a general purpose
+# scripting language, such as Python or Perl.
+
+# Append a line containing "profile();" after each line ending with ";".
+/;$/a\
+profile();
+
+# Insert a line containing "profile();" before each line ending with ";".
+/;$/i\
+profile();
+
+# Change each line text inside REDACTED blocks into [REDACTED].
+/REDACTED-BEGIN/,/REDACTED-END/c\
+[REDACTED]
+
+# Replace the tag "<ourstyle>" by reading and outputting the file style.css.
+/<ourstyle>/ {
+ r style.css
+ d
+}
+
+# Change each line inside REDACTED blocks into [REDACTED].
+# Also write (append) a copy of the redacted text in the file redacted.txt.
+/REDACTED-BEGIN/,/REDACTED-END/ {
+ w redacted.txt
+ c\
+ [REDACTED]
+}
+
+# All operations described so far operate on a buffer called "pattern space".
+# In addition, sed offers another buffer called "hold space".
+# The following commands operate on the two, and can be used to keep
+# state or combine multiple lines.
+
+# Replace the contents of the pattern space with the contents of
+# the hold space.
+g
+
+# Append a newline character followed by the contents of the hold
+# space to the pattern space.
+G
+
+# Replace the contents of the hold space with the contents of the
+# pattern space.
+h
+
+# Append a newline character followed by the contents of the
+# pattern space to the hold space.
+H
+
+# Delete the initial segment of the pattern space through the first
+# newline character and start the next cycle.
+D
+
+# Replace the contents of the pattern space with the contents of
+# the hold space.
+g
+
+# Append a newline character followed by the contents of the hold
+# space to the pattern space.
+G
+
+# Replace the contents of the hold space with the contents of the
+# pattern space.
+h
+
+# Append a newline character followed by the contents of the
+# pattern space to the hold space.
+H
+
+# Write the pattern space to the standard output if the default
+# output has not been suppressed, and replace the pattern space
+# with the next line of input.
+n
+
+# Append the next line of input to the pattern space, using an
+# embedded newline character to separate the appended material from
+# the original contents. Note that the current line number
+# changes.
+N
+
+# Write the pattern space, up to the first newline character to the
+# standard output.
+P
+
+# Swap the contents of the pattern and hold spaces.
+x
+
+# Here is a complete example of some of the buffer commands.
+# Move the file's first line to its end.
+1 {
+ h
+ d
+}
+
+$ {
+ p
+ x
+}
+
+
+# Three sed commands influence a script's control flow
+
+# Name this script position "my_label", to which the "b" and
+# "t" commands may branch.
+:my_label
+
+# Continue executing commands from the position of my_label.
+b my_label
+
+# Branch to the end of the script.
+b
+
+# Branch to my_label if any substitutions have been made since the most
+# recent reading of an input line or execution of a "t" (test) function.
+t my_label
+
+# Here is a complete example of branching
+# Join lines that end with a backspace into a single space-separated one
+
+# Name this position "loop"
+: loop
+# On lines ending with a backslash
+/\\$/ {
+ # Read the next line and append it to the pattern space
+ N
+ # Substitute backslash newline with a space
+ s/\\\n/ /
+ # Branch to the top for testing this line's ending
+ b loop
+}
+```
+
+Further Reading:
+
+* [The Open Group: sed - stream editor](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html)
+ The POSIX standard regarding sed.
+ Follow this for maximum portability.
+* [FreeBSD sed -- stream editor](https://www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1)
+ The BSD manual page.
+ This version of sed runs on BSD systems and macOS.
+* [Project GNU: sed, a stream editor](https://www.gnu.org/software/sed/manual/sed.html)
+ The GNU manual page. GNU sed is found on most Linux systems.
+* [Lee E. McMahon: SED -- A Non-interactive Text Editor](https://wolfram.schneider.org/bsd/7thEdManVol2/sed/sed.pdf)
+ The original sed documentation
+* [A collection of sed resources](http://sed.sourceforge.net/)
+* [The sed FAQ](http://sed.sourceforge.net/sedfaq.html)
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
index d55ab7d5..144b4bbf 100644
--- a/set-theory.html.markdown
+++ b/set-theory.html.markdown
@@ -2,7 +2,9 @@
category: Algorithms & Data Structures
name: Set theory
contributors:
+ - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"]
---
+
Set theory is a branch of mathematics that studies sets, their operations, and their properties.
* A set is a collection of disjoint items.
@@ -17,7 +19,7 @@ Set theory is a branch of mathematics that studies sets, their operations, and t
* the cross operator, `×`, means "the Cartesian product of".
### Qualifiers
-* the colon qualifier, `:`, means "such that";
+* the colon, `:`, or the vertical bar `|` qualifiers are interchangeable and mean "such that";
* the membership qualifier, `∈`, means "belongs to";
* the subset qualifier, `⊆`, means "is a subset of";
* the proper subset qualifier, `⊂`, means "is a subset of but is not equal to".
@@ -59,7 +61,7 @@ Long lists may be shortened with ellipses as long as the context is clear. For e
Set builder notation is a more descriptive way of constructing a set. It relies on a _subject_ and a _predicate_ such that `S = { subject : predicate }`. For example,
```
-A = { x : x is a vowel } = { a, e, i, o, u, y}
+A = { x : x is a vowel } = { a, e, i, o, u }
B = { x : x ∈ N, x < 10 } = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
C = { x : x = 2k, k ∈ N } = { 0, 2, 4, 6, 8, ... }
```
diff --git a/sing.html.markdown b/sing.html.markdown
index 2e439800..50b52390 100644
--- a/sing.html.markdown
+++ b/sing.html.markdown
@@ -154,7 +154,7 @@ fn learnTypes() void
sys.validate(dyna_array.size() == 1);
// a map that associates a number to a string.
- // "map(x)..." reads "map with key of type x and vaue of type..."
+ // "map(x)..." reads "map with key of type x and value of type..."
var a_map map(string)i32;
a_map.insert("one", 1);
diff --git a/sk-sk/elixir-sk.html.markdown b/sk-sk/elixir-sk.html.markdown
index 2401f92e..c9522b49 100644
--- a/sk-sk/elixir-sk.html.markdown
+++ b/sk-sk/elixir-sk.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -14,7 +14,7 @@ Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym
strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax
a množstvo funkcií.
-```Elixir
+```elixir
# Jednoriadkový komentár zaÄína symbolom #
@@ -24,7 +24,7 @@ a množstvo funkcií.
# Pre spustenie Elixir shellu zadajte príkaz `iex`
# Kompiláciu zdrojových kódov vykonáte príkazom `elixirc`
-# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir
+# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali Elixir
# správne.
## ---------------------------
@@ -86,7 +86,7 @@ reťazec.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` v elixire vráti ASCII Äíselnú reprezentáciu pre znak `a`
+# `?a` v Elixir vráti ASCII Äíselnú reprezentáciu pre znak `a`
?a #=> 97
# Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>`
@@ -119,7 +119,7 @@ pohlavia.gillian #=> "žena"
5 * 2 #=> 10
10 / 2 #=> 5.0
-# V elixire operátor `/` vždy vráti float (reálne Äíslo).
+# V Elixir operátor `/` vždy vráti float (reálne Äíslo).
# Pre celoÄíselné delenie sa používa `div`
div(10, 2) #=> 5
@@ -182,7 +182,7 @@ else
end
# Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v
-# elixire sa spoliehajú práve na pattern matching.
+# Elixir sa spoliehajú práve na pattern matching.
# `case` dovolí nám porovnať hodnotu oproti mnohým vzorom:
case {:one, :two} do
@@ -314,7 +314,7 @@ Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048
# Geometria.oblast({:kruh, "nie_je_cislo"})
#=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1
-# VÄaka nemeniteľnosti (immutability) je rekurzia významnou ÄasÅ¥ou elixiru
+# VÄaka nemeniteľnosti (immutability) je rekurzia významnou ÄasÅ¥ou Elixir
defmodule Rekurzia do
def sumuj_zoznam([hlavicka | schvost], acc) do
sumuj_zoznam(chvost, acc + hlavicka)
@@ -389,7 +389,7 @@ end
## ---------------------------
# Elixir sa pri konkurencii spolieha na Actor model. VÅ¡etko Äo je
-# potrebné na písanie konkuretných programov v elixire sú tri primitívy:
+# potrebné na písanie konkuretných programov v Elixir sú tri primitívy:
# spawning procesy, posielanie a prijímanie správ.
# Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako
diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown
index 21741406..ddcd9658 100644
--- a/sk-sk/git-sk.html.markdown
+++ b/sk-sk/git-sk.html.markdown
@@ -514,8 +514,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/sk-sk/latex-sk.html.markdown.tex b/sk-sk/latex-sk.html.markdown
index 5e2f9c7f..5e2f9c7f 100644
--- a/sk-sk/latex-sk.html.markdown.tex
+++ b/sk-sk/latex-sk.html.markdown
diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex
deleted file mode 100644
index 5cc7b11f..00000000
--- a/sk-sk/learn-latex-sk.tex
+++ /dev/null
@@ -1,209 +0,0 @@
-% VÅ¡etky komentáre zaÄínajú s %
-% Viac-riadkové komentáre sa nedajú urobiť
-
-% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer
-
-% Každý LaTeX príkaz zaÄína s opaÄným lomítkom (\)
-
-% LaTeX dokumenty zaÄínajú s definíciou typu kompilovaného dokumentu
-% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atÄ.
-% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu.
-\documentclass[12pt]{article}
-
-% ÄŽalej definujeme balíÄky, ktoré dokuemnt používa.
-% Ak chceÅ¡ zahrnúť grafiku, farebný text, Äi zdrojový kód iného jazyka, musíš rozšíriÅ¥ možnosti LaTeXu dodatoÄnými balíÄkami.
-% Zahŕňam float a caption. Na podporu slovenÄiny treba zahrnúť aj utf8 balíÄek.
-\usepackage{caption}
-\usepackage{float}
-\usepackage[utf8]{inputenc}
-% Tu môžme definovať ostatné vlastnosti dokumentu!
-% Autori tohto dokumentu, "\\*" znamená "choÄ na nový riadok"
-\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková}
-% Vygeneruje dnešný dátum
-\date{\today}
-\title{NauÄ sa LaTeX za Y Minút!}
-% Teraz môžme zaÄaÅ¥ pracovaÅ¥ na samotnom dokumente.
-% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble")
-\begin{document}
-% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu.
-\maketitle
-
-% VäÄÅ¡ina odborných Älánkov má abstrakt, na jeho vytvorenie môžeÅ¡ použiÅ¥ preddefinované príkazy.
-% Ten by sa mal zobraziÅ¥ v logickom poradí, teda po hlaviÄke,
-% no pred hlavnými sekciami tela..
-% Tento príkaz je tiež dostupný v triedach article a report.
-% Tzv. makro "abstract" je fixnou súÄasÅ¥ou LaTeXu, ak chceme použiÅ¥ abstract
-% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom
-\renewcommand\abstractname{Abstrakt}
-
-\begin{abstract}
-LaTeX dokumentácia v LaTeXe! Aké netradiÄné rieÅ¡enie cudzieho nápadu!
-\end{abstract}
-
-% Príkazy pre sekciu sú intuitívne
-% Všetky nadpisy sekcií sú pridané automaticky do obsahu.
-\section{Úvod}
-ÄŒaute, volám sa Colton a spoloÄne sa pustíme do skúmania LaTeXu (toho druhého)!
-
-\section{Ďalšia sekcia}
-Toto je text ÄalÅ¡ej sekcie. Myslím, že potrebuje podsekciu.
-
-\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne.
-Zdá sa mi, že treba ÄalÅ¡iu.
-
-\subsubsection{Pytagoras}
-To je ono!
-\label{subsec:pytagoras}
-
-% Použitím '*' môžeme potlaÄiÅ¥ zabudované Äíslovanie LaTeXu.
-% Toto funguje aj na iné príkazy.
-\section*{Toto je neÄíslovaná sekcia}
-VÅ¡etky Äíslované byÅ¥ nemusia!
-
-\section{Nejaké poznámoÄky}
-Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak
-potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do
-zdrojového kódu. \\
-
-\section{Zoznamy}
-Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam.
-\begin{enumerate} % "enumerate" spustí Äíslovanie prvkov.
- % \item povie LaTeXu, ako že treba pripoÄítaÅ¥ 1
- \item Vlašský šalát.
- \item 5 rožkov.
- \item 3 Horalky.
- % Äíslovanie môžeme pozmeniÅ¥ použitím []
- \item[koľko?] Stredne veľkých guliÄkoviek.
-
- Ja už nie som položka zoznamu, no stále som ÄasÅ¥ "enumerate".
-
-\end{enumerate} % VÅ¡etky prostredia konÄia s "end".
-
-\section{Matika}
-
-Jedným z primárnych použití LaTeXu je písanie akademických, Äi technických prác. ZvyÄajne za použitia matematiky a vedy. Podpora Å¡peciálnych symbolov preto nemôže chýbaÅ¥!\\
-
-Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať;
-Množinové a relaÄné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\
-
-Množiny a relácie hrajú hlavnú rolu v mnohých matematických Älánkoch.
-Takto napíšeÅ¡, že nieÄo platí pre vÅ¡etky x patriace do X, $\forall$ x $\in$ X. \\
-% Všimni si, že som pridal $ pred a po symboloch. Je to
-% preto, lebo pri písaní sme v textovom móde,
-% no matematické symboly existujú len v matematickom.
-% Vstúpime doňho z textového práve '$' znamienkami.
-% Platí to aj opaÄne. Premenná môže byÅ¥ zobrazená v matematickom móde takisto.
-% Do matematického módu sa dá dostať aj s \[\]
-
-\[a^2 + b^2 = c^2 \]
-
-Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$.
-Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal!
-
-Operátory sú dôležitou súÄasÅ¥ou matematických dokumentov:
-goniometrické funkcie ($\sin$, $\cos$, $\tan$),
-logaritmy and exponenciálne výrazy ($\log$, $\exp$),
-limity ($\lim$), atÄ.
-majú pred-definované LaTeXové príkazy.
-Napíšme si rovnicu, nech vidíme, ako to funguje: \\
-
-$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
-
-Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách:
-
-% 10 / 7
-$^{10}/_{7}$
-
-% Relatívne komplexné zlomky sa píšu ako
-% \frac{Äitateľ}{menovateľ}
-$\frac{n!}{k!(n - k)!}$ \\
-
-Rovnice tiež môžeme zadať v "rovnicovom prostredí".
-
-% Takto funguje rovnicové prostredie
-\begin{equation} % vstúpi do matematického módu
- c^2 = a^2 + b^2.
- \label{eq:pythagoras} % na odkazovanie
-\end{equation} % vÅ¡etky \begin príkazy musia maÅ¥ koneÄný príkaz.
-
-Teraz môžeme odkázať na novovytvorenú rovnicu!
-Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. OdkazovaÅ¥ môžme na veľa vecí, napr na: Äísla, rovnice, Äi sekcie.
-
-Sumácie a Integrály sa píšu príkazmi sum a int:
-
-% Niektoré prekladaÄe LaTeXu sa môžu sÅ¥ažovaÅ¥ na prázdne riadky (ak tam sú)
-% v rovnicovom prostredí.
-\begin{equation}
- \sum_{i=0}^{5} f_{i}
-\end{equation}
-\begin{equation}
- \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
-\end{equation}
-
-\section{Obrázky}
-
-Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok.
-\renewcommand\figurename{Obrázok}
-\begin{figure}[H] % H znaÄí možnosÅ¥ zarovnania.
- \centering % nacentruje obrázok na stránku
- % Vloží obrázok na 80% šírky stránky.
- %\includegraphics[width=0.8\linewidth]{right-triangle.png}
- % Zakomentované kvôli kompilácií, použi svoju predstavivosť :).
- \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$}
- \label{fig:right-triangle}
-\end{figure}
-% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj
-\renewcommand\tablename{Tabuľka}
-
-\subsection{Tabuľky}
-Tabuľky sa vkládajú podobne ako obrázky.
-
-\begin{table}[H]
- \caption{Nadpis tabuľky.}
- % zátvorky: {} hovoria ako sa vykreslí každý riadok.
- % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz!
- \begin{tabular}{c|cc}
- Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $
- \hline % horizontálna Äiara
- 1 & Ladislav & Meliško \\
- 2 & Eva & Máziková
- \end{tabular}
-\end{table}
-
-% \section{Hyperlinks} % Už Äoskoro :)
-
-\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)}
-Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom.
-Toto sa robí vo verbatim prostredí.
-
-% Tiež sú na to Å¡peciálne balíÄky, (napr. minty, lstlisting, atÄ.)
-% ale verbatim je to najzákladnejÅ¡ie, Äo môžeÅ¡ použiÅ¥.
-\begin{verbatim}
- print("Hello World!")
- a%b; pozri! Vo verbatime môžme použiť % znamienka.
- random = 4; #priradené randomným hodom kockou
-\end{verbatim}
-
-\section{Kompilácia}
-
-Už by bolo naÄase túto nádheru skompilovaÅ¥ a zhliadnuÅ¥ jej úžasnú úžasnosÅ¥ v podobe LaTeX pdfka, Äo povieÅ¡?
-(áno, tento dokument sa musí kompilovať). \\
-Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov:
- \begin{enumerate}
- \item Napíš dokument v Äistom texte (v "zdrojáku").
- \item Skompiluj zdroják na získanie pdfka.
- Kompilácia by mala vyzerať nasledovne (v Linuxe): \\
- \begin{verbatim}
- $pdflatex learn-latex.tex learn-latex.pdf
- \end{verbatim}
- \end{enumerate}
-
-Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie.
-Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte.
-
-\section{Koniec}
-
-To je zatiaľ všetko!
-
-% koniec dokumentu
-\end{document}
diff --git a/sl-si/asciidoc-sl.html.markdown b/sl-si/asciidoc-sl.html.markdown
index 52f30fbd..84bb85a1 100644
--- a/sl-si/asciidoc-sl.html.markdown
+++ b/sl-si/asciidoc-sl.html.markdown
@@ -6,7 +6,7 @@ contributors:
translators:
- ["Filip Å tamcar", "https://github.com/filips123"]
lang: sl-si
-filename: asciidoc-sl.md
+filename: asciidoc-sl.adoc
---
AsciiDoc je oznaÄevalni jezik, ki je podoben Markdownu in ga je mogoÄe uporabiti za vse od knjig do spletnih dnevnikov. Jezik, ki ga je leta 2002 ustvaril Stuart Rackham, je preprost, vendar omogoÄa veliko prilagoditev.
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index aaa592dc..9c2e870e 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -2,16 +2,15 @@
language: Smalltalk
filename: smalltalk.st
contributors:
- - ["Jigyasa Grover", "https://github.com/jigyasa-grover"]
+ - ["Jigyasa Grover", "https://jigyasa-grover.github.io"]
- ["tim Rowledge", "tim@rowledge.org"]
---
+<blockquote>Every effort has been made in the preparation of this material to ensure the accuracy and completeness of the information presented. However, no guarantee is given nor responsibility taken for errors or omissions. In case of any error, questions or suggestions on reach out to me at <a href="https://jigyasa-grover.github.io" target="_blank">jigyasa-grover.github.io</a> or drop me an e-mail at <a href="mailto:grover.jigyasa1@gmail.com" target="_blank">grover[dot]jigyasa1[at]gmail.com</a>.</blockquote>
- Smalltalk is a fully object-oriented, dynamically typed, reflective programming language with no 'non-object' types.
- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis."
- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s.
-`Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at grover.jigyasa1@gmail.com.`
-
## The Basics
### Everything is an object
@@ -60,7 +59,7 @@ doSomethingWith: argumentObject
Everything here except the `^` involves sending more messages. Event the `ifTrue:` that you might think is a language control structure is just Smalltalk code.
-We start by sending `size` to `self`. `self` is the object currently running the code - so in this case it is the myObject we started with. `size` is a very common message that we might anticipate tells us something about how big an object is; you could look it up with the Smalltalk tools very simply. The result we get is then sent the message `>` with the plain old integer 4 (which is an object too; no strange primitive types to pollute the system here) and nobody should be surprised the `>` is a comparison that answers true or false. That boolean (which is actually a Boolean object in Smalltalk) is sent the message `ifTrue:` with the block of code between the `[]` as its argument; obvioulsy a true boolean might be expected to run that block of code and a false to ignore it.
+We start by sending `size` to `self`. `self` is the object currently running the code - so in this case it is the myObject we started with. `size` is a very common message that we might anticipate tells us something about how big an object is; you could look it up with the Smalltalk tools very simply. The result we get is then sent the message `>` with the plain old integer 4 (which is an object too; no strange primitive types to pollute the system here) and nobody should be surprised the `>` is a comparison that answers true or false. That boolean (which is actually a Boolean object in Smalltalk) is sent the message `ifTrue:` with the block of code between the `[]` as its argument; obviously a true boolean might be expected to run that block of code and a false to ignore it.
If the block is run then we do some more message sending to the argument object and noting the `^` we return the answer back to our starting point and it gets assigned to `result`. If the block is ignored we seem to run out of code and so `self` is returned and assigned to `result`.
@@ -162,7 +161,7 @@ b := (x < 5) xor: (y > 1). "test if one true and other false"
b := 5 between: 3 and: 12. "between (inclusive)"
b := 123 isKindOf: Number. "test if object is class or subclass of"
b := 123 isMemberOf: SmallInteger. "test if object is type of class"
-b := 123 respondsTo: sqrt. "test if object responds to message"
+b := 123 respondsTo: #sqrt. "test if object responds to message"
b := x isNil. "test if object is nil"
b := x isZero. "test if number is zero"
b := x positive. "test if number is positive"
diff --git a/solidity.html.markdown b/solidity.html.markdown
index 5f8ef407..d40536b4 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -214,7 +214,7 @@ assert(c >= a); // assert tests for internal invariants; require is used for use
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
-// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truely random number using something like Chainlink VRF.
+// No random functions built in, you can get a pseduo-random number by hashing the current blockhash, or get a truly random number using something like Chainlink VRF.
// https://docs.chain.link/docs/get-a-random-number
// Type casting
@@ -278,7 +278,7 @@ f(22); // call
// Delete can be called on most types
// (does NOT destroy value, but sets value to 0, the initial value)
-uint x = 5;
+delete x;
// Destructuring/Tuples
@@ -388,7 +388,7 @@ block.gasLimit();
storage['abc'] = 'def'; // maps 256 bit words to 256 bit words
-// 4. FUNCTIONS AND MORE
+// 5. FUNCTIONS AND MORE
// A. Functions
// Simple function
function increment(uint x) returns (uint) {
@@ -396,13 +396,13 @@ function increment(uint x) returns (uint) {
return x;
}
-// Functions can return many arguments, and by specifying returned arguments
-// name don't need to explicitly return
+// Functions can return many arguments,
+// and by specifying returned arguments name explicit return is not needed
function increment(uint x, uint y) returns (uint x, uint y) {
x += 1;
y += 1;
}
-// Call previous functon
+// Call previous function
uint (a,b) = increment(1,1);
// 'view' (alias for 'constant')
@@ -435,7 +435,7 @@ function increment(uint x) view returns (uint x) {
// Functions hoisted - and can assign a function to a variable
function a() {
var z = b;
- b();
+ z();
}
function b() {
@@ -494,9 +494,9 @@ Coin.LogSent().watch({}, '', function(error, result) {
// '_' (underscore) often included as last line in body, and indicates
// function being called should be placed there
modifier onlyAfter(uint _time) { require (now >= _time); _; }
-modifier onlyOwner { require(msg.sender == owner) _; }
+modifier onlyOwner { require(msg.sender == owner); _; }
// commonly used with state machines
-modifier onlyIfStateA (State currState) { require(currState == State.A) _; }
+modifier onlyIfStateA (State currState) { require(currState == State.A); _; }
// Append right after function declaration
function changeOwner(newOwner)
@@ -646,7 +646,7 @@ reveal(100, "mySecret");
// All data to start of time is stored in blockchain, so
// anyone can observe all previous data and changes
-// E. Oracles and External Data
+// D. Oracles and External Data
// Oracles are ways to interact with your smart contracts outside the blockchain.
// They are used to get data from the real world, send post requests, to the real world
// or vise versa.
@@ -654,7 +654,7 @@ reveal(100, "mySecret");
// Time-based implementations of contracts are also done through oracles, as
// contracts need to be directly called and can not "subscribe" to a time.
// Due to smart contracts being decentralized, you also want to get your data
-// in a decentralized manner, other your run into the centralized risk that
+// in a decentralized manner, otherwise you run into the centralized risk that
// smart contract design matter prevents.
// To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds
@@ -671,12 +671,12 @@ reveal(100, "mySecret");
// Setting up oracle networks yourself
-// D. Cron Job
+// E. Cron Job
// Contracts must be manually called to handle time-based scheduling; can create external
// code to regularly ping, or provide incentives (ether) for others to
//
-// E. Observer Pattern
+// F. Observer Pattern
// An Observer Pattern lets you register as a subscriber and
// register a function which is called by the oracle (note, the oracle pays
// for this action to be run)
@@ -714,7 +714,7 @@ contract SomeOracle {
// Now, your client contract can addSubscriber by importing SomeOracleCallback
// and registering with Some Oracle
-// F. State machines
+// G. State machines
// see example below for State enum and inState modifier
```
diff --git a/sorbet.html.markdown b/sorbet.html.markdown
new file mode 100644
index 00000000..9c2e809b
--- /dev/null
+++ b/sorbet.html.markdown
@@ -0,0 +1,1040 @@
+---
+language: sorbet
+filename: learnsorbet.rb
+contributors:
+ - ["Jeremy Kaplan", "https://jdkaplan.dev"]
+---
+
+Sorbet is a type checker for Ruby. It adds syntax for method signatures that
+enable both static and runtime type checking.
+
+The easiest way to see it in action is in the playground at
+[sorbet.run](https://sorbet.run).
+
+Try copying in one of the sections below! Each top-level `class` or `module`
+is independent from the others.
+
+```ruby
+# Every file should have a "typed sigil" that tells Sorbet how strict to be
+# during static type checking.
+#
+# Strictness levels (lax to strict):
+#
+# ignore: Sorbet won't even read the file. This means its contents are not
+# visible during type checking. Avoid this.
+#
+# false: Sorbet will only report errors related to constant resolution. This is
+# the default if no sigil is included.
+#
+# true: Sorbet will report all static type errors. This is the sweet spot of
+# safety for effort.
+#
+# strict: Sorbet will require that all methods, constants, and instance
+# variables have static types.
+#
+# strong: Sorbet will no longer allow anything to be T.untyped, even
+# explicitly. Almost nothing satisfies this.
+
+# typed: true
+
+# Include the runtime type-checking library. This lets you write inline sigs
+# and have them checked at runtime (instead of running Sorbet as RBI-only).
+# These runtime checks happen even for files with `ignore` or `false` sigils.
+require 'sorbet-runtime'
+
+class BasicSigs
+ # Bring in the type definition helpers. You'll almost always need this.
+ extend T::Sig
+
+ # Sigs are defined with `sig` and a block. Define the return value type with
+ # `returns`.
+ #
+ # This method returns a value whose class is `String`. These are the most
+ # common types, and Sorbet calls them "class types".
+ sig { returns(String) }
+ def greet
+ 'Hello, World!'
+ end
+
+ # Define parameter value types with `params`.
+ sig { params(n: Integer).returns(String) }
+ def greet_repeat(n)
+ (1..n).map { greet }.join("\n")
+ end
+
+ # Define keyword parameters the same way.
+ sig { params(n: Integer, sep: String).returns(String) }
+ def greet_repeat_2(n, sep: "\n")
+ (1..n).map { greet }.join(sep)
+ end
+
+ # Notice that positional/keyword and required/optional make no difference
+ # here. They're all defined the same way in `params`.
+
+ # For lots of parameters, it's nicer to use do..end and a multiline block
+ # instead of curly braces.
+ sig do
+ params(
+ str: String,
+ num: Integer,
+ sym: Symbol,
+ ).returns(String)
+ end
+ def uhh(str:, num:, sym:)
+ 'What would you even do with these?'
+ end
+
+ # For a method whose return value is useless, use `void`.
+ sig { params(name: String).void }
+ def say_hello(name)
+ puts "Hello, #{name}!"
+ end
+
+ # Splats! Also known as "rest parameters", "*args", "**kwargs", and others.
+ #
+ # Type the value that a _member_ of `args` or `kwargs` will have, not `args`
+ # or `kwargs` itself.
+ sig { params(args: Integer, kwargs: String).void }
+ def no_op(*args, **kwargs)
+ if kwargs[:op] == 'minus'
+ args.each { |i| puts(i - 1) }
+ else
+ args.each { |i| puts(i + 1) }
+ end
+ end
+
+ # Most initializers should be `void`.
+ sig { params(name: String).void }
+ def initialize(name:)
+ # Instance variables must have annotated types to participate in static
+ # type checking.
+
+ # The value in `T.let` is checked statically and at runtime.
+ @upname = T.let(name.upcase, String)
+
+ # Sorbet can infer this one!
+ @name = name
+ end
+
+ # Constants also need annotated types.
+ SORBET = T.let('A delicious frozen treat', String)
+
+ # Class variables too.
+ @@the_answer = T.let(42, Integer)
+
+ # Sorbet knows about the `attr_*` family.
+ sig { returns(String) }
+ attr_reader :upname
+
+ sig { params(write_only: Integer).returns(Integer) }
+ attr_writer :write_only
+
+ # You say the reader part and Sorbet will say the writer part.
+ sig { returns(String) }
+ attr_accessor :name
+end
+
+module Debugging
+ extend T::Sig
+
+ # Sometimes it's helpful to know what type Sorbet has inferred for an
+ # expression. Use `T.reveal_type` to make type-checking show a special error
+ # with that information.
+ #
+ # This is most useful if you have Sorbet integrated into your editor so you
+ # can see the result as soon as you save the file.
+
+ sig { params(obj: Object).returns(String) }
+ def debug(obj)
+ T.reveal_type(obj) # Revealed type: Object
+ repr = obj.inspect
+
+ # Remember that Ruby methods can be called without arguments, so you can
+ # save a couple characters!
+ T.reveal_type repr # Revealed type: String
+
+ "DEBUG: " + repr
+ end
+end
+
+module StandardLibrary
+ extend T::Sig
+ # Sorbet provides some helpers for typing the Ruby standard library.
+
+ # Use T::Boolean to catch both `true` and `false`.
+ #
+ # For the curious, this is equivalent to
+ #
+ # T.type_alias { T.any(TrueClass, FalseClass) }
+ #
+ sig { params(str: String).returns(T::Boolean) }
+ def confirmed?(str)
+ str == 'yes'
+ end
+
+ # Remember that the value `nil` is an instance of NilClass.
+ sig { params(val: NilClass).void }
+ def only_nil(val:); end
+
+ # To avoid modifying standard library classes, Sorbet provides wrappers to
+ # support common generics.
+ #
+ # Here's the full list:
+ # * T::Array
+ # * T::Enumerable
+ # * T::Enumerator
+ # * T::Hash
+ # * T::Range
+ # * T::Set
+ sig { params(config: T::Hash[Symbol, String]).returns(T::Array[String]) }
+ def merge_values(config)
+ keyset = [:old_key, :new_key]
+ config.each_pair.flat_map do |key, value|
+ keyset.include?(key) ? value : 'sensible default'
+ end
+ end
+
+ # Sometimes (usually dependency injection), a method will accept a reference
+ # to a class rather than an instance of the class. Use `T.class_of(Dep)` to
+ # accept the `Dep` class itself (or something that inherits from it).
+ class Dep; end
+
+ sig { params(dep: T.class_of(Dep)).returns(Dep) }
+ def dependency_injection(dep:)
+ dep.new
+ end
+
+ # Blocks, procs, and lambdas, oh my! All of these are typed with `T.proc`.
+ #
+ # Limitations:
+ # 1. All parameters are assumed to be required positional parameters.
+ # 2. The only runtime check is that the value is a `Proc`. The argument types
+ # are only checked statically.
+ sig do
+ params(
+ data: T::Array[String],
+ blk: T.proc.params(val: String).returns(Integer),
+ ).returns(Integer)
+ end
+ def count(data, &blk)
+ data.sum(&blk)
+ end
+
+ sig { returns(Integer) }
+ def count_usage
+ count(["one", "two", "three"]) { |word| word.length + 1 }
+ end
+
+ # If the method takes an implicit block, Sorbet will infer `T.untyped` for
+ # it. Use the explicit block syntax if the types are important.
+ sig { params(str: String).returns(T.untyped) }
+ def implicit_block(str)
+ yield(str)
+ end
+
+ # If you're writing a DSL and will execute the block in a different context,
+ # use `bind`.
+ sig { params(num: Integer, blk: T.proc.bind(Integer).void).void }
+ def number_fun(num, &blk)
+ num.instance_eval(&blk)
+ end
+
+ sig { params(num: Integer).void }
+ def number_fun_usage(num)
+ number_fun(10) { puts digits.join }
+ end
+
+ # If the block doesn't take any parameters, don't include `params`.
+ sig { params(blk: T.proc.returns(Integer)).returns(Integer) }
+ def doubled_block(&blk)
+ 2 * blk.call
+ end
+end
+
+module Combinators
+ extend T::Sig
+ # These methods let you define new types from existing types.
+
+ # Use `T.any` when you have a value that can be one of many types. These are
+ # sometimes known as "union types" or "sum types".
+ sig { params(num: T.any(Integer, Float)).returns(Rational) }
+ def hundreds(num)
+ num.rationalize
+ end
+
+ # `T.nilable(Type)` is a convenient alias for `T.any(Type, NilClass)`.
+ sig { params(val: T.nilable(String)).returns(Integer) }
+ def strlen(val)
+ val.nil? ? -1 : val.length
+ end
+
+ # Use `T.all` when you have a value that must satisfy multiple types. These
+ # are sometimes known as "intersection types". They're most useful for
+ # interfaces (described later), but can also describe helper modules.
+
+ module Reversible
+ extend T::Sig
+ sig { void }
+ def reverse
+ # Pretend this is actually implemented
+ end
+ end
+
+ module Sortable
+ extend T::Sig
+ sig { void }
+ def sort
+ # Pretend this is actually implemented
+ end
+ end
+
+ class List
+ include Reversible
+ include Sortable
+ end
+
+ sig { params(list: T.all(Reversible, Sortable)).void }
+ def rev_sort(list)
+ # reverse from Reversible
+ list.reverse
+ # sort from Sortable
+ list.sort
+ end
+
+ def rev_sort_usage
+ rev_sort(List.new)
+ end
+
+ # Sometimes, actually spelling out the type every time becomes more confusing
+ # than helpful. Use type aliases to make them easier to work with.
+ JSONLiteral = T.type_alias { T.any(Float, String, T::Boolean, NilClass) }
+
+ sig { params(val: JSONLiteral).returns(String) }
+ def stringify(val)
+ val.to_s
+ end
+end
+
+module DataClasses
+ extend T::Sig
+ # Use `T::Struct` to create a new class with type-checked fields. It combines
+ # the best parts of the standard Struct and OpenStruct, and then adds static
+ # typing on top.
+ #
+ # Types constructed this way are sometimes known as "product types".
+
+ class Matcher < T::Struct
+ # Use `prop` to define a field with both a reader and writer.
+ prop :count, Integer
+ # Use `const` to only define the reader and skip the writer.
+ const :pattern, Regexp
+ # You can still set a default value with `default`.
+ const :message, String, default: 'Found one!'
+
+ # This is otherwise a normal class, so you can still define methods.
+
+ # You'll still need to bring `sig` in if you want to use it though.
+ extend T::Sig
+
+ sig { void }
+ def reset
+ self.count = 0
+ end
+ end
+
+ sig { params(text: String, matchers: T::Array[Matcher]).void }
+ def awk(text, matchers)
+ matchers.each(&:reset)
+ text.lines.each do |line|
+ matchers.each do |matcher|
+ if matcher.pattern =~ line
+ Kernel.puts matcher.message
+ matcher.count += 1
+ end
+ end
+ end
+ end
+
+ # Gotchas and limitations
+
+ # 1. `const` fields are not truly immutable. They don't have a writer method,
+ # but may be changed in other ways.
+ class ChangeMe < T::Struct
+ const :list, T::Array[Integer]
+ end
+
+ sig { params(change_me: ChangeMe).returns(T::Boolean) }
+ def whoops!(change_me)
+ change_me = ChangeMe.new(list: [1, 2, 3, 4])
+ change_me.list.reverse!
+ change_me.list == [4, 3, 2, 1]
+ end
+
+ # 2. `T::Struct` inherits its equality method from `BasicObject`, which uses
+ # identity equality (also known as "reference equality").
+ class Coordinate < T::Struct
+ const :row, Integer
+ const :col, Integer
+ end
+
+ sig { returns(T::Boolean) }
+ def never_equal!
+ p1 = Coordinate.new(row: 1, col: 2)
+ p2 = Coordinate.new(row: 1, col: 2)
+ p1 != p2
+ end
+
+ # Define your own `#==` method to check the fields, if that's what you want.
+ class Position < T::Struct
+ extend T::Sig
+
+ const :x, Integer
+ const :y, Integer
+
+ sig { params(other: Object).returns(T::Boolean) }
+ def ==(other)
+ # There's a real implementation here:
+ # https://github.com/tricycle/sorbet-struct-comparable
+ true
+ end
+ end
+
+ # Use `T::Enum` to define a fixed set of values that are easy to reference.
+ # This is especially useful when you don't care what the values _are_ as much
+ # as you care that the set of possibilities is closed and static.
+ class Crayon < T::Enum
+ extend T::Sig
+
+ # Initialize members with `enums`.
+ enums do
+ # Define each member with `new`. Each of these is an instance of the
+ # `Crayon` class.
+ Red = new
+ Orange = new
+ Yellow = new
+ Green = new
+ Blue = new
+ Violet = new
+ Brown = new
+ Black = new
+ # The default value of the enum is its name in all-lowercase. To change
+ # that, pass a value to `new`.
+ Gray90 = new('light-gray')
+ end
+
+ sig { returns(String) }
+ def to_hex
+ case self
+ when Red then '#ff0000'
+ when Green then '#00ff00'
+ # ...
+ else '#ffffff'
+ end
+ end
+ end
+
+ sig { params(crayon: Crayon, path: T::Array[Position]).void }
+ def draw(crayon:, path:)
+ path.each do |pos|
+ Kernel.puts "(#{pos.x}, #{pos.y}) = " + crayon.to_hex
+ end
+ end
+
+ # To get all the values in the enum, use `.values`. For convenience there's
+ # already a `#serialize` to get the enum string value.
+
+ sig { returns(T::Array[String]) }
+ def crayon_names
+ Crayon.values.map(&:serialize)
+ end
+
+ # Use the "deserialize" family to go from string to enum value.
+
+ sig { params(name: String).returns(T.nilable(Crayon)) }
+ def crayon_from_name(name)
+ if Crayon.has_serialized?(name)
+ # If the value is not found, this will raise a `KeyError`.
+ Crayon.deserialize(name)
+ end
+
+ # If the value is not found, this will return `nil`.
+ Crayon.try_deserialize(name)
+ end
+end
+
+module FlowSensitivity
+ extend T::Sig
+ # Sorbet understands Ruby's control flow constructs and uses that information
+ # to get more accurate types when your code branches.
+
+ # You'll see this most often when doing nil checks.
+ sig { params(name: T.nilable(String)).returns(String) }
+ def greet_loudly(name)
+ if name.nil?
+ 'HELLO, YOU!'
+ else
+ # Sorbet knows that `name` must be a String here, so it's safe to call
+ # `#upcase`.
+ "HELLO, #{name.upcase}!"
+ end
+ end
+
+ # The nils are a special case of refining `T.any`.
+ sig { params(id: T.any(Integer, T::Array[Integer])).returns(T::Array[String]) }
+ def database_lookup(id)
+ if id.is_a?(Integer)
+ # `ids` must be an Integer here.
+ [id.to_s]
+ else
+ # `ids` must be a T::Array[Integer] here.
+ id.map(&:to_s)
+ end
+ end
+
+ # Sorbet recognizes these methods that narrow type definitions:
+ # * is_a?
+ # * kind_of?
+ # * nil?
+ # * Class#===
+ # * Class#<
+ # * block_given?
+ #
+ # Because they're so common, it also recognizes these Rails extensions:
+ # * blank?
+ # * present?
+ #
+ # Be careful to maintain Sorbet assumptions if you redefine these methods!
+
+ # Have you ever written this line of code?
+ #
+ # raise StandardError, "Can't happen"
+ #
+ # Sorbet can help you prove that statically (this is known as
+ # "exhaustiveness") with `T.absurd`. It's extra cool when combined with
+ # `T::Enum`!
+
+ class Size < T::Enum
+ extend T::Sig
+
+ enums do
+ Byte = new('B')
+ Kibibyte = new('KiB')
+ Mebibyte = new('MiB')
+ # "640K ought to be enough for anybody"
+ end
+
+ sig { returns(Integer) }
+ def bytes
+ case self
+ when Byte then 1 << 0
+ when Kibibyte then 1 << 10
+ when Mebibyte then 1 << 20
+ else
+ # Sorbet knows you've checked all the cases, so there's no possible
+ # value that `self` could have here.
+ #
+ # But if you _do_ get here somehow, this will raise at runtime.
+ T.absurd(self)
+
+ # If you're missing a case, Sorbet can even tell you which one it is!
+ end
+ end
+ end
+
+ # We're gonna need `puts` and `raise` for this next part.
+ include Kernel
+
+ # Sorbet knows that no code can execute after a `raise` statement because it
+ # "never returns".
+ sig { params(num: T.nilable(Integer)).returns(Integer) }
+ def decrement(num)
+ raise ArgumentError, '¯\_(ツ)_/¯' unless num
+
+ num - 1
+ end
+
+ class CustomError < StandardError; end
+
+ # You can annotate your own error-raising methods with `T.noreturn`.
+ sig { params(message: String).returns(T.noreturn) }
+ def oh_no(message = 'A bad thing happened')
+ puts message
+ raise CustomError, message
+ end
+
+ # Infinite loops also don't return.
+ sig { returns(T.noreturn) }
+ def loading
+ loop do
+ %q(-\|/).each_char do |c|
+ print "\r#{c} reticulating splines..."
+ sleep 1
+ end
+ end
+ end
+
+ # You may run into a situation where Sorbet "loses" your type refinement.
+ # Remember that almost everything you do in Ruby is a method call that could
+ # return a different value next time you call it. Sorbet doesn't assume that
+ # any methods are pure (even those from `attr_reader` and `attr_accessor`).
+ sig { returns(T.nilable(Integer)) }
+ def answer
+ rand > 0.5 ? 42 : nil
+ end
+
+ sig { void }
+ def bad_typecheck
+ if answer.nil?
+ 0
+ else
+ # But answer might return `nil` if we call it again!
+ answer + 1
+ # ^ Method + does not exist on NilClass component of T.nilable(Integer)
+ end
+ end
+
+ sig { void }
+ def good_typecheck
+ ans = answer
+ if ans.nil?
+ 0
+ else
+ # This time, Sorbet knows that `ans` is non-nil.
+ ans + 1
+ end
+ end
+end
+
+module InheritancePatterns
+ extend T::Sig
+
+ # If you have a method that always returns the type of its receiver, use
+ # `T.self_type`. This is common in fluent interfaces and DSLs.
+ #
+ # Warning: This feature is still experimental!
+ class Logging
+ extend T::Sig
+
+ sig { returns(T.self_type) }
+ def log
+ pp self
+ self
+ end
+ end
+
+ class Data < Logging
+ extend T::Sig
+
+ sig { params(x: Integer, y: String).void }
+ def initialize(x: 0, y: '')
+ @x = x
+ @y = y
+ end
+
+ # You don't _have_ to use `T.self_type` if there's only one relevant class.
+ sig { params(x: Integer).returns(Data) }
+ def setX(x)
+ @x = x
+ self
+ end
+
+ sig { params(y: String).returns(Data) }
+ def setY(y)
+ @y = y
+ self
+ end
+ end
+
+ # Ta-da!
+ sig { params(data: Data).void }
+ def chaining(data)
+ data.setX(1).log.setY('a')
+ end
+
+ # If it's a class method (a.k.a. singleton method), use `T.attached_class`.
+ #
+ # No warning here. This one is stable!
+ class Box
+ extend T::Sig
+
+ sig { params(contents: String, weight: Integer).void }
+ def initialize(contents, weight)
+ @contents = contents
+ @weight = weight
+ end
+
+ sig { params(contents: String).returns(T.attached_class) }
+ def self.pack(contents)
+ new(contents, contents.chars.uniq.length)
+ end
+ end
+
+ class CompanionCube < Box
+ extend T::Sig
+
+ sig { returns(String) }
+ def pick_up
+ "♥#{@contents}ðŸ¤"
+ end
+ end
+
+ sig { returns(String) }
+ def befriend
+ CompanionCube.pack('').pick_up
+ end
+
+ # Sorbet has support for abstract classes and interfaces. It can check that
+ # all the concrete classes and implementations actually define the required
+ # methods with compatible signatures.
+
+ # Here's an abstract class:
+
+ class WorkflowStep
+ extend T::Sig
+
+ # Bring in the inheritance helpers.
+ extend T::Helpers
+
+ # Mark this class as abstract. This means it cannot be instantiated with
+ # `.new`, but it can still be subclassed.
+ abstract!
+
+ sig { params(args: T::Array[String]).void }
+ def run(args)
+ pre_hook
+ execute(args)
+ post_hook
+ end
+
+ # This is an abstract method, which means it _must_ be implemented by
+ # subclasses. Add a signature with `abstract` to an empty method to tell
+ # Sorbet about it.
+ #
+ # If this implementation of the method actually gets called at runtime, it
+ # will raise `NotImplementedError`.
+ sig { abstract.params(args: T::Array[String]).void }
+ def execute(args); end
+
+ # The following non-abstract methods _can_ be implemented by subclasses,
+ # but they're optional.
+
+ sig { void }
+ def pre_hook; end
+
+ sig { void }
+ def post_hook; end
+ end
+
+ class Configure < WorkflowStep
+ extend T::Sig
+
+ sig { void }
+ def pre_hook
+ puts 'Configuring...'
+ end
+
+ # To implement an abstract method, mark the signature with `override`.
+ sig { override.params(args: T::Array[String]).void }
+ def execute(args)
+ # ...
+ end
+ end
+
+ # And here's an interface:
+
+ module Queue
+ extend T::Sig
+
+ # Bring in the inheritance helpers.
+ extend T::Helpers
+
+ # Mark this module as an interface. This adds the following restrictions:
+ # 1. All of its methods must be abstract.
+ # 2. It cannot have any private or protected methods.
+ interface!
+
+ sig { abstract.params(num: Integer).void }
+ def push(num); end
+
+ sig { abstract.returns(T.nilable(Integer)) }
+ def pop; end
+ end
+
+ class PriorityQueue
+ extend T::Sig
+
+ # Include the interface to tell Sorbet that this class implements it.
+ # Sorbet doesn't support implicitly implemented interfaces (also known as
+ # "duck typing").
+ include Queue
+
+ sig { void }
+ def initialize
+ @items = T.let([], T::Array[Integer])
+ end
+
+ # Implement the Queue interface's abstract methods. Remember to use
+ # `override`!
+
+ sig { override.params(num: Integer).void }
+ def push(num)
+ @items << num
+ @items.sort!
+ end
+
+ sig { override.returns(T.nilable(Integer)) }
+ def pop
+ @items.shift
+ end
+ end
+
+ # If you use the `included` hook to get class methods from your modules,
+ # you'll have to use `mixes_in_class_methods` to get them to type-check.
+
+ module Mixin
+ extend T::Helpers
+ interface!
+
+ module ClassMethods
+ extend T::Sig
+
+ sig { void }
+ def whisk
+ 'fskfskfsk'
+ end
+ end
+
+ mixes_in_class_methods(ClassMethods)
+ end
+
+ class EggBeater
+ include Mixin
+ end
+
+ EggBeater.whisk # Meringue!
+end
+
+module EscapeHatches
+ extend T::Sig
+
+ # Ruby is a very dynamic language, and sometimes Sorbet can't infer the
+ # properties you already know to be true. Although there are ways to rewrite
+ # your code so Sorbet can prove safety, you can also choose to "break out" of
+ # Sorbet using these "escape hatches".
+
+ # Once you start using `T.nilable`, Sorbet will start telling you _all_ the
+ # places you're not handling nils. Sometimes, you know a value can't be nil,
+ # but it's not practical to fix the sigs so Sorbet can prove it. In that
+ # case, you can use `T.must`.
+ sig { params(maybe_str: T.nilable(String)).returns(String) }
+ def no_nils_here(maybe_str)
+ # If maybe_str _is_ actually nil, this will error at runtime.
+ str = T.must(maybe_str)
+ str.downcase
+ end
+
+ # More generally, if you know that a value must be a specific type, you can
+ # use `T.cast`.
+ sig do
+ params(
+ str_or_ary: T.any(String, T::Array[String]),
+ idx_or_range: T.any(Integer, T::Range[Integer]),
+ ).returns(T::Array[String])
+ end
+ def slice2(str_or_ary, idx_or_range)
+ # Let's say that, for some reason, we want individual characters from
+ # strings or sub-arrays from arrays. The other options are not allowed.
+ if str_or_ary.is_a?(String)
+ # Here, we know that `idx_or_range` must be a single index. If it's not,
+ # this will error at runtime.
+ idx = T.cast(idx_or_range, Integer)
+ [str_or_ary.chars.fetch(idx)]
+ else
+ # Here, we know that `idx_or_range` must be a range. If it's not, this
+ # will error at runtime.
+ range = T.cast(idx_or_range, T::Range[Integer])
+ str_or_ary.slice(range) || []
+ end
+ end
+
+ # If you know that a method exists, but Sorbet doesn't, you can use
+ # `T.unsafe` so Sorbet will let you call it. Although we tend to think of
+ # this as being an "unsafe method call", `T.unsafe` is called on the receiver
+ # rather than the whole expression.
+ sig { params(count: Integer).returns(Date) }
+ def the_future(count)
+ # Let's say you've defined some extra date helpers that Sorbet can't find.
+ # So `2.decades` is effectively `(2*10).years` from ActiveSupport.
+ Date.today + T.unsafe(count).decades
+ end
+
+ # If this is a method on the implicit `self`, you'll have to make that
+ # explicit to use `T.unsafe`.
+ sig { params(count: Integer).returns(Date) }
+ def the_past(count)
+ # Let's say that metaprogramming defines a `now` helper method for
+ # `Time.new`. Using it would normally look like this:
+ #
+ # now - 1234
+ #
+ T.unsafe(self).now - 1234
+ end
+
+ # There's a special type in Sorbet called `T.untyped`. For any value of this
+ # type, Sorbet will allow it to be used for any method argument and receive
+ # any method call.
+
+ sig { params(num: Integer, anything: T.untyped).returns(T.untyped) }
+ def nothing_to_see_here(num, anything)
+ anything.digits # Is it an Integer...
+ anything.upcase # ... or a String?
+
+ # Sorbet will not be able to infer anything about this return value because
+ # it's untyped.
+ BasicObject.new
+ end
+
+ def see_here
+ # It's actually nil! This will crash at runtime, but Sorbet allows it.
+ nothing_to_see_here(1, nil)
+ end
+
+ # For a method without a sig, Sorbet infers the type of each argument and the
+ # return value to be `T.untyped`.
+end
+
+# The following types are not officially documented but are still useful. They
+# may be experimental, deprecated, or not supported.
+
+module ValueSet
+ extend T::Sig
+
+ # A common pattern in Ruby is to have a method accept one value from a set of
+ # options. Especially when starting out with Sorbet, it may not be practical
+ # to refactor the code to use `T::Enum`. In this case, you can use `T.enum`.
+ #
+ # Note: Sorbet can't check this statically becuase it doesn't track the
+ # values themselves.
+ sig do
+ params(
+ data: T::Array[Numeric],
+ shape: T.enum([:circle, :square, :triangle])
+ ).void
+ end
+ def plot_points(data, shape: :circle)
+ data.each_with_index do |y, x|
+ Kernel.puts "#{x}: #{y}"
+ end
+ end
+end
+
+module Generics
+ extend T::Sig
+
+ # Generics are useful when you have a class whose method types change based
+ # on the data it contains or a method whose method type changes based on what
+ # its arguments are.
+
+ # A generic method uses `type_parameters` to declare type variables and
+ # `T.type_parameter` to refer back to them.
+ sig do
+ type_parameters(:element)
+ .params(
+ element: T.type_parameter(:element),
+ count: Integer,
+ ).returns(T::Array[T.type_parameter(:element)])
+ end
+ def repeat_value(element, count)
+ count.times.each_with_object([]) do |elt, ary|
+ ary << elt
+ end
+ end
+
+ sig do
+ type_parameters(:element)
+ .params(
+ count: Integer,
+ block: T.proc.returns(T.type_parameter(:element)),
+ ).returns(T::Array[T.type_parameter(:element)])
+ end
+ def repeat_cached(count, &block)
+ elt = block.call
+ ary = []
+ count.times do
+ ary << elt
+ end
+ ary
+ end
+
+ # A generic class uses `T::Generic.type_member` to define type variables that
+ # can be like regular type names.
+ class BidirectionalHash
+ extend T::Sig
+ extend T::Generic
+
+ Left = type_member
+ Right = type_member
+
+ sig { void }
+ def initialize
+ @left_hash = T.let({}, T::Hash[Left, Right])
+ @right_hash = T.let({}, T::Hash[Right, Left])
+ end
+
+ # Implement just enough to make the methods below work.
+
+ sig { params(lkey: Left).returns(T::Boolean) }
+ def lhas?(lkey)
+ @left_hash.has_key?(lkey)
+ end
+
+ sig { params(rkey: Right).returns(T.nilable(Left)) }
+ def rget(rkey)
+ @right_hash[rkey]
+ end
+ end
+
+ # To specialize a generic type, use brackets.
+ sig do
+ params(
+ options: BidirectionalHash[Symbol, Integer],
+ choice: T.any(Symbol, Integer),
+ ).returns(T.nilable(String))
+ end
+ def lookup(options, choice)
+ case choice
+ when Symbol
+ options.lhas?(choice) ? choice.to_s : nil
+ when Integer
+ options.rget(choice).to_s
+ else
+ T.absurd(choice)
+ end
+ end
+
+ # To specialize through inheritance, re-declare the `type_member` with
+ # `fixed`.
+ class Options < BidirectionalHash
+ Left = type_member(fixed: Symbol)
+ Right = type_member(fixed: Integer)
+ end
+
+ sig do
+ params(
+ options: Options,
+ choice: T.any(Symbol, Integer),
+ ).returns(T.nilable(String))
+ end
+ def lookup2(options, choice)
+ lookup(options, choice)
+ end
+
+ # There are other variance annotations you can add to `type_member`, but
+ # they're rarely used.
+end
+```
+
+## Additional resources
+
+- [Official Documentation](https://sorbet.org/docs/overview)
+- [sorbet.run](https://sorbet.run) - Playground
diff --git a/sql.html.markdown b/sql.html.markdown
index 685e522d..834cf00b 100644
--- a/sql.html.markdown
+++ b/sql.html.markdown
@@ -95,7 +95,7 @@ UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
-- Delete rows from the tablename1 table
-- where the lname value begins with 'M'.
-DELETE FROM tablename1 WHERE lname like 'M%';
+DELETE FROM tablename1 WHERE lname LIKE 'M%';
-- Delete all rows from the tablename1 table, leaving the empty table.
DELETE FROM tablename1;
diff --git a/swift.html.markdown b/swift.html.markdown
index e46dcc75..36124e11 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -679,6 +679,9 @@ class Rect: Shape {
// A simple class `Square` extends `Rect`
class Square: Rect {
+ // Use a convenience initializer to make calling a designated initializer faster and more "convenient".
+ // Convenience initializers call other initializers in the same class and pass default values to one or more of their parameters.
+ // Convenience initializers can have parameters as well, which are useful to customize the called initializer parameters or choose a proper initializer based on the value passed.
convenience init() {
self.init(sideLength: 5)
}
diff --git a/tact.html.markdown b/tact.html.markdown
new file mode 100644
index 00000000..2cb650ee
--- /dev/null
+++ b/tact.html.markdown
@@ -0,0 +1,603 @@
+---
+language: Tact
+filename: tact.tc
+contributors:
+ - ["Tal Kol", "https://www.orbs.com/"]
+ - ["Kirill Malev", "https://fslabs.io"]
+ - ["Yash Garg", "https://github.com/yash0501"]
+---
+
+Tact language is used to program smart contracts on the
+[The Open Network](https://ton.org) blockchain. Contract logic is executed in
+TVM, the stack-based TON Virtual Machine.
+
+Tact is a statically typed, but language was designed to be friendly for
+developers with JS and Python background.
+
+This page is based on [Tact-by-Example](https://tact-by-example.org/).
+You can use this resource to play around with contracts and check out
+the interactive features.
+
+# Basic syntax, function definition
+
+```c
+// Single line comment
+
+ // This is a multi-line comment
+ // this is a comment in the comment
+
+ get fun greeting(): String {
+ // This is a function that returns "hello world" message
+ // Return type is specified after a colon :
+ return "hello world";
+ }
+```
+
+# A Simple Counter contract
+
+This is a simple counter contract that allows users to increment its value.
+
+This contract has a state variable `val` that persists between contract calls
+
+- the counter value. When persisted, this variable is encoded as `uint32` -
+ a 32-bit unsigned integer. Contracts pay rent in proportion to the amount
+ of persistent space they consume, so compact representations are encouraged.
+
+State variables should be initialized in `init()` that runs on deployment of
+the contract.
+
+## Messages
+
+The actor model is a model of concurrent computation and is at the heart of TON
+smart contracts. Each smart contract can process one message at a time, change
+its own state, or send one or several messages. Processing of the message
+occurs in one transaction, that is, it cannot be interrupted. Messages to one
+contract are processed consequently one by one. As a result, the execution of
+each transaction is local and can be parallelized at the blockchain level,
+which allows for on-demand throughput horizontal scaling and hosting an
+unlimited number of users and transactions.
+
+## Receiving messages
+
+This contract can receive messages from users. Unlike getters that are just
+read-only, messages can do write operations and change the contract's
+persistent state. Incoming messages are processed in receive() methods as
+transactions and cost gas for the sender.
+
+After deploying the contract, send the increment message by pressing the Send
+increment button in order to increase the counter value by one. Afterwards,
+call the getter value() to see that the value indeed changed.
+
+```c
+contract Counter {
+// Tact allows to create a contract
+ // persistent state variable of type Int to hold the counter value
+ val: Int as uint32;
+
+ // initialize the state variable when contract is deployed
+ init() {
+ self.val = 0;
+ }
+
+ // handler for incoming increment messages that change the state
+ receive("increment") {
+ self.val = self.val + 1;
+ }
+
+ // read-only getter for querying the counter value
+ get fun value(): Int {
+ return self.val;
+ }
+}
+```
+
+# The Deployable Trait
+
+Tact doesn't support classical class inheritance, but contracts can implement
+traits. One of the commonly used traits is `Deployable`. It implements a simple
+receiver for the Deploy message which helps deploy contracts in a standard way.
+
+All contracts are deployed by sending them a message. This can be any message,
+but best practice is to designate the special `Deploy`
+message for this purpose.
+
+This message has a single field, `queryId`, which is provided by the deployer
+(normally zero). If the deploy succeeds, the contract will reply with the
+message `DeployOk` and echo the same `queryId` in the response.
+
+If you're using Tact's [auto-generated](https://docs.tact-lang.org/tools/typescript#tact-contract-in-typescript) TypeScript
+classes to deploy, sending the deploy message should look like:
+
+```c
+const msg = { $$type: "Deploy", queryId: 0n };
+ await contract.send(sender, { value: toNano(1) }, msg);
+```
+
+You can see the implementation of the trait [here](https://github.com/tact-lang/tact/blob/main/stdlib/libs/deploy.tact).
+Notice that the file deploy.tact needs to be imported from the standard
+library using the import keyword.
+
+```c
+// this trait has to be imported
+import "@stdlib/deploy";
+
+// the Deployable trait adds a default receiver for the "Deploy" message
+contract Counter with Deployable {
+
+ val: Int as uint32;
+
+ init() {
+ self.val = 0;
+ }
+
+ receive("increment") {
+ self.val = self.val + 1;
+ }
+
+ get fun value(): Int {
+ return self.val;
+ }
+}
+```
+
+# Integers
+
+Tact supports a number of primitive data types that are tailored for
+smart contract use.
+
+`Int` is the primary number type. Math in smart contracts is always done
+with integers and never with floating points since floats are [unpredictable](https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision).
+
+The runtime type `Int` is always 257-bit signed, so all runtime calculations
+are done at 257-bit. This should be large enough for pretty much anything you
+need as it's large enough to hold the number of atoms in the universe.
+
+Persistent state variables can be initialized inline or inside `init()`.
+If you forget to initialize a state variable, the code will not compile.
+
+## State costs
+
+When encoding `Int` to persistent state, we will usually use smaller
+representations than 257-bit to reduce storage cost.
+The persistent state size is specified in every declaration of
+a state variable after the `as` keyword.
+
+Storing 1000 257-bit integers in state [costs](https://ton.org/docs/develop/smart-contracts/fees#how-to-calculate-fees) about
+0.184 TON per year. Storing 1000 32-bit integers only costs
+0.023 TON per year by comparison.
+
+```c
+import "@stdlib/deploy";
+
+contract Integers with Deployable {
+
+ // contract persistent state variables
+ // integers can be persisted in state in various sizes
+ // range -2^256 to 2^256 - 1 (takes 257 bit = 32 bytes + 1 bit)
+ i1: Int as int257 = 3001;
+ i2: Int as uint256; // range 0 to 2^256 - 1 (takes 256 bit = 32 bytes)
+ // range -2^255 to 2^255 - 1 (takes 256 bit = 32 bytes)
+ i3: Int as int256 = 17;
+ i4: Int as uint128; // range 0 to 2^128 - 1 (takes 128 bit = 16 bytes)
+ // range -2^127 to 2^127 - 1 (takes 128 bit = 16 bytes)
+ i5: Int as int128;
+ i6: Int as coins; // range 0 to 2^120 - 1 (takes 120 bit = 15 bytes)
+ // range 0 to 18,446,744,073,709,551,615 (takes 64 bit = 8 bytes)
+ i7: Int as uint64 = 0x1c4a;
+ // range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
+ // (takes 64 bit = 8 bytes)
+ i8: Int as int64 = -203;
+ i9: Int as uint32 = 0; // range 0 to 4,294,967,295 (takes 32 bit = 4 bytes)
+ // range -2,147,483,648 to 2,147,483,647 (takes 32 bit = 4 bytes)
+ i10: Int as int32 = 0;
+ i11: Int as uint16 = 0; // range 0 to 65,535 (takes 16 bit = 2 bytes)
+ i12: Int as int16 = 0; // range -32,768 to 32,767 (takes 16 bit = 2 bytes)
+ i13: Int as uint8 = 0; // range 0 to 255 (takes 8 bit = 1 byte)
+ i14: Int as int8 = 0; // range -128 to 127 (takes 8 bit = 1 byte)
+
+ init() {
+ // we can define numbers in hex (base 16)
+ self.i2 = 0x83dfd552e6372;
+ self.i4 = 1507998500293440234999; // we can define numbers in decimal
+ self.i5 = pow(10, 9); // this is 10^9 = 1,000,000,000
+ self.i6 = ton("1.23"); // easy to read coin balances
+ // (coins type is nano-tons, like cents, just with 9 decimals)
+ }
+
+ receive("show all") {
+ dump(self.i1);
+ dump(self.i2);
+ dump(self.i3);
+ dump(self.i4);
+ dump(self.i5);
+ dump(self.i6);
+ dump(self.i7);
+ dump(self.i8);
+ }
+
+ get fun result(): Int {
+ return self.i1;
+ }
+}
+```
+
+## Bools, Addresses, Strings, Operators and Constants
+
+### Bool
+
+Bool can be used for boolean variables
+
+```js
+b1: Bool = true;
+b2: Bool = false;
+```
+
+### Address
+
+Address is another primitive data type. It represents standard addresses on
+the TON blockchain.
+TON is divided into multiple chains called workchains. One of the internal
+fields of the address is the workchain id:
+0 - The standard workchain, for regular users. Your contracts will be here.
+-1 - The masterchain, usually for validators.
+
+```js
+// bouncable (same foundation wallet)
+a1: Address = address("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N");
+// non-bounceable (same foundation wallet)
+a2: Address = address("UQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqEBI");
+```
+
+### String
+
+Tact has basic support for strings. Strings support unicode and don't
+have any special escape characters like \n.
+Strings are immutable. Once a sequence of characters is created, this
+sequence cannot be modified.
+If you need to concatenate strings in run-time, you can use a StringBuilder.
+This object handles gas efficiently and supports append() of various types to
+the string.
+
+```js
+s1: String = "hello world";
+sb: StringBuilder = beginString();
+sb.append(self.s1);
+```
+
+### Integer Operations
+
+Addition, subtraction, multiplication, division, modulo,
+shift left and right, minimum and maximum numbers, absolute value
+
+```js
+i: Int = -12; // temporary variable, runtime Int type is always int257
+i = i1 * 3 + (i2 - i); // basic math expressions
+i = i1 % 10; // modulo (remainder after division), 3001 % 10 = 1
+i = i1 / 1000; // integer division (truncation toward zero), 3001 / 1000 = 3
+i = i1 >> 3; // shift right (multiply by 2^n)
+i = i1 << 2; // shift left (divide by 2^n)
+i = min(i2, 11); // minimum between two numbers
+i = max(i2, 66); // maximum between two numbers
+i = abs(-1 * i2); // absolute value
+```
+
+### Constants
+
+Unlike variables, constants cannot change. Their values are
+calculated in compile-time and cannot change during execution.
+
+```js
+const StateUnpaid: Int = 0;
+```
+
+## Getters, Receivers and Messages
+
+### Getters
+
+Getters are special contract functions that allow users to query
+information from the contract.
+Contract methods starting with the prefix get fun are all getters.
+Calling getters is free and does not cost gas.
+Getters are read-only, they cannot change the contract persistent state.
+A contract cannot execute a getter of another contract. Getters are only
+executable by end-users off-chain.
+
+```js
+count: Int as uint32 = 17;
+
+get fun counter(): Int {
+ return self.count;
+}
+```
+
+### Receivers
+
+Contract methods named receive() are the handlers that process
+each incoming message type.
+Tact will automatically route every incoming message to the correct receiver
+listening for it according to its type. A message is only handled by one receiver.
+
+Handler for "increment" textual message - this is a textual string message,
+these cannot carry input arguments
+
+```js
+receive("increment") {
+ self.val = self.val + 1;
+}
+```
+
+### Messages
+
+Messages are defined using the message keyword. They can carry input
+arguments. For integers, you must define the encoding size, just like in
+state variables.
+
+Handler for the "Add" message - this is a binary message that has an input
+argument (amount)
+
+```js
+receive(msg: Add) {
+ self.val = self.val + msg.amount;
+}
+```
+
+## Structs
+
+Structs allow you to combine multiple primitives together in a more semantic way.
+Structs can define complex data types that contain multiple fields of
+different types. They can also be nested.
+
+```js
+// Normal struct
+struct Point {
+ x: Int as int64;
+ y: Int as int64;
+}
+
+// Nested struct
+struct Params {
+ name: String = "Satoshi"; // default value
+ age: Int? = null; // optional field
+ point: Point; // nested structs
+}
+```
+
+## Message Sender and Throwing Errors
+
+### Message Sender
+
+Every incoming message is sent from some contract that has
+an address. You can query the address of the message sender by calling sender()
+
+```js
+deployer: Address = sender();
+```
+
+### Errors
+
+When an error is thrown, the transaction reverts. By writing a
+require() on a condition that isn't met
+
+```js
+require(self.val < 5, "Counter is too high");
+```
+
+## Messages Between Contracts, Sending and Receiving TON Coins
+
+### Messages Between Contracts
+
+Different contracts can only communicate with
+each other by sending each other messages.
+
+This example sends a message to the to address with value of 1 TON and body
+of a comment with a string "Hello, World!".
+SendIgnoreErrors means that even when error occurs during message sending
+next messages would be sent anyway.
+
+```js
+let to: Address = ...;
+let value: Int = ton("1");
+send(SendParameters{
+ to: to, // address of receiver
+ value: value, // amount of TON you want to send
+ mode: SendIgnoreErrors, // 8-bit flag configuring how to send message
+ bounce: true, // if set to true (default) then message
+ // will be bounced back to sender
+ body: "Hello, World!".asComment() // message body as Cell
+});
+```
+
+### Receiving TONs
+
+You can query the contract balance with myBalance() - note
+that the value is in nano-tons (like cents, just with 9 decimals). The balance
+already contains the incoming message value.
+You can also get the incoming TON balance with context().value
+
+```js
+val: Int as int64 = myBalance()
+// or
+// print how much TON coin were sent with this message
+dump(context().value);
+```
+
+### Sending TONs
+
+We can send any amount of TON to any address just like we created
+a send call between different contracts
+
+Send mode SendRemainingValue will add to the outgoing value any excess left
+from the incoming message after all gas costs are deducted from it.
+
+```js
+amount: Int as coins = ton("1");
+send(SendParameters{
+ to: sender(),
+ bounce: true,
+ value: amount,
+ mode: SendRemainingValue + SendIgnoreErrors
+});
+```
+
+## If/Else statements and Loops
+
+### If
+
+Tact supports if statements in a similar syntax to most programming
+languages. Curly braces are required.
+We can have the else and else if similar to other programming languages.
+
+```js
+if (val > 1000) {
+ dump("larger than 1000");
+} else if (val > 500) {
+ dump("between 500 and 1000");
+} else {
+ dump("smaller than 500");
+}
+```
+
+### Loops
+
+Tact does not support traditional 'for' loops, 'break' and 'continue'
+statements in loops.
+The repeat loop statement input number must fit within an int32.
+
+```js
+// repeat exactly 10 times
+
+repeat (10) {
+ i = i + 1;
+ sum = sum + i;
+}
+
+// While loop
+
+let x: Int = 10;
+while(x > 0) {
+ x = x - 1;
+}
+
+// do-until loop
+
+let x: Int = 10;
+do {
+ x = x - 1;
+} until (x <= 0);
+```
+
+## Functions
+
+Functions in Tact start with the fun keyword. Functions can receive multiple
+input arguments and can optionally return a single output value. You can
+return a struct if you want to return multiple values.
+
+```js
+fun average(a: Int, b: Int): Int {
+ return (a + b) / 2;
+}
+```
+
+## Maps and Arrays
+
+### Maps
+
+Maps are a dictionary type that can hold an arbitrary number of items,
+each under a different key.
+The keys in maps can either be an Int type or an Address type.
+You can check if a key is found in the map by calling the get() method.
+Replace the value under a key by calling the set() method.
+
+```js
+mi1: map<Int, TokenInfo>; // maps with Int as key
+ma1: map<Address, TokenInfo>; // maps with Address as key
+```
+
+### Arrays
+
+To create an array, define a map with 'Int' type as key as well as value.
+
+```js
+arr: map<Int, Int>; // this is our array implemented with a map
+```
+
+## Ownable Standard Library
+
+The Ownable trait allows the contract to set an owner role, which can have
+higher priviliges from everybody else.
+For this you would need to import the "@stdlib/ownable" library and inherit
+it in your contract
+
+- Use the self.requireOwner() call to verify that the person making that
+ function call is the owner of contract
+- 'ChangeOwner{newOwner: Address}' message which allows the owner to
+ transfer ownership.
+- Define state variables named 'owner: Address' and 'stopped: Bool' and
+ call 'self.requireNotStopped()' on actions that should be stopped.
+- Define state variables named 'owner: Address' and "stopped: Bool' and
+ call 'self.requireNotStopped()' on actions that should be stopped.
+
+```js
+import "@stdlib/ownable";
+import "@stdlib/deploy";
+
+contract Counter with Deployable, Ownable {
+ owner: Address;
+
+ init() { // initialize a contract with default values like 'constructor'
+ self.owner = sender(); // we can initialize owner to any value we want, the deployer in this case
+ self.val = 0;
+ }
+
+ // this message in only available to the owner
+ receive("double") {
+ self.requireOwner();
+ self.val = self.val * 2;
+ }
+
+ // this message will only work until the contract was stopped
+ receive("increment") {
+ self.requireNotStopped();
+ self.val = self.val + 1;
+ }
+
+ // this message will only work as long as the contract is not stopped
+ receive("increment2") {
+ self.requireNotStopped();
+ self.val = self.val + 1;
+ }
+}
+
+```
+
+## Additional resources
+
+- [TON Documentation](https://ton.org/docs/#/)
+- [Tact Docs](https://docs.tact-lang.org/)
+- [Tact by Example](https://tact-by-example.org/)
+- [Community portal](https://society.ton.org)
+- [Blockchain portal](https://ton.org)
+- [Stackoverflow](https://stackoverflow.com/questions/tagged/ton)
+
+## Social
+
+- [Tact community](https://t.me/tactlang)
+- [Developer community](https://t.me/tondev_eng)
+- [TON Learn](https://t.me/ton_learn)
+- [Tondev News](https://t.me/tondevnews)
+- [TON Technical Updates](https://t.me/thetontech)
+
+## Useful blogposts
+
+- [Setting up a TON Development Environment](https://society.ton.org/setting-up-a-ton-development-environment)
+- [Hello World on TON](https://society.ton.org/ton-hello-world-step-by-step-guide-for-writing-your-first-smart-contract-in-func)
+
+## Future To Dos
+
+- Add smart contracts examples
+- Add more links to documentations
+
+This file is based on [Tact By Example](https://tact-by-example.org).
+
+P.S. If by any chance you're familiar with [Forth](https://learnxinyminutes.com/docs/forth/),
+you can also take a look at [Fift](https://ton-blockchain.github.io/docs/fiftbase.pdf).
diff --git a/tailspin.html.markdown b/tailspin.html.markdown
new file mode 100644
index 00000000..89ccdb1f
--- /dev/null
+++ b/tailspin.html.markdown
@@ -0,0 +1,383 @@
+---
+language: tailspin
+filename: learntailspin.tt
+contributors:
+ - ["Torbjörn Gannholm", "https://github.com/tobega/"]
+
+---
+
+**Tailspin** works with streams of values in pipelines. You may often feel
+that your program is the machine and that the input data is the program.
+
+While Tailspin is unlikely to become mainstream, or even production-ready,
+it will change the way you think about programming in a good way.
+
+```c
+// Comment to end of line
+
+// Process data in a pipeline with steps separated by ->
+// String literals are delimited by single quotes
+// A bang (!) indicates a sink, or end of the pipe
+// OUT is the standard output object, ::write is the message to write output
+'Hello, World!' -> !OUT::write
+
+// Output a newline by just entering it in the string (multiline strings)
+'
+' -> !OUT::write
+// Or output the decimal unicode value for newline (10) between $# and ;
+'$#10;' -> !OUT::write
+
+// Define an immutable named value. Value syntax is very literal.
+def names: ['Adam', 'George', 'Jenny', 'Lucy'];
+
+// Stream the list to process each name. Note the use of $ to get the value.
+// The current value in the pipeline is always just $
+// String interpolation starts with a $ and ends with ;
+$names... -> 'Hello $;!
+' -> !OUT::write
+
+// You can also stream in the interpolation and nest interpolations
+// Note the list indexing with parentheses and the slice extraction
+// Note the use of ~ to signify an exclusive bound to the range
+// Outputs 'Hello Adam, George, Jenny and Lucy!'
+'Hello $names(first);$names(first~..~last)... -> ', $;'; and $names(last);!
+' -> !OUT::write
+
+// Conditionally say different things to different people
+// Matchers (conditional expressions) are delimited by angle brackets
+// A set of matchers, evaluated top down, must be in templates (a function)
+// Here it is an inline templates delimited by \( to \)
+// Note the doubled '' and $$ to get a literal ' and $
+$names... -> \(
+ when <='Adam'> do 'What''s up $;?' !
+ when <='George'> do 'George, where are the $$10 you owe me?' !
+ otherwise 'Hello $;!' !
+\) -> '$;$#10;' -> !OUT::write
+
+// You can also define templates (functions)
+// A lone ! emits the value into the calling pipeline without returning control
+// The # sends the value to be matched by the matchers
+// Note that templates always take one input value and emit 0 or more outputs
+templates collatz-sequence
+ when <..0> do 'The start seed must be a positive integer' !
+ when <=1> do $!
+// The ?( to ) allows matching a computed value. Can be concatenated as "and"
+ when <?($ mod 2 <=1>)> do
+ $ !
+ 3 * $ + 1 -> #
+ otherwise
+ $ !
+ $ ~/ 2 -> #
+end collatz-sequence
+
+// Collatz sequence from random start on one line separated by spaces
+1000 -> SYS::randomInt -> $ + 1 -> collatz-sequence -> '$; ' -> !OUT::write
+'
+' -> !OUT::write
+
+// Collatz sequence formatted ten per line by an indexed list template
+// Note the square brackets creates a list of the enclosed pipeline results
+// The \[i]( to \) defines a templates to apply to each value of a list,
+// the i (or whatever identifier you choose) holds the index
+[1000 -> SYS::randomInt -> $ + 1 -> collatz-sequence]
+-> \[i](
+ when <=1|?($i mod 10 <=0>)> do '$;$#10;' !
+ otherwise '$; ' !
+\)... -> !OUT::write
+
+// A range can have an optional stride
+def odd-numbers: [1..100:2];
+
+// Use mutable state locally. One variable per templates, always called @
+templates product
+ @: $(first);
+ $(first~..last)... -> @: $@ * $;
+ $@ !
+end product
+
+$odd-numbers(6..8) -> product -> !OUT::write
+'
+' -> !OUT::write
+
+// Use processor objects to hold mutable state.
+// Note that the outer @ must be referred to by name in inner contexts
+// A sink templates gives no output and is called prefixed by !
+// A source templates takes no input and is called prefixed by $
+processor Product
+ @: 1;
+ sink accumulate
+ @Product: $@Product * $;
+ end accumulate
+ source result
+ $@Product !
+ end result
+end Product
+
+// The processor is a constructor templates. This one called with $ (no input)
+def multiplier: $Product;
+
+// Call object templates by sending messages with ::
+1..7 -> !multiplier::accumulate
+-1 -> !multiplier::accumulate
+$multiplier::result -> 'The product is $;
+' -> !OUT::write
+
+// Syntax sugar for a processor implementing the collector interface
+1..7 -> ..=Product -> 'The collected product is $;$#10;' -> !OUT::write
+
+// Symbol sets (essentially enums) can be defined for finite sets of values
+data colour #{green, red, blue, yellow}
+
+// Use processor typestates to model state cleanly.
+// The last named mutable state value set determines the typestate
+processor Lamp
+ def colours: $;
+ @Off: 0;
+ state Off
+ source switchOn
+ @On: $@Off mod $colours::length + 1;
+ 'Shining a $colours($@On); light$#10;' !
+ end switchOn
+ end Off
+ state On
+ source turnOff
+ @Off: $@On;
+ 'Lamp is off$#10;' !
+ end turnOff
+ end On
+end Lamp
+
+def myLamp: [colour#green, colour#blue] -> Lamp;
+
+$myLamp::switchOn -> !OUT::write // Shining a green light
+$myLamp::turnOff -> !OUT::write // Lamp is off
+$myLamp::switchOn -> !OUT::write // Shining a blue light
+$myLamp::turnOff -> !OUT::write // Lamp is off
+$myLamp::switchOn -> !OUT::write // Shining a green light
+
+// Use regular expressions to test strings
+['banana', 'apple', 'pear', 'cherry']... -> \(
+ when <'.*a.*'> do '$; contains an ''a''' !
+ otherwise '$; has no ''a''' !
+\) -> '$;
+' -> !OUT::write
+
+// Use composers with regular expressions and defined rules to parse strings
+composer parse-stock-line
+ {inventory-id: <INT> (<WS>), name: <'\w+'> (<WS>), currency: <'.{3}'>,
+ unit-price: <INT> (<WS>?) <parts>?}
+ rule parts: associated-parts: [<part>+]
+ rule part: <'[A-Z]\d+'> (<=','>?)
+end parse-stock-line
+
+'705 gizmo EUR5 A67,G456,B32' -> parse-stock-line -> !OUT::write
+// {associated-parts: [A67, G456, B32], currency: EUR,
+// inventory-id: 705, name: gizmo, unit-price: 5}
+'
+' -> !OUT::write
+
+// Stream a string to split it into glyphs.
+// A list can be indexed/sliced by an array of indexes
+// Outputs ['h','e','l','l','o'], indexing arrays/lists starts at 1
+['abcdefghijklmnopqrstuvwxyz'...] -> $([8,5,12,12,15]) -> !OUT::write
+'
+' -> !OUT::write
+
+// We have used only raw strings above.
+// Strings can have different types as determined by a tag.
+// Comparing different types is an error, unless a wider type bound is set
+// Type bound is given in ´´ and '' means any string value, tagged or raw
+templates get-string-type
+ when <´''´ '.*'> do '$; is a raw string' !
+ when <´''´ id´'\d+'> do '$; is a numeric id string' !
+ when <´''´ =id´'foo'> do 'id foo found' !
+ when <´''´ id´'.*'> do '$; is an id' !
+ when <´''´ name´'.+'> do '$; is a name' !
+ otherwise '$; is not a name or id, nor a raw string' !
+end get-string-type
+
+[name´'Anna', 'foo', id´'789', city´'London', id´'xzgh', id´'foo']...
+-> get-string-type -> '$;
+' -> !OUT::write
+
+// Numbers can be raw, tagged or have a unit of measure
+// Type .. is any numeric value, tagged, measure or raw
+templates get-number-type
+ when <´..´ =inventory-id´86> do 'inventory-id 86 found' !
+ when <´..´ inventory-id´100..> do '$; is an inventory-id >= 100' !
+ when <´..´ inventory-id´0..|..inventory-id´0> do '$; is an inventory-id' !
+ when <´..´ 0"m"..> do '$; is an m-measure >= 0"m"' !
+ when <´..´ ..0|0..> do '$; is a raw number' !
+ otherwise '$; is not a positive m-measure nor an inventory-id, nor raw' !
+end get-number-type
+
+[inventory-id´86, inventory-id´6, 78"m", 5"s", 99, inventory-id´654]...
+-> get-number-type -> '$;
+' -> !OUT::write
+
+// Measures can be used in arithmetic, "1" is the scalar unit
+// When mixing measures you have to cast to the result measure
+4"m" + 6"m" * 3"1" -> ($ ~/ 2"s")"m/s" -> '$;
+' -> !OUT::write
+
+// Tagged identifiers must be made into raw numbers when used in arithmetic
+// Then you can cast the result back to a tagged identifier if you like
+inventory-id´300 -> inventory-id´($::raw + 1) -> get-number-type -> '$;
+' -> !OUT::write
+
+// Fields get auto-typed, tagging raw strings or numbers by default
+// You cannot assign the wrong type to a field
+def item: { inventory-id: 23, name: 'thingy', length: 12"m" };
+
+'Field inventory-id $item.inventory-id -> get-number-type;
+' -> !OUT::write
+'Field name $item.name -> get-string-type;
+' -> !OUT::write
+'Field length $item.length -> get-number-type;
+' -> !OUT::write
+
+// You can define types and use as type-tests. This also defines a field.
+// It would be an error to assign a non-standard plate to a standard-plate field
+data standard-plate <'[A-Z]{3}[0-9]{3}'>
+
+[['Audi', 'XYZ345'], ['BMW', 'I O U']]... -> \(
+ when <?($(2) <standard-plate>)> do {make: $(1), standard-plate: $(2)}!
+ otherwise {make: $(1), vanity-plate: $(2)}!
+\) -> '$;
+' -> !OUT::write
+
+// You can define union types
+data age <"years"|"months">
+
+[ {name: 'Cesar', age: 20"years"},
+ {name: 'Francesca', age: 19"years"},
+ {name: 'Bobby', age: 11"months"}]...
+-> \(
+// Conditional tests on structures look a lot like literals, with field tests
+ when <{age: <13"years"..19"years">}> do '$.name; is a teenager'!
+ when <{age: <"months">}> do '$.name; is a baby'!
+// You don't need to handle all cases, 'Cesar' will just be ignored
+\) -> '$;
+' -> !OUT::write
+
+// Array/list indexes start at 1 by default, but you can choose
+// Slices return whatever overlaps with the actual array
+[1..5] -> $(-2..2) -> '$;
+' -> !OUT::write // Outputs [1,2]
+0:[1..5] -> $(-2..2) -> '$;
+' -> !OUT::write // Outputs [1,2,3]
+-2:[1..5] -> $(-2..2) -> '$;
+' -> !OUT::write // Outputs [1,2,3,4,5]
+
+// Arrays can have indexes of measures or tagged identifiers
+def game-map: 0"y":[
+ 1..5 -> 0"x":[
+ 1..5 -> level´1:[
+ 1..3 -> {
+ level: $,
+ terrain-id: 6 -> SYS::randomInt,
+ altitude: (10 -> SYS::randomInt)"m"
+ }
+ ]
+ ]
+];
+
+// Projections (indexing) can span several dimensions
+$game-map(3"y"; 1"x"..3"x"; level´1; altitude:) -> '$;
+' -> !OUT::write // Gives a list of three altitude values
+
+// Flatten and do a grouping projection to get stats
+// Count and Max are built-in collector processors
+[$game-map... ... ...] -> $(collect {
+ occurences: Count,
+ highest-on-level: Max&{by: :(altitude:), select: :(level:)}
+ } by $({terrain-id:}))
+-> !OUT::write
+'
+' -> !OUT::write
+
+// Relations are sets of structures/records.
+// Here we get all unique {level:, terrain-id:, altitude:} combinations
+def location-types: {|$game-map... ... ...|};
+
+// Projections can re-map structures. Note § is the relative accessor
+$location-types({terrain-id:, foo: §.level::raw * §.altitude})
+-> '$;
+' -> !OUT::write
+
+// Relational algebra operators can be used on relations
+($location-types join {| {altitude: 3"m"} |})
+-> !OUT::write
+'
+' -> !OUT::write
+
+// Define your own operators for binary operations
+operator (left dot right)
+ $left -> \[i]($ * $right($i)!\)... -> ..=Sum&{of: :()} !
+end dot
+
+([1,2,3] dot [2,5,8]) -> 'dot product: $;
+' -> !OUT::write
+
+// Supply parameters to vary templates behaviour
+templates die-rolls&{sides:}
+ 1..$ -> $sides::raw -> SYS::randomInt -> $ + 1 !
+end die-rolls
+
+[5 -> die-rolls&{sides:4}] -> '$;
+' -> !OUT::write
+
+// Pass templates as parameters, maybe with some parameters pre-filled
+source damage-roll&{first:, second:, third:}
+ (1 -> first) + (1 -> second) + (1 -> third) !
+end damage-roll
+
+$damage-roll&{first: die-rolls&{sides:4},
+ second: die-rolls&{sides:6}, third: die-rolls&{sides:20}}
+-> 'Damage done is $;
+' -> !OUT::write
+
+// Write tests inline. Run by --test flag on command line
+// Note the ~ in the matcher means "not",
+// and the array content matcher matches elements < 1 and > 4
+test 'die-rolls'
+ assert [100 -> die-rolls&{sides: 4}] <~[<..~1|4~..>]> 'all rolls 1..4'
+end 'die-rolls'
+
+// Provide modified modules to tests (aka test doubles or mocks)
+// IN is the standard input object and ::lines gets all lines
+source read-numbers
+ $IN::lines -> #
+ when <'\d+'> do $!
+end read-numbers
+
+test 'read numbers from input'
+ use shadowed core-system/
+ processor MockIn
+ source lines
+ [
+ '12a',
+ '65',
+ 'abc'
+ ]... !
+ end lines
+ end MockIn
+ def IN: $MockIn;
+ end core-system/
+ assert $read-numbers <=65> 'Only 65 is read'
+end 'read numbers from input'
+
+// You can work with byte arrays
+composer hexToBytes
+ <HEX>
+end hexToBytes
+
+'1a5c678d' -> hexToBytes -> ($ and [x 07 x]) -> $(last-1..last) -> '$;
+' -> !OUT::write // Outputs 0005
+
+```
+
+## Further Reading
+
+- [Main Tailspin site](https://github.com/tobega/tailspin-v0/)
+- [Tailspin language reference](https://github.com/tobega/tailspin-v0/blob/master/TailspinReference.md)
diff --git a/tcsh.html.markdown b/tcsh.html.markdown
index e38b7a27..8f8429bc 100644
--- a/tcsh.html.markdown
+++ b/tcsh.html.markdown
@@ -28,23 +28,23 @@ Some more files:
```tcsh
#!/bin/tcsh
-# First line of the script is shebang which tells the system how to execute the
-# script: http://en.wikipedia.org/wiki/Shebang_(Unix)
-# TCSH emulates the shebang on systems which don't understand it.
+# The first line of the script is a shebang which tells the system how to execute
+# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# TCSH emulates the shebang on systems that don't understand it.
-# In most cases you'll use `#!/bin/tcsh -f', because `-f' option does not load
+# In most cases you'll use `#!/bin/tcsh -f`, because `-f` option does not load
# any resource or start-up files, or perform any command hashing, and thus
# starts faster.
# --- the echo command --------------------------------------------------------
-# The `echo' writes each word to the shell's standard output, separated by
+# The `echo` writes each word to the shell's standard output, separated by
# spaces and terminated with a newline. The echo_style shell variable may be
# set to emulate (or not) the flags and escape sequences.
# Display the value of echo_style
echo $echo_style
-# Enable `echo' to support backslashed characters and `-n' option (no new line)
+# Enable `echo` to support backslashed characters and `-n` option (no new line)
# This is the default for tcsh, but your distro may change it. Slackware has
# done so.
set echo_style = both
@@ -65,17 +65,17 @@ echo 'two\nlines'
# --- Basic Syntax ------------------------------------------------------------
# A special character (including a blank or tab) may be prevented from having
-# its special meaning by preceding it with a backslash `\'.
-# this will display the last history commands
+# its special meaning by preceding it with a backslash `\`.
+# This will display the last history commands
echo !!
-# this will not
+# This will not
echo \!\!
-# Single quotes prevents expanding special characters too, but some
-# characters like `!' and backslash have higher priority
-# `$' (variable value) will not expands
+# Single quotes prevent expanding special characters too, but some
+# characters like `!` and backslash have higher priority
+# `$` (variable value) will not expand
echo '$1 tip'
-# `!' (history) will expands
+# `!` (history) will expand
echo '!!'
# Strings enclosed by back-quotes will be executed and replaced by the result.
@@ -85,16 +85,16 @@ echo `ls`
echo 'first line'; echo 'second line'
# There is also conditional execution
-echo "Always executed" || echo "Only executed if first command fails"
-echo "Always executed" && echo "Only executed if first command does NOT fail"
+echo "Always executed" || echo "Only executed if the first command fails"
+echo "Always executed" && echo "Only executed if the first command does NOT fail"
# Parenthesised commands are always executed in a subshell,
-# example: create a project and then informs you that it finished while
+# example: creates a project and then informs you that it finished while
# it does the installation.
make && ( espeak "BOSS, compilation finished"; make install )
-# prints the home directory but leaving you where you were
+# prints the home directory but leaves you where you were
(cd; pwd); pwd
# Read tcsh man-page documentation
@@ -103,10 +103,10 @@ man tcsh
# --- Variables ---------------------------------------------------------------
# The shell maintains a list of variables, each of which has as value a list of
# zero or more words. The values of shell variables can be displayed and
-# changed with the `set' and `unset' commands.
-# The system maintains its own list of ``environment'' variables.
-# These can be displayed and changed with `printenv', `setenv' and `unsetenv'.
-# The syntax of setenv is similar to POSIX sh.
+# changed with the `set` and `unset` commands.
+# The system maintains its own list of "environment" variables.
+# These can be displayed and changed with `printenv`, `setenv`, and `unsetenv`.
+# The syntax of `setenv` is similar to POSIX sh.
# Assign a value or nothing will create a variable
# Assign nothing
@@ -122,7 +122,7 @@ set var = `ls`
# Remove a variable
unset var
-# Prints 1 (true) if the variable `var' exists otherwise prints 0 (false)
+# Prints 1 (true) if the variable `var` exists otherwise prints 0 (false)
echo $?var
# Print all variables and their values
set
@@ -130,10 +130,10 @@ set
# Prints the contents of 'var'
echo $var;
echo "$var";
-# Prints the string `$var'
+# Prints the string `$var`
echo \$var
echo '$var'
-# braces can be used to separate variable from the rest when its needed
+# Braces can be used to separate variables from the rest when it is needed
set num = 12; echo "There ${num}th element"
# Prints the number of characters of the value: 6
@@ -147,7 +147,7 @@ echo $var
echo $var[*]
# Print the count of elements: 5
echo $#var
-# Print indexed element; prints the second element: two
+# Print the indexed element; This prints the second element: two
echo $var[2]
# Print range of elements; prints 2nd up to 3rd: two, three
echo $var[2-3]
@@ -165,8 +165,8 @@ echo $var[-3]
# $! the PID of the last background process started by this shell
# $$ script's PID
-# $path, $PATH the list of directories that will search for executable to run
-# $home, $HOME user's home directory, also the `~' can be used instead
+# $path, $PATH the list of directories that will search for an executable to run
+# $home, $HOME user's home directory, also the `~` can be used instead
# $uid user's login ID
# $user user's login name
# $gid the user's group ID
@@ -174,24 +174,24 @@ echo $var[-3]
# $cwd, $PWD the Current/Print Working Directory
# $owd the previous working directory
# $tcsh tcsh version
-# $tty the current tty; ttyN for linux console, pts/N for terminal
+# $tty the current tty; ttyN for Linux console, pts/N for terminal
# emulators under X
# $term the terminal type
# $verbose if set, causes the words of each command to be printed.
-# can be set by the `-v' command line option too.
+# can be set by the `-v` command line option too.
# $loginsh if set, it is a login shell
# TIP: $?0 is always false in interactive shells
# TIP: $?prompt is always false in non-interactive shells
-# TIP: if `$?tcsh' is unset; you run the original `csh' or something else;
-# try `echo $shell'
-# TIP: $verbose this is useful to debugging scripts
-# NOTE: $PWD and $PATH are synchronised with $cwd and $pwd automatically.
+# TIP: if `$?tcsh` is unset; you run the original `csh` or something else;
+# try `echo $shell`
+# TIP: `$verbose` is useful for debugging scripts
+# NOTE: `$PWD` and `$PATH` are synchronised with `$cwd` and `$pwd` automatically.
# --- Variable modifiers ------------------------------------------------------
# Syntax: ${var}:m[:mN]
# Where <m> is:
-# h : the directory t : the filenane r : remove extension e : the extension
+# h : the directory t : the filename r : remove extension e : the extension
# u : uppercase the first lowercase letter
# l : lowercase the first uppercase letter
# p : print but do not execute it (hist)
@@ -199,8 +199,8 @@ echo $var[-3]
# x : like q, but break into words at white spaces
# g : apply the following modifier once to each word
# a : apply the following modifier as many times as possible to single word
-# s/l/r/ : search for `l' and replace with `r', not regex; the `&' in the r is
-# replaced by l
+# s/l/r/ : search for `l` and replace with `r`, not regex; the `&` in the `r` is
+# replaced by `l`
# & : Repeat the previous substitution
# start with this file
@@ -232,7 +232,7 @@ echo 'this string' >> file.txt
echo 'this string' >>& file.txt
# Redirect the standard input from file.txt
cat < file.txt
-# Input from keyboard; this stores the input line to variable `x'
+# Input from keyboard; this stores the input line to variable `x`
set x = $<
# Document here;
cat << LABEL
@@ -243,7 +243,7 @@ LABEL
(grep 'AGP' /usr/src/linux/Documentation/* > output-file.txt) >& error-file.txt
# example: read a name from standard input and display a greetings message
-echo -n "Enter your name? "
+echo -n "Enter your name: "
set name = $<
echo "Greetings $name"
@@ -266,15 +266,15 @@ if ( $name != $user ) echo "Your name isn't your username"
# NOTE: if $name is empty, tcsh sees the above condition as:
# if ( != $user ) ...
# which is invalid syntax
-# so the "safe" way to use potentially empty variables in tcsh is:
+# The "safe" way to use potentially empty variables in tcsh is:
# if ( "$name" != $user ) ...
# which, when $name is empty, is seen by tcsh as:
# if ( "" != $user ) ...
# which works as expected
# There is also conditional execution
-echo "Always executed" || echo "Only executed if first command fails"
-echo "Always executed" && echo "Only executed if first command does NOT fail"
+echo "Always executed" || echo "Only executed if the first command fails"
+echo "Always executed" && echo "Only executed if the first command does NOT fail"
# To use && and || with if statements, you don't need multiple pairs of
# square brackets:
@@ -286,14 +286,14 @@ if ( "$name" == "Daniya" || "$name" == "Zach" ) then
echo "This will run if $name is Daniya OR Zach."
endif
-# String matching operators ( `=~' and `!~' )
+# String matching operators ( `=~` and `!~` )
# The ‘==’ ‘!=’ ‘=~’ and ‘!~’ operators compare their arguments as strings;
# all others operate on numbers. The operators ‘=~’ and ‘!~’ are like ‘!=’
# and ‘==’ except that the right hand side is a glob-pattern against which
-# the left hand operand is matched.
+# the left-hand operand is matched.
if ( $user =~ ni[ck]* ) echo "Greetings Mr. Nicholas."
-if ( $user !~ ni[ck]* ) echo "Hey, get out of Nicholas PC."
+if ( $user !~ ni[ck]* ) echo "Hey, get out of Nicholas' PC."
# Arithmetic expressions are denoted with the following format:
@ result = 10 + 5
@@ -302,16 +302,16 @@ echo $result
# Arithmetic Operators
# +, -, *, /, %
#
-# Arithmetic Operators which must be parenthesised
+# Arithmetic Operators which must be parenthesized
# !, ~, |, &, ^, ~, <<, >>,
# Compare and logical operators
#
-# All operators are same as in C.
+# All operators are the same as in C.
# It is non so well documented that numeric expressions require spaces
-# in-between; Also, `@' has its own parser, it seems that work well when the
-# expression is parenthesised otherwise the primary parser seems it is active.
-# Parenthesis require spaces around, this is documented.
+# in-between; Also, `@` has its own parser, it seems that it works well when
+# the expression is parenthesized, otherwise the primary parser seems to be
+# active. Parentheses require spaces around, this is documented.
# wrong
@ x = $y+1
@@ -330,32 +330,32 @@ echo $result
# C's operators ++ and -- are supported if there is not assignment
@ result ++
-# None shell created to do mathematics;
+# No shell was created to do mathematics;
# Except for the basic operations, use an external command with backslashes.
#
# I suggest the calc as the best option.
# (http://www.isthe.com/chongo/tech/comp/calc/)
#
-# The standard Unix's bc as second option
+# The standard Unix's bc as the second option
# (https://www.gnu.org/software/bc/manual/html_mono/bc.html)
#
-# The standard Unix's AWK as third option
+# The standard Unix's AWK as the third option
# (https://www.gnu.org/software/gawk/manual/gawk.html)
-# You can also use `perl', `php' or even several BASICs, but prefer the
-# above utilities for faster load-and-run results.
+# You can also use `Perl`, `PHP`, `python`, or even several BASICs, but prefer
+# the above utilities for faster load-and-run results.
# real example: (that I answer in StackExchange)
# REQ: x := 1001b OR 0110b
-# in `tcsh' expression (by using octal)
+# in `tcsh` expression (by using octal)
@ x = ( 011 | 06 ); echo $x
-# the same by using `calc' (and using binary as the original req)
+# the same by using `calc` (and using binary as the original req)
set x = `calc '0b1001 | 0b110'`; echo $x
# --- File Inquiry Operators --------------------------------------------------
-# NOTE: The builtin `filetest' command do the same thing.
+# NOTE: The built-in `filetest` command does the same thing.
#### Boolean operators
# -r read access -w write access -x execute access -e existence
@@ -366,23 +366,23 @@ set x = `calc '0b1001 | 0b110'`; echo $x
# -b block device -c char device
# -t file (digit) is an open file descriptor for a terminal device
-# if the file `README' exists, displays a message
+# If the file `README` exists, display a message
if ( -e README ) echo "I have already README file"
-# if the `less' program is installed, use this instead of `more'
+# If the `less` program is installed, use it instead of `more`
if ( -e `where less` ) then
- alias more 'less'
+ alias more 'less'
endif
#### Non-boolean operators
# -Z returns the file size in bytes
# -M returns the modification time (mtime) -M: returns mtime string
-# -A returns the lass access time (atime) -A: returns atime string
-# -U returns the owners user ID -U: returns the owners user-name
-# -G returns the group ID -G: returns the group-name
+# -A returns the last access time (atime) -A: returns atime string
+# -U returns the owner's user ID -U: returns the owner's user name
+# -G returns the owner's group ID -G: returns the owner's group name
# -P returns the permissions as octal number -Pmode returns perm. AND mode
-# this will display the date as Unix-time integer: 1498511486
+# this will display the date as a Unix-time integer: 1498511486
filetest -M README.md
# This will display "Tue Jun 27 00:11:26 2017"
@@ -390,14 +390,14 @@ filetest -M: README.md
# --- Basic Commands ----------------------------------------------------------
-# Navigate though file system with `chdir' (cd)
+# Navigate through the filesystem with `chdir` (cd)
cd path # change working directory
-cd # change to home directory
-cd - # change to previous directory
+cd # change to the home directory
+cd - # change to the previous directory
cd .. # go up one directory
# Examples:
-cd ~/Downloads # go to my `Downloads' directory
+cd ~/Downloads # go to my `Downloads` directory
# Use `mkdir` to create new directories.
mkdir newdir
@@ -413,7 +413,7 @@ where csh
# --- Pipe-lines --------------------------------------------------------------
# A pipeline is a sequence of processes chained together by their standard
# streams, so that the output of each process (stdout) feeds directly as input
-# (stdin) to the next one. This `pipes' are created with the `|' special
+# (stdin) to the next one. These `pipes` are created with the `|` special
# character and it is one of the most powerful characteristics of Unix.
# example:
@@ -422,18 +422,18 @@ ls -l | grep key | less
# input (stdin) of the process for "grep key"; and likewise for the process
# for "less".
-# the `ls', the `grep' and the `less' are programs of Unix and they have their
-# own man-page. The `pipe' mechanism is part of the kernel but the syntax
-# and the control is job of the shell, the tcsh in our case.
+# the `ls`, the `grep`, and the `less` are Unix programs and they have their
+# own man-page. The `pipe` mechanism is part of the kernel but the syntax
+# and the control is the shell's job, the tcsh in our case.
-# NOTE: `pipe' mechanism has Windows too, but it is buggy and I sign it for all
-# versions until Windows XP SP3 API32 which was the last one that I worked on.
-# Microsoft still denied it but is well known bug since it is a common method
-# for inter-process communication. For small I/O it will work well.
-# tcsh, along with grep, gcc and perl is one of the first Unix programs that
+# NOTE: Windows has the `pipe` mechanism too, but it is buggy and I signed it
+# for all versions until Windows XP SP3 API32 which was the last one that I
+# worked on. Microsoft denied it, but it is a well-known bug since it is a
+# common method for inter-process communication. For small I/O it will work well.
+# tcsh, along with grep, GCC, and Perl is one of the first Unix programs that
# ported to DOS (with EMX DOS extender) and later to Windows (1998).
-# example: this will convert tcsh to PostScript and will show it with okular
+# example: this will convert tcsh to PostScript and will show it with Okular
zcat /usr/man/man1/tcsh.1.gz | groff -Tps -man | okular -
# a better version
@@ -451,10 +451,10 @@ set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz");
set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz");
zcat `eval $loc` | groff -Tps -man | ps2pdf - ${page}.pdf && okular tcsh.pdf
-# NOTE: `okular' is the default application of KDE environment and it shows
-# postcript and pdf files. You can replace it with your lovely pdf viewer.
-# zcat, locate, groff, are common programs in all Unices. `ps2pdf' program
-# is part of `ghostscript' package that is widely used.
+# NOTE: `okular` is the default application of the KDE environment and it shows
+# postcript and pdf files. You can replace it with your lovely PDF viewer.
+# `zcat`, `locate`, `groff`, are common programs in all Unixes. The `ps2pdf`
+# program is part of the `ghostscript` package that is widely used.
# --- Control Flow ------------------------------------------------------------
@@ -468,8 +468,8 @@ set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz");
# ...]
# endif
#
-# If the specified expr is true then the commands to the first else are
-# executed; otherwise if expr2 is true then the commands to the second else
+# If the specified `expr` is true then the commands to the first else are
+# executed; otherwise if `expr2` is true then the commands to the second else
# are executed, etc.
# Any number of else-if pairs are possible; only one endif is needed.
#
@@ -477,24 +477,24 @@ set page = tcsh; set loc = (locate -b -n 1 "\\\\"${page}".1.gz");
#
# if ( expr ) command
#
-# If `expr' evaluates true, then command is executed.
-# `command' must be a simple command, not an alias, a pipeline, a command list
-# or a parenthesized command list. With few words, avoid to use it.
+# If `expr` evaluates to true, then the command is executed.
+# `command` must be a simple command, not an alias, a pipeline, a command list
+#, or a parenthesized command list. With a few words, avoid using it.
#
-# BUG: Input/output redirection occurs even if expr is false and command is
-# thus not executed.
+# BUG: Input/output redirection occurs even if expr is false and the command
+# is thus not executed.
#
-# check if we are in non-interactive shell and quit if true
+# check if we are in a non-interactive shell and quit if true
if ( $?USER == 0 || $?prompt == 0 ) exit
# check if we are a login shell
if ( $?loginsh ) then
- # check if you are on linux console (not X's terminal)
- if ( $tty =~ tty* ) then
- # enable keypad application keys (man console_codes)
- echo '\033='
- endif
+ # check if you are on linux console (not X's terminal)
+ if ( $tty =~ tty* ) then
+ # enable keypad application keys (man console_codes)
+ echo '\033='
+ endif
endif
#### SWITCH-ENDSW
@@ -509,37 +509,37 @@ endif
#
# tcsh uses a case statement that works similarly to switch in C.
# Each case label is successively matched, against the specified string which
-# is first command and filename expanded. The file metacharacters `*', `?'
-# and `[...]' may be used in the case labels. If none of the labels match the
-# execution begins after the default label if its defined.
-# The command `breaksw' causes execution to continue after the endsw. Otherwise
+# is first command and filename expanded. The file metacharacters `*`, `?`
+# and `[...]` may be used in the case labels. If none of the labels match the
+# execution begins after the default label if it's defined.
+# The command `breaksw` causes execution to continue after the endsw. Otherwise,
# control may fall through case labels and default labels as in C.
switch ( $var )
case *.[1-9]:
case *.[1-9].gz:
- echo "$var is a man-page."
- breaksw
+ echo "$var is a man-page."
+ breaksw
case *gz:
- echo "$var is gzipped"
- breaksw
+ echo "$var is gzipped"
+ breaksw
default:
- file $var
+ file $var
endsw
#### FOREACH-END
# Syntax:
# foreach name ( wordlist )
-# ...
+# ...
# [break | continue]
# end
#
-# Successively sets the variable `name' to each member of `wordlist' and
+# Successively sets the variable `name` to each member of `wordlist` and
# executes the sequence of commands between this command and the matching
-# `end' keyword. The `continue' keyword jump to the next element back to
-# top; and the `break' keyword terminates the loop.
+# `end` keyword. The `continue` keyword jumps to the next element back to
+# top, and the `break` keyword terminates the loop.
#
-# BUG: `foreach' doesn't ignore here documents when looking for its end.
+# BUG: `foreach` doesn't ignore here documents when looking for its end.
# example: counting 1 to 10
foreach i ( `seq 1 10` )
@@ -548,12 +548,12 @@ end
# example: type all files in the list
foreach f ( a.txt b.txt c.txt )
- cat $f
+ cat $f
end
# example: convert wma to ogg
foreach f ( *.wma )
- ffmpeg -i "$f" "$f:r".ogg
+ ffmpeg -i "$f" "$f:r".ogg
end
#### WHILE-END
@@ -562,22 +562,22 @@ end
# [break | continue]
# end
#
-# Executes the commands between the `while' and the matching `end' while `expr'
-# evaluates non-zero. `break' and `continue' may be used to terminate or
+# Executes the commands between the `while` and the matching `end` while `expr`
+# evaluates non-zero. `break` and `continue` may be used to terminate or
# continue the loop prematurely.
# count from 1 to 10
set num = 1
while ( $num <= 10 )
- echo $num
- @ num ++
+ echo $num
+ @ num ++
end
# print all directories of CWD
set lst = ( * )
while ( $#lst )
- if ( -d $lst[1] ) echo $lst[1] is directory
- shift lst
+ if ( -d $lst[1] ) echo $lst[1] is directory
+ shift lst
end
# separate command-line arguments to options or parameters
@@ -585,12 +585,12 @@ set options
set params
set lst = ( $* )
while ( $#lst )
- if ( "$lst[1]" =~ '-*' ) then
- set options = ( $options $lst[1] )
- else
- set params = ( $params $lst[1] )
- endif
- shift lst
+ if ( "$lst[1]" =~ '-*' ) then
+ set options = ( $options $lst[1] )
+ else
+ set params = ( $params $lst[1] )
+ endif
+ shift lst
end
echo 'options =' $options
echo 'parameters =' $params
@@ -599,16 +599,16 @@ echo 'parameters =' $params
# Syntax: repeat count command
#
# The specified command, which is subject to the same restrictions as the
-# command in the one line if statement above, is executed count times.
-# I/O redirections occur exactly once, even if count is 0.
+# command in the one line `if` statement above, is executed count times.
+# I/O redirections occur exactly once, even if `count` is 0.
#
-# TIP: in most cases prefer `while'
+# TIP: in most cases prefer `while`
repeat 3 echo "ding dong"
# --- Functions ---------------------------------------------------------------
# tcsh has no functions but its expression syntax is advanced enough to use
-# `alias' as functions. Another method is recursion
+# `alias` as functions. Another method is recursion
# Alias argument selectors; the ability to define an alias to take arguments
# supplied to it and apply them to the commands that it refers to.
@@ -637,48 +637,48 @@ alias cd 'cd \!* && ls'
#!/bin/tcsh -f
set todo = option1
if ( $#argv > 0 ) then
- set todo = $argv[1]
+ set todo = $argv[1]
endif
switch ( $todo )
case option1:
-# ...
- $0 results
- breaksw
+# ...
+ $0 results
+ breaksw
case option2:
-# ...
- $0 results
- breaksw
+# ...
+ $0 results
+ breaksw
case results:
- echo "print the results here"
-# ...
- breaksw
+ echo "print the results here"
+# ...
+ breaksw
default:
- echo "Unknown option: $todo"
-# exit 0
+ echo "Unknown option: $todo"
+# exit 0
endsw
# --- Recursion method --- end ---
# --- examples ----------------------------------------------------------------
# this script prints available power-states if no argument is set;
-# otherwise it set the state of the $argv[1]
+# otherwise it sets the state of the $argv[1]
# --- power-state script --- begin --------------------------------------------
#!/bin/tcsh -f
# get parameter ("help" for none)
set todo = help
if ( $#argv > 0 ) then
- set todo = $argv[1]
+ set todo = $argv[1]
endif
# available options
set opts = `cat /sys/power/state`
# is known?
foreach o ( $opts )
- if ( $todo == $o ) then
- # found; execute it
- echo -n $todo > /sys/power/state
- break
- endif
+ if ( $todo == $o ) then
+ # found; execute it
+ echo -n $todo > /sys/power/state
+ break
+ endif
end
# print help and exit
echo "usage: $0 [option]"
@@ -691,19 +691,19 @@ echo "available options on kernel: $opts"
set secret=`shuf -i1-100 -n1`
echo "I have a secret number from 1 up to 100"
while ( 1 )
- echo -n "Guess: "
- set guess = $<
- if ( $secret == $guess ) then
- echo "You found it"
- exit 1
- else
- if ( $secret > $guess ) then
- echo "its greater"
- else if ( $secret < $guess ) then
- echo "its lesser"
- endif
- endif
- endif
+ echo -n "Guess: "
+ set guess = $<
+ if ( $secret == $guess ) then
+ echo "You found it"
+ exit 1
+ else
+ if ( $secret > $guess ) then
+ echo "its greater"
+ else if ( $secret < $guess ) then
+ echo "its lesser"
+ endif
+ endif
+ endif
end
# --- secretnum.csh --- end ---------------------------------------------------
@@ -711,36 +711,36 @@ end
# Appendices
#### About [T]CSH:
-# * CSH is notorious about its bugs;
-# * It was also famous about its advanced interactive mode.
-# * TCSH is famous that have the most advanced completition subsystem.
-# * TCSH is famous that have the most advanced aliases subsystem; aliases
-# can take parameters and often used as functions!
-# * TCSH is well known that preferred by people (me too) because of better
-# syntax. All shells are using Thomson's syntax with exception of [t]csh,
-# fish and plan9's shells (rc, ex).
-# * It is smaller and consume far less memory than bash, zsh even mksh!
+# * CSH is notorious for its bugs;
+# * It is also famous for its advanced interactive mode.
+# * TCSH is famous for having the most advanced completion subsystem.
+# * TCSH is famous for having the most advanced aliases subsystem; aliases
+# can take parameters and often be used as functions!
+# * TCSH is well known and preferred by people (me too) because of better
+# syntax. All shells are using Thomson's syntax with the exception of
+# [t]csh, fish, and plan9's shells (rc, ex).
+# * It is smaller and consumes far less memory than bash, zsh, and even mksh!
# (memusage reports)
-# * TCSH still has bugs; less but have; if you write readable clean code you'll
-# find none; well almost none... This has to do with the implementation of
-# csh; that no means the other shells has good implementation.
-# * no one well known shell is capable for regular programming; if your script
-# getting big, use a programming language, or at least PHP or Perl (good
-# script languages).
+# * TCSH still has bugs; fewer, but it does; if you write readable clean code
+# you'll find none; well almost none... This has to do with the implementation
+# of csh; that doesn't mean the other shells have a good implementation.
+# * no well-known shell is capable of regular programming; if your script
+# is getting big, use a programming language, like Python, PHP, or Perl (good
+# scripting languages).
#
-# Advises:
-# 1. Do not use redirection in single-line if (it is well documented bug)
-# In most cases avoid to use single-line IFs.
-# 2. Do not mess up with other shells code, c-shell is not compatible with
+# Advice:
+# 1. Do not use redirection in single-line IFs (it is well documented bug)
+# In most cases avoid using single-line IFs.
+# 2. Do not mess up with other shells' code, c-shell is not compatible with
# other shells and has different abilities and priorities.
# 3. Use spaces as you'll use them to write readable code in any language.
-# A bug of csh was `set x=1' worked, `set x = 1' worked, `set x =1' did not!
-# 4. It is well documented that numeric expressions require spaces in-between;
-# also parenthesise all bit-wise and unary operators.
-# 5. Do not write a huge weird expression with several quotes, backslashes etc
+# A bug of csh was `set x=1` and `set x = 1` worked, but `set x =1` did not!
+# 4. It is well documented that numeric expressions require spaces in between;
+# also parenthesize all bit-wise and unary operators.
+# 5. Do not write a huge weird expression with several quotes, backslashes, etc
# It is bad practice for generic programming, it is dangerous in any shell.
# 6. Help tcsh, report the bug here <https://bugs.gw.com/>
-# 7. Read the man page, `tcsh' has huge number of options, and variables.
+# 7. Read the man page, `tcsh` has a huge number of options and variables.
#
# I suggest the following options enabled by default
# --------------------------------------------------
@@ -770,14 +770,14 @@ end
# unset time
# unset tperiod
#
-# NOTE: If the `backslash_quote' is set, it may create compatibility issues
-# with other tcsh scripts which was written without it.
+# NOTE: If the `backslash_quote` is set, it may create compatibility issues
+# with other tcsh scripts that were written without it.
#
-# NOTE: The same for `parseoctal', but it is better to fix the problematic
+# NOTE: The same for `parseoctal`, but it is better to fix the problematic
# scripts.
#
# NOTE: **for beginners only**
-# This enable automatically rescan `path' directories if need to. (like bash)
+# This enables automatic rescanning of `path` directories if needed. (like bash)
# set autorehash
#### common aliases
diff --git a/textile.html.markdown b/textile.html.markdown
index 2b81674a..293e647d 100644
--- a/textile.html.markdown
+++ b/textile.html.markdown
@@ -165,11 +165,11 @@ but again, they use different HTML markup and thus the distinction.
###. Superscripts and Subscripts use carats and tildes:
-Superscripts are 2 ^nd^ to none, but subscripts are CO ~2~ L too.
+Superscripts are 2 ^and^ to none, but subscripts are CO ~2~ L too.
Note the spaces around the superscripts and subscripts.
To avoid the spaces, add square brackets around them:
-2[^nd^] and CO[~2~]L
+2[^and^] and CO[~2~]L
###. Insertions and deletions are indicated using -/+ symbols:
This is -deleted- text and this is +inserted+ text.
@@ -375,7 +375,7 @@ table(tableclass).
|a|classy|table|
|a|classy|table|
-###. Spanning rows and colums:
+###. Spanning rows and columns:
A backslash \ is used for a column span:
|\2. spans two cols |
diff --git a/tmux.html.markdown b/tmux.html.markdown
index 1c2c2da3..095e24fb 100644
--- a/tmux.html.markdown
+++ b/tmux.html.markdown
@@ -183,7 +183,7 @@ bind a send-prefix
### Theme
###########################################################################
-# Statusbar Color Palatte
+# Statusbar Color Palette
set-option -g status-justify left
set-option -g status-bg black
set-option -g status-fg white
diff --git a/toml.html.markdown b/toml.html.markdown
index 79aa544c..69dfd754 100755
--- a/toml.html.markdown
+++ b/toml.html.markdown
@@ -69,11 +69,15 @@ The first newline is trimmed in raw strings.
###########
## Integers can start with a +, a - or nothing.
-## Leading zeros are not allowed. Hex, octal, and binary forms are not allowed.
+## Leading zeros are not allowed.
+## Hex, octal, and binary forms are allowed.
## Values that cannot be expressed as a series of digits are not allowed.
int1 = +42
int2 = 0
int3 = -21
+int4 = 0xdeadbeef
+int5 = 0o755
+int6 = 0b11011100
integerRange = 64
## You can use underscores to enhance readability. Each
diff --git a/tr-tr/bf-tr.html.markdown b/tr-tr/bf-tr.html.markdown
index e7015cd0..ef46f362 100644
--- a/tr-tr/bf-tr.html.markdown
+++ b/tr-tr/bf-tr.html.markdown
@@ -1,6 +1,6 @@
---
language: bf
-filename: brainfuck-tr
+filename: brainfuck-tr.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io"]
translators:
diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown
index 9d65cf9c..c944f245 100644
--- a/tr-tr/c++-tr.html.markdown
+++ b/tr-tr/c++-tr.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
lang: tr-tr
filename: learncpp-tr.cpp
contributors:
diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown
index 4ef12527..05531d64 100644
--- a/tr-tr/c-tr.html.markdown
+++ b/tr-tr/c-tr.html.markdown
@@ -1,7 +1,7 @@
---
-name: c
+name: C
category: language
-language: c
+language: C
filename: learnc-tr.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
diff --git a/tr-tr/clojure-tr.html.markdown b/tr-tr/clojure-tr.html.markdown
index 5ebe5ce6..d21947ee 100644
--- a/tr-tr/clojure-tr.html.markdown
+++ b/tr-tr/clojure-tr.html.markdown
@@ -482,7 +482,7 @@ Clojuredocs.org, örneklerle bezenmiş Clojure dökümantasyonu:
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure, interaktif bir ÅŸekilde FP ve Clojure yeteneklerinizi geliÅŸtirmenize olanak veriyor:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org, Başlangıç için bir içeriklere sahip:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown
index 91c7c269..9834be20 100644
--- a/tr-tr/csharp-tr.html.markdown
+++ b/tr-tr/csharp-tr.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown
index 87c1820c..c6979468 100644
--- a/tr-tr/git-tr.html.markdown
+++ b/tr-tr/git-tr.html.markdown
@@ -587,8 +587,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Kopya Kağıdı](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - Basit bir kılavuz](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 74cd15c6..64f5ca5b 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -2,6 +2,7 @@
language: TypeScript
contributors:
- ["Philippe Vlérick", "https://github.com/pvlerick"]
+ - ["Kiwimoe", "https://github.com/kiwimoe"]
filename: learntypescript.ts
---
@@ -291,7 +292,6 @@ foo.baz = 'hello world'
## Further Reading
* [TypeScript Official website] (http://www.typescriptlang.org/)
- * [TypeScript language specifications] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)
- * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [TypeScript language specifications] (https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md)
+ * [Learn TypeScript] (https://learntypescript.dev/)
* [Source Code on GitHub] (https://github.com/Microsoft/TypeScript)
- * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/uk-ua/c-ua.html.markdown b/uk-ua/c-ua.html.markdown
index c4dac75f..56a2b2ad 100644
--- a/uk-ua/c-ua.html.markdown
+++ b/uk-ua/c-ua.html.markdown
@@ -1,5 +1,5 @@
---
-language: c
+language: C
filename: learnc-ua.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
diff --git a/uk-ua/go-ua.html.markdown b/uk-ua/go-ua.html.markdown
index f980f7b1..6f294b1f 100644
--- a/uk-ua/go-ua.html.markdown
+++ b/uk-ua/go-ua.html.markdown
@@ -434,15 +434,15 @@ func requestServer() {
## Подальше вивченнÑ
-ОÑновним джерелом вÑієї інформації про Go залишаєтьÑÑ [офіційна веб-Ñторінка](http://golang.org/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати.
-Окрім туру, у [документації](https://golang.org/doc/) міÑтитьÑÑ Ñ–Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ Ñк пиÑати чиÑтий та ефективний код на Go, Ð´Ð¾ÐºÑƒÐ¼ÐµÐ½Ñ‚Ð°Ñ†Ñ–Ñ Ð¿Ð°ÐºÐµÑ‚Ñ–Ð² та окремих команд, а також Ñ–ÑÑ‚Ð¾Ñ€Ñ–Ñ Ñ€ÐµÐ»Ñ–Ð·Ñ–Ð².
+ОÑновним джерелом вÑієї інформації про Go залишаєтьÑÑ [офіційна веб-Ñторінка](https://go.dev/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати.
+Окрім туру, у [документації](https://go.dev/doc/) міÑтитьÑÑ Ñ–Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ Ñк пиÑати чиÑтий та ефективний код на Go, Ð´Ð¾ÐºÑƒÐ¼ÐµÐ½Ñ‚Ð°Ñ†Ñ–Ñ Ð¿Ð°ÐºÐµÑ‚Ñ–Ð² та окремих команд, а також Ñ–ÑÑ‚Ð¾Ñ€Ñ–Ñ Ñ€ÐµÐ»Ñ–Ð·Ñ–Ð².
Ðадзвичайно рекомендуєтьÑÑ Ð¾Ð·Ð½Ð°Ð¹Ð¾Ð¼Ð¸Ñ‚Ð¸ÑÑŒ із визначеннÑм мови. Вона легко читаєтьÑÑ Ñ‚Ð° на диво коротка (в порівнÑнні з іншими ÑучаÑними мовами).
-Можна погратиÑÑŒ з кодом вище на [Go playground](https://play.golang.org/p/tnWMjr16Mm). Спробуй змінити його та запуÑтити із Ñвого браузера. Поміть, що можна викориÑтовувати [https://play.golang.org](https://play.golang.org) Ñк [REPL](https://uk.wikipedia.org/wiki/REPL) до теÑтів та коду в твоєму браузері, без вÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Go.
+Можна погратиÑÑŒ з кодом вище на [Go playground](https://go.dev/play/p/tnWMjr16Mm). Спробуй змінити його та запуÑтити із Ñвого браузера. Поміть, що можна викориÑтовувати [https://go.dev/play/](https://go.dev/play/) Ñк [REPL](https://uk.wikipedia.org/wiki/REPL) до теÑтів та коду в твоєму браузері, без вÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Go.
-Ð’ ÑпиÑку Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð½Ñ Ð½Ð¾Ð²Ð°Ñ‡ÐºÐ°Ð¼ в Go - [вихідний код Ñтандартної бібліотеки](http://golang.org/src/pkg/). Код вÑеоÑÑжно задокоментований, тому Ñ” найкращим прикладом з боку зручного Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð½Ñ Ñ‚Ð° швидкоÑÑ‚Ñ– Ñ€Ð¾Ð·ÑƒÐ¼Ñ–Ð½Ð½Ñ ÐºÐ¾Ð´Ñƒ на цій мові програмуваннÑ. Приведений Ñтиль та ідіоми Go.
-Крім того, можна проÑто натиÑнути на назву функції в [документації](http://golang.org/pkg/), щоб перейти до Ñ—Ñ— реалізації.
+Ð’ ÑпиÑку Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð½Ñ Ð½Ð¾Ð²Ð°Ñ‡ÐºÐ°Ð¼ в Go - [вихідний код Ñтандартної бібліотеки](https://go.dev/src/). Код вÑеоÑÑжно задокоментований, тому Ñ” найкращим прикладом з боку зручного Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð½Ñ Ñ‚Ð° швидкоÑÑ‚Ñ– Ñ€Ð¾Ð·ÑƒÐ¼Ñ–Ð½Ð½Ñ ÐºÐ¾Ð´Ñƒ на цій мові програмуваннÑ. Приведений Ñтиль та ідіоми Go.
+Крім того, можна проÑто натиÑнути на назву функції в [документації](https://go.dev/pkg/), щоб перейти до Ñ—Ñ— реалізації.
Іншим прекраÑним поÑиланнÑм Ð´Ð»Ñ Ð²Ð¸Ð²Ñ‡ÐµÐ½Ð½Ñ Go Ñ” [Go by example](https://gobyexample.com/).
diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown
index 422de371..4aad0cbb 100644
--- a/uk-ua/rust-ua.html.markdown
+++ b/uk-ua/rust-ua.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/v.html.markdown b/v.html.markdown
new file mode 100644
index 00000000..4f698184
--- /dev/null
+++ b/v.html.markdown
@@ -0,0 +1,229 @@
+---
+language: v
+filename: vlang.v
+contributors:
+ - ["Maou Shimazu", "https://github.com/Maou-Shimazu"]
+---
+
+V is a statically typed compiled programming language
+designed for building maintainable software.
+
+It's similar to Go and its design has also been influenced by
+Oberon, Rust, Swift, Kotlin, and Python.
+
+The language promotes writing
+simple and clear code with minimal abstraction.
+
+Despite being simple, V gives the developer a lot of power.
+Anything you can do in other languages, you can do in V.
+
+```v
+// Single Line Comment.
+/*
+ Multi Line Comment
+*/
+
+struct User { // Cannot be defined in main, explained later.
+ age int
+ name string
+ pos int = -1 // custom default value
+}
+// struct method
+fn (u User) can_register() bool {
+ return u.age > 16
+}
+
+struct Parser {
+ token Token
+}
+
+// c like enums
+enum Token {
+ plus
+ minus
+ div
+ mult
+}
+
+// 1. functions
+// language does not use semi colons
+fn add(x int, y int) int {
+ return x + y
+}
+// can return multiple values
+fn foo() (int, int) {
+ return 2, 3
+}
+
+// function visibility
+pub fn public_function() { // pub can only be used from a named module.
+}
+
+fn private_function() {
+}
+
+
+
+// Main function
+fn main() {
+ // Anonymous functions can be declared inside other functions:
+ double_fn := fn (n int) int {
+ return n + n
+ }
+ // 2. Variables: they are immutable by default
+ // implicitly typed
+ x := 1
+ // x = 2 // error
+ mut y := 2
+ y = 4
+ name := "John"
+ large_number := i64(9999999999999)
+ println("$x, $y, $name, $large_number") // 1, 4, John, 9999999999999
+
+ // unpacking values from functions.
+ a, b := foo()
+ println("$a, $b") // 2, 3
+ c, _ := foo() // ignore values using `_`
+ println("$c") // 2
+
+ // Numbers
+ u := u16(12)
+ v := 13 + u // v is of type `u16`
+ r := f32(45.6)
+ q := r + 3.14 // x is of type `f32`
+ s := 75 // a is of type `int`
+ l := 14.7 // b is of type `f64`
+ e := u + s // c is of type `int`
+ d := l + r // d is of type `f64`
+
+ // Strings
+ mut bob := 'Bob'
+ assert bob[0] == u8(66) // indexing gives a byte, u8(66) == `B`
+ assert bob[1..3] == 'ob' // slicing gives a string 'ob'
+ bobby := bob + 'by' // + is used to concatenate strings
+ println(bobby) // "Bobby"
+ bob += "by2" // += is used to append to strings
+ println(bob) // "Bobby2"
+
+ //String values are immutable. You cannot mutate elements:
+ //mut s := 'hello 🌎'
+ //s[0] = `H` // not allowed
+
+ //For raw strings, prepend r. Escape handling is not done for raw strings:
+ rstring := r'hello\nworld' // the `\n` will be preserved as two characters
+ println(rstring) // "hello\nworld"
+
+ // string interpolation
+ println('Hello, $bob!') // Hello, Bob!
+ println('Bob length + 10: ${bob.len + 10}!') // Bob length + 10: 13!
+
+ // 3. Arrays
+ mut numbers := [1, 2, 3]
+ println(numbers) // `[1, 2, 3]`
+ numbers << 4 // append elements with <<
+ println(numbers[3]) // `4`
+ numbers[1] = 5
+ println(numbers) // `[1, 5, 3]`
+ // numbers << "John" // error: `numbers` is an array of numbers
+ numbers = [] // array is now empty
+ arr := []int{len: 5, init: -1}
+ // `arr == [-1, -1, -1, -1, -1]`, arr.cap == 5
+
+ number_slices := [0, 10, 20, 30, 40]
+ println(number_slices[1..4]) // [10, 20, 30]
+ println(number_slices[..4]) // [0, 10, 20, 30]
+ println(number_slices[1..]) // [10, 20, 30, 40]
+
+ // 4. structs and enums
+ // struct User {
+ // age int
+ // name string
+ // pos int = -1 // custom default value
+ // }
+ mut users := User{21, 'Bob', 0}
+ println(users.age) // 21
+
+ // enum Token {
+ // plus
+ // minus
+ // div
+ // mult
+ // }
+
+ // struct Parser {
+ // token Token
+ // }
+ parser := Parser{}
+ if parser.token == .plus || parser.token == .minus
+ || parser.token == .div || parser.token == .mult {
+ // ...
+ }
+
+
+ // 5. Maps
+ number_map := {
+ 'one': 1
+ 'two': 2
+ }
+ println(number_map) // {'one': 1, 'two': 2}
+ println(number_map["one"]) // 1
+ mut m := map[string]int{} // a map with `string` keys and `int` values
+ m['one'] = 1
+ m['two'] = 2
+ println(m['one']) // "1"
+ println(m['bad_key']) // "0"
+ m.delete('two')
+
+ // 6. Conditionals
+ a_number := 10
+ b_number := 20
+ if a_number < b {
+ println('$a_number < $b_number')
+ } else if a_number > b {
+ println('$a_number > $b_number')
+ } else {
+ println('$a_number == $b_number')
+ }
+ num := 777
+ even_odd := if num % 2 == 0 { 'even' } else { 'odd' }
+ println(even_odd)
+
+ match even_odd {
+ 'even' { println('even') }
+ 'odd' { println('odd') }
+ else { println('unknown') }
+ }
+
+ // 7. Loops
+ loops := [1, 2, 3, 4, 5]
+ for lp in loops {
+ println(lp)
+ }
+ loop_names := ['Sam', 'Peter']
+ for i, lname in loop_names {
+ println('$i) $lname')
+ // Output: 0) Sam
+ // 1) Peter
+ }
+ // You can also use break and continue followed by a
+ // label name to refer to an outer for loop:
+ outer: for i := 4; true; i++ {
+ println(i)
+ for {
+ if i < 7 {
+ continue outer
+ } else {
+ break outer
+ }
+ }
+ }
+}
+
+```
+## Further reading
+
+There are more complex concepts to be learnt in V which are available at the
+official [V documentation](https://github.com/vlang/v/blob/master/doc/docs.md).
+
+You can also find more information about the V language at the [official website](https://vlang.io/)
+or check it out at the [v playground](https://v-wasm.vercel.app/). \ No newline at end of file
diff --git a/vala.html.markdown b/vala.html.markdown
index 06d6dedc..739e0fda 100755
--- a/vala.html.markdown
+++ b/vala.html.markdown
@@ -486,7 +486,7 @@ int more = 57;
int* more_pointer = &more; // & = address-of
int indirection_demo = more_pointer*; // indirection
-// Profiles: affect which Vala features are avaliable and which libraries the
+// Profiles: affect which Vala features are available and which libraries the
// C-code will use.
// - gobject (default)
// posix
diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown
index 1bcc94a0..f5454ebf 100644
--- a/vi-vn/git-vi.html.markdown
+++ b/vi-vn/git-vi.html.markdown
@@ -396,8 +396,6 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
-
* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown
index 257216ff..f709b838 100644
--- a/vi-vn/json-vi.html.markdown
+++ b/vi-vn/json-vi.html.markdown
@@ -37,7 +37,7 @@ kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD
"các khóa": "phải luôn được đặt trong dấu ngoặc kép",
"số": 0,
- "chuá»—i kí tá»±": "Xin chàø. Tất cả kí tá»± unicode Ä‘á»u được chấp nhận, sá»­ dụng vá»›i dạng \"kí tá»±\"."
+ "chuá»—i kí tá»±": "Xin chàø. Tất cả kí tá»± unicode Ä‘á»u được chấp nhận, sá»­ dụng vá»›i dạng \"kí tá»±\".",
"có đúng không?": true,
"không có gì": null,
diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown
index 89b59253..52c2df42 100644
--- a/vi-vn/markdown-vi.html.markdown
+++ b/vi-vn/markdown-vi.html.markdown
@@ -48,6 +48,7 @@ bằng cách thêm số lượng dấu thăng (#) đằng trước chuỗi cần
##### Äây là đầu mục <h5>
###### Äây là đầu mục <h6>
```
+
Markdown còn cung cấp cách khác để tạo đầu mục hạng nhất h1 và hạng nhì h2.
```md
@@ -79,6 +80,7 @@ Trong cài đặt Markdown để hiển thị file của GitHub,ta còn có gạ
```md
~~Äoạn văn bản này được gạch ngang.~~
```
+
## Äoạn văn
Äoạn văn bao gồm má»™t hay nhiá»u dòng văn bản liên tiếp nhau được phân cách
@@ -153,6 +155,7 @@ Ta không nhất thiết phải Ä‘iá»n số thứ thá»± cho chỉ mục đúng
1. Mục thứ hai
1. Mục thứ ba
```
+
(Sẽ hiển thị như ví dụ trước đó)
Ta còn có thể sử dụng danh sách con
@@ -189,7 +192,7 @@ Ta còn có thể thêm dấu nhảy (hoặc thêm vào bốn dấu cách nữa)
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -201,12 +204,13 @@ John didn't even know what the `go_to()` function did!
Trong Markdown của GitHub, ta còn có thêm cách để hiển thị code:
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
The above text doesn't require indenting, plus GitHub will use syntax
highlighting of the language you specify after the \`\`\`
@@ -231,11 +235,13 @@ Một trong những thứ tốt nhất khi làm việc với Markdown là khả
```md
[Click me!](http://test.com/)
```
+
Ta còn có thể tạo tiêu đỠcho liên kết sử dụng cặp ngoặc nháy bên trong cặp ngoặc tròn
```md
[Click me!](http://test.com/ "Link to Test.com")
```
+
ÄÆ°á»ng dẫn tÆ°Æ¡ng đối cÅ©ng hoạt Ä‘á»™ng.
```md
@@ -244,19 +250,23 @@ Ta còn có thể tạo tiêu đỠcho liên kết sử dụng cặp ngoặc nh
Markdown còn hỗ trợ liên kết kiểu tham chiếu.
-<pre><code class="highlight">&#x5b;<span class="nv">Nhấn vào đây</span>][<span class="ss">link1</span>] để xem thêm!
-&#x5b;<span class="nv">Ngoài ra nhấn vào đây</span>][<span class="ss">foobar</span>] nếu bạn muốn xem qua.
+```md
+[Nhấn vào đây][link1] để xem thêm!
+[Ngoài ra nhấn vào đây][foobar] nếu bạn muốn xem qua.
-&#x5b;<span class="nv">link1</span>]: <span class="sx">http://test.com/</span> <span class="nn">"Tuyệt!"</span>
-&#x5b;<span class="nv">foobar</span>]: <span class="sx">http://foobar.biz/</span> <span class="nn">"Tốt!"</span></code></pre>
+[link1]: http://test.com/ "Tuyệt!"
+[foobar]: http://foobar.biz/ "Tốt!"
+```
Tiêu đỠcó thể được đóng trong dấu nháy hay ngoặc đơn, hoặc có thể được bỠqua. Tham chiếu có thể được đặt bất kì đâu trong văn bản và ID của tham chiếu có thể là bất kì gì miễn là nó độc nhất.
Ngoài ra còn có kiểu đặt tên ngầm cho phép ta sá»­ dụng Ä‘Æ°á»ng dẫn làm ID.
-<pre><code class="highlight">&#x5b;<span class="nv">This</span>][] is a link.
+```md
+[This][] is a link.
-&#x5b;<span class="nv">this</span>]: <span class="sx">http://thisisalink.com/</span></code></pre>
+[this]: http://thisisalink.com/
+```
Nhưng nó không được sử dụng rộng rãi.
@@ -270,9 +280,11 @@ Hiển thị ảnh tương tự như liên kết nhưng có thêm dấu chấm t
Và kiểu tham chiếu cũng hoạt động như vậy.
-<pre><code class="highlight">!&#x5b;<span class="nv">Äây là thuá»™c tính alt.</span>][<span class="ss">myimage</span>]
+```md
+![Äây là thuá»™c tính alt.][myimage]
-&#x5b;<span class="nv">myimage</span>]: <span class="sx">relative/urls/cool/image.jpg</span> <span class="nn">"Äây là tiêu Ä‘á»"</span></code></pre>
+[myimage]: relative/urls/cool/image.jpg "Äây là tiêu Ä‘á»"
+```
## Khác
@@ -303,6 +315,7 @@ Trong Markdown của Github, ta có thể sử dụng thẻ `<kbd>` để thay c
Máy treo? Thử bấm tổ hợp
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
```
+
### Bảng biểu
Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v và khá khó viết:
@@ -313,6 +326,7 @@ Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v
| Căn trái | Căn giữa | Căn phải |
| blah | blah | blah |
```
+
Hoặc có thể sử dụng kết quả dưới đây
```md
diff --git a/vi-vn/xml-vi.html.markdown b/vi-vn/xml-vi.html.markdown
new file mode 100644
index 00000000..7a74c154
--- /dev/null
+++ b/vi-vn/xml-vi.html.markdown
@@ -0,0 +1,170 @@
+---
+language: xml
+filename: learnxml.xml
+contributors:
+ - ['João Farias', 'https://github.com/JoaoGFarias']
+ - ['Rachel Stiyer', 'https://github.com/rstiyer']
+ - ['Deepanshu Utkarsh', 'https://github.com/duci9y']
+translators:
+ - ['Thanh Duy Phan', 'https://github.com/thanhpd']
+lang: vi-vn
+---
+
+XML là ngôn ngữ đánh dấu được thiết kế để lÆ°u trữ và truyá»n tải dữ liệu. Nó có thể được Ä‘á»c hiểu bởi cả ngÆ°á»i và máy.
+
+Không giống như HTML, XML không biểu đạt cách hiển thị hoặc định dạng dữ liệu, chỉ chứa dữ liệu mà thôi.
+
+Có những sự khác biệt rõ ràng giữa **nội dung** và **các đánh dấu**. Nói vắn tắt thì nội dung có thể là bất cứ gì trong khi các đánh dấu được định nghĩa trước.
+
+## Một số định nghĩa và giới thiệu
+
+Các XML Document (Văn bản XML) được cấu thành bởi các _elements (phần tá»­)_ và chúng có thể có các _attributes (thuá»™c tính)_ để mô tả, đồng thá»i cÅ©ng có thể chứa các ná»™i dung theo ngữ cảnh và má»™t hoặc nhiá»u phần tá»­ con. Tất cả XML document phải có má»™t phần tá»­ gốc đóng vai trò tổ tiên cho tất cả các phần tá»­ khác trong văn bản.
+
+Các trình phân tích cú pháp XML (XML Parser) được thiết kế để phân tích rất chặt chẽ, và sẽ dừng phân tích các văn bản không đúng định dạng. Vì vậy cần đảm bảo tất cả văn bản XML tuân theo [Các luật cú pháp XML](http://www.w3schools.com/xml/xml_syntax.asp).
+
+```xml
+<!-- Äây là má»™t bình luận. Nó không được phép chứa hai dấu gạch ngang (-) liên tiếp -->
+<!-- Comments can span
+ trải dài nhiá»u dòngmultiple lines -->
+
+<!-- Element - Phần tử -->
+<!-- Một element là thành phần XML cơ bản nhất. Có hai loại, thử nhất là rỗng nô -->
+<element1 thuoc-tinh="gia trialue" /> <Các element rỗng không chứa bất kì nội dung gìtent -->
+<!-- và không rỗng nội dung: -->
+<element2 thuoc-tinh="gia tri">Ná»™i dung</element2>
+<!-- Tên của element chỉ được phép chứa chữ cái và chữ số -->
+
+<empty /> <!-- Một element có thể là một element với tag rỗng… -->
+<!-- …không chứa bất cứ nội dung gì và chỉ là markup đơn thuần. -->
+
+<notempty> <!-- Hoặc nó chứa một tag bắt đầu… -->
+ <!-- …nội dung… -->
+</notempty> <!-- và kết thúc với tag đóng. -->
+
+<!-- Tên element phân biệt chữ hoa và thÆ°á»ng. -->
+<element />
+<!-- không giống như -->
+<eLEMENT />
+
+<!-- Attribute - Thuộc tính -->
+<!-- Một thuộc tính là một cặp key-value và tồn tại bên trong element. -->
+<element thuoctinh="giatri" thuoctinhkhac="giatrikhac" nhieugiatri="danhsach phanbiet bangdaucach" />
+<!-- Một thuộc tính chỉ xuất hiện một lần trong một element. Nó chỉ chứa một giá trị.
+ Một cách giải quyết là sử dụng danh sách giá trị được phân biệt bởi dấu cách. -->
+
+<!-- Nesting element - Phần tử lồng nhau -->
+<!-- Nội dung một element có thể chứa các element khác -->
+<cha>
+ <con>Text</con>
+ <elementrong />
+</cha>
+<!-- Danh pháp cây tiêu chuẩn được tuân theo. Má»—i phần tá»­ được gá»i là má»™t nút.
+ Phần tử cấp trên là cha, phần tử cấp dưới là con.
+ Các element trong cùng một element cha có mức tương đương nhau như anh chị em. -->
+
+<!-- XML bảo lưu dấu cách. -->
+<child>
+ Văn bản
+</child>
+<!-- sẽ không giống như -->
+<child>Văn bản</child>
+```
+
+## Một văn bản XML - XML document
+
+Äây là thứ làm cho XML rất linh hoạt do nó giúp con ngÆ°á»i cÅ©ng Ä‘á»c được. Văn bản sau đây cho ta biết nó định nghÄ©a má»™t hiệu sách bản ba quyển sách, trong đó có má»™t cuốn tên Learning XML bởi Erik T. Ray. Tất cả những việc này chÆ°a cần phải sá»­ dụng XML Parser.
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Äây là phần mở đầu, không bắt buá»™c cần nhÆ°ng nên có -->
+<hieusach>
+ <sach danhmuc="NAUAN">
+ <tieude lang="en">Everyday Italian</tieude>
+ <tacgia>Giada De Laurentiis</tacgia>
+ <nam>2005</nam>
+ <giaban>30.00</giaban>
+ </sach>
+ <sach danhmuc="TREEM">
+ <tieude lang="en">Harry Potter</tieude>
+ <tacgia>J K. Rowling</tacgia>
+ <nam>2005</nam>
+ <giaban>29.99</giaban>
+ </sach>
+ <sach danhmuc="WEB">
+ <tieude lang="en">Learning XML</tieude>
+ <tacgia>Erik T. Ray</tacgia>
+ <nam>2003</nam>
+ <giaban>39.95</giaban>
+ </sach>
+</hieusach>
+```
+
+## Tính đúng đắn và việc xác minh
+
+Má»™t văn bản XML là _đúng đắn (well-formed)_ nếu nó có cú pháp chính xác. Ty nhiên, ta có thể thêm nhiá»u ràng buá»™c vào văn bản, sá»­ dụng Document Type Definition (DTD) - Äịnh dạng loại văn bản. Má»™t văn bản mà các phần tá»­ và thuá»™c tính được khai báo trong má»™t DTÄ và tuân theo ngữ pháp được Ä‘Æ°a ra trong DTD đó được gá»i là _valid - được chấp nhận_ và tuân theo DTD bên cạnh việc đúng đắn.
+
+```xml
+<!-- Khai báo DTD lấy từ tệp bên ngoài: -->
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE hieusach SYSTEM "Hieusach.dtd">
+<!-- Khai báo hieusach là phần tá»­ gốc và 'Hieusach.dtd' là Ä‘Æ°á»ng dẫn
+ tới tệp DTD. -->
+<hieusach>
+ <sach danhmuc="NAUAN">
+ <tieude lang="en">Everyday Italian</tieude>
+ <tacgia>Giada De Laurentiis</tacgia>
+ <nam>2005</nam>
+ <giaban>30.00</giaban>
+ </sach>
+</hieusach>
+
+<!-- Tệp DTD: -->
+<!ELEMENT hieusach (sach+)>
+<!-- Element hieusach có thể chứa má»™t hoặc nhiá»u element sach. -->
+<!ELEMENT sach (tieude, giaban)>
+<!-- Mỗi sach cần có các element con tên tieude và giaban. -->
+<!ATTLIST sach danhmuc CDATA "Vanhoc">
+<!-- Mỗi sach cần có một thuộc tính danhmuc. Nếu không có, giá trị mặc định
+ sẽ là 'Vanhoc'. -->
+<!ELEMENT tieude (#PCDATA)>
+<!-- Element tieude chỉ được chứa nội dung dữ liệu kĩ tự được phân tích.
+Nói cách khác, nó có thể
+ chỉ chứa văn bản được phân tích bởi parser và không được phép chứa element con
+ So sánh với CDATA, hay dữ liệu kí tự -->
+<!ELEMENT giaban (#PCDATA)>
+]>
+
+<!-- DTD có thể được khai báo bên trong chính tệp XML.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE hieusach [
+<!ELEMENT hieusach (sach+)>
+<!ELEMENT sach (tieude, giaban)>
+<!ATTLIST sach danhmuc CDATA "Vanhoc">
+<!ELEMENT tieude (#PCDATA)>
+<!ELEMENT giaban (#PCDATA)>
+]>
+
+<hieusach>
+ <sach danhmuc="NAUAN">
+ <tieude lang="en">Everyday Italian</tieude>
+ <giaban>30.00</giaban>
+ </sach>
+</hieusach>
+```
+
+## DTD Compatibility and XML Schema Definitions (Tương thích DTD và định nghĩa XML Schema)
+
+Há»— trợ cho DTD khá nhiá»u do chúng đã quá cÅ©. Tuy nhiên, nhiá»u tính năng hiện đại của XML nhÆ° namespace không được há»— trợ bởi DTD. XML Schema Definition (XSD) - Äịnh nghÄ©a lược đồ XML được coi nhÆ° sẽ thay thế DTD để định nghÄ©a cấu trúc ngữ pháp của văn bản XML.
+
+## Tra cứu
+
+- [Validate your XML (Xác minh XML)](http://www.xmlvalidation.com)
+
+## Äá»c thêm
+
+- [Hướng dẫn XML Schema Definitions](http://www.w3schools.com/schema/)
+- [Hướng dẫn DTD](http://www.w3schools.com/xml/xml_dtd_intro.asp)
+- [Hướng dẫn XML](http://www.w3schools.com/xml/default.asp)
+- [Dùng XPath queries để phân tích cú pháp XML](http://www.w3schools.com/xml/xml_xpath.asp)
diff --git a/vim.html.markdown b/vim.html.markdown
index 00a44807..fb2fc81f 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: vim
contributors:
- ["RadhikaG", "https://github.com/RadhikaG"]
+ - ["kaymmm", "https://github.com/kaymmm"]
filename: LearnVim.txt
---
@@ -19,70 +20,71 @@ specific points in the file, and for fast editing.
## Basics of navigating Vim
```
- vim <filename> # Open <filename> in vim
- :help <topic> # Open up built-in help docs about <topic> if any exists
- :q # Quit vim
- :w # Save current file
- :wq # Save file and quit vim
- ZZ # Save file and quit vim
- :q! # Quit vim without saving file
- # ! *forces* :q to execute, hence quiting vim without saving
- ZQ # Quit vim without saving file
- :x # Save file and quit vim, shorter version of :wq
-
- u # Undo
- CTRL+R # Redo
-
- h # Move left one character
- j # Move down one line
- k # Move up one line
- l # Move right one character
-
- Ctrl+B # Move back one full screen
- Ctrl+F # Move forward one full screen
- Ctrl+D # Move forward 1/2 a screen
- Ctrl+U # Move back 1/2 a screen
+ vim <filename> # Open <filename> in vim
+ :help <topic> # Open up built-in help docs about <topic> if any exists
+ :q # Quit vim
+ :w # Save current file
+ :wq # Save file and quit vim
+ ZZ # Save file and quit vim
+ :q! # Quit vim without saving file
+ # ! *forces* :q to execute, hence quitting vim without saving
+ ZQ # Quit vim without saving file
+ :x # Save file(only when the file is modified) and quit vim
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # Move left one character
+ j # Move down one line
+ k # Move up one line
+ l # Move right one character
+
+ Ctrl+B # Move back one full screen
+ Ctrl+F # Move forward one full screen
+ Ctrl+D # Move forward 1/2 a screen
+ Ctrl+U # Move back 1/2 a screen
# Moving within the line
- 0 # Move to beginning of line
- $ # Move to end of line
- ^ # Move to first non-blank character in line
+ 0 # Move to beginning of line
+ $ # Move to end of line
+ ^ # Move to first non-blank character in line
# Searching in the text
- /word # Highlights all occurrences of word after cursor
- ?word # Highlights all occurrences of word before cursor
- n # Moves cursor to next occurrence of word after search
- N # Moves cursor to previous occerence of word
+ /word # Highlights all occurrences of word after cursor
+ ?word # Highlights all occurrences of word before cursor
+ n # Moves cursor to next occurrence of word after search
+ N # Moves cursor to previous occurrence of word
- :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file
- :s/foo/bar/g # Change 'foo' to 'bar' on the current line
- :%s/\n/\r/g # Replace new line characters with new line characters
+ :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file
+ :s/foo/bar/g # Change 'foo' to 'bar' on the current line
+ :%s/\n/\r/g # Replace new line characters with new line characters
+ :'<,'>s/foo/bar/g # Change 'foo' to 'bar on every line in the current visual selection
# Jumping to characters
- f<character> # Jump forward and land on <character>
- t<character> # Jump forward and land right before <character>
+ f<character> # Jump forward and land on <character>
+ t<character> # Jump forward and land right before <character>
# For example,
- f< # Jump forward and land on <
- t< # Jump forward and land right before <
+ f< # Jump forward and land on <
+ t< # Jump forward and land right before <
# Moving by word
- w # Move forward by one word
- b # Move back by one word
- e # Move to end of current word
+ w # Move forward by one word
+ b # Move back by one word
+ e # Move to end of current word
# Other characters for moving around
- gg # Go to the top of the file
- G # Go to the bottom of the file
- :NUM # Go to line number NUM (NUM is any number)
- H # Move to the top of the screen
- M # Move to the middle of the screen
- L # Move to the bottom of the screen
+ gg # Go to the top of the file
+ G # Go to the bottom of the file
+ :NUM # Go to line number NUM (NUM is any number)
+ H # Move to the top of the screen
+ M # Move to the middle of the screen
+ L # Move to the bottom of the screen
```
## Help docs:
@@ -104,28 +106,28 @@ Vim is based on the concept on **modes**.
- Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands
```
- i # Puts vim into insert mode, before the cursor position
- a # Puts vim into insert mode, after the cursor position
- v # Puts vim into visual mode
- : # Puts vim into ex mode
- <esc> # 'Escapes' from whichever mode you're in, into Command mode
+ i # Puts vim into insert mode, before the cursor position
+ a # Puts vim into insert mode, after the cursor position
+ v # Puts vim into visual mode
+ : # Puts vim into ex mode
+ <esc> # 'Escapes' from whichever mode you're in, into Command mode
# Copying and pasting text
- # Operations use the vim register by default
- # Think of it as vim's private clipboard
+ # Operations use the vim register by default
+ # Think of it as vim's private clipboard
- # Yank ~ copy text into vim register
- y # Yank whatever is selected
- yy # Yank the current line
+ # Yank ~ copy text into vim register
+ y # Yank whatever is selected
+ yy # Yank the current line
- # Delete ~ yank text and delete from file
- d # Delete whatever is selected
- dd # Delete the current line
+ # Delete ~ yank text and delete from file
+ d # Delete whatever is selected
+ dd # Delete the current line
- p # Paste text in vim register after the current cursor position
- P # Paste text in vim register before the current cursor position
+ p # Paste text in vim register after the current cursor position
+ P # Paste text in vim register before the current cursor position
- x # Delete character under current cursor position
+ x # Delete character under current cursor position
```
## The 'Grammar' of vim
@@ -142,64 +144,75 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
```
# 'Verbs'
- d # Delete
- c # Change
- y # Yank (copy)
- v # Visually select
+ d # Delete
+ c # Change
+ y # Yank (copy)
+ v # Visually select
# 'Modifiers'
- i # Inside
- a # Around
- NUM # Number (NUM is any number)
- f # Searches for something and lands on it
- t # Searches for something and stops before it
- / # Finds a string from cursor onwards
- ? # Finds a string before cursor
+ i # Inside
+ a # Around
+ NUM # Number (NUM is any number)
+ f # Searches for something and lands on it
+ t # Searches for something and stops before it
+ / # Finds a string from cursor onwards
+ ? # Finds a string before cursor
# 'Nouns'
- w # Word
- s # Sentence
- p # Paragraph
- b # Block
+ w # Word
+ s # Sentence
+ p # Paragraph
+ b # Block
# Sample 'sentences' or commands
- d2w # Delete 2 words
- cis # Change inside sentence
- yip # Yank inside paragraph (copy the para you're in)
- ct< # Change to open bracket
- # Change the text from where you are to the next open bracket
- d$ # Delete till end of line
+ d2w # Delete 2 words
+ cis # Change inside sentence
+ yip # Yank inside paragraph (copy the para you're in)
+ ct< # Change to open bracket
+ # Change the text from where you are to the next open bracket
+ d$ # Delete till end of line
```
## Some shortcuts and tricks
<!--TODO: Add more!-->
```
- > # Indent selection by one block
- < # Dedent selection by one block
- :earlier 15m # Reverts the document back to how it was 15 minutes ago
- :later 15m # Reverse above command
- ddp # Swap position of consecutive lines, dd then p
- . # Repeat previous action
- :w !sudo tee % # Save the current file as root
- :set syntax=c # Set syntax highlighting to 'c'
- :sort # Sort all lines
- :sort! # Sort all lines in reverse
- :sort u # Sort all lines and remove duplicates
- ~ # Toggle letter case of selected text
- u # Selected text to lower case
- U # Selected text to upper case
- J # Join the current line with the next line
+ > # Indent selection by one block
+ < # Dedent selection by one block
+ :earlier 15m # Reverts the document back to how it was 15 minutes ago
+ :later 15m # Reverse above command
+ ddp # Swap position of consecutive lines, dd then p
+ . # Repeat previous action
+ :w !sudo tee % # Save the current file as root
+ :set syntax=c # Set syntax highlighting to 'c'
+ :sort # Sort all lines
+ :sort! # Sort all lines in reverse
+ :sort u # Sort all lines and remove duplicates
+ ~ # Toggle letter case of selected text
+ u # Selected text to lower case
+ U # Selected text to upper case
+ J # Join the current line with the next line
# Fold text
- zf # Create fold from selected text
- zo # Open current fold
- zc # Close current fold
- zR # Open all folds
- zM # Close all folds
+ zf # Create fold from selected text
+ zd # Delete fold on the current line
+ zD # Recursively delete nested or visually selected folds
+ zE # Eliminate all folds in the window
+ zo # Open current fold
+ zO # Recursively open nested or visually selected folds
+ zc # Close current fold
+ zC # Recursively close nested or visually selected folds
+ zR # Open all folds
+ zM # Close all folds
+ za # Toggle open/close current fold
+ zA # Recursively toggle open/close nested fold
+ [z # Move to the start of the current fold
+ ]z # Move to the end of the current fold
+ zj # Move to the start of the next fold
+ zk # Move to the end of the previous fold
```
## Macros
@@ -210,9 +223,9 @@ you use, until you stop recording. On invoking a macro, it applies the exact
same sequence of actions and commands again on the text selection.
```
- qa # Start recording a macro named 'a'
- q # Stop recording
- @a # Play back the macro
+ qa # Start recording a macro named 'a'
+ q # Stop recording
+ @a # Play back the macro
```
### Configuring ~/.vimrc
diff --git a/vimscript.html.markdown b/vimscript.html.markdown
index c2934af8..04fee6fa 100644
--- a/vimscript.html.markdown
+++ b/vimscript.html.markdown
@@ -11,7 +11,7 @@ contributors:
" ##############
"
" Vim script (also called VimL) is the subset of Vim's ex-commands which
-" supplies a number of features one one would expect from a scripting language,
+" supplies a number of features one would expect from a scripting language,
" such as values, variables, functions or loops. Always keep in the back of
" your mind that a Vim script file is just a sequence of ex-commands. It is
" very common for a script to mix programming-language features and raw
@@ -38,11 +38,11 @@ echo 'Hello' | echo 'world!'
" Putting a comment after a command usually works
pwd " Displays the current working directory
-" Except for some commands it does not; use the command delemiter before the
+" Except for some commands it does not; use the command delimiter before the
" comment (echo assumes that the quotation mark begins a string)
echo 'Hello world!' | " Displays a message
-" Line breaks can be escaped by pacing a backslash as the first non-whitespace
+" Line breaks can be escaped by placing a backslash as the first non-whitespace
" character on the *following* line. Only works in script files, not on the
" command line
echo " Hello
@@ -98,7 +98,7 @@ echo v:false | " Evaluates to 0 or the string 'v:false'
" Boolean values can result from comparison of two objects.
echo x == y | " Equality by value
-echo x != y | " Unequality
+echo x != y | " Inequality
echo x > y | " Greater than
echo x >= y | " Greater than or equal
echo x < y | " Smaller than
@@ -110,7 +110,7 @@ echo x isnot y | " Instance non-identity (lists and dictionaries)
" echo 'a' < 'b'. Case sensitivity depends on the setting of 'ignorecase'
"
" Explicit case-sensitivity is specified by appending '#' (match case) or '?'
-" (ignore case) to the operator. Prefer explicity case sensitivity when writing
+" (ignore case) to the operator. Prefer explicitly case sensitivity when writing
" portable scripts.
echo 'a' < 'B' | " True or false depending on 'ignorecase'
@@ -315,7 +315,7 @@ let s:isNumber = {x -> type(x) == type(0)} | " Local: any name allowed
" Assign values of list to multiple variables (number of items must match)
let [x, y] = [1, 2]
-" Assign the remainer to a rest variable (note the semicolon)
+" Assign the remainder to a rest variable (note the semicolon)
let [mother, father; children] = ['Alice', 'Bob', 'Carol', 'Dennis', 'Emily']
@@ -610,7 +610,7 @@ echo exists(':Make') | " Command
echo exists("#CursorHold") | " Auto-command defined for event
echo exists("#BufReadPre#*.gz") | " Event and pattern
echo exists("#filetypeindent") | " Auto-command group
-echo exists("##ColorScheme") | " Auto-commnand supported for event
+echo exists("##ColorScheme") | " Auto-command supported for event
" Various dynamic values (see |expand()|)
echo expand('%') | " Current file name
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index a253af48..b79017dc 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -5,7 +5,7 @@ contributors:
filename: learnvisualbasic.vb
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/vyper.html.markdown b/vyper.html.markdown
index fec1a79f..bad0c31e 100644
--- a/vyper.html.markdown
+++ b/vyper.html.markdown
@@ -181,7 +181,7 @@ def _changeTaskStatus( \
_status: uint256, \
):
# backslashes (\) allow for multi-line code
- # Natspec comments are particularly helpful for documentation and readibility
+ # Natspec comments are particularly helpful for documentation and readability
# Natspec can be included using familiar Pythonic docstring syntax
"""
@notice
@@ -429,16 +429,16 @@ struct Struct:
owner: address
_balance: uint256 # balance is a reserved keyword, is a member for addresses
-exampleStuct: Struct
+exampleStruct: Struct
@public
def foo() -> uint256:
- self.exampleStuct = Struct({owner: msg.sender, _balance: 5})
- self.exampleStuct._balance = 10
- self.exampleStuct._balance = 5 # set to new value
- clear(self.exampleStuct._balance)
- clear(self.exampleStuct)
- return self.exampleStuct._balance
+ self.exampleStruct = Struct({owner: msg.sender, _balance: 5})
+ self.exampleStruct._balance = 10
+ self.exampleStruct._balance = 5 # set to new value
+ clear(self.exampleStruct._balance)
+ clear(self.exampleStruct)
+ return self.exampleStruct._balance
# Data locations: Memory vs. storage vs. calldata - all complex types (arrays,
@@ -510,7 +510,7 @@ def increment(x: uint256, y: uint256) -> (uint256, uint256):
y += 1
return (x, y)
-# Call previous functon
+# Call previous function
@public
@constant
def willCall() -> (uint256, uint256):
@@ -679,7 +679,7 @@ sha3(concat("ab", "cd")) # returns bytes32
# Step 1. Commit
# Place a commitment by sending output of `sha3()`
-sha3("a secret"); # btyes32 commit
+sha3("a secret"); # bytes32 commit
sha3(concat("secret", "other secret", "salt")); # commit multiple things
# The `sha3()` calculation should occur off-chain, only the bytes32
# output should be inputted into some `commit()` function
diff --git a/wolfram.html.markdown b/wolfram.html.markdown
index 5fddbc82..fa8ee078 100644
--- a/wolfram.html.markdown
+++ b/wolfram.html.markdown
@@ -14,7 +14,7 @@ Wolfram Language has several interfaces:
The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up.
-```
+```mathematica
(* This is a comment *)
(* In Mathematica instead of using these comments you can create a text cell
diff --git a/xml.html.markdown b/xml.html.markdown
index 2a258d94..630e4c90 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -165,7 +165,7 @@ Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XM
## Further Reading
-* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/)
+* [XML Schema Definitions Tutorial](https://www.w3schools.com/xml/schema_intro.asp)
* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp)
* [XML Tutorial](http://www.w3schools.com/xml/default.asp)
* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp)
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 6dc5905e..2bb35d42 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -2,8 +2,10 @@
language: yaml
filename: learnyaml.yaml
contributors:
+
- [Leigh Brenecki, 'https://leigh.net.au']
- [Suhas SG, 'https://github.com/jargnar']
+
---
YAML is a data serialisation language designed to be directly writable and
@@ -17,6 +19,7 @@ YAML doesn't allow literal tab characters for indentation.
--- # document start
# Comments in YAML look like this.
+# YAML supports single-line comments.
################
# SCALAR TYPES #
@@ -28,11 +31,24 @@ key: value
another_key: Another value goes here.
a_number_value: 100
scientific_notation: 1e+12
-# The number 1 will be interpreted as a number, not a boolean. if you want
-# it to be interpreted as a boolean, use true
+hex_notation: 0x123 # evaluates to 291
+octal_notation: 0123 # evaluates to 83
+
+# The number 1 will be interpreted as a number, not a boolean.
+# If you want it to be interpreted as a boolean, use true.
boolean: true
null_value: null
+another_null_value: ~
key with spaces: value
+
+# Yes and No (doesn't matter the case) will be evaluated to boolean
+# true and false values respectively.
+# To use the actual value use single or double quotes.
+no: no # evaluates to "no": false
+yes: No # evaluates to "yes": false
+not_enclosed: yes # evaluates to "not_enclosed": true
+enclosed: "yes" # evaluates to "enclosed": yes
+
# Notice that strings don't need to be quoted. However, they can be.
however: 'A string, enclosed in quotes.'
'Keys can be quoted too.': "Useful if you want to put a ':' in your key."
@@ -41,25 +57,49 @@ double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more."
# UTF-8/16/32 characters need to be encoded
Superscript two: \u00B2
-# Multiple-line strings can be written either as a 'literal block' (using |),
+# Special characters must be enclosed in single or double quotes
+special_characters: "[ John ] & { Jane } - <Doe>"
+
+# Multiple-line strings can be written either as a 'literal block' (using |),
# or a 'folded block' (using '>').
+# Literal block turn every newline within the string into a literal newline (\n).
+# Folded block removes newlines within the string.
literal_block: |
- This entire block of text will be the value of the 'literal_block' key,
- with line breaks being preserved.
+ This entire block of text will be the value of the 'literal_block' key,
+ with line breaks being preserved.
- The literal continues until de-dented, and the leading indentation is
- stripped.
+ The literal continues until de-dented, and the leading indentation is
+ stripped.
- Any lines that are 'more-indented' keep the rest of their indentation -
- these lines will be indented by 4 spaces.
+ Any lines that are 'more-indented' keep the rest of their indentation -
+ these lines will be indented by 4 spaces.
folded_style: >
- This entire block of text will be the value of 'folded_style', but this
- time, all newlines will be replaced with a single space.
+ This entire block of text will be the value of 'folded_style', but this
+ time, all newlines will be replaced with a single space.
- Blank lines, like above, are converted to a newline character.
+ Blank lines, like above, are converted to a newline character.
- 'More-indented' lines keep their newlines, too -
- this text will appear over two lines.
+ 'More-indented' lines keep their newlines, too -
+ this text will appear over two lines.
+
+# |- and >- removes the trailing blank lines (also called literal/block "strip")
+literal_strip: |-
+ This entire block of text will be the value of the 'literal_block' key,
+ with trailing blank line being stripped.
+block_strip: >-
+ This entire block of text will be the value of 'folded_style', but this
+ time, all newlines will be replaced with a single space and
+ trailing blank line being stripped.
+
+# |+ and >+ keeps trailing blank lines (also called literal/block "keep")
+literal_keep: |+
+ This entire block of text will be the value of the 'literal_block' key,
+ with trailing blank line being kept.
+
+block_keep: >+
+ This entire block of text will be the value of 'folded_style', but this
+ time, all newlines will be replaced with a single space and
+ trailing blank line being kept.
####################
# COLLECTION TYPES #
@@ -87,7 +127,7 @@ a_nested_map:
# An example
? - Manchester United
- Real Madrid
-: [2001-01-01, 2002-02-02]
+: [ 2001-01-01, 2002-02-02 ]
# Sequences (equivalent to lists or arrays) look like this
# (note that the '-' counts as indentation):
@@ -98,24 +138,26 @@ a_sequence:
- Item 4
- key: value
another_key: another_value
- -
- - This is a sequence
+ - - This is a sequence
- inside another sequence
- - - Nested sequence indicators
- can be collapsed
# Since YAML is a superset of JSON, you can also write JSON-style maps and
# sequences:
-json_map: {"key": "value"}
-json_seq: [3, 2, 1, "takeoff"]
-and quotes are optional: {key: [3, 2, 1, takeoff]}
+json_map: { "key": "value" }
+json_seq: [ 3, 2, 1, "takeoff" ]
+and quotes are optional: { key: [ 3, 2, 1, takeoff ] }
#######################
# EXTRA YAML FEATURES #
#######################
# YAML also has a handy feature called 'anchors', which let you easily duplicate
-# content across your document. Both of these keys will have the same value:
+# content across your document.
+# Anchors identified by & character which define the value.
+# Aliases identified by * character which acts as "see above" command.
+# Both of these keys will have the same value:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
@@ -123,28 +165,35 @@ other_anchor: *anchor_name
base: &base
name: Everyone has same name
-# The regexp << is called Merge Key Language-Independent Type. It is used to
+# The regexp << is called 'Merge Key Language-Independent Type'. It is used to
# indicate that all the keys of one or more specified maps should be inserted
# into the current map.
-
+# NOTE: If key already exists alias will not be merged
foo:
- <<: *base
+ <<: *base # doesn't merge the anchor
age: 10
-
+ name: John
bar:
- <<: *base
+ <<: *base # base anchor will be merged
age: 20
# foo and bar would also have name: Everyone has same name
# YAML also has tags, which you can use to explicitly declare types.
+# Syntax: !![typeName] [value]
+explicit_boolean: !!bool true
+explicit_integer: !!int 42
+explicit_float: !!float -42.24
explicit_string: !!str 0.5
+explicit_datetime: !!timestamp 2022-11-17 12:34:56.78 +9
+explicit_null: !!null null
+
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j
# We can also use yaml complex keys with language specific tags
-? !!python/tuple [5, 7]
+? !!python/tuple [ 5, 7 ]
: Fifty Seven
# Would be {(5, 7): 'Fifty Seven'} in Python
@@ -154,9 +203,10 @@ python_complex_number: !!python/complex 1+2j
# Strings and numbers aren't the only scalars that YAML can understand.
# ISO-formatted date and datetime literals are also parsed.
-datetime: 2001-12-15T02:59:43.1Z
-datetime_with_spaces: 2001-12-14 21:59:43.10 -5
-date: 2002-12-14
+datetime_canonical: 2001-12-15T02:59:43.1Z
+datetime_space_separated_with_time_zone: 2001-12-14 21:59:43.10 -5
+date_implicit: 2002-12-14
+date_explicit: !!timestamp 2002-12-14
# The !!binary tag indicates that a string is actually a base64-encoded
# representation of a binary blob.
@@ -171,7 +221,7 @@ set:
? item1
? item2
? item3
-or: {item1, item2, item3}
+or: { item1, item2, item3 }
# Sets are just maps with null values; the above is equivalent to:
set2:
@@ -186,3 +236,4 @@ set2:
+ [YAML official website](https://yaml.org/)
+ [Online YAML Validator](http://www.yamllint.com/)
++ [JSON ⇆ YAML](https://www.json2yaml.com/)
diff --git a/zfs.html.markdown b/zfs.html.markdown
index 6795b1fa..3f5a76b5 100644
--- a/zfs.html.markdown
+++ b/zfs.html.markdown
@@ -3,6 +3,7 @@ category: tool
tool: zfs
contributors:
- ["sarlalian", "http://github.com/sarlalian"]
+ - ["A1EF", "https://github.com/A1EF"]
filename: LearnZfs.txt
---
@@ -25,7 +26,6 @@ RAID setup with ZFS, as ZFS expects to directly manage the underlying disks.
Types of VDEV's
-* stripe (a single disk, no redundancy)
* mirror (n-way mirrors supported)
* raidz
* raidz1 (1-disk parity, similar to RAID 5)
@@ -71,7 +71,7 @@ List zpools
```bash
# Create a raidz zpool
-$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
# List ZPools
$ zpool list
@@ -160,22 +160,22 @@ Create datasets
```bash
# Create dataset
-$ zfs create tank/root/data
+$ zfs create zroot/root/data
$ mount | grep data
-tank/root/data on /data (zfs, local, nfsv4acls)
+zroot/root/data on /data (zfs, local, nfsv4acls)
# Create child dataset
-$ zfs create tank/root/data/stuff
+$ zfs create zroot/root/data/stuff
$ mount | grep data
-tank/root/data on /data (zfs, local, nfsv4acls)
-tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+zroot/root/data on /data (zfs, local, nfsv4acls)
+zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
# Create Volume
$ zfs create -V zroot/win_vm
$ zfs list zroot/win_vm
NAME USED AVAIL REFER MOUNTPOINT
-tank/win_vm 4.13G 17.9G 64K -
+zroot/win_vm 4.13G 17.9G 64K -
```
List datasets
@@ -213,28 +213,28 @@ zroot/var/tmp@daily-2015-10-15
Rename datasets
```bash
-$ zfs rename tank/root/home tank/root/old_home
-$ zfs rename tank/root/new_home tank/root/home
+$ zfs rename zroot/root/home zroot/root/old_home
+$ zfs rename zroot/root/new_home zroot/root/home
```
Delete dataset
```bash
# Datasets cannot be deleted if they have any snapshots
-$ zfs destroy tank/root/home
+$ zfs destroy zroot/root/home
```
Get / set properties of a dataset
```bash
# Get all properties
-$ zfs get all zroot/usr/home │157 # Create Volume
-NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm
-zroot/home type filesystem - │159 $ zfs list zroot/win_vm
-zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT
-zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K -
-zroot/home available 94.1G - │162 ```
-zroot/home referenced 11.9G - │163
+$ zfs get all zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home type filesystem -
+zroot/home creation Mon Oct 20 14:44 2014 -
+zroot/home used 11.9G -
+zroot/home available 94.1G -
+zroot/home referenced 11.9G -
zroot/home mounted yes -
...
@@ -244,7 +244,7 @@ NAME PROPERTY VALUE SOURCE
zroot/home compression off default
# Set property on dataset
-$ zfs set compression=gzip-9 mypool/lamb
+$ zfs set compression=lz4 zroot/lamb
# Get a set of properties from all datasets
$ zfs list -o name,quota,reservation
@@ -283,16 +283,16 @@ Create snapshots
```bash
# Create a snapshot of a single dataset
-zfs snapshot tank/home/sarlalian@now
+zfs snapshot zroot/home/sarlalian@now
# Create a snapshot of a dataset and its children
-$ zfs snapshot -r tank/home@now
+$ zfs snapshot -r zroot/home@now
$ zfs list -t snapshot
NAME USED AVAIL REFER MOUNTPOINT
-tank/home@now 0 - 26K -
-tank/home/sarlalian@now 0 - 259M -
-tank/home/alice@now 0 - 156M -
-tank/home/bob@now 0 - 156M -
+zroot/home@now 0 - 26K -
+zroot/home/sarlalian@now 0 - 259M -
+zroot/home/alice@now 0 - 156M -
+zroot/home/bob@now 0 - 156M -
...
```
@@ -300,10 +300,10 @@ Destroy snapshots
```bash
# How to destroy a snapshot
-$ zfs destroy tank/home/sarlalian@now
+$ zfs destroy zroot/home/sarlalian@now
# Delete a snapshot on a parent dataset and its children
-$ zfs destroy -r tank/home/sarlalian@now
+$ zfs destroy -r zroot/home/sarlalian@now
```
@@ -311,10 +311,10 @@ Renaming Snapshots
```bash
# Rename a snapshot
-$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today
-$ zfs rename tank/home/sarlalian@now today
+$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today
+$ zfs rename zroot/home/sarlalian@now today
-$ zfs rename -r tank/home@now @yesterday
+$ zfs rename -r zroot/home@now @yesterday
```
Accessing snapshots
@@ -328,26 +328,26 @@ Sending and Receiving
```bash
# Backup a snapshot to a file
-$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz
+$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz
# Send a snapshot to another dataset
-$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian
+$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian
# Send a snapshot to a remote host
-$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian'
+$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian'
# Send full dataset with snapshots to new host
-$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home'
+$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home'
```
Cloning Snapshots
```bash
# Clone a snapshot
-$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new
+$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new
# Promoting the clone so it is no longer dependent on the snapshot
-$ zfs promote tank/home/sarlalian_new
+$ zfs promote zroot/home/sarlalian_new
```
### Putting it all together
diff --git a/zh-cn/asciidoc-cn.html.markdown b/zh-cn/asciidoc-cn.html.markdown
index 74eed445..0709e8c1 100644
--- a/zh-cn/asciidoc-cn.html.markdown
+++ b/zh-cn/asciidoc-cn.html.markdown
@@ -1,6 +1,6 @@
---
language: asciidoc
-filename: asciidoc-cn.md
+filename: asciidoc-cn.adoc
contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
- ["Abel Salgado Romero", "https://twitter.com/abelsromero"]
diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown
index 8ee2db2c..02f1f7d5 100644
--- a/zh-cn/awk-cn.html.markdown
+++ b/zh-cn/awk-cn.html.markdown
@@ -179,7 +179,7 @@ function string_functions( localvar, arr) {
# 都是返回替æ¢çš„个数
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
- gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
+ gsub("e", ".", localvar) # localvar => "M..t m. at th. bar"
# æœç´¢åŒ¹é…正则的字符串
# index() 也是æœç´¢, ä¸æ”¯æŒæ­£åˆ™
diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown
index e0d6b6fe..a6a61949 100644
--- a/zh-cn/c++-cn.html.markdown
+++ b/zh-cn/c++-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: c++
+language: C++
filename: learncpp-cn.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index dbad5030..851f2981 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: c
+language: C
filename: learnc-cn.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
@@ -474,7 +474,7 @@ void testFunc() {
// 用户自定义类型和结构
///////////////////////////////////////
-// Typedefså¯ä»¥åˆ›å»ºç±»åž‹åˆ«å
+// typedef å¯ä»¥åˆ›å»ºç±»åž‹åˆ«å
typedef int my_type;
my_type my_type_var = 0;
diff --git a/zh-cn/clojure-cn.html.markdown b/zh-cn/clojure-cn.html.markdown
index fa241384..e98eac2a 100644
--- a/zh-cn/clojure-cn.html.markdown
+++ b/zh-cn/clojure-cn.html.markdown
@@ -362,7 +362,7 @@ Clojuredocs.org有大多数核心函数的文档,还带了示例哦:
[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core)
4Clojure是个很赞的用æ¥ç»ƒä¹ clojure/FP技能的地方:
-[http://www.4clojure.com/](http://www.4clojure.com/)
+[https://4clojure.oxal.org/](https://4clojure.oxal.org/)
Clojure-doc.org (你没看错)有很多入门级的文章:
[http://clojure-doc.org/](http://clojure-doc.org/)
diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macro-cn.html.markdown
index 23b2f203..85b966e9 100644
--- a/zh-cn/clojure-macro-cn.html.markdown
+++ b/zh-cn/clojure-macro-cn.html.markdown
@@ -131,7 +131,7 @@ lang: zh-cn
; 然而,如果我们希望它在编译期执行,就需è¦åˆ›å»ºå®
(defmacro inline-2 [form]
- (inline-2-helper form)))
+ (inline-2-helper form))
(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
diff --git a/zh-cn/cobol-cn.html.markdown b/zh-cn/cobol-cn.html.markdown
new file mode 100644
index 00000000..08eb36fb
--- /dev/null
+++ b/zh-cn/cobol-cn.html.markdown
@@ -0,0 +1,192 @@
+---
+language: COBOL
+filename: learn-cn.COB
+contributors:
+ - ["Hyphz", "http://github.com/hyphz/"]
+translators:
+ - ["GOLGO11", "https://github.com/GOLGO11/"]
+lang: zh-cn
+---
+COBOL是一门é¢å‘商业的语言,它从1960年最åˆè®¾è®¡ä»¥æ¥è¢«ä¿®è®¢è¿‡æ•°æ¬¡ã€‚它被宣称ä»ç„¶æœ‰è¶…过80%的机构在使用它。
+
+```cobol
+ *COBOL. 最好是按照它1985年的标准æ¥ç¼–程。
+ *用附带GnuCOBOL编译器的OpenCobolIDE 4.7.6æ¥ç¼–译。
+
+ *COBOL在è€ç‰ˆï¼ˆCOBOL-85)和新版(COBOL-2002以åŠCOBOL-2014)之间有明显的差别。
+ *è€ç‰ˆCOBOLè¦æ±‚ç¼–ç çš„å‰ä¸€åˆ°å…­åˆ—是空ç€çš„(它们被用æ¥å­˜å‚¨ç©¿å­”å¡ç‰‡çš„åºåˆ—å·...
+ *第七列的一个“*â€ç¬¦å·è¡¨ç¤ºæ³¨é‡Šçš„开始。
+ *在è€ç‰ˆCOBOL中,一æ¡ä»¥*开头的注释最长åªèƒ½å ä¸€è¡Œï¼Œ
+ *新版COBOLä¸éœ€è¦é¢å¤–的列æ¥è¡¥åºåˆ—å·ï¼Œå¹¶ä¸”用“*>" æ¥æ³¨é‡Šï¼Œå…许在行中开始注释
+ *è€ç‰ˆCOBOL也强加了对最大行长度的é™åˆ¶
+ *关键字在è€ç‰ˆCOBOL中必须大写,
+ *但在新版COBOL中ä¸åŒºåˆ†å¤§å°å†™
+ *虽然新版COBOLå…许你编写大å°å†™æ··åˆçš„代ç 
+ *但是在大多数情况下编写COBOL代ç æ—¶å…¨ç”¨å¤§å†™å­—符
+ *大多数专业的COBOLå¼€å‘者都是这么åšçš„。
+ *COBOL语å¥ä»¥å¥ç‚¹ç»“尾。
+
+ *COBOL代ç è¢«æ‹†æˆäº†å››ä¸ªéƒ¨ã€‚
+ *å„部按顺åºï¼Œå®ƒä»¬æ˜¯:
+ *IDENTIFICATION DIVSION.(标识部)
+ *ENVIRONMENT DIVISION.(环境部)
+ *DATA DIVISION.(数æ®éƒ¨ï¼‰
+ *PROCEDURE DIVISION.(过程部)
+
+ *第一步,我们必须给我们的程åºä¸€ä¸ªID。
+ *Identification division 也能包å«å…¶ä»–的值,
+ *但它们都åªæ˜¯ç¨‹åºçš„元数æ®ã€‚Program-id是唯一一个必须给出的值。
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARN.
+ AUTHOR. JOHN DOE.
+ DATE-WRITTEN. 05/02/2020.
+
+ *让我们æ¥å£°æ˜Žä¸€äº›å˜é‡ã€‚
+ *我们è¦åœ¨DATA DIVISIONçš„WORKING-STORAGE节æ¥å®Œæˆè¿™ä¸ªäº‹æƒ…。
+ *æ¯ä¸ªæ•°æ®é¡¹ï¼ˆåˆåå˜é‡ï¼‰ä»Žä¸€ä¸ªçº§åˆ«ç¼–å·å¼€å§‹ã€‚
+ *然åŽæ˜¯æ•°æ®é¡¹çš„å字,åŽè¾¹å†è·Ÿç€ä¸€ä¸ªpicture关键字,
+ *æ¥æ述这个å˜é‡å°†è¦åŒ…å«çš„æ•°æ®çš„类型。
+ *几乎所有的COBOLå¼€å‘者都会把PICTURE简写为PIC。
+ *A代表字æ¯ï¼ŒX代表字æ¯å’Œæ•°å­—,9代表数字。
+
+ *举例:
+ 01 MYNAME PIC xxxxxxxxxx. *> å个字符的字符串。
+
+ *但是é€ä¸ªæ•°é‚£äº›x会导致错误,
+ *所以以上代ç å¯ä»¥ï¼Œå¹¶ä¸”应该
+ *这样é‡å†™ï¼š
+ 01 MYNAME PIC X(10).
+
+ *这是几个更多的例å­ï¼š
+ 01 AGE PIC 9(3). *> 数字最多三ä½
+ 01 LAST_NAME PIC X(10). *> 字符串最多å个字符
+
+ *在COBOL里,一行中多个空格和一个空格的效果是一样的, 所以通常
+ *情况下都用多个空格排列代ç æ¥ä¾¿äºŽ
+ *其他的开å‘者阅读。
+ 01 inyear picture s9(7). *> S 使数字为正数.
+ *> 括å·é‡Œæ„æ€æ˜¯é‡å¤7次9,
+ *> å³å…­ä½æ•°å­—(ä¸æ˜¯æ•°ç»„)
+
+ *现在让我们æ¥å†™ä¸€ç‚¹å„¿ä»£ç ã€‚这是一个简å•çš„Hello World程åºã€‚
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLO.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 THE-MESSAGE PIC X(20).
+ PROCEDURE DIVSION.
+ DISPLAY "STARTING PROGRAM".
+ MOVE "HELLO WORLD" TO THE-MESSAGE.
+ DISPLAY THE-MESSAGE.
+ STOP RUN.
+
+ *以上的代ç ä¼šè¾“出:
+ *STARTING PROGRAM
+ *HELLO WORLD
+
+
+
+ ********用COBOLå¯ä»¥åšæ•°å­¦è¿ç®—***************
+ ADD 1 TO AGE GIVING NEW-AGE.
+ SUBTRACT 1 FROM COUNT.
+ DIVIDE VAR-1 INTO VAR-2 GIVING VAR-3.
+ COMPUTE TOTAL-COUNT = COUNT1 PLUS COUNT2.
+
+
+ *********PERFORM********************
+ *PERFORM关键字å…许你跳到代ç ä¸­å…¶ä»–特殊的代ç æ®µï¼Œ
+ *当这段特殊的代ç è¢«æ‰§è¡Œå®ŒåŽç»§ç»­å›žæ¥æ‰§è¡Œä¸‹é¢çš„å¯æ‰§è¡Œè¯­å¥ã€‚
+ *你必须把PERFORM这个è¯å†™å®Œæ•´ï¼Œä¸å¯ä»¥ç¼©å†™å®ƒã€‚
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. HELLOCOBOL.
+
+ PROCEDURE DIVISION.
+ FIRST-PARA.
+ DISPLAY 'THIS IS IN FIRST-PARA'.
+ PERFORM THIRD-PARA THRU FOURTH-PARA. *>跳过second-para,执行3rd&4th
+ *> 之åŽå½“thirdå’Œfourth执行完,
+ *> 回到这里继续往下执行直到é‡åˆ°STOP RUN.
+
+ SECOND-PARA.
+ DISPLAY 'THIS IS IN SECOND-PARA'.
+ STOP RUN.
+
+ THIRD-PARA.
+ DISPLAY 'THIS IS IN THIRD-PARA'.
+
+ FOURTH-PARA.
+ DISPLAY 'THIS IS IN FOURTH-PARA'.
+
+
+ *当你编译执行以上程åºæ—¶ï¼Œå®ƒä¼šç”Ÿæˆä»¥ä¸‹ç»“果:
+ THIS IS IN FIRST-PARA
+ THIS IS IN THIRD-PARA
+ THIS IS IN FOURTH-PARA
+ THIS IS IN SECOND-PARA
+
+
+ **********用STRING关键字把å˜é‡ç»„åˆåˆ°ä¸€èµ·************
+
+ *现在是时候学习两个类似的COBOL动è¯äº†ï¼šstringå’Œunstring。.
+
+ *string动è¯ç»å¸¸è¢«ç”¨æ¥è¿žæŽ¥ä¸¤ä¸ªæˆ–多个字符串(把它们拼在一起)。
+ *没什么特别的,Unstring被用æ¥æŠŠä¸€ä¸ªå­—符串拆分æˆä¸¤ä¸ªæˆ–多个更å°çš„字符串。
+ *当你在程åºä¸­ä½¿ç”¨string或unstringæ—¶ä¸è¦å¿˜è®°ä½¿ç”¨â€delimited by“,这个很é‡è¦ã€‚
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LEARNING.
+ ENVIRONMENT DIVISION.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 FULL-NAME PIC X(20).
+ 01 FIRST-NAME PIC X(13) VALUE "BOB GIBBERISH".
+ 01 LAST-NAME PIC X(5) VALUE "COBB".
+ PROCEDURE DIVISION.
+ STRING FIRST-NAME DELIMITED BY SPACE
+ " "
+ LAST-NAME DELIMITED BY SIZE
+ INTO FULL-NAME
+ END-STRING.
+ DISPLAY "THE FULL NAME IS: "FULL-NAME.
+ STOP RUN.
+
+
+ *以上代ç å°†ä¼šè¾“出:
+ THE FULL NAME IS: BOB COBB
+
+
+ *让我们æ¥çœ‹çœ‹ä¸ºä»€ä¹ˆæ˜¯è¿™æ ·ã€‚
+
+ *首先,我们在DATA DIVISION声明了所有的å˜é‡ï¼Œ
+ *包括我们想存储string命令生æˆçš„新字符串用到的的å˜é‡ã€‚
+
+ *这个æ“作过程在PROCEDURE DIVISION完æˆã€‚
+ *我们从STRING 关键字开始,到END-STRING结æŸã€‚
+ *在它们之间我们列出我们想è¦ç»„åˆå˜é‡å½¢æˆæ›´å¤§çš„主å˜é‡çš„过程。
+ *这里,我们组åˆäº†FIRST-NAME, 一个空格和LAST-NAME。
+
+ *跟在FIRST-NAMEå’ŒLAST-NAMEåŽé¢çš„DELIMITED BY短语告诉程åºæˆ‘们想è¦åœ¨å„自å˜é‡ä¸Šæˆªå–字符的规则。
+ *DELIMITED BY SPACE告诉程åºä»Žæœ€å¼€å§‹æˆªå–字符直到é‡åˆ°ä¸€ä¸ªç©ºæ ¼ã€‚
+ *DELIMITED BY SIZE告诉程åºæˆªå–字符的完整长度。
+ *我们在FIRST-NAMEåŽé¢ä½¿ç”¨DELIMITED BY SPACE,字符串中的GIBBERISH部分就被忽略了。
+
+ *为了更清楚,改å˜ä»£ç ä¸­çš„第10行如下:
+
+ STRING FIRST-NAME DELIMITED BY SIZE
+
+ *然åŽé‡æ–°æ‰§è¡Œç¨‹åº. 这次的输出å˜æˆ:
+
+ THE FULL NAME IS: BOB GIBBERISH COBB
+
+
+
+
+
+
+```
+
+## 想了解更多�
+
+* [GnuCOBOL](https://sourceforge.net/projects/open-cobol/)
+
diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown
index 971c1be9..b6cc70c0 100644
--- a/zh-cn/csharp-cn.html.markdown
+++ b/zh-cn/csharp-cn.html.markdown
@@ -1,49 +1,68 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
- ["Melvyn Laïly", "http://x2a.yt"]
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
+ - ["Wouter Van Schandevijl", "http://github.com/laoujin"]
+ - ["Jo Pearce", "http://github.com/jdpearce"]
+ - ["Chris Zimmerman", "https://github.com/chriszimmerman"]
+ - ["Shawn McGuire", "https://github.com/bigbash"]
translators:
- ["Jakukyo Friel", "http://weakish.github.io"]
+ - ["CatfishWen", "http://catfishwen.github.io"]
filename: LearnCSharp-cn.cs
lang: zh-cn
---
+C#是一ç§ä¼˜é›…且类型安全的é¢å‘对象的语言,使开å‘人员能够构建è¿è¡Œåœ¨è·¨å¹³å°çš„.NET框架上,安全且å¥å£®çš„应用程åºã€‚
-C#是一个优雅的ã€ç±»åž‹å®‰å…¨çš„é¢å‘对象语言。使用C#,开å‘者å¯ä»¥åœ¨.NET框架下构建安全ã€å¥å£®çš„应用程åºã€‚
-
-[更多关于C#的介ç»](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx)
+[更多关于C#的介ç»](https://learn.microsoft.com/zh-cn/dotnet/csharp/tour-of-csharp/)
```c#
// å•è¡Œæ³¨é‡Šä»¥ // 开始
/*
多行注释是这样的
*/
+
/// <summary>
-/// XML文档注释
+/// 这是 XML文档注释
+/// å¯ç”¨äºŽç”Ÿæˆå¤–部文档或在 IDE 中æ供上下文帮助
/// </summary>
+/// <param name="firstParam">这是 firstParam å‚数的文档</param>
+/// <returns>这是函数返回值的信æ¯</returns>
+public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { }
-// 声明应用用到的命å空间
+// 声明这段æºç ä½¿ç”¨åˆ°çš„命å空间
+// 下é¢çš„命å空间都是标准 .NET Framework 类库的一部分
using System;
using System.Collections.Generic;
-using System.Data.Entity;
using System.Dynamic;
using System.Linq;
-using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using System.IO;
-// 定义作用域,将代ç ç»„织æˆåŒ…
+// 但是这个并ä¸æ˜¯æ ‡å‡†ç±»åº“:
+using System.Data.Entity;
+// 为了在下方使用它,你需è¦æ·»åŠ ä¸€ä¸ª dll 引用
+// ä½ å¯ä»¥ä½¿ç”¨ NuGet 包管ç†å™¨è¿›è¡Œå®‰è£…
+// `Install-Package EntityFramework`
+
+// 命å空间 Namespaces å¯ç”¨äºŽå°†ä¸€å®šçš„代ç ç»„织为 “包†或者 “模å—â€
+// ä½ å¯ä»¥åœ¨å…¶ä»–文件中这样引用:using Learning.CSharp;
+
+// 在 C# 10 以åŽï¼Œä½ ä¹Ÿå¯ä»¥è¿™æ ·å®šä¹‰å‘½å空间。这被称为 file-scoped namespaces(文件范围的命å空间).
+// namespace Learning.CSharp;
+
namespace Learning
{
// æ¯ä¸ª .cs 文件至少需è¦åŒ…å«ä¸€ä¸ªå’Œæ–‡ä»¶å相åŒçš„ç±»
- // ä½ å¯ä»¥ä¸è¿™ä¹ˆå¹²ï¼Œä½†æ˜¯è¿™æ ·ä¸å¥½ã€‚
+ // ä½ å¯ä»¥ä¸è¿™ä¹ˆå¹²ï¼Œä½†æ˜¯è¿™æ ·å¹¶ä¸æŽ¨è。
public class LearnCSharp
{
- // 基本语法 - 如果你以å‰ç”¨è¿‡ Java 或 C++ çš„è¯ï¼Œå¯ä»¥ç›´æŽ¥è·³åˆ°åŽæ–‡ã€Œæœ‰è¶£çš„特性ã€
+ // 基本语法 - 如果你以å‰ç”¨è¿‡ Java 或 C++ çš„è¯ï¼Œå¯ä»¥ç›´æŽ¥è·³åˆ°åŽæ–‡ã€Œæœ‰è¶£çš„特性ã€
public static void Syntax()
{
// 使用 Console.WriteLine 打å°ä¿¡æ¯
@@ -53,7 +72,7 @@ namespace Learning
" Double: " + 3.14 +
" Boolean: " + true);
- // 使用 Console.Write 打å°ï¼Œä¸å¸¦æ¢è¡Œç¬¦å·
+ // 使用 Console.Write 打å°å°†ä¸ä¼šæ¢è¡Œ
Console.Write("Hello ");
Console.Write("World");
@@ -113,7 +132,7 @@ namespace Learning
char charFromString = fooString[1]; // => 'e'
// 字符串ä¸å¯ä¿®æ”¹: fooString[1] = 'X' 是行ä¸é€šçš„;
- // æ ¹æ®å½“å‰çš„locale设定比较字符串,大å°å†™ä¸æ•æ„Ÿ
+ // æ ¹æ®å½“å‰çš„区域格å¼è®¾ç½®æ¯”较字符串,大å°å†™ä¸æ•æ„Ÿ
string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
// 基于sprintf的字符串格å¼åŒ–
@@ -123,12 +142,13 @@ namespace Learning
DateTime fooDate = DateTime.Now;
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
- // 使用 @ 符å·å¯ä»¥åˆ›å»ºè·¨è¡Œçš„字符串。使用 "" æ¥è¡¨ç¤º "
+ // é€å­—字符串
+ // 使用 @ 符å·å¯ä»¥åˆ›å»ºè·¨è¡Œçš„字符串。使用 "" æ¥è¡¨ç¤º "
string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";
- // 使用const或read-only定义常é‡
- // 常é‡åœ¨ç¼–译期演算
+ // 使用 const 或 read-only 定义常é‡
+ // 常é‡åœ¨ç¼–译阶段演算
const int HOURS_I_WORK_PER_WEEK = 9001;
///////////////////////////////////////////////////
@@ -136,7 +156,7 @@ on a new line! ""Wow!"", the masses cried";
///////////////////////////////////////////////////
// 数组 - 从0开始计数
- // 声明数组时需è¦ç¡®å®šæ•°ç»„长度
+ // 声明数组时需è¦æŒ‡å®šæ•°ç»„长度
// 声明数组的格å¼å¦‚下:
// <datatype>[] <var name> = new <datatype>[<array size>];
int[] intArray = new int[10];
@@ -155,8 +175,8 @@ on a new line! ""Wow!"", the masses cried";
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
- List<int> z = new List<int> { 9000, 1000, 1337 }; // i
- // <>用于泛型 - å‚考下文
+ List<int> z = new List<int> { 9000, 1000, 1337 }; // åˆå§‹åŒ–
+ // <> 用于泛型 - å‚考下文
// 列表无默认值
// 访问列表元素时必须首先添加元素
@@ -164,18 +184,18 @@ on a new line! ""Wow!"", the masses cried";
Console.WriteLine("intList @ 0: " + intList[0]);
// 其他数æ®ç»“构:
- // 堆栈/队列
- // 字典 (哈希表的实现)
- // 哈希集åˆ
- // åªè¯»é›†åˆ
- // 元组 (.Net 4+)
+ // Stack 堆栈 / Queue 队列
+ // Dictionary 字典 (哈希表的实现)
+ // HashSet 哈希集åˆ
+ // Read-only Collections åªè¯»é›†åˆ
+ // Tuple 元组 (.Net 4+)
///////////////////////////////////////
// æ“作符
///////////////////////////////////////
Console.WriteLine("\n->Operators");
- int i1 = 1, i2 = 2; // 多é‡å£°æ˜Žçš„简写形å¼
+ int i1 = 1, i2 = 2; // 声明多个å˜é‡çš„简写形å¼
// 算术直截了当
Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
@@ -214,7 +234,7 @@ on a new line! ""Wow!"", the masses cried";
///////////////////////////////////////
Console.WriteLine("\n->Control Structures");
- // 类似Cçš„if语å¥
+ // 类似 C çš„ if 语å¥
int j = 10;
if (j == 10)
{
@@ -239,7 +259,7 @@ on a new line! ""Wow!"", the masses cried";
int fooWhile = 0;
while (fooWhile < 100)
{
- //迭代 100 次, fooWhile 0->99
+ // 迭代 100 次, fooWhile 0->99
fooWhile++;
}
@@ -247,14 +267,21 @@ on a new line! ""Wow!"", the masses cried";
int fooDoWhile = 0;
do
{
- //迭代 100 次, fooDoWhile 0->99
+ // 迭代 100 次, fooDoWhile 0->99
+ if (false)
+ continue; // 跳过本次迭代
+
fooDoWhile++;
+
+ if (fooDoWhile == 50)
+ break; // 结æŸæ•´ä¸ªå¾ªçŽ¯
+
} while (fooDoWhile < 100);
- //for 循环结构 => for(<åˆå§‹æ¡ä»¶>; <æ¡ä»¶>; <æ­¥>)
+ // for 循环结构 => for(<åˆå§‹æ¡ä»¶>; <æ¡ä»¶>; <æ­¥>)
for (int fooFor = 0; fooFor < 10; fooFor++)
{
- //迭代10次, fooFor 0->9
+ // 迭代10次, fooFor 0->9
}
// foreach循环
@@ -269,7 +296,7 @@ on a new line! ""Wow!"", the masses cried";
}
// Switch 语å¥
- // switch 适用于 byteã€shortã€charå’Œint æ•°æ®ç±»åž‹ã€‚
+ // switch 适用于 byteã€shortã€char å’Œ int æ•°æ®ç±»åž‹ã€‚
// åŒæ ·é€‚用于å¯æžšä¸¾çš„类型
// 包括字符串类, 以åŠä¸€äº›å°è£…了原始值的类:
// Characterã€Byteã€Shortå’ŒInteger。
@@ -307,46 +334,63 @@ on a new line! ""Wow!"", the masses cried";
// 转æ¢å­—符串为整数
// 转æ¢å¤±è´¥ä¼šæŠ›å‡ºå¼‚常
- int.Parse("123");//返回整数类型的"123"
+ int.Parse("123"); // 返回整数类型的"123"
- // TryParse会å°è¯•è½¬æ¢ç±»åž‹ï¼Œå¤±è´¥æ—¶ä¼šè¿”回缺çœç±»åž‹
+ // TryParse 会å°è¯•è½¬æ¢ç±»åž‹ï¼Œå¤±è´¥æ—¶ä¼šè¿”回缺çœç±»åž‹
// 例如 0
int tryInt;
if (int.TryParse("123", out tryInt)) // Funciton is boolean
Console.WriteLine(tryInt); // 123
// 转æ¢æ•´æ•°ä¸ºå­—符串
- // Convertç±»æ供了一系列便利转æ¢çš„方法
+ // Convert ç±»æ供了一系列方便转æ¢ç±»åž‹çš„方法
+
+ // 比如 字符串 与 int 之间
+
+ // 最佳方法
+ bool result = int.TryParse(string, out var integer)
+ int.Parse(string);
+
+ // ä¸æŽ¨è
Convert.ToString(123);
- // or
+
+ // Int 到字符串
tryInt.ToString();
+
+ // 转æ¢
+ // 显å¼è½¬æ¢ decimal 类型的 15 为 int 类型
+ // 然åŽéšå¼è½¬æ¢ä¸º long 类型
+ long x = (int) 15M;
}
///////////////////////////////////////
- // ç±»
+ // ç±» - 请å‚阅文件末尾的定义
///////////////////////////////////////
public static void Classes()
{
// å‚看文件尾部的对象声明
- // 使用newåˆå§‹åŒ–对象
+ // 使用 new åˆå§‹åŒ–对象
Bicycle trek = new Bicycle();
// 调用对象的方法
- trek.SpeedUp(3); // 你应该一直使用setter和getter方法
+ trek.SpeedUp(3); // 你应该一直使用 setter 和 getter 方法
trek.Cadence = 100;
// 查看对象的信æ¯.
Console.WriteLine("trek info: " + trek.Info());
- // 实例化一个新的Penny Farthing
+ // 实例化一个新的 Penny Farthing 对象
PennyFarthing funbike = new PennyFarthing(1, 10);
Console.WriteLine("funbike info: " + funbike.Info());
Console.Read();
} // 结æŸmain方法
- // ç»ˆç«¯ç¨‹åº ç»ˆç«¯ç¨‹åºå¿…须有一个main方法作为入å£
+ // record 在 C# 9 åŠä»¥åŽå¯ç”¨, 这基本上是类的语法糖. record 对象是ä¸å¯å˜çš„ immutable*.
+ public record ARecord(string Csharp);
+
+ // 终端程åºå…¥å£ 终端程åºå¿…须有一个 main 方法作为入å£
public static void Main(string[] args)
{
OtherInterestingFeatures();
@@ -359,11 +403,11 @@ on a new line! ""Wow!"", the masses cried";
// 默认方法签å
public // å¯è§æ€§
- static // å…许直接调用类,无需先创建实例
- int, //返回值
+ static // å…许从类直接调用,无需先创建实例
+ int // 返回值类型
MethodSignatures(
- int maxCount, // 第一个å˜é‡ï¼Œç±»åž‹ä¸ºæ•´åž‹
- int count = 0, // 如果没有传入值,则缺çœå€¼ä¸º0
+ int maxCount, // 第一个å‚数,类型为整型
+ int count = 0, // 如果没有传入值,则缺çœå€¼ä¸º 0
int another = 3,
params string[] otherParams // æ•èŽ·å…¶ä»–å‚æ•°
)
@@ -371,17 +415,22 @@ on a new line! ""Wow!"", the masses cried";
return -1;
}
- // 方法å¯ä»¥é‡å,åªè¦ç­¾åä¸ä¸€æ ·
- public static void MethodSignature(string maxCount)
+ // 方法å¯ä»¥é‡å,åªè¦æ–¹æ³•ç­¾åä¸ä¸€æ ·
+ // 一个åªæœ‰è¿”回值类型ä¸åŒçš„方法
+ public static void MethodSignatures(
+ ref int maxCount, // 通过引用传递
+ out int count)
{
+ // 通过 'count' å‚数传入的值将在该方法外ä¿ç•™å€¼ 15
+ count = 15; // 必须在离开方法之å‰ä¸º out å‚数赋值
}
- //泛型
- // TKey和TValue类由用用户调用函数时指定。
- // 以下函数模拟了Python的SetDefault
+ // 泛型
+ // TKey 和 TValue 由用户调用方法时指定
+ // 以下函数模拟了 Python 的 SetDefault
public static TValue SetDefault<TKey, TValue>(
- IDictionary<TKey, TValue> dictionary,
- TKey key,
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
TValue defaultItem)
{
TValue result;
@@ -393,55 +442,125 @@ on a new line! ""Wow!"", the masses cried";
// ä½ å¯ä»¥é™å®šä¼ å…¥å€¼çš„范围
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
{
- // 我们å¯ä»¥è¿›è¡Œè¿­ä»£ï¼Œå› ä¸ºT是å¯æžšä¸¾çš„
+ // 我们å¯ä»¥è¿›è¡Œè¿­ä»£ï¼Œå› ä¸º T 是å¯æžšä¸¾çš„
foreach (var item in toPrint)
- // ittm为整数
+ // item 为整数
Console.WriteLine(item.ToString());
}
+ // YIELD
+ // 使用 "yield" 关键字表明它出现的方法是一个迭代器 Iterator
+ // (è¿™æ„味ç€ä½ å¯ä»¥åœ¨ foreach 循环中使用它)
+ public static IEnumerable<int> YieldCounter(int limit = 10)
+ {
+ for (var i = 0; i < limit; i++)
+ yield return i;
+ }
+
+ // ä½ å¯ä»¥è¿™æ ·è°ƒç”¨å®ƒ
+ public static void PrintYieldCounterToConsole()
+ {
+ foreach (var counter in YieldCounter())
+ Console.WriteLine(counter);
+ }
+
+ // ä½ å¯ä»¥åœ¨ä¸€ä¸ªæ–¹æ³•ä¸­ä½¿ç”¨å¤šä¸ª "yield return"
+ public static IEnumerable<int> ManyYieldCounter()
+ {
+ yield return 0;
+ yield return 1;
+ yield return 2;
+ yield return 3;
+ }
+
+ // 你也å¯ä»¥ä½¿ç”¨ "yield break" åœæ­¢è¯¥è¿­ä»£å™¨
+ // 此方法åªä¼šè¿”回从 0 到 limit 的一åŠå€¼ã€‚
+ public static IEnumerable<int> YieldCounterWithBreak(int limit = 10)
+ {
+ for (var i = 0; i < limit; i++)
+ {
+ if (i > limit / 2) yield break;
+ yield return i;
+ }
+ }
+
public static void OtherInterestingFeatures()
{
- // å¯é€‰å‚æ•°
+ // å¯é€‰å‚æ•°
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
MethodSignatures(3, another: 3); // 显å¼æŒ‡å®šå‚数,忽略å¯é€‰å‚æ•°
+ // 使用 ref å’Œ out å‚æ•°
+ int maxCount = 0, count; // ref å‚数必须有值
+ MethodSignatures(ref maxCount, out count);
+
// 扩展方法
int i = 3;
- i.Print(); // å‚è§ä¸‹é¢çš„定义
+ i.Print(); // å‚è§ä¸‹é¢çš„定义
- // å¯ä¸ºnull的类型 对数æ®åº“交互ã€è¿”回值很有用
+ // å¯ä¸º null 的类型 对数æ®åº“交互ã€è¿”回值很有用
// 任何值类型 (i.e. ä¸ä¸ºç±») 添加åŽç¼€ ? åŽä¼šå˜ä¸ºå¯ä¸ºnull的值
// <类型>? <å˜é‡å> = <值>
int? nullable = null; // Nullable<int> 的简写形å¼
Console.WriteLine("Nullable variable: " + nullable);
bool hasValue = nullable.HasValue; // ä¸ä¸ºnull时返回真
+
// ?? 是用于指定默认值的语法糖
// 以防å˜é‡ä¸ºnull的情况
int notNullable = nullable ?? 0; // 0
+ // ?. 是å¦ä¸€ä¸ªå¯ç©ºç±»åž‹çš„æ“作符 - 简写 null 检查
+ nullable?.Print(); // 当å¯ç©ºç±»åž‹å€¼ä¸ä¸º null 的时候调用 Print() 拓展方法
+
// å˜é‡ç±»åž‹æŽ¨æ–­ - ä½ å¯ä»¥è®©ç¼–译器推断å˜é‡ç±»åž‹:
var magic = "编译器确定magic是一个字符串,所以ä»ç„¶æ˜¯ç±»åž‹å®‰å…¨çš„";
- // magic = 9; // ä¸å·¥ä½œï¼Œå› ä¸ºmagic是字符串,而ä¸æ˜¯æ•´æ•°ã€‚
+ // magic = 9; // ä¸å·¥ä½œï¼Œå› ä¸ºmagic是字符串,而ä¸æ˜¯æ•´æ•°ã€‚
// 泛型
//
- var phonebook = new Dictionary<string, string>() {
+ var phonebook = new Dictionary<string, string>() {
{"Sarah", "212 555 5555"} // 在电è¯ç°¿ä¸­åŠ å…¥æ–°æ¡ç›®
};
- // 调用上é¢å®šä¹‰ä¸ºæ³›åž‹çš„SETDEFAULT
- Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // 没有电è¯
- // ä½ ä¸ç”¨æŒ‡å®šTKeyã€TValue,因为它们会被éšå¼åœ°æŽ¨å¯¼å‡ºæ¥
+ // 调用上é¢å®šä¹‰ä¸ºæ³›åž‹çš„ SETDEFAULT
+ Console.WriteLine(SetDefault<string, string>(phonebook, "Shaun", "No Phone")); // No Phone
+ // ä½ ä¸ç”¨æŒ‡å®š TKeyã€TValue 的类型
+ // 因为它们会被éšå¼åœ°æŽ¨å¯¼å‡ºæ¥
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
// lambdaè¡¨è¾¾å¼ - å…许你用一行代ç æžå®šå‡½æ•°
Func<int, int> square = (x) => x * x; // 最åŽä¸€é¡¹ä¸ºè¿”回值
Console.WriteLine(square(3)); // 9
- // å¯æŠ›å¼ƒçš„资æºç®¡ç† - 让你很容易地处ç†æœªç®¡ç†çš„资æº
- // 大多数访问未管ç†èµ„æº (文件æ“作符ã€è®¾å¤‡ä¸Šä¸‹æ–‡, etc.)的对象
- // 都实现了IDisposable接å£ã€‚
- // using语å¥ä¼šä¸ºä½ æ¸…ç†IDisposable对象。
+ // é”™è¯¯å¤„ç† - 应对ä¸ç¡®å®šçš„世界
+ try
+ {
+ var funBike = PennyFarthing.CreateWithGears(6);
+
+ // å°†ä¸å†æ‰§è¡Œï¼Œå› ä¸º CreateWithGears 抛出异常
+ string some = "";
+ if (true) some = null;
+ some.ToLower(); // 抛出 NullReferenceException
+ }
+ catch (NotSupportedException)
+ {
+ Console.WriteLine("Not so much fun now!");
+ }
+ catch (Exception ex) // æ•èŽ·æ‰€æœ‰å…¶ä»–异常
+ {
+ throw new ApplicationException("It hit the fan", ex);
+ // throw; // é‡æ–°æŠ›å‡ºå¼‚常并ä¿ç•™è°ƒç”¨å †æ ˆ
+ }
+ // catch { } // æ•èŽ·æ‰€æœ‰æ²¡æœ‰æ•èŽ·çš„异常
+ finally
+ {
+ // 在 try 或 catch 之åŽæ‰§è¡Œ
+ }
+
+ // å¯æŠ›å¼ƒçš„资æºç®¡ç† - 让你很容易地处ç†æœªæ‰˜ç®¡çš„资æº
+ // å¤§å¤šæ•°è®¿é—®æœªæ‰˜ç®¡èµ„æº (文件å¥æŸ„ã€è®¾å¤‡ä¸Šä¸‹æ–‡, etc.) 的对象
+ // 都实现了 IDisposable 接å£ã€‚
+ // using语å¥ä¼šä¸ºä½ æ¸…ç† IDisposable 对象
using (StreamWriter writer = new StreamWriter("log.txt"))
{
writer.WriteLine("这里没有什么å¯ç–‘的东西");
@@ -450,29 +569,23 @@ on a new line! ""Wow!"", the masses cried";
}
// 并行框架
- // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
- var websites = new string[] {
- "http://www.google.com", "http://www.reddit.com",
- "http://www.shaunmccarthy.com"
- };
- var responses = new Dictionary<string, string>();
-
- // 为æ¯ä¸ªè¯·æ±‚新开一个线程
- // 在è¿è¡Œä¸‹ä¸€æ­¥å‰åˆå¹¶ç»“æžœ
- Parallel.ForEach(websites,
- new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
- website =>
- {
- // Do something that takes a long time on the file
- using (var r = WebRequest.Create(new Uri(website)).GetResponse())
+ // https://learn.microsoft.com/zh-cn/dotnet/standard/parallel-programming/data-parallelism-task-parallel-library
+
+ var words = new List<string> {"dog", "cat", "horse", "pony"};
+
+ Parallel.ForEach(words,
+ new ParallelOptions() { MaxDegreeOfParallelism = 4 },
+ word =>
{
- responses[website] = r.ContentType;
+ Console.WriteLine(word);
}
- });
+ );
- // 直到所有的请求完æˆåŽæ‰ä¼šè¿è¡Œä¸‹é¢çš„代ç 
- foreach (var key in responses.Keys)
- Console.WriteLine("{0}:{1}", key, responses[key]);
+ // è¿è¡Œå®ƒä¼šäº§ç”Ÿä¸åŒçš„输出
+ // 因为æ¯ä¸ªçº¿ç¨‹åœ¨ä¸åŒçš„时间完æˆ
+ // 一些å¯èƒ½çš„输出是:
+ // cat dog horse pony
+ // dog horse pony cat
// 动æ€å¯¹è±¡ï¼ˆé…åˆå…¶ä»–语言使用很方便)
dynamic student = new ExpandoObject();
@@ -486,10 +599,10 @@ on a new line! ""Wow!"", the masses cried";
// IQUERYABLE<T> - 几乎所有的集åˆéƒ½å®žçŽ°äº†å®ƒï¼Œ
// 带给你 Map / Filter / Reduce 风格的方法
var bikes = new List<Bicycle>();
- bikes.Sort(); // Sorts the array
+ bikes.Sort(); // æŽ’åº array
bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // æ ¹æ®è½¦è½®æ•°æŽ’åº
var result = bikes
- .Where(b => b.Wheels > 3) // 筛选 - å¯ä»¥è¿žé”使用 (返回IQueryable)
+ .Where(b => b.Wheels > 3) // 筛选 - å¯ä»¥è¿žé”使用 (返回 IQueryable)
.Where(b => b.IsBroken && b.HasTassles)
.Select(b => b.ToString()); // Map - 这里我们使用了select,所以结果是IQueryable<string>
@@ -502,19 +615,19 @@ on a new line! ""Wow!"", the masses cried";
Console.WriteLine(bikeSummary.Name);
// ASPARALLEL
- // 邪æ¶çš„特性 —— 组åˆäº†linq和并行æ“作
+ // 这就是事情开始棘手的地方 —— 组åˆäº† linq 和并行æ“作
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
// 以上代ç ä¼šå¹¶å‘地è¿è¡Œã€‚会自动新开线程,分别计算结果。
// 适用于多核ã€å¤§æ•°æ®é‡çš„场景。
- // LINQ - 将IQueryable<T>映射到存储,延缓执行
+ // LINQ - 映射一组 IQueryable<T> 对象,并延迟执行
// 例如 LinqToSql 映射数æ®åº“, LinqToXml 映射XML文档
var db = new BikeRespository();
- // 执行被延迟了,这对于查询数æ®åº“æ¥è¯´å¾ˆå¥½
+ // 执行被延迟了,这对于查询数æ®åº“æ¥è¯´éžå¸¸å¥½
var filter = db.Bikes.Where(b => b.HasTassles); // ä¸è¿è¡ŒæŸ¥è¯¢
if (42 > 6) // ä½ å¯ä»¥ä¸æ–­åœ°å¢žåŠ ç­›é€‰ï¼ŒåŒ…括有æ¡ä»¶çš„筛选,例如用于“高级æœç´¢â€åŠŸèƒ½
- filter = filter.Where(b => b.IsBroken); // ä¸è¿è¡ŒæŸ¥è¯¢
+ filter = filter.Where(b => b.IsBroken); // ä¸è¿è¡ŒæŸ¥è¯¢
var query = filter
.OrderBy(b => b.Wheels)
@@ -541,15 +654,64 @@ on a new line! ""Wow!"", the masses cried";
Console.WriteLine(obj.ToString());
}
}
+
+
+ // 委托 和 事件
+ public class DelegateTest
+ {
+ public static int count = 0;
+ public static int Increment()
+ {
+ // 增加 count 然åŽè¿”回它
+ return ++count;
+ }
+
+ // 委托是一个方法的引用.
+ // è¦å¼•ç”¨ Increment 方法,
+ // 首先声明一个具有相åŒç­¾å的委托,
+ // i.e. ä¸å¸¦å‚数并返回 int
+ public delegate int IncrementDelegate();
+
+ // 事件也å¯ç”¨äºŽè§¦å‘委托
+ // 使用委托类型创建事件
+ public static event IncrementDelegate MyEvent;
+
+ static void Main(string[] args)
+ {
+ // 通过实例化委托æ¥å¼•ç”¨ Increment 方法
+ // 并将方法本身作为å‚数传递
+ IncrementDelegate inc = new IncrementDelegate(Increment);
+ Console.WriteLine(inc()); // => 1
+
+ // 委托å¯ä»¥ç”¨ + è¿ç®—符组åˆ
+ IncrementDelegate composedInc = inc;
+ composedInc += inc;
+ composedInc += inc;
+
+ // composedInc 将执行 Increment 3 次
+ Console.WriteLine(composedInc()); // => 4
+
+
+ // 为事件订阅与委托
+ MyEvent += new IncrementDelegate(Increment);
+ MyEvent += new IncrementDelegate(Increment);
+
+ // 触å‘事件
+ // ie. è¿è¡Œè¿™ä¸ªäº‹ä»¶æ‰€æœ‰çš„委托订阅
+ Console.WriteLine(MyEvent()); // => 6
+ }
+ }
+
+
// 声明类的语法:
// <public/private/protected/internal> class <ç±»å>{
- // //æ•°æ®å­—段, 构造器, 内部函数.
- / // 在Java中函数被称为方法。
+ // // æ•°æ®å­—段, 构造器, 内部函数
+ // // 在Java中函数被称为方法
// }
public class Bicycle
{
- // 自行车的字段ã€å˜é‡
+ // 自行车的字段/å˜é‡
public int Cadence // Public: 任何地方都å¯ä»¥è®¿é—®
{
get // get - 定义获å–属性的方法
@@ -558,30 +720,35 @@ on a new line! ""Wow!"", the masses cried";
}
set // set - 定义设置属性的方法
{
- _cadence = value; // value是被传递给setter的值
+ _cadence = value; // value 是被传递给 setter 的值
}
}
private int _cadence;
- protected virtual int Gear // 类和å­ç±»å¯ä»¥è®¿é—®
+ protected virtual int Gear // Protected: 类和å­ç±»å¯ä»¥è®¿é—®
{
get; // 创建一个自动属性,无需æˆå‘˜å­—段
set;
}
- internal int Wheels // Internal:在åŒä¸€ç¨‹åºé›†å†…å¯ä»¥è®¿é—®
+ internal int Wheels // Internal: 在åŒä¸€ç¨‹åºé›†å†…å¯ä»¥è®¿é—®
{
get;
- private set; // å¯ä»¥ç»™get/set方法添加修饰符
+ private set; // å¯ä»¥ç»™ get/set 方法添加修饰符
}
- int _speed; // 默认为private: åªå¯ä»¥åœ¨è¿™ä¸ªç±»å†…访问,你也å¯ä»¥ä½¿ç”¨`private`关键è¯
+ int _speed; // 类中的任何内容默认为 private: åªå¯ä»¥åœ¨è¿™ä¸ªç±»å†…访问
+ // 你也å¯ä»¥ä½¿ç”¨ `private` 关键è¯æ˜¾å¼æŒ‡å®š
public string Name { get; set; }
- // enum类型包å«ä¸€ç»„常é‡
+ // 当您想è¦ä¸€ä¸ªä»…返回表达å¼ç»“果的åªè¯»å±žæ€§æ—¶ï¼Œ
+ // 属性还具有特殊的语法
+ public string LongName => Name + " " + _speed + " speed";
+
+ // enum 枚举是一ç§å€¼ç±»åž‹ï¼Œç”±ä¸€ç»„命å常é‡ç»„æˆ
// 它将å称映射到值(除éžç‰¹åˆ«è¯´æ˜Žï¼Œæ˜¯ä¸€ä¸ªæ•´åž‹ï¼‰
- // enmu元素的类型å¯ä»¥æ˜¯byteã€sbyteã€shortã€ushortã€intã€uintã€longã€ulong。
- // enumä¸èƒ½åŒ…å«ç›¸åŒçš„值。
+ // enmu 元素的类型å¯ä»¥æ˜¯ byteã€sbyteã€shortã€ushortã€intã€uintã€longã€ulong
+ // enum ä¸èƒ½åŒ…å«ç›¸åŒçš„值
public enum BikeBrand
{
AIST,
@@ -589,13 +756,32 @@ on a new line! ""Wow!"", the masses cried";
Electra = 42, //ä½ å¯ä»¥æ˜¾å¼åœ°èµ‹å€¼
Gitane // 43
}
- // 我们在Bicycle类中定义的这个类型,所以它是一个内嵌类型。
- // 这个类以外的代ç åº”当使用`Bicycle.Brand`æ¥å¼•ç”¨ã€‚
+ // 我们在 Bicycle 类中定义的这个类型,所以它是一个内嵌类型
+ // 这个类以外的代ç åº”当使用 `Bicycle.Brand` æ¥å¼•ç”¨
+
+ public BikeBrand Brand; // 声明一个 enum 类型之åŽï¼Œæˆ‘们å¯ä»¥å£°æ˜Žè¿™ä¸ªç±»åž‹çš„字段
+
+ // 使用 FlagsAttribute 定义枚举,表示有多个值å¯ä»¥è¢«åŒ¹é…
+ // 任何从 Attribute 派生的类都å¯ä»¥ç”¨æ¥ä¿®é¥°ç±»åž‹ã€æ–¹æ³•ã€å‚æ•°ç­‰
+ // ä½è¿ç®—符 & å’Œ | å¯ç”¨äºŽ å’Œ/或 æ“作
+
+ [Flags]
+ public enum BikeAccessories
+ {
+ None = 0,
+ Bell = 1,
+ MudGuards = 2, // 需è¦æ‰‹åŠ¨è®¾å®šå€¼!
+ Racks = 4,
+ Lights = 8,
+ FullPackage = Bell | MudGuards | Racks | Lights
+ }
- public BikeBrand Brand; // 声明一个enum类型之åŽï¼Œæˆ‘们å¯ä»¥å£°æ˜Žè¿™ä¸ªç±»åž‹çš„字段
+ // 用法: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell)
+ // 在 .NET 4 之å‰: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell
+ public BikeAccessories Accessories { get; set; }
- // é™æ€æ–¹æ³•çš„类型为自身,ä¸å±žäºŽç‰¹å®šçš„对象。
- // 你无需引用对象就å¯ä»¥è®¿é—®ä»–们。
+ // é™æ€æ–¹æ³•å±žäºŽç±»åž‹è‡ªèº«ï¼Œä¸å±žäºŽç‰¹å®šçš„对象
+ // 你无需通过对象就å¯ä»¥è®¿é—®ä»–们
// Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
static public int BicyclesCreated = 0;
@@ -607,7 +793,7 @@ on a new line! ""Wow!"", the masses cried";
// 下é¢æ˜¯ä¸€ä¸ªé»˜è®¤çš„构造器
public Bicycle()
{
- this.Gear = 1; // ä½ å¯ä»¥ä½¿ç”¨å…³é”®è¯this访问对象的æˆå‘˜
+ this.Gear = 1; // ä½ å¯ä»¥ä½¿ç”¨å…³é”®è¯ this 访问对象的æˆå‘˜
Cadence = 50; // ä¸è¿‡ä½ å¹¶ä¸æ€»æ˜¯éœ€è¦å®ƒ
_speed = 5;
Name = "Bontrager";
@@ -618,7 +804,7 @@ on a new line! ""Wow!"", the masses cried";
// å¦ä¸€ä¸ªæž„造器的例å­ï¼ˆåŒ…å«å‚数)
public Bicycle(int startCadence, int startSpeed, int startGear,
string name, bool hasCardsInSpokes, BikeBrand brand)
- : base() // 首先调用base
+ : base() // 显å¼è°ƒç”¨åŸºç±»çš„æ— å‚构造方法
{
Gear = startGear;
Cadence = startCadence;
@@ -637,8 +823,9 @@ on a new line! ""Wow!"", the masses cried";
// 函数语法
// <public/private/protected> <返回值> <函数å称>(<å‚æ•°>)
- // ç±»å¯ä»¥ä¸ºå­—段实现 getters å’Œ setters 方法 for their fields
- // 或者å¯ä»¥å®žçŽ°å±žæ€§ï¼ˆC#推è使用这个)
+ // ç±»å¯ä»¥ä¸ºå…¶å­—段实现 getters å’Œ setters 方法
+ // 或者å¯ä»¥ä½¿ç”¨å±žæ€§å°è£…字段(C#推è使用这个)
+
// 方法的å‚æ•°å¯ä»¥æœ‰é»˜è®¤å€¼
// 在有默认值的情况下,调用方法的时候å¯ä»¥çœç•¥ç›¸åº”çš„å‚æ•°
public void SpeedUp(int increment = 1)
@@ -652,8 +839,8 @@ on a new line! ""Wow!"", the masses cried";
}
// 属性å¯ä»¥è®¿é—®å’Œè®¾ç½®å€¼
- // 当åªéœ€è¦è®¿é—®æ•°æ®çš„时候,考虑使用属性。
- // 属性å¯ä»¥å®šä¹‰getå’Œset,或者是åŒæ—¶å®šä¹‰ä¸¤è€…
+ // 当åªéœ€è¦å¤–部访问数æ®çš„时候,考虑使用属性。
+ // 属性å¯ä»¥å®šä¹‰ get å’Œ set,或者是åŒæ—¶å®šä¹‰ä¸¤è€…
private bool _hasTassles; // private variable
public bool HasTassles // public accessor
{
@@ -663,7 +850,7 @@ on a new line! ""Wow!"", the masses cried";
// ä½ å¯ä»¥åœ¨ä¸€è¡Œä¹‹å†…定义自动属性
// 这个语法会自动创建åŽå¤‡å­—段
- // ä½ å¯ä»¥ç»™getter或setter设置访问修饰符
+ // ä½ å¯ä»¥ç»™ getter 或 setter 设置访问修饰符
// 以便é™åˆ¶å®ƒä»¬çš„访问
public bool IsBroken { get; private set; }
@@ -671,12 +858,29 @@ on a new line! ""Wow!"", the masses cried";
public int FrameSize
{
get;
- // ä½ å¯ä»¥ç»™get或set指定访问修饰符
- // 以下代ç æ„味ç€åªæœ‰Bicycleç±»å¯ä»¥è°ƒç”¨Framesizeçš„set
+ // ä½ å¯ä»¥ç»™ get 或 set 指定访问修饰符
+ // 以下代ç æ„味ç€åªæœ‰ Bicycle ç±»å¯ä»¥è°ƒç”¨ Framesize çš„ set
private set;
}
- //显示对象属性的方法
+ // 还å¯ä»¥åœ¨å¯¹è±¡ä¸Šå®šä¹‰è‡ªå®šä¹‰ç´¢å¼•å™¨
+ // 尽管这在本例中并ä¸å®Œå…¨æœ‰ç”¨, you
+ // ä½ å¯ä»¥ä½¿ç”¨ bicycle[0] 返回 "chris" æ¥èŽ·å¾—第一项
+ // 或者 bicycle[1] = "lisa" æ¥è®¾å®šå€¼
+ private string[] passengers = { "chris", "phil", "darren", "regina" };
+
+ public string this[int i]
+ {
+ get {
+ return passengers[i];
+ }
+
+ set {
+ passengers[i] = value;
+ }
+ }
+
+ // 显示对象属性的方法
public virtual string Info()
{
return "Gear: " + Gear +
@@ -698,7 +902,7 @@ on a new line! ""Wow!"", the masses cried";
} // Bicycle类结æŸ
- // PennyFarthing是Bicycle的一个å­ç±»
+ // PennyFarthing 是 Bicycle 的一个å­ç±»
class PennyFarthing : Bicycle
{
// (Penny Farthings是一ç§å‰è½®å¾ˆå¤§çš„自行车。没有齿轮。)
@@ -717,10 +921,17 @@ on a new line! ""Wow!"", the masses cried";
}
set
{
- throw new ArgumentException("ä½ ä¸å¯èƒ½åœ¨PennyFarthing上切æ¢é½¿è½®");
+ throw new ArgumentException("ä½ ä¸å¯èƒ½åœ¨ PennyFarthing 上切æ¢é½¿è½®");
}
}
+ public static PennyFarthing CreateWithGears(int gears)
+ {
+ var penny = new PennyFarthing(1, 1);
+ penny.Gear = gears; // ä½ ä¸èƒ½è¿™æ ·åš!
+ return penny;
+ }
+
public override string Info()
{
string result = "PennyFarthing bicycle ";
@@ -732,7 +943,7 @@ on a new line! ""Wow!"", the masses cried";
// 接å£åªåŒ…å«æˆå‘˜çš„ç­¾å,而没有实现。
interface IJumpable
{
- void Jump(int meters); // 所有接å£æˆå‘˜æ˜¯éšå¼åœ°å…¬å¼€çš„
+ void Jump(int meters); // 所有接å£æˆå‘˜æ˜¯éšå¼åœ°å…¬å¼€çš„ public
}
interface IBreakable
@@ -741,6 +952,8 @@ on a new line! ""Wow!"", the masses cried";
}
// ç±»åªèƒ½ç»§æ‰¿ä¸€ä¸ªç±»ï¼Œä½†æ˜¯å¯ä»¥å®žçŽ°ä»»æ„æ•°é‡çš„接å£
+ // 但是基类å称必须是列表中的第一个,所有接å£éƒ½åœ¨åŽé¢
+ class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
@@ -759,41 +972,374 @@ on a new line! ""Wow!"", the masses cried";
}
/// <summary>
- /// 连接数æ®åº“,一个 LinqToSql的示例。
+ /// 连接数æ®åº“,一个 LinqToSql 的示例。
/// EntityFramework Code First 很棒 (类似 Rubyçš„ ActiveRecord, ä¸è¿‡æ˜¯åŒå‘çš„)
- /// http://msdn.microsoft.com/en-us/data/jj193542.aspx
+ /// https://learn.microsoft.com/zh-cn/ef/ef6/modeling/code-first/workflows/new-database
/// </summary>
- public class BikeRespository : DbSet
+ public class BikeRepository : DbContext
{
- public BikeRespository()
+ public BikeRepository()
: base()
{
}
public DbSet<Bicycle> Bikes { get; set; }
}
+
+ // 一个类å¯ä»¥é€šè¿‡ partial 关键字分别写在多个 .cs 文件中
+ // A1.cs
+ public partial class A
+ {
+ public static void A1()
+ {
+ Console.WriteLine("Method A1 in class A");
+ }
+ }
+
+ // A2.cs
+ public partial class A
+ {
+ public static void A2()
+ {
+ Console.WriteLine("Method A2 in class A");
+ }
+ }
+
+ // 使用 partial 类 "A"
+ public class Program
+ {
+ static void Main()
+ {
+ A.A1();
+ A.A2();
+ }
+ }
+
+ // 通过在字符串å‰åŠ ä¸Š $ å‰ç¼€æ¥è¿›è¡Œå­—符串æ’值
+ // 并用 { å¤§æ‹¬å· } 包裹è¦æ’值的表达å¼
+ // 您还å¯ä»¥å°†æ’值字符串和é€å­—字符串与 $@ 组åˆèµ·æ¥
+ public class Rectangle
+ {
+ public int Length { get; set; }
+ public int Width { get; set; }
+ }
+
+ class Program
+ {
+ static void Main(string[] args)
+ {
+ Rectangle rect = new Rectangle { Length = 5, Width = 3 };
+ Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");
+
+ string username = "User";
+ Console.WriteLine($@"C:\Users\{username}\Desktop");
+ }
+ }
+
+ // C# 6 新特性
+ class GlassBall : IJumpable, IBreakable
+ {
+ // 自动属性设置åˆå§‹å€¼
+ public int Damage { get; private set; } = 0;
+
+ // 为仅有 getter 的自动属性设定åˆå§‹å€¼
+ public string Name { get; } = "Glass ball";
+
+ // 在构造函数中åˆå§‹åŒ–的仅有 getter 的自动属性
+ public string GenieName { get; }
+
+ public GlassBall(string genieName = null)
+ {
+ GenieName = genieName;
+ }
+
+ public void Jump(int meters)
+ {
+ if (meters < 0)
+ // æ–°çš„ nameof() 表达å¼; 编译器将检查标识符是å¦å­˜åœ¨
+ // nameof(x) == "x"
+ // 预防 例如 å‚æ•°å称已更改但错误消æ¯ä¸­æœªæ›´æ–°
+ throw new ArgumentException("Cannot jump negative amount!", nameof(meters));
+
+ Damage += meters;
+ }
+
+ // 表达å¼ä¸»ä½“ expression-bodied 属性 ...
+ public bool Broken
+ => Damage > 100;
+
+ // ... 刚å‘
+ public override string ToString()
+ // æ’值字符串
+ => $"{Name}. Damage taken: {Damage}";
+
+ public string SummonGenie()
+ // Null æ¡ä»¶è¿ç®—符
+ // x?.y 如果 x 为 null 将立å³è¿”回 null; y å°†ä¸ä¼šæ±‚值
+ => GenieName?.ToUpper();
+ }
+
+ static class MagicService
+ {
+ private static bool LogException(Exception ex)
+ {
+ // 记录æŸå¤„的异常
+ return false;
+ }
+
+ public static bool CastSpell(string spell)
+ {
+ try
+ {
+ // å‡è®¾æˆ‘们在这里调用 API
+ throw new MagicServiceException("Spell failed", 42);
+
+ // Spell succeeded
+ return true;
+ }
+ // 仅当 Code 为 42(Spell failed)时æ‰æ•èŽ·
+ catch(MagicServiceException ex) when (ex.Code == 42)
+ {
+ // Spell failed
+ return false;
+ }
+ // 其他异常,或 MagicServiceException çš„ Code ä¸æ˜¯ 42
+ catch(Exception ex) when (LogException(ex))
+ {
+ // 永远ä¸ä¼šæ‰§è¡Œåˆ°è¿™å—代ç 
+ // 堆栈未展开
+ }
+ return false;
+ // 请注æ„,æ•èŽ· MagicServiceException
+ // 并在 Code ä¸æ˜¯ 42 或 117 æ—¶é‡æ–°æŠ›å‡ºæ˜¯ä¸åŒçš„
+ // 因为最终的 catch-all å—å°†ä¸ä¼šæ•èŽ·é‡æ–°æŠ›å‡ºçš„异常
+ }
+ }
+
+ public class MagicServiceException : Exception
+ {
+ public int Code { get; }
+
+ public MagicServiceException(string message, int code) : base(message)
+ {
+ Code = code;
+ }
+ }
+
+ public static class PragmaWarning {
+ // 过时的属性
+ [Obsolete("Use NewMethod instead", false)]
+ public static void ObsoleteMethod()
+ {
+ // obsolete code
+ }
+
+ public static void NewMethod()
+ {
+ // new code
+ }
+
+ public static void Main()
+ {
+ ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替'
+#pragma warning disable CS0618
+ ObsoleteMethod(); // no warning
+#pragma warning restore CS0618
+ ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替'
+ }
+ }
} // ç»“æŸ Namespace
+
+using System;
+// C# 6, é™æ€å¼•ç”¨
+using static System.Math;
+
+namespace Learning.More.CSharp
+{
+ class StaticUsing
+ {
+ static void Main()
+ {
+ // ä¸ä½¿ç”¨é™æ€å¼•ç”¨æ—¶..
+ Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4));
+ // 使用时
+ Console.WriteLine("The square root of 4 is {}.", Sqrt(4));
+ }
+ }
+}
+
+// C# 7 新特性
+// 使用 Nuget 安装 Microsoft.Net.Compilers 最新版
+// 使用 Nuget 安装 System.ValueTuple 最新版
+using System;
+namespace Csharp7
+{
+ // 元组 TUPLES, æžæž„ DECONSTRUCTION å’Œ 弃元 DISCARDS
+ class TuplesTest
+ {
+ public (string, string) GetName()
+ {
+ // 元组中的字段默认命å为 Item1ã€Item2...
+ var names1 = ("Peter", "Parker");
+ Console.WriteLine(names1.Item2); // => Parker
+
+ // 字段å¯ä»¥æ˜¾å¼å‘½å
+ // 第 1 ç§å£°æ˜Ž
+ (string FirstName, string LastName) names2 = ("Peter", "Parker");
+
+ // 第 2 ç§å£°æ˜Ž
+ var names3 = (First:"Peter", Last:"Parker");
+
+ Console.WriteLine(names2.FirstName); // => Peter
+ Console.WriteLine(names3.Last); // => Parker
+
+ return names3;
+ }
+
+ public string GetLastName() {
+ var fullName = GetName();
+
+ // 元组å¯ä»¥è¢«æžæž„
+ (string firstName, string lastName) = fullName;
+
+ // æžæž„获得的字段å¯ä»¥ä½¿ç”¨ 弃元 _ 丢弃
+ var (_, last) = fullName;
+ return last;
+ }
+
+ // 通过指定æžæž„方法,
+ // å¯ä»¥ä»¥ç›¸åŒçš„æ–¹å¼è§£æž„任何类型
+ public int randomNumber = 4;
+ public int anotherRandomNumber = 10;
+
+ public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
+ {
+ randomNumber = this.randomNumber;
+ anotherRandomNumber = this.anotherRandomNumber;
+ }
+
+ static void Main(string[] args)
+ {
+ var tt = new TuplesTest();
+ (int num1, int num2) = tt;
+ Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10
+
+ Console.WriteLine(tt.GetLastName());
+ }
+ }
+
+ // 模å¼åŒ¹é…
+ class PatternMatchingTest
+ {
+ public static (string, int)? CreateLogMessage(object data)
+ {
+ switch(data)
+ {
+ // 使用 when 进行附加过滤
+ case System.Net.Http.HttpRequestException h when h.Message.Contains("404"):
+ return (h.Message, 404);
+ case System.Net.Http.HttpRequestException h when h.Message.Contains("400"):
+ return (h.Message, 400);
+ case Exception e:
+ return (e.Message, 500);
+ case string s:
+ return (s, s.Contains("Error") ? 500 : 200);
+ case null:
+ return null;
+ default:
+ return (data.ToString(), 500);
+ }
+ }
+ }
+
+ // Reference å˜é‡ / ref 局部å˜é‡
+ // å…许返回对象的引用而ä¸ä»…仅是其值
+ class RefLocalsTest
+ {
+ // 返回值å‰æ ‡æ˜Ž ref
+ public static ref string FindItem(string[] arr, string el)
+ {
+ for(int i=0; i<arr.Length; i++)
+ {
+ if(arr[i] == el) {
+ // 返回引用
+ return ref arr[i];
+ }
+ }
+ throw new Exception("Item not found");
+ }
+
+ public static void SomeMethod()
+ {
+ string[] arr = {"this", "is", "an", "array"};
+
+ // è¦åœ¨æ‰€æœ‰åœ°æ–¹ä½¿ç”¨ ref
+ ref string item = ref FindItem(arr, "array");
+ item = "apple";
+ Console.WriteLine(arr[3]); // => apple
+ }
+ }
+
+ // 本地函数 LOCAL FUNCTIONS
+ class LocalFunctionTest
+ {
+ private static int _id = 0;
+ public int id;
+ public LocalFunctionTest()
+ {
+ id = generateId();
+
+ // 这个本地函数åªèƒ½åœ¨æ­¤ä½œç”¨åŸŸä¸­è¢«è®¿é—®
+ int generateId()
+ {
+ return _id++;
+ }
+ }
+
+ public static void AnotherMethod()
+ {
+ var lf1 = new LocalFunctionTest();
+ var lf2 = new LocalFunctionTest();
+ Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1
+
+ int id = generateId();
+ // error CS0103: 当å‰ä¸Šä¸‹æ–‡ä¸­ä¸å­˜åœ¨å称“generateIdâ€
+ }
+ }
+}
+
```
## 没有涉åŠåˆ°çš„主题
+✨ æ–°çš„, 👠旧的, 🎈 长期支æŒçš„, 🔥 跨平å°çš„, 🎠åªæ”¯æŒWindowsçš„
+
+ * 特性 Attributes
+
+ * 异步编程
+
+ * Web å¼€å‘
+ * ASP.NET Core ✨
+
+ * æ¡Œé¢åº”ç”¨å¼€å‘ Development
+ * Windows Presentation Foundation (WPF) 👠🎈 ðŸŽ
+ * Universal Windows Platform (UWP) ✨ ðŸŽ
+ * Uno Platform 🔥 ✨
+ * WinForms 👠🎈 ðŸŽ
+ * Avalonia 🔥 ✨
+ * WinUI ✨ ðŸŽ
- * Flags
- * Attributes
- * é™æ€å±žæ€§
- * Exceptions, Abstraction
- * ASP.NET (Web Forms/MVC/WebMatrix)
- * Winforms
- * Windows Presentation Foundation (WPF)
+ * 跨平å°å¼€å‘
+ * Xamarin.Forms ðŸ‘
+ * MAUI ✨
## 扩展阅读
+ * [C# language reference](https://docs.microsoft.com/dotnet/csharp/language-reference/)
+ * [Learn .NET](https://dotnet.microsoft.com/learn)
+ * [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions)
* [DotNetPerls](http://www.dotnetperls.com)
* [C# in Depth](http://manning.com/skeet2)
- * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
- * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
- * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
- * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
- * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Programming C# 5.0](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
- * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)
+ * [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8)
diff --git a/zh-cn/docker-cn.html.markdown b/zh-cn/docker-cn.html.markdown
index f55e805a..ff793ae0 100644
--- a/zh-cn/docker-cn.html.markdown
+++ b/zh-cn/docker-cn.html.markdown
@@ -1,5 +1,6 @@
---
-language: docker
+category: tool
+tool: docker
lang: zh-cn
filename: docker-cn.bat
contributors:
diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown
index daee8d3c..0ed1d823 100644
--- a/zh-cn/elixir-cn.html.markdown
+++ b/zh-cn/elixir-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
translators:
diff --git a/zh-cn/fortran-cn.html.markdown b/zh-cn/fortran-cn.html.markdown
new file mode 100644
index 00000000..ab521e0a
--- /dev/null
+++ b/zh-cn/fortran-cn.html.markdown
@@ -0,0 +1,444 @@
+---
+language: Fortran
+filename: learnfortran-cn.f90
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+translators:
+ - ["Corvusnest", "https://github.com/Corvusnest"]
+lang: zh-cn
+---
+
+Fortran 是最å¤è€çš„计算机语言之一。它由 IBM å¼€å‘于 1950 年用于数值è¿ç®—(Fortran 为 "Formula
+Translation" 的缩写)。虽然该语言已年代久远,但目å‰ä»ç”¨äºŽé«˜æ€§èƒ½è®¡ç®—,如天气预报。
+该语言ä»åœ¨æŒç»­å‘展,并且基本ä¿æŒå‘下兼容。知å的版本为 Fortran 77, Fortran 90,
+Fortran 95, Fortran 2008, Fortran 2015 和 Fortran 2023。
+
+这篇概è¦å°†è®¨è®º Fortran 2008 的一些特å¾ã€‚因为它是目å‰æ‰€å¹¿æ³›é‡‡ç”¨çš„标准版本,并且与最新版本的内容
+也基本相åŒï¼ˆè€Œ Fortran 77 则是一个éžå¸¸ä¸åŒçš„版本)。
+
+```fortran
+! 这是一个注释
+
+program example ! 声明一个å为 example 的程åº
+
+ ! 代ç åªèƒ½å­˜åœ¨äºŽç¨‹åºã€å‡½æ•°ã€å­ç¨‹åºæˆ–模å—中
+ ! 使用缩进ä¸æ˜¯å¿…需的,但推è使用
+
+ ! 声明å˜é‡
+ ! =========
+
+ ! 所有的声明必须在语å¥å’Œè¡¨è¾¾å¼ä¹‹å‰
+
+ implicit none ! 防止动æ€å£°æ˜Žå˜é‡ï¼ˆæŽ¨èï¼ï¼‰
+ ! implicit none 推è在æ¯ä¸ªå‡½æ•°/程åº/模å—中é‡æ–°å£°æ˜Ž...
+
+ ! æ³¨æ„ - Fortran 中对大å°å†™ä¸æ•æ„Ÿ
+ real z
+ REAL Z2
+
+ real :: v, x ! 警告:默认的åˆå§‹å€¼å–决于编译器ï¼
+ real :: a = 3, b = 2E12, c = 0.01
+ integer :: i, j, k = 1, m
+ real, parameter :: PI = 3.1415926535897931 ! 声明一个常数
+ logical :: y = .TRUE., n = .FALSE. ! 布尔类型
+ complex :: w = (0, 1) ! å•ä½è™šæ•°
+ character(len=3) :: month ! 字符串,长度为 3 个字符
+
+ real :: array(6) ! å£°æ˜Žä¸€ä¸ªåŒ…å« 6 个实数的数组
+ real, dimension(4) :: arrayb ! å¦ä¸€ç§å£°æ˜Žæ•°ç»„çš„æ–¹å¼
+ integer :: arrayc(-10:10) ! 具有自定义索引的数组
+ real :: array2d(3, 2) ! 多维数组
+
+ ! 这些分隔符 '::' 并ä¸æ€»æ˜¯å¿…需的,但推è使用
+
+ ! 还有许多其他的å˜é‡å±žæ€§ï¼š
+ real, pointer :: p ! 声明一个指针
+
+ integer, parameter :: LP = selected_real_kind(20)
+ real(kind=LP) :: d ! 长精度å˜é‡
+
+ ! 警告:在声明过程中åˆå§‹åŒ–å˜é‡ä¼šåœ¨å‡½æ•°ä¸­é€ æˆé—®é¢˜ï¼Œ
+ ! 因为这会自动暗示 'save' 属性,
+ ! 在函数调用之间ä¿å­˜å˜é‡çš„值一般情况下,
+ ! 除了常é‡å¤–,声明和åˆå§‹åŒ–的代ç åº”该分开ï¼
+
+ ! 字符串
+ ! =======
+
+ character :: a_char = 'i'
+ character(len=6) :: a_str = "qwerty"
+ character(len=30) :: str_b
+ character(len=*), parameter :: a_long_str = "This is a long string."
+ ! 使用 (len=*) å¯ä»¥è‡ªåŠ¨è®¡ç®—长度,但åªé€‚用于常é‡
+
+ str_b = a_str//" keyboard" ! 使用 // è¿ç®—符连接字符串
+
+ ! 赋值和算术
+ ! =============
+
+ Z = 1 ! 对上é¢å£°æ˜Žçš„å˜é‡ z 进行赋值(对大å°å†™ä¸æ•æ„Ÿï¼‰
+ j = 10 + 2 - 3
+ a = 11.54/(2.3*3.1)
+ b = 2**3 ! 幂è¿ç®—
+
+ ! æµç¨‹æŽ§åˆ¶è¯­å¥å’Œæ“作符
+ ! ===================
+
+ ! å•è¡Œ if 语å¥
+ if (z == a) b = 4 ! æ¡ä»¶å§‹ç»ˆéœ€è¦åœ¨æ‹¬å·ä¸­
+
+ if (z /= a) then ! z ä¸ç­‰äºŽ a
+ ! 其他的比较æ“作符包括 < > <= >= == /=
+ b = 4
+ else if (z .GT. a) then ! z 大于 a
+ ! 文本等价于符å·æ“作符中的 .LT. .GT. .LE. .GE. .EQ. .NE.
+ b = 6
+ else if (z < a) then ! 'then' 必须在本行上
+ b = 5 ! 执行å—必须在新的一行上
+ else
+ b = 10
+ end if ! end 语å¥åŽéœ€è¦ 'if'(或å¯ä»¥ä½¿ç”¨ 'endif')
+
+ if (.NOT. (x < c .AND. v >= a .OR. z == z)) then ! 布尔è¿ç®—符
+ inner: if (.TRUE.) then ! å¯ä»¥å¯¹ if 结构命å
+ b = 1
+ end if inner ! then 必须命å对应的 endif 语å¥
+ end if
+
+ i = 20
+ select case (i)
+ case (0, 1) ! 当 i == 0 或 i == 1 时
+ j = 0
+ case (2:10) ! 当 i 在 2 到 10 之间(包括边界)时
+ j = 1
+ case (11:) ! 当 i >= 11 时
+ j = 2
+ case default
+ j = 3
+ end select
+
+ month = 'jan'
+ ! æ¡ä»¶å¯ä»¥æ˜¯æ•´æ•°ã€é€»è¾‘ã€æˆ–字符类型
+ ! Select 结构也å¯ä»¥å‘½å
+ monthly:select case(month)
+ case ("jan")
+ j = 0
+ case default
+ j = -1
+ end select monthly
+
+ do i = 2, 10, 2 ! 循环从 2 到 10(包括)以 2 为步长
+ innerloop: do j = 1, 3 ! 循环也å¯ä»¥å‘½å
+ exit ! 退出循环
+ end do innerloop
+ cycle ! 跳到下一个循环迭代
+ end do
+
+ ! 虽然存在 Goto 语å¥ï¼Œä½†å®ƒè¢«å¼ºçƒˆä¸æŽ¨è
+ goto 10
+ stop 1 ! ç«‹å³åœæ­¢ä»£ç ï¼ˆå¹¶è¿”回指定的æ¡ä»¶ä»£ç ï¼‰
+10 j = 201 ! 这一行被标记为 10 行
+
+ ! 数组
+ ! =====
+ array = (/1, 2, 3, 4, 5, 6/)
+ array = [1, 2, 3, 4, 5, 6] ! 使用 Fortran 2003 的表示法
+ arrayb = [10.2, 3e3, 0.41, 4e-5]
+ array2d = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [3, 2])
+
+ ! Fortran 数组索引从 1 开始
+ ! (默认情况下,但对于特定数组å¯ä»¥å®šä¹‰ä¸åŒçš„索引)
+ v = array(1) ! å–数组的第一个元素
+ v = array2d(2, 2)
+
+ print *, array(3:5) ! 打å°ä»Žç¬¬ä¸‰ä¸ªåˆ°ç¬¬äº”个元素(包括)
+ print *, array2d(1, :) ! 打å°äºŒç»´æ•°ç»„的第一列
+
+ array = array*3 + 2 ! å¯ä»¥å¯¹æ•°ç»„应用数学表达å¼
+ array = array*array ! 数组æ“作是é€å…ƒç´ è¿›è¡Œçš„
+ ! array = array*array2d ! 这两个数组是ä¸å…¼å®¹çš„
+
+ ! 有许多内置函数å¯ç”¨äºŽæ•°ç»„
+ c = dot_product(array, array) ! 这是点积
+ ! 使用 matmul() 进行矩阵è¿ç®—
+ c = sum(array)
+ c = maxval(array)
+ print *, minloc(array)
+ c = size(array)
+ print *, shape(array)
+ m = count(array > 0)
+
+ ! 循环数组(通常使用 product() 函数)
+ v = 1
+ do i = 1, size(array)
+ v = v*array(i)
+ end do
+
+ ! æ¡ä»¶æ€§åœ°æ‰§è¡Œé€å…ƒç´ èµ‹å€¼
+ array = [1, 2, 3, 4, 5, 6]
+ where (array > 3)
+ array = array + 1
+ elsewhere(array == 2)
+ array = 1
+ elsewhere
+ array = 0
+ end where
+
+ ! éšå« do 循环是创建数组的紧凑方å¼
+ array = [(i, i=1, 6)] ! 创建一个数组 [1,2,3,4,5,6]
+ array = [(i, i=1, 12, 2)] ! 创建一个数组 [1,3,5,7,9,11]
+ array = [(i**2, i=1, 6)] ! 创建一个数组 [1,4,9,16,25,36]
+ array = [(4, 5, i=1, 3)] ! 创建一个数组 [4,5,4,5,4,5]
+
+ ! 输入/输出
+ ! =========
+
+ print *, b ! å°†å˜é‡ 'b' 打å°åˆ°å‘½ä»¤è¡Œ
+
+ ! å¯ä»¥å¯¹æ‰“å°çš„输出进行格å¼åŒ–
+ print "(I6)", 320 ! æ‰“å° ' 320'
+ print "(I6.4)", 3 ! æ‰“å° ' 0003'
+ print "(F6.3)", 4.32 ! æ‰“å° ' 4.320'
+
+ ! å­—æ¯è¡¨ç¤ºé¢„期的类型,åŽé¢çš„数字表示用于打å°å€¼çš„字符数
+ ! å­—æ¯å¯ä»¥æ˜¯ I(整数),F(实数),E(工程表示法),
+ ! L(逻辑),A(字符串)...
+ print "(I3)", 3200 ! æ‰“å° '***',因为该数字ä¸é€‚åˆ
+
+ ! å¯ä»¥æœ‰å¤šä¸ªæ ¼å¼è§„范
+ print "(I5,F6.2,E6.2)", 120, 43.41, 43.41
+ print "(3I5)", 10, 20, 30 ! 整数的三次é‡å¤ï¼ˆå­—段宽度为 5)
+ print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 ! æ ¼å¼é‡å¤ç»„åˆ
+
+ ! 我们还å¯ä»¥ä»Žç»ˆç«¯è¯»å–输入
+ read (*, *) v
+ read (*, "(2F6.2)") v, x ! 读å–两个数字
+
+ ! 写入文件
+ open (unit=12, file="records.txt", status="replace")
+ ! 文件通过 'unit number' 引用,这个数字å¯ä»¥åœ¨ 9:99 范围内选择
+ ! Status å¯ä»¥æ˜¯ {'old','replace','new'} 中的一个
+ write (12, "(F10.2,F10.2,F10.2)") c, b, a
+ close (12)
+
+ ! 读å–文件
+ open (newunit=m, file="records.txt", status="old")
+ ! 文件通过 'new unit number' 引用,编译器为您选择一个整数
+ read (unit=m, fmt="(3F10.2)") a, b, c
+ close (m)
+
+ ! 还有更多功能å¯ç”¨ï¼Œè¶…出了本文所讨论的范围,
+ ! 还有由于与旧版本的 Fortran çš„å‘åŽå…¼å®¹æ€§è€Œå­˜åœ¨çš„替代方案
+
+ ! 内置函数
+ ! ===========
+
+ ! Fortran 大约有 200 个语言内部的函数/å­ç¨‹åº
+ ! 例如 -
+ call cpu_time(v) ! å°† 'v' 设置为以秒为å•ä½çš„时间
+ k = ior(i, j) ! ä¸¤ä¸ªæ•´æ•°çš„ä½ OR è¿ç®—
+ v = log10(x) ! 以 10 为底的对数
+ i = floor(b) ! 返回å°äºŽæˆ–等于 x 的最接近的整数
+ v = aimag(w) ! å¤æ•°çš„虚部
+
+ ! 函数和å­ç¨‹åº
+ ! ==============
+
+ ! å­ç¨‹åºè¿è¡Œä¸€äº›ä»£ç ï¼Œå¹¶å¯ä»¥å¯¹è¾“入值产生副作用或修改输入值
+
+ call routine(a, c, v) ! å­ç¨‹åºè°ƒç”¨
+
+ ! 函数采用一系列输入å‚数,并返回一个å•ä¸ªå€¼
+ ! ä¸è¿‡ï¼Œè¾“å…¥å‚æ•°å¯èƒ½ä»ä¼šè¢«ä¿®æ”¹ï¼Œå¹¶ä¸”会执行副作用
+
+ m = func(3, 2, k) ! 函数调用
+
+ ! 函数调用还å¯ä»¥åœ¨è¡¨è¾¾å¼ä¸­ä½¿ç”¨
+ print *, func2(3, 2, k)
+
+ ! 一个纯函数是一个ä¸ä¿®æ”¹å…¶è¾“å…¥å‚数,
+ ! 也ä¸ä¼šå¼•èµ·ä»»ä½•å‰¯ä½œç”¨çš„函数
+ m = func3(3, 2, k)
+
+contains ! 包å«ç¨‹åºå†…部定义的å­ç¨‹åºçš„区域
+
+ ! Fortran 有几ç§ç¨å¾®ä¸åŒçš„æ–¹å¼æ¥å®šä¹‰å‡½æ•°
+
+ integer function func(a, b, c) ! 函数返回一个整数值
+ ! implicit none ! å­å˜é‡åŸŸå¯ä»¥ä¸å†å£°æ˜Ž implicit none
+ integer, intent(in) :: a, b, c ! 在函数内部定义输入å‚数的类型
+
+ if (a >= 2) then
+ func = a + b + c ! 返回å˜é‡é»˜è®¤ä¸ºå‡½æ•°å
+ return ! éšæ—¶å¯ä»¥ä»Žå‡½æ•°è¿”回当å‰å€¼
+ end if
+ func = a + c
+
+ ! 在函数的末尾ä¸éœ€è¦ return 语å¥
+ end function func
+
+ function func2(a, b, c) result(f) ! 返回å˜é‡å£°æ˜Žä¸º 'f'
+ integer, intent(in) :: a, b ! å¯ä»¥å£°æ˜Žå’Œå¼ºåˆ¶çº¦å®šå˜é‡
+ ! ä¸ä¼šè¢«å‡½æ•°ä¿®æ”¹
+ integer, intent(inout) :: c
+ integer :: f ! 函数返回类型在函数内部声明
+ integer :: cnt = 0 ! 注æ„:åˆå§‹åŒ–暗示å˜é‡åœ¨å‡½æ•°è°ƒç”¨ä¹‹é—´ä¿å­˜
+ !
+
+ f = a + b - c
+ c = 4 ! 修改输入å˜é‡çš„值
+ cnt = cnt + 1 ! 计算函数调用的次数
+
+ end function func2
+
+ pure function func3(a, b, c) ! 纯函数ä¸èƒ½æœ‰å‰¯ä½œç”¨
+ integer, intent(in) :: a, b, c
+ integer :: func3
+
+ func3 = a*b*c
+
+ end function func3
+
+ subroutine routine(d, e, f)
+ real, intent(inout) :: f
+ real, intent(in) :: d, e
+
+ f = 2*d + 3*e + f
+
+ end subroutine routine
+
+end program example ! 程åºå®šä¹‰ç»“æŸ--------------------------
+
+! 函数和å­ç¨‹åºåœ¨ç¨‹åºåˆ—表之外声明,在程åºä¹‹é—´ä»¥åŠæ¨¡å—中声明时,需è¦ä½¿ç”¨ interface 声明(å³ä½¿å®ƒä»¬åœ¨åŒä¸€æºæ–‡ä»¶ä¸­ï¼‰ï¼ˆè§ä¸‹é¢ï¼‰å°†å®ƒä»¬å®šä¹‰åœ¨æ¨¡å—或程åºçš„ 'contains' 部分更容易
+
+elemental real function func4(a) result(res)
+! elemental 函数是一个纯函数,它采用标é‡è¾“å…¥å˜é‡ï¼Œ
+! 但也å¯ä»¥åœ¨æ•°ç»„上独立应用,并返回一个新的数组
+ real, intent(in) :: a
+
+ res = a**2 + 1.0
+
+end function func4
+
+! 模å—
+! =======
+
+! 模å—是在å¯é‡ç”¨æ€§ä¸­å°†ç›¸å…³çš„声明ã€å‡½æ•°å’Œå­ç¨‹åºç»“åˆåœ¨ä¸€èµ·çš„有用方å¼
+
+module fruit
+
+ real :: apple
+ real :: pear
+ real :: orange
+
+end module fruit
+
+module fruity
+ ! 声明的顺åºå¿…须是:模å—ã€æŽ¥å£ã€å˜é‡
+ !(也å¯ä»¥åœ¨ç¨‹åºä¸­å£°æ˜Žæ¨¡å—和接å£ï¼‰
+
+ use fruit, only: apple, pear ! 使用 fruit 模å—中的 apple å’Œ pear
+ implicit none ! 导入模å—之åŽ
+
+ private ! 将一些内容ç§æœ‰åŒ–(默认为公共)
+ ! 显å¼å°†ä¸€äº›å˜é‡/函数声明为公共
+ public :: apple, mycar, create_mycar
+ ! 将一些å˜é‡/函数声明为模å—ç§æœ‰ï¼ˆæœ¬ä¾‹ä¸­æ˜¯å¤šä½™çš„)
+ private :: func4
+
+ ! 接å£
+ ! ========
+ ! 在模å—内部(最好放在 'contains' 部分)显å¼å£°æ˜Žå¤–部函数/过程
+ interface
+ elemental real function func4(a) result(res)
+ real, intent(in) :: a
+ end function func4
+ end interface
+
+ ! å¯ä»¥ä½¿ç”¨å‘½å接å£å®šä¹‰é‡è½½å‡½æ•°
+ interface myabs
+ ! å¯ä»¥ä½¿ç”¨ 'module procedure' 关键字包括模å—内已ç»å®šä¹‰çš„函数
+ module procedure real_abs, complex_abs
+ end interface
+
+ ! 派生数æ®ç±»åž‹
+ ! ==================
+ ! å¯ä»¥åˆ›å»ºè‡ªå®šä¹‰çš„结构化数æ®é›†åˆ
+ type car
+ character(len=100) :: model
+ real :: weight !(åƒå…‹ï¼‰
+ real :: dimensions(3) ! å³ï¼Œé•¿åº¦-宽度-高度(米)
+ character :: colour
+ contains
+ procedure :: info ! 将过程绑定到类型
+ end type car
+
+ type(car) :: mycar ! 声明自定义类型的å˜é‡
+ ! 请查看 create_mycar() 程åºçš„用法
+
+ ! 注æ„:模å—中没有å¯ä»¥æ‰§è¡Œçš„语å¥
+
+contains
+
+ subroutine create_mycar(mycar)
+ ! 演示派生数æ®ç±»åž‹çš„用法
+ type(car), intent(out) :: mycar
+
+ ! 使用 '%' è¿ç®—符访问类型元素
+ mycar%model = "Ford Prefect"
+ mycar%colour = 'r'
+ mycar%weight = 1400
+ mycar%dimensions(1) = 5.0 ! 默认索引从 1 开始ï¼
+ mycar%dimensions(2) = 3.0
+ mycar%dimensions(3) = 1.5
+
+ end subroutine create_mycar
+
+ subroutine info(self)
+ class(car), intent(in) :: self
+ ! 使用 'class' 关键字将过程绑定到类型
+
+ print *, "Model : ", self%model
+ print *, "Colour : ", self%colour
+ print *, "Weight : ", self%weight
+ print *, "Dimensions: ", self%dimensions
+
+ end subroutine info
+
+ real pure function real_abs(x)
+ real, intent(in) :: x
+
+ if (x < 0) then
+ real_abs = -x
+ else
+ real_abs = x
+ end if
+
+ end function real_abs
+
+ real pure function complex_abs(z)
+ complex, intent(in) :: z
+ ! é•¿è¡Œå¯ä»¥ä½¿ç”¨ç»§ç»­å­—符 '&' 进行延续
+
+ complex_abs = sqrt(real(z)**2 + &
+ aimag(z)**2)
+
+ end function complex_abs
+
+end module fruity
+
+```
+
+### 更多资æº
+
+了解更多的 Fortran ä¿¡æ¯:
+
++ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
++ [Fortran-lang Organization](https://fortran-lang.org/)
++ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
++ [fortranwiki.org](http://fortranwiki.org)
++ [www.fortran90.org/](http://www.fortran90.org)
++ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/)
++ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran)
++ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf)
++ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html)
diff --git a/zh-cn/fortran95-cn.html.markdown b/zh-cn/fortran95-cn.html.markdown
deleted file mode 100644
index e28d309f..00000000
--- a/zh-cn/fortran95-cn.html.markdown
+++ /dev/null
@@ -1,435 +0,0 @@
----
-language: Fortran
-filename: learnfortran-cn.f95
-contributors:
- - ["Robert Steed", "https://github.com/robochat"]
-translators:
- - ["Corvusnest", "https://github.com/Corvusnest"]
-lang: zh-cn
----
-
-Fortran 是最å¤è€çš„计算机语言之一。它由IBMå¼€å‘于1950年用于数值è¿ç®—(Fortran 为 "Formula
-Translation" 的缩写)。虽然该语言已年代久远,但目å‰ä»ç”¨äºŽé«˜æ€§èƒ½è®¡ç®—,如天气预报。
-该语言ä»åœ¨æŒç»­å‘展,并且基本ä¿æŒå‘下兼容。知å的版本为 Fortran 77, Fortran 90,
-Fortran 95, Fortran 2003, Fortran 2008 与 Fortran 2015。
-
-这篇概è¦å°†è®¨è®º Fortran 95 的一些特å¾ã€‚因为它是目å‰æ‰€å¹¿æ³›é‡‡ç”¨çš„标准版本,并且与最新版本的内容
-也基本相åŒï¼ˆè€Œ Fortran 77 则是一个éžå¸¸ä¸åŒçš„版本)。
-
-```fortran
-
-! 这是一行注释
-
-
-program example !声明一个å«åš example 的程åº
-
- ! 代ç åªèƒ½æ”¾åœ¨ç¨‹åºã€å‡½æ•°ã€å­ç¨‹åºæˆ–者模å—内部
- ! 推è使用缩进,但ä¸æ˜¯å¿…须的。
-
- ! 声明å˜é‡
- ! ===================
-
- ! 所有的声明必须放在语å¥ä¸Žè¡¨è¾¾å¼ä¹‹å‰
-
- implicit none !阻止å˜é‡çš„éšå¼å£°æ˜Ž (推è!)
- ! Implicit none 必须在æ¯ä¸€ä¸ª 函数/程åº/æ¨¡å— ä¸­è¿›è¡Œå£°æ˜Ž
-
- ! é‡è¦ - Fortran 对大å°å†™ä¸æ•æ„Ÿ
- real z
- REAL Z2
-
- real :: v,x ! 警告: 默认值å–决于编译器!
- real :: a = 3, b=2E12, c = 0.01
- integer :: i, j, k=1, m
- real, parameter :: PI = 3.1415926535897931 !声明一个常é‡
- logical :: y = .TRUE. , n = .FALSE. !布尔值
- complex :: w = (0,1) !sqrt(-1) (译注: 定义å¤æ•°ï¼Œæ­¤ä¸º-1的平方根)
- character (len=3) :: month !长度为3的字符串
-
- real :: array(6) !声明长度为6的浮点数数组
- real, dimension(4) :: arrayb !声明数组的å¦ä¸€ç§æ–¹æ³•
- integer :: arrayc(-10:10) !有ç€è‡ªå®šä¹‰ç´¢å¼•çš„数组
- real :: array2d(3,2) !多维数组
-
- ! 分隔符 '::' 并ä¸æ€»æ˜¯å¿…è¦çš„,但推è使用
-
- ! 还存在很多其他的å˜é‡ç‰¹å¾:
- real, pointer :: p !声明一个指针
-
- integer, parameter :: LP = selected_real_kind(20)
- real (kind = LP) :: d !长精度å˜é‡
-
- ! 警告:在声明期间åˆå§‹åŒ–å˜é‡å°†å¯¼è‡´åœ¨å‡½æ•°å†…å‘生问题,因为这将自动具备了 “save†属性,
- ! å› æ­¤å˜é‡çš„值在函数的多次调用期间将被存储。一般æ¥è¯´ï¼Œé™¤äº†å¸¸é‡ï¼Œåº”分开声明与åˆå§‹åŒ–ï¼
-
- ! 字符串
- ! =======
-
- character :: a_char = 'i'
- character (len = 6) :: a_str = "qwerty"
- character (len = 30) :: str_b
- character (len = *), parameter :: a_long_str = "This is a long string."
- !å¯ä»¥é€šè¿‡ä½¿ç”¨ (len=*) æ¥è‡ªåŠ¨åˆ¤æ–­é•¿åº¦ï¼Œä½†åªå¯¹å¸¸é‡æœ‰æ•ˆ
-
- str_b = a_str // " keyboard" !通过 // æ“作符æ¥è¿žæŽ¥å­—符串
-
-
- ! 任务与计算
- ! =======================
-
- Z = 1 !å‘之å‰å£°æ˜Žçš„å˜é‡ z 赋值 (大å°å†™ä¸æ•æ„Ÿ).
- j = 10 + 2 - 3
- a = 11.54 / (2.3 * 3.1)
- b = 2**3 !幂
-
-
- ! 控制æµç¨‹è¯­å¥ 与 æ“作符
- ! ===================================
-
- !å•è¡Œ if 语å¥
- if (z == a) b = 4 !判别å¥æ°¸è¿œéœ€è¦æ”¾åœ¨åœ†æ‹¬å·å†…
-
- if (z /= a) then !z ä¸ç­‰äºŽ a
- ! 其他的比较è¿ç®—符: < > <= >= == /=
- b = 4
- else if (z .GT. a) then !z 大于(Greater) a
- ! 文本形å¼çš„比较è¿ç®—符: .LT. .GT. .LE. .GE. .EQ. .NE.
- b = 6
- else if (z < a) then !'then' 必须放在该行
- b = 5 !执行部分必须放在新的一行里
- else
- b = 10
- end if !结æŸè¯­å¥éœ€è¦ 'if' (也å¯ä»¥ç”¨ 'endif').
-
-
- if (.NOT. (x < c .AND. v >= a .OR. z == z)) then !布尔æ“作符
- inner: if (.TRUE.) then !å¯ä»¥ä¸º if 结构命å
- b = 1
- endif inner !接下æ¥å¿…须命å endif 语å¥.
- endif
-
-
- i = 20
- select case (i)
- case (0) !当 i == 0
- j=0
- case (1:10) !当 i 为 1 到 10 之内 ( 1 <= i <= 10 )
- j=1
- case (11:) !当 i>=11
- j=2
- case default
- j=3
- end select
-
-
- month = 'jan'
- ! 状æ€å€¼å¯ä»¥ä¸ºæ•´æ•°ã€å¸ƒå°”值或者字符类型
- ! Select 结构åŒæ ·å¯ä»¥è¢«å‘½å
- monthly: select case (month)
- case ("jan")
- j = 0
- case default
- j = -1
- end select monthly
-
- do i=2,10,2 !从2到10(包å«2å’Œ10)以2为步进值循环
- innerloop: do j=1,3 !循环åŒæ ·å¯ä»¥è¢«å‘½å
- exit !跳出循环
- end do innerloop
- cycle !é‡å¤è·³å…¥ä¸‹ä¸€æ¬¡å¾ªçŽ¯
- enddo
-
-
- ! Goto 语å¥æ˜¯å­˜åœ¨çš„,但强烈ä¸å»ºè®®ä½¿ç”¨
- goto 10
- stop 1 !ç«‹å³åœæ­¢ç¨‹åº (返回一个设定的状æ€ç ).
-10 j = 201 !这一行被标注为 10 行 (line 10)
-
-
- ! 数组
- ! ======
- array = (/1,2,3,4,5,6/)
- array = [1,2,3,4,5,6] !当使用 Fortran 2003 版本.
- arrayb = [10.2,3e3,0.41,4e-5]
- array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2])
-
- ! Fortran 数组索引起始于 1
- ! (默认下如此,也å¯ä»¥ä¸ºæ•°ç»„定义ä¸åŒçš„索引起始)
- v = array(1) !获å–数组的第一个元素
- v = array2d(2,2)
-
- print *, array(3:5) !打å°ä»Žç¬¬3到第五5之内的所有元素
- print *, array2d(1,:) !打å°2维数组的第一列
-
- array = array*3 + 2 !å¯ä¸ºæ•°ç»„设置数学表达å¼
- array = array*array !数组æ“作支æŒå…ƒç´ çº§(æ“作) (element-wise)
- !array = array*array2d !这两类数组并ä¸æ˜¯åŒä¸€ä¸ªç»´åº¦çš„
-
- ! 有很多内置的数组æ“作函数
- c = dot_product(array,array) !点乘 (点积)
- ! 用 matmul() æ¥è¿›è¡ŒçŸ©é˜µè¿ç®—.
- c = sum(array)
- c = maxval(array)
- print *, minloc(array)
- c = size(array)
- print *, shape(array)
- m = count(array > 0)
-
- ! é历一个数组 (一般使用 Product() 函数).
- v = 1
- do i = 1, size(array)
- v = v*array(i)
- end do
-
- ! 有æ¡ä»¶åœ°æ‰§è¡Œå…ƒç´ çº§æ“作
- array = [1,2,3,4,5,6]
- where (array > 3)
- array = array + 1
- elsewhere (array == 2)
- array = 1
- elsewhere
- array = 0
- end where
-
- ! éšå¼DO循环å¯ä»¥å¾ˆæ–¹ä¾¿åœ°åˆ›å»ºæ•°ç»„
- array = [ (i, i = 1,6) ] !创建数组 [1,2,3,4,5,6]
- array = [ (i, i = 1,12,2) ] !创建数组 [1,3,5,7,9,11]
- array = [ (i**2, i = 1,6) ] !创建数组 [1,4,9,16,25,36]
- array = [ (4,5, i = 1,3) ] !创建数组 [4,5,4,5,4,5]
-
-
- ! 输入/输出
- ! ============
-
- print *, b !å‘命令行打å°å˜é‡ 'b'
-
- ! 我们å¯ä»¥æ ¼å¼åŒ–输出
- print "(I6)", 320 !æ‰“å° ' 320'
- print "(I6.4)", 3 !æ‰“å° ' 0003'
- print "(F6.3)", 4.32 !æ‰“å° ' 4.320'
-
-
- ! 该字æ¯ä¸Žæ•°å€¼è§„定了给定的数值与字符所用于打å°è¾“出的类型与格å¼
- ! å­—æ¯å¯ä¸º I (æ•´æ•°), F (浮点数), E (工程格å¼),
- ! L (逻辑/布尔值), A (字符) ...
- print "(I3)", 3200 !如果数值无法符åˆæ ¼å¼å°†æ‰“å° '***'
-
- ! å¯ä»¥åŒæ—¶è®¾å®šå¤šç§æ ¼å¼
- print "(I5,F6.2,E6.2)", 120, 43.41, 43.41
- print "(3I5)", 10, 20, 30 !连续打å°3个整数 (字段宽度 = 5).
- print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 !连续分组格å¼
-
- ! 我们也å¯ä»¥ä»Žç»ˆç«¯è¯»å–输入
- read *, v
- read "(2F6.2)", v, x !读å–2个数值
-
- ! 读å–文件
- open(unit=11, file="records.txt", status="old")
- ! 文件被引用带有一个å•ä½æ•° 'unit', 为一个å–值范围在9-99çš„æ•´æ•°
- ! 'status' å¯ä»¥ä¸º {'old','replace','new'} 其中之一
- read(unit=11, fmt="(3F10.2)") a, b, c
- close(11)
-
- ! 写入一个文件
- open(unit=12, file="records.txt", status="replace")
- write(12, "(F10.2,F10.2,F10.2)") c, b, a
- close(12)
- ! 在讨论范围之外的还有更多的细节与å¯ç”¨åŠŸèƒ½ï¼Œå¹¶äºŽè€ç‰ˆæœ¬çš„ Fortran ä¿æŒå…¼å®¹
-
-
- ! 内置函数
- ! ==================
-
- ! Fortran 拥有大约 200 个内置函数/å­ç¨‹åº
- ! 例å­
- call cpu_time(v) !以秒为å•ä½è®¾ç½®æ—¶é—´
- k = ior(i,j) !2个整数的ä½æˆ–è¿ç®—
- v = log10(x) !以10为底的logè¿ç®—
- i = floor(b) !返回一个最接近的整数å°äºŽæˆ–等于x (地æ¿æ•°)
- v = aimag(w) !å¤æ•°çš„虚数部分
-
-
- ! 函数与å­ç¨‹åº
- ! =======================
-
- ! 一个å­ç¨‹åºä¼šæ ¹æ®è¾“入值è¿è¡Œä¸€äº›ä»£ç å¹¶ä¼šå¯¼è‡´å‰¯ä½œç”¨ (side-effects) 或修改输入值
- ! (译者注: 副作用是指对å­ç¨‹åº/函数外的环境产生影å“,如修改å˜é‡)
-
- call routine(a,c,v) !调用å­ç¨‹åº
-
- ! 一个函数会根æ®è¾“入的一系列数值æ¥è¿”回一个å•ç‹¬çš„值
- ! 但输入值ä»ç„¶å¯èƒ½è¢«ä¿®æ”¹ä»¥åŠäº§ç”Ÿå‰¯ä½œç”¨
-
- m = func(3,2,k) !调用函数
-
- ! 函数å¯ä»¥åœ¨è¡¨è¾¾å¼å†…被调用
- Print *, func2(3,2,k)
-
- ! 一个纯函数ä¸ä¼šåŽ»ä¿®æ”¹è¾“入值或产生副作用
- m = func3(3,2,k)
-
-
-contains ! 用于定义程åºå†…部的副程åº(sub-programs)的区域
-
- ! Fortran 拥有一些ä¸åŒçš„方法去定义函数
-
- integer function func(a,b,c) !一个返回一个整数的函数
- implicit none !最好也在函数内将å«è“„模å¼å…³é—­ (implicit none)
- integer :: a,b,c !输入值类型定义在函数内部
- if (a >= 2) then
- func = a + b + c !返回值默认为函数å
- return !å¯ä»¥åœ¨å‡½æ•°å†…ä»»æ„时间返回当å‰å€¼
- endif
- func = a + c
- ! 在函数的结尾ä¸éœ€è¦è¿”回语å¥
- end function func
-
-
- function func2(a,b,c) result(f) !将返回值声明为 'f'
- implicit none
- integer, intent(in) :: a,b !å¯ä»¥å£°æ˜Žè®©å˜é‡æ— æ³•è¢«å‡½æ•°ä¿®æ”¹
- integer, intent(inout) :: c
- integer :: f !函数的返回值类型在函数内声明
- integer :: cnt = 0 !æ³¨æ„ - éšå¼çš„åˆå§‹åŒ–å˜é‡å°†åœ¨å‡½æ•°çš„多次调用间被存储
- f = a + b - c
- c = 4 !å˜åŠ¨ä¸€ä¸ªè¾“å…¥å˜é‡çš„值
- cnt = cnt + 1 !记录函数的被调用次数
- end function func2
-
-
- pure function func3(a,b,c) !一个没有副作用的纯函数
- implicit none
- integer, intent(in) :: a,b,c
- integer :: func3
- func3 = a*b*c
- end function func3
-
-
- subroutine routine(d,e,f)
- implicit none
- real, intent(inout) :: f
- real, intent(in) :: d,e
- f = 2*d + 3*e + f
- end subroutine routine
-
-
-end program example ! 函数定义完毕 -----------------------
-
-! 函数与å­ç¨‹åºçš„外部声明对于生æˆç¨‹åºæ¸…å•æ¥è¯´ï¼Œéœ€è¦ä¸€ä¸ªæŽ¥å£å£°æ˜Žï¼ˆå³ä½¿å®ƒä»¬åœ¨åŒä¸€ä¸ªæºæ–‡ä»¶å†…)(è§ä¸‹)
-! 使用 'contains' å¯ä»¥å¾ˆå®¹æ˜“地在模å—或程åºå†…定义它们
-
-elemental real function func4(a) result(res)
-! 一个元函数(elemental function) 为一个纯函数使用一个标é‡è¾“入值
-! 但åŒæ—¶ä¹Ÿå¯ä»¥ç”¨åœ¨ä¸€ä¸ªæ•°ç»„并对其中的元素分别处ç†ï¼Œä¹‹åŽè¿”回一个新的数组
- real, intent(in) :: a
- res = a**2 + 1.0
-end function func4
-
-
-! 模å—
-! =======
-
-! 模å—å分适åˆäºŽå­˜æ”¾ä¸Žå¤ç”¨ç›¸å…³è”的一组声明ã€å‡½æ•°ä¸Žå­ç¨‹åº
-
-module fruit
- real :: apple
- real :: pear
- real :: orange
-end module fruit
-
-
-module fruity
-
- ! 声明必须按照顺åº: 模å—ã€æŽ¥å£ã€å˜é‡
- ! (åŒæ ·å¯åœ¨ç¨‹åºå†…声明模å—和接å£)
-
- use fruit, only: apple, pear ! 使用æ¥è‡ªäºŽ fruit 模å—çš„ apple å’Œ pear
- implicit none !在模å—导入åŽå£°æ˜Ž
-
- private !使得模å—内容为ç§æœ‰(private)(默认为公共 public)
- ! 显å¼å£°æ˜Žä¸€äº›å˜é‡/函数为公共
- public :: apple,mycar,create_mycar
- ! 声明一些å˜é‡/函数为ç§æœ‰(在当å‰æƒ…况下没必è¦)(译注: 因为å‰é¢å£°æ˜Žäº†æ¨¡å—全局 private)
- private :: func4
-
- ! 接å£
- ! ==========
- ! 在模å—内显å¼å£°æ˜Žä¸€ä¸ªå¤–部函数/程åº
- ! 一般最好将函数/程åºæ”¾è¿› 'contains' 部分内
- interface
- elemental real function func4(a) result(res)
- real, intent(in) :: a
- end function func4
- end interface
-
- ! é‡è½½å‡½æ•°å¯ä»¥é€šè¿‡å·²å‘½å的接å£æ¥å®šä¹‰
- interface myabs
- ! å¯ä»¥é€šè¿‡ä½¿ç”¨ 'module procedure' 关键è¯æ¥åŒ…å«ä¸€ä¸ªå·²åœ¨æ¨¡å—内定义的函数
- module procedure real_abs, complex_abs
- end interface
-
- ! 派生数æ®ç±»åž‹
- ! ==================
- ! å¯åˆ›å»ºè‡ªå®šä¹‰æ•°æ®ç»“æž„
- type car
- character (len=100) :: model
- real :: weight !(公斤 kg)
- real :: dimensions(3) !例: 长宽高(米)
- character :: colour
- end type car
-
- type(car) :: mycar !声明一个自定义类型的å˜é‡
- ! 用法具体查看 create_mycar()
-
- ! 注: 模å—内没有å¯æ‰§è¡Œçš„语å¥
-
-contains
-
- subroutine create_mycar(mycar)
- ! 展示派生数æ®ç±»åž‹çš„使用
- implicit none
- type(car),intent(out) :: mycar
-
- ! 通过 '%' æ“作符æ¥è®¿é—®(派生数æ®)类型的元素
- mycar%model = "Ford Prefect"
- mycar%colour = 'r'
- mycar%weight = 1400
- mycar%dimensions(1) = 5.0 !索引默认起始值为 1 !
- mycar%dimensions(2) = 3.0
- mycar%dimensions(3) = 1.5
-
- end subroutine
-
- real function real_abs(x)
- real :: x
- if (x<0) then
- real_abs = -x
- else
- real_abs = x
- end if
- end function real_abs
-
- real function complex_abs(z)
- complex :: z
- ! 过长的一行代ç å¯é€šè¿‡å»¶ç»­ç¬¦ '&' æ¥æ¢è¡Œ
- complex_abs = sqrt(real(z)**2 + &
- aimag(z)**2)
- end function complex_abs
-
-
-end module fruity
-
-```
-
-### 更多资æº
-
-了解更多的 Fortran ä¿¡æ¯:
-
-+ [wikipedia](https://en.wikipedia.org/wiki/Fortran)
-+ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features)
-+ [fortranwiki.org](http://fortranwiki.org)
-+ [www.fortran90.org/](http://www.fortran90.org)
-+ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/)
-+ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran)
-+ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf)
-+ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html)
diff --git a/zh-cn/gdscript-cn.html.markdown b/zh-cn/gdscript-cn.html.markdown
new file mode 100644
index 00000000..7c731533
--- /dev/null
+++ b/zh-cn/gdscript-cn.html.markdown
@@ -0,0 +1,317 @@
+---
+language: GDScript
+contributors:
+ - ["Wichamir", "https://github.com/Wichamir/"]
+translators:
+ - ["ShiftWatchOut", "https://github.com/ShiftWatchOut"]
+filename: learngdscript-cn.gd
+lang: zh-cn
+---
+
+GDScript 是一ç§åŠ¨æ€ç±»åž‹çš„脚本语言,专门为å…费开æºæ¸¸æˆå¼•æ“Ž Godot 制作。 GDScript 的语法类似 Python。
+它的主è¦ä¼˜ç‚¹æ˜¯æ˜“于使用和与引擎深度集æˆã€‚ 它éžå¸¸é€‚åˆæ¸¸æˆå¼€å‘。
+
+## 基础
+
+```nim
+# å•è¡Œæ³¨é‡Šä½¿ç”¨ # å·ä¹¦å†™ã€‚
+"""
+ 多行
+ 注释
+ 是
+ 使用
+ 文档字符串(docstring)
+ 书写。
+"""
+
+# 脚本文件本身默认是一个类,文件å为类å,您也å¯ä»¥ä¸ºå…¶å®šä¹‰å…¶ä»–å称。
+class_name MyClass
+
+# 继承
+extends Node2D
+
+# æˆå‘˜å˜é‡
+var x = 8 # æ•´åž‹
+var y = 1.2 # 浮点型
+var b = true # 布尔型
+var s = "Hello World!" # 字符串
+var a = [1, false, "brown fox"] # 数组(Array) - 类似于 Python 的列表(list),
+ # 它å¯ä»¥åŒæ—¶ä¿å­˜ä¸åŒç±»åž‹çš„å˜é‡ã€‚
+var d = {
+ "key" : "value",
+ 42 : true
+} # 字典包å«é”®å€¼å¯¹ã€‚
+var p_arr = PoolStringArray(["Hi", "there", "!"]) # 池数组åªèƒ½åŒ…å«å•ä¸€ç±»åž‹ã€‚
+ # 放入其他类型会被转æ¢ä¸ºç›®æ ‡ç±»åž‹
+
+# 内置å‘é‡ç±»åž‹:
+var v2 = Vector2(1, 2)
+var v3 = Vector3(1, 2, 3)
+
+# 常é‡
+const ANSWER_TO_EVERYTHING = 42
+const BREAKFAST = "Spam and eggs!"
+
+# 枚举
+enum { ZERO, ONE , TWO, THREE }
+enum NamedEnum { ONE = 1, TWO, THREE }
+
+# 导出的å˜é‡å°†åœ¨æ£€æŸ¥å™¨ä¸­å¯è§ã€‚
+export(int) var age
+export(float) var height
+export var person_name = "Bob" # 如果设置了默认值,则ä¸éœ€è¦ç±»åž‹æ³¨è§£ã€‚
+
+# 函数
+func foo():
+ pass # pass 关键字是未书写的代ç çš„å ä½ç¬¦
+
+func add(first, second):
+ return first + second
+
+# 打å°å€¼
+func printing():
+ print("GDScript ", "简直", "棒呆了")
+ prints("这", "些", "字", "被", "空", "格", "分", "割")
+ printt("这", "些", "字", "被", "制", "表", "符", "分", "割")
+ printraw("è¿™å¥è¯å°†è¢«æ‰“å°åˆ°ç³»ç»ŸæŽ§åˆ¶å°ã€‚")
+
+# æ•°å­¦
+func doing_math():
+ var first = 8
+ var second = 4
+ print(first + second) # 12
+ print(first - second) # 4
+ print(first * second) # 32
+ print(first / second) # 2
+ print(first % second) # 0
+ # 还有 +=, -=, *=, /=, %= ç­‰æ“作符,但并没有 ++ å’Œ -- .
+ print(pow(first, 2)) # 64
+ print(sqrt(second)) # 2
+ printt(PI, TAU, INF, NAN) # 内置常é‡
+
+# 控制æµ
+func control_flow():
+ x = 8
+ y = 2 # y 最åˆè¢«è®¾ä¸ºä¸€ä¸ªæµ®ç‚¹æ•°ï¼Œ
+ # 但我们å¯ä»¥åˆ©ç”¨è¯­è¨€æ供的动æ€ç±»åž‹èƒ½åŠ›å°†å®ƒçš„类型å˜ä¸ºæ•´åž‹ï¼
+
+ if x < y:
+ print("x å°äºŽ y")
+ elif x > y:
+ print("x 大于 y")
+ else:
+ print("x 等于 y")
+
+ var a = true
+ var b = false
+ var c = false
+ if a and b or not c: # 你也å¯ä»¥ç”¨ &&, || å’Œ !
+ print("看到这å¥è¯´æ˜Žä¸Šé¢çš„æ¡ä»¶åˆ¤æ–­ä¸ºçœŸï¼")
+
+ for i in range(20): # GDScript 有类似 Python 的 range 函数
+ print(i) # 所以这å¥å°†æ‰“å°ä»Ž 0 到 19 çš„æ•°å­—
+
+ for i in 20: # 与 Python 略有ä¸åŒçš„是,你å¯ä»¥ç›´æŽ¥ç”¨ä¸€ä¸ªæ•´åž‹æ•°å¼€å§‹å¾ªçŽ¯
+ print(i) # 所以这行代ç ä¹Ÿå°†æ‰“å°ä»Ž 0 到 19 çš„æ•°å­—
+
+ for i in ["two", 3, 1.0]: # é历数组
+ print(i)
+
+ while x > y:
+ printt(x, y)
+ y += 1
+
+ x = 2
+ y = 10
+ while x < y:
+ x += 1
+ if x == 6:
+ continue # continue 语å¥ä½¿ x 等于 6 时,程åºè·³è¿‡è¿™æ¬¡å¾ªçŽ¯åŽé¢çš„代ç ï¼Œä¸ä¼šæ‰“å° 6。
+ prints("x 等于:", x)
+ if x == 7:
+ break # 循环将在 x 等于 7 处跳出,åŽç»­æ‰€æœ‰å¾ªçŽ¯ä¸å†æ‰§è¡Œï¼Œå› æ­¤ä¸ä¼šæ‰“å° 8ã€9 å’Œ 10
+
+ match x:
+ 1:
+ print("match 很åƒå…¶ä»–语言中的 switch.")
+ 2:
+ print("但是,您ä¸éœ€è¦åœ¨æ¯ä¸ªå€¼ä¹‹å‰å†™ä¸€ä¸ª case 关键字。")
+ 3:
+ print("此外,æ¯ç§æƒ…况都会默认跳出。")
+ break # 错误ï¼ä¸è¦åœ¨ match 里用 break 语å¥ï¼
+ 4:
+ print("如果您需è¦è·³è¿‡åŽç»­ä»£ç ï¼Œè¿™é‡Œä¹Ÿä½¿ç”¨ continue 关键字。")
+ continue
+ _:
+ print("下划线分支,在其他分支都ä¸æ»¡è¶³æ—¶ï¼Œåœ¨è¿™é‡Œä¹¦å†™é»˜è®¤çš„逻辑。")
+
+ # 三元è¿ç®—符 (写在一行的 if-else 语å¥)
+ prints("x 是", "正值" if x >= 0 else "负值")
+
+# 类型转æ¢
+func casting_examples():
+ var i = 42
+ var f = float(42) # 使用å˜é‡æž„造函数强制转æ¢
+ var b = i as bool # 或使用 as 关键字
+
+# é‡è½½å‡½æ•°
+# 通常,我们åªä¼šé‡è½½ä»¥ä¸‹åˆ’线开头的内置函数,
+# 但实际上您å¯ä»¥é‡è½½å‡ ä¹Žä»»ä½•å‡½æ•°ã€‚
+
+# _init 在对象åˆå§‹åŒ–时被调用。
+# 这是对象的构造函数。
+func _init():
+ # 在此处åˆå§‹åŒ–对象的内部属性。
+ pass
+
+# _ready 在脚本节点åŠå…¶å­èŠ‚点进入场景树时被调用。
+func _ready():
+ pass
+
+# _process 在æ¯ä¸€å¸§ä¸Šéƒ½è¢«è°ƒç”¨ã€‚
+func _process(delta):
+ # 传递给此函数的 delta å‚数是时间,å³ä»Žä¸Šä¸€å¸§åˆ°å½“å‰å¸§ç»è¿‡çš„秒数。
+ print("Delta 时间为:", delta)
+
+# _physics_process 在æ¯ä¸ªç‰©ç†å¸§ä¸Šéƒ½è¢«è°ƒç”¨ã€‚
+# è¿™æ„å‘³ç€ delta 应该是æ’定的。
+func _physics_process(delta):
+ # 使用å‘é‡åŠ æ³•å’Œä¹˜æ³•è¿›è¡Œç®€å•ç§»åŠ¨ã€‚
+ var direction = Vector2(1, 0) # 或使用 Vector2.RIGHT
+ var speed = 100.0
+ self.global_position += direction * speed * delta
+ # self 指å‘当å‰ç±»çš„实例
+
+# é‡è½½å‡½æ•°æ—¶ï¼Œæ‚¨å¯ä»¥ä½¿ç”¨ . è¿ç®—符调用父函数
+# like here:
+func get_children():
+ # 在这里åšä¸€äº›é¢å¤–的事情。
+ var r = .get_children() # 调用父函数的实现
+ return r
+
+# 内部类
+class InnerClass:
+ extends Object
+
+ func hello():
+ print("æ¥è‡ªå†…部类的 Helloï¼")
+
+func use_inner_class():
+ var ic = InnerClass.new()
+ ic.hello()
+ ic.free() # å¯ä»¥è‡ªè¡Œé‡Šæ”¾å†…å­˜
+```
+
+## 访问场景树中其他节点
+
+```nim
+extends Node2D
+
+var sprite # 该å˜é‡å°†ç”¨æ¥ä¿å­˜å¼•ç”¨ã€‚
+
+# 您å¯ä»¥åœ¨ _ready 中获å–对其他节点的引用。
+func _ready() -> void:
+ # NodePath 对于访问节点很有用。
+ # å°† String 传递给其构造函数æ¥åˆ›å»º NodePath:
+ var path1 = NodePath("path/to/something")
+ # 或者使用 NodePath å­—é¢é‡:
+ var path2 = @"path/to/something"
+ # NodePath 示例:
+ var path3 = @"Sprite" # 相对路径,当å‰èŠ‚点的直接å­èŠ‚点
+ var path4 = @"Timers/Firerate" # 相对路径,å­èŠ‚点的å­èŠ‚点
+ var path5 = @".." # 当å‰èŠ‚点的父节点
+ var path6 = @"../Enemy" # 当å‰èŠ‚点的兄弟节点
+ var path7 = @"/root" # ç»å¯¹è·¯å¾„,等价于 get_tree().get_root()
+ var path8 = @"/root/Main/Player/Sprite" # Player çš„ Sprite çš„ç»å¯¹è·¯å¾„
+ var path9 = @"Timers/Firerate:wait_time" # 访问属性
+ var path10 = @"Player:position:x" # 访问å­å±žæ€§
+
+ # 最åŽï¼ŒèŽ·å–节点引用å¯ä»¥ä½¿ç”¨ä»¥ä¸‹æ–¹æ³•:
+ sprite = get_node(@"Sprite") as Sprite # 始终转æ¢ä¸ºæ‚¨æœŸæœ›çš„类型
+ sprite = get_node("Sprite") as Sprite # 这里 String 被éšå¼è½¬æ¢ä¸º NodePath
+ sprite = get_node(path3) as Sprite
+ sprite = get_node_or_null("Sprite") as Sprite
+ sprite = $Sprite as Sprite
+
+func _process(delta):
+ # 现在我们就å¯ä»¥åœ¨åˆ«å¤„使用 sprite 里ä¿å­˜çš„引用了。
+ prints("Sprite 有一个全局ä½ç½® ", sprite.global_position)
+
+# 在 _ready 执行之å‰ï¼Œä½¿ç”¨ onready 关键字为å˜é‡èµ‹å€¼ã€‚
+# 这是一ç§å¸¸ç”¨çš„语法糖。
+onready var tween = $Tween as Tween
+
+# 您å¯ä»¥å¯¼å‡ºè¿™ä¸ª NodePath,以便在检查器中给它赋值。
+export var nodepath = @""
+onready var reference = get_node(nodepath) as Node
+```
+
+## ä¿¡å·(Signals)
+
+ä¿¡å·ç³»ç»Ÿæ˜¯ Godot 对观察者编程模å¼çš„实现。例å­å¦‚下:
+
+```nim
+class_name Player extends Node2D
+
+var hp = 10
+
+signal died() # 定义一个信å·
+signal hurt(hp_old, hp_new) # ä¿¡å·å¯ä»¥å¸¦å‚æ•°
+
+func apply_damage(dmg):
+ var hp_old = hp
+ hp -= dmg
+ emit_signal("hurt", hp_old, hp) # å‘出信å·å¹¶ä¼ é€’å‚æ•°
+ if hp <= 0:
+ emit_signal("died")
+
+func _ready():
+ # å°†ä¿¡å· "died" 连接到 self 中定义的 _on_death 函数
+ self.connect("died", self, "_on_death")
+
+func _on_death():
+ self.queue_free() # æ­»äº¡æ—¶é”€æ¯ Player
+```
+
+## 类型注解
+
+GDScript å¯ä»¥é€‰æ‹©æ€§åœ°ä½¿ç”¨é™æ€ç±»åž‹ã€‚
+
+```nim
+extends Node
+
+var x: int # 定义带有类型的å˜é‡
+var y: float = 4.2
+var z := 1.0 # 使用 := è¿ç®—符根æ®é»˜è®¤å€¼æŽ¨æ–­ç±»åž‹
+
+onready var node_ref_typed := $Child as Node
+
+export var speed := 50.0
+
+const CONSTANT := "Typed constant."
+
+func _ready() -> void:
+ # 此函数ä¸è¿”回任何东西
+ x = "string" # 错误ï¼ä¸è¦æ›´æ”¹ç±»åž‹ï¼
+ return
+
+func join(arg1: String, arg2: String) -> String:
+ # 此函数接å—两个 String 并返回一个 String。
+ return arg1 + arg2
+
+func get_child_at(index: int) -> Node:
+ # 此函数接å—一个 int 并返回一个 Node
+ return get_children()[index]
+
+signal example(arg: int) # 错误ï¼ä¿¡å·ä¸èƒ½æŽ¥å—类型å‚æ•°ï¼
+```
+
+## 延展阅读
+
+* [Godot's Website](https://godotengine.org/)
+* [Godot Docs](https://docs.godotengine.org/en/stable/)
+* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html)
+* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html)
+* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html)
+* [GDQuest](https://www.gdquest.com/)
+* [GDScript.com](https://gdscript.com/) \ No newline at end of file
diff --git a/zh-cn/git-cn.html.markdown b/zh-cn/git-cn.html.markdown
index 63d740a1..9dfbbb93 100644
--- a/zh-cn/git-cn.html.markdown
+++ b/zh-cn/git-cn.html.markdown
@@ -370,5 +370,3 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Atlassian Git - 教程与工作æµç¨‹](https://www.atlassian.com/git/)
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-
-* [GitGuys](http://www.gitguys.com/)
diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index dd52d187..a2b71761 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -22,7 +22,7 @@ Go语言有éžå¸¸æ£’的标准库,还有一个充满热情的社区。
注释 */
// 导入包的å­å¥åœ¨æ¯ä¸ªæºæ–‡ä»¶çš„开头。
-// Main比较特殊,它用æ¥å£°æ˜Žå¯æ‰§è¡Œæ–‡ä»¶ï¼Œè€Œä¸æ˜¯ä¸€ä¸ªåº“。
+// main比较特殊,它用æ¥å£°æ˜Žå¯æ‰§è¡Œæ–‡ä»¶ï¼Œè€Œä¸æ˜¯ä¸€ä¸ªåº“。
package main
// Import语å¥å£°æ˜Žäº†å½“å‰æ–‡ä»¶å¼•ç”¨çš„包。
@@ -78,7 +78,7 @@ func learnTypes() {
// éžascii字符。Go使用UTF-8ç¼–ç ã€‚
g := 'Σ' // rune类型,int32的别å,使用UTF-8ç¼–ç 
- f := 3.14195 // float64类型,IEEE-754 64ä½æµ®ç‚¹æ•°
+ f := 3.14159 // float64类型,IEEE-754 64ä½æµ®ç‚¹æ•°
c := 3 + 4i // complex128类型,内部使用两个float64表示
// varå˜é‡å¯ä»¥ç›´æŽ¥åˆå§‹åŒ–。
@@ -392,15 +392,15 @@ func requestServer() {
## 更进一步
-关于Go的一切你都å¯ä»¥åœ¨[Go官方网站](http://golang.org/)找到。
+关于Go的一切你都å¯ä»¥åœ¨[Go官方网站](https://go.dev/)找到。
在那里你å¯ä»¥èŽ·å¾—教程å‚考,在线试用,和更多的资料。
-在简å•çš„å°è¯•è¿‡åŽï¼Œåœ¨[官方文档](https://golang.org/doc/)那里你会得到你所需è¦çš„所有资料ã€å…³äºŽç¼–写代ç çš„规范ã€åº“和命令行工具的文档与Go的版本历å²ã€‚
+在简å•çš„å°è¯•è¿‡åŽï¼Œåœ¨[官方文档](https://go.dev/doc/)那里你会得到你所需è¦çš„所有资料ã€å…³äºŽç¼–写代ç çš„规范ã€åº“和命令行工具的文档与Go的版本历å²ã€‚
强烈推è阅读语言定义部分,很简å•è€Œä¸”很简æ´ï¼ï¼ˆèµ¶æ—¶é«¦ï¼ï¼‰
-你还å¯ä»¥å‰å¾€[Go在线体验中心](https://play.golang.org/p/tnWMjr16Mm)进,在æµè§ˆå™¨é‡Œä¿®æ”¹å¹¶è¿è¡Œè¿™äº›ä»£ç ï¼Œä¸€å®šè¦è¯•ä¸€è¯•å“¦ï¼ä½ å¯ä»¥å°†[https://play.golang.org](https://play.golang.org)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或è¿è¡Œè‡ªå·±çš„代ç ï¼Œè¿žçŽ¯å¢ƒéƒ½ä¸ç”¨é…ï¼
+你还å¯ä»¥å‰å¾€[Go在线体验中心](https://go.dev/play/p/tnWMjr16Mm)进,在æµè§ˆå™¨é‡Œä¿®æ”¹å¹¶è¿è¡Œè¿™äº›ä»£ç ï¼Œä¸€å®šè¦è¯•ä¸€è¯•å“¦ï¼ä½ å¯ä»¥å°†[https://go.dev/play/](https://go.dev/play/)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或è¿è¡Œè‡ªå·±çš„代ç ï¼Œè¿žçŽ¯å¢ƒéƒ½ä¸ç”¨é…ï¼
-学习Go还è¦é˜…读Go[标准库的æºä»£ç ](http://golang.org/src/),全部文档化了,å¯è¯»æ€§éžå¸¸å¥½ï¼Œå¯ä»¥å­¦åˆ°go,go styleå’Œgo idioms。在[文档](http://golang.org/pkg/)中点击函数å,æºä»£ç å°±å‡ºæ¥äº†ï¼
+学习Go还è¦é˜…读Go[标准库的æºä»£ç ](https://go.dev/src/),全部文档化了,å¯è¯»æ€§éžå¸¸å¥½ï¼Œå¯ä»¥å­¦åˆ°go,go styleå’Œgo idioms。在[文档](https://go.dev/pkg/)中点击函数å,æºä»£ç å°±å‡ºæ¥äº†ï¼
[Go by example](https://gobyexample.com/)也是一个学习的好地方。
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index 1de7f3e6..53a423a8 100644
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -190,7 +190,7 @@ public class LearnJava {
{
//System.out.println(fooWhile);
//增加计数器
- //é历99次, fooWhile 0->99
+ //é历100次, fooWhile 0->99
fooWhile++;
}
System.out.println("fooWhile Value: " + fooWhile);
@@ -201,7 +201,7 @@ public class LearnJava {
{
//System.out.println(fooDoWhile);
//增加计数器
- //é历99次, fooDoWhile 0->99
+ //é历100次, fooDoWhile 0->99
fooDoWhile++;
}while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
diff --git a/zh-cn/json-cn.html.markdown b/zh-cn/json-cn.html.markdown
index 73d3eb57..f5842c07 100644
--- a/zh-cn/json-cn.html.markdown
+++ b/zh-cn/json-cn.html.markdown
@@ -8,24 +8,30 @@ filename: learnjson-cn.json
lang: zh-cn
---
-因为JSON是一个æžå…¶ç®€å•çš„æ•°æ®äº¤æ¢æ ¼å¼ï¼Œæœ¬æ•™ç¨‹æœ€æœ‰å¯èƒ½æˆä¸ºæœ‰å²ä»¥æ¥æœ€ç®€å•çš„
-Learn X in Y Minutes。
+JSON是一个æžå…¶ç®€å•çš„æ•°æ®äº¤æ¢æ ¼å¼ã€‚按[json.org](https://json.org)说的,它对人类易读易写,对机器易解æžæ˜“生æˆã€‚
-纯正的JSON实际上没有注释,但是大多数解æžå™¨éƒ½
-接å—C-风格(//, /\* \*/)的注释。为了兼容性,最好ä¸è¦åœ¨å…¶ä¸­å†™è¿™æ ·å½¢å¼çš„注释。
+一段JSONå¯ä»¥æ˜¯ä¸‹æ–‡åˆ—出的类型的任æ„值,但实际一般按以下两ç§æ–¹å¼ä¹‹ä¸€å‘ˆçŽ°ï¼š
+
+* 一个键值对的集åˆ(`{ }`)。按ä¸åŒè¯­è¨€ï¼Œè¿™å¯èƒ½è¢«ç†è§£ä¸ºå¯¹è±¡/记录/结构体/å­—å…¸/哈希表/有键列表/å…³è”数组
+* 一个有åºçš„值列表(`[ ]`)。按ä¸åŒè¯­è¨€ï¼Œè¿™å¯èƒ½è¢«ç†è§£ä¸ºæ•°ç»„/å‘é‡/列表/åºåˆ—
+
+纯正的JSON实际上没有注释,但是大多数解æžå™¨éƒ½æŽ¥å—C-风格(//, /\* \*/)的注释。一些解æžå™¨è¿˜å®¹è®¸trailing comma,å³æœ€åŽä¸€ä¸ªæ•°ç»„元素或最åŽä¸€ä¸ªå¯¹è±¡å±žæ€§ä¹‹åŽçš„逗å·ã€‚ä¸è¿‡ä¸ºäº†å…¼å®¹æ€§æœ€å¥½é¿å…。
因此,本教程的一切都会是100%有效的JSON。幸äºï¼Œå®ƒçš„表达能力很丰富。
支æŒçš„æ•°æ®ç±»åž‹ï¼š
-- 字符串: "hello", "\"A quote.\"", "\u0abe", "Newline.\n"
-- æ•°å­—: 23, 0.11, 12e10, 3.141e-10, 1.23e+4
-- 对象: { "key": "value" }
-- 数组: ["Values"]
-- 其他: true, false, null
+* 字符串:`"hello"`ã€`"\"A quote.\""`ã€`"\u0abe"`ã€`"Newline.\n"`
+* 数字:`23`ã€`0.11`ã€`12e10`ã€`3.141e-10`ã€`1.23e+4`
+* 对象:`{ "key": "value" }`
+* 数组:`["Values"]`
+* 其它:`true`ã€`false`ã€`null`
```json
{
+ "key": "value",
+
+ "keys": "must always be enclosed in double quotes",
"numbers": 0,
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
"has bools?": true,
@@ -55,6 +61,23 @@ Learn X in Y Minutes。
]
],
- "that was short": "And, you're done. You now know everything JSON has to offer."
+ "alternative style": {
+ "comment": "check this out!"
+ , "comma position": "doesn't matter, if it's before the next key, it's valid"
+ , "another comment": "how nice"
+ },
+
+
+
+ "whitespace": "Does not matter.",
+
+
+
+ "that was short": "And done. You now know everything JSON has to offer."
}
```
+
+## 进一步阅读
+
+* [JSON.org](https://www.json.org/json-zh.html) 完美图解JSON的一切
+* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) 简è¦ä»‹ç»
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
index 6736dc2a..6fd10a32 100644
--- a/zh-cn/lua-cn.html.markdown
+++ b/zh-cn/lua-cn.html.markdown
@@ -391,7 +391,8 @@ dofile('mod2') --> Hi! (å†æ¬¡è¿è¡Œï¼Œä¸Žrequireä¸åŒ)
f = loadfile('mod2') -- Calling f() runs mod2.lua.
-- loadstring是loadfile的字符串版本。
-g = loadstring('print(343)') --返回一个函数。
+-- (loadstring已弃用, 使用load代替)
+g = load('print(343)') --返回一个函数。
g() -- 打å°343; 在此之å‰ä»€ä¹ˆä¹Ÿä¸æ‰“å°ã€‚
--]]
diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown
index 707d6927..23f27dda 100644
--- a/zh-cn/markdown-cn.html.markdown
+++ b/zh-cn/markdown-cn.html.markdown
@@ -147,7 +147,6 @@ GitHub ä¹Ÿæ”¯æŒ Markdown,在 GitHub çš„ Markdown 解æžå™¨ä¸­ï¼Œæˆ‘们å¯ä»¥ä
- 项目
- 项目
- 最åŽä¸€ä¸ªé¡¹ç›®
-
```
有åºåºåˆ—å¯ç”±æ•°å­—加上点 `.` æ¥å®žçŽ°
@@ -188,6 +187,7 @@ GitHub ä¹Ÿæ”¯æŒ Markdown,在 GitHub çš„ Markdown 解æžå™¨ä¸­ï¼Œæˆ‘们å¯ä»¥ä
下é¢è¿™ä¸ªé€‰æ‹©æ¡†å°†ä¼šæ˜¯é€‰ä¸­çŠ¶æ€
- [x] 这个任务已ç»å®Œæˆ
```
+
- [ ] 你看完了这个任务(注:此选择框是无法直接更改的,å³ç¦ç”¨çŠ¶æ€ã€‚)
## 代ç å—
@@ -204,7 +204,7 @@ GitHub ä¹Ÿæ”¯æŒ Markdown,在 GitHub çš„ Markdown 解æžå™¨ä¸­ï¼Œæˆ‘们å¯ä»¥ä
```md
my_array.each do |item|
- puts item
+ puts item
end
```
@@ -216,12 +216,13 @@ John 甚至ä¸çŸ¥é“ `go_to()` 函数是干嘛的!
在GitHubçš„ Markdown(GitHub Flavored Markdown)解æžå™¨ä¸­ï¼Œä½ å¯ä»¥ä½¿ç”¨ç‰¹æ®Šçš„语法表示代ç å—
-<pre>
-<code class="highlight">&#x60;&#x60;&#x60;ruby
+````md
+```ruby
def foobar
- puts "Hello world!"
+ puts "Hello world!"
end
-&#x60;&#x60;&#x60;</code></pre>
+```
+````
以上代ç ä¸éœ€è¦ç¼©è¿›ï¼Œè€Œä¸” GitHub 会根æ®\`\`\`åŽæŒ‡å®šçš„语言æ¥è¿›è¡Œè¯­æ³•é«˜äº®æ˜¾ç¤º
@@ -246,7 +247,6 @@ Markdown 最棒的地方就是便æ·çš„书写链接。把链接文字放在中æ‹
```md
[点我点我!](http://test.com/)
-
```
你也å¯ä»¥åœ¨å°æ‹¬å·å†…使用引å·ï¼Œä¸ºé“¾æŽ¥åŠ ä¸Šä¸€ä¸ªæ ‡é¢˜ï¼ˆtitle)
@@ -345,6 +345,7 @@ MarkdownåŒæ ·æ”¯æŒå¼•ç”¨å½¢å¼çš„链接
| æˆ‘æ˜¯å·¦å¯¹é½ | 居个中 | å³å¯¹é½ |
| æ³¨æ„ | 冒 | å· |
```
+
好å§ï¼Œå¼ºè¡Œå¯¹é½å­—符是很难的。但是,至少比下é¢è¿™ç§å†™æ³•å¥½ä¸€ç‚¹â€”—
```md
@@ -352,6 +353,7 @@ MarkdownåŒæ ·æ”¯æŒå¼•ç”¨å½¢å¼çš„链接
:-- | :-: | --:
这真的太丑了 | è¯ä¸èƒ½ | åœï¼ï¼ï¼ï¼
```
+
真的是*看ç€ä»¤äººå¤´æ™•*
diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown
index d215755c..ca08b36b 100644
--- a/zh-cn/matlab-cn.html.markdown
+++ b/zh-cn/matlab-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: Matlab
+language: MATLAB
filename: matlab-cn.m
contributors:
- ["mendozao", "http://github.com/mendozao"]
diff --git a/zh-cn/nim-cn.html.markdown b/zh-cn/nim-cn.html.markdown
index dc662b1e..fa7d8259 100644
--- a/zh-cn/nim-cn.html.markdown
+++ b/zh-cn/nim-cn.html.markdown
@@ -3,7 +3,7 @@ language: Nim
filename: learnNim-cn.nim
contributors:
- ["Jason J. Ayala P.", "http://JasonAyala.com"]
- - ["Dennis Felsing", "http://felsin9.de/nnis/"]
+ - ["Dennis Felsing", "https://dennis.felsing.org"]
translators:
- ["lzw-723", "https://github.com/lzw-723"]
lang: zh-cn
diff --git a/zh-cn/powershell-cn.html.markdown b/zh-cn/powershell-cn.html.markdown
index 6ab34e9f..875d2e33 100644
--- a/zh-cn/powershell-cn.html.markdown
+++ b/zh-cn/powershell-cn.html.markdown
@@ -13,7 +13,7 @@ PowerShell 是 Windows å¹³å°ä¸‹çš„脚本语言åŒæ—¶ä¹Ÿæ˜¯é…置管ç†æ¡†æž¶ï¼Œ
与 Bash 最大的ä¸åŒæ˜¯ä½ å¤§éƒ¨åˆ†æ“作的东西是对象而ä¸æ˜¯æ™®é€šçš„文本。
-[延伸阅读](https://technet.microsoft.com/en-us/library/bb978526.aspx)
+[延伸阅读](https://docs.microsoft.com/zh-cn/powershell/scripting/overview)
如果你ä¸ç¡®å®šä½ çš„环境,执行如下æ“作:
@@ -263,7 +263,7 @@ Get-Command ConvertTo-*,ConvertFrom-*
### 有用的东西
# æ›´æ–° PATH
-$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
+$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
# 找到 Python 的 PATH
@@ -319,7 +319,7 @@ if (-not (Test-Path $Profile)) {
尚未涉åŠ
-* WMI: Windows 管ç†è§„范 (Get-CimInstance)
+* WMI: Windows 管ç†è§„范 (Get-CimInstance)
* 多任务: Start-Job -scriptBlock {...},
* 代ç ç­¾å
* 远程 (Enter-PSSession/Exit-PSSession; Invoke-Command)
diff --git a/zh-cn/pyqt-cn.html.markdown b/zh-cn/pyqt-cn.html.markdown
index 55e5bbe3..04041c83 100644
--- a/zh-cn/pyqt-cn.html.markdown
+++ b/zh-cn/pyqt-cn.html.markdown
@@ -19,7 +19,7 @@ lang: zh-cn
```python
import sys
from PyQt4 import QtGui
-
+
def window():
# 创建应用对象
app = QtGui.QApplication(sys.argv)
@@ -44,7 +44,7 @@ if __name__ == '__main__':
为了è¿ç”¨ pyqt 中一些更高级的功能,我们需è¦å¼€å§‹å­¦ä¹ ä½¿ç”¨å…¶ä»–控件。下文演示了如何弹出对è¯æ¡†ï¼Œè¯¥å¯¹è¯æ¡†åœ¨ç”¨æˆ·ç¡®è®¤æ“作或输入信æ¯ç­‰æƒ…况下ç»å¸¸ç”¨åˆ°ã€‚
-```Python
+```python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
@@ -62,7 +62,7 @@ def window():
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
-
+
# 对è¯æ¡†çª—å£åˆ›å»ºå‡½æ•°
# 当窗å£ä¸­çš„按钮被点击时退出本程åº
def showdialog():
diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown
index a4e53c1b..127f7ad5 100644
--- a/zh-cn/python-cn.html.markdown
+++ b/zh-cn/python-cn.html.markdown
@@ -552,7 +552,7 @@ next(our_iterator) # => "three"
# 当迭代器所有元素都å–出åŽï¼Œä¼šæŠ›å‡º StopIteration
next(our_iterator) # 抛出 StopIteration
-# 我们å¯ä»¥é€šè¿‡é历还访问所有的值,实际上,for 内部实现了迭代
+# 我们还å¯ä»¥é€šè¿‡é历访问所有的值,实际上,for 内部实现了迭代
our_iterator = iter(our_iterable)
for i in our_iterator:
print(i) # ä¾æ¬¡æ‰“å° one, two, three
@@ -697,7 +697,7 @@ import math
dir(math)
# 当你的脚本文件所在的文件夹也包å«äº†ä¸€ä¸ªå为 math.py çš„ Python 文件
-# 这个 math.p 文件会被代替引入,而ä¸æ˜¯å¼•å…¥ Python 內建模å—中的 math
+# 这个 math.py 文件会被代替引入,而ä¸æ˜¯å¼•å…¥ Python 內建模å—中的 math
# 出现这个情况的原因是本地文件夹的引入优先级è¦æ¯” Python 內建库引入优先级è¦é«˜
@@ -760,7 +760,7 @@ class Human:
del self._age
# 当 Python 解释器在读å–æºæ–‡ä»¶çš„时候,就会执行文件中所有的代ç 
-# 对 __name__ 的检查å¯ä»¥ä¿è¯è¿™å—代ç åªä¼šåœ¨æ‰§è¡Œè¿™ä¸ªæ¨¡å—是ä½ç¨‹åºæƒ…况下被è¿è¡Œï¼ˆè€Œä¸æ˜¯åœ¨å¼•ç”¨æ—¶è¿è¡Œï¼‰
+# 对 __name__ 的检查å¯ä»¥ä¿è¯è¿™å—代ç åªä¼šåœ¨è¿™ä¸ªæ¨¡å—是主程åºçš„情况下被è¿è¡Œï¼ˆè€Œä¸æ˜¯åœ¨å¼•ç”¨æ—¶è¿è¡Œï¼‰
if __name__ == '__main__':
#
i = Human(name="Ian")
diff --git a/zh-cn/qt-cn.html.markdown b/zh-cn/qt-cn.html.markdown
index 8681c85b..1d24f200 100644
--- a/zh-cn/qt-cn.html.markdown
+++ b/zh-cn/qt-cn.html.markdown
@@ -1,7 +1,7 @@
---
category: tool
tool: Qt Framework
-language: c++
+language: C++
filename: learnqt-cn.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 63adab64..b0b8b58c 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -430,7 +430,7 @@ def guests(*array)
array.each { |guest| puts guest }
end
-# 结构
+# 解构
# 如果函数返回一个数组,在赋值时å¯ä»¥è¿›è¡Œæ‹†åˆ†ï¼š
def foods
@@ -449,7 +449,7 @@ end
best *ranked_competitors.first(3) #=> Winners are John, Sally, and Dingus.
-# 结构æ“作符也å¯æ”¾åœ¨å‚数里é¢
+# 解构æ“作符也å¯æ”¾åœ¨å‚数里é¢
def best(first, second, third, *others)
puts "Winners are #{first}, #{second}, and #{third}."
puts "There were #{others.count} other participants."
diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown
index b77c9c38..6bed1650 100644
--- a/zh-cn/rust-cn.html.markdown
+++ b/zh-cn/rust-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: rust
+language: Rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown
index e30041b3..cda7b864 100644
--- a/zh-cn/visualbasic-cn.html.markdown
+++ b/zh-cn/visualbasic-cn.html.markdown
@@ -8,7 +8,7 @@ lang: zh-cn
filename: learnvisualbasic-cn.vb
---
-```
+```visualbasic
Module Module1
Sub Main()
diff --git a/zh-cn/wolfram-cn.html.markdown b/zh-cn/wolfram-cn.html.markdown
index 9d6ef54f..64990234 100644
--- a/zh-cn/wolfram-cn.html.markdown
+++ b/zh-cn/wolfram-cn.html.markdown
@@ -18,7 +18,7 @@ Wolfram 语言有几个界é¢ã€‚
本例中的代ç å¯ä»¥åœ¨ä»»ä½•ç•Œé¢ä¸­è¾“入,并使用 Wolfram Workbench 进行编辑。直接加载到 Mathematica 中å¯èƒ½ä¼šå¾ˆä¸æ–¹ä¾¿ï¼Œå› ä¸ºè¯¥æ–‡ä»¶ä¸åŒ…å«å•å…ƒæ ¼æ ¼å¼åŒ–ä¿¡æ¯ï¼ˆè¿™å°†ä½¿è¯¥æ–‡ä»¶ä½œä¸ºæ–‡æœ¬é˜…读时å˜å¾—一团糟)--它å¯ä»¥è¢«æŸ¥çœ‹/编辑,但å¯èƒ½éœ€è¦ä¸€äº›è®¾ç½®ã€‚
-```mma
+```mathematica
(* 这是一个注释 *)
(* 在Mathematica中,您å¯ä»¥åˆ›å»ºä¸€ä¸ªæ–‡æœ¬å•å…ƒæ ¼ï¼Œç”¨æŽ’版好的文本和图åƒæ¥æ³¨é‡Šæ‚¨çš„代ç ï¼Œè€Œä¸æ˜¯ä½¿ç”¨è¿™äº›æ³¨é‡Š *)
diff --git a/zh-tw/elixir-tw.html.markdown b/zh-tw/elixir-tw.html.markdown
index c15f90c1..3dba95b3 100644
--- a/zh-tw/elixir-tw.html.markdown
+++ b/zh-tw/elixir-tw.html.markdown
@@ -1,5 +1,5 @@
---
-language: elixir
+language: Elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
@@ -19,10 +19,10 @@ Elixir 是一門建構在 Erlang 虛擬機上的ç¾ä»£å‡½æ•¸å¼èªžè¨€ã€‚它完å…
# 沒有多行註解的功能
# 但你å¯ä»¥é€£çºŒä½¿ç”¨å¤šå€‹å–®è¡Œ
-# 用 `iex` 來進入 elixir shell
+# 用 `iex` 來進入 Elixir shell
# 用 `elixirc` 來編譯你的模組
-# 如果你已æˆåŠŸå®‰è£ elixir 的話,這兩個命令應已在你的 path 下。
+# 如果你已æˆåŠŸå®‰è£ Elixir 的話,這兩個命令應已在你的 path 下。
## ---------------------------
## -- 基本型別
@@ -50,7 +50,7 @@ elem({1, 2, 3}, 0) #=> 1
head #=> 1
tail #=> [2,3]
-# 在 elixir ä¸­ï¼Œå°±å¦‚åŒ Erlang 裡一樣,`=` 代表的是模å¼æ¯”å°ï¼Œè€ŒéžæŒ‡æ´¾ã€‚
+# 在 Elixir ä¸­ï¼Œå°±å¦‚åŒ Erlang 裡一樣,`=` 代表的是模å¼æ¯”å°ï¼Œè€ŒéžæŒ‡æ´¾ã€‚
#
# é€™ä»£è¡¨å°‡ä½¿ç”¨å·¦æ‰‹é‚Šçš„æ¨¡å¼ (pattern) 去與å³æ‰‹é‚Šçš„值進行比å°ã€‚
#
@@ -80,7 +80,7 @@ string.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
-# `?a` 在 elixir ä¸­æœƒå›žå‚³å­—æ¯ `a` çš„ ASCII 整數
+# `?a` 在 Elixir ä¸­æœƒå›žå‚³å­—æ¯ `a` çš„ ASCII 整數
?a #=> 97
# 用 `++` 來åˆä½µä¸²åˆ—,而åˆä½µäºŒé€²ä½å‰‡è¦ç”¨ `<>`
@@ -105,7 +105,7 @@ lower..upper = 1..10 # å¯ä»¥å° range 進行模å¼æ¯”å°
5 * 2 #=> 10
10 / 2 #=> 5.0
-# 在 elixir 中, `/` é‹ç®—元永é å›žå‚³æµ®é»žæ•¸ã€‚
+# 在 Elixir 中, `/` é‹ç®—元永é å›žå‚³æµ®é»žæ•¸ã€‚
# 若需è¦å›žå‚³æ•´æ•¸çš„除法,用 `div`
div(10, 2) #=> 5
@@ -290,7 +290,7 @@ Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
-# 由於ä¸å¯è®Šç‰¹æ€§ (immutability),éžè¿´åœ¨ elixir 中扮演é‡è¦çš„角色。
+# 由於ä¸å¯è®Šç‰¹æ€§ (immutability),éžè¿´åœ¨ Elixir 中扮演é‡è¦çš„角色。
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
@@ -356,7 +356,7 @@ end
## -- 平行處ç†
## ---------------------------
-# Elixir ä¾é  actor 模å¼ä¾†é€²è¡Œå¹³è¡Œè™•ç†ã€‚在 elixir 中è¦å¯«å‡ºå¹³è¡Œè™•ç†ç¨‹å¼ï¼Œ
+# Elixir ä¾é  actor 模å¼ä¾†é€²è¡Œå¹³è¡Œè™•ç†ã€‚在 Elixir 中è¦å¯«å‡ºå¹³è¡Œè™•ç†ç¨‹å¼ï¼Œ
# åªéœ€è¦ä¸‰å€‹åŸºæœ¬è¦ç´ ï¼šå»ºç«‹è¡Œç¨‹ï¼Œç™¼é€è¨Šæ¯åŠæŽ¥æ”¶è¨Šæ¯ã€‚
# 我們用 `spawn` 函å¼ä¾†å»ºç«‹è¡Œç¨‹ï¼Œå®ƒæŽ¥æ”¶ä¸€å€‹å‡½å¼ç•¶åƒæ•¸ã€‚
diff --git a/zig.html.markdown b/zig.html.markdown
new file mode 100644
index 00000000..65fd1e6b
--- /dev/null
+++ b/zig.html.markdown
@@ -0,0 +1,981 @@
+---
+language: zig
+filename: learnzig.zig
+contributors:
+ - ["Philippe Pittoli", "https://karchnu.fr/"]
+---
+
+[Zig][ziglang] aims to be a replacement for the C programming language.
+
+**WARNING**: this document expects you to understand a few basic concepts in computer science, such as pointers, stack and heap memory, etc.
+
+**WARNING**: Zig isn't considered as ready for production. Bugs are expected.
+
+Prior knowledge of C is recommended.
+
+## Quick overview: Zig compared to C
+
+- Syntax is mostly the same, with some improvements (less ambiguity).
+- Zig introduces namespaces.
+- `try` and `catch` mechanism, which is both convenient, efficient and optional.
+- Most of the C undefined behaviors (UBs) are fixed.
+- Compared to C, raw pointers are safer to use and less likely to be needed.
+ * The type system distinguishes between a pointer to a single value, or multiple values, etc.
+ * Slices are preferred, which is a structure with a pointer and a runtime known size, which characterizes most uses of pointers in the first place.
+- Some arbitrary language limitations are removed. For example, enumerations, structures and unions can have functions.
+- Simple access to SIMD operations (basic maths on vectors).
+- Zig provides both low-level features of C and the one provided through compiler extensions.
+ For example: packed structures.
+- An extensive standard library, including data structures and algorithms.
+- Cross-compilation capability is provided by default, without any dependency.
+ Different libc are provided to ease the process.
+ Cross-compilation works from, and to, any operating system and architecture.
+
+## Zig language
+
+```zig
+//! Top-level documentation.
+
+/// Documentation comment.
+
+// Simple comment.
+```
+
+### Hello world.
+
+```zig
+// Import standard library, reachable through the "std" constant.
+const std = @import("std");
+
+// "info" now refers to the "std.log.info" function.
+const info = std.log.info;
+
+// Usual hello world.
+// syntax: [pub] fn <function-name>(<arguments>) <return-type> { <body> }
+pub fn main() void {
+ // Contrary to C functions, Zig functions have a fixed number of arguments.
+ // In C: "printf" takes any number of arguments.
+ // In Zig: std.log.info takes a format and a list of elements to print.
+ info("hello world", .{}); // .{} is an empty anonymous tuple.
+}
+```
+
+### Booleans, integers and float.
+
+```zig
+// Booleans.
+// Keywords are preferred to operators for boolean operations.
+print("{}\n{}\n{}\n", .{
+ true and false,
+ true or false,
+ !true,
+});
+
+// Integers.
+const one_plus_one: i32 = 1 + 1;
+print("1 + 1 = {}\n", .{one_plus_one}); // 2
+
+// Floats.
+const seven_div_three: f32 = 7.0 / 3.0;
+print("7.0 / 3.0 = {}\n", .{seven_div_three}); // 2.33333325e+00
+
+// Integers have arbitrary value lengths.
+var myvar: u10 = 5; // 10-bit unsigned integer
+// Useful for example to read network packets, or complex binary formats.
+
+// Number representation is greatly improved compared to C.
+const one_billion = 1_000_000_000; // Decimal.
+const binary_mask = 0b1_1111_1111; // Binary. Ex: network mask.
+const permissions = 0o7_5_5; // Octal. Ex: Unix permissions.
+const big_address = 0xFF80_0000_0000_0000; // Hexa. Ex: IPv6 address.
+
+
+// Overflow operators: tell the compiler when it's okay to overflow.
+var i: u8 = 0; // "i" is an unsigned 8-bit integer
+i -= 1; // runtime overflow error (unsigned value always are positive)
+i -%= 1; // okay (wrapping operator), i == 255
+
+// Saturation operators: values will stick to their lower and upper bounds.
+var i: u8 = 200; // "i" is an unsigned 8-bit integer (values: from 0 to 255)
+i +| 100 == 255 // u8: won't go higher than 255
+i -| 300 == 0 // unsigned, won't go lower than 0
+i *| 2 == 255 // u8: won't go higher than 255
+i <<| 8 == 255 // u8: won't go higher than 255
+```
+
+### Arrays.
+
+```zig
+// An array is a well-defined structure with a length attribute (len).
+
+// 5-byte array with undefined content (stack garbage).
+var array1: [5]u8 = undefined;
+
+// 5-byte array with defined content.
+var array2 = [_]u8{ 1, 2, 3, 4, 5 };
+// [_] means the compiler knows the length at compile-time.
+
+// 1000-byte array with defined content (0).
+var array3 = [_]u8{0} ** 1000;
+
+// Another 1000-byte array with defined content.
+// The content is provided by the "foo" function, called at compile-time and
+// allows complex initializations.
+var array4 = [_]u8{foo()} ** 1000;
+
+// In any case, array.len gives the length of the array,
+// array1.len and array2.len produce 5, array3.len and array4.len produce 1000.
+
+
+// Modifying and accessing arrays content.
+
+// Array of 10 32-bit undefined integers.
+var some_integers: [10]i32 = undefined;
+
+some_integers[0] = 30; // first element of the array is now 30
+
+var x = some_integers[0]; // "x" now equals to 30, its type is inferred.
+var y = some_integers[1]; // Second element of the array isn't defined.
+ // "y" got a stack garbage value (no runtime error).
+
+// Array of 10 32-bit undefined integers.
+var some_integers: [10]i32 = undefined;
+
+var z = some_integers[20]; // index > array size, compilation error.
+
+// At runtime, we loop over the elements of "some_integers" with an index.
+// Index i = 20, then we try:
+try some_integers[i]; // Runtime error 'index out of bounds'.
+ // "try" keyword is necessary when accessing an array with
+ // an index, since there is a potential runtime error.
+ // More on that later.
+```
+
+### Multidimensional arrays.
+
+```zig
+const mat4x4 = [4][4]f32{
+ [_]f32{ 1.0, 0.0, 0.0, 0.0 },
+ [_]f32{ 0.0, 1.0, 0.0, 1.0 },
+ [_]f32{ 0.0, 0.0, 1.0, 0.0 },
+ [_]f32{ 0.0, 0.0, 0.0, 1.0 },
+};
+
+// Access the 2D array then the inner array through indexes.
+try expect(mat4x4[1][1] == 1.0);
+
+// Here we iterate with for loops.
+for (mat4x4) |row, row_index| {
+ for (row) |cell, column_index| {
+ // ...
+ }
+}
+```
+
+### Strings.
+
+```zig
+// Simple string constant.
+const greetings = "hello";
+// ... which is equivalent to:
+const greetings: *const [5:0]u8 = "hello";
+// In words: "greetings" is a constant value, a pointer on a constant array of 5
+// elements (8-bit unsigned integers), with an extra '0' at the end.
+// The extra "0" is called a "sentinel value".
+
+print("string: {s}\n", .{greetings});
+
+// This represents rather faithfully C strings. Although, Zig strings are
+// structures, no need for "strlen" to compute their size.
+// greetings.len == 5
+```
+
+### Slices.
+
+```zig
+// A slice is a pointer and a size, an array without compile-time known size.
+// Slices have runtime out-of-band verifications.
+
+const array = [_]u8{1,2,3,4,5}; // [_] = array with compile-time known size.
+const slice = array[0..array.len]; // "slice" represents the whole array.
+ // slice[10] gives a runtime error.
+```
+
+### Pointers.
+
+```zig
+// Pointer on a value can be created with "&".
+const x: i32 = 1;
+const pointer: *i32 = &x; // "pointer" is a pointer on the i32 var "x".
+print("1 = {}, {}\n", .{x, pointer});
+
+// Pointer values are accessed and modified with ".*".
+if (pointer.* == 1) {
+ print("x value == {}\n", .{pointer.*});
+}
+
+// ".?" is a shortcut for "orelse unreachable".
+const foo = pointer.?; // Get the pointed value, otherwise crash.
+```
+
+### Optional values (?<type>).
+
+```zig
+// An optional is a value than can be of any type or null.
+
+// Example: "optional_value" can either be "null" or an unsigned 32-bit integer.
+var optional_value: ?u32 = null; // optional_value == null
+optional_value = 42; // optional_value != null
+
+// "some_function" returns ?u32
+var x = some_function();
+if (x) |value| {
+ // In case "some_function" returned a value.
+ // Do something with 'value'.
+}
+```
+
+### Errors.
+
+```zig
+// Zig provides an unified way to express errors.
+
+// Errors are defined in error enumerations, example:
+const Error = error {
+ WatchingAnyNetflixTVShow,
+ BeOnTwitter,
+};
+
+// Normal enumerations are expressed the same way, but with "enum" keyword.
+const SuccessStory = enum {
+ DoingSport,
+ ReadABook,
+};
+
+
+// Error union (!).
+// Either the value "mylife" is an an error or a normal value.
+var mylife: Error!SuccessStory = Error.BeOnTwitter;
+// mylife is an error. Sad.
+
+mylife = SuccessStory.ReadABook;
+// Now mylife is an enum.
+
+
+// Zig ships with many pre-defined errors. Example:
+const value: anyerror!u32 = error.Broken;
+
+
+// Handling errors.
+
+// Some error examples.
+const Error = error {
+ UnExpected,
+ Authentication,
+};
+
+// "some_function" can either return an "Error" or an integer.
+fn some_function() Error!u8 {
+ return Error.UnExpected; // It returns an error.
+}
+
+// Errors can be "catch" without intermediate variable.
+var value = some_function() catch |err| switch(err) {
+ Error.UnExpected => return err, // Returns the error.
+ Error.Authentication => unreachable, // Not expected. Crashes the program.
+ else => unreachable,
+};
+
+// An error can be "catch" without giving it a name.
+const unwrapped = some_function() catch 1234; // "unwrapped" = 1234
+
+// "try" is a very handy shortcut for "catch |err| return err".
+var value = try some_function();
+// If "some_function" fails, the current function stops and returns the error.
+// "value" can only have a valid value, the error already is handled with "try".
+```
+
+### Control flow.
+
+```zig
+// Conditional branching.
+
+if (condition) {
+ ...
+}
+else {
+ ...
+}
+
+// Ternary.
+var value = if (condition) x else y;
+
+// Shortcut for "if (x) x else 0"
+var value = x orelse 0;
+
+// If "a" is an optional, which may contain a value.
+if (a) |value| {
+ print("value: {}\n", .{value});
+}
+else {
+ print("'a' is null\n", .{});
+}
+
+// Get a pointer on the value (if it exists).
+if (a) |*value| { value.* += 1; }
+
+
+// Loops.
+
+// Syntax examples:
+// while (condition) statement
+// while (condition) : (end-of-iteration-statement) statement
+//
+// for (iterable) statement
+// for (iterable) |capture| statement
+// for (iterable) statement else statement
+
+// Note: loops work the same way over arrays or slices.
+
+// Simple "while" loop.
+while (i < 10) { i += 1; }
+
+// While loop with a "continue expression"
+// (expression executed as the last expression of the loop).
+while (i < 10) : (i += 1) { ... }
+// Same, with a more complex continue expression (block of code).
+while (i * j < 2000) : ({ i *= 2; j *= 3; }) { ... }
+
+// To iterate over a portion of a slice, reslice.
+for (items[0..1]) |value| { sum += value; }
+
+// Loop over every item of an array (or slice).
+for (items) |value| { sum += value; }
+
+// Iterate and get pointers on values instead of copies.
+for (items) |*value| { value.* += 1; }
+
+// Iterate with an index.
+for (items) |value, i| { print("val[{}] = {}\n", .{i, value}); }
+
+// Iterate with pointer and index.
+for (items) |*value, i| { print("val[{}] = {}\n", .{i, value}); value.* += 1; }
+
+
+// Break and continue are supported.
+for (items) |value| {
+ if (value == 0) { continue; }
+ if (value >= 10) { break; }
+ // ...
+}
+
+// For loops can also be used as expressions.
+// Similar to while loops, when you break from a for loop,
+// the else branch is not evaluated.
+var sum: i32 = 0;
+// The "for" loop has to provide a value, which will be the "else" value.
+const result = for (items) |value| {
+ if (value != null) {
+ sum += value.?; // "result" will be the last "sum" value.
+ }
+} else 0; // Last value.
+```
+
+### Labels.
+
+```zig
+// Labels are a way to name an instruction, a location in the code.
+// Labels can be used to "continue" or "break" in a nested loop.
+outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
+ for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
+ count += 1;
+ continue :outer; // "continue" for the first loop.
+ }
+} // count = 8
+outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
+ for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
+ count += 1;
+ break :outer; // "break" for the first loop.
+ }
+} // count = 1
+
+
+// Labels can also be used to return a value from a block.
+var y: i32 = 5;
+const x = blk: {
+ y += 1;
+ break :blk y; // Now "x" equals 6.
+};
+// Relevant in cases like "for else" expression (explained in the following).
+
+// For loops can be used as expressions.
+// When you break from a for loop, the else branch is not evaluated.
+// WARNING: counter-intuitive.
+// The "for" loop will run, then the "else" block will run.
+// The "else" keyword has to be followed by the value to give to "result".
+// See later for another form.
+var sum: u8 = 0;
+const result = for (items) |value| {
+ sum += value;
+} else 8; // result = 8
+
+// In this case, the "else" keyword is followed by a value, too.
+// However, the syntax is different: it is labeled.
+// Instead of a value, there is a label followed by a block of code, which
+// allows to do stuff before returning the value (see the "break" invocation).
+const result = for (items) |value| { // First: loop.
+ sum += value;
+} else blk: { // Second: "else" block.
+ std.log.info("executed AFTER the loop!", .{});
+ break :blk sum; // The "sum" value will replace the label "blk".
+};
+```
+
+### Switch.
+
+```zig
+// As a switch in C, but slightly more advanced.
+// Syntax:
+// switch (value) {
+// pattern => expression,
+// pattern => expression,
+// else => expression
+// };
+
+// A switch only checking for simple values.
+var x = switch(value) {
+ Error.UnExpected => return err,
+ Error.Authentication => unreachable,
+ else => unreachable,
+};
+
+// A slightly more advanced switch, accepting a range of values:
+const foo: i32 = 0;
+const bar = switch (foo) {
+ 0 => "zero",
+ 1...std.math.maxInt(i32) => "positive",
+ else => "negative",
+};
+```
+
+### Structures.
+
+```zig
+// Structure containing a single value.
+const Full = struct {
+ number: u16,
+};
+
+// Packed structure, with guaranteed in-memory layout.
+const Divided = packed struct {
+ half1: u8,
+ quarter3: u4,
+ quarter4: u4,
+};
+
+// Point is a constant representing a structure containing two u32, "x" and "y".
+// "x" has a default value, which wasn't possible in C.
+const Point = struct {
+ x: u32 = 1, // default value
+ y: u32,
+};
+
+// Variable "p" is a new Point, with x = 1 (default value) and y = 2.
+var p = Point{ .y = 2 };
+
+// Fields are accessed as usual with the dot notation: variable.field.
+print("p.x: {}\n", .{p.x}); // 1
+print("p.y: {}\n", .{p.y}); // 2
+
+
+// A structure can also contain public constants and functions.
+const Point = struct {
+ pub const some_constant = 30;
+
+ x: u32,
+ y: u32,
+
+ // This function "init" creates a Point and returns it.
+ pub fn init() Point {
+ return Point{ .x = 0, .y = 0 };
+ }
+};
+
+
+// How to access a structure public constant.
+// The value isn't accessed from an "instance" of the structure, but from the
+// constant representing the structure definition (Point).
+print("constant: {}\n", .{Point.some_constant});
+
+// Having an "init" function is rather idiomatic in the standard library.
+// More on that later.
+var p = Point.init();
+print("p.x: {}\n", .{p.x}); // p.x = 0
+print("p.y: {}\n", .{p.y}); // p.y = 0
+
+
+// Structures often have functions to modify their state, similar to
+// object-oriented programming.
+const Point = struct {
+ const Self = @This(); // Refers to its own type (later called "Point").
+
+ x: u32,
+ y: u32,
+
+ // Take a look at the signature. First argument is of type *Self: "self" is
+ // a pointer on the instance of the structure.
+ // This allows the same "dot" notation as in OOP, like "instance.set(x,y)".
+ // See the following example.
+ pub fn set(self: *Self, x: u32, y: u32) void {
+ self.x = x;
+ self.y = y;
+ }
+
+ // Again, look at the signature. First argument is of type Self (not *Self),
+ // this isn't a pointer. In this case, "self" refers to the instance of the
+ // structure, but can't be modified.
+ pub fn getx(self: Self) u32 {
+ return self.x;
+ }
+
+ // PS: two previous functions may be somewhat useless.
+ // Attributes can be changed directly, no need for accessor functions.
+ // It was just an example.
+};
+
+// Let's use the previous structure.
+var p = Point{ .x = 0, .y = 0 }; // "p" variable is a Point.
+
+p.set(10, 30); // x and y attributes of "p" are modified via the "set" function.
+print("p.x: {}\n", .{p.x}); // 10
+print("p.y: {}\n", .{p.y}); // 30
+
+// In C:
+// 1. We would have written something like: point_set(p, 10, 30).
+// 2. Since all functions are in the same namespace, it would have been
+// very cumbersome to create functions with different names for different
+// structures. Many long names, painful to read.
+//
+// In Zig, structures provide namespaces for their own functions.
+// Different structures can have the same names for their functions,
+// which brings clarity.
+```
+
+### Tuples.
+
+```zig
+// A tuple is a list of elements, possibly of different types.
+
+const foo = .{ "hello", true, 42 };
+// foo.len == 3
+```
+
+### Enumerations.
+
+```zig
+const Type = enum { ok, not_ok };
+
+const CardinalDirections = enum { North, South, East, West };
+const direction: CardinalDirections = .North;
+const x = switch (direction) {
+ // shorthand for CardinalDirections.North
+ .North => true,
+ else => false
+};
+
+// Switch statements need exhaustiveness.
+// WARNING: won't compile. East and West are missing.
+const x = switch (direction) {
+ .North => true,
+ .South => true,
+};
+
+
+// Switch statements need exhaustiveness.
+// Won't compile: East and West are missing.
+const x = switch (direction) {
+ .North => true,
+ .South => true,
+ .East, // Its value is the same as the following pattern: false.
+ .West => false,
+};
+
+
+// Enumerations are like structures: they can have functions.
+```
+
+### Unions.
+
+```zig
+const Bar = union {
+ boolean: bool,
+ int: i16,
+ float: f32,
+};
+
+// Both syntaxes are equivalent.
+const foo = Bar{ .int = 42 };
+const foo: Bar = .{ .int = 42 };
+
+// Unions, like enumerations and structures, can have functions.
+```
+
+### Tagged unions.
+
+```zig
+// Unions can be declared with an enum tag type, allowing them to be used in
+// switch expressions.
+
+const MaybeEnum = enum {
+ success,
+ failure,
+};
+
+const Maybe = union(MaybeEnum) {
+ success: u8,
+ failure: []const u8,
+};
+
+// First value: success!
+const yay = Maybe{ .success = 42 };
+switch (yay) {
+ .success => |value| std.log.info("success: {}", .{value}),
+ .failure => |err_msg| std.log.info("failure: {}", .{err_msg}),
+}
+
+// Second value: failure! :(
+const nay = Maybe{ .failure = "I was too lazy" };
+switch (nay) {
+ .success => |value| std.log.info("success: {}", .{value}),
+ .failure => |err_msg| std.log.info("failure: {}", .{err_msg}),
+}
+```
+
+### Defer and errdefer.
+
+```zig
+// Make sure that an action (single instruction or block of code) is executed
+// before the end of the scope (function, block of code).
+// Even on error, that action will be executed.
+// Useful for memory allocations, and resource management in general.
+
+pub fn main() void {
+ // Should be executed at the end of the function.
+ defer print("third!\n", .{});
+
+ {
+ // Last element of its scope: will be executed right away.
+ defer print("first!\n", .{});
+ }
+
+ print("second!\n", .{});
+}
+
+fn hello_world() void {
+ defer print("end of function\n", .{}); // after "hello world!"
+
+ print("hello world!\n", .{});
+}
+
+// errdefer executes the instruction (or block of code) only on error.
+fn second_hello_world() !void {
+ errdefer print("2. something went wrong!\n", .{}); // if "foo" fails.
+ defer print("1. second hello world\n", .{}); // executed after "foo"
+
+ try foo();
+}
+// Defer statements can be seen as stacked: first one is executed last.
+```
+
+### Memory allocators.
+Memory isn't managed directly in the standard library, instead an "allocator" is asked every time an operation on memory is required.
+Thus, the standard library lets developers handle memory as they need, through structures called "allocators", handling all memory operations.
+
+**NOTE**: the choice of the allocator isn't in the scope of this document.
+A whole book could be written about it.
+However, here are some examples, to get an idea of what you can expect:
+- `page_allocator`.
+ Allocate a whole page of memory each time we ask for some memory.
+ Very simple, very dumb, very wasteful.
+- `GeneralPurposeAllocator`.
+ Get some memory first and manage some buckets of memory in order to
+ reduce the number of allocations.
+ A bit complex. Can be combined with other allocators.
+ Can detect leaks and provide useful information to find them.
+- `FixedBufferAllocator`.
+ Use a fixed buffer to get its memory, don't ask memory to the kernel.
+ Very simple, limited and wasteful (can't deallocate), but very fast.
+- `ArenaAllocator`.
+ Allow to free all allocated memory at once.
+ To use in combinations with another allocator.
+ Very simple way of avoiding leaks.
+
+A first example.
+
+```zig
+// "!void" means the function doesn't return any value except for errors.
+// In this case we try to allocate memory, and this may fail.
+fn foo() !void {
+ // In this example we use a page allocator.
+ var allocator = std.heap.page_allocator;
+
+ // "list" is an ArrayList of 8-bit unsigned integers.
+ // An ArrayList is a contiguous, growable list of elements in memory.
+ var list = try ArrayList(u8).initAllocated(allocator);
+ defer list.deinit(); // Free the memory at the end of the scope. Can't leak.
+ // "defer" allows to express memory release right after its allocation,
+ // regardless of the complexity of the function (loops, conditions, etc.).
+
+ list.add(5); // Some memory is allocated here, with the provided allocator.
+
+ for (list.items) |item| {
+ std.debug.print("item: {}\n", .{item});
+ }
+}
+```
+
+### Memory allocation combined with error management and defer.
+
+```zig
+fn some_memory_allocation_example() !void {
+ // Memory allocation may fail, so we "try" to allocate the memory and
+ // in case there is an error, the current function returns it.
+ var buf = try page_allocator.alloc(u8, 10);
+ // Defer memory release right after the allocation.
+ // Will happen even if an error occurs.
+ defer page_allocator.free(buf);
+
+ // Second allocation.
+ // In case of a failure, the first allocation is correctly released.
+ var buf2 = try page_allocator.alloc(u8, 10);
+ defer page_allocator.free(buf2);
+
+ // In case of failure, both previous allocations are correctly deallocated.
+ try foo();
+ try bar();
+
+ // ...
+}
+```
+
+### Memory allocators: a taste of the standard library.
+
+```zig
+// Allocators: 4 main functions to know
+// single_value = create (type)
+// destroy (single_value)
+// slice = alloc (type, size)
+// free (slice)
+
+// Page Allocator
+fn page_allocator_fn() !void {
+ var slice = try std.heap.page_allocator.alloc(u8, 3);
+ defer std.heap.page_allocator.free(slice);
+
+ // playing_with_a_slice(slice);
+}
+
+// GeneralPurposeAllocator
+fn general_purpose_allocator_fn() !void {
+ // GeneralPurposeAllocator has to be configured.
+ // In this case, we want to track down memory leaks.
+ const config = .{.safety = true};
+ var gpa = std.heap.GeneralPurposeAllocator(config){};
+ defer _ = gpa.deinit();
+
+ const allocator = gpa.allocator();
+
+ var slice = try allocator.alloc(u8, 3);
+ defer allocator.free(slice);
+
+ // playing_with_a_slice(slice);
+}
+
+// FixedBufferAllocator
+fn fixed_buffer_allocator_fn() !void {
+ var buffer = [_]u8{0} ** 1000; // array of 1000 u8, all initialized at zero.
+ var fba = std.heap.FixedBufferAllocator.init(buffer[0..]);
+ // Side note: buffer[0..] is a way to create a slice from an array.
+ // Since the function takes a slice and not an array, this makes
+ // the type system happy.
+
+ var allocator = fba.allocator();
+
+ var slice = try allocator.alloc(u8, 3);
+ // No need for "free", memory cannot be freed with a fixed buffer allocator.
+ // defer allocator.free(slice);
+
+ // playing_with_a_slice(slice);
+}
+
+// ArenaAllocator
+fn arena_allocator_fn() !void {
+ // Reminder: arena doesn't allocate memory, it uses an inner allocator.
+ // In this case, we combine the arena allocator with the page allocator.
+ var arena = std.heap.arena_allocator.init(std.heap.page_allocator);
+ defer arena.deinit(); // end of function = all allocations are freed.
+
+ var allocator = arena.allocator();
+
+ const slice = try allocator.alloc(u8, 3);
+ // No need for "free", memory will be freed anyway.
+
+ // playing_with_a_slice(slice);
+}
+
+
+// Combining the general purpose and arena allocators. Both are very useful,
+// and their combinations should be in everyone's favorite cookbook.
+fn gpa_arena_allocator_fn() !void {
+ const config = .{.safety = true};
+ var gpa = std.heap.GeneralPurposeAllocator(config){};
+ defer _ = gpa.deinit();
+
+ const gpa_allocator = gpa.allocator();
+
+ var arena = arena_allocator.init(gpa_allocator);
+ defer arena.deinit();
+
+ const allocator = arena.allocator();
+
+ var slice = try allocator.alloc(u8, 3);
+ defer allocator.free(slice);
+
+ // playing_with_a_slice(slice);
+}
+```
+
+### Comptime.
+
+```zig
+// Comptime is a way to avoid the pre-processor.
+// The idea is simple: run code at compilation.
+
+inline fn max(comptime T: type, a: T, b: T) T {
+ return if (a > b) a else b;
+}
+
+var res = max(u64, 1, 2);
+var res = max(f32, 10.50, 32.19);
+
+
+// Comptime: creating generic structures.
+
+fn List(comptime T: type) type {
+ return struct {
+ items: []T,
+
+ fn init() ... { ... }
+ fn deinit() ... { ... }
+ fn do() ... { ... }
+ };
+}
+
+const MyList = List(u8);
+
+
+// use
+var list = MyList{
+ .items = ... // memory allocation
+};
+
+list.items[0] = 10;
+```
+
+### Conditional compilation.
+
+```zig
+const available_os = enum { OpenBSD, Linux };
+const myos = available_os.OpenBSD;
+
+
+// The following switch is based on a constant value.
+// This means that the only possible outcome is known at compile-time.
+// Thus, there is no need to build the rest of the possibilities.
+// Similar to the "#ifdef" in C, but without requiring a pre-processor.
+const string = switch (myos) {
+ .OpenBSD => "OpenBSD is awesome!",
+ .Linux => "Linux rocks!",
+};
+
+// Also works in this case.
+const myprint = switch(myos) {
+ .OpenBSD => std.debug.print,
+ .Linux => std.log.info,
+}
+```
+
+### Testing our functions.
+
+```zig
+const std = @import("std");
+const expect = std.testing.expect;
+
+// Function to test.
+pub fn some_function() bool {
+ return true;
+}
+
+// This "test" block can be run with "zig test".
+// It will test the function at compile-time.
+test "returns true" {
+ expect(false == some_function());
+}
+```
+
+### Compiler built-ins.
+The compiler has special functions called "built-ins", starting with an "@".
+There are more than a hundred built-ins, allowing very low-level stuff:
+- compile-time errors, logging, verifications
+- type coercion and conversion, even in an unsafe way
+- alignment management
+- memory tricks (such as getting the byte offset of a field in a struct)
+- calling functions at compile-time
+- including C headers to transparently call C functions
+- atomic operations
+- embed files into the executable (@embedFile)
+- frame manipulations (for async functions, for example)
+- etc.
+
+Example: enums aren't integers, they have to be converted with a built-in.
+
+```zig
+const Value = enum { zero, stuff, blah };
+if (@enumToInt(Value.zero) == 0) { ... }
+if (@enumToInt(Value.stuff) == 1) { ... }
+if (@enumToInt(Value.blah) == 2) { ... }
+```
+
+### A few "not yourself in the foot" measures in the Zig language.
+
+- Namespaces: name conflicts are easily avoided.
+ In practice, that means a unified API between different structures (data types).
+- Enumerations aren't integers. Comparing an enumeration to an integer requires a conversion.
+- Explicit casts, coercion exists but is limited.
+ Types are slightly more enforced than in C, just a taste:
+ Pointers aren't integers, explicit conversion is necessary.
+ You won't lose precision by accident, implicit coercions are only authorized in cases where no precision can be lost.
+ Unions cannot be reinterpreted (in a union with an integer and a float, one cannot take a value for another by accident).
+ Etc.
+- Removing most of the C undefined behaviors (UBs), and when the compiler encounters one, it stops.
+- Slice and Array structures are preferred to pointers.
+ Types enforced by the compiler are less prone to errors than pointer manipulations.
+- Numerical overflows produce an error, unless explicitly accepted using wrapping operators.
+- `try` and `catch` mechanism.
+ It's both handy, trivially implemented (simple error enumeration), and it takes almost no space nor computation time.
+- Unused variables are considered to be errors by the compiler.
+- Many pointer types exist in order to represent what is pointed to.
+ Example: is this a single value or an array, is the length known, etc.
+- Structures need a value for their attributes, and it is still possible to give an undefined value (stack garbage), but at least it is explicitly undefined.
+
+
+## Further Reading
+
+For a start, some concepts are presented on [zig.guide][zigguide].
+
+The [official website][zigdoc] provides the reference documentation of the language. The standard library [has its own documentation][zigstd].
+
+[ziglang]: https://ziglang.org
+[zigguide]: https://zig.guide/
+[zigdoc]: https://ziglang.org/documentation/
+[zigstd]: https://ziglang.org/documentation/master/std/