From 4b0f53d964cc219c491765bfa9c8635cf6d38863 Mon Sep 17 00:00:00 2001 From: Tomasz Janiszewski Date: Thu, 1 Oct 2015 09:56:31 +0200 Subject: [PATCH 01/77] Add Polish translations for XML --- pl-pl/xml-pl.html.markdown | 137 +++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 pl-pl/xml-pl.html.markdown diff --git a/pl-pl/xml-pl.html.markdown b/pl-pl/xml-pl.html.markdown new file mode 100644 index 00000000..7cce138f --- /dev/null +++ b/pl-pl/xml-pl.html.markdown @@ -0,0 +1,137 @@ +--- +language: xml +filename: learnxml-pl.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Tomasz Janiszewski", "https://github.com/janisz"] +lang: pl-pl +--- + +XML (_Extensible Markup Language_) to rozszerzalny język znaczników, stworzony +do przechowywania i transportu danych. + +W przeciwieństwie do HTML, XML nie specyfikuje w jaki sposób wyświetlić dane, a +tylko je przechowuje. + +* Składnia XML + +```xml + + + + + + Codzienny Włoski + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Nauka XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + +komputer.gif + + +``` + +* Dobrze sformatowany dokument i walidacja + +Dokument XML jest dobrze sformatowany gdy jest syntaktycznie poprawny. +Jednakże możliwe jest wstrzykiwanie większej liczby ograniczeń w dokumencie, +używając definicji takich jak DTD i XML Schema. + +Dokument XML, który jest zgodny ze swoją definicją jest poprawny. + + +Korzystając z tych narzędzi możesz sprawdzić dane zawarte w dokumencie poza +logiką aplikacji. + +```xml + + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` From 95af711a03e89d6f95b81e5b9d9b4cb530789a35 Mon Sep 17 00:00:00 2001 From: Tomy Date: Sun, 18 Oct 2015 13:00:23 +0900 Subject: [PATCH 02/77] begin translate --- ja-jp/php.html.markdown | 767 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 767 insertions(+) create mode 100644 ja-jp/php.html.markdown diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown new file mode 100644 index 00000000..3831e220 --- /dev/null +++ b/ja-jp/php.html.markdown @@ -0,0 +1,767 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Kazushige Tominaga", "https://github.com/kazu9su"] +filename: learnphp.php +--- + +このドキュメントでは、 PHP 5+ について説明します。 + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Delete variable +unset($int1); + +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$number = 0; +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evaluation) +$number /= $float; // Divide and assign the quotient to $number + +// Strings should be enclosed in single quotes; +$sgl_quotes = '$String'; // => '$String' + +// Avoid using double quotes except to embed other variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Enclose a variable in curly braces if needed +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 introduced a new syntax +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints 1 + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Add an element to the end of an array +$array[] = 'Four'; +// or +array_push($array, 'Five'); + +// Remove element from array +unset($array[3]); + +/******************************** + * Output + */ + +echo('Hello World!'); +// Prints Hello World! to stdout. +// Stdout is the web page if running in a browser. + +print('Hello World!'); // The same as echo + +// echo is actually a language construct, so you can drop the parentheses. +echo 'Hello World!'; +print 'Hello World!'; // So is print + +$paragraph = 'paragraph'; + +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables + +// If short open tags are configured, or your PHP version is +// 5.4.0 or greater, you can use the short echo syntax +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dumps type and value of variable to stdout +var_dump($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert throws a warning if its argument is not true + +// These comparisons will always be true, even if the types aren't the same. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// spaceship operator since PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + +// Variables can be converted between types, depending on their usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings are coerced to integers) + +$string = 'one'; +echo $string + $string; // => 0 +// Outputs 0 because the + operator cannot cast the string 'one' to a number + +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// There are also dedicated functions for casting most types +$integer = 5; +$string = strval($integer); + +$var = null; // Null value + + +/******************************** + * Control Structures + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// This alternative syntax is useful for templates: +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// You can iterate over the keys as well as the values +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Functions + */ + +// Define a function with "function": +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. + +function add ($x, $y = 1) { // $y is optional and defaults to 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result is not accessible outside the function +// print $result; // Gives a warning. + +// Since PHP 5.3 you can declare anonymous functions; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Functions can return functions +function bar ($x, $y) { + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// You can call named functions using strings +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Useful for programatically determining which function to run. +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + //final keyword would make a function unoverridable + final function youCannotOverrideMe() + { + } + +/* + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Class constants can always be accessed statically +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// Instantiate classes using new +$my_class = new MyClass('An instance property'); +// The parentheses are optional if not passing in an argument. + +// Access class members using -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sun, 18 Oct 2015 13:27:55 +0900 Subject: [PATCH 03/77] translate first block --- ja-jp/php.html.markdown | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 3831e220..4448a1f5 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -13,32 +13,30 @@ filename: learnphp.php ```php Hello World Again! Date: Sat, 24 Oct 2015 20:51:42 -0200 Subject: [PATCH 04/77] Add more resources, add me to contributors --- pt-br/ruby-pt.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 89a051d4..668cd25f 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -4,6 +4,7 @@ lang: pt-br filename: learnruby-pt.rb contributors: - ["Bruno Henrique - Garu", "http://garulab.com"] + - ["Jean Matheus Souto", "http://jeanmatheussouto.github.io"] translators: - ["Katyanna Moura", "https://twitter.com/amelie_kn"] --- @@ -161,9 +162,6 @@ hash['numero'] #=> 5 hash['nada aqui'] #=> nil # Interar sobre hashes com o método #each: -hash.each do |k, v| - puts "#{k} is #{v}" -end hash.each do |k, v| puts "#{k} é #{v}" @@ -385,3 +383,11 @@ Humano.bar # 0 Doutor.bar # nil ``` + +## Mais sobre Ruby + +- [Documentação oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Aprenda Ruby com desafios](http://www.learneroo.com/modules/61/nodes/338) - Uma coleção de desafios para testar a linguagem. +- [Ruby a partir de outras linguagens](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/)- Um mais antigo [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) e tambem uma versão online disponível. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Uma versão colaborativa de um *style-guide* From b27ddf1bd65c0d62293934eee085fafe340937d4 Mon Sep 17 00:00:00 2001 From: meinkej Date: Thu, 29 Oct 2015 19:44:21 +0100 Subject: [PATCH 05/77] [go/de] More infos, reformulation and typo fixes for Go. --- de-de/go-de.html.markdown | 40 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d3a192fe..099927b6 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -4,17 +4,16 @@ filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] - ["Dennis Keller", "https://github.com/denniskeller"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de --- -Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in -der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in -der realen Welt zu lösen. - -Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung -und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu -verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern -Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große -Programmierprojekte. +Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007 +benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele +Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und +benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente +für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen +Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten +erleichtert. Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine aktive Community. @@ -24,7 +23,7 @@ aktive Community. /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung). // "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. @@ -40,7 +39,7 @@ import ( // Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des -// Programms. Vergessen Sie nicht die geschweiften Klammern! +// Programms. func main() { // Println gibt eine Zeile zu stdout aus. // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. @@ -50,8 +49,8 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert, -// die aber auch bei keinen Parametern erforderlich sind. +// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. @@ -306,14 +305,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel -Dokumentation lesen. +Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor +allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr -kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen +ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil +verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). - From e5a02057227506b95630658971caabb30b64f705 Mon Sep 17 00:00:00 2001 From: meinkej Date: Thu, 29 Oct 2015 19:50:17 +0100 Subject: [PATCH 06/77] Fix a typo introduced in the previous commit. Reformatted some lines. --- de-de/go-de.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 099927b6..94f48e65 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -49,7 +49,7 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert, // die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. @@ -98,7 +98,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre // Vorzüge, aber slices werden viel häufiger verwendet s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse - s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0 + s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0 var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung bs := []byte("eine slice") // Umwandlungs-Syntax @@ -200,7 +200,8 @@ type pair struct { x, y int } -// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface. +// Definiere eine Methode von "pair". +// Dieser Typ erfüllt jetzt das Stringer interface. func (p pair) String() string { // p ist der Empfänger // Sprintf ist eine weitere öffentliche Funktion von fmt. // Der Syntax mit Punkt greift auf die Felder zu. @@ -254,8 +255,9 @@ func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für // maps, slices und Kanäle. c := make(chan int) - // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. + // Starte drei parallele "Goroutines". + // Die Zahlen werden parallel (concurrently) erhöht. + // Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) From 608615360c7f49cb33c9e7eb3957e031b9b8a89c Mon Sep 17 00:00:00 2001 From: Niko Weh Date: Sat, 31 Oct 2015 22:37:13 +1000 Subject: [PATCH 07/77] [haskell/en] Extended section on GHCi - Added the :i command, as i feel that it is as useful as :t. - Added another example for :t, hopefully showcasing it's flexibility - For consistency, changed the name of (.) from function to operator (as is already the case with ($)), and added a short remark in the GHCi section that (most) operators are also functions. --- haskell.html.markdown | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 936744a0..940cf4c7 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -193,7 +193,7 @@ foo = (+10) foo 5 -- 15 -- function composition --- the (.) function chains functions together. +-- the operator `.` chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, -- multiplies the result of that by 4, and then returns the final value. foo = (*4) . (+10) @@ -401,11 +401,26 @@ main'' = do let foo = 5 --- You can see the type of any value with `:t`: +-- You can see the type of any value or expression with `:t`: ->:t foo +> :t foo foo :: Integer +-- Operators, such as `+`, `:` and `$`, are functions. +-- Their type can be inspected by putting the operator in parentheses: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- You can get additional information on any `name` using `:i`: + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + -- You can also run any action of type `IO ()` > sayHello From b336e810865a1a2ce54c53b467bcd1545455a679 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:12:18 +0300 Subject: [PATCH 08/77] removed controversial performance info, fixed recursion info and typos --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..13e8d9d8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -231,7 +231,7 @@ r foreach println (5 to 1 by -1) foreach (println) -// A while loops +// A while loop var i = 0 while (i < 10) { println("i " + i); i += 1 } @@ -239,17 +239,18 @@ while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very - // fast, faster that Java loops, but using the combinators and - // comprehensions above is easier to understand and parallelize + // fast, but using the combinators and comprehensions above is easier + // to understand and parallelize -// A do while loop +// A do-while loop i = 0 do { println("i is still less than 10") i += 1 } while (i < 10) -// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursion is the idiomatic way of repeating an action in Scala (as in most +// other functional languages). // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. def showNumbersInRange(a: Int, b: Int): Unit = { @@ -267,7 +268,7 @@ val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") +if (x == 11) println("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" From 92a736f5e06473d454f197b8017dc542ba8c404c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:02:00 -0500 Subject: [PATCH 09/77] Added solidity --- solidity.html.markdown | 381 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 solidity.html.markdown diff --git a/solidity.html.markdown b/solidity.html.markdown new file mode 100644 index 00000000..6409828a --- /dev/null +++ b/solidity.html.markdown @@ -0,0 +1,381 @@ +--- +language: Solidity +filename: learnSolidity.sol +contributors: + - ["Nemil Dalal", "https://www.nemil.com"] +--- + +Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. + +Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. + +As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. + +```javascript +// Let's start with a simple Bank contract, before diving into to the key components of the language + +// Start with a Natspec comment (the three slashes) that can be used +// for documentation - and as descriptive data for UI elements +/// @title A simple deposit/withdrawal bank built on Bitcoin + +// All contracts are declared and named (in CamelCase) +contract AcmeBank { + // Declare state variables outside a function, + // these are persistent throughout the life of the contract + + // a dictionary that maps addresses to balances + mapping (address -> uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable), the 'constant' means this value to be + // changed after initialization + address public constant owner; + + // Constructor, can receive one or many variables here + function AcmeBank() { + // msg is a default variable that provides both the + // contract messager's address and amount + owner = msg.address; + // the owner has no additional rights, we're setting it for + // illustrative purposes + } + + function deposit(uint balance) { + balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + + return balances[msg.sender]; + } + + function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; + balances[msg.sender].send(withdrawAmount); + + return balances[msg.sender]; + } + } + + // The 'constant' prevents the function from editing state variables + function balance() constant { + return balances[msg.sender]; + } + + // Fallback function + // This function is called if invalid data is sent or ether without data; + // Added so that ether sent to this contract is reverted if the contract fails + // otherwise, the sender loses their money; you should add this in most contracts + function () { throw; } +} +// End example + +// Now let's go through the basics of Solidity + +// 1. DATA TYPES +// uint is the data type typically used for currency (there are no doubles +// or floats) and for dates +uint x; +int const a = 8; // int of 256 bits, cannot be changed after instantiation +uint8 b; +int64 c; +// int256 is same as int +// For both int and uint, you can explicitly set space in steps of 8, +// e.g., int8, int16 +uint248 e; + +// Type casting +int x = int(b) + +bool b = true; // or do 'var b = true;' for inferred typing + +// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract +// ('Contract Account)') or person/external entity ('External Account') +address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter + +// All addresses can be sent ether in the following way: +owner.send(SOME_BALANCE); // returns false on failure +owner.balance; // the balance of the owner + +// Bytes are provided from 1 to 32 +byte a; // byte is same as bytes1 +bytes32 b; + +// Dynamically sized +bytes m; // A special array, same as byte[] (but packed tightly) +// same as bytes, but does not allow length or index access (for now) +string n = 'hello'; + +// Type inference +// var does inferred typing based on first assignment, +// can't be used in functions parameters +var a = true; +// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// that is different from what the user wanted (uint16), so use carefully + +// by default, all values are set to 0 on instantiation + +// Delete can be called on most types, and will set the values to 0 +uint x = 5; +delete(x); // x is now 0 + +// 2. DATA STRUCTURES +// Arrays +bytes32[] names; +uint newLength = names.push("John"); // adding returns new length of the array +// Length +names.length; // get length +names.length = 1; // lengths can also be set, unlike many other languages + +// Dictionaries (any type to any other type) +mapping (string -> uint) public balances; +balances["john"] = 1; +console.log(balances[jill]); // is 0, all non-set key values return zeroes +// The 'public' lets you do the following from another contract +contractName.balances("john"); // returns 1 +// The 'public' keyword here created a getter (but not setter) that behaves like the following: +function balances(address _account) returns (uint balance) { + return balances[_account]; +} + +// To delete +delete(balances["John"]); +delete(balances); // deletes all elements + +// Unlike languages like Javascript, you cannot iterate through all elements in +// a map, without knowing the source keys + +// Structs and enums + struct Bank { // note the capital + address owner; + uint balance; + } +Bank b = Bank({ + owner: msg.sender, + balance: 5 +}); +delete(b); // set all values to 0, except any mappings + +// Enums +enum State { Created, Locked, Inactive }; +State public state; // Declare variable from enum +state = State.Created; + +// 3. Variables of note +// storage - A persistent storage hash (does not need to be declared) +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + +// tx - This transaction +tx.origin // address, sender of the transaction +tx.gasprice // uint, gas price of the transaction + +// msg - The current message received by the contract +msg.sender; // address, The address of the sender +msg.value; // uint, The amount of gas provided to this contract in wei +msg.data // bytes, complete call data + +// balance of the current contract (both contract and external accounts +// have balances) - often used at the end of a contracts life to send the +// remaining balance to a party +this.balance +// block +now // uint, current time, alias for block.timestamp +block.number // uint, current block number +block.difficulty // uint, current block difficulty +block.blockhash(1) // returns bytes32, only provides for most recent 256 block + +// 4. FUNCTIONS AND MORE +// A. Functions +// Simple function +function increment(uint x) returns (uint) { + x += 1; + return x; +} + +// Functions can return many arguments, and by specifying the returned arguments +// you don't need to explicity return +function increment(uint x, uint y) returns (uint x, uint y) { + x += 1; + y += 1; +} +// This function would have been called like this, and assigned to a tuple +uint (a,b) = increment(1,1); + +// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +uint y; + +function increment(uint x) constant returns (uint x) { + x += 1; + y += 1; // this line would fail + // as y is a state variable, and can't be changed in a constant function +} + +// There are a few 'function visibility specifiers' that can be placed where 'constant' +// is, which include: +// internal (can only be called by an internal function, not one external to the contract) +// public - visibile externally and internally +// private - only visible in the current contract + +// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +function a() { + var z = b; + b(); +} + +function b() { + +} + +// B. Events +// Events are an easy way to notify external listeners that something changed +// You typically decalre them after your contract parameters +event Sent(address from, address to, uint amount); + +// You then call it in a function, when you want to trigger it +sent(from, to, amount); + +// For an external party (a contract or external entity), to watch +// for an event, you write the following: +Coin.Sent().watch({}, '', function(error, result) { + if (!error) { + console.log("Coin transfer: " + result.args.amount + + " coins were sent from " + result.args.from + + " to " + result.args.to + "."); + console.log("Balances now:\n" + + "Sender: " + Coin.balances.call(result.args.from) + + "Receiver: " + Coin.balances.call(result.args.to)); + } +} +// This is a common paradigm for one contract to depend on another (e.g., a +// contract that depends on the current exchange rate provided by another +// contract) + +// C. Modifiers +// Modifiers let you validate inputs to functions +// The '_' (underscore) must be included, and is an indicator that the +// function being called should be placed there +modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } + +// You can then append it right after the function declaration +function test() + onlyBefore() +{ + +} + +// 5. BRANCHING AND LOOPS + +// All basic logic blocks work - including if/else, for, while, break, continue, return +// switch is not provided +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean + +// 6. CALLING AN EXTERNAL CONTRACT + +contract infoFeed { + function info() returns (uint ret) { return 42; } +} + +contract Consumer { + InfoFeed feed; // create a variable that will point to a contract on the blockchain + function setFeed(address addr) { + // Link to the contract by creating on the address + feed = InfoFeed(addr); + } + function callFeed() { + // T final parentheses call the contract, optionally adding + // custom value or gas numbers + feed.info.value(10).gas(800)(); + } +} + +// 7. CONTRACT DESIGN PATTERNS + +// A. Obfuscation +// Remember that all variables are publicly viewable on the blockchain, so +// anything that needs some privacy needs to be obfuscated (e.g., hashed) + +// B. Throwing +// Throwing +throw; // throwing is easily done, and reverts unused money to the sender +// You can't currently catch + +// A common design pattern is: +if (!addr.send(123)) { + throw; +} + +// C. Suicide +// Suicide +suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) + +// D. Storage optimization +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to +// planning your data structures) + +// *** EXAMPLE: Let's do a more complex example *** +// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// - has a 'constant' state variable +// - has a state machine (uses modifier) +// - sends money to an address +// - gets information from another contract (we'll show code for both contracts) +// - Shows inheritance +// - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// Ideas: +// - crowdfunding? +// - Peer to peer insurance +// ] + +// *** END EXAMPLE *** + +// Some final points +// 7. NATIVE FUNCTIONS + +// Currency units +// By default, currency is defined using wei, the smallest unit of Ether +uint minAmount = 1 wei; +uint a = 1 finney; // 1 ether = 1000 finney +// There are a number of other units, see: http://ether.fund/tool/converter + +// Time units +1 == 1 second +1 minutes == 60 seconds + + +// You typically multiply a variable times the unit, as these units are not +// directly stored in a variable +uint x = 5; +(x * 1 days); // 5 days + +// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) + +// Cryptography +// All strings passed are concatenated before the hash is run +sha3("ab", "cd"); +ripemd160("abc"); +sha256("def"); + +// These are natspec comments, when a user is asked to confirm a transaction +/// +/** */ + +// 8. COMMON MISTAKES +// A few common mistakes +// You cannot restrict a human or computer from reading the content of +// your transaction or a transaction's state + +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data states + +// 9. STYLE NOTES +// Use 4 spaces for indentation +// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +``` + +## Additional resources +- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) +- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file From d5bcbceb21954d0f8739fb841fc511aa32c2bcc6 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:07:17 -0500 Subject: [PATCH 10/77] Fixed withdrawal check --- solidity.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6409828a..79debed6 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -49,7 +49,10 @@ contract AcmeBank { function withdraw(uint withdrawAmount) returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - balances[msg.sender].send(withdrawAmount); + + if (!balances[msg.sender].send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; + } return balances[msg.sender]; } From 08f3ee3687fc18286fdb3825f0fc1fd74c086798 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:39:05 -0500 Subject: [PATCH 11/77] Added remove function --- solidity.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 79debed6..bcbdec5f 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -35,15 +35,13 @@ contract AcmeBank { function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; - // the owner has no additional rights, we're setting it for - // illustrative purposes + owner = msg.address; // msg.address refers to the address of the contract creator } function deposit(uint balance) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable - return balances[msg.sender]; + return balances[msg.sender]; // msg.sender refers to the contract caller } function withdraw(uint withdrawAmount) returns (uint remainingBalance) { @@ -58,6 +56,13 @@ contract AcmeBank { } } + // It's good practice to have a remove function, which disables this contract + function remove () { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } + // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; From 1f4738cbc75f789992270c3926cf9cdd30c4674a Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 24 Nov 2015 00:09:10 -0500 Subject: [PATCH 12/77] Several fixes per Andreas's feedback --- solidity.html.markdown | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index bcbdec5f..88ccd817 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,28 +14,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// START EXAMPLE // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin // All contracts are declared and named (in CamelCase) +// They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address -> uint) balances; + mapping (address => uint) balances; // the 'public' makes 'owner' externally readable by users or contracts // (but not writeable), the 'constant' means this value to be // changed after initialization - address public constant owner; + address public owner; // Constructor, can receive one or many variables here function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; // msg.address refers to the address of the contract creator + owner = msg.sender; // msg.sender refers to the address of the contract creator } function deposit(uint balance) { @@ -48,7 +50,7 @@ contract AcmeBank { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!balances[msg.sender].send(withdrawAmount)) { + if (!msg.sender.send(withdrawAmount)) { balances[msg.sender] += withdrawAmount; } @@ -56,7 +58,7 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract + // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner function remove () { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -74,7 +76,7 @@ contract AcmeBank { // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// End example +// END EXAMPLE // Now let's go through the basics of Solidity @@ -82,7 +84,7 @@ contract AcmeBank { // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; -int const a = 8; // int of 256 bits, cannot be changed after instantiation +int constant a = 8; // int of 256 bits, cannot be changed after instantiation uint8 b; int64 c; // int256 is same as int @@ -134,7 +136,7 @@ names.length; // get length names.length = 1; // lengths can also be set, unlike many other languages // Dictionaries (any type to any other type) -mapping (string -> uint) public balances; +mapping (string => uint) public balances; balances["john"] = 1; console.log(balances[jill]); // is 0, all non-set key values return zeroes // The 'public' lets you do the following from another contract @@ -322,13 +324,14 @@ suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the add // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** -// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable // - has a state machine (uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// - Shows the swapping out of a contract // Ideas: // - crowdfunding? // - Peer to peer insurance @@ -375,7 +378,9 @@ sha256("def"); // All data to the start of time is stored in the blockchain, so you and // anyone can observe all previous data states -// 9. STYLE NOTES +// 9. TESTING + +// 10. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` From 700f3e7a1cb6ef5b905eac7ec3fe3aa2e713c079 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:45:03 -0500 Subject: [PATCH 13/77] Many minor updates --- solidity.html.markdown | 226 ++++++++++++++++++++++++++--------------- 1 file changed, 145 insertions(+), 81 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 88ccd817..0fa1fddc 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,7 +14,7 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language -// START EXAMPLE +// ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin @@ -22,31 +22,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat // All contracts are declared and named (in CamelCase) // They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { - // Declare state variables outside a function, + // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + mapping (address => uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable) - + address public owner; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable), the 'constant' means this value to be - // changed after initialization - address public owner; - // Constructor, can receive one or many variables here function AcmeBank() { - // msg is a default variable that provides both the + // msg is a default variable that provides both the // contract messager's address and amount owner = msg.sender; // msg.sender refers to the address of the contract creator } - - function deposit(uint balance) { + + function deposit(uint balance) public { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller } - function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; @@ -58,8 +57,9 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner - function remove () { + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner } @@ -71,29 +71,35 @@ contract AcmeBank { } // Fallback function - // This function is called if invalid data is sent or ether without data; + // The fallback function is called if none of the other functions matches the given function identifier. + // It is often meant to be called when invalid data is sent or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// END EXAMPLE +// ** END EXAMPLE ** // Now let's go through the basics of Solidity -// 1. DATA TYPES +// 1. DATA TYPES AND ASSOCIATED METHOD // uint is the data type typically used for currency (there are no doubles // or floats) and for dates -uint x; -int constant a = 8; // int of 256 bits, cannot be changed after instantiation +uint x; + + +// with 'constant', the compiler replaces each occurence with the acutal value +// int of 256 bits, cannot be changed after instantiation +int constant a = 8; +int256 constant a = 8; // same effect as line above, here the 256 is explict + +// For both int and uint, you can explicitly set space in steps of 8 +// e.g., int8, int16 uint8 b; int64 c; -// int256 is same as int -// For both int and uint, you can explicitly set space in steps of 8, -// e.g., int8, int16 uint248 e; // Type casting -int x = int(b) +int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing @@ -115,21 +121,22 @@ bytes m; // A special array, same as byte[] (but packed tightly) string n = 'hello'; // Type inference -// var does inferred typing based on first assignment, +// var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// there are edge cases where inference leads to a value being set (e.g., an uint 8) // that is different from what the user wanted (uint16), so use carefully // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 +// Delete can be called on most types, and will set the values to 0 by assignment uint x = 5; delete(x); // x is now 0 // 2. DATA STRUCTURES // Arrays -bytes32[] names; +bytes32[5] nicknames; // static array +bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length @@ -153,13 +160,13 @@ delete(balances); // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys -// Structs and enums +// Structs and enums struct Bank { // note the capital address owner; uint balance; } Bank b = Bank({ - owner: msg.sender, + owner: msg.sender, balance: 5 }); delete(b); // set all values to 0, except any mappings @@ -168,29 +175,39 @@ delete(b); // set all values to 0, except any mappings enum State { Created, Locked, Inactive }; State public state; // Declare variable from enum state = State.Created; +// enums can be explicitly converted to ints + +// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// 'memory' does not persist, 'storage' does +// Default is 'storage' for local and state variables; 'memory' for function parameters // 3. Variables of note -// storage - A persistent storage hash (does not need to be declared) -storage['abc'] = 'def'; // maps 256 bit words to 256 bit words +// ** this ** +this; // the address of the current contract +// 'balance' often used at the end of a contracts life to send the +// remaining balance to a party +this.balance; +this.someFunction(); // calls a function externally (via a message call, not via an internal jump) -// tx - This transaction -tx.origin // address, sender of the transaction -tx.gasprice // uint, gas price of the transaction - -// msg - The current message received by the contract +// ** msg - The current message received by the contract ** ** msg.sender; // address, The address of the sender msg.value; // uint, The amount of gas provided to this contract in wei -msg.data // bytes, complete call data +msg.data; // bytes, complete call data +msg.gas; // remaining gas -// balance of the current contract (both contract and external accounts -// have balances) - often used at the end of a contracts life to send the -// remaining balance to a party -this.balance -// block +// ** tx - This transaction ** +tx.origin; // address, sender of the transaction +tx.gasprice; // uint, gas price of the transaction + +// ** block - Information about the current block ** now // uint, current time, alias for block.timestamp -block.number // uint, current block number -block.difficulty // uint, current block difficulty -block.blockhash(1) // returns bytes32, only provides for most recent 256 block +block.number; // uint, current block number +block.difficulty; // uint, current block difficulty +block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +block.gasLimit(); + +// ** storage - A persistent storage hash (does not need to be declared) ** +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // 4. FUNCTIONS AND MORE // A. Functions @@ -236,13 +253,13 @@ function b() { // B. Events // Events are an easy way to notify external listeners that something changed -// You typically decalre them after your contract parameters +// You typically declare them after your contract parameters event Sent(address from, address to, uint amount); // You then call it in a function, when you want to trigger it sent(from, to, amount); -// For an external party (a contract or external entity), to watch +// For an external party (a contract or external entity), to watch // for an event, you write the following: Coin.Sent().watch({}, '', function(error, result) { if (!error) { @@ -254,53 +271,89 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a +// This is a common paradigm for one contract to depend on another (e.g., a // contract that depends on the current exchange rate provided by another // contract) // C. Modifiers -// Modifiers let you validate inputs to functions -// The '_' (underscore) must be included, and is an indicator that the +// Modifiers let you validate inputs to functions such as a minimal balance or user authentication +// It's similar to a guard clause in other languages + +// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } // You can then append it right after the function declaration -function test() - onlyBefore() -{ - +function changeOwner(newOwner) + onlyBefore(someTime) + { + owner = newOwner; } // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return // switch is not provided -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean -// 6. CALLING AN EXTERNAL CONTRACT +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean, so comparison operators must be used to get the boolean value +// 6. OBJECTS/CONTRACTS + +// A. Calling an external contract contract infoFeed { function info() returns (uint ret) { return 42; } } contract Consumer { InfoFeed feed; // create a variable that will point to a contract on the blockchain - function setFeed(address addr) { + + // Set feed to an existing contract + function setFeed(address addr) { // Link to the contract by creating on the address - feed = InfoFeed(addr); + feed = InfoFeed(addr); } - function callFeed() { - // T final parentheses call the contract, optionally adding + + // Set feed based to a new instance of the contract + function createNewFeed() { + feed = new InfoFeed(); + } + + function callFeed() { + // T final parentheses call the contract, optionally adding // custom value or gas numbers feed.info.value(10).gas(800)(); } } +// B. Inheritance + +// Order matters, last inherited contract (i.e., 'def') can override parts of the previously +// inherited contracts +contact MyContract is abc, def("a custom argument to def") { + +// Override function + + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function + } + } + + }; + +// C. Import + +import "filename"; +import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; + +// Importing is under active development and will change +// Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so +// Remember that all variables are publicly viewable on the blockchain, so // anything that needs some privacy needs to be obfuscated (e.g., hashed) // B. Throwing @@ -317,26 +370,34 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// This is a common pattern that lets the owner end the contract +function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } +} + // D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** + +// ** START EXAMPLE ** // [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable -// - has a state machine (uses modifier) +// - has a state machine (and uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract +// - Shows the swapping out of a contract address // Ideas: // - crowdfunding? // - Peer to peer insurance // ] - // *** END EXAMPLE *** // Some final points @@ -353,7 +414,7 @@ uint a = 1 finney; // 1 ether = 1000 finney 1 minutes == 60 seconds -// You typically multiply a variable times the unit, as these units are not +// You typically multiply a variable times the unit, as these units are not // directly stored in a variable uint x = 5; (x * 1 days); // 5 days @@ -366,22 +427,22 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -// These are natspec comments, when a user is asked to confirm a transaction -/// -/** */ +// 8. COMMON MISTAKES/MISCONCEPTIONS +// A few common mistakes and misconceptions: -// 8. COMMON MISTAKES -// A few common mistakes -// You cannot restrict a human or computer from reading the content of +// A. You cannot restrict a human or computer from reading the content of // your transaction or a transaction's state -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data states +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data stats -// 9. TESTING +// When you don't specify public on a variable, you are indicating that other *contracts* can't +// read the data - but any person can still read the data -// 10. STYLE NOTES -// Use 4 spaces for indentation +// TODO + +// 9. STYLE NOTES +// Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` @@ -391,4 +452,7 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) -Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file +## Information purposefully excluded +- Libraries + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail From ec6172fc5e904c65e672ca22bbc6102a94a60ec9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:48:47 -0500 Subject: [PATCH 14/77] Formatting --- solidity.html.markdown | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 0fa1fddc..2adfc00b 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -81,12 +81,12 @@ contract AcmeBank { // Now let's go through the basics of Solidity -// 1. DATA TYPES AND ASSOCIATED METHOD + +// 1. DATA TYPES AND ASSOCIATED METHODS // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; - // with 'constant', the compiler replaces each occurence with the acutal value // int of 256 bits, cannot be changed after instantiation int constant a = 8; @@ -133,6 +133,7 @@ var a = true; uint x = 5; delete(x); // x is now 0 + // 2. DATA STRUCTURES // Arrays bytes32[5] nicknames; // static array @@ -181,6 +182,7 @@ state = State.Created; // 'memory' does not persist, 'storage' does // Default is 'storage' for local and state variables; 'memory' for function parameters + // 3. Variables of note // ** this ** this; // the address of the current contract @@ -209,6 +211,7 @@ block.gasLimit(); // ** storage - A persistent storage hash (does not need to be declared) ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + // 4. FUNCTIONS AND MORE // A. Functions // Simple function @@ -290,6 +293,7 @@ function changeOwner(newOwner) owner = newOwner; } + // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return @@ -298,6 +302,7 @@ function changeOwner(newOwner) // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value + // 6. OBJECTS/CONTRACTS // A. Calling an external contract @@ -350,6 +355,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing is under active development and will change // Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation @@ -383,6 +389,8 @@ function remove() { // compilation may better handle this, but for now there are benefits to // planning your data structures) + + // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -400,7 +408,7 @@ function remove() { // ] // *** END EXAMPLE *** -// Some final points + // 7. NATIVE FUNCTIONS // Currency units @@ -427,6 +435,7 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); + // 8. COMMON MISTAKES/MISCONCEPTIONS // A few common mistakes and misconceptions: @@ -441,6 +450,7 @@ sha256("def"); // TODO + // 9. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) From 4b7d7e3d2e86e6e2d5b95b518864ecd89392d7c0 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:01:51 -0500 Subject: [PATCH 15/77] Spelling and grammar --- solidity.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2adfc00b..3e47f080 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -72,7 +72,7 @@ contract AcmeBank { // Fallback function // The fallback function is called if none of the other functions matches the given function identifier. - // It is often meant to be called when invalid data is sent or ether without data. + // Typically, called when invalid data is sent to the contract or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } @@ -87,10 +87,10 @@ contract AcmeBank { // or floats) and for dates uint x; -// with 'constant', the compiler replaces each occurence with the acutal value +// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; -int256 constant a = 8; // same effect as line above, here the 256 is explict +int256 constant a = 8; // same effect as line above, here the 256 is explicit // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -221,7 +221,7 @@ function increment(uint x) returns (uint) { } // Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicity return +// you don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { x += 1; y += 1; @@ -241,7 +241,7 @@ function increment(uint x) constant returns (uint x) { // There are a few 'function visibility specifiers' that can be placed where 'constant' // is, which include: // internal (can only be called by an internal function, not one external to the contract) -// public - visibile externally and internally +// public - visible externally and internally // private - only visible in the current contract // Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable From 8ef890b0de22d9fd14572f4ac171a238ea4f3f20 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:14:26 -0500 Subject: [PATCH 16/77] Added sample contracts --- solidity.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3e47f080..2b461a95 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -462,6 +462,10 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +## Sample contracts +- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) +- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) + ## Information purposefully excluded - Libraries From add8f68f1acdceca1b9e09d6458627c515e73047 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:51:53 -0500 Subject: [PATCH 17/77] Add exposition around example bank --- solidity.html.markdown | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2b461a95..77648e51 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -13,6 +13,10 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// This bank has three main capabilities: +// - deposit +// - withdrawal +// - check balance // ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used @@ -57,14 +61,6 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } - } - // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; @@ -406,6 +402,14 @@ function remove() { // - crowdfunding? // - Peer to peer insurance // ] + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + // For a decentralized bank without a trusted part + function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } // *** END EXAMPLE *** From 541c278de4b253090b27a1ef126f5ed27e050f7c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 17:23:41 -0500 Subject: [PATCH 18/77] Minor updates --- solidity.html.markdown | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 77648e51..298b01f3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -30,10 +30,13 @@ contract AcmeBank { // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + // the private means that other contracts can't see balances + // but the data is still available to all other parties on the + // blockchain + mapping (address => uint) private balances; // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) - + // (but not writeable) address public owner; // Constructor, can receive one or many variables here @@ -125,9 +128,10 @@ var a = true; // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 by assignment +// Delete can be called on most types +// (it does NOT destroy the value, but rather sets the value to 0 by assignment) uint x = 5; -delete(x); // x is now 0 +delete x; // x is now 0 // 2. DATA STRUCTURES @@ -151,8 +155,8 @@ function balances(address _account) returns (uint balance) { } // To delete -delete(balances["John"]); -delete(balances); // deletes all elements +delete balances["John"]; +delete balances; // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys @@ -166,7 +170,7 @@ Bank b = Bank({ owner: msg.sender, balance: 5 }); -delete(b); // set all values to 0, except any mappings +delete b; // set all variables in struct to 0, except any mappings // Enums enum State { Created, Locked, Inactive }; @@ -226,6 +230,7 @@ function increment(uint x, uint y) returns (uint x, uint y) { uint (a,b) = increment(1,1); // The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +// Constant function execute locally, not on the blockchain uint y; function increment(uint x) constant returns (uint x) { @@ -469,6 +474,7 @@ sha256("def"); ## Sample contracts - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded - Libraries From 8d7085893535825ea6879e3f29ee0eb614a16f9b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Fri, 11 Dec 2015 13:07:01 -0500 Subject: [PATCH 19/77] Few minor fixes --- solidity.html.markdown | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 298b01f3..7f925918 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,9 +5,9 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. -Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. @@ -46,7 +46,7 @@ contract AcmeBank { owner = msg.sender; // msg.sender refers to the address of the contract creator } - function deposit(uint balance) public { + function deposit(uint balance) public returns (uint) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller @@ -65,7 +65,7 @@ contract AcmeBank { } // The 'constant' prevents the function from editing state variables - function balance() constant { + function balance() constant returns (uint) { return balances[msg.sender]; } @@ -90,6 +90,7 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; int256 constant a = 8; // same effect as line above, here the 256 is explicit +uint constant VERSION_ID = 0x123A1; // A hex constant // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -285,12 +286,14 @@ Coin.Sent().watch({}, '', function(error, result) { // The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there -modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } +modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } +modifier onlyOwner { if (msg.sender == owner) _ } // You can then append it right after the function declaration function changeOwner(newOwner) - onlyBefore(someTime) - { +onlyAfter(someTime) +onlyOwner() +{ owner = newOwner; } @@ -298,7 +301,7 @@ function changeOwner(newOwner) // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return -// switch is not provided +// Unlike other languages, the 'switch' statement is NOT provided // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value @@ -377,7 +380,7 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) -// This is a common pattern that lets the owner end the contract +// This is a common contract pattern that lets the owner end the contract, and receive remaining funds function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -391,7 +394,6 @@ function remove() { // planning your data structures) - // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -472,6 +474,7 @@ sha256("def"); - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) ## Sample contracts +- [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) From 0b8a0526249264c7ac34069adf3159f2b72771a8 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 18:03:47 -0500 Subject: [PATCH 20/77] Add info on references, modules, and objects These topics are central to modern usage of Perl. --- perl.html.markdown | 132 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 125 insertions(+), 7 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 1b86f410..85f3974e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -5,6 +5,7 @@ language: perl filename: learnperl.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Dan Book", "http://github.com/Grinnz"] --- Perl 5 is a highly capable, feature-rich programming language with over 25 years of development. @@ -14,7 +15,6 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. - #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. @@ -37,7 +37,9 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); - +# Array elements are accessed using square brackets, with a $ to indicate +# one value will be returned. +my $second = $animals[1]; ## Hashes # A hash represents a set of key/value pairs: @@ -50,11 +52,39 @@ my %fruit_color = ( apple => "red", banana => "yellow", ); + +# Hash elements are accessed using curly braces, again with the $ sigil. +my $color = $fruit_color{apple}; + # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). -# More complex data types can be constructed using references, which allow you -# to build lists and hashes within lists and hashes. +#### References + +# More complex data types can be constructed using references, which allow +# you to build arrays and hashes within arrays and hashes. + +my $array_ref = \@array; +my $hash_ref = \%hash; +my @array_of_arrays = (\@array1, \@array2, \@array3); + +# You can also create anonymous arrays or hashes, returning a reference: + +my $fruits = ["apple", "banana"]; +my $colors = {apple => "red", banana => "yellow"}; + +# References can be dereferenced by prefixing the appropriate sigil. + +my @fruits_array = @$fruits; +my %colors_hash = %$colors; + +# As a shortcut, the arrow operator can be used to dereference and access a +# single value. + +my $first = $array_ref->[0]; +my $value = $hash_ref->{banana}; + +# See perlreftut and perlref for more in-depth documentation on references. #### Conditional and looping constructs @@ -105,6 +135,9 @@ for (@elements) { # the Perlish post-condition way again print for @elements; +# iterating through the keys and values of a referenced hash +print $hash_ref->{$_} for keys %$hash_ref; + #### Regular expressions # Perl's regular expression support is both broad and deep, and is the subject @@ -151,11 +184,96 @@ sub logger { # Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!"); + +#### Modules + +# A module is a set of Perl code, usually subroutines, which can be used in +# other Perl code. It is usually stored in a file with the extension .pm so +# that Perl can find it. + +package MyModule; + +sub trim { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +1; + +# From elsewhere: + +use MyModule; +MyModule::trim($string); + +# The Exporter module can help with making subroutines exportable, so they +# can be used like this: + +use MyModule 'trim'; +trim($string); + +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and +# provide a range of features to help you avoid reinventing the wheel. A +# number of popular modules like Exporter are included with the Perl +# distribution itself. See perlmod for more details on modules in Perl. + +#### Objects + +# Objects in Perl are just references that know which class (package) they +# belong to, so that methods (subroutines) called on it can be found there. +# The bless function is used in constructors (usually new) to set this up. +# However, you never need to call it yourself if you use a module like Moose +# or Moo (see below). + +package MyCounter; + +sub new { + my $class = shift; + my $self = {count => 0}; + return bless $self, $class; +} + +sub count { + my $self = shift; + return $self->{count}; +} + +sub increment { + my $self = shift; + $self->{count}++; +} + +1; + +# Methods can be called on a class or object instance with the arrow operator. + +my $counter = MyCounter->new; +print $counter->count, "\n"; # 0 +$counter->increment; +print $counter->count, "\n"; # 1 + +# The modules Moose and Moo from CPAN can help you set up your object classes. +# They provide a constructor and simple syntax for declaring attributes. This +# class can be used equivalently to the one above. + +package MyCounter; +use Moo; + +has 'count' => (is => 'rwp', default => 0, init_arg => undef); + +sub increment { + my $self = shift; + $self->_set_count($self->count + 1); +} + +1; + +# Object-oriented programming is covered more thoroughly in perlootut, and its +# low-level implementation in Perl is covered in perlobj. ``` -#### Using Perl modules - -Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself. +#### FAQ perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. From 35b3c490ce06fb94b8b51bd7f5ceb1638401fb1a Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:22:29 -0500 Subject: [PATCH 21/77] Add blurb about strict and warnings --- perl.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/perl.html.markdown b/perl.html.markdown index 85f3974e..ab71a6ab 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -15,6 +15,16 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. +#### Strict and warnings + +use strict; +use warnings; + +# All perl scripts and modules should include these lines. Strict causes +# compilation to fail in cases like misspelled variable names, and warnings +# will print warning messages in case of common pitfalls like concatenating +# to an undefined value. + #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. From 88af462c699b9f48310a9624bb6bbe94b7101af1 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:39:37 -0500 Subject: [PATCH 22/77] use strict and warnings in example modules --- perl.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/perl.html.markdown b/perl.html.markdown index ab71a6ab..d919e00e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -202,6 +202,8 @@ logger("We have a logger subroutine!"); # that Perl can find it. package MyModule; +use strict; +use warnings; sub trim { my $string = shift; @@ -237,6 +239,8 @@ trim($string); # or Moo (see below). package MyCounter; +use strict; +use warnings; sub new { my $class = shift; @@ -268,7 +272,7 @@ print $counter->count, "\n"; # 1 # class can be used equivalently to the one above. package MyCounter; -use Moo; +use Moo; # imports strict and warnings has 'count' => (is => 'rwp', default => 0, init_arg => undef); From 16d879d712878e2d1aa262dc1218b6543aec99c9 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:51:57 -0500 Subject: [PATCH 23/77] add missing use line --- perl.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/perl.html.markdown b/perl.html.markdown index d919e00e..61e8cd0e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -262,6 +262,7 @@ sub increment { # Methods can be called on a class or object instance with the arrow operator. +use MyCounter; my $counter = MyCounter->new; print $counter->count, "\n"; # 0 $counter->increment; From 299d064ecf7598144e49ef336e0abd00ccc4ae16 Mon Sep 17 00:00:00 2001 From: sarthfrey Date: Wed, 16 Dec 2015 16:41:07 -0500 Subject: [PATCH 24/77] Added Python Resources --- python.html.markdown | 1 + python3.html.markdown | 1 + 2 files changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index d8f18e9b..1d6c0a19 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -726,6 +726,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) ### Dead Tree diff --git a/python3.html.markdown b/python3.html.markdown index 8cc03320..f8c22047 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -780,6 +780,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) * [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) ### Dead Tree From 6749790c8d08aa5aaa06fd0501fd6bdd012ee29b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:11:00 -0500 Subject: [PATCH 25/77] Many edits --- solidity.html.markdown | 739 ++++++++++++++++++++++++++++------------- 1 file changed, 499 insertions(+), 240 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7f925918..a6620986 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,134 +5,194 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a +blockchain-based virtual machine that allows the creation and +computation of smart contracts, without needing centralized or trusted parties. -Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity is a statically typed, contract programming language that has +similarities to Javascript and C. Like objects in OOP, each contract contains +state variables, functions, and common data types. Contract-specific features +include modifier (guard) clauses, event notifiers for listeners, and custom +global variables. -As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. +Some Ethereum contract examples include crowdfunding, voting, and blind auctions. + +As Solidity and Ethereum are under active development, experimental or beta +features are explicitly marked, and subject to change. Pull requests welcome. ```javascript -// Let's start with a simple Bank contract, before diving into to the key components of the language -// This bank has three main capabilities: -// - deposit -// - withdrawal -// - check balance +// First, a simple Bank contract +// Allows deposits, withdrawals, and balance checks -// ** START EXAMPLE ** -// Start with a Natspec comment (the three slashes) that can be used -// for documentation - and as descriptive data for UI elements -/// @title A simple deposit/withdrawal bank built on Bitcoin +// simple_bank.sol (note .sol extension) +/* **** START EXAMPLE **** */ -// All contracts are declared and named (in CamelCase) -// They are similar to 'class' in other languages (and allow capabilities like inheritance) -contract AcmeBank { - // Declare state variables outside a function, - // these are persistent throughout the life of the contract +// Start with Natspec comment (the three slashes) +// used for documentation - and as descriptive data for UI elements/actions - // a dictionary that maps addresses to balances - // the private means that other contracts can't see balances - // but the data is still available to all other parties on the - // blockchain +/// @title SimpleBank +/// @author nemild + +/* 'contract' has similarities to 'class' in other languages (class variables, +inheritance, etc.) */ +contract SimpleBank { // CamelCase + // Declare state variables outside function, persist through life of contract + + // dictionary that maps addresses to balances mapping (address => uint) private balances; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) + // "private" means that other contracts can't directly query balances + // but data is still viewable to other parties on blockchain + address public owner; + // 'public' makes externally readable (not writeable) by users or contracts - // Constructor, can receive one or many variables here + // Events - publicize actions to external listeners + event DepositMade(address accountAddress, uint amount); + + // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg is a default variable that provides both the - // contract messager's address and amount - owner = msg.sender; // msg.sender refers to the address of the contract creator + // msg provides contract messager's address and amount + // msg.sender is contract caller (address of contract creator) + owner = msg.sender; } - function deposit(uint balance) public returns (uint) { - balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + /// @notice Deposit ether into bank + /// @return The balance of the user after the deposit is made + function deposit() public returns (uint) { + balances[msg.sender] += msg.value; + // no "this." or "self." required with state variable + // all values initialized to 0 by default - return balances[msg.sender]; // msg.sender refers to the contract caller - } - - function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { - if(balances[msg.sender] >= withdrawAmount) { - balances[msg.sender] -= withdrawAmount; - - if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; - } + DepositMade(msg.sender, msg.value); // fire event return balances[msg.sender]; + } + + /// @notice Withdraw ether from bank + /// @dev This does not return any excess ether sent to it + /// @param withdrawAmount amount you want to withdraw + /// @return The balance remaining for the user + function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; + + if (!msg.sender.send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; // to be safe + } + + return balances[msg.sender]; } } - // The 'constant' prevents the function from editing state variables + /// @notice Get balance + /// @return The balance of the user + // 'constant' prevents function from editing state variables; + // allows function to run locally/off blockchain function balance() constant returns (uint) { - return balances[msg.sender]; + return balances[msg.sender]; } - // Fallback function - // The fallback function is called if none of the other functions matches the given function identifier. - // Typically, called when invalid data is sent to the contract or ether without data. - // Added so that ether sent to this contract is reverted if the contract fails - // otherwise, the sender loses their money; you should add this in most contracts - function () { throw; } + // Fallback function - Called if other functions don't match call or + // sent ether without data + // Typically, called when invalid data is sent + // Added so ether sent to this contract is reverted if the contract fails + // otherwise, the sender's money is transferred to contract + function () { + throw; // throw reverts state to before call + } } // ** END EXAMPLE ** -// Now let's go through the basics of Solidity +// Now, the basics of Solidity // 1. DATA TYPES AND ASSOCIATED METHODS -// uint is the data type typically used for currency (there are no doubles -// or floats) and for dates +// uint used for currency amount (there are no doubles +// or floats) and for dates (in unix time) uint x; -// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; + +// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant -// For both int and uint, you can explicitly set space in steps of 8 -// e.g., int8, int16 +// Be careful that you don't overflow, and protect against attacks that do + +// For int and uint, can explicitly set space in steps of 8 up to 256 +// e.g., int8, int16, int24 uint8 b; int64 c; uint248 e; +// No random functions built in, use other contracts for randomness + // Type casting int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing -// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract -// ('Contract Account)') or person/external entity ('External Account') -address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter +// Addresses - holds 20 byte/160 bit Ethereum addresses +// No arithmetic allowed +address public owner; -// All addresses can be sent ether in the following way: +// Types of accounts: +// Contract account: address set on create (func of creator address, num transactions sent) +// External Account: (person/external entity): address created from public key + +// Add 'public' field to indicate publicly/externally accessible +// a getter is automatically created, but NOT a setter + +// All addresses can be sent ether owner.send(SOME_BALANCE); // returns false on failure -owner.balance; // the balance of the owner +if (owner.send) {} // typically wrap in 'if', as contract addresses have +// functions have executed on send and can fail -// Bytes are provided from 1 to 32 +// can override send by defining your own + +// Can check balance +owner.balance; // the balance of the owner (user or contract) + + +// Bytes available from 1 to 32 byte a; // byte is same as bytes1 -bytes32 b; +bytes2 b; +bytes32 c; + +// Dynamically sized bytes +bytes m; // A special array, same as byte[] array (but packed tightly) +// More expensive than byte1-byte32, so use those when possible -// Dynamically sized -bytes m; // A special array, same as byte[] (but packed tightly) // same as bytes, but does not allow length or index access (for now) -string n = 'hello'; +string n = "hello"; // stored in UTF8, note double quotes, not single +// string utility functions to be added in future +// prefer bytes32/bytes, as UTF8 uses more storage -// Type inference +// Type inferrence // var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) -// that is different from what the user wanted (uint16), so use carefully +// use carefully, inference may provide wrong type +// e.g., an int8, when a counter needs to be int16 + +// var can be used to assign function to variable +function a(uint x) returns (uint) { + return x * 2; +} +var f = a; +f(22); // call // by default, all values are set to 0 on instantiation // Delete can be called on most types -// (it does NOT destroy the value, but rather sets the value to 0 by assignment) +// (does NOT destroy value, but sets value to 0, the initial value) uint x = 5; -delete x; // x is now 0 + + +// Destructuring/Tuples +(x, y) = (2, 7); // assign/swap multiple value // 2. DATA STRUCTURES @@ -142,74 +202,97 @@ bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length -names.length = 1; // lengths can also be set, unlike many other languages +names.length = 1; // lengths can be set (for dynamic arrays in storage only) + +// multidimensional array +uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages) // Dictionaries (any type to any other type) mapping (string => uint) public balances; -balances["john"] = 1; -console.log(balances[jill]); // is 0, all non-set key values return zeroes -// The 'public' lets you do the following from another contract -contractName.balances("john"); // returns 1 -// The 'public' keyword here created a getter (but not setter) that behaves like the following: +balances["charles"] = 1; +console.log(balances["ada"]); // is 0, all non-set key values return zeroes +// 'public' allows following from another contract +contractName.balances("claude"); // returns 1 +// 'public' created a getter (but not setter) like the following: function balances(address _account) returns (uint balance) { - return balances[_account]; + return balances[_account]; } +// Nested mappings +mapping (address => mapping (address => uint) balances) public custodians; + // To delete delete balances["John"]; -delete balances; // deletes all elements +delete balances; // sets all elements to 0 -// Unlike languages like Javascript, you cannot iterate through all elements in -// a map, without knowing the source keys +// Unlike other languages, CANNOT iterate through all elements in +// mapping, without knowing source keys - can build data structure +// on top to do this // Structs and enums - struct Bank { // note the capital - address owner; - uint balance; - } +struct Bank { + address owner; + uint balance; +} Bank b = Bank({ - owner: msg.sender, - balance: 5 + owner: msg.sender, + balance: 5 }); -delete b; // set all variables in struct to 0, except any mappings +// or +Bank c = Bank(msg.sender, 5); + +c.amount = 5; // set to new value +delete b; +// sets to initial value, set all variables in struct to 0, except mappings // Enums -enum State { Created, Locked, Inactive }; +enum State { Created, Locked, Inactive }; // often used for state machine State public state; // Declare variable from enum state = State.Created; // enums can be explicitly converted to ints +uint createdState = uint(State.Created); // 0 -// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// Data locations: Memory vs. storage vs. stack - all complex types (arrays, +// structs) have a data location // 'memory' does not persist, 'storage' does -// Default is 'storage' for local and state variables; 'memory' for function parameters +// Default is 'storage' for local and state variables; 'memory' for func params +// stack holds small local variables + +// for most types, can explicitly set which data location to use -// 3. Variables of note +// 3. Simple operators +// Comparisons, bit operators and arithmetic operators are provided +// exponentiation: ** +// exclusive or: ^ +// bitwise negation: ~ + + +// 4. Global Variables of note // ** this ** -this; // the address of the current contract -// 'balance' often used at the end of a contracts life to send the -// remaining balance to a party +this; // address of contract +// often used at end of contract life to send remaining balance to party this.balance; -this.someFunction(); // calls a function externally (via a message call, not via an internal jump) +this.someFunction(); // calls func externally via call, not via internal jump -// ** msg - The current message received by the contract ** ** -msg.sender; // address, The address of the sender -msg.value; // uint, The amount of gas provided to this contract in wei +// ** msg - Current message received by the contract ** ** +msg.sender; // address of sender +msg.value; // amount of gas provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas // ** tx - This transaction ** -tx.origin; // address, sender of the transaction -tx.gasprice; // uint, gas price of the transaction +tx.origin; // address of sender of the transaction +tx.gasprice; // gas price of the transaction -// ** block - Information about the current block ** -now // uint, current time, alias for block.timestamp -block.number; // uint, current block number -block.difficulty; // uint, current block difficulty -block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +// ** block - Information about current block ** +now // current time (approximately), alias for block.timestamp (uses Unix time) +block.number; // current block number +block.difficulty; // current block difficulty +block.blockhash(1); // returns bytes32, only works for most recent 256 blocks block.gasLimit(); -// ** storage - A persistent storage hash (does not need to be declared) ** +// ** storage - Persistent storage hash ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words @@ -217,55 +300,61 @@ storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // A. Functions // Simple function function increment(uint x) returns (uint) { - x += 1; - return x; + x += 1; + return x; } -// Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicitly return +// Functions can return many arguments, and by specifying returned arguments +// name don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { - x += 1; - y += 1; + x += 1; + y += 1; } -// This function would have been called like this, and assigned to a tuple +// Call previous functon uint (a,b) = increment(1,1); -// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables -// Constant function execute locally, not on the blockchain +// 'constant' indicates that function does not/cannot change persistent vars +// Constant function execute locally, not on blockchain uint y; function increment(uint x) constant returns (uint x) { - x += 1; - y += 1; // this line would fail - // as y is a state variable, and can't be changed in a constant function + x += 1; + y += 1; // this line would fail + // y is a state variable, and can't be changed in a constant function } -// There are a few 'function visibility specifiers' that can be placed where 'constant' -// is, which include: -// internal (can only be called by an internal function, not one external to the contract) -// public - visible externally and internally +// 'Function Visibility specifiers' +// These can be placed where 'constant' is, including: +// public - visible externally and internally (default) +// external // private - only visible in the current contract +// internal - only visible in current contract, and those deriving from it -// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +// Functions hoisted - and can assign a function to a variable function a() { - var z = b; - b(); + var z = b; + b(); } function b() { } + +// Prefer loops to recursion (max call stack depth is 1024) + // B. Events -// Events are an easy way to notify external listeners that something changed -// You typically declare them after your contract parameters -event Sent(address from, address to, uint amount); +// Events are notify external parties; easy to search and +// access events from outside blockchain (with lightweight clients) +// typically declare after contract parameters -// You then call it in a function, when you want to trigger it -sent(from, to, amount); +// Declare +event Sent(address from, address to, uint amount); // note capital first letter -// For an external party (a contract or external entity), to watch -// for an event, you write the following: +// Call +Sent(from, to, amount); + +// For an external party (a contract or external entity), to watch: Coin.Sent().watch({}, '', function(error, result) { if (!error) { console.log("Coin transfer: " + result.args.amount + @@ -276,195 +365,356 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a -// contract that depends on the current exchange rate provided by another -// contract) +// Common paradigm for one contract to depend on another (e.g., a +// contract that depends on current exchange rate provided by another) // C. Modifiers -// Modifiers let you validate inputs to functions such as a minimal balance or user authentication -// It's similar to a guard clause in other languages +// Modifiers validate inputs to functions such as minimal balance or user auth; +// similar to guard clause in other languages -// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the +// '_' (underscore) often included as last line in body, and indicates // function being called should be placed there modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } modifier onlyOwner { if (msg.sender == owner) _ } +// commonly used with state machines +modifier onlyIfState (State currState) { if (currState != State.A) _ } -// You can then append it right after the function declaration +// Append right after function declaration function changeOwner(newOwner) onlyAfter(someTime) onlyOwner() +onlyIfState(State.A) { - owner = newOwner; + owner = newOwner; +} + +// underscore can be included before end of body, +// but explicitly returning will skip, so use carefully +modifier checkValue(uint amount) { + _ + if (msg.value > amount) { + msg.sender.send(amount - msg.value); + } } -// 5. BRANCHING AND LOOPS +// 6. BRANCHING AND LOOPS -// All basic logic blocks work - including if/else, for, while, break, continue, return -// Unlike other languages, the 'switch' statement is NOT provided +// All basic logic blocks work - including if/else, for, while, break, continue +// return - but no switch -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean, so comparison operators must be used to get the boolean value +// Syntax same as javascript, but no type conversion from non-boolean +// to boolean (comparison operators must be used to get the boolean val) -// 6. OBJECTS/CONTRACTS +// 7. OBJECTS/CONTRACTS -// A. Calling an external contract +// A. Calling external contract contract infoFeed { - function info() returns (uint ret) { return 42; } + function info() returns (uint ret) { return 42; } } contract Consumer { - InfoFeed feed; // create a variable that will point to a contract on the blockchain + InfoFeed feed; // points to contract on blockchain - // Set feed to an existing contract - function setFeed(address addr) { - // Link to the contract by creating on the address - feed = InfoFeed(addr); - } + // Set feed to existing contract instance + function setFeed(address addr) { + // automatically cast, be careful; constructor is not called + feed = InfoFeed(addr); + } - // Set feed based to a new instance of the contract - function createNewFeed() { - feed = new InfoFeed(); - } + // Set feed to new instance of contract + function createNewFeed() { + feed = new InfoFeed(); // constructor called + } - function callFeed() { - // T final parentheses call the contract, optionally adding - // custom value or gas numbers - feed.info.value(10).gas(800)(); - } + function callFeed() { + // final parentheses call contract, can optionally add + // custom ether value or gas + feed.info.value(10).gas(800)(); + } } // B. Inheritance -// Order matters, last inherited contract (i.e., 'def') can override parts of the previously -// inherited contracts -contact MyContract is abc, def("a custom argument to def") { +// Order matters, last inherited contract (i.e., 'def') can override parts of +// previously inherited contracts +contract MyContract is abc, def("a custom argument to def") { // Override function - - function z() { - if (msg.sender == owner) { - def.z(); // call overridden function + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function from def + super.z(); // call immediate parent overriden function + } } - } +} - }; +// abstract function +function someAbstractFunction(uint x); +// cannot be compiled, so used in base/abstract contracts +// that are then implemented // C. Import import "filename"; import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; -// Importing is under active development and will change -// Importing cannot currently be done at the command line +// Importing under active development +// Cannot currently be done at command line + +// 8. OTHER KEYWORDS + +// A. Throwing +// Throwing +throw; // reverts unused money to sender, state is reverted +// Can't currently catch + +// Common design pattern is: +if (!addr.send(123)) { + throw; +} + +// B. Selfdestruct +// selfdestruct current contract, sending funds to address (often creator) +selfdestruct(SOME_ADDRESS); + +// removes storage/code from current/future blocks +// helps thin clients, but previous data persists in blockchain + +// Common pattern, lets owner end the contract and receive remaining funds +function remove() { + if(msg.sender == creator) { // Only let the contract creator do this + selfdestruct(creator); // Makes contract inactive, returns funds + } +} + +// May want to deactivate contract manually, rather than selfdestruct +// (ether sent to selfdestructed contract is lost) -// 7. CONTRACT DESIGN PATTERNS +// 9. CONTRACT DESIGN NOTES // A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so -// anything that needs some privacy needs to be obfuscated (e.g., hashed) +// Remember all variables are publicly viewable on blockchain, so +// anything that needs privacy needs to be obfuscated (e.g., hashed) -// B. Throwing -// Throwing -throw; // throwing is easily done, and reverts unused money to the sender -// You can't currently catch +// Steps: 1. Commit to something, 2. Reveal commitment +sha3("some_bid_amount", "some secret"); // commit -// A common design pattern is: -if (!addr.send(123)) { - throw; -} +// call contract's reveal function showing bid plus secret that hashes to SHA3 +reveal(100, "mySecret"); -// C. Suicide -// Suicide -suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// B. Storage optimization +// Writing to blockchain can be expensive, as data stored forever encourages +// smart ways to use memory (eventually, compilation will be better, but for now +// benefits to planning data structures - and storing min amount in blockchain) -// This is a common contract pattern that lets the owner end the contract, and receive remaining funds -function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } -} +// Cost can often be high for items like multidimensional arrays +// (cost is for storing data - not declaring unfilled variables) -// D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to -// planning your data structures) +// C. Cannot restrict human or computer from reading contents of +// transaction or transaction's state +// When 'private' specified, indicating that other *contracts* can't read +// the data directly - any other party can still read the data in blockchain -// *** EXAMPLE: Let's do a more complex example *** +// D. All data to start of time is stored in blockchain, so +// anyone can observe all previous data and changes +// E. Cron +// Contracts must be manually called to handle time-based scheduling; can create +// external code to do, or provide incentives (ether) for others to do for you + +// F. State machines +// see example below for State enum and inState modifier + +// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** -// [TODO: Decide what a more complex example looks like, needs a few characteristics: -// - has a 'constant' state variable -// - has a state machine (and uses modifier) -// - sends money to an address -// - gets information from another contract (we'll show code for both contracts) -// - Shows inheritance -// - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract address -// Ideas: -// - crowdfunding? -// - Peer to peer insurance -// ] - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - // For a decentralized bank without a trusted part - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } + +// CrowdFunder.sol + +/// @title CrowdFunder +/// @author nemild +contract CrowdFunder { + // Variables set on create by creator + address public creator; + address public fundRecipient; // creator may be different than recipient + uint public minimumToRaise; // required to tip, else everyone gets refund + string campaignUrl; + + // Data structures + enum State { + Fundraising, + ExpiredRefundPending, + Successful, + ExpiredRefundComplete + } + struct Contribution { + uint amount; + address contributor; } -// *** END EXAMPLE *** + // State variables + State public state = State.Fundraising; // initialize on create + uint public totalRaised; + uint public raiseBy; + Contribution[] contributions; -// 7. NATIVE FUNCTIONS + event fundingReceived(address addr, uint amount, uint currentTotal); + event allRefundsSent(); + event winnerPaid(address winnerAddress); + + modifier inState(State _state) { + if (state != _state) throw; + _ + } + + modifier isCreator() { + if (msg.sender != creator) throw; + _ + } + + modifier atEndOfLifecycle() { + if(state != State.ExpiredRefundComplete && state != State.Successful) { + throw; + } + } + + function CrowdFunder( + uint timeInHoursForFundraising, + string _campaignUrl, + address _fundRecipient, + uint _minimumToRaise) + { + creator = msg.sender; + fundRecipient = _fundRecipient; + campaignUrl = _campaignUrl; + minimumToRaise = _minimumToRaise; + raiseBy = now + (timeInHoursForFundraising * 1 hours); + } + + function contribute() + public + inState(State.Fundraising) + { + contributions.push( + Contribution({ + amount: msg.value, + contributor: msg.sender + }) // use array, so can iterate + ); + totalRaised += msg.value; + + fundingReceived(msg.sender, msg.value, totalRaised); + + checkIfFundingCompleteOrExpired(); + } + + function checkIfFundingCompleteOrExpired() { + if (totalRaised > minimumToRaise) { + state = State.Successful; + payOut(); + + // could incentivize sender who initiated state change here + } else if ( now > raiseBy ) { + state = State.ExpiredRefundPending; + refundAll(); + } + } + + function payOut() + public + inState(State.Successful) + { + if(!fundRecipient.send(this.balance)) { + throw; + } + + winnerPaid(fundRecipient); + } + + function refundAll() + public + inState(State.ExpiredRefundPending) + { + uint length = contributions.length; + for (uint i = 0; i < length; i++) { + if(!contributions[i].contributor.send(contributions[i].amount)) { + throw; + } + } + + allRefundsSent(); + state = State.ExpiredRefundComplete; + } + + function removeContract() + public + isCreator() + atEndOfLifecycle() + { + selfdestruct(msg.sender); + } + + function () { throw; } +} +// ** END EXAMPLE ** + +// 10. OTHER NATIVE FUNCTIONS // Currency units -// By default, currency is defined using wei, the smallest unit of Ether +// Currency is defined using wei, smallest unit of Ether uint minAmount = 1 wei; -uint a = 1 finney; // 1 ether = 1000 finney -// There are a number of other units, see: http://ether.fund/tool/converter +uint a = 1 finney; // 1 ether == 1000 finney +// Other units, see: http://ether.fund/tool/converter // Time units 1 == 1 second 1 minutes == 60 seconds - -// You typically multiply a variable times the unit, as these units are not -// directly stored in a variable +// Can multiply a variable times unit, as units are not stored in a variable uint x = 5; (x * 1 days); // 5 days -// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) +// Careful about leap seconds/years with equality statements for time +// (instead, prefer greater than/less than) // Cryptography -// All strings passed are concatenated before the hash is run +// All strings passed are concatenated before hash action sha3("ab", "cd"); ripemd160("abc"); sha256("def"); +11. LOW LEVEL FUNCTIONS +// call - low level, not often used, does not provide type safety +successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); -// 8. COMMON MISTAKES/MISCONCEPTIONS -// A few common mistakes and misconceptions: +// callcode - Code at target address executed in *context* of calling contract +// provides library functionality +someContractAddress.callcode('function_name'); -// A. You cannot restrict a human or computer from reading the content of -// your transaction or a transaction's state +// 12. STYLE NOTES +// Based on Python's PEP8 style guide -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data stats +// 4 spaces for indentation +// Two lines separate contract declarations (and other top level declarations) +// Avoid extraneous spaces in parentheses +// Can omit curly braces for one line statement (if, for, etc) +// else should be placed on own line -// When you don't specify public on a variable, you are indicating that other *contracts* can't -// read the data - but any person can still read the data +// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// Contract natspec - always above contract definition +/// @title Contract title +/// @author Author name -// TODO +// Function natspec +/// @notice information about what function does; shown when function to execute +/// @dev Function documentation for developer - -// 9. STYLE NOTES -// Use 4 spaces for indentation -// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +// Function parameter/return value natspec +/// @param someParam Some description of what the param does +/// @return Description of the return value ``` ## Additional resources @@ -472,6 +722,8 @@ sha256("def"); - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) @@ -481,5 +733,12 @@ sha256("def"); ## Information purposefully excluded - Libraries +- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) + +## Style +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) + +## Future To Dos +- New keywords: protected, inheritable Feel free to send a pull request with any edits - or email nemild -/at-/ gmail From 8f9f9e53e825b346c49139769b8bbfd08d0bed4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:13:20 -0500 Subject: [PATCH 26/77] Spacing --- solidity.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a6620986..7de92fce 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -463,6 +463,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing under active development // Cannot currently be done at command line + // 8. OTHER KEYWORDS // A. Throwing @@ -529,6 +530,7 @@ reveal(100, "mySecret"); // F. State machines // see example below for State enum and inState modifier + // *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** @@ -661,6 +663,7 @@ contract CrowdFunder { } // ** END EXAMPLE ** + // 10. OTHER NATIVE FUNCTIONS // Currency units @@ -686,7 +689,8 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -11. LOW LEVEL FUNCTIONS + +// 11. LOW LEVEL FUNCTIONS // call - low level, not often used, does not provide type safety successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); @@ -694,6 +698,7 @@ successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); // provides library functionality someContractAddress.callcode('function_name'); + // 12. STYLE NOTES // Based on Python's PEP8 style guide @@ -703,6 +708,7 @@ someContractAddress.callcode('function_name'); // Can omit curly braces for one line statement (if, for, etc) // else should be placed on own line + // 13. NATSPEC comments - used for documentation, commenting, and external UIs // Contract natspec - always above contract definition /// @title Contract title From 43138aef5cc6a89ec0c02db03cec61ab902acb97 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 16:36:48 -0800 Subject: [PATCH 27/77] fixes in withdraw() and msg --- solidity.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..146d6e83 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -7,7 +7,7 @@ contributors: Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and -computation of smart contracts, without needing centralized or trusted parties. +execution of smart contracts, without needing centralized or trusted parties. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in OOP, each contract contains @@ -52,7 +52,7 @@ contract SimpleBank { // CamelCase // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg provides contract messager's address and amount + // msg provides details about the message that's sent to the contract // msg.sender is contract caller (address of contract creator) owner = msg.sender; } @@ -77,12 +77,12 @@ contract SimpleBank { // CamelCase if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + if (!msg.sender.send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; // to be safe + } } - - return balances[msg.sender]; - } + + return balances[msg.sender]; } /// @notice Get balance @@ -277,7 +277,7 @@ this.someFunction(); // calls func externally via call, not via internal jump // ** msg - Current message received by the contract ** ** msg.sender; // address of sender -msg.value; // amount of gas provided to this contract in wei +msg.value; // amount of ether provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas From 65cba2b1f5405d53e498bfa96a0e407423dd9a4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:53:37 -0500 Subject: [PATCH 28/77] Fixed mapping --- solidity.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..5b632c11 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -219,7 +219,7 @@ function balances(address _account) returns (uint balance) { } // Nested mappings -mapping (address => mapping (address => uint) balances) public custodians; +mapping (address => mapping (address => uint)) public custodians; // To delete delete balances["John"]; From ba3d5a6feb4a340c43b55b75516fed1d78fad9fb Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:58:31 -0500 Subject: [PATCH 29/77] Added Joseph Chow as contributor --- solidity.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2d653bf9..b73ca0e5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -2,7 +2,8 @@ language: Solidity filename: learnSolidity.sol contributors: - - ["Nemil Dalal", "https://www.nemil.com"] + - ["Nemil Dalal", "https://www.nemil.com"] + - ["Joseph Chow", ""] --- Solidity lets you program on [Ethereum](https://www.ethereum.org/), a @@ -81,7 +82,7 @@ contract SimpleBank { // CamelCase balances[msg.sender] += withdrawAmount; // to be safe } } - + return balances[msg.sender]; } From 58ebc87f5f4114c3610633a7cd9c4264647b2448 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:29:19 -0500 Subject: [PATCH 30/77] Minor edits --- solidity.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index b73ca0e5..5946c1f5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -79,7 +79,9 @@ contract SimpleBank { // CamelCase balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + // to be safe, may be sending to contract that + // has overridden 'send' which may then fail + balances[msg.sender] += withdrawAmount; } } @@ -710,7 +712,9 @@ someContractAddress.callcode('function_name'); // else should be placed on own line -// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// 13. NATSPEC COMENTS +// used for documentation, commenting, and external UIs + // Contract natspec - always above contract definition /// @title Contract title /// @author Author name @@ -740,7 +744,6 @@ someContractAddress.callcode('function_name'); ## Information purposefully excluded - Libraries -- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) From bdd8a8b0c87d58332f39facc60d6ab7d576764df Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:31:48 -0500 Subject: [PATCH 31/77] Wording --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 5946c1f5..ebc58491 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -500,8 +500,8 @@ function remove() { // 9. CONTRACT DESIGN NOTES // A. Obfuscation -// Remember all variables are publicly viewable on blockchain, so -// anything that needs privacy needs to be obfuscated (e.g., hashed) +// All variables are publicly viewable on blockchain, so anything +// that should be totally private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit From 24740321f478c25bb1dc651f6c95e11525a16781 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 23:45:58 -0800 Subject: [PATCH 32/77] update links to docs and Gitter --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..911aca92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -729,17 +729,17 @@ someContractAddress.callcode('function_name'); ``` ## Additional resources -- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) -- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Gitter Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) - Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) -- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded From fc528c92ddbdca1d0cb3a5c8f3ad477fbc115ad9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 10:59:01 -0500 Subject: [PATCH 33/77] Cleaned up data types --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..d84b6a68 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -117,12 +117,10 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; - -// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant +// with 'constant', compiler replaces each occurrence with actual value -// Be careful that you don't overflow, and protect against attacks that do // For int and uint, can explicitly set space in steps of 8 up to 256 // e.g., int8, int16, int24 @@ -130,6 +128,8 @@ uint8 b; int64 c; uint248 e; +// Be careful that you don't overflow, and protect against attacks that do + // No random functions built in, use other contracts for randomness // Type casting From 7e4a42d0b8cec4c0e2a6b90ad261c7755afe1136 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 11:10:39 -0500 Subject: [PATCH 34/77] Reorganizing later sections --- solidity.html.markdown | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 8c416be3..6705dde9 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -501,7 +501,7 @@ function remove() { // A. Obfuscation // All variables are publicly viewable on blockchain, so anything -// that should be totally private needs to be obfuscated (e.g., hashed w/secret) +// that is private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit @@ -510,27 +510,28 @@ sha3("some_bid_amount", "some secret"); // commit reveal(100, "mySecret"); // B. Storage optimization -// Writing to blockchain can be expensive, as data stored forever encourages +// Writing to blockchain can be expensive, as data stored forever; encourages // smart ways to use memory (eventually, compilation will be better, but for now // benefits to planning data structures - and storing min amount in blockchain) // Cost can often be high for items like multidimensional arrays // (cost is for storing data - not declaring unfilled variables) -// C. Cannot restrict human or computer from reading contents of +// C. Data access in blockchain +// Cannot restrict human or computer from reading contents of // transaction or transaction's state -// When 'private' specified, indicating that other *contracts* can't read -// the data directly - any other party can still read the data in blockchain +// While 'private' prevents other *contracts* from reading data +// directly - any other party can still read data in blockchain -// D. All data to start of time is stored in blockchain, so +// All data to start of time is stored in blockchain, so // anyone can observe all previous data and changes -// E. Cron -// Contracts must be manually called to handle time-based scheduling; can create -// external code to do, or provide incentives (ether) for others to do for you +// D. Cron Job +// Contracts must be manually called to handle time-based scheduling; can create external +// code to regularly ping, or provide incentives (ether) for others to -// F. State machines +// E. State machines // see example below for State enum and inState modifier @@ -705,6 +706,7 @@ someContractAddress.callcode('function_name'); // 12. STYLE NOTES // Based on Python's PEP8 style guide +// Quick summary: // 4 spaces for indentation // Two lines separate contract declarations (and other top level declarations) // Avoid extraneous spaces in parentheses From d97c7be291b6bc3fb1477c30ac96b5b6cc36b9c4 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 13:05:45 -0500 Subject: [PATCH 35/77] Minor wording changes, typos --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6705dde9..71a44b92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -63,7 +63,7 @@ contract SimpleBank { // CamelCase function deposit() public returns (uint) { balances[msg.sender] += msg.value; // no "this." or "self." required with state variable - // all values initialized to 0 by default + // all values set to data type's initial value by default DepositMade(msg.sender, msg.value); // fire event @@ -289,7 +289,7 @@ tx.origin; // address of sender of the transaction tx.gasprice; // gas price of the transaction // ** block - Information about current block ** -now // current time (approximately), alias for block.timestamp (uses Unix time) +now; // current time (approximately), alias for block.timestamp (uses Unix time) block.number; // current block number block.difficulty; // current block difficulty block.blockhash(1); // returns bytes32, only works for most recent 256 blocks @@ -428,7 +428,7 @@ contract Consumer { // Set feed to new instance of contract function createNewFeed() { - feed = new InfoFeed(); // constructor called + feed = new InfoFeed(); // new instance created; constructor called } function callFeed() { From b41a699099ff3d6d770775dc73ab47466f498454 Mon Sep 17 00:00:00 2001 From: Tomy Date: Thu, 14 Jan 2016 00:01:47 +0900 Subject: [PATCH 36/77] translate until line 100 --- ja-jp/php.html.markdown | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 4448a1f5..0cea2041 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -39,61 +39,62 @@ Hello World Again! * 型と変数について */ -// Variables begin with the $ symbol. -// A valid variable name starts with a letter or underscore, -// followed by any number of letters, numbers, or underscores. +// 変数は"$"マークで始まります +// 有効な変数名にするには、文字またはアンダースコア(_)で始めて, +// その後はどんな数字でも、文字でも、アンダースコアで続けても構いません -// Boolean values are case-insensitive +//ブーリアン値は大文字、小文字問いません $boolean = true; // or TRUE or True $boolean = false; // or FALSE or False -// Integers +// 数値 $int1 = 12; // => 12 $int2 = -12; // => -12 -$int3 = 012; // => 10 (a leading 0 denotes an octal number) -$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +$int3 = 012; // => 10 (先頭の0は8進法を示す) +$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す) -// Floats (aka doubles) +// floats(浮動小数) (別名double) $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Delete variable +// 変数の削除 unset($int1); -// Arithmetic +// 計算式 $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 $product = 2 * 2; // 4 $quotient = 2 / 1; // 2 -// Shorthand arithmetic +// 式の省略 $number = 0; -$number += 1; // Increment $number by 1 -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evaluation) -$number /= $float; // Divide and assign the quotient to $number +$number += 1; // $numberに1加算Increment $number by 1 +echo $number++; // 1 がプリントされる(式の評価の後に加算される) +echo ++$number; // 3 がプリントされる(式の評価の前に加算される) +$number /= $float; // 割り算した結果の商を$numberに割り当てる -// Strings should be enclosed in single quotes; +// 文字列はシングルクォートで囲むのが望ましいです $sgl_quotes = '$String'; // => '$String' -// Avoid using double quotes except to embed other variables +// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' // Special characters are only escaped in double quotes +// 特殊文字はダブルクォートによってのみ、エスケープされます $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; -// Enclose a variable in curly braces if needed +// 必要があれば、変数を波括弧で囲みます $money = "I have $${number} in the bank."; -// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます $nowdoc = <<<'END' Multi line string END; -// Heredocs will do string interpolation +// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。 $heredoc = << Date: Thu, 14 Jan 2016 21:15:25 +0900 Subject: [PATCH 37/77] translate 100 to 150 lines --- ja-jp/php.html.markdown | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 0cea2041..c01e2ba0 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -100,53 +100,54 @@ Multi line $sgl_quotes END; -// String concatenation is done with . +// 文字列の連結は . で行います echo 'This string ' . 'is concatenated'; -// Strings can be passed in as parameters to echo +// 別々のパラメータとしてechoに渡すこともできます echo 'Multiple', 'Parameters', 'Valid'; /******************************** - * Constants + * 定数 */ -// A constant is defined by using define() -// and can never be changed during runtime! +// 定数は define() を使って定義します +// また、実行中は変更することができないので注意が必要です! -// a valid constant name starts with a letter or underscore, -// followed by any number of letters, numbers, or underscores. +// 有効は定数は文字かアンダースコアで始めます +// それ移行のは、どんな数値でも文字列でもアンダースコアでも構いません define("FOO", "something"); +// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます // access to a constant is possible by direct using the choosen name echo 'This outputs '.FOO; /******************************** - * Arrays + * 配列 */ -// All arrays in PHP are associative arrays (hashmaps), +// PHPの配列はすべて連想配列です -// Associative arrays, known as hashmaps in some languages. +// 連想配列は、他の言語ではハッシュ(ハッシュマップ)として知られています -// Works with all PHP versions +// すべてのバージョンのPHPで動作します $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); -// PHP 5.4 introduced a new syntax +// PHP 5.4 から、新しいシンタックスが導入されました $associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; -echo $associative['One']; // prints 1 +echo $associative['One']; // 1とプリントされます -// List literals implicitly assign integer keys +// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" -// Add an element to the end of an array +// 配列の最後に要素を追加する $array[] = 'Four'; -// or +// または、次のようにも書けます array_push($array, 'Five'); -// Remove element from array +// 配列から要素を削除 unset($array[3]); /******************************** From e8c0c436c9aad0f3902a4e0826bf72de49bde12b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 10:17:51 -0500 Subject: [PATCH 38/77] Added observer pattern, per barkthin's feedback --- solidity.html.markdown | 45 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 71a44b92..3a5e8ff5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -506,7 +506,8 @@ function remove() { // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit -// call contract's reveal function showing bid plus secret that hashes to SHA3 +// call contract's reveal function in the future +// showing bid plus secret that hashes to SHA3 reveal(100, "mySecret"); // B. Storage optimization @@ -531,7 +532,45 @@ reveal(100, "mySecret"); // Contracts must be manually called to handle time-based scheduling; can create external // code to regularly ping, or provide incentives (ether) for others to -// E. State machines +// E. Observer Pattern +// An Observer Pattern lets you register as a subscriber and +// register a function which is called by the oracle (note, the oracle pays +// for this action to be run) +// Some similarities to subscription in Pub/sub + +// This is an abstract contract, both client and server classes import +// the client should implement +contract SomeOracleCallback { + function oracleCallback(int _value, uint _time, bytes32 info) external; +} + +contract SomeOracle { + SomeOracleCallback[] callbacks; // array of all subscribers + + // Register subscriber + function addSubscriber(SomeOracleCallback a) { + callbacks.push(a); + } + + function notify(value, time, info) private { + for(uint i = 0;i < callbacks.length; i++) { + // all called subscribers must implement the oracleCallback + callbacks[i].oracleCallback(value, time, info); + } + } + + function doSomething() public { + // Code to do something + + // Notify all subscribers + notify(_value, _time, _info); + } +} + +// Now, your client contract can addSubscriber by importing SampleOracleCallback +// and registering with Sample Oracle + +// F. State machines // see example below for State enum and inState modifier @@ -748,7 +787,7 @@ someContractAddress.callcode('function_name'); - Libraries ## Style -- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy ## Future To Dos - New keywords: protected, inheritable From 810108ee73a6acc882155ec7ff1bc07983ced05e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 14:01:45 -0500 Subject: [PATCH 39/77] Fixed error in name --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3a5e8ff5..a511bbb3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -567,8 +567,8 @@ contract SomeOracle { } } -// Now, your client contract can addSubscriber by importing SampleOracleCallback -// and registering with Sample Oracle +// Now, your client contract can addSubscriber by importing SomeOracleCallback +// and registering with Some Oracle // F. State machines // see example below for State enum and inState modifier From b5bdff8f9eca5385dcd76c42cd19b17e58307584 Mon Sep 17 00:00:00 2001 From: Tomy Date: Sat, 16 Jan 2016 00:07:29 +0900 Subject: [PATCH 40/77] translate to 328 --- ja-jp/php.html.markdown | 85 +++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 41 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index c01e2ba0..22c0561c 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -151,37 +151,39 @@ array_push($array, 'Five'); unset($array[3]); /******************************** - * Output + * 出力 */ echo('Hello World!'); -// Prints Hello World! to stdout. +// 標準出力にHello World! とプリントします +// 標準出力はブラウザーで実行していればWebページに出力されます // Stdout is the web page if running in a browser. -print('Hello World!'); // The same as echo +print('Hello World!'); // echoの結果と同じです +// echo は言語自体の構成要素であり、括弧なしで呼び出せます // echo is actually a language construct, so you can drop the parentheses. echo 'Hello World!'; -print 'Hello World!'; // So is print +print 'Hello World!'; // printも同様です $paragraph = 'paragraph'; -echo 100; // Echo scalar variables directly -echo $paragraph; // or variables +echo 100; // スカラー数値を直接出力します +echo $paragraph; // 変数も使用できます -// If short open tags are configured, or your PHP version is -// 5.4.0 or greater, you can use the short echo syntax +// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが +// 5.4.0 以上であれば、短縮echoシンタックスを使用できます ?>

