summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorLuis Custodio <luis.custodio@gmail.com>2015-10-17 13:11:25 +0200
committerLuis Custodio <luis.custodio@gmail.com>2015-10-17 13:11:25 +0200
commitf5873b08901bfaec3fb46518258ff9e886fd04c4 (patch)
tree62886b71c7226f0c6c4f979d61ff96c839a641a9
parentc9348e5a82b639093f8f3eee955ffdf6fb99b5d8 (diff)
parent0e6d9f6fe9aeffc64c3adad3e4a0ee1cc0d1dd88 (diff)
Merge branch 'master' of github.com:adambard/learnxinyminutes-docs
-rw-r--r--README.markdown2
-rw-r--r--amd.html.markdown8
-rw-r--r--asymptotic-notation.html.markdown26
-rw-r--r--bash.html.markdown15
-rw-r--r--c++.html.markdown4
-rw-r--r--c.html.markdown115
-rw-r--r--chapel.html.markdown8
-rw-r--r--clojure-macros.html.markdown6
-rw-r--r--coffeescript.html.markdown36
-rw-r--r--coldfusion.html.markdown321
-rw-r--r--common-lisp.html.markdown2
-rw-r--r--cs-cz/python3.html.markdown6
-rw-r--r--csharp.html.markdown111
-rw-r--r--css.html.markdown262
-rw-r--r--d.html.markdown103
-rw-r--r--dart.html.markdown10
-rw-r--r--de-de/csharp-de.html.markdown2
-rw-r--r--el-gr/css-gr.html.markdown243
-rw-r--r--erlang.html.markdown2
-rw-r--r--es-es/javascript-es.html.markdown4
-rw-r--r--es-es/visualbasic-es.html.markdown286
-rw-r--r--forth.html.markdown4
-rw-r--r--fr-fr/haml-fr.html.markdown157
-rw-r--r--fr-fr/objective-c-fr.html.markdown2
-rw-r--r--fr-fr/php.html.markdown696
-rw-r--r--fr-fr/python3-fr.html.markdown723
-rw-r--r--fr-fr/scala.html.markdown9
-rw-r--r--fr-fr/yaml-fr.html.markdown92
-rw-r--r--fsharp.html.markdown316
-rw-r--r--git.html.markdown30
-rw-r--r--go.html.markdown11
-rw-r--r--groovy.html.markdown13
-rw-r--r--hack.html.markdown20
-rw-r--r--haml.html.markdown33
-rw-r--r--hu-hu/ruby.html.markdown555
-rw-r--r--java.html.markdown299
-rw-r--r--javascript.html.markdown34
-rw-r--r--json.html.markdown19
-rw-r--r--julia.html.markdown36
-rw-r--r--latex.html.markdown231
-rw-r--r--livescript.html.markdown6
-rw-r--r--make.html.markdown8
-rw-r--r--markdown.html.markdown8
-rw-r--r--matlab.html.markdown132
-rw-r--r--neat.html.markdown28
-rw-r--r--nim.html.markdown2
-rw-r--r--nl-nl/brainfuck-nl.html.markdown2
-rw-r--r--objective-c.html.markdown165
-rw-r--r--ocaml.html.markdown12
-rw-r--r--perl.html.markdown2
-rw-r--r--perl6.html.markdown144
-rw-r--r--php.html.markdown39
-rw-r--r--pt-br/c-pt.html.markdown19
-rw-r--r--pt-br/clojure-macros-pt.html.markdown154
-rw-r--r--pt-br/css-pt.html.markdown257
-rw-r--r--pt-br/sass-pt.html.markdown477
-rw-r--r--pt-pt/scala-pt.html.markdown651
-rw-r--r--purescript.html.markdown134
-rw-r--r--python.html.markdown19
-rw-r--r--python3.html.markdown258
-rw-r--r--r.html.markdown40
-rw-r--r--racket.html.markdown4
-rw-r--r--red.html.markdown88
-rw-r--r--ru-ru/objective-c-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown61
-rw-r--r--ruby.html.markdown32
-rw-r--r--rust.html.markdown18
-rw-r--r--sass.html.markdown447
-rw-r--r--scala.html.markdown16
-rw-r--r--self.html.markdown42
-rw-r--r--smalltalk.html.markdown90
-rw-r--r--swift.html.markdown62
-rw-r--r--tcl.html.markdown48
-rw-r--r--tr-tr/objective-c-tr.html.markdown2
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--vi-vn/ruby-vi.html.markdown549
-rw-r--r--visualbasic.html.markdown24
-rw-r--r--xml.html.markdown27
78 files changed, 7633 insertions, 1290 deletions
diff --git a/README.markdown b/README.markdown
index 774797d5..28fa5093 100644
--- a/README.markdown
+++ b/README.markdown
@@ -8,7 +8,7 @@ commented code and explained as they go.
... to write more inline code tutorials. Just grab an existing file from
this repo and copy the formatting (don't worry, it's all very simple).
-Make a new file, send a pull request, and if it passes muster I'll get it up pronto.
+Make a new file, send a pull request, and if it passes master I'll get it up pronto.
Remember to fill in the "contributors" fields so you get credited
properly!
diff --git a/amd.html.markdown b/amd.html.markdown
index b3237dc7..d7fb41ba 100644
--- a/amd.html.markdown
+++ b/amd.html.markdown
@@ -8,10 +8,10 @@ filename: learnamd.js
## Getting Started with AMD
-The **Asynchronous Module Definition** API specifies a mechanism for defining
-JavaScript modules such that the module and its dependencies can be asynchronously
-loaded. This is particularly well suited for the browser environment where
-synchronous loading of modules incurs performance, usability, debugging, and
+The **Asynchronous Module Definition** API specifies a mechanism for defining
+JavaScript modules such that the module and its dependencies can be asynchronously
+loaded. This is particularly well suited for the browser environment where
+synchronous loading of modules incurs performance, usability, debugging, and
cross-domain access problems.
### Basic concept
diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown
index e1f961f8..a516737e 100644
--- a/asymptotic-notation.html.markdown
+++ b/asymptotic-notation.html.markdown
@@ -72,45 +72,45 @@ for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arb
you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0),
`f(n)` <= `c g(n)` for every input size n (n > 0).
-*Example 1*
+*Example 1*
```
-f(n) = 3log n + 100
+f(n) = 3log n + 100
g(n) = log n
```
-Is `f(n)` O(g(n))?
-Is `3 log n + 100` O(log n)?
+Is `f(n)` O(g(n))?
+Is `3 log n + 100` O(log n)?
Let's look to the definition of Big-O.
```
-3log n + 100 <= c * log n
+3log n + 100 <= c * log n
```
-Is there some constant c that satisfies this for all n?
+Is there some constant c that satisfies this for all n?
```
-3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1)
+3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1)
```
Yes! The definition of Big-O has been met therefore `f(n)` is O(g(n)).
-*Example 2*
+*Example 2*
```
-f(n) = 3*n^2
+f(n) = 3*n^2
g(n) = n
```
-Is `f(n)` O(g(n))?
-Is `3 * n^2` O(n)?
+Is `f(n)` O(g(n))?
+Is `3 * n^2` O(n)?
Let's look at the definition of Big-O.
```
-3 * n^2 <= c * n
+3 * n^2 <= c * n
```
-Is there some constant c that satisfies this for all n?
+Is there some constant c that satisfies this for all n?
No, there isn't. `f(n)` is NOT O(g(n)).
### Big-Omega
diff --git a/bash.html.markdown b/bash.html.markdown
index d4f3d424..211d2944 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -90,17 +90,26 @@ else
echo "Your name is your username"
fi
+# NOTE: if $Name is empty, bash sees the above condition as:
+if [ -ne $USER ]
+# which is invalid syntax
+# so the "safe" way to use potentially empty variables in bash is:
+if [ "$Name" -ne $USER ] ...
+# which, when $Name is empty, is seen by bash as:
+if [ "" -ne $USER ] ...
+# which works as expected
+
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets:
-if [ $Name == "Steve" ] && [ $Age -eq 15 ]
+if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
echo "This will run if $Name is Steve AND $Age is 15."
fi
-if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
+if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi
@@ -252,7 +261,7 @@ grep "^foo.*bar$" file.txt
grep -c "^foo.*bar$" file.txt
# if you literally want to search for the string,
# and not the regex, use fgrep (or grep -F)
-fgrep "^foo.*bar$" file.txt
+fgrep "^foo.*bar$" file.txt
# Read Bash shell builtins documentation with the bash 'help' builtin:
diff --git a/c++.html.markdown b/c++.html.markdown
index 8ee964ca..2bee51dc 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -264,7 +264,7 @@ string retVal = tempObjectFun();
// What happens in the second line is actually:
// - a string object is returned from tempObjectFun
-// - a new string is constructed with the returned object as arugment to the
+// - a new string is constructed with the returned object as argument to the
// constructor
// - the returned object is destroyed
// The returned object is called a temporary object. Temporary objects are
@@ -404,6 +404,8 @@ int main() {
// Inheritance:
// This class inherits everything public and protected from the Dog class
+// as well as private but may not directly access private members/methods
+// without a public or protected method for doing so
class OwnedDog : public Dog {
void setOwner(const std::string& dogsOwner);
diff --git a/c.html.markdown b/c.html.markdown
index db2ac930..a8f71057 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -6,7 +6,8 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
-
+ - ["Zachary Ferguson", "https://github.io/zfergus2"]
+ - ["himanshu", "https://github.com/himanshu81494"]
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -27,6 +28,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
*/ // ...not this one!
// Constants: #define <keyword>
+// Constants are written in all-caps out of convention, not requirement
#define DAYS_IN_YEAR 365
// Enumeration constants are also ways to declare constants.
@@ -52,10 +54,21 @@ int function_2(void);
// Must declare a 'function prototype' before main() when functions occur after
// your main() function.
int add_two_ints(int x1, int x2); // function prototype
+// although `int add_two_ints(int, int);` is also valid (no need to name the args),
+// it is recommended to name arguments in the prototype as well for easier inspection
// Your program's entry point is a function called
// main with an integer return type.
int main(void) {
+ // your program
+}
+
+// The command line arguments used to run your program are also passed to main
+// argc being the number of arguments - your program's name counts as 1
+// argv is an array of character arrays - containing the arguments themselves
+// argv[0] = name of your program, argv[1] = first argument, etc.
+int main (int argc, char** argv)
+{
// print output using printf, for "print formatted"
// %d is an integer, \n is a newline
printf("%d\n", 0); // => Prints 0
@@ -63,6 +76,9 @@ int main(void) {
///////////////////////////////////////
// Types
///////////////////////////////////////
+
+ // All variables MUST be declared at the top of the current block scope
+ // we declare them dynamically along the code for the sake of the tutorial
// ints are usually 4 bytes
int x_int = 0;
@@ -221,7 +237,7 @@ int main(void) {
0 || 1; // => 1 (Logical or)
0 || 0; // => 0
- // Conditional expression ( ? : )
+ // Conditional ternary expression ( ? : )
int e = 5;
int f = 10;
int z;
@@ -291,6 +307,8 @@ int main(void) {
for (i = 0; i <= 5; i++) {
; // use semicolon to act as the body (null statement)
}
+ // Or
+ for (i = 0; i <= 5; i++);
// branching with multiple choices: switch()
switch (a) {
@@ -306,7 +324,29 @@ int main(void) {
exit(-1);
break;
}
-
+ /*
+ using "goto" in C
+ */
+ typedef enum { false, true } bool;
+ // for C don't have bool as data type :(
+ bool disaster = false;
+ int i, j;
+ for(i=0;i<100;++i)
+ for(j=0;j<100;++j)
+ {
+ if((i + j) >= 150)
+ disaster = true;
+ if(disaster)
+ goto error;
+ }
+ error :
+ printf("Error occured at i = %d & j = %d.\n", i, j);
+ /*
+ https://ideone.com/GuPhd6
+ this will print out "Error occured at i = 52 & j = 99."
+ */
+
+
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
@@ -472,7 +512,24 @@ char c[] = "This is a test.";
str_reverse(c);
printf("%s\n", c); // => ".tset a si sihT"
*/
-
+/*
+as we can return only one variable
+to change values of more than one variables we use call by reference
+*/
+void swapTwoNumbers(int *a, int *b)
+{
+ int temp = *a;
+ *a = *b;
+ *b = temp;
+}
+/*
+int first = 10;
+int second = 20;
+printf("first: %d\nsecond: %d\n", first, second);
+swapTwoNumbers(&first, &second);
+printf("first: %d\nsecond: %d\n", first, second);
+// values will be swapped
+*/
// if referring to external variables outside function, must use extern keyword.
int i = 0;
void testFunc() {
@@ -628,8 +685,56 @@ typedef void (*my_fnp_type)(char *);
// , | left to right //
//---------------------------------------------------//
-```
+/******************************* Header Files **********************************
+Header files are an important part of c as they allow for the connection of c
+source files and can simplify code and definitions by seperating them into
+seperate files.
+
+Header files are syntaxtically similar to c source files but reside in ".h"
+files. They can be included in your c source file by using the precompiler
+command #include "example.h", given that example.h exists in the same directory
+as the c file.
+*/
+
+/* A safe guard to prevent the header from being defined too many times. This */
+/* happens in the case of circle dependency, the contents of the header is */
+/* already defined. */
+#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
+#define EXAMPLE_H /* Define the macro EXAMPLE_H. */
+
+/* Other headers can be included in headers and therefore transitively */
+/* included into files that include this header. */
+#include <string.h>
+
+/* Like c source files macros can be defined in headers and used in files */
+/* that include this header file. */
+#define EXAMPLE_NAME "Dennis Ritchie"
+/* Function macros can also be defined. */
+#define ADD(a, b) (a + b)
+
+/* Structs and typedefs can be used for consistency between files. */
+typedef struct node
+{
+ int val;
+ struct node *next;
+} Node;
+
+/* So can enumerations. */
+enum traffic_light_state {GREEN, YELLOW, RED};
+
+/* Function prototypes can also be defined here for use in multiple files, */
+/* but it is bad practice to define the function in the header. Definitions */
+/* should instead be put in a c file. */
+Node createLinkedList(int *vals, int len);
+
+/* Beyond the above elements, other definitions should be left to a c source */
+/* file. Excessive includeds or definitions should, also not be contained in */
+/* a header file but instead put into separate headers or a c file. */
+
+#endif /* End of the if precompiler directive. */
+
+```
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 02a96b04..7252a3e4 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -307,7 +307,7 @@ var stringSet: domain(string); // empty set of strings
stringSet += "a";
stringSet += "b";
stringSet += "c";
-stringSet += "a"; // Redundant add "a"
+stringSet += "a"; // Redundant add "a"
stringSet -= "c"; // Remove "c"
writeln( stringSet );
@@ -524,12 +524,12 @@ genericProc( 1.0+2.0i, 3.0+4.0i );
// The param modifier on the arg is used to enforce this constraint.
proc whereProc( param N : int ): void
where ( N > 0 ) {
- writeln( "N is greater than 0" );
+ writeln( "N is greater than 0" );
}
proc whereProc( param N : int ): void
where ( N < 0 ) {
- writeln( "N is less than 0" );
+ writeln( "N is less than 0" );
}
whereProc( 10 );
@@ -633,7 +633,7 @@ writeln( toThisArray );
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
// exhibits a runtime error.
// Even though the domain of the array and the loop-expression are
-// the same size, the body of the expression can be though of as an iterator.
+// the same size, the body of the expression can be thought of as an iterator.
// Because iterators can yield nothing, that iterator yields a different number
// of things than the domain of the array or loop, which is not allowed.
diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown
index 9e907a7f..d74f77cf 100644
--- a/clojure-macros.html.markdown
+++ b/clojure-macros.html.markdown
@@ -142,11 +142,11 @@ You'll want to be familiar with Clojure. Make sure you understand everything in
### Further Reading
-Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/)
+Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/)
[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
-Official docs
+Official docs
[http://clojure.org/macros](http://clojure.org/macros)
-When to use macros?
+When to use macros?
[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index 4c080bc6..89a29677 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -6,8 +6,8 @@ contributors:
filename: coffeescript.coffee
---
-CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
-As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
+CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
+As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime.
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
@@ -54,35 +54,35 @@ math =
square: square
cube: (x) -> x * square x
#=> var math = {
-# "root": Math.sqrt,
-# "square": square,
-# "cube": function(x) { return x * square(x); }
-#}
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+# };
# Splats:
race = (winner, runners...) ->
print winner, runners
#=>race = function() {
-# var runners, winner;
-# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
-# return print(winner, runners);
-#};
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+# };
# Existence:
alert "I knew it!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
# Array comprehensions:
-cubes = (math.cube num for num in list)
+cubes = (math.cube num for num in list)
#=>cubes = (function() {
-# var _i, _len, _results;
-# _results = [];
+# var _i, _len, _results;
+# _results = [];
# for (_i = 0, _len = list.length; _i < _len; _i++) {
-# num = list[_i];
-# _results.push(math.cube(num));
-# }
-# return _results;
-# })();
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
new file mode 100644
index 00000000..e2f0737d
--- /dev/null
+++ b/coldfusion.html.markdown
@@ -0,0 +1,321 @@
+---
+language: ColdFusion
+contributors:
+ - ["Wayne Boka", "http://wboka.github.io"]
+filename: LearnColdFusion.cfm
+---
+
+ColdFusion is a scripting language for web development.
+[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
+
+```ColdFusion
+
+<em>HTML tags have been provided for output readability</em>
+
+<!--- Comments start with "<!---" and end with "--->" --->
+<!---
+ Comments can
+ also
+ span
+ multiple lines
+--->
+
+<!--- CFML tags have a similar format to HTML tags. --->
+<h1>Simple Variables</h1>
+<!--- Variable Declaration: Variables are loosely typed, similar to javascript --->
+<p>Set <b>myVariable</b> to "myValue"</p>
+<cfset myVariable = "myValue" />
+<p>Set <b>myNumber</b> to 3.14</p>
+<cfset myNumber = 3.14 />
+
+<!--- Displaying simple data --->
+<!--- Use <cfoutput> for simple values such as strings, numbers, and expressions --->
+<p>Display <b>myVariable</b>: <cfoutput>#myVariable#</cfoutput></p><!--- myValue --->
+<p>Display <b>myNumber</b>: <cfoutput>#myNumber#</cfoutput></p><!--- 3.14 --->
+
+<hr />
+
+<h1>Complex Variables</h1>
+<!--- Declaring complex variables --->
+<!--- Declaring an array of 1 dimension: literal or bracket notation --->
+<p>Set <b>myArray1</b> to an array of 1 dimension using literal or bracket notation</p>
+<cfset myArray1 = [] />
+<!--- Declaring an array of 1 dimension: function notation --->
+<p>Set <b>myArray2</b> to an array of 1 dimension using function notation</p>
+<cfset myArray2 = ArrayNew(1) />
+
+<!--- Outputting complex variables --->
+<p>Contents of <b>myArray1</b></p>
+<cfdump var="#myArray1#" /> <!--- An empty array object --->
+<p>Contents of <b>myArray2</b></p>
+<cfdump var="#myArray2#" /> <!--- An empty array object --->
+
+<!--- Operators --->
+<!--- Arithmetic --->
+<h1>Operators</h1>
+<h2>Arithmetic</h2>
+<p>1 + 1 = <cfoutput>#1 + 1#</cfoutput></p>
+<p>10 - 7 = <cfoutput>#10 - 7#<br /></cfoutput></p>
+<p>15 * 10 = <cfoutput>#15 * 10#<br /></cfoutput></p>
+<p>100 / 5 = <cfoutput>#100 / 5#<br /></cfoutput></p>
+<p>120 % 5 = <cfoutput>#120 % 5#<br /></cfoutput></p>
+<p>120 mod 5 = <cfoutput>#120 mod 5#<br /></cfoutput></p>
+
+<hr />
+
+<!--- Comparison --->
+<h2>Comparison</h2>
+<h3>Standard Notation</h3>
+<p>Is 1 eq 1? <cfoutput>#1 eq 1#</cfoutput></p>
+<p>Is 15 neq 1? <cfoutput>#15 neq 1#</cfoutput></p>
+<p>Is 10 gt 8? <cfoutput>#10 gt 8#</cfoutput></p>
+<p>Is 1 lt 2? <cfoutput>#1 lt 2#</cfoutput></p>
+<p>Is 10 gte 5? <cfoutput>#10 gte 5#</cfoutput></p>
+<p>Is 1 lte 5? <cfoutput>#1 lte 5#</cfoutput></p>
+
+<h3>Alternative Notation</h3>
+<p>Is 1 == 1? <cfoutput>#1 eq 1#</cfoutput></p>
+<p>Is 15 != 1? <cfoutput>#15 neq 1#</cfoutput></p>
+<p>Is 10 > 8? <cfoutput>#10 gt 8#</cfoutput></p>
+<p>Is 1 < 2? <cfoutput>#1 lt 2#</cfoutput></p>
+<p>Is 10 >= 5? <cfoutput>#10 gte 5#</cfoutput></p>
+<p>Is 1 <= 5? <cfoutput>#1 lte 5#</cfoutput></p>
+
+<hr />
+
+<!--- Control Structures --->
+<h1>Control Structures</h1>
+
+<cfset myCondition = "Test" />
+
+<p>Condition to test for: "<cfoutput>#myCondition#</cfoutput>"</p>
+
+<cfif myCondition eq "Test">
+ <cfoutput>#myCondition#. We're testing.</cfoutput>
+<cfelseif myCondition eq "Production">
+ <cfoutput>#myCondition#. Proceed Carefully!!!</cfoutput>
+<cfelse>
+ myCondition is unknown
+</cfif>
+
+<hr />
+
+<!--- Loops --->
+<h1>Loops</h1>
+<h2>For Loop</h2>
+<cfloop from="0" to="10" index="i">
+ <p>Index equals <cfoutput>#i#</cfoutput></p>
+</cfloop>
+
+<h2>For Each Loop (Complex Variables)</h2>
+
+<p>Set <b>myArray3</b> to [5, 15, 99, 45, 100]</p>
+
+<cfset myArray3 = [5, 15, 99, 45, 100] />
+
+<cfloop array="#myArray3#" index="i">
+ <p>Index equals <cfoutput>#i#</cfoutput></p>
+</cfloop>
+
+<p>Set <b>myArray4</b> to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]</p>
+
+<cfset myArray4 = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"] />
+
+<cfloop array="#myArray4#" index="s">
+ <p>Index equals <cfoutput>#s#</cfoutput></p>
+</cfloop>
+
+<h2>Switch Statement</h2>
+
+<p>Set <b>myArray5</b> to [5, 15, 99, 45, 100]</p>
+
+<cfset myArray5 = [5, 15, 99, 45, 100] />
+
+<cfloop array="#myArray5#" index="i">
+ <cfswitch expression="#i#">
+ <cfcase value="5,15,45" delimiters=",">
+ <p><cfoutput>#i#</cfoutput> is a multiple of 5.</p>
+ </cfcase>
+ <cfcase value="99">
+ <p><cfoutput>#i#</cfoutput> is ninety-nine.</p>
+ </cfcase>
+ <cfdefaultcase>
+ <p><cfoutput>#i#</cfoutput> is not 5, 15, 45, or 99.</p>
+ </cfdefaultcase>
+ </cfswitch>
+</cfloop>
+
+<hr />
+
+<h1>Converting types</h1>
+
+<style>
+ table.table th, table.table td {
+ border: 1px solid #000000;
+ padding: 2px;
+ }
+
+ table.table th {
+ background-color: #CCCCCC;
+ }
+</style>
+
+<table class="table" cellspacing="0">
+ <thead>
+ <tr>
+ <th>Value</th>
+ <th>As Boolean</th>
+ <th>As number</th>
+ <th>As date-time</th>
+ <th>As string</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th>"Yes"</th>
+ <td>TRUE</td>
+ <td>1</td>
+ <td>Error</td>
+ <td>"Yes"</td>
+ </tr>
+ <tr>
+ <th>"No"</th>
+ <td>FALSE</td>
+ <td>0</td>
+ <td>Error</td>
+ <td>"No"</td>
+ </tr>
+ <tr>
+ <th>TRUE</th>
+ <td>TRUE</td>
+ <td>1</td>
+ <td>Error</td>
+ <td>"Yes"</td>
+ </tr>
+ <tr>
+ <th>FALSE</th>
+ <td>FALSE</td>
+ <td>0</td>
+ <td>Error</td>
+ <td>"No"</td>
+ </tr>
+ <tr>
+ <th>Number</th>
+ <td>True if Number is not 0; False otherwise.</td>
+ <td>Number</td>
+ <td>See &#34;Date-time values&#34; earlier in this chapter.</td>
+ <td>String representation of the number (for example, &#34;8&#34;).</td>
+ </tr>
+ <tr>
+ <th>String</th>
+ <td>If "Yes", True <br>If "No", False <br>If it can be converted to 0, False <br>If it can be converted to any other number, True</td>
+ <td>If it represents a number (for example, &#34;1,000&#34; or &#34;12.36E-12&#34;), it is converted to the corresponding number.</td>
+ <td>If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. <br>If it is an ODBC date, time, or timestamp (for example &#34;{ts &#39;2001-06-14 11:30:13&#39;}&#34;, or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. <br>Days of the week or unusual punctuation result in an error. <br>Dashes, forward-slashes, and spaces are generally allowed.</td>
+ <td>String</td>
+ </tr>
+ <tr>
+ <th>Date</th>
+ <td>Error</td>
+ <td>The numeric value of the date-time object.</td>
+ <td>Date</td>
+ <td>An ODBC timestamp.</td>
+ </tr>
+ </tbody>
+</table>
+
+<hr />
+
+<h1>Components</h1>
+
+<em>Code for reference (Functions must return something to support IE)</em>
+
+<pre>
+&lt;cfcomponent&gt;
+ &lt;cfset this.hello = "Hello" /&gt;
+ &lt;cfset this.world = "world" /&gt;
+
+ &lt;cffunction name="sayHello"&gt;
+ &lt;cfreturn this.hello & ", " & this.world & "!" /&gt;
+ &lt;/cffunction&gt;
+
+ &lt;cffunction name="setHello"&gt;
+ &lt;cfargument name="newHello" type="string" required="true" /&gt;
+
+ &lt;cfset this.hello = arguments.newHello /&gt;
+
+ &lt;cfreturn true /&gt;
+ &lt;/cffunction&gt;
+
+ &lt;cffunction name="setWorld"&gt;
+ &lt;cfargument name="newWorld" type="string" required="true" /&gt;
+
+ &lt;cfset this.world = arguments.newWorld /&gt;
+
+ &lt;cfreturn true /&gt;
+ &lt;/cffunction&gt;
+
+ &lt;cffunction name="getHello"&gt;
+ &lt;cfreturn this.hello /&gt;
+ &lt;/cffunction&gt;
+
+ &lt;cffunction name="getWorld"&gt;
+ &lt;cfreturn this.world /&gt;
+ &lt;/cffunction&gt;
+&lt;/cfcomponent&gt;
+</pre>
+
+<cfset this.hello = "Hello" />
+<cfset this.world = "world" />
+
+<cffunction name="sayHello">
+ <cfreturn this.hello & ", " & this.world & "!" />
+</cffunction>
+
+<cffunction name="setHello">
+ <cfargument name="newHello" type="string" required="true" />
+
+ <cfset this.hello = arguments.newHello />
+
+ <cfreturn true />
+</cffunction>
+
+<cffunction name="setWorld">
+ <cfargument name="newWorld" type="string" required="true" />
+
+ <cfset this.world = arguments.newWorld />
+
+ <cfreturn true />
+</cffunction>
+
+<cffunction name="getHello">
+ <cfreturn this.hello />
+</cffunction>
+
+<cffunction name="getWorld">
+ <cfreturn this.world />
+</cffunction>
+
+
+<b>sayHello()</b>
+<cfoutput><p>#sayHello()#</p></cfoutput>
+<b>getHello()</b>
+<cfoutput><p>#getHello()#</p></cfoutput>
+<b>getWorld()</b>
+<cfoutput><p>#getWorld()#</p></cfoutput>
+<b>setHello("Hola")</b>
+<cfoutput><p>#setHello("Hola")#</p></cfoutput>
+<b>setWorld("mundo")</b>
+<cfoutput><p>#setWorld("mundo")#</p></cfoutput>
+<b>sayHello()</b>
+<cfoutput><p>#sayHello()#</p></cfoutput>
+<b>getHello()</b>
+<cfoutput><p>#getHello()#</p></cfoutput>
+<b>getWorld()</b>
+<cfoutput><p>#getWorld()#</p></cfoutput>
+```
+
+## Further Reading
+
+The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
+
+1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index e0597e94..63183c1e 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -261,7 +261,7 @@ nil ; for false - and the empty list
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
:adjustable t :fill-pointer t))
-
+
*adjvec* ; => #(1 2 3)
;; Adding new element:
diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown
index 11c8a654..6d2fd1eb 100644
--- a/cs-cz/python3.html.markdown
+++ b/cs-cz/python3.html.markdown
@@ -48,7 +48,7 @@ Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit sta
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
-# Pokud použiteje desetinné číslo, výsledek je jím také
+# Pokud použijete desetinné číslo, výsledek je jím také
3 * 2.0 # => 6.0
# Modulo
@@ -420,7 +420,7 @@ next(iterator) # Vyhodí StopIteration
## 4. Funkce
####################################################
-# Pro vytvoření nové funkce použijte def
+# Pro vytvoření nové funkce použijte klíčové slovo def
def secist(x, y):
print("x je {} a y je {}".format(x, y))
return x + y # Hodnoty se vrací pomocí return
@@ -520,7 +520,7 @@ class Clovek(object):
# podtržítka na začátku a na konci značí, že se jedná o atribut nebo
# objekt využívaný Pythonem ke speciálním účelům, ale můžete sami
# definovat jeho chování. Metody jako __init__, __str__, __repr__
- # a další se nazývají "magické metody". Nikdy nepoužívejte toto
+ # a další se nazývají "magické metody". Nikdy nepoužívejte toto
# speciální pojmenování pro běžné metody.
def __init__(self, jmeno):
# Přiřazení parametru do atributu instance jmeno
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 222ba0d2..7aca2c6f 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Melvyn Laïly", "http://x2a.yt"]
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
- ["Wouter Van Schandevijl", "http://github.com/laoujin"]
+ - ["Jo Pearce", "http://github.com/jdpearce"]
filename: LearnCSharp.cs
---
@@ -25,7 +26,7 @@ Multi-line comments look like this
//public void MethodOrClassOrOtherWithParsableHelp() {}
// Specify the namespaces this source code will be using
-// The namespaces below are all part of the standard .NET Framework Class Libary
+// The namespaces below are all part of the standard .NET Framework Class Libary
using System;
using System.Collections.Generic;
using System.Dynamic;
@@ -48,7 +49,7 @@ namespace Learning.CSharp
public class LearnCSharp
{
// BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
- public static void Syntax()
+ public static void Syntax()
{
// Use Console.WriteLine to print lines
Console.WriteLine("Hello World");
@@ -159,7 +160,7 @@ on a new line! ""Wow!"", the masses cried";
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
- List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize
+ List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize
// The <> are for generics - Check out the cool stuff section
// Lists don't default to a value;
@@ -371,11 +372,11 @@ on a new line! ""Wow!"", the masses cried";
//
// INTERESTING FEATURES
//
-
+
// DEFAULT METHOD SIGNATURES
public // Visibility
- static // Allows for direct call on class without object
+ static // Allows for direct call on class without object
int // Return Type,
MethodSignatures(
int maxCount, // First variable, expects an int
@@ -383,7 +384,7 @@ on a new line! ""Wow!"", the masses cried";
int another = 3,
params string[] otherParams // captures all other parameters passed to method
)
- {
+ {
return -1;
}
@@ -400,8 +401,8 @@ on a new line! ""Wow!"", the masses cried";
// The classes for TKey and TValue is specified by the user calling this function.
// This method emulates the SetDefault of Python
public static TValue SetDefault<TKey, TValue>(
- IDictionary<TKey, TValue> dictionary,
- TKey key,
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
TValue defaultItem)
{
TValue result;
@@ -410,7 +411,7 @@ on a new line! ""Wow!"", the masses cried";
return result;
}
- // You can narrow down the objects that are passed in
+ // You can narrow down the objects that are passed in
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
{
// We can iterate, since T is a IEnumerable
@@ -418,12 +419,48 @@ on a new line! ""Wow!"", the masses cried";
// Item is an int
Console.WriteLine(item.ToString());
}
+
+ // YIELD
+ // Usage of the "yield" keyword indicates that the method it appears in is an Iterator
+ // (this means you can use it in a foreach loop)
+ public static IEnumerable<int> YieldCounter(int limit = 10)
+ {
+ for (var i = 0; i < limit; i++)
+ yield return i;
+ }
+
+ // which you would call like this :
+ public static void PrintYieldCounterToConsole()
+ {
+ foreach (var counter in YieldCounter())
+ Console.WriteLine(counter);
+ }
+
+ // you can use more than one "yield return" in a method
+ public static IEnumerable<int> ManyYieldCounter()
+ {
+ yield return 0;
+ yield return 1;
+ yield return 2;
+ yield return 3;
+ }
+
+ // you can also use "yield break" to stop the Iterator
+ // this method would only return half of the values from 0 to limit.
+ public static IEnumerable<int> YieldCounterWithBreak(int limit = 10)
+ {
+ for (var i = 0; i < limit; i++)
+ {
+ if (i > limit/2) yield break;
+ yield return i;
+ }
+ }
public static void OtherInterestingFeatures()
{
// OPTIONAL PARAMETERS
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
- MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones
+ MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones
// BY REF AND OUT PARAMETERS
int maxCount = 0, count; // ref params must have value
@@ -443,6 +480,9 @@ on a new line! ""Wow!"", the masses cried";
// ?? is syntactic sugar for specifying default value (coalesce)
// in case variable is null
int notNullable = nullable ?? 0; // 0
+
+ // ?. is an operator for null-propagation - a shorthand way of checking for null
+ nullable?.Print(); // Use the Print() extension method if nullable isn't null
// IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
var magic = "magic is a string, at compile time, so you still get type safety";
@@ -450,13 +490,13 @@ on a new line! ""Wow!"", the masses cried";
// GENERICS
//
- var phonebook = new Dictionary<string, string>() {
+ var phonebook = new Dictionary<string, string>() {
{"Sarah", "212 555 5555"} // Add some entries to the phone book
};
// Calling SETDEFAULT defined as a generic above
Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // No Phone
- // nb, you don't need to specify the TKey and TValue since they can be
+ // nb, you don't need to specify the TKey and TValue since they can be
// derived implicitly
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
@@ -491,26 +531,26 @@ on a new line! ""Wow!"", the masses cried";
// DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
// Most of objects that access unmanaged resources (file handle, device contexts, etc.)
- // implement the IDisposable interface. The using statement takes care of
+ // implement the IDisposable interface. The using statement takes care of
// cleaning those IDisposable objects for you.
using (StreamWriter writer = new StreamWriter("log.txt"))
{
writer.WriteLine("Nothing suspicious here");
// At the end of scope, resources will be released.
// Even if an exception is thrown.
- }
+ }
// PARALLEL FRAMEWORK
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
- var websites = new string[] {
- "http://www.google.com", "http://www.reddit.com",
+ var websites = new string[] {
+ "http://www.google.com", "http://www.reddit.com",
"http://www.shaunmccarthy.com"
};
var responses = new Dictionary<string, string>();
-
+
// Will spin up separate threads for each request, and join on them
// before going to the next step!
- Parallel.ForEach(websites,
+ Parallel.ForEach(websites,
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
website =>
{
@@ -534,7 +574,7 @@ on a new line! ""Wow!"", the masses cried";
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
Console.WriteLine(student.Introduce("Beth"));
- // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
+ // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
// very useful Map / Filter / Reduce style methods
var bikes = new List<Bicycle>();
bikes.Sort(); // Sorts the array
@@ -556,8 +596,8 @@ on a new line! ""Wow!"", the masses cried";
// ASPARALLEL
// And this is where things get wicked - combines linq and parallel operations
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
- // this will happen in parallel! Threads will automagically be spun up and the
- // results divvied amongst them! Amazing for large datasets when you have lots of
+ // this will happen in parallel! Threads will automagically be spun up and the
+ // results divvied amongst them! Amazing for large datasets when you have lots of
// cores
// LINQ - maps a store to IQueryable<T> objects, with delayed execution
@@ -575,9 +615,9 @@ on a new line! ""Wow!"", the masses cried";
.Select(b => b.Name); // still no query run
// Now the query runs, but opens a reader, so only populates are you iterate through
- foreach (string bike in query)
+ foreach (string bike in query)
Console.WriteLine(result);
-
+
}
@@ -610,7 +650,7 @@ on a new line! ""Wow!"", the masses cried";
{
return _cadence;
}
- set // set - define a method to set a proprety
+ set // set - define a method to set a property
{
_cadence = value; // Value is the value passed in to the setter
}
@@ -629,7 +669,7 @@ on a new line! ""Wow!"", the masses cried";
private set; // You can set modifiers on the get/set methods
}
- int _speed; // Everything is private by default: Only accessible from within this class.
+ int _speed; // Everything is private by default: Only accessible from within this class.
// can also use keyword private
public string Name { get; set; }
@@ -676,7 +716,7 @@ on a new line! ""Wow!"", the masses cried";
// Constructors are a way of creating classes
// This is a default constructor
- public Bicycle()
+ public Bicycle()
{
this.Gear = 1; // you can access members of the object with the keyword this
Cadence = 50; // but you don't always need it
@@ -688,13 +728,13 @@ on a new line! ""Wow!"", the masses cried";
// This is a specified constructor (it contains arguments)
public Bicycle(int startCadence, int startSpeed, int startGear,
- string name, bool hasCardsInSpokes, BikeBrand brand)
+ string name, bool hasCardsInSpokes, BikeBrand brand)
: base() // calls base first
{
- Gear = startGear;
+ Gear = startGear;
Cadence = startCadence;
_speed = startSpeed;
- Name = name;
+ Name = name;
_hasCardsInSpokes = hasCardsInSpokes;
Brand = brand;
}
@@ -750,7 +790,7 @@ on a new line! ""Wow!"", the masses cried";
// It's also possible to define custom Indexers on objects.
// All though this is not entirely useful in this example, you
- // could do bicycle[0] which yields "chris" to get the first passenger or
+ // could do bicycle[0] which returns "chris" to get the first passenger or
// bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle)
private string[] passengers = { "chris", "phil", "darren", "regina" };
@@ -761,7 +801,7 @@ on a new line! ""Wow!"", the masses cried";
}
set {
- return passengers[i] = value;
+ passengers[i] = value;
}
}
@@ -837,7 +877,8 @@ on a new line! ""Wow!"", the masses cried";
bool Broken { get; } // interfaces can contain properties as well as methods & events
}
- // Class can inherit only one other class, but can implement any amount of interfaces
+ // Class can inherit only one other class, but can implement any amount of interfaces, however
+ // the base class name must be the first in the list and all interfaces follow
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
@@ -857,7 +898,7 @@ on a new line! ""Wow!"", the masses cried";
}
/// <summary>
- /// Used to connect to DB for LinqToSql example.
+ /// Used to connect to DB for LinqToSql example.
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
/// </summary>
@@ -876,13 +917,13 @@ on a new line! ""Wow!"", the masses cried";
## Topics Not Covered
* Attributes
- * async/await, yield, pragma directives
+ * async/await, pragma directives
* Web Development
* ASP.NET MVC & WebApi (new)
* ASP.NET Web Forms (old)
* WebMatrix (tool)
* Desktop Development
- * Windows Presentation Foundation (WPF) (new)
+ * Windows Presentation Foundation (WPF) (new)
* Winforms (old)
## Further Reading
diff --git a/css.html.markdown b/css.html.markdown
index e217906f..d8f30ca3 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -5,25 +5,20 @@ contributors:
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
filename: learncss.css
---
-In the early days of the web there were no visual elements, just pure text. But with the
-further development of browsers, fully visual web pages also became common.
-CSS is the standard language that exists to keep the separation between
-the content (HTML) and the look-and-feel of web pages.
+In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common.
-In short, what CSS does is to provide a syntax that enables you to target
-different elements on an HTML page and assign different visual properties to them.
+CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page.
-Like any other languages, CSS has many versions. Here we focus on CSS2.0,
-which is not the most recent version, but is the most widely supported and compatible version.
+CSS lets you target different elements on an HTML page and assign different visual properties to them.
-**NOTE:** Because the outcome of CSS consists of visual effects, in order to
-learn it, you need try everything in a
-CSS playground like [dabblet](http://dabblet.com/).
-The main focus of this article is on the syntax and some general tips.
+This guide has been written for CSS 2, though CSS 3 is fast becoming popular.
+**NOTE:** Because CSS produces visual results, in order to learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/).
+The main focus of this article is on the syntax and some general tips.
```css
/* comments appear inside slash-asterisk, just like this line!
@@ -33,92 +28,103 @@ The main focus of this article is on the syntax and some general tips.
## SELECTORS
#################### */
-/* Generally, the primary statement in CSS is very simple */
+/* the selector is used to target an element on a page.
selector { property: value; /* more properties...*/ }
-/* the selector is used to target an element on page.
-
-You can target all elements on the page using asterisk! */
-* { color:red; }
-
/*
-Given an element like this on the page:
+Here is an example element:
-<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' />
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
*/
-/* you can target it by its name */
-.some-class { }
+/* You can target it using one of its CSS classes */
+.class1 { }
-/* or by both classes! */
-.some-class.class2 { }
+/* or both classes! */
+.class1.class2 { }
-/* or by its element name */
+/* or its name */
div { }
/* or its id */
-#someId { }
+#anID { }
-/* or by the fact that it has an attribute! */
+/* or using the fact that it has an attribute! */
[attr] { font-size:smaller; }
/* or that the attribute has a specific value */
[attr='value'] { font-size:smaller; }
-/* start with a value (CSS3) */
+/* starts with a value (CSS 3) */
[attr^='val'] { font-size:smaller; }
-/* or ends with (CSS3) */
+/* or ends with a value (CSS 3) */
[attr$='ue'] { font-size:smaller; }
-/* or select by one of the values from the whitespace separated list (CSS3) */
-[otherAttr~='foo'] { font-size:smaller; }
+/* or contains a value in a space-separated list */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
-/* or value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D) */
+/* or contains a value in a dash-separated list, ie, "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
-/* and more importantly you can combine these together -- there shouldn't be
-any space between different parts because that makes it to have another
-meaning. */
+/* You can concatenate different selectors to create a narrower selector. Don't
+ put spaces between them. */
div.some-class[attr$='ue'] { }
-/* you can also select an element based on its parent. */
+/* You can select an element which is a child of another element */
+div.some-parent > .class-name { }
+
+/* or a descendant of another element. Children are the direct descendants of
+ their parent element, only one level down the tree. Descendants can be any
+ level down the tree. */
+div.some-parent .class-name { }
-/* an element which is direct child of an element (selected the same way) */
-div.some-parent > .class-name {}
+/* Warning: the same selector without a space has another meaning.
+ Can you guess what? */
+div.some-parent.class-name { }
-/* or any of its parents in the tree
- the following basically means any element that has class "class-name"
- and is child of a div with class name "some-parent" IN ANY DEPTH */
-div.some-parent .class-name {}
+/* You may also select an element based on its adjacent sibling */
+.i-am-just-before + .this-element { }
-/* warning: the same selector without space has another meaning.
- can you say what? */
-div.some-parent.class-name {}
+/* or any sibling preceding it */
+.i-am-any-element-before ~ .this-element { }
-/* you also might choose to select an element based on its direct
- previous sibling */
-.i-am-before + .this-element { }
+/* There are some selectors called pseudo classes that can be used to select an
+ element when it is in a particular state */
-/* or any sibling before this */
-.i-am-any-before ~ .this-element {}
+/* for example, when the cursor hovers over an element */
+selector:hover { }
-/* There are some pseudo classes that allows you to select an element
- based on its page behaviour (rather than page structure) */
+/* or a link has been visited */
+selector:visited { }
-/* for example for when an element is hovered */
-selector:hover {}
+/* or hasn't been visited */
+selected:link { }
-/* or a visited link */
-selected:visited {}
+/* or an element in focus */
+selected:focus { }
-/* or not visited link */
-selected:link {}
+/* any element that is the first child of its parent */
+selector:first-child {}
-/* or an input element which is focused */
-selected:focus {}
+/* any element that is the last child of its parent */
+selector:last-child {}
+/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
+
+/* matches a virtual first child of the selected element */
+selector::before {}
+
+/* matches a virtual last child of the selected element */
+selector::after {}
+
+/* At appropriate places, an asterisk may be used as a wildcard to select every
+ element */
+* { } /* all elements */
+.parent * { } /* all descendants */
+.parent > * { } /* all children */
/* ####################
## PROPERTIES
@@ -126,126 +132,122 @@ selected:focus {}
selector {
- /* Units */
- width: 50%; /* in percent */
- font-size: 2em; /* times current font-size */
- width: 200px; /* in pixels */
- font-size: 20pt; /* in points */
- width: 5cm; /* in centimeters */
- min-width: 50mm; /* in millimeters */
- max-width: 5in; /* in inches. max-(width|height) */
- height: 0.2vh; /* times vertical height of browser viewport (CSS3) */
- width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */
- min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */
- max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */
+ /* Units of length can be absolute or relative. */
+
+ /* Relative units */
+ width: 50%; /* percentage of parent element width */
+ font-size: 2em; /* multiples of element's original font-size */
+ font-size: 2rem; /* or the root element's font-size */
+ font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
+ font-size: 2vh; /* or its height */
+ font-size: 2vmin; /* whichever of a vh or a vw is smaller */
+ font-size: 2vmax; /* or greater */
+
+ /* Absolute units */
+ width: 200px; /* pixels */
+ font-size: 20pt; /* points */
+ width: 5cm; /* centimeters */
+ min-width: 50mm; /* millimeters */
+ max-width: 5in; /* inches */
/* Colors */
- background-color: #F6E; /* in short hex */
- background-color: #F262E2; /* in long hex format */
- background-color: tomato; /* can be a named color */
- background-color: rgb(255, 255, 255); /* in rgb */
- background-color: rgb(10%, 20%, 50%); /* in rgb percent */
- background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */
- background-color: transparent; /* see thru */
- background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */
- background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */
-
+ color: #F6E; /* short hex format */
+ color: #FF66EE; /* long hex format */
+ color: tomato; /* a named color */
+ color: rgb(255, 255, 255); /* as rgb values */
+ color: rgb(10%, 20%, 50%); /* as rgb percentages */
+ color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */
+ color: transparent; /* equivalent to setting the alpha to 0 */
+ color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
+ color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */
- /* Images */
- background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
+ /* Images as backgrounds of elements */
+ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
/* Fonts */
font-family: Arial;
- font-family: "Courier New"; /* if name has space it appears in single or double quotes */
- font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found
- browser uses the second font, and so forth */
+ /* if the font family name has a space, it must be quoted */
+ font-family: "Courier New";
+ /* if the first one is not found, the browser uses the next, and so on */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
-
```
## Usage
-Save any CSS you want in a file with extension `.css`.
+Save a CSS stylesheet with the extension `.css`.
```xml
-<!-- you need to include the css file in your page's <head>: -->
+<!-- You need to include the css file in your page's <head>. This is the
+ recommended method. Refer to http://stackoverflow.com/questions/8284365 -->
<link rel='stylesheet' type='text/css' href='path/to/style.css' />
-<!-- you can also include some CSS inline in your markup. However it is highly
-recommended to avoid this. -->
+<!-- You can also include some CSS inline in your markup. -->
<style>
a { color: purple; }
</style>
-<!-- or directly set CSS properties on the element.
-This has to be avoided as much as you can. -->
+<!-- Or directly set CSS properties on the element. -->
<div style="border: 1px solid red;">
</div>
-
```
-## Precedence
+## Precedence or Cascade
-As you noticed an element may be targetted by more than one selector.
-and may have a property set on it in more than one.
-In these cases, one of the rules takes precedence over others.
+An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
+
+This process is called cascading, hence the name Cascading Style Sheets.
Given the following CSS:
```css
-/*A*/
+/* A */
p.class1[attr='value']
-/*B*/
-p.class1 {}
+/* B */
+p.class1 { }
-/*C*/
-p.class2 {}
+/* C */
+p.class2 { }
-/*D*/
-p {}
+/* D */
+p { }
-/*E*/
+/* E */
p { property: value !important; }
-
```
and the following markup:
```xml
-<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
-</p>
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```
-The precedence of style is as followed:
-Remember, the precedence is for each **property**, not for the entire block.
+The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block.
-* `E` has the highest precedence because of the keyword `!important`.
- It is recommended to avoid this unless it is strictly necessary to use.
-* `F` is next, because it is inline style.
-* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
- class name `class1` + 1 attribute `attr='value'`
-* `C` is next. although it has the same specificness as `B`
- but it appears last.
-* Then is `B`
-* and lastly is `D`.
+* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage.
+* `F` is next, because it is an inline style.
+* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`.
+* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`.
+* `B` is next.
+* `D` is the last one.
## Compatibility
-Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatibility
-of what you use in CSS with your target browsers.
+Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature.
-[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
+## Resources
-To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource.
+* To run a quick compatibility check, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
## Further Reading
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/d.html.markdown b/d.html.markdown
index daba8020..80c1dc65 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -1,6 +1,6 @@
---
-language: D
-filename: learnd.d
+language: D
+filename: learnd.d
contributors:
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
lang: en
@@ -18,13 +18,15 @@ void main(string[] args) {
}
```
-If you're like me and spend way too much time on the internet, odds are you've heard
+If you're like me and spend way too much time on the internet, odds are you've heard
about [D](http://dlang.org/). The D programming language is a modern, general-purpose,
-multi-paradigm language with support for everything from low-level features to
+multi-paradigm language with support for everything from low-level features to
expressive high-level abstractions.
-D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
-dudes. With all that out of the way, let's look at some examples!
+D is actively developed by a large group of super-smart people and is spearheaded by
+[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and
+[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu).
+With all that out of the way, let's look at some examples!
```c
import std.stdio;
@@ -36,9 +38,10 @@ void main() {
writeln(i);
}
- auto n = 1; // use auto for type inferred variables
-
- // Numeric literals can use _ as a digit seperator for clarity
+ // 'auto' can be used for inferring types.
+ auto n = 1;
+
+ // Numeric literals can use '_' as a digit separator for clarity.
while(n < 10_000) {
n += n;
}
@@ -47,13 +50,15 @@ void main() {
n -= (n / 2);
} while(n > 0);
- // For and while are nice, but in D-land we prefer foreach
- // The .. creates a continuous range, excluding the end
- foreach(i; 1..1_000_000) {
+ // For and while are nice, but in D-land we prefer 'foreach' loops.
+ // The '..' creates a continuous range, including the first value
+ // but excluding the last.
+ foreach(i; 1..1_000_000) {
if(n % 2 == 0)
writeln(i);
}
+ // There's also 'foreach_reverse' when you want to loop backwards.
foreach_reverse(i; 1..int.max) {
if(n % 2 == 1) {
writeln(i);
@@ -69,16 +74,18 @@ are passed to functions by value (i.e. copied) and classes are passed by referen
we can use templates to parameterize all of these on both types and values!
```c
-// Here, T is a type parameter. Think <T> from C++/C#/Java
+// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java.
struct LinkedList(T) {
T data = null;
- LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T>
+
+ // Use '!' to instantiate a parameterized type. Again, think '<T>'.
+ LinkedList!(T)* next;
}
class BinTree(T) {
T data = null;
-
- // If there is only one template parameter, we can omit parens
+
+ // If there is only one template parameter, we can omit the parentheses.
BinTree!T left;
BinTree!T right;
}
@@ -93,37 +100,34 @@ enum Day {
Saturday,
}
-// Use alias to create abbreviations for types
-
+// Use alias to create abbreviations for types.
alias IntList = LinkedList!int;
alias NumTree = BinTree!double;
// We can create function templates as well!
-
T max(T)(T a, T b) {
- if(a < b)
+ if(a < b)
return b;
return a;
}
-// Use the ref keyword to ensure pass by referece.
-// That is, even if a and b are value types, they
-// will always be passed by reference to swap
+// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b'
+// are value types, they will always be passed by reference to 'swap()'.
void swap(T)(ref T a, ref T b) {
auto temp = a;
a = b;
- b = temp;
+ b = temp;
}
-// With templates, we can also parameterize on values, not just types
+// With templates, we can also parameterize on values, not just types.
class Matrix(uint m, uint n, T = int) {
T[m] rows;
T[n] columns;
}
-auto mat = new Matrix!(3, 3); // We've defaulted type T to int
+auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'.
```
@@ -133,25 +137,24 @@ have the syntax of POD structures (`structure.x = 7`) with the semantics of
getter and setter methods (`object.setX(7)`)!
```c
-// Consider a class parameterized on a types T, U
-
+// Consider a class parameterized on types 'T' & 'U'.
class MyClass(T, U) {
T _data;
U _other;
-
}
-// And "getter" and "setter" methods like so
+// And "getter" and "setter" methods like so:
class MyClass(T, U) {
T _data;
U _other;
-
- // Constructors are always named `this`
+
+ // Constructors are always named 'this'.
this(T t, U u) {
+ // This will call the setter methods below.
data = t;
other = u;
}
-
+
// getters
@property T data() {
return _data;
@@ -161,7 +164,7 @@ class MyClass(T, U) {
return _other;
}
- // setters
+ // setters
@property void data(T t) {
_data = t;
}
@@ -170,16 +173,24 @@ class MyClass(T, U) {
_other = u;
}
}
-// And we use them in this manner
+// And we use them in this manner:
void main() {
- auto mc = MyClass!(int, string);
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Import the 'stdio' module from the standard library for writing to
+ // console (imports can be local to a scope).
+ import std.stdio;
- mc.data = 7;
- mc.other = "seven";
-
- writeln(mc.data);
- writeln(mc.other);
+ // Call the getters to fetch the values.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // Call the setters to assign new values.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // Call the getters again to fetch the new values.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
}
```
@@ -193,7 +204,7 @@ and `override`ing methods. D does inheritance just like Java:
Extend one class, implement as many interfaces as you please.
We've seen D's OOP facilities, but let's switch gears. D offers
-functional programming with first-class functions, `pure`
+functional programming with first-class functions, `pure`
functions, and immutable data. In addition, all of your favorite
functional algorithms (map, filter, reduce and friends) can be
found in the wonderful `std.algorithm` module!
@@ -205,7 +216,7 @@ import std.range : iota; // builds an end-exclusive range
void main() {
// We want to print the sum of a list of squares of even ints
// from 1 to 100. Easy!
-
+
// Just pass lambda expressions as template parameters!
// You can pass any old function you like, but lambdas are convenient here.
auto num = iota(1, 101).filter!(x => x % 2 == 0)
@@ -216,12 +227,12 @@ void main() {
}
```
-Notice how we got to build a nice Haskellian pipeline to compute num?
+Notice how we got to build a nice Haskellian pipeline to compute num?
That's thanks to a D innovation know as Uniform Function Call Syntax.
With UFCS, we can choose whether to write a function call as a method
or free function call! Walter wrote a nice article on this
-[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
-In short, you can call functions whose first parameter
+[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+In short, you can call functions whose first parameter
is of some type A on any expression of type A as a method.
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
diff --git a/dart.html.markdown b/dart.html.markdown
index 34d1c6a8..f7601271 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -81,7 +81,7 @@ example5() {
// Where classBody can include instance methods and variables, but also
// class methods and variables.
class Example6Class {
- var example6InstanceVariable = "Example6 instance variable";
+ var example6InstanceVariable = "Example6 instance variable";
sayIt() {
print(example6InstanceVariable);
}
@@ -92,7 +92,7 @@ example6() {
// Class methods and variables are declared with "static" terms.
class Example7Class {
- static var example7ClassVariable = "Example7 class variable";
+ static var example7ClassVariable = "Example7 class variable";
static sayItFromClass() {
print(example7ClassVariable);
}
@@ -111,7 +111,7 @@ example7() {
// by default. But arrays and maps are not. They can be made constant by
// declaring them "const".
var example8A = const ["Example8 const array"],
- example8M = const {"someKey": "Example8 const map"};
+ example8M = const {"someKey": "Example8 const map"};
example8() {
print(example8A[0]);
print(example8M["someKey"]);
@@ -245,7 +245,7 @@ example18() {
// Strings with triple single-quotes or triple double-quotes span
// multiple lines and include line delimiters.
example19() {
- print('''Example19 <a href="etc">
+ print('''Example19 <a href="etc">
Example19 Don't can't I'm Etc
Example19 </a>''');
}
@@ -272,7 +272,7 @@ example20() {
class Example21 {
List<String> _names;
Example21() {
- _names = ["a", "b"];
+ _names = ["a", "b"];
}
List<String> get names => _names;
set names(List<String> list) {
diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
index 8ad7d71f..78bb0a6b 100644
--- a/de-de/csharp-de.html.markdown
+++ b/de-de/csharp-de.html.markdown
@@ -883,7 +883,7 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
* [LINQ](http://shop.oreilly.com/product/9780596519254.do)
* [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
* [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown
new file mode 100644
index 00000000..327dc1a0
--- /dev/null
+++ b/el-gr/css-gr.html.markdown
@@ -0,0 +1,243 @@
+---
+language: css
+contributors:
+ - ["Kostas Bariotis", "http://kostasbariotis.com"]
+filename: css-gr.html.markdown
+lang: el-gr
+---
+
+Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
+του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα,
+γίναν καθημερινότητα.
+
+Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή.
+
+Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ).
+
+```css
+/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
+ Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */
+
+/* ####################
+ ## ΚΑΝΟΝΕΣ
+ #################### */
+
+/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector).
+selector { property: value; /* περισσότερες ιδιότητες...*/ }
+
+/*
+Αυτό είναι ενα παράδειγμα αντικειμένου¨
+
+<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
+*/
+
+/* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */
+.class1 { }
+
+/* Ή και με τις δύο κλάσεις! */
+.class1.class2 { }
+
+/* Και με το όνομα του */
+div { }
+
+/* Ή με το id του */
+#anID { }
+
+/* Ή με το γεγονός ότι περιέχει ενα attribute */
+[attr] { font-size:smaller; }
+
+/* Ή οτι το attribute αυτό έχει μια συγκεκριμένη τιμή */
+[attr='value'] { font-size:smaller; }
+
+/* Ξεκινάει απο το λεκτικό (CSS 3) */
+[attr^='val'] { font-size:smaller; }
+
+/* Καταλήγει σε αυτο το λεκτικό (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* Περιέχει κάποιο λεκτικό */
+[otherAttr~='foo'] { }
+[otherAttr~='bar'] { }
+
+/* περιέχει το λεκτικό σε λίστα χωρισμένη με παύλες, δηλαδή: "-" (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
+
+/* Μπορούμε να προσθέσουμε μεταξύ τους selectors για να δημιουργήσουμε πιο αυστηρούς.
+ Δεν βάζουμε κενά ανάμεσα. */
+div.some-class[attr$='ue'] { }
+
+/* Μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται μέσα σε άλλα. */
+div.some-parent > .class-name { }
+
+/* Ή κάποιο αντικείμενο απόγονο ανεξαρτήτου του βάθους της σχέσης τους. */
+div.some-parent .class-name { }
+
+/* ΠΡΟΣΟΧΗ: ο ίδιος selector χωρίς κενά έχει άλλο νόημα. (Άσκηση προς τον αναγνώστη) */
+div.some-parent.class-name { }
+
+/* Μπορούμε να επιλέξουμε αντικείμενα με βάση το αμέσως επόμενο αντικείμενο στο ίδιο επίπεδο. */
+.i-am-just-before + .this-element { }
+
+/* Ή οποιοδήποτε αντικείμενο που προηγείται */
+.i-am-any-element-before ~ .this-element { }
+
+/* Με την βοήθεια των ψευδο-κλάσεων μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται σε μια
+ ορισμένη κατάασταση. */
+
+/* π.χ. όταν ο κέρσορας είναι πάνω απο ένα αντικείμενο */
+selector:hover { }
+
+/* ή ένας υπερσύνδεσμος που πατήθηκε */
+selector:visited { }
+
+/* ή που δεν πατήθηκε */
+selected:link { }
+
+/* ή ένα αντικείμενο που επιλέχθηκε */
+selected:focus { }
+
+/* οποιοδήποτε αντικείμενο είναι το πρώτο παιδί των γονέων του */
+selector:first-child {}
+
+/* οποιοδήποτε αντικείμενο είναι το πρώτοτελευταίο παιδί των γονέων του */
+selector:last-child {}
+
+/* Όπως και με τις ψευδο-κλάσεις, τα ψευδο-αντικείμενα μας επιτρέπουν τα τροποοιήσουμε συγκεκριμένα
+ κομμάτια της σελίδας */
+
+/* επιλέγει το ψευδο-αντικείμενο ακριβώς πριν απο το αντικείμενο */
+selector::before {}
+
+/* επιλέγει το ψευδο-αντικείμενο ακριβώς μετά απο τον αντικείμενο */
+selector::after {}
+
+/* Σε σωστά σημεία (όχι πολύ ψηλά στην ιεραρχία) ο αστερίσκος μπορείς να χρησιμοποιηθεί για να
+ επιλέξουμε όλα τα αντικείμενα */
+* { } /* όλα τα αντικείμενα της σελίδας */
+.parent * { } /* όλους τους απόγονους */
+.parent > * { } /* όλους τους απόγονους πρώτου επιπέδου */
+
+/* ####################
+ ## Ιδιότητες
+ #################### */
+
+selector {
+
+ /* Οι μονάδες μπορούν να είναι είτε απόλυτες είτε σχετικές */
+
+ /* Σχετικές μονάδες */
+ width: 50%; /* ποσοστό επί του πλάτους του γονέα */
+ font-size: 2em; /* πολλαπλασιαστής της αρχικής τιμής του αντικειμένου */
+ font-size: 2rem; /* ή της τιμής του πρώτου αντικειμένου στην ιεραρχία */
+ font-size: 2vw; /* πολλαπλαστιαστής του 1% του οπτικού πλάτους */
+ font-size: 2vh; /* ή τους ύψους */
+ font-size: 2vmin; /* οποιοδήποτε απο αυτα τα δύο είναι το μικρότερο */
+ font-size: 2vmax; /* ή το μεγαλύτερο */
+
+ /* Απόλυτες μονάδες */
+ width: 200px; /* pixels */
+ font-size: 20pt; /* στιγμες */
+ width: 5cm; /* εκατοστά */
+ min-width: 50mm; /* χιλιοστά */
+ max-width: 5in; /* ίντσες */
+
+ /* Χρώματα */
+ color: #F6E; /* σύντομη δεκαεξαδική μορφή */
+ color: #FF66EE; /* δεκαεξαδική μορφή */
+ color: tomato; /* χρώμα με το όνομα του (συγκεκριμένα χρώματα) */
+ color: rgb(255, 255, 255); /* τιμή RGB */
+ color: rgb(10%, 20%, 50%); /* τιμή RGB με ποσοστά */
+ color: rgba(255, 0, 0, 0.3); /* τιμή RGBA (CSS3) σσ. 0 < a < 1 */
+ color: transparent; /* όπως και το παραπάνω με a = 0 */
+ color: hsl(0, 100%, 50%); /* τιμή hsl με ποσοστά (CSS 3) */
+ color: hsla(0, 100%, 50%, 0.3); /* τιμή hsla με ποσοστά και a */
+
+ /* Εικόνες μπορούν να τοποθετηθούν στον φόντο ενός αντικειμένου */
+ background-image: url(/img-path/img.jpg);
+
+ /* Γραμματοσειρές */
+ font-family: Arial;
+ /* εάν η γραμματοσειρα περιέχει κενά */
+ font-family: "Courier New";
+ /* εάν η πρώτη γραμματοσειρα δε βρεθεί εγκατεστημένη στο Λειτουργικό Σύστυμα, αυτόματα
+ επιλέγετε η δεύτερη, κ.κ.ε. */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif;
+}
+```
+
+## Χρήση
+
+Αποθηκεύουμε ένα αρχείο CSS με την επέκταση `.css`.
+
+```xml
+<!-- Πρέπει να συμπεριλάβουμε το αρχείο στην επικεφαλίδα(head) ενος HTML αρχείου.
+ σσ. http://stackoverflow.com/questions/8284365 -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- Μπορούμε να το ενσωματώσουμε -->
+<style>
+ a { color: purple; }
+</style>
+
+<!-- Ή απευθείας σε κάποιο αντικείμενο (inline) -->
+<div style="border: 1px solid red;">
+</div>
+```
+
+## Ειδικότητα των κανόνων (Cascading απο το αγγλικό τίτλο Cascading Style Sheets)
+
+Ένα αντικείμενο μπορεί να στοχευθεί απο πολλούς κανόνες και μπορεί η ίδια ιδιότητα να
+περιλαμβάνετε σε πολλούς κανόνες. Σε αυτές της περιπτώσεις υπερισχύει πάντα ο πιο ειδικός
+κανόνας και απο αυτούς, αυτός που εμφανίζεται τελευταίος.
+
+```css
+/* A */
+p.class1[attr='value']
+
+/* B */
+p.class1 { }
+
+/* C */
+p.class2 { }
+
+/* D */
+p { }
+
+/* E */
+p { property: value !important; }
+```
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```
+
+Η σειρά θα είναι:
+
+* `E` έχει μεγαλύτερο βάρος λόγω του `!important`. Κάλες πρακτικές λένε να το αποφεύγουμε.
+* `F` επόμενο λόγω του inline κανόνα.
+* `A` επόμενο λόγω του το οτι είναι πιο ειδικό. Περιέχει τρεις selectors.
+* `C` επόμενο, λόγω του οτι εμφανίζεται μετα το Β και ας έχει την ίδια ειδικότητα.
+* `B` επόμενο.
+* `D` τελευταίο.
+
+## Συμβατότητα
+
+Τα περισσότερα απο τα παραπάνω ήδη υποστηρίζονται απο τους γνωστούς φυλλομετρητές. Άλλα θα πρέπει
+πάντα να ελέγχουμε πρωτου τους χρησιμοποιήσουμε.
+
+## Περισσότερα
+
+* Έλεγχος συμβατότητας, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
+
+## Μελέτη
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 4e2f1d84..d6ed7b86 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -292,7 +292,7 @@ calculateArea() ->
_ ->
io:format("We can only calculate area of rectangles or circles.")
end.
-
+
% Compile the module and create a process that evaluates `calculateArea` in the
% shell.
c(calculateGeometry).
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index 036d7082..d475cf42 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con
web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común
para front-end que Java.
-JavaScript no sólo se limita a los navegadores web, aunque: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
+Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
¡La retroalimentación es bienvenida! Puedes encontrarme en:
[@adambrenecki](https://twitter.com/adambrenecki), o
@@ -124,7 +124,7 @@ undefined; // usado para indicar que un valor no está presente actualmente
// (aunque undefined es un valor en sí mismo)
// false, null, undefined, NaN, 0 y "" es false; todo lo demás es true.
-// Note que 0 is false y "0" es true, a pesar de que 0 == "0".
+// Note que 0 es false y "0" es true, a pesar de que 0 == "0".
// Aunque 0 === "0" sí es false.
///////////////////////////////////
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
new file mode 100644
index 00000000..c7f581c0
--- /dev/null
+++ b/es-es/visualbasic-es.html.markdown
@@ -0,0 +1,286 @@
+---
+language: Visual Basic
+contributors:
+ - ["Brian Martin", "http://brianmartin.biz"]
+translators:
+ - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"]
+author: Brian Martin
+author_url: https://github.com/fitojb
+filename: learnvisualbasic-es.vb
+lang: es-es
+---
+
+```vb
+Module Module1
+
+ Sub Main()
+ ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes
+ ' de que profundicemos en el tema.
+ ' El apóstrofo inicia una línea de comentario.
+ ' Para explorar este tutorial dentro del Compilador de Visual Basic,
+ ' he creado un sistema de navegación.
+ ' Dicho sistema se explicará a medida que avancemos en este
+ ' tutorial; gradualmente entenderás lo que significa todo.
+ Console.Title = ("Aprende X en Y minutos")
+ Console.WriteLine("NAVEGACIÓN") 'Mostrar
+ Console.WriteLine("")
+ Console.ForegroundColor = ConsoleColor.Green
+ Console.WriteLine("1. Salida «Hola, mundo»")
+ Console.WriteLine("2. Entrada «Hola, mundo»")
+ Console.WriteLine("3. Calcular números enteros")
+ Console.WriteLine("4. Calcular números decimales")
+ Console.WriteLine("5. Una calculadora funcional")
+ Console.WriteLine("6. Uso de bucles «Do While»")
+ Console.WriteLine("7. Uso de bucles «For While»")
+ Console.WriteLine("8. Declaraciones condicionales")
+ Console.WriteLine("9. Selecciona una bebida")
+ Console.WriteLine("50. Acerca de")
+ Console.WriteLine("Elige un número de la lista anterior")
+ Dim selection As String = Console.ReadLine
+ Select Case selection
+ Case "1" 'Salida «hola, mundo»
+ Console.Clear() 'Limpia la consola y abre la subrutina privada
+ SalidaHolaMundo() 'Abre la subrutina privada nombrada
+ Case "2" 'Entrada «hola, mundo»
+ Console.Clear()
+ EntradaHolaMundo()
+ Case "3" 'Calcular números enteros
+ Console.Clear()
+ CalcularNumerosEnteros()
+ Case "4" 'Calcular números decimales
+ Console.Clear()
+ CalcularNumerosDecimales()
+ Case "5" 'Una calculadora funcional
+ Console.Clear()
+ CalculadoraFuncional()
+ Case "6" 'Uso de bucles «Do While»
+ Console.Clear()
+ UsoBuclesDoWhile()
+ Case "7" 'Uso de bucles «For While»
+ Console.Clear()
+ UsoBuclesFor()
+ Case "8" 'Declaraciones condicionales
+ Console.Clear()
+ DeclaracionCondicional()
+ Case "9" 'Declaración «If/Else»
+ Console.Clear()
+ DeclaracionIfElse() 'Selecciona una bebida
+ Case "50" 'Cuadro de mensaje «Acerca de»
+ Console.Clear()
+ Console.Title = ("Aprende X en Y minutos :: Acerca de")
+ MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn")
+ Console.Clear()
+ Main()
+ Console.ReadLine()
+
+ End Select
+ End Sub
+
+ 'Uno - He usado números para guiarme por el sistema de navegación anterior
+ 'cuando regrese posteriormente a implementarlo.
+
+ 'Usamos subrutinas privadas para separar distintas secciones del programa.
+ Private Sub SalidaHolaMundo()
+ 'Título de la aplicación de consola
+ Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos"
+ 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas.
+ 'Seguido por Console.Read(), o bien, Console.Readline()
+ 'Console.ReadLine() muestra la salida en la consola.
+ Console.WriteLine("Hola, mundo")
+ Console.ReadLine()
+ End Sub
+
+ 'Dos
+ Private Sub EntradaHolaMundo()
+ Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos"
+ ' Variables
+ ' Los datos que introduzca un usuario deben almacenarse.
+ ' Las variables también empiezan por Dim y terminan por As VariableType.
+
+ ' En este tutorial queremos conocer tu nombre y hacer que el programa
+ ' responda a este.
+ Dim nombredeusuario As String
+ 'Usamos «string» porque es una variable basada en texto.
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario.
+ Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre
+ Console.ReadLine() 'Muestra lo anterior.
+ 'El código anterior te hará una pregunta y mostrará la respuesta.
+ 'Entre otras variables está Integer, la cual usaremos para números enteros.
+ End Sub
+
+ 'Tres
+ Private Sub CalcularNumerosEnteros()
+ Console.Title = "Calcular números enteros | Aprende X en Y minutos"
+ Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc
+ Dim a As Integer = Console.ReadLine()
+ Console.Write("Segundo número: ") 'Escribe otro número entero.
+ Dim b As Integer = Console.ReadLine()
+ Dim c As Integer = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Lo anterior es una calculadora sencilla
+ End Sub
+
+ 'Cuatro
+ Private Sub CalcularNumerosDecimales()
+ Console.Title = "Calcular con tipo doble | Aprende X en Y minutos"
+ 'Por supuesto, nos gustaría sumar decimales.
+ 'Por ello podríamos cambiar del tipo Integer al Double.
+
+ 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ") 'Escribe el segundo número.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Este programa puede sumar 1.1 y 2.2
+ End Sub
+
+ 'Cinco
+ Private Sub CalculadoraFuncional()
+ Console.Title = "La calculadora funcional | Aprende X en Y minutos"
+ 'Pero si quieres que la calculadora reste, divida, multiplique y
+ 'sume.
+ 'Copia y pega lo anterior.
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ 'Mediante las líneas siguientes podremos restar,
+ 'multiplicar y dividir los valores a y b
+ Console.Write(a.ToString() + " + " + b.ToString())
+ 'Queremos dar un margen izquierdo de 3 espacios a los resultados.
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+
+ End Sub
+
+ 'Seis
+ Private Sub UsoBuclesDoWhile()
+ 'Igual que la subrutina privada anterior
+ 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?)
+ 'Usamos el bucle Do While porque no sabemos si el usuario quiere
+ 'usar el programa más de una vez.
+ Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos"
+ Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto
+ Do 'Comenzamos el programa con
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ Console.Write(a.ToString() + " + " + b.ToString())
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+ 'Preguntar si el usuario quiere continuar. Desafortunadamente,
+ 'distingue entre mayúsculas y minúsculas.
+ Console.Write("¿Quieres continuar? (s / n)")
+ 'El programa toma la variable, la muestra y comienza de nuevo.
+ respuesta = Console.ReadLine
+ 'La orden que hará funcionar esta variable es en este caso «s»
+ Loop While respuesta = "s"
+
+ End Sub
+
+ 'Siete
+ Private Sub UsoBuclesFor()
+ 'A veces el programa debe ejecutarse solo una vez.
+ 'En este programa contaremos a partir de 10.
+
+ Console.Title = "Uso de bucles «For» | Aprende X en Y minutos"
+ 'Declarar Variable y desde qué número debe contar en Step -1,
+ 'Step -2, Step -3, etc.
+ For i As Integer = 10 To 0 Step -1
+ Console.WriteLine(i.ToString) 'Muestra el valor del contador
+ Next i 'Calcular el valor nuevo
+ Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!!
+ Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :)
+ End Sub
+
+ 'Ocho
+ Private Sub DeclaracionCondicional()
+ Console.Title = "Declaraciones condicionales | Aprende X en Y minutos"
+ Dim nombredeUsuario As String = Console.ReadLine
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario.
+ If nombredeUsuario = "Adam" Then
+ Console.WriteLine("Hola, Adam")
+ Console.WriteLine("Gracias por crear este útil sitio web")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Hola, " + nombredeUsuario)
+ Console.WriteLine("¿Has visitado www.learnxinyminutes.com?")
+ Console.ReadLine() 'Termina y muestra la declaración anterior.
+ End If
+ End Sub
+
+ 'Nueve
+ Private Sub DeclaracionIfElse()
+ Console.Title = "Declaración «If / Else» | Aprende X en Y minutos"
+ 'A veces es importante considerar más de dos alternativas.
+ 'A veces, algunas de estas son mejores.
+ 'Cuando esto sucede, necesitaríamos más de una declaración «if».
+ 'Una declaración «if» es adecuada para máquinas expendedoras.
+ 'En las que el usuario escribe un código (A1, A2, A3) para elegir.
+ 'Pueden combinarse todas las elecciones en una sola declaración «if».
+
+ Dim seleccion As String = Console.ReadLine 'Valor de la selección
+ Console.WriteLine("A1. para 7Up")
+ Console.WriteLine("A2. para Fanta")
+ Console.WriteLine("A3. para Dr. Pepper")
+ Console.WriteLine("A4. para Coca-Cola")
+ Console.ReadLine()
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ Console.ReadLine()
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ Console.ReadLine()
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ Console.ReadLine()
+ ElseIf selection = "A4" Then
+ Console.WriteLine("coca-cola")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Selecciona un producto")
+ Console.ReadLine()
+ End If
+
+ End Sub
+
+End Module
+
+```
+
+## Referencias
+
+Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad.
+
+He creado un <a href="http://www.vbbootcamp.co.uk/" Title="Tutorial de Visual Basic">tutorial de Visual Basic</a> más exhaustivo para quienes quieran saber más.
+
+Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa.
diff --git a/forth.html.markdown b/forth.html.markdown
index f7c0bf34..b4a5581b 100644
--- a/forth.html.markdown
+++ b/forth.html.markdown
@@ -117,7 +117,7 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
15 0 threes \ 0 3 6 9 12 ok
-\ Indefinite loops with `begin` <stuff to do> <flag> `unil`:
+\ Indefinite loops with `begin` <stuff to do> <flag> `until`:
: death ( -- ) begin ." Are we there yet?" 0 until ; \ ok
\ ---------------------------- Variables and Memory ----------------------------
@@ -133,7 +133,7 @@ variable age \ ok
age @ . \ 21 ok
age ? \ 21 ok
-\ Constants are quite simiar, except we don't bother with memory addresses:
+\ Constants are quite similar, except we don't bother with memory addresses:
100 constant WATER-BOILING-POINT \ ok
WATER-BOILING-POINT . \ 100 ok
diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown
new file mode 100644
index 00000000..24be8bf9
--- /dev/null
+++ b/fr-fr/haml-fr.html.markdown
@@ -0,0 +1,157 @@
+---
+language: haml
+filename: learnhaml.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Thibault", "https://github.com/iTech-"]
+lang: fr-fr
+---
+
+Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage.
+
+Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire.
+
+Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes.
+
+$ haml fichier_entree.haml fichier_sortie.html
+
+
+```haml
+/ -------------------------------------------
+/ Indentation
+/ -------------------------------------------
+
+/
+ A cause de l'importance de l'indentation sur la manière dont votre code sera
+ converti, l'indentation doit être constante à travers votre document. Un
+ simple changement d'indentation entrainera une erreur. En général, on utilise
+ deux espaces, mais ce genre de décision sur l'indentation vous appartient, du
+ moment que vous vous y tenez.
+
+/ -------------------------------------------
+/ Commentaires
+/ -------------------------------------------
+
+/ Ceci est un commentaire en Haml.
+
+/
+ Pour écrire un commentaire sur plusieurs lignes, indentez votre code
+ commenté en le commençant par un slash
+
+-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier
+
+
+/ -------------------------------------------
+/ Eléments HTML
+/ -------------------------------------------
+
+/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise
+%body
+ %header
+ %nav
+
+/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci
+ <body>
+ <header>
+ <nav></nav>
+ </header>
+ </body>
+
+/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci
+.balise
+
+/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration
+%h1 Titre contenu
+
+/ Pour écrire du contenu sur plusieurs lignes, imbriquez le
+%p
+ Ce paragraphe contient beaucoup de contenu qui pourrait
+ probablement tenir sur deux lignes séparées.
+
+/
+ Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va
+ convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple
+
+%p
+ &= "Oui & oui"
+
+/ Produira 'Oui &amp; oui'
+
+/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant !=
+%p
+ != "Voici comment écrire une balise de paragraphe <p></p>"
+
+/ Cela produira 'Voici comment écrire une balise de paragraphe <p></p>'
+
+/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe
+%div.truc.machin
+
+/ ou en utilisant un hash de Ruby
+%div{:class => 'truc machin'}
+
+/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash
+%a{:href => '#', :class => 'machin', :title => 'Titre machin'}
+
+/ Pour affecter une valeur à un booléen, utilisez 'true'
+%input{:selected => true}
+
+/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash
+%div{:data => {:attribute => 'machin'}}
+
+
+/ -------------------------------------------
+/ Insérer du Ruby
+/ -------------------------------------------
+
+/
+ Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le
+ signe égal suivi du code Ruby
+
+%h1= livre.titre
+
+%p
+ = livre.auteur
+ = livre.editeur
+
+
+/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union
+- livres = ['livre 1', 'livre 2', 'livre 3']
+
+/ Ceci vous permet de faire des choses géniales comme des blocs Ruby
+- livre.shuffle.each_with_index do |livre, index|
+ %h1= livre
+
+ if livre do
+ %p Ceci est un livre
+
+/
+ Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même
+ pour Ruby.
+ L'indentation le fera pour vous.
+
+
+/ -------------------------------------------
+/ Ruby en-ligne / Interpolation en Ruby
+/ -------------------------------------------
+
+/ Inclure une variable Ruby dans une ligne en utilisant #{}
+%p Votre meilleur score est #{record}
+
+
+/ -------------------------------------------
+/ Filtres
+/ -------------------------------------------
+
+/
+ Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple
+ utiliser un filtre :javascript pour écrire du contenu en-ligne js
+
+:javascript
+ console.log('Ceci est la balise en-ligne <script>');
+
+```
+
+## Lectures complémentaires
+
+- [Qu'est-ce que HAML ?](http://haml.info/) - Une bonne introduction qui explique très bien les avantages d'utiliser HAML.
+- [Documentation officielle](http://haml.info/docs/yardoc/file.REFERENCE.html) - Si vous souhaitez en apprendre plus et aller plus loin.
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index 69f4d8f9..4e31c4bf 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -14,7 +14,7 @@ lang: fr-fr
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
-```objective_c
+```objective-c
// Les commentaires sur une seule ligne commencent par //
/*
diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown
new file mode 100644
index 00000000..f4eaf396
--- /dev/null
+++ b/fr-fr/php.html.markdown
@@ -0,0 +1,696 @@
+---
+language: PHP
+contributors:
+ - ["Malcolm Fell", "http://emarref.net/"]
+ - ["Trismegiste", "https://github.com/Trismegiste"]
+translators:
+ - ["Pascal Boutin", "http://pboutin.net/"]
+lang: fr-fr
+---
+
+This document describes PHP 5+.
+
+```php
+ // Le code PHP doit être placé à l'intérieur de balises '<?php'
+
+// Si votre fichier php ne contient que du code PHP, il est
+// généralement recommandé de ne pas fermer la balise '?>'
+
+// Deux barres obliques amorcent un commentaire simple.
+
+# Le dièse aussi, bien que les barres obliques soient plus courantes
+
+/*
+ Les barres obliques et les astérisques peuvent être utilisés
+ pour faire un commentaire multi-lignes.
+*/
+
+// Utilisez "echo" ou "print" afficher une sortie
+print('Hello '); // Affiche "Hello " sans retour à la ligne
+
+// Les parenthèses sont facultatives pour print et echo
+echo "World\n"; // Affiche "World" avec un retour à la ligne
+
+// toutes les instructions doivent se terminer par un point-virgule
+
+// Tout ce qui se trouve en dehors des <?php ?> est automatiquement
+// affiché en sortie
+Hello World Again!
+<?php
+
+
+/************************************
+ * Types & Variables
+ */
+
+// Les noms de variables débutent par le symbole $
+// Un nom de variable valide commence par une lettre ou un souligné,
+// suivi de n'importe quelle lettre, nombre ou de soulignés.
+
+// Les valeurs booléenes ne sont pas sensibles à la casse
+$boolean = true; // ou TRUE ou True
+$boolean = false; // ou FALSE ou False
+
+// Entiers (integers)
+$int1 = 12; // => 12
+$int2 = -12; // => -12
+$int3 = 012; // => 10 (un 0 devant la valeur désigne une valeur octale)
+$int4 = 0x0F; // => 15 (un 0x devant la valeur désigne une valeur hexadécimale)
+
+// Réels (floats, doubles)
+$float = 1.234;
+$float = 1.2e3;
+$float = 7E-10;
+
+// Suppression d'une variable
+unset($int1);
+
+// Arithmétique
+$sum = 1 + 1; // 2 (addition)
+$difference = 2 - 1; // 1 (soustraction)
+$product = 2 * 2; // 4 (produit)
+$quotient = 2 / 1; // 2 (division)
+
+// Arithmétique (raccourcis)
+$number = 0;
+$number += 2; // Incrémente $number de 2
+echo $number++; // Affiche 2 (incrémente après l'évaluation)
+echo ++$number; // Affiche 4 (incrémente avant l'évaluation)
+$number /= $float; // Divise et assigne le quotient à $number
+
+// Les chaînes de caractères (strings) doivent être à
+// l'intérieur d'une paire d'apostrophes
+$sgl_quotes = '$String'; // => '$String'
+
+// Évitez les guillemets sauf pour inclure le contenu d'une autre variable
+$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
+
+// Les caractères spéciaux sont seulement échappés avec des guillemets
+$escaped = "This contains a \t tab character.";
+$unescaped = 'This just contains a slash and a t: \t';
+
+// En cas de besoin, placez la variable dans des accolades
+$money = "I have $${number} in the bank.";
+
+// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes
+// multi-lignes non-interprétées
+$nowdoc = <<<'END'
+Multi line
+string
+END;
+
+// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées
+$heredoc = <<<END
+Multi line
+$sgl_quotes
+END;
+
+// La concaténation de chaînes se fait avec un .
+echo 'This string ' . 'is concatenated';
+
+
+/********************************
+ * Constantes
+ */
+
+// Une constante est déclarée avec define()
+// et ne peut jamais être changée durant l'exécution
+
+// un nom valide de constante commence par une lettre ou un souligné,
+// suivi de n'importe quelle lettre, nombre ou soulignés.
+define("FOO", "something");
+
+// on peut accéder à une constante en utilisant directement son nom
+echo 'This outputs '.FOO;
+
+
+/********************************
+ * Tableaux (array)
+ */
+
+// Tous les tableaux en PHP sont associatifs (hashmaps),
+
+// Fonctionne dans toutes les versions de PHP
+$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
+
+// PHP 5.4 a introduit une nouvelle syntaxe
+$associative = ['One' => 1, 'Two' => 2, 'Three' => 3];
+
+echo $associative['One']; // affiche 1
+
+// Dans une liste simple, l'index est automatiquement attribué en tant que clé
+$array = ['One', 'Two', 'Three'];
+echo $array[0]; // => "One"
+
+// Ajoute un élément à la fin du tableau
+$array[] = 'Four';
+
+// Retrait d'un élément du tableau
+unset($array[3]);
+
+/********************************
+ * Affichage
+ */
+
+echo('Hello World!');
+// Affiche Hello World! dans stdout.
+// Stdout est la page web si on exécute depuis un navigateur.
+
+print('Hello World!'); // Pareil à "écho"
+
+// Pour écho, vous n'avez pas besoin des parenthèses
+echo 'Hello World!';
+print 'Hello World!'; // Pour print non plus
+
+$paragraph = 'paragraph';
+
+echo 100; // Affichez un scalaire directement
+echo $paragraph; // ou des variables
+
+// Si le raccourci de sortie est configuré, ou si votre version de PHP est
+// 5.4.0+, vous pouvez utiliser ceci:
+?>
+<p><?= $paragraph ?></p>
+<?php
+
+$x = 1;
+$y = 2;
+$x = $y; // $x contient maintenant la même valeur que $y
+$z = &$y;
+// $z contient une référence vers $y. Changer la valeur de
+// $z changerait également la valeur de $y, et vice-versa.
+// $x resterait inchangé comme la valeur initiale de $y
+
+echo $x; // => 2
+echo $z; // => 2
+$y = 0;
+echo $x; // => 2
+echo $z; // => 0
+
+// Affiche le type et la valeur de la variable dans stdout
+var_dump($z); // prints int(0)
+
+// Affiche la variable dans stdout dans un format plus convivial
+print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three )
+
+/********************************
+ * Logique
+ */
+$a = 0;
+$b = '0';
+$c = '1';
+$d = '1';
+
+// assert affiche un avertissement dans son argument n'est pas vrai
+
+// Ces comparaisons vont toujours être vraies, même si leurs
+// types ne sont pas les mêmes.
+assert($a == $b); // égalité
+assert($c != $a); // inégalité
+assert($c <> $a); // inégalité (moins courant)
+assert($a < $c);
+assert($c > $b);
+assert($a <= $b);
+assert($c >= $d);
+
+// Ces comparaisons vont seulement être vraies si les types concordent.
+assert($c === $d);
+assert($a !== $d);
+assert(1 === '1');
+assert(1 !== '1');
+
+// Opérateur 'spaceship' depuis PHP 7
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 0 car ils sont égaux
+echo $a <=> $b; // -1 car $a < $b
+echo $b <=> $a; // 1 car $b > $a
+
+// Les variables peuvent être transtypées dépendamment de leur usage.
+
+$integer = 1;
+echo $integer + $integer; // => 2
+
+$string = '1';
+echo $string + $string; // => 2
+
+$string = 'one';
+echo $string + $string; // => 0
+// Donne 0 car l'opérateur + ne peut pas transtyper la chaîne 'one' en un nombre
+
+// On peut également transtyper manuellement pour utiliser
+// une variable dans un autre type
+
+$boolean = (boolean) 1; // => true
+
+$zero = 0;
+$boolean = (boolean) $zero; // => false
+
+// Il y a également des fonctions dédiées pour transtyper
+$integer = 5;
+$string = strval($integer);
+
+$var = null; // Valeur nulle
+
+
+/********************************
+ * Structures de contrôle
+ */
+
+if (true) {
+ print 'Je suis affiché';
+}
+
+if (false) {
+ print 'Je ne le suis pas';
+} else {
+ print 'Je suis affiché';
+}
+
+if (false) {
+ print 'Je ne suis pas affiché';
+} elseif (true) {
+ print 'Je le suis';
+}
+
+// Opérateur ternaire
+print (false ? 'N\'est pas affiché' : 'L\'est');
+
+// Opérateur ternaire depuis PHP 5.3
+// équivalent de $x ? $x : 'Does'
+$x = false;
+print($x ?: 'Does');
+
+// depuis PHP 7, on peut facilement vérifier si une valeur est nulle
+$a = null;
+$b = 'Hello World';
+echo $a ?? 'a is not set'; // Affiche 'a is not set'
+echo $b ?? 'b is not set'; // Affiche 'Hello World'
+
+
+$x = 0;
+if ($x === '0') {
+ print 'Pas affiché';
+} elseif($x == '1') {
+ print 'Pas affiché';
+} else {
+ print 'Affiché';
+}
+
+
+// Cette syntaxe alternative est particulièrement utile avec du HTML:
+?>
+
+<?php if ($x): ?>
+<p>Ceci est affiché si $x est vrai</p>
+<?php else: ?>
+<p>Ceci est affiché si $x est faux</p>
+<?php endif; ?>
+
+<?php
+
+// On peut également utiliser une condition multiple (switch case)
+switch ($x) {
+ case '0':
+ print 'Les switch font du transtypage implicite';
+ break; // Il est important de déclaré un 'break', sinon les cas
+ // 'two' et 'three' seront évalués
+ case 'two':
+ case 'three':
+ // Si $x == 'two' || $x == 'three'
+ break;
+ default:
+ // Si aucun cas n'a été vrai
+}
+
+// Structures itératives (for, while, do while)
+$i = 0;
+while ($i < 5) {
+ echo $i++;
+}; // Affiche "01234"
+
+echo "\n";
+
+$i = 0;
+do {
+ echo $i++;
+} while ($i < 5); // Affiche "01234"
+
+echo "\n";
+
+for ($x = 0; $x < 10; $x++) {
+ echo $x;
+} // Affiche "0123456789"
+
+echo "\n";
+
+$wheels = ['bicycle' => 2, 'car' => 4];
+
+// Les boucles 'foreach' sont utiles pour parcourir les tableaux
+foreach ($wheels as $wheel_count) {
+ echo $wheel_count;
+} // Affiche "24"
+
+echo "\n";
+
+// Il est également possible d'accéder aux clés du tableau
+foreach ($wheels as $vehicle => $wheel_count) {
+ echo "The $vehicle have $wheel_count wheels";
+}
+
+echo "\n";
+
+$i = 0;
+while ($i < 5) {
+ if ($i === 3) {
+ break; // Permet d'arrêter la boucle
+ }
+ echo $i++;
+} // Affiche "012"
+
+for ($i = 0; $i < 5; $i++) {
+ if ($i === 3) {
+ continue; // Permet de passer immédiatement à l'itération suivante
+ }
+ echo $i;
+} // Affiche "0124"
+
+
+/********************************
+ * Fonctions
+ */
+
+// On peut déclarer une fonction avec le mot clé 'function'
+function my_function () {
+ return 'Hello';
+}
+
+echo my_function(); // => "Hello"
+
+
+// Les noms de fonction débutent par le symbole $
+// Un nom de variable valide commence par une lettre ou un souligné,
+// suivi de n'importe quelle lettre, nombre ou de soulignés.
+
+function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1
+ $result = $x + $y;
+ return $result;
+}
+
+echo add(4); // => 5
+echo add(4, 2); // => 6
+
+// $result n'est pas accessible en dehors de la fonction
+// print $result; // Retourne un avertissement
+
+// Depuis PHP 5.3 on peut déclarer des fonctions anonymes
+$inc = function ($x) {
+ return $x + 1;
+};
+
+echo $inc(2); // => 3
+
+function foo ($x, $y, $z) {
+ echo "$x - $y - $z";
+}
+
+// Une fonction peut retourner une fonction
+function bar ($x, $y) {
+ // On peut utiliser 'use' pour passer des variables externes
+ return function ($z) use ($x, $y) {
+ foo($x, $y, $z);
+ };
+}
+
+$bar = bar('A', 'B');
+$bar('C'); // Affiche "A - B - C"
+
+// On peut exécuter une fonction par son nom en chaîne de caractères
+$function_name = 'add';
+echo $function_name(1, 2); // => 3
+// Utile pour déterminer par programmation quelle fonction exécuter.
+
+// On peut également utiliser
+call_user_func(callable $callback [, $parameter [, ... ]]);
+
+/********************************
+ * Insertions
+ */
+
+<?php
+// Le PHP se trouvant dans un fichier inclus doit
+// également commencer par une balise PHP.
+
+include 'my-file.php';
+// Le code se trouvant dans my-file.php est maintenant disponible dans
+// le contexte courant. Si le fichier ne peut pas être inclus
+// (ex. non trouvé), un avertissement sera émit.
+
+include_once 'my-file.php';
+// Si le code dans my-file.php a déjà été inclus ailleur, il ne va pas
+// être inclus de nouveau.
+
+require 'my-file.php';
+require_once 'my-file.php';
+// Même comportement que include() mais déclenche une érreur fatale si le fichier ne peux pas être inclus.
+
+// Contenu de my-include.php:
+<?php
+
+return 'Anything you like.';
+// Fin de my-include.php
+
+// include() et require() peuvent également retourner une valeur
+$value = include('my-include.php');
+
+// Les fichiers sont inclus depuis le chemin donné ou, si aucun chemin n'est donné,
+// la configuration 'include_path'. Si le fichier n'est pas trouvé dans le 'include_path',
+// include va finalement vérifier dans le répertoire courant avant d'échouer.
+
+/********************************
+ * Classes
+ */
+
+// Les classes sont définies avec le mot clé 'class'
+
+class MyClass
+{
+ const MY_CONST = 'value'; // Une constante
+
+ static $staticVar = 'static';
+
+ // Variables statiques et leur visibilité
+ public static $publicStaticVar = 'publicStatic';
+ // Accessible à l'intérieur de la classe seulement
+ private static $privateStaticVar = 'privateStatic';
+ // Accessible à l'intérieur de la classe et des classes enfants
+ protected static $protectedStaticVar = 'protectedStatic';
+
+ // Les attributs doivent définir leur visibilité
+ public $property = 'public';
+ public $instanceProp;
+ protected $prot = 'protected';
+ private $priv = 'private';
+
+ // Déclaration d'un constructeur avec __construct
+ public function __construct($instanceProp) {
+ // Access instance variables with $this
+ $this->instanceProp = $instanceProp;
+ }
+
+ // Les méthodes sont déclarés par des fonctions au sein de la classe
+ public function myMethod()
+ {
+ print 'MyClass';
+ }
+
+ // le mot clé 'final' rend la function impossible à surcharger
+ final function youCannotOverrideMe()
+ {
+ }
+
+/*
+ * Les attributs et méthodes statiques peuvent être accédés sans devoir
+ * instancier la classe. Les attributs statiques ne sont pas accessibles depuis
+ * une instance, même si les méthodes statiques le sont.
+ */
+
+ public static function myStaticMethod()
+ {
+ print 'I am static';
+ }
+}
+
+// Les constantes d'une classe peuvent toujours être utilisé de façon statique
+echo MyClass::MY_CONST; // Outputs 'value';
+
+echo MyClass::$staticVar; // Retourne 'static';
+MyClass::myStaticMethod(); // Retourne 'I am static';
+
+// On peut instancier une classe en utilisant le mot clé 'new'
+$my_class = new MyClass('An instance property');
+
+// On peut accéder aux attributs/méthodes d'une instance avec ->
+echo $my_class->property; // => "public"
+echo $my_class->instanceProp; // => "An instance property"
+$my_class->myMethod(); // => "MyClass"
+
+
+// On peut hériter d'une classe en utilisant 'extends'
+class MyOtherClass extends MyClass
+{
+ function printProtectedProperty()
+ {
+ echo $this->prot;
+ }
+
+ // Surcharge d'une méthode
+ function myMethod()
+ {
+ parent::myMethod();
+ print ' > MyOtherClass';
+ }
+}
+
+$my_other_class = new MyOtherClass('Instance prop');
+$my_other_class->printProtectedProperty(); // => Retourne "protected"
+$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass"
+
+// On peut empêcher qu'une classe soit héritée
+final class YouCannotExtendMe
+{
+}
+
+// On peut utiliser des "méthodes magiques" pour se faire des accesseurs
+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; // Va utiliser la méthode __get()
+$x->property = 'Something'; // Va utiliser la méthode __set()
+
+// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou
+// elle peuvent implémenter une interface (en utilisant le mot clé 'implement').
+
+// Une interface peut être déclarée avec le mot clé 'interface'
+
+interface InterfaceOne
+{
+ public function doSomething();
+}
+
+interface InterfaceTwo
+{
+ public function doSomethingElse();
+}
+
+// Les interfaces peuvent hériter d'autres interfaces
+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';
+ }
+}
+
+
+// Les classes peuvent implémenter plusieurs interfaces à la fois
+class SomeOtherClass implements InterfaceOne, InterfaceTwo
+{
+ public function doSomething()
+ {
+ echo 'doSomething';
+ }
+
+ public function doSomethingElse()
+ {
+ echo 'doSomethingElse';
+ }
+}
+
+/********************************
+ * Espaces de noms (namespaces)
+ */
+
+// Cette section est séparée, car une déclaration d'espace de nom doit être
+// la première chose que l'on retrouve dans un fichier PHP,
+// imaginons que c'est le cas
+
+<?php
+
+// Par défaut, les classes existent dans l'espace de nom global et peuvent
+// être appelé explicitement avec un antislash.
+
+$cls = new \MyClass();
+
+
+
+// On peut spécifier l'espace de nom d'un fichier comme cela
+namespace My\Namespace;
+
+class MyClass
+{
+}
+
+// (depuis un autre fichier...)
+$cls = new My\Namespace\MyClass;
+
+// Ou depuis un autre espace de nom
+namespace My\Other\Namespace;
+
+use My\Namespace\MyClass;
+
+$cls = new MyClass();
+
+// On peut également utiliser un alias sur un espace de nom
+
+namespace My\Other\Namespace;
+
+use My\Namespace as SomeOtherNamespace;
+
+$cls = new SomeOtherNamespace\MyClass();
+
+*/
+
+```
+
+## Pour plus d'informations
+
+Visitez la [documentation officielle](http://www.php.net/manual/fr).
+
+Si vous êtes intéressé par les bonnes pratiques, visitez
+[PHP The Right Way](http://www.phptherightway.com/) (anglais seulement).
+
+Si vous êtes habitué à utiliser de bons gestionaires de dépendances, regardez
+[Composer](http://getcomposer.org/).
+
+Pour consulter les standards, visitez "the PHP Framework Interoperability Groups"
+[PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown
new file mode 100644
index 00000000..04d0a55d
--- /dev/null
+++ b/fr-fr/python3-fr.html.markdown
@@ -0,0 +1,723 @@
+---
+language: python3
+contributors:
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
+translators:
+ - ["Gnomino", "https://github.com/Gnomino"]
+filename: learnpython3-fr.py
+lang: fr-fr
+---
+
+Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des
+langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe.
+C'est tout simplement du pseudo-code exécutable.
+
+L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service]
+
+Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7
+
+```python
+
+# Un commentaire d'une ligne commence par un dièse
+
+""" Les chaînes de caractères peuvent être écrites
+ avec 3 guillemets doubles ("), et sont souvent
+ utilisées comme des commentaires.
+"""
+
+####################################################
+## 1. Types de données primaires et opérateurs
+####################################################
+
+# On a des nombres
+3 # => 3
+
+# Les calculs sont ce à quoi on s'attend
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+
+# Sauf pour la division qui retourne un float (nombre à virgule flottante)
+35 / 5 # => 7.0
+
+# Résultats de divisions entières tronqués pour les nombres positifs et négatifs
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Quand on utilise un float, le résultat est un float
+3 * 2.0 # => 6.0
+
+# Modulo (reste de la division)
+7 % 3 # => 1
+
+# Exponentiation (x**y, x élevé à la puissance y)
+2**4 # => 16
+
+# Forcer la priorité de calcul avec des parenthèses
+(1 + 3) * 2 # => 8
+
+# Les valeurs booléennes sont primitives
+True
+False
+
+# Négation avec not
+not True # => False
+not False # => True
+
+# Opérateurs booléens
+# On note que "and" et "or" sont sensibles à la casse
+True and False #=> False
+False or True #=> True
+
+# Utilisation des opérations booléennes avec des entiers :
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# On vérifie une égalité avec ==
+1 == 1 # => True
+2 == 1 # => False
+
+# On vérifie une inégalité avec !=
+1 != 1 # => False
+2 != 1 # => True
+
+# Autres opérateurs de comparaison
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# On peut enchaîner les comparaisons
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie
+# si les objets ont la même valeur.
+a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4]
+b = a # b pointe sur a
+b is a # => True, a et b pointent sur le même objet
+b == a # => True, les objets a et b sont égaux
+b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4]
+b is a # => False, a et b ne pointent pas sur le même objet
+b == a # => True, les objets a et b ne pointent pas sur le même objet
+
+# Les chaînes (ou strings) sont créées avec " ou '
+"Ceci est une chaine"
+'Ceci est une chaine aussi.'
+
+# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire.
+"Hello " + "world!" # => "Hello world!"
+# On peut aussi le faire sans utiliser '+'
+"Hello " "world!" # => "Hello world!"
+
+# On peut traîter une chaîne comme une liste de caractères
+"This is a string"[0] # => 'T'
+
+# .format peut être utilisé pour formatter des chaînes, comme ceci:
+"{} peuvent etre {}".format("Les chaînes", "interpolées")
+
+# On peut aussi réutiliser le même argument pour gagner du temps.
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
+# On peut aussi utiliser des mots clés pour éviter de devoir compter.
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+
+# Si votre code doit aussi être compatible avec Python 2.5 et moins,
+# vous pouvez encore utiliser l'ancienne syntaxe :
+"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille")
+
+
+# None est un objet
+None # => None
+
+# N'utilisez pas "==" pour comparer des objets à None
+# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets.
+"etc" is None # => False
+None is None # => True
+
+# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens.
+# Toutes les autres valeurs valent True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+
+
+####################################################
+## 2. Variables et Collections
+####################################################
+
+# Python a une fonction print pour afficher du texte
+print("I'm Python. Nice to meet you!")
+
+# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin.
+# Utilisez l'argument optionnel end pour changer ce caractère de fin.
+print("Hello, World", end="!") # => Hello, World!
+
+# Pas besoin de déclarer des variables avant de les définir.
+# La convention est de nommer ses variables avec des minuscules_et_underscores
+some_var = 5
+some_var # => 5
+
+# Tenter d'accéder à une variable non définie lève une exception.
+# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions.
+une_variable_inconnue # Lève une NameError
+
+# Les listes permettent de stocker des séquences
+li = []
+# On peut initialiser une liste pré-remplie
+other_li = [4, 5, 6]
+
+# On ajoute des objets à la fin d'une liste avec .append
+li.append(1) # li vaut maintenant [1]
+li.append(2) # li vaut maintenant [1, 2]
+li.append(4) # li vaut maintenant [1, 2, 4]
+li.append(3) # li vaut maintenant [1, 2, 4, 3]
+# On enlève le dernier élément avec .pop
+li.pop() # => 3 et li vaut maintenant [1, 2, 4]
+# Et on le remet
+li.append(3) # li vaut de nouveau [1, 2, 4, 3]
+
+# Accès à un élément d'une liste :
+li[0] # => 1
+# Accès au dernier élément :
+li[-1] # => 3
+
+# Accéder à un élément en dehors des limites lève une IndexError
+li[4] # Lève une IndexError
+
+# On peut accéder à une intervalle avec la syntaxe "slice"
+# (c'est un rang du type "fermé/ouvert")
+li[1:3] # => [2, 4]
+# Omettre les deux premiers éléments
+li[2:] # => [4, 3]
+# Prendre les trois premiers
+li[:3] # => [1, 2, 4]
+# Sélectionner un élément sur deux
+li[::2] # =>[1, 4]
+# Avoir une copie de la liste à l'envers
+li[::-1] # => [3, 4, 2, 1]
+# Pour des "slices" plus élaborées :
+# li[debut:fin:pas]
+
+# Faire une copie d'une profondeur de un avec les "slices"
+li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False.
+
+# Enlever des éléments arbitrairement d'une liste
+del li[2] # li is now [1, 2, 3]
+
+# On peut additionner des listes
+# Note: les valeurs de li et other_li ne sont pas modifiées.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concaténer des listes avec "extend()"
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# Vérifier la présence d'un objet dans une liste avec "in"
+1 in li # => True
+
+# Examiner la longueur avec "len()"
+len(li) # => 6
+
+
+# Les tuples sont comme des listes mais sont immuables.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Lève une TypeError
+
+# Note : un tuple de taille un doit avoir une virgule après le dernier élément,
+# mais ce n'est pas le cas des tuples d'autres tailles, même zéro.
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
+
+# On peut utiliser la plupart des opérations des listes sur des tuples.
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# Vous pouvez décomposer des tuples (ou des listes) dans des variables
+a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3
+# Les tuples sont créés par défaut sans parenthèses
+d, e, f = 4, 5, 6
+# Voyez comme il est facile d'intervertir deux valeurs :
+e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4
+
+
+# Créer un dictionnaire :
+empty_dict = {}
+# Un dictionnaire pré-rempli :
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Note : les clés des dictionnaires doivent être de types immuables.
+# Elles doivent être convertibles en une valeur constante pour une recherche rapide.
+# Les types immuables incluent les ints, floats, strings et tuples.
+invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type.
+
+# On trouve une valeur avec []
+filled_dict["one"] # => 1
+
+# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer
+# de list() pour avoir une liste Note: l'ordre n'est pas garanti.
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
+
+# On obtient toutes les valeurs sous forme d'un itérable avec "values()".
+# Là aussi, il faut utiliser list() pour avoir une liste.
+# Note : l'ordre n'est toujours pas garanti.
+list(filled_dict.values()) # => [3, 2, 1]
+
+
+# On vérifie la présence d'une clé dans un dictionnaire avec "in"
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# L'accès à une clé non-existente lève une KeyError
+filled_dict["four"] # KeyError
+
+# On utilise "get()" pour éviter la KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante.
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente.
+filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5
+
+# Ajouter à un dictionnaire
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 # une autre méthode
+
+# Enlever des clés d'un dictionnaire avec del
+del filled_dict["one"] # Enlever la clé "one" de filled_dict.
+
+
+# Les sets stockent des ensembles
+empty_set = set()
+# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé.
+some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4}
+
+# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables.
+invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
+
+# On peut changer un set :
+filled_set = some_set
+
+# Ajouter un objet au set :
+filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5}
+
+# Chercher les intersections de deux sets avec &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# On fait l'union de sets avec |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# On fait la différence de deux sets avec -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# On vérifie la présence d'un objet dans un set avec in
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+
+####################################################
+## 3. Structures de contrôle et Itérables
+####################################################
+
+# On crée juste une variable
+some_var = 5
+
+# Voici une condition "si". L'indentation est significative en Python!
+# Affiche: "some_var is smaller than 10"
+if some_var > 10:
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # La clause elif ("sinon si") est optionelle
+ print("some_var is smaller than 10.")
+else: # La clause else ("sinon") l'est aussi.
+ print("some_var is indeed 10.")
+
+
+"""
+Les boucles "for" itèrent sur une liste
+Affiche:
+ chien est un mammifère
+ chat est un mammifère
+ souris est un mammifère
+"""
+for animal in ["chien", "chat", "souris"]:
+ # On peut utiliser format() pour interpoler des chaînes formattées
+ print("{} est un mammifère".format(animal))
+
+"""
+"range(nombre)" retourne un itérable de nombres
+de zéro au nombre donné
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+"range(debut, fin)" retourne un itérable de nombre
+de debut à fin.
+Affiche:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(debut, fin, pas)" retourne un itérable de nombres
+de début à fin en incrémentant de pas.
+Si le pas n'est pas indiqué, la valeur par défaut est 1.
+Affiche:
+ 4
+ 6
+ 8
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
+Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse.
+Affiche:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # Raccourci pour x = x + 1
+
+# On gère les exceptions avec un bloc try/except
+try:
+ # On utilise "raise" pour lever une erreur
+ raise IndexError("Ceci est une erreur d'index")
+except IndexError as e:
+ pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici.
+except (TypeError, NameError):
+ pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps.
+else: # Clause optionelle des blocs try/except. Doit être après tous les except.
+ print("Tout va bien!") # Uniquement si aucune exception n'est levée.
+finally: # Éxécuté dans toutes les circonstances.
+ print("On nettoie les ressources ici")
+
+# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Python offre une abstraction fondamentale : l'Iterable.
+# Un itérable est un objet pouvant être traîté comme une séquence.
+# L'objet retourné par la fonction range() est un itérable.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable
+
+# On peut boucler dessus
+for i in our_iterable:
+ print(i) # Affiche one, two, three
+
+# Cependant, on ne peut pas accéder aux éléments par leur adresse.
+our_iterable[1] # Lève une TypeError
+
+# Un itérable est un objet qui sait créer un itérateur.
+our_iterator = iter(our_iterable)
+
+# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse.
+# On passe à l'élément suivant avec "next()".
+next(our_iterator) #=> "one"
+
+# Il garde son état quand on itère.
+next(our_iterator) #=> "two"
+next(our_iterator) #=> "three"
+
+# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator
+next(our_iterator) # Lève une StopIteration
+
+# On peut mettre tous les éléments d'un itérateur dans une liste avec list()
+list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+
+
+####################################################
+## 4. Fonctions
+####################################################
+
+# On utilise "def" pour créer des fonctions
+def add(x, y):
+ print("x est {} et y est {}".format(x, y))
+ return x + y # On retourne une valeur avec return
+
+# Appel d'une fonction avec des paramètres :
+add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11
+
+# Une autre manière d'appeller une fonction : avec des arguments
+add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre.
+
+# Définir une fonction qui prend un nombre variable d'arguments
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+# On peut aussi définir une fonction qui prend un nombre variable de paramètres.
+def keyword_args(**kwargs):
+ return kwargs
+
+# Appelons la pour voir ce qu'il se passe :
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# On peut aussi faire les deux à la fois :
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) affiche:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# En appelant des fonctions, on peut aussi faire l'inverse :
+# utiliser * pour étendre un tuple de paramètres
+# et ** pour étendre un dictionnaire d'arguments.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # équivalent à foo(1, 2, 3, 4)
+all_the_args(**kwargs) # équivalent à foo(a=3, b=4)
+all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4)
+
+# Retourne plusieurs valeurs (avec un tuple)
+def swap(x, y):
+ return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses.
+ # (Note: on peut aussi utiliser des parenthèses)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses
+
+# Portée des fonctions :
+x = 5
+
+def setX(num):
+ # La variable locale x n'est pas la même que la variable globale x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # la variable globale x est maintenant 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# Python a des fonctions de première classe
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# Mais aussi des fonctions anonymes
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# TODO - Fix for iterables
+# Il y a aussi des fonctions de base
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+
+# On peut utiliser les compréhensions de listes pour de jolies maps et filtres.
+# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée.
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+####################################################
+## 5. Classes
+####################################################
+
+
+# On utilise l'opérateur "classe" pour définir une classe
+class Human:
+
+ # Un attribut de la classe. Il est partagé par toutes les instances de la classe.
+ species = "H. sapiens"
+
+ # L'initialiseur de base. Il est appelé quand la classe est instanciée.
+ # Note : les doubles underscores au début et à la fin sont utilisés pour
+ # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur.
+ # Les méthodes (ou objets ou attributs) comme: __init__, __str__,
+ # __repr__ etc. sont appelés méthodes magiques.
+ # Vous ne devriez pas inventer de noms de ce style.
+ def __init__(self, name):
+ # Assigner l'argument à l'attribut de l'instance
+ self.name = name
+
+ # Une méthode de l'instance. Toutes prennent "self" comme premier argument.
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
+
+ # Une méthode de classe est partagée avec entre les instances
+ # Ils sont appelés avec la classe comme premier argument
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Une méthode statique est appelée sans référence à une instance ni à une classe.
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Instantier une classe
+i = Human(name="Ian")
+print(i.say("hi")) # affiche "Ian: hi"
+
+j = Human("Joel")
+print(j.say("hello")) # affiche "Joel: hello"
+
+# Appeller notre méthode de classe
+i.get_species() # => "H. sapiens"
+
+# Changer les attributs partagés
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# Appeller la méthode statique
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. Modules
+####################################################
+
+# On peut importer des modules
+import math
+print(math.sqrt(16)) # => 4
+
+# On peut importer des fonctions spécifiques d'un module
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# On peut importer toutes les fonctions d'un module
+# Attention: ce n'est pas recommandé.
+from math import *
+
+# On peut raccourcir un nom de module
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Les modules Python sont juste des fichiers Python.
+# Vous pouvez écrire les vôtres et les importer. Le nom du module
+# est le nom du fichier.
+
+# On peut voir quels fonctions et objets un module définit
+import math
+dir(math)
+
+
+####################################################
+## 7. Avancé
+####################################################
+
+# Les générateurs aident à faire du code paresseux (lazy)
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Un générateur crée des valeurs à la volée.
+# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque
+# itération. Cela signifie que les valeurs supérieures à 15 ne seront pas traîtées par
+# double_numbers.
+# Note : range est un générateur aussi.
+# Créer une liste 1-900000000 prendrait beaucoup de temps
+# On met un underscore à la fin d'un nom de variable normalement réservé par Python.
+range_ = range(1, 900000000)
+# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Decorateurs
+# Dans cet exemple, beg enveloppe say
+# Beg appellera say. Si say_please vaut True le message retourné sera changé
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # affiche Can you buy me a beer?
+print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :(
+```
+
+## Prêt pour encore plus ?
+
+### En ligne et gratuit (en anglais)
+
+* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [The Official Docs](http://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+* [Python Course](http://www.python-course.eu/index.php)
+* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+
+### Livres (en anglais)
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown
index a43edf16..c6d06361 100644
--- a/fr-fr/scala.html.markdown
+++ b/fr-fr/scala.html.markdown
@@ -208,6 +208,7 @@ sSquared.reduce (_+_)
// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et
// sélectionne tous les éléments qui satisfont ce prédicat
List(1, 2, 3) filter (_ > 2) // List(3)
+case class Person(name: String, age: Int)
List(
Person(name = "Dom", age = 23),
Person(name = "Bob", age = 30)
@@ -217,6 +218,7 @@ List(
// Scala a une méthode foreach définie pour certaines collections
// qui prend en argument une fonction renvoyant Unit (une méthode void)
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
@@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique.
// mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus
// facile pour comprendre et pour faire la parallélisation
+i = 0
// La boucle do while
do {
println("x is still less then 10");
- x += 1
-} while (x < 10)
+ i += 1
+} while (i < 10)
// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala.
@@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com"
"Les chaînes de caractères Scala sont entourées de doubles guillements"
'a' // Un caractère de Scala
-'Les simples guillemets n'existent pas en Scala // Erreur
+// 'Les simples guillemets n'existent pas en Scala' // Erreur
"Les chaînes de caractères possèdent les méthodes usuelles de Java".length
"Il y a aussi quelques méthodes extra de Scala.".reverse
diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
index 43b1df54..1e8296d3 100644
--- a/fr-fr/yaml-fr.html.markdown
+++ b/fr-fr/yaml-fr.html.markdown
@@ -8,113 +8,117 @@ lang: fr-fr
Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
représentation de données par sérialisation, conçu pour être aisément
-éditable et lisible par nous même, les humains.
+modifiable et lisible par nous-mêmes, les humains.
-YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages.
+YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le
+découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont
+il est un parent naturel. Toutefois, YAML emprunte également des idées et
+concepts de Python, et s'intègre bien avec bon nombre de langages.
+Contrairement à ce dernier, YAML interdit l'utilisation des tabulations.
```yaml
-# les Commentaires sont précédés d'un signe "#", comme cette ligne.
+# Les commentaires sont précédés d'un signe "#", comme cette ligne.
#############
# SCALAIRES #
#############
-# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
-# ( listes ou tableaux associatifs ).
+# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
+# (listes ou tableaux associatifs).
-# Notre objet root ( racine ), sera une map ( carte ) et englobera
-# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
+# Notre objet root (racine), sera une map (carte) et englobera
+# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
# hash ou objet dans d'autres langages.
clé: valeur
-aurtre_clé: une autre valeur
+autre_clé: une autre valeur
valeur_numérique: 100
notation_scientifique: 1e+12
-boolean: true
+booléen: true
valeur_null: null
clé avec espaces: valeur
-# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
+# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères
# entre guillemets, cela reste possible, et parfois utile.
toutefois: "Une chaîne, peut être contenue entre guillemets."
-"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé."
+"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé."
-# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
-# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ).
+# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
+# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>').
bloc_littéral: |
- Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral',
- avec préservation des retours à la ligne. ( chaque ligne vide à
- l'intérieur du même bloc, sera remplacée par "\n\n" )
+ Tout ce bloc de texte sera la valeur de la clé "bloc_littéral",
+ avec préservation des retours à la ligne.
Le littéral continue jusqu'à ce que l'indentation soit annulée.
- Toutes lignes qui serait "d'avantage indentées" conservent leur
+ Toutes lignes qui seraient "davantage indentées" conservent leur
indentation, constituée de 4 espaces.
bloc_replié: >
- Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais
- cette fois ci, toutes les nouvelles lignes deviendront un simple espace.
+ Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais
+ cette fois-ci, toutes les nouvelles lignes deviendront un simple espace.
- Les lignes vides, comme ci-dessus, seront converties en caractère "\n".
+ Les lignes vides, comme ci-dessus, seront converties en caractère de
+ nouvelle ligne.
- Les lignes 'plus-indentées' gardent leurs retours à la ligne -
+ Les lignes "plus-indentées" gardent leurs retours à la ligne -
ce texte apparaîtra sur deux lignes.
###############
# COLLECTIONS #
###############
-# l'Imbrication est créée par indentation.
+# L'imbrication est créée par indentation.
une_map_imbriquée:
clé: valeur
autre_clé: autre valeur
autre_map_imbriquée:
bonjour: bonjour
-# les Clés des Maps ne sont pas nécessairement des chaînes de caractères.
-0.25: une clé de type float
+# Les clés des maps ne sont pas nécessairement des chaînes de caractères.
+0.25: une clé de type flottant
-# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
+# Les clés peuvent également être des objets s'étendant sur plusieurs lignes,
# en utilisant le signe "?" pour indiquer le début de la clé.
? |
- ceci est une Clé
+ ceci est une clé
sur de multiples lignes
-: et ceci est sa Valeur
+: et ceci est sa valeur
# YAML autorise aussi l'usage des collections à l'intérieur des clés,
# mais certains langages de programmation ne le tolère pas si bien.
-# les Séquences (équivalent des listes ou tableaux) ressemblent à cela:
+# Les séquences (équivalent des listes ou tableaux) ressemblent à cela :
une_séquence:
- - Item 1
- - Item 2
+ - Objet 1
+ - Objet 2
- 0.5 # les séquences peuvent contenir des types variés.
- - Item 4
+ - Objet 4
- clé: valeur
autre_clé: autre_valeur
-
- Ceci est une séquence
- dans une autre séquence
-# YAML étant un proche parent de JSON, vous pouvez écrire directement
+# YAML étant un proche parent de JSON, vous pouvez écrire directement
# des maps et séquences façon JSON
json_map: {"clé": "valeur"}
json_seq: [1, 2, 3, "soleil"]
-#################################
+################################
# AUTRES FONCTIONNALITÉES YAML #
-#################################
+################################
-# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci
+# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci
# vous permet de dupliquer aisément du contenu au sein de votre document.
-# Les deux clés suivantes auront la même valeur:
+# Les deux clés suivantes auront la même valeur :
contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
autre_ancre: *nom_ancre
-# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données.
+# Avec les tags YAML, vous pouvez explicitement déclarer des types de données.
chaine_explicite: !!str 0.5
-# Certains parsers implémentent des tags spécifiques à d'autres langages,
-# comme par exemple le "complex number" de Python.
+# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à
+# d'autres langages, comme par exemple celui des nombres complexes de Python.
python_complex_number: !!python/complex 1+2j
#####################
@@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j
#####################
# YAML interprète également les données formatées ISO de type date et datetime,
-# pas seulement les chaînes et nombres.
+# pas seulement les chaînes et nombres.
datetime: 2001-12-15T02:59:43.1Z
datetime_avec_espaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
@@ -135,14 +139,14 @@ fichier_gif: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML a de même un type "set", qui ressemble à cela:
+# YAML a de même un type "set", semblable à ceci :
set:
? item1
? item2
? item3
# Comme dans Python, les sets ne sont que des maps contenant des valeurs null ;
-# le set précédent est l'équivalent du suivant:
+# le set précédent est l'équivalent du suivant :
set2:
item1: null
item2: null
@@ -152,6 +156,6 @@ set2:
Quelques références et outils :
-- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
+- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
-- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
+- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 49951c78..76318d7d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -5,7 +5,7 @@ contributors:
filename: learnfsharp.fs
---
-F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
+F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language.
@@ -90,7 +90,7 @@ let simplePatternMatch =
| _ -> printfn "x is something else" // underscore matches anything
// F# doesn't allow nulls by default -- you must use an Option type
-// and then pattern match.
+// and then pattern match.
// Some(..) and None are roughly analogous to Nullable wrappers
let validValue = Some(99)
let invalidValue = None
@@ -115,39 +115,39 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
// into a string, similar to String.Format in C#.
// ================================================
-// More on functions
+// More on functions
// ================================================
// F# is a true functional language -- functions are first
-// class entities and can be combined easy to make powerful
+// class entities and can be combined easily to make powerful
// constructs
// Modules are used to group functions together
// Indentation is needed for each nested module.
-module FunctionExamples =
+module FunctionExamples =
// define a simple adding function
let add x y = x + y
-
+
// basic usage of a function
let a = add 1 2
printfn "1+2 = %i" a
-
+
// partial application to "bake in" parameters
let add42 = add 42
let b = add42 1
printfn "42+1 = %i" b
-
+
// composition to combine functions
let add1 = add 1
let add2 = add 2
let add3 = add1 >> add2
let c = add3 7
printfn "3+7 = %i" c
-
+
// higher order functions
[1..10] |> List.map add3 |> printfn "new list is %A"
-
+
// lists of functions, and more
let add6 = [add1; add2; add3] |> List.reduce (>>)
let d = add6 7
@@ -158,54 +158,54 @@ module FunctionExamples =
// ================================================
// There are three types of ordered collection:
-// * Lists are most basic immutable collection.
-// * Arrays are mutable and more efficient when needed.
-// * Sequences are lazy and infinite (e.g. an enumerator).
+// * Lists are most basic immutable collection.
+// * Arrays are mutable and more efficient when needed.
+// * Sequences are lazy and infinite (e.g. an enumerator).
//
// Other collections include immutable maps and sets
// plus all the standard .NET collections
-module ListExamples =
+module ListExamples =
- // lists use square brackets
+ // lists use square brackets
let list1 = ["a";"b"]
let list2 = "c" :: list1 // :: is prepending
let list3 = list1 @ list2 // @ is concat
-
+
// list comprehensions (aka generators)
- let squares = [for i in 1..10 do yield i*i]
+ let squares = [for i in 1..10 do yield i*i]
// prime number generator
let rec sieve = function
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
| [] -> []
let primes = sieve [2..50]
- printfn "%A" primes
-
+ printfn "%A" primes
+
// pattern matching for lists
- let listMatcher aList =
+ let listMatcher aList =
match aList with
- | [] -> printfn "the list is empty"
- | [first] -> printfn "the list has one element %A " first
- | [first; second] -> printfn "list is %A and %A" first second
- | _ -> printfn "the list has more than two elements"
+ | [] -> printfn "the list is empty"
+ | [first] -> printfn "the list has one element %A " first
+ | [first; second] -> printfn "list is %A and %A" first second
+ | _ -> printfn "the list has more than two elements"
listMatcher [1;2;3;4]
listMatcher [1;2]
listMatcher [1]
- listMatcher []
+ listMatcher []
// recursion using lists
- let rec sum aList =
+ let rec sum aList =
match aList with
| [] -> 0
| x::xs -> x + sum xs
sum [1..10]
-
- // -----------------------------------------
- // Standard library functions
+
+ // -----------------------------------------
+ // Standard library functions
// -----------------------------------------
-
+
// map
let add3 x = x + 3
[1..10] |> List.map add3
@@ -213,68 +213,68 @@ module ListExamples =
// filter
let even x = x % 2 = 0
[1..10] |> List.filter even
-
+
// many more -- see documentation
-
-module ArrayExamples =
+
+module ArrayExamples =
// arrays use square brackets with bar
let array1 = [| "a";"b" |]
let first = array1.[0] // indexed access using dot
-
+
// pattern matching for arrays is same as for lists
- let arrayMatcher aList =
+ let arrayMatcher aList =
match aList with
- | [| |] -> printfn "the array is empty"
- | [| first |] -> printfn "the array has one element %A " first
- | [| first; second |] -> printfn "array is %A and %A" first second
- | _ -> printfn "the array has more than two elements"
+ | [| |] -> printfn "the array is empty"
+ | [| first |] -> printfn "the array has one element %A " first
+ | [| first; second |] -> printfn "array is %A and %A" first second
+ | _ -> printfn "the array has more than two elements"
arrayMatcher [| 1;2;3;4 |]
// Standard library functions just as for List
-
- [| 1..10 |]
+
+ [| 1..10 |]
|> Array.map (fun i -> i+3)
|> Array.filter (fun i -> i%2 = 0)
|> Array.iter (printfn "value is %i. ")
-
-
-module SequenceExamples =
+
+
+module SequenceExamples =
// sequences use curly braces
let seq1 = seq { yield "a"; yield "b" }
-
- // sequences can use yield and
+
+ // sequences can use yield and
// can contain subsequences
let strange = seq {
// "yield! adds one element
yield 1; yield 2;
-
+
// "yield!" adds a whole subsequence
- yield! [5..10]
+ yield! [5..10]
yield! seq {
- for i in 1..10 do
+ for i in 1..10 do
if i%2 = 0 then yield i }}
- // test
- strange |> Seq.toList
-
+ // test
+ strange |> Seq.toList
+
// Sequences can be created using "unfold"
// Here's the fibonacci series
let fib = Seq.unfold (fun (fst,snd) ->
Some(fst + snd, (snd, fst + snd))) (0,1)
- // test
+ // test
let fib10 = fib |> Seq.take 10 |> Seq.toList
- printf "first 10 fibs are %A" fib10
-
-
+ printf "first 10 fibs are %A" fib10
+
+
// ================================================
-// Data Types
+// Data Types
// ================================================
-module DataTypeExamples =
+module DataTypeExamples =
// All data is immutable by default
@@ -282,33 +282,33 @@ module DataTypeExamples =
// -- Use a comma to create a tuple
let twoTuple = 1,2
let threeTuple = "a",2,true
-
+
// Pattern match to unpack
let x,y = twoTuple //sets x=1 y=2
- // ------------------------------------
- // Record types have named fields
- // ------------------------------------
+ // ------------------------------------
+ // Record types have named fields
+ // ------------------------------------
// Use "type" with curly braces to define a record type
type Person = {First:string; Last:string}
-
- // Use "let" with curly braces to create a record
+
+ // Use "let" with curly braces to create a record
let person1 = {First="John"; Last="Doe"}
// Pattern match to unpack
let {First=first} = person1 //sets first="john"
- // ------------------------------------
+ // ------------------------------------
// Union types (aka variants) have a set of choices
// Only case can be valid at a time.
- // ------------------------------------
+ // ------------------------------------
// Use "type" with bar/pipe to define a union type
- type Temp =
+ type Temp =
| DegreesC of float
| DegreesF of float
-
+
// Use one of the cases to create one
let temp1 = DegreesF 98.6
let temp2 = DegreesC 37.0
@@ -317,29 +317,29 @@ module DataTypeExamples =
let printTemp = function
| DegreesC t -> printfn "%f degC" t
| DegreesF t -> printfn "%f degF" t
-
- printTemp temp1
+
+ printTemp temp1
printTemp temp2
- // ------------------------------------
+ // ------------------------------------
// Recursive types
- // ------------------------------------
+ // ------------------------------------
- // Types can be combined recursively in complex ways
+ // Types can be combined recursively in complex ways
// without having to create subclasses
- type Employee =
+ type Employee =
| Worker of Person
| Manager of Employee list
let jdoe = {First="John";Last="Doe"}
let worker = Worker jdoe
-
- // ------------------------------------
+
+ // ------------------------------------
// Modelling with types
- // ------------------------------------
-
+ // ------------------------------------
+
// Union types are great for modelling state without using flags
- type EmailAddress =
+ type EmailAddress =
| ValidEmailAddress of string
| InvalidEmailAddress of string
@@ -350,40 +350,40 @@ module DataTypeExamples =
// The combination of union types and record types together
// provide a great foundation for domain driven design.
- // You can create hundreds of little types that accurately
+ // You can create hundreds of little types that accurately
// reflect the domain.
type CartItem = { ProductCode: string; Qty: int }
type Payment = Payment of float
type ActiveCartData = { UnpaidItems: CartItem list }
type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
-
- type ShoppingCart =
+
+ type ShoppingCart =
| EmptyCart // no data
| ActiveCart of ActiveCartData
- | PaidCart of PaidCartData
+ | PaidCart of PaidCartData
- // ------------------------------------
+ // ------------------------------------
// Built in behavior for types
- // ------------------------------------
+ // ------------------------------------
// Core types have useful "out-of-the-box" behavior, no coding needed.
// * Immutability
// * Pretty printing when debugging
// * Equality and comparison
// * Serialization
-
+
// Pretty printing using %A
- printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
+ printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
twoTuple person1 temp1 worker
// Equality and comparison built in.
// Here's an example with cards.
type Suit = Club | Diamond | Spade | Heart
- type Rank = Two | Three | Four | Five | Six | Seven | Eight
- | Nine | Ten | Jack | Queen | King | Ace
+ type Rank = Two | Three | Four | Five | Six | Seven | Eight
+ | Nine | Ten | Jack | Queen | King | Ace
- let hand = [ Club,Ace; Heart,Three; Heart,Ace;
+ let hand = [ Club,Ace; Heart,Three; Heart,Ace;
Spade,Jack; Diamond,Two; Diamond,Ace ]
// sorting
@@ -391,27 +391,27 @@ module DataTypeExamples =
List.max hand |> printfn "high card is %A"
List.min hand |> printfn "low card is %A"
-
+
// ================================================
// Active patterns
// ================================================
-module ActivePatternExamples =
+module ActivePatternExamples =
- // F# has a special type of pattern matching called "active patterns"
- // where the pattern can be parsed or detected dynamically.
+ // F# has a special type of pattern matching called "active patterns"
+ // where the pattern can be parsed or detected dynamically.
// "banana clips" are the syntax for active patterns
-
+
// for example, define an "active" pattern to match character types...
- let (|Digit|Letter|Whitespace|Other|) ch =
+ let (|Digit|Letter|Whitespace|Other|) ch =
if System.Char.IsDigit(ch) then Digit
else if System.Char.IsLetter(ch) then Letter
else if System.Char.IsWhiteSpace(ch) then Whitespace
- else Other
+ else Other
// ... and then use it to make parsing logic much clearer
- let printChar ch =
+ let printChar ch =
match ch with
| Digit -> printfn "%c is a Digit" ch
| Letter -> printfn "%c is a Letter" ch
@@ -424,52 +424,52 @@ module ActivePatternExamples =
// -----------------------------------
// FizzBuzz using active patterns
// -----------------------------------
-
+
// You can create partial matching patterns as well
// Just use undercore in the defintion, and return Some if matched.
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
// the main function
- let fizzBuzz i =
+ let fizzBuzz i =
match i with
- | MultOf3 & MultOf5 -> printf "FizzBuzz, "
- | MultOf3 -> printf "Fizz, "
- | MultOf5 -> printf "Buzz, "
+ | MultOf3 & MultOf5 -> printf "FizzBuzz, "
+ | MultOf3 -> printf "Fizz, "
+ | MultOf5 -> printf "Buzz, "
| _ -> printf "%i, " i
-
+
// test
- [1..20] |> List.iter fizzBuzz
-
+ [1..20] |> List.iter fizzBuzz
+
// ================================================
-// Conciseness
+// Conciseness
// ================================================
-module AlgorithmExamples =
+module AlgorithmExamples =
- // F# has a high signal/noise ratio, so code reads
+ // F# has a high signal/noise ratio, so code reads
// almost like the actual algorithm
// ------ Example: define sumOfSquares function ------
- let sumOfSquares n =
+ let sumOfSquares n =
[1..n] // 1) take all the numbers from 1 to n
|> List.map square // 2) square each one
|> List.sum // 3) sum the results
- // test
- sumOfSquares 100 |> printfn "Sum of squares = %A"
-
- // ------ Example: define a sort function ------
+ // test
+ sumOfSquares 100 |> printfn "Sum of squares = %A"
+
+ // ------ Example: define a sort function ------
let rec sort list =
match list with
- // If the list is empty
- | [] ->
+ // If the list is empty
+ | [] ->
[] // return an empty list
- // If the list is not empty
- | firstElem::otherElements -> // take the first element
- let smallerElements = // extract the smaller elements
+ // If the list is not empty
+ | firstElem::otherElements -> // take the first element
+ let smallerElements = // extract the smaller elements
otherElements // from the remaining ones
- |> List.filter (fun e -> e < firstElem)
+ |> List.filter (fun e -> e < firstElem)
|> sort // and sort them
let largerElements = // extract the larger ones
otherElements // from the remaining ones
@@ -479,13 +479,13 @@ module AlgorithmExamples =
List.concat [smallerElements; [firstElem]; largerElements]
// test
- sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
+ sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
// ================================================
// Asynchronous Code
// ================================================
-module AsyncExample =
+module AsyncExample =
// F# has built-in features to help with async code
// without encountering the "pyramid of doom"
@@ -495,23 +495,23 @@ module AsyncExample =
open System.Net
open System
open System.IO
- open Microsoft.FSharp.Control.CommonExtensions
+ open Microsoft.FSharp.Control.CommonExtensions
// Fetch the contents of a URL asynchronously
- let fetchUrlAsync url =
- async { // "async" keyword and curly braces
+ let fetchUrlAsync url =
+ async { // "async" keyword and curly braces
// creates an "async" object
- let req = WebRequest.Create(Uri(url))
- use! resp = req.AsyncGetResponse()
+ let req = WebRequest.Create(Uri(url))
+ use! resp = req.AsyncGetResponse()
// use! is async assignment
- use stream = resp.GetResponseStream()
+ use stream = resp.GetResponseStream()
// "use" triggers automatic close()
// on resource at end of scope
- use reader = new IO.StreamReader(stream)
- let html = reader.ReadToEnd()
- printfn "finished downloading %s" url
+ use reader = new IO.StreamReader(stream)
+ let html = reader.ReadToEnd()
+ printfn "finished downloading %s" url
}
-
+
// a list of sites to fetch
let sites = ["http://www.bing.com";
"http://www.google.com";
@@ -520,7 +520,7 @@ module AsyncExample =
"http://www.yahoo.com"]
// do it
- sites
+ sites
|> List.map fetchUrlAsync // make a list of async tasks
|> Async.Parallel // set up the tasks to run in parallel
|> Async.RunSynchronously // start them off
@@ -529,58 +529,58 @@ module AsyncExample =
// .NET compatability
// ================================================
-module NetCompatibilityExamples =
+module NetCompatibilityExamples =
// F# can do almost everything C# can do, and it integrates
// seamlessly with .NET or Mono libraries.
// ------- work with existing library functions -------
-
+
let (i1success,i1) = System.Int32.TryParse("123");
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
// ------- Implement interfaces on the fly! -------
-
+
// create a new object that implements IDisposable
- let makeResource name =
- { new System.IDisposable
+ let makeResource name =
+ { new System.IDisposable
with member this.Dispose() = printfn "%s disposed" name }
- let useAndDisposeResources =
+ let useAndDisposeResources =
use r1 = makeResource "first resource"
- printfn "using first resource"
+ printfn "using first resource"
for i in [1..3] do
let resourceName = sprintf "\tinner resource %d" i
- use temp = makeResource resourceName
- printfn "\tdo something with %s" resourceName
+ use temp = makeResource resourceName
+ printfn "\tdo something with %s" resourceName
use r2 = makeResource "second resource"
- printfn "using second resource"
- printfn "done."
+ printfn "using second resource"
+ printfn "done."
// ------- Object oriented code -------
-
+
// F# is also a fully fledged OO language.
// It supports classes, inheritance, virtual methods, etc.
// interface with generic type
- type IEnumerator<'a> =
+ type IEnumerator<'a> =
abstract member Current : 'a
- abstract MoveNext : unit -> bool
+ abstract MoveNext : unit -> bool
// abstract base class with virtual methods
[<AbstractClass>]
- type Shape() =
+ type Shape() =
//readonly properties
abstract member Width : int with get
abstract member Height : int with get
//non-virtual method
member this.BoundingArea = this.Height * this.Width
//virtual method with base implementation
- abstract member Print : unit -> unit
+ abstract member Print : unit -> unit
default this.Print () = printfn "I'm a shape"
- // concrete class that inherits from base class and overrides
- type Rectangle(x:int, y:int) =
+ // concrete class that inherits from base class and overrides
+ type Rectangle(x:int, y:int) =
inherit Shape()
override this.Width = x
override this.Height = y
@@ -590,20 +590,20 @@ module NetCompatibilityExamples =
let r = Rectangle(2,3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
- r.Print()
+ r.Print()
// ------- extension methods -------
-
+
//Just as in C#, F# can extend existing classes with extension methods.
type System.String with
member this.StartsWithA = this.StartsWith "A"
//test
let s = "Alice"
- printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
-
+ printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
+
// ------- events -------
-
+
type MyButton() =
let clickEvent = new Event<_>()
@@ -615,11 +615,11 @@ module NetCompatibilityExamples =
// test
let myButton = new MyButton()
- myButton.OnClick.Add(fun (sender, arg) ->
+ myButton.OnClick.Add(fun (sender, arg) ->
printfn "Click event with arg=%O" arg)
myButton.TestEvent("Hello World!")
-
+
```
## More Information
diff --git a/git.html.markdown b/git.html.markdown
index b1347309..971d53e4 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Leo Rudberg" , "http://github.com/LOZORD"]
- ["Betsy Lorton" , "http://github.com/schbetsy"]
+ - ["Bruno Volcov", "http://github.com/volcov"]
filename: LearnGit.txt
---
@@ -76,6 +77,11 @@ other repositories, or not!
A branch is essentially a pointer to the last commit you made. As you go on
committing, this pointer will automatically update to point the latest commit.
+### Tag
+
+A tag is a mark on specific point in history. Typically people use this
+functionality to mark release points (v1.0, and so on)
+
### HEAD and head (component of .git dir)
HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD.
@@ -206,6 +212,28 @@ $ git branch -m myBranchName myNewBranchName
$ git branch myBranchName --edit-description
```
+### tag
+
+Manage your tags
+
+```bash
+# List tags
+$ git tag
+# Create a annotated tag
+# The -m specifies a tagging message,which is stored with the tag.
+# If you don’t specify a message for an annotated tag,
+# Git launches your editor so you can type it in.
+$ git tag -a v2.0 -m 'my version 2.0'
+# Show info about tag
+# That shows the tagger information, the date the commit was tagged,
+# and the annotation message before showing the commit information.
+$ git show v2.0
+# Push a single tag to remote
+$ git push origin v2.0
+# Push a lot of tags to remote
+$ git push origin --tags
+```
+
### checkout
Updates all files in the working tree to match the version in the index, or specified tree.
@@ -484,6 +512,8 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
+
* [git-scm - Video Tutorials](http://git-scm.com/videos)
* [git-scm - Documentation](http://git-scm.com/docs)
diff --git a/go.html.markdown b/go.html.markdown
index 34b855e3..a857a76c 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -10,6 +10,7 @@ contributors:
- ["Quint Guvernator", "https://github.com/qguv"]
- ["Jose Donizetti", "https://github.com/josedonizetti"]
- ["Alexej Friesen", "https://github.com/heyalexej"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -115,7 +116,7 @@ can include line breaks.` // Same string type.
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
// To append another slice, instead of list of atomic elements we can
// pass a reference to a slice or a slice literal like this, with a
- // trailing elipsis, meaning take a slice and unpack its elements,
+ // trailing ellipsis, meaning take a slice and unpack its elements,
// appending them to slice s.
s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
@@ -129,7 +130,7 @@ can include line breaks.` // Same string type.
m["one"] = 1
// Unused variables are an error in Go.
- // The underbar lets you "use" a variable but discard its value.
+ // The underscore lets you "use" a variable but discard its value.
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
// Output of course counts as using a variable.
fmt.Println(s, c, a4, s3, d2, m)
@@ -164,7 +165,7 @@ func expensiveComputation() float64 {
}
func learnFlowControl() {
- // If statements require brace brackets, and do not require parens.
+ // If statements require brace brackets, and do not require parentheses.
if true {
fmt.Println("told ya")
}
@@ -407,6 +408,8 @@ func requestServer() {
The root of all things Go is the [official Go web site](http://golang.org/).
There you can follow the tutorial, play interactively, and read lots.
+Aside from a tour, [the docs](https://golang.org/doc/) contain information on
+how to write clean and effective Go code, package and command docs, and release history.
The language definition itself is highly recommended. It's easy to read
and amazingly short (as language definitions go these days.)
@@ -420,3 +423,5 @@ idioms. Or you can click on a function name in [the
documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
+
+Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information.
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 519f36ce..492c1ba2 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -99,7 +99,7 @@ technologies.sort()
// To sort without mutating original, you can do:
sortedTechnologies = technologies.sort( false )
-/*** Manipulating Lists ***/
+/*** Manipulating Lists ***/e
//Replace all elements in the list
Collections.replaceAll(technologies, 'Gradle', 'gradle')
@@ -200,6 +200,14 @@ def y = 10
def x = (y > 1) ? "worked" : "failed"
assert x == "worked"
+//Groovy supports 'The Elvis Operator' too!
+//Instead of using the ternary operator:
+
+displayName = user.name ? user.name : 'Anonymous'
+
+//We can write it:
+displayName = user.name ?: 'Anonymous'
+
//For loop
//Iterate over a range
def x = 0
@@ -422,6 +430,3 @@ Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html)
[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html
-
-
-
diff --git a/hack.html.markdown b/hack.html.markdown
index b9730dc0..b3d19f8e 100644
--- a/hack.html.markdown
+++ b/hack.html.markdown
@@ -51,7 +51,7 @@ function identity(?string $stringOrNull) : ?string
class TypeHintedProperties
{
public ?string $name;
-
+
protected int $id;
private float $score = 100.0;
@@ -91,7 +91,7 @@ function openBox(Box<int> $box) : int
// Shapes
-//
+//
// Hack adds the concept of shapes for defining struct-like arrays with a
// guaranteed, type-checked set of keys
type Point2D = shape('x' => int, 'y' => int);
@@ -108,7 +108,7 @@ distance(
// Type aliasing
-//
+//
// Hack adds a bunch of type aliasing features for making complex types readable
newtype VectorArray = array<int, Vector<int>>;
@@ -142,7 +142,7 @@ function getRoadType() : RoadType
// Constructor argument promotion
-//
+//
// To avoid boilerplate property and constructor definitions that only set
// properties, Hack adds a concise syntax for defining properties and a
// constructor at the same time.
@@ -171,12 +171,12 @@ class WithoutArgumentPromotion
// Co-operative multi-tasking
-//
+//
// Two new keywords "async" and "await" can be used to perform multi-tasking
// Note that this does not involve threads - it just allows transfer of control
async function cooperativePrint(int $start, int $end) : Awaitable<void>
{
- for ($i = $start; $i <= $end; $i++) {
+ for ($i = $start; $i <= $end; $i++) {
echo "$i ";
// Give other tasks a chance to do something
@@ -193,9 +193,9 @@ AwaitAllWaitHandle::fromArray([
// Attributes
-//
+//
// Attributes are a form of metadata for functions. Hack provides some
-// special built-in attributes that introduce useful behaviour.
+// special built-in attributes that introduce useful behaviour.
// The __Memoize special attribute causes the result of a function to be cached
<<__Memoize>>
@@ -248,7 +248,7 @@ class ConsistentBar extends ConsistentFoo
class InvalidFooSubclass extends ConsistentFoo
{
// Not matching the parent constructor will cause a type checker error:
- //
+ //
// "This object is of type ConsistentBaz. It is incompatible with this object
// of type ConsistentFoo because some of their methods are incompatible"
//
@@ -259,7 +259,7 @@ class InvalidFooSubclass extends ConsistentFoo
// Using the __Override annotation on a non-overriden method will cause a
// type checker error:
- //
+ //
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
// parent definition found or overridden parent is defined in non-<?hh code"
//
diff --git a/haml.html.markdown b/haml.html.markdown
index aed3dcae..0948e9ef 100644
--- a/haml.html.markdown
+++ b/haml.html.markdown
@@ -62,11 +62,11 @@ $ haml input_file.haml output_file.html
%h1 Headline copy
/ To write multiline content, nest it instead
-%p
+%p
This is a lot of content that we could probably split onto two
separate lines.
-/
+/
You can escape html by using the ampersand and equals sign ( &= ). This
converts html-sensitive characters (&, /, :) into their html encoded
equivalents. For example
@@ -102,7 +102,7 @@ $ haml input_file.haml output_file.html
/ Inserting Ruby
/ -------------------------------------------
-/
+/
To output a Ruby value as the contents of a tag, use an equals sign followed
by the Ruby code
@@ -122,11 +122,36 @@ $ haml input_file.haml output_file.html
if book do
%p This is a book
+
+/ Adding ordered / unordered list
+%ul
+ %li
+ =item1
+ =item2
/
Again, no need to add the closing tags to the block, even for the Ruby.
Indentation will take care of that for you.
+/ -------------------------------------------
+/ Inserting Table with bootstrap classes
+/ -------------------------------------------
+
+%table.table.table-hover
+ %thead
+ %tr
+ %th Header 1
+ %th Header 2
+
+ %tr
+ %td Value1
+ %td value2
+
+ %tfoot
+ %tr
+ %td
+ Foot value
+
/ -------------------------------------------
/ Inline Ruby / Ruby interpolation
@@ -141,7 +166,7 @@ $ haml input_file.haml output_file.html
/ -------------------------------------------
/
- Use the colon to define Haml filters, one example of a filter you can
+ Use the colon to define Haml filters, one example of a filter you can
use is :javascript, which can be used for writing inline js
:javascript
diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby.html.markdown
new file mode 100644
index 00000000..169f2b8e
--- /dev/null
+++ b/hu-hu/ruby.html.markdown
@@ -0,0 +1,555 @@
+---
+language: ruby
+lang: hu-hu
+filenev: learnruby.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ translators:
+ - ["Zsolt Prontvai", "https://github.com/prozsolt"]
+---
+
+```ruby
+# Ez egy komment
+
+=begin
+Ez egy többsoros komment
+Senki sem használja
+Neked sem kellene
+=end
+
+# Először is: Minden objektum
+
+# A számok objektumok
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Néhány alapvető számtani művelet
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# A számtani művelet csak szintaktikus cukor
+# az objektumon történő függvény hívásra
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# A speciális értékek objektumok
+nil # Nincs itt semmi látnivaló
+true # igaz
+false # hamis
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Egyenlőség
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Egyenlőtlenség
+1 != 1 #=> false
+2 != 1 #=> true
+
+# A false-on kívül, nil az egyetlen hamis érték
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Még több összehasonlítás
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Logikai operátorok
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb
+# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak
+# amíg egyikük igaz vagy hamis értékkel nem tér vissza.
+
+# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel
+# tért vissza.
+csinalj_valamit() and csinalj_valami_mast()
+# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel
+# tért vissza.
+csinalj_valamit() or log_error()
+
+
+# A sztringek objektumok
+
+'Én egy sztring vagyok'.class #=> String
+"Én is egy sztring vagyok".class #=> String
+
+helykitolto = 'interpolációt használhatok'
+"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem"
+#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem"
+
+# A szimpla idézőjelet preferáljuk, ahol csak lehet,
+# mert a dupla idézőjel extra számításokat végez.
+
+# Kombinálhatunk sztringeket, de nem számokkal
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# kiírás a kimenetre
+puts "Írok"
+
+# Változók
+x = 25 #=> 25
+x #=> 25
+
+# Értékadás az adott értékkel tér vissza
+# Ez azt jelenti, hogy használhatunk többszörös értékadást:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Konvencióból, snake_case változó neveket használj
+snake_case = true
+
+# Leíró változó neveket használj
+ut_a_projekt_gyokerehez = '/jo/nev/'
+ut = '/rossz/nev/'
+
+# A szimbólumok (objektumok)
+# A szimbólumok megváltoztathatatlan, újra felhasználható konstans,
+# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják,
+# hogy effektíven közvetítsünk konkrét, értelmes értékeket
+
+:fuggoben.class #=> Symbol
+
+statusz = :fuggoben
+
+statusz == :fuggoben #=> true
+
+statusz == 'fuggoben' #=> false
+
+statusz == :jovahagyott #=> false
+
+# Tömbök
+
+# Ez egy tömb
+tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# A tömmbök különböző tipusú dolgokat tartalmazhat
+
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Tömbök indexelhetőek
+# Az elejéről
+tomb[0] #=> 1
+tomb[12] #=> nil
+
+# Akárcsak a számtani műveletek [var] hozzáférés
+# is csak szintaktikus cukor
+# a [] függvény hívására az objektumon
+tomb.[] 0 #=> 1
+tomb.[] 12 #=> nil
+
+# A végéről
+tomb[-1] #=> 5
+
+# Kezdőértékkel és hosszal
+tomb[2, 3] #=> [3, 4, 5]
+
+# Tömb megfordítása
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Vagy tartománnyal
+tomb[1..3] #=> [2, 3, 4]
+
+# Így adhatunk a tömbhöz
+tomb << 6 #=> [1, 2, 3, 4, 5, 6]
+# Vagy így
+tomb.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Ellenőrízük, hogy a tömb tartalmaz egy elemet
+tomb.include?(1) #=> true
+
+# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal
+# Hash-eket kapcsos zárójellel jelöljük
+hash = { 'szin' => 'zold', 'szam' => 5 }
+
+hash.keys #=> ['szin', 'szam']
+
+# Hash-ekben könnyen kreshetünk a kulcs segítségével:
+hash['szin'] #=> 'zold'
+hash['szam'] #=> 5
+
+# Nem létező kulcsra keresve nil-t kapunk:
+hash['nincs itt semmi'] #=> nil
+
+# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot
+# használunk kulcsnak
+
+uj_hash = { defcon: 3, action: true }
+
+uj_hash.keys #=> [:defcon, :action]
+
+# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben
+uj_hash.has_key?(:defcon) #=> true
+uj_hash.has_value?(3) #=> true
+
+# Tip: A tömbök és hash-ek is felsorolhatóak
+# Sok közös függvényük van, akár az each, map, count, és több
+
+# Kontroll Struktúrák
+
+if true
+ 'ha állítás'
+elsif false
+ 'különben ha, opcionális'
+else
+ 'különben, szintén opcionális'
+end
+
+for szamlalo in 1..5
+ puts "iteracio #{szamlalo}"
+end
+#=> iteracio 1
+#=> iteracio 2
+#=> iteracio 3
+#=> iteracio 4
+#=> iteracio 5
+
+# HOWEVER, No-one uses for loops.
+# Instead you should use the "each" method and pass it a block.
+# A block is a bunch of code that you can pass to a method like "each".
+# It is analogous to lambdas, anonymous functions or closures in other
+# programming languages.
+#
+# The "each" method of a range runs the block once for each element of the range.
+# The block is passed a counter as a parameter.
+# Calling the "each" method with a block looks like this:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# You can also surround blocks in curly brackets:
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# The contents of data structures can also be iterated using each.
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+jegy = '4'
+
+case jegy
+when '5'
+ puts 'Kitünő'
+when '4'
+ puts 'Jó'
+when '3'
+ puts 'Közepes'
+when '2'
+ puts 'Elégsége'
+when '1'
+ puts 'Elégtelen'
+else
+ puts 'Alternatív értékelés, hm?'
+end
+#=> "Jó"
+
+# case-ek tartományokat is használhatnak
+jegy = 82
+case jegy
+when 90..100
+ puts 'Hurrá!'
+when 80...90
+ puts 'Jó munka'
+else
+ puts 'Megbuktál!'
+end
+#=> "Jó munka"
+
+# kivétel kezelés:
+begin
+ # kód ami kivételt dobhat
+ raise NoMemoryError, 'Megtelt a memória'
+rescue NoMemoryError => kivetel_valtozo
+ puts 'NoMemoryError-t dobott', kivetel_valtozo
+rescue RuntimeError => mas_kivetel_valtozo
+ puts 'RuntimeError dobott most'
+else
+ puts 'Ez akkor fut ha nem dob kivételt'
+ensure
+ puts 'Ez a kód mindenképpen lefut'
+end
+
+# Függvények
+
+def ketszeres(x)
+ x * 2
+end
+
+# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel
+ketszeres(2) #=> 4
+
+# Zárójelezés opcionális, ha az eredmény félreérthetetlen
+ketszeres 3 #=> 6
+
+ketszeres ketszeres 3 #=> 12
+
+def osszeg(x, y)
+ x + y
+end
+
+# Függvény argumentumait vesszővel választjuk el.
+osszeg 3, 4 #=> 7
+
+osszeg osszeg(3, 4), 5 #=> 12
+
+# yield
+# Minden függvénynek van egy implicit, opcionális block paramétere
+# 'yield' kulcsszóval hívhatjuk
+
+def korulvesz
+ puts '{'
+ yield
+ puts '}'
+end
+
+korulvesz { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+
+# Fuggvénynek átadhatunk blokkot
+# "&" jelöli az átadott blokk referenciáját
+def vendegek(&block)
+ block.call 'valami_argumentum'
+end
+
+# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva
+# Erre való a splat operátor ("*")
+def vendegek(*array)
+ array.each { |vendeg| puts vendeg }
+end
+
+# Osztályt a class kulcsszóval definiálhatunk
+class Ember
+
+ # Az osztály változó. Az osztály minden példánnyával megvan osztva
+ @@faj = 'H. sapiens'
+
+ # Alap inicializáló
+ def initialize(nev, kor = 0)
+ # Hozzárendeli az argumentumot a "nev" példány változóhoz
+ @nev = nev
+ # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni
+ @kor = kor
+ end
+
+ # Alap setter függvény
+ def nev=(nev)
+ @nev = nev
+ end
+
+ # Alap getter függvény
+ def nev
+ @nev
+ end
+
+ # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük
+ attr_accessor :nev
+
+ # Getter/setter függvények egyenként is kreálhatóak
+ attr_reader :nev
+ attr_writer :nev
+
+ # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a
+ # példány függvényektől
+ # Az osztályn hívhatóak, nem a példányon
+ def self.mond(uzenet)
+ puts uzenet
+ end
+
+ def faj
+ @@faj
+ end
+end
+
+
+# Példányosítsuk az osztályt
+jim = Ember.new('Jim Halpert')
+
+dwight = Ember.new('Dwight K. Schrute')
+
+# Hívjunk meg pár függvényt
+jim.faj #=> "H. sapiens"
+jim.nev #=> "Jim Halpert"
+jim.nev = "Jim Halpert II" #=> "Jim Halpert II"
+jim.nev #=> "Jim Halpert II"
+dwight.faj #=> "H. sapiens"
+dwight.nev #=> "Dwight K. Schrute"
+
+# Hívjuk meg az osztály függvényt
+Ember.mond('Hi') #=> "Hi"
+
+# Változók szókjait az elnevezésük definiálja
+# $ kezdetű változók globálisak
+$var = "Én egy globális változó vagyok"
+defined? $var #=> "global-variable"
+
+# Változók amik @-al kezdődnek példány szkópjuk van
+@var = "Én egy példány változó vagyok"
+defined? @var #=> "instance-variable"
+
+# Változók amik @@-al kezdődnek példány szkópjuk van
+@@var = "Én egy osztály változó vagyok"
+defined? @@var #=> "class variable"
+
+# Változók amik nagy betűvel kezdődnek a konstansok
+Var = "Konstans vagyok"
+defined? Var #=> "constant"
+
+# Az osztály is objetum. Tehát az osztálynak lehet példány változója
+# Az osztályváltozón osztozik minden pédány és leszármazott
+
+# Ős osztály
+class Ember
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(ertek)
+ @@foo = ertek
+ end
+end
+
+# Leszarmazott osztály
+class Dolgozo < Ember
+end
+
+Ember.foo # 0
+Dolgozo.foo # 0
+
+Ember.foo = 2 # 2
+Dolgozo.foo # 2
+
+# Az osztálynak példány változóját nem látja az osztály leszármazottja.
+
+class Ember
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(ertek)
+ @bar = ertek
+ end
+end
+
+class Doctor < Ember
+end
+
+Ember.bar # 0
+Doctor.bar # nil
+
+module ModulePelda
+ def foo
+ 'foo'
+ end
+end
+
+# Modulok include-olása a fügvényeiket az osztály példányaihoz köti.
+# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti.
+
+class Szemely
+ include ModulePelda
+end
+
+class Konyv
+ extend ModulePelda
+end
+
+Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class
+Szemely.new.foo # => 'foo'
+Konyv.foo # => 'foo'
+Konyv.new.foo # => NoMethodError: undefined method `foo'
+
+# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult
+
+module ConcernPelda
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
+ end
+ end
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Valami
+ include ConcernPelda
+end
+
+Valami.bar # => 'bar'
+Valami.qux # => NoMethodError: undefined method `qux'
+Valami.new.bar # => NoMethodError: undefined method `bar'
+Valami.new.qux # => 'qux'
+```
+
+## Egyéb források
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338)
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby from other languages](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/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide)
diff --git a/java.html.markdown b/java.html.markdown
index 478ec683..fa5cf8fc 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -5,6 +5,8 @@ contributors:
- ["Jakukyo Friel", "http://weakish.github.io"]
- ["Madison Dickson", "http://github.com/mix3d"]
- ["Simon Morgan", "http://sjm.io/"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
+ - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"]
filename: LearnJava.java
---
@@ -31,7 +33,7 @@ import java.security.*;
// the file.
public class LearnJava {
- // A program must have a main method as an entry point.
+ // In order to run a java program, it must have a main method as an entry point.
public static void main (String[] args) {
// Use System.out.println() to print lines.
@@ -45,11 +47,13 @@ public class LearnJava {
System.out.print("Hello ");
System.out.print("World");
+ // Use System.out.printf() for easy formatted printing.
+ System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
///////////////////////////////////////
- // Variables
+ // Variables
///////////////////////////////////////
-
+
/*
* Variable Declaration
*/
@@ -92,11 +96,13 @@ public class LearnJava {
// Note: Java has no unsigned types.
// Float - Single-precision 32-bit IEEE 754 Floating Point
+ // 2^-149 <= float <= (2-2^-23) * 2^127
float fooFloat = 234.5f;
- // f is used to denote that this variable value is of type float;
+ // f or F is used to denote that this variable value is of type float;
// otherwise it is treated as double.
// Double - Double-precision 64-bit IEEE 754 Floating Point
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
double fooDouble = 123.4;
// Boolean - true & false
@@ -106,8 +112,39 @@ public class LearnJava {
// Char - A single 16-bit Unicode character
char fooChar = 'A';
- // final variables can't be reassigned to another object.
+ // final variables can't be reassigned to another object,
final int HOURS_I_WORK_PER_WEEK = 9001;
+ // but they can be initialized later.
+ final double E;
+ E = 2.71828;
+
+
+ // BigInteger - Immutable arbitrary-precision integers
+ //
+ // BigInteger is a data type that allows programmers to manipulate
+ // integers longer than 64-bits. Integers are stored as an array of
+ // of bytes and are manipulated using functions built into BigInteger
+ //
+ // BigInteger can be initialized using an array of bytes or a string.
+
+ BigInteger fooBigInteger = new BigDecimal(fooByteArray);
+
+
+ // BigDecimal - Immutable, arbitrary-precision signed decimal number
+ //
+ // A BigDecimal takes two parts: an arbitrary precision integer
+ // unscaled value and a 32-bit integer scale
+ //
+ // BigDecimal allows the programmer complete control over decimal
+ // rounding. It is recommended to use BigDecimal with currency values
+ // and where exact decimal percision is required.
+ //
+ // BigDecimal can be initialized with an int, long, double or String
+ // or by initializing the unscaled value (BigInteger) and scale (int).
+
+ BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
+
+
// Strings
String fooString = "My String Is Here!";
@@ -166,6 +203,7 @@ public class LearnJava {
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
+ System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
@@ -178,12 +216,17 @@ public class LearnJava {
System.out.println("2 <= 2? " + (2 <= 2)); // => true
System.out.println("2 >= 2? " + (2 >= 2)); // => true
+ // Boolean operators
+ System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
+ System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
+ System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
+
// Bitwise operators!
/*
~ Unary bitwise complement
<< Signed left shift
- >> Signed right shift
- >>> Unsigned right shift
+ >> Signed/Arithmetic right shift
+ >>> Unsigned/Logical right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
@@ -207,7 +250,7 @@ public class LearnJava {
// If statements are c-like
int j = 10;
- if (j == 10){
+ if (j == 10) {
System.out.println("I get printed");
} else if (j > 10) {
System.out.println("I don't");
@@ -236,14 +279,24 @@ public class LearnJava {
System.out.println("fooDoWhile Value: " + fooDoWhile);
// For Loop
- int fooFor;
// for loop structure => for(<start_statement>; <conditional>; <step>)
- for (fooFor = 0; fooFor < 10; fooFor++) {
+ for (int fooFor = 0; fooFor < 10; fooFor++) {
System.out.println(fooFor);
// Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
-
+
+ // Nested For Loop Exit with Label
+ outer:
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (i == 5 && j ==5) {
+ break outer;
+ // breaks out of outer loop instead of only the inner one
+ }
+ }
+ }
+
// For Each Loop
// The for loop is also able to iterate over arrays as well as objects
// that implement the Iterable interface.
@@ -275,6 +328,23 @@ public class LearnJava {
break;
}
System.out.println("Switch Case Result: " + monthString);
+
+ // Starting in Java 7 and above, switching Strings works like this:
+ String myAnswer = "maybe";
+ switch(myAnswer){
+ case "yes":
+ System.out.println("You answered yes.");
+ break;
+ case "no":
+ System.out.println("You answered no.");
+ break;
+ case "maybe":
+ System.out.println("You answered maybe.");
+ break;
+ default:
+ System.out.println("You answered " + myAnswer);
+ break;
+ }
// Conditional Shorthand
// You can use the '?' operator for quick assignments or logic forks.
@@ -325,31 +395,31 @@ public class LearnJava {
// toString returns this Object's string representation.
System.out.println("trek info: " + trek.toString());
-
+
// Double Brace Initialization
// The Java Language has no syntax for how to create static Collections
// in an easy way. Usually you end up in the following way:
-
+
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
- validCodes.add("DENMARK");
- validCodes.add("SWEDEN");
- validCodes.add("FINLAND");
+ validCodes.add("DENMARK");
+ validCodes.add("SWEDEN");
+ validCodes.add("FINLAND");
}
-
- // But there's a nifty way to achive the same thing in an
+
+ // But there's a nifty way to achieve the same thing in an
// easier way, by using something that is called Double Brace
// Initialization.
-
+
private static final Set<String> COUNTRIES = HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
- add("FINLAND");
+ add("FINLAND");
}}
-
- // The first brace is creating an new AnonymousInnerClass and the
- // second one declares and instance initializer block. This block
- // is called with the anonymous inner class is created.
+
+ // The first brace is creating a new AnonymousInnerClass and the
+ // second one declares an instance initializer block. This block
+ // is called when the anonymous inner class is created.
// This does not only work for Collections, it works for all
// non-final classes.
@@ -357,7 +427,8 @@ public class LearnJava {
} // End LearnJava class
-// You can include other, non-public outer-level classes in a .java file
+// You can include other, non-public outer-level classes in a .java file,
+// but it is good practice. Instead split classes into separate files.
// Class Declaration Syntax:
@@ -377,6 +448,8 @@ class Bicycle {
// Constructors are a way of creating classes
// This is a constructor
public Bicycle() {
+ // You can also call another constructor:
+ // this(1, 50, 5, "Bontrager");
gear = 1;
cadence = 50;
speed = 5;
@@ -392,13 +465,13 @@ class Bicycle {
this.name = name;
}
- // Function Syntax:
+ // Method Syntax:
// <public/private/protected> <return type> <function name>(<args>)
// Java classes often implement getters and setters for their fields
// Method declaration syntax:
- // <scope> <return type> <method name>(<args>)
+ // <access modifier> <return type> <method name>(<args>)
public int getCadence() {
return cadence;
}
@@ -429,7 +502,7 @@ class Bicycle {
}
//Method to display the attribute values of this Object.
- @Override
+ @Override // Inherited from the Object class.
public String toString() {
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
" name: " + name;
@@ -464,108 +537,150 @@ class PennyFarthing extends Bicycle {
// Example - Food:
public interface Edible {
- public void eat(); // Any class that implements this interface, must
+ public void eat(); // Any class that implements this interface, must
// implement this method.
}
public interface Digestible {
- public void digest();
+ public void digest();
}
// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
+
@Override
- public void eat() {
- // ...
- }
+ public void eat() {
+ // ...
+ }
@Override
- public void digest() {
- // ...
- }
+ public void digest() {
+ // ...
+ }
}
// In Java, you can extend only one class, but you can implement many
// interfaces. For example:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
+
@Override
- public void InterfaceOneMethod() {
- }
+ public void InterfaceOneMethod() {
+ }
@Override
- public void InterfaceTwoMethod() {
- }
+ public void InterfaceTwoMethod() {
+ }
+
}
+// Abstract Classes
-// Abstract Classes
// Abstract Class declaration syntax
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
// // Constants and variables
// // Method declarations
// }
-// Methods can't have bodies in an interface, unless the method is
-// static. Also variables are NOT final by default, unlike an interface.
-// Also abstract classes CAN have the "main" method.
-// Abstract classes solve these problems.
+// Marking a class as abstract means that it contains abstract methods that must
+// be defined in a child class. Similar to interfaces, abstract classes cannot
+// be instantiated, but instead must be extended and the abstract methods
+// defined. Different from interfaces, abstract classes can contain a mixture of
+// concrete and abstract methods. Methods in an interface cannot have a body,
+// unless the method is static, and variables are final by default, unlike an
+// abstract class. Also abstract classes CAN have the "main" method.
-public abstract class Animal
+public abstract class Animal
{
- public abstract void makeSound();
-
- // Method can have a body
- public void eat()
- {
- System.out.println("I am an animal and I am Eating.");
- // Note: We can access private variable here.
- age = 30;
- }
-
- // No need to initialize, however in an interface
- // a variable is implicitly final and hence has
- // to be initialized.
- private int age;
-
- public void printAge()
- {
- System.out.println(age);
- }
-
- // Abstract classes can have main function.
- public static void main(String[] args)
- {
- System.out.println("I am abstract");
- }
+ public abstract void makeSound();
+
+ // Method can have a body
+ public void eat()
+ {
+ System.out.println("I am an animal and I am Eating.");
+ // Note: We can access private variable here.
+ age = 30;
+ }
+
+ // No need to initialize, however in an interface
+ // a variable is implicitly final and hence has
+ // to be initialized.
+ protected int age;
+
+ public void printAge()
+ {
+ System.out.println(age);
+ }
+
+ // Abstract classes can have main function.
+ public static void main(String[] args)
+ {
+ System.out.println("I am abstract");
+ }
}
class Dog extends Animal
{
- // Note still have to override the abstract methods in the
- // abstract class.
- @Override
- public void makeSound()
- {
- System.out.println("Bark");
- // age = 30; ==> ERROR! age is private to Animal
- }
-
- // NOTE: You will get an error if you used the
- // @Override annotation here, since java doesn't allow
- // overriding of static methods.
- // What is happening here is called METHOD HIDING.
- // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
- public static void main(String[] args)
- {
- Dog pluto = new Dog();
- pluto.makeSound();
- pluto.eat();
- pluto.printAge();
- }
+ // Note still have to override the abstract methods in the
+ // abstract class.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Bark");
+ // age = 30; ==> ERROR! age is private to Animal
+ }
+
+ // NOTE: You will get an error if you used the
+ // @Override annotation here, since java doesn't allow
+ // overriding of static methods.
+ // What is happening here is called METHOD HIDING.
+ // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
+ public static void main(String[] args)
+ {
+ Dog pluto = new Dog();
+ pluto.makeSound();
+ pluto.eat();
+ pluto.printAge();
+ }
}
+// Final Classes
+
+// Final Class declaration syntax
+// <access-level> final <final-class-name> {
+// // Constants and variables
+// // Method declarations
+// }
+
+// Final classes are classes that cannot be inherited from and are therefore a
+// final child. In a way, final classes are the opposite of abstract classes
+// because abstract classes must be extended, but final classes cannot be
+// extended.
+public final class SaberToothedCat extends Animal
+{
+ // Note still have to override the abstract methods in the
+ // abstract class.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Roar");
+ }
+}
+
+// Final Methods
+public abstract class Mammal()
+{
+ // Final Method Syntax:
+ // <access modifier> final <return type> <function name>(<args>)
+
+ // Final methods, like, final classes cannot be overridden by a child class,
+ // and are therefore the final implementation of the method.
+ public final boolean isWarmBlooded()
+ {
+ return true;
+ }
+}
```
## Further Reading
diff --git a/javascript.html.markdown b/javascript.html.markdown
index ba2e8ce4..34ba9b47 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -64,7 +64,7 @@ doStuff()
// There are three special not-a-real-number values:
Infinity; // result of e.g. 1/0
-Infinity; // result of e.g. -1/0
-NaN; // result of e.g. 0/0
+NaN; // result of e.g. 0/0, stands for 'Not a Number'
// There's also a boolean type.
true;
@@ -189,7 +189,7 @@ myObj.myFourthKey; // = undefined
///////////////////////////////////
// 3. Logic and Control Structures
-// The syntax for this section is almost identical to Java's.
+// The syntax for this section is almost identical to Java's.
// The `if` structure works as you'd expect.
var count = 1;
@@ -218,6 +218,26 @@ for (var i = 0; i < 5; i++){
// will run 5 times
}
+//The For/In statement loops iterates over every property across the entire prototype chain
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ description += person[x] + " ";
+}
+
+//If only want to consider properties attached to the object itself,
+//and not its prototypes use hasOwnProperty() check
+var description = "";
+var person = {fname:"Paul", lname:"Ken", age:18};
+for (var x in person){
+ if (person.hasOwnProperty(x)){
+ description += person[x] + " ";
+ }
+}
+
+//for/in should not be used to iterate over an Array where the index order is important.
+//There is no guarantee that for/in will return the indexes in any particular order
+
// && is logical and, || is logical or
if (house.size == "big" && house.colour == "blue"){
house.contains = "bear";
@@ -231,8 +251,8 @@ var name = otherName || "default";
// The `switch` statement checks for equality with `===`.
-// use 'break' after each case
-// or the cases after the correct one will be executed too.
+// use 'break' after each case
+// or the cases after the correct one will be executed too.
grade = 'B';
switch (grade) {
case 'A':
@@ -393,7 +413,7 @@ var doubler = product.bind(this, 2);
doubler(8); // = 16
// When you call a function with the `new` keyword, a new object is created, and
-// made available to the function via the this keyword. Functions designed to be
+// made available to the function via the `this` keyword. Functions designed to be
// called like that are called constructors.
var MyConstructor = function(){
@@ -516,12 +536,12 @@ more about how to use JavaScript in web pages, start by learning about the
[Document Object
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
guide of all the counter-intuitive parts of the language.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
In addition to direct contributors to this article, some content is adapted
from Louie Dinh's Python tutorial on this site, and the [JS
diff --git a/json.html.markdown b/json.html.markdown
index 47a8cb21..060e9c3d 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -4,19 +4,28 @@ filename: learnjson.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
---
As JSON is an extremely simple data-interchange format, this is most likely going
to be the simplest Learn X in Y Minutes ever.
JSON in its purest form has no actual comments, but most parsers will accept
-C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
-going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
+(i.e. a comma after the last element of an array or the after the last property of an object),
+but they should be avoided for better compatibility.
+
+For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+
+Data types supported by JSON includes: numbers, string, boolean, array, object and null.
+Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
+JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json"
+Drawbacks of JSON include lack of type definition and some sort of DTD.
```json
{
"key": "value",
-
+
"keys": "must always be enclosed in double quotes",
"numbers": 0,
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
@@ -46,10 +55,10 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
[0, 0, 0, 1]
]
],
-
+
"alternative style": {
"comment": "check this out!"
- , "comma position": "doesn't matter - as long as it's before the value, then it's valid"
+ , "comma position": "doesn't matter - as long as it's before the next key, then it's valid"
, "another comment": "how nice"
},
diff --git a/julia.html.markdown b/julia.html.markdown
index 5ccd6484..c5089dc3 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -14,7 +14,7 @@ This is based on Julia 0.3.
# Single line comments start with a hash (pound) symbol.
#= Multiline comments can be written
- by putting '#=' before the text and '=#'
+ by putting '#=' before the text and '=#'
after the text. They can also be nested.
=#
@@ -81,10 +81,13 @@ false
# Strings are created with "
"This is a string."
+# Julia has several types of strings, including ASCIIString and UTF8String.
+# More on this in the Types section.
+
# Character literals are written with '
'a'
-# A string can be indexed like an array of characters
+# Some strings can be indexed like an array of characters
"This is a string"[1] # => 'T' # Julia indexes from 1
# However, this is will not work well for UTF8 strings,
# so iterating over strings is recommended (map, for loops, etc).
@@ -314,7 +317,7 @@ end
# For loops iterate over iterables.
-# Iterable types include Range, Array, Set, Dict, and String.
+# Iterable types include Range, Array, Set, Dict, and AbstractString.
for animal=["dog", "cat", "mouse"]
println("$animal is a mammal")
# You can use $ to interpolate variables or expression into strings
@@ -537,6 +540,17 @@ subtypes(Number) # => 6-element Array{Any,1}:
# Real
subtypes(Cat) # => 0-element Array{Any,1}
+# AbstractString, as the name implies, is also an abstract type
+subtypes(AbstractString) # 8-element Array{Any,1}:
+ # Base.SubstitutionString{T<:AbstractString}
+ # DirectIndexString
+ # RepString
+ # RevString{T<:AbstractString}
+ # RopeString
+ # SubString{T<:AbstractString}
+ # UTF16String
+ # UTF8String
+
# Every type has a super type; use the `super` function to get it.
typeof(5) # => Int64
super(Int64) # => Signed
@@ -546,17 +560,21 @@ super(Number) # => Any
super(super(Signed)) # => Number
super(Any) # => Any
# All of these type, except for Int64, are abstract.
+typeof("fire") # => ASCIIString
+super(ASCIIString) # => DirectIndexString
+super(DirectIndexString) # => AbstractString
+# Likewise here with ASCIIString
# <: is the subtyping operator
type Lion <: Cat # Lion is a subtype of Cat
mane_color
- roar::String
+ roar::AbstractString
end
# You can define more constructors for your type
# Just define a function of the same name as the type
# and call an existing constructor to get a value of the correct type
-Lion(roar::String) = Lion("green",roar)
+Lion(roar::AbstractString) = Lion("green",roar)
# This is an outer constructor because it's outside the type definition
type Panther <: Cat # Panther is also a subtype of Cat
@@ -670,7 +688,7 @@ square_area(l) = l * l # square_area (generic function with 1 method)
square_area(5) #25
# What happens when we feed square_area an integer?
-code_native(square_area, (Int32,))
+code_native(square_area, (Int32,))
# .section __TEXT,__text,regular,pure_instructions
# Filename: none
# Source line: 1 # Prologue
@@ -703,10 +721,10 @@ code_native(square_area, (Float64,))
# vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
# pop RBP
# ret
- #
+ #
# Note that julia will use floating point instructions if any of the
# arguements are floats.
-# Let's calculate the area of a circle
+# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
@@ -737,7 +755,7 @@ code_native(circle_area, (Float64,))
# vmulsd XMM0, XMM1, XMM0
# pop RBP
# ret
- #
+ #
```
## Further Reading
diff --git a/latex.html.markdown b/latex.html.markdown
new file mode 100644
index 00000000..e180e622
--- /dev/null
+++ b/latex.html.markdown
@@ -0,0 +1,231 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
+filename: learn-latex.tex
+---
+% All comment lines start with %
+% There are no multi-line comments
+
+% LaTeX is NOT a "What You See Is What You Get" word processing software like
+% MS Word, or OpenOffice Writer
+
+% Every LaTeX command starts with a backslash (\)
+
+% LaTeX documents start with a defining the type of document it's compiling
+% Other document types include book, report, presentations, etc.
+% The options for the document appear in the [] brackets. In this case
+% it specifies we want to use 12pt font.
+\documentclass[12pt]{article}
+
+% Next we define the packages the document uses.
+% If you want to include graphics, colored text, or
+% source code from another language file into your document,
+% you need to enhance the capabilities of LaTeX. This is done by adding packages.
+% I'm going to include the float and caption packages for figures.
+\usepackage{caption}
+\usepackage{float}
+
+% We can define some other document properties too!
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
+\date{\today}
+\title{Learn LaTeX in Y Minutes!}
+
+% Now we're ready to begin the document
+% Everything before this line is called "The Preamble"
+\begin{document}
+% if we set the author, date, title fields, we can have LaTeX
+% create a title page for us.
+\maketitle
+
+% Most research papers have abstract, you can use the predefined commands for this.
+% This should appear in its logical order, therefore, after the top matter,
+% but before the main sections of the body.
+% This command is available in the document classes article and report.
+\begin{abstract}
+ LaTeX documentation written as LaTeX! How novel and totally not my idea!
+\end{abstract}
+
+% Section commands are intuitive.
+% All the titles of the sections are added automatically to the table of contents.
+\section{Introduction}
+Hello, my name is Colton and together we're going to explore LaTeX!
+
+\section{Another section}
+This is the text for another section. I think it needs a subsection.
+
+\subsection{This is a subsection} % Subsections are also intuitive.
+I think we need another one
+
+\subsubsection{Pythagoras}
+Much better now.
+\label{subsec:pythagoras}
+
+% By using the asterisk we can suppress LaTeX's inbuilt numbering.
+% This works for other LaTeX commands as well.
+\section*{This is an unnumbered section}
+However not all sections have to be numbered!
+
+\section{Some Text notes}
+LaTeX is generally pretty good about placing text where it should go. If
+a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to
+the source code. \\
+
+\section{Lists}
+Lists are one of the easiest things to create in LaTeX! I need to go shopping
+tomorrow, so let's make a grocery list.
+\begin{enumerate} % This creates an "enumerate" environment.
+ % \item tells the enumerate to increment
+ \item Salad.
+ \item 27 watermelon.
+ \item A single jackrabbit.
+ % we can even override the item number by using []
+ \item[how many?] Medium sized squirt guns.
+
+ Not a list item, but still part of the enumerate.
+
+\end{enumerate} % All environments must have an end.
+
+\section{Math}
+
+One of the primary uses for LaTeX is to produce academic articles or
+technical papers. Usually in the realm of math and science. As such,
+we need to be able to add special symbols to our paper! \\
+
+Math has many symbols, far beyond what you can find on a keyboard;
+Set and relation symbols, arrows, operators, and Greek letters to name a few.\\
+
+Sets and relations play a vital role in many mathematical research papers.
+Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\
+% Notice how I needed to add $ signs before and after the symbols. This is
+% because when writing, we are in text-mode.
+% However, the math symbols only exist in math-mode.
+% We can enter math-mode from text mode with the $ signs.
+% The opposite also holds true. Variable can also be rendered in math-mode.
+
+My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+I haven't found a Greek letter that yet that LaTeX doesn't know about!
+
+Operators are essential parts of a mathematical document:
+trigonometric functions ($\sin$, $\cos$, $\tan$),
+logarithms and exponentials ($\log$, $\exp$),
+limits ($\lim$), etc.
+have per-defined LaTeX commands.
+Let's write an equation to see how it's done: \\
+
+$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$
+
+Fractions(Numerator-denominators) can be written in these forms:
+
+% 10 / 7
+$^{10}/_{7}$
+
+% Relatively complex fractions can be written as
+% \frac{numerator}{denominator}
+$\frac{n!}{k!(n - k)!}$ \\
+
+We can also insert equations in an "equation environment".
+
+% Display math with the equation 'environment'
+\begin{equation} % enters math-mode
+ c^2 = a^2 + b^2.
+ \label{eq:pythagoras} % for referencing
+\end{equation} % all \begin statements must have an end statement
+
+We can then reference our new equation!
+Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
+the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled:
+figures, equations, sections, etc.
+
+Summations and Integrals are written with sum and int commands:
+
+% Some LaTeX compilers will complain if there are blank lines
+% In an equation environment.
+\begin{equation}
+ \sum_{i=0}^{5} f_{i}
+\end{equation}
+\begin{equation}
+ \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x
+\end{equation}
+
+\section{Figures}
+
+Let's insert a Figure. Figure placement can get a little tricky.
+I definitely have to lookup the placement options each time.
+
+\begin{figure}[H] % H here denoted the placement option.
+ \centering % centers the figure on the page
+ % Inserts a figure scaled to 0.8 the width of the page.
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Commented out for compilation purposes. Please use your imagination.
+ \caption{Right triangle with sides $a$, $b$, $c$}
+ \label{fig:right-triangle}
+\end{figure}
+
+\subsection{Table}
+We can also insert Tables in the same way as figures.
+
+\begin{table}[H]
+ \caption{Caption for the Table.}
+ % the {} arguments below describe how each row of the table is drawn.
+ % Again, I have to look these up. Each. And. Every. Time.
+ \begin{tabular}{c|cc}
+ Number & Last Name & First Name \\ % Column rows are separated by $
+ \hline % a horizontal line
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
+\end{table}
+
+% \section{Hyperlinks} % Coming soon
+
+\section{Getting LaTeX to not compile something (i.e. Source Code)}
+Let's say we want to include some code into our LaTeX document,
+we would then need LaTeX to not try and interpret that text and
+instead just print it to the document. We do this we a verbatim
+environment.
+
+% There are other packages that exist (i.e. minty, lstlisting, etc.)
+% but verbatim is the bare-bones basic one.
+\begin{verbatim}
+ print("Hello World!")
+ a%b; % look! We can use % signs in verbatim.
+ random = 4; #decided by fair random dice roll
+\end{verbatim}
+
+\section{Compiling}
+
+By now you're probably wondering how to compile this fabulous document
+and look at the glorious glory that is a LaTeX pdf.
+(yes, this document actually does compiles). \\
+Getting to the final document using LaTeX consists of the following steps:
+ \begin{enumerate}
+ \item Write the document in plain text (the "source code").
+ \item Compile source code to produce a pdf.
+ The compilation step looks something like this (in Linux): \\
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
+software. So, you get to see Step 1, but not Step 2 completely.
+Step 2 is still happening behind the scenes.
+
+You write all your formatting information in plain text in Step 1.
+The compilation part in Step 2 takes care of producing the document in the
+format you defined in Step 1.
+
+\section{End}
+
+That's all for now!
+
+% end the document
+\end{document}
+```
+## More on LaTeX
+
+* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
diff --git a/livescript.html.markdown b/livescript.html.markdown
index e64f7719..9235f5ce 100644
--- a/livescript.html.markdown
+++ b/livescript.html.markdown
@@ -166,7 +166,7 @@ not false # => true
########################################################################
## 3. Functions
-########################################################################
+########################################################################
# Since LiveScript is functional, you'd expect functions to get a nice
# treatment. In LiveScript it's even more apparent that functions are
@@ -229,7 +229,7 @@ double-minus-one = (- 1) . (* 2)
# Other than the usual `f . g` mathematical formulae, you get the `>>`
# and `<<` operators, that describe how the flow of values through the
-# functions.
+# functions.
double-minus-one = (* 2) >> (- 1)
double-minus-one = (- 1) << (* 2)
@@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*"
## Further reading
There's just so much more to LiveScript, but this should be enough to
-get you started writing little functional things in it. The
+get you started writing little functional things in it. The
[official website](http://livescript.net/) has a lot of information on the
language, and a nice online compiler for you to try stuff out!
diff --git a/make.html.markdown b/make.html.markdown
index 75543dcd..563139d1 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -31,7 +31,7 @@ we are using GNU make which is the standard on Linux.
file0.txt:
echo "foo" > file0.txt
# Even comments in these 'recipe' sections get passed to the shell.
- # Try `make file0.txt` or simply `make` - first rule is the default.
+ # Try `make file0.txt` or simply `make` - first rule is the default.
# This rule will only run if file0.txt is newer than file1.txt.
@@ -49,7 +49,7 @@ file2.txt file3.txt: file0.txt file1.txt
touch file2.txt
touch file3.txt
-# Make will complain about multiple recipes for the same rule. Empty
+# Make will complain about multiple recipes for the same rule. Empty
# recipes don't count though and can be used to add new dependencies.
#-----------------------------------------------------------------------
@@ -115,7 +115,7 @@ small/%.png: %.svg
%.png: %.ps
@echo this rule is not chosen if *.svg and *.ps are both present
-# make already has some pattern rules built-in. For instance, it knows
+# make already has some pattern rules built-in. For instance, it knows
# how to turn *.c files into *.o files.
# Older makefiles might use suffix rules instead of pattern rules
@@ -185,7 +185,7 @@ var := hello
var2 ::= $(var) hello
#:= and ::= are equivalent.
-# These variables are evaluated procedurely (in the order that they
+# These variables are evaluated procedurely (in the order that they
# appear), thus breaking with the rest of the language !
# This doesn't work
diff --git a/markdown.html.markdown b/markdown.html.markdown
index acb808ea..2333110f 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -70,7 +70,7 @@ I'm in paragraph three!
<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
with two or more spaces and then begin a new paragraph. -->
-I end with two spaces (highlight me to see them).
+I end with two spaces (highlight me to see them).
There's a <br /> above me!
@@ -97,7 +97,7 @@ or
+ Item
+ One more item
-or
+or
- Item
- Item
@@ -129,7 +129,7 @@ render the numbers in order, but this may not be a good idea -->
<!-- There are even task lists. This creates HTML checkboxes. -->
Boxes below without the 'x' are unchecked HTML checkboxes.
-- [ ] First task to complete.
+- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
@@ -169,7 +169,7 @@ with or without spaces. -->
***
---
-- - -
+- - -
****************
<!-- Links -->
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 00f4c53a..0cbc6f57 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -3,10 +3,11 @@ language: Matlab
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
---
-MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
+MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
If you have any feedback please feel free to reach me at
[@the_ozzinator](https://twitter.com/the_ozzinator), or
@@ -16,7 +17,7 @@ If you have any feedback please feel free to reach me at
% Comments start with a percent sign.
%{
-Multi line comments look
+Multi line comments look
something
like
this
@@ -62,10 +63,10 @@ disp('text') % print "text" to the screen
% Variables & Expressions
myVariable = 4 % Notice Workspace pane shows newly created variable
myVariable = 4; % Semi colon suppresses output to the Command Window
-4 + 6 % ans = 10
-8 * myVariable % ans = 32
-2 ^ 3 % ans = 8
-a = 2; b = 3;
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+2 ^ 3 % ans = 8
+a = 2; b = 3;
c = exp(a)*sin(pi/2) % c = 7.3891
% Calling functions can be done in either of two ways:
@@ -73,7 +74,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
% Command syntax:
load myFile.mat y % no parentheses, and spaces instead of commas
-% Note the lack of quote marks in command form: inputs are always passed as
+% Note the lack of quote marks in command form: inputs are always passed as
% literal text - cannot pass variable values. Also, can't receive output:
[V,D] = eig(A); % this has no equivalent in command form
[~,D] = eig(A); % if you only want D and not V
@@ -103,7 +104,7 @@ a(2) % ans = y
% Cells
-a = {'one', 'two', 'three'}
+a = {'one', 'two', 'three'}
a(1) % ans = 'one' - returns a cell
char(a(1)) % ans = one - returns a string
@@ -113,7 +114,7 @@ A.c = [1 2];
A.d.e = false;
% Vectors
-x = [4 32 53 7 1]
+x = [4 32 53 7 1]
x(2) % ans = 32, indices in Matlab start 1, not 0
x(2:3) % ans = 32 53
x(2:end) % ans = 32 53 7 1
@@ -123,7 +124,7 @@ x = [4; 32; 53; 7; 1] % Column vector
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
% Matrices
-A = [1 2 3; 4 5 6; 7 8 9]
+A = [1 2 3; 4 5 6; 7 8 9]
% Rows are separated by a semicolon; elements are separated with space or comma
% A =
@@ -132,7 +133,7 @@ A = [1 2 3; 4 5 6; 7 8 9]
% 7 8 9
A(2,3) % ans = 6, A(row, column)
-A(6) % ans = 8
+A(6) % ans = 8
% (implicitly concatenates columns into vector, then indexes into that)
@@ -171,7 +172,7 @@ A(1,:) % All columns in row 1
% 4 5 42
% 7 8 9
-% this is the same as
+% this is the same as
vertcat(A,A);
@@ -183,7 +184,7 @@ vertcat(A,A);
% 4 5 42 4 5 42
% 7 8 9 7 8 9
-% this is the same as
+% this is the same as
horzcat(A,A);
@@ -201,21 +202,21 @@ A(:, 1) =[] % Delete the first column of the matrix
transpose(A) % Transpose the matrix, which is the same as:
A one
-ctranspose(A) % Hermitian transpose the matrix
+ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
-% Element by Element Arithmetic vs. Matrix Arithmetic
+% Element by Element Arithmetic vs. Matrix Arithmetic
% On their own, the arithmetic operators act on whole matrices. When preceded
% by a period, they act on each element instead. For example:
A * B % Matrix multiplication
A .* B % Multiple each element in A by its corresponding element in B
-% There are several pairs of functions, where one acts on each element, and
+% There are several pairs of functions, where one acts on each element, and
% the other (whose name ends in m) acts on the whole matrix.
-exp(A) % exponentiate each element
+exp(A) % exponentiate each element
expm(A) % calculate the matrix exponential
sqrt(A) % take the square root of each element
sqrtm(A) % find the matrix whose square is A
@@ -233,7 +234,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1
plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot
legend('Line 1 label', 'Line 2 label') % Label curves with a legend
-% Alternative method to plot multiple functions in one plot.
+% Alternative method to plot multiple functions in one plot.
% while 'hold' is on, commands add to existing graph rather than replacing it
plot(x, y)
hold on
@@ -271,9 +272,9 @@ clf clear % clear current figure window, and reset most figure properties
% Properties can be set and changed through a figure handle.
% You can save a handle to a figure when you create it.
-% The function gcf returns a handle to the current figure
+% The function gcf returns a handle to the current figure
h = plot(x, y); % you can save a handle to a figure when you create it
-set(h, 'Color', 'r')
+set(h, 'Color', 'r')
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
set(h, 'LineStyle', '--')
% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line
@@ -298,8 +299,8 @@ cd /path/to/move/into % change directory
% Variables can be saved to .mat files
-save('myFileName.mat') % Save the variables in your Workspace
-load('myFileName.mat') % Load saved variables into Workspace
+save('myFileName.mat') % Save the variables in your Workspace
+load('myFileName.mat') % Load saved variables into Workspace
% M-file Scripts
% A script file is an external file that contains a sequence of statements.
@@ -312,11 +313,11 @@ load('myFileName.mat') % Load saved variables into Workspace
% Also, they have their own workspace (ie. different variable scope).
% Function name should match file name (so save this example as double_input.m).
% 'help double_input.m' returns the comments under line beginning function
-function output = double_input(x)
+function output = double_input(x)
%double_input(x) returns twice the value of x
output = 2*x;
end
-double_input(6) % ans = 12
+double_input(6) % ans = 12
% You can also have subfunctions and nested functions.
@@ -325,8 +326,8 @@ double_input(6) % ans = 12
% functions, and have access to both its workspace and their own workspace.
% If you want to create a function without creating a new file you can use an
-% anonymous function. Useful when quickly defining a function to pass to
-% another function (eg. plot with fplot, evaluate an indefinite integral
+% anonymous function. Useful when quickly defining a function to pass to
+% another function (eg. plot with fplot, evaluate an indefinite integral
% with quad, find roots with fzero, or find minimum with fminsearch).
% Example that returns the square of it's input, assigned to to the handle sqr:
sqr = @(x) x.^2;
@@ -336,12 +337,12 @@ doc function_handle % find out more
% User input
a = input('Enter the value: ')
-% Stops execution of file and gives control to the keyboard: user can examine
+% Stops execution of file and gives control to the keyboard: user can examine
% or change variables. Type 'return' to continue execution, or 'dbquit' to exit
keyboard
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
-fopen(filename)
+fopen(filename)
% Output
disp(a) % Print out the value of variable a
@@ -363,8 +364,8 @@ end
for k = 1:5
disp(k)
end
-
-k = 0;
+
+k = 0;
while (k < 5)
k = k + 1;
end
@@ -382,7 +383,7 @@ password = 'root';
driver = 'com.mysql.jdbc.Driver';
dburl = ['jdbc:mysql://localhost:8889/' dbname];
javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
-conn = database(dbname, username, password, driver, dburl);
+conn = database(dbname, username, password, driver, dburl);
sql = ['SELECT * from table_name where id = 22'] % Example sql statement
a = fetch(conn, sql) %a will contain your data
@@ -394,7 +395,7 @@ tan(x)
asin(x)
acos(x)
atan(x)
-exp(x)
+exp(x)
sqrt(x)
log(x)
log10(x)
@@ -426,7 +427,7 @@ pinv(A) % calculate the pseudo-inverse
zeros(m,n) % m x n matrix of 0's
ones(m,n) % m x n matrix of 1's
diag(A) % Extracts the diagonal elements of a matrix A
-diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
+diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
eye(m,n) % Identity matrix
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
inv(A) % Inverse of matrix A
@@ -452,18 +453,71 @@ flipud(A) % Flip matrix up to down
[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order
% Common vector functions
-max % largest component
-min % smallest component
+max % largest component
+min % smallest component
length % length of a vector
-sort % sort in ascending order
-sum % sum of elements
+sort % sort in ascending order
+sum % sum of elements
prod % product of elements
mode % modal value
-median % median value
-mean % mean value
+median % median value
+mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
+
+% Classes
+% Matlab can support object-oriented programming.
+% Classes must be put in a file of the class name with a .m extension.
+% To begin, we create a simple class to store GPS waypoints.
+% Begin WaypointClass.m
+classdef WaypointClass % The class name.
+ properties % The properties of the class behave like Structures
+ latitude
+ longitude
+ end
+ methods
+ % This method that has the same name of the class is the constructor.
+ function obj = WaypointClass(lat, lon)
+ obj.latitude = lat;
+ obj.longitude = lon;
+ end
+
+ % Other functions that use the Waypoint object
+ function r = multiplyLatBy(obj, n)
+ r = n*[obj.latitude];
+ end
+
+ % If we want to add two Waypoint objects together without calling
+ % a special function we can overload Matlab's arithmetic like so:
+ function r = plus(o1,o2)
+ r = WaypointClass([o1.latitude] +[o2.latitude], ...
+ [o1.longitude]+[o2.longitude]);
+ end
+ end
+end
+% End WaypointClass.m
+
+% We can create an object of the class using the constructor
+a = WaypointClass(45.0, 45.0)
+
+% Class properties behave exactly like Matlab Structures.
+a.latitude = 70.0
+a.longitude = 25.0
+
+% Methods can be called in the same way as functions
+ans = multiplyLatBy(a,3)
+
+% The method can also be called using dot notation. In this case, the object
+% does not need to be passed to the method.
+ans = a.multiplyLatBy(a,1/3)
+
+% Matlab functions can be overloaded to handle objects.
+% In the method above, we have overloaded how Matlab handles
+% the addition of two Waypoint objects.
+b = WaypointClass(15.0, 32.0)
+c = a + b
+
```
## More on Matlab
diff --git a/neat.html.markdown b/neat.html.markdown
index e99d1e0e..f02461ee 100644
--- a/neat.html.markdown
+++ b/neat.html.markdown
@@ -47,18 +47,18 @@ void main(string[] args) {
// There are no one-value tuples though.
// So you can always use () in the mathematical sense.
// (string) arg; <- is an error
-
+
/*
byte: 8 bit signed integer
char: 8 bit UTF-8 byte component.
short: 16 bit signed integer
int: 32 bit signed integer
long: 64 bit signed integer
-
+
float: 32 bit floating point
double: 64 bit floating point
real: biggest native size floating point (80 bit on x86).
-
+
bool: true or false
*/
int a = 5;
@@ -139,14 +139,14 @@ void main(string[] args) {
assert !(hewo is s);
// same as
assert (hewo !is s);
-
+
// Allocate arrays using "new array length"
int[] integers = new int[] 10;
assert(integers.length == 10);
assert(integers[0] == 0); // zero is default initializer
integers = integers ~ 5; // This allocates a new array!
assert(integers.length == 11);
-
+
// This is an appender array.
// Instead of (length, pointer), it tracks (capacity, length, pointer).
// When you append to it, it will use the free capacity if it can.
@@ -156,13 +156,13 @@ void main(string[] args) {
appender ~= 2;
appender ~= 3;
appender.free(); // same as {mem.free(appender.ptr); appender = null;}
-
+
// Scope variables are automatically freed at the end of the current scope.
scope int[auto~] someOtherAppender;
// This is the same as:
int[auto~] someOtherAppender2;
onExit { someOtherAppender2.free; }
-
+
// You can do a C for loop too
// - but why would you want to?
for (int i = 0; i < 5; ++i) { }
@@ -178,23 +178,23 @@ void main(string[] args) {
assert(i == 5);
break; // otherwise we'd go back up to do {
}
-
+
// This is a nested function.
// Nested functions can access the surrounding function.
string returnS() { return s; }
writeln returnS();
-
+
// Take the address of a function using &
// The type of a global function is ReturnType function(ParameterTypeTuple).
void function() foop = &foo;
-
+
// Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
string delegate() returnSp = &returnS;
writeln returnSp();
// Class member functions and struct member functions also fit into delegate variables.
// In general, delegates are functions that carry an additional context pointer.
// ("fat pointers" in C)
-
+
// Allocate a "snapshot" with "new delegate".
// Snapshots are not closures! I used to call them closures too,
// but then my Haskell-using friends yelled at me so I had to stop.
@@ -232,8 +232,8 @@ void main(string[] args) {
auto nestfun = λ() { } // There is NO semicolon needed here!
// "}" can always substitute for "};".
// This provides syntactic consistency with built-in statements.
-
-
+
+
// This is a class.
// Note: almost all elements of Neat can be used on the module level
// or just as well inside a function.
@@ -268,7 +268,7 @@ void main(string[] args) {
E e = E:cd; // dynamic class cast!
e.doE();
writeln "$e"; // all interfaces convert to Object implicitly.
-
+
// Templates!
// Templates are parameterized namespaces, taking a type as a parameter.
template Templ(T) {
diff --git a/nim.html.markdown b/nim.html.markdown
index c9548a1c..79271732 100644
--- a/nim.html.markdown
+++ b/nim.html.markdown
@@ -235,7 +235,7 @@ proc ask(question: string): Answer =
else: echo("Please be clear: yes or no")
proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
- assert(amount > 0 or amount < 9000, "Crazy Sugar")
+ assert(amount > 0 and amount < 9000, "Crazy Sugar")
for a in 1..amount:
echo(a, " sugar...")
diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown
index cd12b1d0..6062b24c 100644
--- a/nl-nl/brainfuck-nl.html.markdown
+++ b/nl-nl/brainfuck-nl.html.markdown
@@ -15,7 +15,7 @@ minimalistische Turing-complete programmeertaal met maar acht commando's.
```
Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd.
-Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel
+Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel
gevuld is met nullen en een pointer die wijst naar de huidige cel.
Dit zijn de acht commando's:
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 91b84b47..cf6bf780 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -5,14 +5,15 @@ contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
filename: LearnObjectiveC.m
---
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
-It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
+It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
-```objective_c
+```objective-c
// Single-line comments start with //
/*
@@ -40,15 +41,15 @@ int main (int argc, const char * argv[])
// Use NSLog to print lines to the console
NSLog(@"Hello World!"); // Print the string "Hello World!"
-
+
///////////////////////////////////////
// Types & Variables
///////////////////////////////////////
-
+
// Primitive declarations
int myPrimitive1 = 1;
long myPrimitive2 = 234554664565;
-
+
// Object declarations
// Put the * in front of the variable names for strongly-typed object declarations
MyClass *myObject1 = nil; // Strong typing
@@ -56,15 +57,15 @@ int main (int argc, const char * argv[])
// %@ is an object
// 'description' is a convention to display the value of the Objects
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)"
-
+
// String
NSString *worldString = @"World";
- NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
+ NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
// NSMutableString is a mutable version of the NSString object
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
[mutableString appendString:@" World!"];
NSLog(@"%@", mutableString); // prints => "Hello World!"
-
+
// Character literals
NSNumber *theLetterZNumber = @'Z';
char theLetterZ = [theLetterZNumber charValue]; // or 'Z'
@@ -74,11 +75,11 @@ int main (int argc, const char * argv[])
NSNumber *fortyTwoNumber = @42;
int fortyTwo = [fortyTwoNumber intValue]; // or 42
NSLog(@"%i", fortyTwo);
-
+
NSNumber *fortyTwoUnsignedNumber = @42U;
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
NSLog(@"%u", fortyTwoUnsigned);
-
+
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42
NSLog(@"%hi", fortyTwoShort);
@@ -86,7 +87,7 @@ int main (int argc, const char * argv[])
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
NSLog(@"%u", fortyOneUnsigned);
-
+
NSNumber *fortyTwoLongNumber = @42L;
long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42
NSLog(@"%li", fortyTwoLong);
@@ -100,7 +101,7 @@ int main (int argc, const char * argv[])
float piFloat = [piFloatNumber floatValue]; // or 3.141592654f
NSLog(@"%f", piFloat); // prints => 3.141592654
NSLog(@"%5.2f", piFloat); // prints => " 3.14"
-
+
NSNumber *piDoubleNumber = @3.1415926535;
double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535
NSLog(@"%f", piDouble);
@@ -110,7 +111,7 @@ int main (int argc, const char * argv[])
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
- [oneDecNum decimalNumberByAdding:twoDecNum];
+ [oneDecNum decimalNumberByAdding:twoDecNum];
[oneDecNum decimalNumberBySubtracting:twoDecNum];
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
[oneDecNum decimalNumberByDividingBy:twoDecNum];
@@ -129,8 +130,8 @@ int main (int argc, const char * argv[])
NSArray *anArray = @[@1, @2, @3, @4];
NSNumber *thirdNumber = anArray[2];
NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3"
- // NSMutableArray is a mutable version of NSArray, allowing you to change
- // the items in the array and to extend or shrink the array object.
+ // NSMutableArray is a mutable version of NSArray, allowing you to change
+ // the items in the array and to extend or shrink the array object.
// Convenient, but not as efficient as NSArray.
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
[mutableArray addObject:@"Hello"];
@@ -160,7 +161,7 @@ int main (int argc, const char * argv[])
///////////////////////////////////////
// Operators
///////////////////////////////////////
-
+
// The operators works like in the C language
// For example:
2 + 5; // => 7
@@ -205,13 +206,13 @@ int main (int argc, const char * argv[])
NSLog(@"I print");
} break;
}
-
+
// While loops statements
int ii = 0;
while (ii < 4)
{
NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
@@ -221,25 +222,25 @@ int main (int argc, const char * argv[])
for (jj=0; jj < 4; jj++)
{
NSLog(@"%d,", jj);
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
-
- // Foreach statements
+
+ // Foreach statements
NSArray *values = @[@0, @1, @2, @3];
for (NSNumber *value in values)
{
NSLog(@"%@,", value);
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
// Object for loop statement. Can be used with any Objective-C object type
- for (id item in values) {
- NSLog(@"%@,", item);
- } // prints => "0,"
+ for (id item in values) {
+ NSLog(@"%@,", item);
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
@@ -250,7 +251,7 @@ int main (int argc, const char * argv[])
// Your statements here
@throw [NSException exceptionWithName:@"FileNotFoundException"
reason:@"File Not Found on System" userInfo:nil];
- } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
+ } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
{
NSLog(@"Exception: %@", e);
} @finally
@@ -259,17 +260,17 @@ int main (int argc, const char * argv[])
} // prints => "Exception: File Not Found on System"
// "Finally. Time to clean up."
- // NSError objects are useful for function arguments to populate on user mistakes.
+ // NSError objects are useful for function arguments to populate on user mistakes.
NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
-
+
///////////////////////////////////////
// Objects
///////////////////////////////////////
-
+
// Create an object instance by allocating memory and initializing it
// An object is not fully functional until both steps have been completed
MyClass *myObject = [[MyClass alloc] init];
-
+
// The Objective-C model of object-oriented programming is based on message
// passing to object instances
// In Objective-C one does not simply call a method; one sends a message
@@ -280,7 +281,7 @@ int main (int argc, const char * argv[])
// End of @autoreleasepool
}
-
+
// End the program
return 0;
}
@@ -301,9 +302,9 @@ int main (int argc, const char * argv[])
@interface MyClass : NSObject <MyProtocol> // NSObject is Objective-C's base object class.
{
// Instance variable declarations (can exist in either interface or implementation file)
- int count; // Protected access by default.
+ int count; // Protected access by default.
@private id data; // Private access (More convenient to declare in implementation file)
- NSString *name;
+ NSString *name;
}
// Convenient notation for public access variables to auto generate a setter method
// By default, setter method name is 'set' followed by @property variable name
@@ -313,7 +314,7 @@ int main (int argc, const char * argv[])
@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor
// You can customize the getter and setter names instead of using default 'set' name:
@property (getter=lengthGet, setter=lengthSet:) int length;
-
+
// Methods
+/- (return type)methodSignature:(Parameter Type *)parameterName;
@@ -335,7 +336,7 @@ int main (int argc, const char * argv[])
// To access public variables from the implementation file, @property generates a setter method
// automatically. Method name is 'set' followed by @property variable name:
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
-[myClass setCount:10];
+[myClass setCount:10];
NSLog(@"%d", [myClass count]); // prints => 10
// Or using the custom getter and setter method defined in @interface:
[myClass lengthSet:32];
@@ -358,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell
// as a variable
// SEL is the data type. @selector() returns a selector from method name provided
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
-SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
+SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
// Must put all method arguments into one object to send to performSelector function
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
@@ -382,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation
@synthesize roString = _roString; // _roString available now in @implementation
// Called before calling any class methods or instantiating any objects
-+ (void)initialize
++ (void)initialize
{
if (self == [MyClass class]) {
distance = 0;
@@ -392,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation
// Counterpart to initialize method. Called when an object's reference count is zero
- (void)dealloc
{
- [height release]; // If not using ARC, make sure to release class variable objects
+ [height release]; // If not using ARC, make sure to release class variable objects
[super dealloc]; // and call parent class dealloc
}
@@ -407,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation
return self;
}
// Can create constructors that contain arguments:
-- (id)initWithDistance:(int)defaultDistance
+- (id)initWithDistance:(int)defaultDistance
{
distance = defaultDistance;
return self;
@@ -418,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation
return @"Some string";
}
-+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
{
height = defaultHeight;
return [[self alloc] init];
@@ -434,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation
return @42;
}
-// Objective-C does not have private method declarations, but you can simulate them.
+// Objective-C does not have private method declarations, but you can simulate them.
// To simulate a private method, create the method in the @implementation but not in the @interface.
- (NSNumber *)secretPrivateMethod {
return @72;
@@ -453,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation
// Categories
///////////////////////////////////////
// A category is a group of methods designed to extend a class. They allow you to add new methods
-// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
-// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
+// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
+// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
// functionality to an object.
// Categories allow you to:
// -- Add methods to an existing class for organizational purposes.
// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
-// -- Add ability to create protected and private methods to classes.
-// NOTE: Do not override methods of the base class in a category even though you have the ability
-// to. Overriding methods may cause compiler errors later between different categories and it
+// -- Add ability to create protected and private methods to classes.
+// NOTE: Do not override methods of the base class in a category even though you have the ability
+// to. Overriding methods may cause compiler errors later between different categories and it
// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.
// Here is a simple Car base class.
@@ -493,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation
@end
// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
-// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
-// functionality to this existing Car. A good example would be to clean the car. So we would create
+// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
+// functionality to this existing Car. A good example would be to clean the car. So we would create
// a category to add these cleaning methods:
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
#import "Car.h" // Make sure to import base class to extend.
@@ -518,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation
NSLog(@"Waxed.");
}
-@end
+@end
// Any Car object instance has the ability to use a category. All they need to do is import it:
#import "Car+Clean.h" // Import as many different categories as you want to use.
@@ -533,7 +534,7 @@ int main (int argc, const char * argv[]) {
[mustang turnOn]; // Use methods from base Car class.
[mustang washWindows]; // Use methods from Car's Clean category.
}
- return 0;
+ return 0;
}
// Objective-C does not have protected method declarations but you can simulate them.
@@ -547,7 +548,7 @@ int main (int argc, const char * argv[]) {
//To use protected methods, import the category, then implement the methods:
#import "Car+Protected.h" // Remember, import in the @implementation file only.
-@implementation Car
+@implementation Car
- (void)lockCar {
NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
@@ -570,8 +571,8 @@ int main (int argc, const char * argv[]) {
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
// @implementation filename: Shape.m
#import "Shape.h"
-// Extensions live in the same file as the class @implementation.
-@interface Shape () // () after base class name declares an extension.
+// Extensions live in the same file as the class @implementation.
+@interface Shape () // () after base class name declares an extension.
@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
@@ -579,7 +580,7 @@ int main (int argc, const char * argv[]) {
@end
// The main @implementation:
-@implementation Shape
+@implementation Shape
@synthesize numOfSides = _numOfSides;
@@ -603,14 +604,14 @@ int main (int argc, const char * argv[]) {
@property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
- (void)turnOnEngine; // all defined methods.
@end
-// Below is an example class implementing the protocol.
+// Below is an example class implementing the protocol.
#import "CarUtilities.h" // Import the @protocol file.
@interface Car : NSObject <CarUtilities> // Name of protocol goes inside <>
// You don't need the @property or method names here for CarUtilities. Only @implementation does.
- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // You can use protocols as data too.
@end
-// The @implementation needs to implement the @properties and methods for the protocol.
+// The @implementation needs to implement the @properties and methods for the protocol.
@implementation Car : NSObject <CarUtilities>
@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
@@ -619,14 +620,14 @@ int main (int argc, const char * argv[]) {
_engineOn = YES; // how you implement a method, it just requires that you do implement it.
}
// You may use a protocol as data as you know what methods and variables it has implemented.
-- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
+- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
[objectOfSomeKind engineOn]; // You have access to object variables
- [objectOfSomeKind turnOnEngine]; // and the methods inside.
+ [objectOfSomeKind turnOnEngine]; // and the methods inside.
[objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
}
@end
-// Instances of Car now have access to the protocol.
+// Instances of Car now have access to the protocol.
Car *carInstance = [[Car alloc] init];
[carInstance setEngineOn:NO];
[carInstance turnOnEngine];
@@ -655,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
// See the problem is that Sister relies on Brother, and Brother relies on Sister.
#import "Sister.h"
-@protocol Sister; // These lines stop the recursion, resolving the issue.
+@protocol Sister; // These lines stop the recursion, resolving the issue.
@protocol Brother <NSObject>
-
+
- (void)beNiceToSister:(id <Sister>)sister;
@end
@@ -667,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
///////////////////////////////////////
// Blocks
///////////////////////////////////////
-// Blocks are statements of code, just like a function, that are able to be used as data.
+// Blocks are statements of code, just like a function, that are able to be used as data.
// Below is a simple block with an integer argument that returns the argument plus 4.
-int (^addUp)(int n); // Declare a variable to store the block.
-void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
+int (^addUp)(int n); // Declare a variable to store the block.
+void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
// Blocks have access to variables in the same scope. But the variables are readonly and the
-// value passed to the block is the value of the variable when the block is created.
+// value passed to the block is the value of the variable when the block is created.
int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17.
__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar.
-addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
+addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
NSLog(@"You may have as many lines in a block as you would like.");
NSSet *blockSet; // Also, you can declare local variables.
mutableVar = 32; // Assigning new value to __block variable.
- return n + outsideVar; // Return statements are optional.
+ return n + outsideVar; // Return statements are optional.
}
-int addUp = add(10 + 16); // Calls block code with arguments.
+int addUp = add(10 + 16); // Calls block code with arguments.
// Blocks are often used as arguments to functions to be called later, or for callbacks.
-@implementation BlockExample : NSObject
-
+@implementation BlockExample : NSObject
+
- (void)runBlock:(void (^)(NSString))block {
NSLog(@"Block argument returns nothing and takes in a NSString object.");
block(@"Argument given to block to execute."); // Calling block.
@@ -696,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments.
///////////////////////////////////////
// Memory Management
///////////////////////////////////////
-/*
+/*
For each object used in an application, memory must be allocated for that object. When the application
-is done using that object, memory must be deallocated to ensure application efficiency.
-Objective-C does not use garbage collection and instead uses reference counting. As long as
+is done using that object, memory must be deallocated to ensure application efficiency.
+Objective-C does not use garbage collection and instead uses reference counting. As long as
there is at least one reference to an object (also called "owning" an object), then the object
-will be available to use (known as "ownership").
+will be available to use (known as "ownership").
When an instance owns an object, its reference counter is increments by one. When the
object is released, the reference counter decrements by one. When reference count is zero,
-the object is removed from memory.
+the object is removed from memory.
-With all object interactions, follow the pattern of:
-(1) create the object, (2) use the object, (3) then free the object from memory.
+With all object interactions, follow the pattern of:
+(1) create the object, (2) use the object, (3) then free the object from memory.
*/
MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object
@@ -723,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still
// Automatic Reference Counting (ARC)
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
-// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
+// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
// you must not use retain, relase, or autorelease
-MyClass *arcMyClass = [[MyClass alloc] init];
+MyClass *arcMyClass = [[MyClass alloc] init];
// ... code using arcMyClass
-// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
+// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
// there is no need. It will insert this release statement for you
// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
@@ -747,4 +748,8 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not se
[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf)
+[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html)
+
+[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html)
+
[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started)
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index b0027fea..02435e4d 100644
--- a/ocaml.html.markdown
+++ b/ocaml.html.markdown
@@ -34,13 +34,13 @@ For a source file you can use "ocamlc -i /path/to/file.ml" command
to print all names and type signatures.
```
-$ cat sigtest.ml
+$ cat sigtest.ml
let inc x = x + 1
let add x y = x + y
-let a = 1
+let a = 1
-$ ocamlc -i ./sigtest.ml
+$ ocamlc -i ./sigtest.ml
val inc : int -> int
val add : int -> int -> int
val a : int
@@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;;
let sqr2 = sqr (-2) ;;
(* Every function must have at least one argument.
- Since some funcions naturally don't take any arguments, there's
+ Since some funcions naturally don't take any arguments, there's
"unit" type for it that has the only one value written as "()" *)
let print_hello () = print_endline "hello world" ;;
@@ -301,7 +301,7 @@ let l = IntList (1, EmptyList) ;;
(* Pattern matching is somewhat similar to switch statement in imperative
languages, but offers a lot more expressive power.
- Even though it may look complicated, it really boils down to matching
+ Even though it may look complicated, it really boils down to matching
an argument against an exact value, a predicate, or a type constructor.
The type system is what makes it so powerful. *)
@@ -320,7 +320,7 @@ let is_one = function
;;
(* Matching predicates, aka "guarded pattern matching". *)
-let abs x =
+let abs x =
match x with
| x when x < 0 -> -x
| _ -> x
diff --git a/perl.html.markdown b/perl.html.markdown
index 4e172406..1b86f410 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -102,6 +102,8 @@ for (@elements) {
print;
}
+# the Perlish post-condition way again
+print for @elements;
#### Regular expressions
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 8d425f7d..45b15f05 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -7,13 +7,11 @@ contributors:
- ["Nami-Doc", "http://github.com/Nami-Doc"]
---
-Perl 6 is a highly capable, feature-rich programming language made for at
+Perl 6 is a highly capable, feature-rich programming language made for at
least the next hundred years.
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
-the JVM and [the MoarVM](http://moarvm.com) and
-[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/),
-[the Parrot VM](http://parrot.org/).
+the JVM and [the MoarVM](http://moarvm.com).
Meta-note : the triple pound signs are here to denote headlines,
double paragraphs, and single notes.
@@ -75,7 +73,7 @@ say @array; #=> a 6 b
# except they get "flattened" (hash context), removing duplicated keys.
my %hash = 1 => 2,
3 => 4;
-my %hash = autoquoted => "key", # keys get auto-quoted
+my %hash = foo => "bar", # keys get auto-quoted
"some other" => "value", # trailing commas are okay
;
my %hash = <key1 value1 key2 value2>; # you can also create a hash
@@ -96,7 +94,6 @@ say %hash<key2>; # If it's a string, you can actually use <>
# (`{key1}` doesn't work, as Perl6 doesn't have barewords)
## * Subs (subroutines, or functions in most other languages).
-# Stored in variable, they use `&`.
sub say-hello { say "Hello, world" }
sub say-hello-to(Str $name) { # You can provide the type of an argument
@@ -107,8 +104,8 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument
## It can also have optional arguments:
sub with-optional($arg?) { # the "?" marks the argument optional
- say "I might return `(Any)` if I don't have an argument passed,
- or I'll return my argument";
+ say "I might return `(Any)` (Perl's "null"-like value) if I don't have
+ an argument passed, or I'll return my argument";
$arg;
}
with-optional; # returns Any
@@ -125,14 +122,14 @@ hello-to('You'); #=> Hello, You !
## You can also, by using a syntax akin to the one of hashes (yay unified syntax !),
## pass *named* arguments to a `sub`.
-# They're optional, and will default to "Any" (Perl's "null"-like value).
+# They're optional, and will default to "Any".
sub with-named($normal-arg, :$named) {
say $normal-arg + $named;
}
with-named(1, named => 6); #=> 7
# There's one gotcha to be aware of, here:
# If you quote your key, Perl 6 won't be able to see it at compile time,
-# and you'll have a single Pair object as a positional paramater,
+# and you'll have a single Pair object as a positional parameter,
# which means this fails:
with-named(1, 'named' => 6);
@@ -143,7 +140,7 @@ sub with-mandatory-named(:$str!) {
say "$str !";
}
with-mandatory-named(str => "My String"); #=> My String !
-with-mandatory-named; # run time error: "Required named parameter not passed"
+with-mandatory-named; # run time error: "Required named parameter not passed"
with-mandatory-named(3); # run time error: "Too many positional parameters passed"
## If a sub takes a named boolean argument ...
@@ -162,7 +159,7 @@ named-def; #=> 5
named-def(def => 15); #=> 15
# Since you can omit parenthesis to call a function with no arguments,
-# you need "&" in the name to capture `say-hello`.
+# you need "&" in the name to store `say-hello` in a variable.
my &s = &say-hello;
my &other-s = sub { say "Anonymous function !" }
@@ -173,8 +170,8 @@ sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything els
say @rest.join(' / ') ~ " !";
}
say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday !
- # Note that the splat did not consume
- # the parameter before.
+ # Note that the splat (the *) did not
+ # consume the parameter before.
## You can call a function with an array using the
# "argument list flattening" operator `|`
@@ -197,7 +194,7 @@ sub mutate($n is rw) {
say "\$n is now $n !";
}
-# If what you want is a copy instead, use `is copy`.
+# If what you want a copy instead, use `is copy`.
# A sub itself returns a container, which means it can be marked as rw:
my $x = 42;
@@ -234,7 +231,7 @@ say "Quite truthy" if True;
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
my $a = $condition ?? $value-if-true !! $value-if-false;
-# - `given`-`when` looks like other languages `switch`, but much more
+# - `given`-`when` looks like other languages' `switch`, but much more
# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
#
# This variable contains the default argument of a block,
@@ -290,7 +287,7 @@ for @array -> $variable {
# That means you can use `when` in a `for` just like you were in a `given`.
for @array {
say "I've got $_";
-
+
.say; # This is also allowed.
# A dot call with no "topic" (receiver) is sent to `$_` by default
$_.say; # the above and this are equivalent.
@@ -378,9 +375,11 @@ say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
-# You can use that in most places you'd expect, even assigning to an array
-my @numbers = ^20;
-my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
+# You can use that in most places you'd expect, even assigning to an array
+my @numbers = ^20;
+
+# Here numbers increase by "6"; more on `...` operator later.
+my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
# only the 15 needed values will be calculated.
say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87
@@ -525,7 +524,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)
# The constructs for declaring types are "class", "role",
# which you'll see later.
-# For now, let us examinate "subset":
+# For now, let us examine "subset":
# a "subset" is a "sub-type" with additional checks.
# For example: "a very big integer is an Int that's greater than 500"
# You can specify the type you're subtyping (by default, Any),
@@ -608,40 +607,39 @@ sub foo {
bar(); # call `bar` in-place
}
sub bar {
- say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s,
+ say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s,
# even though the blocks aren't nested (they're call-nested).
#=> 1
}
### Object Model
-## Perl 6 has a quite comprehensive object model
# You declare a class with the keyword `class`, fields with `has`,
-# methods with `method`. Every field to private, and is named `$!attr`,
-# but you have `$.` to get a public (immutable) accessor along with it.
-# (using `$.` is like using `$!` plus a `method` with the same name)
+# methods with `method`. Every attribute that is private is named `$!attr`.
+# Immutable public attributes are named `$.attr`
+# (you can make them mutable with `is rw`)
-# (Perl 6's object model ("SixModel") is very flexible,
+# Perl 6's object model ("SixModel") is very flexible,
# and allows you to dynamically add methods, change semantics, etc ...
# (this will not be covered here, and you should refer to the Synopsis).
class A {
has $.field; # `$.field` is immutable.
# From inside the class, use `$!field` to modify it.
- has $.other-field is rw; # You can obviously mark a public field `rw`.
+ has $.other-field is rw; # You can mark a public attribute `rw`.
has Int $!private-field = 10;
method get-value {
$.field + $!private-field;
}
-
+
method set-value($n) {
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
$!field = $n; # This works, because `$!` is always mutable.
-
+
$.other-field = 5; # This works, because `$.other-field` is `rw`.
}
-
+
method !private-method {
say "This method is private to the class !";
}
@@ -656,23 +654,22 @@ $a.other-field = 10; # This, however, works, because the public field
# is mutable (`rw`).
## Perl 6 also has inheritance (along with multiple inheritance)
-# (though considered a misfeature by many)
class A {
has $.val;
-
+
submethod not-inherited {
say "This method won't be available on B.";
say "This is most useful for BUILD, which we'll see later";
}
-
+
method bar { $.val * 5 }
}
class B is A { # inheritance uses `is`
method foo {
say $.val;
}
-
+
method bar { $.val * 10 } # this shadows A's `bar`
}
@@ -699,20 +696,20 @@ role PrintableVal {
# you "import" a mixin (a "role") with "does":
class Item does PrintableVal {
has $.val;
-
+
# When `does`-ed, a `role` literally "mixes in" the class:
# the methods and fields are put together, which means a class can access
# the private fields/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
-
+
# However, this:
# method print {}
# is ONLY valid when `print` isn't a `multi` with the same dispatch.
# (this means a parent class can shadow a child class's `multi print() {}`,
# but it's an error if a role does)
-
+
# NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
# will be shadowed, since the compiler will consider `ROLE` to be a class.
}
@@ -751,7 +748,7 @@ fail "foo"; # We're not trying to access the value, so no problem.
try {
fail "foo";
CATCH {
- default { say "It threw because we try to get the fail's value!" }
+ default { say "It threw because we tried to get the fail's value!" }
}
}
@@ -763,7 +760,7 @@ try {
### Packages
# Packages are a way to reuse code. Packages are like "namespaces", and any
# element of the six model (`module`, `role`, `class`, `grammar`, `subset`
-# and `enum`) are actually packages. (Packages are the lowest common denomitor)
+# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
# You usually don't use packages directly: you use `class Package::Name::Here;`,
@@ -773,7 +770,7 @@ module Hello::World { # Bracketed form
# that can be redeclared as something else later.
# ... declarations here ...
}
-module Parse::Text; # file-scoped form
+unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
@@ -797,10 +794,8 @@ my $actions = JSON::Tiny::Actions.new;
# You've already seen `my` and `has`, we'll now explore the others.
## * `our` (happens at `INIT` time -- see "Phasers" below)
-# Along with `my`, there are several others declarators you can use.
-# The first one you'll want for the previous part is `our`.
+# It's like `my`, but it also creates a package variable.
# (All packagish things (`class`, `role`, etc) are `our` by default)
-# it's like `my`, but it also creates a package variable:
module Foo::Bar {
our $n = 1; # note: you can't put a type constraint on an `our` variable
our sub inc {
@@ -812,7 +807,7 @@ module Foo::Bar {
say "Can't access me from outside, I'm my !";
}
}
-
+
say ++$n; # lexically-scoped variables are still available
}
say $Foo::Bar::n; #=> 1
@@ -829,7 +824,7 @@ constant why-not = 5, 15 ... *;
say why-not[^5]; #=> 5 15 25 35 45
## * `state` (happens at run time, but only once)
-# State variables are only executed one time
+# State variables are only initialized one time
# (they exist in other langages such as C as `static`)
sub fixed-rand {
state $val = rand;
@@ -862,7 +857,7 @@ for ^5 -> $a {
## * Compile-time phasers
BEGIN { say "[*] Runs at compile time, as soon as possible, only once" }
-CHECK { say "[*] Runs at compile time, instead as late as possible, only once" }
+CHECK { say "[*] Runs at compile time, as late as possible, only once" }
## * Run-time phasers
INIT { say "[*] Runs at run time, as soon as possible, only once" }
@@ -870,10 +865,13 @@ END { say "Runs at run time, as late as possible, only once" }
## * Block phasers
ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" }
-LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." }
+LEAVE { say "Runs everytime you leave a block, even when an exception
+ happened. Repeats on loop blocks." }
-PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" }
-POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" }
+PRE { say "Asserts a precondition at every block entry,
+ before ENTER (especially useful for loops)" }
+POST { say "Asserts a postcondition at every block exit,
+ after LEAVE (especially useful for loops)" }
## * Block/exceptions phasers
sub {
@@ -891,12 +889,12 @@ for ^5 {
## * Role/class phasers
COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" }
-# They allow for cute trick or clever code ...:
-say "This code took " ~ (time - CHECK time) ~ "s to run";
+# They allow for cute tricks or clever code ...:
+say "This code took " ~ (time - CHECK time) ~ "s to compile";
# ... or clever organization:
sub do-db-stuff {
- ENTER $db.start-transaction; # New transaction everytime we enter the sub
+ $db.start-transaction; # start a new transaction
KEEP $db.commit; # commit the transaction if all went well
UNDO $db.rollback; # or rollback if all hell broke loose
}
@@ -1020,7 +1018,7 @@ sub circumfix:<[ ]>(Int $n) {
$n ** $n
}
say [5]; #=> 3125
- # circumfix is around. Again, not whitespace.
+ # circumfix is around. Again, no whitespace.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
# post-circumfix is
@@ -1052,9 +1050,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)
# Basically, they're operators that apply another operator.
## * Reduce meta-operator
-# It's a prefix meta-operator that takes a binary functions and
+# It's a prefix meta-operator that takes a binary function and
# one or many lists. If it doesn't get passed any argument,
-# it either return a "default value" for this operator
+# it either returns a "default value" for this operator
# (a meaningless value) or `Any` if there's none (examples below).
#
# Otherwise, it pops an element from the list(s) one at a time, and applies
@@ -1075,8 +1073,8 @@ say [//] Nil, Any, False, 1, 5; #=> False
# Default value examples:
-say [*] (); #=> 1
-say [+] (); #=> 0
+say [*] (); #=> 1
+say [+] (); #=> 0
# meaningless values, since N*1=N and N+0=N.
say [//]; #=> (Any)
# There's no "default value" for `//`.
@@ -1089,7 +1087,7 @@ say [[&add]] 1, 2, 3; #=> 6
# This one is an infix meta-operator than also can be used as a "normal" operator.
# It takes an optional binary function (by default, it just creates a pair),
# and will pop one value off of each array and call its binary function on these
-# until it runs out of elements. It runs the an array with all these new elements.
+# until it runs out of elements. It returns an array with all of these new elements.
(1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array
1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function
@@ -1109,8 +1107,7 @@ say [[&add]] 1, 2, 3; #=> 6
# (and might include a closure), and on the right, a value or the predicate
# that says when to stop (or Whatever for a lazy infinite list).
my @list = 1, 2, 3 ... 10; # basic deducing
-#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop,
- # because Perl 6 can't figure out the end
+#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end
my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element
# (the iteration when the predicate matches).
my @list = 1, 3, 9 ... * > 30; # you can use a predicate
@@ -1222,7 +1219,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)
# they use a more perl6-ish syntax:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
# You can use ranges:
-say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou'
+say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae'
# Just like in normal regexes, if you want to use a special character, escape it
# (the last one is escaping a space)
say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !'
@@ -1244,7 +1241,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
# The previous line returns `True`.
-# We match the "abc" 1 or more time (the `+` was applied to the group).
+# We match the "ABC" 1 or more time (the `+` was applied to the group).
# But this does not go far enough, because we can't actually get back what
# we matched.
@@ -1287,10 +1284,12 @@ say $/[0][0].Str; #=> ~
# This stems from a very simple fact: `$/` does not contain strings, integers or arrays,
# it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods.
-# (but you can also just use `match<key>` for hash access and `match[idx]` for array access)
+# (but you can also just use `match<key>` for hash access
+# and `match[idx]` for array access)
say $/[0].list.perl; #=> (Match.new(...),).list
- # We can see it's a list of Match objects. Those contain a bunch of infos:
- # where the match started/ended, the "ast" (see actions later), etc.
+ # We can see it's a list of Match objects. Those contain
+ # a bunch of infos: where the match started/ended,
+ # the "ast" (see actions later), etc.
# You'll see named capture below with grammars.
## Alternatives - the `or` of regexps
@@ -1328,14 +1327,14 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
### Extra: the MAIN subroutime
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
-# It's very powerful, because Perl 6 actually parses the argument
+# It's very powerful, because Perl 6 actually parses the arguments
# and pass them as such to the sub. It also handles named argument (`--foo`)
# and will even go as far as to autogenerate a `--help`
sub MAIN($name) { say "Hello, $name !" }
# This produces:
# $ perl6 cli.pl
# Usage:
-# t.pl <name>
+# t.pl <name>
# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
# (using a "Bool" for the named argument so that we can do `--replace`
@@ -1346,9 +1345,9 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
# This produces:
-# $ perl 6 cli.pl
+# $ perl6 cli.pl
# Usage:
-# t.pl [--replace] add <key> <value>
+# t.pl [--replace] add <key> <value>
# t.pl remove <key>
# t.pl [--as=<Str>] import (File)
# As you can see, this is *very* powerful.
@@ -1400,7 +1399,7 @@ for <well met young hero we shall meet later> {
# (explained in details below).
.say
}
-
+
if rand == 0 ff rand == 1 { # compare variables other than `$_`
say "This ... probably will never run ...";
}
@@ -1429,7 +1428,7 @@ for <well met young hero we shall meet later> {
# A flip-flop can change state as many times as needed:
for <test start print it stop not printing start print again stop not anymore> {
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
- #=> "print this printing again"
+ #=> "print it print again"
}
# you might also use a Whatever Star,
@@ -1461,4 +1460,3 @@ If you want to go further, you can:
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
-
diff --git a/php.html.markdown b/php.html.markdown
index 93066284..39ec5aef 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -515,7 +515,7 @@ class MyClass
}
}
-// Class constants can always be accessed statically
+// Class constants can always be accessed statically
echo MyClass::MY_CONST; // Outputs 'value';
echo MyClass::$staticVar; // Outputs 'static';
@@ -693,8 +693,43 @@ use My\Namespace as SomeOtherNamespace;
$cls = new SomeOtherNamespace\MyClass();
+/**********************
+* Error Handling
+*
*/
+// Simple error handling can be done with try catch block
+
+try {
+ // Do something
+} catch ( Exception $e) {
+ // Handle exception
+}
+
+// When using try catch blocks in a namespaced enviroment use the following
+
+try {
+ // Do something
+} catch (\Exception $e) {
+ // Handle exception
+}
+
+// Custom exceptions
+
+class MyException extends Exception {}
+
+try {
+
+ $condition = true;
+
+ if ($condition) {
+ throw new MyException('Something just happend');
+ }
+
+} catch (MyException $e) {
+ // Handle my exception
+}
+
```
## More Information
@@ -709,4 +744,4 @@ If you're coming from a language with good package management, check out
[Composer](http://getcomposer.org/).
For common standards, visit the PHP Framework Interoperability Group's
-[PSR standards](https://github.com/php-fig/fig-standards). \ No newline at end of file
+[PSR standards](https://github.com/php-fig/fig-standards).
diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown
index 451df4f3..43688724 100644
--- a/pt-br/c-pt.html.markdown
+++ b/pt-br/c-pt.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
translators:
- ["João Farias", "https://github.com/JoaoGFarias"]
+ - ["Elton Viana", "https://github.com/eltonvs"]
lang: pt-br
filename: c-pt.el
---
@@ -139,13 +140,13 @@ int main() {
int var_length_array[size]; // declara o VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
- //Uma possível saída para esse programa seria:
- // > Entre o tamanho do array:: 10
+ // Uma possível saída para esse programa seria:
+ // > Entre o tamanho do array: 10
// > sizeof array = 40
// String são apenas arrays de caracteres terminados por um
- // byte NUL (0x00), representado em string pelo caracter especial '\0'.
- // (Não precisamos incluir o byte NUL em literais de string; o compilador
+ // byte nulo (0x00), representado em string pelo caracter especial '\0'.
+ // (Não precisamos incluir o byte nulo em literais de string; o compilador
// o insere ao final do array para nós.)
char uma_string[20] = "Isto é uma string";
// Observe que 'é' não está na tabela ASCII
@@ -153,8 +154,8 @@ int main() {
// Porém, comentários podem conter acentos
printf("%s\n", uma_string); // %s formata a string
- printf("%d\n", uma_string[16]); // => 0
- // i.e., byte #17 é 0 (assim como 18, 19, e 20)
+ printf("%d\n", uma_string[17]); // => 0
+ // i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...)
// Se temos caracteres entre aspas simples, temos um caracter literal.
// Seu tipo é `int`, *não* `char` (por razões históricas).
@@ -220,11 +221,11 @@ int main() {
0 || 1; // => 1 (Ou lógico)
0 || 0; // => 0
- //Expressão condicional ( ? : )
+ //Expressão condicional ternária ( ? : )
int a = 5;
int b = 10;
int z;
- z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
+ z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b."
//Operadores de incremento e decremento:
char *s = "iLoveC";
@@ -290,6 +291,8 @@ int main() {
for (i = 0; i <= 5; i++) {
; // Use ponto e vírgula para agir como um corpo (declaração nula)
}
+ // Ou
+ for (i = 0; i <= 5; i++);
// Criando branchs com escolhas múltiplas: switch()
switch (alguma_expressao_integral) {
diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown
new file mode 100644
index 00000000..dbc0c25c
--- /dev/null
+++ b/pt-br/clojure-macros-pt.html.markdown
@@ -0,0 +1,154 @@
+---
+language: clojure
+filename: learnclojure-pt.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Raphael Bezerra do Nascimento"]
+lang: pt-br
+---
+
+Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic)
+do Clojure lhe dá acesso a toda a extensão da linguagem
+para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem
+às suas necessidades.
+
+Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas
+quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado.
+
+Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em
+[Clojure em Y Minutos](/docs/clojure/).
+
+```clojure
+;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa
+;; ser avaliada como codigo Clojure.
+;;
+;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World")
+(defmacro my-first-macro []
+ (list reverse "Hello World"))
+
+;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1.
+;;
+;; Note que a chamada deve utilizar aspas simples.
+(macroexpand '(my-first-macro))
+;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hello World")
+
+;; Você pode avaliar o resultad de macroexpand diretamente:
+(eval (macroexpand '(my-first-macro)))
+; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; mas você deve usar esse mais suscinto, sintax como de função:
+(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta
+;; para criar listas nas suas macros:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hello World"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hello World")
+;; Note que reverse não é mais uma função objeto, mas um simbolo.
+
+;; Macros podem ter argumentos.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o
+;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples
+;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Lembrar o do!
+
+(macroexpand '(unless true (reverse "Hello World")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hello World")))
+
+;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso.
+;; caso contrario, retorna nil
+
+(unless true "Hello") ; -> nil
+(unless false "Hello") ; -> "Hello"
+
+;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;;s Para evitar isso, use gensym para receber um identificador unico
+(gensym 'x) ; -> x1281 (ou outra coisa)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente
+(defmacro define-x-hygenically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygenically) ; -> (2)
+(list x) ; -> (4)
+
+;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco
+;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida)
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Given args [x (+ y)], return (+ x y)"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Podemos testar isso imediatamente, sem criar uma macro
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação
+(defmacro inline-2 [form]
+ (inline-2-helper form)))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com /
+
+### Leitura adicional
+
+Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/)
+[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
+
+Documentos oficiais
+[http://clojure.org/macros](http://clojure.org/macros)
+
+Quando utilizar macros?
+[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown
new file mode 100644
index 00000000..ed6f6c4c
--- /dev/null
+++ b/pt-br/css-pt.html.markdown
@@ -0,0 +1,257 @@
+---
+language: css
+filename: learncss-pt.css
+contributors:
+ - ["Mohammad Valipour", "https://github.com/mvalipour"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
+ - ["Connor Shea", "https://github.com/connorshea"]
+ - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
+translators:
+ - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+lang: pt-br
+---
+
+Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum.
+
+CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web.
+
+CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles.
+
+Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular.
+
+**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/).
+O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais.
+
+```css
+/* Comentários aparecem dentro do slash-asterisk, tal como esta linha!
+ não há "comentários de uma linha"; este é o único estilo de comentário * /
+
+/* ####################
+ ## SELETORES
+ #################### */
+
+/* O seletor é usado para direcionar um elemento em uma página.
+ seletor { propriedade: valor; / * Mais propriedades ... * / }
+
+/*
+Abaixo um elemento de exemplo:
+
+<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' />
+*/
+
+/* Você pode direciona-lo usando uma das suas classes CSS */
+.class1 { }
+
+/* ou ambas as classes! */
+.class1.class2 { }
+
+/* ou o seu nome */
+div { }
+
+/* ou o seu id */
+#anID { }
+
+/* ou utilizando o fator de que tem um atributo!*/
+[attr] { font-size:smaller; }
+
+/* ou que o atributo tem um valor específico */
+[attr='value'] { font-size:smaller; }
+
+/* começa com um valor (CSS 3) */
+[attr^='val'] { font-size:smaller; }
+
+/* ou terminando com um valor (CSS 3) */
+[attr$='ue'] { font-size:smaller; }
+
+
+/* Ou contém um valor em uma lista separada por espaços */
+[otherAttr ~ = 'foo'] {}
+[otherAttr ~ = 'bar'] {}
+
+/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */
+[otherAttr | = 'en'] {font-size: smaller; }
+
+
+/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não
+   colocar espaços entre eles. */
+classe div.some [attr $ = 'ue'] {}
+
+/* Você pode selecionar um elemento que é filho de outro elemento */
+div.some-parent> .class-name {}
+
+/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de
+   seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes
+   nivelar por baixo da árvore. */
+div.some-parent class-name {}
+
+/* Atenção: o mesmo seletor sem espaço tem um outro significado.
+   Você consegue adivinhar o que? */
+div.some-parent.class-name {}
+
+/* Você também pode selecionar um elemento com base em seu irmão adjacente */
+.i am just-antes + .Este elemento {}
+
+/* Ou qualquer irmão que o precede */
+.i am-qualquer-elemento antes ~ .Este elemento {}
+
+/* Existem alguns selectores chamado pseudo classes que podem ser usados para selecionar um
+   elemento quando ele está em um determinado estado */
+
+/* Por exemplo, quando o cursor passa sobre um elemento */
+seletor:hover {}
+
+/* Ou um link foi visitado */
+seletor:visited {}
+
+/* Ou não tenha sido visitado */
+seletor:link {}
+
+/* Ou um elemento em foco */
+seletor:focus {}
+
+/* Qualquer elemento que é o primeiro filho de seu pai */
+seletor:first-child {}
+
+/* Qualquer elemento que é o último filho de seu pai */
+seletor:last-child {}
+
+/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */
+
+/* Corresponde a um primeiro filho virtual do elemento selecionado */
+seletor::before {}
+
+/* Corresponde a um último filho virtual do elemento selecionado */
+seletor::after {}
+
+/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos
+   elemento */
+* {} /* */ Todos os elementos
+.parent * {} /* */ todos os descendentes
+.parent> * {} /* */ todas as crianças
+
+/* ####################
+   ## PROPRIEDADES
+   #################### */
+
+seletor {
+
+    /* Unidades de comprimento pode ser absoluta ou relativa. */
+
+    /* Unidades relativas */
+    width: 50%; /* Percentagem de largura elemento pai */
+    font-size: 2em; /* Múltiplos de font-size original de elemento */
+    font-size: 2rem; /* Ou do elemento raiz font-size */
+    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */
+    font-size: 2vh; /* Ou a sua altura */
+    font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */
+    font-size: 2vmax; /* Ou superior */
+
+    /* Unidades absolutas */
+    width: 200px; /* píxeis */
+    font-size: 20pt; /* Pontos */
+    width: 5cm; /* Centímetros */
+    min-width: 50mm; /* Milímetros */
+    max-width: 5 polegadas; /* Polegadas */
+
+    /* Cores */
+    color: # F6E; /* Formato hexadecimal curto */
+    color: # FF66EE; /* Formato hexadecimal longo */
+    color: tomato; /* Uma cor nomeada */
+    color: rgb (255, 255, 255); /* Como valores rgb */
+    cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */
+    cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */
+    color: transparent; /* Equivale a definir o alfa a 0 */
+    cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */
+    cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */
+
+    /* Imagens como fundos de elementos */
+    background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */
+
+    /* Fontes */
+    font-family: Arial;
+    /* Se o nome da família de fonte tem um espaço, deve ser citado */
+    font-family: "Courier New";
+    /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */
+    font-family: "Courier New", Trebuchet, Arial, sans-serif;
+}
+```
+
+## Uso
+
+Guardar uma folha de estilo CSS com a extensão `.css`.
+
+```xml
+<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o
+     método recomendado. Consulte http://stackoverflow.com/questions/8284365 -->
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
+
+<!-- Você também pode incluir alguns CSS inline na sua marcação. -->
+<style>
+   a { color: purple; }
+</style>
+
+<!-- Ou diretamente definir propriedades CSS no elemento. -->
+<div style="border: 1px solid red;">
+</div>
+```
+
+## Precedência ou Cascata
+
+Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior.
+
+Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata.
+
+Dado o seguinte CSS:
+
+```css
+/* UMA */
+p.class1[attr="value"]
+
+/* B */
+p.class1 {}
+
+/* C */
+p.class2 {}
+
+/* D */
+p { }
+
+/* E */
+p { property: value !important; }
+```
+
+e a seguinte marcação:
+
+```xml
+<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
+```
+
+A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco.
+
+* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso.
+* `F` é a próxima, porque é um estilo interno.
+* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`.
+* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`.
+* `B` é o próximo.
+* `D` é a última.
+
+## Compatibilidade
+
+A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso.
+
+## Recursos
+
+* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/)
+
+## Leitura adicional
+
+* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento
+* [CSS-Tricks](https://css-tricks.com)
diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown
new file mode 100644
index 00000000..105896b2
--- /dev/null
+++ b/pt-br/sass-pt.html.markdown
@@ -0,0 +1,477 @@
+---
+language: sass
+filename: learnsass-pt.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+translators:
+ - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"]
+lang: pt-br
+---
+
+Sass é uma linguagem de extensão CSS que adiciona recursos, como variáveis, aninhamento, mixins e muito mais.
+Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os desenvolvedores a escrever código de fácil manutenção e DRY (Do not Repeat Yourself).
+
+Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula.
+Este tutorial é escrito usando SCSS.
+
+Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente.
+
+```scss
+
+
+// Comentários de linha única são removidos quando Sass é compilado para CSS.
+
+/* Comentários multi-line são preservados. */
+
+
+
+/*Variáveis
+==============================*/
+
+
+
+/* É possível armazenar um valor CSS (tais como a cor) de uma variável.
+Use o símbolo "$" para criar uma variável. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* Você pode usar as variáveis em toda a sua folha de estilo.
+Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* Quando compilar ficaria assim: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/ * Este é muito mais fácil de manter do que ter de mudar a cor
+cada vez que aparece em toda a sua folha de estilo. * /
+
+
+
+
+/*Mixins
+==============================*/
+
+
+
+/* Se você achar que você está escrevendo o mesmo código para mais de um
+elemento, você pode querer armazenar esse código em um mixin.
+
+Use a diretiva '@mixin', além de um nome para o seu mixin. */
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* Você pode usar o mixin com '@include' e o nome mixin. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/* Apoś compilar ficaria assim: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* Você pode usar mixins para criar uma propriedade estenográfica. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/* O que você pode invocar passando argumentos de largura e altura. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* Isso compilado ficará assim: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/*Funções
+==============================*/
+
+
+
+/* Sass fornece funções que podem ser utilizados para realizar uma variedade de
+    tarefas. Considere o seguinte */
+
+/* Funções pode ser chamado usando seu nome e passando o
+    argumentos necessários */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Sass code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos
+   mixins. Ao tentar escolher entre uma função ou um mixin, lembre-
+   que mixins são os melhores para gerar CSS enquanto as funções são melhores para
+   lógica que pode ser usado em todo o seu código Sass. Os exemplos
+   seção Operadores Math 'são candidatos ideais para se tornar um reutilizável
+   função. */
+
+/* Esta função terá um tamanho de destino eo tamanho do pai e calcular
+   e voltar a percentagem */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compila para: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/* Extend (Herança)
+============================== */
+
+
+
+/*Extend é uma maneira de compartilhar as propriedades de um seletor com outro. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Ampliando uma declaração CSS é preferível a criação de um mixin
+   por causa da maneira agrupa as classes que todos compartilham
+   o mesmo estilo base. Se isso for feito com um mixin, a largura,
+   altura, e a borda seria duplicado para cada instrução que
+   o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será
+   adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */
+
+
+
+/*Assentamento
+==============================*/
+
+
+
+/ * Sass permite seletores ninhos dentro seletores * /
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' será substituído pelo selector pai. */
+/* Você também pode aninhar pseudo-classes. */
+/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável.
+Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação.
+Por exemplo: */
+
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compila para: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Parciais e Importações
+==============================*/
+
+
+/* Sass permite criar arquivos parciais. Isso pode ajudar a manter seu Sass
+   código modularizado. Arquivos parciais deve começar com um '_', por exemplo, _reset.css.
+   Parciais não são geradas em CSS. */
+
+
+
+/* Considere o seguinte CSS que nós vamos colocar em um arquivo chamado _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Sass takes the
+ imported file and combines it with the compiled code. */
+
+/* Sass oferece @import que pode ser usado para importar parciais em um arquivo.
+   Isso difere da declaração CSS @import tradicional, que faz
+   outra solicitação HTTP para buscar o arquivo importado. Sass converte os
+   importadas arquivo e combina com o código compilado. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Placeholder Selectors
+==============================*/
+
+
+
+/* Placeholders are useful when creating a CSS statement to extend. If you
+ wanted to create a CSS statement that was exclusively used with @extend,
+ you can do so using a placeholder. Placeholders begin with a '%' instead
+ of '.' or '#'. Placeholders will not appear in the compiled CSS. */
+
+/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você
+   queria criar uma instrução CSS que foi usado exclusivamente com @extend,
+   Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez
+   de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * /
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compilado para: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/*Operações Math
+============================== * /
+
+
+/* Sass provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Sass files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem
+   ser úteis para calcular os valores diretamente no seu Sass arquivos em vez
+   de usar valores que você já calculados pela mão. Abaixo está um exemplo
+   de uma criação de um projeto simples de duas colunas. * /
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+
+
+## SASS ou Sass?
+Alguma vez você já se perguntou se Sass é um acrônimo ou não? Você provavelmente não tem, mas vou dizer-lhe de qualquer maneira. O nome do idioma é uma palavra, "Sass", e não uma sigla.
+Porque as pessoas estavam constantemente a escrevê-lo como "SASS", o criador da linguagem de brincadeira chamou de "StyleSheets Sintaticamente Incríveis".
+
+
+## Prática Sass
+Se você quiser jogar com Sass em seu navegador, vá para [SassMeister](http://sassmeister.com/).
+Você pode usar uma sintaxe, basta ir para as configurações e selecionar Sass ou SCSS.
+
+
+## Compatibilidade
+
+Sass pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo
+em CSS. Você vai querer verificar se o CSS que você está usando é compatível
+com os seus navegadores de destino.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificação de compatibilidade.
+
+
+## Leitura
+* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) fornece tutoriais (iniciante avançados) e artigos.
diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown
new file mode 100644
index 00000000..a4c1c02b
--- /dev/null
+++ b/pt-pt/scala-pt.html.markdown
@@ -0,0 +1,651 @@
+---
+language: Scala
+filename: learnscala-pt.scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
+ - ["Ha-Duong Nguyen", "http://reference-error.org"]
+translators:
+ - ["João Costa", "http://joaocosta.eu"]
+lang: pt-pt
+---
+
+Scala - a linguagem escalável
+
+```scala
+
+/*
+ Prepare tudo:
+
+ 1) Faça Download do Scala - http://www.scala-lang.org/downloads
+ 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na
+ variável de ambiente `PATH`
+ 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer:
+
+ scala>
+
+ Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete).
+ Pode escrever qualquer expressão de Scala e o resultado será imprimido.
+ Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já,
+ vamos começar com os básicos.
+
+*/
+
+
+/////////////////////////////////////////////////
+// 1. Basicos
+/////////////////////////////////////////////////
+
+// Uma linha de comentários é marcada com duas barras
+
+/*
+ Comentários de multiplas linhas, como se pode ver neste exemplo, são assim.
+*/
+
+// Imprimir, forçando uma nova linha no final
+println("Hello world!")
+println(10)
+
+// Imprimir, sem forçar uma nova linha no final
+print("Hello world")
+
+// Valores são declarados com var ou val.
+// As declarações val são imutáveis, enquanto que vars são mutáveis.
+// A immutabilidade é uma propriedade geralmente vantajosa.
+val x = 10 // x é agora 10
+x = 20 // erro: reatribuição de um val
+var y = 10
+y = 20 // y é agora 12
+
+/*
+ Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima
+ não especificamos um tipo. Isto é devido a uma funcionalidade chamada
+ inferência de tipos. Na maior parte dos casos, o compilador de scala consegue
+ inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre.
+ Podemos declarar o tipo de uma variável da seguinte forma:
+*/
+val z: Int = 10
+val a: Double = 1.0
+
+// Note a conversão automática de Int para Double: o resultado é 10.0, não 10
+val b: Double = 10
+
+// Valores booleanos
+true
+false
+
+// Operações booleanas
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+// A matemática funciona da maneira habitual
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
+
+
+// Avaliar expressões na REPL dá o tipo e valor do resultado
+
+1 + 7
+
+/* A linha acima resulta em:
+
+ scala> 1 + 7
+ res29: Int = 8
+
+ Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com
+ o valor 8.
+
+ Note que "res29" é um nome de uma variavel gerado sequencialmente para
+ armazenar os resultados das expressões que escreveu, por isso o resultado
+ pode ser ligeiramente diferente.
+*/
+
+"Strings em scala são rodeadas por aspas"
+'a' // Um caracter de Scala
+// 'Strings entre plicas não existem' <= Isto causa um erro
+
+// Strings tem os métodos de Java habituais definidos
+"olá mundo".length
+"olá mundo".substring(2, 6)
+"olá mundo".replace("á", "é")
+
+// Para além disso, também possuem métodos de Scala.
+// Ver: scala.collection.immutable.StringOps
+"olá mundo".take(5)
+"olá mundo".drop(5)
+
+// Interpolação de Strings: repare no prefixo "s"
+val n = 45
+s"Temos $n maçãs" // => "Temos 45 maçãs"
+
+// Expressões dentro de Strings interpoladas também são possíveis
+val a = Array(11, 9, 6)
+s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos."
+s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs."
+s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4"
+
+// Strings interpoladas são formatadas com o prefixo "f"
+f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25"
+f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454"
+
+// Strings prefixadas com "raw" ignoram caracteres especiais
+raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r."
+
+// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string:
+"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown""
+
+// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas
+val html = """<form id="daform">
+ <p>Carrega aqui, Zé</p>
+ <input type="submit">
+ </form>"""
+
+
+/////////////////////////////////////////////////
+// 2. Funções
+/////////////////////////////////////////////////
+
+// Funções são definidas como:
+//
+// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... }
+//
+// Se vem de linugagens mais tradicionais, repare na omissão da palavra
+// return keyword. Em Scala, a ultima expressão de um bloco é o seu
+// valor de retorno
+def somaQuadrados(x: Int, y: Int): Int = {
+ val x2 = x * x
+ val y2 = y * y
+ x2 + y2
+}
+
+// As { } podem ser omitidas se o corpo da função for apenas uma expressão:
+def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y
+
+// A sintaxe para chamar funções deve ser familiar:
+somaQuadrados(3, 4) // => 25
+
+// Na maior parte dos casos (sendo funções recursivas a principal excepção), o
+// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos
+// é aplicada aos valores de retorno
+def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int
+
+// Funções podem ter parâmetros por omissão:
+def somaComOmissão(x: Int, y: Int = 5) = x + y
+somaComOmissão(1, 2) // => 3
+somaComOmissão(1) // => 6
+
+
+// Funções anónimas são definidas da seguinte forma:
+(x: Int) => x * x
+
+// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido
+// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma
+// funão que recebe Int e retorna Int.
+val quadrado: Int => Int = x => x * x
+
+// Funcões anónimas são chamadas como funções normais:
+quadrado(10) // => 100
+
+// Se cada argumento de uma função anónima for usado apenas uma vez, existe
+// uma forma ainda mais curta de os definir. Estas funções anónumas são
+// extremamente comuns, como será visto na secção sobre estruturas de dados.
+val somaUm: Int => Int = _ + 1
+val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3)
+
+somaUm(5) // => 6
+somaEstranha(2, 4) // => 16
+
+
+// O código return existe em Scala, mas apenas retorna do def mais interior
+// que o rodeia.
+// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros.
+// Não tem qualquer efeito em funções anónimas, por exemplo:
+def foo(x: Int): Int = {
+ val funcAnon: Int => Int = { z =>
+ if (z > 5)
+ return z // Esta linha faz com que z seja o retorno de foo!
+ else
+ z + 2 // Esta linha define o retorno de funcAnon
+ }
+ funcAnon(x) // Esta linha define o valor de retorno de foo
+}
+
+
+/////////////////////////////////////////////////
+// 3. Controlo de fluxo
+/////////////////////////////////////////////////
+
+1 to 5
+val r = 1 to 5
+r.foreach(println)
+
+r foreach println
+// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as
+// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis
+
+(5 to 1 by -1) foreach (println)
+
+// Ciclos while
+var i = 0
+while (i < 10) { println("i " + i); i += 1 }
+
+while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê?
+
+i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico -
+ // executa sequencialmente enquanto muda uma variável. Ciclos while são
+ // rápidos, por vezes até mais que ciclos de Java, mas combinadores e
+ // compreensões (usados anteriormente) são mais fáceis de entender e
+ // paralelizar
+
+// Um ciclo do while
+i = 0
+do {
+ println("i ainda é menor que 10")
+ i += 1
+} while (i < 10)
+
+// A forma idiomática em Scala de definir acções recorrentes é através de
+// recursão em cauda.
+// Funções recursivas necessitam de um tipo de retorno definido explicitamente.
+// Neste caso, é Unit.
+def mostraNumerosEntre(a: Int, b: Int): Unit = {
+ print(a)
+ if (a < b)
+ mostraNumerosEntre(a + 1, b)
+}
+mostraNumerosEntre(1, 14)
+
+
+// Condicionais
+
+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")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+
+/////////////////////////////////////////////////
+// 4. Estruturas de dados
+/////////////////////////////////////////////////
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Lança uma excepção
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Lança uma excepção
+
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+val s = Set(1, 3, 7)
+s(0)
+s(1)
+
+/* Veja a documentação de mapas de scala em -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+ * e verifique que a consegue aceder
+ */
+
+
+// Tuplos
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "três")
+
+(a, 2, "três")
+
+// Porquê ter isto?
+val divideInts = (x: Int, y: Int) => (x / y, x % y)
+
+divideInts(10, 3) // A função divideInts returna o resultado e o resto
+
+// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice
+// (começado em 1) do elemento
+val d = divideInts(10, 3)
+
+d._1
+
+d._2
+
+
+/////////////////////////////////////////////////
+// 5. Programação Orientada a Objectos
+/////////////////////////////////////////////////
+
+/*
+ Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples
+ (valores, funções, etc). Estas expressões são suficientes para executar no
+ interpretador da linha de comandos para testes rápidos, mas não podem existir
+ isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um
+ ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas
+ construções de topo permitidas são:
+
+ - object
+ - class
+ - case class
+ - trait
+
+ Vamos agora explicar o que são:
+*/
+
+// Classes são semelhantes a classes noutras linguagens. Os argumentos do
+// construtor são declarados após o nome da classe, sendo a inicialização feita
+// no corpo da classe.
+class Cão(rc: String) {
+ // Código de construção
+ var raça: String = rc
+
+ // Define um método chamado "ladra", que retorna uma String
+ def ladra = "Woof, woof!"
+
+ // Valores e métodos são assumidos como públicos, mas é possivel usar
+ // os códigos "protected" and "private".
+ private def dormir(horas: Int) =
+ println(s"Vou dormir por $horas horas")
+
+ // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima
+ // linha, a classe Cão é declarada como abstracta
+ // abstract class Cão(...) { ... }
+ // def persegue(oQue: String): String
+}
+
+val oMeuCão = new Cão("greyhound")
+println(oMeuCão.raça) // => "greyhound"
+println(oMeuCão.ladra) // => "Woof, woof!"
+
+
+// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum
+// que classes de Scala possuam um "objecto companheiro", onde o comportamento
+// por instância é capturado nas classes, equanto que o comportamento
+// relacionado com todas as instancias dessa classe ficam no objecto.
+// A diferença é semelhante a métodos de classes e métodos estáticos noutras
+// linguagens. Note que objectos e classes podem ter o mesmo nome.
+object Cão {
+ def raçasConhecidas = List("pitbull", "shepherd", "retriever")
+ def criarCão(raça: String) = new Cão(raça)
+}
+
+
+// Case classes são classes com funcionalidades extra incluidas. Uma questão
+// comum de iniciantes de scala é quando devem usar classes e quando devem usar
+// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se
+// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes
+// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal
+// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos
+// métods, sendo que estes raramente possuem efeitos secundários.
+case class Pessoa(nome: String, telefone: String)
+
+// Cria uma nova instancia. De notar que case classes não precisam de "new"
+val jorge = Pessoa("Jorge", "1234")
+val cátia = Pessoa("Cátia", "4567")
+
+// Case classes trazem algumas vantagens de borla, como acessores:
+jorge.telefone // => "1234"
+
+// Igualdade por campo (não é preciso fazer override do .equals)
+Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false
+
+// Cópia simples
+// outroJorge == Person("jorge", "9876")
+val outroJorge = jorge.copy(telefone = "9876")
+
+// Entre outras. Case classes também suportam correspondência de padrões de
+// borla, como pode ser visto de seguida.
+
+
+// Traits em breve!
+
+
+/////////////////////////////////////////////////
+// 6. Correspondência de Padrões
+/////////////////////////////////////////////////
+
+// A correspondência de padrões é uma funcionalidade poderosa e bastante
+// utilizada em Scala. Eis como fazer correspondência de padrões numa case class:
+// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de
+// breaks, a computação termina no primeiro sucesso.
+
+def reconhecePessoa(pessoa: Pessoa): String = pessoa match {
+ // Agora, especifique os padrões:
+ case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel
+ case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel
+ case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel
+}
+
+val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo.
+
+// A correspondência de padrões pode parecer familiar aos switches em linguagens
+// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer
+// correspondências com muito mais:
+def correspondeTudo(obj: Any): String = obj match {
+ // Pode-se corresponder valores:
+ case "Olá mundo" => "Recebi uma string Olá mundo."
+
+ // Corresponder por tipo:
+ case x: Double => "Recebi um Double: " + x
+
+ // Corresponder tendo em conta condições especificas:
+ case x: Int if x > 10000 => "Recebi um número bem grande!"
+
+ // Fazer correspondências com case classes (visto anteriormente):
+ case Pessoa(nome, tel) => s"Recebi o contacto para $nome!"
+
+ // Fazer correspondência com expressões regulares:
+ case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio"
+
+ // Corresponder tuplos:
+ case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c"
+
+ // Corresponder estruturas de dados:
+ case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c"
+
+ // Combinar padrões:
+ case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo"
+}
+
+// Na realidade, é possível fazer correspondência com qualquer objecto que
+// defina o método "unapply". Esta funcionalidade é tão poderosa que permite
+// definir funções sob a forma de padrões:
+val funcPaddrao: Pessoa => String = {
+ case Pessoa("Jorge", tel) => s"Número do Jorge: $tel"
+ case Pessoa(nome, tel) => s"Número de alguém: $tel"
+}
+
+
+/////////////////////////////////////////////////
+// 7. Programação Funcional
+/////////////////////////////////////////////////
+
+// Scala permite que funções e métodos retornem, ou recebam como parámetros,
+// outras funções ou métodos
+
+val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int
+List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento
+
+// Funções anónimas também podem ser usadas
+List(1, 2, 3) map (x => x + 10)
+
+// Sendo que o símbolo _ também pode ser usado se a função anónima só receber
+// um argumento. Este fica com o valor da variável
+List(1, 2, 3) map (_ + 10)
+
+// Se tanto o bloco como a função apenas receberem um argumento, o próprio
+// _ pode ser omitido
+List("Dom", "Bob", "Natalia") foreach println
+
+
+// Combinadores
+
+s.map(quadrado)
+
+val sQuadrado = s.map(quadrado)
+
+sQuadrado.filter(_ < 10)
+
+sQuadrado.reduce (_+_)
+
+// O método filter recebe um predicado (uma função de A => Boolean) e escolhe
+// todos os elementos que satisfazem o predicado
+List(1, 2, 3) filter (_ > 2) // List(3)
+case class Pessoa(nome: String, idade: Int)
+List(
+ Pessoa(nome = "Dom", idade = 23),
+ Pessoa(nome = "Bob", idade = 30)
+).filter(_.idade > 25) // List(Pessoa("Bob", 30))
+
+
+// O método foreach recebe uma função de A => Unit, executando essa função em
+// cada elemento da colecção
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// Compreensões For
+
+for { n <- s } yield quadrado(n)
+
+val nQuadrado2 = for { n <- s } yield quadrado(n)
+
+for { n <- nQuadrado2 if n < 10 } yield n
+
+for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado
+
+/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto
+ que uma compreensão define a relação entre dois conjuntos de dados. */
+
+
+/////////////////////////////////////////////////
+// 8. Implicitos
+/////////////////////////////////////////////////
+
+/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito
+ * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem
+ * resistir a tentação de usá-los até que compreendam não só como funcionam,
+ * mas também as melhores práticas. Apenas incluimos esta secção no tutorial
+ * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas
+ * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve
+ * para compreender como trabalhar com implicitos, não como declará-los.
+*/
+
+// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como
+// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5
+// nestes exemplos
+
+implicit val oMeuIntImplicito = 100
+implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça)
+
+// Por si só, a palavra implicit não altera o comportamento de um valor, sendo
+// que estes podem ser usados da forma habitual.
+oMeuIntImplicito + 2 // => 102
+aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull"
+
+// A diferença é que estes valores podem ser utilizados quando outro pedaço de
+// código "necessite" de uma valor implicito. Um exemplo são argumentos
+// implicitos de funções:
+def enviaCumprimentos(aQuem: String)(implicit quantos: Int) =
+ s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!"
+
+// Se dermos um valor a "quantos", a função comporta-se normalmente
+enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!"
+
+// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é
+// usado, neste caso, "oMeuInteiroImplicito"
+enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!"
+
+// Parâmentros implicitos de funções permitem-nos simular classes de tipos de
+// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação.
+// As seguintes linhas representam a mesma coisa
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
+
+
+// Outra situação em que o compilador prouca um implicito é se encontrar uma
+// expressão
+// obj.método(...)
+// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma
+// conversão implicita A => B, onde A é o tipo de obj, e B possui um método
+// chamado "método", a conversão é aplicada. Ou seja, tendo
+// aMinhaFunçãoImplicita definida, podemos dizer
+"Retriever".raça // => "Golden Retriever"
+"Sheperd".ladra // => "Woof, woof!"
+
+// Neste caso, a String é primeiro convertida para Cão usando a nossa funão,
+// sendo depois chamado o método apropriado. Esta é uma funcionalidade
+// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade,
+// ao definir a função implicita, o compilador deve lançar um aviso a insisitir
+// que só deve definir a função se souber o que está a fazer.
+
+
+/////////////////////////////////////////////////
+// 9. Misc
+/////////////////////////////////////////////////
+
+// Importar coisas
+import scala.collection.immutable.List
+
+// Importar todos os "sub pacotes"
+import scala.collection.immutable._
+
+// Importar multiplas classes numa linha
+import scala.collection.immutable.{List, Map}
+
+// Renomear uma classe importada usando '=>'
+import scala.collection.immutable.{List => ImmutableList}
+
+// Importar todas as classes excepto algumas. Set e Map são excluidos:
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala
+// com um método main:
+object Aplicação {
+ def main(args: Array[String]): Unit = {
+ // código aqui.
+ }
+}
+
+// Ficheiros podem conter várias classes o objectos. Compilar com scalac
+
+
+
+
+// Input e output
+
+// Ler um ficheiro linha a linha
+import scala.io.Source
+for(linha <- Source.fromFile("ficheiro.txt").getLines())
+ println(linha)
+
+// Escrever um ficheiro usando o PrintWriter de Java
+val writer = new PrintWriter("ficheiro.txt")
+writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator)
+writer.write("Outra linha aqui" + util.Properties.lineSeparator)
+writer.close()
+
+```
+
+## Mais recursos
+
+* [Scala for the impatient](http://horstmann.com/scala/)
+* [Twitter Scala school](http://twitter.github.io/scala_school/)
+* [The scala documentation](http://docs.scala-lang.org/)
+* [Try Scala in your browser](http://scalatutorials.com/tour/)
+* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 6bff7545..6d8cfbb9 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -2,40 +2,49 @@
language: purescript
contributors:
- ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
+ - ["Thimoteus", "https://github.com/Thimoteus"]
---
PureScript is a small strongly, statically typed language compiling to Javascript.
* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
-* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/)
+* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/)
* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
+All the noncommented lines of code can be run in the PSCI REPL, though some will
+require the `--multi-line-mode` flag.
+
```haskell
--
-- 1. Primitive datatypes that corresponds to their Javascript
-- equivalents at runtime.
+import Prelude
-- Numbers
-1 + 7*5 :: Number -- 36
+1.0 + 7.2*5.5 :: Number -- 40.6
+-- Ints
+1 + 2*5 :: Int -- 11
-- Types are inferred, so the following works fine
-9 / 2.5 + 4.4 -- 8
+9.0/2.5 + 4.4 -- 8.0
+-- But Ints and Numbers don't mix, so the following won't
+5/2 + 2.5 -- Expression 2.5 does not have type Int
-- Hexadecimal literals
0xff + 1 -- 256
-- Unary negation
6 * -3 -- -18
6 * negate 3 -- -18
--- Modulus
-3 % 2 -- 1
-4 % 2 -- 0
+-- Modulus, from purescript-math (Math)
+3.0 % 2.0 -- 1.0
+4.0 % 2.0 -- 0.0
-- Inspect the type of an expression in psci
-:t 9 / 2.5 + 4.4 -- Prim.Number
+:t 9.5/2.5 + 4.4 -- Prim.Number
-- Booleans
true :: Boolean -- true
false :: Boolean -- false
-- Negation
-not true --false
+not true -- false
23 == 23 -- true
1 /= 4 -- true
1 >= 4 -- false
@@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true
-- Strings
"Hellow" :: String -- "Hellow"
--- Multiline string
+-- Multiline string without newlines, to run in psci use the --multi-line-mode flag
"Hellow\
\orld" -- "Helloworld"
+-- Multiline string with newlines
+"""Hello
+world""" -- "Hello\nworld"
-- Concatenate
"such " ++ "amaze" -- "such amaze"
--
-- 2. Arrays are Javascript arrays, but must be homogeneous
-[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8]
-[true, true, false] :: [Boolean] -- [true,true,false]
+[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8]
+[true, true, false] :: Array Boolean -- [true,true,false]
-- [1,2, true, "false"] won't work
--- `Cannot unify Prim.Number with Prim.Boolean`
+-- `Cannot unify Prim.Int with Prim.Boolean`
-- Cons (prepend)
1 : [2,4,3] -- [1,2,4,3]
@@ -70,12 +82,12 @@ true && (9 >= 19 || 1 < 2) -- true
-- Safe access return Maybe a
head [1,2,3] -- Just (1)
-tail [3,2,1] -- Just ([2,1])
+tail [3,2,1] -- Just ([2,1])
init [1,2,3] -- Just ([1,2])
last [3,2,1] -- Just (1)
-- Random access - indexing
[3,4,5,6,7] !! 2 -- Just (5)
--- Range
+-- Range
1..5 -- [1,2,3,4,5]
length [2,2,2] -- 3
drop 3 [5,4,3,2,1] -- [2,1]
@@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
--
-- 3. Records are Javascript objects, with zero or more fields, which
--- can have different types
+-- can have different types.
+-- In psci you have to write `let` in front of the function to get a
+-- top level binding.
let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
-- Access properties
book.title -- "Foucault's pendulum"
-getTitle b = b.title
+let getTitle b = b.title
-- Works on all records with a title (but doesn't require any other field)
getTitle book -- "Foucault's pendulum"
getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
+-- Can use underscores as shorthand
+_.title book -- "Foucault's pendulum"
-- Update a record
-changeTitle b t = b {title = t}
-changeTitle book "Ill nome della rosa" -- {title: "Ill nome della
- -- rosa", author: "Umberto Eco"}
+let changeTitle b t = b {title = t}
+getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa"
--
-- 4. Functions
-sumOfSquares x y = x*x+y*y
+-- In psci's multiline mode
+let sumOfSquares :: Int -> Int -> Int
+ sumOfSquares x y = x*x + y*y
sumOfSquares 3 4 -- 25
--- In psci you have to write `let` in front of the function to get a
--- top level binding
-mod x y = x % y
-mod 3 2 -- 1
+let myMod x y = x % y
+myMod 3.0 2.0 -- 1.0
-- Infix application of function
3 `mod` 2 -- 1
--- function application have higher precedence than all other
+-- function application has higher precedence than all other
-- operators
sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
-- Conditional
-abs' n = if n>=0 then n else -n
+let abs' n = if n>=0 then n else -n
abs' (-3) -- 3
-- Guarded equations
-abs n | n >= 0 = n
- | otherwise = -n
+let abs'' n | n >= 0 = n
+ | otherwise = -n
-- Pattern matching
--- Note the type signature, input is an array of numbers The pattern
--- matching destructures and binds the array into parts
-first :: [Number] -> Number
-first (x:_) = x
-first [3,4,5] -- 3
-second :: [Number] -> Number
-second (_:y:_) = y
-second [3,4,5] -- 4
-sumTwo :: [Number] -> [Number]
-sumTwo (x:y:rest) = (x+y) : rest
-sumTwo [2,3,4,5,6] -- [5,4,5,6]
-
--- sumTwo doesn't handle when the array is empty or just have one
--- element in which case you get an error
+-- Note the type signature, input is a list of numbers. The pattern matching
+-- destructures and binds the list into parts.
+-- Requires purescript-lists (Data.List)
+let first :: forall a. List a -> a
+ first (Cons x _) = x
+first (toList [3,4,5]) -- 3
+let second :: forall a. List a -> a
+ second (Cons _ (Cons y _)) = y
+second (toList [3,4,5]) -- 4
+let sumTwo :: List Int -> List Int
+ sumTwo (Cons x (Cons y rest)) = x + y : rest
+fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6]
+
+-- sumTwo doesn't handle when the list is empty or there's only one element in
+-- which case you get an error.
sumTwo [1] -- Failed pattern match
-- Complementing patterns to match
-- Good ol' Fibonacci
-fib 1 = 1
-fib 2 = 2
-fib x = fib (x-1) + fib (x-2)
+let fib 1 = 1
+ fib 2 = 2
+ fib x = fib (x-1) + fib (x-2)
fib 10 -- 89
-- Use underscore to match any, where you don't care about the binding name
-isZero 0 = true
-isZero _ = false
+let isZero 0 = true
+ isZero _ = false
-- Pattern matching on records
-ecoTitle {author = "Umberto Eco", title = t} = Just t
-ecoTitle _ = Nothing
+let ecoTitle {author = "Umberto Eco", title = t} = Just t
+ ecoTitle _ = Nothing
ecoTitle book -- Just ("Foucault's pendulum")
ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
-- ecoTitle requires both field to type check:
-ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
+ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author"
-- Lambda expressions
(\x -> x*x) 3 -- 9
-(\x y -> x*x + y*y) 4 5 -- 41
-sqr = \x -> x*x
+(\x y -> x*x + y*y) 4 5 -- 41
+let sqr = \x -> x*x
-- Currying
-add x y = x + y -- is equivalent with
-add = \x -> (\y -> x+y)
-add3 = add 3
-:t add3 -- Prim.Number -> Prim.Number
+let myAdd x y = x + y -- is equivalent with
+let myAdd' = \x -> \y -> x + y
+let add3 = myAdd 3
+:t add3 -- Prim.Int -> Prim.Int
-- Forward and backward function composition
-- drop 3 followed by taking 5
@@ -177,9 +193,9 @@ add3 = add 3
(drop 3 <<< take 5) (1..20) -- [4,5]
-- Operations using higher order functions
-even x = x % 2 == 0
+let even x = x `mod` 2 == 0
filter even (1..10) -- [2,4,6,8,10]
-map (\x -> x+11) (1..5) -- [12,13,14,15,16]
+map (\x -> x + 11) (1..5) -- [12,13,14,15,16]
-- Requires purescript-foldable-traversabe (Data.Foldable)
@@ -187,7 +203,7 @@ foldr (+) 0 (1..10) -- 55
sum (1..10) -- 55
product (1..10) -- 3628800
--- Testing with predicate
+-- Testing with predicate
any even [1,2,3] -- true
all even [1,2,3] -- false
diff --git a/python.html.markdown b/python.html.markdown
index 5572e38e..b939ebbe 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -14,7 +14,13 @@ executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020,
+it is though recommended to start learnign Python with Python 3.
+For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).
+
+It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time,
+using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports
+allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial.
```python
@@ -142,7 +148,13 @@ bool("") # => False
####################################################
# Python has a print statement
-print "I'm Python. Nice to meet you!"
+print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
+
+# Simple way to get input data from console
+input_string_var = raw_input("Enter some data: ") # Returns the data as a string
+input_var = input("Enter some data: ") # Evaluates the data as python code
+# Warning: Caution is recommended for input() method usage
+# Note: In python 3, input() is deprecated and raw_input() is renamed to input()
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
@@ -473,9 +485,12 @@ add_10(3) # => 13
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# There are built-in higher order functions
map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
diff --git a/python3.html.markdown b/python3.html.markdown
index 971ca0a4..a1125c73 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -33,27 +33,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
3 # => 3
# Math is what you would expect
-1 + 1 # => 2
-8 - 1 # => 7
+1 + 1 # => 2
+8 - 1 # => 7
10 * 2 # => 20
# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
-5 // 3 # => 1
-5.0 // 3.0 # => 1.0 # works on floats too
--5 // 3 # => -2
--5.0 // 3.0 # => -2.0
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
# When you use a float, results are floats
-3 * 2.0 # => 6.0
+3 * 2.0 # => 6.0
# Modulo operation
-7 % 3 # => 1
+7 % 3 # => 1
# Exponentiation (x**y, x to the yth power)
-2**4 # => 16
+2**4 # => 16
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -63,20 +63,20 @@ True
False
# negate with not
-not True # => False
+not True # => False
not False # => True
# Boolean Operators
# Note "and" and "or" are case-sensitive
-True and False #=> False
-False or True #=> True
+True and False # => False
+False or True # => True
# Note using Bool operators with ints
-0 and 2 #=> 0
--5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
-1 == True #=> True
+0 and 2 # => 0
+-5 or 0 # => -5
+0 == False # => True
+2 == True # => False
+1 == True # => True
# Equality is ==
1 == 1 # => True
@@ -96,15 +96,15 @@ False or True #=> True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# (is vs. ==) is checks if two variable refer to the same object, but == checks
+# (is vs. ==) is checks if two variable refer to the same object, but == checks
# if the objects pointed to have the same values.
-a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
-b = a # Point b at what a is pointing to
-b is a # => True, a and b refer to the same object
-b == a # => True, a's and b's objects are equal
-b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
-b is a # => False, a and b do not refer to the same object
-b == a # => True, a's and b's objects are equal
+a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b = a # Point b at what a is pointing to
+b is a # => True, a and b refer to the same object
+b == a # => True, a's and b's objects are equal
+b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b is a # => False, a and b do not refer to the same object
+b == a # => True, a's and b's objects are equal
# Strings are created with " or '
"This is a string."
@@ -113,24 +113,24 @@ b == a # => True, a's and b's objects are equal
# Strings can be added too! But try not to do this.
"Hello " + "world!" # => "Hello world!"
# Strings can be added without using '+'
-"Hello " "world!" # => "Hello world!"
+"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
# .format can be used to format strings, like this:
-"{} can be {}".format("strings", "interpolated")
+"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated"
# You can repeat the formatting arguments to save some typing.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
-#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
# You can use keywords if you don't want to count.
-"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna"
# If your Python 3 code also needs to run on Python 2.5 and below, you can also
# still use the old style of formatting:
-"%s can be %s the %s way" % ("strings", "interpolated", "old")
+"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way"
# None is an object
@@ -139,14 +139,14 @@ None # => None
# Don't use the equality "==" symbol to compare objects to None
# Use "is" instead. This checks for equality of object identity.
"etc" is None # => False
-None is None # => True
+None is None # => True
# None, 0, and empty strings/lists/dicts all evaluate to False.
# All other values are True
-bool(0) # => False
+bool(0) # => False
bool("") # => False
-bool([]) #=> False
-bool({}) #=> False
+bool([]) # => False
+bool({}) # => False
####################################################
@@ -154,11 +154,15 @@ bool({}) #=> False
####################################################
# Python has a print function
-print("I'm Python. Nice to meet you!")
+print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end character.
-print("Hello, World", end="!") # => Hello, World!
+print("Hello, World", end="!") # => Hello, World!
+
+# Simple way to get input data from console
+input_string_var = input("Enter some data: ") # Returns the data as a string
+# Note: In earlier versions of Python, input() method was named as raw_input()
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
@@ -185,7 +189,7 @@ li.pop() # => 3 and li is now [1, 2, 4]
li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
-li[0] # => 1
+li[0] # => 1
# Look at the last element
li[-1] # => 3
@@ -194,61 +198,61 @@ li[4] # Raises an IndexError
# You can look at ranges with slice syntax.
# (It's a closed/open range for you mathy types.)
-li[1:3] # => [2, 4]
+li[1:3] # => [2, 4]
# Omit the beginning
-li[2:] # => [4, 3]
+li[2:] # => [4, 3]
# Omit the end
-li[:3] # => [1, 2, 4]
+li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
# Return a reversed copy of the list
-li[::-1] # => [3, 4, 2, 1]
+li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
# Make a one layer deep copy using slices
-li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
# Remove arbitrary elements from a list with "del"
-del li[2] # li is now [1, 2, 3]
+del li[2] # li is now [1, 2, 3]
# You can add lists
# Note: values for li and for other_li are not modified.
-li + other_li # => [1, 2, 3, 4, 5, 6]
+li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
-li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
# Check for existence in a list with "in"
-1 in li # => True
+1 in li # => True
# Examine the length with "len()"
-len(li) # => 6
+len(li) # => 6
# Tuples are like lists but are immutable.
tup = (1, 2, 3)
-tup[0] # => 1
+tup[0] # => 1
tup[0] = 3 # Raises a TypeError
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
-type((1)) # => <class 'int'>
-type((1,)) # => <class 'tuple'>
-type(()) # => <class 'tuple'>
+type((1)) # => <class 'int'>
+type((1,)) # => <class 'tuple'>
+type(()) # => <class 'tuple'>
# You can do most of the list operations on tuples too
-len(tup) # => 3
-tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
-tup[:2] # => (1, 2)
-2 in tup # => True
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
# You can unpack tuples (or lists) into variables
-a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
-e, d = d, e # d is now 5 and e is now 4
+e, d = d, e # d is now 5 and e is now 4
# Dictionaries store mappings
@@ -256,48 +260,48 @@ empty_dict = {}
# Here is a prefilled dictionary
filled_dict = {"one": 1, "two": 2, "three": 3}
-# Note keys for dictionaries have to be immutable types. This is to ensure that
-# the key can be converted to a constant hash value for quick look-ups.
+# Note keys for dictionaries have to be immutable types. This is to ensure that
+# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
-invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
-valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
# Look up values with []
-filled_dict["one"] # => 1
+filled_dict["one"] # => 1
# Get all keys as an iterable with "keys()". We need to wrap the call in list()
# to turn it into a list. We'll talk about those later. Note - Dictionary key
# ordering is not guaranteed. Your results might not match this exactly.
-list(filled_dict.keys()) # => ["three", "two", "one"]
+list(filled_dict.keys()) # => ["three", "two", "one"]
# Get all values as an iterable with "values()". Once again we need to wrap it
# in list() to get it out of the iterable. Note - Same as above regarding key
# ordering.
-list(filled_dict.values()) # => [3, 2, 1]
+list(filled_dict.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in"
-"one" in filled_dict # => True
-1 in filled_dict # => False
+"one" in filled_dict # => True
+1 in filled_dict # => False
# Looking up a non-existing key is a KeyError
-filled_dict["four"] # KeyError
+filled_dict["four"] # KeyError
# Use "get()" method to avoid the KeyError
-filled_dict.get("one") # => 1
-filled_dict.get("four") # => None
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
-filled_dict.get("four", 4) # => 4
+filled_dict.get("four", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
# Adding to a dictionary
-filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
-#filled_dict["four"] = 4 #another way to add to dict
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 #another way to add to dict
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
@@ -306,31 +310,31 @@ del filled_dict["one"] # Removes the key "one" from filled dict
# Sets store ... well sets
empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
-some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Similar to keys of a dictionary, elements of a set have to be immutable.
-invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}
# Can set new variables to a set
filled_set = some_set
# Add one more item to the set
-filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
other_set = {3, 4, 5, 6}
-filled_set & other_set # => {3, 4, 5}
+filled_set & other_set # => {3, 4, 5}
# Do set union with |
-filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with -
-{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Check for existence in a set with in
2 in filled_set # => True
-10 in filled_set # => False
+10 in filled_set # => False
@@ -416,14 +420,14 @@ try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
- pass # Pass is just a no-op. Usually you would do recovery here.
+ pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
- pass # Multiple exceptions can be handled together, if required.
-else: # Optional clause to the try/except block. Must follow all except blocks
+ pass # Multiple exceptions can be handled together, if required.
+else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
-finally: # Execute under all circumstances
+finally: # Execute under all circumstances
print("We can clean up resources here")
-
+
# Instead of try/finally to cleanup resources you can use a with statement
with open("myfile.txt") as f:
for line in f:
@@ -435,11 +439,11 @@ with open("myfile.txt") as f:
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
-print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface
+print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface
# We can loop over it.
for i in our_iterable:
- print(i) # Prints one, two, three
+ print(i) # Prints one, two, three
# However we cannot address elements by index.
our_iterable[1] # Raises a TypeError
@@ -449,17 +453,17 @@ our_iterator = iter(our_iterable)
# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
-next(our_iterator) #=> "one"
+next(our_iterator) # => "one"
# It maintains state as we iterate.
-next(our_iterator) #=> "two"
-next(our_iterator) #=> "three"
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
# After the iterator has returned all of its data, it gives you a StopIterator Exception
-next(our_iterator) # Raises StopIteration
+next(our_iterator) # Raises StopIteration
# You can grab all the elements of an iterator by calling list() on it.
-list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+list(filled_dict.keys()) # => Returns ["one", "two", "three"]
####################################################
@@ -469,20 +473,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
# Use "def" to create new functions
def add(x, y):
print("x is {} and y is {}".format(x, y))
- return x + y # Return values with a return statement
+ return x + y # Return values with a return statement
# Calling functions with parameters
-add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
+add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
# Another way to call functions is with keyword arguments
-add(y=6, x=5) # Keyword arguments can arrive in any order.
+add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
# positional arguments
def varargs(*args):
return args
-varargs(1, 2, 3) # => (1, 2, 3)
+varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
# keyword arguments, as well
@@ -490,7 +494,7 @@ def keyword_args(**kwargs):
return kwargs
# Let's call it to see what happens
-keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can do both at once, if you like
@@ -507,33 +511,33 @@ all_the_args(1, 2, a=3, b=4) prints:
# Use * to expand tuples and use ** to expand kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
-all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
-all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
- return y, x # Return multiple values as a tuple without the parenthesis.
- # (Note: parenthesis have been excluded but can be included)
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
x = 1
y = 2
-x, y = swap(x, y) # => x = 2, y = 1
-# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
def setX(num):
# Local var x not the same as global variable x
- x = num # => 43
- print (x) # => 43
+ x = num # => 43
+ print (x) # => 43
def setGlobalX(num):
global x
- print (x) # => 5
- x = num # global var x is now set to 6
- print (x) # => 6
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
setX(43)
setGlobalX(6)
@@ -549,25 +553,28 @@ add_10 = create_adder(10)
add_10(3) # => 13
# There are also anonymous functions
-(lambda x: x > 2)(3) # => True
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# TODO - Fix for iterables
# There are built-in higher order functions
-map(add_10, [1, 2, 3]) # => [11, 12, 13]
-filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
+map(add_10, [1, 2, 3]) # => [11, 12, 13]
+map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
+
+filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
# List comprehension stores the output as a list which can itself be a nested list
-[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
-[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Classes
####################################################
-# We subclass from object to get a class.
-class Human(object):
+# We use the "class" operator to get a class
+class Human:
# A class attribute. It is shared by all instances of this class
species = "H. sapiens"
@@ -606,15 +613,15 @@ j = Human("Joel")
print(j.say("hello")) # prints out "Joel: hello"
# Call our class method
-i.get_species() # => "H. sapiens"
+i.get_species() # => "H. sapiens"
# Change the shared attribute
Human.species = "H. neanderthalensis"
-i.get_species() # => "H. neanderthalensis"
-j.get_species() # => "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
# Call the static method
-Human.grunt() # => "*grunt*"
+Human.grunt() # => "*grunt*"
####################################################
@@ -627,8 +634,8 @@ print(math.sqrt(16)) # => 4
# You can get specific functions from a module
from math import ceil, floor
-print(ceil(3.7)) # => 4.0
-print(floor(3.7)) # => 3.0
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
# You can import all functions from a module.
# Warning: this is not recommended
@@ -636,7 +643,7 @@ from math import *
# You can shorten module names
import math as m
-math.sqrt(16) == m.sqrt(16) # => True
+math.sqrt(16) == m.sqrt(16) # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
@@ -661,8 +668,6 @@ def double_numbers(iterable):
# Instead of generating and returning all values at once it creates one in each
# iteration. This means values bigger than 15 wont be processed in
# double_numbers.
-# Note range is a generator too. Creating a list 1-900000000 would take lot of
-# time to be made
# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
range_ = range(1, 900000000)
@@ -697,7 +702,7 @@ def say(say_please=False):
return msg, say_please
-print(say()) # Can you buy me a beer?
+print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
@@ -714,6 +719,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
+* [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/)
### Dead Tree
diff --git a/r.html.markdown b/r.html.markdown
index d3d725d3..93751df5 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -36,8 +36,8 @@ head(rivers) # peek at the data set
length(rivers) # how many rivers were measured?
# 141
summary(rivers) # what are some summary statistics?
-# Min. 1st Qu. Median Mean 3rd Qu. Max.
-# 135.0 310.0 425.0 591.2 680.0 3710.0
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
# make a stem-and-leaf plot (a histogram-like data visualization)
stem(rivers)
@@ -54,14 +54,14 @@ stem(rivers)
# 14 | 56
# 16 | 7
# 18 | 9
-# 20 |
+# 20 |
# 22 | 25
# 24 | 3
-# 26 |
-# 28 |
-# 30 |
-# 32 |
-# 34 |
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
# 36 | 1
stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
@@ -70,7 +70,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# The decimal point is 1 digit(s) to the left of the |
#
# 48 | 1
-# 50 |
+# 50 |
# 52 | 15578
# 54 | 44571222466689
# 56 | 023334677000124455789
@@ -85,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 74 | 84
# 76 | 56
# 78 | 4
-# 80 |
+# 80 |
# 82 | 2
# make a histogram:
@@ -108,7 +108,7 @@ sort(discoveries)
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
stem(discoveries, scale=2)
-#
+#
# The decimal point is at the |
#
# 0 | 000000000
@@ -122,14 +122,14 @@ stem(discoveries, scale=2)
# 8 | 0
# 9 | 0
# 10 | 0
-# 11 |
+# 11 |
# 12 | 0
max(discoveries)
# 12
summary(discoveries)
-# Min. 1st Qu. Median Mean 3rd Qu. Max.
-# 0.0 2.0 3.0 3.1 4.0 12.0
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
round(runif(7, min=.5, max=6.5))
@@ -262,7 +262,7 @@ class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
parakeet
# =>
-# [1] "beak" "feathers" "wings" "eyes"
+# [1] "beak" "feathers" "wings" "eyes"
parakeet <- NULL
parakeet
# =>
@@ -279,7 +279,7 @@ as.numeric("Bilbo")
# =>
# [1] NA
# Warning message:
-# NAs introduced by coercion
+# NAs introduced by coercion
# Also note: those were just the basic data types
# There are many more data types, such as for dates, time series, etc.
@@ -419,10 +419,10 @@ mat %*% t(mat)
mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
mat2
# =>
-# [,1] [,2]
-# [1,] "1" "dog"
-# [2,] "2" "cat"
-# [3,] "3" "bird"
+# [,1] [,2]
+# [1,] "1" "dog"
+# [2,] "2" "cat"
+# [3,] "3" "bird"
# [4,] "4" "dog"
class(mat2) # matrix
# Again, note what happened!
diff --git a/racket.html.markdown b/racket.html.markdown
index e345db8b..0fe3f030 100644
--- a/racket.html.markdown
+++ b/racket.html.markdown
@@ -285,7 +285,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(= 3 3.0) ; => #t
(= 2 1) ; => #f
-;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
+;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
;; #f otherwise.
;; In other words, it's a simple pointer comparison.
(eq? '() '()) ; => #t, since there exists only one empty list in memory
@@ -320,7 +320,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
;; `equal?' supports the comparison of the following datatypes:
-;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
+;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
;; hash tables, and inspectable structures.
;; for other datatypes, `equal?' and `eqv?' return the same result.
(equal? 3 3.0) ; => #f
diff --git a/red.html.markdown b/red.html.markdown
index f33060c4..05da3c3f 100644
--- a/red.html.markdown
+++ b/red.html.markdown
@@ -8,31 +8,31 @@ contributors:
---
-Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
+Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language.
Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in.
-Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
-Red/System, covers the more basic needs of programming like C can, being closer to the metal.
+Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
+Red/System, covers the more basic needs of programming like C can, being closer to the metal.
-Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
-from the metal to the meta without the aid of other stack tools.
-Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
+Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
+from the metal to the meta without the aid of other stack tools.
+Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB.
Ready to learn your first Red?
```
-All text before the header will be treated as comment, as long as you avoid using the
-word "red" starting with a capital "R" in this pre-header text. This is a temporary
-shortcoming of the used lexer but most of the time you start your script or program
-with the header itself.
-The header of a red script is the capitalized word "red" followed by a
+All text before the header will be treated as comment, as long as you avoid using the
+word "red" starting with a capital "R" in this pre-header text. This is a temporary
+shortcoming of the used lexer but most of the time you start your script or program
+with the header itself.
+The header of a red script is the capitalized word "red" followed by a
whitespace character followed by a block of square brackets [].
-The block of brackets can be filled with useful information about this script or
+The block of brackets can be filled with useful information about this script or
program: the author's name, the filename, the version, the license, a summary of
what the program does or any other files it needs.
-The red/System header is just like the red header, only saying "red/System" and
+The red/System header is just like the red header, only saying "red/System" and
not "red".
Red []
@@ -49,21 +49,21 @@ comment {
; Your program's entry point is the first executable code that is found
; no need to restrict this to a 'main' function.
-; Valid variable names start with a letter and can contain numbers,
-; variables containing only capital A thru F and numbers and ending with 'h' are
-; forbidden, because that is how hexadecimal numbers are expressed in Red and
+; Valid variable names start with a letter and can contain numbers,
+; variables containing only capital A thru F and numbers and ending with 'h' are
+; forbidden, because that is how hexadecimal numbers are expressed in Red and
; Red/System.
; assign a value to a variable using a colon ":"
my-name: "Red"
-reason-for-using-the-colon: {Assigning values using the colon makes
- the equality sign "=" exclusively usable for comparisons purposes,
- exactly what "=" was intended for in the first place!
+reason-for-using-the-colon: {Assigning values using the colon makes
+ the equality sign "=" exclusively usable for comparisons purposes,
+ exactly what "=" was intended for in the first place!
Remember this y = x + 1 and x = 1 => y = 2 stuff from school?
}
is-this-name-valid?: true
-; print output using print, or prin for printing without a newline or linefeed at the
+; print output using print, or prin for printing without a newline or linefeed at the
; end of the printed text.
prin " My name is " print my-name
@@ -77,20 +77,20 @@ My name is Red
;
; Datatypes
;
-; If you know Rebol, you probably have noticed it has lots of datatypes. Red
-; does not have yet all those types, but as Red want to be close to Rebol it
+; If you know Rebol, you probably have noticed it has lots of datatypes. Red
+; does not have yet all those types, but as Red want to be close to Rebol it
; will have a lot of datatypes.
-; You can recognize types by the exclamation sign at the end. But beware
-; names ending with an exclamation sign are allowed.
-; Some of the available types are integer! string! block!
-
-; Declaring variables before using them?
-; Red knows by itself what variable is best to use for the data you want to use it
-; for.
-; A variable declaration is not always necessary.
+; You can recognize types by the exclamation sign at the end. But beware
+; names ending with an exclamation sign are allowed.
+; Some of the available types are integer! string! block!
+
+; Declaring variables before using them?
+; Red knows by itself what variable is best to use for the data you want to use it
+; for.
+; A variable declaration is not always necessary.
; It is considered good coding practise to declare your variables,
; but it is not forced upon you by Red.
-; You can declare a variable and specify its type. a variable's type determines its
+; You can declare a variable and specify its type. a variable's type determines its
; size in bytes.
; Variables of integer! type are usually 4 bytes or 32 bits
@@ -101,7 +101,7 @@ my-integer: 0
type? my-integer
integer!
-; A variable can be initialized using another variable that gets initialized
+; A variable can be initialized using another variable that gets initialized
; at the same time.
i2: 1 + i1: 1
@@ -111,9 +111,9 @@ i2 - i1 ; result 1
i2 * i1 ; result 2
i1 / i2 ; result 0 (0.5, but truncated towards 0)
-; Comparison operators are probably familiar, and unlike in other languages you
+; Comparison operators are probably familiar, and unlike in other languages you
; only need a single '=' sign for comparison.
-; There is a boolean like type in Red. It has values true and false, but also the
+; There is a boolean like type in Red. It has values true and false, but also the
; values on/off or yes/no can be used
3 = 2 ; result false
@@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0)
;
; Control Structures
-;
+;
; if
-; Evaluate a block of code if a given condition is true. IF does not return any value,
+; Evaluate a block of code if a given condition is true. IF does not return any value,
; so cannot be used in an expression.
if a < 0 [print "a is negative"]
; either
-; Evaluate a block of code if a given condition is true, else evaluate an alternative
-; block of code. If the last expressions in both blocks have the same type, EITHER can
+; Evaluate a block of code if a given condition is true, else evaluate an alternative
+; block of code. If the last expressions in both blocks have the same type, EITHER can
; be used inside an expression.
either a < 0 [
either a = 0 [
@@ -147,7 +147,7 @@ either a < 0 [
print ["a is " msg lf]
-; There is an alternative way to write this
+; There is an alternative way to write this
; (Which is allowed because all code paths return a value of the same type):
msg: either a < 0 [
@@ -162,7 +162,7 @@ msg: either a < 0 [
print ["a is " msg lf]
; until
-; Loop over a block of code until the condition at end of block, is met.
+; Loop over a block of code until the condition at end of block, is met.
; UNTIL does not return any value, so it cannot be used in an expression.
c: 5
until [
@@ -172,11 +172,11 @@ until [
]
; will output:
ooooo
-; Note that the loop will always be evaluated at least once, even if the condition is
+; Note that the loop will always be evaluated at least once, even if the condition is
; not met from the beginning.
; while
-; While a given condition is met, evaluate a block of code.
+; While a given condition is met, evaluate a block of code.
; WHILE does not return any value, so it cannot be used in an expression.
c: 5
while [c > 0][
@@ -206,7 +206,7 @@ print twice b ; will output 6.
## Further Reading
-The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
+The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
The source can be found on [github](https://github.com/red/red).
@@ -218,4 +218,4 @@ Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/r
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
-You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
+You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index ddff2e5c..8eac4ddb 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -17,7 +17,7 @@ Cocoa Touch.
Он является объектно-ориентированным языком программирования общего назначения,
который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C.
-```objective_c
+```objective-c
// Однострочные комментарии начинаются с //
/*
diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index 53b2f916..5672aa90 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["SlaF", "https://github.com/SlaF"]
+ - ["Corpsee", "https://github.com/corpsee"]
lang: ru-ru
filename: learnphp-ru.php
---
@@ -14,8 +15,8 @@ filename: learnphp-ru.php
```php
<?php // PHP код должен быть заключен в теги <?php
-// Если ваш файл содержит только PHP код, то можно
-// пропустить закрывающийся ?>
+// Если ваш файл содержит только PHP-код, то можно
+пропустить закрывающий ?>
// А так начинаются комментарии
@@ -30,10 +31,10 @@ filename: learnphp-ru.php
print('Hello '); // Напечатать "Hello " без перевода строки
// () необязательно применять для print и echo
-echo "World\n"; // Печатать "World" и перейти на новую строку.
+echo "World\n"; // Напечатать "World" и перейти на новую строку.
// (все утверждения должны заканчиваться ;)
-// Любые символы за пределами закрывающегося тега выводятся автоматически:
+// Любые символы за пределами закрывающего тега выводятся автоматически:
?>
Hello World Again!
<?php
@@ -46,7 +47,7 @@ Hello World Again!
// Переменные начинаются с символа $.
// Правильное имя переменной начинается с буквы или знака подчеркивания,
// и может содержать любые цифры, буквы, или знаки подчеркивания.
-// Не рекомендуется использовать кирилические символы в именах (прим. пер.)
+// Не рекомендуется использовать кириллические символы в именах (прим. пер.)
// Логические значения нечувствительны к регистру
$boolean = true; // или TRUE или True
@@ -56,7 +57,7 @@ $boolean = false; // или FALSE или False
$int1 = 12; // => 12
$int2 = -12; // => -12-
$int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число)
-$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число)
+$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число)
// Дробные числа
$float = 1.234;
@@ -126,7 +127,7 @@ echo 'This outputs '.FOO;
// Все массивы в PHP - это ассоциативные массивы или хеши,
-// Ассоциативные массивы, известные в других языках как хеш-карты.
+// Ассоциативные массивы, известные в других языках как HashMap.
// Работает во всех версиях РHP
$associative = array('One' => 1, 'Two' => 2, 'Three' => 3);
@@ -199,13 +200,13 @@ assert($c > $b); // больше
assert($a <= $b); // меньше или равно
assert($c >= $d); // больше или равно
-// Следующие утверждения истинны если переменные имеют одинаковый тип.
+// Следующие утверждения истинны, если переменные имеют одинаковый тип.
assert($c === $d);
assert($a !== $d);
assert(1 == '1');
assert(1 !== '1');
-// Переменные могут изменять тип, в зависимости от их использования.
+// Переменные могут изменять тип в зависимости от их использования.
$integer = 1;
echo $integer + $integer; // => 2
@@ -235,7 +236,7 @@ $var = null; // Null
$integer = 10;
$boolen = settype($integer, "string") // теперь $integer имеет строковый тип
-// settype возвращает true - если преобразование удалось и false в противном случае
+// settype возвращает true, если преобразование удалось и false в противном случае
/********************************
* Управляющие структуры
@@ -311,7 +312,7 @@ echo "\n";
for ($x = 0; $x < 10; $x++) {
echo $x;
-} // Prints "0123456789"
+} // Напечатает "0123456789"
echo "\n";
@@ -320,7 +321,7 @@ $wheels = ['bicycle' => 2, 'car' => 4];
// Циклы foreach могут обходить массивы
foreach ($wheels as $wheel_count) {
echo $wheel_count;
-} // Prints "24"
+} // Напечатает "24"
echo "\n";
@@ -337,14 +338,14 @@ while ($i < 5) {
break; // Exit out of the while loop
}
echo $i++;
-} // Prints "012"
+} // Напечатает "012"
for ($i = 0; $i < 5; $i++) {
if ($i === 3) {
continue; // Skip this iteration of the loop
}
echo $i;
-} // Prints "0124"
+} // Напечатает "0124"
/********************************
@@ -369,7 +370,7 @@ function add ($x, $y = 1) { // $y по умолчанию равно 1
echo add(4); // => 5
echo add(4, 2); // => 6
-// $result недоступна за пределами функции
+// $result недоступен за пределами функции
// print $result; // Выдает предупреждение
// Начиная с PHP 5.3 вы можете объявлять анонимные функции:
@@ -402,19 +403,19 @@ echo $function_name(1, 2); // => 3
/********************************
- * Includes
+ * Включения
*/
<?php
// PHP код внутри включаемого файла должен начинаться с тега PHP.
include 'my-file.php';
-// Код в файле my-file.php теперь доступен в текущем в текущем пространстве имен.
-// Если файл не удалось включить, будет выдано предупреждение.
+// Код в файле my-file.php теперь доступен в текущем пространстве имен.
+// Если файл не удалось подключить, то будет выдано предупреждение.
include_once 'my-file.php';
-// Если код в файле my-file.php уже был включен, он не будет включен повторно.
-// Это предотвращает ошибку повторного включения файла.
+// Если код в файле my-file.php уже был подключен, он не будет подключен повторно.
+// Это предотвращает ошибку повторного подключения файла.
require 'my-file.php';
require_once 'my-file.php';
@@ -422,7 +423,7 @@ require_once 'my-file.php';
// Same as include(), except require() will cause a fatal error if the
// file cannot be included.
// Действует также как и include(), но если файл не удалось подключить,
-// функция выдает неисправимую ошибку
+// функция выдает фатальную ошибку
// Содержимое файла my-include.php:
<?php
@@ -452,19 +453,19 @@ class MyClass
static $staticVar = 'static';
- // 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';
@@ -502,7 +503,7 @@ class MyOtherClass extends MyClass
echo $this->prot;
}
- // Override a method
+ // Переопределение родительского метода
function myMethod()
{
parent::myMethod();
@@ -595,7 +596,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo
* Трейты
*/
-// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait
+// Трейты появились в PHP 5.4 и объявляются при помощи ключевого слова trait
trait MyTrait
{
@@ -611,7 +612,7 @@ class MyTraitfulClass
}
$cls = new MyTraitfulClass();
-$cls->myTraitMethod(); // Prints "I have MyTrait"
+$cls->myTraitMethod(); // Напечатает "I have MyTrait"
/********************************
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 8f23b2e6..0e798706 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -12,7 +12,7 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
-
+ - ["Gabriel Halley", https://github.com/ghalley"]
---
```ruby
@@ -39,6 +39,7 @@ You shouldn't either
10 * 2 #=> 20
35 / 5 #=> 7
2**5 #=> 32
+5 % 3 #=> 2
# Arithmetic is just syntactic sugar
# for calling a method on an object
@@ -106,8 +107,14 @@ placeholder = 'use string interpolation'
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
'hello ' + 3.to_s #=> "hello 3"
-# print to the output
+# print to the output with a newline at the end
puts "I'm printing!"
+#=> I'm printing!
+#=> nil
+
+# print to the output without a newline
+print "I'm printing!"
+#=> I'm printing! => nill
# Variables
x = 25 #=> 25
@@ -154,6 +161,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can be indexed
# From the front
array[0] #=> 1
+array.first #=> 1
array[12] #=> nil
# Like arithmetic, [var] access
@@ -164,6 +172,7 @@ array.[] 12 #=> nil
# From the end
array[-1] #=> 5
+array.last #=> 5
# With a start index and length
array[2, 3] #=> [3, 4, 5]
@@ -258,6 +267,12 @@ 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
+# variable
+array.each_with_index do |element, index|
+ puts "#{element} is number #{index} in the array"
+end
+
counter = 1
while counter <= 5 do
puts "iteration #{counter}"
@@ -269,6 +284,19 @@ end
#=> iteration 4
#=> iteration 5
+# There are a bunch of other helpful looping functions in Ruby,
+# for example "map", "reduce", "inject", the list goes on. Map,
+# for instance, takes the array it's looping over, does something
+# to it as defined in your block, and returns an entirely new array.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
+
grade = 'B'
case grade
diff --git a/rust.html.markdown b/rust.html.markdown
index 3157fcf4..d0c56b4a 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -6,20 +6,20 @@ filename: learnrust.rs
---
Rust is a programming language developed by Mozilla Research.
-Rust combines low-level control over performance with high-level convenience and
-safety guarantees.
+Rust combines low-level control over performance with high-level convenience and
+safety guarantees.
-It achieves these goals without requiring a garbage collector or runtime, making
+It achieves these goals without requiring a garbage collector or runtime, making
it possible to use Rust libraries as a "drop-in replacement" for C.
-Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
+Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
moved so quickly that until recently the use of stable releases was discouraged
-and instead the general advice was to use nightly builds.
+and instead the general advice was to use nightly builds.
-On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
+On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
compatibility. Improvements to compile times and other aspects of the compiler are
currently available in the nightly builds. Rust has adopted a train-based release
-model with regular releases every six weeks. Rust 1.1 beta was made available at
+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
@@ -287,9 +287,9 @@ fn main() {
// While a value is mutably borrowed, it cannot be accessed at all.
let mut var2 = 4;
let ref_var2: &mut i32 = &mut var2;
- *ref_var2 += 2;
+ *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2
- println!("{}", *ref_var2); // 6
+ println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value.
// var2 = 2; // this would not compile because `var2` is borrowed
}
```
diff --git a/sass.html.markdown b/sass.html.markdown
new file mode 100644
index 00000000..02bec47f
--- /dev/null
+++ b/sass.html.markdown
@@ -0,0 +1,447 @@
+---
+language: sass
+filename: learnsass.scss
+contributors:
+ - ["Laura Kyle", "https://github.com/LauraNK"]
+ - ["Sean Corrales", "https://github.com/droidenator"]
+---
+
+Sass is a CSS extension language that adds features such as variables, nesting, mixins and more.
+Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code.
+
+Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons.
+This tutorial is written using SCSS.
+
+If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier.
+
+```scss
+
+
+//Single line comments are removed when Sass is compiled to CSS.
+
+/*Multi line comments are preserved. */
+
+
+
+/*Variables
+==============================*/
+
+
+
+/* You can store a CSS value (such as a color) in a variable.
+Use the '$' symbol to create a variable. */
+
+$primary-color: #A3A4FF;
+$secondary-color: #51527F;
+$body-font: 'Roboto', sans-serif;
+
+/* You can use the variables throughout your stylesheet.
+Now if you want to change a color, you only have to make the change once.*/
+
+body {
+ background-color: $primary-color;
+ color: $secondary-color;
+ font-family: $body-font;
+}
+
+/* This would compile to: */
+body {
+ background-color: #A3A4FF;
+ color: #51527F;
+ font-family: 'Roboto', sans-serif;
+}
+
+
+/* This is much more maintainable than having to change the color
+each time it appears throughout your stylesheet. */
+
+
+
+/*Mixins
+==============================*/
+
+
+
+/* If you find you are writing the same code for more than one
+element, you might want to store that code in a mixin.
+
+Use the '@mixin' directive, plus a name for your mixin.*/
+
+@mixin center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+}
+
+/* You can use the mixin with '@include' and the mixin name. */
+
+div {
+ @include center;
+ background-color: $primary-color;
+}
+
+/*Which would compile to: */
+div {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ left: 0;
+ right: 0;
+ background-color: #A3A4FF;
+}
+
+
+/* You can use mixins to create a shorthand property. */
+
+@mixin size($width, $height) {
+ width: $width;
+ height: $height;
+}
+
+/*Which you can invoke by passing width and height arguments. */
+
+.rectangle {
+ @include size(100px, 60px);
+}
+
+.square {
+ @include size(40px, 40px);
+}
+
+/* This compiles to: */
+.rectangle {
+ width: 100px;
+ height: 60px;
+}
+
+.square {
+ width: 40px;
+ height: 40px;
+}
+
+
+
+/*Functions
+==============================*/
+
+
+
+/* Sass provides functions that can be used to accomplish a variety of
+ tasks. Consider the following */
+
+/* Functions can be invoked by using their name and passing in the
+ required arguments */
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* Compiles to: */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to
+ mixins. When trying to choose between a function or a mixin, remember
+ that mixins are best for generating CSS while functions are better for
+ logic that might be used throughout your Sass code. The examples in
+ the Math Operators' section are ideal candidates for becoming a reusable
+ function. */
+
+/* This function will take a target size and the parent size and calculate
+ and return the percentage */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* Compiles to: */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+
+
+/*Extend (Inheritance)
+==============================*/
+
+
+
+/*Extend is a way to share the properties of one selector with another. */
+
+.display {
+ @include size(5em, 5em);
+ border: 5px solid $secondary-color;
+}
+
+.display-success {
+ @extend .display;
+ border-color: #22df56;
+}
+
+/* Compiles to: */
+.display, .display-success {
+ width: 5em;
+ height: 5em;
+ border: 5px solid #51527F;
+}
+
+.display-success {
+ border-color: #22df56;
+}
+
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way it groups together the classes that all share
+ the same base styling. If this was done with a mixin, the width,
+ height, and border would be duplicated for each statement that
+ called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Sass compiler. */
+
+
+
+/*Nesting
+==============================*/
+
+
+
+/*Sass allows you to nest selectors within selectors */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: #FF0000;
+ }
+}
+
+/* '&' will be replaced by the parent selector. */
+/* You can also nest pseudo-classes. */
+/* Keep in mind that over-nesting will make your code less maintainable.
+Best practices recommend going no more than 3 levels deep when nesting.
+For example: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+
+ li {
+ background-color: red;
+
+ &:hover {
+ background-color: blue;
+ }
+
+ a {
+ color: white;
+ }
+ }
+}
+
+/* Compiles to: */
+
+ul {
+ list-style-type: none;
+ margin-top: 2em;
+}
+
+ul li {
+ background-color: red;
+}
+
+ul li:hover {
+ background-color: blue;
+}
+
+ul li a {
+ color: white;
+}
+
+
+
+/*Partials and Imports
+==============================*/
+
+
+
+/* Sass allows you to create partial files. This can help keep your Sass
+ code modularized. Partial files should begin with an '_', e.g. _reset.css.
+ Partials are not generated into CSS. */
+
+/* Consider the following CSS which we'll put in a file called _reset.css */
+
+html,
+body,
+ul,
+ol {
+ margin: 0;
+ padding: 0;
+}
+
+/* Sass offers @import which can be used to import partials into a file.
+ This differs from the traditional CSS @import statement which makes
+ another HTTP request to fetch the imported file. Sass takes the
+ imported file and combines it with the compiled code. */
+
+@import 'reset';
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+/* Compiles to: */
+
+html, body, ul, ol {
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-size: 16px;
+ font-family: Helvetica, Arial, Sans-serif;
+}
+
+
+
+/*Placeholder Selectors
+==============================*/
+
+
+
+/* Placeholders are useful when creating a CSS statement to extend. If you
+ wanted to create a CSS statement that was exclusively used with @extend,
+ you can do so using a placeholder. Placeholders begin with a '%' instead
+ of '.' or '#'. Placeholders will not appear in the compiled CSS. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
+
+/* Compiles to: */
+
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ background-color: #0000ff;
+}
+
+
+
+/*Math Operations
+==============================*/
+
+
+
+/* Sass provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Sass files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
+
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: $main-size;
+}
+
+.sidebar {
+ width: $sidebar-size;
+}
+
+.gutter {
+ width: $gutter;
+}
+
+/* Compiles to: */
+
+body {
+ width: 100%;
+}
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
+.gutter {
+ width: 6.25%;
+}
+
+
+```
+
+
+
+## SASS or Sass?
+Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym.
+Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets".
+
+
+## Practice Sass
+If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/).
+You can use either syntax, just go into the settings and select either Sass or SCSS.
+
+
+## Compatibility
+
+Sass can be used in any project as long as you have a program to compile it
+into CSS. You'll want to verify that the CSS you're using is compatible
+with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility.
+
+
+## Further reading
+* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
+* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles.
diff --git a/scala.html.markdown b/scala.html.markdown
index c482752d..7f545196 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -6,7 +6,6 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Ha-Duong Nguyen", "http://reference-error.org"]
-filename: learn.scala
---
Scala - the scalable language
@@ -43,9 +42,13 @@ Scala - the scalable language
// Printing, and forcing a new line on the next print
println("Hello world!")
println(10)
+// Hello world!
+// 10
// Printing, without forcing a new line on next print
print("Hello world")
+print(10)
+// Hello world!10
// Declaring values is done using either var or val.
// val declarations are immutable, whereas vars are mutable. Immutability is
@@ -240,10 +243,11 @@ i // Show the value of i. Note that while is a loop in the classical sense -
// comprehensions above is easier to understand and parallelize
// A do while loop
+i = 0
do {
- println("x is still less than 10")
- x += 1
-} while (x < 10)
+ println("i is still less than 10")
+ i += 1
+} while (i < 10)
// Tail recursion is an idiomatic way of doing recurring things in Scala.
// Recursive functions need an explicit return type, the compiler can't infer it.
@@ -562,8 +566,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
// Implicit function parameters enable us to simulate type classes in other
// functional languages. It is so often used that it gets its own shorthand. The
// following two lines mean the same thing:
-def foo[T](implicit c: C[T]) = ...
-def foo[T : C] = ...
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
// Another situation in which the compiler looks for an implicit is if you have
diff --git a/self.html.markdown b/self.html.markdown
index 69524a84..9290a0c9 100644
--- a/self.html.markdown
+++ b/self.html.markdown
@@ -5,13 +5,13 @@ contributors:
filename: learnself.self
---
-Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
+Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots.
# Constructing objects
-The inbuild Self parser can construct objects, including method objects.
+The inbuild Self parser can construct objects, including method objects.
```
"This is a comment"
@@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects.
x <- 20.
|)
-"An object which understands the method 'doubleX' which
+"An object which understands the method 'doubleX' which
doubles the value of x and then returns the object"
(|
x <- 20.
doubleX = (x: x * 2. self)
|)
-"An object which understands all the messages
-that 'traits point' understands". The parser
-looks up 'traits point' by sending the messages
-'traits' then 'point' to a known object called
-the 'lobby'. It looks up the 'true' object by
+"An object which understands all the messages
+that 'traits point' understands". The parser
+looks up 'traits point' by sending the messages
+'traits' then 'point' to a known object called
+the 'lobby'. It looks up the 'true' object by
also sending the message 'true' to the lobby."
(| parent* = traits point.
x = 7.
@@ -63,19 +63,19 @@ also sending the message 'true' to the lobby."
Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
```
-"unary message, sends 'printLine' to the object '23'
+"unary message, sends 'printLine' to the object '23'
which prints the string '23' to stdout and returns the receiving object (ie 23)"
23 printLine
"sends the message '+' with '7' to '23', then the message '*' with '8' to the result"
-(23 + 7) * 8
+(23 + 7) * 8
"sends 'power:' to '2' with '8' returns 256"
-2 power: 8
+2 power: 8
-"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
+"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
Returns 1, the index of 'e' in 'hello'."
-'hello' keyOf: 'e' IfAbsent: -1
+'hello' keyOf: 'e' IfAbsent: -1
```
# Blocks
@@ -90,13 +90,13 @@ Examples of the use of a block:
```
"returns 'HELLO'"
-'hello' copyMutable mapBy: [|:c| c capitalize]
+'hello' copyMutable mapBy: [|:c| c capitalize]
"returns 'Nah'"
-'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
+'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
"returns 'HaLLO'"
-'hello' copyMutable mapBy: [|:c|
+'hello' copyMutable mapBy: [|:c|
c = 'e' ifTrue: [c capitalize]
False: ['a']]
```
@@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately.
```
"returns An 'E'! How icky!"
-'hello' copyMutable mapBy: [|:c. tmp <- ''|
+'hello' copyMutable mapBy: [|:c. tmp <- ''|
tmp: c capitalize.
tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
c capitalize
@@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t
x: 15.
"Repeatedly sends 'value' to the first block while the result of sending 'value' to the
second block is the 'true' object"
- [x > 0] whileTrue: [x: x - 1].
+ [x > 0] whileTrue: [x: x - 1].
x
] value
```
@@ -130,12 +130,12 @@ Methods are like blocks but they are not within a context but instead are stored
```
"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'.
-Sending the message 'reduceXTo: 10' to this object will put
+Sending the message 'reduceXTo: 10' to this object will put
the object '10' in the 'x' slot and return the original object"
-(|
+(|
x <- 50.
reduceXTo: y = (
- [x > y] whileTrue: [x: x - 1].
+ [x > y] whileTrue: [x: x - 1].
self)
|)
.
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index a434a1ad..3b388505 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -11,28 +11,28 @@ contributors:
Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`.
-##Allowable characters:
-- a-z
-- A-Z
-- 0-9
+##Allowable characters:
+- a-z
+- A-Z
+- 0-9
- .+/\*~<>@%|&?
- blank, tab, cr, ff, lf
##Variables:
-- variables must be declared before use
-- shared vars must begin with uppercase
-- local vars must begin with lowercase
+- variables must be declared before use
+- shared vars must begin with uppercase
+- local vars must begin with lowercase
- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
-##Variable scope:
-- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
-- Method Temporary: local to a method
-- Block Temporary: local to a block
-- Pool: variables in a Dictionary object
+##Variable scope:
+- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
+- Method Temporary: local to a method
+- Block Temporary: local to a block
+- Pool: variables in a Dictionary object
- Method Parameters: automatic local vars created as a result of message call with params
- Block Parameters: automatic local vars created as a result of value: message call
-- Class: shared with all instances of one class & its subclasses
-- Class Instance: unique to each instance of a class
+- Class: shared with all instances of one class & its subclasses
+- Class Instance: unique to each instance of a class
- Instance Variables: unique to each instance
`"Comments are enclosed in quotes"`
@@ -53,7 +53,7 @@ Transcript cr. "carriage return / l
Transcript endEntry. "flush the output buffer"
```
-##Assignment:
+##Assignment:
```
| x y |
x _ 4. "assignment (Squeak) <-"
@@ -72,7 +72,7 @@ y := x deepCopy. "copy object and ins
y := x veryDeepCopy. "complete tree copy using a dictionary"
```
-##Constants:
+##Constants:
```
| b |
b := true. "true constant"
@@ -93,7 +93,7 @@ x := #('abc' 2 $a). "mixing of types all
```
-## Booleans:
+## Booleans:
```
| b x y |
x := 1. y := 2.
@@ -132,7 +132,7 @@ b := $A isLowercase. "test if lower case
```
-## Arithmetic expressions:
+## Arithmetic expressions:
```
| x |
x := 6 + 3. "addition"
@@ -190,7 +190,7 @@ x := 100 atRandom. "quick random number
```
-##Bitwise Manipulation:
+##Bitwise Manipulation:
```
| b x |
x := 16rFF bitAnd: 16r0F. "and bits"
@@ -207,7 +207,7 @@ b := 16rFF noMask: 16r0F. "test if all bits se
```
-## Conversion:
+## Conversion:
```
| x |
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
@@ -223,15 +223,15 @@ x := 15 storeStringBase: 16.
```
-## Blocks:
-- blocks are objects and may be assigned to a variable
-- value is last expression evaluated unless explicit return
-- blocks may be nested
-- specification [ arguments | | localvars | expressions ]
-- Squeak does not currently support localvars in blocks
-- max of three arguments allowed
-- `^`expression terminates block & method (exits all nested blocks)
-- blocks intended for long term storage should not contain `^`
+## Blocks:
+- blocks are objects and may be assigned to a variable
+- value is last expression evaluated unless explicit return
+- blocks may be nested
+- specification [ arguments | | localvars | expressions ]
+- Squeak does not currently support localvars in blocks
+- max of three arguments allowed
+- `^`expression terminates block & method (exits all nested blocks)
+- blocks intended for long term storage should not contain `^`
```
| x y z |
@@ -241,18 +241,18 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu
"x := [ | z | z := 1.]. *** localvars not available in squeak blocks"
```
-## Method calls:
-- unary methods are messages with no arguments
-- binary methods
-- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
-- accessing (get/set methods)
-- testing (boolean tests - is)
-- comparing (boolean tests with parameter
-- displaying (gui related methods)
-- printing (methods for printing)
-- updating (receive notification of changes)
-- private (methods private to class)
-- instance-creation (class methods for creating instance)
+## Method calls:
+- unary methods are messages with no arguments
+- binary methods
+- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
+- accessing (get/set methods)
+- testing (boolean tests - is)
+- comparing (boolean tests with parameter
+- displaying (gui related methods)
+- printing (methods for printing)
+- updating (receive notification of changes)
+- private (methods private to class)
+- instance-creation (class methods for creating instance)
```
| x |
x := 2 sqrt. "unary message"
@@ -299,7 +299,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr].
result := (switch at: $B) value.
```
-## Iteration statements:
+## Iteration statements:
```
| x y |
x := 4. y := 1.
@@ -311,7 +311,7 @@ x timesRepeat: [y := y * 2]. "times repear loop (
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
```
-## Character:
+## Character:
```
| x y |
x := $A. "character assignment"
@@ -544,7 +544,7 @@ y := x asSet. "convert to set coll
```
## Set: like Bag except duplicates not allowed
-## IdentitySet: uses identity test (== rather than =)
+## IdentitySet: uses identity test (== rather than =)
```
| b x y sum max |
x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
@@ -603,7 +603,7 @@ y := x asBag. "convert to bag coll
y := x asSet. "convert to set collection"
```
-##Associations:
+##Associations:
```
| x y |
x := #myVar->'hello'.
diff --git a/swift.html.markdown b/swift.html.markdown
index 509c9d2f..f451288d 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -3,8 +3,9 @@ language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
- ["Christopher Bess", "http://github.com/cbess"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
+ - ["Clayton Walker", "https://github.com/cwalk"]
filename: learnswift.swift
---
@@ -12,7 +13,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D
The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
-See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift.
+See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift.
```swift
// import a module
@@ -57,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals are a Swift language feature that allows you to store a `Some` or
- `None` value.
+ Optionals are a Swift language feature that either contains a value,
+ or contains nil (no value) to indicate that a value is missing.
+ A question mark (?) after the type marks the value as optional.
Because Swift requires every property to have a value, even nil must be
explicitly stored as an Optional value.
@@ -74,11 +76,17 @@ if someOptionalString != nil {
if someOptionalString!.hasPrefix("opt") {
print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+ Trying to use ! to access a non-existent optional value triggers a runtime
+ error. Always make sure that an optional contains a non-nil value before
+ using ! to force-unwrap its value.
+*/
+
// implicitly unwrapped optional
var unwrappedString: String! = "Value is expected."
// same as above, but ! is a postfix operator (more syntax candy)
@@ -93,13 +101,13 @@ if let someOptionalStringConstant = someOptionalString {
// Swift has support for storing a value of any type.
// AnyObject == id
-// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc)
+// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
Comment here
-
+
/*
Nested comments are also supported
*/
@@ -295,10 +303,10 @@ print(numbers) // [3, 6, 18]
// MARK: Structures
//
-// Structures and classes have very similar capabilites
+// Structures and classes have very similar capabilities
struct NamesTable {
let names = [String]()
-
+
// Custom subscript
subscript(index: Int) -> String {
return names[index]
@@ -329,7 +337,7 @@ public class Shape {
internal class Rect: Shape {
var sideLength: Int = 1
-
+
// Custom getter and setter property
private var perimeter: Int {
get {
@@ -340,11 +348,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// Lazily load a property
// subShape remains nil (uninitialized) until getter called
lazy var subShape = Rect(sideLength: 4)
-
+
// If you don't need a custom getter and setter,
// but still want to run code before and after getting or setting
// a property, you can use `willSet` and `didSet`
@@ -354,19 +362,19 @@ internal class Rect: Shape {
print(someIdentifier)
}
}
-
+
init(sideLength: Int) {
self.sideLength = sideLength
// always super.init last when init custom properties
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
override func getArea() -> Int {
return sideLength * sideLength
}
@@ -398,13 +406,13 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// Place a question mark postfix after `init` is an optional init
// which can return nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -458,7 +466,7 @@ enum Furniture {
case Desk(height: Int)
// Associate with String and Int
case Chair(String, Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -497,7 +505,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -532,7 +540,7 @@ extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
@@ -574,4 +582,18 @@ print(mySquare.sideLength) // 4
// change side length using custom !!! operator, increases size by 3
!!!mySquare
print(mySquare.sideLength) // 12
+
+// Operators can also be generics
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
```
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 3982807f..b90bd690 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -14,7 +14,7 @@ programming language. It can also be used as a portable C library, even in
cases where no scripting capability is needed, as it provides data structures
such as dynamic strings, lists, and hash tables. The C library also provides
portable functionality for loading dynamic libraries, string formatting and
-code conversion, filesystem operations, network operations, and more.
+code conversion, filesystem operations, network operations, and more.
Various features of Tcl stand out:
* Convenient cross-platform networking API
@@ -58,14 +58,14 @@ lighter that that of Lisp, just gets out of the way.
#! /bin/env tclsh
################################################################################
-## 1. Guidelines
+## 1. Guidelines
################################################################################
# Tcl is not Bash or C! This needs to be said because standard shell quoting
# habits almost work in Tcl and it is common for people to pick up Tcl and try
# to get by with syntax they know from another language. It works at first,
# but soon leads to frustration with more complex scripts.
-
+
# Braces are just a quoting mechanism, not a code block constructor or a list
# constructor. Tcl doesn't have either of those things. Braces are used,
# though, to escape special characters in procedure bodies and in strings that
@@ -73,7 +73,7 @@ lighter that that of Lisp, just gets out of the way.
################################################################################
-## 2. Syntax
+## 2. Syntax
################################################################################
# Every line is a command. The first word is the name of the command, and
@@ -83,13 +83,13 @@ lighter that that of Lisp, just gets out of the way.
# are used, they are not a string constructor, but just another escaping
# character.
-set greeting1 Sal
+set greeting1 Sal
set greeting2 ut
set greeting3 ations
#semicolon also delimits commands
-set greeting1 Sal; set greeting2 ut; set greeting3 ations
+set greeting1 Sal; set greeting2 ut; set greeting3 ations
# Dollar sign introduces variable substitution
@@ -126,11 +126,11 @@ puts lots\nof\n\n\n\n\n\nnewlines
set somevar {
This is a literal $ sign, and this \} escaped
brace remains uninterpreted
-}
+}
# In a word enclosed in double quotes, whitespace characters lose their special
-# meaning
+# meaning
set name Neo
set greeting "Hello, $name"
@@ -178,7 +178,7 @@ set greeting "Hello $people::person1::name"
################################################################################
-## 3. A Few Notes
+## 3. A Few Notes
################################################################################
# All other functionality is implemented via commands. From this point on,
@@ -193,8 +193,8 @@ set greeting "Hello $people::person1::name"
namespace delete ::
-# Because of name resolution behaviour, it's safer to use the "variable" command to
-# declare or to assign a value to a namespace. If a variable called "name" already
+# Because of name resolution behaviour, it's safer to use the "variable" command to
+# declare or to assign a value to a namespace. If a variable called "name" already
# exists in the global namespace, using "set" here will assign a value to the global variable
# instead of creating a new variable in the local namespace.
namespace eval people {
@@ -210,7 +210,7 @@ set people::person1::name Neo
################################################################################
-## 4. Commands
+## 4. Commands
################################################################################
# Math can be done with the "expr" command.
@@ -295,7 +295,7 @@ while {$i < 10} {
# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values
-set amounts 10\ 33\ 18
+set amounts 10\ 33\ 18
set amount [lindex $amounts 1]
@@ -339,7 +339,7 @@ eval {set name Neo}
eval [list set greeting "Hello, $name"]
-# Therefore, when using "eval", use [list] to build up a desired command
+# Therefore, when using "eval", use [list] to build up a desired command
set command {set name}
lappend command {Archibald Sorbisol}
eval $command
@@ -355,7 +355,7 @@ eval $command ;# There is an error here, because there are too many arguments \
# This mistake can easily occur with the "subst" command.
set replacement {Archibald Sorbisol}
set command {set name $replacement}
-set command [subst $command]
+set command [subst $command]
eval $command ;# The same error as before: too many arguments to "set" in \
{set name Archibald Sorbisol}
@@ -364,12 +364,12 @@ eval $command ;# The same error as before: too many arguments to "set" in \
# command.
set replacement [list {Archibald Sorbisol}]
set command {set name $replacement}
-set command [subst $command]
+set command [subst $command]
eval $command
# It is extremely common to see the "list" command being used to properly
-# format values that are substituted into Tcl script templates. There are
+# format values that are substituted into Tcl script templates. There are
# several examples of this, below.
@@ -422,12 +422,12 @@ proc while {condition script} {
# The "coroutine" command creates a separate call stack, along with a command
# to enter that call stack. The "yield" command suspends execution in that
-# stack.
+# stack.
proc countdown {} {
#send something back to the initial "coroutine" command
yield
- set count 3
+ set count 3
while {$count > 1} {
yield [incr count -1]
}
@@ -435,12 +435,12 @@ proc countdown {} {
}
coroutine countdown1 countdown
coroutine countdown2 countdown
-puts [countdown 1] ;# -> 2
-puts [countdown 2] ;# -> 2
-puts [countdown 1] ;# -> 1
-puts [countdown 1] ;# -> 0
+puts [countdown 1] ;# -> 2
+puts [countdown 2] ;# -> 2
+puts [countdown 1] ;# -> 1
+puts [countdown 1] ;# -> 0
puts [coundown 1] ;# -> invalid command name "countdown1"
-puts [countdown 2] ;# -> 1
+puts [countdown 2] ;# -> 1
```
diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown
index f27cbf08..727f973e 100644
--- a/tr-tr/objective-c-tr.html.markdown
+++ b/tr-tr/objective-c-tr.html.markdown
@@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di
Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C
programlama diline Smalltalk stilinde mesajlaşma ekler.
-```objective_c
+```objective-c
// Tek satır yorum // işaretleri ile başlar
/*
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index c97bb560..38e418e9 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown
new file mode 100644
index 00000000..73382100
--- /dev/null
+++ b/vi-vn/ruby-vi.html.markdown
@@ -0,0 +1,549 @@
+---
+language: ruby
+filename: learnruby.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Vinh Nguyen", "http://rubydaily.net"]
+lang: vi-vn
+
+---
+
+```ruby
+# Đây là một comment
+
+=begin
+Đây là một comment nhiều dòng
+Không ai dùng cách này
+Bạn không nên dùng
+=end
+
+# Đầu tiên và quan trọng nhất: Mọi thứ là đối tượng.
+
+# Các con số là các đối tượng.
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Một vài bài toán số học căn bản
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# Số học vừa là các cú pháp thân thiện cho việc gọi
+# một hàm trên một đối tượng
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# Các giá trị đặc biệt là các đối tượng
+nil # Ở đây không có gì để xem
+true # luôn đúng
+false # luôn sai
+
+nil.class #=> Lớp Nil
+true.class #=> Lớp True
+false.class #=> Lớp False
+
+# So sánh bằng
+1 == 1 #=> true
+2 == 1 #=> false
+
+# So sánh không bằng
+1 != 1 #=> false
+2 != 1 #=> true
+
+# Ngoài chính false, thì nil là một giá trị khác của false
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Các loại so sánh khác
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Các toán tử logic
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+
+# Có các cách khác của các toán tử logic với mức thấp hơn
+# Chúng được sử dụng như các cấu trúc điều khiển luồng nối các mệnh đề
+# với nhau cho đến khi một trong số chúng trả về đúng hoặc sai.
+
+# `do_something_else` chỉ được gọi nếu như hàm `do_something` thành công.
+do_something() and do_something_else()
+# `log_error` chỉ được gọi nếu hàm `do_something` không thành công.
+do_something() or log_error()
+
+
+# Các chuỗi là các đối tượng
+
+'I am a string'.class #=> String
+"I am a string too".class #=> String
+
+placeholder = 'use string interpolation'
+"I can #{placeholder} when using double quoted strings"
+#=> "I can use string interpolation when using double quoted strings"
+
+# Nên đưa các chuỗi vào trong dấu nháy đơn
+# Ngoài ra dấu nháy kép được sử dụng trong tính toán.
+
+# Nối các chuỗi, nhưng không nối với các số.
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# Xuất ra ngoài màn hình
+puts "I'm printing!"
+
+# Các biến
+x = 25 #=> 25
+x #=> 25
+
+# Chú ý về việc gán các giá trị được trả về vào biến.
+# Điều này có nghĩa là bạn có thể gán nhiều biến.
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Theo quy ước, dùng snake_case cho các tên của biến.
+snake_case = true
+
+# Dùng để mô tả tên các biến
+path_to_project_root = '/good/name/'
+path = '/bad/name/'
+
+# Ký tự (là các đối tượng)
+# Các ký tự là bất biến, như các biến hằng số chỉ đến các số nguyên.
+# Chúng thường xuyên được sử dụng thay cho các chuỗi để chuyển đổi các giá
+# trị hiệu quả.
+
+:pending.class #=> Symbol
+
+status = :pending
+
+status == :pending #=> true
+
+status == 'pending' #=> false
+
+status == :approved #=> false
+
+# Các mảng
+
+# Đây là một mảng
+array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# Các mảng có thể chứa nhiều phần tử khác nhau
+
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Có thể truy cập các giá trị của mảng thông qua các chỉ mục
+array[0] #=> 1
+array[12] #=> nil
+
+# Giống như số học, sử dụng [biến] là một cú pháp thông dụng
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Lấy phần tử cuối cùng
+array[-1] #=> 5
+
+# Bắt đầu từ chỉ mục và số phần tử cần lấy
+array[2, 3] #=> [3, 4, 5]
+
+# Đảo ngược một mảng
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Lấy một khoảng
+array[1..3] #=> [2, 3, 4]
+
+# Thêm phần tử vào mảng bằng cách này
+array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Hoặc cách này
+array.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Kiểm tra phần tử có tồn tại trong mảng
+array.include?(1) #=> true
+
+# Băm là phần chính của Ruby với các cặp khoá/giá trị
+# Băm được biểu thị bằng dấu ngoặc nhọn:
+hash = { 'color' => 'green', 'number' => 5 }
+
+hash.keys #=> ['color', 'number']
+
+# Băm có thể được truy cập nhanh chóng thông qua khoá
+hash['color'] #=> 'green'
+hash['number'] #=> 5
+
+# Khoá không tồn tại sẽ trả về nil
+hash['nothing here'] #=> nil
+
+# Kể từ Ruby bản 1.9, đây là một cú pháp đặc biệt, sử dụng symbol như khoá
+
+new_hash = { defcon: 3, action: true }
+
+new_hash.keys #=> [:defcon, :action]
+
+# Kiểm tra khoá hoặc giá trị có tồn tại hay không
+new_hash.has_key?(:defcon) #=> true
+new_hash.has_value?(3) #=> true
+
+# Mẹo: Cả Mảng và Băm đều là Enumberable
+# Chúng cùng chia sẻ rất nhiều phương thức hữu ích như each, map, count...
+
+# Cấu trúc điều khiển
+
+if true
+ 'if statement'
+elsif false
+ 'else if, optional'
+else
+ 'else, also optional'
+end
+
+for counter in 1..5
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# TUY NHIÊN, không ai sử dụng vòng lặp for.
+# Thay vào đó, ban nên dùng phương thức "each" và truyền vào đó một khối.
+# Một khối là một loạt các mã mà bạn có thể truyền
+# cho một phương thức giống như each.
+# Nó tương tự với lambda, các hàm ẩn danh hoặc closures trong các ngôn ngữ
+# lập trình khác.
+#
+# Phương thức "each" cho một khoản sẽ chạy qua từng phần tử của khoảng đó.
+# Khối được truyền vào là một số đếm như là tham số.
+# Gọi một method "each" với một khối sẽ trông như thế này:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# Bạn cũng có thể bao khối trong các dấu ngoặc nhọn.
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# Các nội dung của cấu trúc dữ liệu cũng có thể được lặp bằng each.
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+grade = 'B'
+
+case grade
+when 'A'
+ puts 'Way to go kiddo'
+when 'B'
+ puts 'Better luck next time'
+when 'C'
+ puts 'You can do better'
+when 'D'
+ puts 'Scraping through'
+when 'F'
+ puts 'You failed!'
+else
+ puts 'Alternative grading system, eh?'
+end
+#=> "Better luck next time"
+
+# Cases cũng được dùng cho các dãy
+grade = 82
+case grade
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
+end
+#=> "OK job"
+
+# Xử lý ngoại lệ:
+begin
+ # Code ở đây có thể sẽ đưa ra một ngoại lệ.
+ raise NoMemoryError, 'You ran out of memory.'
+rescue NoMemoryError => exception_variable
+ puts 'NoMemoryError was raised', exception_variable
+rescue RuntimeError => other_exception_variable
+ puts 'RuntimeError was raised now'
+else
+ puts 'This runs if no exceptions were thrown at all'
+ensure
+ puts 'This code always runs no matter what'
+end
+
+# Hàm
+
+def double(x)
+ x * 2
+end
+
+# Hàm (và tất cả các khối) được mặc định giá trị trả về ở mệnh đề cuối.
+double(2) #=> 4
+
+# Dấu ngoặc là một tuỳ chọn cho một kết quả rõ ràng.
+double 3 #=> 6
+
+double double 3 #=> 12
+
+def sum(x, y)
+ x + y
+end
+
+# Các đối số được chia cắt bởi dấu phẩy.
+sum 3, 4 #=> 7
+
+sum sum(3, 4), 5 #=> 12
+
+# yield
+# Tất cả các hàm có thể có một tham số tuỳ chọn.
+# Nó có thể được gọi với từ khóa "yield".
+def surround
+ puts '{'
+ yield
+ puts '}'
+end
+
+surround { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+
+# Bạn có thể truyền một khối đến một hàm
+# Dấu "&" được đánh dấu đến một khối
+def guests(&block)
+ block.call 'some_argument'
+end
+
+# Bạn có thể truyền một danh sách các tham số, nó sẽ được chuyển thành mảng.
+# Thông qua việc sử dụng dấu *.
+def guests(*array)
+ array.each { |guest| puts guest }
+end
+
+# Định nghĩ một lớp thông qua từ khoá class.
+class Human
+
+ # Một biến class. Nó được chia sẽ cho tất cả các instance của lớp này.
+ @@species = 'H. sapiens'
+
+ # Các khởi tạo căn bản
+ def initialize(name, age = 0)
+ # Gán đối số đến biến instance "name"
+ @name = name
+ # Nếu không có age, sẽ lấy giá trị mặc định trong danh sách đối số.
+ @age = age
+ end
+
+ # Hàm nhập giá trị căn bản
+ def name=(name)
+ @name = name
+ end
+
+ # Hàm lấy giá trị căn bản
+ def name
+ @name
+ end
+
+ # Các hàm trên có thể được gọn lại bằng cách dùng hàm attr_accessor
+ attr_accessor :name
+
+ # Các hàm nhận/lấy cũng có thể được tạo riêng như sau:
+ attr_reader :name
+ attr_writer :name
+
+ # Một hàm lớp dùng self để phân biệt với hàm instance.
+ # Nó chỉ có thể được gọi trên lớp.
+ def self.say(msg)
+ puts msg
+ end
+
+ def species
+ @@species
+ end
+end
+
+
+# Khởi tạo một lớp
+jim = Human.new('Jim Halpert')
+
+dwight = Human.new('Dwight K. Schrute')
+
+# Hãy gọi một cặp các hàm.
+jim.species #=> "H. sapiens"
+jim.name #=> "Jim Halpert"
+jim.name = "Jim Halpert II" #=> "Jim Halpert II"
+jim.name #=> "Jim Halpert II"
+dwight.species #=> "H. sapiens"
+dwight.name #=> "Dwight K. Schrute"
+
+# Gọi một hàm lớp
+Human.say('Hi') #=> "Hi"
+
+# Phạm vi của biến được định nghĩa bởi cách chúng ta đặt tên cho chúng.
+# Các biến bắt đầu với dấu $ là biến toàn cục.
+$var = "I'm a global var"
+defined? $var #=> "global-variable"
+
+# Các biến bắt đầu với dấu @ là biến phạm vi.
+@var = "I'm an instance var"
+defined? @var #=> "instance-variable"
+
+# Các biến bắt đầu với dấu @@ có pham vi là trong một lớp.
+@@var = "I'm a class var"
+defined? @@var #=> "class variable"
+
+# Các biến bắt đầu với ký tự viết hoa là biến hằng.
+Var = "I'm a constant"
+defined? Var #=> "constant"
+
+# Lớp cũng là một đối tượng trong Ruby. Bởi vậy lớp có các biến instance.
+# Biến lớp được chia sẽ trong lớp và các lớp kế thừa nó.
+
+# Lớp cơ sở
+class Human
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(value)
+ @@foo = value
+ end
+end
+
+# Lớp kế thừa
+class Worker < Human
+end
+
+Human.foo # 0
+Worker.foo # 0
+
+Human.foo = 2 # 2
+Worker.foo # 2
+
+# Các biến lớp instance không được chia sẽ trong lớp kế thừa.
+
+class Human
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(value)
+ @bar = value
+ end
+end
+
+class Doctor < Human
+end
+
+Human.bar # 0
+Doctor.bar # nil
+
+module ModuleExample
+ def foo
+ 'foo'
+ end
+end
+
+# Include một module sẽ đưa các hàm của module thành instances của lớp.
+# Extend một module sẽ đưa các hàm của module thành các biến của lớp.
+
+class Person
+ include ModuleExample
+end
+
+class Book
+ extend ModuleExample
+end
+
+Person.foo # => NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo # => 'foo'
+Book.foo # => 'foo'
+Book.new.foo # => NoMethodError: undefined method `foo'
+
+# Hàm hồi quy được thực hiện khi include và extend một module.
+
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
+ end
+ end
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar # => 'bar'
+Something.qux # => NoMethodError: undefined method `qux'
+Something.new.bar # => NoMethodError: undefined method `bar'
+Something.new.qux # => 'qux'
+```
+
+## Các nguồn tham khảo thêm.
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby from other languages](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/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index f9906e96..bdfdcc10 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -17,7 +17,7 @@ Module Module1
' This navigation system is explained however as we go deeper into this
' tutorial, you'll understand what it all means.
Console.Title = ("Learn X in Y Minutes")
- Console.WriteLine("NAVIGATION") 'Display
+ Console.WriteLine("NAVIGATION") 'Display
Console.WriteLine("")
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine("1. Hello World Output")
@@ -39,13 +39,13 @@ Module Module1
Case "2" 'Hello Input
Console.Clear()
HelloWorldInput()
- Case "3" 'Calculating Whole Numbers
+ Case "3" 'Calculating Whole Numbers
Console.Clear()
CalculatingWholeNumbers()
- Case "4" 'Calculting Decimal Numbers
+ Case "4" 'Calculting Decimal Numbers
Console.Clear()
CalculatingDecimalNumbers()
- Case "5" 'Working Calcculator
+ Case "5" 'Working Calcculator
Console.Clear()
WorkingCalculator()
Case "6" 'Using Do While Loops
@@ -74,7 +74,7 @@ Module Module1
'One - I'm using numbers to help with the above navigation when I come back
'later to build it.
- 'We use private subs to seperate different sections of the program.
+ 'We use private subs to seperate different sections of the program.
Private Sub HelloWorldOutput()
'Title of Console Application
Console.Title = "Hello World Ouput | Learn X in Y Minutes"
@@ -172,7 +172,7 @@ Module Module1
'program more than once.
Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes"
Dim answer As String 'We use the variable "String" as the answer is text
- Do 'We start the program with
+ Do 'We start the program with
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
Console.Write("Second number: ")
@@ -192,7 +192,7 @@ Module Module1
Console.WriteLine(" = " + f.ToString.PadLeft(3))
Console.ReadLine()
'Ask the question, does the user wish to continue? Unfortunately it
- 'is case sensitive.
+ 'is case sensitive.
Console.Write("Would you like to continue? (yes / no)")
'The program grabs the variable and prints and starts again.
answer = Console.ReadLine
@@ -208,8 +208,8 @@ Module Module1
Console.Title = "Using For Loops | Learn X in Y Minutes"
'Declare Variable and what number it should count down in Step -1,
- 'Step -2, Step -3 ect.
- For i As Integer = 10 To 0 Step -1
+ 'Step -2, Step -3 ect.
+ For i As Integer = 10 To 0 Step -1
Console.WriteLine(i.ToString) 'Print the value of the counter
Next i 'Calculate new value
Console.WriteLine("Start") 'Lets start the program baby!!
@@ -274,8 +274,8 @@ End Module
## References
-I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
+I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
-I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more.
+I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more.
-The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
+The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
diff --git a/xml.html.markdown b/xml.html.markdown
index 059ea132..efc2340f 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -7,7 +7,7 @@ contributors:
XML is a markup language designed to store and transport data.
-Unlike HTML, XML does not specify how to display or to format data, just carry it.
+Unlike HTML, XML does not specify how to display or to format data, it just carries it.
* XML Syntax
@@ -38,15 +38,16 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
<!-- Above is a typical XML file.
It starts with a declaration, informing some metadata (optional).
-
+
XML uses a tree structure. Above, the root node is 'bookstore', which has
- three child nodes, all 'books'. Those nodes has more child nodes, and so on...
-
- Nodes are created using open/close tags, and childs are just nodes between
+ three child nodes, all 'books'. Those nodes have more child nodes (or
+ children), and so on...
+
+ Nodes are created using open/close tags, and children are just nodes between
the open and close tags.-->
-<!-- XML carries two kind of data:
+<!-- XML carries two kinds of data:
1 - Attributes -> That's metadata about a node.
Usually, the XML parser uses this information to store the data properly.
It is characterized by appearing with the format name="value" within the opening
@@ -54,8 +55,8 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
2 - Elements -> That's pure data.
That's what the parser will retrieve from the XML file.
Elements appear between the open and close tags. -->
-
-
+
+
<!-- Below, an element with two attributes -->
<file type="gif" id="4293">computer.gif</file>
@@ -68,21 +69,21 @@ A XML document is well-formated if it is syntactically correct.
However, it is possible to inject more constraints in the document,
using document definitions, such as DTD and XML Schema.
-A XML document which follows a document definition is called valid,
-regarding that document.
+A XML document which follows a document definition is called valid,
+regarding that document.
With this tool, you can check the XML data outside the application logic.
```xml
-<!-- Below, you can see an simplified version of bookstore document,
+<!-- Below, you can see an simplified version of bookstore document,
with the addition of DTD definition.-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Bookstore.dtd">
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>
@@ -120,7 +121,7 @@ With this tool, you can check the XML data outside the application logic.
<bookstore>
<book category="COOKING">
- <title >Everyday Italian</title>
+ <title>Everyday Italian</title>
<price>30.00</price>
</book>
</bookstore>