summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--asymptotic-notation.html.markdown4
-rw-r--r--common-lisp.html.markdown2
-rw-r--r--cs-cz/markdown.html.markdown2
-rw-r--r--cypher.html.markdown34
-rw-r--r--es-es/markdown-es.html.markdown2
-rw-r--r--es-es/objective-c-es.html.markdown2
-rw-r--r--es-es/visualbasic-es.html.markdown2
-rw-r--r--fi-fi/markdown-fi.html.markdown2
-rw-r--r--fr-fr/jquery-fr.html.markdown2
-rw-r--r--id-id/markdown.html.markdown2
-rw-r--r--it-it/markdown.html.markdown2
-rw-r--r--julia.html.markdown590
-rw-r--r--ko-kr/markdown-kr.html.markdown2
-rw-r--r--markdown.html.markdown2
-rw-r--r--mips.html.markdown366
-rw-r--r--nl-nl/markdown-nl.html.markdown2
-rw-r--r--pt-br/common-lisp-pt.html.markdown2
-rw-r--r--pt-br/markdown-pt.html.markdown2
-rw-r--r--pt-br/visualbasic-pt.html.markdown2
-rw-r--r--ru-ru/markdown-ru.html.markdown2
-rwxr-xr-xtoml.html.markdown2
-rw-r--r--tr-tr/markdown-tr.html.markdown2
-rw-r--r--uk-ua/python-ua.html.markdown818
-rw-r--r--visualbasic.html.markdown2
-rw-r--r--zh-cn/c-cn.html.markdown2
-rw-r--r--zh-cn/visualbasic-cn.html.markdown2
26 files changed, 1518 insertions, 336 deletions
diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown
index 6a6df968..a1dfe9e1 100644
--- a/asymptotic-notation.html.markdown
+++ b/asymptotic-notation.html.markdown
@@ -155,7 +155,7 @@ Small-o, commonly written as **o**, is an Asymptotic Notation to denote the
upper bound (that is not asymptotically tight) on the growth rate of runtime
of an algorithm.
-`f(n)` is o(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
+`f(n)` is o(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of O-notation and o-notation are similar. The main difference
@@ -168,7 +168,7 @@ Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote
the lower bound (that is not asymptotically tight) on the growth rate of
runtime of an algorithm.
-`f(n)` is ω(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
+`f(n)` is ω(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of Ω-notation and ω-notation are similar. The main difference
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index e2cf62fb..76e7735b 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -16,7 +16,7 @@ popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book ab
-```common-lisp
+```lisp
;;;-----------------------------------------------------------------------------
;;; 0. Syntax
diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown
index 568e4343..35becf94 100644
--- a/cs-cz/markdown.html.markdown
+++ b/cs-cz/markdown.html.markdown
@@ -13,7 +13,7 @@ Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce či
a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha
dalších formátů)
-```markdown
+```md
<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v
diff --git a/cypher.html.markdown b/cypher.html.markdown
index b7be544a..acd44733 100644
--- a/cypher.html.markdown
+++ b/cypher.html.markdown
@@ -16,19 +16,19 @@ Nodes
**Represents a record in a graph.**
-```()```
+`()`
It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query.
-```(n)```
+`(n)`
It's a *node* referred by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase.
-```(p:Person)```
+`(p:Person)`
You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase.
-```(p:Person:Manager)```
+`(p:Person:Manager)`
A node can have many *labels*.
-```(p:Person {name : 'Théo Gauchoux', age : 22})```
+`(p:Person {name : 'Théo Gauchoux', age : 22})`
A node can have some *properties*, here **name** and **age**. It begins with lowercase and uses camelCase.
The types allowed in properties :
@@ -40,7 +40,7 @@ The types allowed in properties :
*Warning : there isn't datetime property in Cypher ! You can use String with a specific pattern or a Numeric from a specific date.*
-```p.name```
+`p.name`
You can access to a property with the dot style.
@@ -49,16 +49,16 @@ Relationships (or Edges)
**Connects two nodes**
-```[:KNOWS]```
+`[:KNOWS]`
It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE.
-```[k:KNOWS]```
+`[k:KNOWS]`
The same *relationship*, referred by the variable **k**, reusable in the query, but it's not necessary.
-```[k:KNOWS {since:2017}]```
+`[k:KNOWS {since:2017}]`
The same *relationship*, with *properties* (like *node*), here **since**.
-```[k:KNOWS*..4]```
+`[k:KNOWS*..4]`
It's a structural information to use in a *path* (seen later). Here, **\*..4** says "Match the pattern, with the relationship **k** which be repeated between 1 and 4 times.
@@ -67,16 +67,16 @@ Paths
**The way to mix nodes and relationships.**
-```(a:Person)-[:KNOWS]-(b:Person)```
+`(a:Person)-[:KNOWS]-(b:Person)`
A path describing that **a** and **b** know each other.
-```(a:Person)-[:MANAGES]->(b:Person)```
+`(a:Person)-[:MANAGES]->(b:Person)`
A path can be directed. This path describes that **a** is the manager of **b**.
-```(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)```
+`(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)`
You can chain multiple relationships. This path describes the friend of a friend.
-```(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)```
+`(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)`
A chain can also be directed. This path describes that **a** is the boss of **b** and the big boss of **c**.
Patterns often used (from Neo4j doc) :
@@ -230,13 +230,13 @@ DELETE n, r
Other useful clauses
---
-```PROFILE```
+`PROFILE`
Before a query, show the execution plan of it.
-```COUNT(e)```
+`COUNT(e)`
Count entities (nodes or relationships) matching **e**.
-```LIMIT x```
+`LIMIT x`
Limit the result to the x first results.
diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown
index 0505b4cb..e23a94ea 100644
--- a/es-es/markdown-es.html.markdown
+++ b/es-es/markdown-es.html.markdown
@@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también).
¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
-```markdown
+```md
<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
válido, eso significa que podemos usar elementos HTML en Markdown como, por
ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún
diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown
index bdbce524..26cd14d9 100644
--- a/es-es/objective-c-es.html.markdown
+++ b/es-es/objective-c-es.html.markdown
@@ -13,7 +13,7 @@ Objective C es el lenguaje de programación principal utilizado por Apple para l
Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk".
-```objective_c
+```objectivec
// Los comentarios de una sola línea inician con //
/*
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
index c7f581c0..ca00626b 100644
--- a/es-es/visualbasic-es.html.markdown
+++ b/es-es/visualbasic-es.html.markdown
@@ -10,7 +10,7 @@ filename: learnvisualbasic-es.vb
lang: es-es
---
-```vb
+```
Module Module1
Sub Main()
diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown
index c5ee52b0..defc7100 100644
--- a/fi-fi/markdown-fi.html.markdown
+++ b/fi-fi/markdown-fi.html.markdown
@@ -10,7 +10,7 @@ lang: fi-fi
John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi).
-```markdown
+```md
<!-- Jokainen HTML-tiedosto on pätevää Markdownia. Tämä tarkoittaa että voimme
käyttää HTML-elementtejä Markdownissa, kuten kommentteja, ilman että markdown
-jäsennin vaikuttaa niihin. Tästä johtuen et voi kuitenkaan käyttää markdownia
diff --git a/fr-fr/jquery-fr.html.markdown b/fr-fr/jquery-fr.html.markdown
index 1842e02b..aeddbd53 100644
--- a/fr-fr/jquery-fr.html.markdown
+++ b/fr-fr/jquery-fr.html.markdown
@@ -138,5 +138,5 @@ $('p').each(function() {
});
-``
+```
diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown
index 06ad1092..1ff1963b 100644
--- a/id-id/markdown.html.markdown
+++ b/id-id/markdown.html.markdown
@@ -13,7 +13,7 @@ Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax
Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request!
-```markdown
+```md
<!-- Markdown adalah superset dari HTML, jadi setiap berkas HTML adalah markdown yang
valid, ini berarti kita dapat menggunakan elemen HTML dalam markdown, seperti elemen
komentar, dan ia tidak akan terpengaruh parser markdown. Namun, jika Anda membuat
diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown
index 44801747..11da81ec 100644
--- a/it-it/markdown.html.markdown
+++ b/it-it/markdown.html.markdown
@@ -28,7 +28,7 @@ Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida ce
## Elementi HTML
Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido.
-```markdown
+```md
<!-- Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti,
e questi non saranno modificati dal parser di Markdown. State attenti però,
se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi
diff --git a/julia.html.markdown b/julia.html.markdown
index a30871eb..891a0a00 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -2,17 +2,17 @@
language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
- - ["Pranit Bauva", "http://github.com/pranitbauva1997"]
- - ["Daniel YC Lin", "http://github.com/dlintw"]
+ - ["Pranit Bauva", "https://github.com/pranitbauva1997"]
+ - ["Daniel YC Lin", "https://github.com/dlintw"]
filename: learnjulia.jl
---
Julia is a new homoiconic functional language focused on technical computing.
While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python.
-This is based on Julia 0.6.4
+This is based on Julia 1.0.0
-```ruby
+```julia
# Single line comments start with a hash (pound) symbol.
#= Multiline comments can be written
@@ -27,38 +27,38 @@ This is based on Julia 0.6.4
# Everything in Julia is an expression.
# There are several basic types of numbers.
-3 # => 3 (Int64)
-3.2 # => 3.2 (Float64)
-2 + 1im # => 2 + 1im (Complex{Int64})
-2//3 # => 2//3 (Rational{Int64})
+3 # => 3 (Int64)
+3.2 # => 3.2 (Float64)
+2 + 1im # => 2 + 1im (Complex{Int64})
+2 // 3 # => 2 // 3 (Rational{Int64})
# All of the normal infix operators are available.
-1 + 1 # => 2
-8 - 1 # => 7
-10 * 2 # => 20
-35 / 5 # => 7.0
-5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float
-div(5, 2) # => 2 # for a truncated result, use div
-5 \ 35 # => 7.0
-2 ^ 2 # => 4 # power, not bitwise xor
-12 % 10 # => 2
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7.0
+5 / 2 # => 2.5 # dividing integers always results in a Float64
+div(5, 2) # => 2 # for a truncated result, use div
+5 \ 35 # => 7.0
+2^2 # => 4 # power, not bitwise xor
+12 % 10 # => 2
# Enforce precedence with parentheses
-(1 + 3) * 2 # => 8
+(1 + 3) * 2 # => 8
# Bitwise Operators
-~2 # => -3 # bitwise not
-3 & 5 # => 1 # bitwise and
-2 | 4 # => 6 # bitwise or
-xor(2, 4) # => 6 # bitwise xor
-2 >>> 1 # => 1 # logical shift right
-2 >> 1 # => 1 # arithmetic shift right
-2 << 1 # => 4 # logical/arithmetic shift left
-
-# You can use the bits function to see the binary representation of a number.
-bits(12345)
+~2 # => -3 # bitwise not
+3 & 5 # => 1 # bitwise and
+2 | 4 # => 6 # bitwise or
+xor(2, 4) # => 6 # bitwise xor
+2 >>> 1 # => 1 # logical shift right
+2 >> 1 # => 1 # arithmetic shift right
+2 << 1 # => 4 # logical/arithmetic shift left
+
+# Use the bitstring function to see the binary representation of a number.
+bitstring(12345)
# => "0000000000000000000000000000000000000000000000000011000000111001"
-bits(12345.0)
+bitstring(12345.0)
# => "0100000011001000000111001000000000000000000000000000000000000000"
# Boolean values are primitives
@@ -66,48 +66,38 @@ true
false
# Boolean operators
-!true # => false
-!false # => true
-1 == 1 # => true
-2 == 1 # => false
-1 != 1 # => false
-2 != 1 # => true
-1 < 10 # => true
-1 > 10 # => false
-2 <= 2 # => true
-2 >= 2 # => true
+!true # => false
+!false # => true
+1 == 1 # => true
+2 == 1 # => false
+1 != 1 # => false
+2 != 1 # => true
+1 < 10 # => true
+1 > 10 # => false
+2 <= 2 # => true
+2 >= 2 # => true
# Comparisons can be chained
-1 < 2 < 3 # => true
-2 < 3 < 2 # => false
+1 < 2 < 3 # => true
+2 < 3 < 2 # => false
# Strings are created with "
-try
"This is a string."
-catch ; end
-
-# Julia has several types of strings, including ASCIIString and UTF8String.
-# More on this in the Types section.
# Character literals are written with '
-try
'a'
-catch ; end
-# Some strings can be indexed like an array of characters
-try
-"This is a string"[1] # => 'T' # Julia indexes from 1
-catch ; end
-# However, this is will not work well for UTF8 strings,
-# so iterating over strings is recommended (map, for loops, etc).
+# Strings are UTF8 encoded. Only if they contain only ASCII characters can
+# they be safely indexed.
+ascii("This is a string")[1] # => 'T' # Julia indexes from 1
+# Otherwise, iterating over strings is recommended (map, for loops, etc).
# $ can be used for string interpolation:
-try
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
-catch ; end
# You can put any Julia expression inside the parentheses.
-# Another way to format strings is the printf macro.
-@printf "%d is less than %f" 4.5 5.3 # 4 is less than 5.300000
+# Another way to format strings is the printf macro from the stdlib Printf.
+using Printf
+@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000
# Printing is easy
println("I'm Julia. Nice to meet you!")
@@ -115,29 +105,29 @@ println("I'm Julia. Nice to meet you!")
# String can be compared lexicographically
"good" > "bye" # => true
"good" == "good" # => true
-"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true
+"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true
####################################################
## 2. Variables and Collections
####################################################
# You don't declare variables before assigning to them.
-some_var = 5 # => 5
-some_var # => 5
+some_var = 5 # => 5
+some_var # => 5
# Accessing a previously unassigned variable is an error
try
- some_other_var # => ERROR: some_other_var not defined
+ some_other_var # => ERROR: UndefVarError: some_other_var not defined
catch e
println(e)
end
# Variable names start with a letter or underscore.
# After that, you can use letters, digits, underscores, and exclamation points.
-SomeOtherVar123! = 6 # => 6
+SomeOtherVar123! = 6 # => 6
# You can also use certain unicode characters
-☃ = 8 # => 8
+☃ = 8 # => 8
# These are especially handy for mathematical notation
2 * π # => 6.283185307179586
@@ -156,165 +146,168 @@ SomeOtherVar123! = 6 # => 6
# functions are sometimes called mutating functions or in-place functions.
# Arrays store a sequence of values indexed by integers 1 through n:
-a = Int64[] # => 0-element Int64 Array
+a = Int64[] # => 0-element Int64 Array
# 1-dimensional array literals can be written with comma-separated values.
-b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
-b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6]
-b[1] # => 4
-b[end] # => 6
+b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6]
+b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6]
+b[1] # => 4
+b[end] # => 6
# 2-dimensional arrays use space-separated values and semicolon-separated rows.
-matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
+matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4]
-# Arrays of a particular Type
-b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6]
+# Arrays of a particular type
+b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6]
# Add stuff to the end of a list with push! and append!
-push!(a,1) # => [1]
-push!(a,2) # => [1,2]
-push!(a,4) # => [1,2,4]
-push!(a,3) # => [1,2,4,3]
-append!(a,b) # => [1,2,4,3,4,5,6]
+push!(a, 1) # => [1]
+push!(a, 2) # => [1,2]
+push!(a, 4) # => [1,2,4]
+push!(a, 3) # => [1,2,4,3]
+append!(a, b) # => [1,2,4,3,4,5,6]
# Remove from the end with pop
-pop!(b) # => 6 and b is now [4,5]
+pop!(b) # => 6 and b is now [4,5]
# Let's put it back
-push!(b,6) # b is now [4,5,6] again.
+push!(b, 6) # b is now [4,5,6] again.
-a[1] # => 1 # remember that Julia indexes from 1, not 0!
+a[1] # => 1 # remember that Julia indexes from 1, not 0!
# end is a shorthand for the last index. It can be used in any
# indexing expression
-a[end] # => 6
+a[end] # => 6
-# we also have shift and unshift
-shift!(a) # => 1 and a is now [2,4,3,4,5,6]
-unshift!(a,7) # => [7,2,4,3,4,5,6]
+# we also have popfirst! and pushfirst!
+popfirst!(a) # => 1 and a is now [2,4,3,4,5,6]
+pushfirst!(a, 7) # => [7,2,4,3,4,5,6]
# Function names that end in exclamations points indicate that they modify
# their argument.
-arr = [5,4,6] # => 3-element Int64 Array: [5,4,6]
-sort(arr) # => [4,5,6]; arr is still [5,4,6]
-sort!(arr) # => [4,5,6]; arr is now [4,5,6]
+arr = [5,4,6] # => 3-element Int64 Array: [5,4,6]
+sort(arr) # => [4,5,6]; arr is still [5,4,6]
+sort!(arr) # => [4,5,6]; arr is now [4,5,6]
# Looking out of bounds is a BoundsError
try
- a[0] # => ERROR: BoundsError() in getindex at array.jl:270
- a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270
+ a[0]
+ # => BoundsError: attempt to access 7-element Array{Int64,1} at index [0]
+ a[end + 1]
+ # => BoundsError: attempt to access 7-element Array{Int64,1} at index [8]
catch e
println(e)
end
# Errors list the line and file they came from, even if it's in the standard
-# library. If you built Julia from source, you can look in the folder base
-# inside the julia folder to find these files.
+# library. You can look in the folder share/julia inside the julia folder to
+# find these files.
# You can initialize arrays from ranges
-a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5]
+a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5]
# You can look at ranges with slice syntax.
-a[1:3] # => [1, 2, 3]
-a[2:end] # => [2, 3, 4, 5]
+a[1:3] # => [1, 2, 3]
+a[2:end] # => [2, 3, 4, 5]
# Remove elements from an array by index with splice!
arr = [3,4,5]
-splice!(arr,2) # => 4 ; arr is now [3,5]
+splice!(arr, 2) # => 4 ; arr is now [3,5]
# Concatenate lists with append!
b = [1,2,3]
-append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3]
+append!(a, b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3]
# Check for existence in a list with in
-in(1, a) # => true
+in(1, a) # => true
# Examine the length with length
-length(a) # => 8
+length(a) # => 8
# Tuples are immutable.
-tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple.
-tup[1] # => 1
-try:
- tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64)
+tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple.
+tup[1] # => 1
+try
+ tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64)
catch e
println(e)
end
-# Many list functions also work on tuples
-length(tup) # => 3
-tup[1:2] # => (1,2)
-in(2, tup) # => true
+# Many array functions also work on tuples
+length(tup) # => 3
+tup[1:2] # => (1,2)
+in(2, tup) # => true
# You can unpack tuples into variables
-a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3
+a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3
# Tuples are created even if you leave out the parentheses
-d, e, f = 4, 5, 6 # => (4,5,6)
+d, e, f = 4, 5, 6 # => (4,5,6)
# A 1-element tuple is distinct from the value it contains
-(1,) == 1 # => false
-(1) == 1 # => true
+(1,) == 1 # => false
+(1) == 1 # => true
# Look how easy it is to swap two values
-e, d = d, e # => (5,4) # d is now 5 and e is now 4
+e, d = d, e # => (5,4) # d is now 5 and e is now 4
# Dictionaries store mappings
-empty_dict = Dict() # => Dict{Any,Any}()
+empty_dict = Dict() # => Dict{Any,Any}()
# You can create a dictionary using a literal
-filled_dict = Dict("one"=> 1, "two"=> 2, "three"=> 3)
-# => Dict{ASCIIString,Int64}
+filled_dict = Dict("one" => 1, "two" => 2, "three" => 3)
+# => Dict{String,Int64}
# Look up values with []
-filled_dict["one"] # => 1
+filled_dict["one"] # => 1
# Get all keys
keys(filled_dict)
-# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
+# => Base.KeySet for a Dict{String,Int64} with 3 entries. Keys:
+# "two", "one", "three"
# Note - dictionary keys are not sorted or in the order you inserted them.
# Get all values
values(filled_dict)
-# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2])
+# => Base.ValueIterator{Dict{String,Int64}} with 3 entries. Values: 2, 1, 3
# Note - Same as above regarding key ordering.
# Check for existence of keys in a dictionary with in, haskey
-in(("one" => 1), filled_dict) # => true
-in(("two" => 3), filled_dict) # => false
-haskey(filled_dict, "one") # => true
-haskey(filled_dict, 1) # => false
+in(("one" => 1), filled_dict) # => true
+in(("two" => 3), filled_dict) # => false
+haskey(filled_dict, "one") # => true
+haskey(filled_dict, 1) # => false
# Trying to look up a non-existent key will raise an error
try
- filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489
+ filled_dict["four"] # => KeyError: key "four" not found
catch e
println(e)
end
# Use the get method to avoid that error by providing a default value
-# get(dictionary,key,default_value)
-get(filled_dict,"one",4) # => 1
-get(filled_dict,"four",4) # => 4
+# get(dictionary, key, default_value)
+get(filled_dict, "one", 4) # => 1
+get(filled_dict, "four", 4) # => 4
# Use Sets to represent collections of unordered, unique values
-empty_set = Set() # => Set{Any}()
+empty_set = Set() # => Set{Any}()
# Initialize a set with values
-filled_set = Set([1,2,2,3,4]) # => Set{Int64}(1,2,3,4)
+filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1])
# Add more values to a set
-push!(filled_set,5) # => Set{Int64}(5,4,2,3,1)
+push!(filled_set, 5) # => Set([4, 2, 3, 5, 1])
# Check if the values are in the set
-in(2, filled_set) # => true
-in(10, filled_set) # => false
+in(2, filled_set) # => true
+in(10, filled_set) # => false
# There are functions for set intersection, union, and difference.
-other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3)
-intersect(filled_set, other_set) # => Set{Int64}(3,4,5)
-union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6)
-setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4)
+other_set = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6])
+intersect(filled_set, other_set) # => Set([4, 3, 5])
+union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1])
+setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1])
####################################################
@@ -337,7 +330,7 @@ end
# For loops iterate over iterables.
# Iterable types include Range, Array, Set, Dict, and AbstractString.
-for animal=["dog", "cat", "mouse"]
+for animal = ["dog", "cat", "mouse"]
println("$animal is a mammal")
# You can use $ to interpolate variables or expression into strings
end
@@ -355,15 +348,16 @@ end
# cat is a mammal
# mouse is a mammal
-for a in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal")
- println("$(a[1]) is a $(a[2])")
+for pair in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal")
+ from, to = pair
+ println("$from is a $to")
end
# prints:
# dog is a mammal
# cat is a mammal
# mouse is a mammal
-for (k,v) in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal")
+for (k, v) in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal")
println("$k is a $v")
end
# prints:
@@ -372,10 +366,11 @@ end
# mouse is a mammal
# While loops loop while a condition is true
-x = 0
-while x < 4
- println(x)
- x += 1 # Shorthand for x = x + 1
+let x = 0
+ while x < 4
+ println(x)
+ x += 1 # Shorthand for x = x + 1
+ end
end
# prints:
# 0
@@ -385,9 +380,9 @@ end
# Handle exceptions with a try/catch block
try
- error("help")
+ error("help")
catch e
- println("caught it $e")
+ println("caught it $e")
end
# => caught it ErrorException("help")
@@ -407,15 +402,15 @@ function add(x, y)
x + y
end
-add(5, 6) # => 11 after printing out "x is 5 and y is 6"
+add(5, 6) # => 11 after printing out "x is 5 and y is 6"
# Compact assignment of functions
-f_add(x, y) = x + y # => "f (generic function with 1 method)"
-f_add(3, 4) # => 7
+f_add(x, y) = x + y # => "f (generic function with 1 method)"
+f_add(3, 4) # => 7
# Function can also return multiple values as tuple
fn(x, y) = x + y, x - y
-fn(3, 4) # => (7, -1)
+fn(3, 4) # => (7, -1)
# You can define functions that take a variable number of
# positional arguments
@@ -425,41 +420,41 @@ function varargs(args...)
end
# => varargs (generic function with 1 method)
-varargs(1,2,3) # => (1,2,3)
+varargs(1, 2, 3) # => (1,2,3)
# The ... is called a splat.
# We just used it in a function definition.
# It can also be used in a function call,
# where it will splat an Array or Tuple's contents into the argument list.
-add([5,6]...) # this is equivalent to add(5,6)
+add([5,6]...) # this is equivalent to add(5,6)
-x = (5,6) # => (5,6)
-add(x...) # this is equivalent to add(5,6)
+x = (5, 6) # => (5,6)
+add(x...) # this is equivalent to add(5,6)
# You can define functions with optional positional arguments
-function defaults(a,b,x=5,y=6)
+function defaults(a, b, x=5, y=6)
return "$a $b and $x $y"
end
-defaults('h','g') # => "h g and 5 6"
-defaults('h','g','j') # => "h g and j 6"
-defaults('h','g','j','k') # => "h g and j k"
+defaults('h', 'g') # => "h g and 5 6"
+defaults('h', 'g', 'j') # => "h g and j 6"
+defaults('h', 'g', 'j', 'k') # => "h g and j k"
try
- defaults('h') # => ERROR: no method defaults(Char,)
- defaults() # => ERROR: no methods defaults()
+ defaults('h') # => ERROR: no method defaults(Char,)
+ defaults() # => ERROR: no methods defaults()
catch e
println(e)
end
# You can define functions that take keyword arguments
-function keyword_args(;k1=4,name2="hello") # note the ;
- return Dict("k1"=>k1,"name2"=>name2)
+function keyword_args(;k1=4, name2="hello") # note the ;
+ return Dict("k1" => k1, "name2" => name2)
end
-keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4]
-keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"]
-keyword_args() # => ["name2"=>"hello","k1"=>4]
+keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4]
+keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"]
+keyword_args() # => ["name2"=>"hello","k1"=>4]
# You can combine all kinds of arguments in the same function
function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo")
@@ -483,7 +478,7 @@ function create_adder(x)
end
# This is "stabby lambda syntax" for creating anonymous functions
-(x -> x > 2)(3) # => true
+(x -> x > 2)(3) # => true
# This function is identical to create_adder implementation above.
function create_adder(x)
@@ -499,16 +494,17 @@ function create_adder(x)
end
add_10 = create_adder(10)
-add_10(3) # => 13
+add_10(3) # => 13
# There are built-in higher order functions
-map(add_10, [1,2,3]) # => [11, 12, 13]
-filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+map(add_10, [1,2,3]) # => [11, 12, 13]
+filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
-# We can use list comprehensions for nicer maps
-[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13]
+# We can use list comprehensions
+[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13]
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Types
@@ -517,11 +513,11 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# Julia has a type system.
# Every value has a type; variables do not have types themselves.
# You can use the `typeof` function to get the type of a value.
-typeof(5) # => Int64
+typeof(5) # => Int64
# Types are first-class values
-typeof(Int64) # => DataType
-typeof(DataType) # => DataType
+typeof(Int64) # => DataType
+typeof(DataType) # => DataType
# DataType is the type that represents types, including itself.
# Types are used for documentation, optimizations, and dispatch.
@@ -529,78 +525,77 @@ typeof(DataType) # => DataType
# Users can define types
# They are like records or structs in other languages.
-# New types are defined using the `type` keyword.
+# New types are defined using the `struct` keyword.
-# type Name
+# struct Name
# field::OptionalType
# ...
# end
-type Tiger
- taillength::Float64
- coatcolor # not including a type annotation is the same as `::Any`
+struct Tiger
+ taillength::Float64
+ coatcolor # not including a type annotation is the same as `::Any`
end
# The default constructor's arguments are the properties
# of the type, in the order they are listed in the definition
-tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange")
+tigger = Tiger(3.5, "orange") # => Tiger(3.5,"orange")
# The type doubles as the constructor function for values of that type
-sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire")
+sherekhan = typeof(tigger)(5.6, "fire") # => Tiger(5.6,"fire")
# These struct-style types are called concrete types
# They can be instantiated, but cannot have subtypes.
# The other kind of types is abstract types.
# abstract Name
-abstract type Cat end # just a name and point in the type hierarchy
+abstract type Cat end # just a name and point in the type hierarchy
# Abstract types cannot be instantiated, but can have subtypes.
+using InteractiveUtils # defines the subtype and supertype function
# For example, Number is an abstract type
-subtypes(Number) # => 2-element Array{Any,1}:
+subtypes(Number) # => 2-element Array{Any,1}:
# Complex{T<:Real}
# Real
-subtypes(Cat) # => 0-element Array{Any,1}
+subtypes(Cat) # => 0-element Array{Any,1}
# AbstractString, as the name implies, is also an abstract type
-subtypes(AbstractString) # 6-element Array{Union{DataType, UnionAll},1}:
- # Base.SubstitutionString
- # Base.Test.GenericString
- # DirectIndexString
- # RevString
- # String
- # SubString
+subtypes(AbstractString) # 4-element Array{Any,1}:
+ # String
+ # SubString
+ # SubstitutionString
+ # Test.GenericString
# Every type has a super type; use the `supertype` function to get it.
-typeof(5) # => Int64
-supertype(Int64) # => Signed
-supertype(Signed) # => Integer
-supertype(Integer) # => Real
-supertype(Real) # => Number
-supertype(Number) # => Any
-supertype(supertype(Signed)) # => Real
-supertype(Any) # => Any
+typeof(5) # => Int64
+supertype(Int64) # => Signed
+supertype(Signed) # => Integer
+supertype(Integer) # => Real
+supertype(Real) # => Number
+supertype(Number) # => Any
+supertype(supertype(Signed)) # => Real
+supertype(Any) # => Any
# All of these type, except for Int64, are abstract.
-typeof("fire") # => String
-supertype(String) # => AbstractString
+typeof("fire") # => String
+supertype(String) # => AbstractString
# Likewise here with String
-supertype(DirectIndexString) # => AbstractString
+supertype(SubString) # => AbstractString
# <: is the subtyping operator
-type Lion <: Cat # Lion is a subtype of Cat
- mane_color
- roar::AbstractString
+struct Lion <: Cat # Lion is a subtype of Cat
+ mane_color
+ roar::AbstractString
end
# You can define more constructors for your type
# Just define a function of the same name as the type
# and call an existing constructor to get a value of the correct type
-Lion(roar::AbstractString) = Lion("green",roar)
+Lion(roar::AbstractString) = Lion("green", roar)
# This is an outer constructor because it's outside the type definition
-type Panther <: Cat # Panther is also a subtype of Cat
- eye_color
- Panther() = new("green")
- # Panthers will only have this constructor, and no default constructor.
+struct Panther <: Cat # Panther is also a subtype of Cat
+ eye_color
+ Panther() = new("green")
+ # Panthers will only have this constructor, and no default constructor.
end
# Using inner constructors, like Panther does, gives you control
# over how values of the type can be created.
@@ -618,35 +613,35 @@ end
# Definitions for Lion, Panther, Tiger
function meow(animal::Lion)
- animal.roar # access type properties using dot notation
+ animal.roar # access type properties using dot notation
end
function meow(animal::Panther)
- "grrr"
+ "grrr"
end
function meow(animal::Tiger)
- "rawwwr"
+ "rawwwr"
end
# Testing the meow function
-meow(tigger) # => "rawwr"
-meow(Lion("brown","ROAAR")) # => "ROAAR"
-meow(Panther()) # => "grrr"
+meow(tigger) # => "rawwr"
+meow(Lion("brown", "ROAAR")) # => "ROAAR"
+meow(Panther()) # => "grrr"
# Review the local type hierarchy
-issubtype(Tiger,Cat) # => false
-issubtype(Lion,Cat) # => true
-issubtype(Panther,Cat) # => true
+Tiger <: Cat # => false
+Lion <: Cat # => true
+Panther <: Cat # => true
# Defining a function that takes Cats
function pet_cat(cat::Cat)
- println("The cat says $(meow(cat))")
+ println("The cat says $(meow(cat))")
end
-pet_cat(Lion("42")) # => prints "The cat says 42"
+pet_cat(Lion("42")) # => prints "The cat says 42"
try
- pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,)
+ pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,)
catch e
println(e)
end
@@ -656,129 +651,132 @@ end
# In Julia, all of the argument types contribute to selecting the best method.
# Let's define a function with more arguments, so we can see the difference
-function fight(t::Tiger,c::Cat)
- println("The $(t.coatcolor) tiger wins!")
+function fight(t::Tiger, c::Cat)
+ println("The $(t.coatcolor) tiger wins!")
end
# => fight (generic function with 1 method)
-fight(tigger,Panther()) # => prints The orange tiger wins!
-fight(tigger,Lion("ROAR")) # => prints The orange tiger wins!
+fight(tigger, Panther()) # => prints The orange tiger wins!
+fight(tigger, Lion("ROAR")) # => prints The orange tiger wins!
# Let's change the behavior when the Cat is specifically a Lion
-fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!")
+fight(t::Tiger, l::Lion) = println("The $(l.mane_color)-maned lion wins!")
# => fight (generic function with 2 methods)
-fight(tigger,Panther()) # => prints The orange tiger wins!
-fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins!
+fight(tigger, Panther()) # => prints The orange tiger wins!
+fight(tigger, Lion("ROAR")) # => prints The green-maned lion wins!
# We don't need a Tiger in order to fight
-fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))")
+fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))")
# => fight (generic function with 3 methods)
-fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr
+fight(Lion("balooga!"), Panther()) # => prints The victorious cat says grrr
try
- fight(Panther(),Lion("RAWR"))
+ fight(Panther(), Lion("RAWR"))
catch e
- println(e)
- # => MethodError(fight, (Panther("green"), Lion("green", "RAWR")), 0x000000000000557b)
+ println(e)
+ # => MethodError(fight, (Panther("green"), Lion("green", "RAWR")),
+ # 0x000000000000557b)
end
# Also let the cat go first
-fight(c::Cat,l::Lion) = println("The cat beats the Lion")
+fight(c::Cat, l::Lion) = println("The cat beats the Lion")
# This warning is because it's unclear which fight will be called in:
try
- fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr
+ fight(Lion("RAR"), Lion("brown", "rarrr"))
+ # => prints The victorious cat says rarrr
catch e
- println(e)
- # => MethodError(fight, (Lion("green", "RAR"), Lion("brown", "rarrr")), 0x000000000000557c)
+ println(e)
+ # => MethodError(fight, (Lion("green", "RAR"), Lion("brown", "rarrr")),
+ # 0x000000000000557c)
end
# The result may be different in other versions of Julia
-fight(l::Lion,l2::Lion) = println("The lions come to a tie")
-fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie
+fight(l::Lion, l2::Lion) = println("The lions come to a tie")
+fight(Lion("RAR"), Lion("brown", "rarrr")) # => prints The lions come to a tie
# Under the hood
# You can take a look at the llvm and the assembly code generated.
-square_area(l) = l * l # square_area (generic function with 1 method)
+square_area(l) = l * l # square_area (generic function with 1 method)
-square_area(5) #25
+square_area(5) # => 25
# What happens when we feed square_area an integer?
code_native(square_area, (Int32,))
- # .section __TEXT,__text,regular,pure_instructions
- # Filename: none
- # Source line: 1 # Prologue
- # push RBP
- # mov RBP, RSP
- # Source line: 1
- # movsxd RAX, EDI # Fetch l from memory?
- # imul RAX, RAX # Square l and store the result in RAX
- # pop RBP # Restore old base pointer
- # ret # Result will still be in RAX
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1 # Prologue
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # movsxd RAX, EDI # Fetch l from memory?
+ # imul RAX, RAX # Square l and store the result in RAX
+ # pop RBP # Restore old base pointer
+ # ret # Result will still be in RAX
code_native(square_area, (Float32,))
- # .section __TEXT,__text,regular,pure_instructions
- # Filename: none
- # Source line: 1
- # push RBP
- # mov RBP, RSP
- # Source line: 1
- # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX)
- # pop RBP
- # ret
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX)
+ # pop RBP
+ # ret
code_native(square_area, (Float64,))
- # .section __TEXT,__text,regular,pure_instructions
- # Filename: none
- # Source line: 1
- # push RBP
- # mov RBP, RSP
- # Source line: 1
- # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
- # pop RBP
- # ret
- #
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
+ # pop RBP
+ # ret
+ #
# Note that julia will use floating point instructions if any of the
# arguments are floats.
# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
-circle_area(5) # 78.53981633974483
+circle_area(5) # 78.53981633974483
code_native(circle_area, (Int32,))
- # .section __TEXT,__text,regular,pure_instructions
- # Filename: none
- # Source line: 1
- # push RBP
- # mov RBP, RSP
- # Source line: 1
- # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory
- # movabs RAX, 4593140240 # Load pi
- # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r
- # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r
- # pop RBP
- # ret
- #
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # Source line: 1
+ # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory
+ # movabs RAX, 4593140240 # Load pi
+ # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r
+ # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r
+ # pop RBP
+ # ret
+ #
code_native(circle_area, (Float64,))
- # .section __TEXT,__text,regular,pure_instructions
- # Filename: none
- # Source line: 1
- # push RBP
- # mov RBP, RSP
- # movabs RAX, 4593140496
- # Source line: 1
- # vmulsd XMM1, XMM0, QWORD PTR [RAX]
- # vmulsd XMM0, XMM1, XMM0
- # pop RBP
- # ret
- #
+ # .section __TEXT,__text,regular,pure_instructions
+ # Filename: none
+ # Source line: 1
+ # push RBP
+ # mov RBP, RSP
+ # movabs RAX, 4593140496
+ # Source line: 1
+ # vmulsd XMM1, XMM0, QWORD PTR [RAX]
+ # vmulsd XMM0, XMM1, XMM0
+ # pop RBP
+ # ret
+ #
```
## Further Reading
-You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/#Manual-1)
+You can get a lot more detail from the [Julia Documentation](https://docs.julialang.org/)
The best place to get help with Julia is the (very friendly) [Discourse forum](https://discourse.julialang.org/).
diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown
index bfa2a877..4e115ec5 100644
--- a/ko-kr/markdown-kr.html.markdown
+++ b/ko-kr/markdown-kr.html.markdown
@@ -25,7 +25,7 @@ lang: ko-kr
## HTML 요소
HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다.
-```markdown
+```md
<!--따라서 주석과 같은 HTML 요소들을 마크다운에 사용할 수 있으며, 마크다운 파서에 영향을
받지 않을 것입니다. 하지만 마크다운 파일에서 HTML 요소를 만든다면 그 요소의 안에서는
마크다운 문법을 사용할 수 없습니다.-->
diff --git a/markdown.html.markdown b/markdown.html.markdown
index ece2567c..cf4286e2 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -197,7 +197,7 @@ inside your code
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!
diff --git a/mips.html.markdown b/mips.html.markdown
new file mode 100644
index 00000000..1133f769
--- /dev/null
+++ b/mips.html.markdown
@@ -0,0 +1,366 @@
+---
+language: "MIPS Assembly"
+filename: MIPS.asm
+contributors:
+ - ["Stanley Lim", "https://github.com/Spiderpig86"]
+---
+
+The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language
+is designed to work with the MIPS microprocessor paradigm designed by J. L.
+Hennessy in 1981. These RISC processors are used in embedded systems such as
+gateways and routers.
+
+[Read More](https://en.wikipedia.org/wiki/MIPS_architecture)
+
+```assembly
+# Comments are denoted with a '#'
+
+# Everything that occurs after a '#' will be ignored by the assembler's lexer.
+
+# Programs typically contain a .data and .text sections
+
+.data # Section where data is stored in memory (allocated in RAM), similar to
+ # variables in higher level languages
+
+ # Declarations follow a ( label: .type value(s) ) form of declaration
+ hello_world: .asciiz "Hello World\n" # Declare a null terminated string
+ num1: .word 42 # Integers are referred to as words
+ # (32 bit value)
+
+ arr1: .word 1, 2, 3, 4, 5 # Array of words
+ arr2: .byte 'a', 'b' # Array of chars (1 byte each)
+ buffer: .space 60 # Allocates space in the RAM
+ # (not cleared to 0)
+
+ # Datatype sizes
+ _byte: .byte 'a' # 1 byte
+ _halfword: .half 53 # 2 bytes
+ _word: .word 3 # 4 bytes
+ _float: .float 3.14 # 4 bytes
+ _double: .double 7.0 # 8 bytes
+
+ .align 2 # Memory alignment of data, where
+ # number indicates byte alignment in
+ # powers of 2. (.align 2 represents
+ # word alignment since 2^2 = 4 bytes)
+
+.text # Section that contains instructions
+ # and program logic
+.globl _main # Declares an instruction label as
+ # global, making it accessible to
+ # other files
+
+ _main: # MIPS programs execute instructions
+ # sequentially, where the code under
+ # this label will be executed firsts
+
+ # Let's print "hello world"
+ la $a0, hello_world # Load address of string stored in
+ # memory
+ li $v0, 4 # Load the syscall value (indicating
+ # type of functionality)
+ syscall # Perform the specified syscall with
+ # the given argument ($a0)
+
+ # Registers (used to hold data during program execution)
+ # $t0 - $t9 # Temporary registers used for
+ # intermediate calculations inside
+ # subroutines (not saved across
+ # function calls)
+
+ # $s0 - $s7 # Saved registers where values are
+ # saved across subroutine calls.
+ # Typically saved in stack
+
+ # $a0 - $a3 # Argument registers for passing in
+ # arguments for subroutines
+ # $v0 - $v1 # Return registers for returning
+ # values to caller function
+
+ # Types of load/store instructions
+ la $t0, label # Copy the address of a value in
+ # memory specified by the label into
+ # register $t0
+ lw $t0, label # Copy a word value from memory
+ lw $t1, 4($s0) # Copy a word value from an address
+ # stored in a register with an offset
+ # of 4 bytes (addr + 4)
+ lb $t2, label # Copy a byte value to the lower order
+ # portion of the register $t2
+ lb $t2, 0($s0) # Copy a byte value from the source
+ # address in $s0 with offset 0
+ # Same idea with 'lh' for halfwords
+
+ sw $t0, label # Store word value into memory address
+ # mapped by label
+ sw $t0, 8($s0) # Store word value into address
+ # specified in $s0 and offset of 8 bytes
+ # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist
+
+### Math ###
+ _math:
+ # Remember to load your values into a register
+ lw $t0, num # From the data section
+ li $t0, 5 # Or from an immediate (constant)
+ li $t1, 6
+ add $t2, $t0, $t1 # $t2 = $t0 + $t1
+ 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)
+ div $t0, $t1 # Performs $t0 / $t1. Get the quotient
+ # using 'mflo' and remainder using 'mfhi'
+
+ # Bitwise Shifting
+ sll $t0, $t0, 2 # Bitwise shift to the left with
+ # immediate (constant value) of 2
+ sllv $t0, $t1, $t2 # Shift left by a variable amount in
+ # register
+ srl $t0, $t0, 5 # Bitwise shift to the right (does
+ # not sign preserve, sign-extends with 0)
+ srlv $t0, $t1, $t2 # Shift right by a variable amount in
+ # a register
+ sra $t0, $t0, 7 # Bitwise arithmetic shift to the right
+ # (preserves sign)
+ srav $t0, $t1, $t2 # Shift right by a variable amount
+ # in a register
+
+ # Bitwise operators
+ and $t0, $t1, $t2 # Bitwise AND
+ andi $t0, $t1, 0xFFF # Bitwise AND with immediate
+ or $t0, $t1, $t2 # Bitwise OR
+ ori $t0, $t1, 0xFFF # Bitwise OR with immediate
+ xor $t0, $t1, $t2 # Bitwise XOR
+ xori $t0, $t1, 0xFFF # Bitwise XOR with immediate
+ nor $t0, $t1, $t2 # Bitwise NOR
+
+## BRANCHING ##
+ _branching:
+ # The basic format of these branching instructions typically follow <instr>
+ # <reg1> <reg2> <label> where label is the label we want to jump to if the
+ # given conditional evaluates to true
+ # Sometimes it is easier to write the conditional logic backwards, as seen
+ # in the simple if statement example below
+
+ beq $t0, $t1, reg_eq # Will branch to reg_eq if
+ # $t0 == $t1, otherwise
+ # execute the next line
+ bne $t0, $t1, reg_neq # Branches when $t0 != $t1
+ b branch_target # Unconditional branch, will always execute
+ beqz $t0, req_eq_zero # Branches when $t0 == 0
+ bnez $t0, req_neq_zero # Branches when $t0 != 0
+ bgt $t0, $t1, t0_gt_t1 # Branches when $t0 > $t1
+ bge $t0, $t1, t0_gte_t1 # Branches when $t0 >= $t1
+ bgtz $t0, t0_gt0 # Branches when $t0 > 0
+ 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 when
+ # $t0 < $t1 with reuslt in $s0 (1 for true)
+
+ # Simple if statement
+ # if (i == j)
+ # f = g + h;
+ # f = f - i;
+
+ # Let $s0 = f, $s1 = g, $s2 = h, $s3 = i, $s4 = j
+ bne $s3, $s4, L1 # if (i !=j)
+ add $s0, $s1, $s2 # f = g + h
+
+ L1:
+ sub $s0, $s0, $s3 # f = f - i
+
+ # Below is an example of finding the max of 3 numbers
+ # A direct translation in Java from MIPS logic:
+ # if (a > b)
+ # if (a > c)
+ # max = a;
+ # else
+ # max = c;
+ # else
+ # max = b;
+ # else
+ # max = c;
+
+ # Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register
+ ble $s0, $s1, a_LTE_b # if (a <= b) branch(a_LTE_b)
+ ble $s0, $s2, max_C # if (a > b && a <=c) branch(max_C)
+ move $v0, $s1 # else [a > b && a > c] max = a
+ j done # Jump to the end of the program
+
+ a_LTE_b: # Label for when a <= b
+ ble $s1, $s2, max_C # if (a <= b && b <= c) branch(max_C)
+ move $v0, $s1 # if (a <= b && b > c) max = b
+ j done # Jump to done
+
+ max_C:
+ move $v0, $s2 # max = c
+
+ done: # End of program
+
+## LOOPS ##
+ _loops:
+ # The basic structure of loops is having an exit condition and a jump
+ instruction to continue its execution
+ li $t0, 0
+ while:
+ bgt $t0, 10, end_while # While $t0 is less than 10, keep iterating
+ addi $t0, $t0, 1 # Increment the value
+ j while # Jump back to the beginning of the loop
+ end_while:
+
+ # 2D Matrix Traversal
+ # Assume that $a0 stores the address of an integer matrix which is 3 x 3
+ li $t0, 0 # Counter for i
+ li $t1, 0 # Counter for j
+ matrix_row:
+ bgt $t0, 3, matrix_row_end
+
+ matrix_col:
+ bgt $t1, 3, matrix_col_end
+
+ # Do stuff
+
+ addi $t1, $t1, 1 # Increment the col counter
+ matrix_col_end:
+
+ # Do stuff
+
+ addi $t0, $t0, 1
+ matrix_row_end:
+
+## FUNCTIONS ##
+ _functions:
+ # Functions are callable procedures that can accept arguments and return
+ values all denoted with labels, like above
+
+ main: # Programs begin with main func
+ jal return_1 # jal will store the current PC in $ra
+ # and then jump to return_1
+
+ # What if we want to pass in args?
+ # First we must pass in our parameters to the argument registers
+ li $a0, 1
+ li $a1, 2
+ jal sum # Now we can call the function
+
+ # How about recursion?
+ # This is a bit more work since we need to make sure we save and restore
+ # the previous PC in $ra since jal will automatically overwrite on each call
+ li $a0, 3
+ jal fact
+
+ li $v0, 10
+ syscall
+
+ # This function returns 1
+ return_1:
+ li $v0, 1 # Load val in return register $v0
+ jr $ra # Jump back to old PC to continue exec
+
+
+ # Function with 2 args
+ sum:
+ add $v0, $a0, $a1
+ jr $ra # Return
+
+ # Recursive function to find factorial
+ fact:
+ addi $sp, $sp, -8 # Allocate space in stack
+ sw $s0, ($sp) # Store reg that holds current num
+ sw $ra, 4($sp) # Store previous PC
+
+ li $v0, 1 # Init return value
+ beq $a0, 0, fact_done # Finish if param is 0
+
+ # Otherwise, continue recursion
+ move $s0, $a0 # Copy $a0 to $s0
+ sub $a0, $a0, 1
+ jal fact
+
+ mul $v0, $s0, $v0 # Multiplication is done
+
+ fact_done:
+ lw $s0, ($sp)
+ lw $ra, ($sp) # Restore the PC
+ addi $sp, $sp, 8
+
+ jr $ra
+
+## MACROS ##
+ _macros:
+ # Macros are extremly useful for substituting repeated code blocks with a
+ # single label for better readability
+ # These are in no means substitutes for functions
+ # These must be declared before it is used
+
+ # Macro for printing new lines (since these can be very repetitive)
+ .macro println()
+ la $a0, newline # New line string stored here
+ li $v0, 4
+ syscall
+ .end_macro
+
+ println() # Assembler will copy that block of
+ # code here before running
+
+ # Parameters can be passed in through macros.
+ # These are denoted by a '%' sign with any name you choose
+ .macro print_int(%num)
+ li $v0, 1
+ lw $a0, %num
+ syscall
+ .end_macro
+
+ li $t0, 1
+ print_int($t0)
+
+ # We can also pass in immediates for macros
+ .macro immediates(%a, %b)
+ add $t0, %a, %b
+ .end_macro
+
+ immediates(3, 5)
+
+ # Along with passing in labels
+ .macro print(%string)
+ la $a0, %string
+ li $v0, 4
+ syscall
+ .end_macro
+
+ print(hello_world)
+
+## ARRAYS ##
+.data
+ list: .word 3, 0, 1, 2, 6 # This is an array of words
+ char_arr: .asciiz "hello" # This is a char array
+ buffer: .space 128 # Allocates a block in memory, does
+ # not automatically clear
+ # These blocks of memory are aligned
+ # next each other
+
+.text
+ la $s0, list # Load address of list
+ li $t0, 0 # Counter
+ li $t1, 5 # Length of the list
+
+ loop:
+ bgt $t0, $t1, end_loop
+
+ lw $a0, ($s0)
+ li $v0, 1
+ syscall # Print the number
+
+ addi $s0, $s0, 4 # Size of a word is 4 bytes
+ addi $t0, $t0, 1 # Increment
+ j loop
+ end_loop:
+
+## INCLUDE ##
+# You do this to import external files into your program (behind the scenes,
+# it really just takes whatever code that is in that file and places it where
+# the include statement is)
+.include "somefile.asm"
+
+```
diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown
index 35cc67c5..b5b4681c 100644
--- a/nl-nl/markdown-nl.html.markdown
+++ b/nl-nl/markdown-nl.html.markdown
@@ -12,7 +12,7 @@ Markdown is gecreëerd door John Gruber in 2004. Het is bedoeld om met een gemak
schrijven syntax te zijn die gemakkelijk omgevormd kan worden naar HTML (en op heden verschillende
andere formaten)
-```markdown
+```md
<!-- Markdown erft over van HTML, dus ieder HTML bestand is een geldig Markdown
bestand. Dit betekend ook dat html elementen gebruikt kunnen worden in Markdown
zoals het commentaar element. Echter, als je een html element maakt in een Markdown
diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown
index c3381824..c22cfd8e 100644
--- a/pt-br/common-lisp-pt.html.markdown
+++ b/pt-br/common-lisp-pt.html.markdown
@@ -19,7 +19,7 @@ Outro livro recente e popular é o
[Land of Lisp](http://landoflisp.com/).
-```common-lisp
+```lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 0. Sintaxe
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown
index f22093f9..c2aa515d 100644
--- a/pt-br/markdown-pt.html.markdown
+++ b/pt-br/markdown-pt.html.markdown
@@ -14,7 +14,7 @@ escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos
Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e
puxar o projeto (pull request)
-```markdown
+```md
<!-- Markdown é um superconjunto do HTML, de modo que qualquer arvquivo 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
diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown
index b94ab609..2a7205cd 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
---
-```vb
+```
Module Module1
module Module1
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
index ff7a0cc3..3e20b5d5 100644
--- a/ru-ru/markdown-ru.html.markdown
+++ b/ru-ru/markdown-ru.html.markdown
@@ -36,7 +36,7 @@ lang: ru-ru
Markdown является надмножеством HTML, поэтому любой HTML-файл является
корректным документом Markdown.
- ```markdown
+ ```md
<!-- Это позволяет использовать напрямую
любые элементы HTML-разметки, такие, например, как этот комментарий.
Встроенные в документ HTML-элементы не затрагиваются парсером Markdown
diff --git a/toml.html.markdown b/toml.html.markdown
index 39caaa23..814e57e7 100755
--- a/toml.html.markdown
+++ b/toml.html.markdown
@@ -12,7 +12,7 @@ It is an alternative to YAML and JSON. It aims to be more human friendly than JS
Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you
should assume that it is unstable and act accordingly. This document follows TOML v0.4.0.
-```toml
+```
# Comments in TOML look like this.
################
diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown
index b8f11e39..6caba1da 100644
--- a/tr-tr/markdown-tr.html.markdown
+++ b/tr-tr/markdown-tr.html.markdown
@@ -11,7 +11,7 @@ filename: markdown-tr.md
Markdown, 2004 yılında John Gruber tarafından oluşturuldu. Asıl amacı kolay okuma ve yazmayı sağlamakla beraber kolayca HTML (artık bir çok diğer formatlara) dönüşüm sağlamaktır.
-```markdown
+```md
<!-- Markdown, HTML'i kapsar, yani her HTML dosyası geçerli bir Markdown dosyasıdır, bu demektir
ki Markdown içerisinde HTML etiketleri kullanabiliriz, örneğin bu yorum elementi, ve
markdown işleyicisinde etki etmezler. Fakat, markdown dosyası içerisinde HTML elementi oluşturursanız,
diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown
new file mode 100644
index 00000000..2406678d
--- /dev/null
+++ b/uk-ua/python-ua.html.markdown
@@ -0,0 +1,818 @@
+---
+language: python
+lang: uk-ua
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Amin Bandali", "https://aminb.org"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["evuez", "http://github.com/evuez"]
+ - ["asyne", "https://github.com/justblah"]
+ - ["habi", "http://github.com/habi"]
+translators:
+ - ["Oleg Gromyak", "https://github.com/ogroleg"]
+filename: learnpython-ua.py
+---
+
+Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з
+найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому
+синтаксису. Це майже як виконуваний псевдокод.
+
+З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh)
+або louiedinh [at] [поштовий сервіс від Google]
+
+Примітка: Ця стаття стосується Python 2.7, проте має працювати і
+у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну,
+його підтримку припинять у 2020, тож наразі краще починати вивчення Python
+з версії 3.x.
+Аби вивчити Python 3.x, звертайтесь до статті по Python 3.
+
+```python
+# Однорядкові коментарі починаються з символу решітки.
+
+""" Текст, що займає декілька рядків,
+ може бути записаний з використанням 3 знаків " і
+ зазвичай використовується у якості
+ вбудованої документації
+"""
+
+####################################################
+## 1. Примітивні типи даних та оператори
+####################################################
+
+# У вас є числа
+3 # => 3
+
+# Математика працює досить передбачувано
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+35 / 5 # => 7
+
+# А ось з діленням все трохи складніше. Воно цілочисельне і результат
+# автоматично округлюється у меншу сторону.
+5 / 2 # => 2
+
+# Аби правильно ділити, спершу варто дізнатися про числа
+# з плаваючою комою.
+2.0 # Це число з плаваючою комою
+11.0 / 4.0 # => 2.75 ох... Так набагато краще
+
+# Результат цілочисельного ділення округлюється у меншу сторону
+# як для додатніх, так і для від'ємних чисел.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Зверніть увагу, що ми також можемо імпортувати модуль для ділення,
+# див. розділ Модулі
+# аби звичне ділення працювало при використанні лише '/'.
+from __future__ import division
+
+11 / 4 # => 2.75 ...звичне ділення
+11 // 4 # => 2 ...цілочисельне ділення
+
+# Залишок від ділення
+7 % 3 # => 1
+
+# Піднесення до степеня
+2 ** 4 # => 16
+
+# Приорітет операцій вказується дужками
+(1 + 3) * 2 # => 8
+
+# Логічні оператори
+# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв
+True and False # => False
+False or True # => True
+
+# Завважте, що логічні оператори також використовуються і з цілими числами
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
+
+# Для заперечення використовується not
+not True # => False
+not False # => True
+
+# Рівність — це ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Нерівність — це !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Ще трохи порівнянь
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Порівняння можуть бути записані ланцюжком!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# Рядки позначаються символом " або '
+"Це рядок."
+'Це теж рядок.'
+
+# І рядки також можна додавати!
+"Привіт " + "світ!" # => "Привіт світ!"
+# Рядки можна додавати і без '+'
+"Привіт " "світ!" # => "Привіт світ!"
+
+# ... або множити
+"Привіт" * 3 # => "ПривітПривітПривіт"
+
+# З рядком можна працювати як зі списком символів
+"Це рядок"[0] # => 'Ц'
+
+# Ви можете дізнатися довжину рядка
+len("Це рядок") # => 8
+
+# Символ % використовується для форматування рядків, наприклад:
+"%s можуть бути %s" % ("рядки", "інтерпольовані")
+
+# Новий спосіб форматування рядків — використання методу format.
+# Це бажаний спосіб.
+"{} є {}".format("Це", "заповнювач")
+"{0} можуть бути {1}".format("рядки", "форматовані")
+# Якщо ви не хочете рахувати, то можете скористатися ключовими словами.
+"{name} хоче з'істи {food}".format(name="Боб", food="лазанью")
+
+# None - це об'єкт
+None # => None
+
+# Не використовуйте оператор рівності '=='' для порівняння
+# об'єктів з None. Використовуйте для цього «is»
+"etc" is None # => False
+None is None # => True
+
+# Оператор 'is' перевіряє ідентичність об'єктів. Він не
+# дуже корисний при роботі з примітивними типами, проте
+# незамінний при роботі з об'єктами.
+
+# None, 0 і порожні рядки/списки рівні False.
+# Всі інші значення рівні True
+bool(0) # => False
+bool("") # => False
+
+
+####################################################
+## 2. Змінні та колекції
+####################################################
+
+# В Python є оператор print
+print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись!
+
+# Отримати дані з консолі просто
+input_string_var = raw_input(
+ "Введіть щось: ") # Повертає дані у вигляді рядка
+input_var = input("Введіть щось: ") # Працює з даними як з кодом на python
+# Застереження: будьте обережні при використанні методу input()
+
+# Оголошувати змінні перед ініціалізацією не потрібно.
+some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями
+some_var # => 5
+
+# При спробі доступу до неініціалізованої змінної
+# виникне виняткова ситуація.
+# Див. розділ Потік управління, аби дізнатись про винятки більше.
+some_other_var # Помилка в імені
+
+# if може використовуватися як вираз
+# Такий запис еквівалентний тернарному оператору '?:' у мові С
+"yahoo!" if 3 > 2 else 2 # => "yahoo!"
+
+# Списки зберігають послідовності
+li = []
+# Можна одразу створити заповнений список
+other_li = [4, 5, 6]
+
+# Об'єкти додаються у кінець списку за допомогою методу append
+li.append(1) # li тепер дорівнює [1]
+li.append(2) # li тепер дорівнює [1, 2]
+li.append(4) # li тепер дорівнює [1, 2, 4]
+li.append(3) # li тепер дорівнює [1, 2, 4, 3]
+# І видаляються з кінця методом pop
+li.pop() # => повертає 3 і li стає рівним [1, 2, 4]
+# Повернемо елемент назад
+li.append(3) # li тепер знову дорівнює [1, 2, 4, 3]
+
+# Поводьтесь зі списком як зі звичайним масивом
+li[0] # => 1
+# Присвоюйте нові значення вже ініціалізованим індексам за допомогою =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення
+# Звертаємось до останнього елементу
+li[-1] # => 3
+
+# Спроба вийти за границі масиву призводить до помилки в індексі
+li[4] # помилка в індексі
+
+# Можна звертатися до діапазону, використовуючи так звані зрізи
+# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал).
+li[1:3] # => [2, 4]
+# Опускаємо початок
+li[2:] # => [4, 3]
+# Опускаємо кінець
+li[:3] # => [1, 2, 4]
+# Вибираємо кожен другий елемент
+li[::2] # => [1, 4]
+# Перевертаємо список
+li[::-1] # => [3, 4, 2, 1]
+# Використовуйте суміш вищеназваного для більш складних зрізів
+# li[початок:кінець:крок]
+
+# Видаляємо довільні елементи зі списку оператором del
+del li[2] # li тепер [1, 2, 3]
+
+# Ви можете додавати списки
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# Зверніть увагу: значення li та other_li при цьому не змінились.
+
+# Поєднувати списки можна за допомогою методу extend
+li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6]
+
+# Видалити перше входження значення
+li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6]
+li.remove(2) # Помилка значення, оскільки у списку li немає 2
+
+# Вставити елемент за вказаним індексом
+li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6]
+
+# Отримати індекс першого знайденого елементу
+li.index(2) # => 1
+li.index(7) # Помилка значення, оскільки у списку li немає 7
+
+# Перевірити елемент на входження у список можна оператором in
+1 in li # => True
+
+# Довжина списку обчислюється за допомогою функції len
+len(li) # => 6
+
+# Кортежі схожі на списки, лише незмінні
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Виникає помилка типу
+
+# Все те ж саме можна робити і з кортежами
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Ви можете розпаковувати кортежі (або списки) у змінні
+a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3
+d, e, f = 4, 5, 6 # дужки можна опустити
+# Кортежі створюються за замовчуванням, якщо дужки опущено
+g = 4, 5, 6 # => (4, 5, 6)
+# Дивіться, як легко обміняти значення двох змінних
+e, d = d, e # тепер d дорівнює 5, а e дорівнює 4
+
+# Словники містять асоціативні масиви
+empty_dict = {}
+# Ось так описується попередньо заповнений словник
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Значення можна отримати так само, як і зі списку
+filled_dict["one"] # => 1
+
+# Можна отримати всі ключі у виді списку за допомогою методу keys
+filled_dict.keys() # => ["three", "two", "one"]
+# Примітка: збереження порядку ключів у словників не гарантується
+# Ваші результати можуть не співпадати з цими.
+
+# Можна отримати і всі значення у вигляді списку, використовуйте метод values
+filled_dict.values() # => [3, 2, 1]
+# Те ж зауваження щодо порядку ключів діє і тут
+
+# Отримуйте всі пари ключ-значення у вигляді списку кортежів
+# за допомогою "items()"
+filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
+
+# За допомогою оператору in можна перевіряти ключі на входження у словник
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# Спроба отримати значення за неіснуючим ключем викине помилку ключа
+filled_dict["four"] # помилка ключа
+
+# Аби уникнути цього, використовуйте метод get()
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# Метод get також приймає аргумент за замовчуванням, значення якого буде
+# повернуто при відсутності вказаного ключа
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+# Зверніть увагу, що filled_dict.get("four") все ще => None
+# (get не встановлює значення елементу словника)
+
+# Присвоюйте значення ключам так само, як і в списках
+filled_dict["four"] = 4 # тепер filled_dict["four"] => 4
+
+# Метод setdefault() вставляє пару ключ-значення лише
+# за відсутності такого ключа
+filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5
+
+
+# Множини містять... ну, загалом, множини
+# (які схожі на списки, проте в них не може бути елементів, які повторюються)
+empty_set = set()
+# Ініціалізація множини набором значень
+some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4])
+
+# Порядок не гарантовано, хоча інколи множини виглядають відсортованими
+another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4])
+
+# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Додавання нових елементів у множину
+filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5}
+
+# Перетин множин: &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Об'єднання множин: |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Різниця множин: -
+{1,2,3,4} - {2,3,5} # => {1, 4}
+
+# Симетрична різниця множин: ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Перевіряємо чи множина зліва є надмножиною множини справа
+{1, 2} >= {1, 2, 3} # => False
+
+# Перевіряємо чи множина зліва є підмножиною множини справа
+{1, 2} <= {1, 2, 3} # => True
+
+# Перевірка на входження у множину: in
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. Потік управління
+####################################################
+
+# Для початку створимо змінну
+some_var = 5
+
+# Так виглядає вираз if. Відступи у python дуже важливі!
+# результат: «some_var менше, ніж 10»
+if some_var > 10:
+ print("some_var набагато більше, ніж 10.")
+elif some_var < 10: # Вираз elif є необов'язковим.
+ print("some_var менше, ніж 10.")
+else: # Це теж необов'язково.
+ print("some_var дорівнює 10.")
+
+
+"""
+Цикли For проходять по спискам
+
+Результат:
+ собака — це ссавець
+ кішка — це ссавець
+ миша — це ссавець
+"""
+for animal in ["собака", "кішка", "миша"]:
+ # Можете використовувати оператор {0} для інтерполяції форматованих рядків
+ print "{0} — це ссавець".format(animal)
+
+"""
+"range(число)" повертає список чисел
+від нуля до заданого числа
+Друкує:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+"""
+"range(нижня_границя, верхня_границя)" повертає список чисел
+від нижньої границі до верхньої
+Друкує:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print i
+
+"""
+Цикли while продовжуються до тих пір, поки вказана умова не стане хибною.
+Друкує:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # Короткий запис для x = x + 1
+
+# Обробляйте винятки блоками try/except
+
+# Працює у Python 2.6 і вище:
+try:
+ # Аби створити виняток, використовується raise
+ raise IndexError("Помилка у індексі!")
+except IndexError as e:
+ pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається
+ # відновлення після помилки.
+except (TypeError, NameError):
+ pass # Винятки можна обробляти групами, якщо потрібно.
+else: # Необов'язковий вираз. Має слідувати за останнім блоком except
+ print("Все добре!") # Виконається лише якщо не було ніяких винятків
+finally: # Виконується у будь-якому випадку
+ print "Тут ми можемо звільнити ресурси"
+
+# Замість try/finally для звільнення ресурсів
+# ви можете використовувати вираз with
+with open("myfile.txt") as f:
+ for line in f:
+ print line
+
+
+####################################################
+## 4. Функції
+####################################################
+
+# Використовуйте def для створення нових функцій
+def add(x, y):
+ print "x дорівнює {0}, а y дорівнює {1}".format(x, y)
+ return x + y # Повертайте результат за допомогою ключового слова return
+
+
+# Виклик функції з аргументами
+add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11
+
+# Інший спосіб виклику функції — виклик з іменованими аргументами
+add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку
+
+
+# Ви можете визначити функцію, яка приймає змінну кількість аргументів,
+# які будуть інтерпретовані як кортеж, за допомогою *
+def varargs(*args):
+ return args
+
+
+varargs(1, 2, 3) # => (1,2,3)
+
+
+# А також можете визначити функцію, яка приймає змінне число
+# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою **
+def keyword_args(**kwargs):
+ return kwargs
+
+
+# Давайте подивимось що з цього вийде
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+# Якщо хочете, можете використовувати обидва способи одночасно
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+
+
+"""
+all_the_args(1, 2, a=3, b=4) друкує:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# Коли викликаєте функції, то можете зробити навпаки!
+# Використовуйте символ * аби розпакувати позиційні аргументи і
+# ** для іменованих аргументів
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # еквівалентно foo(1, 2, 3, 4)
+all_the_args(**kwargs) # еквівалентно foo(a=3, b=4)
+all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4)
+
+# ви можете передавати довільне число позиційних або іменованих аргументів
+# іншим функціям, які їх приймають, розпаковуючи за допомогою
+# * або ** відповідно
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
+
+# Область визначення функцій
+x = 5
+
+
+def set_x(num):
+ # Локальна змінна x - не те ж саме, що глобальна змінна x
+ x = num # => 43
+ print x # => 43
+
+
+def set_global_x(num):
+ global x
+ print x # => 5
+ x = num # глобальна змінна x тепер дорівнює 6
+ print x # => 6
+
+
+set_x(43)
+set_global_x(6)
+
+# В Python функції є об'єктами першого класу
+def create_adder(x):
+ def adder(y):
+ return x + y
+
+ return adder
+
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Також є і анонімні функції
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# Присутні вбудовані функції вищого порядку
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# Для зручного відображення і фільтрації можна використовувати
+# включення у вигляді списків
+[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]
+
+# Ви також можете скористатися включеннями множин та словників
+{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
+{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+## 5. Класи
+####################################################
+
+# Аби отримати клас, ми наслідуємо object.
+class Human(object):
+ # Атрибут класу. Він розділяється всіма екземплярами цього класу.
+ species = "H. sapiens"
+
+ # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу
+ # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені
+ # використовується для позначення об'єктів та атрибутів,
+ # які використовуються Python, але знаходяться у просторах імен,
+ # якими керує користувач. Не варто вигадувати для них імена самостійно.
+ def __init__(self, name):
+ # Присвоєння значення аргумента атрибуту класу name
+ self.name = name
+
+ # Ініціалізуємо властивість
+ self.age = 0
+
+ # Метод екземпляру. Всі методи приймають self у якості першого аргументу
+ def say(self, msg):
+ return "%s: %s" % (self.name, msg)
+
+ # Методи класу розділяються між усіма екземплярами
+ # Вони викликаються з вказанням викликаючого класу
+ # у якості першого аргументу
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Статичний метод викликається без посилання на клас або екземпляр
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # Властивість.
+ # Перетворює метод age() в атрибут тільки для читання
+ # з таким же ім'ям.
+ @property
+ def age(self):
+ return self._age
+
+ # Це дозволяє змінювати значення властивості
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # Це дозволяє видаляти властивість
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# Створюємо екземпляр класу
+i = Human(name="Данило")
+print(i.say("привіт")) # Друкує: «Данило: привіт»
+
+j = Human("Меланка")
+print(j.say("Привіт")) # Друкує: «Меланка: привіт»
+
+# Виклик методу класу
+i.get_species() # => "H. sapiens"
+
+# Зміна розділюваного атрибуту
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Виклик статичного методу
+Human.grunt() # => "*grunt*"
+
+# Оновлюємо властивість
+i.age = 42
+
+# Отримуємо значення
+i.age # => 42
+
+# Видаляємо властивість
+del i.age
+i.age # => виникає помилка атрибуту
+
+####################################################
+## 6. Модулі
+####################################################
+
+# Ви можете імпортувати модулі
+import math
+
+print(math.sqrt(16)) # => 4
+
+# Ви можете імпортувати окремі функції з модуля
+from math import ceil, floor
+
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# Можете імпортувати всі функції модуля.
+# Попередження: краще так не робіть
+from math import *
+
+# Можете скорочувати імена модулів
+import math as m
+
+math.sqrt(16) == m.sqrt(16) # => True
+# Ви також можете переконатися, що функції еквівалентні
+from math import sqrt
+
+math.sqrt == m.sqrt == sqrt # => True
+
+# Модулі в Python — це звичайні Python-файли. Ви
+# можете писати свої модулі та імпортувати їх. Назва
+# модуля співпадає з назвою файлу.
+
+# Ви можете дізнатися, які функції та атрибути визначені
+# в модулі
+import math
+
+dir(math)
+
+
+# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що
+# і ваш поточний скрипт, то файл math.py
+# може бути завантажено замість вбудованого у Python модуля.
+# Так трапляється, оскільки локальна папка має перевагу
+# над вбудованими у Python бібліотеками.
+
+####################################################
+## 7. Додатково
+####################################################
+
+# Генератори
+# Генератор "генерує" значення тоді, коли вони запитуються, замість того,
+# щоб зберігати все одразу
+
+# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх
+# в `double_arr`. При великих розмірах може знадобитися багато ресурсів!
+def double_numbers(iterable):
+ double_arr = []
+ for i in iterable:
+ double_arr.append(i + i)
+ return double_arr
+
+
+# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх,
+# аби перевірити умову
+for value in double_numbers(range(1000000)): # `test_non_generator`
+ print value
+ if value > 5:
+ break
+
+
+# Натомість ми можемо скористатися генератором, аби "згенерувати"
+# подвійне значення, як тільки воно буде запитане
+def double_numbers_generator(iterable):
+ for i in iterable:
+ yield i + i
+
+
+# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по
+# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються
+# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми
+# виходимо з циклу і більше не подвоюємо більшість значень,
+# які отримали на вхід (НАБАГАТО ШВИДШЕ!)
+for value in double_numbers_generator(xrange(1000000)): # `test_generator`
+ print value
+ if value > 5:
+ break
+
+# Між іншим: ви помітили використання `range` у `test_non_generator` і
+# `xrange` у `test_generator`?
+# Як `double_numbers_generator` є версією-генератором `double_numbers`, так
+# і `xrange` є аналогом `range`, але у вигляді генератора.
+# `range` поверне нам масив з 1000000 значень
+# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді,
+# коли ми їх запитуємо / будемо проходитись по ним.
+
+# Аналогічно включенням у вигляді списків, ви можете створювати включення
+# у вигляді генераторів.
+values = (-x for x in [1, 2, 3, 4, 5])
+for x in values:
+ print(x) # друкує -1 -2 -3 -4 -5
+
+# Включення у вигляді генератора можна явно перетворити у список
+values = (-x for x in [1, 2, 3, 4, 5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+# Декоратори
+# Декоратор – це функція вищого порядку, яка приймає та повертає функцію.
+# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в
+# список fruits, який повертає цільова функція get_fruits.
+def add_apples(func):
+ def get_fruits():
+ fruits = func()
+ fruits.append('Apple')
+ return fruits
+ return get_fruits
+
+@add_apples
+def get_fruits():
+ return ['Banana', 'Mango', 'Orange']
+
+# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому:
+# Banana, Mango, Orange, Apple
+print ', '.join(get_fruits())
+
+# У цьому прикладі beg обертає say
+# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення,
+# що повертається, буде змінено.
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Будь ласка! Я бідний :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Ви можете купити мені пива?"
+ return msg, say_please
+
+
+print say() # Ви можете купити мені пива?
+print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :(
+```
+
+## Готові до більшого?
+
+### Безкоштовні онлайн-матеріали
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [Официальная документация](http://docs.python.org/2.6/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+
+### Платні
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index 041641d3..63f224b7 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -5,7 +5,7 @@ contributors:
filename: learnvisualbasic.vb
---
-```vbnet
+```
Module Module1
Sub Main()
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 1e10416e..02ec7f7b 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -41,7 +41,7 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
void function_1(char c);
void function_2(void);
-// 如果函数出现在main()之后,那么必须在main()之前
+// 如果函数调用在main()之后,那么必须在main()之前
// 先声明一个函数原型
int add_two_ints(int x1, int x2); // 函数原型
diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown
index cdc2d808..e30041b3 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
---
-```vbnet
+```
Module Module1
Sub Main()