2 echo $z; // => 2 @@ -189,23 +191,23 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 -// Dumps type and value of variable to stdout -var_dump($z); // prints int(0) +// 変数の型と値を標準出力へダンプします +var_dump($z); // int(0) と出力されます -// Prints variable to stdout in human-readable format +// 人間が読めるフォーマットで変数を標準出力にプリントします print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) /******************************** - * Logic + * ロジック */ $a = 0; $b = '0'; $c = '1'; $d = '1'; -// assert throws a warning if its argument is not true +// assertは引数がfalseの場合、Exceptionを投げます -// These comparisons will always be true, even if the types aren't the same. +//これらの比較は型が違ったとしても、常に真です。 assert($a == $b); // equality assert($c != $a); // inequality assert($c <> $a); // alternative inequality @@ -214,32 +216,33 @@ assert($c > $b); assert($a <= $b); assert($c >= $d); -// The following will only be true if the values match and are the same type. +// 次の比較は値が等しく、かつ同じ型である場合のみ真です assert($c === $d); assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// spaceship operator since PHP 7 +// spaceship演算子はPHP7から使用可能です $a = 100; $b = 1000; -echo $a <=> $a; // 0 since they are equal -echo $a <=> $b; // -1 since $a < $b -echo $b <=> $a; // 1 since $b > $a +echo $a <=> $a; // 等しいので0になります +echo $a <=> $b; // $a < $b なので -1 です +echo $b <=> $a; // $b > $a なので 1 です -// Variables can be converted between types, depending on their usage. +// 変数は使用するコンテキストによって、変換されます $integer = 1; echo $integer + $integer; // => 2 $string = '1'; -echo $string + $string; // => 2 (strings are coerced to integers) +echo $string + $string; // => 2 (文字列は強制的に数値として処理されます) $string = 'one'; echo $string + $string; // => 0 -// Outputs 0 because the + operator cannot cast the string 'one' to a number +// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます +// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます // Type casting can be used to treat a variable as another type $boolean = (boolean) 1; // => true @@ -247,15 +250,15 @@ $boolean = (boolean) 1; // => true $zero = 0; $boolean = (boolean) $zero; // => false -// There are also dedicated functions for casting most types +// 型をキャストするため専用の関数も存在します $integer = 5; $string = strval($integer); -$var = null; // Null value +$var = null; // Null値 /******************************** - * Control Structures + * 制御構造 */ if (true) { @@ -274,15 +277,15 @@ if (false) { print 'Does'; } -// ternary operator +// 参考演算子 print (false ? 'Does not get printed' : 'Does'); -// ternary shortcut operator since PHP 5.3 -// equivalent of "$x ? $x : 'Does'"" +// PHP 5.3から、三項演算子の短縮形が使用できます +// $x ? $x : 'Does'と同義です $x = false; print($x ?: 'Does'); -// null coalesce operator since php 7 +// null合体演算子はPHP 7から使用できます $a = null; $b = 'Does print'; echo $a ?? 'a is not set'; // prints 'a is not set' @@ -300,29 +303,29 @@ if ($x === '0') { -// This alternative syntax is useful for templates: +// :を用いる別の構文はテンプレートで有用です ?> -This is displayed if the test is truthy. +この部分はifが真のとき表示されます -This is displayed otherwise. +それ以外の場合は、この部分が表示されます Date: Sun, 17 Jan 2016 13:04:25 +0900 Subject: [PATCH 41/77] translate to 487 --- ja-jp/php.html.markdown | 64 +++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 22c0561c..96d45f08 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -328,7 +328,7 @@ switch ($x) { //デフォルトで何かを実行します } -// While, do...while and for loops are probably familiar +// while, do, forの構文は、おそらく他の言語とも共通なものです $i = 0; while ($i < 5) { echo $i++; @@ -351,14 +351,14 @@ echo "\n"; $wheels = ['bicycle' => 2, 'car' => 4]; -// Foreach loops can iterate over arrays +//Foreachループによって、 配列を反復処理できます foreach ($wheels as $wheel_count) { echo $wheel_count; } // Prints "24" echo "\n"; -// You can iterate over the keys as well as the values +// 値と同じ様に、keyも反復処理できます foreach ($wheels as $vehicle => $wheel_count) { echo "A $vehicle has $wheel_count wheels"; } @@ -382,20 +382,20 @@ for ($i = 0; $i < 5; $i++) { /******************************** - * Functions + * 関数 */ -// Define a function with "function": +// 関数を"function"で定義します function my_function () { return 'Hello'; } echo my_function(); // => "Hello" -// A valid function name starts with a letter or underscore, followed by any -// number of letters, numbers, or underscores. +// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は +// どれだけ長い文字、数値、アンダースコアを続けても構いません -function add ($x, $y = 1) { // $y is optional and defaults to 1 +function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です $result = $x + $y; return $result; } @@ -403,10 +403,10 @@ function add ($x, $y = 1) { // $y is optional and defaults to 1 echo add(4); // => 5 echo add(4, 2); // => 6 -// $result is not accessible outside the function -// print $result; // Gives a warning. +// $result には、関数の外からアクセス出来ません +// print $result; // エラーになります -// Since PHP 5.3 you can declare anonymous functions; +// PHP 5.3 から、無名関数が使えます $inc = function ($x) { return $x + 1; }; @@ -417,9 +417,9 @@ function foo ($x, $y, $z) { echo "$x - $y - $z"; } -// Functions can return functions +// 関数は、関数を返すことができます function bar ($x, $y) { - // Use 'use' to bring in outside variables + // 関数外の変数を利用したいときは、'use'を使います return function ($z) use ($x, $y) { foo($x, $y, $z); }; @@ -428,14 +428,15 @@ function bar ($x, $y) { $bar = bar('A', 'B'); $bar('C'); // Prints "A - B - C" -// You can call named functions using strings +// 文字列を使って、定義済みの関数を呼び出すことができます $function_name = 'add'; echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. -// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + +// プログラミング中に、動的に動かす関数を決める場合に便利です。 +// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます -// You can get the all the parameters passed to a function +// 特に指定しなくても、渡された引数を受け取ることもできます function parameters() { $numargs = func_num_args(); if ($numargs > 0) { @@ -450,38 +451,39 @@ function parameters() { parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | /******************************** - * Includes + * ファイルの読み込み */ Date: Sun, 17 Jan 2016 16:18:48 +0900 Subject: [PATCH 42/77] translate all --- ja-jp/php.html.markdown | 118 +++++++++++++++++++++------------------- 1 file changed, 61 insertions(+), 57 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 96d45f08..a5b48120 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -487,51 +487,52 @@ $value = include 'my-include.php'; /* */ /******************************** - * Classes + * クラス */ -// Classes are defined with the class keyword +// クラスはclassキーワードで定義します class MyClass { - const MY_CONST = 'value'; // A constant + const MY_CONST = 'value'; // クラス定数です static $staticVar = 'static'; - // Static variables and their visibility + // スタティック変数とアクセス制限 public static $publicStaticVar = 'publicStatic'; - // Accessible within the class only + // クラス内でのみアクセス可能 private static $privateStaticVar = 'privateStatic'; - // Accessible from the class and subclasses + // そのクラスと子クラスで参照可能 protected static $protectedStaticVar = 'protectedStatic'; - // Properties must declare their visibility + // プロパティはアクセス制限を宣言する必要があります public $property = 'public'; public $instanceProp; - protected $prot = 'protected'; // Accessible from the class and subclasses - private $priv = 'private'; // Accessible within the class only + protected $prot = 'protected'; // そのクラスと子クラスで参照可能 + private $priv = 'private'; // クラス内でのみアクセス可能 - // Create a constructor with __construct + // __constructでコンストラクターを生成します public function __construct($instanceProp) { - // Access instance variables with $this + // $thisでインスタンス変数にアクセスします $this->instanceProp = $instanceProp; } - // Methods are declared as functions inside a class + // メソッドはクラス内で関数として定義されます public function myMethod() { print 'MyClass'; } - //final keyword would make a function unoverridable + // finalキーワードは関数の上書きを禁止します final function youCannotOverrideMe() { } /* - * Declaring class properties or methods as static makes them accessible without - * needing an instantiation of the class. A property declared as static can not - * be accessed with an instantiated class object (though a static method can). + * クラスプロパティまたはメソッドをstaticとして作成すれば、 + * クラスをインスタンス化(newすること)しなくてもアクセスできます。 + * プロパティをstaticとして定義すると、 + * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。 */ public static function myStaticMethod() @@ -540,23 +541,23 @@ class MyClass } } -// Class constants can always be accessed statically +// クラス定数は、いつでも静的にアクセスできます。 echo MyClass::MY_CONST; // Outputs 'value'; echo MyClass::$staticVar; // Outputs 'static'; MyClass::myStaticMethod(); // Outputs 'I am static'; -// Instantiate classes using new +// クラスをインスタンス化するには、newを使います。 $my_class = new MyClass('An instance property'); -// The parentheses are optional if not passing in an argument. +// 括弧はもし引数を渡す必要がなければ省略可能です。 -// Access class members using -> +// ->を使ってクラスのメンバにアクセスします。 echo $my_class->property; // => "public" echo $my_class->instanceProp; // => "An instance property" $my_class->myMethod(); // => "MyClass" -// Extend classes using "extends" +// extendsを使用してクラスを継承します。 class MyOtherClass extends MyClass { function printProtectedProperty() @@ -564,7 +565,7 @@ class MyOtherClass extends MyClass echo $this->prot; } - // Override a method + // メソッドを上書きします。 function myMethod() { parent::myMethod(); @@ -580,7 +581,7 @@ final class YouCannotExtendMe { } -// You can use "magic methods" to create getters and setters +// 「マジックメソッド」を使ってゲッターとセッターを生成できます。 class MyMapClass { private $property; @@ -597,12 +598,12 @@ class MyMapClass } $x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +echo $x->property; // __get() メソッドを使用します +$x->property = 'Something'; // __set() メソッドを使用します -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、 +// インターフェースを実装することもできます(implementsキーワードを使用します)。 +// インターフェースはinterfaceキーワードで定義します。 interface InterfaceOne { @@ -614,7 +615,7 @@ interface InterfaceTwo public function doSomethingElse(); } -// interfaces can be extended +// インターフェースは継承することができます interface InterfaceThree extends InterfaceTwo { public function doAnotherContract(); @@ -639,7 +640,7 @@ class MyConcreteClass extends MyAbstractClass implements InterfaceTwo } -// Classes can implement more than one interface +// クラスは1つ以上のインターフェースを実装できます。 class SomeOtherClass implements InterfaceOne, InterfaceTwo { public function doSomething() @@ -655,10 +656,10 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo /******************************** - * Traits + * トレイト */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。 trait MyTrait { @@ -678,39 +679,40 @@ $cls->myTraitMethod(); // Prints "I have MyTrait" /******************************** - * Namespaces + * 名前空間 */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、 +// 独立しています。 +// そのケースには当てはまらないふりをして続けましょう。 Date: Sun, 17 Jan 2016 16:21:04 +0900 Subject: [PATCH 43/77] fix typo --- ja-jp/php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index a5b48120..b07dfb2f 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -277,7 +277,7 @@ if (false) { print 'Does'; } -// 参考演算子 +// 三項演算子 print (false ? 'Does not get printed' : 'Does'); // PHP 5.3から、三項演算子の短縮形が使用できます From e91cb98abedd979f67acdc08dd7cb81b75f317cc Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 19:38:14 +0100 Subject: [PATCH 44/77] Translated Wolfram tutorial to french --- fr-fr/wolfram-fr.html.markdown | 166 +++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 fr-fr/wolfram-fr.html.markdown diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown new file mode 100644 index 00000000..d297bd74 --- /dev/null +++ b/fr-fr/wolfram-fr.html.markdown @@ -0,0 +1,166 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] + - ["altaris", "http://github.com/altaris/"] +filename: learnwolfram.nb +--- + +Le langage Wolfram est utilisé dans les programmes suivants : +* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas +gérer des éléments graphiques. +* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques : +appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule +contenant le résultat. +* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage +Wolfram. + +Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le +copier-coller directement dans Mathematica peut causer des problèmes de +formatage, car il ne contient aucune information de mise en page. + +``` +(* Ceci est un commentaire *) + +(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des + cellules de texte et insérer de jolies images *) + +(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le + résultat *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Appels de fonction *) +(* Le langage Wolfram est sensible à la casse *) +Sin[Pi/2] (* 1 *) + +(* Syntaxe alternative pour les appels de fonction à 1 paramètre *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de + fonction *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Utiliser une variable pour la première fois la déclare globalement *) +x = 5 (* 5 *) +x == 5 (* True, l'assignation et le test d'égalité est écrit comme + dans le C *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) +x (* 20 *) + +(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des + variables non déclarées n'est pas illégal *) +cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation + s'arrête là *) +cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) +% (* 15 + cow, % représente le dernier résultat *) +% - cow (* 15, les variables non déclarées peuvent quand même + s'annuler *) +moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) + +(* Déclaration d'une fonction *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) + +(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +MyFirst[] (* Hello World *) + +(* Boucles For à la C *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) +myHash[["Green"]] (* 2, l'utilise *) +myHash[["Green"]] := 5 (* 5, la modifie *) +myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* Pour finir, toute bonne démonstration du langage Wolfram contient un + Manipulate ! *) +Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui + affiche y^2, permettant à l'utilisateur de + modifier la valeur de y grâce à un contrôle + allant de 0 à 20. Ne fonctionne que si le + logiciel utilisé gère les éléments graphique. *) +``` + +## Envie d'aller plus loin ? + +* [Documentation du langage Wolfram (en anglais)] +(http://reference.wolfram.com/language/) \ No newline at end of file From c70f53aabea745d4450aa51abdc33aa1ac51bdd2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:53:21 +0100 Subject: [PATCH 45/77] Translated make tutorial to french --- fr-fr/make-fr.html.markdown | 266 ++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 fr-fr/make-fr.html.markdown diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown new file mode 100644 index 00000000..8643ba45 --- /dev/null +++ b/fr-fr/make-fr.html.markdown @@ -0,0 +1,266 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] +filename: Makefile +--- + +Un makefile est un fichier qui définit un ensemble de règles liées entre elles +pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail +possible afin de mettre à jour la ou les cibles en fonction des dépendances. + +Écrit en un week-end par Stuart Feldman en 1976, le make et les +makefiles sont encore très utilisés (principalement dans les systèmes Unix), +malgré la concurrence et les critiques faites à son égard. + +Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons +l'implémentation standard : GNU make. + +```make + +# Ceci est un commentaire. + +# Un makefile devrait être nommé "Makefile" (avec ou sans la +# majuscule). Il peut alors être exécuté par `make `. +# Ce nommage n'est toutefois pas obligatoire : utiliser +# `make -f "fichier" `. + +# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des +# tabulations, pas avec des espaces ! + +#----------------------------------------------------------------------- +# Les basiques +#----------------------------------------------------------------------- + +# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. +file0.txt: + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. + +# Cette règle ne sera exécutée que si fichier0.txt est plus récent que +# fichier1.txt. +file1.txt: fichier0.txt + cat fichier0.txt > fichier1.txt + # Utiliser les même guillemets que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à être exécutée si cette + # commande échoue. + +# Un règle peut avoir plusieurs cibles et plusieurs dépendances. +file2.txt fichier3.txt: fichier0.txt fichier1.txt + touch fichier2.txt + touch fichier3.txt + +# Make affichera un avertissement si le makefile comporte plusieurs règles pour +# une même cible. Cependant les règles vides ne comptent pas, et peuvent être +# utilisées pour ajouter des dépendances plus facilement. + +#----------------------------------------------------------------------- +# Fausses règles +#----------------------------------------------------------------------- + +# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à +# chaque demande. +all: maker process + +# La déclaration des règles peut être faite dans n'importe quel ordre. +maker: + touch ex0.txt ex1.txt + +# On peut transformer une règle en fausse règle grâce à la cible spéciale +# suivante : +.PHONY: all maker process + +# Un règle dépendante d'une fausse règle sera toujours exécutée. +ex0.txt ex1.txt: maker + +# Voici quelques exemples fréquents de fausses règles : all, make, clean, +# install... + +#----------------------------------------------------------------------- +# Variables automatiques et wildcards +#----------------------------------------------------------------------- + +# Utilise un wildcard pour des noms de fichier +process: fichier*.txt + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. + +# Même si la définition de la règle est scindée en plusieurs morceaux, $^ +# listera toutes les dépendances indiquées. +process: ex1.txt fichier0.txt +# Ici, fichier0.txt est un duplicata dans $+. + +#----------------------------------------------------------------------- +# Pattern matching +#----------------------------------------------------------------------- + +# En utilisant le pattern matching, on peut par exemple créer des règles pour +# convertir les fichiers d'un certain format dans un autre. +%.png: %.svg + inkscape --export-png $^ + +# Make exécute une règle même si le fichier correspondant est situé dans un sous +# dossier. En cas de conflit, la règle avec la meilleure correspondance est +# choisie. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Dans ce type de conflit (même cible, même dépendances), make exécutera la +# dernière règle déclarée... +%.png: %.svg + @echo cette règle est choisie + +# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make +# exécutera la première règle pouvant être exécutée. +%.png: %.ps + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + +# Make a des règles pré établies. Par exemple, il sait comment créer la cible +# *.o à partir de *.c. + +# Les makefiles plus vieux utilisent un matching par extension de fichier. +.png.ps: + @echo cette règle est similaire à une règle par pattern matching + +# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par +# extension de fichier. +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables, ou macros +#----------------------------------------------------------------------- + +# Les variables sont des chaînes de caractères. + +variable = Ted +variable2="Sarah" + +echo: + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + +# Les variables sont déclarées de 4 manières, de la plus grande priorité à la +# plus faible : +# 1 : dans la ligne de commande qui invoque make, +# 2 : dans le makefile, +# 3 : dans les variables d’environnement du terminal qui invoque make, +# 4 : les variables prédéfinies. + +# Assigne la variable si une variable d’environnement du même nom n'existe pas +# déjà. +variable4 ?= Jean + +# Empêche cette variable d'être modifiée par la ligne de commande. +override variable5 = David + +# Concatène à une variable (avec un espace avant). +variable4 +=gris + +# Assignations de variable pour les règles correspondant à un pattern +# (spécifique à GNU make). +*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous + # leurs descendants, la variable variable2 vaudra + # "Sara". +# Si le jeux des dépendances et descendances devient vraiment trop compliqué, +# des inconsistances peuvent survenir. + +# Certaines variables sont prédéfinies par make : +affiche_predefinies: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables : le retour +#----------------------------------------------------------------------- + +# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en +# calculs. Pour parer à ce problème, il existe dans GNU make une seconde +# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule +# fois seulement. + +var := wesh +var2 ::= $(var) mec # := et ::= sont équivalents. + +# Ces variables sont évaluées procéduralement (i.e. dans leur ordre +# d'apparition), contrairement au règles par exemple ! + +# Ceci ne fonctionne pas. +var3 ::= $(var4) et fais de beaux rêves +var4 ::= bonne nuit + +#----------------------------------------------------------------------- +# Fonctions +#----------------------------------------------------------------------- + +# Make a une multitude de fonctions. La syntaxe générale est +# $(fonction arg0,arg1,arg2...). + +# Quelques exemples : + +fichiers_source = $(wildcard *.c */*.c) +fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) + +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Inclut d'autres makefiles. +include meuh.mk + +# Branchements conditionnels. +sport = tennis +report: +ifeq ($(sport),tennis) # Il y a aussi ifneq. + @echo 'jeu, set et match' +else + @echo "C'est pas ici Wimbledon ?" +endif + +truc = true +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' +endif +``` + +## Quelques références + +### En français + ++ [Introduction à Makefile (developpez.com)] +(http://gl.developpez.com/tutoriel/outil/makefile/), ++ [Compilez sous GNU/Linux ! (openclassrooms)] +(https://openclassrooms.com/courses/compilez-sous-gnu-linux). + +### En anglais + ++ [Documentation de GNU make](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). \ No newline at end of file From 5c4eba5ef34593a0c6425da64f6a0d7688fca3d2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:54:51 +0100 Subject: [PATCH 46/77] Removed tabs in header --- fr-fr/make-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 8643ba45..405c47cd 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,8 +1,8 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["altaris", "https://github.com/altaris"] + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] filename: Makefile --- From a4e4b76afdb538fa577db8823bb7349ff7872722 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:07:20 +0100 Subject: [PATCH 47/77] Corrections to make-fr ... according to pull request comments: - completed header; - some typos; - finished translating target names. --- fr-fr/make-fr.html.markdown | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 405c47cd..b8255ce7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -3,7 +3,8 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] - ["altaris", "https://github.com/altaris"] -filename: Makefile +filename: Makefile-fr +lang: fr-fr --- Un makefile est un fichier qui définit un ensemble de règles liées entre elles @@ -34,23 +35,23 @@ l'implémentation standard : GNU make. #----------------------------------------------------------------------- # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. -file0.txt: +fichier0.txt: echo "truc" > fichier0.txt # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. -file1.txt: fichier0.txt +fichier1.txt: fichier0.txt cat fichier0.txt > fichier1.txt - # Utiliser les même guillemets que dans un terminal. + # Utiliser la même syntaxe que dans un terminal. @cat fichier0.txt >> fichier1.txt # @ empêche l'affichage de la sortie texte d'une commande. -@echo 'hello' - # - signifie que la règle devrait continuer à être exécutée si cette - # commande échoue. + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. -# Un règle peut avoir plusieurs cibles et plusieurs dépendances. -file2.txt fichier3.txt: fichier0.txt fichier1.txt +# Une règle peut avoir plusieurs cibles et plusieurs dépendances. +fichier2.txt fichier3.txt: fichier0.txt fichier1.txt touch fichier2.txt touch fichier3.txt @@ -62,7 +63,7 @@ file2.txt fichier3.txt: fichier0.txt fichier1.txt # Fausses règles #----------------------------------------------------------------------- -# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Une fausse règle est une règle qui ne correspond pas à un fichier. # Par définition, elle ne peut pas être à jour, et donc make l’exécutera à # chaque demande. all: maker process @@ -75,7 +76,7 @@ maker: # suivante : .PHONY: all maker process -# Un règle dépendante d'une fausse règle sera toujours exécutée. +# Une règle dépendante d'une fausse règle sera toujours exécutée. ex0.txt ex1.txt: maker # Voici quelques exemples fréquents de fausses règles : all, make, clean, From 8cff05396eeb7059904c52c3c2e62440d6c975b6 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:16:37 +0100 Subject: [PATCH 48/77] Corrected header Added myself as translator. --- fr-fr/make-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b8255ce7..993eccba 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] +translators: - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr @@ -264,4 +265,4 @@ endif + [Documentation de GNU make](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). \ No newline at end of file +[ex28](http://c.learncodethehardway.org/book/ex28.html). From db99c9966ce21789dfa4d6618998ea288756d0ae Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:17:50 +0100 Subject: [PATCH 49/77] Corrected header - Added muself as translator; - set lang field; - corrected filename field. --- fr-fr/wolfram-fr.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index d297bd74..3a69e1d8 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -2,8 +2,10 @@ language: wolfram contributors: - ["hyphz", "http://github.com/hyphz/"] +translators: - ["altaris", "http://github.com/altaris/"] -filename: learnwolfram.nb +filename: learnwolfram-fr.nb +lang: fr-fr --- Le langage Wolfram est utilisé dans les programmes suivants : @@ -163,4 +165,4 @@ Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui ## Envie d'aller plus loin ? * [Documentation du langage Wolfram (en anglais)] -(http://reference.wolfram.com/language/) \ No newline at end of file +(http://reference.wolfram.com/language/) From ee88bcd13cf4b89843dde2cf530b832d314d1da7 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Tue, 19 Jan 2016 11:07:22 +0800 Subject: [PATCH 50/77] [xml/id-id] update changes --- id-id/xml-id.html.markdown | 79 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index 8b8d72ae..fedba711 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -5,19 +5,76 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin. Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. -* Sintaks XML +Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu. + +## Definisi dan Pendahuluan + +Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML. + +Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp). ```xml - + + + + + + +Konten + + + + + + + + + + + + + + + + + + + + + + + Teks + + + + + + + Teks + + +Teks +``` + + +## Dokumen XML + +```xml + Everyday Italian @@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, ``` -* Dokumen yang well-formated & Validasi +## Dokumen yang well-formated & Validasi Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, @@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. ``` +## Kompatibilitas DTD dan Definisi Skema XML + +Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML. + +## Sumber + +* [Validasi dokumen XML](http://www.xmlvalidation.com) + +## Bacaan lainnya + +* [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) From 0fe63187a9d61a0daa789ff59fc130b5dc678a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric?= Date: Tue, 19 Jan 2016 11:53:13 +0100 Subject: [PATCH 51/77] Corrected typos in wolfram-fr --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 3a69e1d8..b9fe986f 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -110,7 +110,7 @@ BetterPrintTo[x_] := Module[{y}, (For[y=0, y Date: Tue, 19 Jan 2016 12:36:33 +0100 Subject: [PATCH 52/77] More typos --- fr-fr/make-fr.html.markdown | 110 ++++++++++++++++++------------------ 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 993eccba..b404e1a1 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,33 +113,33 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching -# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par -# extension de fichier. +# Utiliser cette règle spéciale pour déclarer une règle comme ayant un +# matching par extension de fichier. .SUFFIXES: .png #----------------------------------------------------------------------- @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, -# des inconsistances peuvent survenir. +# des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -202,11 +202,11 @@ affiche_predefinies: # manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule # fois seulement. -var := wesh -var2 ::= $(var) mec # := et ::= sont équivalents. +var := A B C +var2 ::= $(var) D E F # := et ::= sont équivalents. # Ces variables sont évaluées procéduralement (i.e. dans leur ordre -# d'apparition), contrairement au règles par exemple ! +# d'apparition), contrairement aux règles par exemple ! # Ceci ne fonctionne pas. var3 ::= $(var4) et fais de beaux rêves @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true -ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' endif ``` From 43c93e3449c2b82bf71529a901034b38077cbcc1 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Tue, 19 Jan 2016 12:38:39 +0100 Subject: [PATCH 53/77] Changed indentation to tabs They were converted to spaces by error in previous commit. oups. --- fr-fr/make-fr.html.markdown | 100 ++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b404e1a1..5a1e03e7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,9 +1,9 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] + - ["Robert Steed", "https://github.com/robochat"] translators: - - ["altaris", "https://github.com/altaris"] + - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr --- @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,30 +113,30 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching # Utiliser cette règle spéciale pour déclarer une règle comme ayant un # matching par extension de fichier. @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, # des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' + machin = 'salut' endif ``` From e3346920d211f19ac651fc6c1618db35f81067ff Mon Sep 17 00:00:00 2001 From: krikmo <616c6c@gmail.com> Date: Tue, 19 Jan 2016 20:54:37 -0200 Subject: [PATCH 54/77] [javascript pt-br]: Use articles translated to portuguese --- pt-br/javascript-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 6424214e..59c6890e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -519,13 +519,13 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir ## Leitura Adicional O [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma excelente documentação sobre Javascript e seu uso nos browsers. E mais, é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando os outros compartilhando do seu conhecimento. [Uma re-introdução do JavaScript pela MDN] -(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala somente sobre a linguagem JavaScript em si; se você quiser aprender mais sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre @@ -542,5 +542,5 @@ profundo de todas as partes do JavaScript. / livro de referência. Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está -nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) da Mozilla Developer Network. From f39e2fcab76fa0d111195c3b4660b87a101f2032 Mon Sep 17 00:00:00 2001 From: qinhanlei Date: Thu, 21 Jan 2016 16:55:20 +0800 Subject: [PATCH 55/77] synchronized with EN version. --- zh-cn/lua-cn.html.markdown | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index fc0375f5..a0acce05 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -91,10 +91,10 @@ until num == 0 -- 2. 函数。 ---------------------------------------------------- -function fib(n) - if n < 2 then return 1 end - return fib(n - 2) + fib(n - 1) -end +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end -- 支持闭包及匿名函数: function adder(x) @@ -129,9 +129,11 @@ function f(x) return x * x end f = function (x) return x * x end -- 这些也是等价的: -local function g(x) return math.sin(x) end -local g; g = function (x) return math.sin(x) end --- 'local g'使得g可以自引用。 +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 以上均因'local g',使得g可以自引用。 +local g = function(x) return math.sin(x) end +-- 等价于 local function g(x)..., 但函数体中g不可自引用 -- 顺便提下,三角函数以弧度为单位。 @@ -328,7 +330,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 如果有必要,子类也可以有new(),与基类相似: function LoudDog:new() - newObj = {} + local newObj = {} -- 初始化newObj self.__index = self return setmetatable(newObj, self) @@ -340,7 +342,9 @@ end --[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 +``` +```lua -- 假设文件mod.lua的内容类似这样: local M = {} @@ -411,4 +415,9 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * io library * os library +顺便说一下,整个文件是可运行的Lua; +保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! + +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. + 使用Lua,欢乐常在! From 4d1b90826f7625fc5fb438b3581866e2d33f7e99 Mon Sep 17 00:00:00 2001 From: Hanlei Qin Date: Fri, 22 Jan 2016 11:01:28 +0800 Subject: [PATCH 56/77] Update lua-cn.html.markdown change link to Markdown style. --- zh-cn/lua-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index a0acce05..f7065445 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -418,6 +418,6 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us 顺便说一下,整个文件是可运行的Lua; 保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! -本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. 使用Lua,欢乐常在! From a3e68ea324716f1f018888782b357812be3865a2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:31:17 +0100 Subject: [PATCH 57/77] Transleted code variables and strings to french --- fr-fr/wolfram-fr.html.markdown | 116 ++++++++++++++++----------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index b9fe986f..ea07aae5 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -57,101 +57,101 @@ x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des variables non déclarées n'est pas illégal *) -cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation +truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) -cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) -% (* 15 + cow, % représente le dernier résultat *) -% - cow (* 15, les variables non déclarées peuvent quand même +truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) +% (* 15 + truc, % représente le dernier résultat *) +% - truc (* 15, les variables non déclarées peuvent quand même s'annuler *) -moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) +chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *) (* Déclaration d'une fonction *) -Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme - à droite *) -Double[10] (* 20 *) -Double[Sin[Pi/2]] (* 2 *) -Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets - fermants si moches *) -(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans - l'ordre d'appel *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) (* Pour la programmation impérative, utiliser ; pour séparer les expressions *) -MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires - car ; est prioritaire sur := *) -MyFirst[] (* Hello World *) +Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +Salut[] (* Hello World *) (* Boucles For à la C *) -PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) -myHash[["Green"]] (* 2, l'utilise *) -myHash[["Green"]] := 5 (* 5, la modifie *) -myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) -KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) -Keys[myHash] (* {Red} *) -Values[myHash] (* {1} *) +table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *) +table[["Vert"]] (* 2, l'utilise *) +table[["Vert"]] := 5 (* 5, la modifie *) +table[["Bleu"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) +Keys[table] (* {Rouge} *) +Values[table] (* {1} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) From 3ea060e936b4260ab57abfee6de9dabc3232d6fd Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:32:02 +0100 Subject: [PATCH 58/77] Corrected code results in comments In subsection on hash tables. --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index ea07aae5..9cdbabcc 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -150,8 +150,8 @@ table[["Vert"]] (* 2, l'utilise *) table[["Vert"]] := 5 (* 5, la modifie *) table[["Bleu"]] := 3.5 (* 3.5, l'étend *) KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) -Keys[table] (* {Rouge} *) -Values[table] (* {1} *) +Keys[table] (* {Rouge, Bleu} *) +Values[table] (* {1, 3.5} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) From 2b3d1e524d483e647fd6a193d6b17808d67af5ab Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:37:15 +0100 Subject: [PATCH 59/77] Some improvments in comments --- fr-fr/wolfram-fr.html.markdown | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 9cdbabcc..7b446259 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -33,22 +33,21 @@ formatage, car il ne contient aucune information de mise en page. 5+8 (* 13 *) (* Appels de fonction *) -(* Le langage Wolfram est sensible à la casse *) Sin[Pi/2] (* 1 *) - (* Syntaxe alternative pour les appels de fonction à 1 paramètre *) Sin@(Pi/2) (* 1 *) (Pi/2) // Sin (* 1 *) -(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de - fonction *) +(* Attention : le langage est sensible à la casse ! *) + +(* Toutes les expressions sont en réalité des appels de fonction *) Times[2, 2] (* 4 *) Plus[5, 8] (* 13 *) (* Utiliser une variable pour la première fois la déclare globalement *) x = 5 (* 5 *) x == 5 (* True, l'assignation et le test d'égalité est écrit comme - dans le C *) + en C *) x (* 5 *) x = x + 5 (* 10 *) x (* 10 *) @@ -56,7 +55,7 @@ Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des - variables non déclarées n'est pas illégal *) + variables non déclarées est légal *) truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) @@ -75,18 +74,18 @@ Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets (Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans l'ordre d'appel *) -(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +(* En programmation impérative, utiliser ; pour séparer les expressions *) Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires car ; est prioritaire sur := *) Salut[] (* Hello World *) (* Boucles For à la C *) Compter[x_] := For[y=0, y Date: Mon, 25 Jan 2016 18:34:25 -0500 Subject: [PATCH 60/77] removed merge stuff --- python.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 70f7f73f..2e7fd8be 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -726,11 +726,8 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -<<<<<<< HEAD * [LearnPython](http://www.learnpython.org/) -======= * [Fullstack Python](https://www.fullstackpython.com/) ->>>>>>> adambard/master ### Dead Tree From 82cb669cd77e0b394be0161ea8c688aa78f955d6 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:44:47 +1100 Subject: [PATCH 61/77] Fix typo --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 3eed2d3c..24dd788a 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -285,7 +285,7 @@ hash.each do |key, value| puts "#{key} is #{value}" end -# If you still need and index you can use "each_with_index" and define an index +# If you still need an index you can use "each_with_index" and define an index # variable array.each_with_index do |element, index| puts "#{element} is number #{index} in the array" From 0f5c74a79f328aa1b385a2dae3389d48faa47ce5 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:52:06 +1100 Subject: [PATCH 62/77] Add note on destructuring assignment --- ruby.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 24dd788a..6743de6b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -411,6 +411,15 @@ def guests(*array) array.each { |guest| puts guest } end +# If a method returns an array, you can use destructuring assignment +def foods + ['pancake', 'sandwich', 'quesadilla'] +end +breakfast, lunch, dinner = foods +breakfast # 'pancake' +dinner # 'quesadilla' + + # Define a class with the class keyword class Human From b9c1502cab19360bda496df5a2503a198f7c4f50 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:58:46 +1100 Subject: [PATCH 63/77] Add note on method naming conventions --- ruby.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 6743de6b..bdad4d06 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -419,6 +419,19 @@ breakfast, lunch, dinner = foods breakfast # 'pancake' dinner # 'quesadilla' +# By convention, all methods that return booleans end with a question mark +5.even? # false +5.odd? # true + +# And if a method ends with an exclamation mark, it does something destructive +# like mutate the receiver. Many methods have a ! version to make a change, and +# a non-! version to just return a new changed version +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +company_name.upcase! # we're mutating company_name this time! +company_name #=> "DUNDER MIFFLIN" + # Define a class with the class keyword class Human From 236cc1c14c71e561d9ab715079f6974a86fad271 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:59:08 +1100 Subject: [PATCH 64/77] Fix formatting on comments --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index bdad4d06..adf5ce81 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -416,8 +416,8 @@ def foods ['pancake', 'sandwich', 'quesadilla'] end breakfast, lunch, dinner = foods -breakfast # 'pancake' -dinner # 'quesadilla' +breakfast #=> 'pancake' +dinner #=> 'quesadilla' # By convention, all methods that return booleans end with a question mark 5.even? # false From 92beb9c37ca76d9ff0ea8b8c25cfe191accb6977 Mon Sep 17 00:00:00 2001 From: Tomy Date: Tue, 26 Jan 2016 19:53:14 +0900 Subject: [PATCH 65/77] feedback --- ja-jp/{php.html.markdown => php-jp.html.markdown} | 1 + 1 file changed, 1 insertion(+) rename ja-jp/{php.html.markdown => php-jp.html.markdown} (99%) diff --git a/ja-jp/php.html.markdown b/ja-jp/php-jp.html.markdown similarity index 99% rename from ja-jp/php.html.markdown rename to ja-jp/php-jp.html.markdown index b07dfb2f..2ca17179 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php-jp.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["Kazushige Tominaga", "https://github.com/kazu9su"] filename: learnphp.php +lang: ja-jp --- このドキュメントでは、 PHP 5+ について説明します。 From e48f99593eb4d4c82aba4198ccebceb8a2fb5bd9 Mon Sep 17 00:00:00 2001 From: Tomy Date: Tue, 26 Jan 2016 19:56:15 +0900 Subject: [PATCH 66/77] update filename --- ja-jp/php-jp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja-jp/php-jp.html.markdown b/ja-jp/php-jp.html.markdown index 2ca17179..112916f4 100644 --- a/ja-jp/php-jp.html.markdown +++ b/ja-jp/php-jp.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["Kazushige Tominaga", "https://github.com/kazu9su"] -filename: learnphp.php +filename: learnphp-jp.php lang: ja-jp --- From 32f18cd992b5b6988a3b37eaa533f8215d83fe2e Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 10:38:51 +0530 Subject: [PATCH 67/77] Added Tuple --- c++.html.markdown | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index 44cad665..b8ab656c 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -955,6 +955,54 @@ v.push_back(Foo()); // New value is copied into the first Foo we inserted // explanation of why this works. v.swap(vector()); + +/////////////////////////////////////// +// Tuples (C++11 and above) +/////////////////////////////////////// + +#include + +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// its elements are accessed by their order in the tuple. + +// We start with constructing a tuple. +// +// Packing values into tuple +auto first = make_tuple ( 10 , 'A' ) ; +const int maxN = 1e9; +int maxL = 15; +auto second = make_tuple ( maxN , maxL ) ; + +// printing elements of 'first' tuple +cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A + +// printing elements of 'second' tuple +cout << get<0>(second)<< " " << get<1>(second) << "\n"; // prints: 1000000000 15 + + +// Unpacking tuple into variables + +int first_int; +char first_char; +tie (first_int , first_char ) = first; +cout << first_int << " " << first_char << "\n"; // prints : 10 A + +// We can also create tuple like this. + +tuple third ( 11 ,'A' , 3.14141); +// tuple_size returns number of elements in a tuple (as a constexpr) + +cout << tuple_size< decltype(third)>::value << "\n"; // prints: 3 + +// tuple_cat concatenates the elements of all the tuples in the same order. + +auto concatenated_tuple = tuple_cat( first, second ,third); +// concatenated_tuple becomes = (10 , 'A' , 1e9 , 15 , 11 , 'A' , 3.14141 ) + +cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 +cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 +cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' + ``` Further Reading: From a931cd772de4f5debc2dc379c0e8125ef9338d13 Mon Sep 17 00:00:00 2001 From: can Date: Thu, 28 Jan 2016 16:45:24 +0800 Subject: [PATCH 68/77] Remove junk string `450635425` --- zh-cn/java-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index a8fd2a4c..1e9c38f6 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -302,7 +302,7 @@ class Bicycle { // 构造函数是初始化一个对象的方式 // 以下是一个默认构造函数 - public Bi450635425cycle() { + public Bicycle() { gear = 1; cadence = 50; speed = 5; @@ -328,7 +328,7 @@ class Bicycle { return cadence; } - // void返450635425回值函数没有返回值 + // void返回值函数没有返回值 public void setCadence(int newValue) { cadence = newValue; } From c805148618f5b2679d6581ff41885abc7140fd4d Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 15:26:35 +0530 Subject: [PATCH 69/77] [C++/en] Tuples in C++ --- c++.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index b8ab656c..594cf15f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -966,25 +966,24 @@ v.swap(vector()); // its elements are accessed by their order in the tuple. // We start with constructing a tuple. -// // Packing values into tuple -auto first = make_tuple ( 10 , 'A' ) ; +auto first = make_tuple( 10 , 'A' ) ; const int maxN = 1e9; -int maxL = 15; -auto second = make_tuple ( maxN , maxL ) ; +const int maxL = 15; +auto second = make_tuple( maxN , maxL ) ; // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A // printing elements of 'second' tuple -cout << get<0>(second)<< " " << get<1>(second) << "\n"; // prints: 1000000000 15 +cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables int first_int; char first_char; -tie (first_int , first_char ) = first; +tie(first_int , first_char ) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. @@ -992,7 +991,7 @@ cout << first_int << " " << first_char << "\n"; // prints : 10 A tuple third ( 11 ,'A' , 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) -cout << tuple_size< decltype(third)>::value << "\n"; // prints: 3 +cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. From 4a1a6857ce30f19f8c04dcca4571bb27f7dc36d0 Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 17:15:44 +0530 Subject: [PATCH 70/77] [C++/en] Tuple , updated --- c++.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 594cf15f..ea6ef034 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple( 10 , 'A' ) ; +auto first = make_tuple(10,'A') ; const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple( maxN , maxL ) ; +auto second = make_tuple(maxN,maxL) ; // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -983,12 +983,12 @@ cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 1 int first_int; char first_char; -tie(first_int , first_char ) = first; +tie(first_int,first_char) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. -tuple third ( 11 ,'A' , 3.14141); +tuple third (11,'A',3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 @@ -996,7 +996,7 @@ cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat( first, second ,third); -// concatenated_tuple becomes = (10 , 'A' , 1e9 , 15 , 11 , 'A' , 3.14141 ) +// concatenated_tuple becomes = (10,'A',1e9,15,11,'A',3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 From fa2b171008061bc82cf9b35e0470eebeaecb4a26 Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 18:22:11 +0530 Subject: [PATCH 71/77] [C++/en] Tuple , Updated --- c++.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index ea6ef034..1065b9e8 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple(10,'A') ; +auto first = make_tuple(10,'A'); const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple(maxN,maxL) ; +auto second = make_tuple(maxN,maxL); // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -978,7 +978,6 @@ cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A // printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 - // Unpacking tuple into variables int first_int; From e1016455d5e4472e7a533c8cdd6df8ae4f2e7854 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 28 Jan 2016 14:04:41 +0100 Subject: [PATCH 72/77] #2119 fixups --- c++.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 1065b9e8..82662b15 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple(10,'A'); +auto first = make_tuple(10, 'A'); const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple(maxN,maxL); +auto second = make_tuple(maxN, maxL); // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -982,20 +982,20 @@ cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 1 int first_int; char first_char; -tie(first_int,first_char) = first; +tie(first_int, first_char) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. -tuple third (11,'A',3.14141); +tuple third(11, 'A', 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) -cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 +cout << tuple_size::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. -auto concatenated_tuple = tuple_cat( first, second ,third); -// concatenated_tuple becomes = (10,'A',1e9,15,11,'A',3.14141) +auto concatenated_tuple = tuple_cat(first, second, third); +// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 From 89f24b7c255686723a8e7e89a3c820fc203c0243 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [PATCH 73/77] [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sun, 31 Jan 2016 16:08:28 +0100 Subject: [PATCH 74/77] Update c++.html.markdown v.empty() queries if v is empty while v.clear() actually clears it (or rather sets size to 0). --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 82662b15..a59b4db8 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -948,7 +948,7 @@ for (int i = 0; i < 10; ++i) // Following line sets size of v to 0, but destructors don't get called // and resources aren't released! -v.empty(); +v.clear(); v.push_back(Foo()); // New value is copied into the first Foo we inserted // Truly destroys all values in v. See section about temporary objects for From b7e166dc45edd2d5cc6dd271749cd49ef003b8ae Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [PATCH 75/77] [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [PATCH 76/77] [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [PATCH 77/77] [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen.