From 8de5c352bc94bf6f1e5886e68356b53e0ffd80d4 Mon Sep 17 00:00:00 2001 From: David Underwood Date: Fri, 28 Jun 2013 15:57:57 -0400 Subject: [PATCH 001/110] Initial WIP commit for ruby --- ruby.html.markdown | 202 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 ruby.html.markdown diff --git a/ruby.html.markdown b/ruby.html.markdown new file mode 100644 index 00000000..32dfeff3 --- /dev/null +++ b/ruby.html.markdown @@ -0,0 +1,202 @@ +--- +language: ruby +author: David Underwood +author_url: http://theflyingdeveloper.com +--- + +```ruby +# This is a comment + +=begin +This is a multiline comment +No-one uses them +You shouldn't either +=end + + +3 #=> 3 + + +# Some basic arithmetic +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 + +# Special values +nil #=> Nothing to see here +true #=> truth +false #=> falsehood + +# Equality +1 == 1 #=> true +2 == 1 #=> false + +# Inequality +1 != 1 #=> false +2 != 1 #=> true +!true #=> false +!false #=> true + +# More comparisons +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +'I am a string' +"I am a string too" + +placeholder = "use variables inline" +"I can #{placeholder} when using double quoted strings" +#=> "I can use variables inline when using double quoted strings" + + +# print to the output +puts "I'm printing!" + +# Variables +x = 25 #=> 25 + +# Note that assignment returns the value assigned +# This means you can do multiple assignment: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# By convention, use snake_case for variable names +snake_case = true + +# Use descriptive variable names +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Arrays + +# This is an array +[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Arrays can contain different types of items + +array = [1, "hello", false] #=> => [1, "hello", false] + +# Arrays can be indexed +# From the front +array[0] #=> 1 +array[12] #=> nil + +# From the end +array[-1] #=> 5 + +# With a start and end index +array[2, 4] #=> [3, 4, 5] + +# Or with a range +array[1..3] #=> [2, 3, 4] + +# Add to the end of an array like this +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Or like this +array.push 7 #=> [1, 2, 3, 4, 5, 6, 7] + +# Or to the beginning like this +array.unshift 0 #=> [0, 1, 2, 3, 4, 5, 6, 7] + +# Remove the first item in an array + +array.shift #=> [1, 2, 3, 4, 5, 6, 7] + +# Or the last + +array.pop #=> [1, 2, 3, 4, 5, 6] + +# Note that push and pop do the opposite of each other +# Shift and unshift are the same. + +# Control structures + +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 + +# HOWEVER +# No-one uses for loops +# Use `each` instead, like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" +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!" + + +# Functions + +def double(x) + x * 2 +end + +# Functions (and all blocks) implcitly return the value of the last statement +double(2) #=> 4 + +# Parentheses are optional where the result is unambiguous +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x,y) + x + y +end + +# Method arguments are separated by a comma +sum 3, 4 #=> 7 + +sum sum(3,4), 5 #=> 12 + +# yield +# All methods have an implicit, optional block parameter +# it can be called with the 'yield' keyword + + +``` \ No newline at end of file From 6cfb00d10650c46508703d4356dddeccacb70e03 Mon Sep 17 00:00:00 2001 From: Nick Presta Date: Fri, 28 Jun 2013 18:34:30 -0400 Subject: [PATCH 002/110] Removing the bit about commas and exceptions. --- python.html.markdown | 6 ------ 1 file changed, 6 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index a599f5d3..2c08e73e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -283,12 +283,6 @@ try: except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. -# Works for Python 2.7 and down: -try: - raise IndexError("This is an index error") -except IndexError, e: # No "as", comma instead - pass - #################################################### ## 4. Functions From a19ba3205dd7bada3a20f2cc10e8199ab1f08a9a Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sat, 29 Jun 2013 19:44:10 +0930 Subject: [PATCH 003/110] Start work on the JavaScript tutorial --- javascript.html.markdown | 114 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 javascript.html.markdown diff --git a/javascript.html.markdown b/javascript.html.markdown new file mode 100644 index 00000000..737638b1 --- /dev/null +++ b/javascript.html.markdown @@ -0,0 +1,114 @@ +--- +language: javascript +author: Adam Brenecki +author_url: http://adam.brenecki.id.au +--- + +Javascript was created by Netscape's Brendan Eich in 1995. It was originally +intended as a simpler scripting language for web apps, complimenting Java for +more complex ones, but has become far more widely used than Java on the web. + +Feedback would be highly appreciated! You can reach me at +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```javascript +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ + +// Statements can be terminated by ; +doStuff(); + +// ... but they don't have to be, as semicolons are automatically inserted +// wherever there's a newline, except in certain cases. +doStuff() + +// Semicolons are a heated topic in the JavaScript world, but they're really a +// matter of personal or style-guide preference. We'll leave them off here. + +/*********** + * 1. Primitive Datatypes and Operators + ***********/ + +// Javascript has one number type that covers ints and floats. +3 // = 3 +1.5 // = 1.5 + +// which support all the operations you'd expect. +1 + 1 // = 2 +8 - 1 // = 7 +10 * 2 // = 20 +35 / 5 // = 7 + +// Uneven division works how you'd expect, too. +5 / 2 # = 2.5 + +// Enforce precedence with parentheses +(1 + 3) * 2 // = 8 + +// There's also a boolean type. +true +false + +// Strings are created with ' or ". +'abc' +"Hello, world" + +// Negation uses the ! symbol +!true // = false +!false // = true + +// Equality is == +1 == 1 // = true +2 == 1 // = false + +// Inequality is != +1 != 1 // = false +2 != 1 // = true + +// More comparisons +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +// Strings are concatenated with + +"Hello " + "world!" // = "Hello world!" + +// and are compared with < and > +"a" < "b" // = true + +// You can also compare strings with numbers +"5" == 5 // = true + +// but this is almost always not what you want, so use === to stop this +"5" === 5 // = false + +// You can access characters in a string with charAt +"This is a string".charAt(0) + +// There's also a null keyword +null // = null + +/*********** + * 2. Variables and Lists + ***********/ + +// variables are declared with the var keyword +var some_var = 5 + +// if you leave them off, you won't get an error... +some_other_var = 10 + +// but your variable will always end up with the global scope, even if it wasn't +// defined there, so don't do it. + +/*********** + * 3. Control Structures + ***********/ + +/*********** + * 4. Objects + ***********/ +``` From a8672f19bfe97c0f9157d7ff1050913df75c976e Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sat, 29 Jun 2013 19:58:54 +0930 Subject: [PATCH 004/110] Add the rest of the tutorial's structure --- javascript.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 737638b1..826fe7cd 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -111,4 +111,12 @@ some_other_var = 10 /*********** * 4. Objects ***********/ + +/*********** + * 5. Functions, Scope and Closures + ***********/ + +/*********** + * 6. Constructors and Prototypes + ***********/ ``` From 9c81beb8114d246cd0de5e83340363cdebc87155 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sat, 29 Jun 2013 21:09:19 +0930 Subject: [PATCH 005/110] Begin writing about JavaScript arrays and dictionaries --- javascript.html.markdown | 121 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 113 insertions(+), 8 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 826fe7cd..1565f541 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -92,24 +92,41 @@ false null // = null /*********** - * 2. Variables and Lists + * 2. Variables, Arrays and Objects ***********/ -// variables are declared with the var keyword +// Variables are declared with the var keyword. Javascript is dynamically typed, +// so you don't need to specify type. Assignment uses a single = character. var some_var = 5 -// if you leave them off, you won't get an error... +// if you leave the var keyword off, you won't get an error... some_other_var = 10 // but your variable will always end up with the global scope, even if it wasn't // defined there, so don't do it. -/*********** - * 3. Control Structures - ***********/ +// Arrays are ordered lists of values, of any type. +["Hello", 45, true] + +// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// languages: an unordered collection of key-value pairs. +{key1: "Hello", key2: "World"} + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4} + +// Object attributes can be accessed using the 'subscript' syntax, +myObj["my other key"] // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey // = "myValue" + +// Objects are mutable, values can be changed and new keys added. +myObj.myThirdKey = true /*********** - * 4. Objects + * 3. Control Structures ***********/ /*********** @@ -117,6 +134,94 @@ some_other_var = 10 ***********/ /*********** - * 6. Constructors and Prototypes + * 6. More about Objects; Constructors and Prototypes ***********/ + +// Objects can contain functions, which can be called using the dot syntax. +myObj = { + myFunc: function(){ + return "Hello world!" + } +} +myObj.myFunc() // = "Hello world!" + +// When functions are called like this, they can access the object they're +// attached to using the this keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString + } +} +myObj.myFunc() // = "Hello world!" + +// The value of this has to do with how the function is called, not where it's +// defined. So, that doesn't work if the function isn't called in the context of +// the object. +var myFunc = myObj.myFunc +myFunc() // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through this, even if it wasn't defined as such. +var myOtherFunc = function(){ + return this.myString.toUpperCase() +} +myObj.myOtherFunc = myOtherFunc +myObj.myOtherFunc() // = "HELLO WORLD!" + +// When you call a function with the new keyword, a new object is created, and +// made available to the function via this. Functions designed to be called +// like this are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5 +} +myNewObj = new MyConstructor() // = {myNumber: 5} +myNewObj.myNumber // = 5 + +// JavaScript objects aren't defined in terms of classes like other languages, +// but you can use prototypes to do many of the same things. When you try to +// access a property of an object that isn't present, its prototype is searched. +var myObj = {} +var myPrototype = { + meaningOfLife: 42, + myThirdFunc: function(){ + return this.myString.toLowerCase() + } +} +myObj.__proto__ = myPrototype +myObj.myThirdFunc() // = "hello world!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +} +myObj.myBoolean // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myObj. + +// The __proto__ magic property we've used to access prototypes isn't standard, +// and shouldn't be used in real-world code. There is a way to create a new +// object with another given object as its prototype, though: +var myObj = Object.create(myPrototype) +myObj.meaningOfLife // = 42 + +// Unfortunately, Object.create is quite recent and isn't available in many +// browsers, so you often can't use that, either. The most reliable way to set +// prototypes involves constructors. + +// TODO: write about the .prototype property on constructors + +// Built-in types' prototypes work like this too, so you can actually change +// the prototype of a string, for instance (although whether you should is +// another matter). +String.prototype.firstCharacter = function(){ + return this.charAt(0) +} +"abc".firstCharacter() // = "a" + ``` From 325ecf20a02655643c22e9692d697d258211814e Mon Sep 17 00:00:00 2001 From: DrJonOsterman Date: Sat, 29 Jun 2013 08:46:34 -0400 Subject: [PATCH 006/110] comment syntax fix --- javascript.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 1565f541..c3bf131c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -42,7 +42,7 @@ doStuff() 35 / 5 // = 7 // Uneven division works how you'd expect, too. -5 / 2 # = 2.5 +5 / 2 // = 2.5 // Enforce precedence with parentheses (1 + 3) * 2 // = 8 @@ -68,10 +68,10 @@ false 2 != 1 // = true // More comparisons -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True +1 < 10 // => True +1 > 10 // => False +2 <= 2 // => True +2 >= 2 // => True // Strings are concatenated with + "Hello " + "world!" // = "Hello world!" From 2669bc8ff63e1efa26ccb372c02b9453e0c4cb02 Mon Sep 17 00:00:00 2001 From: Jakehp Date: Sat, 29 Jun 2013 12:12:23 -0500 Subject: [PATCH 007/110] java --- java.html.markdown | 369 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 369 insertions(+) create mode 100644 java.html.markdown diff --git a/java.html.markdown b/java.html.markdown new file mode 100644 index 00000000..d780d515 --- /dev/null +++ b/java.html.markdown @@ -0,0 +1,369 @@ +--- +language: java +author: Jake Prather +author_url: http://github.com/JakeHP +--- + +Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. +Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) + +```java +// Single-line comments start with // +/* +Multi-line comments look like this. +*/ + +// Import Packages +import java.util.ArrayList; +import package.path.here; +// Import "sub-packages" +import java.lang.Math.*; + +// Your program's entry point is a function called main +public class Main +{ + public static void main (String[] args) throws java.lang.Exception + { + //stuff here + } +} + +// Printing +System.out.println("Hello World"); +System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); + +/////////////////////////////////////// +// Types +/////////////////////////////////////// + +// You have to declare variables before using them. A variable declaration +// requires you to specify its type; a variable's type determines its size +// in bytes. + +// Integers +int x_int = 0; + +// shorts are usually 2 bytes +short x_short = 0; + +// chars are guaranteed to be 1 byte +char x_char = 0; +char y_char = 'y'; // Char literals are quoted with '' + +// longs are often 4 to 8 bytes; long longs are guaranteed to be at least +// 64 bits +long x_long = 0; +long long x_long_long = 0; + +// floats are usually 32-bit floating point numbers +float x_float = 0.0; + +// doubles are usually 64-bit floating-point numbers +double x_double = 0.0; + +// Integral types may be unsigned. This means they can't be negative, but +// the maximum value of an unsigned variable is greater than the maximum +// value of the same size. +unsigned char ux_char; +unsigned short ux_short; +unsigned int ux_int; +unsigned long long ux_long_long; + +// Other than char, which is always 1 byte, these types vary in size depending +// on your machine. sizeof(T) gives you the size of a variable with type T in +// bytes so you can express the size of these types in a portable way. +// For example, +printf("%d\n", sizeof(int)); // => 4 (on machines with 4-byte words) + +// Arrays must be initialized with a concrete size. +char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes +int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes + // (assuming 4-byte words) + + +// You can initialize an array to 0 thusly: +char my_array[20] = {0}; + +// Indexing an array is like other languages -- or, +// rather, other languages are like C +my_array[0]; // => 0 + +// Arrays are mutable; it's just memory! +my_array[1] = 2; +printf("%d\n", my_array[1]); // => 2 + +// Strings are just arrays of chars terminated by a NUL (0x00) byte, +// represented in strings as the special character '\0'. +// (We don't have to include the NUL byte in string literals; the compiler +// inserts it at the end of the array for us.) +char a_string[20] = "This is a string"; +printf("%s\n", a_string); // %s formats a string + +/* +You may have noticed that a_string is only 16 chars long. +Char #17 is the NUL byte. +Chars #18, 19 and 20 have undefined values. +*/ + +printf("%d\n", a_string[16]); => 0 + +/////////////////////////////////////// +// Operators +/////////////////////////////////////// + +int i1 = 1, i2 = 2; // Shorthand for multiple declaration +float f1 = 1.0, f2 = 2.0; + +// Arithmetic is straightforward +i1 + i2; // => 3 +i2 - i1; // => 1 +i2 * i1; // => 2 +i1 / i2; // => 0 (0.5, but truncated towards 0) + +f1 / f2; // => 0.5, plus or minus epsilon + +// Modulo is there as well +11 % 3; // => 2 + +// Comparison operators are probably familiar, but +// there is no boolean type in c. We use ints instead. +// 0 is false, anything else is true. (The comparison +// operators always return 0 or 1.) +3 == 2; // => 0 (false) +3 != 2; // => 1 (true) +3 > 2; // => 1 +3 < 2; // => 0 +2 <= 2; // => 1 +2 >= 2; // => 1 + +// Logic works on ints +!3; // => 0 (Logical not) +!0; // => 1 +1 && 1; // => 1 (Logical and) +0 && 1; // => 0 +0 || 1; // => 1 (Logical or) +0 || 0; // => 0 + +// Bitwise operators! +~0x0F; // => 0xF0 (bitwise negation) +0x0F & 0xF0; // => 0x00 (bitwise AND) +0x0F | 0xF0; // => 0xFF (bitwise OR) +0x04 ^ 0x0F; // => 0x0B (bitwise XOR) +0x01 << 1; // => 0x02 (bitwise left shift (by 1)) +0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) + +/////////////////////////////////////// +// Control Structures +/////////////////////////////////////// + +if (0) { + printf("I am never run\n"); +} else if (0) { + printf("I am also never run\n"); +} else { + printf("I print\n"); +} + +// While loops exist +int ii = 0; +while (ii < 10) { + printf("%d, ", ii++); // ii++ increments ii in-place, after using its value. +} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +int kk = 0; +do { + printf("%d, ", kk); +} while (++kk < 10); // ++kk increments kk in-place, before using its value +// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +// For loops too +int jj; +for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); +} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + +printf("\n"); + +/////////////////////////////////////// +// Typecasting +/////////////////////////////////////// + +// Every value in C has a type, but you can cast one value into another type +// if you want. + +int x_hex = 0x01; // You can assign vars with hex literals + +// Casting between types will attempt to preserve their numeric values +printf("%d\n", x_hex); // => Prints 1 +printf("%d\n", (short) x_hex); // => Prints 1 +printf("%d\n", (char) x_hex); // => Prints 1 + +// Types will overflow without warning +printf("%d\n", (char) 257); // => 1 (Max char = 255) + +// Integral types can be cast to floating-point types, and vice-versa. +printf("%f\n", (float)100); // %f formats a float +printf("%lf\n", (double)100); // %lf formats a double +printf("%d\n", (char)100.0); + +/////////////////////////////////////// +// Pointers +/////////////////////////////////////// + +// A pointer is a variable declared to store a memory address. Its declaration will +// also tell you the type of data it points to. You can retrieve the memory address +// of your variables, then mess with them. + +int x = 0; +printf("%p\n", &x); // Use & to retrieve the address of a variable +// (%p formats a pointer) +// => Prints some address in memory; + +// Pointer types end with * in their declaration +int* px; // px is a pointer to an int +px = &x; // Stores the address of x in px +printf("%p\n", px); // => Prints some address in memory + +// To retreive the value at the address a pointer is pointing to, +// put * in front to de-reference it. +printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of + +// You can also change the value the pointer is pointing to. +// We'll have to wrap the de-reference in parenthesis because +// ++ has a higher precedence than *. +(*px)++; // Increment the value px is pointing to by 1 +printf("%d\n", *px); // => Prints 1 +printf("%d\n", x); // => Prints 1 + +int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory +int xx; +for (xx=0; xx<20; xx++) { + x_array[xx] = 20 - xx; +} // Initialize x_array to 20, 19, 18,... 2, 1 + +// Declare a pointer of type int and initialize it to point to x_array +int* x_ptr = x_array; +// x_ptr now points to the first element in the array (the integer 20). +// This works because arrays are actually just pointers to their first element. + +// Arrays are pointers to their first element +printf("%d\n", *(x_ptr)); // => Prints 20 +printf("%d\n", x_array[0]); // => Prints 20 + +// Pointers are incremented and decremented based on their type +printf("%d\n", *(x_ptr + 1)); // => Prints 19 +printf("%d\n", x_array[1]); // => Prints 19 + +// You can also dynamically allocate contiguous blocks of memory with the +// standard library function malloc, which takes one integer argument +// representing the number of bytes to allocate from the heap. +int* my_ptr = (int*) malloc(sizeof(int) * 20); +for (xx=0; xx<20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here +} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) + +// Dereferencing memory that you haven't allocated gives +// unpredictable results +printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? + +// When you're done with a malloc'd block of memory, you need to free it, +// or else no one else can use it until your program terminates +free(my_ptr); + +// Strings can be char arrays, but are usually represented as char +// pointers: +char* my_str = "This is my very own string"; + +printf("%c\n", *my_str); // => 'T' + +function_1(); +} // end main function + +/////////////////////////////////////// +// Functions +/////////////////////////////////////// + +// Function declaration syntax: +// () + +int add_two_ints(int x1, int x2){ + return x1 + x2; // Use return to return a value +} + +/* +Functions are pass-by-value, but you can make your own references +with pointers so functions can mutate their values. + +Example: in-place string reversal +*/ + +// A void function returns no value +void str_reverse(char* str_in){ + char tmp; + int ii=0, len = strlen(str_in); // Strlen is part of the c standard library + for(ii=0; ii ".tset a si sihT" +*/ + +/////////////////////////////////////// +// User-defined types and structs +/////////////////////////////////////// + +// Typedefs can be used to create type aliases +typedef int my_type; +my_type my_type_var = 0; + +// Structs are just collections of data +struct rectangle { + int width; + int height; +}; + + +void function_1(){ + + struct rectangle my_rec; + + // Access struct members with . + my_rec.width = 10; + my_rec.height = 20; + + // You can declare pointers to structs + struct rectangle* my_rec_ptr = &my_rec; + + // Use dereferencing to set struct pointer members... + (*my_rec_ptr).width = 30; + + // ... or use the -> shorthand + my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; +} + +// You can apply a typedef to a struct for convenience +typedef struct rectangle rect; + +int area(rect r){ + return r.width * r.height; +} + +``` + +## 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) + +Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/) + +Other than that, Google is your friend. From d32bad8aed47e58c4f675d9487537ac42d54004e Mon Sep 17 00:00:00 2001 From: Jakehp Date: Sat, 29 Jun 2013 12:46:34 -0500 Subject: [PATCH 008/110] up --- java.html.markdown | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index d780d515..48e1ff36 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -36,38 +36,23 @@ System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); // Types /////////////////////////////////////// -// You have to declare variables before using them. A variable declaration -// requires you to specify its type; a variable's type determines its size -// in bytes. +// Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) -// Integers -int x_int = 0; +// Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) -// shorts are usually 2 bytes -short x_short = 0; +//Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) +int x = 1; -// chars are guaranteed to be 1 byte -char x_char = 0; -char y_char = 'y'; // Char literals are quoted with '' +//Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) -// longs are often 4 to 8 bytes; long longs are guaranteed to be at least -// 64 bits -long x_long = 0; -long long x_long_long = 0; +//Float - Single-precision 32-bit IEEE 754 Floating Point -// floats are usually 32-bit floating point numbers -float x_float = 0.0; +//Double - Double-precision 64-bit IEEE 754 Floating Point -// doubles are usually 64-bit floating-point numbers -double x_double = 0.0; +//Boolean - True & False + +//Char - A single 16-bit Unicode character -// Integral types may be unsigned. This means they can't be negative, but -// the maximum value of an unsigned variable is greater than the maximum -// value of the same size. -unsigned char ux_char; -unsigned short ux_short; -unsigned int ux_int; -unsigned long long ux_long_long; // Other than char, which is always 1 byte, these types vary in size depending // on your machine. sizeof(T) gives you the size of a variable with type T in From b9e0c189ee856de31a3fd035b39bd54765104a8d Mon Sep 17 00:00:00 2001 From: David Underwood Date: Sat, 29 Jun 2013 18:04:37 -0400 Subject: [PATCH 009/110] fixes typos in the boolean results --- ruby.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 32dfeff3..a317c498 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -39,10 +39,10 @@ false #=> falsehood !false #=> true # More comparisons -1 < 10 #=> True -1 > 10 #=> False -2 <= 2 #=> True -2 >= 2 #=> True +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true 'I am a string' "I am a string too" From 4b873348fce636644917b812fbf746f59b56bcc4 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:12:03 -0500 Subject: [PATCH 010/110] Update java.html.markdown --- java.html.markdown | 290 ++++++++++++++++++++++----------------------- 1 file changed, 144 insertions(+), 146 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 48e1ff36..0ca36132 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,177 +1,175 @@ --- + language: java + author: Jake Prather + author_url: http://github.com/JakeHP + --- Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) ```java -// Single-line comments start with // -/* -Multi-line comments look like this. -*/ - -// Import Packages -import java.util.ArrayList; -import package.path.here; -// Import "sub-packages" -import java.lang.Math.*; - -// Your program's entry point is a function called main -public class Main -{ - public static void main (String[] args) throws java.lang.Exception +/////////////////////////////////////// +// General +/////////////////////////////////////// + // Single-line comments start with // + /* + Multi-line comments look like this. + */ + + // Import Packages + import java.util.ArrayList; + import package.path.here; + // Import all "sub-packages" + import java.lang.Math.*; + + // Your program's entry point is a function called main + public class Main { - //stuff here + public static void main (String[] args) throws java.lang.Exception + { + //stuff here + } } -} - -// Printing -System.out.println("Hello World"); -System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); + + // Printing, and forcing a new line on next print = println() + System.out.println("Hello World"); + System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); + // Printing, without forcing a new line on next print = print() + System.out.print("Hello World"); + System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); /////////////////////////////////////// // Types /////////////////////////////////////// -// Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) - -// Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) - -//Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) -int x = 1; - -//Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - -//Float - Single-precision 32-bit IEEE 754 Floating Point - -//Double - Double-precision 64-bit IEEE 754 Floating Point - -//Boolean - True & False - -//Char - A single 16-bit Unicode character - - -// Other than char, which is always 1 byte, these types vary in size depending -// on your machine. sizeof(T) gives you the size of a variable with type T in -// bytes so you can express the size of these types in a portable way. -// For example, -printf("%d\n", sizeof(int)); // => 4 (on machines with 4-byte words) - -// Arrays must be initialized with a concrete size. -char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes -int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes - // (assuming 4-byte words) - - -// You can initialize an array to 0 thusly: -char my_array[20] = {0}; - -// Indexing an array is like other languages -- or, -// rather, other languages are like C -my_array[0]; // => 0 - -// Arrays are mutable; it's just memory! -my_array[1] = 2; -printf("%d\n", my_array[1]); // => 2 - -// Strings are just arrays of chars terminated by a NUL (0x00) byte, -// represented in strings as the special character '\0'. -// (We don't have to include the NUL byte in string literals; the compiler -// inserts it at the end of the array for us.) -char a_string[20] = "This is a string"; -printf("%s\n", a_string); // %s formats a string - -/* -You may have noticed that a_string is only 16 chars long. -Char #17 is the NUL byte. -Chars #18, 19 and 20 have undefined values. -*/ - -printf("%d\n", a_string[16]); => 0 + // Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) + byte foo = 100; + + // Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) + short bar = 10000; + + //Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) + int foo = 1; + + //Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long bar = 100000L; + + //Float - Single-precision 32-bit IEEE 754 Floating Point + float foo = 234.5f; + + //Double - Double-precision 64-bit IEEE 754 Floating Point + double bar = 123.4; + + //Boolean - True & False + boolean foo = true; + boolean bar = false; + + //Char - A single 16-bit Unicode character + char foo = 'A'; + + //Strings + String foo = "Hello World!"; + // \n is an escaped character that starts a new line + String foo = "Hello World!\nLine2!"; + System.out.println(foo); + //Hello World! + //Line2! + + //Arrays + //The array size must be decided upon declaration + //The format for declaring an array is follows: + // [] = new []; + int [] array = new int[10]; + String [] array = new String[1]; + boolean [] array = new boolean[100]; + + // Indexing an array - Accessing an element + array[0]; + + // Arrays are mutable; it's just memory! + array[1] = 1; + System.out.println(array[1]); // => 1 + array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + //Others to check out + //ArrayLists - Like arrays except more functionality is offered, and the size is mutable + //LinkedLists + //Maps + //HashMaps /////////////////////////////////////// // Operators /////////////////////////////////////// -int i1 = 1, i2 = 2; // Shorthand for multiple declaration -float f1 = 1.0, f2 = 2.0; - -// Arithmetic is straightforward -i1 + i2; // => 3 -i2 - i1; // => 1 -i2 * i1; // => 2 -i1 / i2; // => 0 (0.5, but truncated towards 0) - -f1 / f2; // => 0.5, plus or minus epsilon - -// Modulo is there as well -11 % 3; // => 2 - -// Comparison operators are probably familiar, but -// there is no boolean type in c. We use ints instead. -// 0 is false, anything else is true. (The comparison -// operators always return 0 or 1.) -3 == 2; // => 0 (false) -3 != 2; // => 1 (true) -3 > 2; // => 1 -3 < 2; // => 0 -2 <= 2; // => 1 -2 >= 2; // => 1 - -// Logic works on ints -!3; // => 0 (Logical not) -!0; // => 1 -1 && 1; // => 1 (Logical and) -0 && 1; // => 0 -0 || 1; // => 1 (Logical or) -0 || 0; // => 0 - -// Bitwise operators! -~0x0F; // => 0xF0 (bitwise negation) -0x0F & 0xF0; // => 0x00 (bitwise AND) -0x0F | 0xF0; // => 0xFF (bitwise OR) -0x04 ^ 0x0F; // => 0x0B (bitwise XOR) -0x01 << 1; // => 0x02 (bitwise left shift (by 1)) -0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5, but truncated towards 0) + + // Modulo + 11 % 3; // => 2 + + // Comparison operators + 3 == 2; // => 0 (false) + 3 != 2; // => 1 (true) + 3 > 2; // => 1 + 3 < 2; // => 0 + 2 <= 2; // => 1 + 2 >= 2; // => 1 + + // Bitwise operators! + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR /////////////////////////////////////// // Control Structures /////////////////////////////////////// -if (0) { - printf("I am never run\n"); -} else if (0) { - printf("I am also never run\n"); -} else { - printf("I print\n"); -} + if (false) { + System.out.println("I never run"); + } else if (false) { + System.out.println("I am also never run"); + } else { + System.out.println("I print"); + } + } -// While loops exist -int ii = 0; -while (ii < 10) { - printf("%d, ", ii++); // ii++ increments ii in-place, after using its value. -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -int kk = 0; -do { - printf("%d, ", kk); -} while (++kk < 10); // ++kk increments kk in-place, before using its value -// => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); - -// For loops too -int jj; -for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); -} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - -printf("\n"); + // While loops exist + int ii = 0; + while (ii < 10) { + printf("%d, ", ii++); // ii++ increments ii in-place, after using its value. + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk increments kk in-place, before using its value + // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); + + // For loops too + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + + printf("\n"); /////////////////////////////////////// // Typecasting From 83aeecb68a20751d09bb83793691f19a8dc97aa2 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:19:14 -0700 Subject: [PATCH 011/110] Added filename parameter --- c.html.markdown | 7 +++++-- clojure.html.markdown | 1 + dart.html.markdown | 1 + file.erb | 1 + fsharp.html.markdown | 1 + haskell.html.markdown | 1 + lua.html.markdown | 1 + php.html.markdown | 1 + python.html.markdown | 1 + r.html.markdown | 2 +- 10 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 file.erb diff --git a/c.html.markdown b/c.html.markdown index f2b9047b..69bf099e 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -2,6 +2,7 @@ language: c author: Adam Bard author_url: http://adambard.com/ +filename: learnc.c --- Ah, C. Still the language of modern high-performance computing. @@ -12,6 +13,7 @@ memory management and C will take you as far as you need to go. ```c // Single-line comments start with // + /* Multi-line comments look like this. */ @@ -19,6 +21,7 @@ Multi-line comments look like this. // Import headers with #include #include #include +#include // Declare function signatures in advance in a .h file, or at the top of // your .c file. @@ -75,7 +78,7 @@ unsigned long long ux_long_long; // on your machine. sizeof(T) gives you the size of a variable with type T in // bytes so you can express the size of these types in a portable way. // For example, -printf("%d\n", sizeof(int)); // => 4 (on machines with 4-byte words) +printf("%lu\n", sizeof(int)); // => 4 (on machines with 4-byte words) // Arrays must be initialized with a concrete size. char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes @@ -107,7 +110,7 @@ Char #17 is the NUL byte. Chars #18, 19 and 20 have undefined values. */ -printf("%d\n", a_string[16]); => 0 +printf("%d\n", a_string[16]); // => 0 /////////////////////////////////////// // Operators diff --git a/clojure.html.markdown b/clojure.html.markdown index c5298aab..12611fd3 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -2,6 +2,7 @@ language: clojure author: Adam Bard author_url: http://adambard.com/ +filename: test.clj --- Clojure is a variant of LISP developed for the Java Virtual Machine. It has diff --git a/dart.html.markdown b/dart.html.markdown index c503fb4a..27365746 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -2,6 +2,7 @@ language: dart author: Joao Pedrosa author_url: https://github.com/jpedrosa/ +filename: learndart.dart --- Dart is a newcomer into the realm of programming languages. diff --git a/file.erb b/file.erb new file mode 100644 index 00000000..5f162aa5 --- /dev/null +++ b/file.erb @@ -0,0 +1 @@ +<%= rawcode %> diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 1deaf437..b1860372 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -2,6 +2,7 @@ language: F# author: Scott Wlaschin author_url: http://fsharpforfunandprofit.com/ +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. diff --git a/haskell.html.markdown b/haskell.html.markdown index fbaa93f2..a696cb5f 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -2,6 +2,7 @@ language: haskell author: Adit Bhargava author_url: http://adit.io +filename: learnhaskell.hs --- Haskell was designed as a practical, purely functional programming language. It's famous for diff --git a/lua.html.markdown b/lua.html.markdown index 66ebf6bd..4df57a92 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -2,6 +2,7 @@ language: lua author: Tyler Neylon author_url: http://tylerneylon.com/ +filename: learnlua.lua --- ```lua diff --git a/php.html.markdown b/php.html.markdown index 1a8dea2c..b3c8f822 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -2,6 +2,7 @@ language: php author: Malcolm Fell author_url: http://emarref.net/ +filename: learnphp.php --- This document describes PHP 5+. diff --git a/python.html.markdown b/python.html.markdown index eddff031..d1152b82 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -2,6 +2,7 @@ language: python author: Louie Dinh author_url: http://ldinh.ca +filename: learnpython.py --- Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular diff --git a/r.html.markdown b/r.html.markdown index 1ace3ed5..f68ede0e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -2,7 +2,7 @@ language: R author: e99n09 author_url: http://github.com/e99n09 - +filename: learnr.r --- R is a statistical computing language. From 6f08caf97867f20ac7f2f2dd1eb6b9f63835c80e Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:25:21 -0700 Subject: [PATCH 012/110] Merged PHP review from emarref --- php.html.markdown | 170 ++++++++++++++++++++++++++-------------------- 1 file changed, 98 insertions(+), 72 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index b3c8f822..7db50136 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -10,6 +10,8 @@ This document describes PHP 5+. ```php tags +// If your php file only contains PHP code, it is best practise to omit the php closing tag. + // Two forward slashes start a one-line comment. # So will a hash (aka pound symbol) but // is more common @@ -23,7 +25,7 @@ This document describes PHP 5+. print('Hello '); // Prints "Hello " with no line break // () are optional for print and echo -echo 'World\n'; // Prints "World" with a line break +echo "World\n"; // Prints "World" with a line break // (all statements must end with a semicolon) // Anything outside 19 -$int2 = -19; // => -19 -$int3 = 019; // => 15 (a leading 0 denotes an octal number) +$int1 = 19; // => 19 +$int2 = -19; // => -19 +$int3 = 019; // => 15 (a leading 0 denotes an octal number) $int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) // Floats (aka doubles) @@ -55,26 +57,26 @@ $float = 1.2e3; $float = 7E-10; // Arithmetic -$sum = 1 + 1; // 2 +$sum = 1 + 1; // 2 $difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 // Shorthand arithmetic $number = 0; -$number += 1; // Add 1 to $number -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evalutation) +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evalutation) $number /= $float; // Divide and assign the quotient to $number // Strings should be enclosed in single quotes; $sgl_quotes = '$String'; // => '$String' // Avoid using double quotes except to embed other variables -$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String' +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' // Special characters are only escaped in double quotes -$escaped = "This contains a \t tab character."; +$escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; // Enclose a variable in curly braces if needed @@ -110,7 +112,7 @@ $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); // PHP 5.4 introduced a new syntax $associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; -echo $associative['One']; // prints "1" +echo $associative['One']; // prints 1 // List literals implicitly assign integer keys $array = ['One', 'Two', 'Three']; @@ -133,8 +135,8 @@ print 'Hello World!'; // So is print $paragraph = 'paragraph'; -echo 100; -echo $paragraph; +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables // If short open tags are configured, or your PHP version is // 5.4.0 or greater, you can use the short echo syntax @@ -144,10 +146,11 @@ echo $paragraph; $x = 1; $y = 2; -$x = $y; // A now contains the same value sa $y +$x = $y; // $x now contains the same value as $y $z = &$y; -// $x now contains a reference to $y. Changing the value of -// $x will change the value of $y also, and vice-versa. +// $z now contains a reference to $y. Changing the value of +// $z will change the value of $y also, and vice-versa. +// $x will remain unchanged as the original value of $y echo $x; // => 2 echo $z; // => 2 @@ -216,7 +219,7 @@ if (true) { } if (false) { - print "I don't"; + print 'I don\'t'; } else { print 'I get printed'; } @@ -251,7 +254,7 @@ This is displayed otherwise. switch ($x) { case '0': print 'Switch does type coercion'; - break; // You must include a break, or you will fall through + break; // You must include a break, or you will fall through to cases 'two' and 'three' case 'two': case 'three': // Do something if $variable is either 'two' or 'three' @@ -276,16 +279,16 @@ do { echo "\n"; for ($x = 0; $x < 10; $x++) { - echo $x; // Will echo 0 - 9 -}// Prints "0123456789" + echo $x; +} // Prints "0123456789" echo "\n"; $wheels = ['bicycle' => 2, 'car' => 4]; // Foreach loops can iterate over arrays -foreach ($wheels as $wheel_count){ - echo "$wheel_count"; +foreach ($wheels as $wheel_count) { + echo $wheel_count; } // Prints "24" echo "\n"; @@ -303,9 +306,9 @@ while ($i < 5) { break; // Exit out of the while loop } echo $i++; -}// Prints "012" +} // Prints "012" -for($i = 0; $i < 5; $i++){ +for ($i = 0; $i < 5; $i++) { if ($i === 3) { continue; // Skip this iteration of the loop } @@ -318,7 +321,7 @@ for($i = 0; $i < 5; $i++){ */ // Define a function with "function": -function my_function() { +function my_function () { return 'Hello'; } @@ -327,7 +330,7 @@ echo my_function(); // => "Hello" // A valid function name starts with a letter or underscore, followed by any // number of letters, numbers, or underscores. -function add($x, $y = 1) { // $y is optional, and defaults to 2 +function add ($x, $y = 1) { // $y is optional and defaults to 1 $result = $x + $y; return $result; } @@ -339,7 +342,7 @@ echo add(4, 2); // => 6 // print $result; // Gives a warning. // Since PHP 5.3 you can declare anonymous functions; -$inc = function($x){ +$inc = function ($x) { return $x + 1; }; @@ -358,78 +361,92 @@ function bar ($x, $y) { } $bar = bar('A', 'B'); -$bar('C'); +$bar('C'); // Prints "A - B - C" // You can call named functions using strings $function_name = 'add'; echo $function_name(1, 2); // => 3 -// But, you should probably use anonymous functions instead. +// Useful for programatically determining which function to run. +// Alternatively, use call_user_func(callable $callback [, mixed $parameter [, mixed $... ]]); /******************************** * Classes */ -//Classes are defined with the class keyword +// Classes are defined with the class keyword -class MyClass { - const MY_CONST = 'value'; // A constant - static $staticVar = 'static'; - public $property = 'public'; // Properties must declare their visibility - private $privprop = 'private'; // Accessible within the class only - protected $protprop = 'protected'; // Accessible within the class and subclasses +class MyClass +{ + const MY_CONST = 'value'; // A constant + + static $staticVar = 'static'; + + // Properties must declare their visibility + public $property = 'public'; public $instanceProp; + protected $protProp = 'protected'; // Accessible within the class and subclasses + private $privProp = 'private'; // Accessible within the class only // Create a constructor with __construct - public function __construct($instanceProp){ + public function __construct($instanceProp) { // Access instance variables with $this $this->instanceProp = $instanceProp; } + // Methods are declared as functions inside a class - public function myMethod() { - print "MyClass"; + public function myMethod() + { + print 'MyClass'; } - final function youCannotOverrideMe() { + final function youCannotOverrideMe() + { } - public static function myStaticMethod() { - print "I am static"; + public static function myStaticMethod() + { + print 'I am static'; } } -echo MyClass::MY_CONST; // Outputs "value"; -echo MyClass::$staticVar; // Outputs 'static'; -MyClass::myStaticMethod(); // Outputs "I am static"; +echo MyClass::MY_CONST; // Outputs 'value'; +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; -// Access class members using ->. -$my_class = new MyClass("An instance property"); // The parentheses are optional. -echo $my_class->property; // => "public" +// Access class members using -> +$my_class = new MyClass('An instance property'); // The parentheses are optional if not passing in an argument. +echo $my_class->property; // => "public" echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" +$my_class->myMethod(); // => "MyClass" // Extend classes using "extends" -class MyOtherClass extends MyClass{ - function printProtectedProperty(){ - echo $this->protprop; +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->protProp; } // Override a method - function myMethod() { + function myMethod() + { parent::myMethod(); - print " > MyOtherClass"; + print ' > MyOtherClass'; } } -$my_other_class = new MyOtherClass("Instance prop"); +$my_other_class = new MyOtherClass('Instance prop'); $my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" -final class YouCannotExtendMe { +final class YouCannotExtendMe +{ } // You can use "magic methods" to create getters and setters -class MyMapClass { +class MyMapClass +{ private $property; public function __get($key) @@ -463,16 +480,19 @@ interface InterfaceTwo abstract class MyAbstractClass implements InterfaceOne { - public $x = "doSomething"; + public $x = 'doSomething'; } class MyConcreteClass extends MyAbstractClass implements InterfaceTwo { - public function doSomething(){ + public function doSomething() + { echo $x; } - public function doSomethingElse(){ - echo "doSomethingElse"; + + public function doSomethingElse() + { + echo 'doSomethingElse'; } } @@ -480,11 +500,14 @@ class MyConcreteClass extends MyAbstractClass implements InterfaceTwo // Classes can implement more than one interface class SomeOtherClass implements InterfaceOne, InterfaceTwo { - public function doSomething(){ - echo "doSomething"; + public function doSomething() + { + echo 'doSomething'; } - public function doSomethingElse(){ - echo "doSomethingElse"; + + public function doSomethingElse() + { + echo 'doSomethingElse'; } } @@ -493,12 +516,13 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Traits */ -//Traits are available since PHP 5.4.0 and are declared using the trait keyword. +// Traits are available since PHP 5.4.0 and are declared using the trait keyword. -trait MyTrait { +trait MyTrait +{ public function myTraitMethod() { - print "I have MyTrait"; + print 'I have MyTrait'; } } @@ -566,3 +590,5 @@ Visit the [official PHP documentation](http://www.php.net/manual/) for reference If you're interested in up-to-date best practices, visit [PHP The Right Way](http://www.phptherightway.com/). 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). From 789cc2c2a7f77585792bd32ac5e06737891609b1 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:38:22 -0700 Subject: [PATCH 013/110] Merged in (and formatted line lenghts for) emarref's require commit --- php.html.markdown | 63 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 7db50136..20923548 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -10,7 +10,8 @@ This document describes PHP 5+. ```php tags -// If your php file only contains PHP code, it is best practise to omit the php closing tag. +// If your php file only contains PHP code, it is best practise +// to omit the php closing tag. // Two forward slashes start a one-line comment. @@ -171,8 +172,8 @@ $d = '1'; // These comparisons will always be true, even if the types aren't the same. assert($a == $b); // equality -assert($b != $a); // inequality -assert($a <> $b); // alternative inequality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality assert($a < $c); assert($c > $b); assert($a <= $b); @@ -254,7 +255,8 @@ This is displayed otherwise. switch ($x) { case '0': print 'Switch does type coercion'; - break; // You must include a break, or you will fall through to cases 'two' and 'three' + break; // You must include a break, or you will fall through + // to cases 'two' and 'three' case 'two': case 'three': // Do something if $variable is either 'two' or 'three' @@ -367,7 +369,45 @@ $bar('C'); // Prints "A - B - C" $function_name = 'add'; echo $function_name(1, 2); // => 3 // Useful for programatically determining which function to run. -// Alternatively, use call_user_func(callable $callback [, mixed $parameter [, mixed $... ]]); +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + +/******************************** + * Includes + */ + +/* +``` +```php + -$my_class = new MyClass('An instance property'); // The parentheses are optional if not passing in an argument. echo $my_class->property; // => "public" echo $my_class->instanceProp; // => "An instance property" $my_class->myMethod(); // => "MyClass" @@ -425,7 +468,7 @@ class MyOtherClass extends MyClass { function printProtectedProperty() { - echo $this->protProp; + echo $this->prot; } // Override a method @@ -516,7 +559,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Traits */ -// Traits are available since PHP 5.4.0 and are declared using the trait keyword. +// Traits are available from PHP 5.4.0 and are declared using "trait" trait MyTrait { From 5b29da12e6d595bce088a8d25c956abbdb5fee7a Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:52:18 -0500 Subject: [PATCH 014/110] Update java.html.markdown --- java.html.markdown | 297 +++++++++++++++++---------------------------- 1 file changed, 113 insertions(+), 184 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 0ca36132..2f9c143b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -71,6 +71,9 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) //Char - A single 16-bit Unicode character char foo = 'A'; + //Make a variable a constant + final int HOURS_I_WORK_PER_WEEK = 9001; + //Strings String foo = "Hello World!"; // \n is an escaped character that starts a new line @@ -133,6 +136,13 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR + + // Incrementations + int i=0; + i++; //i = 1. Post Incrementation + ++i; //i = 2. Pre Incrementation + i--; //i = 1. Post Decrementation + --i; //i = 0. Pre Decrementation /////////////////////////////////////// // Control Structures @@ -147,206 +157,125 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) } } - // While loops exist - int ii = 0; - while (ii < 10) { - printf("%d, ", ii++); // ii++ increments ii in-place, after using its value. - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + // While loop + int i = 0; + while(i < 100){ + System.out.println(i); + //Increment the counter + i++; + } - printf("\n"); + // Do While Loop + int i = 0; + do{ + System.out.println(i); + //Increment the counter + i++; + }while(i < 100); - int kk = 0; - do { - printf("%d, ", kk); - } while (++kk < 10); // ++kk increments kk in-place, before using its value - // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " + // For Loop + int i; + //for loop structure => for(;;) + for(i=0;i<100;i++){ + System.out.println(i); + } - printf("\n"); - - // For loops too - int jj; - for (jj=0; jj < 10; jj++) { - printf("%d, ", jj); - } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " - - printf("\n"); /////////////////////////////////////// // Typecasting /////////////////////////////////////// -// Every value in C has a type, but you can cast one value into another type -// if you want. - -int x_hex = 0x01; // You can assign vars with hex literals - -// Casting between types will attempt to preserve their numeric values -printf("%d\n", x_hex); // => Prints 1 -printf("%d\n", (short) x_hex); // => Prints 1 -printf("%d\n", (char) x_hex); // => Prints 1 - -// Types will overflow without warning -printf("%d\n", (char) 257); // => 1 (Max char = 255) - -// Integral types can be cast to floating-point types, and vice-versa. -printf("%f\n", (float)100); // %f formats a float -printf("%lf\n", (double)100); // %lf formats a double -printf("%d\n", (char)100.0); + // Converting data + + //Convert String To Integer + Integer.parseInt("123");//returns an integer version of "123" + + //Convert Integer To String + Integer.toString(123);//returns a string version of 123 + + //For other conversions check out the following classes: + //Double + //Long + //String + + // You can also cast java objects, there's a lot of details and + // deals with some more intermediate concepts. + // Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + /////////////////////////////////////// -// Pointers +// Classes And Functions /////////////////////////////////////// -// A pointer is a variable declared to store a memory address. Its declaration will -// also tell you the type of data it points to. You can retrieve the memory address -// of your variables, then mess with them. + // Classes Syntax shown below. + // Function declaration syntax: + // () + // Here is a quick rundown on access level modifiers (public, private, etcetc) http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html -int x = 0; -printf("%p\n", &x); // Use & to retrieve the address of a variable -// (%p formats a pointer) -// => Prints some address in memory; + + public class Bicycle { + + // Bicycle's Fields/Variables + public int cadence; + public int gear; + public int speed; + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle(){ + gear = 1; + cadence = 50; + startGear = 1; + } -// Pointer types end with * in their declaration -int* px; // px is a pointer to an int -px = &x; // Stores the address of x in px -printf("%p\n", px); // => Prints some address in memory - -// To retreive the value at the address a pointer is pointing to, -// put * in front to de-reference it. -printf("%d\n", *px); // => Prints 0, the value of x, which is what px is pointing to the address of - -// You can also change the value the pointer is pointing to. -// We'll have to wrap the de-reference in parenthesis because -// ++ has a higher precedence than *. -(*px)++; // Increment the value px is pointing to by 1 -printf("%d\n", *px); // => Prints 1 -printf("%d\n", x); // => Prints 1 - -int x_array[20]; // Arrays are a good way to allocate a contiguous block of memory -int xx; -for (xx=0; xx<20; xx++) { - x_array[xx] = 20 - xx; -} // Initialize x_array to 20, 19, 18,... 2, 1 - -// Declare a pointer of type int and initialize it to point to x_array -int* x_ptr = x_array; -// x_ptr now points to the first element in the array (the integer 20). -// This works because arrays are actually just pointers to their first element. - -// Arrays are pointers to their first element -printf("%d\n", *(x_ptr)); // => Prints 20 -printf("%d\n", x_array[0]); // => Prints 20 - -// Pointers are incremented and decremented based on their type -printf("%d\n", *(x_ptr + 1)); // => Prints 19 -printf("%d\n", x_array[1]); // => Prints 19 - -// You can also dynamically allocate contiguous blocks of memory with the -// standard library function malloc, which takes one integer argument -// representing the number of bytes to allocate from the heap. -int* my_ptr = (int*) malloc(sizeof(int) * 20); -for (xx=0; xx<20; xx++) { - *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx would also work here -} // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - -// Dereferencing memory that you haven't allocated gives -// unpredictable results -printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? - -// When you're done with a malloc'd block of memory, you need to free it, -// or else no one else can use it until your program terminates -free(my_ptr); - -// Strings can be char arrays, but are usually represented as char -// pointers: -char* my_str = "This is my very own string"; - -printf("%c\n", *my_str); // => 'T' - -function_1(); -} // end main function - -/////////////////////////////////////// -// Functions -/////////////////////////////////////// - -// Function declaration syntax: -// () - -int add_two_ints(int x1, int x2){ - return x1 + x2; // Use return to return a value -} - -/* -Functions are pass-by-value, but you can make your own references -with pointers so functions can mutate their values. - -Example: in-place string reversal -*/ - -// A void function returns no value -void str_reverse(char* str_in){ - char tmp; - int ii=0, len = strlen(str_in); // Strlen is part of the c standard library - for(ii=0; ii ".tset a si sihT" -*/ - -/////////////////////////////////////// -// User-defined types and structs -/////////////////////////////////////// - -// Typedefs can be used to create type aliases -typedef int my_type; -my_type my_type_var = 0; - -// Structs are just collections of data -struct rectangle { - int width; - int height; -}; - - -void function_1(){ - - struct rectangle my_rec; - - // Access struct members with . - my_rec.width = 10; - my_rec.height = 20; - - // You can declare pointers to structs - struct rectangle* my_rec_ptr = &my_rec; - - // Use dereferencing to set struct pointer members... - (*my_rec_ptr).width = 30; - - // ... or use the -> shorthand - my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10; -} - -// You can apply a typedef to a struct for convenience -typedef struct rectangle rect; - -int area(rect r){ - return r.width * r.height; -} + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // the Bicycle class has + // four methods + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void applyBrake(int decrement) { + speed -= decrement; + } + + public void speedUp(int increment) { + speed += increment; + } + + } + + //Now..Later in the main / driver of your java program + + public class Main + { + public static void main (String[] args) throws java.lang.Exception + { + //Call bicycle's constructor + Bicycle trek = new Bicycle(); + trek.speedUp(3); + trek.setCadence(100); + } + } ``` ## 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) - -Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/) - -Other than that, Google is your friend. +Other Topics To Research: + -Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) + -Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) + -Exceptions (http://en.wikipedia.org/wiki/Exception_handling) + -Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) + -Generics (http://en.wikipedia.org/wiki/Generics_in_Java) + The links provided are just to get an understanding of the topic, feel free to google and find specific examples From c3df7c1c5358e34673264122f16ceaf5f17e236c Mon Sep 17 00:00:00 2001 From: Malcolm Fell Date: Sun, 30 Jun 2013 15:52:45 +1200 Subject: [PATCH 015/110] Clarify includes and open tags. If it's not PHP, it doesn't need the open tag. --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 20923548..75bbd214 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -379,7 +379,7 @@ echo $function_name(1, 2); // => 3 ``` ```php Date: Sat, 29 Jun 2013 22:54:10 -0500 Subject: [PATCH 016/110] Update java.html.markdown --- java.html.markdown | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 2f9c143b..80271f7f 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -180,6 +180,38 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) System.out.println(i); } + // Switch Case + int month = 8; + String monthString; + switch (month) { + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + case 4: monthString = "April"; + break; + case 5: monthString = "May"; + break; + case 6: monthString = "June"; + break; + case 7: monthString = "July"; + break; + case 8: monthString = "August"; + break; + case 9: monthString = "September"; + break; + case 10: monthString = "October"; + break; + case 11: monthString = "November"; + break; + case 12: monthString = "December"; + break; + default: monthString = "Invalid month"; + break; + } + System.out.println(monthString); /////////////////////////////////////// // Typecasting From 9c9f2c6b9a50ccc7a987d3c9bf6fd26bd1cc3d15 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:54:53 -0500 Subject: [PATCH 017/110] Update java.html.markdown --- java.html.markdown | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 80271f7f..5f8aec2b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -305,9 +305,15 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) ## Further Reading Other Topics To Research: - -Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) - -Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) - -Exceptions (http://en.wikipedia.org/wiki/Exception_handling) - -Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) - -Generics (http://en.wikipedia.org/wiki/Generics_in_Java) - The links provided are just to get an understanding of the topic, feel free to google and find specific examples + + * Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) + + * Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) + + * Exceptions (http://en.wikipedia.org/wiki/Exception_handling) + + * Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) + + * Generics (http://en.wikipedia.org/wiki/Generics_in_Java) + + * The links provided are just to get an understanding of the topic, feel free to google and find specific examples From 0523de70a1335c036442863b6dc672d50157d66a Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:56:22 -0500 Subject: [PATCH 018/110] Update java.html.markdown --- java.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 5f8aec2b..e14f356d 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -97,7 +97,7 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) array[1] = 1; System.out.println(array[1]); // => 1 array[1] = 2; - printf("%d\n", my_array[1]); // => 2 + System.out.println(array[1]); // => 2 //Others to check out //ArrayLists - Like arrays except more functionality is offered, and the size is mutable @@ -139,10 +139,10 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) // Incrementations int i=0; - i++; //i = 1. Post Incrementation - ++i; //i = 2. Pre Incrementation - i--; //i = 1. Post Decrementation - --i; //i = 0. Pre Decrementation + i++; //i = 1. Post-Incrementation + ++i; //i = 2. Pre-Incrementation + i--; //i = 1. Post-Decrementation + --i; //i = 0. Pre-Decrementation /////////////////////////////////////// // Control Structures @@ -288,13 +288,13 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) } //Now..Later in the main / driver of your java program - public class Main { public static void main (String[] args) throws java.lang.Exception { //Call bicycle's constructor Bicycle trek = new Bicycle(); + //Manipulate your object trek.speedUp(3); trek.setCadence(100); } From 79c26e6679948063036675b132a409b855d43cf1 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Sat, 29 Jun 2013 21:35:11 -0700 Subject: [PATCH 019/110] Added a few lines about truthiness, how lists can contain arbitrary data types, how you can unpack both tuples and lists, using ange, assigning lambdas to variables, dictionary comprehensions, modules, and links to more info about the standard library. --- python.html.markdown | 65 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index d1152b82..9c59a8d7 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -91,6 +91,16 @@ not False #=> True # None is an object None #=> None +# Don't use the equality `==` symbol to compare objects to None +# Use `is` instead +"etc" is None #=> False +None is None #=> True + +# None, 0, and empty strings/lists all evaluate to False. +# All other values are True +0 == False #=> True +"" == False #=> True + #################################################### ## 2. Variables and Collections @@ -164,6 +174,9 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Examine the length with len len(li) #=> 6 +# Note: lists can contain arbitrary values +li2 = [1, "Hello", [[], "Hi", 5,]] + # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 @@ -178,7 +191,7 @@ tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True -# You can unpack tuples into variables +# 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 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 @@ -276,6 +289,18 @@ prints: for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings print "%s is a mammal" % animal + +""" +`range(number)` returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i """ While loops go until a condition is no longer met. @@ -364,6 +389,8 @@ add_10(3) #=> 13 # There are also anonymous functions (lambda x: x > 2)(3) #=> True +rectangle_area = lambda a, b: a * b +print rectangle_area(3, 4) #=> 12 # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] @@ -373,6 +400,9 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# You can also use dictionary comprehensions +{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13} + #################################################### ## 5. Classes #################################################### @@ -388,7 +418,8 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument + # An instance method. All methods take self as the first argument, + # which refers to the instance of this class def say(self, msg): return "%s: %s" % (self.name, msg) @@ -421,9 +452,39 @@ j.get_species() #=> "H. neanderthalensis" # Call the static method Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +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 floor3.7) #=> 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python modules are just ordinary python files. You +# can write your own, and import them. + + ``` ## Further Reading Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +Python has a huge amount of modules within the standard library. See the +[official documentation](http://docs.python.org/2/library/index.html) or +[Python Module of the Week](http://pymotw.com/2/) for more. From ba55f6fcaadebbcd76501ab69b5be03a66d0460f Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 23:13:53 -0700 Subject: [PATCH 020/110] Fix whitespace --- java.html.markdown | 474 +++++++++++++++++++++---------------------- python.html.markdown | 13 +- 2 files changed, 245 insertions(+), 242 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index e14f356d..f6890d9b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -15,173 +15,173 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) /////////////////////////////////////// // General /////////////////////////////////////// - // Single-line comments start with // - /* - Multi-line comments look like this. - */ - - // Import Packages - import java.util.ArrayList; - import package.path.here; - // Import all "sub-packages" - import java.lang.Math.*; - - // Your program's entry point is a function called main - public class Main - { - public static void main (String[] args) throws java.lang.Exception - { - //stuff here - } - } - - // Printing, and forcing a new line on next print = println() - System.out.println("Hello World"); - System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); - // Printing, without forcing a new line on next print = print() - System.out.print("Hello World"); - System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); +// Single-line comments start with // +/* +Multi-line comments look like this. +*/ + +// Import Packages +import java.util.ArrayList; +import package.path.here; +// Import all "sub-packages" +import java.lang.Math.*; + +// Your program's entry point is a function called main +public class Main +{ + public static void main (String[] args) throws java.lang.Exception + { + //stuff here + } +} + +// Printing, and forcing a new line on next print = println() +System.out.println("Hello World"); +System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); +// Printing, without forcing a new line on next print = print() +System.out.print("Hello World"); +System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); /////////////////////////////////////// // Types /////////////////////////////////////// - // Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) - byte foo = 100; - - // Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) - short bar = 10000; - - //Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) - int foo = 1; - - //Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long bar = 100000L; - - //Float - Single-precision 32-bit IEEE 754 Floating Point - float foo = 234.5f; - - //Double - Double-precision 64-bit IEEE 754 Floating Point - double bar = 123.4; - - //Boolean - True & False - boolean foo = true; - boolean bar = false; - - //Char - A single 16-bit Unicode character - char foo = 'A'; - - //Make a variable a constant - final int HOURS_I_WORK_PER_WEEK = 9001; - - //Strings - String foo = "Hello World!"; - // \n is an escaped character that starts a new line - String foo = "Hello World!\nLine2!"; - System.out.println(foo); - //Hello World! - //Line2! - - //Arrays - //The array size must be decided upon declaration - //The format for declaring an array is follows: - // [] = new []; - int [] array = new int[10]; - String [] array = new String[1]; - boolean [] array = new boolean[100]; - - // Indexing an array - Accessing an element - array[0]; - - // Arrays are mutable; it's just memory! - array[1] = 1; - System.out.println(array[1]); // => 1 - array[1] = 2; - System.out.println(array[1]); // => 2 - - //Others to check out - //ArrayLists - Like arrays except more functionality is offered, and the size is mutable - //LinkedLists - //Maps - //HashMaps +// Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) +byte foo = 100; + +// Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) +short bar = 10000; + +//Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) +int foo = 1; + +//Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) +long bar = 100000L; + +//Float - Single-precision 32-bit IEEE 754 Floating Point +float foo = 234.5f; + +//Double - Double-precision 64-bit IEEE 754 Floating Point +double bar = 123.4; + +//Boolean - True & False +boolean foo = true; +boolean bar = false; + +//Char - A single 16-bit Unicode character +char foo = 'A'; + +//Make a variable a constant +final int HOURS_I_WORK_PER_WEEK = 9001; + +//Strings +String foo = "Hello World!"; +// \n is an escaped character that starts a new line +String foo = "Hello World!\nLine2!"; +System.out.println(foo); +//Hello World! +//Line2! + +//Arrays +//The array size must be decided upon declaration +//The format for declaring an array is follows: +// [] = new []; +int [] array = new int[10]; +String [] array = new String[1]; +boolean [] array = new boolean[100]; + +// Indexing an array - Accessing an element +array[0]; + +// Arrays are mutable; it's just memory! +array[1] = 1; +System.out.println(array[1]); // => 1 +array[1] = 2; +System.out.println(array[1]); // => 2 + +//Others to check out +//ArrayLists - Like arrays except more functionality is offered, and the size is mutable +//LinkedLists +//Maps +//HashMaps /////////////////////////////////////// // Operators /////////////////////////////////////// - int i1 = 1, i2 = 2; // Shorthand for multiple declarations - - // Arithmetic is straightforward - i1 + i2; // => 3 - i2 - i1; // => 1 - i2 * i1; // => 2 - i1 / i2; // => 0 (0.5, but truncated towards 0) - - // Modulo - 11 % 3; // => 2 - - // Comparison operators - 3 == 2; // => 0 (false) - 3 != 2; // => 1 (true) - 3 > 2; // => 1 - 3 < 2; // => 0 - 2 <= 2; // => 1 - 2 >= 2; // => 1 - - // Bitwise operators! - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR - - // Incrementations - int i=0; - i++; //i = 1. Post-Incrementation - ++i; //i = 2. Pre-Incrementation - i--; //i = 1. Post-Decrementation - --i; //i = 0. Pre-Decrementation +int i1 = 1, i2 = 2; // Shorthand for multiple declarations + +// Arithmetic is straightforward +i1 + i2; // => 3 +i2 - i1; // => 1 +i2 * i1; // => 2 +i1 / i2; // => 0 (0.5, but truncated towards 0) + +// Modulo +11 % 3; // => 2 + +// Comparison operators +3 == 2; // => 0 (false) +3 != 2; // => 1 (true) +3 > 2; // => 1 +3 < 2; // => 0 +2 <= 2; // => 1 +2 >= 2; // => 1 + +// Bitwise operators! +~ Unary bitwise complement +<< Signed left shift +>> Signed right shift +>>> Unsigned right shift +& Bitwise AND +^ Bitwise exclusive OR +| Bitwise inclusive OR + +// Incrementations +int i=0; +i++; //i = 1. Post-Incrementation +++i; //i = 2. Pre-Incrementation +i--; //i = 1. Post-Decrementation +--i; //i = 0. Pre-Decrementation /////////////////////////////////////// // Control Structures /////////////////////////////////////// - if (false) { - System.out.println("I never run"); - } else if (false) { - System.out.println("I am also never run"); - } else { - System.out.println("I print"); - } - } +if (false) { + System.out.println("I never run"); + } else if (false) { + System.out.println("I am also never run"); + } else { + System.out.println("I print"); + } +} - // While loop - int i = 0; - while(i < 100){ - System.out.println(i); - //Increment the counter - i++; - } - - // Do While Loop - int i = 0; - do{ - System.out.println(i); - //Increment the counter - i++; - }while(i < 100); - - // For Loop - int i; - //for loop structure => for(;;) - for(i=0;i<100;i++){ - System.out.println(i); - } - - // Switch Case - int month = 8; +// While loop +int i = 0; +while(i < 100){ + System.out.println(i); + //Increment the counter + i++; +} + +// Do While Loop +int i = 0; +do{ + System.out.println(i); + //Increment the counter + i++; +}while(i < 100); + +// For Loop +int i; +//for loop structure => for(;;) +for(i=0;i<100;i++){ + System.out.println(i); +} + +// Switch Case +int month = 8; String monthString; switch (month) { case 1: monthString = "January"; @@ -217,88 +217,88 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) // Typecasting /////////////////////////////////////// - // Converting data - - //Convert String To Integer - Integer.parseInt("123");//returns an integer version of "123" - - //Convert Integer To String - Integer.toString(123);//returns a string version of 123 - - //For other conversions check out the following classes: - //Double - //Long - //String - - // You can also cast java objects, there's a lot of details and - // deals with some more intermediate concepts. - // Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - +// Converting data + +//Convert String To Integer +Integer.parseInt("123");//returns an integer version of "123" + +//Convert Integer To String +Integer.toString(123);//returns a string version of 123 + +//For other conversions check out the following classes: +//Double +//Long +//String + +// You can also cast java objects, there's a lot of details and +// deals with some more intermediate concepts. +// Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + /////////////////////////////////////// // Classes And Functions /////////////////////////////////////// - // Classes Syntax shown below. - // Function declaration syntax: - // () - // Here is a quick rundown on access level modifiers (public, private, etcetc) http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html +// Classes Syntax shown below. +// Function declaration syntax: +// () +// Here is a quick rundown on access level modifiers (public, private, etcetc) http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html - - public class Bicycle { - - // Bicycle's Fields/Variables - public int cadence; - public int gear; - public int speed; - - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle(){ - gear = 1; - cadence = 50; - startGear = 1; - } - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear) { - gear = startGear; - cadence = startCadence; - speed = startSpeed; - } - - // the Bicycle class has - // four methods - public void setCadence(int newValue) { - cadence = newValue; - } - - public void setGear(int newValue) { - gear = newValue; - } - - public void applyBrake(int decrement) { - speed -= decrement; - } - - public void speedUp(int increment) { - speed += increment; - } - - } - - //Now..Later in the main / driver of your java program - public class Main - { - public static void main (String[] args) throws java.lang.Exception - { - //Call bicycle's constructor - Bicycle trek = new Bicycle(); - //Manipulate your object - trek.speedUp(3); - trek.setCadence(100); - } - } +public class Bicycle { + + // Bicycle's Fields/Variables + public int cadence; + public int gear; + public int speed; + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle(){ + gear = 1; + cadence = 50; + startGear = 1; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // the Bicycle class has + // four methods + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void applyBrake(int decrement) { + speed -= decrement; + } + + public void speedUp(int increment) { + speed += increment; + } + +} + +//Now..Later in the main / driver of your java program +public class Main +{ + public static void main (String[] args) throws java.lang.Exception + { + //Call bicycle's constructor + Bicycle trek = new Bicycle(); + //Manipulate your object + trek.speedUp(3); + trek.setCadence(100); + } +} ``` @@ -306,14 +306,14 @@ Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) Other Topics To Research: - * Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) - - * Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) - - * Exceptions (http://en.wikipedia.org/wiki/Exception_handling) - - * Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) - - * Generics (http://en.wikipedia.org/wiki/Generics_in_Java) - - * The links provided are just to get an understanding of the topic, feel free to google and find specific examples +* Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) + +* Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) + +* Exceptions (http://en.wikipedia.org/wiki/Exception_handling) + +* Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) + +* Generics (http://en.wikipedia.org/wiki/Generics_in_Java) + +* The links provided are just to get an understanding of the topic, feel free to google and find specific examples diff --git a/python.html.markdown b/python.html.markdown index d1152b82..467a179e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -111,7 +111,7 @@ except NameError: print "Raises a name error" # if can be used as an expression -some_var = a if a > b else b +some_var = 1 if 1 > 2 else 2 # => 2 # If a is greater than b, then a is assigned to some_var. # Otherwise b is assigned to some_var. @@ -207,8 +207,11 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -# Trying to look up a non-existing key will raise a KeyError -filled_dict["four"] #=> KeyError +try: + # Trying to look up a non-existing key will raise a KeyError + filled_dict["four"] #=> KeyError +except KeyError: + pass # Use get method to avoid the KeyError filled_dict.get("one") #=> 1 @@ -235,7 +238,7 @@ filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & -other_set = set{3, 4, 5, 6} +other_set = {3, 4, 5, 6} filled_set & other_set #=> {3, 4, 5} # Do set union with | @@ -337,7 +340,7 @@ def keyword_args(**kwargs): keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} # You can do both at once, if you like -def all_the_args(*args, **kwargs): +def foo(*args, **kwargs): print args print kwargs """ From 0615be257d5d3437e256be8de9ed5abac4315f02 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 23:16:41 -0700 Subject: [PATCH 021/110] Fixed line lengths --- java.html.markdown | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index f6890d9b..8d882234 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -12,9 +12,6 @@ Java is a general-purpose, concurrent, class-based, object-oriented computer pro Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) ```java -/////////////////////////////////////// -// General -/////////////////////////////////////// // Single-line comments start with // /* Multi-line comments look like this. @@ -46,18 +43,24 @@ System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); // Types /////////////////////////////////////// -// Byte - 8-bit signed two's complement integer (-128 <= byte <= 127) +// Byte - 8-bit signed two's complement integer +// (-128 <= byte <= 127) byte foo = 100; -// Short - 16-bit signed two's complement integer (-32,768 <= short <= 32,767) +// Short - 16-bit signed two's complement integer +// (-32,768 <= short <= 32,767) short bar = 10000; -//Integer - 32-bit signed two's complement integer (-2,147,483,648 <= int <= 2,147,483,647) +//Integer - 32-bit signed two's complement integer +// (-2,147,483,648 <= int <= 2,147,483,647) int foo = 1; -//Long - 64-bit signed two's complement integer (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) +//Long - 64-bit signed two's complement integer +// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long bar = 100000L; +// (Java has no unsigned types) + //Float - Single-precision 32-bit IEEE 754 Floating Point float foo = 234.5f; @@ -100,7 +103,8 @@ array[1] = 2; System.out.println(array[1]); // => 2 //Others to check out -//ArrayLists - Like arrays except more functionality is offered, and the size is mutable +//ArrayLists - Like arrays except more functionality is offered, +// and the size is mutable //LinkedLists //Maps //HashMaps @@ -232,7 +236,8 @@ Integer.toString(123);//returns a string version of 123 // You can also cast java objects, there's a lot of details and // deals with some more intermediate concepts. -// Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html +// Feel free to check it out here: +// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html /////////////////////////////////////// @@ -242,7 +247,8 @@ Integer.toString(123);//returns a string version of 123 // Classes Syntax shown below. // Function declaration syntax: // () -// Here is a quick rundown on access level modifiers (public, private, etcetc) http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html +// Here is a quick rundown on access level modifiers (public, private, etc.) +// http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html public class Bicycle { From 600b5b5b741f6a8937b20f8f154362a125ce4e92 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 30 Jun 2013 17:33:10 +0930 Subject: [PATCH 022/110] Added links to MDN, tidied intro --- javascript.html.markdown | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index c3bf131c..acac1795 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -5,8 +5,10 @@ author_url: http://adam.brenecki.id.au --- Javascript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for web apps, complimenting Java for -more complex ones, but has become far more widely used than Java on the web. +intended as a simpler scripting language for websites, complimenting the use of +Java for more complex web applications, but its tight integration with Web pages +and built-in support in browsers has caused it to become far more common than +Java in web frontends. Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or @@ -225,3 +227,11 @@ String.prototype.firstCharacter = function(){ "abc".firstCharacter() // = "a" ``` + +## Further Reading + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. From 7c4bd7120c36b525c126e08df0b22c25830ba4e0 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 30 Jun 2013 17:44:25 +0930 Subject: [PATCH 023/110] Edits to section on strings and numbers --- javascript.html.markdown | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index acac1795..6234aebc 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -26,29 +26,34 @@ doStuff(); // wherever there's a newline, except in certain cases. doStuff() -// Semicolons are a heated topic in the JavaScript world, but they're really a -// matter of personal or style-guide preference. We'll leave them off here. +// We'll leave semicolons off here; whether you do or not will depend on your +// personal preference or your project's style guide. /*********** - * 1. Primitive Datatypes and Operators + * 1. Numbers, Strings and Operators ***********/ // Javascript has one number type that covers ints and floats. 3 // = 3 1.5 // = 1.5 -// which support all the operations you'd expect. +// All the basic arithmetic works as you'd expect. 1 + 1 // = 2 8 - 1 // = 7 10 * 2 // = 20 35 / 5 // = 7 -// Uneven division works how you'd expect, too. +// Including uneven division. 5 / 2 // = 2.5 // Enforce precedence with parentheses (1 + 3) * 2 // = 8 +// 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 + // There's also a boolean type. true false @@ -70,10 +75,10 @@ false 2 != 1 // = true // More comparisons -1 < 10 // => True -1 > 10 // => False -2 <= 2 // => True -2 >= 2 // => True +1 < 10 // = true +1 > 10 // = false +2 <= 2 // = true +2 >= 2 // = true // Strings are concatenated with + "Hello " + "world!" // = "Hello world!" @@ -81,17 +86,21 @@ false // and are compared with < and > "a" < "b" // = true -// You can also compare strings with numbers +// Type coercion is performed for comparisons... "5" == 5 // = true -// but this is almost always not what you want, so use === to stop this +// ...unless you use === "5" === 5 // = false // You can access characters in a string with charAt "This is a string".charAt(0) -// There's also a null keyword -null // = null +// There's also null and undefined +null // used to indicate a deliberate non-value +undefined // used to indicate a value that hasn't been set yet + +// null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". /*********** * 2. Variables, Arrays and Objects From c2d5429472fb945bec81b42789dc0fd6161df433 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 30 Jun 2013 17:48:50 +0930 Subject: [PATCH 024/110] Tidy up section on variables, arrays and objects --- javascript.html.markdown | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 6234aebc..cb866886 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -108,13 +108,16 @@ undefined // used to indicate a value that hasn't been set yet // Variables are declared with the var keyword. Javascript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. -var some_var = 5 +var someVar = 5 // if you leave the var keyword off, you won't get an error... -some_other_var = 10 +someOtherVar = 10 -// but your variable will always end up with the global scope, even if it wasn't -// defined there, so don't do it. +// ...but your variable will be created in the global scope, not in the scope +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar // = undefined // Arrays are ordered lists of values, of any type. ["Hello", 45, true] @@ -133,7 +136,7 @@ myObj["my other key"] // = 4 // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey // = "myValue" -// Objects are mutable, values can be changed and new keys added. +// Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true /*********** From 3b8ece99323979cbb598589ec062b56fa311ad2c Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 30 Jun 2013 18:14:53 +0930 Subject: [PATCH 025/110] Continue work on objects cont'd section --- javascript.html.markdown | 73 ++++++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 21 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index cb866886..afa37bf1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -139,6 +139,9 @@ myObj.myKey // = "myValue" // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true +// If you try to access a value that's not yet set, you'll get undefined. +myObj.myFourthKey // = undefined + /*********** * 3. Control Structures ***********/ @@ -151,16 +154,16 @@ myObj.myThirdKey = true * 6. More about Objects; Constructors and Prototypes ***********/ -// Objects can contain functions, which can be called using the dot syntax. -myObj = { +// Objects can contain functions. +var myObj = { myFunc: function(){ return "Hello world!" } } myObj.myFunc() // = "Hello world!" -// When functions are called like this, they can access the object they're -// attached to using the this keyword. +// When functions attached to an object are called, they can access the object +// they're attached to using the this keyword. myObj = { myString: "Hello world!", myFunc: function(){ @@ -169,14 +172,14 @@ myObj = { } myObj.myFunc() // = "Hello world!" -// The value of this has to do with how the function is called, not where it's -// defined. So, that doesn't work if the function isn't called in the context of -// the object. +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. var myFunc = myObj.myFunc myFunc() // = undefined // Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't defined as such. +// through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase() } @@ -193,18 +196,27 @@ var MyConstructor = function(){ myNewObj = new MyConstructor() // = {myNumber: 5} myNewObj.myNumber // = 5 -// JavaScript objects aren't defined in terms of classes like other languages, -// but you can use prototypes to do many of the same things. When you try to -// access a property of an object that isn't present, its prototype is searched. -var myObj = {} +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property __proto__. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +var myObj = { + myString: "Hello world!", +} var myPrototype = { meaningOfLife: 42, - myThirdFunc: function(){ + myFunc: function(){ return this.myString.toLowerCase() } } myObj.__proto__ = myPrototype -myObj.myThirdFunc() // = "hello world!" +myObj.meaningOfLife // = 42 + +// This works for functions, too. +myObj.myFunc() // = "hello world!" // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. @@ -216,13 +228,18 @@ myObj.myBoolean // = true // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. -myObj. +myPrototype.meaningOfLife = 43 +myObj.meaningOfLife // = 43 -// The __proto__ magic property we've used to access prototypes isn't standard, -// and shouldn't be used in real-world code. There is a way to create a new -// object with another given object as its prototype, though: +// While the __proto__ magic property we've seen so far is useful for +// explaining prototypes, it's non-standard. There's no standard way to change +// an existing object's prototype, but there's two ways to set the prototype of +// a new object when you first create it. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 42 +myObj.meaningOfLife // = 43 // Unfortunately, Object.create is quite recent and isn't available in many // browsers, so you often can't use that, either. The most reliable way to set @@ -231,13 +248,27 @@ myObj.meaningOfLife // = 42 // TODO: write about the .prototype property on constructors // Built-in types' prototypes work like this too, so you can actually change -// the prototype of a string, for instance (although whether you should is -// another matter). +// the prototype of a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0) } "abc".firstCharacter() // = "a" +// There are several implementations of JavaScript, which all gain new features +// at different times. Sometimes, however, it's possible to replicate new +// features by altering built in types or prototypes, which is called +// "polyfilling". + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it if we do this: +if (Object.create === undefined){ + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){} + Constructor.prototype = proto + return new Constructor() + } +} ``` ## Further Reading From 8a870cab449e1aa1dd9741657457b061020a3ae9 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 30 Jun 2013 18:57:40 +0930 Subject: [PATCH 026/110] Add control structures --- javascript.html.markdown | 60 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index afa37bf1..858cec52 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -119,8 +119,20 @@ someOtherVar = 10 // Variables declared without being assigned to are set to undefined. var someThirdVar // = undefined +// There's shorthand for performing math operations on variables: +someVar += 5 // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10 // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++ // now someVar is 101 +someVar-- // back to 100 + // Arrays are ordered lists of values, of any type. -["Hello", 45, true] +var myArray = ["Hello", 45, true] + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1] // = 45 // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. @@ -130,7 +142,7 @@ var someThirdVar // = undefined // JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4} -// Object attributes can be accessed using the 'subscript' syntax, +// Object attributes can also be accessed using the subscript syntax, myObj["my other key"] // = 4 // ... or using the dot syntax, provided the key is a valid identifier. @@ -143,9 +155,46 @@ myObj.myThirdKey = true myObj.myFourthKey // = undefined /*********** - * 3. Control Structures + * 3. Logic and Control Structures ***********/ +// The if structure works as you'd expect. +var count = 1 +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4) { + // evaluated if count is 4 +} else { + // evaluated if it's not either +} + +// As does while. +while (true) { + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input +do { + input = getInput() +} while (!isValid(input)) + +// the for loop is the same as C and Java: initialisation; test; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear" +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values... +var name = otherName || "default"; + /*********** * 5. Functions, Scope and Closures ***********/ @@ -278,3 +327,8 @@ Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides excellent documentation for JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you can help others out by sharing your own knowledge. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. From 2008bcc258b899aae6d11033c1f28ef79db7ba42 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sun, 30 Jun 2013 07:50:04 -0500 Subject: [PATCH 027/110] Fixed url links. Now use markdown. --- java.html.markdown | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 8d882234..648b98bc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -9,7 +9,7 @@ author_url: http://github.com/JakeHP --- Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. -Read more here: https://en.wikipedia.org/wiki/Java_(programming_language) +[Read more here.](http://docs.oracle.com/javase/tutorial/java/index.html) ```java // Single-line comments start with // @@ -236,8 +236,7 @@ Integer.toString(123);//returns a string version of 123 // You can also cast java objects, there's a lot of details and // deals with some more intermediate concepts. -// Feel free to check it out here: -// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html +// Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html /////////////////////////////////////// @@ -312,14 +311,16 @@ public class Main Other Topics To Research: -* Inheritance (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) +* [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) -* Abstraction (http://en.wikipedia.org/wiki/Abstraction_(computer_science)) +* [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) -* Exceptions (http://en.wikipedia.org/wiki/Exception_handling) +* [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) -* Interfaces (http://en.wikipedia.org/wiki/Interfaces_(computer_science)) +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) -* Generics (http://en.wikipedia.org/wiki/Generics_in_Java) +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) * The links provided are just to get an understanding of the topic, feel free to google and find specific examples From 7ee4774f9b857f4d17fdcb086130bca862ae15f0 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Sun, 30 Jun 2013 10:03:42 -0700 Subject: [PATCH 028/110] fixing issues listed in "gripes about haskell" (fixes bug #45) --- haskell.html.markdown | 66 +++++++++++++++++++++++++++++++------------ 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index a696cb5f..7158e2aa 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -45,15 +45,21 @@ not False -- True 1 /= 1 -- False 1 < 10 -- True +-- In the above examples, `not` is a function that takes one value. +-- Haskell doesn't need parentheses for function calls...all the arguments +-- are just listed after the function. So the general pattern is: +-- func arg1 arg2 arg3... +-- See the section on functions for information on how to write your own. + -- Strings and characters "This is a string." 'a' -- character 'You cant use single quotes for strings.' -- error! --- Strings can be added too! +-- Strings can be concatenated "Hello " ++ "world!" -- "Hello world!" --- A string can be treated like a list of characters +-- A string is a list of characters "This is a string" !! 0 -- 'T' @@ -69,14 +75,24 @@ not False -- True -- You can also have infinite lists in Haskell! [1..] -- a list of all the natural numbers --- joining two lists +-- Infinite lists work because Haskell has "lazy evaluation". This means +-- that Haskell only evaluates things when it needs to. So you can ask for +-- the 1000th element of your list and Haskell will give it to you: + +[1..] !! 999 -- 1000 + +-- And now Haskell has evaluated elements 1 - 1000 of this list...but the +-- rest of the elements of this "infinite" list don't exist yet! Haskell won't +-- actually evaluate them until it needs to. + +- joining two lists [1..5] ++ [6..10] -- adding to the head of a list 0:[1..5] -- [0, 1, 2, 3, 4, 5] -- indexing into a list -[0..] !! 5 -- 4 +[0..] !! 5 -- 5 -- more list operations head [1..5] -- 1 @@ -136,12 +152,12 @@ foo (x, y) = (x + 1, y + 2) -- Pattern matching on arrays. Here `x` is the first element -- in the array, and `xs` is the rest of the array. We can write -- our own map function: -map func [x] = [func x] -map func (x:xs) = func x:(map func xs) +myMap func [x] = [func x] +myMap func (x:xs) = func x:(myMap func xs) -- Anonymous functions are created with a backslash followed by -- all the arguments. -map (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] -- using fold (called `inject` in some languages) with an anonymous -- function. foldl1 means fold left, and use the first value in the @@ -180,10 +196,10 @@ foo 5 -- 75 -- of parentheses: -- before -(even (double 7)) -- true +(even (fib 7)) -- true -- after -even . double $ 7 -- true +even . fib $ 7 -- true ---------------------------------------------------- -- 5. Type signatures @@ -198,13 +214,17 @@ True :: Bool -- Functions have types too. -- `not` takes a boolean and returns a boolean: -not :: Bool -> Bool +-- not :: Bool -> Bool -- Here's a function that takes two arguments: -add :: Integer -> Integer -> Integer +-- add :: Integer -> Integer -> Integer + +-- When you define a value, it's good practice to write it's type above it: +double :: Integer -> Integer +double x = x * 2 ---------------------------------------------------- --- 6. Control Flow +-- 6. Control Flow and If Statements ---------------------------------------------------- -- if statements @@ -263,25 +283,35 @@ Just 1 -- 8. Haskell IO ---------------------------------------------------- --- While IO can't be explained fully without explaining monads --- it is not hard to explain enough to get going +-- While IO can't be explained fully without explaining monads, +-- it is not hard to explain enough to get going. --- An IO a value is an IO action: you can chain them with do blocks +-- An `IO a` value is an IO action: you can chain them with do blocks +action :: IO String action = do putStrLn "This is a line. Duh" input <- getLine -- this gets a line and gives it the name "input" input2 <- getLine - return (input1++"\n"++input2) -- This is the result of the whole action + return (input1 ++ "\n" ++ input2) -- This is the result of the whole action -- This didn't actually do anything. When a haskell program is executed --- an IO action called "main" is read and interprete +-- an IO action called "main" is read and interpreted. main = do putStrLn "Our first program. How exciting!" result <- action -- our defined action is just like the default ones putStrLn result putStrLn "This was all, folks!" - + +-- Haskell does IO through a monad because this allows it to be a purely +-- functional language. Our `action` function had a type signature of `IO String`. +-- In general any function that interacts with the outside world (i.e. does IO) +-- gets marked as `IO` in it's type signature. This lets us reason about what +-- functions are "pure" (don't interact with the outside world or modify state) +-- and what functions aren't. + +-- This is a powerful feature, because it's easy to run pure functions concurrently +-- so concurrency in Haskell is very easy. ---------------------------------------------------- From fbe0fb471896e55c40d734b082f5e994e6dc775d Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sun, 30 Jun 2013 12:17:19 -0500 Subject: [PATCH 029/110] Added file name param and more. See description. -Fixed some minor issues/details -Can actually compile now (not just a bunch of random snippets) -Added more text & explanation to a few parts --- java.html.markdown | 379 ++++++++++++++++++++++++--------------------- 1 file changed, 201 insertions(+), 178 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 648b98bc..3208971d 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,6 +6,8 @@ author: Jake Prather author_url: http://github.com/JakeHP +filename: learnjava.java + --- Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. @@ -19,120 +21,120 @@ Multi-line comments look like this. // Import Packages import java.util.ArrayList; -import package.path.here; // Import all "sub-packages" import java.lang.Math.*; -// Your program's entry point is a function called main -public class Main +// Inside of the learnjava class, is your program's +// starting point. The main method. +public class learnjava { - public static void main (String[] args) throws java.lang.Exception + //main method + public static void main (String[] args) { - //stuff here - } -} - -// Printing, and forcing a new line on next print = println() -System.out.println("Hello World"); -System.out.println("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); -// Printing, without forcing a new line on next print = print() -System.out.print("Hello World"); -System.out.print("Integer: "+10+"Double: "+3.14+ "Boolean: "+true); + +System.out.println("->Printing"); +// Printing, and forcing a new line on next print, use println() +System.out.println("Hello World!"); +System.out.println("Integer: "+10+" Double: "+3.14+ " Boolean: "+true); +// Printing, without forcing a new line on next print, use print() +System.out.print("Hello World - "); +System.out.print("Integer: "+10+" Double: "+3.14+ " Boolean: "+true); /////////////////////////////////////// // Types /////////////////////////////////////// - +System.out.println("\n\n->Types"); // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) -byte foo = 100; +byte fooByte = 100; // Short - 16-bit signed two's complement integer // (-32,768 <= short <= 32,767) -short bar = 10000; +short fooShort = 10000; -//Integer - 32-bit signed two's complement integer +// Integer - 32-bit signed two's complement integer // (-2,147,483,648 <= int <= 2,147,483,647) -int foo = 1; +int fooInt = 1; -//Long - 64-bit signed two's complement integer +// Long - 64-bit signed two's complement integer // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) -long bar = 100000L; +long fooLong = 100000L; // (Java has no unsigned types) -//Float - Single-precision 32-bit IEEE 754 Floating Point -float foo = 234.5f; +// Float - Single-precision 32-bit IEEE 754 Floating Point +float fooFloat = 234.5f; -//Double - Double-precision 64-bit IEEE 754 Floating Point -double bar = 123.4; +// Double - Double-precision 64-bit IEEE 754 Floating Point +double fooDouble = 123.4; -//Boolean - True & False -boolean foo = true; -boolean bar = false; +// Boolean - True & False +boolean fooBoolean = true; +boolean barBoolean = false; -//Char - A single 16-bit Unicode character -char foo = 'A'; +// Char - A single 16-bit Unicode character +char fooChar = 'A'; -//Make a variable a constant +// Make a variable a constant final int HOURS_I_WORK_PER_WEEK = 9001; -//Strings -String foo = "Hello World!"; +// Strings +String fooString = "My String Is Here!"; // \n is an escaped character that starts a new line -String foo = "Hello World!\nLine2!"; -System.out.println(foo); -//Hello World! -//Line2! +String barString = "Printing on a new line?\nNo Problem!"; +System.out.println(fooString); +System.out.println(barString); -//Arrays +// Arrays //The array size must be decided upon declaration //The format for declaring an array is follows: // [] = new []; -int [] array = new int[10]; -String [] array = new String[1]; -boolean [] array = new boolean[100]; +int [] intArray = new int[10]; +String [] stringArray = new String[1]; +boolean [] booleanArray = new boolean[100]; // Indexing an array - Accessing an element -array[0]; +System.out.println("intArray @ 0: "+intArray[0]); // Arrays are mutable; it's just memory! -array[1] = 1; -System.out.println(array[1]); // => 1 -array[1] = 2; -System.out.println(array[1]); // => 2 +intArray[1] = 1; +System.out.println("intArray @ 1: "+intArray[1]); // => 1 +intArray[1] = 2; +System.out.println("intArray @ 1: "+intArray[1]); // => 2 -//Others to check out -//ArrayLists - Like arrays except more functionality is offered, +// Others to check out +// ArrayLists - Like arrays except more functionality is offered, // and the size is mutable -//LinkedLists -//Maps -//HashMaps +// LinkedLists +// Maps +// HashMaps /////////////////////////////////////// // Operators /////////////////////////////////////// +System.out.println("\n->Operators"); int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward -i1 + i2; // => 3 -i2 - i1; // => 1 -i2 * i1; // => 2 -i1 / i2; // => 0 (0.5, but truncated towards 0) +System.out.println("1+2 = "+(i1 + i2)); // => 3 +System.out.println("1+2 = "+(i2 - i1)); // => 1 +System.out.println("1+2 = "+(i2 * i1)); // => 2 +System.out.println("1+2 = "+(i1 / i2)); // => 0 (0.5, but truncated towards 0) // Modulo -11 % 3; // => 2 +System.out.println("11%3 = "+(11 % 3)); // => 2 // Comparison operators -3 == 2; // => 0 (false) -3 != 2; // => 1 (true) -3 > 2; // => 1 -3 < 2; // => 0 -2 <= 2; // => 1 -2 >= 2; // => 1 +System.out.println("3 == 2? "+(3 == 2)); // => 0 (false) +System.out.println("3 != 2? "+(3 != 2)); // => 1 (true) +System.out.println("3 > 2? "+(3 > 2)); // => 1 +System.out.println("3 < 2? "+(3 < 2)); // => 0 +System.out.println("2 <= 2? "+(2 <= 2)); // => 1 +System.out.println("2 >= 2? "+(2 >= 2)); // => 1 // Bitwise operators! +/* ~ Unary bitwise complement << Signed left shift >> Signed right shift @@ -140,100 +142,110 @@ i1 / i2; // => 0 (0.5, but truncated towards 0) & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR +*/ // Incrementations int i=0; -i++; //i = 1. Post-Incrementation -++i; //i = 2. Pre-Incrementation -i--; //i = 1. Post-Decrementation ---i; //i = 0. Pre-Decrementation +System.out.println("\n->Inc/Dec-rementation"); +System.out.println(i++); //i = 1. Post-Incrementation +System.out.println(++i); //i = 2. Pre-Incrementation +System.out.println(i--); //i = 1. Post-Decrementation +System.out.println(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// // Control Structures /////////////////////////////////////// - -if (false) { - System.out.println("I never run"); - } else if (false) { - System.out.println("I am also never run"); - } else { - System.out.println("I print"); - } +System.out.println("\n->Control Structures"); +if (false){ + System.out.println("I never run"); +}else if (false) { + System.out.println("I am also never run"); +} else { + System.out.println("I print"); } // While loop -int i = 0; -while(i < 100){ - System.out.println(i); +int fooWhile = 0; +while(fooWhile < 100) +{ + //System.out.println(fooWhile); //Increment the counter - i++; + //Iterated 99 times, fooWhile 0->99 + fooWhile++; } +System.out.println("fooWhile Value: "+fooWhile); // Do While Loop -int i = 0; -do{ - System.out.println(i); +int fooDoWhile = 0; +do +{ + //System.out.println(fooDoWhile); //Increment the counter - i++; -}while(i < 100); + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; +}while(fooDoWhile < 100); +System.out.println("fooDoWhile Value: "+fooDoWhile); // For Loop -int i; +int fooFor; //for loop structure => for(;;) -for(i=0;i<100;i++){ - System.out.println(i); +for(fooFor=0;fooFor<100;fooFor++){ + //System.out.println(fooFor); + //Iterated 99 times, fooFor 0->99 } +System.out.println("fooFor Value: "+fooFor); // Switch Case int month = 8; - String monthString; - switch (month) { - case 1: monthString = "January"; - break; - case 2: monthString = "February"; - break; - case 3: monthString = "March"; - break; - case 4: monthString = "April"; - break; - case 5: monthString = "May"; - break; - case 6: monthString = "June"; - break; - case 7: monthString = "July"; - break; - case 8: monthString = "August"; - break; - case 9: monthString = "September"; - break; - case 10: monthString = "October"; - break; - case 11: monthString = "November"; - break; - case 12: monthString = "December"; - break; - default: monthString = "Invalid month"; - break; - } - System.out.println(monthString); +String monthString; +switch (month){ + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + case 4: monthString = "April"; + break; + case 5: monthString = "May"; + break; + case 6: monthString = "June"; + break; + case 7: monthString = "July"; + break; + case 8: monthString = "August"; + break; + case 9: monthString = "September"; + break; + case 10: monthString = "October"; + break; + case 11: monthString = "November"; + break; + case 12: monthString = "December"; + break; + default: monthString = "Invalid month"; + break; +} +System.out.println("Switch Case Result: "+monthString); /////////////////////////////////////// -// Typecasting +// Converting Data Types And Typcasting /////////////////////////////////////// // Converting data -//Convert String To Integer +// Convert String To Integer Integer.parseInt("123");//returns an integer version of "123" -//Convert Integer To String +// Convert Integer To String Integer.toString(123);//returns a string version of 123 -//For other conversions check out the following classes: -//Double -//Long -//String +// For other conversions check out the following classes: +// Double +// Long +// String +// Typecsating // You can also cast java objects, there's a lot of details and // deals with some more intermediate concepts. // Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html @@ -243,66 +255,77 @@ Integer.toString(123);//returns a string version of 123 // Classes And Functions /////////////////////////////////////// -// Classes Syntax shown below. -// Function declaration syntax: -// () -// Here is a quick rundown on access level modifiers (public, private, etc.) -// http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html + // Read about the class, and function syntax before + // reading this. + System.out.println("\n->Classes & Functions"); + // Call bicycle's constructor + Bicycle trek = new Bicycle(); + // Manipulate your object + trek.speedUp(3); + trek.setCadence(100); + System.out.println("trek info: "+trek.toString()); + // Classes Syntax: + // class { + // //data fields, constructors, functions all inside + // } + // Function Syntax: + // () + // Here is a quick rundown on access level modifiers (public, private, etc.) + // http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html -public class Bicycle { - - // Bicycle's Fields/Variables - public int cadence; - public int gear; - public int speed; - - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle(){ - gear = 1; - cadence = 50; - startGear = 1; - } - - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear) { - gear = startGear; - cadence = startCadence; - speed = startSpeed; - } - - // the Bicycle class has - // four methods - public void setCadence(int newValue) { - cadence = newValue; - } - - public void setGear(int newValue) { - gear = newValue; - } - - public void applyBrake(int decrement) { - speed -= decrement; - } - - public void speedUp(int increment) { - speed += increment; - } - +// This bracket ends the main method } + // The static field is only required because this class + // is nested inside of the learnjava.java class. + public static class Bicycle { -//Now..Later in the main / driver of your java program -public class Main -{ - public static void main (String[] args) throws java.lang.Exception - { - //Call bicycle's constructor - Bicycle trek = new Bicycle(); - //Manipulate your object - trek.speedUp(3); - trek.setCadence(100); + // Bicycle's Fields/Variables + public int cadence; + public int gear; + public int speed; + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle(){ + gear = 1; + cadence = 50; + speed = 5; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // the Bicycle class has + // four functions/methods + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void applyBrake(int decrement) { + speed -= decrement; + } + + public void speedUp(int increment) { + speed += increment; + } + + public String toString(){ + return "gear: "+Integer.toString(gear)+ + " cadence: "+Integer.toString(cadence)+ + " speed: "+Integer.toString(speed); + } + // bracket to close nested Bicycle class } +// bracket to close learnjava.java } ``` From bc0f1fca6c5f248257993e7bc80bf2d54652b7aa Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 30 Jun 2013 14:50:51 -0700 Subject: [PATCH 030/110] Removed filename from haskell tutorial (file is not executable) --- haskell.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 7158e2aa..2437ceed 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -2,7 +2,6 @@ language: haskell author: Adit Bhargava author_url: http://adit.io -filename: learnhaskell.hs --- Haskell was designed as a practical, purely functional programming language. It's famous for From 77672e78916c4d35a67934b6c78e20b015ec687a Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:16:55 -0700 Subject: [PATCH 031/110] Fix some inconsistencies so that the doc can be read top to bottom --- python.html.markdown | 47 +++++++++++++++++--------------------------- 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 467a179e..9b0f0241 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -87,6 +87,8 @@ not False #=> True # A newer way to format strings is the format method. # This method is the preferred way "{0} can be {1}".format("strings", "formatted") +# You can use keywords if you don't want to count. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object None #=> None @@ -104,16 +106,12 @@ print "I'm Python. Nice to meet you!" some_var = 5 # Convention is to use lower_case_with_underscores some_var #=> 5 -# Accessing a previously unassigned variable is an exception -try: - some_other_var -except NameError: - print "Raises a name error" +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_other_var # Raises a name error # if can be used as an expression -some_var = 1 if 1 > 2 else 2 # => 2 -# If a is greater than b, then a is assigned to some_var. -# Otherwise b is assigned to some_var. +"yahoo!" if 1 > 2 else 2 #=> "yahoo!" # Lists store sequences li = [] @@ -136,10 +134,7 @@ li[0] #=> 1 li[-1] #=> 3 # Looking out of bounds is an IndexError -try: - li[4] # Raises an IndexError -except IndexError: - print "Raises an IndexError" +li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) @@ -167,10 +162,7 @@ len(li) #=> 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 -try: - tup[0] = 3 # Raises a TypeError -except TypeError: - print "Tuples cannot be mutated." +tup[0] = 3 # Raises a TypeError # You can do all those list thingies on tuples too len(tup) #=> 3 @@ -207,16 +199,12 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -try: - # Trying to look up a non-existing key will raise a KeyError - filled_dict["four"] #=> KeyError -except KeyError: - pass + # Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError # Use get method to avoid the KeyError 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 @@ -259,7 +247,7 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6} # Let's just make a variable some_var = 5 -# Here is an if statement. INDENTATION IS SIGNIFICANT IN PYTHON! +# Here is an if statement. Indentation is significant in python! # prints "some var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." @@ -340,21 +328,22 @@ def keyword_args(**kwargs): keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} # You can do both at once, if you like -def foo(*args, **kwargs): +def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4) prints: - [1, 2] + (1, 2) {"a": 3, "b": 4} """ -# You can also use * and ** when calling a function +# When calling functions, you can do the opposite of varargs/kwargs! +# Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -foo(*args) # equivalent to foo(1, 2, 3, 4) -foo(**kwargs) # equivalent to foo(a=3, b=4) -foo(*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) # Python has first class functions def create_adder(x): From ae5060a4bf432095539bc3ff77bfec67082cbbb3 Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:35:20 -0700 Subject: [PATCH 032/110] Add to Python reference material --- python.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 9b0f0241..76f96d57 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -417,5 +417,8 @@ Human.grunt() #=> "*grunt*" ## Further Reading -Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +Still up for more? Try: +[Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +[Dive Into Python](http://www.diveintopython.net/) +[The Official Docs](http://docs.python.org/2.6/) From 34a9f1aab1b35258c56e46b858f6b1e7a7f8e28b Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:36:37 -0700 Subject: [PATCH 033/110] Add line breaks --- python.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 76f96d57..34fa2680 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -420,5 +420,7 @@ Human.grunt() #=> "*grunt*" Still up for more? Try: [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) + [Dive Into Python](http://www.diveintopython.net/) + [The Official Docs](http://docs.python.org/2.6/) From 868b259db1e74010ded00c7020d8800255c4034d Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:47:56 -0700 Subject: [PATCH 034/110] Change formatting --- python.html.markdown | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 34fa2680..f34412ab 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -419,8 +419,6 @@ Human.grunt() #=> "*grunt*" Still up for more? Try: -[Learn Python The Hard Way](http://learnpythonthehardway.org/book/) - -[Dive Into Python](http://www.diveintopython.net/) - -[The Official Docs](http://docs.python.org/2.6/) +*[Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +*[Dive Into Python](http://www.diveintopython.net/) +*[The Official Docs](http://docs.python.org/2.6/) From 4d501a48fcd4d0f5e64f55a0a962b5e4302272a4 Mon Sep 17 00:00:00 2001 From: lodin Date: Sun, 30 Jun 2013 16:02:37 -0700 Subject: [PATCH 035/110] Fix typo. --- python.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index f34412ab..cf3ef9c5 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -419,6 +419,6 @@ Human.grunt() #=> "*grunt*" Still up for more? Try: -*[Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -*[Dive Into Python](http://www.diveintopython.net/) -*[The Official Docs](http://docs.python.org/2.6/) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) From ec6ffed3c92928bc86424ae9f2ea6d1e02bbbc03 Mon Sep 17 00:00:00 2001 From: lodin Date: Sun, 30 Jun 2013 16:18:20 -0700 Subject: [PATCH 036/110] Add hitchhiker's guide to python. --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/python.html.markdown b/python.html.markdown index cf3ef9c5..e2ad1eff 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -422,3 +422,4 @@ Still up for more? Try: * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) From 1193d43e89326feb150d7f7c0e8d03428115c80b Mon Sep 17 00:00:00 2001 From: Alexander Kahl Date: Mon, 1 Jul 2013 13:58:34 +0200 Subject: [PATCH 037/110] Rectified relationship to Lisp LISP refers to the historic programming language LISt Processing, whereas Lisp is the correct (modern) name of the programming language family. The change reflects this. Also see Wikipedia. --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 12611fd3..cb202a92 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -5,7 +5,7 @@ author_url: http://adambard.com/ filename: test.clj --- -Clojure is a variant of LISP developed for the Java Virtual Machine. It has +Clojure is a Lisp family language developed for the Java Virtual Machine. It has a much stronger emphasis on pure [functional programming](https://en.wikipedia.org/wiki/Functional_programming) than Common Lisp, but includes several [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) utilities to handle state as it comes up. From 2d6ed6d0832b12b7463f391b80a2fbd9dd9466ae Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 07:56:02 -0500 Subject: [PATCH 038/110] fixed some issues & added a new array init --- java.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 3208971d..e0ef49c3 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -19,10 +19,10 @@ Java is a general-purpose, concurrent, class-based, object-oriented computer pro Multi-line comments look like this. */ -// Import Packages +// Import ArrayList class inside of the java.util package import java.util.ArrayList; -// Import all "sub-packages" -import java.lang.Math.*; +// Import all classes inside of java.lang package +import java.lang.*; // Inside of the learnjava class, is your program's // starting point. The main method. @@ -93,6 +93,9 @@ int [] intArray = new int[10]; String [] stringArray = new String[1]; boolean [] booleanArray = new boolean[100]; +// Another way to declare & initialize an array +int [] y = {9000, 1000, 1337}; + // Indexing an array - Accessing an element System.out.println("intArray @ 0: "+intArray[0]); @@ -118,9 +121,9 @@ int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward System.out.println("1+2 = "+(i1 + i2)); // => 3 -System.out.println("1+2 = "+(i2 - i1)); // => 1 -System.out.println("1+2 = "+(i2 * i1)); // => 2 -System.out.println("1+2 = "+(i1 / i2)); // => 0 (0.5, but truncated towards 0) +System.out.println("1-2 = "+(i2 - i1)); // => 1 +System.out.println("1*2 = "+(i2 * i1)); // => 2 +System.out.println("1/2 = "+(i1 / i2)); // => 0 (0.5, but truncated towards 0) // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 From 1863a5de878d527ade6d15f0e4c4ad92695c054d Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 07:59:59 -0500 Subject: [PATCH 039/110] Text fix. --- java.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index e0ef49c3..587e793e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -121,8 +121,8 @@ int i1 = 1, i2 = 2; // Shorthand for multiple declarations // Arithmetic is straightforward System.out.println("1+2 = "+(i1 + i2)); // => 3 -System.out.println("1-2 = "+(i2 - i1)); // => 1 -System.out.println("1*2 = "+(i2 * i1)); // => 2 +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, but truncated towards 0) // Modulo From cc3dc30518605f80e2ef11751a050ebd2997bac9 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Sat, 29 Jun 2013 21:35:11 -0700 Subject: [PATCH 040/110] Added a few lines about truthiness, how lists can contain arbitrary data types, how you can unpack both tuples and lists, using ange, assigning lambdas to variables, dictionary comprehensions, modules, and links to more info about the standard library. --- python.html.markdown | 66 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 19e2aebe..c75e90c4 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -93,6 +93,16 @@ not False #=> True # None is an object None #=> None +# Don't use the equality `==` symbol to compare objects to None +# Use `is` instead +"etc" is None #=> False +None is None #=> True + +# None, 0, and empty strings/lists all evaluate to False. +# All other values are True +0 == False #=> True +"" == False #=> True + #################################################### ## 2. Variables and Collections @@ -159,6 +169,9 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Examine the length with len len(li) #=> 6 +# Note: lists can contain arbitrary values +li2 = [1, "Hello", [[], "Hi", 5,]] + # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 @@ -170,7 +183,7 @@ tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True -# You can unpack tuples into variables +# 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 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 @@ -267,6 +280,18 @@ prints: for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings print "%s is a mammal" % animal + +""" +`range(number)` returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i """ While loops go until a condition is no longer met. @@ -350,6 +375,8 @@ add_10(3) #=> 13 # There are also anonymous functions (lambda x: x > 2)(3) #=> True +rectangle_area = lambda a, b: a * b +print rectangle_area(3, 4) #=> 12 # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] @@ -359,6 +386,9 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# You can also use dictionary comprehensions +{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13} + #################################################### ## 5. Classes #################################################### @@ -374,7 +404,8 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument + # An instance method. All methods take self as the first argument, + # which refers to the instance of this class def say(self, msg): return "%s: %s" % (self.name, msg) @@ -407,6 +438,33 @@ j.get_species() #=> "H. neanderthalensis" # Call the static method Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +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 floor3.7) #=> 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Python modules are just ordinary python files. You +# can write your own, and import them. + + ``` ## Further Reading @@ -417,3 +475,7 @@ Still up for more? Try: * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) + +Python has a huge amount of modules within the standard library. See the +[official documentation](http://docs.python.org/2/library/index.html) or +[Python Module of the Week](http://pymotw.com/2/) for more. From c74780755887d270aebf5563bcfa4449e170dab0 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Mon, 1 Jul 2013 06:21:03 -0700 Subject: [PATCH 041/110] Incorporated feedback from lodin/adambard/others Changes: - Added a few lines on using "is" to compare object identity. - Removed example about lists containing arbitrary values. - Removed example about assigning lambdas to variables. - Removed example about dictionary comprehensions. - Removed the additional explanation about 'self' - Added a clarification on modules. --- python.html.markdown | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index c75e90c4..9324e29b 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -98,6 +98,10 @@ None #=> None "etc" is None #=> False None is None #=> True +# The 'is' operator tests for object identity. This isn't +# very useful when dealing with primitive values, but is +# very useful when dealing with objects. + # None, 0, and empty strings/lists all evaluate to False. # All other values are True 0 == False #=> True @@ -169,9 +173,6 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Examine the length with len len(li) #=> 6 -# Note: lists can contain arbitrary values -li2 = [1, "Hello", [[], "Hi", 5,]] - # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 @@ -375,8 +376,6 @@ add_10(3) #=> 13 # There are also anonymous functions (lambda x: x > 2)(3) #=> True -rectangle_area = lambda a, b: a * b -print rectangle_area(3, 4) #=> 12 # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] @@ -386,9 +385,6 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] -# You can also use dictionary comprehensions -{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13} - #################################################### ## 5. Classes #################################################### @@ -404,8 +400,7 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument, - # which refers to the instance of this class + # An instance method. All methods take self as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) @@ -462,7 +457,8 @@ import math as m math.sqrt(16) == m.sqrt(16) #=> True # Python modules are just ordinary python files. You -# can write your own, and import them. +# can write your own, and import them. The name of the +# module is the same as the name of the file. ``` From ebf9dd011de8b2e2a79d92c188d6aee63fc31cb7 Mon Sep 17 00:00:00 2001 From: vsthsqrs Date: Mon, 1 Jul 2013 16:10:05 +0200 Subject: [PATCH 042/110] Fixed typo: typcsating => typecasting --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 3208971d..7c297737 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -245,7 +245,7 @@ Integer.toString(123);//returns a string version of 123 // Long // String -// Typecsating +// Typecasting // You can also cast java objects, there's a lot of details and // deals with some more intermediate concepts. // Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html From 9da1289d91d710dcd9157e364a32b0ba7928c679 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 09:32:19 -0500 Subject: [PATCH 043/110] Added code conventions link --- java.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 587e793e..3d2e6bbe 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -349,4 +349,6 @@ Other Topics To Research: * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + * The links provided are just to get an understanding of the topic, feel free to google and find specific examples From 1ee6d1b17cbf417adb24db393586f36ab904099a Mon Sep 17 00:00:00 2001 From: Giovanni Cappellotto Date: Mon, 1 Jul 2013 16:39:39 +0200 Subject: [PATCH 044/110] Learn Erlang in Y minutes --- erlang.html.markdown | 239 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 erlang.html.markdown diff --git a/erlang.html.markdown b/erlang.html.markdown new file mode 100644 index 00000000..6ceb3172 --- /dev/null +++ b/erlang.html.markdown @@ -0,0 +1,239 @@ +--- +language: erlang +author: Giovanni Cappellotto +author_url: http://www.focustheweb.com/ +filename: learnerlang.erl +--- + +```erlang +% Percent sign start a one-line comment. + +%% Two percent characters shall be used to comment functions. + +%%% Three percent characters shall be used to comment modules. + +% We use three types of punctuation in Erlang. +% Commas (`,`) separate arguments in function calls, data constructors, and +% patterns. +% Periods (`.`) (followed by whitespace) separate entire functions and +% expressions in the shell. +% Semicolons (`;`) separate clauses. We find clauses in several contexts: in kn +% function definitions and in `case`, `if`, `try..catch` and `receive` +% expressions. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Variables and pattern matching. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % All variable names must start with an uppercase letter. +% Erlang has single assignment variables, if you try to assign a different value +% to the variable `Num`, you’ll get an error. + +% In most languages, `=` denotes an assignment statement. In Erlang, however, +% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this: +% evaluate the right side (Rhs), and then match the result against the pattern +% on the left side (Lhs). +Num = 7 * 6. + +% Floating point number. +Pi = 3.14159. + +% Atoms, are used to represent different non-numerical constant values. Atoms +% start with lowercase letters, followed by a sequence of alphanumeric +% characters or the underscore (`_`) or at (`@`) sign. +Hello = hello. + +% Tuples are similar to structs in C. +Point = {point, 10, 45}. + +% If we want to extract some values from a tuple, we use the pattern matching +% operator `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% We can use `_` as a placeholder for variables that we’re not interested in. +% The symbol `_` is called an anonymous variable. Unlike regular variables, +% several occurrences of _ in the same pattern don’t have to bind to the same +% value. +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% We create a list by enclosing the list elements in square brackets and +% separating them with commas. +% The individual elements of a list can be of any type. +% The first element of a list the head of the list. If you imagine removing the +% head from the list, what’s left is called the tail of the list. +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% If `T` is a list, then `[H|T]` is also a list, with head H and tail T. +% The vertical bar (`|`) separates the head of a list from its tail. +% `[]` is the empty list. +% We can extract elements from a list with a pattern matching operation. If we +% have the nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y` +% are unbound variables, will extract the head of the list into `X` and the tail +% of the list into `Y`. +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% There are no strings in Erlang. Strings are really just lists of integers. +% Strings are enclosed in double quotation marks (`"`). +Name = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Sequential programming. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Modules are the basic unit of code in Erlang. All the functions we write are +% stored in modules. Modules are stored in files with `.erl` extensions. +% Modules must be compiled before the code can be run. A compiled module has the +% extension `.beam`. +-module(geometry). +-export([area/1]). + +% The function area consists of two clauses. The clauses are separated by a +% semicolon, and the final clause is terminated by dot-whitespace. +% Each clause has a head and a body; the head consists of a function name +% followed by a pattern (in parentheses), and the body consists of a sequence of +% expressions, which are evaluated if the pattern in the head is successfully +% matched against the calling arguments. The patterns are matched in the order +% they appear in the function definition. +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% Compile the code in the file geometry.erl. +c(geometry). % {ok,geometry} + +% We need to include the module name together with the function name in order to +% identify exactly which function we want to call. +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% In Erlang, two functions with the same name and different arity in the same +% module represent entirely different functions. +-module(lib_misc). +-export([sum/1]). +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Funs are "anonymous" functions. They are called this because they have no +% name. +Double = fun(X) -> 2*X end. +Double(2). % 4 + +% Functions accept funs as their arguments and can return funs. +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% List comprehensions are expressions that create lists without having to use +% funs, maps, or filters. +% The notation `[F(X) || X <- L]` means "the list of `F(X)` where `X` is taken +% from the list `L`." +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] + +% Guards are constructs that we can use to increase the power of pattern +% matching. Using guards, we can perform simple tests and comparisons on the +% variables in a pattern. +% You can use guards in the heads of function definitions where they are +% introduced by the `when` keyword, or you can use them at any place in the +% language where an expression is allowed. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% A guard is a series of guard expressions, separated by commas (`,`). +% The guard `GuardExpr1, GuardExpr2, ..., GuardExprN` is true if all the guard +% expressions `GuardExpr1, GuardExpr2, ...` evaluate to true. +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% A `guard sequence` is either a single guard or a series of guards, separated +%by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at least +% one of the guards `G1, G2, ...` evaluates to true. +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Records provide a method for associating a name with a particular element in a +% tuple. +% Record definitions can be included in Erlang source code files or put in files +% with the extension `.hrl`, which are then included by Erlang source code +% files. +-record(todo, { + status = reminder, % Default value + who = joe, + text +}). + +% We have to read the record definitions into the shell before we can define a +% record. We use the shell function `rr` (short for read records) to do this. +rr("records.hrl"). % [todo] + +% Creating and updating records: +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% `case` expressions. +% `filter` returns a list of all those elements `X` in `L` for which `P(X)` is +% true. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. + +% `if` expressions. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% Warning: at least one of the guards in the if expression must evaluate to true; +% otherwise, an exception will be raised. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Exceptions. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Exceptions are raised by the system when internal errors are encountered or +% explicitly in code by calling `throw(Exception)`, `exit(Exception)` or +% `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% Erlang has two methods of catching an exception. One is to enclose the call to +% the function, which raised the exception within a `try...catch` expression. +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% The other is to enclose the call in a `catch` expression. When you catch an +% exception, it is converted into a tuple that describes the error. +catcher(N) -> catch generate_exception(N). + +``` + +## References + +* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) +* [Erlang/OTP Documentation](http://www.erlang.org/doc/) \ No newline at end of file From 5d946b13faf2ef9cccaa5338da0ee218d8e06ae4 Mon Sep 17 00:00:00 2001 From: Bruno Date: Mon, 1 Jul 2013 17:18:15 +0200 Subject: [PATCH 045/110] Make myMap work on empty lists Which is cleaner and the correct thing to do. --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index f3baa9a5..134ea2a9 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -155,7 +155,7 @@ foo (x, y) = (x + 1, y + 2) -- Pattern matching on arrays. Here `x` is the first element -- in the array, and `xs` is the rest of the array. We can write -- our own map function: -myMap func [x] = [func x] +myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) -- Anonymous functions are created with a backslash followed by From 9b6c837916dc50a4646ae1666528681e6e4a881c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lubom=C3=ADr=20Sedl=C3=A1=C5=99?= Date: Mon, 1 Jul 2013 17:33:25 +0200 Subject: [PATCH 046/110] Remove mentions of array Since all the functions work with lists, calling them arrays is inaccurate. This commit also updates `myMap` function so that it works on an empty list as well as resolves ambiguity about `x` from comment. --- haskell.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index f3baa9a5..1a4cdc67 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -152,10 +152,10 @@ fib x = fib (x - 1) + fib (x - 2) -- Pattern matching on tuples: foo (x, y) = (x + 1, y + 2) --- Pattern matching on arrays. Here `x` is the first element --- in the array, and `xs` is the rest of the array. We can write +-- Pattern matching on lists. Here `x` is the first element +-- in the list, and `xs` is the rest of the list. We can write -- our own map function: -myMap func [x] = [func x] +myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) -- Anonymous functions are created with a backslash followed by @@ -164,7 +164,7 @@ myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] -- using fold (called `inject` in some languages) with an anonymous -- function. foldl1 means fold left, and use the first value in the --- array as the initial value for the accumulator. +-- list as the initial value for the accumulator. foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- From 71f465ace674b595f03e9495ea04ed63c3730427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lubom=C3=ADr=20Sedl=C3=A1=C5=99?= Date: Mon, 1 Jul 2013 17:40:06 +0200 Subject: [PATCH 047/110] Fix typos in R tutorial --- r.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index f68ede0e..38317776 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -130,7 +130,7 @@ vec <- c(4, 5, 6, 7) vec # => [1] 4 5 6 7 # The class of a vector is the class of its components class(vec) # => [1] "numeric" -# If you vectorize items of different classes, weird coersions happen +# If you vectorize items of different classes, weird coercions happen c(TRUE, 4) # => [1] 1 4 c("dog", TRUE, 4) # => [1] "dog" "TRUE" "4" @@ -192,7 +192,7 @@ mat3 # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# Aah, everything of the same class. No coersions. Much better. +# Aah, everything of the same class. No coercions. Much better. # TWO-DIMENSIONAL (DIFFERENT CLASSES) @@ -273,7 +273,7 @@ apply(mat, MAR = 2, myFunc) # [2,] 7 19 # [3,] 11 23 # Other functions: ?lapply, ?sapply -# Don't feel too intimiated; everyone agrees they are rather confusing +# Don't feel too intimidated; everyone agrees they are rather confusing # The plyr package aims to replace (and improve upon!) the *apply() family. From d553ee4c6bf17f14acf06471963859326f8a5f8b Mon Sep 17 00:00:00 2001 From: elisee Date: Mon, 1 Jul 2013 17:50:25 +0200 Subject: [PATCH 048/110] Fix various "it's" -> "its" for Haskell doc --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 1a4cdc67..84b8f263 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -5,7 +5,7 @@ author_url: http://adit.io --- Haskell was designed as a practical, purely functional programming language. It's famous for -it's monads and it's type system, but I keep coming back to it because of it's elegance. Haskell +its monads and its type system, but I keep coming back to it because of its elegance. Haskell makes coding a real joy for me. ```haskell @@ -222,7 +222,7 @@ True :: Bool -- Here's a function that takes two arguments: -- add :: Integer -> Integer -> Integer --- When you define a value, it's good practice to write it's type above it: +-- When you define a value, it's good practice to write its type above it: double :: Integer -> Integer double x = x * 2 @@ -309,7 +309,7 @@ main = do -- Haskell does IO through a monad because this allows it to be a purely -- functional language. Our `action` function had a type signature of `IO String`. -- In general any function that interacts with the outside world (i.e. does IO) --- gets marked as `IO` in it's type signature. This lets us reason about what +-- gets marked as `IO` in its type signature. This lets us reason about what -- functions are "pure" (don't interact with the outside world or modify state) -- and what functions aren't. From 4642a4884c077477a2946e724fbfc2d483edc569 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 08:53:12 -0700 Subject: [PATCH 049/110] Updates --- erlang.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 6ceb3172..66370a7d 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -5,7 +5,7 @@ author_url: http://www.focustheweb.com/ filename: learnerlang.erl --- -```erlang +```latex % Percent sign start a one-line comment. %% Two percent characters shall be used to comment functions. @@ -236,4 +236,4 @@ catcher(N) -> catch generate_exception(N). * "Programming Erlang: Software for a Concurrent World" by Joe Armstrong * [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) -* [Erlang/OTP Documentation](http://www.erlang.org/doc/) \ No newline at end of file +* [Erlang/OTP Documentation](http://www.erlang.org/doc/) From 832652a45762d46804587ce1525f8a26e210055a Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 09:24:57 -0700 Subject: [PATCH 050/110] Updated java quick --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 3339b6d1..206f9cbe 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -22,7 +22,7 @@ Multi-line comments look like this. // Import ArrayList class inside of the java.util package import java.util.ArrayList; // Import all classes inside of java.lang package -import java.lang.*; +import java.security.*; // Inside of the learnjava class, is your program's // starting point. The main method. From 07aa1d9337252eea9f4d5103e028c894132be91f Mon Sep 17 00:00:00 2001 From: David Underwood Date: Mon, 1 Jul 2013 12:27:15 -0400 Subject: [PATCH 051/110] Adds sections for symbols, hashes, and yields --- ruby.html.markdown | 51 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index a317c498..b07c92c9 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -72,6 +72,18 @@ snake_case = true path_to_project_root = '/good/name/' path = '/bad/name/' +# Symbols +# Symbols are immutable, reusable constants represented internally by an integer value +# They're often used instead of strings to efficiently convey specific, meaningful values + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +position = :left + # Arrays # This is an array @@ -115,6 +127,33 @@ array.pop #=> [1, 2, 3, 4, 5, 6] # Note that push and pop do the opposite of each other # Shift and unshift are the same. +# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes are denoted with curly braces: +hash = {'color' => 'green', 'number' => 5} + +hash.keys #=> ['color', 'number'] + +# Hashes can be quickly looked up by key: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Asking a hash for a key that doesn't exist returns nil: +hash['nothing here'] #=> nil + +# Iterate over hashes with the #each method: +hash.each do |k, v| + puts "#{k} is #{v}" +end + +# Since Ruby 1.9, there's a special syntax when using symbols as keys: + +new_hash = { defcon: 3, action: true} + +new_hash.keys #=> [:defcon, :action] + +# Tip: Both Arrays and Hashes are Enumerable +# This means they share a lot of useful methods + # Control structures if true @@ -160,7 +199,7 @@ end grade = 'B' case grade when 'A' - puts "way to go kiddo" + puts "Way to go kiddo" when 'B' puts "Better luck next time" when 'C' @@ -198,5 +237,15 @@ sum sum(3,4), 5 #=> 12 # All methods have an implicit, optional block parameter # it can be called with the 'yield' keyword +def surround + puts "{" + yield + puts "}" +end +surround { puts 'hello world' } + +# { +# hello world +# } ``` \ No newline at end of file From 83900dc50427bddebae92545f82530e555fe6365 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Mon, 1 Jul 2013 10:32:42 -0700 Subject: [PATCH 052/110] Tighten up py doc a bit --- python.html.markdown | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index e3f04e19..90eaf1c9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -125,7 +125,7 @@ some_var #=> 5 some_other_var # Raises a name error # if can be used as an expression -"yahoo!" if 1 > 2 else 2 #=> "yahoo!" +"yahoo!" if 3 > 2 else 2 #=> "yahoo!" # Lists store sequences li = [] @@ -173,8 +173,6 @@ li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Examine the length with len len(li) #=> 6 -# Note: lists can contain arbitrary values -li2 = [1, "Hello", [[], "Hi", 5,]] # Tuples are like lists but are immutable. tup = (1, 2, 3) @@ -379,8 +377,6 @@ add_10(3) #=> 13 # There are also anonymous functions (lambda x: x > 2)(3) #=> True -rectangle_area = lambda a, b: a * b -print rectangle_area(3, 4) #=> 12 # There are built-in higher order functions map(add_10, [1,2,3]) #=> [11, 12, 13] @@ -390,9 +386,6 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] -# You can also use dictionary comprehensions -{i: add_10(i) for i in [1, 2, 3]} #=> {1: 11, 2: 12, 3: 13} - #################################################### ## 5. Classes #################################################### @@ -408,8 +401,7 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name - # An instance method. All methods take self as the first argument, - # which refers to the instance of this class + # An instance method. All methods take self as the first argument def say(self, msg): return "%s: %s" % (self.name, msg) @@ -480,7 +472,4 @@ Still up for more? Try: * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) - -Python has a huge amount of modules within the standard library. See the -[official documentation](http://docs.python.org/2/library/index.html) or -[Python Module of the Week](http://pymotw.com/2/) for more. +* [Python Module of the Week](http://pymotw.com/2/) From e5d2150714a7145e539245f305303aa39962df7c Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 11:03:36 -0700 Subject: [PATCH 053/110] Change name of java file to be a camelcase class name --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 206f9cbe..712233ba 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -6,7 +6,7 @@ author: Jake Prather author_url: http://github.com/JakeHP -filename: learnjava.java +filename: LearnJava.java --- @@ -24,9 +24,9 @@ import java.util.ArrayList; // Import all classes inside of java.lang package import java.security.*; -// Inside of the learnjava class, is your program's +// Inside of the LearnJava class, is your program's // starting point. The main method. -public class learnjava +public class LearnJava { //main method public static void main (String[] args) From 2995cd100529f95e497b56288035a5f5d252a412 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 14:45:59 -0400 Subject: [PATCH 054/110] draft of Julia entry based on Python entry; finish up to Tuples section. --- julia.html.markdown | 427 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 427 insertions(+) create mode 100644 julia.html.markdown diff --git a/julia.html.markdown b/julia.html.markdown new file mode 100644 index 00000000..ff2f2339 --- /dev/null +++ b/julia.html.markdown @@ -0,0 +1,427 @@ +--- +language: julia +author: Leah Hanson +author_url: http://leahhanson.us +--- + +Julia is a new homoiconic functional language focused on technical computing. +While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. + +This is based on the current development version of Julia, as of June 29th, 2013. + +```julia +# Single line comments start with a hash. + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# Everything in Julia is a expression. + +# You have numbers +3 #=> 3 (Int64) +3.2 #=> 3.2 (Float64) +2 + 1im #=> 2 + 1im (Complex{Int64}) +2//3 #=> 2//3 (Rational{Int64}) + +# Math is what you would expect +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7.0 +5 \ 35 #=> 7.0 +5 / 2 #=> 2.5 +div(5, 2) #=> 2 +2 ^ 2 #=> 4 +12 % 10 #=> 2 + +# Enforce precedence with parentheses +(1 + 3) * 2 #=> 8 + +# Bitwise Operators +~2 #=> -3 # bitwise not +3 & 5 #=> 1 # bitwise and +2 | 4 #=> 6 # bitwise or +2 $ 4 #=> 6 # bitwise xor +2 >>> 1 #=> 1 # logical shift right +2 >> 1 #=> 1 # arithmetic shift right +2 << 1 #=> 4 # logical/arithmetic shift left + +# You can use the bits function to see the binary representation of a number. +bits(2) #=> "0000000000000000000000000000000000000000000000000000000000000010" +bits(2.0) #=> "0100000000000000000000000000000000000000000000000000000000000000" + +# Boolean values are primitives +true +false + +# Boolean operators +!true #=> false +!false #=> true +1 == 1 #=> true +2 == 1 #=> false +1 != 1 #=> false +2 != 1 #=> true +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +# Comparisons can be chained +1 < 2 < 3 #=> true +2 < 3 < 2 #=> false + +# Strings are created with " +"This is a string." + +# Character literals written with ' +'a' + +# A string can be treated like a list of characters +"This is a string"[1] #=> 'T' # Julia indexes from 1 + +# $ can be used for string interpolation: +"2 + 2 = $(2+2)" # => "2 + 2 = 4" +# You can put any Julia expression inside the parenthesis. + +# Another way to format strings is the printf macro. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +#################################################### +## 2. Variables and Collections +#################################################### + +# Printing is pretty easy +println("I'm Julia. Nice to meet you!") + +# No need to declare variables before assigning to them. +some_var = 5 #=> 5 +some_var #=> 5 +# Accessing a previously unassigned variable is an error +some_other_var #=> ERROR: some_other_var not defined + +# Variable Names: +Some!Other1Var! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well. +☃ = 8 #=> 8 # You can also use unicode characters + +# A note on naming conventions in Julia: +# * Names of variables are in lower case, with word separation indicated by underscores ('\_'). +# * Names of Types begin with a capital letter and word separation is shown with CamelCase instead of underscores. +# * Names of functions and macros are in lower case, without underscores. +# * Functions that modify their inputs have names that end in !. These functions are sometimes called mutating functions or in-place functions. + + +# Arrays store sequences +li = Int64[] #=> 0-element Int64 Array +# 1-dimensional array literals can be written with comma-separated values. +other_li = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] +# 2-dimentional arrays use space-separated values and semicolon-separated rows. +matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] + +# Add stuff to the end of a list with push! and append! +push!(li,1) #=> [1] +push!(li,2) #=> [1,2] +push!(li,4) #=> [1,2,4] +push!(li,3) #=> [1,2,4,3] +append!(li,other_li) #=> [1,2,4,3,4,5,6] +# Remove from the end with pop +pop!(other_li) #=> 6 and other_li is now [4,5] +# Let's put it back +push!(other_li,6) # other_li is now [4,5,6] again. + +# Remember that Julia indexes from 1, not 0! +li[1] #=> 1 + +# Function names that end in exclamations points indicate that they modify their argument. +arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] +sort(arr) #=> [4,5,6]; arr is still [5,4,6] +sort!(arr) #=> [4,5,6]; arr is now [4,5,6] + +# Looking out of bounds is a BoundsError +li[0] # ERROR: BoundsError() in getindex at array.jl:270 +# Errors list the line and file they came from, even if it's in the standard library. +# If you built Julia from source, you can look in the folder base inside the julia folder to find these files. + +# You can initialize arrays from ranges +li = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] + +# You can look at ranges with slice syntax. +li[1:3] #=> [1, 2, 3] +# Omit the beginning +li[2:] #=> [2, 3, 4, 5] + +# Remove arbitrary elements from a list with splice! +splice!(li,2) #=> 2 ; li is now [1, 3, 4, 5] + +# Concatenate lists with append! +other_li = [1,2,3] +append!(li,other_li) # Now li is [1, 3, 4, 5, 1, 2, 3] + +# Check for existence in a list with contains +contains(li,1) #=> true + +# Examine the length with length +length(li) #=> 7 + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] #=> 1 +try: + tup[0] = 3 # Raises a TypeError +except TypeError: + print "Tuples cannot be mutated." + +# You can do all those list thingies on tuples too +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 into variables +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 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] #=> 1 + +# Get all keys as a list +filled_dict.keys() #=> ["three", "two", "one"] +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. + +# Get all values as a list +filled_dict.values() #=> [3, 2, 1] +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with in +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Trying to look up a non-existing key will raise a KeyError +filled_dict["four"] #=> KeyError + +# Use get method to avoid the KeyError +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 + +# Setdefault method is a safe way to add new key-value pair into dictionary +filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values +some_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) + +# Since Python 2.7, {} can be used to declare a set +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} + +# Add more items to a set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = set{3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Do set union with | +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{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 + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. INDENTATION IS SIGNIFICANT IN PYTHON! +# prints "some var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # This elif clause is optional. + print "some_var is smaller than 10." +else: # This is optional too. + print "some_var is indeed 10." + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use % to interpolate formatted strings + print "%s is a mammal" % animal + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block + +# Works on Python 2.6 and up: +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. + +# Works for Python 2.7 and down: +try: + raise IndexError("This is an index error") +except IndexError, e: # No "as", comma instead + pass + + +#################################################### +## 4. Functions +#################################################### + +# Use def to create new functions +def add(x, y): + print "x is %s and y is %s" % (x, y) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) #=> 11 and prints out "x is 5 and y is 6" +# Another way to call functions is with keyword arguments +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) + + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + [1, 2] + {"a": 3, "b": 4} +""" + +# You can also use * and ** when calling a function +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +foo(*args) # equivalent to foo(1, 2, 3, 4) +foo(**kwargs) # equivalent to foo(a=3, b=4) +foo(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) #=> True + +# 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] + +# We can use list comprehensions for nice maps and filters +[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): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # An instance method. All methods take self as the first argument + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantiate a class +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") #prints out "Joel: hello" + +# Call our class method +i.get_species() #=> "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Call the static method +Human.grunt() #=> "*grunt*" +``` + +## Further Reading + +Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) + From 0e0fed1e304e89ef16d449d9e2ffcc374a152071 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Mon, 1 Jul 2013 11:50:19 -0700 Subject: [PATCH 055/110] Fix typo --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 90eaf1c9..59a0b85c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -447,7 +447,7 @@ 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 floor3.7) #=> 3.0 +print floor(3.7) #=> 3.0 # You can import all functions from a module. # Warning: this is not recommended From 18c413f6f55b24d031a37590a85d4e602ac6bceb Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 16:21:56 -0400 Subject: [PATCH 056/110] edited tuples section --- julia.html.markdown | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index ff2f2339..b036b1dd 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -109,7 +109,6 @@ Some!Other1Var! = 6 #=> 6 # You can use uppercase letters, digits, and exclamati # * Names of functions and macros are in lower case, without underscores. # * Functions that modify their inputs have names that end in !. These functions are sometimes called mutating functions or in-place functions. - # Arrays store sequences li = Int64[] #=> 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. @@ -128,8 +127,8 @@ pop!(other_li) #=> 6 and other_li is now [4,5] # Let's put it back push!(other_li,6) # other_li is now [4,5,6] again. -# Remember that Julia indexes from 1, not 0! -li[1] #=> 1 +li[1] #=> 1 # remember that Julia indexes from 1, not 0! +li[end] #=> 6 # end is a shorthand for the last index; it can be used in any indexing expression. # Function names that end in exclamations points indicate that they modify their argument. arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] @@ -162,26 +161,22 @@ contains(li,1) #=> true # Examine the length with length length(li) #=> 7 -# Tuples are like lists but are immutable. -tup = (1, 2, 3) -tup[0] #=> 1 -try: - tup[0] = 3 # Raises a TypeError -except TypeError: - print "Tuples cannot be mutated." +# Tuples are immutable. +tup = (1, 2, 3) #=>(1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] #=> 1 +tup[0] = 3 # ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) -# You can do all those list thingies on tuples too -len(tup) #=> 3 -tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) -tup[:2] #=> (1, 2) -2 in tup #=> True +# Many list functions also work on tuples +length(tup) #=> 3 +tup[1:2] #=> (1,2) +contains(tup,2) #=> true # You can unpack tuples 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) #=> (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 +d, e, f = 4, 5, 6 #=> (4,5,6) # Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e #=> (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings From a333018593affb355c8d805f8e0792ff80955712 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 16:34:39 -0400 Subject: [PATCH 057/110] edited Dict section --- julia.html.markdown | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index b036b1dd..e60b4e52 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -180,43 +180,37 @@ e, d = d, e #=> (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings -empty_dict = {} +empty_dict = Dict() #=> Dict{Any,Any}() # Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] #=> ["one"=> 1, "two"=> 2, "three"=> 3] # Dict{ASCIIString,Int64} # Look up values with [] filled_dict["one"] #=> 1 -# Get all keys as a list -filled_dict.keys() #=> ["three", "two", "one"] +# Get all keys +keys(filled_dict) #=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. -# Get all values as a list -filled_dict.values() #=> [3, 2, 1] +# Get all values +values(d) #=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Same as above regarding key ordering. -# Check for existence of keys in a dictionary with in -"one" in filled_dict #=> True -1 in filled_dict #=> False +# Check for existence of keys in a dictionary with contains, haskey +contains(filled_dict,("one",1)) #=> true +contains(filled_dict,("two",3)) #=> false +haskey(filled_dict,"one") #=> true +haskey(filled_dict,1) #=> false -# Trying to look up a non-existing key will raise a KeyError -filled_dict["four"] #=> KeyError +# Trying to look up a non-existing key will raise an error +filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 -# Use get method to avoid the KeyError -filled_dict.get("one") #=> 1 -filled_dict.get("four") #=> None +# Use get method to avoid the error +# get(dictionary,key,default_value) +get(filled_dict,"one",4) #=> 1 +get(filled_dict,"four",4) #=> 4 -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) #=> 1 -filled_dict.get("four", 4) #=> 4 - -# Setdefault method is a safe way to add new key-value pair into dictionary -filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 - - -# Sets store ... well sets +# Sets store sets empty_set = set() # Initialize a set with a bunch of values some_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) From 2a2dae61ce885d57fc257b28c5c041076041cf9e Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 16:44:47 -0400 Subject: [PATCH 058/110] edited Set section --- julia.html.markdown | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index e60b4e52..b19250af 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -211,29 +211,22 @@ get(filled_dict,"one",4) #=> 1 get(filled_dict,"four",4) #=> 4 # Sets store sets -empty_set = set() +empty_set = Set() #=> Set{Any}() # Initialize a set with a bunch of values -some_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) - -# Since Python 2.7, {} can be used to declare a set -filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} +filled_set = Set(1,2,2,3,4) #=> Set{Int64}(1,2,3,4) # Add more items to a set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +add!(filled_set,5) #=> Set{Int64}(5,4,2,3,1) -# Do set intersection with & -other_set = set{3, 4, 5, 6} -filled_set & other_set #=> {3, 4, 5} +# There are functions for set intersection, union, and difference. +other_set = Set(3, 4, 5, 6) #=> Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) #=> Set{Int64}(3,4,5) +union(filled_set, other_set) #=> Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) #=> Set{Int64}(1,4) -# Do set union with | -filled_set | other_set #=> {1, 2, 3, 4, 5, 6} - -# Do set difference with - -{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 +# Check for existence in a set with contains +contains(filled_set,2) #=> true +contains(filled_set,10) #=> false #################################################### From 2627624bb495a0d5450e493b685a938c70eaa32d Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 16:59:53 -0400 Subject: [PATCH 059/110] edited control flow section --- julia.html.markdown | 84 ++++++++++++++++++++++++--------------------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index b19250af..12f52e6e 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -233,57 +233,63 @@ contains(filled_set,10) #=> false ## 3. Control Flow #################################################### -# Let's just make a variable +# Let's make a variable some_var = 5 -# Here is an if statement. INDENTATION IS SIGNIFICANT IN PYTHON! +# Here is an if statement. Indentation is NOT meaningful in Julia. # prints "some var is smaller than 10" -if some_var > 10: - print "some_var is totally bigger than 10." -elif some_var < 10: # This elif clause is optional. - print "some_var is smaller than 10." -else: # This is optional too. - print "some_var is indeed 10." +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # This elseif clause is optional. + println("some_var is smaller than 10.") +else # This is optional too. + println("some_var is indeed 10.") +end -""" -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal -""" -for animal in ["dog", "cat", "mouse"]: - # You can use % to interpolate formatted strings - print "%s is a mammal" % animal -""" -While loops go until a condition is no longer met. -prints: - 0 - 1 - 2 - 3 -""" +# For loops iterate over iterable things, such as ranges, lists, sets, dicts, strings. +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for animal=["dog", "cat", "mouse"] + # You can use $ to interpolate into strings + println("$animal is a mammal") +end + +# You can use in instead of =, if you want. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is $(a[2])") +end + + +# While loops go until a condition is no longer met. +# prints: +# 0 +# 1 +# 2 +# 3 x = 0 -while x < 4: - print x +while x < 4 + println(x) x += 1 # Shorthand for x = x + 1 +end # Handle exceptions with a try/except block -# Works on Python 2.6 and up: -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. +error("help") # ERROR: help in error at error.jl:21 -# Works for Python 2.7 and down: -try: - raise IndexError("This is an index error") -except IndexError, e: # No "as", comma instead - pass +try + error("my error!") +except + println("caught it!") +end #################################################### From 0f641aed5e7d52633f11443ff6d80ea0a8ee3fe1 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 17:03:05 -0400 Subject: [PATCH 060/110] fixed try/catch section --- julia.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 12f52e6e..5ba27efc 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -286,10 +286,11 @@ end error("help") # ERROR: help in error at error.jl:21 try - error("my error!") -except - println("caught it!") -end + error("help") +catch e + println("caught it $e") +end +#=> caught it ErrorException("help") #################################################### From 43129d86e1d94c7fec5806b37d1f5522992c25b8 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 17:39:42 -0400 Subject: [PATCH 061/110] small changes based on Stefan's feedback. --- julia.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 5ba27efc..f26694d7 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -32,7 +32,7 @@ This is based on the current development version of Julia, as of June 29th, 2013 5 \ 35 #=> 7.0 5 / 2 #=> 2.5 div(5, 2) #=> 2 -2 ^ 2 #=> 4 +2 ^ 2 #=> 4 # power, not bitwise xor 12 % 10 #=> 2 # Enforce precedence with parentheses @@ -100,7 +100,7 @@ some_var #=> 5 some_other_var #=> ERROR: some_other_var not defined # Variable Names: -Some!Other1Var! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well. +SomeOtherVar123! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well. ☃ = 8 #=> 8 # You can also use unicode characters # A note on naming conventions in Julia: @@ -149,7 +149,8 @@ li[1:3] #=> [1, 2, 3] li[2:] #=> [2, 3, 4, 5] # Remove arbitrary elements from a list with splice! -splice!(li,2) #=> 2 ; li is now [1, 3, 4, 5] +arr = [3,4,5] +splice!(arr,2) #=> 4 ; arr is now [3,5] # Concatenate lists with append! other_li = [1,2,3] From 34c86dc9583b43935e6fe292fbd3aaa69c4ef048 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 14:50:59 -0700 Subject: [PATCH 062/110] Updated clojure doc --- clojure.html.markdown | 91 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 77 insertions(+), 14 deletions(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index cb202a92..39a27bcf 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -2,7 +2,7 @@ language: clojure author: Adam Bard author_url: http://adambard.com/ -filename: test.clj +filename: learnclojure.clj --- Clojure is a Lisp family language developed for the Java Virtual Machine. It has @@ -24,9 +24,9 @@ and often automatically. ; ; The clojure reader assumes that the first thing is a ; function or macro to call, and the rest are arguments. -; -; Here's a function that sets the current namespace: -(ns test) + +; The first call in a file should be ns, to set the namespace +(ns learnclojure) ; More basic examples: @@ -71,6 +71,7 @@ and often automatically. ; Collections & Sequences ;;;;;;;;;;;;;;;;;;; +; Lists are linked-list data structures, while Vectors are array-backed. ; Vectors and Lists are java classes too! (class [1 2 3]); => clojure.lang.PersistentVector (class '(1 2 3)); => clojure.lang.PersistentList @@ -79,16 +80,18 @@ and often automatically. ; it to stop the reader thinking it's a function. ; Also, (list 1 2 3) is the same as '(1 2 3) +; "Collections" are just groups of data ; Both lists and vectors are collections: (coll? '(1 2 3)) ; => true (coll? [1 2 3]) ; => true +; "Sequences" (seqs) are abstract descriptions of lists of data. ; Only lists are seqs. (seq? '(1 2 3)) ; => true (seq? [1 2 3]) ; => false -; Seqs are an interface for logical lists, which can be lazy. -; "Lazy" means that a seq can define an infinite series, like so: +; A seq need only provide an entry when it is accessed. +; So, seqs which can be lazy -- they can define infinite series: (range 4) ; => (0 1 2 3) (range) ; => (0 1 2 3 4 ...) (an infinite series) (take 4 (range)) ; (0 1 2 3) @@ -97,8 +100,8 @@ and often automatically. (cons 4 [1 2 3]) ; => (4 1 2 3) (cons 4 '(1 2 3)) ; => (4 1 2 3) -; Use conj to add an item to the beginning of a list, -; or the end of a vector +; Conj will add an item to a collection in the most efficient way. +; For lists, they insert at the beginning. For vectors, they insert at the end. (conj [1 2 3] 4) ; => [1 2 3 4] (conj '(1 2 3) 4) ; => (4 1 2 3) @@ -168,20 +171,26 @@ x ; => 1 ; => "Hello Finn, you passed 3 extra args" -; Hashmaps +; Maps ;;;;;;;;;; +; Hash maps and array maps share an interface. Hash maps have faster lookups +; but don't retain key order. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap +; Arraymaps will automatically become hashmaps through most operations +; if they get big enough, so you don't need to worry. + +; Maps can use any hashable type as a key, but usually keywords are best ; Keywords are like strings with some efficiency bonuses (class :a) ; => clojure.lang.Keyword -; Maps can use any type as a key, but usually keywords are best -(def stringmap (hash-map "a" 1, "b" 2, "c" 3)) +(def stringmap {"a" 1, "b" 2, "c" 3}) stringmap ; => {"a" 1, "b" 2, "c" 3} -(def keymap (hash-map :a 1 :b 2 :c 3)) -keymap ; => {:a 1, :c 3, :b 2} (order is not guaranteed) +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} ; By the way, commas are always treated as whitespace and do nothing. @@ -200,7 +209,8 @@ keymap ; => {:a 1, :c 3, :b 2} (order is not guaranteed) (stringmap "d") ; => nil ; Use assoc to add new keys to hash-maps -(assoc keymap :d 4) ; => {:a 1, :b 2, :c 3, :d 4} +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} ; But remember, clojure types are immutable! keymap ; => {:a 1, :b 2, :c 3} @@ -271,6 +281,7 @@ keymap ; => {:a 1, :b 2, :c 3} (require 'clojure.string) ; Use / to call functions from a module +; Here, the module is clojure.string and the function is blank? (clojure.string/blank? "") ; => true ; You can give a module a shorter name on import @@ -314,4 +325,56 @@ keymap ; => {:a 1, :b 2, :c 3} (doto (Calendar/getInstance) (.set 2000 1 1 0 0 0) .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory is the mechanism clojure uses to handle +; persistent state. There are a few constructs in clojure that use this. + +; An atom is the simplest. Pass it an initial value +(def my-atom (atom {})) + +; Update an atom with swap!. +; swap! takes a function and calls it with the current value of the atom +; as the first argument, and any trailing arguments as the second +(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2) + + ; Use '@' to dereference the atom and get the value +my-atom ;=> Atom<#...> (Returns the Atom object) +@my-atom ; => {:a 1 :b 2} + +; Here's a simple counter using an atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Other STM constructs are refs and agents. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents ``` + +### Further Reading + +This is far from exhaustive, but hopefully it's enought o get you on your feet. + +Clojure.org has lots of articles: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org has documentation with examples for most core functions: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure is a great way to build your clojure/FP skills: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org (yeah, really) has a number of getting started articles: +[http://clojure-doc.org/](http://clojure-doc.org/) From 3ebd8c55fd018aec6381ef69cca9c9f55f0e4796 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 17:58:25 -0400 Subject: [PATCH 063/110] edited functions through keyword args --- julia.html.markdown | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index f26694d7..c6e54f70 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -298,31 +298,45 @@ end ## 4. Functions #################################################### -# Use def to create new functions -def add(x, y): - print "x is %s and y is %s" % (x, y) - return x + y # Return values with a return statement +# Use the keyword function to create new functions +function add(x, y) + println("x is $x and y is $y") + x + y # or equivalently: return x + y +end -# Calling functions with parameters add(5, 6) #=> 11 and prints out "x is 5 and y is 6" -# Another way to call functions is with keyword arguments -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): +function varargs(args...) return args +end varargs(1, 2, 3) #=> (1,2,3) +# You can define functions with optional positional arguments +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs +defaults('h','g') #=> "h g and 5 6" +defaults('h','g','j') #=> "h g and j 6" +defaults('h','g','j','k') #=> "h g and j k" +defaults('h') #=> ERROR: no method defaults(Char,) +defaults() #=> ERROR: no methods defaults() -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} +# You can define functions that take keyword arguments +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] +keyword_args() #=> ["name2"=>"hello","k2"=>4] + +#### +#### In progress point +#### # You can do both at once, if you like def all_the_args(*args, **kwargs): From 7b21a8ae1bdd909b9923290f588ffae17ea960a5 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Mon, 1 Jul 2013 18:00:13 -0400 Subject: [PATCH 064/110] added another dictionary-for-loop example --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index c6e54f70..222a490a 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -269,6 +269,10 @@ for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] println("$(a[1]) is $(a[2])") end +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is $v") +end + # While loops go until a condition is no longer met. # prints: From b58a7d9d23220cf1671e592c113d510f7e0df3aa Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 15:50:18 -0700 Subject: [PATCH 065/110] Updated java --- java.html.markdown | 583 +++++++++++++++++++++++---------------------- 1 file changed, 298 insertions(+), 285 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 712233ba..729ff531 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -24,311 +24,324 @@ import java.util.ArrayList; // Import all classes inside of java.lang package import java.security.*; -// Inside of the LearnJava class, is your program's -// starting point. The main method. -public class LearnJava -{ - //main method - public static void main (String[] args) - { - -System.out.println("->Printing"); -// Printing, and forcing a new line on next print, use println() -System.out.println("Hello World!"); -System.out.println("Integer: "+10+" Double: "+3.14+ " Boolean: "+true); -// Printing, without forcing a new line on next print, use print() -System.out.print("Hello World - "); -System.out.print("Integer: "+10+" Double: "+3.14+ " Boolean: "+true); +// Each .java file contains one public class, with the same name as the file. +public class LearnJava { -/////////////////////////////////////// -// Types -/////////////////////////////////////// -System.out.println("\n\n->Types"); -// Byte - 8-bit signed two's complement integer -// (-128 <= byte <= 127) -byte fooByte = 100; + // A program must have a main method as an entry point + public static void main (String[] args) { -// Short - 16-bit signed two's complement integer -// (-32,768 <= short <= 32,767) -short fooShort = 10000; + // Use System.out.println to print lines + System.out.println("Hello World!"); + System.out.println("Integer: " + 10 + " Double: " + 3.14 + " Boolean: " + true); -// Integer - 32-bit signed two's complement integer -// (-2,147,483,648 <= int <= 2,147,483,647) -int fooInt = 1; - -// Long - 64-bit signed two's complement integer -// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) -long fooLong = 100000L; - -// (Java has no unsigned types) - -// Float - Single-precision 32-bit IEEE 754 Floating Point -float fooFloat = 234.5f; - -// Double - Double-precision 64-bit IEEE 754 Floating Point -double fooDouble = 123.4; - -// Boolean - True & False -boolean fooBoolean = true; -boolean barBoolean = false; - -// Char - A single 16-bit Unicode character -char fooChar = 'A'; - -// Make a variable a constant -final int HOURS_I_WORK_PER_WEEK = 9001; - -// Strings -String fooString = "My String Is Here!"; -// \n is an escaped character that starts a new line -String barString = "Printing on a new line?\nNo Problem!"; -System.out.println(fooString); -System.out.println(barString); - -// Arrays -//The array size must be decided upon declaration -//The format for declaring an array is follows: -// [] = new []; -int [] intArray = new int[10]; -String [] stringArray = new String[1]; -boolean [] booleanArray = new boolean[100]; - -// Another way to declare & initialize an array -int [] y = {9000, 1000, 1337}; - -// Indexing an array - Accessing an element -System.out.println("intArray @ 0: "+intArray[0]); - -// Arrays are mutable; it's just memory! -intArray[1] = 1; -System.out.println("intArray @ 1: "+intArray[1]); // => 1 -intArray[1] = 2; -System.out.println("intArray @ 1: "+intArray[1]); // => 2 - -// Others to check out -// ArrayLists - Like arrays except more functionality is offered, -// and the size is mutable -// LinkedLists -// Maps -// HashMaps - -/////////////////////////////////////// -// Operators -/////////////////////////////////////// -System.out.println("\n->Operators"); - -int i1 = 1, i2 = 2; // Shorthand for multiple declarations - -// Arithmetic is straightforward -System.out.println("1+2 = "+(i1 + i2)); // => 3 -System.out.println("2-1 = "+(i2 - i1)); // => 1 -System.out.println("2*1 = "+(i2 * i1)); // => 2 -System.out.println("1/2 = "+(i1 / i2)); // => 0 (0.5, but truncated towards 0) - -// Modulo -System.out.println("11%3 = "+(11 % 3)); // => 2 - -// Comparison operators -System.out.println("3 == 2? "+(3 == 2)); // => 0 (false) -System.out.println("3 != 2? "+(3 != 2)); // => 1 (true) -System.out.println("3 > 2? "+(3 > 2)); // => 1 -System.out.println("3 < 2? "+(3 < 2)); // => 0 -System.out.println("2 <= 2? "+(2 <= 2)); // => 1 -System.out.println("2 >= 2? "+(2 >= 2)); // => 1 - -// Bitwise operators! -/* -~ Unary bitwise complement -<< Signed left shift ->> Signed right shift ->>> Unsigned right shift -& Bitwise AND -^ Bitwise exclusive OR -| Bitwise inclusive OR -*/ - -// Incrementations -int i=0; -System.out.println("\n->Inc/Dec-rementation"); -System.out.println(i++); //i = 1. Post-Incrementation -System.out.println(++i); //i = 2. Pre-Incrementation -System.out.println(i--); //i = 1. Post-Decrementation -System.out.println(--i); //i = 0. Pre-Decrementation - -/////////////////////////////////////// -// Control Structures -/////////////////////////////////////// -System.out.println("\n->Control Structures"); -if (false){ - System.out.println("I never run"); -}else if (false) { - System.out.println("I am also never run"); -} else { - System.out.println("I print"); -} - -// While loop -int fooWhile = 0; -while(fooWhile < 100) -{ - //System.out.println(fooWhile); - //Increment the counter - //Iterated 99 times, fooWhile 0->99 - fooWhile++; -} -System.out.println("fooWhile Value: "+fooWhile); - -// Do While Loop -int fooDoWhile = 0; -do -{ - //System.out.println(fooDoWhile); - //Increment the counter - //Iterated 99 times, fooDoWhile 0->99 - fooDoWhile++; -}while(fooDoWhile < 100); -System.out.println("fooDoWhile Value: "+fooDoWhile); - -// For Loop -int fooFor; -//for loop structure => for(;;) -for(fooFor=0;fooFor<100;fooFor++){ - //System.out.println(fooFor); - //Iterated 99 times, fooFor 0->99 -} -System.out.println("fooFor Value: "+fooFor); - -// Switch Case -int month = 8; -String monthString; -switch (month){ - case 1: monthString = "January"; - break; - case 2: monthString = "February"; - break; - case 3: monthString = "March"; - break; - case 4: monthString = "April"; - break; - case 5: monthString = "May"; - break; - case 6: monthString = "June"; - break; - case 7: monthString = "July"; - break; - case 8: monthString = "August"; - break; - case 9: monthString = "September"; - break; - case 10: monthString = "October"; - break; - case 11: monthString = "November"; - break; - case 12: monthString = "December"; - break; - default: monthString = "Invalid month"; - break; -} -System.out.println("Switch Case Result: "+monthString); - -/////////////////////////////////////// -// Converting Data Types And Typcasting -/////////////////////////////////////// - -// Converting data - -// Convert String To Integer -Integer.parseInt("123");//returns an integer version of "123" - -// Convert Integer To String -Integer.toString(123);//returns a string version of 123 - -// For other conversions check out the following classes: -// Double -// Long -// String - -// Typecasting -// You can also cast java objects, there's a lot of details and -// deals with some more intermediate concepts. -// Feel free to check it out here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + // To print without a newline, use System.out.print + System.out.print("Hello "); + System.out.print("World"); -/////////////////////////////////////// -// Classes And Functions -/////////////////////////////////////// + /////////////////////////////////////// + // Types & Variables + /////////////////////////////////////// - // Read about the class, and function syntax before - // reading this. - System.out.println("\n->Classes & Functions"); - // Call bicycle's constructor - Bicycle trek = new Bicycle(); - // Manipulate your object - trek.speedUp(3); - trek.setCadence(100); - System.out.println("trek info: "+trek.toString()); + // Declare a variable using [ + // Byte - 8-bit signed two's complement integer + // (-128 <= byte <= 127) + byte fooByte = 100; - // Classes Syntax: - // class { - // //data fields, constructors, functions all inside - // } - // Function Syntax: - // () - // Here is a quick rundown on access level modifiers (public, private, etc.) - // http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html + // Short - 16-bit signed two's complement integer + // (-32,768 <= short <= 32,767) + short fooShort = 10000; -// This bracket ends the main method -} - // The static field is only required because this class - // is nested inside of the learnjava.java class. - public static class Bicycle { + // Integer - 32-bit signed two's complement integer + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; - // Bicycle's Fields/Variables - public int cadence; - public int gear; - public int speed; + // Long - 64-bit signed two's complement integer + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle(){ - gear = 1; - cadence = 50; - speed = 5; + // (Java has no unsigned types) + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; + + // Boolean - true & false + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Use final to make a variable immutable + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Strings + String fooString = "My String Is Here!"; + + // \n is an escaped character that starts a new line + String barString = "Printing on a new line?\nNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + + // Arrays + //The array size must be decided upon declaration + //The format for declaring an array is follows: + // [] = new []; + int [] intArray = new int[10]; + String [] stringArray = new String[1]; + boolean [] booleanArray = new boolean[100]; + + // Another way to declare & initialize an array + int [] y = {9000, 1000, 1337}; + + // Indexing an array - Accessing an element + System.out.println("intArray @ 0: " + intArray[0]); + + // Arrays are zero-indexed and mutable. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Others to check out + // ArrayLists - Like arrays except more functionality is offered, + // and the size is mutable + // LinkedLists + // Maps + // HashMaps + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5, but truncated towards 0) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Comparison operators + System.out.println("3 == 2? " + (3 == 2)); // => 0 (false) + System.out.println("3 != 2? " + (3 != 2)); // => 1 (true) + System.out.println("3 > 2? " + (3 > 2)); // => 1 + System.out.println("3 < 2? " + (3 < 2)); // => 0 + System.out.println("2 <= 2? " + (2 <= 2)); // => 1 + System.out.println("2 >= 2? " + (2 >= 2)); // => 1 + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i=0; + System.out.println("\n->Inc/Dec-rementation"); + System.out.println(i++); //i = 1. Post-Incrementation + System.out.println(++i); //i = 2. Pre-Incrementation + System.out.println(i--); //i = 1. Post-Decrementation + System.out.println(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // If statements are c-like + if (false){ + System.out.println("I never run"); + }else if (false) { + System.out.println("I am also never run"); + } else { + System.out.println("I print"); } - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear) { - gear = startGear; - cadence = startCadence; - speed = startSpeed; + // While loop + int fooWhile = 0; + while(fooWhile < 100) + { + //System.out.println(fooWhile); + //Increment the counter + //Iterated 99 times, fooWhile 0->99 + fooWhile++; } + System.out.println("fooWhile Value: " + fooWhile); - // the Bicycle class has - // four functions/methods - public void setCadence(int newValue) { - cadence = newValue; - } + // Do While Loop + int fooDoWhile = 0; + do + { + //System.out.println(fooDoWhile); + //Increment the counter + //Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + }while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); - public void setGear(int newValue) { - gear = newValue; + // For Loop + int fooFor; + //for loop structure => for(; ; ) + for(fooFor=0; fooFor<10; fooFor++){ + //System.out.println(fooFor); + //Iterated 10 times, fooFor 0->9 } + System.out.println("fooFor Value: " + fooFor); - public void applyBrake(int decrement) { - speed -= decrement; + // Switch Case + int month = 3; + String monthString; + switch (month){ + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + default: monthString = "Some other month"; + break; } + System.out.println("Switch Case Result: " + monthString); - public void speedUp(int increment) { - speed += increment; - } - - public String toString(){ - return "gear: "+Integer.toString(gear)+ - " cadence: "+Integer.toString(cadence)+ - " speed: "+Integer.toString(speed); - } - // bracket to close nested Bicycle class + + /////////////////////////////////////// + // Converting Data Types And Typcasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + Integer.parseInt("123");//returns an integer version of "123" + + // Convert Integer To String + Integer.toString(123);//returns a string version of 123 + + // For other conversions check out the following classes: + // Double + // Long + // String + + // Typecasting + // You can also cast java objects, there's a lot of details and + // deals with some more intermediate concepts. + // Feel free to check it out here: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); + trek.setCadence(100); + + // toString is a convention + System.out.println("trek info: " + trek.toString()); + + } // End main method +} // End LearnJava class + + +// You can include other, non-public classes in a .java file + + +// Class Declaration Syntax: +// class { +// //data fields, constructors, functions all inside +// } + +class Bicycle { + + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int speed; // Private: Only accessable from within the class + protected int gear; // Protected: Accessible from the class and subclasses + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() { + gear = 1; + cadence = 50; + speed = 5; } -// bracket to close learnjava.java + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } + + // Function Syntax: + // () + + // Java classes often implement getters and setters for their fields + + // Method declaration syntax: + // () + public int getCadence() { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public String toString() { + return "gear: "+Integer.toString(gear)+ + " cadence: "+Integer.toString(cadence)+ + " speed: "+Integer.toString(speed); + } +} // end class Bicycle + +// Use `extends` to extend a class +class PennyFarthing extends Bicycle { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Call the parent constructor with super + super(startCadence, startSpeed, 0); + } + + // You should mark a method you're overriding with an @annotation + @Override + public void setGear(int gear) { + gear = 0; + } + } ``` From bd7390d7990afc452cb72a720885c49afb617d79 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 15:51:55 -0700 Subject: [PATCH 066/110] Fixes for line length --- java.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 729ff531..ab69d4b4 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -32,7 +32,10 @@ public class LearnJava { // Use System.out.println to print lines System.out.println("Hello World!"); - System.out.println("Integer: " + 10 + " Double: " + 3.14 + " Boolean: " + true); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); // To print without a newline, use System.out.print System.out.print("Hello "); @@ -122,7 +125,7 @@ public class LearnJava { System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5, but truncated towards 0) + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 From d22f6fc28740495f3923a5d8839fede03b2be0df Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 18:08:48 -0500 Subject: [PATCH 067/110] typo --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index ab69d4b4..f4ab4220 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -21,7 +21,7 @@ Multi-line comments look like this. // Import ArrayList class inside of the java.util package import java.util.ArrayList; -// Import all classes inside of java.lang package +// Import all classes inside of java.security package import java.security.*; // Each .java file contains one public class, with the same name as the file. From b751e00faa8480c5dbb2f9155e362fbff02c4b82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Ricardo?= Date: Mon, 1 Jul 2013 22:34:40 -0300 Subject: [PATCH 068/110] Fixing list initialization in the R example. --- r.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index 38317776..3f681c88 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -243,7 +243,8 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) # Finally, R has lists (of vectors) -list1 <- list(time = 1:40, price = c(rnorm(40,.5*list1$time,4))) # random +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random list1 # You can get items in the list like so From 442652961d653db32db734be186d0a9bf3659e34 Mon Sep 17 00:00:00 2001 From: e99n09 Date: Mon, 1 Jul 2013 22:00:22 -0400 Subject: [PATCH 069/110] Update r.html.markdown Fixed the mistake about integers that yuhui brought up. Deleted the confusing suggestion about command-enter (doesn't work for all GUIs or on Windows). Added some more information about vectors. Added some information about conditional clauses. Included some information at the very end on where to get R and R GUIs --- r.html.markdown | 75 ++++++++++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 29 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index ad2a4559..e19eaeb8 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -5,7 +5,7 @@ author_url: http://github.com/e99n09 --- -R is a statistical computing language. +R is a statistical computing language. It has lots of good built-in functions for uploading and cleaning data sets, running common statistical tests, and making graphs. You can also easily compile it within a LaTeX document. ```r @@ -14,36 +14,28 @@ R is a statistical computing language. # You can't make a multi-line comment per se, # but you can stack multiple comments like so. -# Protip: hit COMMAND-ENTER to execute a line - ################################################################################### # The absolute basics ################################################################################### -# NUMERICS +# NUMBERS -# We've got numbers! Behold the "numeric" class +# We've got doubles! Behold the "numeric" class 5 # => [1] 5 class(5) # => [1] "numeric" +# We've also got integers! They look suspiciously similar, +# but indeed are different +5L # => [1] 5 +class(5L) # => [1] "integer" # Try ?class for more information on the class() function # In fact, you can look up the documentation on just about anything with ? -# Numerics are like doubles. There's no such thing as integers -5 == 5.0 # => [1] TRUE -# Because R doesn't distinguish between integers and doubles, -# R shows the "integer" form instead of the equivalent "double" form -# whenever it's convenient: -5.0 # => [1] 5 - # All the normal operations! 10 + 66 # => [1] 76 53.2 - 4 # => [1] 49.2 -3.37 * 5.4 # => [1] 18.198 2 * 2.0 # => [1] 4 -3 / 4 # => [1] 0.75 -2.0 / 2 # => [1] 1 +3L / 4 # => [1] 0.75 3 %% 2 # => [1] 1 -4 %% 2 # => [1] 0 # Finally, we've got not-a-numbers! They're numerics too class(NaN) # => [1] "numeric" @@ -107,6 +99,17 @@ while (a > 4) { # Operations on entire vectors (i.e. a whole row, a whole column) # or apply()-type functions (we'll discuss later) are preferred +# IF/ELSE + +# Again, pretty standard +if (4 > 3) { + print("Huzzah! It worked!") +} else { + print("Noooo! This is blatantly illogical!") +} +# => +# [1] "Huzzah! It worked!" + # FUNCTIONS # Defined like so: @@ -126,8 +129,8 @@ myFunc(5) # => [1] 19 # ONE-DIMENSIONAL # You can vectorize anything, so long as all components have the same type -vec <- c(4, 5, 6, 7) -vec # => [1] 4 5 6 7 +vec <- c(8, 9, 10, 11) +vec # => [1] 8 9 10 11 # The class of a vector is the class of its components class(vec) # => [1] "numeric" # If you vectorize items of different classes, weird coersions happen @@ -135,15 +138,27 @@ c(TRUE, 4) # => [1] 1 4 c("dog", TRUE, 4) # => [1] "dog" "TRUE" "4" # We ask for specific components like so (R starts counting from 1) -vec[1] # => [1] 4 -# We can also search for the indices of specific components -which(vec %% 2 == 0) +vec[1] # => [1] 8 +# We can also search for the indices of specific components, +which(vec %% 2 == 0) # => [1] 1 3 +# or grab just the first or last entry in the vector +head(vec, 1) # => [1] 8 +tail(vec, 1) # => [1] 11 # If an index "goes over" you'll get NA: vec[6] # => [1] NA +# You can find the length of your vector with length() +length(vec) # => [1] 4 # You can perform operations on entire vectors or subsets of vectors vec * 4 # => [1] 16 20 24 28 vec[2:3] * 5 # => [1] 25 30 +# and there are many built-in functions to summarize vectors +mean(vec) # => [1] 9.5 +var(vec) # => [1] 1.666667 +sd(vec) # => [1] 1.290994 +max(vec) # => [1] 11 +min(vec) # => [1] 8 +sum(vec) # => [1] 38 # TWO-DIMENSIONAL (ALL ONE CLASS) @@ -192,7 +207,7 @@ mat3 # [,1] [,2] [,3] [,4] # [1,] 1 2 4 5 # [2,] 6 7 0 4 -# Aah, everything of the same class. No coersions. Much better. +# Aah, everything of the same class. No coercions. Much better. # TWO-DIMENSIONAL (DIFFERENT CLASSES) @@ -273,7 +288,6 @@ apply(mat, MAR = 2, myFunc) # [2,] 7 19 # [3,] 11 23 # Other functions: ?lapply, ?sapply -# Don't feel too intimiated; everyone agrees they are rather confusing # The plyr package aims to replace (and improve upon!) the *apply() family. @@ -298,18 +312,18 @@ write.csv(pets, "pets2.csv") # to make a new .csv file in the working directory # Try ?read.csv and ?write.csv for more information ################################################################################### -# Plots +# Plots and tests ################################################################################### # Scatterplots! plot(list1$time, list1$price, main = "fake data") -# Fit a linear model -myLm <- lm(price ~ time, data = list1) -myLm # outputs result of regression +# Regressions! +linearModel <- lm(price ~ time, data = list1) +linearModel # outputs result of regression # Plot regression line on existing plot -abline(myLm, col = "red") +abline(linearModel, col = "red") # Get a variety of nice diagnostics -plot(myLm) +plot(linearModel) # Histograms! hist(rpois(n = 10000, lambda = 5), col = "thistle") @@ -325,4 +339,7 @@ require(ggplot2) ``` +## How do I get R? +* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) is another GUI From a2e2e202f4d91a97ba81c7437958586b69ceb56e Mon Sep 17 00:00:00 2001 From: Sonia Hamilton Date: Tue, 2 Jul 2013 20:06:22 +1000 Subject: [PATCH 070/110] Java - clarify extends --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index f4ab4220..8ba48d73 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -329,7 +329,7 @@ class Bicycle { } } // end class Bicycle -// Use `extends` to extend a class +// PennyFarthing is a subclass of Bicycle class PennyFarthing extends Bicycle { // (Penny Farthings are those bicycles with the big front wheel. // They have no gears.) From a86c8fe2c959b4ada383c748e4aae1525b8bf7c3 Mon Sep 17 00:00:00 2001 From: mrshankly Date: Tue, 2 Jul 2013 12:07:34 +0100 Subject: [PATCH 071/110] Added first draft for elixir. --- elixir.html.markdown | 204 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 elixir.html.markdown diff --git a/elixir.html.markdown b/elixir.html.markdown new file mode 100644 index 00000000..9343a683 --- /dev/null +++ b/elixir.html.markdown @@ -0,0 +1,204 @@ +--- +language: elixir +author: Joao Marques +author_url: http://github.com/mrshankly +filename: learnelixir.ex +--- + +```elixir +# Single line comments start with a hash. + +## -------------------- +## -- Basic types +## -------------------- + +# There are numbers +3 # integer +0x1F # integer +3.0 # float + +# Atoms, that are literals, a constant with name. They start with `:`. +:hello # atom + +# Tuples that are stored contigously in memory. +{1,2,3} # tuple + +# We can access a tuple element with the `elem` function: +elem({1, 2, 3}, 0) # => 1 + +# Lists that are implemented as linked lists. +[1,2,3] # list + +# We can access the head and tail of a list as follows: +[head | tail] = [1,2,3] +head # => 1 +tail # => [2,3] + +# In elixir, just like in erlang, the `=` denotes pattern matching and +# not an assignment. +# +# This means that the left-hand side (pattern) is matched against a +# right-hand side. +# +# This is how the above example of accessing the head and tail of a list works. + +# A pattern match will error when the sides don't match, in this example +# the tuples have different sizes. +{a, b, c} = {1, 2} # => ** (MatchError) no match of right hand side value: {1,2} + +# There's also binaries +<<1,2,3>> # binary + +# Strings and char lists +"hello" # string +'hello' # char list + +# Strings are all encoded in UTF-8: +"héllò" # => "héllò" + +# Strings are really just binaries, and char lists are just lists. +<> # => "abc" +[?a, ?b, ?c] # => 'abc' + +# `?a` in elixir returns the ASCII integer for the letter `a` +?a # => 97 + +## TODO: +###################################################### +## JOIN BINARIES AND LISTS +###################################################### + +## -------------------- +## -- Operators +## -------------------- + +# Some math +1 + 1 # => 2 +10 - 5 # => 5 +5 * 2 # => 10 +10 / 2 # => 5.0 + +# In elixir the operator `/` always returns a float. + +# To do integer division use `div` +div(10, 2) # => 5 + +# To get the division remainder use `rem` +rem(10, 3) # => 1 + +# There's also boolean operators: `or`, `and` and `not`. +# These operators expect a boolean as their first argument. +true and true # => true +false or true # => true +1 and true # => ** (ArgumentError) argument error + +# Elixir also provides `||`, `&&` and `!` which accept arguments of any type. +# All values except `false` and `nil` will evaluate to true. +1 || true # => 1 +false && 1 # => false +nil && 20 # => nil + +!true # => false + +# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` +1 == 1 # => true +1 != 1 # => false +1 < 2 # => true + +# `===` and `!==` are more strict when comparing integers and floats: +1 == 1.0 # => true +1 === 1.0 # => false + +# We can also compare two different data types: +1 < :hello # => true + +# The overall sorting order is defined below: +number < atom < reference < functions < port < pid < tuple < list < bit string + +# To quote Joe Armstrong on this: "The actual order is not important, +# but that a total ordering is well defined is important." + +## -------------------- +## -- Control Flow +## -------------------- + +# `if` expression +if false do + "This will never be seen" +else + "This will" +end + +# There's also `unless` +unless true do + "This will never be seen" +else + "This will" +end + +# Remember pattern matching? Many control-flow structures in elixir rely on it. + +# `case` allows us to compare a value against many patterns: +case {:one, :two} do + {:four, :five} -> + "This won't match" + {:one, x} -> + "This will match and assign `x` to `:two`" + _ -> + "This will match any value" +end + +# It's common practive to assign a value to `_` if we don't need it. +# For example, if only the head of a list matters to us: +[head | _] = [1,2,3] +head # => 1 + +# For better readability we can do the following: +[head | _tail] = [:a, :b, :c] +head # => :a + +# `cond` lets us check for many conditions at the same time. +# Use `cond` instead of nesting many `if` expressions. +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + 1 + 2 == 3 -> + "But I will" +end + +# It is common to see a last condition equal to `true`, which will always match. +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + true -> + "But I will (this is essentially an else)" +end + +# `try/catch` is used to catch values that are thrown, it also supports an +# `after` clause that is invoked whether or not a value is catched. +try do + throw(:hello) +catch + message -> "Got #{message}." +after + IO.puts("I'm the after clause.") +end +# => I'm the after clause +# "Got :hello" + +## TODO: +###################################################### +## GUARDS +###################################################### + +## --------------------------- +## -- Modules and Functions +## --------------------------- + + + +``` \ No newline at end of file From f68a80312b4bf56fd14b5f03d4644688d26710a0 Mon Sep 17 00:00:00 2001 From: mrshankly Date: Tue, 2 Jul 2013 13:16:12 +0100 Subject: [PATCH 072/110] Added section about functions, modules and records. --- elixir.html.markdown | 116 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 111 insertions(+), 5 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 9343a683..a37d0f5e 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -68,9 +68,9 @@ tail # => [2,3] ## JOIN BINARIES AND LISTS ###################################################### -## -------------------- +## --------------------------- ## -- Operators -## -------------------- +## --------------------------- # Some math 1 + 1 # => 2 @@ -118,9 +118,9 @@ number < atom < reference < functions < port < pid < tuple < list < bit string # To quote Joe Armstrong on this: "The actual order is not important, # but that a total ordering is well defined is important." -## -------------------- +## --------------------------- ## -- Control Flow -## -------------------- +## --------------------------- # `if` expression if false do @@ -199,6 +199,112 @@ end ## -- Modules and Functions ## --------------------------- +############################### +## EXPLAIN built-in functions? +############################### +# Anonymous functions (notice the dot) +square = fn(x) -> x * x end +square.(5) #=> 25 -``` \ No newline at end of file +# They also accept many clauses and guards +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# You can group several functions into a module. Inside a module use `def` +# to define your functions. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Match.square(3) #=> 9 + +# To compile our little Math module save it as `math.ex` and use `elixirc` +elixirc math.ex + +# Inside a module we can define functions with `def` and +# private functions with `defp`. +# +# A function defined with `def` is available to be invoked from other modules, +# a private function can only be invoked locally. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Function declarations also support guards and multiple clauses: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when r > 0 do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 + +# Due to immutability, recursion is a big part of elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +############################### +## EXPLAIN module attributes +############################### + +## --------------------------- +## -- Records and Exceptions +## --------------------------- + +# Records are basically structures that allow you to associate a name with +# a particular value. +defrecord Person, name: nil, age: 0, height: 0 + +joe_info = Person.new(name: "Joe", age: 30, height: 180) +#=> Person[name: "Joe", age: 30, height: 180] + +# Access the value of name +joe_info.name #=> "Joe" + +# Update the value of age +joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] + +## TODO: Exceptions + +## --------------------------- +## -- Concurrency +## --------------------------- + +## TODO +``` From b642fcb3097bdaa4117bccab23088654f0ce4c76 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Tue, 2 Jul 2013 11:49:19 -0400 Subject: [PATCH 073/110] added section on splatting and translated default-and-keyword args function. --- julia.html.markdown | 42 +++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 222a490a..e1c6731c 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -318,6 +318,17 @@ end varargs(1, 2, 3) #=> (1,2,3) +# The ... is called a splat. +# It can also be used in a fuction call +# to splat a list or tuple out to be the arguments +Set([1,2,3]) #=>Set{Array{Int64,1}}([1,2,3]) # no ..., produces a Set of Arrays +Set([1,2,3]...) #=>Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) + +x = (1,2,3) #=> (1,2,3) +Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) #=> Set{Int64}(2,3,1) + + # You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) return "$a $b and $x $y" @@ -338,27 +349,24 @@ keyword_args(name2="ness") #=> ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") #=> ["k1"=>"mine","name2"=>"hello"] keyword_args() #=> ["name2"=>"hello","k2"=>4] +# You can also do both at once +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + + #### #### In progress point #### -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print args - print kwargs -""" -all_the_args(1, 2, a=3, b=4) prints: - [1, 2] - {"a": 3, "b": 4} -""" - -# You can also use * and ** when calling a function -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -foo(*args) # equivalent to foo(1, 2, 3, 4) -foo(**kwargs) # equivalent to foo(a=3, b=4) -foo(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) - # Python has first class functions def create_adder(x): def adder(y): From 918123e8cef7047550bf3bb9dbecc9b3efb01de2 Mon Sep 17 00:00:00 2001 From: David Underwood Date: Tue, 2 Jul 2013 13:24:50 -0400 Subject: [PATCH 074/110] changes string interpolation text as suggested by @fbernier --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index b07c92c9..44b0e46c 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -47,9 +47,9 @@ false #=> falsehood 'I am a string' "I am a string too" -placeholder = "use variables inline" +placeholder = "use string interpolation" "I can #{placeholder} when using double quoted strings" -#=> "I can use variables inline when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" # print to the output From 705e8fd023f6c61e4ccb79095238474ee922a0bd Mon Sep 17 00:00:00 2001 From: David Underwood Date: Tue, 2 Jul 2013 13:46:58 -0400 Subject: [PATCH 075/110] Adds emphasis about the object-oriented nature of ruby, and removes references to lesser-used array functions --- ruby.html.markdown | 59 ++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 44b0e46c..62db549c 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -13,8 +13,13 @@ No-one uses them You shouldn't either =end +# First and foremost: Everything is an object. -3 #=> 3 +# Numbers are objects + +3.class #=> Fixnum + +3.to_s #=> "3" # Some basic arithmetic @@ -23,15 +28,24 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 -# Special values -nil #=> Nothing to see here -true #=> truth -false #=> falsehood +# Special values are objects +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass # Equality 1 == 1 #=> true 2 == 1 #=> false +# apart from false itself, nil is the only other 'falsey' value + +nil == false #=> true +0 == false #=> false + # Inequality 1 != 1 #=> false 2 != 1 #=> true @@ -44,8 +58,10 @@ false #=> falsehood 2 <= 2 #=> true 2 >= 2 #=> true -'I am a string' -"I am a string too" +# Strings are objects + +'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" @@ -57,6 +73,7 @@ puts "I'm printing!" # Variables x = 25 #=> 25 +x #=> 25 # Note that assignment returns the value assigned # This means you can do multiple assignment: @@ -72,17 +89,19 @@ snake_case = true path_to_project_root = '/good/name/' path = '/bad/name/' -# Symbols +# Symbols (are objects) # Symbols are immutable, reusable constants represented internally by an integer value # They're often used instead of strings to efficiently convey specific, meaningful values +:pending.class #=> Symbol + status = :pending status == :pending #=> true status == 'pending' #=> false -position = :left +status == :approved #=> false # Arrays @@ -107,26 +126,9 @@ array[2, 4] #=> [3, 4, 5] # Or with a range array[1..3] #=> [2, 3, 4] -# Add to the end of an array like this +# Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] -# Or like this -array.push 7 #=> [1, 2, 3, 4, 5, 6, 7] - -# Or to the beginning like this -array.unshift 0 #=> [0, 1, 2, 3, 4, 5, 6, 7] - -# Remove the first item in an array - -array.shift #=> [1, 2, 3, 4, 5, 6, 7] - -# Or the last - -array.pop #=> [1, 2, 3, 4, 5, 6] - -# Note that push and pop do the opposite of each other -# Shift and unshift are the same. - # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: hash = {'color' => 'green', 'number' => 5} @@ -152,7 +154,7 @@ new_hash = { defcon: 3, action: true} new_hash.keys #=> [:defcon, :action] # Tip: Both Arrays and Hashes are Enumerable -# This means they share a lot of useful methods +# This means they share a lot of useful methods such as each, map, count, and more # Control structures @@ -197,6 +199,7 @@ end #=> iteration 5 grade = 'B' + case grade when 'A' puts "Way to go kiddo" From 94bd7fc1ee62c255f1f1c223c15cefc47e4b7820 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 11:00:30 -0700 Subject: [PATCH 076/110] Added more on folds wrt replacing loops --- haskell.html.markdown | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 84b8f263..bc712505 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -245,7 +245,7 @@ case args of _ -> putStrLn "bad args" -- Haskell doesn't have loops because it uses recursion instead. --- map a function over every element in an array +-- map calls a function over every element in an array map (*2) [1..5] -- [2, 4, 6, 8, 10] @@ -258,6 +258,19 @@ for [0..5] $ \i -> show i -- we could've written that like this too: for [0..5] show +-- You can use foldl or foldr to reduce a list +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- This is the same as +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl is left-handed, foldr is right- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- This is now the same as +(2 * 3 + (2 * 2 + (2 * 1 + 4) + ---------------------------------------------------- -- 7. Data Types ---------------------------------------------------- From d92508a4cb19278146dc49209e9abf1a4dd1330a Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 11:05:22 -0700 Subject: [PATCH 077/110] Changed 'calls ' to 'applies' before someone else does --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index bc712505..840569fb 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -245,7 +245,7 @@ case args of _ -> putStrLn "bad args" -- Haskell doesn't have loops because it uses recursion instead. --- map calls a function over every element in an array +-- map applies a function over every element in an array map (*2) [1..5] -- [2, 4, 6, 8, 10] From bbb3cf771b9a15706b16e79d7849c978485b8b35 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 11:55:09 -0700 Subject: [PATCH 078/110] Actual erlang highlighting --- erlang.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 66370a7d..42d0b809 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -5,7 +5,7 @@ author_url: http://www.focustheweb.com/ filename: learnerlang.erl --- -```latex +```erlang % Percent sign start a one-line comment. %% Two percent characters shall be used to comment functions. From b1e305626efe710e366003206ae53018f8e76df8 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Tue, 2 Jul 2013 17:23:10 -0400 Subject: [PATCH 079/110] finished function section --- julia.html.markdown | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index e1c6731c..d54e7d0e 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -362,30 +362,44 @@ all_the_args(1, 3, keyword_arg=4) # optional arg: 3 # keyword arg: 4 +# Julia has first class functions +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end -#### -#### In progress point -#### +# or equivalently +function create_adder(x) + y -> x + y +end -# Python has first class functions -def create_adder(x): - def adder(y): - return x + y - return adder +# you can also name the internal function, if you want +function create_adder(x) + function adder(y) + x + y + end + adder +end add_10 = create_adder(10) add_10(3) #=> 13 -# There are also anonymous functions -(lambda x: x > 2)(3) #=> True +# The first two inner functions above are anonymous functions +(x -> x > 2)(3) #=> true # 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] +filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # We can use list comprehensions for nice maps and filters +[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#### +#### In progress point +#### #################################################### ## 5. Classes From 587e35062cd129f6b7665f80daab384960863327 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Tue, 2 Jul 2013 18:00:32 -0400 Subject: [PATCH 080/110] added types section --- julia.html.markdown | 83 +++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 49 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index d54e7d0e..e18fc3cd 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -397,61 +397,46 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] [add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +#################################################### +## 5. Types and Multiple-Dispatch +#################################################### + +# Type definition +type Tiger + taillength::Float64 + coatcolor # no type annotation is implicitly Any +end +# default constructor is the properties in order +# so, Tiger(taillength,coatcolor) + +# Type instantiation +tigger = Tiger(3.5,"orange") # the type doubles as the constructor function + +# Abtract Types +abstract Cat # just a name and point in the type hierarchy + +# types defined with the type keyword are concrete types; they can be instantiated +# types defined with the abstract keyword are abstract types; they can have subtypes +# each type has one supertype; a supertype can have zero or more subtypes. + +type Lion <: Cat # Lion is a subtype of Cat + mane_color + roar::String +end + +type Panther <: Cat # Panther is also a subtype of Cat + eye_color + Panther() = new("green") # Panthers will only have this constructor, and no default constructor. +end + #### #### In progress point #### -#################################################### -## 5. Classes -#################################################### - -# We subclass from object to get a class. -class Human(object): - - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" - - # Basic initializer - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name - - # An instance method. All methods take self as the first argument - def say(self, msg): - return "%s: %s" % (self.name, msg) - - # A class method is shared among all instances - # They are called with the calling class as the first argument - @classmethod - def get_species(cls): - return cls.species - - # A static method is called without a class or instance reference - @staticmethod - def grunt(): - return "*grunt*" - - -# Instantiate a class -i = Human(name="Ian") -print i.say("hi") # prints out "Ian: hi" - -j = Human("Joel") -print j.say("hello") #prints out "Joel: hello" - -# Call our class method -i.get_species() #=> "H. sapiens" - -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() #=> "H. neanderthalensis" -j.get_species() #=> "H. neanderthalensis" - -# Call the static method -Human.grunt() #=> "*grunt*" -``` +#### Multiple Dispatch ## Further Reading +#### Link to Maunual Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) From 6763fc89e314b9b6b43cc4e2a38d4d7fdacfa2d4 Mon Sep 17 00:00:00 2001 From: mrshankly Date: Tue, 2 Jul 2013 23:23:49 +0100 Subject: [PATCH 081/110] Finished first draft of learnelixir. --- elixir.html.markdown | 179 ++++++++++++++++++++++++++++++------------- 1 file changed, 125 insertions(+), 54 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index a37d0f5e..11a0701c 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -24,15 +24,15 @@ filename: learnelixir.ex {1,2,3} # tuple # We can access a tuple element with the `elem` function: -elem({1, 2, 3}, 0) # => 1 +elem({1, 2, 3}, 0) #=> 1 # Lists that are implemented as linked lists. [1,2,3] # list # We can access the head and tail of a list as follows: [head | tail] = [1,2,3] -head # => 1 -tail # => [2,3] +head #=> 1 +tail #=> [2,3] # In elixir, just like in erlang, the `=` denotes pattern matching and # not an assignment. @@ -44,7 +44,7 @@ tail # => [2,3] # A pattern match will error when the sides don't match, in this example # the tuples have different sizes. -{a, b, c} = {1, 2} # => ** (MatchError) no match of right hand side value: {1,2} +{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} # There's also binaries <<1,2,3>> # binary @@ -53,64 +53,73 @@ tail # => [2,3] "hello" # string 'hello' # char list +# Multi-line strings +""" +I'm a multi-line +string. +""" +#=> "I'm a multi-line\nstring.\n" + # Strings are all encoded in UTF-8: -"héllò" # => "héllò" +"héllò" #=> "héllò" # Strings are really just binaries, and char lists are just lists. -<> # => "abc" -[?a, ?b, ?c] # => 'abc' +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' # `?a` in elixir returns the ASCII integer for the letter `a` -?a # => 97 +?a #=> 97 -## TODO: -###################################################### -## JOIN BINARIES AND LISTS -###################################################### +# To concatenate lists use `++`, for binaries use `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" ## --------------------------- ## -- Operators ## --------------------------- # Some math -1 + 1 # => 2 -10 - 5 # => 5 -5 * 2 # => 10 -10 / 2 # => 5.0 +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 # In elixir the operator `/` always returns a float. # To do integer division use `div` -div(10, 2) # => 5 +div(10, 2) #=> 5 # To get the division remainder use `rem` -rem(10, 3) # => 1 +rem(10, 3) #=> 1 # There's also boolean operators: `or`, `and` and `not`. # These operators expect a boolean as their first argument. -true and true # => true -false or true # => true -1 and true # => ** (ArgumentError) argument error +true and true #=> true +false or true #=> true +1 and true #=> ** (ArgumentError) argument error # Elixir also provides `||`, `&&` and `!` which accept arguments of any type. # All values except `false` and `nil` will evaluate to true. -1 || true # => 1 -false && 1 # => false -nil && 20 # => nil +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil -!true # => false +!true #=> false # For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` -1 == 1 # => true -1 != 1 # => false -1 < 2 # => true +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true # `===` and `!==` are more strict when comparing integers and floats: -1 == 1.0 # => true -1 === 1.0 # => false +1 == 1.0 #=> true +1 === 1.0 #=> false # We can also compare two different data types: -1 < :hello # => true +1 < :hello #=> true # The overall sorting order is defined below: number < atom < reference < functions < port < pid < tuple < list < bit string @@ -151,11 +160,11 @@ end # It's common practive to assign a value to `_` if we don't need it. # For example, if only the head of a list matters to us: [head | _] = [1,2,3] -head # => 1 +head #=> 1 # For better readability we can do the following: [head | _tail] = [:a, :b, :c] -head # => :a +head #=> :a # `cond` lets us check for many conditions at the same time. # Use `cond` instead of nesting many `if` expressions. @@ -187,27 +196,19 @@ catch after IO.puts("I'm the after clause.") end -# => I'm the after clause -# "Got :hello" - -## TODO: -###################################################### -## GUARDS -###################################################### +#=> I'm the after clause +# "Got :hello" ## --------------------------- ## -- Modules and Functions ## --------------------------- -############################### -## EXPLAIN built-in functions? -############################### - # Anonymous functions (notice the dot) square = fn(x) -> x * x end square.(5) #=> 25 -# They also accept many clauses and guards +# They also accept many clauses and guards. Guards let you fine tune pattern matching, +# they are indicated by the `when` keyword: f = fn x, y when x > 0 -> x + y x, y -> x * y @@ -216,6 +217,12 @@ end f.(1, 3) #=> 4 f.(-1, 3) #=> -3 +# Elixir also provides many built-in functions. +# These are available in the current scope. +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + # You can group several functions into a module. Inside a module use `def` # to define your functions. defmodule Math do @@ -234,9 +241,7 @@ Match.square(3) #=> 9 # To compile our little Math module save it as `math.ex` and use `elixirc` elixirc math.ex -# Inside a module we can define functions with `def` and -# private functions with `defp`. -# +# Inside a module we can define functions with `def` and private functions with `defp`. # A function defined with `def` is available to be invoked from other modules, # a private function can only be invoked locally. defmodule PrivateMath do @@ -258,7 +263,7 @@ defmodule Geometry do w * h end - def area({:circle, r}) when r > 0 do + def area({:circle, r}) when is_number(r) do 3.14 * r * r end end @@ -279,9 +284,17 @@ end Recursion.sum_list([1,2,3], 0) #=> 6 -############################### -## EXPLAIN module attributes -############################### +# Elixir modules support attributes, there are built-in attributes and you +# may also add custom attributes. + +defmodule MyMod do + @moduledoc """ + This is a built-in attribute on a example module. + """ + + @my_data 100 # This is a custom attribute. + IO.inspect(@my_data) #=> 100 +end ## --------------------------- ## -- Records and Exceptions @@ -300,11 +313,69 @@ joe_info.name #=> "Joe" # Update the value of age joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] -## TODO: Exceptions +# The `try` block with the `rescue` keyword is used to handle exceptions +try do + raise "some error" +rescue + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" +end + +# All exceptions have a message +try do + raise "some error" +rescue + x in [RuntimeError] -> + x.message +end ## --------------------------- ## -- Concurrency ## --------------------------- -## TODO +# Elixir relies on the actor model for concurrency. All we need to write +# concurrent programs in elixir are three primitives: spawning processes, +# sending messages and receiving messages. + +# To start a new process we use the `spawn` function, which takes a function +# as argument. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` returns a pid (process identifier), you can use this pid to send +# messages to the process. To do message passing we use the `<-` operator. +# For all of this to be useful we need to be able to receive messages. This is +# achived with the `receive` mechanism: + +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compile the module and create a process that evaluates `area_loop` in the shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Send a message to `pid` that will match a pattern in the receive statement +pid <- {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +pid <- {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} ``` + +## References + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert +* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong \ No newline at end of file From 178eaad9df4b4730f7d54994633812220e132f78 Mon Sep 17 00:00:00 2001 From: Yaser Alraddadi Date: Wed, 3 Jul 2013 01:33:48 +0300 Subject: [PATCH 082/110] Added dir() function Added dir() function --- python.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 59a0b85c..ff77fac6 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -461,6 +461,11 @@ math.sqrt(16) == m.sqrt(16) #=> True # can write your own, and import them. The name of the # module is the same as the name of the file. +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + ``` From 231a211ef213142bd856356924102f9a25d55e83 Mon Sep 17 00:00:00 2001 From: mrshankly Date: Tue, 2 Jul 2013 23:37:18 +0100 Subject: [PATCH 083/110] Added some info about how to run the shell and compile modules. --- elixir.html.markdown | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 11a0701c..255d311d 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -6,11 +6,19 @@ filename: learnelixir.ex --- ```elixir -# Single line comments start with a hash. +# Single line comments start with a hashtag. -## -------------------- +# There's no multi-line comment, +# but you can stack multiple comments. + +# To use the elixir shell use the `iex` command. +# Compile your modules with the `elixirc` command. + +# Both should be in your path if you installed elixir correctly. + +## --------------------------- ## -- Basic types -## -------------------- +## --------------------------- # There are numbers 3 # integer @@ -286,7 +294,6 @@ Recursion.sum_list([1,2,3], 0) #=> 6 # Elixir modules support attributes, there are built-in attributes and you # may also add custom attributes. - defmodule MyMod do @moduledoc """ This is a built-in attribute on a example module. @@ -346,7 +353,6 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `<-` operator. # For all of this to be useful we need to be able to receive messages. This is # achived with the `receive` mechanism: - defmodule Geometry do def area_loop do receive do @@ -371,6 +377,9 @@ pid <- {:rectangle, 2, 3} pid <- {:circle, 2} #=> Area = 12.56000000000000049738 # {:circle,2} + +# The shell is also a process, you can use `self` to get the current pid +self() #=> #PID<0.27.0> ``` ## References From 0cf568d278db4cb766723e30d88b15c38f1d4536 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Tue, 2 Jul 2013 18:55:23 -0400 Subject: [PATCH 084/110] finished first draft :) --- julia.html.markdown | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index e18fc3cd..f722f7ee 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -429,14 +429,37 @@ type Panther <: Cat # Panther is also a subtype of Cat Panther() = new("green") # Panthers will only have this constructor, and no default constructor. end -#### -#### In progress point -#### +# Multiple Dispatch + +# In Julia, all named functions are generic functions +# This means that they are built up from many small methods +# For example, let's make a function meow: +function meow(cat::Lion) + cat.roar # access properties using dot notation +end + +function meow(cat::Panther) + "grrr" +end + +function meow(cat::Tiger) + "rawwwr" +end + +meow(tigger) #=> "rawwr" +meow(Lion("brown","ROAAR")) #=> "ROAAR" +meow(Panther()) #=> "grrr" + +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) +pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" -#### Multiple Dispatch ## Further Reading -#### Link to Maunual -Still up for more? Try [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) + From a136cfe86a3c28ac16c2aa4a3323413cfd76c46f Mon Sep 17 00:00:00 2001 From: mrshankly Date: Wed, 3 Jul 2013 00:03:44 +0100 Subject: [PATCH 085/110] Added one more example with guards, fixed typos and identation. --- elixir.html.markdown | 154 ++++++++++++++++++++++--------------------- 1 file changed, 78 insertions(+), 76 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 255d311d..0ded7562 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -141,33 +141,33 @@ number < atom < reference < functions < port < pid < tuple < list < bit string # `if` expression if false do - "This will never be seen" + "This will never be seen" else - "This will" + "This will" end # There's also `unless` unless true do - "This will never be seen" + "This will never be seen" else - "This will" + "This will" end # Remember pattern matching? Many control-flow structures in elixir rely on it. # `case` allows us to compare a value against many patterns: case {:one, :two} do - {:four, :five} -> - "This won't match" - {:one, x} -> - "This will match and assign `x` to `:two`" - _ -> - "This will match any value" + {:four, :five} -> + "This won't match" + {:one, x} -> + "This will match and assign `x` to `:two`" + _ -> + "This will match any value" end # It's common practive to assign a value to `_` if we don't need it. # For example, if only the head of a list matters to us: -[head | _] = [1,2,3] +[head | _] = [1,2,3] head #=> 1 # For better readability we can do the following: @@ -177,35 +177,35 @@ head #=> :a # `cond` lets us check for many conditions at the same time. # Use `cond` instead of nesting many `if` expressions. cond do - 1 + 1 == 3 -> - "I will never be seen" - 2 * 5 == 12 -> - "Me neither" - 1 + 2 == 3 -> - "But I will" + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + 1 + 2 == 3 -> + "But I will" end # It is common to see a last condition equal to `true`, which will always match. cond do - 1 + 1 == 3 -> - "I will never be seen" - 2 * 5 == 12 -> - "Me neither" - true -> - "But I will (this is essentially an else)" + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + true -> + "But I will (this is essentially an else)" end # `try/catch` is used to catch values that are thrown, it also supports an # `after` clause that is invoked whether or not a value is catched. try do - throw(:hello) + throw(:hello) catch - message -> "Got #{message}." + message -> "Got #{message}." after - IO.puts("I'm the after clause.") + IO.puts("I'm the after clause.") end #=> I'm the after clause -# "Got :hello" +# "Got :hello" ## --------------------------- ## -- Modules and Functions @@ -218,8 +218,8 @@ square.(5) #=> 25 # They also accept many clauses and guards. Guards let you fine tune pattern matching, # they are indicated by the `when` keyword: f = fn - x, y when x > 0 -> x + y - x, y -> x * y + x, y when x > 0 -> x + y + x, y -> x * y end f.(1, 3) #=> 4 @@ -234,32 +234,32 @@ elem({1,2,3}, 0) #=> 1 # You can group several functions into a module. Inside a module use `def` # to define your functions. defmodule Math do - def sum(a, b) do - a + b - end + def sum(a, b) do + a + b + end - def square(x) do - x * x - end + def square(x) do + x * x + end end Math.sum(1, 2) #=> 3 Match.square(3) #=> 9 -# To compile our little Math module save it as `math.ex` and use `elixirc` -elixirc math.ex +# To compile our simple Math module save it as `math.ex` and use `elixirc` +# in your terminal: elixirc math.ex # Inside a module we can define functions with `def` and private functions with `defp`. # A function defined with `def` is available to be invoked from other modules, # a private function can only be invoked locally. defmodule PrivateMath do - def sum(a, b) do - do_sum(a, b) - end + def sum(a, b) do + do_sum(a, b) + end - defp do_sum(a, b) do - a + b - end + defp do_sum(a, b) do + a + b + end end PrivateMath.sum(1, 2) #=> 3 @@ -267,27 +267,29 @@ PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) # Function declarations also support guards and multiple clauses: defmodule Geometry do - def area({:rectangle, w, h}) do - w * h - end + def area({:rectangle, w, h}) do + w * h + end - def area({:circle, r}) when is_number(r) do - 3.14 * r * r - end + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end end Geometry.area({:rectangle, 2, 3}) #=> 6 Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 # Due to immutability, recursion is a big part of elixir defmodule Recursion do - def sum_list([head | tail], acc) do - sum_list(tail, acc + head) - end + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end - def sum_list([], acc) do - acc - end + def sum_list([], acc) do + acc + end end Recursion.sum_list([1,2,3], 0) #=> 6 @@ -295,12 +297,12 @@ Recursion.sum_list([1,2,3], 0) #=> 6 # Elixir modules support attributes, there are built-in attributes and you # may also add custom attributes. defmodule MyMod do - @moduledoc """ - This is a built-in attribute on a example module. - """ + @moduledoc """ + This is a built-in attribute on a example module. + """ - @my_data 100 # This is a custom attribute. - IO.inspect(@my_data) #=> 100 + @my_data 100 # This is a custom attribute. + IO.inspect(@my_data) #=> 100 end ## --------------------------- @@ -322,18 +324,18 @@ joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] # The `try` block with the `rescue` keyword is used to handle exceptions try do - raise "some error" + raise "some error" rescue - RuntimeError -> "rescued a runtime error" - _error -> "this will rescue any error" + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" end # All exceptions have a message try do - raise "some error" + raise "some error" rescue - x in [RuntimeError] -> - x.message + x in [RuntimeError] -> + x.message end ## --------------------------- @@ -354,16 +356,16 @@ spawn(f) #=> #PID<0.40.0> # For all of this to be useful we need to be able to receive messages. This is # achived with the `receive` mechanism: defmodule Geometry do - def area_loop do - receive do - {:rectangle, w, h} -> - IO.puts("Area = #{w * h}") - area_loop() - {:circle, r} -> - IO.puts("Area = #{3.14 * r * r}") - area_loop() - end - end + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end end # Compile the module and create a process that evaluates `area_loop` in the shell From 78970bb8414e2ae956dae8720513eaf3024254f9 Mon Sep 17 00:00:00 2001 From: mrshankly Date: Wed, 3 Jul 2013 00:07:55 +0100 Subject: [PATCH 086/110] Added new line at the end of file. --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 0ded7562..c0544982 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -389,4 +389,4 @@ self() #=> #PID<0.27.0> * [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) * ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert -* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong \ No newline at end of file +* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong From bbfe94770feb3f9373a6c8b8fbffb97e8f06e867 Mon Sep 17 00:00:00 2001 From: Stefan Karpinski Date: Tue, 2 Jul 2013 23:15:34 -0400 Subject: [PATCH 087/110] suggested edits to the learn Julia in Y minutes document. --- julia.html.markdown | 95 +++++++++++++++++++++++++-------------------- 1 file changed, 52 insertions(+), 43 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index f722f7ee..0dd40f73 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -51,6 +51,15 @@ div(5, 2) #=> 2 bits(2) #=> "0000000000000000000000000000000000000000000000000000000000000010" bits(2.0) #=> "0100000000000000000000000000000000000000000000000000000000000000" +# this might be a better example: +julia> bits(123) +"0000000000000000000000000000000000000000000000000000000001111011" + +julia> bits(123.0) +"0100000001011110110000000000000000000000000000000000000000000000" +# the other one stands the risk of someone thinking that floating-point +# numbers are just integers with reversed bit-patterns or something. + # Boolean values are primitives true false @@ -80,7 +89,7 @@ false "This is a string"[1] #=> 'T' # Julia indexes from 1 # $ can be used for string interpolation: -"2 + 2 = $(2+2)" # => "2 + 2 = 4" +"2 + 2 = $(2 + 2)" #=> "2 + 2 = 4" # You can put any Julia expression inside the parenthesis. # Another way to format strings is the printf macro. @@ -100,7 +109,7 @@ some_var #=> 5 some_other_var #=> ERROR: some_other_var not defined # Variable Names: -SomeOtherVar123! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well. +SomeOtherVar123! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well after the initial alphabetic character. ☃ = 8 #=> 8 # You can also use unicode characters # A note on naming conventions in Julia: @@ -109,26 +118,28 @@ SomeOtherVar123! = 6 #=> 6 # You can use uppercase letters, digits, and exclamat # * Names of functions and macros are in lower case, without underscores. # * Functions that modify their inputs have names that end in !. These functions are sometimes called mutating functions or in-place functions. -# Arrays store sequences -li = Int64[] #=> 0-element Int64 Array +# Arrays store a sequence of values indexed by integers 1 through n: +a = Int64[] #=> 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. -other_li = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] +b = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] +b[1] #=> 4 +b[end] #=> 6 # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] # Add stuff to the end of a list with push! and append! -push!(li,1) #=> [1] -push!(li,2) #=> [1,2] -push!(li,4) #=> [1,2,4] -push!(li,3) #=> [1,2,4,3] -append!(li,other_li) #=> [1,2,4,3,4,5,6] +push!(a,1) #=> [1] +push!(a,2) #=> [1,2] +push!(a,4) #=> [1,2,4] +push!(a,3) #=> [1,2,4,3] +append!(a,b) #=> [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(other_li) #=> 6 and other_li is now [4,5] +pop!(a) #=> 6 and b is now [4,5] # Let's put it back -push!(other_li,6) # other_li is now [4,5,6] again. +push!(b,6) # b is now [4,5,6] again. -li[1] #=> 1 # remember that Julia indexes from 1, not 0! -li[end] #=> 6 # end is a shorthand for the last index; it can be used in any indexing expression. +a[1] #=> 1 # remember that Julia indexes from 1, not 0! +a[end] #=> 6 # end is a shorthand for the last index; it can be used in any indexing expression. # Function names that end in exclamations points indicate that they modify their argument. arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] @@ -136,36 +147,37 @@ sort(arr) #=> [4,5,6]; arr is still [5,4,6] sort!(arr) #=> [4,5,6]; arr is now [4,5,6] # Looking out of bounds is a BoundsError -li[0] # ERROR: BoundsError() in getindex at array.jl:270 +a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 +a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 # Errors list the line and file they came from, even if it's in the standard library. # If you built Julia from source, you can look in the folder base inside the julia folder to find these files. # You can initialize arrays from ranges -li = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] +a = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. -li[1:3] #=> [1, 2, 3] +a[1:3] #=> [1, 2, 3] # Omit the beginning -li[2:] #=> [2, 3, 4, 5] +a[2:] #=> [2, 3, 4, 5] # Remove arbitrary elements from a list with splice! arr = [3,4,5] splice!(arr,2) #=> 4 ; arr is now [3,5] # Concatenate lists with append! -other_li = [1,2,3] -append!(li,other_li) # Now li is [1, 3, 4, 5, 1, 2, 3] +b = [1,2,3] +append!(a,b) # Now a is [1, 3, 4, 5, 1, 2, 3] # Check for existence in a list with contains -contains(li,1) #=> true +contains(a,1) #=> true # Examine the length with length -length(li) #=> 7 +length(a) #=> 7 # Tuples are immutable. tup = (1, 2, 3) #=>(1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] #=> 1 -tup[0] = 3 # ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) # Many list functions also work on tuples length(tup) #=> 3 @@ -190,8 +202,7 @@ filled_dict["one"] #=> 1 # Get all keys keys(filled_dict) #=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. +# Note - dictionary keys are not sorted or in the order you inserted them. # Get all values values(d) #=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) @@ -243,12 +254,11 @@ if some_var > 10 println("some_var is totally bigger than 10.") elseif some_var < 10 # This elseif clause is optional. println("some_var is smaller than 10.") -else # This is optional too. +else # The else clause is optional too. println("some_var is indeed 10.") end - # For loops iterate over iterable things, such as ranges, lists, sets, dicts, strings. # prints: # dog is a mammal @@ -308,7 +318,7 @@ function add(x, y) x + y # or equivalently: return x + y end -add(5, 6) #=> 11 and prints out "x is 5 and y is 6" +add(5, 6) #=> 11 after printing out "x is 5 and y is 6" # You can define functions that take a variable number of # positional arguments @@ -316,13 +326,13 @@ function varargs(args...) return args end -varargs(1, 2, 3) #=> (1,2,3) +varargs(1,2,3) #=> (1,2,3) # The ... is called a splat. # It can also be used in a fuction call # to splat a list or tuple out to be the arguments -Set([1,2,3]) #=>Set{Array{Int64,1}}([1,2,3]) # no ..., produces a Set of Arrays -Set([1,2,3]...) #=>Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) +Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # no ..., produces a Set of Arrays +Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) x = (1,2,3) #=> (1,2,3) Set(x) #=> Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples @@ -331,7 +341,7 @@ Set(x...) #=> Set{Int64}(2,3,1) # You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) - return "$a $b and $x $y" + return "$a $b and $x $y" end defaults('h','g') #=> "h g and 5 6" @@ -364,10 +374,10 @@ all_the_args(1, 3, keyword_arg=4) # Julia has first class functions function create_adder(x) - adder = function (y) - return x + y - end - return adder + adder = function (y) + return x + y + end + return adder end # or equivalently @@ -377,10 +387,10 @@ end # you can also name the internal function, if you want function create_adder(x) - function adder(y) - x + y - end - adder + function adder(y) + x + y + end + adder end add_10 = create_adder(10) @@ -394,8 +404,8 @@ map(add_10, [1,2,3]) #=> [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # We can use list comprehensions for nice maps and filters -[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i=[1, 2, 3]] #=> [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] #################################################### ## 5. Types and Multiple-Dispatch @@ -462,4 +472,3 @@ pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) - From 9adefc58b1adf5a58bacf06f0434a53137dd8b89 Mon Sep 17 00:00:00 2001 From: Stefan Karpinski Date: Tue, 2 Jul 2013 23:27:19 -0400 Subject: [PATCH 088/110] don't be lazy and actually make the first change I suggested. --- julia.html.markdown | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 0dd40f73..c31df752 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -48,17 +48,8 @@ div(5, 2) #=> 2 2 << 1 #=> 4 # logical/arithmetic shift left # You can use the bits function to see the binary representation of a number. -bits(2) #=> "0000000000000000000000000000000000000000000000000000000000000010" -bits(2.0) #=> "0100000000000000000000000000000000000000000000000000000000000000" - -# this might be a better example: -julia> bits(123) -"0000000000000000000000000000000000000000000000000000000001111011" - -julia> bits(123.0) -"0100000001011110110000000000000000000000000000000000000000000000" -# the other one stands the risk of someone thinking that floating-point -# numbers are just integers with reversed bit-patterns or something. +bits(12345) #=> "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) #=> "0100000011001000000111001000000000000000000000000000000000000000" # Boolean values are primitives true From 0df65c8761ddb05526c729f34678cefe0cdf5349 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 22:13:30 -0700 Subject: [PATCH 089/110] Edited julia code for line length and runnability --- julia.html.markdown | 154 ++++++++++++++++++++++++++++++-------------- 1 file changed, 107 insertions(+), 47 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index c31df752..6c719b5c 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -2,6 +2,7 @@ language: julia author: Leah Hanson author_url: http://leahhanson.us +filename: learnjulia.jl --- Julia is a new homoiconic functional language focused on technical computing. @@ -9,7 +10,8 @@ While having the full power of homoiconic macros, first-class functions, and low This is based on the current development version of Julia, as of June 29th, 2013. -```julia +```ruby + # Single line comments start with a hash. #################################################### @@ -48,8 +50,10 @@ div(5, 2) #=> 2 2 << 1 #=> 4 # logical/arithmetic shift left # You can use the bits function to see the binary representation of a number. -bits(12345) #=> "0000000000000000000000000000000000000000000000000011000000111001" -bits(12345.0) #=> "0100000011001000000111001000000000000000000000000000000000000000" +bits(12345) +#=> "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +#=> "0100000011001000000111001000000000000000000000000000000000000000" # Boolean values are primitives true @@ -96,25 +100,42 @@ println("I'm Julia. Nice to meet you!") # No need to declare variables before assigning to them. some_var = 5 #=> 5 some_var #=> 5 -# Accessing a previously unassigned variable is an error -some_other_var #=> ERROR: some_other_var not defined -# Variable Names: -SomeOtherVar123! = 6 #=> 6 # You can use uppercase letters, digits, and exclamation points as well after the initial alphabetic character. -☃ = 8 #=> 8 # You can also use unicode characters +# Accessing a previously unassigned variable is an error +try + some_other_var #=> ERROR: some_other_var not defined +catch e + println(e) +end + +# Variable name start with a letter. You can use uppercase letters, digits, +# and exclamation points as well after the initial alphabetic character. +SomeOtherVar123! = 6 #=> 6 + +# You can also use unicode characters +☃ = 8 #=> 8 # A note on naming conventions in Julia: -# * Names of variables are in lower case, with word separation indicated by underscores ('\_'). -# * Names of Types begin with a capital letter and word separation is shown with CamelCase instead of underscores. +# +# * Names of variables are in lower case, with word separation indicated by +# underscores ('\_'). +# +# * Names of Types begin with a capital letter and word separation is shown +# with CamelCase instead of underscores. +# # * Names of functions and macros are in lower case, without underscores. -# * Functions that modify their inputs have names that end in !. These functions are sometimes called mutating functions or in-place functions. +# +# * Functions that modify their inputs have names that end in !. These +# functions are sometimes called mutating functions or in-place functions. # Arrays store a sequence of values indexed by integers 1 through n: a = Int64[] #=> 0-element Int64 Array + # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] #=> 3-element Int64 Array: [4, 5, 6] b[1] #=> 4 b[end] #=> 6 + # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] #=> 2x2 Int64 Array: [1 2; 3 4] @@ -124,42 +145,53 @@ push!(a,2) #=> [1,2] push!(a,4) #=> [1,2,4] push!(a,3) #=> [1,2,4,3] append!(a,b) #=> [1,2,4,3,4,5,6] + # Remove from the end with pop pop!(a) #=> 6 and b is now [4,5] + # Let's put it back push!(b,6) # b is now [4,5,6] again. a[1] #=> 1 # remember that Julia indexes from 1, not 0! -a[end] #=> 6 # end is a shorthand for the last index; it can be used in any indexing expression. -# Function names that end in exclamations points indicate that they modify their argument. +# end is a shorthand for the last index. It can be used in any +# indexing expression +a[end] #=> 6 + +# Function names that end in exclamations points indicate that they modify +# their argument. arr = [5,4,6] #=> 3-element Int64 Array: [5,4,6] sort(arr) #=> [4,5,6]; arr is still [5,4,6] sort!(arr) #=> [4,5,6]; arr is now [4,5,6] # Looking out of bounds is a BoundsError -a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 -a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 -# Errors list the line and file they came from, even if it's in the standard library. -# If you built Julia from source, you can look in the folder base inside the julia folder to find these files. +try + a[0] #=> ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] #=> ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Errors list the line and file they came from, even if it's in the standard +# library. If you built Julia from source, you can look in the folder base +# inside the julia folder to find these files. # You can initialize arrays from ranges a = [1:5] #=> 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. a[1:3] #=> [1, 2, 3] -# Omit the beginning a[2:] #=> [2, 3, 4, 5] # Remove arbitrary elements from a list with splice! arr = [3,4,5] splice!(arr,2) #=> 4 ; arr is now [3,5] -# Concatenate lists with append! +# Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 3, 4, 5, 1, 2, 3] -# Check for existence in a list with contains +# Check for existence in a list with contains contains(a,1) #=> true # Examine the length with length @@ -168,7 +200,11 @@ length(a) #=> 7 # Tuples are immutable. tup = (1, 2, 3) #=>(1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] #=> 1 -tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +try: + tup[0] = 3 #=> ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end # Many list functions also work on tuples length(tup) #=> 3 @@ -177,36 +213,46 @@ contains(tup,2) #=> true # You can unpack tuples into variables a, b, c = (1, 2, 3) #=> (1,2,3) # a is now 1, b is now 2 and c is now 3 + # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 #=> (4,5,6) + # Now look how easy it is to swap two values e, d = d, e #=> (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings empty_dict = Dict() #=> Dict{Any,Any}() + # Here is a prefilled dictionary -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] #=> ["one"=> 1, "two"=> 2, "three"=> 3] # Dict{ASCIIString,Int64} +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} # Look up values with [] filled_dict["one"] #=> 1 # Get all keys -keys(filled_dict) #=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +keys(filled_dict) +#=> KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - dictionary keys are not sorted or in the order you inserted them. # Get all values -values(d) #=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +values(filled_dict) +#=> ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with contains, haskey -contains(filled_dict,("one",1)) #=> true -contains(filled_dict,("two",3)) #=> false -haskey(filled_dict,"one") #=> true -haskey(filled_dict,1) #=> false +contains(filled_dict, ("one", 1)) #=> true +contains(filled_dict, ("two", 3)) #=> false +haskey(filled_dict, "one") #=> true +haskey(filled_dict, 1) #=> false # Trying to look up a non-existing key will raise an error -filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 +try + filled_dict["four"] #=> ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end # Use get method to avoid the error # get(dictionary,key,default_value) @@ -250,16 +296,16 @@ else # The else clause is optional too. end -# For loops iterate over iterable things, such as ranges, lists, sets, dicts, strings. -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# For loops iterate over iterables, such as ranges, lists, sets, dicts, strings. for animal=["dog", "cat", "mouse"] # You can use $ to interpolate into strings println("$animal is a mammal") end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal # You can use in instead of =, if you want. for animal in ["dog", "cat", "mouse"] @@ -288,14 +334,11 @@ while x < 4 end # Handle exceptions with a try/except block - -error("help") # ERROR: help in error at error.jl:21 - try error("help") catch e println("caught it $e") -end +end #=> caught it ErrorException("help") @@ -306,7 +349,9 @@ end # Use the keyword function to create new functions function add(x, y) println("x is $x and y is $y") - x + y # or equivalently: return x + y + + # Functions implicitly return the value of their last statement + x + y end add(5, 6) #=> 11 after printing out "x is 5 and y is 6" @@ -322,7 +367,7 @@ varargs(1,2,3) #=> (1,2,3) # The ... is called a splat. # It can also be used in a fuction call # to splat a list or tuple out to be the arguments -Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # no ..., produces a Set of Arrays +Set([1,2,3]) #=> Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays Set([1,2,3]...) #=> Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) x = (1,2,3) #=> (1,2,3) @@ -338,8 +383,12 @@ end defaults('h','g') #=> "h g and 5 6" defaults('h','g','j') #=> "h g and j 6" defaults('h','g','j','k') #=> "h g and j k" -defaults('h') #=> ERROR: no method defaults(Char,) -defaults() #=> ERROR: no methods defaults() +try + defaults('h') #=> ERROR: no method defaults(Char,) + defaults() #=> ERROR: no methods defaults() +catch e +println(e) +end # You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # note the ; @@ -416,9 +465,13 @@ tigger = Tiger(3.5,"orange") # the type doubles as the constructor function # Abtract Types abstract Cat # just a name and point in the type hierarchy -# types defined with the type keyword are concrete types; they can be instantiated -# types defined with the abstract keyword are abstract types; they can have subtypes -# each type has one supertype; a supertype can have zero or more subtypes. +# * types defined with the type keyword are concrete types; they can be +# instantiated +# +# * types defined with the abstract keyword are abstract types; they can +# have subtypes. +# +# * each type has one supertype; a supertype can have zero or more subtypes. type Lion <: Cat # Lion is a subtype of Cat mane_color @@ -427,7 +480,8 @@ end type Panther <: Cat # Panther is also a subtype of Cat eye_color - Panther() = new("green") # Panthers will only have this constructor, and no default constructor. + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. end # Multiple Dispatch @@ -455,9 +509,15 @@ function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end -pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) +try + pet_cat(tigger) #=> ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + pet_cat(Lion(Panther(),"42")) #=> prints "The cat says 42" +``` ## Further Reading From 03ac46f56654ce669596399ff9861d770b890102 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 22:47:37 -0700 Subject: [PATCH 090/110] Edited elixir doc for length and runnability --- elixir.html.markdown | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index c0544982..2e9aa5a1 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -5,7 +5,12 @@ author_url: http://github.com/mrshankly filename: learnelixir.ex --- -```elixir +Elixir is a modern functional language built on top of the Erlang VM. +It's fully compatible with Erlang, but features a more standard syntax +and many more features. + +```ruby + # Single line comments start with a hashtag. # There's no multi-line comment, @@ -52,7 +57,7 @@ tail #=> [2,3] # A pattern match will error when the sides don't match, in this example # the tuples have different sizes. -{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} # There's also binaries <<1,2,3>> # binary @@ -107,7 +112,7 @@ rem(10, 3) #=> 1 # These operators expect a boolean as their first argument. true and true #=> true false or true #=> true -1 and true #=> ** (ArgumentError) argument error +# 1 and true #=> ** (ArgumentError) argument error # Elixir also provides `||`, `&&` and `!` which accept arguments of any type. # All values except `false` and `nil` will evaluate to true. @@ -130,7 +135,7 @@ nil && 20 #=> nil 1 < :hello #=> true # The overall sorting order is defined below: -number < atom < reference < functions < port < pid < tuple < list < bit string +# number < atom < reference < functions < port < pid < tuple < list < bit string # To quote Joe Armstrong on this: "The actual order is not important, # but that a total ordering is well defined is important." @@ -215,7 +220,8 @@ end square = fn(x) -> x * x end square.(5) #=> 25 -# They also accept many clauses and guards. Guards let you fine tune pattern matching, +# They also accept many clauses and guards. +# Guards let you fine tune pattern matching, # they are indicated by the `when` keyword: f = fn x, y when x > 0 -> x + y @@ -244,7 +250,7 @@ defmodule Math do end Math.sum(1, 2) #=> 3 -Match.square(3) #=> 9 +Math.square(3) #=> 9 # To compile our simple Math module save it as `math.ex` and use `elixirc` # in your terminal: elixirc math.ex @@ -263,7 +269,7 @@ defmodule PrivateMath do end PrivateMath.sum(1, 2) #=> 3 -PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) # Function declarations also support guards and multiple clauses: defmodule Geometry do @@ -278,7 +284,7 @@ end Geometry.area({:rectangle, 2, 3}) #=> 6 Geometry.area({:circle, 3}) #=> 28.25999999999999801048 -Geometry.area({:circle, "not_a_number"}) +# Geometry.area({:circle, "not_a_number"}) #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 # Due to immutability, recursion is a big part of elixir From 3dfdab742dc52b61c58682664db35c20b737a05c Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 3 Jul 2013 15:21:03 +0930 Subject: [PATCH 091/110] Miscellaneous edits to JavaScript --- javascript.html.markdown | 69 ++++++++++++++++++++++++++++------------ 1 file changed, 48 insertions(+), 21 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 858cec52..f8dd2ab2 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -33,7 +33,7 @@ doStuff() * 1. Numbers, Strings and Operators ***********/ -// Javascript has one number type that covers ints and floats. +// Javascript has one number type, which is a 64-bit IEEE 754 double. 3 // = 3 1.5 // = 1.5 @@ -46,6 +46,10 @@ doStuff() // Including uneven division. 5 / 2 // = 2.5 +// Bitwise operations also work; when you perform a bitwise operation your float +// is converted to a signed int *up to* 32 bits. +1 << 2 // = 4 + // Enforce precedence with parentheses (1 + 3) * 2 // = 8 @@ -165,7 +169,7 @@ if (count == 3){ } else if (count == 4) { // evaluated if count is 4 } else { - // evaluated if it's not either + // evaluated if it's not either 3 or 4 } // As does while. @@ -179,7 +183,8 @@ do { input = getInput() } while (!isValid(input)) -// the for loop is the same as C and Java: initialisation; test; iteration. +// the for loop is the same as C and Java: +// initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times } @@ -192,8 +197,8 @@ if (colour == "red" || colour == "blue"){ // colour is either red or blue } -// && and || "short circuit", which is useful for setting default values... -var name = otherName || "default"; +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default" /*********** * 5. Functions, Scope and Closures @@ -280,41 +285,63 @@ myObj.myBoolean // = true myPrototype.meaningOfLife = 43 myObj.meaningOfLife // = 43 -// While the __proto__ magic property we've seen so far is useful for -// explaining prototypes, it's non-standard. There's no standard way to change -// an existing object's prototype, but there's two ways to set the prototype of -// a new object when you first create it. +// We mentioned that __proto__ was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there's two ways to +// create a new object with a given prototype. // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. var myObj = Object.create(myPrototype) myObj.meaningOfLife // = 43 -// Unfortunately, Object.create is quite recent and isn't available in many -// browsers, so you often can't use that, either. The most reliable way to set -// prototypes involves constructors. +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// the constructor function itself; instead, it's the prototype that new objects +// are given when they're created with that constructor and the new keyword. +myConstructor.prototype = { + getMyNumber: function(){ + return self.myNumber + } +} +var myNewObj2 = new myConstructor() +myNewObj2.getMyNumber() // = 5 -// TODO: write about the .prototype property on constructors +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +var myNumber = 12 +var myNumberObj = new Number(12) +myNumber == myNumberObj // = true -// Built-in types' prototypes work like this too, so you can actually change -// the prototype of a string, for instance. +// Except, they aren't exactly equivalent. +typeof(myNumber) // = 'number' +typeof(myNumberObj) // = 'object' +myNumber === myNumberObj // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0) } "abc".firstCharacter() // = "a" -// There are several implementations of JavaScript, which all gain new features -// at different times. Sometimes, however, it's possible to replicate new -// features by altering built in types or prototypes, which is called -// "polyfilling". +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. // For instance, we mentioned that Object.create isn't yet available in all -// implementations, but we can still use it if we do this: -if (Object.create === undefined){ +// implementations, but we can still use it with this polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists Object.create = function(proto){ // make a temporary constructor with the right prototype var Constructor = function(){} Constructor.prototype = proto + // then use it to create a new, appropriately-prototyped object return new Constructor() } } From bc6b91a43fcd965a471724a6ee946f0f87d5d5af Mon Sep 17 00:00:00 2001 From: Paolo Mainardi Date: Wed, 3 Jul 2013 13:31:09 +0200 Subject: [PATCH 092/110] Ternary operator example --- php.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 75bbd214..f0c5c918 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -231,6 +231,9 @@ if (false) { print 'Does'; } +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + $x = 0; if ($x === '0') { print 'Does not print'; @@ -240,6 +243,8 @@ if ($x === '0') { print 'Does print'; } + + // This alternative syntax is useful for templates: ?> From aa66a13d49f4e2ccfad3d29e427527c94b191064 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 08:49:29 -0700 Subject: [PATCH 093/110] Small fix in python --- python.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index ff77fac6..e0851950 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -328,7 +328,8 @@ def add(x, y): return x + y # Return values with a return statement # Calling functions with parameters -add(5, 6) #=> 11 and prints out "x is 5 and y is 6" +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. From 99192fea522aa80ec01aeb7d4e570ee24088981b Mon Sep 17 00:00:00 2001 From: David Underwood Date: Wed, 3 Jul 2013 15:21:29 -0400 Subject: [PATCH 094/110] Adds class documentation written by @joelwalden in #95 --- ruby.html.markdown | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 62db549c..7863ebd2 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -251,4 +251,56 @@ surround { puts 'hello world' } # { # hello world # } + + +# Define a class with the class keyword +class Human + + # A class variable. It is shared by all instances of this class. + @@species = "H. sapiens" + + # Basic initializer + def initialize(name, age=0): + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end + + # Basic setter method + def name=(name) + @name = name + end + + # Basic getter method + def name + @name + end + + # A class method; uses self to distinguish from instance methods. (Can only be called on class, not an instance). + + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end + +end + + +# Instantiate a class +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# Let's call a couple of methods +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Call the class method +Human.say("Hi") #=> "Hi" ``` \ No newline at end of file From 2419d8c30aada12c72f0c7ee36db58298263e110 Mon Sep 17 00:00:00 2001 From: David Underwood Date: Wed, 3 Jul 2013 15:39:43 -0400 Subject: [PATCH 095/110] Updates YAML front-matter to match #97 --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 7863ebd2..2de134ae 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -1,7 +1,7 @@ --- language: ruby -author: David Underwood -author_url: http://theflyingdeveloper.com +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] --- ```ruby From 2954fc9bb5767c39f99b08acce5d5220d68c0c90 Mon Sep 17 00:00:00 2001 From: Adel Qalieh Date: Wed, 3 Jul 2013 18:20:03 -0400 Subject: [PATCH 096/110] Fix grammatical errors --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 463556d9..4419bbea 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -5,7 +5,7 @@ author_url: http://ldinh.ca --- Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular -languages in existence. I fell in love with Python for it's syntactic clarity. It's basically +languages in existence. I fell in love with Python for its syntactic clarity. Its basically executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] From 6be90f117b87e20f742cec382728142377847ba5 Mon Sep 17 00:00:00 2001 From: ilyagr Date: Wed, 3 Jul 2013 17:22:49 -0700 Subject: [PATCH 097/110] Update haskell.html.markdown Fixed unmatched parentheses --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 840569fb..e8d7c077 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -269,7 +269,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- This is now the same as -(2 * 3 + (2 * 2 + (2 * 1 + 4) +(2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- -- 7. Data Types From 3308c9c015e130b4e813f998898852d9fc2d7e05 Mon Sep 17 00:00:00 2001 From: sergiokas Date: Wed, 3 Jul 2013 23:57:37 -0300 Subject: [PATCH 098/110] Adding small function pointers example --- c.html.markdown | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index 69bf099e..fba587fc 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -323,6 +323,30 @@ str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ +/* +Functions are located in known memory addresses, so they can be called +through function pointers. Syntax may be initially confusing. + +Example: use str_reverse from a pointer +*/ +void str_reverse_through_pointer(char * str_in) { + // Define a function pointer variable, named f. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at runtime) + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternate but equally valid syntax for calling it. +} + +/* +As long as function signatures match, you can assign any function to the same pointer. +Useful for passing handlers (or callback functions) around. +Function pointers are usually typedef'd for simplicity and readability, as follows: + +typedef void (*my_fnp_type)(char *); +... +my_fnp_type f; +*/ + /////////////////////////////////////// // User-defined types and structs /////////////////////////////////////// From 0376e0807a796b9c38285e908589b8ef3f2ded21 Mon Sep 17 00:00:00 2001 From: sergiokas Date: Thu, 4 Jul 2013 00:00:49 -0300 Subject: [PATCH 099/110] Update c.html.markdown --- c.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index fba587fc..23d97560 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -341,11 +341,14 @@ void str_reverse_through_pointer(char * str_in) { As long as function signatures match, you can assign any function to the same pointer. Useful for passing handlers (or callback functions) around. Function pointers are usually typedef'd for simplicity and readability, as follows: +*/ typedef void (*my_fnp_type)(char *); -... -my_fnp_type f; -*/ + +// The used when declaring the actual pointer variable: +// ... +// my_fnp_type f; + /////////////////////////////////////// // User-defined types and structs From fbd54a79a8971454886f0390af3663e5b2d657bb Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 22:52:48 -0700 Subject: [PATCH 100/110] Merged haskell changes from ilyagr --- haskell.html.markdown | 87 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 16 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index e8d7c077..e50602ac 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -11,7 +11,7 @@ makes coding a real joy for me. ```haskell -- Single line comments start with two dashes. {- Multiline comments can be enclosed -in a block like this. +en a block like this. -} ---------------------------------------------------- @@ -281,10 +281,11 @@ data Color = Red | Blue | Green -- Now you can use it in a function: -say :: Color -> IO String -say Red = putStrLn "You are Red!" -say Blue = putStrLn "You are Blue!" -say Green = putStrLn "You are Green!" + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" -- Your data types can have parameters too: @@ -302,26 +303,72 @@ Just 1 -- While IO can't be explained fully without explaining monads, -- it is not hard to explain enough to get going. --- An `IO a` value is an IO action: you can chain them with do blocks +-- When a Haskell program is executed, the function `main` is +-- called. It must return a value of type `IO ()`. For example: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn has type String -> IO () + +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function +-- interact :: (String -> String) -> IO () +-- inputs some text, runs a function on it, and prints out the +-- output. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- You can think of a value of type `IO ()` as representing a +-- sequence of actions for the computer to do, much like a +-- computer program written in an imperative language. We can use +-- the `do` notation to chain actions together. For example: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- this gets a line and gives it the name "input" + putStrLn $ "Hello, " ++ name + +-- Exercise: write your own version of `interact` that only reads +-- one line of input. + +-- The code in `sayHello` will never be executed, however. The only +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` +-- and replace it with: +-- main = sayHello + +-- Let's understand better how the function `getLine` we just +-- used works. Its type is: +-- getLine :: IO String +-- You can think of a value of type `IO String` as representing a +-- computer program that will generate a value of type `String` +-- when executed (in addition to anything else it does). We can +-- store and reuse this value using `<-`. We can also +-- make our own action of type `IO String`: + action :: IO String action = do putStrLn "This is a line. Duh" - input <- getLine -- this gets a line and gives it the name "input" + input1 <- getLine input2 <- getLine - return (input1 ++ "\n" ++ input2) -- This is the result of the whole action + -- The type of the `do` statement is that of its last line. + -- `return` is not a keyword, but merely a function + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- This didn't actually do anything. When a haskell program is executed --- an IO action called "main" is read and interpreted. +-- We can use this just like we used `getLine`: -main = do - putStrLn "Our first program. How exciting!" - result <- action -- our defined action is just like the default ones +main'' = do + putStrLn "I will echo two lines!" + result <- action putStrLn result putStrLn "This was all, folks!" --- Haskell does IO through a monad because this allows it to be a purely --- functional language. Our `action` function had a type signature of `IO String`. --- In general any function that interacts with the outside world (i.e. does IO) +-- The type `IO` is an example of a "monad". The way Haskell uses a monad to do IO allows it to +-- be a purely functional language. Any function that interacts with the outside world (i.e. does IO) -- gets marked as `IO` in its type signature. This lets us reason about what -- functions are "pure" (don't interact with the outside world or modify state) -- and what functions aren't. @@ -344,6 +391,14 @@ let foo = 5 >:t foo foo :: Integer + +-- You can also run any action of type `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + ``` There's a lot more to Haskell, including typeclasses and monads. These are the big ideas that make Haskell such fun to code in. I'll leave you with one final Haskell example: an implementation of quicksort in Haskell: From 3840036912bc8e5a31b45cfa6ef7eae993e7464b Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 22:53:12 -0700 Subject: [PATCH 101/110] Ruby updates --- ruby.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 2de134ae..4c41b133 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -2,6 +2,7 @@ language: ruby contributors: - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] --- ```ruby @@ -154,7 +155,7 @@ new_hash = { defcon: 3, action: true} new_hash.keys #=> [:defcon, :action] # Tip: Both Arrays and Hashes are Enumerable -# This means they share a lot of useful methods such as each, map, count, and more +# They share a lot of useful methods such as each, map, count, and more # Control structures @@ -277,8 +278,8 @@ class Human @name end - # A class method; uses self to distinguish from instance methods. (Can only be called on class, not an instance). - + # A class method uses self to distinguish from instance methods. + $ It can only be called on the class, not an instance. def self.say(msg) puts "#{msg}" end @@ -303,4 +304,4 @@ dwight.name #=> "Dwight K. Schrute" # Call the class method Human.say("Hi") #=> "Hi" -``` \ No newline at end of file +``` From 9ad61b5586993bda1eebd70a8dd4c721db83a396 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 22:59:13 -0700 Subject: [PATCH 102/110] Authors -> Contributors --- c.html.markdown | 4 ++-- clojure.html.markdown | 4 ++-- dart.html.markdown | 4 ++-- elixir.html.markdown | 4 ++-- erlang.html.markdown | 4 ++-- fsharp.html.markdown | 4 ++-- haskell.html.markdown | 4 ++-- java.html.markdown | 7 ++----- julia.html.markdown | 4 ++-- lua.html.markdown | 4 ++-- php.html.markdown | 4 ++-- python.html.markdown | 4 ++-- r.html.markdown | 4 ++-- ruby.html.markdown | 1 + 14 files changed, 27 insertions(+), 29 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 69bf099e..8786aa85 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -1,8 +1,8 @@ --- language: c -author: Adam Bard -author_url: http://adambard.com/ filename: learnc.c +contributors: + - ["Adam Bard", "http://adambard.com/"] --- Ah, C. Still the language of modern high-performance computing. diff --git a/clojure.html.markdown b/clojure.html.markdown index 39a27bcf..6baae0ce 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -1,8 +1,8 @@ --- language: clojure -author: Adam Bard -author_url: http://adambard.com/ filename: learnclojure.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] --- Clojure is a Lisp family language developed for the Java Virtual Machine. It has diff --git a/dart.html.markdown b/dart.html.markdown index 27365746..34d1c6a8 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -1,8 +1,8 @@ --- language: dart -author: Joao Pedrosa -author_url: https://github.com/jpedrosa/ filename: learndart.dart +contributors: + - ["Joao Pedrosa", "https://github.com/jpedrosa/"] --- Dart is a newcomer into the realm of programming languages. diff --git a/elixir.html.markdown b/elixir.html.markdown index 2e9aa5a1..3a11ce1f 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -1,7 +1,7 @@ --- language: elixir -author: Joao Marques -author_url: http://github.com/mrshankly +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] filename: learnelixir.ex --- diff --git a/erlang.html.markdown b/erlang.html.markdown index 42d0b809..208f31e4 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -1,7 +1,7 @@ --- language: erlang -author: Giovanni Cappellotto -author_url: http://www.focustheweb.com/ +contributor: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] filename: learnerlang.erl --- diff --git a/fsharp.html.markdown b/fsharp.html.markdown index b1860372..49951c78 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -1,7 +1,7 @@ --- language: F# -author: Scott Wlaschin -author_url: http://fsharpforfunandprofit.com/ +contributors: + - ["Scott Wlaschin", "http://fsharpforfunandprofit.com/"] filename: learnfsharp.fs --- diff --git a/haskell.html.markdown b/haskell.html.markdown index e50602ac..4d5ce642 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -1,7 +1,7 @@ --- language: haskell -author: Adit Bhargava -author_url: http://adit.io +contributors: + - ["Adit Bhargava", "http://adit.io"] --- Haskell was designed as a practical, purely functional programming language. It's famous for diff --git a/java.html.markdown b/java.html.markdown index 8ba48d73..785a2cb9 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,11 +1,8 @@ --- language: java - -author: Jake Prather - -author_url: http://github.com/JakeHP - +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] filename: LearnJava.java --- diff --git a/julia.html.markdown b/julia.html.markdown index 6c719b5c..1023e303 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -1,7 +1,7 @@ --- language: julia -author: Leah Hanson -author_url: http://leahhanson.us +contributors: + - ["Leah Hanson", "http://leahhanson.us"] filename: learnjulia.jl --- diff --git a/lua.html.markdown b/lua.html.markdown index 4df57a92..0ece399f 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -1,7 +1,7 @@ --- language: lua -author: Tyler Neylon -author_url: http://tylerneylon.com/ +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] filename: learnlua.lua --- diff --git a/php.html.markdown b/php.html.markdown index f0c5c918..a20e1d11 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -1,7 +1,7 @@ --- language: php -author: Malcolm Fell -author_url: http://emarref.net/ +contributors: + - ["Malcolm Fell", "http://emarref.net/"] filename: learnphp.php --- diff --git a/python.html.markdown b/python.html.markdown index fe8a204c..e7ee6fbd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -1,7 +1,7 @@ --- language: python -author: Louie Dinh -author_url: http://ldinh.ca +contributors: + - ["Louie Dinh", "http://ldinh.ca"] filename: learnpython.py --- diff --git a/r.html.markdown b/r.html.markdown index 535b9065..0240e8fb 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -1,7 +1,7 @@ --- language: R -author: e99n09 -author_url: http://github.com/e99n09 +contributors: + - ["e99n09", "http://github.com/e99n09"] filename: learnr.r --- diff --git a/ruby.html.markdown b/ruby.html.markdown index 4c41b133..bf57a816 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -1,5 +1,6 @@ --- language: ruby +filename: learnruby.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] From 8b536513d786d79fd95b7b0eb6a505dc71ed9604 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 23:01:47 -0700 Subject: [PATCH 103/110] Edit for line length --- haskell.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 4d5ce642..11109ab8 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -367,14 +367,14 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- The type `IO` is an example of a "monad". The way Haskell uses a monad to do IO allows it to --- be a purely functional language. Any function that interacts with the outside world (i.e. does IO) --- gets marked as `IO` in its type signature. This lets us reason about what --- functions are "pure" (don't interact with the outside world or modify state) --- and what functions aren't. +-- The type `IO` is an example of a "monad". The way Haskell uses a monad to +-- do IO allows it to be a purely functional language. Any function that +-- interacts with the outside world (i.e. does IO) gets marked as `IO` in its +-- type signature. This lets us reason about what functions are "pure" (don't +-- interact with the outside world or modify state) and what functions aren't. --- This is a powerful feature, because it's easy to run pure functions concurrently --- so concurrency in Haskell is very easy. +-- This is a powerful feature, because it's easy to run pure functions +-- concurrently; so, concurrency in Haskell is very easy. ---------------------------------------------------- From 54772928244b17315aee7f252ad2c491fa5f55d5 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 3 Jul 2013 23:03:25 -0700 Subject: [PATCH 104/110] Line length edit for ruby --- ruby.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index bf57a816..2c9a4cb9 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -92,8 +92,9 @@ path_to_project_root = '/good/name/' path = '/bad/name/' # Symbols (are objects) -# Symbols are immutable, reusable constants represented internally by an integer value -# They're often used instead of strings to efficiently convey specific, meaningful values +# Symbols are immutable, reusable constants represented internally by an +# integer value. They're often used instead of strings to efficiently convey +# specific, meaningful values :pending.class #=> Symbol From 3c48fae101bd4c0b1d8db2d7ca2445e04f64ab00 Mon Sep 17 00:00:00 2001 From: ilyagr Date: Wed, 3 Jul 2013 23:12:53 -0700 Subject: [PATCH 105/110] Update haskell.html.markdown Minor improvements to polymorphic types --- haskell.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 11109ab8..34df4d08 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -292,9 +292,9 @@ say Green = "You are Green!" data Maybe a = Nothing | Just a -- These are all of type Maybe -Nothing -Just "hello" -Just 1 +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` ---------------------------------------------------- -- 8. Haskell IO @@ -344,8 +344,8 @@ sayHello = do -- Let's understand better how the function `getLine` we just -- used works. Its type is: -- getLine :: IO String --- You can think of a value of type `IO String` as representing a --- computer program that will generate a value of type `String` +-- You can think of a value of type `IO a` as representing a +-- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can -- store and reuse this value using `<-`. We can also -- make our own action of type `IO String`: From 80c16770cdfadb84be0c08dbc4e2a7ff7e274745 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 4 Jul 2013 19:49:24 +0930 Subject: [PATCH 106/110] Added 'functions, scope and closures' section --- javascript.html.markdown | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index f8dd2ab2..bdb386f7 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -204,6 +204,71 @@ var name = otherName || "default" * 5. Functions, Scope and Closures ***********/ +// JavaScript functions are declared with the function keyword. +function myFunction(thing){ + return thing.toUpperCase() +} +myFunction("foo") // = "FOO" + +// Functions can also be defined "anonymously" - without a name: +function(thing){ + return thing.toLowerCase() +} +// (we can't call our function, since we don't have a name to refer to it with) + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000) + +// You can even write the function statement directly in the call to the other +// function. + +setTimeout(function myFunction(){ + // this code will be called in 5 seconds' time +}, 5000) + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5 +} +i // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +function(){ + var temporary = 5 + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10 + // Or, as previously mentioned, we can just leave the var keyword off. + permanent2 = 15 +}() +temporary // raises ReferenceError +permanent // = 10 +permanent2 // = 15 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!" + function inner(){ + alert(prompt) + } + setTimeout(inner, 5000) + // setTimeout is asynchronous, so this function will finish without waiting + // 5 seconds. However, once the 5 seconds is up, inner will still have + // access to the value of prompt. +} +sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s + /*********** * 6. More about Objects; Constructors and Prototypes ***********/ From 8120eb7ff0c8e96ffe72e299ec02ad6426505835 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 4 Jul 2013 19:49:35 +0930 Subject: [PATCH 107/110] Miscellaneous additions --- javascript.html.markdown | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index bdb386f7..9a51e32a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -10,6 +10,10 @@ Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. +JavaScript isn't just limited to web browsers, though: Node.js, a project that +provides a standalone runtime for Google Chrome's V8 JavaScript engine, is +becoming more and more popular. + Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or [adam@brenecki.id.au](mailto:adam@brenecki.id.au). @@ -33,7 +37,7 @@ doStuff() * 1. Numbers, Strings and Operators ***********/ -// Javascript has one number type, which is a 64-bit IEEE 754 double. +// Javascript has one number type (which is a 64-bit IEEE 754 double). 3 // = 3 1.5 // = 1.5 @@ -50,7 +54,7 @@ doStuff() // is converted to a signed int *up to* 32 bits. 1 << 2 // = 4 -// Enforce precedence with parentheses +// Precedence is enforced with parentheses. (1 + 3) * 2 // = 8 // There are three special not-a-real-number values: @@ -420,6 +424,14 @@ excellent documentation for JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you can help others out by sharing your own knowledge. +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +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) + In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) From fff3f61e2c64745eb4404ccaf582730e218043cf Mon Sep 17 00:00:00 2001 From: sergiokas Date: Thu, 4 Jul 2013 11:42:36 -0300 Subject: [PATCH 108/110] #102, moving function pointers section to the end of the doc --- c.html.markdown | 57 ++++++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 23d97560..f5f28608 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -323,33 +323,6 @@ str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ -/* -Functions are located in known memory addresses, so they can be called -through function pointers. Syntax may be initially confusing. - -Example: use str_reverse from a pointer -*/ -void str_reverse_through_pointer(char * str_in) { - // Define a function pointer variable, named f. - void (*f)(char *); // Signature should exactly match the target function. - f = &str_reverse; // Assign the address for the actual function (determined at runtime) - (*f)(str_in); // Just calling the function through the pointer - // f(str_in); // That's an alternate but equally valid syntax for calling it. -} - -/* -As long as function signatures match, you can assign any function to the same pointer. -Useful for passing handlers (or callback functions) around. -Function pointers are usually typedef'd for simplicity and readability, as follows: -*/ - -typedef void (*my_fnp_type)(char *); - -// The used when declaring the actual pointer variable: -// ... -// my_fnp_type f; - - /////////////////////////////////////// // User-defined types and structs /////////////////////////////////////// @@ -390,6 +363,36 @@ int area(rect r){ return r.width * r.height; } +/////////////////////////////////////// +// Function pointers +/////////////////////////////////////// +/* +At runtime, functions are located at known memory addresses. Function pointers are +much likely any other pointer (they just store a memory address), but can be used +to invoke functions directly, and to pass handlers (or callback functions) around. +However, definition syntax may be initially confusing. + +Example: use str_reverse from a pointer +*/ +void str_reverse_through_pointer(char * str_in) { + // Define a function pointer variable, named f. + void (*f)(char *); // Signature should exactly match the target function. + f = &str_reverse; // Assign the address for the actual function (determined at runtime) + (*f)(str_in); // Just calling the function through the pointer + // f(str_in); // That's an alternative but equally valid syntax for calling it. +} + +/* +As long as function signatures match, you can assign any function to the same pointer. +Function pointers are usually typedef'd for simplicity and readability, as follows: +*/ + +typedef void (*my_fnp_type)(char *); + +// The used when declaring the actual pointer variable: +// ... +// my_fnp_type f; + ``` ## Further Reading From 36f0eeac14a0f6207cc164472b51cb19aa326a59 Mon Sep 17 00:00:00 2001 From: Adam Date: Thu, 4 Jul 2013 09:24:21 -0700 Subject: [PATCH 109/110] Minor edits to javascript --- javascript.html.markdown | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 9a51e32a..254163e8 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -18,7 +18,7 @@ Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or [adam@brenecki.id.au](mailto:adam@brenecki.id.au). -```javascript +```js // Comments are like C. Single-line comments start with two slashes, /* and multiline comments start with slash-star and end with star-slash */ @@ -33,9 +33,8 @@ doStuff() // We'll leave semicolons off here; whether you do or not will depend on your // personal preference or your project's style guide. -/*********** - * 1. Numbers, Strings and Operators - ***********/ +/////////////////////////////////// +// 1. Numbers, Strings and Operators // Javascript has one number type (which is a 64-bit IEEE 754 double). 3 // = 3 @@ -110,9 +109,8 @@ undefined // used to indicate a value that hasn't been set yet // null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". -/*********** - * 2. Variables, Arrays and Objects - ***********/ +/////////////////////////////////// +// 2. Variables, Arrays and Objects // Variables are declared with the var keyword. Javascript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. @@ -162,9 +160,8 @@ myObj.myThirdKey = true // If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey // = undefined -/*********** - * 3. Logic and Control Structures - ***********/ +/////////////////////////////////// +// 3. Logic and Control Structures // The if structure works as you'd expect. var count = 1 @@ -204,9 +201,8 @@ if (colour == "red" || colour == "blue"){ // && and || "short circuit", which is useful for setting default values. var name = otherName || "default" -/*********** - * 5. Functions, Scope and Closures - ***********/ +/////////////////////////////////// +// 4. Functions, Scope and Closures // JavaScript functions are declared with the function keyword. function myFunction(thing){ @@ -273,9 +269,8 @@ function sayHelloInFiveSeconds(name){ } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s -/*********** - * 6. More about Objects; Constructors and Prototypes - ***********/ +/////////////////////////////////// +// 5. More about Objects; Constructors and Prototypes // Objects can contain functions. var myObj = { From c14253f70896c7815e0a78984b5129e5b434c86a Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Thu, 4 Jul 2013 20:18:42 -0500 Subject: [PATCH 110/110] annotations explanation --- java.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 785a2cb9..418bd649 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -337,6 +337,8 @@ class PennyFarthing extends Bicycle { } // You should mark a method you're overriding with an @annotation + // To learn more about what annotations are and their purpose + // check this out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { gear = 0;