diff options
-rw-r--r-- | dart.html.markdown | 412 | ||||
-rw-r--r-- | de-de/d-de.html.markdown | 64 | ||||
-rw-r--r-- | el-gr/python3-gr.html.markdown | 3 | ||||
-rw-r--r-- | es-es/sql-es.html.markdown | 115 | ||||
-rw-r--r-- | go.html.markdown | 13 | ||||
-rw-r--r-- | mips.html.markdown | 99 | ||||
-rw-r--r-- | ru-ru/javascript-ru.html.markdown | 2 | ||||
-rw-r--r-- | rust.html.markdown | 2 |
8 files changed, 485 insertions, 225 deletions
diff --git a/dart.html.markdown b/dart.html.markdown index 7db9bd33..2672dc6a 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -2,28 +2,72 @@ language: dart filename: learndart.dart contributors: - - ["Joao Pedrosa", "https://github.com/jpedrosa/"] + - ["Joao Pedrosa", "https://github.com/jpedrosa/"] + - ["Vince Ramces Oliveros", "https://github.com/ram231"] --- -Dart is a newcomer into the realm of programming languages. -It borrows a lot from other mainstream languages, having as a goal not to deviate too much from -its JavaScript sibling. Like JavaScript, Dart aims for great browser integration. +**Dart** is a single threaded, general puprose programming languages. +It borrows a lot from other mainstream languages. +It supports Streams, Futures(known as Promises in JavaScript), Generics, First-class functions(closures) and static type checking. +Dart can run in any platform such as Web, CLI, Desktop, Mobile and IoT devices. -Dart's most controversial feature must be its Optional Typing. +Dart's most controversial feature is its ~~Optional Typing~~ Static Type safety and [Sound Type checks](https://dart.dev/guides/language/sound-dart). ```dart import "dart:collection"; -import "dart:math" as DM; - -// Welcome to Learn Dart in 15 minutes. http://www.dartlang.org/ -// This is an executable tutorial. You can run it with Dart or on -// the Try Dart! site if you copy/paste it there. http://try.dartlang.org/ - -// Function declaration and method declaration look the same. Function -// declarations can be nested. The declaration takes the form of -// name() {} or name() => singleLineExpression; -// The fat arrow function declaration has an implicit return for the result of -// the expression. +import "dart:math" as math; + +/// Welcome to Learn Dart in 15 minutes. http://dart.dev/ +/// This is an executable tutorial. You can run it with Dart or on +/// the Try Dart! site if you copy/paste it there. http://dartpad.dev/ +/// You can also run Flutter in DartPad by click the `< > New Pad ` and choose Flutter + + +/// In Dart, Everything is an Object. +/// Every declaration of an object is an instance of Null and +/// Null is also an object. + + +/// 3 Types of comments in dart +// Single line comment +/** +* Multi-line comment +* Can comment more than 2 lines +*/ +/// Code doc comment +/// It uses markdown syntax to generate code docs when making an API. +/// Code doc comment is the recommended choice when documenting your APIs, classes and methods. + +/// 4 types of variable declaration. +/// Constants are variables that are immutable cannot be change or altered. +/// `const` in dart should practice SCREAMING_SNAKE_CASE name declaration. +const CONSTANT_VALUE = "I CANNOT CHANGE"; +CONSTANT_VALUE = "DID I?"; //Error +/// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions +/// `final` can be declared in pascalCase. +final finalValue = "value cannot be change once instantiated"; +finalValue = "Seems not"; //Error + +/// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type +var mutableValue = "Variable string"; +mutableValue = "this is valid"; +mutableValue = false; // Error. + +/// `dynamic` is another variable declaration in which the type is not evaluated by the dart static type checking. +/// It can change its value and data type. +/// Some dartisans uses dynamic cautiously as it cannot keep track of its data type. so use it at your own risk +dynamic dynamicValue = "I'm a string"; +dynamicValue = false; // false + + +/// Functions can be declared in a global space +/// Function declaration and method declaration look the same. Function +/// declarations can be nested. The declaration takes the form of +/// name() {} or name() => singleLineExpression; +/// The fat arrow function declaration can be an implicit or +/// explicit return for the result of the expression. +/// Dart will execute a function called `main()` anywhere in the dart project. +/// example1() { nested1() { nested2() => print("Example1 nested 1 nested 2"); @@ -33,23 +77,23 @@ example1() { nested1(); } -// Anonymous functions don't include a name. +/// Anonymous functions don't include a name but can take number of arguments example2() { - nested1(fn) { + //// Explicit return type. + nested1(Function<void> fn) { fn(); } nested1(() => print("Example2 nested 1")); } -// When a function parameter is declared, the declaration can include the -// number of parameters the function takes by specifying the names of the -// parameters it takes. +/// When a function parameter is declared, the declaration can include the +/// number of parameters the function takes by explicitly specifying the names of the +/// parameters it takes. example3() { - planA(fn(informSomething)) { + planA(fn(String informSomething)) { fn("Example3 plan A"); } - planB(fn) { // Or don't declare number of parameters. fn("Example3 plan B"); @@ -59,7 +103,9 @@ example3() { planB((s) => print(s)); } -// Functions have closure access to outer variables. +/// Functions have closure access to outer variables. +/// Dart will infer types when the variable has a value of something. +/// In this example dart knows that this variable is a String. var example4Something = "Example4 nested 1"; example4() { nested1(fn(informSomething)) { @@ -69,8 +115,8 @@ example4() { nested1((s) => print(s)); } -// Class declaration with a sayIt method, which also has closure access -// to the outer variable as though it were a function as seen before. +/// Class declaration with a sayIt method, which also has closure access +/// to the outer variable as though it were a function as seen before. var example5method = "Example5 sayIt"; class Example5Class { @@ -80,14 +126,15 @@ class Example5Class { } example5() { - // Create an anonymous instance of the Example5Class and call the sayIt - // method on it. + /// Create an anonymous instance of the Example5Class and call the sayIt + /// method on it. + /// the `new` keyword is optional in Dart. new Example5Class().sayIt(); } -// Class declaration takes the form of class name { [classBody] }. -// Where classBody can include instance methods and variables, but also -// class methods and variables. +/// Class declaration takes the form of class name { [classBody] }. +/// Where classBody can include instance methods and variables, but also +/// class methods and variables. class Example6Class { var instanceVariable = "Example6 instance variable"; sayIt() { @@ -96,10 +143,10 @@ class Example6Class { } example6() { - new Example6Class().sayIt(); + Example6Class().sayIt(); } -// Class methods and variables are declared with "static" terms. +/// Class methods and variables are declared with "static" terms. class Example7Class { static var classVariable = "Example7 class variable"; static sayItFromClass() { @@ -116,24 +163,68 @@ example7() { new Example7Class().sayItFromInstance(); } -// Literals are great, but there's a restriction for what literals can be -// outside of function/method bodies. Literals on the outer scope of class -// or outside of class have to be constant. Strings and numbers are constant -// by default. But arrays and maps are not. They can be made constant by -// declaring them "const". -var example8Array = const ["Example8 const array"], - example8Map = const {"someKey": "Example8 const map"}; +/// Dart supports Generics. +/// Generics refers to the technique of writing the code for a class +/// without specifying the data type(s) that the class works on. +/// Source: https://stackoverflow.com/questions/4560890/what-are-generics-in-c + +/// Type `T` refers to any type that has been instantiated +/// you can call whatever you want +/// Programmers uses the convention in the following +/// T - Type(used for class and primitype types) +/// E - Element(used for List, Set, or Iterable) +/// K,V - Key Value(used for Map) +class GenericExample<T>{ + void printType(){ + print("$T") + } + // methods can also have generics + genericMethod<M>(){ + print("class:$T, method: $M"); + } +} + + +/// List are similar to arrays but list is a child of Iterable<E> +/// Therefore Maps, List, LinkedList are all child of Iterable<E> to be able to loop using the keyword `for` +/// Important things to remember: +/// () - Iterable<E> +/// [] - List<E> +/// {} - Map<K,V> + + +/// List are great, but there's a restriction for what List can be +/// outside of function/method bodies. List on the outer scope of class +/// or outside of class have to be constant. Strings and numbers are constant +/// by default. But arrays and maps are not. They can be made constant by +/// declaring them "const". Kind of similar to Javascript's Object.freeze() +const example8List = ["Example8 const array"], +const example8Map = {"someKey": "Example8 const map"}; +/// Declare List or Maps as Objects. + List<String> explicitList = new List<String>(); + Map<String,dynamic> explicitMaps = new Map<String,dynamic>(); + + explicitList.add("SomeArray"); example8() { print(example8Array[0]); print(example8Map["someKey"]); + print(explicitList[0]); } -// Loops in Dart take the form of standard for () {} or while () {} loops, -// slightly more modern for (.. in ..) {}, or functional callbacks with many -// supported features, starting with forEach. +/// Assigning a list from one variable to another will not be the same result. +/// Because dart is pass-reference-by-value. +/// So when you assign an existing list to a new variable. +/// Instead of List, it becomes an Iterable +var iterableExplicitList = explicitList; +print(iterableExplicitList) // ("SomeArray"); "[]" becomes "()" +var newExplicitLists = explicitList.toList() // Converts Iterable<E> to List<E> + +/// Loops in Dart take the form of standard for () {} or while () {} loops, +/// slightly more modern for (.. in ..) {}, or functional callbacks with many +/// supported features, starting with forEach,map and where. var example9Array = const ["a", "b"]; example9() { - for (var i = 0; i < example9Array.length; i++) { + for (final i = 0; i < example9Array.length; i++) { print("Example9 for loop '${example9Array[i]}'"); } var i = 0; @@ -141,13 +232,15 @@ example9() { print("Example9 while loop '${example9Array[i]}'"); i++; } - for (var e in example9Array) { + for (final e in example9Array) { print("Example9 for-in loop '${e}'"); } + example9Array.forEach((e) => print("Example9 forEach loop '${e}'")); + } -// To loop over the characters of a string or to extract a substring. +/// To loop over the characters of a string or to extract a substring. var example10String = "ab"; example10() { for (var i = 0; i < example10String.length; i++) { @@ -158,14 +251,37 @@ example10() { } } -// Int and double are the two supported number formats. +/// `int`, `double` and `num` are the three supported number formats. +/// `num` can be either `int` or `double`. +/// `int` and `double` are children of type `num` example11() { var i = 1 + 320, d = 3.2 + 0.01; + num myNumDouble = 2.2; + num myNumInt = 2; + int myInt = 1; + double myDouble = 0; // Dart will add decimal prefix, becomes 0.0; + myNumDouble = myInt; // valid + myNumDouble = myDouble; //valid + myNumDouble = myNumInt; //valid + + myNumInt = myInt; // valid + myNumInt = myDouble; // valid + myNumInt = myNumDouble; // valid + + myInt = myNumDouble; //Error + myInt = myDouble; //Error + myInt = myNumInt; //valid + + myDouble = myInt; //error + myDouble = myNumInt; //valid + myDouble = myNumDouble; //valid + print("Example11 int ${i}"); print("Example11 double ${d}"); + } -// DateTime provides date/time arithmetic. +/// DateTime provides date/time arithmetic. example12() { var now = new DateTime.now(); print("Example12 now '${now}'"); @@ -173,7 +289,7 @@ example12() { print("Example12 tomorrow '${now}'"); } -// Regular expressions are supported. +/// Regular expressions are supported. example13() { var s1 = "some string", s2 = "some", re = new RegExp("^s.+?g\$"); match(s) { @@ -188,7 +304,7 @@ example13() { match(s2); } -// Boolean expressions support implicit conversions and dynamic type +/// Boolean expressions support implicit conversions and dynamic type example14() { var a = true; if (a) { @@ -198,11 +314,11 @@ example14() { if (a) { print("true, a is $a"); } else { - print("false, a is $a"); // runs here + print("false, a is $a"); /// runs here } - // dynamic typed null can be convert to bool - var b; // b is dynamic type + /// dynamic typed null can be convert to bool + var b;/// b is dynamic type b = "abc"; try { if (b) { @@ -211,35 +327,35 @@ example14() { print("false, b is $b"); } } catch (e) { - print("error, b is $b"); // this could be run but got error + print("error, b is $b"); /// this could be run but got error } b = null; if (b) { print("true, b is $b"); } else { - print("false, b is $b"); // runs here + print("false, b is $b"); /// runs here } - // statically typed null can not be convert to bool + /// statically typed null can not be convert to bool var c = "abc"; c = null; - // compile failed - // if (c) { - // print("true, c is $c"); - // } else { - // print("false, c is $c"); - // } + /// complie failed + /// if (c) { + /// print("true, c is $c"); + /// } else { + /// print("false, c is $c"); + /// } } -// try/catch/finally and throw are used for exception handling. -// throw takes any object as parameter; +/// try/catch/finally and throw are used for exception handling. +/// throw takes any object as parameter; example15() { try { try { throw "Some unexpected error."; } catch (e) { print("Example15 an exception: '${e}'"); - throw e; // Re-throw + throw e; /// Re-throw } } catch (e) { print("Example15 catch exception being re-thrown: '${e}'"); @@ -248,8 +364,8 @@ example15() { } } -// To be efficient when creating a long string dynamically, use -// StringBuffer. Or you could join a string array. +/// To be efficient when creating a long string dynamically, use +/// StringBuffer. Or you could join a string array. example16() { var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e; for (e in a) { @@ -260,8 +376,9 @@ example16() { print("Example16 join string array '${a.join()}'"); } -// Strings can be concatenated by just having string literals next to -// one another with no further operator needed. +/// Strings can be concatenated by just having string List next to +/// one another with no further operator needed. + example17() { print("Example17 " "concatenate " @@ -269,44 +386,44 @@ example17() { "just like that"); } -// Strings have single-quote or double-quote for delimiters with no -// actual difference between the two. The given flexibility can be good -// to avoid the need to escape content that matches the delimiter being -// used. For example, double-quotes of HTML attributes if the string -// contains HTML content. +/// Strings have single-quote or double-quote for delimiters with no +/// actual difference between the two. The given flexibility can be good +/// to avoid the need to escape content that matches the delimiter being +/// used. For example, double-quotes of HTML attributes if the string +/// contains HTML content. example18() { print('Example18 <a href="etc">' "Don't can't I'm Etc" '</a>'); } -// Strings with triple single-quotes or triple double-quotes span -// multiple lines and include line delimiters. +/// Strings with triple single-quotes or triple double-quotes span +/// multiple lines and include line delimiters. example19() { print('''Example19 <a href="etc"> Example19 Don't can't I'm Etc Example19 </a>'''); } -// Strings have the nice interpolation feature with the $ character. -// With $ { [expression] }, the return of the expression is interpolated. -// $ followed by a variable name interpolates the content of that variable. -// $ can be escaped like so \$ to just add it to the string instead. +/// Strings have the nice interpolation feature with the $ character. +/// With $ { [expression] }, the return of the expression is interpolated. +/// $ followed by a variable name interpolates the content of that variable. +/// $ can be escaped like so \$ to just add it to the string instead. example20() { var s1 = "'\${s}'", s2 = "'\$s'"; print("Example20 \$ interpolation ${s1} or $s2 works."); } -// Optional types allow for the annotation of APIs and come to the aid of -// IDEs so the IDEs can better refactor, auto-complete and check for -// errors. So far we haven't declared any types and the programs have -// worked just fine. In fact, types are disregarded during runtime. -// Types can even be wrong and the program will still be given the -// benefit of the doubt and be run as though the types didn't matter. -// There's a runtime parameter that checks for type errors which is -// the checked mode, which is said to be useful during development time, -// but which is also slower because of the extra checking and is thus -// avoided during deployment runtime. +/// Optional types allow for the annotation of APIs and come to the aid of +/// IDEs so the IDEs can better refactor, auto-complete and check for +/// errors. So far we haven't declared any types and the programs have +/// worked just fine. In fact, types are disregarded during runtime. +/// Types can even be wrong and the program will still be given the +/// benefit of the doubt and be run as though the types didn't matter. +/// There's a runtime parameter that checks for type errors which is +/// the checked mode, which is said to be useful during development time, +/// but which is also slower because of the extra checking and is thus +/// avoided during deployment runtime. class Example21 { List<String> _names; Example21() { @@ -331,7 +448,7 @@ void example21() { print("Example21 names '${o.names}' and length '${o.length}'"); } -// Class inheritance takes the form of class name extends AnotherClassName {}. +/// Class inheritance takes the form of class name extends AnotherClassName {}. class Example22A { var _name = "Some Name!"; get name => _name; @@ -344,13 +461,13 @@ example22() { print("Example22 class inheritance '${o.name}'"); } -// Class mixin is also available, and takes the form of -// class name extends SomeClass with AnotherClassName {}. -// It's necessary to extend some class to be able to mixin another one. -// The template class of mixin cannot at the moment have a constructor. -// Mixin is mostly used to share methods with distant classes, so the -// single inheritance doesn't get in the way of reusable code. -// Mixins follow the "with" statement during the class declaration. +/// Class mixin is also available, and takes the form of +/// class name extends SomeClass with AnotherClassName {}. +/// It's necessary to extend some class to be able to mixin another one. +/// The template class of mixin cannot at the moment have a constructor. +/// Mixin is mostly used to share methods with distant classes, so the +/// single inheritance doesn't get in the way of reusable code. +/// Mixins follow the "with" statement during the class declaration. class Example23A {} class Example23Utils { @@ -371,10 +488,10 @@ example23() { print("Example23 addTwo(1, 2) results in '${r2}'"); } -// The Class constructor method uses the same name of the class and -// takes the form of SomeClass() : super() {}, where the ": super()" -// part is optional and it's used to delegate constant parameters to the -// super-parent's constructor. +/// The Class constructor method uses the same name of the class and +/// takes the form of SomeClass() : super() {}, where the ": super()" +/// part is optional and it's used to delegate constant parameters to the +/// super-parent's constructor. class Example24A { var _value; Example24A({value: "someValue"}) { @@ -393,9 +510,9 @@ example24() { print("Example24 calling super during constructor '${o2.value}'"); } -// There's a shortcut to set constructor parameters in case of simpler classes. -// Just use the this.parameterName prefix and it will set the parameter on -// an instance variable of same name. +/// There's a shortcut to set constructor parameters in case of simpler classes. +/// Just use the this.parameterName prefix and it will set the parameter on +/// an instance variable of same name. class Example25 { var value, anotherValue; Example25({this.value, this.anotherValue}); @@ -407,9 +524,9 @@ example25() { "'${o.anotherValue}'"); } -// Named parameters are available when declared between {}. -// Parameter order can be optional when declared between {}. -// Parameters can be made optional when declared between []. +/// Named parameters are available when declared between {}. +/// Parameter order can be optional when declared between {}. +/// Parameters can be made optional when declared between []. example26() { var _name, _surname, _email; setConfig1({name, surname}) { @@ -431,13 +548,13 @@ example26() { "email '${_email}'"); } -// Variables declared with final can only be set once. -// In case of classes, final instance variables can be set via constant -// constructor parameter. +/// Variables declared with final can only be set once. +/// In case of classes, final instance variables can be set via constant +/// constructor parameter. class Example27 { final color1, color2; - // A little flexibility to set final instance variables with syntax - // that follows the : + /// A little flexibility to set final instance variables with syntax + /// that follows the : Example27({this.color1, color2}) : color2 = color2; } @@ -447,11 +564,11 @@ example27() { print("Example27 color is '${o.color1}' and '${o.color2}'"); } -// To import a library, use import "libraryPath" or if it's a core library, -// import "dart:libraryName". There's also the "pub" package management with -// its own convention of import "package:packageName". -// See import "dart:collection"; at the top. Imports must come before -// other code declarations. IterableBase comes from dart:collection. +/// To import a library, use import "libraryPath" or if it's a core library, +/// import "dart:libraryName". There's also the "pub" package management with +/// its own convention of import "package:packageName". +/// See import "dart:collection"; at the top. Imports must come before +/// other code declarations. IterableBase comes from dart:collection. class Example28 extends IterableBase { var names; Example28() { @@ -465,11 +582,11 @@ example28() { o.forEach((name) => print("Example28 '${name}'")); } -// For control flow we have: -// * standard switch with must break statements -// * if-else if-else and ternary ..?..:.. operator -// * closures and anonymous functions -// * break, continue and return statements +/// For control flow we have: +/// * standard switch with must break statements +/// * if-else if-else and ternary ..?..:.. operator +/// * closures and anonymous functions +/// * break, continue and return statements example29() { var v = true ? 30 : 60; switch (v) { @@ -498,12 +615,12 @@ example29() { } else { continue; } - // Never gets here. + /// Never gets here. } } -// Parse int, convert double to int, or just keep int when dividing numbers -// by using the ~/ operation. Let's play a guess game too. +/// Parse int, convert double to int, or just keep int when dividing numbers +/// by using the ~/ operation. Let's play a guess game too. example30() { var gn, tooHigh = false, @@ -512,7 +629,7 @@ example30() { top = int.parse("123") ~/ n2, bottom = 0; top = top ~/ 6; - gn = new DM.Random().nextInt(top + 1); // +1 because nextInt top is exclusive + gn = new DM.Random().nextInt(top + 1); /// +1 because nextInt top is exclusive print("Example30 Guess a number between 0 and ${top}"); guessNumber(i) { if (n == gn) { @@ -536,8 +653,8 @@ example30() { } } -// Optional Positional Parameter: -// parameter will be disclosed with square bracket [ ] & square bracketed parameter are optional. +/// Optional Positional Parameter: +/// parameter will be disclosed with square bracket [ ] & square bracketed parameter are optional. example31() { findVolume31(int length, int breath, [int height]) { print('length = $length, breath = $breath, height = $height'); @@ -547,12 +664,12 @@ example31() { findVolume31(10,20); //also valid } -// Optional Named Parameter: -// parameter will be disclosed with curly bracket { } -// curly bracketed parameter are optional. -// have to use parameter name to assign a value which separated with colan : -// in curly bracketed parameter order does not matter -// these type parameter help us to avoid confusion while passing value for a function which has many parameter. +/// Optional Named Parameter: +/// parameter will be disclosed with curly bracket { } +/// curly bracketed parameter are optional. +/// have to use parameter name to assign a value which separated with colan : +/// in curly bracketed parameter order does not matter +/// these type parameter help us to avoid confusion while passing value for a function which has many parameter. example32() { findVolume32(int length, int breath, {int height}) { print('length = $length, breath = $breath, height = $height'); @@ -562,23 +679,28 @@ example32() { findVolume32(10,20);//also valid } -// Optional Default Parameter: -// same like optional named parameter in addition we can assign default value for this parameter. -// which means no value is passed this default value will be taken. +/// Optional Default Parameter: +/// same like optional named parameter in addition we can assign default value for this parameter. +/// which means no value is passed this default value will be taken. example33() { findVolume33(int length, int breath, {int height=10}) { print('length = $length, breath = $breath, height = $height'); - } + } findVolume33(10,20,height:30);//valid - findVolume33(10,20);//valid + findVolume33(10,20);//valid } -// Programs have only one entry point in the main function. -// Nothing is expected to be executed on the outer scope before a program -// starts running with what's in its main function. -// This helps with faster loading and even lazily loading of just what -// the program needs to startup with. +/// Dart has also added feature such as Null aware operators +var isBool = true; +var hasString = isBool ?? "default String"; +var hasValue ??= "default Value"; + +/// Programs have only one entry point in the main function. +/// Nothing is expected to be executed on the outer scope before a program +/// starts running with what's in its main function. +/// This helps with faster loading and even lazily loading of just what +/// the program needs to startup with. main() { print("Learn Dart in 15 minutes!"); [ diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 2b0b38dd..28ecc7ae 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -9,7 +9,7 @@ lang: de-de --- ```c -// Es war klar dass das kommt... +// Es war klar, dass das kommt... module hello; import std.stdio; @@ -20,13 +20,13 @@ void main(string[] args) { } ``` -Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut -das du schonmal über [D](http://dlang.org/) gehört hast. -Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis -High Level verwendet werden kann und dabei viele Stile anbietet. +Wenn du so wie ich bist und viel Zeit im Internet verbringst, stehen die Chancen +gut, dass du schonmal über [D](http://dlang.org/) gehört hast. +Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von +Low bis High Level verwendet werden kann und dabei viele Stile anbietet. D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, -richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen! +richtig coole leute. Da das jetzt alles aus dem Weg ist - auf zu den Beispielen! ```c import std.stdio; @@ -38,7 +38,7 @@ void main() { writeln(i); } - auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen + auto n = 1; // auto um den Typ vom Compiler bestimmen zu lassen // Zahlenliterale können _ verwenden für lesbarkeit while(n < 10_000) { @@ -68,21 +68,22 @@ void main() { } ``` -Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions -werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden. -Templates können verwendet werden um alle typen zu parameterisieren. +Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. +Structs und unions werden as-value (koppiert) an Methoden übergeben wogegen +Klassen als Referenz übergeben werden. Templates können verwendet werden um +alle Typen zu parameterisieren. ```c // Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++ struct LinkedList(T) { T data = null; - LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. (<T> in C#/Java/C++) + LinkedList!(T)* next; // Das ! wird verwendet, um T zu übergeben. (<T> in C#/Java/C++) } class BinTree(T) { T data = null; - // Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden + // Wenn es nur einen T Parameter gibt, können die Klammern um ihn weggelassen werden BinTree!T left; BinTree!T right; } @@ -97,7 +98,7 @@ enum Day { Saturday, } -// Aliase können verwendet werden um die Entwicklung zu erleichtern +// Aliase können verwendet werden, um die Entwicklung zu erleichtern alias IntList = LinkedList!int; alias NumTree = BinTree!double; @@ -111,8 +112,8 @@ T max(T)(T a, T b) { return a; } -// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird. -// Selbst bei werten wird es immer eine Referenz sein. +// Steht ref vor einem Parameter, wird sichergestellt, dass er als Referenz +übergeben wird. Selbst bei Werten wird es immer eine Referenz sein. void swap(T)(ref T a, ref T b) { auto temp = a; @@ -120,18 +121,18 @@ void swap(T)(ref T a, ref T b) { b = temp; } -// Templates können ebenso werte parameterisieren. +// Templates können ebenso Werte parameterisieren. class Matrix(uint m, uint n, T = int) { T[m] rows; T[n] columns; } -auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer +auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom Typ Integer ``` Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property -ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax +ist eine Funktion, die wie ein Wert agiert. Das gibt uns viel klarere Syntax im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` ```c @@ -187,18 +188,17 @@ void main() { ``` Mit properties können wir sehr viel logik hinter unseren gettern -und settern hinter einer schönen syntax verstecken +und settern hinter einer schönen Syntax verstecken -Other object-oriented goodies at our disposal Andere Objektorientierte features sind beispielsweise `interface`s, `abstract class` und `override`. Vererbung funktioniert in D wie in Java: -Erben von einer Klasse, so viele interfaces wie man will. +Erben von einer Klasse, so viele Interfaces wie man will. -Jetzt haben wir Objektorientierung in D gesehen aber schauen +Jetzt haben wir Objektorientierung in D gesehen, aber schauen wir uns noch was anderes an. -D bietet funktionale programmierung mit _first-class functions_ -puren funktionen und unveränderbare daten. +D bietet funktionale Programmierung mit _first-class functions_ +puren Funktionen und unveränderbaren Daten. Zusätzlich können viele funktionale Algorithmen wie z.B map, filter, reduce und friends im `std.algorithm` Modul gefunden werden! @@ -207,11 +207,11 @@ import std.algorithm : map, filter, reduce; import std.range : iota; // builds an end-exclusive range void main() { - // Wir wollen die summe aller quadratzahlen zwischen + // Wir wollen die Summe aller Quadratzahlen zwischen // 1 und 100 ausgeben. Nichts leichter als das! - // Einfach eine lambda funktion als template parameter übergeben - // Es ist genau so gut möglich eine normale funktion hier zu übergeben + // Einfach eine Lambda-Funktion als Template Parameter übergeben + // Es ist genau so gut möglich eine normale Funktion hier zu übergeben // Lambdas bieten sich hier aber an. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) @@ -221,13 +221,13 @@ void main() { } ``` -Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben +Ist dir aufgefallen, wie wir eine Haskell-Style Pipeline gebaut haben um num zu berechnen? Das war möglich durch die Uniform Function Call Syntax. -Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder +Mit UFCS können wir auswählen, ob wir eine Funktion als Methode oder als freie Funktion aufrufen. Walters artikel dazu findet ihr [hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) -Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als +Kurzgesagt kann man Funktionen, deren erster Parameter vom typ A ist, als Methode auf A anwenden. Parrallel Computing ist eine Tolle sache, findest du nicht auch? @@ -239,10 +239,10 @@ import std.math : sqrt; void main() { // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen - // und dabei alle Kerne verwenden die wir zur verfügung haben + // und dabei alle Kerne verwenden, die wir zur verfügung haben auto arr = new double[1_000_000]; - // Wir verwenden den index und das element als referenz + // Wir verwenden den Index und das Element als Referenz // und rufen einfach parallel auf! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); diff --git a/el-gr/python3-gr.html.markdown b/el-gr/python3-gr.html.markdown index 08c3d4aa..445b85ba 100644 --- a/el-gr/python3-gr.html.markdown +++ b/el-gr/python3-gr.html.markdown @@ -8,7 +8,8 @@ contributors: - ["evuez", "http://github.com/evuez"] - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] -filename: learnpython3.py +filename: learnpython3-gr.py +lang: el-gr --- Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο diff --git a/es-es/sql-es.html.markdown b/es-es/sql-es.html.markdown new file mode 100644 index 00000000..1ee0d454 --- /dev/null +++ b/es-es/sql-es.html.markdown @@ -0,0 +1,115 @@ +--- +language: SQL +filename: learnsql-es.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["FedeHC", "https://github.com/FedeHC"] +lang: es-es +--- + +El lenguaje de consulta estructurada (SQL en inglés) es un lenguaje estándar ISO para crear y trabajar con bases de datos almacenados en un conjunto de tablas. Las implementaciones generalmente añaden sus propias extensiones al lenguaje; [Comparación entre diferentes implementaciones de SQL](http://troels.arvin.dk/db/rdbms/) es una buena referencia sobre las diferencias entre distintos productos. + +Las implementaciones típicamente proveen de una línea de comandos donde uno puede introducir los comandos que se muestran aquí en forma interactiva, y también ofrecen una forma de ejecutar una serie de estos comandos almacenados en un archivo de script (mostrar que uno ha terminado con el prompt interactivo es un buen ejemplo de algo que no está estandarizado - la mayoría de las implementaciones de SQL soportan las palabras clave QUIT, EXIT, o ambas). + +Varios de estos comandos que sirven de ejemplo asumen que la [base de datos de empleados de muestra de MySQL](https://dev.mysql.com/doc/employee/en/) disponible en [github](https://github.com/datacharmer/test_db) ya ha sido cargada. Los archivos github son scripts de comandos, similares a los comandos que aparecen a continuación, que crean y cargan tablas de datos sobre los empleados de una empresa ficticia. La sintaxis para ejecutar estos scripts dependerá de la implementación de SQL que esté utilizando. Una aplicación que se ejecuta desde el prompt del sistema operativo suele ser lo habitual. + + +```sql +-- Los comentarios empiezan con dos guiones. Se termina cada comando con punto +-- y coma. + +-- SQL no distingue entre mayúsculas y minúsculas en palabras clave. Los +-- comandos de ejemplo que aquí se muestran siguen la convención de ser escritos +-- en mayúsculas porque hace más fácil distinguirlos de los nombres de las bases +-- de datos, de las tablas y de las columnas. + +-- A cont. se crea y se elimina una base de datos. Los nombres de la base de +-- datos y de la tabla son sensibles a mayúsculas y minúsculas. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Lista todas las bases de datos disponibles. +SHOW DATABASES; + +-- Usa una base de datos existente en particular. +USE employees; + +-- Selecciona todas las filas y las columnas de la tabla departments en la base +-- de datos actual. La actividad predeterminada es que el intérprete desplace +-- los resultados por la pantalla. +SELECT * FROM departments; + +-- Recupera todas las filas de la tabla departments, pero sólo las columnas +-- dept_no y dept_name. +-- Separar los comandos en varias líneas está permitido. +SELECT dept_no, + dept_name FROM departments; + +-- Obtiene todas las columnas de departments, pero se limita a 5 filas. +SELECT * FROM departments LIMIT 5; + +-- Obtiene los valores de la columna dept_name desde la tabla departments cuando +-- dept_name tiene como valor la subcadena 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Recuperar todas las columnas de la tabla departments donde la columna +-- dept_name comienza con una 'S' y tiene exactamente 4 caracteres después +-- de ella. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Selecciona los valores de los títulos de la tabla titles, pero no muestra +-- duplicados. +SELECT DISTINCT title FROM titles; + +-- Igual que el anterior, pero ordenado por los valores de title (se distingue +-- entre mayúsculas y minúsculas). +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Muestra el número de filas de la tabla departments. +SELECT COUNT(*) FROM departments; + +-- Muestra el número de filas en la tabla departments que contiene 'en' como +-- subcadena en la columna dept_name. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Una unión (JOIN) de información desde varias tablas: la tabla titles muestra +-- quién tiene qué títulos de trabajo, según sus números de empleados, y desde +-- qué fecha hasta qué fecha. Se obtiene esta información, pero en lugar del +-- número de empleado se utiliza el mismo como una referencia cruzada a la +-- tabla employee para obtener el nombre y apellido de cada empleado (y se +-- limita los resultados a 10 filas). +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- Se enumera todas las tablas de todas las bases de datos. Las implementaciones +-- típicamente proveen sus propios comandos para hacer esto con la base de datos +-- actualmente en uso. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Crear una tabla llamada tablename1, con las dos columnas mostradas, a partir +-- de la base de datos en uso. Hay muchas otras opciones disponibles para la +-- forma en que se especifican las columnas, como por ej. sus tipos de datos. +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Insertar una fila de datos en la tabla tablename1. Se asume que la tabla ha +-- sido definida para aceptar estos valores como aptos. +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- En tablename1, se cambia el valor de fname a 'John' para todas las filas que +-- tengan un valor en lname igual a 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Se borra las filas de la tabla tablename1 donde el valor de lname comience +-- con 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Se borra todas las filas de la tabla tablename1, dejando la tabla vacía. +DELETE FROM tablename1; + +-- Se elimina toda la tabla tablename1 por completo. +DROP TABLE tablename1; +``` diff --git a/go.html.markdown b/go.html.markdown index 49f1ade4..739ec05d 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -109,6 +109,11 @@ can include line breaks.` // Same string type. a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of five // elements, with values 3, 1, 5, 10, and 100. + // Arrays have value semantics. + a4_cpy := a4 // a4_cpy is a copy of a4, two separate instances. + a4_cpy[0] = 25 // Only a4_cpy is changed, a4 stays the same. + fmt.Println(a4_cpy[0] == a4[0]) // false + // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. s3 := []int{4, 5, 9} // Compare to a5. No ellipsis here. @@ -116,6 +121,11 @@ can include line breaks.` // Same string type. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. + // Slices (as well as maps and channels) have reference semantics. + s3_cpy := s3 // Both variables point to the same instance. + s3_cpy[0] = 0 // Which means both are updated. + fmt.Println(s3_cpy[0] == s3[0]) // true + // Because they are dynamic, slices can be appended to on-demand. // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, @@ -168,10 +178,11 @@ func learnNamedReturns(x, y int) (z int) { // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. +// Unlike in C/Cpp taking and returning an address of a local varible is also safe. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. p = new(int) // Built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. + // The allocated int slice is initialized to 0, p is no longer nil. s := make([]int, 20) // Allocate 20 ints as a single block of memory. s[3] = 7 // Assign one of them. r := -2 // Declare another local variable. diff --git a/mips.html.markdown b/mips.html.markdown index 45e16e7b..7f759bec 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -39,28 +39,30 @@ gateways and routers. _float: .float 3.14 # 4 bytes _double: .double 7.0 # 8 bytes - .align 2 # Memory alignment of data, where - # number indicates byte alignment in - # powers of 2. (.align 2 represents - # word alignment since 2^2 = 4 bytes) - -.text # Section that contains instructions - # and program logic + .align 2 # Memory alignment of data, where + # number indicates byte alignment + # in powers of 2. (.align 2 + # represents word alignment since + # 2^2 = 4 bytes) + +.text # Section that contains + # instructions and program logic .globl _main # Declares an instruction label as # global, making it accessible to # other files - _main: # MIPS programs execute instructions - # sequentially, where the code under - # this label will be executed firsts + _main: # MIPS programs execute + # instructions sequentially, where + # the code under this label will be + # executed first # Let's print "hello world" - la $a0, hello_world # Load address of string stored in - # memory - li $v0, 4 # Load the syscall value (indicating - # type of functionality) - syscall # Perform the specified syscall with - # the given argument ($a0) + la $a0, hello_world # Load address of string stored + # in memory + li $v0, 4 # Load the syscall value (number + # indicating which syscall to make) + syscall # Perform the specified syscall + # with the given argument ($a0) # Registers (used to hold data during program execution) # $t0 - $t9 # Temporary registers used for @@ -79,22 +81,24 @@ gateways and routers. # Types of load/store instructions la $t0, label # Copy the address of a value in - # memory specified by the label into - # register $t0 + # memory specified by the label + # into register $t0 lw $t0, label # Copy a word value from memory lw $t1, 4($s0) # Copy a word value from an address - # stored in a register with an offset - # of 4 bytes (addr + 4) - lb $t2, label # Copy a byte value to the lower order - # portion of the register $t2 + # stored in a register with an + # offset of 4 bytes (addr + 4) + lb $t2, label # Copy a byte value to the + # lower order portion of + # the register $t2 lb $t2, 0($s0) # Copy a byte value from the source # address in $s0 with offset 0 # Same idea with 'lh' for halfwords - sw $t0, label # Store word value into memory address - # mapped by label + sw $t0, label # Store word value into + # memory address mapped by label sw $t0, 8($s0) # Store word value into address - # specified in $s0 and offset of 8 bytes + # specified in $s0 and offset of + # 8 bytes # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist ### Math ### @@ -108,20 +112,22 @@ gateways and routers. mul $t2, $t0, $t1 # $t2 = $t0 * $t1 div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be # supported in some versons of MARS) - div $t0, $t1 # Performs $t0 / $t1. Get the quotient - # using 'mflo' and remainder using 'mfhi' + div $t0, $t1 # Performs $t0 / $t1. Get the + # quotient using 'mflo' and + # remainder using 'mfhi' # Bitwise Shifting sll $t0, $t0, 2 # Bitwise shift to the left with # immediate (constant value) of 2 - sllv $t0, $t1, $t2 # Shift left by a variable amount in - # register + sllv $t0, $t1, $t2 # Shift left by a variable amount + # in register srl $t0, $t0, 5 # Bitwise shift to the right (does - # not sign preserve, sign-extends with 0) - srlv $t0, $t1, $t2 # Shift right by a variable amount in - # a register - sra $t0, $t0, 7 # Bitwise arithmetic shift to the right - # (preserves sign) + # not sign preserve, sign-extends + # with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount + # in a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to + # the right (preserves sign) srav $t0, $t1, $t2 # Shift right by a variable amount # in a register @@ -146,7 +152,8 @@ gateways and routers. # $t0 == $t1, otherwise # execute the next line bne $t0, $t1, reg_neq # Branches when $t0 != $t1 - b branch_target # Unconditional branch, will always execute + b branch_target # Unconditional branch, will + # always execute beqz $t0, req_eq_zero # Branches when $t0 == 0 bnez $t0, req_neq_zero # Branches when $t0 != 0 bgt $t0, $t1, t0_gt_t1 # Branches when $t0 > $t1 @@ -155,8 +162,9 @@ gateways and routers. blt $t0, $t1, t0_gt_t1 # Branches when $t0 < $t1 ble $t0, $t1, t0_gte_t1 # Branches when $t0 <= $t1 bltz $t0, t0_lt0 # Branches when $t0 < 0 - slt $s0, $t0, $t1 # Instruction that sends a signal when - # $t0 < $t1 with result in $s0 (1 for true) + slt $s0, $t0, $t1 # Instruction that sends a signal + # when $t0 < $t1 with result in $s0 + # (1 for true) # Simple if statement # if (i == j) @@ -183,14 +191,14 @@ gateways and routers. # max = c; # Let $s0 = a, $s1 = b, $s2 = c, $v0 = return register - ble $s0, $s1, a_LTE_b # if (a <= b) branch(a_LTE_b) - ble $s0, $s2, max_C # if (a > b && a <=c) branch(max_C) + ble $s0, $s1, a_LTE_b # if(a <= b) branch(a_LTE_b) + ble $s0, $s2, max_C # if(a > b && a <=c) branch(max_C) move $v0, $s1 # else [a > b && a > c] max = a j done # Jump to the end of the program a_LTE_b: # Label for when a <= b - ble $s1, $s2, max_C # if (a <= b && b <= c) branch(max_C) - move $v0, $s1 # if (a <= b && b > c) max = b + ble $s1, $s2, max_C # if(a <= b && b <= c) branch(max_C) + move $v0, $s1 # if(a <= b && b > c) max = b j done # Jump to done max_C: @@ -204,9 +212,11 @@ gateways and routers. instruction to continue its execution li $t0, 0 while: - bgt $t0, 10, end_while # While $t0 is less than 10, keep iterating + bgt $t0, 10, end_while # While $t0 is less than 10, + # keep iterating addi $t0, $t0, 1 # Increment the value - j while # Jump back to the beginning of the loop + j while # Jump back to the beginning of + # the loop end_while: # 2D Matrix Traversal @@ -246,7 +256,8 @@ gateways and routers. # How about recursion? # This is a bit more work since we need to make sure we save and restore - # the previous PC in $ra since jal will automatically overwrite on each call + # the previous PC in $ra since jal will automatically overwrite + # on each call li $a0, 3 jal fact diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1f1ffce6..27874e93 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -420,7 +420,7 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 // Для функций это тоже работает. -myObj.myFunc(); // = "Привет, мир!" +myObj.myFunc(); // = "привет, мир!" // Если интерпретатор не найдёт свойство в прототипе, то продожит поиск // в прототипе прототипа и так далее. diff --git a/rust.html.markdown b/rust.html.markdown index 23dcbd4f..413939bf 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -22,7 +22,7 @@ currently available in the nightly builds. Rust has adopted a train-based releas model with regular releases every six weeks. Rust 1.1 beta was made available at the same time of the release of Rust 1.0. -Although Rust is a relatively low-level language, Rust has some functional +Although Rust is a relatively low-level language, it has some functional concepts that are generally found in higher-level languages. This makes Rust not only fast, but also easy and efficient to code in. |