From 6cfb00d10650c46508703d4356dddeccacb70e03 Mon Sep 17 00:00:00 2001 From: Nick Presta Date: Fri, 28 Jun 2013 18:34:30 -0400 Subject: 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 -- cgit v1.2.3 From 6e3e27345103147c37954fe7b9e3976709548456 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 08:52:41 -0700 Subject: A few fixes --- dart.html.markdown | 2 +- r.html.markdown | 26 +++++++++++++------------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index d064dc7d..c503fb4a 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -1,5 +1,5 @@ --- -language: Dart +language: dart author: Joao Pedrosa author_url: https://github.com/jpedrosa/ --- diff --git a/r.html.markdown b/r.html.markdown index ad2a4559..1ace3ed5 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -7,7 +7,7 @@ author_url: http://github.com/e99n09 R is a statistical computing language. -```r +```python # Comments start with hashtags. @@ -16,9 +16,9 @@ R is a statistical computing language. # Protip: hit COMMAND-ENTER to execute a line -################################################################################### +######################### # The absolute basics -################################################################################### +######################### # NUMERICS @@ -119,9 +119,9 @@ myFunc <- function(x) { # Called like any other R function: myFunc(5) # => [1] 19 -################################################################################### +######################### # Fun with data: vectors, matrices, data frames, and arrays -################################################################################### +######################### # ONE-DIMENSIONAL @@ -243,7 +243,7 @@ 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))) # generate random +list1 <- list(time = 1:40, price = c(rnorm(40,.5*list1$time,4))) # random list1 # You can get items in the list like so @@ -251,9 +251,9 @@ list1$time # You can subset list items like vectors list1$price[4] -################################################################################### +######################### # The apply() family of functions -################################################################################### +######################### # Remember mat? mat @@ -281,9 +281,9 @@ install.packages("plyr") require(plyr) ?plyr -################################################################################### +######################### # Loading data -################################################################################### +######################### # "pets.csv" is a file on the internet pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") @@ -292,14 +292,14 @@ head(pets, 2) # first two rows tail(pets, 1) # last row # To save a data frame or matrix as a .csv file -write.csv(pets, "pets2.csv") # to make a new .csv file in the working directory +write.csv(pets, "pets2.csv") # to make a new .csv file # set working directory with setwd(), look it up with getwd() # Try ?read.csv and ?write.csv for more information -################################################################################### +######################### # Plots -################################################################################### +######################### # Scatterplots! plot(list1$time, list1$price, main = "fake data") -- cgit v1.2.3 From 2669bc8ff63e1efa26ccb372c02b9453e0c4cb02 Mon Sep 17 00:00:00 2001 From: Jakehp Date: Sat, 29 Jun 2013 12:12:23 -0500 Subject: 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. -- cgit v1.2.3 From d32bad8aed47e58c4f675d9487537ac42d54004e Mon Sep 17 00:00:00 2001 From: Jakehp Date: Sat, 29 Jun 2013 12:46:34 -0500 Subject: up --- java.html.markdown | 49 +++++++++++++++++-------------------------------- 1 file changed, 17 insertions(+), 32 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. - -// 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; +// 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 -- cgit v1.2.3 From 03461ad0dec6cf8a2f44c6ddbc40d2bb381d2253 Mon Sep 17 00:00:00 2001 From: Leah Hanson Date: Sat, 29 Jun 2013 16:21:55 -0400 Subject: tiny typo fix in python we -> be --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 2b67ab83..eddff031 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -15,7 +15,7 @@ to Python 2.x. Look for another tour of Python 3 soon! ```python # Single line comments start with a hash. -""" Multiline strings can we written +""" Multiline strings can be written using three "'s, and are often used as comments """ -- cgit v1.2.3 From 7e4bd6d17e2003b0f5fd2fe6859c722a72c4acc3 Mon Sep 17 00:00:00 2001 From: noahlz Date: Sat, 29 Jun 2013 17:17:52 -0400 Subject: Fix issue #50 --- haskell.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/haskell.html.markdown b/haskell.html.markdown index 563674c9..45cfb819 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -104,6 +104,10 @@ snd ("haskell", 1) -- 1 -- A simple function that takes two variables add a b = a + b +-- Note that if you are using ghci (the Haskell interpreter) +-- You'll need to use `let`, i.e. +-- let add a b = a + b + -- Using the function add 1 2 -- 3 -- cgit v1.2.3 From 4d0576490a78b290527919775eb1b5f96f05607a Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 14:34:54 -0700 Subject: Massive edit on PHP --- php.html.markdown | 576 +++++++++++++++++++++++++++--------------------------- 1 file changed, 284 insertions(+), 292 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 339499eb..1a8dea2c 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -6,15 +6,8 @@ author_url: http://emarref.net/ This document describes PHP 5+. -## [Basic Syntax](http://www.php.net/manual/en/language.basic-syntax.php) - -All statements must end with a semi-colon; All PHP code must be between tags. PHP can also be -configured to respect the [short open tags](http://www.php.net/manual/en/ini.core.php#ini.short-open-tag) . - -## [Comments](http://www.php.net/manual/en/language.basic-syntax.comments.php) - ```php - tags // Two forward slashes start a one-line comment. @@ -24,27 +17,36 @@ configured to respect the [short open tags](http://www.php.net/manual/en/ini.cor Surrounding text in slash-asterisk and asterisk-slash makes it a multi-line comment. */ -``` - -## [Types](http://www.php.net/manual/en/language.types.php) -Types are [weakly typed](http://en.wikipedia.org/wiki/Strong_and_weak_typing) and begin with the $ symbol. -A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. +// Use "echo" or "print" to print output +print('Hello '); // Prints "Hello " with no line break -### Scalars +// () are optional for print and echo +echo 'World\n'; // Prints "World" with a line break +// (all statements must end with a semicolon) -```php +// Anything outside Hello World Again! 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) $float = 1.234; @@ -52,28 +54,30 @@ $float = 1.2e3; $float = 7E-10; // Arithmetic -$sum = $number + $float; -$difference = $number - $float; -$product = $number * $float; -$quotient = $number / $float; +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 // Shorthand arithmetic +$number = 0; $number += 1; // Add 1 to $number -$number++; // Add 1 to $number after it is used -++$number; // Add 1 to $number before it is used. -$number /= $float // Divide and assign the quotient to $number +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' -// Escape special characters with backslash +// Special characters are only escaped in double quotes $escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; // Enclose a variable in curly braces if needed -$money = "I have $${integer} in the bank." +$money = "I have $${number} in the bank."; // Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners $nowdoc = <<<'END' @@ -81,35 +85,40 @@ Multi line string END; +// Heredocs will do string interpolation $heredoc = << 1, "Two" => 2, "Three" => 3]; -$associative["One"]; // Holds the value 1 -``` -## Output +// Works with all PHP versions +$associative = array('One' => 1, 'Two' => 2, 'Three' => 3); -```php - 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints "1" + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + + +/******************************** + * Output + */ echo('Hello World!'); // Prints Hello World! to stdout. @@ -121,133 +130,127 @@ print('Hello World!'); // The same as echo echo 'Hello World!'; print 'Hello World!'; // So is print +$paragraph = 'paragraph'; + echo 100; -echo $variable; -echo function_result(); +echo $paragraph; // If short open tags are configured, or your PHP version is // 5.4.0 or greater, you can use the short echo syntax - -``` - -## [Operators](http://www.php.net/manual/en/language.operators.php) - -### Assignment - -```php +?> +

