summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--c.html.markdown9
-rw-r--r--chapel.html.markdown4
-rw-r--r--coldfusion.html.markdown11
-rw-r--r--css.html.markdown35
-rw-r--r--d.html.markdown6
-rw-r--r--de-de/haskell-de.html.markdown101
-rw-r--r--de-de/scala-de.html.markdown518
-rw-r--r--de-de/yaml-de.html.markdown4
-rw-r--r--edn.html.markdown108
-rw-r--r--fa-ir/brainfuck-fa.html.markdown (renamed from fa-ir/brainfuck.html.markdown)0
-rw-r--r--fa-ir/javascript-fa.html.markdown (renamed from fa-ir/javascript.html.markdown)0
-rw-r--r--fr-fr/livescript-fr.html.markdown2
-rw-r--r--fsharp.html.markdown78
-rw-r--r--git.html.markdown14
-rw-r--r--haskell.html.markdown2
-rw-r--r--hu-hu/coffeescript-hu.html.markdown106
-rw-r--r--hu-hu/go-hu.html.markdown (renamed from hu-hu/go.html.markdown)0
-rw-r--r--hu-hu/ruby-hu.html.markdown (renamed from hu-hu/ruby.html.markdown)0
-rw-r--r--java.html.markdown83
-rw-r--r--javascript.html.markdown48
-rw-r--r--make.html.markdown2
-rw-r--r--markdown.html.markdown36
-rw-r--r--matlab.html.markdown22
-rw-r--r--ms-my/javascript-my.html.markdown588
-rw-r--r--nl-nl/amd-nl.html.markdown235
-rw-r--r--objective-c.html.markdown59
-rw-r--r--pt-br/c-pt.html.markdown71
-rw-r--r--pt-br/css-pt.html.markdown8
-rw-r--r--pt-br/java-pt.html.markdown213
-rw-r--r--pt-br/json-pt.html.markdown15
-rw-r--r--pt-br/sass-pt.html.markdown27
-rw-r--r--python.html.markdown32
-rw-r--r--ru-ru/clojure-ru.html.markdown2
-rw-r--r--ru-ru/java-ru.html.markdown2
-rw-r--r--ru-ru/javascript-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown4
-rw-r--r--ru-ru/python-ru.html.markdown2
-rw-r--r--ruby.html.markdown11
-rw-r--r--scala.html.markdown6
-rw-r--r--swift.html.markdown6
-rw-r--r--ta_in/css-ta.html.markdown (renamed from ta_in/css.html.markdown)0
-rw-r--r--ta_in/javascript-ta.html.markdown (renamed from ta_in/javascript.html.markdown)0
-rw-r--r--ta_in/json-ta.html.markdown (renamed from ta_in/json.html.markdown)0
-rw-r--r--ta_in/xml-ta.html.markdown (renamed from ta_in/xml.html.markdown)0
-rw-r--r--tr-tr/brainfuck-tr.html.markdown2
-rw-r--r--tr-tr/c-tr.html.markdown34
-rw-r--r--ua-ua/javascript-ua.html.markdown501
-rw-r--r--visualbasic.html.markdown3
-rw-r--r--xml.html.markdown155
-rw-r--r--zh-cn/haskell-cn.html.markdown6
-rw-r--r--zh-cn/java-cn.html.markdown2
51 files changed, 2595 insertions, 580 deletions
diff --git a/c.html.markdown b/c.html.markdown
index 3d632eab..7c2386ef 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -148,15 +148,10 @@ int main (int argc, char** argv)
printf("Enter the array size: "); // ask the user for an array size
int size;
fscanf(stdin, "%d", &size);
- char buf[size];
- fgets(buf, sizeof buf, stdin);
-
- // strtoul parses a string to an unsigned integer
- size_t size2 = strtoul(buf, NULL, 10);
- int var_length_array[size2]; // declare the VLA
+ int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- // A possible outcome of this program may be:
+ // Example:
// > Enter the array size: 10
// > sizeof array = 40
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 7252a3e4..866e92d2 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -629,7 +629,7 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){
}
writeln( toThisArray );
-// This is all very important in undestanding why the statement
+// This is all very important in understanding why the statement
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
// exhibits a runtime error.
// Even though the domain of the array and the loop-expression are
@@ -914,7 +914,7 @@ proc main(){
[ val in myBigArray ] val = 1 / val; // Parallel operation
// Atomic variables, common to many languages, are ones whose operations
- // occur uninterupted. Multiple threads can both modify atomic variables
+ // occur uninterrupted. Multiple threads can both modify atomic variables
// and can know that their values are safe.
// Chapel atomic variables can be of type bool, int, uint, and real.
var uranium: atomic int;
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index 70804a1e..d49ad254 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -3,13 +3,17 @@ language: coldfusion
filename: learncoldfusion.cfm
contributors:
- ["Wayne Boka", "http://wboka.github.io"]
+ - ["Kevin Morris", "https://twitter.com/kevinmorris"]
---
ColdFusion is a scripting language for web development.
[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
-```html
+### CFML
+_**C**old**F**usion **M**arkup **L**anguage_
+ColdFusion started as a tag-based language. Almost all functionality is available using tags.
+```html
<em>HTML tags have been provided for output readability</em>
<!--- Comments start with "<!---" and end with "--->" --->
@@ -314,8 +318,13 @@ ColdFusion is a scripting language for web development.
<cfoutput><p>#getWorld()#</p></cfoutput>
```
+### CFScript
+_**C**old**F**usion **S**cript_
+In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax.
+
## Further Reading
The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
+2. [Open Source Documentation](http://cfdocs.org/)
diff --git a/css.html.markdown b/css.html.markdown
index d8f30ca3..8ee4f4b9 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -6,20 +6,21 @@ contributors:
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+ - ["Tyler Mumford", "https://tylermumford.com"]
filename: learncss.css
---
-In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common.
+Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**.
-CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page.
+CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors.
-CSS lets you target different elements on an HTML page and assign different visual properties to them.
+This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
-This guide has been written for CSS 2, though CSS 3 is fast becoming popular.
-
-**NOTE:** Because CSS produces visual results, in order to learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/).
+**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
The main focus of this article is on the syntax and some general tips.
+## Syntax
+
```css
/* comments appear inside slash-asterisk, just like this line!
there are no "one-line comments"; this is the only comment style */
@@ -28,7 +29,7 @@ The main focus of this article is on the syntax and some general tips.
## SELECTORS
#################### */
-/* the selector is used to target an element on a page.
+/* the selector is used to target an element on a page. */
selector { property: value; /* more properties...*/ }
/*
@@ -69,7 +70,7 @@ div { }
[otherAttr|='en'] { font-size:smaller; }
-/* You can concatenate different selectors to create a narrower selector. Don't
+/* You can combine different selectors to create a more focused selector. Don't
put spaces between them. */
div.some-class[attr$='ue'] { }
@@ -92,7 +93,7 @@ div.some-parent.class-name { }
.i-am-any-element-before ~ .this-element { }
/* There are some selectors called pseudo classes that can be used to select an
- element when it is in a particular state */
+ element only when it is in a particular state */
/* for example, when the cursor hovers over an element */
selector:hover { }
@@ -103,7 +104,7 @@ selector:visited { }
/* or hasn't been visited */
selected:link { }
-/* or an element in focus */
+/* or an element is in focus */
selected:focus { }
/* any element that is the first child of its parent */
@@ -156,10 +157,10 @@ selector {
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: 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 hsla percentages with alpha */
+ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
/* Images as backgrounds of elements */
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
@@ -194,7 +195,7 @@ Save a CSS stylesheet with the extension `.css`.
## 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. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
+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 occuring later in the stylesheet overwrites a previous one.
This process is called cascading, hence the name Cascading Style Sheets.
@@ -238,10 +239,10 @@ Most of the features in CSS 2 (and many in CSS 3) are available across all brows
## Resources
-* To run a quick compatibility check, [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)
## Further Reading
diff --git a/d.html.markdown b/d.html.markdown
index 80c1dc65..6f3710ab 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -199,8 +199,8 @@ our getter and setter methods, and keep the clean syntax of
accessing members directly!
Other object-oriented goodies at our disposal
-include `interface`s, `abstract class`es,
-and `override`ing methods. D does inheritance just like Java:
+include interfaces, abstract classes,
+and overriding methods. D does inheritance just like Java:
Extend one class, implement as many interfaces as you please.
We've seen D's OOP facilities, but let's switch gears. D offers
@@ -247,7 +247,7 @@ void main() {
// and take advantage of as many cores as we have available.
auto arr = new double[1_000_000];
- // Use an index, and an array element by referece,
+ // Use an index, and an array element by reference,
// and just call parallel on the array!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
index 2c548961..d1a0008e 100644
--- a/de-de/haskell-de.html.markdown
+++ b/de-de/haskell-de.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
- ["Henrik Jürges", "https://github.com/santifa"]
+ - ["Nikolai Weh", "http://weh.hamburg"]
filename: haskell-de.hs
---
@@ -58,12 +59,13 @@ not False -- True
-- Strings und Zeichen
"Das ist ein String."
'a' -- Zeichen
-'Einfache Anfuehrungszeichen gehen nicht.' -- error!
+'Einfache Anführungszeichen gehen nicht.' -- error!
-- Strings können konkateniert werden.
"Hello " ++ "world!" -- "Hello world!"
-- Ein String ist eine Liste von Zeichen.
+['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!"
"Das ist eine String" !! 0 -- 'D'
@@ -76,11 +78,23 @@ not False -- True
[1, 2, 3, 4, 5]
[1..5]
--- Haskell unterstuetzt unendliche Listen!
-[1..] -- Die Liste aller natuerlichen Zahlen
+-- Die zweite Variante nennt sich die "range"-Syntax.
+-- Ranges sind recht flexibel:
+['A'..'F'] -- "ABCDEF"
+
+-- Es ist möglich eine Schrittweite anzugeben:
+[0,2..10] -- [0,2,4,6,8,10]
+[5..1] -- [], da Haskell standardmässig inkrementiert.
+[5,4..1] -- [5,4,3,2,1]
+
+-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index:
+[1..10] !! 3 -- 4
+
+-- Haskell unterstützt unendliche Listen!
+[1..] -- Die Liste aller natürlichen Zahlen
-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation"
--- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird.
+-- unterstützt. Haskell evaluiert erst etwas, wenn es benötigt wird.
-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir:
[1..] !! 999 -- 1000
@@ -92,12 +106,9 @@ not False -- True
-- Zwei Listen konkatenieren
[1..5] ++ [6..10]
--- Ein Element als Head hinzufuegen
+-- Ein Element als Head hinzufügen
0:[1..5] -- [0, 1, 2, 3, 4, 5]
--- Gibt den 5. Index zurueck
-[0..] !! 5 -- 5
-
-- Weitere Listenoperationen
head [1..5] -- 1
tail [1..5] -- [2, 3, 4, 5]
@@ -114,7 +125,8 @@ last [1..5] -- 5
-- Ein Tupel:
("haskell", 1)
--- Auf Elemente eines Tupels zugreifen:
+-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt
+-- zugreifen kann:
fst ("haskell", 1) -- "haskell"
snd ("haskell", 1) -- 1
@@ -140,9 +152,9 @@ add 1 2 -- 3
(//) a b = a `div` b
35 // 4 -- 8
--- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen.
+-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen.
fib x
- | x < 2 = x
+ | x < 2 = 1
| otherwise = fib (x - 1) + fib (x - 2)
-- Pattern Matching funktioniert ähnlich.
@@ -174,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15
-- 4. Mehr Funktionen
----------------------------------------------------
--- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt,
+-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt,
-- so wird sie eine neue Funktion gebildet ("curried").
-- Es findet eine partielle Applikation statt und die neue Funktion
-- nimmt die fehlenden Argumente auf.
@@ -190,23 +202,28 @@ foo 5 -- 15
-- Funktionskomposition
-- Die (.) Funktion verkettet Funktionen.
-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
--- multipliziert dieses Ergebnis mit 5.
-foo = (*5) . (+10)
+-- multipliziert dieses Ergebnis mit 4.
+foo = (*4) . (+10)
+
+-- (5 + 10) * 4 = 60
+foo 5 -- 60
--- (5 + 10) * 5 = 75
-foo 5 -- 75
+-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt.
+-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist
+-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator
+-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt,
+-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die
+-- Funktion auf der linken Seite verwendet wird.
+-- Mit `.` und `$` kann man sich so viele Klammern ersparen.
--- Haskell hat eine Funktion `$`. Diese ändert den Vorrang,
--- so dass alles links von ihr zuerst berechnet wird und
--- und dann an die rechte Seite weitergegeben wird.
--- Mit `.` und `$` kann man sich viele Klammern ersparen.
+(even (fib 7)) -- false
--- Vorher
-(even (fib 7)) -- true
+-- Äquivalent:
+even $ fib 7 -- false
--- Danach
-even . fib $ 7 -- true
+-- Funktionskomposition:
+even . fib $ 7 -- false
----------------------------------------------------
-- 5. Typensystem
@@ -221,31 +238,31 @@ even . fib $ 7 -- true
True :: Bool
-- Funktionen haben genauso Typen.
--- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt:
+-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt:
-- not :: Bool -> Bool
-- Eine Funktion die zwei Integer Argumente annimmt:
-- add :: Integer -> Integer -> Integer
-- Es ist guter Stil zu jeder Funktionsdefinition eine
--- Typdefinition darueber zu schreiben:
+-- Typdefinition darüber zu schreiben:
double :: Integer -> Integer
double x = x * 2
----------------------------------------------------
--- 6. If-Anweisung und Kontrollstrukturen
+-- 6. If-Ausdrücke und Kontrollstrukturen
----------------------------------------------------
--- If-Anweisung:
+-- If-Ausdruck:
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
--- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein.
--- Das Einruecken ist dabei äußerst wichtig.
+-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein.
+-- Die Einrückung ist dabei wichtig.
haskell = if 1 == 1
then "awesome"
else "awful"
--- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen.
+-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten.
case args of
"help" -> printHelp
"start" -> startProgram
@@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
-- die Abarbeitung sieht so aus:
-(2 * 3 + (2 * 2 + (2 * 1 + 4)))
+(2 * 1 + (2 * 2 + (2 * 3 + 4)))
----------------------------------------------------
-- 7. Datentypen
@@ -300,7 +317,7 @@ data Maybe a = Nothing | Just a
-- Diese sind alle vom Typ Maybe:
Just "hello" -- vom Typ `Maybe String`
Just 1 -- vom Typ `Maybe Int`
-Nothing -- vom Typ `Maybe a` fuer jedes `a`
+Nothing -- vom Typ `Maybe a` für jedes `a`
----------------------------------------------------
-- 8. Haskell IO
@@ -309,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a`
-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären,
-- aber man kann die grundlegenden Dinge erklären.
--- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen.
--- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel:
+-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen.
+-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel:
main :: IO ()
main = putStrLn $ "Hello, sky! " ++ (say Blue)
@@ -338,10 +355,10 @@ sayHello = do
-- an die Variable "name" gebunden
putStrLn $ "Hello, " ++ name
--- Uebung: Schreibe deine eigene Version von `interact`,
+-- Übung: Schreibe deine eigene Version von `interact`,
-- die nur eine Zeile einliest.
--- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt.
+-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt.
-- Um `sayHello` laufen zulassen kommentiere die Definition von `main`
-- aus und ersetze sie mit:
-- main = sayHello
@@ -359,7 +376,7 @@ action = do
input1 <- getLine
input2 <- getLine
-- Der Typ von `do` ergibt sich aus der letzten Zeile.
- -- `return` ist eine Funktion und keine Schluesselwort
+ -- `return` ist eine Funktion und keine Schlüsselwort
return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
-- Nun können wir `action` wie `getLine` benutzen:
@@ -370,7 +387,7 @@ main'' = do
putStrLn result
putStrLn "This was all, folks!"
--- Der Typ `IO` ist ein Beispiel fuer eine Monade.
+-- Der Typ `IO` ist ein Beispiel für eine Monade.
-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit
-- eine rein funktional Sprache zu sein.
-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO)
@@ -387,7 +404,7 @@ main'' = do
-- Starte die REPL mit dem Befehl `ghci`
-- Nun kann man Haskell Code eingeben.
--- Alle neuen Werte muessen mit `let` gebunden werden:
+-- Alle neuen Werte müssen mit `let` gebunden werden:
let foo = 5
@@ -396,7 +413,7 @@ let foo = 5
>:t foo
foo :: Integer
--- Auch jede `IO ()` Funktion kann ausgefuehrt werden.
+-- Auch jede `IO ()` Funktion kann ausgeführt werden.
> sayHello
What is your name?
@@ -420,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
Haskell ist sehr einfach zu installieren.
Hohl es dir von [hier](http://www.haskell.org/platform/).
-Eine sehr viele langsamere Einfuehrung findest du unter:
+Eine sehr viele langsamere Einführung findest du unter:
[Learn you a Haskell](http://learnyouahaskell.com/) oder
[Real World Haskell](http://book.realworldhaskell.org/).
diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown
index 7fd299b4..456403a2 100644
--- a/de-de/scala-de.html.markdown
+++ b/de-de/scala-de.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Ha-Duong Nguyen", "http://reference-error.org"]
+ - ["Dennis Keller", "github.com/denniskeller"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
filename: learnscala-de.scala
@@ -16,167 +17,172 @@ für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben
zu erledigen. Scala hat einen akademischen Hintergrund und wurde an
der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt.
-
-# 0. Umgebung einrichten
+```scala
+/*
Scala Umgebung einrichten:
1. Scala binaries herunterladen- http://www.scala-lang.org/downloads
2. Unzip/untar in ein Verzeichnis
3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen
4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt:
-```
+
scala>
-```
Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter.
Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt
ausgegeben.
Als nächstes beschäftigen wir uns mit ein paar Scala Basics.
+*/
-# 1. Basics
-Einzeilige Kommentare beginnen mit zwei vorwärts Slash
+/////////////////////////////////////////////////
+// 1. Basics
+/////////////////////////////////////////////////
+
+// Einzeilige Kommentare beginnen mit zwei Slashes
/*
- Mehrzeilige Kommentare, werden starten
- mit Slash-Stern und enden mit Stern-Slash
+ Mehrzeilige Kommentare, starten
+ mit einem Slash-Stern und enden mit einem Stern-Slash
*/
// Einen Wert, und eine zusätzliche neue Zeile ausgeben
-```
+
println("Hello world!")
println(10)
-```
+
// Einen Wert, ohne eine zusätzliche neue Zeile ausgeben
-```
+
print("Hello world")
-```
-// Variablen werden entweder mit var oder val deklariert.
-// Deklarationen mit val sind immutable, also unveränderlich
-// Deklarationen mit var sind mutable, also veränderlich
-// Immutability ist gut.
-```
+/*
+ Variablen werden entweder mit var oder val deklariert.
+ Deklarationen mit val sind immutable, also unveränderlich
+ Deklarationen mit var sind mutable, also veränderlich
+ Immutability ist gut.
+*/
val x = 10 // x ist 10
x = 20 // error: reassignment to val
var y = 10
y = 20 // y ist jetzt 20
-```
-Scala ist eine statisch getypte Sprache, auch wenn in dem o.g. Beispiel
+/*
+Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel
keine Typen an x und y geschrieben haben.
-In Scala ist etwas eingebaut, was sich Type Inference nennt. D.h. das der
-Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine ist,
-so dass der Typ nicht jedes mal angegeben werden soll.
+In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der
+Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist,
+so dass der Typ nicht jedes mal angegeben werden muss.
Einen Typ gibt man bei einer Variablendeklaration wie folgt an:
-```
+*/
val z: Int = 10
val a: Double = 1.0
-```
+
// Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0
-```
+
val b: Double = 10
-```
+
// Boolean Werte
-```
+
true
false
-```
+
// Boolean Operationen
-```
+
!true // false
!false // true
true == false // false
10 > 5 // true
-```
+
// Mathematische Operationen sind wie gewohnt
-```
+
1 + 1 // 2
2 - 1 // 1
5 * 3 // 15
6 / 2 // 3
6 / 4 // 1
6.0 / 4 // 1.5
-```
+
// Die Auswertung eines Ausdrucks in der REPL gibt den Typ
// und das Ergebnis zurück.
-```
+
scala> 1 + 7
res29: Int = 8
-```
+/*
Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt
von Typ Int ist und einen Wert 0 hat.
"res29" ist ein sequentiell generierter name, um das Ergebnis des
Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein...
-
+*/
"Scala strings werden in doppelten Anführungszeichen eingeschlossen"
'a' // A Scala Char
// 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error
// Für Strings gibt es die üblichen Java Methoden
-```
+
"hello world".length
"hello world".substring(2, 6)
"hello world".replace("C", "3")
-```
+
// Zusätzlich gibt es noch extra Scala Methoden
// siehe: scala.collection.immutable.StringOps
-```
+
"hello world".take(5)
"hello world".drop(5)
-```
+
// String interpolation: prefix "s"
-```
+
val n = 45
s"We have $n apples" // => "We have 45 apples"
-```
-// Ausdrücke im innern von interpolierten Strings gibt es auch
-```
+
+// Ausdrücke im Innern von interpolierten Strings gibt es auch
+
val a = Array(11, 9, 6)
val n = 100
s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
-```
+
// Formatierung der interpolierten Strings mit dem prefix "f"
-```
+
f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
-```
+
// Raw Strings, ignorieren Sonderzeichen.
-```
+
raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
-```
+
// Manche Zeichen müssen "escaped" werden, z.B.
// ein doppeltes Anführungszeichen in innern eines Strings.
-```
+
"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
-```
+
// Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht
// und Anführungszeichen enthalten kann.
-```
+
val html = """<form id="daform">
<p>Press belo', Joe</p>
<input type="submit">
</form>"""
-```
-# 2. Funktionen
+
+/////////////////////////////////////////////////
+// 2. Funktionen
+/////////////////////////////////////////////////
// Funktionen werden so definiert
//
@@ -184,74 +190,74 @@ val html = """<form id="daform">
//
// Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck
// in einer Funktion der Rückgabewert.
-```
+
def sumOfSquares(x: Int, y: Int): Int = {
val x2 = x * x
val y2 = y * y
x2 + y2
}
-```
+
// Die geschweiften Klammern können weggelassen werden, wenn
// die Funktion nur aus einem einzigen Ausdruck besteht:
-```
+
def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
-```
+
// Syntax für Funktionsaufrufe:
-```
+
sumOfSquares(3, 4) // => 25
-```
+
// In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können
// Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei
// Variablen, auch bei Funktionen greift:
-```
+
def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist
-```
+
// Funktionen können default parameter haben:
-```
+
def addWithDefault(x: Int, y: Int = 5) = x + y
addWithDefault(1, 2) // => 3
addWithDefault(1) // => 6
-```
+
// Anonyme Funktionen sehen so aus:
-```
+
(x: Int) => x * x
-```
+
// Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen
// sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist.
// Beachte den Typ "Int => Int", dies beschreibt eine Funktion,
// welche Int als Parameter erwartet und Int zurückgibt.
-```
+
val sq: Int => Int = x => x * x
-```
+
// Anonyme Funktionen benutzt man ganz normal:
-```
+
sq(10) // => 100
-```
+
// Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird,
// bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen,
// indem die Parameter als Unterstrich "_" in der Parameterreihenfolge
// verwendet werden. Diese anonymen Funktionen werden sehr häufig
// verwendet.
-```
+
val addOne: Int => Int = _ + 1
val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3)
addOne(5) // => 6
weirdSum(2, 4) // => 16
-```
+
// Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung
// nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus
// dem innersten def, welches den return Ausdruck umgibt, zurück.
// "return" hat keinen Effekt in anonymen Funktionen:
-```
+
def foo(x: Int): Int = {
val anonFunc: Int => Int = { z =>
if (z > 5)
@@ -261,28 +267,30 @@ def foo(x: Int): Int = {
}
anonFunc(x) // Zeile ist der return Wert von foo
}
-```
-# 3. Flow Control
-## Wertebereiche und Schleifen
-```
+/////////////////////////////////////////////////
+// 3. Flow Control
+/////////////////////////////////////////////////
+
+// Wertebereiche und Schleifen
+
1 to 5
val r = 1 to 5
r.foreach(println)
r foreach println
(5 to 1 by -1) foreach (println)
-```
-// Scala ist syntaktisch sehr grosszügig, Semikolons am Zeilenende
+
+// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende
// sind optional, beim Aufruf von Methoden können die Punkte
// und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden
// while Schleife
-```
+
var i = 0
while (i < 10) { println("i " + i); i += 1 }
i // i ausgeben, res3: Int = 10
-```
+
// Beachte: while ist eine Schleife im klassischen Sinne -
// Sie läuft sequentiell ab und verändert die loop-Variable.
@@ -291,28 +299,28 @@ i // i ausgeben, res3: Int = 10
// und zu parellelisieren.
// Ein do while Schleife
-```
+
do {
println("x ist immer noch weniger wie 10")
x += 1
} while (x < 10)
-```
+
// Endrekursionen sind ideomatisch um sich wiederholende
// Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen
// return Typ, der Compiler kann ihn nicht erraten.
// Unit, in diesem Beispiel.
-```
+
def showNumbersInRange(a: Int, b: Int): Unit = {
print(a)
if (a < b)
showNumbersInRange(a + 1, b)
}
showNumbersInRange(1, 14)
-```
-## Conditionals
-```
+
+// Conditionals
+
val x = 10
if (x == 1) println("yeah")
if (x == 10) println("yeah")
@@ -320,186 +328,193 @@ if (x == 11) println("yeah")
if (x == 11) println ("yeah") else println("nay")
println(if (x == 10) "yeah" else "nope")
val text = if (x == 10) "yeah" else "nope"
-```
-# 4. Daten Strukturen (Array, Map, Set, Tuples)
-## Array
-```
+/////////////////////////////////////////////////
+// 4. Daten Strukturen (Array, Map, Set, Tuples)
+/////////////////////////////////////////////////
+
+// Array
+
val a = Array(1, 2, 3, 5, 8, 13)
a(0)
a(3)
a(21) // Exception
-```
-## Map - Speichert Key-Value-Paare
-```
+
+// Map - Speichert Key-Value-Paare
+
val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
m("fork")
m("spoon")
m("bottle") // Exception
val safeM = m.withDefaultValue("no lo se")
safeM("bottle")
-```
-## Set - Speichert Unikate, unsortiert (sortiert -> SortedSet)
-```
+
+// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet)
+
val s = Set(1, 3, 7)
s(0) //false
s(1) //true
val s = Set(1,1,3,3,7)
s: scala.collection.immutable.Set[Int] = Set(1, 3, 7)
-```
-## Tuple - Speichert beliebige Daten und "verbindet" sie miteinander
+
+// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander
// Ein Tuple ist keine Collection.
-```
+
(1, 2)
(4, 3, 2)
(1, 2, "three")
(a, 2, "three")
-```
+
// Hier ist der Rückgabewert der Funktion ein Tuple
// Die Funktion gibt das Ergebnis, so wie den Rest zurück.
-```
+
val divideInts = (x: Int, y: Int) => (x / y, x % y)
divideInts(10, 3)
-```
+
// Um die Elemente eines Tuples anzusprechen, benutzt man diese
// Notation: _._n wobei n der index des Elements ist (Index startet bei 1)
-```
+
val d = divideInts(10, 3)
d._1
d._2
-```
-# 5. Objekt Orientierte Programmierung
-Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar
-zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in
-einem Scala file selten alleine zu finden sind.
-Die einzigen Top-Level Konstrukte in Scala sind nämlich:
-- Klassen (classes)
-- Objekte (objects)
-- case classes
-- traits
+/////////////////////////////////////////////////
+// 5. Objektorientierte Programmierung
+/////////////////////////////////////////////////
+
+/*
+ Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar
+ zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in
+ einem Scala file selten alleine zu finden sind.
+ Die einzigen Top-Level Konstrukte in Scala sind nämlich:
+
+ - Klassen (classes)
+ - Objekte (objects)
+ - case classes
+ - traits
-Diesen Sprachelemente wenden wir uns jetzt zu.
+ Diesen Sprachelemente wenden wir uns jetzt zu.
+*/
-## Klassen
+// Klassen
// Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen
// anderen Sprachen auch.
// erzeugt Klasse mit default Konstruktor
-```
+
class Hund
scala> val t = new Hund
t: Hund = Hund@7103745
-```
+
// Der Konstruktor wird direkt hinter dem Klassennamen deklariert.
-```
+
class Hund(sorte: String)
scala> val t = new Hund("Dackel")
t: Hund = Hund@14be750c
scala> t.sorte //error: value sorte is not a member of Hund
-```
+
// Per val wird aus dem Attribut ein unveränderliches Feld der Klasse
// Per var wird aus dem Attribut ein veränderliches Feld der Klasse
-```
+
class Hund(val sorte: String)
scala> val t = new Hund("Dackel")
t: Hund = Hund@74a85515
scala> t.sorte
res18: String = Dackel
-```
+
// Methoden werden mit def geschrieben
-```
+
def bark = "Woof, woof!"
-```
+
// Felder und Methoden können public, protected und private sein
// default ist public
// private ist nur innerhalb des deklarierten Bereichs sichtbar
-```
+
class Hund {
private def x = ...
def y = ...
}
-```
+
// protected ist nur innerhalb des deklarierten und aller
// erbenden Bereiche sichtbar
-```
+
class Hund {
protected def x = ...
}
class Dackel extends Hund {
// x ist sichtbar
}
-```
-## Object
-Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog.
-"companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so
-ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse
-benutzen ohne ein Objekt instanziieren zu müssen.
-Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn
-es genauso heisst und in derselben Datei wie die Klasse definiert wurde.
-```
+
+// Object
+// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog.
+// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so
+// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse
+// benutzen ohne ein Objekt instanziieren zu müssen.
+// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn
+// es genauso heisst und in derselben Datei wie die Klasse definiert wurde.
+
object Hund {
def alleSorten = List("Pitbull", "Dackel", "Retriever")
def createHund(sorte: String) = new Hund(sorte)
}
-```
-## Case classes
-Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra
-Funktionalität erweitern. Mit Case Klassen bekommt man ein paar
-Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B.
-ein companion object mit den entsprechenden Methoden,
-Hilfsmethoden wie toString(), equals() und hashCode() und auch noch
-Getter für unsere Attribute (das Angeben von val entfällt dadurch)
-```
+
+// Case classes
+// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra
+// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar
+// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B.
+// ein companion object mit den entsprechenden Methoden,
+// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch
+// Getter für unsere Attribute (das Angeben von val entfällt dadurch)
+
class Person(val name: String)
class Hund(val sorte: String, val farbe: String, val halter: Person)
-```
+
// Es genügt das Schlüsselwort case vor die Klasse zu schreiben.
-```
+
case class Person(name: String)
case class Hund(sorte: String, farbe: String, halter: Person)
-```
+
// Für neue Instanzen brauch man kein "new"
-```
+
val dackel = Hund("dackel", "grau", Person("peter"))
val dogge = Hund("dogge", "grau", Person("peter"))
-```
+
// getter
-```
+
dackel.halter // => Person = Person(peter)
-```
+
// equals
-```
+
dogge == dackel // => false
-```
+
// copy
// otherGeorge == Person("george", "9876")
-```
+
val otherGeorge = george.copy(phoneNumber = "9876")
-```
-## Traits
-Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp
-und Methodensignaturen. Scala erlaubt allerdings das teilweise
-implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt.
-Traits können von anderen Traits oder Klassen erben, aber nur von
-parameterlosen.
-```
+
+// Traits
+// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp
+// und Methodensignaturen. Scala erlaubt allerdings das teilweise
+// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt.
+// Traits können von anderen Traits oder Klassen erben, aber nur von
+// parameterlosen.
+
trait Hund {
def sorte: String
def farbe: String
@@ -511,9 +526,9 @@ class Bernhardiner extends Hund{
val farbe = "braun"
def beissen = false
}
-```
+
-```
+
scala> b
res0: Bernhardiner = Bernhardiner@3e57cd70
scala> b.sorte
@@ -522,10 +537,10 @@ scala> b.bellen
res2: Boolean = true
scala> b.beissen
res3: Boolean = false
-```
+
// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden
-```
+
trait Bellen {
def bellen: String = "Woof"
}
@@ -541,25 +556,27 @@ scala> val b = new Bernhardiner
b: Bernhardiner = Bernhardiner@7b69c6ba
scala> b.bellen
res0: String = Woof
-```
-# 6. Pattern Matching
-Pattern matching in Scala ist ein sehr nützliches und wesentlich
-mächtigeres Feature als Vergleichsfunktionen in Java. In Scala
-benötigt ein case Statement kein "break", ein fall-through gibt es nicht.
-Mehrere Überprüfungen können mit einem Statement gemacht werden.
-Pattern matching wird mit dem Schlüsselwort "match" gemacht.
-```
+/////////////////////////////////////////////////
+// 6. Pattern Matching
+/////////////////////////////////////////////////
+
+// Pattern matching in Scala ist ein sehr nützliches und wesentlich
+// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala
+// benötigt ein case Statement kein "break", ein fall-through gibt es nicht.
+// Mehrere Überprüfungen können mit einem Statement gemacht werden.
+// Pattern matching wird mit dem Schlüsselwort "match" gemacht.
+
val x = ...
x match {
case 2 =>
case 3 =>
case _ =>
}
-```
+
// Pattern Matching kann auf beliebige Typen prüfen
-```
+
val any: Any = ...
val gleicht = any match {
case 2 | 3 | 5 => "Zahl"
@@ -568,19 +585,19 @@ val gleicht = any match {
case 45.35 => "Double"
case _ => "Unbekannt"
}
-```
+
// und auf Objektgleichheit
-```
+
def matchPerson(person: Person): String = person match {
case Person("George", nummer) => "George! Die Nummer ist " + number
case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer
case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer
}
-```
+
// Und viele mehr...
-```
+
val email = "(.*)@(.*)".r // regex
def matchEverything(obj: Any): String = obj match {
// Werte:
@@ -600,18 +617,21 @@ def matchEverything(obj: Any): String = obj match {
// Patterns kann man ineinander schachteln:
case List(List((1, 2, "YAY"))) => "Got a list of list of tuple"
}
-```
+
// Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden
// Ganze Funktionen können Patterns sein
-```
+
val patternFunc: Person => String = {
case Person("George", number) => s"George's number: $number"
case Person(name, number) => s"Random person's number: $number"
}
-```
-# 7. Higher-order functions
+
+/////////////////////////////////////////////////
+// 37. Higher-order functions
+/////////////////////////////////////////////////
+
Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden
als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen
higher-order functions
@@ -621,116 +641,117 @@ Nennenswerte sind:
"filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall"
## List
-```
+
def isGleichVier(a:Int) = a == 4
val list = List(1, 2, 3, 4)
val resultExists4 = list.exists(isEqualToFour)
-```
+
## map
// map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt
// eine neue Liste
// Funktion erwartet ein Int und returned ein Int
-```
+
val add10: Int => Int = _ + 10
-```
+
// add10 wird auf jedes Element angewendet
-```
+
List(1, 2, 3) map add10 // => List(11, 12, 13)
-```
+
// Anonyme Funktionen können anstatt definierter Funktionen verwendet werden
-```
+
List(1, 2, 3) map (x => x + 10)
-```
+
// Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion
// verwendet. Er wird an die Variable gebunden.
-```
+
List(1, 2, 3) map (_ + 10)
-```
+
// Wenn der anonyme Block und die Funtion beide EIN Argument erwarten,
// kann sogar der Unterstrich weggelassen werden.
-```
+
List("Dom", "Bob", "Natalia") foreach println
-```
-## filter
+
+// filter
// filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet
// alle Elemente die auf das Prädikat passen
-```
+
List(1, 2, 3) filter (_ > 2) // => List(3)
case class Person(name: String, age: Int)
List(
Person(name = "Dom", age = 23),
Person(name = "Bob", age = 30)
).filter(_.age > 25) // List(Person("Bob", 30))
-```
-## reduce
+
+// reduce
// reduce nimmt zwei Elemente und kombiniert sie zu einem Element,
// und zwar solange bis nur noch ein Element da ist.
-## foreach
+// foreach
// foreach gibt es für einige Collections
-```
+
val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
-```
-## For comprehensions
+
+// For comprehensions
// Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets.
// Dies ist keine for-Schleife.
-```
+
for { n <- s } yield sq(n)
val nSquared2 = for { n <- s } yield sq(n)
for { n <- nSquared2 if n < 10 } yield n
for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
-```
+
/////////////////////////////////////////////////
-# 8. Implicits
+// 8. Implicits
/////////////////////////////////////////////////
-**ACHTUNG:**
-Implicits sind ein sehr mächtiges Sprachfeature von Scala. Es sehr einfach
-sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am
-besten erst dann benutzen, wenn man versteht wie sie funktionieren.
-Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle
-vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles
-machen kann.
-Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren.
+// **ACHTUNG:**
+// Implicits sind ein sehr mächtiges Sprachfeature von Scala.
+// Es sehr einfach
+// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am
+// besten erst dann benutzen, wenn man versteht wie sie funktionieren.
+// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle
+// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles
+// machen kann.
+// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren.
// Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte
// zu "implicit Methods" werden.
-```
+
implicit val myImplicitInt = 100
implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte)
-```
+
// implicit ändert nicht das Verhalten eines Wertes oder einer Funktion
-```
+
myImplicitInt + 2 // => 102
myImplicitFunction("Pitbull").sorte // => "Golden Pitbull"
-```
+
// Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein
// anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von
// implicit Funktionsparametern
// Diese Funktion hat zwei Parameter: einen normalen und einen implicit
-```
+
def sendGreetings(toWhom: String)(implicit howMany: Int) =
s"Hello $toWhom, $howMany blessings to you and yours!"
-```
+
// Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet
-```
+
sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!"
-```
+
// Wird der implicit Parameter jedoch weggelassen, wird ein anderer
// implicit Wert vom gleichen Typ genommen. Der Compiler sucht im
@@ -739,66 +760,69 @@ sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!
// geforderten Typ konvertieren kann.
// Hier also: "myImplicitInt", da ein Int gesucht wird
-```
+
sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
-```
+
// bzw. "myImplicitFunction"
// Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und
// dann wird die Methode aufgerufen
-```
+
"Retriever".sorte // => "Golden Retriever"
-```
-# 9. Misc
-## Importe
-```
+
+/////////////////////////////////////////////////
+// 19. Misc
+/////////////////////////////////////////////////
+// Importe
+
import scala.collection.immutable.List
-```
+
// Importiere alle Unterpackages
-```
+
import scala.collection.immutable._
-```
+
// Importiere verschiedene Klassen mit einem Statement
-```
+
import scala.collection.immutable.{List, Map}
-```
+
// Einen Import kann man mit '=>' umbenennen
-```
+
import scala.collection.immutable.{List => ImmutableList}
-```
+
// Importiere alle Klasses, mit Ausnahem von....
// Hier ohne: Map and Set:
-```
+
import scala.collection.immutable.{Map => _, Set => _, _}
-```
-## Main
-```
+
+// Main
+
object Application {
def main(args: Array[String]): Unit = {
- // stuff goes here.
+ // Sachen kommen hierhin
}
}
-```
-## I/O
+
+// I/O
// Eine Datei Zeile für Zeile lesen
-```
+
import scala.io.Source
for(line <- Source.fromFile("myfile.txt").getLines())
println(line)
-```
+
// Eine Datei schreiben
-```
+
val writer = new PrintWriter("myfile.txt")
writer.write("Schreibe Zeile" + util.Properties.lineSeparator)
writer.write("Und noch eine Zeile" + util.Properties.lineSeparator)
writer.close()
+
```
## Weiterführende Hinweise
diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown
index 19ea9e87..a46c30f6 100644
--- a/de-de/yaml-de.html.markdown
+++ b/de-de/yaml-de.html.markdown
@@ -30,7 +30,7 @@ null_Wert: null
Schlüssel mit Leerzeichen: value
# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber:
jedoch: "Ein String in Anführungzeichen"
-"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst."
+"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst."
# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text)
# oder ein 'folded block' (> gefolgt vom text).
@@ -64,7 +64,7 @@ eine_verschachtelte_map:
hallo: hallo
# Schlüssel müssen nicht immer String sein.
-0.25: ein Float-Wert als Schluessel
+0.25: ein Float-Wert als Schlüssel
# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels
? |
diff --git a/edn.html.markdown b/edn.html.markdown
new file mode 100644
index 00000000..0a0dc9b5
--- /dev/null
+++ b/edn.html.markdown
@@ -0,0 +1,108 @@
+---
+language: edn
+filename: learnedn.edn
+contributors:
+ - ["Jason Yeo", "https://github.com/jsyeo"]
+---
+
+Extensible Data Notation or EDN for short is a format for serializing data.
+
+The notation is used internally by Clojure to represent programs and it also
+used as a data transfer format like JSON. Though it is more commonly used in
+Clojure land, there are implementations of EDN for many other languages.
+
+The main benefit of EDN over JSON and YAML is that it is extensible, which we
+will see how it is extended later on.
+
+```Clojure
+; Comments start with a semicolon.
+; Anything after the semicolon is ignored.
+
+;;;;;;;;;;;;;;;;;;;
+;;; Basic Types ;;;
+;;;;;;;;;;;;;;;;;;;
+
+nil ; also known in other languages as null
+
+; Booleans
+true
+false
+
+; Strings are enclosed in double quotes
+"hungarian breakfast"
+"farmer's cheesy omelette"
+
+; Characters are preceeded by backslashes
+\g \r \a \c \e
+
+; Keywords start with a colon. They behave like enums. Kind of
+; like symbols in Ruby.
+:eggs
+:cheese
+:olives
+
+; Symbols are used to represent identifiers. They start with #.
+; You can namespace symbols by using /. Whatever preceeds / is
+; the namespace of the name.
+#spoon
+#kitchen/spoon ; not the same as #spoon
+#kitchen/fork
+#github/fork ; you can't eat with this
+
+; Integers and floats
+42
+3.14159
+
+; Lists are sequences of values
+(:bun :beef-patty 9 "yum!")
+
+; Vectors allow random access
+[:gelato 1 2 -2]
+
+; Maps are associative data structures that associates the key with its value
+{:eggs 2
+ :lemon-juice 3.5
+ :butter 1}
+
+; You're not restricted to using keywords as keys
+{[1 2 3 4] "tell the people what she wore",
+ [5 6 7 8] "the more you see the more you hate"}
+
+; You may use commas for readability. They are treated as whitespaces.
+
+; Sets are collections that contain unique elements.
+#{:a :b 88 "huat"}
+
+;;;;;;;;;;;;;;;;;;;;;;;
+;;; Tagged Elements ;;;
+;;;;;;;;;;;;;;;;;;;;;;;
+
+; EDN can be extended by tagging elements with # symbols.
+
+#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
+
+; Let me explain this with a clojure example. Suppose I want to transform that
+; piece of edn into a MenuItem record.
+
+(defrecord MenuItem [name rating])
+
+; To transform edn to clojure values, I will need to use the built in EDN
+; reader, edn/read-string
+
+(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
+; -> {:eggs 2 :butter 1 :flour 5}
+
+; To transform tagged elements, define the reader function and pass a map
+; that maps tags to reader functions to edn/read-string like so
+
+(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
+ "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
+; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
+
+```
+
+# References
+
+- [EDN spec](https://github.com/edn-format/edn)
+- [Implementations](https://github.com/edn-format/edn/wiki/Implementations)
+- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/)
diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck-fa.html.markdown
index ef2bcba3..ef2bcba3 100644
--- a/fa-ir/brainfuck.html.markdown
+++ b/fa-ir/brainfuck-fa.html.markdown
diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript-fa.html.markdown
index fe3555af..fe3555af 100644
--- a/fa-ir/javascript.html.markdown
+++ b/fa-ir/javascript-fa.html.markdown
diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown
index 9c3b8003..13bbffe5 100644
--- a/fr-fr/livescript-fr.html.markdown
+++ b/fr-fr/livescript-fr.html.markdown
@@ -4,7 +4,7 @@ filename: learnLivescript-fr.ls
contributors:
- ["Christina Whyte", "http://github.com/kurisuwhyte/"]
translators:
- - ["Morgan Bohn", "https://github.com/morganbohn"]
+ - ["Morgan Bohn", "https://github.com/dotmobo"]
lang: fr-fr
---
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 76318d7d..d63b9f1d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www.
// The "let" keyword defines an (immutable) value
let myInt = 5
let myFloat = 3.14
-let myString = "hello" //note that no types needed
+let myString = "hello" // note that no types needed
// ------ Lists ------
-let twoToFive = [2;3;4;5] // Square brackets create a list with
+let twoToFive = [2; 3; 4; 5] // Square brackets create a list with
// semicolon delimiters.
let oneToFive = 1 :: twoToFive // :: creates list with new 1st element
-// The result is [1;2;3;4;5]
-let zeroToFive = [0;1] @ twoToFive // @ concats two lists
+// The result is [1; 2; 3; 4; 5]
+let zeroToFive = [0; 1] @ twoToFive // @ concats two lists
// IMPORTANT: commas are never used as delimiters, only semicolons!
@@ -53,7 +53,7 @@ add 2 3 // Now run the function.
// to define a multiline function, just use indents. No semicolons needed.
let evens list =
- let isEven x = x%2 = 0 // Define "isEven" as a sub function
+ let isEven x = x % 2 = 0 // Define "isEven" as a sub function
List.filter isEven list // List.filter is a library function
// with two parameters: a boolean function
// and a list to work on
@@ -75,7 +75,7 @@ let sumOfSquaresTo100piped =
// you can define lambdas (anonymous functions) using the "fun" keyword
let sumOfSquaresTo100withFun =
- [1..100] |> List.map (fun x -> x*x) |> List.sum
+ [1..100] |> List.map (fun x -> x * x) |> List.sum
// In F# there is no "return" keyword. A function always
// returns the value of the last expression used.
@@ -109,7 +109,7 @@ optionPatternMatch invalidValue
// The printf/printfn functions are similar to the
// Console.Write/WriteLine functions in C#.
printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true
-printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
+printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4]
// There are also sprintf/sprintfn functions for formatting data
// into a string, similar to String.Format in C#.
@@ -131,19 +131,19 @@ module FunctionExamples =
// basic usage of a function
let a = add 1 2
- printfn "1+2 = %i" a
+ printfn "1 + 2 = %i" a
// partial application to "bake in" parameters
let add42 = add 42
let b = add42 1
- printfn "42+1 = %i" b
+ printfn "42 + 1 = %i" b
// composition to combine functions
let add1 = add 1
let add2 = add 2
let add3 = add1 >> add2
let c = add3 7
- printfn "3+7 = %i" c
+ printfn "3 + 7 = %i" c
// higher order functions
[1..10] |> List.map add3 |> printfn "new list is %A"
@@ -151,7 +151,7 @@ module FunctionExamples =
// lists of functions, and more
let add6 = [add1; add2; add3] |> List.reduce (>>)
let d = add6 7
- printfn "1+2+3+7 = %i" d
+ printfn "1 + 2 + 3 + 7 = %i" d
// ================================================
// Lists and collection
@@ -168,12 +168,12 @@ module FunctionExamples =
module ListExamples =
// lists use square brackets
- let list1 = ["a";"b"]
+ let list1 = ["a"; "b"]
let list2 = "c" :: list1 // :: is prepending
let list3 = list1 @ list2 // @ is concat
// list comprehensions (aka generators)
- let squares = [for i in 1..10 do yield i*i]
+ let squares = [for i in 1..10 do yield i * i]
// prime number generator
let rec sieve = function
@@ -190,8 +190,8 @@ module ListExamples =
| [first; second] -> printfn "list is %A and %A" first second
| _ -> printfn "the list has more than two elements"
- listMatcher [1;2;3;4]
- listMatcher [1;2]
+ listMatcher [1; 2; 3; 4]
+ listMatcher [1; 2]
listMatcher [1]
listMatcher []
@@ -219,7 +219,7 @@ module ListExamples =
module ArrayExamples =
// arrays use square brackets with bar
- let array1 = [| "a";"b" |]
+ let array1 = [| "a"; "b" |]
let first = array1.[0] // indexed access using dot
// pattern matching for arrays is same as for lists
@@ -230,13 +230,13 @@ module ArrayExamples =
| [| first; second |] -> printfn "array is %A and %A" first second
| _ -> printfn "the array has more than two elements"
- arrayMatcher [| 1;2;3;4 |]
+ arrayMatcher [| 1; 2; 3; 4 |]
// Standard library functions just as for List
[| 1..10 |]
- |> Array.map (fun i -> i+3)
- |> Array.filter (fun i -> i%2 = 0)
+ |> Array.map (fun i -> i + 3)
+ |> Array.filter (fun i -> i % 2 = 0)
|> Array.iter (printfn "value is %i. ")
@@ -248,14 +248,14 @@ module SequenceExamples =
// sequences can use yield and
// can contain subsequences
let strange = seq {
- // "yield! adds one element
+ // "yield" adds one element
yield 1; yield 2;
// "yield!" adds a whole subsequence
yield! [5..10]
yield! seq {
for i in 1..10 do
- if i%2 = 0 then yield i }}
+ if i % 2 = 0 then yield i }}
// test
strange |> Seq.toList
@@ -280,11 +280,11 @@ module DataTypeExamples =
// Tuples are quick 'n easy anonymous types
// -- Use a comma to create a tuple
- let twoTuple = 1,2
- let threeTuple = "a",2,true
+ let twoTuple = 1, 2
+ let threeTuple = "a", 2, true
// Pattern match to unpack
- let x,y = twoTuple //sets x=1 y=2
+ let x, y = twoTuple // sets x = 1, y = 2
// ------------------------------------
// Record types have named fields
@@ -297,7 +297,7 @@ module DataTypeExamples =
let person1 = {First="John"; Last="Doe"}
// Pattern match to unpack
- let {First=first} = person1 //sets first="john"
+ let {First = first} = person1 // sets first="John"
// ------------------------------------
// Union types (aka variants) have a set of choices
@@ -331,7 +331,7 @@ module DataTypeExamples =
| Worker of Person
| Manager of Employee list
- let jdoe = {First="John";Last="Doe"}
+ let jdoe = {First="John"; Last="Doe"}
let worker = Worker jdoe
// ------------------------------------
@@ -383,8 +383,8 @@ module DataTypeExamples =
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine | Ten | Jack | Queen | King | Ace
- let hand = [ Club,Ace; Heart,Three; Heart,Ace;
- Spade,Jack; Diamond,Two; Diamond,Ace ]
+ let hand = [ Club, Ace; Heart, Three; Heart, Ace;
+ Spade, Jack; Diamond, Two; Diamond, Ace ]
// sorting
List.sort hand |> printfn "sorted hand is (low to high) %A"
@@ -419,14 +419,14 @@ module ActivePatternExamples =
| _ -> printfn "%c is something else" ch
// print a list
- ['a';'b';'1';' ';'-';'c'] |> List.iter printChar
+ ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar
// -----------------------------------
// FizzBuzz using active patterns
// -----------------------------------
// You can create partial matching patterns as well
- // Just use undercore in the defintion, and return Some if matched.
+ // Just use underscore in the defintion, and return Some if matched.
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
@@ -479,7 +479,7 @@ module AlgorithmExamples =
List.concat [smallerElements; [firstElem]; largerElements]
// test
- sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
+ sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A"
// ================================================
// Asynchronous Code
@@ -536,7 +536,7 @@ module NetCompatibilityExamples =
// ------- work with existing library functions -------
- let (i1success,i1) = System.Int32.TryParse("123");
+ let (i1success, i1) = System.Int32.TryParse("123");
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
// ------- Implement interfaces on the fly! -------
@@ -570,12 +570,12 @@ module NetCompatibilityExamples =
// abstract base class with virtual methods
[<AbstractClass>]
type Shape() =
- //readonly properties
+ // readonly properties
abstract member Width : int with get
abstract member Height : int with get
- //non-virtual method
+ // non-virtual method
member this.BoundingArea = this.Height * this.Width
- //virtual method with base implementation
+ // virtual method with base implementation
abstract member Print : unit -> unit
default this.Print () = printfn "I'm a shape"
@@ -586,19 +586,19 @@ module NetCompatibilityExamples =
override this.Height = y
override this.Print () = printfn "I'm a Rectangle"
- //test
- let r = Rectangle(2,3)
+ // test
+ let r = Rectangle(2, 3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
r.Print()
// ------- extension methods -------
- //Just as in C#, F# can extend existing classes with extension methods.
+ // Just as in C#, F# can extend existing classes with extension methods.
type System.String with
member this.StartsWithA = this.StartsWith "A"
- //test
+ // test
let s = "Alice"
printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
diff --git a/git.html.markdown b/git.html.markdown
index bedc9853..e7ca07d6 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Leo Rudberg" , "http://github.com/LOZORD"]
- ["Betsy Lorton" , "http://github.com/schbetsy"]
- ["Bruno Volcov", "http://github.com/volcov"]
+ - ["Andrew Taylor", "http://github.com/andrewjt71"]
filename: LearnGit.txt
---
@@ -333,6 +334,9 @@ $ git log --oneline
# Show merge commits only
$ git log --merges
+
+# Show all commits represented by an ASCII graph
+$ git log --graph
```
### merge
@@ -499,6 +503,16 @@ $ git reset 31f2bb1
# after the specified commit).
$ git reset --hard 31f2bb1
```
+### revert
+
+Revert can be used to undo a commit. It should not be confused with reset which restores
+the state of a project to a previous point. Revert will add a new commit which is the
+inverse of the specified commit, thus reverting it.
+
+```bash
+# Revert a specified commit
+$ git revert <commit>
+```
### rm
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 08611e63..936744a0 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -81,7 +81,7 @@ not False -- True
[5,4..1] -- [5, 4, 3, 2, 1]
-- indexing into a list
-[0..] !! 5 -- 5
+[1..10] !! 3 -- 4
-- You can also have infinite lists in Haskell!
[1..] -- a list of all the natural numbers
diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown
new file mode 100644
index 00000000..267db4d0
--- /dev/null
+++ b/hu-hu/coffeescript-hu.html.markdown
@@ -0,0 +1,106 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["Tamás Diószegi", "http://github.com/ditam"]
+filename: coffeescript-hu.coffee
+---
+
+A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni.
+Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik.
+
+Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található.
+
+```coffeescript
+# A CoffeeScript egy hipszter nyelv.
+# Követi több modern nyelv trendjeit.
+# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek.
+
+###
+A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak
+az eredményül kapott JavaScript kódban.
+
+Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával
+tisztában vagy.
+
+(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.)
+###
+
+# Értékadás:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Feltételes utasítások:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Függvények:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
+# Szám tartományok:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objektumok:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+# };
+
+# "Splat" jellegű függvény-paraméterek:
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
+
+# Létezés-vizsgálat:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Tömb értelmezések: (array comprehensions)
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
+
+## További források
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) \ No newline at end of file
diff --git a/hu-hu/go.html.markdown b/hu-hu/go-hu.html.markdown
index 638c9489..638c9489 100644
--- a/hu-hu/go.html.markdown
+++ b/hu-hu/go-hu.html.markdown
diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby-hu.html.markdown
index 169f2b8e..169f2b8e 100644
--- a/hu-hu/ruby.html.markdown
+++ b/hu-hu/ruby-hu.html.markdown
diff --git a/java.html.markdown b/java.html.markdown
index aae64ccf..84978ecc 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -128,7 +128,7 @@ public class LearnJava {
//
// BigInteger can be initialized using an array of bytes or a string.
- BigInteger fooBigInteger = new BigDecimal(fooByteArray);
+ BigInteger fooBigInteger = new BigInteger(fooByteArray);
// BigDecimal - Immutable, arbitrary-precision signed decimal number
@@ -144,7 +144,12 @@ public class LearnJava {
// or by initializing the unscaled value (BigInteger) and scale (int).
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
-
+
+ // Be wary of the constructor that takes a float or double as
+ // the inaccuracy of the float/double will be copied in BigDecimal.
+ // Prefer the String constructor when you need an exact value.
+
+ BigDecimal tenCents = new BigDecimal("0.1");
// Strings
@@ -186,9 +191,9 @@ public class LearnJava {
// operations perform as could be expected for a
// doubly-linked list.
// Maps - A set of objects that map keys to values. Map is
- // an interface and therefore cannot be instantiated.
- // The type of keys and values contained in a Map must
- // be specified upon instantiation of the implementing
+ // an interface and therefore cannot be instantiated.
+ // The type of keys and values contained in a Map must
+ // be specified upon instantiation of the implementing
// class. Each key may map to only one corresponding value,
// and each key may appear only once (no duplicates).
// HashMaps - This class uses a hashtable to implement the Map
@@ -207,8 +212,8 @@ public class LearnJava {
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
- System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
- System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int)
+ System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -416,7 +421,7 @@ public class LearnJava {
// easier way, by using something that is called Double Brace
// Initialization.
- private static final Set<String> COUNTRIES = HashSet<String>() {{
+ private static final Set<String> COUNTRIES = new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
@@ -697,6 +702,66 @@ public abstract class Mammal()
return true;
}
}
+
+
+// Enum Type
+//
+// An enum type is a special data type that enables for a variable to be a set
+// of predefined constants. The variable must be equal to one of the values that
+// have been predefined for it. Because they are constants, the names of an enum
+// type's fields are in uppercase letters. In the Java programming language, you
+// define an enum type by using the enum keyword. For example, you would specify
+// a days-of-the-week enum type as:
+
+public enum Day {
+ SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
+ THURSDAY, FRIDAY, SATURDAY
+}
+
+// We can use our enum Day like that:
+
+public class EnumTest {
+
+ // Variable Enum
+ Day day;
+
+ public EnumTest(Day day) {
+ this.day = day;
+ }
+
+ public void tellItLikeItIs() {
+ switch (day) {
+ case MONDAY:
+ System.out.println("Mondays are bad.");
+ break;
+
+ case FRIDAY:
+ System.out.println("Fridays are better.");
+ break;
+
+ case SATURDAY:
+ case SUNDAY:
+ System.out.println("Weekends are best.");
+ break;
+
+ default:
+ System.out.println("Midweek days are so-so.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTest firstDay = new EnumTest(Day.MONDAY);
+ firstDay.tellItLikeItIs(); // => Mondays are bad.
+ EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
+ thirdDay.tellItLikeItIs(); // => Midweek days are so-so.
+ }
+}
+
+// Enum types are much more powerful than we show above.
+// The enum body can include methods and other fields.
+// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
```
## Further Reading
@@ -720,7 +785,7 @@ The links provided here below are just to get an understanding of the topic, fee
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
**Online Practice and Tutorials**
diff --git a/javascript.html.markdown b/javascript.html.markdown
index cce488e1..98261334 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -16,9 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that
provides a standalone runtime for Google Chrome's V8 JavaScript engine, is
becoming more and more popular.
+JavaScript has a C-like syntax, so if you've used languages like C or Java,
+a lot of the basic syntax will already be familiar. Despite this, and despite
+the similarity in name, JavaScript's object model is significantly different to
+Java's.
+
```js
-// Comments are like C's. Single-line comments start with two slashes,
-/* and multiline comments start with slash-star
+// Single-line comments start with two slashes.
+/* Multiline comments start with slash-star,
and end with star-slash */
// Statements can be terminated by ;
@@ -36,7 +41,7 @@ doStuff()
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
// Doubles have a 52-bit mantissa, which is enough to store integers
-// up to about 9✕10¹⁵ precisely.
+// up to about 9✕10¹⁵ precisely.
3; // = 3
1.5; // = 1.5
@@ -96,6 +101,10 @@ false;
// Strings are concatenated with +
"Hello " + "world!"; // = "Hello world!"
+// ... which works with more than just strings
+"1, 2, " + 3; // = "1, 2, 3"
+"Hello " + ["world", "!"] // = "Hello world,!"
+
// and are compared with < and >
"a" < "b"; // = true
@@ -136,7 +145,7 @@ undefined; // used to indicate a value is not currently present (although
// character.
var someVar = 5;
-// if you leave the var keyword off, you won't get an error...
+// If you leave the var keyword off, you won't get an error...
someOtherVar = 10;
// ...but your variable will be created in the global scope, not in the scope
@@ -145,7 +154,7 @@ someOtherVar = 10;
// Variables declared without being assigned to are set to undefined.
var someThirdVar; // = undefined
-// if you wan't to declare a couple of variables, then you could use a comma
+// If you want to declare a couple of variables, then you could use a comma
// separator
var someFourthVar = 2, someFifthVar = 4;
@@ -194,8 +203,6 @@ myObj.myFourthKey; // = undefined
///////////////////////////////////
// 3. Logic and Control Structures
-// The syntax for this section is almost identical to Java's.
-
// The `if` structure works as you'd expect.
var count = 1;
if (count == 3){
@@ -223,15 +230,15 @@ for (var i = 0; i < 5; i++){
// will run 5 times
}
-//The For/In statement loops iterates over every property across the entire prototype chain
+// The for/in statement iterates over every property across the entire prototype chain.
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
for (var x in person){
description += person[x] + " ";
}
-//If only want to consider properties attached to the object itself,
-//and not its prototypes use hasOwnProperty() check
+// To only consider properties attached to the object itself
+// and not its prototypes, use the `hasOwnProperty()` check.
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
for (var x in person){
@@ -240,8 +247,9 @@ for (var x in person){
}
}
-//for/in should not be used to iterate over an Array where the index order is important.
-//There is no guarantee that for/in will return the indexes in any particular order
+// For/in should not be used to iterate over an Array where the index order
+// is important, as there is no guarantee that for/in will return the indexes
+// in any particular order.
// && is logical and, || is logical or
if (house.size == "big" && house.colour == "blue"){
@@ -256,7 +264,7 @@ var name = otherName || "default";
// The `switch` statement checks for equality with `===`.
-// use 'break' after each case
+// Use 'break' after each case
// or the cases after the correct one will be executed too.
grade = 'B';
switch (grade) {
@@ -503,6 +511,10 @@ myNumber === myNumberObj; // = false
if (0){
// This code won't execute, because 0 is falsy.
}
+if (new Number(0)){
+ // This code will execute, because wrapped numbers are objects, and objects
+ // are always truthy.
+}
// However, the wrapper objects and the regular builtins share a prototype, so
// you can actually add functionality to a string, for instance.
@@ -547,6 +559,13 @@ of the language.
[JavaScript: The Definitive Guide][6] is a classic guide and reference book.
+[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
+
+[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
+
+[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.
+
+
In addition to direct contributors to this article, some content is adapted from
Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
Mozilla Developer Network.
@@ -559,3 +578,6 @@ 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]: http://eloquentjavascript.net/
+[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
+[10]: http://jstherightway.org/
diff --git a/make.html.markdown b/make.html.markdown
index 563139d1..e8cfd2b5 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -234,10 +234,8 @@ bar = 'hello'
endif
```
-
### More Resources
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
-
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 2333110f..b956a5f2 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -11,7 +11,7 @@ Give me as much feedback as you want! / Feel free to fork and pull request!
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
+<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. 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
@@ -21,9 +21,9 @@ element's contents. -->
guide will attempt to clarify when features are universal or when they are
specific to a certain parser. -->
-<!-- Headers -->
+<!-- Headings -->
<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#) -->
+text you want to be in that element by a number of hashes (#). -->
# This is an <h1>
## This is an <h2>
### This is an <h3>
@@ -31,7 +31,7 @@ text you want to be in that element by a number of hashes (#) -->
##### This is an <h5>
###### This is an <h6>
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 -->
+<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. -->
This is an h1
=============
@@ -39,7 +39,7 @@ This is an h2
-------------
<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown -->
+<!-- Text can be easily styled as italic or bold using markdown. -->
*This text is in italics.*
_And so is this text._
@@ -85,7 +85,7 @@ There's a <br /> above me!
> How neat is that?
<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens -->
+<!-- Unordered lists can be made using asterisks, pluses, or hyphens. -->
* Item
* Item
@@ -103,21 +103,21 @@ or
- Item
- One last item
-<!-- Ordered lists are done with a number followed by a period -->
+<!-- Ordered lists are done with a number followed by a period. -->
1. Item one
2. Item two
3. Item three
<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea -->
+render the numbers in order, but this may not be a good idea. -->
1. Item one
1. Item two
1. Item three
<!-- (This renders the same as the above example) -->
-<!-- You can also use sublists -->
+<!-- You can also use sublists. -->
1. Item one
2. Item two
@@ -136,13 +136,13 @@ This checkbox below will be a checked HTML checkbox.
<!-- Code blocks -->
<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab -->
+a line with four spaces or a tab. -->
This is code
So is this
<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code -->
+inside your code. -->
my_array.each do |item|
puts item
@@ -152,7 +152,7 @@ inside your code -->
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. -->
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
def foobar
@@ -174,11 +174,11 @@ with or without spaces. -->
<!-- Links -->
<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses () -->
+the text to display in hard brackets [] followed by the url in parentheses (). -->
[Click me!](http://test.com/)
-<!-- You can also add a link title using quotes inside the parentheses -->
+<!-- You can also add a link title using quotes inside the parentheses. -->
[Click me!](http://test.com/ "Link to Test.com")
@@ -186,7 +186,7 @@ the text to display in hard brackets [] followed by the url in parentheses () --
[Go to music](/music/).
-<!-- Markdown also supports reference style links -->
+<!-- Markdown also supports reference style links. -->
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
@@ -198,7 +198,7 @@ the text to display in hard brackets [] followed by the url in parentheses () --
entirely. The references can be anywhere in your document and the reference IDs
can be anything so long as they are unique. -->
-<!-- There is also "implicit naming" which lets you use the link text as the id -->
+<!-- There is also "implicit naming" which lets you use the link text as the id. -->
[This][] is a link.
@@ -211,7 +211,7 @@ can be anything so long as they are unique. -->
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
-<!-- And reference style works as expected -->
+<!-- And reference style works as expected. -->
![This is the alt-attribute.][myimage]
@@ -233,7 +233,7 @@ I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
<!-- Keyboard keys -->
-<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys -->
+<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. -->
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 4d97834c..9d78978e 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -123,6 +123,7 @@ x(2:end) % ans = 32 53 7 1
x = [4; 32; 53; 7; 1] % Column vector
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9
% Matrices
A = [1 2 3; 4 5 6; 7 8 9]
@@ -205,6 +206,8 @@ transpose(A) % Transpose the matrix, which is the same as:
A one
ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
+A' % Concise version of complex transpose
+A.' % Concise version of transpose (without taking complex conjugate)
@@ -254,6 +257,8 @@ axis equal % Set aspect ratio so data units are the same in every direction
scatter(x, y); % Scatter-plot
hist(x); % Histogram
+stem(x); % Plot values as stems, useful for displaying discrete data
+bar(x); % Plot bar graph
z = sin(x);
plot3(x,y,z); % 3D line plot
@@ -262,7 +267,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value
contour(A) % Contour plot of matrix
mesh(A) % Plot as a mesh surface
-h = figure % Create new figure object, with handle h
+h = figure % Create new figure object, with handle h
figure(h) % Makes the figure corresponding to handle h the current figure
close(h) % close figure with handle h
close all % close all open figure windows
@@ -400,7 +405,7 @@ exp(x)
sqrt(x)
log(x)
log10(x)
-abs(x)
+abs(x) %If x is complex, returns magnitude
min(x)
max(x)
ceil(x)
@@ -411,6 +416,14 @@ rand % Uniformly distributed pseudorandom numbers
randi % Uniformly distributed pseudorandom integers
randn % Normally distributed pseudorandom numbers
+%Complex math operations
+abs(x) % Magnitude of complex variable x
+phase(x) % Phase (or angle) of complex variable x
+real(x) % Returns the real part of x (i.e returns a if x = a +jb)
+imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb)
+conj(x) % Returns the complex conjugate
+
+
% Common constants
pi
NaN
@@ -460,11 +473,14 @@ length % length of a vector
sort % sort in ascending order
sum % sum of elements
prod % product of elements
-mode % modal value
+mode % modal value
median % median value
mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
+find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators,
+ % i.e. find( x == 3 ) returns indexes of elements that are equal to 3
+ % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3
% Classes
diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown
new file mode 100644
index 00000000..90e37133
--- /dev/null
+++ b/ms-my/javascript-my.html.markdown
@@ -0,0 +1,588 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-ms.js
+translators:
+ - ["abdalim", "https://github.com/abdalim"]
+lang: ms-my
+---
+
+Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia
+dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan
+Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada
+halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi
+lebih kerap digunakan berbanding Java pada bahagian hadapan laman web.
+
+Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek
+yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang
+kian mendapat sambutan yang hangat.
+
+```js
+// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang
+/* dan komentar banyak baris bermula dengan sengkang-bintang
+ dan berakhir dengan bintang-sengkang */
+
+// Pernyataan boleh ditamatkan dengan ';'
+doStuff();
+
+// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan
+// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes
+// tertentu.
+doStuff()
+
+// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami
+// akan sentiasa menggunakan koma bertitik dalam panduan ini.
+
+///////////////////////////////////
+// 1. Nombor, String dan Operator
+
+// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double).
+// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer
+// sehingga 9✕10¹⁵ secara tepatnya.
+3; // = 3
+1.5; // = 1.5
+
+// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Termasuk pembahagian tidak rata.
+5 / 2; // = 2.5
+
+// Dan pembahagian modulo.
+10 % 2; // = 0
+30 % 4; // = 2
+18.5 % 7; // = 4.5
+
+// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise,
+// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit.
+1 << 2; // = 4
+
+// Keutamaan ditekankan menggunakan kurungan.
+(1 + 3) * 2; // = 8
+
+// Terdapat tiga nilai nombor-tidak-nyata istimewa
+Infinity; // hasil operasi seperti 1/0
+-Infinity; // hasil operasi seperti -1/0
+NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor'
+
+// Terdapat juga jenis boolean
+true;
+false;
+
+// Talian dicipta dengan ' atau ''.
+'abc';
+"Hello, world";
+
+// Penafian menggunakan simbol !
+!true; // = tidak benar
+!false; // = benar
+
+// Sama ialah ===
+1 === 1; // = benar
+2 === 1; // = tidak benar
+
+// Tidak sama ialah !==
+1 !== 1; // = tidak benar
+2 !== 1; // = benar
+
+// Lagi perbandingan
+1 < 10; // = benar
+1 > 10; // = tidak benar
+2 <= 2; // = benar
+2 >= 2; // = benar
+
+// Talian disambungkan dengan +
+"Hello " + "world!"; // = "Hello world!"
+
+// dan dibandingkan dengan < dan >
+"a" < "b"; // = benar
+
+// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan...
+"5" == 5; // = benar
+null == undefined; // = benar
+
+// ...melainkan anda menggunakan ===
+"5" === 5; // = tidak benar
+null === undefined; // = tidak benar
+
+// ...yang boleh menghasilkan keputusan yang pelik...
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Anda boleh akses huruf dalam perkataan dengan `charAt`
+"This is a string".charAt(0); // = 'T'
+
+// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar.
+"Hello world".substring(0, 5); // = "Hello"
+
+// `length` adalah ciri, maka jangan gunakan ().
+"Hello".length; // = 5
+
+// Selain itu, terdapat juga `null` dan `undefined`.
+null; // digunakan untuk menandakan bukan-nilai yang disengajakan
+undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga)
+
+// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar.
+// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0".
+
+///////////////////////////////////
+// 2. Pembolehubah, Array dan Objek
+
+// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah
+// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan
+// jenis pembolehubah. Penetapan menggunakan satu '=' karakter.
+var someVar = 5;
+
+// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat...
+someOtherVar = 10;
+
+// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di
+// dalam skop anda menciptanya.
+
+// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan
+// ditetapkan kepada undefined.
+var someThirdVar; // = undefined
+
+// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh
+// menggunakan koma sebagai pembahagi
+var someFourthVar = 2, someFifthVar = 4;
+
+// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada
+// pembolehubah:
+someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang
+someVar *= 10; // sekarang someVar bernilai 100
+
+// dan cara lebih mudah untuk penambahan atau penolakan 1
+someVar++; // sekarang someVar ialah 101
+someVar--; // kembali kepada 100
+
+// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada
+// pembolehubah pelbagai jenis.
+var myArray = ["Hello", 45, true];
+
+// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak.
+// Indeks array bermula pada sifar.
+myArray[1]; // = 45
+
+// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah.
+myArray.push("World");
+myArray.length; // = 4
+
+// Tambah/Ubah di index yang spesifik
+myArray[3] = "Hello";
+
+// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa
+// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai
+// sebarang susunan.
+var myObj = {key1: "Hello", key2: "World"};
+
+// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam
+// javascript yang sah. Nilai boleh mempunyai sebarang jenis.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan-
+// petak),
+myObj["my other key"]; // = 4
+
+// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah.
+myObj.myKey; // = "myValue"
+
+// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah.
+myObj.myThirdKey = true;
+
+// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat
+// undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logik dan Struktur Kawalan
+
+// Syntax untuk bahagian ini adalah hampir sama dengan Java.
+
+// Struktur `if` berfungsi seperti yang anda jangkakan.
+var count = 1;
+if (count == 3){
+ // dinilai jika count ialah 3
+} else if (count == 4){
+ // dinilai jika count ialah 4
+} else {
+ // dinilai jika count bukan 3 atau 4
+}
+
+// Sama juga dengan `while`.
+while (true){
+ // Sebuah ulangan yang tidak terhingga!
+ // An infinite loop!
+}
+
+// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang
+// sekurang-kurangnya sekali.
+var input;
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// Ulangan `for` adalah sama dengan C dan Java:
+// Persiapan; kondisi untuk bersambung; pengulangan.
+for (var i = 0; i < 5; i++){
+ // akan berulang selama 5 kali
+}
+
+// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan
+// 'prototype'
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it
+// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty()
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana
+// indeks susunan adalah penting.
+// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam
+// mana - mana susunan
+
+// && adalah logikal dan, || adalah logikal atau
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+}
+if (colour == "red" || colour == "blue"){
+ // warna adalah sama ada 'red' atau 'blue'
+}
+
+// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan
+// nilai asal.
+var name = otherName || "default";
+
+
+// Pernyataan `switch` menyemak persamaan menggunakan `===`.
+// gunakan pernyataan `break` selepas setiap kes
+// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga.
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Functions, Skop dan Closures
+
+// Function javascript dideklarasikan dengan kata kunci `function`.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama
+// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan
+// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga -
+// jaga dengan hal ini apabila menggunakan Allman style.
+function myFunction(){
+ return // <- semicolon dimasukkan secara automatik di sini
+ {thisIsAn: 'object literal'}
+}
+myFunction(); // = undefined
+
+// Function javascript adalah objek kelas pertama, maka ia boleh diberikan
+// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai
+// input - sebagai contoh, apabila membekalkan pengendali event:
+function myFunction(){
+ // kod ini akan dijalankan selepas 5 saat
+}
+setTimeout(myFunction, 5000);
+// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan
+// oleh pelayar web dan Node.js.
+
+// Satu lagi function yang disediakan oleh pelayar web adalah setInterval
+function myFunction(){
+ // kod ini akan dijalankan setiap 5 saat
+}
+setInterval(myFunction, 5000);
+
+// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis
+// function yang tidak bernama didalam input sebuah function lain.
+setTimeout(function(){
+ // kod ini akan dijalankan dalam 5 saat
+}, 5000);
+
+// Javascript mempunyai skop function; function mempunyai skop mereka
+// tersendiri tetapi blok tidak.
+if (true){
+ var i = 5;
+}
+i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop
+
+// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous
+// functions", yang mengelakkan pembolehubah sementara daripada bocor ke
+// skop global.
+(function(){
+ var temporary = 5;
+ // Kita boleh akses skop global dengan menetapkan nilai ke "objek global",
+ // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin
+ // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js.
+ window.permanent = 10;
+})();
+temporary; // akan menghasilkan ralat ReferenceError
+permanent; // = 10
+
+// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function
+// didefinisikan di dalam sebuah function lain, function yang di dalam akan
+// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun
+// selepas function yang di luar tersebut selesai.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ // Function dalam diletakkan di dalam skop lokal secara asal, seperti
+ // ia dideklarasikan dengan `var`.
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil
+ // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam
+ // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah
+ // `prompt` apabila ia dipanggil.
+}
+sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s
+
+///////////////////////////////////
+// 5. Lagi tentang Objek, Constructor dan Prototype
+
+// Objek boleh mengandungi function.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya
+// dengan menggunakan kata kunci `this`.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana
+// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it,
+// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks
+// objeknya.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses
+// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia
+// didefinisikan.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila
+// ia dipanggil menggunakan `call` atau `apply`.
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array
+// sebagai senarai input.
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai
+// input dan anda mahu menggunakan sebuah array sebagai input.
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini.
+// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak
+// sepenuhnya (curry).
+
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah
+// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui
+// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa
+// dikenali sebagai constructors.
+
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu
+// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan
+// mencari ciri itu didalam `prototype`nya.
+
+// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah
+// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan
+// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat
+// cara - cara piawai untuk menggunakan prototypes nanti.
+var myObj = {
+ myString: "Hello world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Ini berfungsi untuk function juga.
+myObj.myFunc(); // = "hello world!"
+
+// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada
+// prototype anda akan disemak, dan seterusnya.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada
+// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan
+// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi
+// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua
+// cara untuk mencipta objek baru dengan sesebuah prototype.
+
+// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS,
+// dan oleh itu tiada dalam semua implementasi buat masa ini.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan
+// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype.
+// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang
+// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan
+// kata kunci new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor
+// yang mencipta objek pembalut yang serupa.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Kecuali, mereka sebenarnya tak sama sepenuhnya.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar.
+}
+
+// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi
+// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi
+// kepada string.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi
+// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh
+// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama.
+
+// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia
+// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill:
+if (Object.create === undefined){ // jangan ganti jika ia sudah wujud
+ Object.create = function(proto){
+ // buat satu constructor sementara dengan prototype yang betul
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // kemudian gunakannya untuk mencipta objek baru yang diberikan
+ // prototype yang betul
+ return new Constructor();
+ }
+}
+```
+## Bacaan Lanjut
+
+[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk
+JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula,
+ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh
+membantu orang lain dengan berkongsi pengetahuan anda.
+
+[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang
+diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa
+aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut
+tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari
+tentang [Document Object Model][3].
+
+[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini
+dengan cabaran yang tersedia pakai.
+
+[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai
+semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau
+kebiasaan.
+
+[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan.
+
+Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya
+adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini,
+dan [JS Tutorial][7] di Mozilla Developer Network.
+
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[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
diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown
new file mode 100644
index 00000000..d5e0022a
--- /dev/null
+++ b/nl-nl/amd-nl.html.markdown
@@ -0,0 +1,235 @@
+---
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+translators:
+ - ["Reinoud Kruithof", "https://github.com/reinoudk"]
+filename: learnamd-nl.js
+lang: nl-nl
+---
+
+## Aan de slag met AMD
+
+De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript
+ modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon
+ geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het
+ synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid,
+ debugging en cross-domain toegangsproblemen.
+
+### Basis concept
+```javascript
+// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require`
+// and gaat vooral over de definitie en gebruik van modules:
+// `define(id?, dependencies?, factory)` definieert een module
+// `require(dependencies, callback)` importeert een set van dependencies en
+// gebruikt ze in de gegeven callback
+
+// Laten we starten met het gebruiken van define om een nieuwe module (met naam)
+// te creeren, welke geen dependencies heeft. Dit doen we door een naam
+// en een zogeheten factory functie door te geven aan define:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // De return waarde van een module's factory functie is
+ // wat andere modules of require calls ontvangen wanneer
+ // ze onze `awesomeAMD` module requiren.
+ // De gexporteerde waarde kan van alles zijn: (constructor) functies,
+ // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft).
+ return isAMDAwesome;
+});
+
+
+// We gaan nu een andere module defineren die afhankelijk is van onze
+// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument
+// is die de dependencies van onze module defineert:
+define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){
+ // dependencies worden naar de factory's functieargumenten
+ // gestuurd in de volgorde waarin ze gespecificeert zijn
+ var vertelIedereen = function(){
+ if (awesomeAMD()){
+ alert('Dit is zOoOo cool!');
+ } else {
+ alert('Vrij saai, niet?');
+ }
+ };
+ return vertelIedereen;
+});
+
+// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken
+// om ons programma mee te starten. De vorm van `require` is
+// `(arrayVanDependencies, callback)`.
+require(['schreeuwlelijk'], function(schreewlelijk){
+ schreeuwlelijk();
+});
+
+// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic
+// (niet-asynchrone) versie van AMD implementeren:
+function define(naam, deps, factory){
+ // merk op hoe modules zonder dependencies worden afgehandeld
+ define[naam] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // we halen eerst alle dependecies op die nodig zijn
+ // om require aan te roepen
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // voldoe aan alle dependencies van de callback
+ return callback.apply(null, args);
+}
+// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/
+```
+
+### require.js in de echte wereld
+
+In contrast met het voorbeeld uit de introductie, implementeert `require.js`
+ (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk
+ om je modules en hun dependencies asynchroon in the laden via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/someClass'], function(SomeClass){
+ // de callback word uitgesteld tot de dependency geladen is
+ var things = new SomeClass();
+});
+console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd
+```
+
+De afspraak is dat je over het algemeen n module in n bestand opslaat.
+`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie,
+dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen
+ door hun locatie te gebruiken.
+In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map,
+ relatief ten opzichte van de `baseUrl` uit je configuratie.
+
+* app/
+ * main.js
+ * modules/
+ * someClass.js
+ * someHelpers.js
+ * ...
+ * daos/
+ * things.js
+ * ...
+
+Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren:
+
+```javascript
+/* file: app/modules/someClass.js */
+define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
+ // definitie van de module gebeurt, natuurlijk, ook asynchroon
+ function SomeClass(){
+ this.method = function(){/**/};
+ // ...
+ }
+ return SomeClass;
+});
+```
+Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping
+ aan te passen in je `main.js`:
+
+```javascript
+/* file: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // je kan ook modules uit andere locatie inladen
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibUitBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){
+ // een `main` bestand moet require minstens eenmaal aanroepen,
+ // anders zal er geen code uitgevoerd worden
+ coolLib.doFancyDingenMet(helpers.transform($('#foo')));
+});
+```
+Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`)
+ welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut.
+Deze zal automisch geladen en uitgevoerd worden als de pagina laadt:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Honder script tags? Nooi meer!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Een heel project optimaliseren met r.js
+
+Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de
+ ontwikkelfase om code op een gezonde manier te organiseren maar
+ willen nog steeds een enkel scriptbestand gebruiken in productie in
+ plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt.
+
+`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk
+uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de
+dependency book van je project analyseert en een enkel bestand bouwt met daarin
+al je module (juist genaamd), geminificeerd en klaar voor productie.
+
+Instaleren met `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Nu kun je het een configuratiebestand voeden:
+```shell
+$ r.js -o app.build.js
+```
+
+Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // naam van het beginpunt
+ out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt
+ baseUrl : 'app',
+ paths : {
+ // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN,
+ // gebruik makend van de locatie gespecificeert in `main.js`
+ jquery : 'empty:',
+ coolLibUitBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is
+beschikbar in de GitHub repo (Engels).
+
+Hieronder vind je nog meer informatie over AMD (Engels).
+
+### Onderwerpen die niet aan bod zijn gekomen
+* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
+* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
+* [Advanced configuration](http://requirejs.org/docs/api.html#config)
+* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
+* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Using almond.js for builds](https://github.com/jrburke/almond)
+
+### Verder lezen:
+
+* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [Why AMD?](http://requirejs.org/docs/whyamd.html)
+* [Universal Module Definition](https://github.com/umdjs/umd)
+
+### Implementaties:
+
+* [require.js](http://requirejs.org)
+* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
+* [cujo.js](http://cujojs.com/)
+* [curl.js](https://github.com/cujojs/curl)
+* [lsjs](https://github.com/zazl/lsjs)
+* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index f130ea0c..097cb846 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -1,13 +1,12 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: LearnObjectiveC.m
-
---
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
@@ -20,6 +19,10 @@ It is a general-purpose, object-oriented programming language that adds Smalltal
Multi-line comments look like this
*/
+// XCode supports pragma mark directive that improve jump bar readability
+#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'
+#pragma mark - Navigation Functions // Same tag, now with a separator
+
// Imports the Foundation headers with #import
// Use <> to import global files (in general frameworks)
// Use "" to import local files (from project)
@@ -148,13 +151,13 @@ int main (int argc, const char * argv[])
[mutableDictionary setObject:@"value1" forKey:@"key1"];
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
-
+
// Change types from Mutable To Immutable
//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
-
-
+
+
// Set object
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
@@ -599,6 +602,52 @@ int main (int argc, const char * argv[]) {
@end
+// Starting in Xcode 7.0, you can create Generic classes,
+// allowing you to provide greater type safety and clarity
+// without writing excessive boilerplate.
+@interface Result<__covariant A> : NSObject
+
+- (void)handleSuccess:(void(^)(A))success
+ failure:(void(^)(NSError *))failure;
+
+@property (nonatomic) A object;
+
+@end
+
+// we can now declare instances of this class like
+Result<NSNumber *> *result;
+Result<NSArray *> *result;
+
+// Each of these cases would be equivalent to rewriting Result's interface
+// and substituting the appropriate type for A
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSArray *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSArray * object;
+@end
+
+@interface Result : NSObject
+- (void)handleSuccess:(void(^)(NSNumber *))success
+ failure:(void(^)(NSError *))failure;
+@property (nonatomic) NSNumber * object;
+@end
+
+// It should be obvious, however, that writing one
+// Class to solve a problem is always preferable to writing two
+
+// Note that Clang will not accept generic types in @implementations,
+// so your @implemnation of Result would have to look like this:
+
+@implementation Result
+
+- (void)handleSuccess:(void (^)(id))success
+ failure:(void (^)(NSError *))failure {
+ // Do something
+}
+
+@end
+
+
///////////////////////////////////////
// Protocols
///////////////////////////////////////
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 43688724..2c274f12 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -7,29 +7,30 @@ contributors:
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
- ["Elton Viana", "https://github.com/eltonvs"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
lang: pt-br
filename: c-pt.el
---
Ah, C. Ainda é **a** linguagem de computação de alta performance.
-C é a liguangem de mais baixo nível que a maioria dos programadores
-irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique
-antento que este manual de gerenciamento de memória e C vai levanter-te
-tão longe quanto você precisa.
+C é a linguagem de mais baixo nível que a maioria dos programadores
+utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique
+atento se este manual de gerenciamento de memória e C vai te levar
+tão longe quanto precisa.
```c
// Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99
/*
-Comentários de multiplas linhas se parecem com este.
+Comentários de múltiplas linhas se parecem com este.
Funcionam no C89 também.
*/
// Constantes: #define <palavra-chave>
#definie DAY_IN_YEAR 365
-//enumarações também são modos de definir constantes.
+//enumerações também são modos de definir constantes.
enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB};
// SEG recebe 2 automaticamente, TER recebe 3, etc.
@@ -54,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função
// O ponto de entrada do teu programa é uma função
// chamada main, com tipo de retorno inteiro
int main() {
- // Usa-se printf para escrever na tela,
+ // Usa-se printf para escrever na tela,
// para "saída formatada"
// %d é um inteiro, \n é uma nova linha
printf("%d\n", 0); // => Imprime 0
// Todos as declarações devem acabar com
// ponto e vírgula
-
+
///////////////////////////////////////
// Tipos
///////////////////////////////////////
@@ -78,7 +79,7 @@ int main() {
// longs tem entre 4 e 8 bytes; longs long tem garantia
// de ter pelo menos 64 bits
long x_long = 0;
- long long x_long_long = 0;
+ long long x_long_long = 0;
// floats são normalmente números de ponto flutuante
// com 32 bits
@@ -93,7 +94,7 @@ int main() {
unsigned int ux_int;
unsigned long long ux_long_long;
- // caracteres dentro de aspas simples são inteiros
+ // caracteres dentro de aspas simples são inteiros
// no conjunto de caracteres da máquina.
'0' // => 48 na tabela ASCII.
'A' // => 65 na tabela ASCII.
@@ -104,7 +105,7 @@ int main() {
// Se o argumento do operador `sizeof` é uma expressão, então seus argumentos
// não são avaliados (exceto em VLAs (veja abaixo)).
- // O valor devolve, neste caso, é uma constante de tempo de compilação.
+ // O valor devolve, neste caso, é uma constante de tempo de compilação.
int a = 1;
// size_t é um inteiro sem sinal com pelo menos 2 bytes que representa
// o tamanho de um objeto.
@@ -120,7 +121,7 @@ int main() {
// Você pode inicializar um array com 0 desta forma:
char meu_array[20] = {0};
- // Indexar um array é semelhante a outras linguages
+ // Indexar um array é semelhante a outras linguagens
// Melhor dizendo, outras linguagens são semelhantes a C
meu_array[0]; // => 0
@@ -129,7 +130,7 @@ int main() {
printf("%d\n", meu_array[1]); // => 2
// No C99 (e como uma features opcional em C11), arrays de tamanho variável
- // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
+ // VLA (do inglês), podem ser declarados também. O tamanho destes arrays
// não precisam ser uma constante de tempo de compilação:
printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho
char buf[0x100];
@@ -144,14 +145,14 @@ int main() {
// > Entre o tamanho do array: 10
// > sizeof array = 40
- // String são apenas arrays de caracteres terminados por um
+ // String são apenas arrays de caracteres terminados por um
// byte nulo (0x00), representado em string pelo caracter especial '\0'.
// (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
- char uma_string[20] = "Isto é uma string";
+ char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
// A string vai ser salva, mas a saída vai ser estranha
- // Porém, comentários podem conter acentos
+ // Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
printf("%d\n", uma_string[17]); // => 0
@@ -175,7 +176,7 @@ int main() {
///////////////////////////////////////
// Atalho para multiplas declarações:
- int i1 = 1, i2 = 2;
+ int i1 = 1, i2 = 2;
float f1 = 1.0, f2 = 2.0;
int a, b, c;
@@ -206,7 +207,7 @@ int main() {
2 <= 2; // => 1
2 >= 2; // => 1
- // C não é Python - comparações não se encadeam.
+ // C não é Python - comparações não se encadeiam.
int a = 1;
// Errado:
int entre_0_e_2 = 0 < a < 2;
@@ -231,7 +232,7 @@ int main() {
char *s = "iLoveC";
int j = 0;
s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j.
- j = 0;
+ j = 0;
s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s.
// o mesmo com j-- e --j
@@ -308,7 +309,7 @@ int main() {
exit(-1);
break;
}
-
+
///////////////////////////////////////
// Cast de tipos
@@ -327,8 +328,8 @@ int main() {
// Tipos irão ter overflow sem aviso
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits)
- // Para determinar o valor máximo de um `char`, de um `signed char` e de
- // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
+ // Para determinar o valor máximo de um `char`, de um `signed char` e de
+ // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX
// e UCHAR_MAX de <limits.h>
// Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa.
@@ -341,7 +342,7 @@ int main() {
///////////////////////////////////////
// Um ponteiro é uma variável declarada para armazenar um endereço de memória.
- // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você
+ // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você
// Pode usar o endereço de memória de suas variáveis, então, brincar com eles.
int x = 0;
@@ -363,13 +364,13 @@ int main() {
printf("%d\n", *px); // => Imprime 0, o valor de x
// Você também pode mudar o valor que o ponteiro está apontando.
- // Teremo que cercar a de-referência entre parenteses, pois
+ // Temos que cercar a de-referência entre parênteses, pois
// ++ tem uma precedência maior que *.
(*px)++; // Incrementa o valor que px está apontando por 1
printf("%d\n", *px); // => Imprime 1
printf("%d\n", x); // => Imprime 1
- // Arrays são um boa maneira de alocar um bloco contínuo de memória
+ // Arrays são uma boa maneira de alocar um bloco contínuo de memória
int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho
int xx;
for (xx = 0; xx < 20; xx++) {
@@ -379,7 +380,7 @@ int main() {
// Declara um ponteiro do tipo int e inicialize ele para apontar para x_array
int* x_ptr = x_array;
// x_ptr agora aponta para o primeiro elemento do array (o inteiro 20).
- // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos.
+ // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos.
// 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):
@@ -395,7 +396,7 @@ int main() {
printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8"
// Ponteiros podem ser incrementados ou decrementados baseado no seu tipo
- // (isto é chamado aritimética de ponteiros
+ // (isto é chamado aritmética de ponteiros
printf("%d\n", *(x_ptr + 1)); // => Imprime 19
printf("%d\n", x_array[1]); // => Imprime 19
@@ -413,9 +414,9 @@ int main() {
// "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido"
printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa.
- // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo,
+ // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo,
// ou ninguém mais será capaz de usá-lo até o fim da execução
- // (Isto cham-se "memory leak"):
+ // (Isto chama-se "memory leak"):
free(my_ptr);
// Strings são arrays de char, mas elas geralmente são representadas
@@ -537,7 +538,7 @@ int area(retan r)
return r.largura * r.altura;
}
-// Se você tiver structus grande, você pode passá-las "por ponteiro"
+// Se você tiver structus grande, você pode passá-las "por ponteiro"
// para evitar cópia de toda a struct:
int area(const retan *r)
{
@@ -554,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro
diretamente e passá-las para por toda parte.
Entretanto, a sintaxe de definição por ser um pouco confusa.
-Exemplo: use str_reverso através de um ponteiro
-*/
+Exemplo: use str_reverso através de um ponteiro
+*/
void str_reverso_através_ponteiro(char *str_entrada) {
// Define uma variável de ponteiro para função, nomeada f.
void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo.
@@ -575,7 +576,7 @@ typedef void (*minha_função_type)(char *);
// Declarando o ponteiro:
// ...
-// minha_função_type f;
+// minha_função_type f;
//Caracteres especiais:
'\a' // Alerta (sino)
@@ -586,7 +587,7 @@ typedef void (*minha_função_type)(char *);
'\r' // Retorno de carroça
'\b' // Backspace
'\0' // Caracter nulo. Geralmente colocado ao final de string em C.
- // oi\n\0. \0 é usado por convenção para marcar o fim da string.
+ // oi\n\0. \0 é usado por convenção para marcar o fim da string.
'\\' // Barra invertida
'\?' // Interrogação
'\'' // Aspas simples
@@ -606,7 +607,7 @@ typedef void (*minha_função_type)(char *);
"%p" // ponteiro
"%x" // hexadecimal
"%o" // octal
-"%%" // imprime %
+"%%" // imprime %
///////////////////////////////////////
// Ordem de avaliação
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
index ed6f6c4c..b1fbd961 100644
--- a/pt-br/css-pt.html.markdown
+++ b/pt-br/css-pt.html.markdown
@@ -159,11 +159,11 @@ seletor {
    color: # FF66EE; /* Formato hexadecimal longo */
    color: tomato; /* Uma cor nomeada */
    color: rgb (255, 255, 255); /* Como valores rgb */
-    cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
-    cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
+    color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
+    color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
    color: transparent; /* Equivale a definir o alfa a 0 */
-    cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
-    cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
+    color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
+    color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
    /* Imagens como fundos de elementos */
    background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index a884f273..3c9512aa 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -405,6 +405,219 @@ class Velocipede extends Bicicleta {
}
+// Interfaces
+// Sintaxe de declaração de Interface
+// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> {
+// // Constantes
+// // Declarações de método
+//}
+
+// Exemplo - Comida:
+public interface Comestivel {
+ public void comer(); // Qualquer classe que implementa essa interface, deve
+                        // Implementar este método.
+}
+
+public interface Digestivel {
+ public void digerir();
+}
+
+
+// Agora podemos criar uma classe que implementa ambas as interfaces.
+public class Fruta implements Comestivel, Digestivel {
+
+ @Override
+ public void comer() {
+ // ...
+ }
+
+ @Override
+ public void digerir() {
+ // ...
+ }
+}
+
+// Em Java, você pode estender somente uma classe, mas você pode implementar muitas
+// Interfaces. Por exemplo:
+public class ClasseExemplo extends ExemploClassePai implements InterfaceUm,
+ InterfaceDois {
+
+ @Override
+ public void InterfaceUmMetodo() {
+ }
+
+ @Override
+ public void InterfaceDoisMetodo() {
+ }
+
+}
+
+// Classes abstratas
+
+// Sintaxe de declaração de classe abstrata
+// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem
+// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem
+// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos
+// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de
+// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo,
+// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um
+// classe abstrata. Classes abstratas também PODEM ter o método "main".
+
+public abstract class Animal
+{
+ public abstract void fazerSom();
+
+ // Método pode ter um corpo
+ public void comer()
+ {
+ System.out.println("Eu sou um animal e estou comendo.");
+ //Nota: Nós podemos acessar variáveis privadas aqui.
+ idade = 30;
+ }
+
+ // Não há necessidade de inicializar, no entanto, em uma interface
+    // a variável é implicitamente final e, portanto, tem
+    // de ser inicializado.
+ protected int idade;
+
+ public void mostrarIdade()
+ {
+ System.out.println(idade);
+ }
+
+ //Classes abstratas podem ter o método main.
+ public static void main(String[] args)
+ {
+ System.out.println("Eu sou abstrata");
+ }
+}
+
+class Cachorro extends Animal
+{
+
+ // Nota: ainda precisamos substituir os métodos abstratos na
+    // classe abstrata
+ @Override
+ public void fazerSom()
+ {
+ System.out.println("Bark");
+ // idade = 30; ==> ERRO! idade é privada de Animal
+ }
+
+ // NOTA: Você receberá um erro se usou a
+    // anotação Override aqui, uma vez que java não permite
+    // sobrescrita de métodos estáticos.
+    // O que está acontecendo aqui é chamado de "esconder o método".
+    // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Cachorro pluto = new Cachorro();
+ pluto.fazerSom();
+ pluto.comer();
+ pluto.mostrarIdade();
+ }
+}
+
+// Classes Finais
+
+// Sintaxe de declaração de classe final
+// <nível de acesso> final <nome-da-classe-final> {
+// // Constantes e variáveis
+// // Declarações de método
+//}
+
+// Classes finais são classes que não podem ser herdadas e são, portanto, um
+// filha final. De certa forma, as classes finais são o oposto de classes abstratas
+// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser
+// estendidas.
+public final class TigreDenteDeSabre extends Animal
+{
+ // Nota: Ainda precisamos substituir os métodos abstratos na
+     // classe abstrata.
+ @Override
+ public void fazerSom();
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Métodos Finais
+public abstract class Mamifero()
+{
+ // Sintaxe de Métodos Finais:
+ // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>)
+
+ // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha,
+    // e são, portanto, a implementação final do método.
+ public final boolean EImpulsivo()
+ {
+ return true;
+ }
+}
+
+
+// Tipo Enum
+//
+// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A
+// variável deve ser igual a um dos valores que foram previamente definidos para ela.
+// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas.
+// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia
+// especificar um tipo de enum dias-da-semana como:
+
+public enum Dia {
+ DOMINGO, SEGUNDA, TERÇA, QUARTA,
+ QUINTA, SEXTA, SABADO
+}
+
+// Nós podemos usar nosso enum Dia assim:
+
+public class EnumTeste {
+
+ // Variável Enum
+ Dia dia;
+
+ public EnumTeste(Dia dia) {
+ this.dia = dia;
+ }
+
+ public void digaComoE() {
+ switch (dia) {
+ case SEGUNDA:
+ System.out.println("Segundas são ruins.");
+ break;
+
+ case SEXTA:
+ System.out.println("Sextas são melhores.");
+ break;
+
+ case SABADO:
+ case DOMINGO:
+ System.out.println("Finais de semana são os melhores.");
+ break;
+
+ default:
+ System.out.println("Dias no meio da semana são mais ou menos.");
+ break;
+ }
+ }
+
+ public static void main(String[] args) {
+ EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA);
+ primeiroDia.digaComoE(); // => Segundas-feiras são ruins.
+ EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA);
+ terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos.
+ }
+}
+
+// Tipos Enum são muito mais poderosos do que nós mostramos acima.
+// O corpo de um enum pode incluir métodos e outros campos.
+// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
+
```
## Leitura Recomendada
diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown
index e4f10a61..fd822c03 100644
--- a/pt-br/json-pt.html.markdown
+++ b/pt-br/json-pt.html.markdown
@@ -3,6 +3,7 @@ language: json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Francisco Marques", "https://github.com/ToFran"]
translators:
- ["Miguel Araújo", "https://github.com/miguelarauj1o"]
lang: pt-br
@@ -12,10 +13,16 @@ filename: learnjson-pt.json
Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o
"Learn X in Y minutes" mais simples existente.
-JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores
-aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto,
-tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
+JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores
+aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade.
+Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null.
+
+Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+.
+
+A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”.
+
+Mais informação em: http://www.json.org/
```json
{
@@ -57,6 +64,6 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
, "outro comentário": "que bom"
},
- "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.".
+ "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer."
}
```
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
index 105896b2..3d91f1ca 100644
--- a/pt-br/sass-pt.html.markdown
+++ b/pt-br/sass-pt.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Sean Corrales", "https://github.com/droidenator"]
translators:
- ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+ - ["Cássio Böck", "https://github.com/cassiobsilva"]
lang: pt-br
---
@@ -155,16 +156,6 @@ body {
background-color: rgba(0, 0, 0, 0.75);
}
-/* You may also define your own functions. Functions are very similar to
- mixins. When trying to choose between a function or a mixin, remember
- that mixins are best for generating CSS while functions are better for
- logic that might be used throughout your Sass code. The examples in
- the Math Operators' section are ideal candidates for becoming a reusable
- function. */
-
-/* This function will take a target size and the parent size and calculate
- and return the percentage */
-
/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
@@ -319,11 +310,6 @@ ol {
padding: 0;
}
-/* Sass offers @import which can be used to import partials into a file.
- This differs from the traditional CSS @import statement which makes
- another HTTP request to fetch the imported file. Sass takes the
- imported file and combines it with the compiled code. */
-
/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
   Isso difere da declaração CSS @import tradicional, que faz
   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
@@ -354,12 +340,6 @@ body {
==============================*/
-
-/* Placeholders are useful when creating a CSS statement to extend. If you
- wanted to create a CSS statement that was exclusively used with @extend,
- you can do so using a placeholder. Placeholders begin with a '%' instead
- of '.' or '#'. Placeholders will not appear in the compiled CSS. */
-
/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
@@ -396,11 +376,6 @@ body {
============================== * /
-/* Sass provides the following operators: +, -, *, /, and %. These can
- be useful for calculating values directly in your Sass files instead
- of using values that you've already calculated by hand. Below is an example
- of a setting up a simple two column design. */
-
/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
   de usar valores que você já calculados pela mão. Abaixo está um exemplo
diff --git a/python.html.markdown b/python.html.markdown
index 42a52bcf..2b43c5fc 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -15,8 +15,8 @@ executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020,
-it is though recommended to start learnign Python with Python 3.
+to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020,
+it is though recommended to start learning Python with Python 3.
For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
@@ -63,7 +63,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt
# to carry out normal division with just one '/'.
from __future__ import division
11/4 # => 2.75 ...normal division
-11//4 # => 2 ...floored division
+11//4 # => 2 ...floored division
# Modulo operation
7 % 3 # => 1
@@ -123,11 +123,16 @@ not False # => True
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
-# % can be used to format strings, like this:
-"%s can be %s" % ("strings", "interpolated")
+#String formatting with %
+#Even though the % string operator will be deprecated on Python 3.1 and removed
+#later at some time, it may still be good to know how it works.
+x = 'apple'
+y = 'lemon'
+z = "The items in the basket are %s and %s" % (x,y)
# A newer way to format strings is the format method.
# This method is the preferred way
+"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
@@ -144,8 +149,16 @@ None is None # => True
# very useful when dealing with primitive values, but is
# very useful when dealing with objects.
-# None, 0, and empty strings/lists all evaluate to False.
-# All other values are True
+# Any object can be used in a Boolean context.
+# The following values are considered falsey:
+# - None
+# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
+# - empty sequences (e.g., '', (), [])
+# - empty containers (e.g., {}, set())
+# - instances of user-defined classes meeting certain conditions
+# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
+#
+# All other values are truthy (using the bool() function on them returns True).
bool(0) # => False
bool("") # => False
@@ -234,7 +247,7 @@ li.remove(2) # Raises a ValueError as 2 is not in the list
li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again
# Get the index of the first item found
-li.index(2) # => 3
+li.index(2) # => 1
li.index(7) # Raises a ValueError as 7 is not in the list
# Check for existence in a list with "in"
@@ -257,8 +270,9 @@ tup[:2] # => (1, 2)
# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+d, e, f = 4, 5, 6 # you can leave out the parentheses
# Tuples are created by default if you leave out the parentheses
-d, e, f = 4, 5, 6
+g = 4, 5, 6 # => (4, 5, 6)
# Now look how easy it is to swap two values
e, d = d, e # d is now 5 and e is now 4
diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown
index 2f508a00..451da312 100644
--- a/ru-ru/clojure-ru.html.markdown
+++ b/ru-ru/clojure-ru.html.markdown
@@ -144,7 +144,7 @@ Clojure, это представитель семейства Lisp-подобн
;;;;;;;;;;;;;;;;;;;;;
; Функция создается специальной формой fn.
-; "Тело"" функции может состоять из нескольких форм,
+; "Тело" функции может состоять из нескольких форм,
; но результатом вызова функции всегда будет результат вычисления
; последней из них.
(fn [] "Hello World") ; => fn
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
index 005495cc..b24ad555 100644
--- a/ru-ru/java-ru.html.markdown
+++ b/ru-ru/java-ru.html.markdown
@@ -451,7 +451,7 @@ public class Fruit implements Edible, Digestible {
}
}
-// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать
+// В Java Вы можете наследовать только один класс, однако можете реализовывать
// несколько интерфейсов. Например:
public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
public void InterfaceOneMethod() {
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 8655ae4a..54499f46 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -330,7 +330,7 @@ function sayHelloInFiveSeconds(name) {
sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!»
///////////////////////////////////
-// 5. Подробнее об объектах; конструкторы и прототипы
+// 5. Подробнее об объектах; Конструкторы и Прототипы
// Объекты могут содержать в себе функции.
var myObj = {
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 5672aa90..37b6a86e 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -420,8 +420,6 @@ include_once 'my-file.php';
require 'my-file.php';
require_once 'my-file.php';
-// Same as include(), except require() will cause a fatal error if the
-// file cannot be included.
// Действует также как и include(), но если файл не удалось подключить,
// функция выдает фатальную ошибку
@@ -485,7 +483,7 @@ echo MyClass::MY_CONST; // Выведет 'value';
echo MyClass::$staticVar; // Выведет 'static';
MyClass::myStaticMethod(); // Выведет 'I am static';
-// Новый экземпляр класса используя new
+// Создание нового экземпляра класса используя new
$my_class = new MyClass('An instance property');
// Если аргументы отсутствуют, можно не ставить круглые скобки
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 3852a550..43142eff 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -280,7 +280,7 @@ filled_dict.get("four", 4) #=> 4
# Присваивайте значение ключам так же, как и в списках
filled_dict["four"] = 4 # теперь filled_dict["four"] => 4
-# Метод setdefault вставляет() пару ключ-значение, только если такого ключа нет
+# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 998b4bf7..8720fec6 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -41,7 +41,11 @@ You shouldn't either
35 / 5 #=> 7
2**5 #=> 32
5 % 3 #=> 2
-5 ^ 6 #=> 3
+
+# Bitwise operators
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
# Arithmetic is just syntactic sugar
# for calling a method on an object
@@ -77,6 +81,11 @@ false.class #=> FalseClass
2 <= 2 #=> true
2 >= 2 #=> true
+# Combined comparison operator
+1 <=> 10 #=> -1
+10 <=> 1 #=> 1
+1 <=> 1 #=> 0
+
# Logical operators
true && false #=> false
true || false #=> true
diff --git a/scala.html.markdown b/scala.html.markdown
index 192e03d7..bc8cd422 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -169,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
// Syntax for calling functions is familiar:
sumOfSquares(3, 4) // => 25
+// You can use parameters names to specify them in different order
+def subtract(x: Int, y: Int): Int = x - y
+
+subtract(10, 3) // => 7
+subtract(y=10, x=3) // => -7
+
// In most cases (with recursive functions the most notable exception), function
// return type can be omitted, and the same type inference we saw with variables
// will work with function return values:
diff --git a/swift.html.markdown b/swift.html.markdown
index f451288d..f3746613 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: learnswift.swift
---
@@ -25,6 +26,7 @@ import UIKit
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
+// MARK: - Section mark with a separator line
// TODO: Do something soon
// FIXME: Fix this code
@@ -82,7 +84,7 @@ if someOptionalString != nil {
someOptionalString = nil
/*
- Trying to use ! to access a non-existent optional value triggers a runtime
+ Trying to use ! to access a non-existent optional value triggers a runtime
error. Always make sure that an optional contains a non-nil value before
using ! to force-unwrap its value.
*/
@@ -128,6 +130,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // let == immutable
let emptyArray2 = Array<String>() // same as above
var emptyMutableArray = [String]() // var == mutable
+var explicitEmptyMutableStringArray: [String] = [] // same as above
// Dictionary
@@ -139,6 +142,7 @@ occupations["Jayne"] = "Public Relations"
let emptyDictionary = [String: Float]() // let == immutable
let emptyDictionary2 = Dictionary<String, Float>() // same as above
var emptyMutableDictionary = [String: Float]() // var == mutable
+var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above
//
diff --git a/ta_in/css.html.markdown b/ta_in/css-ta.html.markdown
index 56f94ed0..56f94ed0 100644
--- a/ta_in/css.html.markdown
+++ b/ta_in/css-ta.html.markdown
diff --git a/ta_in/javascript.html.markdown b/ta_in/javascript-ta.html.markdown
index f0b0a36a..f0b0a36a 100644
--- a/ta_in/javascript.html.markdown
+++ b/ta_in/javascript-ta.html.markdown
diff --git a/ta_in/json.html.markdown b/ta_in/json-ta.html.markdown
index d85e0d82..d85e0d82 100644
--- a/ta_in/json.html.markdown
+++ b/ta_in/json-ta.html.markdown
diff --git a/ta_in/xml.html.markdown b/ta_in/xml-ta.html.markdown
index a9bfa9cd..a9bfa9cd 100644
--- a/ta_in/xml.html.markdown
+++ b/ta_in/xml-ta.html.markdown
diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown
index baca4217..bd842b17 100644
--- a/tr-tr/brainfuck-tr.html.markdown
+++ b/tr-tr/brainfuck-tr.html.markdown
@@ -19,7 +19,7 @@ gözardı edilir.
Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir
dizidir. İşaretçi ilk hücreyi işaret eder.
-Sekik komut vardır:
+Sekiz komut vardır:
+ : Geçerli hücrenin değerini bir artırır.
- : Geçerli hücrenin değerini bir azaltır.
> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye).
diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown
index 128901de..2d4240ed 100644
--- a/tr-tr/c-tr.html.markdown
+++ b/tr-tr/c-tr.html.markdown
@@ -91,9 +91,9 @@ int main() {
// Örneğin,
printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words)
- // If the argument of the `sizeof` operator an expression, then its argument
- // is not evaluated (except VLAs (see below)).
- // The value it yields in this case is a compile-time constant.
+ // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez.
+ // VLAs hariç asagiya bakiniz).
+ // Bu durumda verimliligin degeri derleme-zamani sabitidir.
int a = 1;
// size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir
@@ -101,7 +101,7 @@ int main() {
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
- // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
+ // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride)
// Diziler somut bir boyut ile oluşturulmalıdır.
char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar
@@ -119,19 +119,19 @@ int main() {
my_array[1] = 2;
printf("%d\n", my_array[1]); // => 2
- // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
- // can be declared as well. The size of such an array need not be a compile
- // time constant:
- printf("Enter the array size: "); // ask the user for an array size
+ // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler.
+ // Böyle bir dizinin boyuunu derlenmesi gerekmez
+ // zaman sabiti:
+ printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor
char buf[0x100];
fgets(buf, sizeof buf, stdin);
- // strtoul parses a string to an unsigned integer
+ // strtoul isaretsiz integerlar icin string ayiricisidir.
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- // A possible outcome of this program may be:
+ // Bu programın olası bir sonucu olabilir:
// > Enter the array size: 10
// > sizeof array = 40
@@ -151,8 +151,8 @@ int main() {
printf("%d\n", a_string[16]); // => 0
// i.e., byte #17 is 0 (as are 18, 19, and 20)
- // If we have characters between single quotes, that's a character literal.
- // It's of type `int`, and *not* `char` (for historical reasons).
+ // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir.
+ // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle).
int cha = 'a'; // fine
char chb = 'a'; // fine too (implicit conversion from int to char)
@@ -201,10 +201,10 @@ int main() {
0x01 << 1; // => 0x02 (bitwise left shift (by 1))
0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
- // Be careful when shifting signed integers - the following are undefined:
- // - shifting into the sign bit of a signed integer (int a = 1 << 32)
- // - left-shifting a negative number (int a = -1 << 2)
- // - shifting by an offset which is >= the width of the type of the LHS:
+ // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir:
+ // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32)
+ // - negatif sayilarda sol kaydirma (int a = -1 << 2)
+ // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma:
// int a = 1 << 32; // UB if int is 32 bits wide
///////////////////////////////////////
@@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding
Diğer taraftan google sizin için bir arkadaş olabilir.
-[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
diff --git a/ua-ua/javascript-ua.html.markdown b/ua-ua/javascript-ua.html.markdown
new file mode 100644
index 00000000..fedbf5ac
--- /dev/null
+++ b/ua-ua/javascript-ua.html.markdown
@@ -0,0 +1,501 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript-ru.js
+translators:
+ - ["Alexey Gonchar", "http://github.com/finico"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+lang: ru-ru
+---
+
+JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape.
+Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java
+для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і
+вбудована підтримка браузерами призвела до того, що JavaScript став популярніший
+за власне Java.
+
+Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js,
+програмна платформа, що дозволяє виконувати JavaScript код з використанням
+рушія V8 від браузера Google Chrome, стає все більш і більш популярною.
+
+```js
+// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш)
+/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і
+ закінчуються символами зірочка-слеш */
+
+Інструкції можуть закінчуватися крапкою з комою ;
+doStuff();
+
+// ... але не обов’язково, тому що крапка з комою автоматично вставляється на
+// місці символу нового рядка, крім деяких випадків.
+doStuff()
+
+// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці
+// винятки можуть призвести до неочікуваних результатів
+
+///////////////////////////////////
+// 1. Числа, Рядки і Оператори
+
+// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double)
+// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з
+// точністю до 9✕10¹⁵.
+3; // = 3
+1.5; // = 1.5
+
+// Деякі прості арифметичні операції працють так, як ми очікуємо.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні)
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// В тому числі ділення з остачою
+5 / 2; // = 2.5
+
+// В JavaScript є побітові операції; коли ви виконуєте таку операцію,
+// число з плаваючою точкою переводиться в ціле зі знаком
+// довжиною *до* 32 розрядів.
+1 << 2; // = 4
+
+// Пріоритет у виразах можна задати явно круглими дужками
+(1 + 3) * 2; // = 8
+
+// Є три спеціальні значення, які не є реальними числами:
+Infinity; // "нескінченність", наприклад, як результат ділення на 0
+-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0
+NaN; // "не число", наприклад, ділення 0/0
+
+// Логічні типи
+true;
+false;
+
+// Рядки створюються за допомогою подвійних та одинарних лапок
+'абв';
+"Hello, world!";
+
+// Для логічного заперечення використовується знак оклику.
+!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
+
+// Рядки об’єднуються за допомогою оператор +
+"hello, " + "world!"; // = "hello, world!"
+
+// І порівнюються за допомогою > і <
+"a" < "b"; // = true
+
+// Перевірка на рівність з приведнням типів здійснюється оператором ==
+"5" == 5; // = true
+null == undefined; // = true
+
+// ... але приведення не виконується при ===
+"5" === 5; // = false
+null === undefined; // = false
+
+// ... приведення типів може призвести до дивних результатів
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// Можна отримати доступ до будь-якого символа рядка за допомгою charAt
+"Это строка".charAt(0); // = 'Э'
+
+// ... або використати метод substring, щоб отримати більший кусок
+"Hello, world".substring(0, 5); // = "Hello"
+
+// length - це не метод, а поле
+"Hello".length; // = 5
+
+// Типи null и undefined
+null; // навмисна відсутність результату
+undefined; // використовується для позначення відсутності присвоєного значення
+
+// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина.
+// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що:
+// 0 == "0".
+
+///////////////////////////////////
+// 2. Змінні, Масиви, Об’єкти
+
+// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з
+// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння
+// значення змінної використовується символ =
+var someVar = 5;
+
+// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ...
+someOtherVar = 10;
+
+// ... але ваша змінна буде створення в глобальному контексті, а не там, де
+// ви її оголосили
+
+// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined
+var someThirdVar; // = undefined
+
+// У математичних операцій є скорочені форми:
+someVar += 5; // як someVar = someVar + 5;
+someVar *= 10; // тепер someVar = 100
+
+// Інкремент і декремент
+someVar++; // тепер someVar дорівнює 101
+someVar--; // а зараз 100
+
+// Масиви — це нумеровані списку, які зберігають значення будь-якого типу.
+var myArray = ["Hello", 45, true];
+
+// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками
+// Індексація починається з нуля
+myArray[1]; // = 45
+
+// Массивы можно изменять, как и их длину,
+myArray.push("Мир");
+myArray.length; // = 4
+
+// додавання і редагування елементів
+myArray[3] = "Hello";
+
+// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах
+var myObj = {key1: "Hello", key2: "World"};
+
+// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє
+// правилам формування назв змінних. Значення можуть бути будь-яких типів.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Атрибути можна отримати використовуючи квадратні дужки
+myObj["my other key"]; // = 4
+
+// Або через точку, якщо ключ є правильним ідентифікатором
+myObj.myKey; // = "myValue"
+
+// Об’єкти можна динамічно змінювати й додавати нові поля
+myObj.myThirdKey = true;
+
+// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Управляючі конструкції
+
+// Синтаксис для цього розділу майже такий самий, як у Java
+
+// Умовна конструкція
+var count = 1;
+if (count == 3) {
+ // виконується, якщо count дорівнює 3
+} else if (count == 4) {
+ // ..
+} else {
+ // ...
+}
+
+// ... цикл while.
+while (true){
+ // Нескінченний цикл!
+}
+
+// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз.
+var input
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// цикл for такий самий, кяк в C і Java:
+// ініціалізація; умова; крок.
+for (var i = 0; i < 5; i++) {
+ // виконається 5 разів
+}
+
+// && — логічне І, || — логічне АБО
+if (house.size == "big" && house.color == "blue") {
+ house.contains = "bear";
+}
+if (color == "red" || color == "blue") {
+ // колір червоний або синій
+}
+
+// && і || використовують скорочене обчислення
+// тому їх можна використовувати для задання значень за замовчуванням.
+var name = otherName || "default";
+
+// Оператор switch виконує перевірку на рівність за допомогою ===
+// використовуйте break, щоб призупити виконання наступного case,
+grade = 4;
+switch (grade) {
+ case 5:
+ console.log("Відмінно");
+ break;
+ case 4:
+ console.log("Добре");
+ break;
+ case 3:
+ console.log("Можна краще");
+ break;
+ default:
+ console.log("Погано!");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Функції, область видимості і замикання
+
+// Функції в JavaScript оголошуються за допомогою ключового слова function.
+function myFunction(thing) {
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж
+// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined
+// із-за автоматичної вставки крапки з комою
+function myFunction()
+{
+ return // <- крапка з комою вставляється автоматично
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися
+// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник
+// події.
+function myFunction() {
+ // код буде виконано через 5 сек.
+}
+setTimeout(myFunction, 5000);
+// setTimeout не є частиною мови, але реалізований в браузерах і Node.js
+
+// Функции не обязательно должны иметь имя при объявлении — вы можете написать
+// анонимное определение функции непосредственно в аргументе другой функции.
+// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати
+// анонімну функцію прямо в якості аргумента іншої функції
+setTimeout(function() {
+ // Цей код буде виконано через п’ять секунд
+}, 5000);
+
+// В JavaScript реалізована концепція області видимості; функції мають свою
+// область видимости, а інші блоки не мають
+if (true) {
+ var i = 5;
+}
+i; // = 5, а не undefined, як це звичайно буває в інших мова
+
+// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе"
+// що дозволяє уникнути проникнення змінних в глобальну область видимості
+(function() {
+ var temporary = 5;
+ // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати
+ // змінні до глобальної області
+ window.permanent = 10;
+})();
+temporary; // повідомлення про помилку ReferenceError
+permanent; // = 10
+
+// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция
+// определена внутри другой функции, то внутренняя функция имеет доступ к
+// переменным внешней функции даже после того, как контекст выполнения выйдет из
+// внешней функции.
+// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена
+// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої
+// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції
+function sayHelloInFiveSeconds(name) {
+ var prompt = "Hello, " + name + "!";
+ // Внутрішня функція зберігається в локальній області так,
+ // ніби функція була оголошена за допомогою ключового слова var
+ function inner() {
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться,
+ // після чого setTimeout викличе функцію inner. Але функція inner
+ // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt
+}
+sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!»
+
+///////////////////////////////////
+// 5. Об’єкти: конструктори і прототипи
+
+// Об’єкти можуть містити функції
+var myObj = {
+ myFunc: function() {
+ return "Hello, world!";
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за
+// допомогою ключового слова this.
+myObj = {
+ myString: "Hello, world!",
+ myFunc: function() {
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello, world!"
+
+// Значення this залежить від того, як функція викликається
+// а не від того, де вона визначена. Таким чином наша функція не працює, якщо
+// вона викликана не в контексті об’єкта
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до
+// цього об’єкта через this
+var myOtherFunc = function() {
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO, WORLD!"
+
+// Контекст виконання функції можна задати за допомогою сall або apply
+var anotherFunc = function(s) {
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!"
+
+// Функцiя apply приймає в якості аргументу масив
+anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!"
+
+// apply можна використати, коли функція працює послідовністю аргументів, а
+// ви хочете передати масив
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (Ой-ой!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт
+// використовують bind
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" Hello!"); // = "Hello world, Hello!"
+
+// Bind можна використати для задання аргументів
+var product = function(a, b) { return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт,
+// доступний функції за допомогою this. Такі функції називають конструкторами.
+var MyConstructor = function() {
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому
+// об’єктів, інтерпретатор буде шукати поле в прототипі
+
+// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через
+// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують
+// стандартні способи використання прототипів, які ми побачимо пізніше
+var myObj = {
+ myString: "Hello, world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function() {
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// Аналогічно для функцій
+myObj.myFunc(); // = "Hello, world!"
+
+// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук
+// в прототипі прототипа і так далі
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити
+// наш прототип, і наші зміни будуть всюди відображені.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу
+// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим
+// прототипом
+
+// Перший спосіб — це Object.create, який з’явився JavaScript недавно,
+// а тому в деяких реалізаціях може бути не доступним.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не*
+// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені
+// цим конструктором і ключового слова new.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function() {
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні
+// об’єкти-обгортки
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Але вони не ідентичні
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0) {
+ // Этот код не выполнится, потому что 0 - это ложь.
+}
+
+// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому
+// ви можете розширити функціонал рядків:
+String.prototype.firstCharacter = function() {
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості
+// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих
+// середовищах
+
+// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо
+// використати функції за допомогою наступного поліфіла:
+if (Object.create === undefined) { // не перезаписываем метод, если он существует
+ Object.create = function(proto) {
+ // Створюємо правильний конструктор з правильним прототипом
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+
+ return new Constructor();
+ }
+}
+```
+
+## Що почитати
+
+[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
+[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
+[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core
+[4]: http://www.learneroo.com/modules/64/nodes/350
+[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]: http://eloquentjavascript.net/
+[9]: http://jstherightway.org/
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index bdfdcc10..accdbf56 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -32,6 +32,9 @@ Module Module1
Console.WriteLine("50. About")
Console.WriteLine("Please Choose A Number From The Above List")
Dim selection As String = Console.ReadLine
+ ' The "Case" in the Select statement is optional.
+ ' For example, "Select selection" instead of "Select Case selection"
+ ' will also work.
Select Case selection
Case "1" 'HelloWorld Output
Console.Clear() 'Clears the application and opens the private sub
diff --git a/xml.html.markdown b/xml.html.markdown
index b95d6088..b4b54330 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -4,18 +4,76 @@ filename: learnxml.xml
contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
- ["Rachel Stiyer", "https://github.com/rstiyer"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
---
-XML is a markup language designed to store and transport data.
+XML is a markup language designed to store and transport data. It is supposed to be both human readable and machine readable.
Unlike HTML, XML does not specify how to display or to format data, it just carries it.
-* XML Syntax
+Distinctions are made between the **content** and the **markup**. In short, content could be anything, markup is defined.
+
+## Some definitions and introductions
+
+XML Documents are basically made up of *elements* which can have *attributes* describing them and may contain some textual content or more elements as its children. All XML documents must have a root element, which is the ancestor of all the other elements in the document.
+
+XML Parsers are designed to be very strict, and will stop parsing malformed documents. Therefore it must be ensured that all XML documents follow the [XML Syntax Rules](http://www.w3schools.com/xml/xml_syntax.asp).
```xml
-<!-- Comments in XML are like this -->
+<!-- This is a comment. It must not contain two consecutive hyphens (-). -->
+<!-- Comments can span
+ multiple lines -->
+
+<!-- Elements -->
+<!-- An element is a basic XML component. There are two types, empty: -->
+<element1 attribute="value" /> <!-- Empty elements do not hold any content -->
+<!-- and non-empty: -->
+<element2 attribute="value">Content</element2>
+<!-- Element names may only contain alphabets and numbers. -->
+
+<empty /> <!-- An element either consists an empty element tag… -->
+<!-- …which does not hold any content and is pure markup. -->
+
+<notempty> <!-- Or, it consists of a start tag… -->
+ <!-- …some content… -->
+</notempty> <!-- and an end tag. -->
+
+<!-- Element names are case sensitive. -->
+<element />
+<!-- is not the same as -->
+<eLEMENT />
+
+<!-- Attributes -->
+<!-- An attribute is a key-value pair and exists within an element. -->
+<element attribute="value" another="anotherValue" many="space-separated list" />
+<!-- An attribute may appear only once in an element. It holds just one value.
+ Common workarounds to this involve the use of space-separated lists. -->
+
+<!-- Nesting elements -->
+<!-- An element's content may include other elements: -->
+<parent>
+ <child>Text</child>
+ <emptysibling />
+</parent>
+<!-- Standard tree nomenclature is followed. Each element being called a node.
+ An ancestor a level up is the parent, descendants a level down are children.
+ Elements within the same parent element are siblings. -->
+
+<!-- XML preserves whitespace. -->
+<child>
+ Text
+</child>
+<!-- is not the same as -->
+<child>Text</child>
+```
+
+## An XML document
+This is what makes XML versatile. It is human readable too. The following document tells us that it defines a bookstore which sells three books, one of which is Learning XML by Erik T. Ray. All this without having used an XML Parser yet.
+
+```xml
<?xml version="1.0" encoding="UTF-8"?>
+<!-- This is called an XML prolog. Optional, but recommended. -->
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
@@ -36,85 +94,49 @@ Unlike HTML, XML does not specify how to display or to format data, it just carr
<price>39.95</price>
</book>
</bookstore>
-
-<!-- Above is a typical XML file.
- It starts with a declaration, informing some metadata (optional).
-
- XML uses a tree structure. Above, the root node is 'bookstore', which has
- three child nodes, all 'books'. Those nodes have more child nodes (or
- children), and so on...
-
- Nodes are created using open/close tags, and children are just nodes between
- the open and close tags.-->
-
-
-<!-- XML carries two kinds of data:
- 1 - Attributes -> That's metadata about a node.
- Usually, the XML parser uses this information to store the data properly.
- It is characterized by appearing with the format name="value" within the opening
- tag.
- 2 - Elements -> That's pure data.
- That's what the parser will retrieve from the XML file.
- Elements appear between the open and close tags. -->
-
-
-<!-- Below, an element with two attributes -->
-<file type="gif" id="4293">computer.gif</file>
-
-
```
-* Well-Formated Document x Validation
-
-An XML document is well-formatted if it is syntactically correct.
-However, it is possible to inject more constraints in the document,
-using document definitions, such as DTD and XML Schema.
+## Well-formedness and Validation
-An XML document which follows a document definition is called valid,
-in regards to that document.
-
-With this tool, you can check the XML data outside the application logic.
+A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed.
```xml
-
-<!-- Below, you can see an simplified version of bookstore document,
- with the addition of DTD definition.-->
-
+<!-- Declaring a DTD externally: -->
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE note SYSTEM "Bookstore.dtd">
+<!DOCTYPE bookstore SYSTEM "Bookstore.dtd">
+<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path
+ to our DTD file. -->
<bookstore>
<book category="COOKING">
- <title>Everyday Italian</title>
+ <title lang="en">Everyday Italian</title>
+ <author>Giada De Laurentiis</author>
+ <year>2005</year>
<price>30.00</price>
</book>
</bookstore>
-<!-- This DTD could be something like:-->
-
-<!DOCTYPE note
-[
+<!-- The DTD file: -->
<!ELEMENT bookstore (book+)>
-<!ELEMENT book (title,price)>
+<!-- The bookstore element may contain one or more child book elements. -->
+<!ELEMENT book (title, price)>
+<!-- Each book must have a title and a price as its children. -->
<!ATTLIST book category CDATA "Literature">
+<!-- A book should have a category attribute. If it doesn't, its default value
+ will be 'Literature'. -->
<!ELEMENT title (#PCDATA)>
+<!-- The element title must only contain parsed character data. That is, it may
+ only contain text which is read by the parser and must not contain children.
+ Compare with CDATA, or character data. -->
<!ELEMENT price (#PCDATA)>
]>
-
-<!-- The DTD starts with a declaration.
- Following, the root node is declared, requiring 1 or more child nodes 'book'.
- Each 'book' should contain exactly one 'title' and 'price' and an attribute
- called 'category', with "Literature" as its default value.
- The 'title' and 'price' nodes contain a parsed character data.-->
-
<!-- The DTD could be declared inside the XML file itself.-->
<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE note
-[
+<!DOCTYPE bookstore [
<!ELEMENT bookstore (book+)>
-<!ELEMENT book (title,price)>
+<!ELEMENT book (title, price)>
<!ATTLIST book category CDATA "Literature">
<!ELEMENT title (#PCDATA)>
<!ELEMENT price (#PCDATA)>
@@ -127,3 +149,18 @@ With this tool, you can check the XML data outside the application logic.
</book>
</bookstore>
```
+
+## DTD Compatibility and XML Schema Definitions
+
+Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XML features like namespaces are not supported by DTDs. XML Schema Definitions (XSDs) are meant to replace DTDs for defining XML document grammar.
+
+## Resources
+
+* [Validate your XML](http://www.xmlvalidation.com)
+
+## Further Reading
+
+* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/)
+* [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/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index 8904970f..b0b1183f 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -200,13 +200,13 @@ foo 5 -- 75
-- 你可以使用 `$` 来移除多余的括号。
-- 修改前
-(even (fib 7)) -- true
+(even (fib 7)) -- False
-- 修改后
-even . fib $ 7 -- true
+even . fib $ 7 -- False
-- 等价地
-even $ fib 7 -- true
+even $ fib 7 -- False
----------------------------------------------------
-- 5. 类型声明
diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown
index 12afa59a..a8fd2a4c 100644
--- a/zh-cn/java-cn.html.markdown
+++ b/zh-cn/java-cn.html.markdown
@@ -405,4 +405,4 @@ class PennyFarthing extends Bicycle {
* [泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-* [Java代码规范](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+* [Java代码规范](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)