2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 -```php - $b // TRUE if $a is not equal to $b after type juggling. -$a < $b // TRUE if $a is strictly less than $b. -$a > $b // TRUE if $a is strictly greater than $b. -$a <= $b // TRUE if $a is less than or equal to $b. -$a >= $b // TRUE if $a is greater than or equal to $b. +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; -// The following will only be true if the values match and are the same type. -$a === $b // TRUE if $a is equal to $b, and they are of the same type. -$a !== $b // TRUE if $a is not equal to $b, or they are not of the same type. -1 == '1' // TRUE -1 === '1' // FALSE -``` +// assert throws a warning if its argument is not true -## [Type Juggling](http://www.php.net/manual/en/language.types.type-juggling.php) +// 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($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); -Variables can be converted between types, depending on their usage. +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 == '1'); +assert(1 !== '1'); -```php - 2 $string = '1'; -echo $string + $string; -// Also outputs 2 because the + operator converts the strings to integers +echo $string + $string; // => 2 (strings are coerced to integers) $string = 'one'; -echo $string + $string; +echo $string + $string; // => 0 // Outputs 0 because the + operator cannot cast the string 'one' to a number -``` -Type casting can be used to treat a variable as another type temporarily by using cast operators in parentheses. +// Type casting can be used to treat a variable as another type -```php -$boolean = (boolean) $integer; // $boolean is true +$boolean = (boolean) 1; // => true $zero = 0; -$boolean = (boolean) $zero; // $boolean is false +$boolean = (boolean) $zero; // => false +// There are also dedicated functions for casting most types $integer = 5; $string = strval($integer); -// There are also dedicated functions for casting most types $var = null; // Null value -``` - -## [Control Structures](http://www.php.net/manual/en/language.control-structures.php) -### If Statements -```php - - + This is displayed if the test is truthy. This is displayed otherwise. -``` - -### Switch statements -```php 2, 'car' => 4]; -$wheels = ["bicycle" => 2, "car" => 4]; +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count){ + echo "$wheel_count"; +} // Prints "24" +echo "\n"; + +// You can iterate over the keys as well as the values foreach ($wheels as $vehicle => $wheel_count) { echo "A $vehicle has $wheel_count wheels"; } -// This loop will stop after outputting 2 +echo "\n"; + $i = 0; while ($i < 5) { - if ($i == 3) { - break; // Exit out of the while loop and continue. + if ($i === 3) { + break; // Exit out of the while loop } echo $i++; -} +}// Prints "012" -// This loop will output everything except 3 -$i = 0; -while ($i < 5) { - if ($i == 3) { +for($i = 0; $i < 5; $i++){ + if ($i === 3) { continue; // Skip this iteration of the loop } - echo $i++; -} -``` - -## Functions + echo $i; +} // Prints "0124" -Functions are created with the ```function``` keyword. -```php - "Hello" -A valid function name starts with a letter or underscore, followed by any -number of letters, numbers, or underscores. There are three ways to declare functions. +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. -### [User-defined](http://www.php.net/manual/en/functions.user-defined.php) - -```php - 5 +echo add(4, 2); // => 6 -// inner_function() does not exist and cannot be called until -// outer_function() is called -``` +// $result is not accessible outside the function +// print $result; // Gives a warning. -This enables [currying](http://en.wikipedia.org/wiki/Currying) in PHP. +// Since PHP 5.3 you can declare anonymous functions; +$inc = function($x){ + return $x + 1; +}; + +echo $inc(2); // => 3 -```php function foo ($x, $y, $z) { echo "$x - $y - $z"; } +// Functions can return functions function bar ($x, $y) { + // Use 'use' to bring in outside variables return function ($z) use ($x, $y) { foo($x, $y, $z); }; @@ -363,92 +358,77 @@ function bar ($x, $y) { $bar = bar('A', 'B'); $bar('C'); -``` - -### [Variable](http://www.php.net/manual/en/functions.variable-functions.php) -```php - 3 +// But, you should probably use anonymous functions instead. -$function_name(); // will execute the my_function_name() function -``` - -### [Anonymous](http://www.php.net/manual/en/functions.anonymous.php) +/******************************** + * Classes + */ -Similar to variable functions, functions may be anonymous. - -```php -instanceProp = $instanceProp; + } + // Methods are declared as functions inside a class + public function myMethod() { + print "MyClass"; } final function youCannotOverrideMe() { } public static function myStaticMethod() { + print "I am static"; } } -$cls = new MyClass(); // The parentheses are optional. +echo MyClass::MY_CONST; // Outputs "value"; +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs "I am static"; -echo MyClass::$staticVar; // Access to static vars +// Access class members using ->. +$my_class = new MyClass("An instance property"); // The parentheses are optional. +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" -echo $cls->property; // Access to properties -MyClass::myStaticMethod(); // myStaticMethod cannot be run on $cls -``` +// Extend classes using "extends" +class MyOtherClass extends MyClass{ + function printProtectedProperty(){ + echo $this->protprop; + } -PHP offers some [magic methods](http://www.php.net/manual/en/language.oop5.magic.php) for classes. + // Override a method + function myMethod() { + parent::myMethod(); + print " > MyOtherClass"; + } +} -```php -printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" -class MyClass { +final class YouCannotExtendMe { +} + +// You can use "magic methods" to create getters and setters +class MyMapClass { private $property; public function __get($key) @@ -462,16 +442,13 @@ class MyClass { } } -$x = new MyClass(); +$x = new MyMapClass(); echo $x->property; // Will use the __get() method $x->property = 'Something'; // Will use the __set() method -``` - -Classes can be abstract (using the ```abstract``` keyword), extend other classes (using the ```extends``` keyword) and -implement interfaces (using the ```implements``` keyword). An interface is declared with the ```interface``` keyword. -```php -myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + +/* +``` ```php myTraitMethod(); ``` ## More Information -- cgit v1.2.3 From 59d801c0dfda9a7ddf27261d8a6f7906b049de0a Mon Sep 17 00:00:00 2001 From: DR6 Date: Sat, 29 Jun 2013 23:10:47 +0100 Subject: Added IO to haskell's tutorial --- haskell.html.markdown | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 563674c9..fbaa93f2 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -259,7 +259,32 @@ Just "hello" Just 1 ---------------------------------------------------- --- 8. The Haskell REPL +-- 8. Haskell IO +---------------------------------------------------- + +-- 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 +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 + +-- This didn't actually do anything. When a haskell program is executed +-- an IO action called "main" is read and interprete + +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!" + + + +---------------------------------------------------- +-- 9. The Haskell REPL ---------------------------------------------------- -- Start the repl by typing `ghci`. -- cgit v1.2.3 From 0a65fd6171b7543b1f31e147d207b33504344a26 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 15:37:42 -0700 Subject: Updated clojure --- clojure.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 24250a87..c5298aab 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -59,10 +59,12 @@ and often automatically. (class false) ; Booleans are java.lang.Boolean (class nil); The "null" value is called nil -; If you want to create a literal list of data, use ' to make a "symbol" +; If you want to create a literal list of data, use ' to stop it from +; being evaluated '(+ 1 2) ; => (+ 1 2) +; (shorthand for (quote (+ 1 2)) -; You can eval symbols. +; You can eval a quoted list (eval '(+ 1 2)) ; => 3 ; Collections & Sequences -- cgit v1.2.3 From e8f407728da807cc22648f341c7fa337b973fb6f Mon Sep 17 00:00:00 2001 From: Malcolm Fell Date: Sun, 30 Jun 2013 13:13:25 +1200 Subject: Remove python as requested language from README --- README.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/README.markdown b/README.markdown index 3223a2bd..77e09abd 100644 --- a/README.markdown +++ b/README.markdown @@ -17,7 +17,6 @@ properly! The most requested languages are: * Scala -* Python * Javascript ... but there are many more requests to do "every language", so don't let that stop you. -- cgit v1.2.3 From 4b873348fce636644917b812fbf746f59b56bcc4 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:12:03 -0500 Subject: 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"); -} - -// 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, " + 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"); + } + } -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 -- cgit v1.2.3 From 83aeecb68a20751d09bb83793691f19a8dc97aa2 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:19:14 -0700 Subject: 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. -- cgit v1.2.3 From 6f08caf97867f20ac7f2f2dd1eb6b9f63835c80e Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:25:21 -0700 Subject: 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'; -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 + // 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). -- cgit v1.2.3 From 789cc2c2a7f77585792bd32ac5e06737891609b1 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 20:38:22 -0700 Subject: 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 { -- cgit v1.2.3 From 5b29da12e6d595bce088a8d25c956abbdb5fee7a Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:52:18 -0500 Subject: Update java.html.markdown --- java.html.markdown | 299 ++++++++++++++++++++--------------------------------- 1 file changed, 114 insertions(+), 185 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, " - - 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, " + // 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); - // 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, " + // For Loop + int i; + //for loop structure => for(;;) + for(i=0;i<100;i++){ + System.out.println(i); + } - 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" -*/ + // 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 + /////////////////////////////////////// -// User-defined types and structs +// Classes And Functions /////////////////////////////////////// -// 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; + // 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 - // 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; -} + + 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(); + 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 -- cgit v1.2.3 From c3df7c1c5358e34673264122f16ceaf5f17e236c Mon Sep 17 00:00:00 2001 From: Malcolm Fell Date: Sun, 30 Jun 2013 15:52:45 +1200 Subject: 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: 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 -- cgit v1.2.3 From 9c9f2c6b9a50ccc7a987d3c9bf6fd26bd1cc3d15 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:54:53 -0500 Subject: 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 -- cgit v1.2.3 From 0523de70a1335c036442863b6dc672d50157d66a Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sat, 29 Jun 2013 22:56:22 -0500 Subject: 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); } -- cgit v1.2.3 From 79c26e6679948063036675b132a409b855d43cf1 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Sat, 29 Jun 2013 21:35:11 -0700 Subject: 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. -- cgit v1.2.3 From ba55f6fcaadebbcd76501ab69b5be03a66d0460f Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 23:13:53 -0700 Subject: Fix whitespace --- java.html.markdown | 480 +++++++++++++++++++++++++-------------------------- python.html.markdown | 13 +- 2 files changed, 248 insertions(+), 245 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"); - } - } - - // 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; +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; 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 - - - 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); - } - } +// 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); + } +} ``` @@ -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 """ -- cgit v1.2.3 From 0615be257d5d3437e256be8de9ed5abac4315f02 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 29 Jun 2013 23:16:41 -0700 Subject: 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 { -- cgit v1.2.3 From 2008bcc258b899aae6d11033c1f28ef79db7ba42 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sun, 30 Jun 2013 07:50:04 -0500 Subject: 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 -- cgit v1.2.3 From 7ee4774f9b857f4d17fdcb086130bca862ae15f0 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Sun, 30 Jun 2013 10:03:42 -0700 Subject: 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. ---------------------------------------------------- -- cgit v1.2.3 From fbe0fb471896e55c40d734b082f5e994e6dc775d Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Sun, 30 Jun 2013 12:17:19 -0500 Subject: 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 | 377 ++++++++++++++++++++++++++++------------------------- 1 file changed, 200 insertions(+), 177 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 - - -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; - } + // 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 + +// 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 { + + // 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; + } - public void setGear(int newValue) { - gear = newValue; - } + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear) { + gear = startGear; + cadence = startCadence; + speed = startSpeed; + } - public void applyBrake(int decrement) { - speed -= decrement; - } + // the Bicycle class has + // four functions/methods + public void setCadence(int newValue) { + cadence = newValue; + } - public void speedUp(int increment) { - speed += increment; - } + public void setGear(int newValue) { + gear = newValue; + } -} + public void applyBrake(int decrement) { + speed -= decrement; + } -//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 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 } ``` -- cgit v1.2.3 From bc0f1fca6c5f248257993e7bc80bf2d54652b7aa Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 30 Jun 2013 14:50:51 -0700 Subject: 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 -- cgit v1.2.3 From 77672e78916c4d35a67934b6c78e20b015ec687a Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:16:55 -0700 Subject: 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): -- cgit v1.2.3 From ae5060a4bf432095539bc3ff77bfec67082cbbb3 Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:35:20 -0700 Subject: 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/) -- cgit v1.2.3 From 34a9f1aab1b35258c56e46b858f6b1e7a7f8e28b Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:36:37 -0700 Subject: 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/) -- cgit v1.2.3 From 868b259db1e74010ded00c7020d8800255c4034d Mon Sep 17 00:00:00 2001 From: ldinh Date: Sun, 30 Jun 2013 15:47:56 -0700 Subject: 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/) -- cgit v1.2.3 From 4d501a48fcd4d0f5e64f55a0a962b5e4302272a4 Mon Sep 17 00:00:00 2001 From: lodin Date: Sun, 30 Jun 2013 16:02:37 -0700 Subject: 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/) -- cgit v1.2.3 From ec6ffed3c92928bc86424ae9f2ea6d1e02bbbc03 Mon Sep 17 00:00:00 2001 From: lodin Date: Sun, 30 Jun 2013 16:18:20 -0700 Subject: 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/) -- cgit v1.2.3 From 1193d43e89326feb150d7f7c0e8d03428115c80b Mon Sep 17 00:00:00 2001 From: Alexander Kahl Date: Mon, 1 Jul 2013 13:58:34 +0200 Subject: 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. -- cgit v1.2.3 From 2d6ed6d0832b12b7463f391b80a2fbd9dd9466ae Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 07:56:02 -0500 Subject: 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 -- cgit v1.2.3 From 1863a5de878d527ade6d15f0e4c4ad92695c054d Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 07:59:59 -0500 Subject: 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 -- cgit v1.2.3 From cc3dc30518605f80e2ef11751a050ebd2997bac9 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Sat, 29 Jun 2013 21:35:11 -0700 Subject: 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. -- cgit v1.2.3 From c74780755887d270aebf5563bcfa4449e170dab0 Mon Sep 17 00:00:00 2001 From: Michael Lee Date: Mon, 1 Jul 2013 06:21:03 -0700 Subject: 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. ``` -- cgit v1.2.3 From ebf9dd011de8b2e2a79d92c188d6aee63fc31cb7 Mon Sep 17 00:00:00 2001 From: vsthsqrs Date: Mon, 1 Jul 2013 16:10:05 +0200 Subject: 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 -- cgit v1.2.3 From 9da1289d91d710dcd9157e364a32b0ba7928c679 Mon Sep 17 00:00:00 2001 From: Jake Prather Date: Mon, 1 Jul 2013 09:32:19 -0500 Subject: 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 -- cgit v1.2.3 From 1ee6d1b17cbf417adb24db393586f36ab904099a Mon Sep 17 00:00:00 2001 From: Giovanni Cappellotto Date: Mon, 1 Jul 2013 16:39:39 +0200 Subject: 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 -- cgit v1.2.3 From 5d946b13faf2ef9cccaa5338da0ee218d8e06ae4 Mon Sep 17 00:00:00 2001 From: Bruno Date: Mon, 1 Jul 2013 17:18:15 +0200 Subject: 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 -- cgit v1.2.3 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: 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 ---------------------------------------------------- -- cgit v1.2.3 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: 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. -- cgit v1.2.3 From d553ee4c6bf17f14acf06471963859326f8a5f8b Mon Sep 17 00:00:00 2001 From: elisee Date: Mon, 1 Jul 2013 17:50:25 +0200 Subject: 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. -- cgit v1.2.3 From 4642a4884c077477a2946e724fbfc2d483edc569 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 08:53:12 -0700 Subject: 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/) -- cgit v1.2.3 From 832652a45762d46804587ce1525f8a26e210055a Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 09:24:57 -0700 Subject: 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. -- cgit v1.2.3 From 83900dc50427bddebae92545f82530e555fe6365 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Mon, 1 Jul 2013 10:32:42 -0700 Subject: 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/) -- cgit v1.2.3 From e5d2150714a7145e539245f305303aa39962df7c Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 11:03:36 -0700 Subject: 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) -- cgit v1.2.3 From 0e0fed1e304e89ef16d449d9e2ffcc374a152071 Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Mon, 1 Jul 2013 11:50:19 -0700 Subject: 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 -- cgit v1.2.3 From 34c86dc9583b43935e6fe292fbd3aaa69c4ef048 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 1 Jul 2013 14:50:59 -0700 Subject: 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/) -- cgit v1.2.3