1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-09-25 22:09:00 +02:00

Merge remote-tracking branch 'adambard/master'

This commit is contained in:
hyphz
2017-07-18 17:56:42 +01:00
402 changed files with 72662 additions and 3902 deletions

65
.gitattributes vendored Normal file
View File

@@ -0,0 +1,65 @@
asciidoc*.html.markdown linguist-language=AsciiDoc
angularjs*.html.markdown linguist-language=JavaScript
bash*.html.markdown linguist-language=bash
bf.html.markdown linguist-language=Brainfuck
bf-*.html.markdown linguist-language=Brainfuck
c-*.html.markdown linguist-language=C
c.html.markdown linguist-language=C
c++*.html.markdown linguist-language=C++
chapel*.html.markdown linguist-language=Chapel
clojure*.html.markdown linguist-language=Clojure
cmake*.html.markdown linguist-language=CMake
coffeescript*.html.markdown linguist-language=CoffeeScript
coldfusion*.html.markdown linguist-language=ColdFusion
common-lisp*.html.markdown linguist-language=lisp
compojure*.html.markdown linguist-language=Clojure
csharp*.html.markdown linguist-language=C#
css*.html.markdown linguist-language=CSS
d.html.markdown linguist-language=D
d-*.html.markdown linguist-language=D
dart*.html.markdown linguist-language=Dart
edn*.html.markdown linguist-language=edn
elisp*.html.markdown linguist-language=elisp
elixir*.html.markdown linguist-language=Elixir
elm*.html.markdown linguist-language=Elm
erlang*.html.markdown linguist-language=Erlang
factor*.html.markdown linguist-language=Factor
forth*.html.markdown linguist-language=Forth
fortran*.html.markdown linguist-language=FORTRAN
fsharp*.html.markdown linguist-language=fsharp
go.html.markdown linguist-language=Go
go-*.html.markdown linguist-language=Go
groovy*.html.markdown linguist-language=Groovy
hack*.html.markdown linguist-language=Hack
haml*.html.markdown linguist-language=Haml
haskell*.html.markdown linguist-language=Haskell
haxe*.html.markdown linguist-language=Haxe
html*.html.markdown linguist-language=HTML
hy.html.markdown linguist-language=Hy
hy-*.html.markdown linguist-language=Hy
inform7*.html.markdown linguist-language=inform7
java.html.markdown linguist-language=Java
java-*.html.markdown linguist-language=Java
javascript*.html.markdown linguist-language=JavaScript
jquery*.html.markdown linguist-language=JavaScript
json*.html.markdown linguist-language=JSON
julia*.html.markdown linguist-language=Julia
kotlin*.html.markdown linguist-language=Kotlin
latex*.html.markdown linguist-language=latex
less*.html.markdown linguist-language=less
livescript*.html.markdown linguist-language=LiveScript
logtalk*.html.markdown linguist-language=Logtalk
lua*.html.markdown linguist-language=Lua
make*.html.markdown linguist-language=Makefile
markdown*.html.markdown linguist-language=Markdown
matlab*.html.markdown linguist-language=Matlab
nim*.html.markdown linguist-language=Nimrod
nix*.html.markdown linguist-language=Nix
objective-c*.html.markdown linguist-language=Objective-C
ocaml*.html.markdown linguist-language=OCaml
paren*.html.markdown linguist-language=lisp
pcre*.html.markdown linguist-language=Perl
perl.html.markdown linguist-language=Perl
perl-*.html.markdown linguist-language=Perl
perl6*.html.markdown linguist-language=Perl6
ruby*.html.markdown linguist-language=Ruby

16
.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
**/*~
**/*#
**/#*#
**/*.swp
**/*.swo
**/*.bak
**/*.log*
**/*.sublime-workspace
**/.DS_Store
**/.DS_Store?
**/._*
**/.Spotlight-V100
**/.Trashes
**/ehthumbs.db
**/Thumbs.db
**/desktop.ini

3
.travis.yml Normal file
View File

@@ -0,0 +1,3 @@
language: ruby
rvm:
- 2.2

519
CHICKEN.html.markdown Normal file
View File

@@ -0,0 +1,519 @@
---
language: "CHICKEN"
filename: CHICKEN.scm
contributors:
- ["Diwakar Wagle", "https://github.com/deewakar"]
---
CHICKEN is an implementation of Scheme programming language that can
compile Scheme programs to C code as well as interpret them. CHICKEN
supports RSR5 and RSR7 (work in progress) standards and many extensions.
```scheme
;; #!/usr/bin/env csi -s
;; Run the CHICKEN REPL in the commandline as follows :
;; $ csi
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 0. Syntax
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Single line comments start with a semicolon
#| Block comments
can span multiple lines and...
#| can be nested
|#
|#
;; S-expression comments are used to comment out expressions
#; (display "nothing") ; discard this expression
;; CHICKEN has two fundamental pieces of syntax: Atoms and S-expressions
;; an atom is something that evaluates to itself
;; all builtin data types viz. numbers, chars, booleans, strings etc. are atoms
;; Furthermore an atom can be a symbol, an identifier, a keyword, a procedure
;; or the empty list (also called null)
'athing ;; => athing
'+ ;; => +
+ ;; => <procedure C_plus>
;; S-expressions (short for symbolic expressions) consists of one or more atoms
(quote +) ;; => + ; another way of writing '+
(+ 1 2 3) ;; => 6 ; this S-expression evaluates to a function call
'(+ 1 2 3) ;; => (+ 1 2 3) ; evaluates to a list
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 1. Primitive Datatypes and Operators
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Numbers
99999999999999999999 ;; integers
#b1010 ;; binary ; => 10
#o10 ;; octal ; => 8
#x8ded ;; hexadecimal ; => 36333
3.14 ;; real
6.02e+23
3/4 ;; rational
;;Characters and Strings
#\A ;; A char
"Hello, World!" ;; strings are fixed-length arrays of characters
;; Booleans
#t ;; true
#f ;; false
;; Function call is written as (f x y z ...)
;; where f is a function and x,y,z, ... are arguments
(print "Hello, World!") ;; => Hello, World!
;; formatted output
(printf "Hello, ~a.\n" "World") ;; => Hello, World.
;; print commandline arguments
(map print (command-line-arguments))
(list 'foo 'bar 'baz) ;; => (foo bar baz)
(string-append "pine" "apple") ;; => "pineapple"
(string-ref "tapioca" 3) ;; => #\i;; character 'i' is at index 3
(string->list "CHICKEN") ;; => (#\C #\H #\I #\C #\K #\E #\N)
(string->intersperse '("1" "2") ":") ;; => "1:2"
(string-split "1:2:3" ":") ;; => ("1" "2" "3")
;; Predicates are special functions that return boolean values
(atom? #t) ;; => #t
(symbol? #t) ;; => #f
(symbol? '+) ;; => #t
(procedure? +) ;; => #t
(pair? '(1 2)) ;; => #t
(pair? '(1 2 . 3)) ;; => #t
(pair? '()) ;; => #f
(list? '()) ;; => #t
;; Some arithmetic operations
(+ 1 1) ;; => 2
(- 8 1) ;; => 7
(* 10 2) ;; => 20
(expt 2 3) ;; => 8
(remainder 5 2) ;; => 1
(/ 35 5) ;; => 7
(/ 1 3) ;; => 0.333333333333333
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 2. Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; You can create variables with define
;; A variable name can use any character except: ()[]{}",'`;#\
(define myvar 5)
myvar ;; => 5
;; Alias to a procedure
(define ** expt)
(** 2 3) ;; => 8
;; Accessing an undefined variable raises an exception
s ;; => Error: unbound variable: s
;; Local binding
(let ((me "Bob"))
(print me)) ;; => Bob
(print me) ;; => Error: unbound variable: me
;; Assign a new value to previously defined variable
(set! myvar 10)
myvar ;; => 10
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 3. Collections
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Pairs
;; 'cons' constructs pairs,
;; 'car' extracts the first element, 'cdr' extracts the rest of the elements
(cons 'subject 'verb) ;; => '(subject . verb)
(car (cons 'subject 'verb)) ;; => subject
(cdr (cons 'subject 'verb)) ;; => verb
;; Lists
;; cons creates a new list if the second item is a list
(cons 0 '()) ;; => (0)
(cons 1 (cons 2 (cons 3 '()))) ;; => (1 2 3)
;; 'list' is a convenience variadic constructor for lists
(list 1 2 3) ;; => (1 2 3)
;; Use 'append' to append lists together
(append '(1 2) '(3 4)) ;; => (1 2 3 4)
;; Some basic operations on lists
(map add1 '(1 2 3)) ;; => (2 3 4)
(reverse '(1 3 4 7)) ;; => (7 4 3 1)
(sort '(11 22 33 44) >) ;; => (44 33 22 11)
(define days '(SUN MON FRI))
(list-ref days 1) ;; => MON
(set! (list-ref days 1) 'TUE)
days ;; => (SUN TUE FRI)
;; Vectors
;; Vectors are heterogeneous structures whose elements are indexed by integers
;; A Vector typically occupies less space than a list of the same length
;; Random access of an element in a vector is faster than in a list
#(1 2 3) ;; => #(1 2 3) ;; literal syntax
(vector 'a 'b 'c) ;; => #(a b c)
(vector? #(1 2 3)) ;; => #t
(vector-length #(1 (2) "a")) ;; => 3
(vector-ref #(1 (2) (3 3)) 2);; => (3 3)
(define vec #(1 2 3))
(vector-set! vec 2 4)
vec ;; => #(1 2 4)
;; Vectors can be created from lists and vice-verca
(vector->list #(1 2 4)) ;; => '(1 2 4)
(list->vector '(a b c)) ;; => #(a b c)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 4. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Use 'lambda' to create functions.
;; A function always returns the value of its last expression
(lambda () "Hello World") ;; => #<procedure (?)>
;; Use extra parens around function definition to execute
((lambda () "Hello World")) ;; => Hello World ;; argument list is empty
;; A function with an argument
((lambda (x) (* x x)) 3) ;; => 9
;; A function with two arguments
((lambda (x y) (* x y)) 2 3) ;; => 6
;; assign a function to a variable
(define sqr (lambda (x) (* x x)))
sqr ;; => #<procedure (sqr x)>
(sqr 3) ;; => 9
;; We can shorten this using the function definition syntactic sugar
(define (sqr x) (* x x))
(sqr 3) ;; => 9
;; We can redefine existing procedures
(foldl cons '() '(1 2 3 4 5)) ;; => (((((() . 1) . 2) . 3) . 4) . 5)
(define (foldl func accu alist)
(if (null? alist)
accu
(foldl func (func (car alist) accu) (cdr alist))))
(foldl cons '() '(1 2 3 4 5)) ;; => (5 4 3 2 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 5. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; For numbers use '='
(= 3 3.0) ;; => #t
(= 2 1) ;; => #f
;; 'eq?' returns #t if two arguments refer to the same object in memory
;; In other words, it's a simple pointer comparision.
(eq? '() '()) ;; => #t ;; there's only one empty list in memory
(eq? (list 3) (list 3)) ;; => #f ;; not the same object
(eq? 'yes 'yes) ;; => #t
(eq? 3 3) ;; => #t ;; don't do this even if it works in this case
(eq? 3 3.0) ;; => #f ;; it's better to use '=' for number comparisions
(eq? "Hello" "Hello") ;; => #f
;; 'eqv?' is same as 'eq?' all datatypes except numbers and characters
(eqv? 3 3.0) ;; => #f
(eqv? (expt 2 3) (expt 2 3)) ;; => #t
(eqv? 'yes 'yes) ;; => #t
;; 'equal?' recursively compares the contents of pairs, vectors, and strings,
;; applying eqv? on other objects such as numbers and symbols.
;; A rule of thumb is that objects are generally equal? if they print the same.
(equal? '(1 2 3) '(1 2 3)) ;; => #t
(equal? #(a b c) #(a b c)) ;; => #t
(equal? 'a 'a) ;; => #t
(equal? "abc" "abc") ;; => #f
;; In Summary:
;; eq? tests if objects are identical
;; eqv? tests if objects are operationally equivalent
;; equal? tests if objects have same structure and contents
;; Comparing strings for equality
(string=? "Hello" "Hello") ;; => #t
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 6. Control Flow
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Conditionals
(if #t ;; test expression
"True" ;; then expression
"False") ;; else expression
;; => "True"
(if (> 3 2)
"yes"
"no") ;; => "yes"
;; In conditionals, all values that are not '#f' are treated as true.
;; 0, '(), #() "" , are all true values
(if 0
"0 is not false"
"0 is false") ;; => "0 is not false"
;; 'cond' chains a series of tests and returns as soon as it encounters a true condition
;; 'cond' can be used to simulate 'if/elseif/else' statements
(cond ((> 2 2) "not true so don't return this")
((< 2 5) "true, so return this")
(else "returning default")) ;; => "true, so return this"
;; A case expression is evaluated as follows:
;; The key is evaluated and compared with each datum in sense of 'eqv?',
;; The corresponding clause in the matching datum is evaluated and returned as result
(case (* 2 3) ;; the key is 6
((2 3 5 7) 'prime) ;; datum 1
((1 4 6 8) 'composite)) ;; datum 2; matched!
;; => composite
;; case with else clause
(case (car '(c d))
((a e i o u) 'vowel)
((w y) 'semivowel)
(else 'consonant)) ;; => consonant
;; Boolean expressions
;; 'and' returns the first expression that evaluates to #f
;; otherwise, it returns the result of the last expression
(and #t #f (= 2 2.0)) ;; => #f
(and (< 2 5) (> 2 0) "0 < 2 < 5") ;; => "0 < 2 < 5"
;; 'or' returns the first expression that evaluates to #t
;; otherwise the result of the last expression is returned
(or #f #t #f) ;; => #t
(or #f #f #f) ;; => #f
;; 'when' is like 'if' without the else expression
(when (positive? 5) "I'm positive") ;; => "I'm positive"
;; 'unless' is equivalent to (when (not <test>) <expr>)
(unless (null? '(1 2 3)) "not null") ;; => "not null"
;; Loops
;; loops can be created with the help of tail-recursions
(define (loop count)
(unless (= count 0)
(print "hello")
(loop (sub1 count))))
(loop 4) ;; => hello, hello ...
;; Or with a named let
(let loop ((i 0) (limit 5))
(when (< i limit)
(printf "i = ~a\n" i)
(loop (add1 i) limit))) ;; => i = 0, i = 1....
;; 'do' is another iteration construct
;; It initializes a set of variables and updates them in each iteration
;; A final expression is evaluated after the exit condition is met
(do ((x 0 (add1 x ))) ;; initialize x = 0 and add 1 in each iteration
((= x 10) (print "done")) ;; exit condition and final expression
(print x)) ;; command to execute in each step
;; => 0,1,2,3....9,done
;; Iteration over lists
(for-each (lambda (a) (print (* a a)))
'(3 5 7)) ;; => 9, 25, 49
;; 'map' is like for-each but returns a list
(map add1 '(11 22 33)) ;; => (12 23 34)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 7. Extensions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The CHICKEN core is very minimal, but additional features are provided by library extensions known as Eggs.
;; You can install Eggs with 'chicken-install <eggname>' command.
;; 'numbers' egg provides support for full numeric tower.
(require-extension numbers)
;; complex numbers
3+4i ;; => 3+2i
;; Supports fractions without falling back to inexact flonums
1/3 ;; => 1/3
;; provides support for large integers through bignums
(expt 9 20) ;; => 12157665459056928801
;; And other 'extended' functions
(log 10 (exp 1)) ;; => 2.30258509299405
(numerator 2/3) ;; => 2
;; 'utf8' provides unicode support
(require-extension utf8)
"\u03BBx:(\u03BC\u0251.\u0251\u2192\u0251).xx" ;; => "λx:(μɑ.ɑ→ɑ).xx"
;; 'posix' provides file I/O and lots of other services for unix-like operating systems
;; Some of the functions are not available in Windows system,
;; See http://wiki.call-cc.org/man/4/Unit%20posix for more details
;; Open a file to append, open "write only" and create file if it does not exist
(define outfn (file-open "chicken-hen.txt" (+ open/append open/wronly open/creat)))
;; write some text to the file
(file-write outfn "Did chicken came before hen?")
;; close the file
(file-close outfn)
;; Open the file "read only"
(define infn (file-open "chicken-hen.txt" open/rdonly))
;; read some text from the file
(file-read infn 30) ;; => ("Did chicken came before hen? ", 28)
(file-close infn)
;; CHICKEN also supports SRFI (Scheme Requests For Implementation) extensions
;; See 'http://srfi.schemers.org/srfi-implementers.html" to see srfi's supported by CHICKEN
(require-extension srfi-1) ;; list library
(filter odd? '(1 2 3 4 5 6 7)) ;; => (1 3 5 7)
(count even? '(1 2 3 4 5)) ;; => 2
(take '(12 24 36 48 60) 3) ;; => (12 24 36)
(drop '(12 24 36 48 60) 2) ;; => (36 48 60)
(circular-list 'z 'q) ;; => z q z q ...
(require-extension srfi-13) ;; string library
(string-reverse "pan") ;; => "nap"
(string-index "Turkey" #\k) ;; => 3
(string-every char-upper-case? "CHICKEN") ;; => #t
(string-join '("foo" "bar" "baz") ":") ;; => "foo:bar:baz"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 8. Macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A 'for .. in ..' iteration like python, for lists
(define-syntax for
(syntax-rules (in)
((for elem in alist body ...)
(for-each (lambda (elem) body ...) alist))))
(for x in '(2 4 8 16)
(print x)) ;; => 2, 4, 8, 16
(for chr in (string->list "PENCHANT")
(print chr)) ;; => P, E, N, C, H, A, N, T
;; While loop
(define-syntax while
(syntax-rules ()
((while cond body ...)
(let loop ()
(when cond
body ...
(loop))))))
(let ((str "PENCHANT") (i 0))
(while (< i (string-length str)) ;; while (condition)
(print (string-ref str i)) ;; body
(set! i (add1 i))))
;; => P, E, N, C, H, A, N, T
;; Advanced Syntax-Rules Primer -> http://petrofsky.org/src/primer.txt
;; Macro system in chicken -> http://lists.gnu.org/archive/html/chicken-users/2008-04/msg00013.html
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 9. Modules
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Also See http://wiki.call-cc.org/man/4/Modules
;; The 'test' module exports a value named 'hello' and a macro named 'greet'
(module test (hello greet)
(import scheme)
(define-syntax greet
(syntax-rules ()
((_ whom)
(begin
(display "Hello, ")
(display whom)
(display " !\n") ) ) ) )
(define (hello)
(greet "world") ) )
;; we can define our modules in a separate file (say test.scm) and load them to the interpreter with
;; (load "test.scm")
;; import the module
(import test)
(hello) ;; => Hello, world !
(greet "schemers") ;; => Hello, schemers !
;; We can compile the module files in to shared libraries by using following command,
;; csc -s test.scm
;; (load "test.so")
;; Functors
;; Functors are high level modules that can be parameterized by other modules
;; Following functor requires another module named 'M' that provides a function called 'multiply'
;; The functor itself exports a generic function 'square'
(functor (squaring-functor (M (multiply))) (square)
(import scheme M)
(define (square x) (multiply x x)))
;; Module 'nums' can be passed as a parameter to 'squaring-functor'
(module nums (multiply)
(import scheme) ;; predefined modules
(define (multiply x y) (* x y)))
;; the final module can be imported and used in our program
(module number-squarer = (squaring-functor nums))
(import number-squarer)
(square 3) ;; => 9
;; We can instantiate the functor for other inputs
;; Here's another example module that can be passed to squaring-functor
(module stars (multiply)
(import chicken scheme) ;; chicken module for the 'use' keyword
(use srfi-1) ;; we can use external libraries in our module
(define (multiply x y)
(list-tabulate x (lambda _ (list-tabulate y (lambda _ '*))))))
(module star-squarer = (squaring-functor stars))
(import star-squarer)
(square 3) ;; => ((* * *)(* * *)(* * *))
```
## Further Reading
* [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual).
* [RSR5 standards](http://www.schemers.org/Documents/Standards/R5RS)
## Extra Info
* [For programmers of other languages](http://wiki.call-cc.org/chicken-for-programmers-of-other-languages)
* [Compare CHICKEN syntax with other languages](http://plr.sourceforge.net/cgi-bin/plr/launch.py)

73
CONTRIBUTING.markdown Normal file
View File

@@ -0,0 +1,73 @@
# Contributing
All contributions are welcome, from the tiniest typo to a brand new article.
Translations in all languages are welcome (or, for that matter, original
articles in any language). Send a pull request or open an issue any time of day
or night.
**Please prepend the tag `[language/lang-code]` to your issues and pull
requests.** For example, `[python/en]` for English Python. This will help
everyone pick out things they care about.
We're happy for any contribution in any form, but if you're making more than one
major change (i.e. translations for two different languages) it would be super
cool of you to make a separate pull request for each one so that someone can
review them more effectively and/or individually.
## Style Guidelines
- **Keep lines of under 80 chars**
+ Try to keep **line length in code blocks to 80 characters or fewer**.
+ Otherwise, the text will overflow and look odd.
- **Prefer example to exposition**
+ Try to use as few words as possible.
+ Code examples are preferred over exposition in all cases.
- **Eschew surplusage**
+ We welcome newcomers, but the target audience for this site is programmers
with some experience.
+ Try to avoid explaining basic concepts except for those specific to the
language in question.
+ Keep articles succinct and scannable. We all know how to use Google here.
- **Use UTF-8**
+ For translations (or EN articles with non-ASCII characters) please make sure
your file is UTF-8 encoded.
+ Try to leave out the byte-order-mark at the start of the file. (`:set nobomb`
in Vim)
+ You can check if the file contains a BOM on Linux/Unix systems by running
`file language.html.markdown` You will see this if it uses a BOM:
`UTF-8 Unicode (with BOM) text`.
### Header configuration
The actual site uses Middleman to generate HTML files from these Markdown ones.
Middleman, or at least the custom scripts underpinning the site, requires that
some key information be defined in the header.
The following fields are necessary for English articles about programming
languages:
- **language** The *programming language* in question
- **contributors** A list of [author, URL] lists to credit
Other fields:
- **filename**: The filename for this article's code. It will be fetched, mashed
together, and made downloadable.
+ For non-English articles, *filename* should have a language-specific
suffix.
- **lang**: For translations, the human language this article is in. For
categorization, mostly.
Here's an example header for an Esperanto translation of Ruby:
```yaml
---
language: ruby
filename: learnruby-epo.ruby
contributors:
- ["Doktor Esperanto", "http://example.com/"]
- ["Someone else", "http://someoneelseswebsite.com/"]
lang: ep-ep
---
```

5
Gemfile Normal file
View File

@@ -0,0 +1,5 @@
source 'http://rubygems.org'
group :test do
gem 'rake'
gem 'charlock_holmes'
end

15
Gemfile.lock Normal file
View File

@@ -0,0 +1,15 @@
GEM
remote: http://rubygems.org/
specs:
charlock_holmes (0.7.3)
rake (12.0.0)
PLATFORMS
ruby
DEPENDENCIES
charlock_holmes
rake
BUNDLED WITH
1.13.7

6
ISSUE_TEMPLATE.md Normal file
View File

@@ -0,0 +1,6 @@
Make sure the issue title is prepended with '[language/lang-code]' if the language is
already on the site.
If it's a request for a new language, use: '[Request] [language/lang-code]'
Issues are always welcome. If you are able and willing, we welcome any pull requests
as this is a community powered project.

185
LOLCODE.html.markdown Normal file
View File

@@ -0,0 +1,185 @@
---
language: LOLCODE
filename: learnLOLCODE.lol
contributors:
- ["abactel", "https://github.com/abactel"]
---
LOLCODE is an esoteric programming language designed to resemble the speech of [lolcats](https://upload.wikimedia.org/wikipedia/commons/a/ab/Lolcat_in_folder.jpg?1493656347257).
```
BTW This is an inline comment
BTW All code must begin with `HAI <language version>` and end with `KTHXBYE`
HAI 1.3
CAN HAS STDIO? BTW Importing standard headers
OBTW
==========================================================================
================================= BASICS =================================
==========================================================================
TLDR
BTW Displaying text:
VISIBLE "HELLO WORLD"
BTW Declaring variables:
I HAS A MESSAGE ITZ "CATZ ARE GOOD"
VISIBLE MESSAGE
OBTW
(This is a codeblock.) Variables are dynamically typed so you don't need to
declare their type. A variable's type matches its content. These are the
types:
TLDR
I HAS A STRING ITZ "DOGZ ARE GOOOD" BTW type is YARN
I HAS A INTEGER ITZ 42 BTW type is NUMBR
I HAS A FLOAT ITZ 3.1415 BTW type is NUMBAR
I HAS A BOOLEAN ITZ WIN BTW type is TROOF
I HAS A UNTYPED BTW type is NOOB
BTW Accepting user input:
I HAS A AGE
GIMMEH AGE
BTW The variable is stored as a YARN. To convert it into NUMBR:
AGE IS NOW A NUMBR
OBTW
==========================================================================
================================== MATH ==================================
==========================================================================
TLDR
BTW LOLCODE uses polish notation style math.
BTW Basic mathematical notation:
SUM OF 21 AN 33 BTW 21 + 33
DIFF OF 90 AN 10 BTW 90 - 10
PRODUKT OF 12 AN 13 BTW 12 * 13
QUOSHUNT OF 32 AN 43 BTW 32 / 43
MOD OF 43 AN 64 BTW 43 modulo 64
BIGGR OF 23 AN 53 BTW max(23, 53)
SMALLR OF 53 AN 45 BTW min(53, 45)
BTW Binary notation:
BOTH OF WIN AN WIN BTW and: WIN if x=WIN, y=WIN
EITHER OF FAIL AN WIN BTW or: FAIL if x=FAIL, y=FAIL
WON OF WIN AN FAIL BTW xor: FAIL if x=y
NOT FAIL BTW unary negation: WIN if x=FAIL
ALL OF WIN AN WIN MKAY BTW infinite arity AND
ANY OF WIN AN FAIL MKAY BTW infinite arity OR
BTW Comparison:
BOTH SAEM "CAT" AN "DOG" BTW WIN if x == y
DIFFRINT 732 AN 184 BTW WIN if x != y
BOTH SAEM 12 AN BIGGR OF 12 AN 4 BTW x >= y
BOTH SAEM 43 AN SMALLR OF 43 AN 56 BTW x <= y
DIFFRINT 64 AN SMALLR OF 64 AN 2 BTW x > y
DIFFRINT 75 AN BIGGR OF 75 AN 643 BTW x < y
OBTW
==========================================================================
============================== FLOW CONTROL ==============================
==========================================================================
TLDR
BTW If/then statement:
I HAS A ANIMAL
GIMMEH ANIMAL
BOTH SAEM ANIMAL AN "CAT", O RLY?
YA RLY
VISIBLE "YOU HAV A CAT"
MEBBE BOTH SAEM ANIMAL AN "MAUS"
VISIBLE "NOM NOM NOM. I EATED IT."
NO WAI
VISIBLE "AHHH IS A WOOF WOOF"
OIC
BTW Case statement:
I HAS A COLOR
GIMMEH COLOR
COLOR, WTF?
OMG "R"
VISIBLE "RED FISH"
GTFO
OMG "Y"
VISIBLE "YELLOW FISH"
BTW Since there is no `GTFO` the next statements will also be tested
OMG "G"
OMG "B"
VISIBLE "FISH HAS A FLAVOR"
GTFO
OMGWTF
VISIBLE "FISH IS TRANSPARENT OHNO WAT"
OIC
BTW For loop:
I HAS A TEMPERATURE
GIMMEH TEMPERATURE
TEMPERATURE IS NOW A NUMBR
IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN TEMPERATURE
VISIBLE ITERATOR
IM OUTTA YR LOOP
BTW While loop:
IM IN YR LOOP NERFIN YR ITERATOR WILE DIFFRINT ITERATOR AN -10
VISIBLE ITERATOR
IM OUTTA YR LOOP
OBTW
=========================================================================
================================ Strings ================================
=========================================================================
TLDR
BTW Linebreaks:
VISIBLE "FIRST LINE :) SECOND LINE"
BTW Tabs:
VISIBLE ":>SPACES ARE SUPERIOR"
BTW Bell (goes beep):
VISIBLE "NXT CUSTOMER PLS :o"
BTW Literal double quote:
VISIBLE "HE SAID :"I LIKE CAKE:""
BTW Literal colon:
VISIBLE "WHERE I LIVE:: CYBERSPACE"
OBTW
=========================================================================
=============================== FUNCTIONS ===============================
=========================================================================
TLDR
BTW Declaring a new function:
HOW IZ I SELECTMOVE YR MOVE BTW `MOVE` is an argument
BOTH SAEM MOVE AN "ROCK", O RLY?
YA RLY
VISIBLE "YOU HAV A ROCK"
NO WAI
VISIBLE "OH NO IS A SNIP-SNIP"
OIC
GTFO BTW This returns NOOB
IF U SAY SO
BTW Declaring a function and returning a value:
HOW IZ I IZYELLOW
FOUND YR "YELLOW"
IF U SAY SO
BTW Calling a function:
I IZ IZYELLOW MKAY
KTHXBYE
```
## Further reading:
- [LCI compiler](https://github.com/justinmeza/lci)
- [Official spec](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md)

6
PULL_REQUEST_TEMPLATE.md Normal file
View File

@@ -0,0 +1,6 @@
- [ ] I solemnly swear that this is all original content of which I am the original author
- [ ] Pull request title is prepended with `[language/lang-code]`
- [ ] Pull request touches only one file (or a set of logically related files with similar changes made)
- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts)
- [ ] If you've changed any part of the YAML Frontmatter, make sure it is formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown)
- [ ] Yes, I have double-checked quotes and field names!

View File

@@ -1,88 +1,47 @@
# [Learn X in Y minutes](http://learnxinyminutes.com)
# [Learn X in Y minutes][1]
[![Build Status](https://travis-ci.org/adambard/learnxinyminutes-docs.svg?branch=master)](https://travis-ci.org/adambard/learnxinyminutes-docs)
Whirlwind tours of (several, hopefully many someday) popular and
ought-to-be-more-popular programming languages, presented as valid,
commented code and explained as they go.
ought-to-be-more-popular programming languages, presented as valid, commented
code and explained as they go.
## We need YOU!...
... to write more inline code tutorials. Just grab an existing file from
this repo and copy the formatting (don't worry, it's all very simple).
Make a new file, send a pull request, and if it passes muster I'll get it up pronto.
Remember to fill in the "contributors" fields so you get credited
properly!
... to write more inline code tutorials. Just grab an existing file from this
repo and copy the formatting (don't worry, it's all very simple). Make a new
file, send a pull request, and if it passes muster I'll get it up pronto.
Remember to fill in the "contributors" fields so you get credited properly!
## Contributing
All contributions are welcome, from the tiniest typo to a brand new article. Translations
in all languages are welcome (or, for that matter, original articles in any language).
Send a pull request or open an issue any time of day or night.
All contributions are welcome, from the tiniest typo to a brand new article.
Translations in all languages are welcome (or, for that matter, original
articles in any language). Send a pull request or open an issue any time of day
or night.
**Please tag your issues and pull requests with [language/lang-code] at the beginning**
**(e.g. [python/en] for English Python).** This will help everyone pick out things they
care about.
**Please prepend the tag `[language/lang-code]` to your issues and pull
requests.** For example, `[python/en]` for English Python. This will help
everyone pick out things they care about.
We're happy for any contribution in any form, but if you're making more than one major change
(i.e. translations for two different languages) it would be super cool of you to make a
separate pull request for each one so that someone can review them more effectively and/or
individually.
We're happy for any contribution in any form, but if you're making more than one
major change (i.e. translations for two different languages) it would be super
cool of you to make a separate pull request for each one so that someone can
review them more effectively and/or individually.
### Style Guidelines
* **Keep lines under 80 chars**
* **Prefer example to exposition**
* **Eschew surplusage**
* **Use UTF-8**
Long version:
* Try to keep **line length in code blocks to 80 characters or fewer**, or they'll overflow
and look odd.
* Try to use as few words as possible. Code examples are preferred over exposition in all cases.
* We welcome newcomers, but the target audience for this site is programmers with some experience.
So, try to avoid explaining basic concepts except for those specific to the language in question,
to keep articles succinct and scannable. We all know how to use Google here.
* For translations (or English articles with non-ASCII characters), please make sure your file is
UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim)
### Header configuration
The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
the custom scripts underpinning the site, requires that some key information be defined in the header.
The following fields are necessary for English articles about programming languages:
* **language** The *programming language* in question
* **contributors** A list of [author, URL] lists to credit
Other fields:
* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable.
For non-English articles, *filename* should have a language-specific suffix.
* **lang**: For translations, the human language this article is in. For categorization, mostly.
Here's an example header for an Esperanto translation of Ruby:
```yaml
---
language: ruby
filename: learnruby-epo.ruby
contributors:
- ["Doktor Esperanto", "http://example.com/"]
- ["Someone else", "http://someoneelseswebsite.com/"]
lang: ep-ep
---
```
For a detailed style guide, please review the full [CONTRIBUTING][2] guidelines.
## License
Contributors retain copyright to their work, and can request removal at any time.
By uploading a doc here, you agree to publish your work under the default
[Creative Commons Attribution-ShareAlike 3.0 Unported](http://creativecommons.org/licenses/by-sa/3.0/deed.en_US)
licensing included on each doc page.
Contributors retain copyright to their work, and can request removal at any
time. By uploading a doc here, you agree to publish your work under the default
[Creative Commons Attribution-ShareAlike 3.0 Unported][3] licensing included on
each doc page.
Anything not covered by the above -- basically, this README -- you can use
as you wish, I guess.
Anything not covered by the above -- basically, this README -- you can use as
you wish, I guess.
[1]: http://learnxinyminutes.com
[2]: /CONTRIBUTING.markdown
[3]: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US

23
Rakefile Normal file
View File

@@ -0,0 +1,23 @@
task default: %w[encoding yaml return_code]
$failure = 0
task :encoding do
begin
ruby 'tests/encoding.rb'
rescue Exception => msg
puts msg
$failure += 1
end
end
task :yaml do
begin
ruby 'tests/yaml.rb'
rescue Exception => msg
puts msg
$failure += 1
end
end
task :return_code do
if $failure != 0
raise "Failed #{$failure} tests!!"
end
end

708
angularjs.html.markdown Normal file
View File

@@ -0,0 +1,708 @@
---
category: tool
tool: AngularJS
contributors:
- ["Walter Cordero", "http://waltercordero.com"]
filename: learnangular.html
---
## AngularJS Tutorial.
AngularJS version 1.0 was released in 2012.
Miško Hevery, a Google employee, started to work with AngularJS in 2009.
The idea turned out very well, and the project is now officially supported by Google.
AngularJS is a JavaScript framework. It can be added to an HTML page with a "script" tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
##What You Should Already Know
Before you study AngularJS, you should have a basic understanding of:
- HTML
- CSS
- JavaScript
```html
// AngularJS is a JavaScript framework. It is a library written in JavaScript.
// AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
// <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
///////////////////////////////////
// AngularJS Extends HTML
//AngularJS extends HTML with ng-directives.
//The ng-app directive defines an AngularJS application.
//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
//The ng-bind directive binds application data to the HTML view.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
/*
* Example explained:
* AngularJS starts automatically when the web page has loaded.
* The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
* The ng-model directive binds the value of the input field to the application variable name.
* The ng-bind directive binds the innerHTML of the <p> element to the application variable name.
*/
<tag> Here are content to be interpreted </tag>
///////////////////////////////////
// AngularJS Expressions
// AngularJS expressions are written inside double braces: {{ expression }}.
// AngularJS expressions binds data to HTML the same way as the ng-bind directive.
// AngularJS will "output" data exactly where the expression is written.
// AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.
// Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
//If you remove the ng-app directive, HTML will display the expression as it is, without solving it:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
// AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
</body>
</html>
// AngularJS numbers are like JavaScript numbers:
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
//AngularJS strings are like JavaScript strings:
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
//AngularJS objects are like JavaScript objects:
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
//AngularJS arrays are like JavaScript arrays:
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
// Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
// Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
// AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
// AngularJS expressions support filters, while JavaScript expressions do not.
///////////////////////////////////
// AngularJS Directives
//AngularJS directives are extended HTML attributes with the prefix ng-.
//The ng-app directive initializes an AngularJS application.
//The ng-init directive initializes application data.
//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
<div ng-app="" ng-init="firstName='John'">
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
//Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.
//The ng-repeat directive repeats an HTML element:
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
//The ng-repeat directive used on an array of objects:
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
// AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
// Just imagine if these objects were records from a database.
// The ng-app directive defines the root element of an AngularJS application.
// The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.
// Later you will learn how ng-app can have a value (like ng-app="myModule"), to connect code modules.
// The ng-init directive defines initial values for an AngularJS application.
// Normally, you will not use ng-init. You will use a controller or module instead.
// You will learn more about controllers and modules later.
//The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
//The ng-model directive can also:
//Provide type validation for application data (number, email, required).
//Provide status for application data (invalid, dirty, touched, error).
//Provide CSS classes for HTML elements.
//Bind HTML elements to HTML forms.
//The ng-repeat directive clones HTML elements once for each item in a collection (in an array).
///////////////////////////////////
// AngularJS Controllers
// AngularJS controllers control the data of AngularJS applications.
// AngularJS controllers are regular JavaScript Objects.
// AngularJS applications are controlled by controllers.
// The ng-controller directive defines the application controller.
// A controller is a JavaScript Object, created by a standard JavaScript object constructor.
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
//Application explained:
//The AngularJS application is defined by ng-app="myApp". The application runs inside the <div>.
//The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
//The myCtrl function is a JavaScript function.
//AngularJS will invoke the controller with a $scope object.
//In AngularJS, $scope is the application object (the owner of application variables and functions).
//The controller creates two properties (variables) in the scope (firstName and lastName).
//The ng-model directives bind the input fields to the controller properties (firstName and lastName).
//The example above demonstrated a controller object with two properties: lastName and firstName.
//A controller can also have methods (variables as functions):
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
});
</script>
//In larger applications, it is common to store controllers in external files.
//Just copy the code between the <script> </script> tags into an external file named personController.js:
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="personController.js"></script>
// For the next example we will create a new controller file:
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});
//Save the file as namesController.js:
//And then use the controller file in an application:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script src="namesController.js"></script>
///////////////////////////////////
// AngularJS Filters
// Filters can be added to expressions and directives using a pipe character.
// AngularJS filters can be used to transform data:
- **currency**: Format a number to a currency format.
- **filter**: Select a subset of items from an array.
- **lowercase**: Format a string to lower case.
- **orderBy**: Orders an array by an expression.
- **uppercase**: Format a string to upper case.
//A filter can be added to an expression with a pipe character (|) and a filter.
//(For the next two examples we will use the person controller from the previous chapter)
//The uppercase filter format strings to upper case:
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
//The lowercase filter format strings to lower case:
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | lowercase }}</p>
</div>
//The currency filter formats a number as currency:
<div ng-app="myApp" ng-controller="costCtrl">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
</div>
//A filter can be added to a directive with a pipe character (|) and a filter.
//The orderBy filter orders an array by an expression:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
<div>
//An input filter can be added to a directive with a pipe character (|)
//and filter followed by a colon and a model name.
//The filter selects a subset of an array:
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>
///////////////////////////////////
// AngularJS AJAX - $http
//$http is an AngularJS service for reading data from remote servers.
// The following data can be provided by a web server:
// http://www.w3schools.com/angular/customers.php
// **Check the URL to see the data format**
// AngularJS $http is a core service for reading data from web servers.
// $http.get(url) is the function to use for reading server data.
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>
Application explained:
// The AngularJS application is defined by ng-app. The application runs inside a <div>.
// The ng-controller directive names the controller object.
// The customersCtrl function is a standard JavaScript object constructor.
// AngularJS will invoke customersCtrl with a $scope and $http object.
// $scope is the application object (the owner of application variables and functions).
// $http is an XMLHttpRequest object for requesting external data.
// $http.get() reads JSON data from http://www.w3schools.com/angular/customers.php.
// If success, the controller creates a property (names) in the scope, with JSON data from the server.
// Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
// Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
// In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
// The following line, in our PHP examples, has been added to allow cross-site access.
header("Access-Control-Allow-Origin: *");
///////////////////////////////////
// AngularJS Tables
// Displaying tables with angular is very simple:
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
});
</script>
// To sort the table, add an orderBy filter:
<table>
<tr ng-repeat="x in names | orderBy : 'Country'">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
// To display the table index, add a <td> with $index:
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
// Using $even and $odd
<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>
///////////////////////////////////
// AngularJS HTML DOM
//AngularJS has directives for binding application data to the attributes of HTML DOM elements.
// The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
<div ng-app="" ng-init="mySwitch=true">
<p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
</div>
//Application explained:
// The ng-disabled directive binds the application data mySwitch to the HTML button's disabled attribute.
// The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
// If the value of mySwitch evaluates to true, the button will be disabled:
<p>
<button disabled>Click Me!</button>
</p>
// If the value of mySwitch evaluates to false, the button will not be disabled:
<p>
<button>Click Me!</button>
</p>
// The ng-show directive shows or hides an HTML element.
<div ng-app="">
<p ng-show="true">I am visible.</p>
<p ng-show="false">I am not visible.</p>
</div>
// The ng-show directive shows (or hides) an HTML element based on the value of ng-show.
// You can use any expression that evaluates to true or false:
<div ng-app="">
<p ng-show="hour > 12">I am visible.</p>
</div>
///////////////////////////////////
// AngularJS Events
// AngularJS has its own HTML events directives.
// The ng-click directive defines an AngularJS click event.
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
// The ng-hide directive can be used to set the visibility of a part of an application.
// The value ng-hide="true" makes an HTML element invisible.
// The value ng-hide="false" makes the element visible.
<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
//Application explained:
// The first part of the personController is the same as in the chapter about controllers.
// The application has a default property (a variable): $scope.myVar = false;
// The ng-hide directive sets the visibility, of a <p> element with two input fields,
// according to the value (true or false) of myVar.
// The function toggle() toggles myVar between true and false.
// The value ng-hide="true" makes the element invisible.
// The ng-show directive can also be used to set the visibility of a part of an application.
// The value ng-show="false" makes an HTML element invisible.
// The value ng-show="true" makes the element visible.
// Here is the same example as above, using ng-show instead of ng-hide:
<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-show="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = true;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
}
});
</script>
///////////////////////////////////
// AngularJS Modules
// An AngularJS module defines an application.
// The module is a container for the different parts of an application.
// The module is a container for the application controllers.
// Controllers always belong to a module.
// This application ("myApp") has one controller ("myCtrl"):
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
// It is common in AngularJS applications to put the module and the controllers in JavaScript files.
// In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
//myApp.js
var app = angular.module("myApp", []);
// The [] parameter in the module definition can be used to define dependent modules.
// myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
// Global functions should be avoided in JavaScript. They can easily be overwritten
// or destroyed by other scripts.
// AngularJS modules reduces this problem, by keeping all functions local to the module.
// While it is common in HTML applications to place scripts at the end of the
// <body> element, it is recommended that you load the AngularJS library either
// in the <head> or at the start of the <body>.
// This is because calls to angular.module can only be compiled after the library has been loaded.
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
///////////////////////////////////
// AngularJS Applications
// AngularJS modules define AngularJS applications.
// AngularJS controllers control AngularJS applications.
// The ng-app directive defines the application, the ng-controller directive defines the controller.
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
// AngularJS modules define applications:
var app = angular.module('myApp', []);
// AngularJS controllers control applications:
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
```
## Source & References
**Examples**
- http://www.w3schools.com/angular/angular_examples.asp
**References**
- http://www.w3schools.com/angular/angular_ref_directives.asp
- http://www.w3schools.com/angular/default.asp
- https://teamtreehouse.com/library/angular-basics/

121
ar-ar/html-ar.html.markdown Normal file
View File

@@ -0,0 +1,121 @@
---
language: html
lang: ar-ar
filename: learnhtml-tf.html
contributors:
- ["Christophe THOMAS", "https://github.com/WinChris"]
translators:
- ["Ader", "https://github.com/y1n0"]
---
HTML اختصار ل HyperText Markup Language، أي "لغة ترميز النص التشعبي".
هي لغة تمكننا من كتابة صفحات موجهة لشبكة الويب العالمي.
هي لغة توصيف للنص، تسمح بكتابة صفحات ويب عن طريق تحديد كيفية عرض النصوص والمعلومات.
في الحقيقة، ملفات html هي ملفات تحتوي على نصوص بسيطة.
ما هو توصيف النص هذا؟ هو طريقة لتنظيم معلومات النص عن طريق إحاطته بوُسوم فتح ووسوم غلق.
هذه الوسوم تعطي معاني محددة للنص الذي تحيطه.
كباقي لغات الحاسوب، هناك الكثير من إصدارات HTML. سنتحدث هنا عن HTLM5.
**ملاحظة:** يمكنك تجريب مختلف الوسوم والعناصر بينما تقرأ الدرس عبر موقع كـ [codepen](http://codepen.io/pen/) حتى ترى تأثيرها وتعرف كيف تعمل وتتعود على استعمالها.
هذه المادة تُعنى أساسا بتركيب HTML .وبعض النصائح المفيدة
```html
<!-- التعاليق تحاط بوسوم كما في هذا السطر -->
<!-- #################### الوسوم #################### -->
<!-- هنا مثال لملف html الذي سنقوم بالعمل عليه. -->
<!doctype html>
<html>
<head>
<title>موقعي</title>
</head>
<body>
<h1>مرحبا بالعالم!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">الق نظرة كيف يبدو هذا من هنا</a>
<p>هذه فقرة.</p>
<p>هذه فقرة أخرى.</p>
<ul>
<li>هذا عنصر من لائحة غير مرقمة. (لائحة بالعرائض)</li>
<li>هذا عنصر آخر</li>
<li>وهذا آخر عنصر في اللائحة</li>
</ul>
</body>
</html>
<!-- ملف HTML يُبتدأ دائما بتبيين أنه ملف HTML للمتصفح -->
<!doctype html>
<!-- بعد هذا، يبدأ بفتح الوسم <html> -->
<html>
<!-- الذي سيغلق في نهاية الملف بـ </html>. -->
</html>
<!-- لا يجب كتابة أي شيء بعد وسم النهاية ذاك. -->
<!-- داخل هذين الوسمين (<html></html>) نجد: -->
<!-- "ترئيس" محدد ب <head> (يجب أن يغلق بـ </head>) -->
<!-- الترأيس يحتوي على أوصاف وبعض المعلومات الإضافية التي لا تظهر في المتصفح, تدعي metadata (المعلومات الوصفية) -->
<head>
<title>موقعي</title><!-- الوسم <title> يحدد للمتصفح العنوان الذي يظهر في المكان المخصص للعنوان في نافذة المتصفح. -->
</head>
<!-- بعد الجزء الخاص بـ <head>، نجد الوسم <body> -->
<!-- حتى هنا، لا شيء مما كُتب سيظهر في النافذة الرئيسية للمتصفح. -->
<!-- يجب ان نملأ "جسد" الصفحة بالمحتوى الذي نريد أن نُظهر -->
<body>
<h1>مرحبا بالعالم!</h1> <!-- الوسم <h1> خاص بالعناوين الكبيرة. -->
<!-- هناك أيضا وسوم خاصة بالعناوين الفرعية من h1، الأكثر أهمية h2 والذي يليه حتى h6 الذي هو آخر عنوان داخلي. -->
<a href = "http://codepen.io/anon/pen/xwjLbZ">ألق نظرة كيف يبدو هذا من هنا</a> <!-- يظهر رابطا للصفحة التي داخل السمة href="" -->
<p>هذه فقرة.</p> <!-- يمكن من اضافة نصوص للصفحة. يميز الفقرات -->
<p>هذه فقرة أخرى.</p>
<ul> <!-- الوسم <ul> يخلق لائحة بالعرائض -->
<!-- إذا أردت لائحة مرقمة، هناك الوسم <ol>. ويكون الترتيب فيه حسب تموضع العناصر داخله، الأول فالأول. -->
<li>هذا عنصر من لائحة غير مرقمة. (لائحة بالعرائض)</li>
<li>هذا عنصر آخر</li>
<li>وهذا آخر عنصر في اللائحة</li>
</ul>
</body>
<!-- وهكذا، كتابة ملفات HTML جد بسيطة -->
<!-- يمكنك كذلك إضافة أنواع أخرى من الوسوم -->
<!-- لادخال صورة: -->
<img src="http://i.imgur.com/XWG0O.gif"/> <!-- مصدر الصورة يحدد داخل السمة: src="" -->
<!-- مصدرها يمكن أن يكون رابطا أو مسارا لصورة في حاسوبك -->
<!-- يمكنك كذلك تشكيل جداول. -->
<table> <!-- نفتح الجدول بالوسم <table> -->
<tr> <!-- <tr> تسمح بتشكيل صف. -->
<th>العنوان الأول</th> <!-- <th> تسمح لنا بإعطاء عنوان لهذا العمود. -->
<th>العنوان الثاني</th>
</tr>
<tr>
<td>الصف الأول، العمود الأول</td> <!-- <td> تسمح بتشكيل الأعمدة، أو خانات داخل كل صف. -->
<td>الصف الأول، العمود الثاني</td>
</tr>
<tr>
<td>الصف الثاني، العمود الأول</td>
<td>الصف الثاني، العمود الأول</td>
</tr>
</table>
```
## الاستعمال
HTML يُكتب في ملفات تنتهي بـ `.html`.
## لمعرفة المزيد
* [wikipedia](https://en.wikipedia.org/wiki/HTML)
* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML)
* [W3School](http://www.w3schools.com/html/html_intro.asp)

122
asciidoc.html.markdown Normal file
View File

@@ -0,0 +1,122 @@
---
language: asciidoc
contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
filename: asciidoc.md
---
AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization.
Document Header
Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line.
Title Only
```
= Document Title
First sentence of document.
```
Title and Author
```
= Document Title
First Last <first.last@learnxinyminutes.com>
Start of this document.
```
Multiple Authors
```
= Document Title
John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
Start of a doc with multiple authors.
```
Revision Line (requires an author line)
```
= Doc Title V1
Potato Man <chip@crunchy.com>
v1.0, 2016-01-13
This article about chips is going to be fun.
```
Paragraphs
```
You don't need anything special for paragraphs.
Add a blank line between paragraphs to separate them.
To create a line blank add a +
and you will receive a line break!
```
Formatting Text
```
_underscore creates italics_
*asterisks for bold*
*_combine for extra fun_*
`use ticks to signify monospace`
`*bolded monospace*`
```
Section Titles
```
= Level 0 (may only be used in document's header)
== Level 1 <h2>
=== Level 2 <h3>
==== Level 3 <h4>
===== Level 4 <h5>
====== Level 5 <h6>
======= Level 6 <h7>
```
Lists
To create a bulleted list use asterisks.
```
* foo
* bar
* baz
```
To create a numbered list use periods.
```
. item 1
. item 2
. item 3
```
You can nest lists by adding extra asterisks or periods up to five times.
```
* foo 1
** foo 2
*** foo 3
**** foo 4
***** foo 5
. foo 1
.. foo 2
... foo 3
.... foo 4
..... foo 5
```

View File

@@ -3,41 +3,52 @@ category: Algorithms & Data Structures
name: Asymptotic Notation
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Divay Prakash", "http://github.com/divayprakash"]
---
# Asymptotic Notations
## What are they?
Asymptotic Notations are languages that allow us to analyze an algorithm's running time by
identifying its behavior as the input size for the algorithm increases. This is also known as
an algorithm's growth rate. Does the algorithm suddenly become incredibly slow when the input
size grows? Does it mostly maintain its quick run time as the input size increases?
Asymptotic Notation gives us the ability to answer these questions.
Asymptotic Notations are languages that allow us to analyze an algorithm's
running time by identifying its behavior as the input size for the algorithm
increases. This is also known as an algorithm's growth rate. Does the
algorithm suddenly become incredibly slow when the input size grows? Does it
mostly maintain its quick run time as the input size increases? Asymptotic
Notation gives us the ability to answer these questions.
## Are there alternatives to answering these questions?
One way would be to count the number of primitive operations at different input sizes.
Though this is a valid solution, the amount of work this takes for even simple algorithms
does not justify its use.
One way would be to count the number of primitive operations at different
input sizes. Though this is a valid solution, the amount of work this takes
for even simple algorithms does not justify its use.
Another way is to physically measure the amount of time an algorithm takes to complete
given different input sizes. However, the accuracy and relativity (times obtained would
only be relative to the machine they were computed on) of this method is bound to
environmental variables such as computer hardware specifications, processing power, etc.
Another way is to physically measure the amount of time an algorithm takes to
complete given different input sizes. However, the accuracy and relativity
(times obtained would only be relative to the machine they were computed on)
of this method is bound to environmental variables such as computer hardware
specifications, processing power, etc.
## Types of Asymptotic Notation
In the first section of this doc we described how an Asymptotic Notation identifies the
behavior of an algorithm as the input size changes. Let us imagine an algorithm as a function
f, n as the input size, and f(n) being the running time. So for a given algorithm f, with input
size n you get some resultant run time f(n). This results in a graph where the Y axis is the
runtime, X axis is the input size, and plot points are the resultants of the amount of time
for a given input size.
In the first section of this doc we described how an Asymptotic Notation
identifies the behavior of an algorithm as the input size changes. Let us
imagine an algorithm as a function f, n as the input size, and f(n) being
the running time. So for a given algorithm f, with input size n you get
some resultant run time f(n). This results in a graph where the Y axis is the
runtime, X axis is the input size, and plot points are the resultants of the
amount of time for a given input size.
You can label a function, or algorithm, with an Asymptotic Notation in many different ways.
Some examples are, you can describe an algorithm by its best case, worse case, or equivalent case.
The most common is to analyze an algorithm by its worst case. You typically don't evaluate by best case because those conditions aren't what you're planning for. A very good example of this is sorting algorithms; specifically, adding elements to a tree structure. Best case for most algorithms could be as low as a single operation. However, in most cases, the element you're adding will need to be sorted appropriately through the tree, which could mean examining an entire branch. This is the worst case, and this is what we plan for.
You can label a function, or algorithm, with an Asymptotic Notation in many
different ways. Some examples are, you can describe an algorithm by its best
case, worse case, or equivalent case. The most common is to analyze an
algorithm by its worst case. You typically don't evaluate by best case because
those conditions aren't what you're planning for. A very good example of this
is sorting algorithms; specifically, adding elements to a tree structure. Best
case for most algorithms could be as low as a single operation. However, in
most cases, the element you're adding will need to be sorted appropriately
through the tree, which could mean examining an entire branch. This is the
worst case, and this is what we plan for.
### Types of functions, limits, and simplification
@@ -45,16 +56,25 @@ The most common is to analyze an algorithm by its worst case. You typically don'
Logarithmic Function - log n
Linear Function - an + b
Quadratic Function - an^2 + bn + c
Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some constant
Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some
constant
Exponential Function - a^n, where a is some constant
```
These are some basic function growth classifications used in various notations. The list starts at the slowest growing function (logarithmic, fastest execution time) and goes on to the fastest growing (exponential, slowest execution time). Notice that as 'n', or the input, increases in each of those functions, the result clearly increases much quicker in quadratic, polynomial, and exponential, compared to logarithmic and linear.
These are some basic function growth classifications used in various
notations. The list starts at the slowest growing function (logarithmic,
fastest execution time) and goes on to the fastest growing (exponential,
slowest execution time). Notice that as 'n', or the input, increases in each
of those functions, the result clearly increases much quicker in quadratic,
polynomial, and exponential, compared to logarithmic and linear.
One extremely important note is that for the notations about to be discussed you should do your best to use simplest terms. This means to disregard constants, and lower order terms, because as the input size (or n in our f(n)
example) increases to infinity (mathematical limits), the lower order terms and constants are of little
to no importance. That being said, if you have constants that are 2^9001, or some other ridiculous,
unimaginable amount, realize that simplifying will skew your notation accuracy.
One extremely important note is that for the notations about to be discussed
you should do your best to use simplest terms. This means to disregard
constants, and lower order terms, because as the input size (or n in our f(n)
example) increases to infinity (mathematical limits), the lower order terms
and constants are of little to no importance. That being said, if you have
constants that are 2^9001, or some other ridiculous, unimaginable amount,
realize that simplifying will skew your notation accuracy.
Since we want simplest form, lets modify our table a bit...
@@ -67,10 +87,13 @@ Exponential - a^n, where a is some constant
```
### Big-O
Big-O, commonly written as O, is an Asymptotic Notation for the worst case, or ceiling of growth
for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity
you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0),
`f(n)` <= `c g(n)` for every input size n (n > 0).
Big-O, commonly written as **O**, is an Asymptotic Notation for the worst
case, or ceiling of growth for a given function. It provides us with an
_**asymptotic upper bound**_ for the growth rate of runtime of an algorithm.
Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time
complexity you are trying to relate to your algorithm. `f(n)` is O(g(n)), if
for some real constants c (c > 0) and n<sub>0</sub>, `f(n)` <= `c g(n)` for every input size
n (n > n<sub>0</sub>).
*Example 1*
@@ -87,7 +110,7 @@ Let's look to the definition of Big-O.
3log n + 100 <= c * log n
```
Is there some constant c that satisfies this for all n?
Is there some pair of constants c, n<sub>0</sub> that satisfies this for all n > <sub>0</sub>?
```
3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1)
@@ -110,23 +133,66 @@ Let's look at the definition of Big-O.
3 * n^2 <= c * n
```
Is there some constant c that satisfies this for all n?
Is there some pair of constants c, n<sub>0</sub> that satisfies this for all n > <sub>0</sub>?
No, there isn't. `f(n)` is NOT O(g(n)).
### Big-Omega
Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate
for a given function.
Big-Omega, commonly written as **Ω**, is an Asymptotic Notation for the best
case, or a floor growth rate for a given function. It provides us with an
_**asymptotic lower bound**_ for the growth rate of runtime of an algorithm.
`f(n)` is Ω(g(n)), if for any real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0).
`f(n)` is Ω(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is >= `c g(n)`
for every input size n (n > n<sub>0</sub>).
Feel free to head over to additional resources for examples on this. Big-O is the primary notation used
for general algorithm time complexity.
### Note
The asymptotic growth rates provided by big-O and big-omega notation may or
may not be asymptotically tight. Thus we use small-o and small-omega notation
to denote bounds that are not asymptotically tight.
### Small-o
Small-o, commonly written as **o**, is an Asymptotic Notation to denote the
upper bound (that is not asymptotically tight) on the growth rate of runtime
of an algorithm.
`f(n)` is o(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of O-notation and o-notation are similar. The main difference
is that in f(n) = O(g(n)), the bound f(n) <= g(n) holds for _**some**_
constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for
_**all**_ constants c > 0.
### Small-omega
Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote
the lower bound (that is not asymptotically tight) on the growth rate of
runtime of an algorithm.
`f(n)` is ω(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of Ω-notation and ω-notation are similar. The main difference
is that in f(n) = Ω(g(n)), the bound f(n) >= g(n) holds for _**some**_
constant c > 0, but in f(n) = ω(g(n)), the bound f(n) > c g(n) holds for
_**all**_ constants c > 0.
### Theta
Theta, commonly written as **Θ**, is an Asymptotic Notation to denote the
_**asymptotically tight bound**_ on the growth rate of runtime of an algorithm.
`f(n)` is Θ(g(n)), if for some real constants c1, c2 and n<sub>0</sub> (c1 > 0, c2 > 0, n<sub>0</sub> > 0),
`c1 g(n)` is < `f(n)` is < `c2 g(n)` for every input size n (n > n<sub>0</sub>).
`f(n)` is Θ(g(n)) implies `f(n)` is O(g(n)) as well as `f(n)` is Ω(g(n)).
Feel free to head over to additional resources for examples on this. Big-O
is the primary notation use for general algorithm time complexity.
### Ending Notes
It's hard to keep this kind of topic short, and you should definitely go through the books and online
resources listed. They go into much greater depth with definitions and examples.
More where x='Algorithms & Data Structures' is on its way; we'll have a doc up on analyzing actual
code examples soon.
It's hard to keep this kind of topic short, and you should definitely go
through the books and online resources listed. They go into much greater depth
with definitions and examples. More where x='Algorithms & Data Structures' is
on its way; we'll have a doc up on analyzing actual code examples soon.
## Books
@@ -137,3 +203,4 @@ code examples soon.
* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf)
* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation)
* [Big-O Cheatsheet](http://bigocheatsheet.com/) - common structures, operations, and algorithms, ranked by complexity.

359
awk.html.markdown Normal file
View File

@@ -0,0 +1,359 @@
---
language: awk
filename: learnawk.awk
contributors:
- ["Marshall Mason", "http://github.com/marshallmason"]
lang: en
---
AWK is a standard tool on every POSIX-compliant UNIX system. It's like a
stripped-down Perl, perfect for text-processing tasks and other scripting
needs. It has a C-like syntax, but without semicolons, manual memory
management, or static typing. It excels at text processing. You can call to it
from a shell script, or you can use it as a stand-alone scripting language.
Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always
count on it, whereas Perl's future is in question. AWK is also easier to read
than Perl. For simple text-processing scripts, particularly ones that read
files line by line and split on delimiters, AWK is probably the right tool for
the job.
```awk
#!/usr/bin/awk -f
# Comments are like this
# AWK programs consist of a collection of patterns and actions. The most
# important pattern is called BEGIN. Actions go into brace blocks.
BEGIN {
# BEGIN will run at the beginning of the program. It's where you put all
# the preliminary set-up code, before you process any text files. If you
# have no text files, then think of BEGIN as the main entry point.
# Variables are global. Just set them or use them, no need to declare..
count = 0
# Operators just like in C and friends
a = count + 1
b = count - 1
c = count * 1
d = count / 1
e = count % 1 # modulus
f = count ^ 1 # exponentiation
a += 1
b -= 1
c *= 1
d /= 1
e %= 1
f ^= 1
# Incrementing and decrementing by one
a++
b--
# As a prefix operator, it returns the incremented value
++a
--b
# Notice, also, no punctuation such as semicolons to terminate statements
# Control statements
if (count == 0)
print "Starting with count of 0"
else
print "Huh?"
# Or you could use the ternary operator
print (count == 0) ? "Starting with count of 0" : "Huh?"
# Blocks consisting of multiple lines use braces
while (a < 10) {
print "String concatenation is done" " with a series" " of"
" space-separated strings"
print a
a++
}
for (i = 0; i < 10; i++)
print "Good ol' for loop"
# As for comparisons, they're the standards:
a < b # Less than
a <= b # Less than or equal
a != b # Not equal
a == b # Equal
a > b # Greater than
a >= b # Greater than or equal
# Logical operators as well
a && b # AND
a || b # OR
# In addition, there's the super useful regular expression match
if ("foo" ~ "^fo+$")
print "Fooey!"
if ("boo" !~ "^fo+$")
print "Boo!"
# Arrays
arr[0] = "foo"
arr[1] = "bar"
# Unfortunately, there is no other way to initialize an array. Ya just
# gotta chug through every value line by line like that.
# You also have associative arrays
assoc["foo"] = "bar"
assoc["bar"] = "baz"
# And multi-dimensional arrays, with some limitations I won't mention here
multidim[0,0] = "foo"
multidim[0,1] = "bar"
multidim[1,0] = "baz"
multidim[1,1] = "boo"
# You can test for array membership
if ("foo" in assoc)
print "Fooey!"
# You can also use the 'in' operator to traverse the keys of an array
for (key in assoc)
print assoc[key]
# The command line is in a special array called ARGV
for (argnum in ARGV)
print ARGV[argnum]
# You can remove elements of an array
# This is particularly useful to prevent AWK from assuming the arguments
# are files for it to process
delete ARGV[1]
# The number of command line arguments is in a variable called ARGC
print ARGC
# AWK has several built-in functions. They fall into three categories. I'll
# demonstrate each of them in their own functions, defined later.
return_value = arithmetic_functions(a, b, c)
string_functions()
io_functions()
}
# Here's how you define a function
function arithmetic_functions(a, b, c, localvar) {
# Probably the most annoying part of AWK is that there are no local
# variables. Everything is global. For short scripts, this is fine, even
# useful, but for longer scripts, this can be a problem.
# There is a work-around (ahem, hack). Function arguments are local to the
# function, and AWK allows you to define more function arguments than it
# needs. So just stick local variable in the function declaration, like I
# did above. As a convention, stick in some extra whitespace to distinguish
# between actual function parameters and local variables. In this example,
# a, b, and c are actual parameters, while d is merely a local variable.
# Now, to demonstrate the arithmetic functions
# Most AWK implementations have some standard trig functions
localvar = sin(a)
localvar = cos(a)
localvar = atan2(a, b) # arc tangent of b / a
# And logarithmic stuff
localvar = exp(a)
localvar = log(a)
# Square root
localvar = sqrt(a)
# Truncate floating point to integer
localvar = int(5.34) # localvar => 5
# Random numbers
srand() # Supply a seed as an argument. By default, it uses the time of day
localvar = rand() # Random number between 0 and 1.
# Here's how to return a value
return localvar
}
function string_functions( localvar, arr) {
# AWK, being a string-processing language, has several string-related
# functions, many of which rely heavily on regular expressions.
# Search and replace, first instance (sub) or all instances (gsub)
# Both return number of matches replaced
localvar = "fooooobar"
sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar"
gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar"
# Search for a string that matches a regular expression
# index() does the same thing, but doesn't allow a regular expression
match(localvar, "t") # => 4, since the 't' is the fourth character
# Split on a delimiter
split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"]
# Other useful stuff
sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3"
substr("foobar", 2, 3) # => "oob"
substr("foobar", 4) # => "bar"
length("foo") # => 3
tolower("FOO") # => "foo"
toupper("foo") # => "FOO"
}
function io_functions( localvar) {
# You've already seen print
print "Hello world"
# There's also printf
printf("%s %d %d %d\n", "Testing", 1, 2, 3)
# AWK doesn't have file handles, per se. It will automatically open a file
# handle for you when you use something that needs one. The string you used
# for this can be treated as a file handle, for purposes of I/O. This makes
# it feel sort of like shell scripting:
print "foobar" >"/tmp/foobar.txt"
# Now the string "/tmp/foobar.txt" is a file handle. You can close it:
close("/tmp/foobar.txt")
# Here's how you run something in the shell
system("echo foobar") # => prints foobar
# Reads a line from standard input and stores in localvar
getline localvar
# Reads a line from a pipe
"echo foobar" | getline localvar # localvar => "foobar"
close("echo foobar")
# Reads a line from a file and stores in localvar
getline localvar <"/tmp/foobar.txt"
close("/tmp/foobar.txt")
}
# As I said at the beginning, AWK programs consist of a collection of patterns
# and actions. You've already seen the all-important BEGIN pattern. Other
# patterns are used only if you're processing lines from files or standard
# input.
#
# When you pass arguments to AWK, they are treated as file names to process.
# It will process them all, in order. Think of it like an implicit for loop,
# iterating over the lines in these files. these patterns and actions are like
# switch statements inside the loop.
/^fo+bar$/ {
# This action will execute for every line that matches the regular
# expression, /^fo+bar$/, and will be skipped for any line that fails to
# match it. Let's just print the line:
print
# Whoa, no argument! That's because print has a default argument: $0.
# $0 is the name of the current line being processed. It is created
# automatically for you.
# You can probably guess there are other $ variables. Every line is
# implicitely split before every action is called, much like the shell
# does. And, like the shell, each field can be access with a dollar sign
# This will print the second and fourth fields in the line
print $2, $4
# AWK automatically defines many other variables to help you inspect and
# process each line. The most important one is NF
# Prints the number of fields on this line
print NF
# Print the last field on this line
print $NF
}
# Every pattern is actually a true/false test. The regular expression in the
# last pattern is also a true/false test, but part of it was hidden. If you
# don't give it a string to test, it will assume $0, the line that it's
# currently processing. Thus, the complete version of it is this:
$0 ~ /^fo+bar$/ {
print "Equivalent to the last pattern"
}
a > 0 {
# This will execute once for each line, as long as a is positive
}
# You get the idea. Processing text files, reading in a line at a time, and
# doing something with it, particularly splitting on a delimiter, is so common
# in UNIX that AWK is a scripting language that does all of it for you, without
# you needing to ask. All you have to do is write the patterns and actions
# based on what you expect of the input, and what you want to do with it.
# Here's a quick example of a simple script, the sort of thing AWK is perfect
# for. It will read a name from standard input and then will print the average
# age of everyone with that first name. Let's say you supply as an argument the
# name of a this data file:
#
# Bob Jones 32
# Jane Doe 22
# Steve Stevens 83
# Bob Smith 29
# Bob Barker 72
#
# Here's the script:
BEGIN {
# First, ask the user for the name
print "What name would you like the average age for?"
# Get a line from standard input, not from files on the command line
getline name <"/dev/stdin"
}
# Now, match every line whose first field is the given name
$1 == name {
# Inside here, we have access to a number of useful variables, already
# pre-loaded for us:
# $0 is the entire line
# $3 is the third field, the age, which is what we're interested in here
# NF is the number of fields, which should be 3
# NR is the number of records (lines) seen so far
# FILENAME is the name of the file being processed
# FS is the field separator being used, which is " " here
# ...etc. There are plenty more, documented in the man page.
# Keep track of a running total and how many lines matched
sum += $3
nlines++
}
# Another special pattern is called END. It will run after processing all the
# text files. Unlike BEGIN, it will only run if you've given it input to
# process. It will run after all the files have been read and processed
# according to the rules and actions you've provided. The purpose of it is
# usually to output some kind of final report, or do something with the
# aggregate of the data you've accumulated over the course of the script.
END {
if (nlines)
print "The average age for " name " is " sum / nlines
}
```
Further Reading:
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
* [Awk man page](https://linux.die.net/man/1/awk)
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems.

View File

@@ -11,6 +11,10 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gregrory Kielian", "https://github.com/gskielian"]
- ["Etan Reisner", "https://github.com/deryni"]
- ["Jonathan Wang", "https://github.com/Jonathansw"]
- ["Leo Rudberg", "https://github.com/LOZORD"]
- ["Betsy Lorton", "https://github.com/schbetsy"]
- ["John Detter", "https://github.com/jdetter"]
filename: LearnBash.sh
---
@@ -54,6 +58,13 @@ echo '$Variable'
# its name without $. If you want to use the variable's value, you should use $.
# Note that ' (single quote) won't expand the variables!
# Parameter expansion ${ }:
echo ${Variable}
# This is a simple usage of parameter expansion
# Parameter Expansion gets a value from a variable. It "expands" or prints the value
# During the expansion time the value or parameter are able to be modified
# Below are other modifications that add onto this expansion
# String substitution in variables
echo ${Variable/Some/A}
# This will substitute the first occurrence of "Some" with "A"
@@ -68,6 +79,12 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.
# Brace Expansion { }
# Used to generate arbitrary strings
echo {1..10}
echo {a..z}
# This will output the range from the start value to the end value
# Builtin variables:
# There are some useful builtin variables, like
echo "Last program's return value: $?"
@@ -76,6 +93,21 @@ echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "Script's arguments separated into different variables: $1 $2..."
# Now that we know how to echo and use variables,
# let's learn some of the other basics of bash!
# Our current directory is available through the command `pwd`.
# `pwd` stands for "print working directory".
# We can also use the builtin variable `$PWD`.
# Observe that the following are equivalent:
echo "I'm in $(pwd)" # execs `pwd` and interpolates output
echo "I'm in $PWD" # interpolates the variable
# If you get too much output in your terminal, or from a script, the command
# `clear` clears your screen
clear
# Ctrl-L also works for clearing output
# Reading a value from input:
echo "What's your name?"
read Name # Note that we didn't need to declare a new variable
@@ -124,12 +156,54 @@ ls
# These commands have options that control their execution:
ls -l # Lists every file and directory on a separate line
ls -t # Sorts the directory contents by last-modified date (descending)
ls -R # Recursively `ls` this directory and all of its subdirectories
# Results of the previous command can be passed to the next command as input.
# grep command filters the input with provided patterns. That's how we can list
# .txt files in the current directory:
ls -l | grep "\.txt"
# Use `cat` to print files to stdout:
cat file.txt
# We can also read the file using `cat`:
Contents=$(cat file.txt)
echo "START OF FILE\n$Contents\nEND OF FILE"
# Use `cp` to copy files or directories from one place to another.
# `cp` creates NEW versions of the sources,
# so editing the copy won't affect the original (and vice versa).
# Note that it will overwrite the destination if it already exists.
cp srcFile.txt clone.txt
cp -r srcDirectory/ dst/ # recursively copy
# Look into `scp` or `sftp` if you plan on exchanging files between computers.
# `scp` behaves very similarly to `cp`.
# `sftp` is more interactive.
# Use `mv` to move files or directories from one place to another.
# `mv` is similar to `cp`, but it deletes the source.
# `mv` is also useful for renaming files!
mv s0urc3.txt dst.txt # sorry, l33t hackers...
# Since bash works in the context of a current directory, you might want to
# run your command in some other directory. We have cd for changing location:
cd ~ # change to home directory
cd .. # go up one directory
# (^^say, from /home/username/Downloads to /home/username)
cd /home/username/Documents # change to specified directory
cd ~/Documents/.. # still in home directory..isn't it??
# Use subshells to work across directories
(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD")
pwd # still in first directory
# Use `mkdir` to create new directories.
mkdir myNewDir
# The `-p` flag causes new intermediate directories to be created as necessary.
mkdir -p myNewDir/with/intermediate/directories
# You can redirect command input and output (stdin, stdout, and stderr).
# Read from stdin until ^EOF$ and overwrite hello.py with the lines
# between "EOF":
@@ -168,7 +242,9 @@ echo "#helloworld" | cat > output.out
echo "#helloworld" | tee output.out >/dev/null
# Cleanup temporary files verbosely (add '-i' for interactive)
# WARNING: `rm` commands cannot be undone
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively delete
# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
@@ -259,10 +335,25 @@ sed -i 's/okay/great/g' file.txt
grep "^foo.*bar$" file.txt
# pass the option "-c" to instead print the number of lines matching the regex
grep -c "^foo.*bar$" file.txt
# Other useful options are:
grep -r "^foo.*bar$" someDir/ # recursively `grep`
grep -n "^foo.*bar$" file.txt # give line numbers
grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files
# perform the same initial search, but filter out the lines containing "baz"
grep "^foo.*bar$" file.txt | grep -v "baz"
# if you literally want to search for the string,
# and not the regex, use fgrep (or grep -F)
fgrep "^foo.*bar$" file.txt
fgrep "foobar" file.txt
# trap command allows you to execute a command when a signal is received by your script.
# Here trap command will execute rm if any one of the three listed signals is received.
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM
# `sudo` is used to perform commands as the superuser
NAME1=$(whoami)
NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"
# Read Bash shell builtins documentation with the bash 'help' builtin:
help

View File

@@ -1,5 +1,5 @@
---
language: brainfuck
language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
@@ -10,7 +10,7 @@ minimal Turing-complete programming language with just 8 commands.
You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
```
```bf
Any character not "><+-.,[]" (excluding quotation marks) is ignored.
Brainfuck is represented by an array with 30,000 cells initialized to zero

326
bg-bg/perl-bg.html.markdown Normal file
View File

@@ -0,0 +1,326 @@
---
name: perl
category: language
language: perl
filename: learnperl.pl
contributors:
- ["Korjavin Ivan", "http://github.com/korjavin"]
- ["Dan Book", "http://github.com/Grinnz"]
translators:
- ["Красимир Беров", "https://github.com/kberov"]
lang: bg-bg
---
Perl 5 е изключително мощен език за програмиране с широка област на приложение
и над 25 годишна история.
Perl 5 работи на повече от 100 операционни системи от мини до супер-компютри и е
подходящ както за бърза разработка на скриптове така и за огромни приложения.
```perl
# Едноредовите коментари започват със знака диез.
#### Стриктен режим и предупреждения
use strict;
use warnings;
# Силно препоръчително е всички скриптове и модули да включват тези редове.
# strict спира компилацията в случай на необявени предварително променливи.
# warnings показва предупредителни съобщения в случай на често допускани грешки,
# например използване на променливи без стойност в низове.
#### Типове променливи в Perl
# Променливите започват със съответен знак (sigil - от латински sigillum ),
# който представлява символ, указващ типа на променливата. Името на самата
# променлива започва с буква или знак за подчертаване (_), следван от какъвто и
# да е брой букви, цифри или знаци за подчертаване. Забележете, че ако напишете
# 'use utf8;' (без кавичките), можете да използвате всякакви букви за имена на
# променливите, включително и български.
### Perl има три главни типа променливи: $scalar (скалар), @array (масив), and %hash (хеш).
## Скалари
# Скаларът представлява единична стойност:
my $animal = "camel";
my $answer = 42;
use utf8;
my $животно = 'камила';
# Стойностите на скаларите могат да бъдат низове, цели числа или числа с
# плаваща запетая (десетични дроби). Perl автоматично ги ползва и превръща от
# един тип стойност в друга, според както е необходимо.
## Масиви
# Масивът представлява списък от стойности:
my @animals = ("камила", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
# Елементите на масива се достъпват като се използват квадратни скоби и $,
# който указва каква стойност ще бъде върната (скалар).
my $second = $animals[1];
## Хешове
# Хешът представлява набор от двойки ключ/стойност:
my %fruit_color = ("ябълка", "червена", "banana", "yellow");
# Може да използвате празно пространство и оператора "=>" (тлъста запетая),
# за да ги изложите по-прегледно:
%fruit_color = (
ябълка => "червена",
banana => "yellow",
);
# Елементите (стойностите) от хеша се достъпват чрез използване на ключовете.
# Ключовете се ограждат с фигурни скоби и се поставя $ пред името на хеша.
my $color = $fruit_color{ябълка};
# Скаларите, масивите и хешовете са документирани по-пълно в perldata.
# На командния ред напишете (без кавичките) 'perldoc perldata'.
#### Указатели (Референции)
# По-сложни типове данни могат да бъдат създавани чрез използване на указатели,
# които ви позволяват да изграждате масиви и хешове в други масиви и хешове.
my $array_ref = \@array;
my $hash_ref = \%hash;
my @array_of_arrays = (\@array1, \@array2, \@array3);
# Също така можете да създавате безименни масиви и хешове, към които сочат само
# указатели.
my $fruits = ["apple", "banana"];
my $colors = {apple => "red", banana => "yellow"};
# Можете да достигате до безименните структури като поставяте отпред съответния
# знак на структурата, която искате да достъпите (дереферирате).
my @fruits_array = @$fruits;
my %colors_hash = %$colors;
# Можете да използвате оператора стрелка (->), за да достигнете до отделна
# скаларна стойност.
my $first = $array_ref->[0];
my $value = $hash_ref->{banana};
# Вижте perlreftut и perlref, където ще намерите по-задълбочена документация за
# указателите (референциите).
#### Условни изрази и цикли
# В Perl ще срещнете повечето от обичайните изрази за условия и обхождане (цикли).
if ($var) {
...
} elsif ($var eq 'bar') {
...
} else {
...
}
unless (условие) {
...
}
# Това е друг, по-четим вариант на "if (!условие)"
# Perl-овския начин след-условие
print "Yow!" if $zippy;
print "Нямаме банани" unless $bananas;
# докато
while (условие) {
...
}
# цикли for и повторение
for (my $i = 0; $i < $max; $i++) {
print "index is $i";
}
for (my $i = 0; $i < @elements; $i++) {
print "Current element is " . $elements[$i];
}
for my $element (@elements) {
print $element;
}
# мълчаливо - използва се подразбиращата се променлива $_.
for (@elements) {
print;
}
# Отново Perl-овския начин след-
print for @elements;
# отпечатване на стойностите чрез обхождане ключовете на указател към хеш
print $hash_ref->{$_} for keys %$hash_ref;
#### Регулярни (обикновени) изрази
# Поддръжката на регулярни изрази е залеганала дълбоко в Perl. Задълбочена
# документация ще намерите в perlrequick, perlretut и на други места.
# Но ето накратко:
# Просто съвпадение
if (/foo/) { ... } # истина ако $_ съдържа "foo"
if ($x =~ /foo/) { ... } # истина ако $x съдържа "foo"
# Просто заместване
$x =~ s/foo/bar/; # замества foo с bar в $x
$x =~ s/foo/bar/g; # Замества ВСИЧКИ ПОЯВИ на foo с bar в $x
#### Файлове и Вход/Изход (I/O)
# Можете да отворите файл за въвеждане на данни в него или за извеждане на
# данни от него като използвате функцията "open()".
open(my $in, "<", "input.txt") or die "Не мога да отворя input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Можете да четете от отворен файлов манипулатор като използвате оператора
# "<>". В скаларен контекст той чете по един ред от файла наведнъж, а в списъчен
# контекст изчита всички редове от файла наведнъж като присвоява всеки ред на
# масива:
my $line = <$in>;
my @lines = <$in>;
#### Подпрограми (функции)
# Да се пишат подпрограми е лесно:
sub logger {
my $logmessage = shift;
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
print $logfile $logmessage;
}
# Сега можем да ползваме подпрограмата като всяка друга вградена функция:
logger("Имаме подпрограма, която пише във файл-отчет!");
#### Модули
# Модулът е набор от програмен код на Perl, обикновено подпрограми, който може
# да бъде използван в друг програмен код на Perl. Обикновено се съхранява във
# файл с разширение .pm, така че perl (програмата) да може лесно да го разпознае.
# В MyModule.pm
package MyModule;
use strict;
use warnings;
sub trim {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
1;
# От другаде:
use MyModule;
MyModule::trim($string);
# Чрез модула Exporter може да направите функциите си износни, така че други
# програми да могат да ги внасят (импортират).
# Такива функции се използват така:
use MyModule 'trim';
trim($string);
# Много Perl-модули могат да се свалят от CPAN (http://www.cpan.org/). Те
# притежават редица полезни свойства, които ще ви помогнат да си свършите работа
# без да откривате колелото. Голям брой известни модули като Exporter са включени
# в дистрибуцията на самия Perl. Вижте perlmod за повече подробности, свързани с
# модулите в Perl.
#### Обекти
# Обектите в Perl са просто референции, които знаят на кой клас (пакет)
# принадлежат. По този начин методите (подпрограми), които се извикват срещу
# тях могат да бъдат намерени в съответния клас. За да се случи това, в
# конструкторите (обикновено new) се използва вградената функция
# bless. Ако използвате обаче модули като Moose или Moo, няма да ви се налага
# сами да извиквате bless (ще видите малко по-долу).
package MyCounter;
use strict;
use warnings;
sub new {
my $class = shift;
my $self = {count => 0};
return bless $self, $class;
}
sub count {
my $self = shift;
return $self->{count};
}
sub increment {
my $self = shift;
$self->{count}++;
}
1;
# Методите могат да се извикват на клас или на обект като се използва оператора
# стрелка (->).
use MyCounter;
my $counter = MyCounter->new;
print $counter->count, "\n"; # 0
$counter->increment;
print $counter->count, "\n"; # 1
# Модулите Moose и Moo от CPAN ви помагат леснот да създавате класове. Те
# предоставят готов конструктор (new) и прост синтаксис за деклариране на
# свойства на обектите (attributes). Този клас може да се използва по същия начин
# като предишния по-горе.
package MyCounter;
use Moo; # внася strict и warnings
has 'count' => (is => 'rwp', default => 0, init_arg => undef);
sub increment {
my $self = shift;
$self->_set_count($self->count + 1);
}
1;
# Обектно-ориентираното програмиране е разгледано по-задълбочено в perlootut,
# а изпълнението му на ниско ниво в Perl е обяснено в perlobj.
```
#### Често задавани въпроси (FAQ)
# perlfaq съдържа въпроси и отговори, отнасящи се до много общи задачи и предлага
# за ползване добри модлули от CPAN, подходящи за решаване на различни проблеми.
#### Повече за четене
- [Въведение в Perl](http://www.slideshare.net/kberov/01-intro-bg)
- [PERL - Курс на МГУ "Св.Иван Рилски" (13 ЧАСТИ)](http://www.mgu.bg/drugi/ebooks/belchevski/perl.html)
- [perl-tutorial](http://perl-tutorial.org/)
- [Learn at www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- и идващото с perl: `perldoc perlintro`

View File

@@ -6,6 +6,8 @@ contributors:
- ["Matt Kline", "https://github.com/mrkline"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Connor Waters", "http://github.com/connorwaters"]
- ["Ankush Goyal", "http://github.com/ankushg07"]
- ["Jatin Dhankhar", "https://github.com/jatindhankhar"]
lang: en
---
@@ -215,7 +217,7 @@ cout << myString + myOtherString; // "Hello World"
cout << myString + " You"; // "Hello You"
// C++ strings are mutable and have value semantics.
// C++ strings are mutable.
myString.append(" Dog");
cout << myString; // "Hello Dog"
@@ -454,7 +456,7 @@ void Dog::print() const
Dog::~Dog()
{
cout << "Goodbye " << name << "\n";
std::cout << "Goodbye " << name << "\n";
}
int main() {
@@ -806,8 +808,8 @@ void doSomethingWithAFile(const std::string& filename)
// have default comparators, but you can override it.
class Foo {
public:
int j;
Foo(int a) : j(a) {}
int j;
Foo(int a) : j(a) {}
};
struct compareFunction {
bool operator()(const Foo& a, const Foo& b) const {
@@ -940,29 +942,13 @@ Foo f1;
f1 = f2;
// How to truly clear a container:
class Foo { ... };
vector<Foo> v;
for (int i = 0; i < 10; ++i)
v.push_back(Foo());
// Following line sets size of v to 0, but destructors don't get called
// and resources aren't released!
v.clear();
v.push_back(Foo()); // New value is copied into the first Foo we inserted
// Truly destroys all values in v. See section about temporary objects for
// explanation of why this works.
v.swap(vector<Foo>());
///////////////////////////////////////
// Tuples (C++11 and above)
///////////////////////////////////////
#include<tuple>
// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members ,
// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members,
// its elements are accessed by their order in the tuple.
// We start with constructing a tuple.
@@ -972,10 +958,10 @@ const int maxN = 1e9;
const int maxL = 15;
auto second = make_tuple(maxN, maxL);
// printing elements of 'first' tuple
// Printing elements of 'first' tuple
cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A
// printing elements of 'second' tuple
// Printing elements of 'second' tuple
cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15
// Unpacking tuple into variables
@@ -995,12 +981,149 @@ cout << tuple_size<decltype(third)>::value << "\n"; // prints: 3
// tuple_cat concatenates the elements of all the tuples in the same order.
auto concatenated_tuple = tuple_cat(first, second, third);
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141)
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141)
cout << get<0>(concatenated_tuple) << "\n"; // prints: 10
cout << get<3>(concatenated_tuple) << "\n"; // prints: 15
cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A'
/////////////////////
// Containers
/////////////////////
// Containers or the Standard Template Library are some predefined templates.
// They manage the storage space for its elements and provide
// member functions to access and manipulate them.
// Few containers are as follows:
// Vector (Dynamic array)
// Allow us to Define the Array or list of objects at run time
#include<vector>
vector<Data_Type> Vector_name; // used to initialize the vector
cin >> val;
Vector_name.push_back(val); // will push the value of variable into array
// To iterate through vector, we have 2 choices:
// Normal looping
for(int i=0; i<Vector_name.size(); i++)
// It will iterate through the vector from index '0' till last index
// Iterator
vector<Data_Type>::iterator it; // initialize the iterator for vector
for(it=vector_name.begin(); it!=vector_name.end();++it)
// For accessing the element of the vector
// Operator []
var = vector_name[index]; // Will assign value at that index to var
// Set
// Sets are containers that store unique elements following a specific order.
// Set is a very useful container to store unique values in sorted order
// without any other functions or code.
#include<set>
set<int> ST; // Will initialize the set of int data type
ST.insert(30); // Will insert the value 30 in set ST
ST.insert(10); // Will insert the value 10 in set ST
ST.insert(20); // Will insert the value 20 in set ST
ST.insert(30); // Will insert the value 30 in set ST
// Now elements of sets are as follows
// 10 20 30
// To erase an element
ST.erase(20); // Will erase element with value 20
// Set ST: 10 30
// To iterate through Set we use iterators
set<int>::iterator it;
for(it=ST.begin();it<ST.end();it++) {
cout << *it << endl;
}
// Output:
// 10
// 30
// To clear the complete container we use Container_name.clear()
ST.clear();
cout << ST.size(); // will print the size of set ST
// Output: 0
// NOTE: for duplicate elements we can use multiset
// Map
// Maps store elements formed by a combination of a key value
// and a mapped value, following a specific order.
#include<map>
map<char, int> mymap; // Will initialize the map with key as char and value as int
mymap.insert(pair<char,int>('A',1));
// Will insert value 1 for key A
mymap.insert(pair<char,int>('Z',26));
// Will insert value 26 for key Z
// To iterate
map<char,int>::iterator it;
for (it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << "->" << it->second << '\n';
// Output:
// A->1
// Z->26
// To find the value corresponding to a key
it = mymap.find('Z');
cout << it->second;
// Output: 26
///////////////////////////////////
// Logical and Bitwise operators
//////////////////////////////////
// Most of the operators in C++ are same as in other languages
// Logical operators
// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or
// evaluated only if the first argument does not suffice to determine the value of the expression
true && false // Performs **logical and** to yield false
true || false // Performs **logical or** to yield true
! true // Performs **logical not** to yield false
// Instead of using symbols equivalent keywords can be used
true and false // Performs **logical and** to yield false
true or false // Performs **logical or** to yield true
not true // Performs **logical not** to yield false
// Bitwise operators
// **<<** Left Shift Operator
// << shifts bits to the left
4 << 1 // Shifts bits of 4 to left by 1 to give 8
// x << n can be thought as x * 2^n
// **>>** Right Shift Operator
// >> shifts bits to the right
4 >> 1 // Shifts bits of 4 to right by 1 to give 2
// x >> n can be thought as x / 2^n
~4 // Performs a bitwise not
4 | 3 // Performs bitwise or
4 & 3 // Performs bitwise and
4 ^ 3 // Performs bitwise xor
// Equivalent keywords are
compl 4 // Performs a bitwise not
4 bitor 3 // Performs bitwise or
4 bitand 3 // Performs bitwise and
4 xor 3 // Performs bitwise xor
```
Further Reading:

View File

@@ -36,7 +36,6 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
// Import headers with #include
#include <stdlib.h>
#include <stdio.h>
@@ -114,7 +113,6 @@ int main (int argc, char** argv)
// sizeof(obj) yields the size of the expression (variable, literal, etc.).
printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
// If the argument of the `sizeof` operator is an expression, then its argument
// is not evaluated (except VLAs (see below)).
// The value it yields in this case is a compile-time constant.
@@ -130,7 +128,6 @@ int main (int argc, char** argv)
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};
@@ -146,9 +143,9 @@ int main (int argc, char** argv)
// can be declared as well. The size of such an array need not be a compile
// time constant:
printf("Enter the array size: "); // ask the user for an array size
int size;
fscanf(stdin, "%d", &size);
int var_length_array[size]; // declare the VLA
int array_size;
fscanf(stdin, "%d", &array_size);
int var_length_array[array_size]; // declare the VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
// Example:
@@ -205,7 +202,7 @@ int main (int argc, char** argv)
11 % 3; // => 2
// Comparison operators are probably familiar, but
// there is no Boolean type in c. We use ints instead.
// there is no Boolean type in C. We use ints instead.
// (Or _Bool or bool in C99.)
// 0 is false, anything else is true. (The comparison
// operators always yield 0 or 1.)
@@ -239,11 +236,9 @@ int main (int argc, char** argv)
z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
// Increment and decrement operators:
char *s = "ILoveC";
int j = 0;
s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
j = 0;
s[++j]; // => "L". Increments value of j THEN returns j-th value of s.
int s = j++; // Return j THEN increase j. (s = 0, j = 1)
s = ++j; // Increase j THEN return j. (s = 2, j = 2)
// same with j-- and --j
// Bitwise operators!
@@ -274,7 +269,7 @@ int main (int argc, char** argv)
// While loops exist
int ii = 0;
while (ii < 10) { //ANY value not zero is true.
while (ii < 10) { //ANY value less than ten is true.
printf("%d, ", ii++); // ii++ increments ii AFTER using its current value.
} // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
@@ -347,7 +342,6 @@ int main (int argc, char** argv)
this will print out "Error occured at i = 52 & j = 99."
*/
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
@@ -386,7 +380,6 @@ int main (int argc, char** argv)
// (%p formats an object pointer of type void *)
// => Prints some address in memory;
// Pointers start with * in their declaration
int *px, not_a_pointer; // px is a pointer to an int
px = &x; // Stores the address of x in px
@@ -432,7 +425,6 @@ int main (int argc, char** argv)
printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr);
// probably prints "40, 4" or "40, 8"
// Pointers are incremented and decremented based on their type
// (this is called pointer arithmetic)
printf("%d\n", *(x_ptr + 1)); // => Prints 19
@@ -455,7 +447,8 @@ int main (int argc, char** argv)
int size = 10;
int *my_arr = malloc(sizeof(int) * size);
// Add an element to the array
my_arr = realloc(my_arr, ++size);
size++;
my_arr = realloc(my_arr, sizeof(int) * size);
my_arr[10] = 5;
// Dereferencing memory that you haven't allocated gives
@@ -518,6 +511,7 @@ void str_reverse(char *str_in)
str_in[len - ii - 1] = tmp;
}
}
//NOTE: string.h header file needs to be included to use strlen()
/*
char c[] = "This is a test.";
@@ -578,8 +572,6 @@ void testFunc2() {
}
//**You may also declare functions as static to make them private**
///////////////////////////////////////
// User-defined types and structs
///////////////////////////////////////
@@ -696,6 +688,7 @@ typedef void (*my_fnp_type)(char *);
"%o"; // octal
"%%"; // prints %
*/
///////////////////////////////////////
// Order of Evaluation
///////////////////////////////////////
@@ -722,14 +715,14 @@ typedef void (*my_fnp_type)(char *);
/******************************* Header Files **********************************
Header files are an important part of c as they allow for the connection of c
source files and can simplify code and definitions by seperating them into
seperate files.
Header files are an important part of C as they allow for the connection of C
source files and can simplify code and definitions by separating them into
separate files.
Header files are syntactically similar to c source files but reside in ".h"
files. They can be included in your c source file by using the precompiler
Header files are syntactically similar to C source files but reside in ".h"
files. They can be included in your C source file by using the precompiler
command #include "example.h", given that example.h exists in the same directory
as the c file.
as the C file.
*/
/* A safe guard to prevent the header from being defined too many times. This */
@@ -760,12 +753,12 @@ enum traffic_light_state {GREEN, YELLOW, RED};
/* Function prototypes can also be defined here for use in multiple files, */
/* but it is bad practice to define the function in the header. Definitions */
/* should instead be put in a c file. */
/* should instead be put in a C file. */
Node createLinkedList(int *vals, int len);
/* Beyond the above elements, other definitions should be left to a c source */
/* file. Excessive includeds or definitions should, also not be contained in */
/* a header file but instead put into separate headers or a c file. */
/* Beyond the above elements, other definitions should be left to a C source */
/* file. Excessive includes or definitions should, also not be contained in */
/* a header file but instead put into separate headers or a C file. */
#endif /* End of the if precompiler directive. */
@@ -782,8 +775,8 @@ If you have a question, read the [compl.lang.c Frequently Asked Questions](http:
It's very important to use proper spacing, indentation and to be consistent with your coding style in general.
Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the
[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
[Linux kernel coding style](https://www.kernel.org/doc/Documentation/process/coding-style.rst).
Other than that, Google is your friend.
[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
[1] [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member)

464
ca-es/go-ca.html.markdown Normal file
View File

@@ -0,0 +1,464 @@
---
name: Go
category: language
language: Go
lang: ca-es
filename: learngo-ca.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["Christopher Bess", "https://github.com/cbess"]
- ["Jesse Johnson", "https://github.com/holocronweaver"]
- ["Quint Guvernator", "https://github.com/qguv"]
- ["Jose Donizetti", "https://github.com/josedonizetti"]
- ["Alexej Friesen", "https://github.com/heyalexej"]
- ["Clayton Walker", "https://github.com/cwalk"]
- ["Leonid Shevtsov", "https://github.com/leonid-shevtsov"]
translators:
- ["Xavier Sala", "http://github.com/utrescu"]
---
Go es va crear degut a la necessitat de fer la feina ràpidament. No segueix
la darrera tendència en informàtica, però és la nova forma i la més ràpida de
resoldre problemes reals.
conceptes familiars de llenguatges imperatius amb tipat estàtic. És ràpid
compilant i ràpid al executar, afegeix una forma fàcil d'entedre de
concurrència per CPUs de diferents núclis i característiques que ajuden en
la programació a gran escala.
Go una gran llibreria de funcions estàndard i una comunitat d'usuaris
entusiasta.
```go
// Comentari d'una sola línia
/* Comentari
multilínia */
// La clausula `package` apareix sempre a sobre de cada fitxer de codi font.
// Quan es desenvolupa un executable en comptes d'una llibreria el nom que
// s'ha de fer servir de `package` ha de ser 'main'.
package main
// `import` es fa servir per indicar quins paquets de llibreries fa servir
// aquest fitxer.
import (
"fmt" // Un paquet de la llibreria estàndard de Go.
"io/ioutil" // Les funcions ioutil de io
m "math" // La llibreria de matemàtiques que es referenciarà com a m.
"net/http" // Si, un servidor web!
"os" // funcions per treballar amb el sistema de fitxers
"strconv" // Conversions de cadenes
)
// La definició d'una funció. `main` és especial. És el punt d'entrada per
// l'executable. Tant si t'agrada com si no, Go fa servir corxets.
func main() {
// Println imprimeix una línia al canal de sortida.
// Es qualifica amb el nom del paquet, fmt.
fmt.Println("Hola món!")
// Crida a una altra funció dins d'aquest paquet.
mesEnllaDeHola()
}
// Els paràmetres de les funcions es posen dins de parèntesis.
// Els parèntesis fan falta encara que no hi hagi cap paràmetre.
func mesEnllaDeHola() {
var x int // Declaració d'una variable.
// S'han de declarar abans de fer-les servir.
x = 3 // Assignació d'una variable
// Hi ha una forma "Curta" amb :=
// Descobreix el tipus, declara la variable i li assigna valor.
y := 4
sum, prod := learnMultiple(x, y) // La funció retorna dos valors.
fmt.Println("sum:", sum, "prod:", prod) // Sortida simple.
aprenTipus() // < y minuts, aprèn més!
}
/* <- comentari multilínia
Les funcions poden tenir paràmetres i (multiples!) valors de retorn.
Aquí `x`, `y` són els argumens i `sum` i `prod` són els valors retornats.
Fixa't que `x` i `sum` reben el tipus `int`.
*/
func learnMultiple(x, y int) (sum, prod int) {
return x + y, x * y // Retorna dos valors.
}
// Alguns tipus incorporats i literals.
func aprenTipus() {
// Normalment la declaració curta et dóna el que vols.
str := "Learn Go!" // tipus string
s2 := `Un tipus cadena "normal" pot tenir
salts de línia.` // El mateix tipus
// literals Non-ASCII literal. El tipus de Go és UTF-8.
g := 'Σ' // El tipus rune, és un àlies de int32 conté un caràcter unicode.
f := 3.14195 // float64, un número de 64 bits amb coma flotant IEEE-754.
c := 3 + 4i // complex128, representat internament amb dos float64.
// Sintaxi amb var i inicialitzadors.
var u uint = 7 // Sense signe, però depèn de la mida com els int.
var pi float32 = 22. / 7
// Conversió de tipus amb declaració curta.
n := byte('\n') // byte és un àlies de uint8.
// Les taules tenen mida fixa en temps de compilació.
var a4 [4]int // Taula de 4 enters inicialitzats a zero.
a3 := [...]int{3, 1, 5} // Taula inicialitzada amb tres elements
// amb els valors 3, 1, i 5.
// Els "Slices" tenen mida dinàmica. Tant les taules com els "slices"
// tenen avantatges però és més habitual que es facin servir slices.
s3 := []int{4, 5, 9} // Compara amb a3. Aquí no hi ha els tres punts
s4 := make([]int, 4) // Crea un slice de 4 enters inicialitzats a zero.
var d2 [][]float64 // Només es declara però no hi ha valors.
bs := []byte("a slice") // Sintaxi de conversió de tipus.
// Com que són dinàmics es poden afegir valors nous als slices.
// Per afegir-hi elements es fa servir el mètode append().
// El primer argument és l'slice en el que s'afegeix.
// Sovint ell mateix com aquí sota.
s := []int{1, 2, 3} // Un slice amb tres elements.
s = append(s, 4, 5, 6) // Ara s tindrà tres elements més
fmt.Println(s) // El resultat serà [1 2 3 4 5 6]
// Per afegir un slice dins d'un altre en comptes de valors atòmics
// S'hi pot passar una referència a l'altre slice o un literal acabat
// amb tres punts, que vol dir que s'ha de desempaquetar els elements
// i afegir-los a "s"
s = append(s, []int{7, 8, 9}...) // El segon argument és un slice
fmt.Println(s) // El resultat ara és [1 2 3 4 5 6 7 8 9]
p, q := aprenMemoria() // Declara p i q com a punters de int.
fmt.Println(*p, *q) // * segueix el punter fins a trobar els valors
// Els "Mapes" són taules dinàmiques associatives com els hash o els
// diccionaris d'altres llenguatges.
m := map[string]int{"tres": 3, "quatre": 4}
m["un"] = 1
// En Go les variables que no es fan servir generen un error.
// El subratllat permet fer servir una variable i descartar-ne el valor.
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
// És útil per descartar algun dels valors retornats per una funció
// Per exemple, es pot ignorar l'error retornat per os.Create amb la idea
// de que sempre es crearà.
file, _ := os.Create("output.txt")
fmt.Fprint(file, "Així es pot escriure en un fitxer")
file.Close()
// La sortida compta com a ús d'una variable.
fmt.Println(s, c, a4, s3, d2, m)
aprenControlDeFluxe() // Tornem.
}
// A diferència d'altres llenguatges les funcions poden retornar valors amb
// nom. Assignant un nom al valor retornat en la declaració de la funció
// permet retornar valors des de diferents llocs del programa a més de posar
// el return sense valors
func aprenRetornAmbNoms(x, y int) (z int) {
z = x * y
return // el retorn de z és implícit perquè ja té valor
}
// Go té un recollidor de basura.
// Té punters però no té aritmetica de punters
// Es poden cometre errors amb un punter a nil però no incrementant-lo.
func aprenMemoria() (p, q *int) {
// Els valors retornats p i q són punters a un enter.
p = new(int) // Funció per reservar memòria
// A la memòria ja hi ha un 0 per defecte, no és nil.
s := make([]int, 20) // Reserva un bloc de memòria de 20 enters.
s[3] = 7 // Assigna un valor a un d'ells.
r := -2 // Declare una altra variable local.
return &s[3], &r // & agafa l'adreça d'un objecte.
}
func expensiveComputation() float64 {
return m.Exp(10)
}
func aprenControlDeFluxe() {
// Els "If" necessiten corxets però no parèntesis.
if true {
fmt.Println("ja ho hem vist")
}
// El format del codi està estandaritzat amb la comanda "go fmt."
if false {
// Pout.
} else {
// Gloat.
}
// Si cal encadenar ifs és millor fer servir switch.
x := 42.0
switch x {
case 0:
case 1:
case 42:
// Els case no "passen a través" no cal "break" per separar-los.
/*
Per fer-ho hi ha una comanda `fallthrough`, mireu:
https://github.com/golang/go/wiki/Switch#fall-through
*/
case 43:
// No hi arriba.
default:
// La opció "default" és opcional
}
// El 'for' tampoc necessita parèntesis, com el 'if'.
// Les variables dins d'un bloc if o for són local del bloc.
for x := 0; x < 3; x++ { // ++ is a statement.
fmt.Println("iteració", x)
}
// x == 42.
// L'única forma de fer bucles en Go és el 'for' però té moltes variants.
for { // bucle infinit.
break // És una broma!.
continue // No hi arriba mai.
}
// Es fa servir "range" per iterar a una taula, un slice, un mapa
// o un canal.
// range torna un valor (channel) o dos (array, slice, string o map).
for key, value := range map[string]int{"un": 1, "dos": 2, "tres": 3} {
// Per cada parell del mapa imprimeix la clau i el valor.
fmt.Printf("clau=%s, valor=%d\n", key, value)
}
// Si només cal el valor es pot fer servir _
for _, name := range []string{"Robert", "Bill", "Josep"} {
fmt.Printf("Hola, %s\n", name)
}
// Es pot usar := per declarar i assignar valors i després
// comprovar-lo y > x.
if y := expensiveComputation(); y > x {
x = y
}
// Les funcions literals són closures
xBig := func() bool {
return x > 10000 // Referencia a x declarada sobre el switch.
}
x = 99999
fmt.Println("xBig:", xBig()) // cert
x = 1.3e3 // x val 1300
fmt.Println("xBig:", xBig()) // fals.
// A més les funcions poden ser definides i cridades com a arguments per
// una funció sempre que:
// a) La funció es cridi inmediatament (),
// b) El tipus del resultat sigui del tipus esperat de l'argument.
fmt.Println("Suma i duplica dos números: ",
func(a, b int) int {
return (a + b) * 2
}(10, 2)) // Es crida amb els arguments 10 i 2
// => Suma i duplica dos números: 24
// Quan el necessitis t'agradarà que hi sigui
goto love
love:
aprenFabricaDeFuncions() // func que retorna func és divertit(3)(3)
aprenDefer() // Revisió ràpida d'una paraula clau.
aprendreInterficies() // Bon material properament!
}
func aprenFabricaDeFuncions() {
// Les dues seguents són equivalents, però la segona és més pràctica
fmt.Println(sentenceFactory("dia")("Un bonic", "d'estiu!"))
d := sentenceFactory("dia")
fmt.Println(d("Un bonic", "d'estiu!"))
fmt.Println(d("Un tranquil", "de primavera!"))
}
// Els decoradors són habituals en altres llenguatges.
// Es pot fer el mateix en Go amb funcions literals que accepten arguments.
func sentenceFactory(mystring string) func(before, after string) string {
return func(before, after string) string {
return fmt.Sprintf("%s %s %s", before, mystring, after) // nou string
}
}
func aprenDefer() (ok bool) {
// Les comandes marcades amb defer s'executen després de que la funció
// hagi acabat.
defer fmt.Println("Les comandes defer s'executen en ordre invers (LIFO).")
defer fmt.Println("\nAquesta és la primera línia que s'imprimeix")
// Defer es fa servir gairebé sempre per tancar un fitxer, en el moment
// en que acaba el mètode.
return true
}
// Defineix Stringer com un tipus interfície amb el mètode String().
type Stringer interface {
String() string
}
// Defineix una estrutura que conté un parell d'enters, x i y.
type parell struct {
x, y int
}
// Defineix un mètode de l'estructura parell. Ara parell implementa Stringer.
func (p parell) String() string { // p és anomenat el "receptor"
// Sprintf és una funció del paquet fmt.
// Fa referència als camps de p.
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func aprendreInterficies() {
// La sintaxi de claus es pot fer servir per inicialitzar un "struct".
// Gràcies a := defineix i inicialitza p com un struct 'parell'.
p := parell{3, 4}
fmt.Println(p.String()) // Es crida al mètode de p.
var i Stringer // Declara i de tipus Stringer.
i = p // parell implementa Stringer per tant és vàlid.
// Es pot cridar el mètode String() igual que abans.
fmt.Println(i.String())
// Les funcions de fmt criden a String() per aconseguir una representació
// imprimible d'un objecte.
fmt.Println(p) // Treu el mateix d'abans. Println crida el mètode String.
fmt.Println(i) // Idèntic resultat
aprendreParamentesVariables("Aquí", "estem", "aprenent!")
}
// Les funcions poden tenir paràmetres variables.
func aprendreParamentesVariables(myStrings ...interface{}) {
// Itera per cada un dels valors dels paràmetres
// Ignorant l'índex de la seva posició
for _, param := range myStrings {
fmt.Println("paràmetre:", param)
}
// Passa el valor de múltipes variables com a paràmetre.
fmt.Println("parametres:", fmt.Sprintln(myStrings...))
aprenControlErrors()
}
func aprenControlErrors() {
// ", ok" Es fa servir per saber si hi és o no.
m := map[int]string{3: "tres", 4: "quatre"}
if x, ok := m[1]; !ok { // ok serà fals perquè 1 no està en el mapa.
fmt.Println("no hi és")
} else {
fmt.Print(x) // x seria el valor, si no estés en el mapa.
}
// Un valor d'error donarà més informació sobre l'error.
if _, err := strconv.Atoi("no-int"); err != nil { // _ descarta el valor
// imprimeix 'strconv.ParseInt: intenta convertir "non-int":
// syntaxi invalida'
fmt.Println(err)
}
// Es tornarà a les interfícies més tard. Mentrestant,
aprenConcurrencia()
}
// c és un canal (channel), una forma segura de comunicar objectes.
func inc(i int, c chan int) {
c <- i + 1 // <- és l'operador "envia" quan un canal està a l'esquerra.
}
// Es pot fer servir inc per incrementar un número de forma concurrent.
func aprenConcurrencia() {
// La funció make es pot fer servir per crear slices, mapes i canals.
c := make(chan int)
// S'inicien tres goroutines.
// Els números s'incrementaran de forma concurrent, En paral·lel
// si la màquina on s'executa pot fer-ho i està correctament configurada.
// Tots tres envien al mateix canal.
go inc(0, c) // go és la comanda que inicia una nova goroutine.
go inc(10, c)
go inc(-805, c)
// Llegeix tres resultats del canal i els imprimeix.
// No es pot saber en quin ordre arribaran els resultats!
fmt.Println(<-c, <-c, <-c) // Canal a la dreta <- és l'operador "rebre"
cs := make(chan string) // Un altre canal que processa strings.
ccs := make(chan chan string) // Un canal de canals string.
go func() { c <- 84 }() // Inicia una goroutine i li envia un valor.
go func() { cs <- "paraula" }() // El mateix però amb cs.
// Select té una sintaxi semblant a switch però amb canals.
// Selecciona un cas aleatòriament dels que poden comunicar-se.
select {
case i := <-c: // El valor rebit pot ser assignat a una variable,
fmt.Printf("és un %T", i)
case <-cs: // O es pot descartar
fmt.Println("és un string")
case <-ccs: // Canal buit, no preparat per la comunicació.
fmt.Println("no ha passat.")
}
// Quan arribi aquí s'haurà agafat un valor de c o bé de cs. Una de les
// goroutines iniciades haurà acabat i l'altra romandrà bloquejada.
aprenProgramacioWeb() // Go ho fa. Tu vols fer-ho.
}
// Una funció del paquet http inicia un servidor web.
func aprenProgramacioWeb() {
// El primer paràmetre de ListenAndServe és l'adreça on escoltar
// i el segon és una interfície http.Handler.
go func() {
err := http.ListenAndServe(":8080", pair{})
fmt.Println(err) // no s'han d'ignorar els errors
}()
requestServer()
}
// Es converteix "parell" en un http.Handler només implementant el
// mètode ServeHTTP.
func (p parell) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Serveix dades en el http.ResponseWriter.
w.Write([]byte("Has après Go en Y minuts!"))
}
func requestServer() {
resp, err := http.Get("http://localhost:8080")
fmt.Println(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("\nEl servidor diu: `%s`", string(body))
}
```
## Més informació
L'arrel de tot en Go és la web oficial [official Go web site]
(http://golang.org/). Allà es pot seguir el tutorial, jugar interactivament
i llegir molt més del que hem vist aquí.En el "tour",
[the docs](https://golang.org/doc/) conté informació sobre com escriure codi
net i efectiu en Go, comandes per empaquetar i generar documentació, i
història de les versions.
És altament recomanable llegir La definició del llenguatge. És fàcil de llegir
i sorprenentment curta (com la definició del llenguatge en aquests dies).
Es pot jugar amb codi a [Go playground](https://play.golang.org/p/tnWMjr16Mm).
Prova de fer canvis en el codi i executar-lo des del navegador! Es pot fer
servir [https://play.golang.org](https://play.golang.org) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi
en el navegador sense haver d'instal·lar Go.
En la llista de lectures pels estudiants de Go hi ha
[el codi font de la llibreria estàndard](http://golang.org/src/pkg/).
Ampliament comentada, que demostra el fàcil que és de llegir i entendre els
programes en Go, l'estil de programació, i les formes de treballar-hi. O es
pot clicar en un nom de funció en [la documentació](http://golang.org/pkg/)
i veure'n el codi!
Un altre gran recurs per aprendre Go és
[Go by example](https://gobyexample.com/).
Go Mobile afegeix suport per plataformes mòbils (Android i iOS). Es poden
escriure aplicacions mòbils o escriure llibreries de paquets de Go, que es
poden cridar des de Java (android) i Objective-C (iOS).
Comproveu la [Go Mobile page](https://github.com/golang/go/wiki/Mobile) per
més informació.

View File

@@ -0,0 +1,437 @@
---
name: Groovy
category: language
language: Groovy
lang: ca-es
filename: learngroovy-ca.groovy
contributors:
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
translations:
- ["Xavier Sala Pujolar", "http://github.com/utrescu"]
---
Groovy - Un llenguatge dinàmic per la plataforma Java [Llegir-ne més.](http://www.groovy-lang.org/)
```groovy
/*
Posa'l en marxa tu mateix:
1) Instal.la SDKMAN - http://sdkman.io/
2) Instal.la Groovy: sdk install groovy
3) Inicia la consola groovy escrivint: groovyConsole
*/
// Els comentaris d'una sola línia comencen amb dues barres inverses
/*
Els comentaris multilínia són com aquest.
*/
// Hola món
println "Hola món!"
/*
Variables:
Es poden assignar valors a les variables per fer-los servir més tard
*/
def x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x
x = false
println x
x = "Groovy!"
println x
/*
Col.leccions i mapes
*/
// Crear una llista buida
def technologies = []
/*** Afegir elements a la llista ***/
// Com en Java
technologies.add("Grails")
// El shift a l'esquerra afegeix i retorna la llista
technologies << "Groovy"
// Afegir múltiples elements
technologies.addAll(["Gradle","Griffon"])
/*** Eliminar elements de la llista ***/
// Com en Java
technologies.remove("Griffon")
// La resta també funciona
technologies = technologies - 'Grails'
/*** Iterar per les llistes ***/
// Iterar per tots els elements de la llista
technologies.each { println "Technology: $it"}
technologies.eachWithIndex { it, i -> println "$i: $it"}
/*** Comprovar el contingut de la llista ***/
//Comprovar si la llista conté un o més elements (resultat boolea)
contained = technologies.contains( 'Groovy' )
// O
contained = 'Groovy' in technologies
// Comprovar diversos elements
technologies.containsAll(['Groovy','Grails'])
/*** Ordenar llistes ***/
// Ordenar una llista (canvia la original)
technologies.sort()
// Per ordenar sense canviar la original es pot fer:
sortedTechnologies = technologies.sort( false )
/*** Manipular llistes ***/
//Canvia tots els elements de la llista
Collections.replaceAll(technologies, 'Gradle', 'gradle')
// Desordena la llista
Collections.shuffle(technologies, new Random())
// Buida la llista
technologies.clear()
// Crear un mapa buit
def devMap = [:]
// Afegir valors al mapa
devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
devMap.put('lastName','Perez')
// Iterar per tots els elements del mapa
devMap.each { println "$it.key: $it.value" }
devMap.eachWithIndex { it, i -> println "$i: $it"}
// Comprovar si la clau hi és
assert devMap.containsKey('name')
// Comprova si el mapa conté un valor concret
assert devMap.containsValue('Roberto')
// Obtenir les claus del mapa
println devMap.keySet()
// Obtenir els valors del mapa
println devMap.values()
/*
Groovy Beans
Els GroovyBeans són JavaBeans però amb una sintaxi molt més senzilla
Quan Groovy es compila a bytecode es fan servir les regles següents.
* Si el nom és declarat amb un modificador (public, private o protected)
es genera el camp
* Un nom declarat sense modificadors genera un camp privat amb un getter
i un setter públics (per exemple una propietat)
* Si la propietat és declarada final el camp privat es crea i no es
genera cap setter.
* Es pot declarar una propietat i també declarar un getter i un setter.
* Es pot declarar una propietat i un camp amb el mateix nom, la propietat
farà servir el camp.
* Si es vol una propietat private o protected s'ha de definir el getter i
el setter que s'han de declarar private o protected.
* Si s'accedeix a una propietat de la classe que està definida en temps
de compilació amb un this implícit o explícit (per exemple this.foo, o
bé només foo), Groovy accedirà al camp directament en comptes de fer-ho
a través del getter i el setter.
* Si s'accedeix a una propietat que no existeix tant implícita com
explicitament, llavors Groovy accedirà a la propietat a través de la
meta classe, que pot fer que falli en temps d'execució.
*/
class Foo {
// Propietat només de lectura
final String name = "Roberto"
// Propietat de només lectura amb getter públic i un setter protected
String language
protected void setLanguage(String language) { this.language = language }
// Propietat amb el tipus definit dinàmicament
def lastName
}
/*
Bucles i estructres de control
*/
//Groovy té el format tradicional de if -else
def x = 3
if(x==1) {
println "One"
} else if(x==2) {
println "Two"
} else {
println "X greater than Two"
}
// Groovy també té l'operador ternari
def y = 10
def x = (y > 1) ? "worked" : "failed"
assert x == "worked"
//I també té 'l'Operador Elvis'!
//En comptes de fer servir l'operador ternari:
displayName = user.name ? user.name : 'Anonymous'
// Es pot escriure d'aquesta forma:
displayName = user.name ?: 'Anonymous'
//Bucle for
//Itera en un rang
def x = 0
for (i in 0 .. 30) {
x += i
}
//Itera per una llista
x = 0
for( i in [5,3,2,1] ) {
x += i
}
//Itera per un array
array = (0..20).toArray()
x = 0
for (i in array) {
x += i
}
//Itera per un mapa
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
x = 0
for ( e in map ) {
x += e.value
}
/*
Operadors
Hi ha una llista d'operadors que poden ser sobreescrits en Groovy:
http://www.groovy-lang.org/operators.html#Operator-Overloading
Operadors útils de Groovy
*/
//Spread operator: Invoca una acció en tots els ítems d'un grup d'objectes.
def technologies = ['Groovy','Grails','Gradle']
technologies*.toUpperCase() // = a technologies.collect { it?.toUpperCase() }
//Safe navigation operator: fet servir per evitar el NullPointerException.
def user = User.get(1)
def username = user?.username
/*
Closures
Un Closure és com un "bloc de codi" o un punter a un mètode. És un troç de
codi que està definit i que s podrà executar més tard.
Més informació a: http://www.groovy-lang.org/closures.html
*/
//Exemple:
def clos = { println "Hola món!" }
println "Executant el Closure:"
clos()
// Passar paràmetres a un Closure
def sum = { a, b -> println a+b }
sum(2,4)
//Els Closures poden fer referència a variables que no formen part de la
// llista dels seus paràmetres.
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)
// Si es té un Closure que agafa un element com a argument, se'n pot ignorar
// la definició
def clos = { print it }
clos( "hi" )
/*
Groovy pot recordar els resultats dels Closures [1][2][3]
*/
def cl = {a, b ->
sleep(3000) // simula un procés llarg
a + b
}
mem = cl.memoize()
def callClosure(a, b) {
def start = System.currentTimeMillis()
mem(a, b)
println "(a = $a, b = $b) - en ${System.currentTimeMillis() - start} ms"
}
callClosure(1, 2)
callClosure(1, 2)
callClosure(2, 3)
callClosure(2, 3)
callClosure(3, 4)
callClosure(3, 4)
callClosure(1, 2)
callClosure(2, 3)
callClosure(3, 4)
/*
Expando
La classe Expando és un bean dinàmic al que se li poden afegir propietats i
closures com a mètodes d'una instància d'aquesta classe.
http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
*/
def user = new Expando(name:"Roberto")
assert 'Roberto' == user.name
user.lastName = 'Pérez'
assert 'Pérez' == user.lastName
user.showInfo = { out ->
out << "Name: $name"
out << ", Last name: $lastName"
}
def sw = new StringWriter()
println user.showInfo(sw)
/*
Metaprogrammació (MOP)
*/
// Fent servir ExpandoMetaClass per afegir comportament
String.metaClass.testAdd = {
println "he afegit això"
}
String x = "test"
x?.testAdd()
//Intercepting method calls
class Test implements GroovyInterceptable {
def sum(Integer x, Integer y) { x + y }
def invokeMethod(String name, args) {
System.out.println "Invoca el mètode $name amb arguments: $args"
}
}
def test = new Test()
test?.sum(2,3)
test?.multiply(2,3)
//Groovy supporta propertyMissing per gestionar la resolució de propietats
class Foo {
def propertyMissing(String name) { name }
}
def f = new Foo()
assertEquals "boo", f.boo
/*
TypeChecked i CompileStatic
Groovy, by nature, és i sempre serà un llenguatge dinàmic però també té
comprovació de tipus i definicions estàtiques
More info: http://www.infoq.com/articles/new-groovy-20
*/
//TypeChecked
import groovy.transform.TypeChecked
void testMethod() {}
@TypeChecked
void test() {
testMeethod()
def name = "Roberto"
println naameee
}
//Un altre exemple:
import groovy.transform.TypeChecked
@TypeChecked
Integer test() {
Integer num = "1"
Integer[] numbers = [1,2,3,4]
Date date = numbers[1]
return "Test"
}
//exemple de CompileStatic
import groovy.transform.CompileStatic
@CompileStatic
int sum(int x, int y) {
x + y
}
assert sum(2,5) == 7
```
## Per aprendre'n més
[documentació de Groovy](http://www.groovy-lang.org/documentation.html)
[Cònsola de Groovy](http://groovyconsole.appspot.com/)
Uneix-te a un [grup d'usuaris Groovy]
(http://www.groovy-lang.org/usergroups.html)
## Llibres
* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook)
* [Groovy in Action] (http://manning.com/koenig2/)
* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do)
[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html

View File

@@ -0,0 +1,389 @@
---
language: kotlin
contributors:
- ["S Webber", "https://github.com/s-webber"]
translators:
- ["Xavier Sala", "https://github.com/utrescu"]
lang: ca-es
filename: LearnKotlin-ca.kt
---
Kotlin és un llenguatge estàtic tipat per la JVM, Android i el navegador.
És interoperable al 100% amb Java.
[Llegir-ne més aquí.](https://kotlinlang.org/)
```kotlin
// Els comentaris d'una línia comencen amb //
/*
Els comentaris multilínia són com aquest
*/
// La paraula clau "package" funciona de la mateixa forma que en Java
package com.learnxinyminutes.kotlin
/*
El punt d'entrada dels programes en Kotlin és una funció anomenada "main".
La funció rep un array que té els arguments fets servir al executar-lo.
*/
fun main(args: Array<String>) {
/*
La declaració de variables es pot fer tant amb "var" com amb "val".
A les declarades amb "val" no se'ls hi pot canviar el valor
en canvi a les declarades amb "var" si.
*/
val fooVal = 10 // no es podrà canviar el valor de fooVal
var fooVar = 10
fooVar = 20 // fooVar si que es pot canviar
/*
Gairebé sempre, Kotlin pot determinar el tipus d'una variable,
de manera que no caldrà definir-lo cada vegada.
Però es pot definir el tipus d'una variable explícitament d'aquesta forma:
*/
val foo: Int = 7
/*
Els "strings" es poden representar igual que com es fa en Java.
Es poden escapar caràcters amb la barra inversa.
*/
val fooString = "Aquí està la meva cadena!"
val barString = "Imprimir en dues línies?\nCap problema!"
val bazString = "Es poden posar tabuladors?\tI tant!"
println(fooString)
println(barString)
println(bazString)
/*
Es poden definir strings literals envoltant-los amb les triples cometes
(""").
Dins hi poden haver tant salts de línies com d'altres caràcters.
*/
val fooRawString = """
fun helloWorld(val name : String) {
println("Hola món!")
}
"""
println(fooRawString)
/*
Els strings poden contenir expressions de plantilla.
Les expressions de plantilla comencen amb el símbol ($).
*/
val fooTemplateString = "$fooString${fooString.length} caràcters"
println(fooTemplateString)
/*
Perquè una variable pugui contenir null ha de ser declarada específicament
com a nullable afengint-li ? al seu tipus.
Es pot accedir a una variable nulable fent servir l'operador ?.
L'operador ?: permet especificar un valor alternatiu en cas de que la
variable sigui null.
*/
var fooNullable: String? = "abc"
println(fooNullable?.length) // => 3
println(fooNullable?.length ?: -1) // => 3
fooNullable = null
println(fooNullable?.length) // => null
println(fooNullable?.length ?: -1) // => -1
/*
Les funcions es declaren amb la paraula "fun".
Els arguments s'especifiquen entre corxets després del nom de la funció.
Els arguments poden tenir un valor per defecte.
El retorn de les funcions, si cal, es posa després de l'argument.
*/
fun hello(name: String = "món"): String {
return "Hola, $name!"
}
println(hello("foo")) // => Hola, foo!
println(hello(name = "bar")) // => Hola, bar!
println(hello()) // => Hola, món!
/*
Un dels paràmetres d'una funció pot ser marcat amb la paraula clau
"vararg" que permet que una funció accepti un número variable
d'arguments.
*/
fun varargExample(vararg names: Int) {
println("S'han rebut ${names.size} arguments")
}
varargExample() // => S'han rebut 0 elements
varargExample(1) // => S'ha rebut 1 element
varargExample(1, 2, 3) // => S'han rebut 3 elements
/*
Quan una funció consisteix en una sola expressió no calen els corxets
El cos de la funció es posa rere el símbol =.
*/
fun odd(x: Int): Boolean = x % 2 == 1
println(odd(6)) // => false
println(odd(7)) // => true
// Si el tipus retornat es pot determinar no cal especificar-lo.
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
// Les funcions poden tenir altres funcions com arguments i
// fins i tot retornar-ne.
fun not(f: (Int) -> Boolean): (Int) -> Boolean {
return {n -> !f.invoke(n)}
}
// Les funcions amb nom es poden especificar quan fan d'arguments amb ::
val notOdd = not(::odd)
val notEven = not(::even)
// Les expressions lambda es poden posar com arguments.
val notZero = not {n -> n == 0}
/*
Si la lambda només té un paràmetre es pot ometre la seva declaració.
El seu valor serà "it".
*/
val notPositive = not {it > 0}
for (i in 0..4) {
println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
}
// Les classes es defineixen amb "class".
class ExampleClass(val x: Int) {
fun memberFunction(y: Int): Int {
return x + y
}
infix fun infixMemberFunction(y: Int): Int {
return x * y
}
}
/*
Per crear una nova instància es crida al constructor.
Tingueu en compte que Kotlin no té l'operador "new".
*/
val fooExampleClass = ExampleClass(7)
// Els mètodes es poden cridar amb la notació .
println(fooExampleClass.memberFunction(4)) // => 11
/*
Si una funció ha estat marcada amb "infix" es pot cridar amb la
notació infix.
*/
println(fooExampleClass infixMemberFunction 4) // => 28
/*
Les classes "data" són classes que només contenen dades.
Es creen automàticament els mètodes "hashCode","equals" i "toString"
*/
data class DataClassExample (val x: Int, val y: Int, val z: Int)
val fooData = DataClassExample(1, 2, 4)
println(fooData) // => DataClassExample(x=1, y=2, z=4)
// Les classes data tenen un mètode "copy".
val fooCopy = fooData.copy(y = 100)
println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
// Els objectes es poden desestructurar amb múltiples variables
val (a, b, c) = fooCopy
println("$a $b $c") // => 1 100 4
// desestructurat en un bucle "for"
for ((a, b, c) in listOf(fooData)) {
println("$a $b $c") // => 1 100 4
}
val mapData = mapOf("a" to 1, "b" to 2)
// Els mapes també
for ((key, value) in mapData) {
println("$key -> $value")
}
// La funció "with" és similar a la de JavaScript.
data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
val fooMutableData = MutableDataClassExample(7, 4, 9)
with (fooMutableData) {
x -= 2
y += 2
z--
}
println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
/*
Es pot crear una llista amb la funció "listOf".
La llista serà immutable - no s'hi poden afegir o treure elements.
*/
val fooList = listOf("a", "b", "c")
println(fooList.size) // => 3
println(fooList.first()) // => a
println(fooList.last()) // => c
// Es pot accedir als elements a partir del seu índex.
println(fooList[1]) // => b
// Es poden crear llistes mutables amb la funció "mutableListOf".
val fooMutableList = mutableListOf("a", "b", "c")
fooMutableList.add("d")
println(fooMutableList.last()) // => d
println(fooMutableList.size) // => 4
// Es poden crear conjunts amb la funció "setOf".
val fooSet = setOf("a", "b", "c")
println(fooSet.contains("a")) // => true
println(fooSet.contains("z")) // => false
// Es poden crear mapes amb la funció "mapOf".
val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
// S'accedeix als valors del mapa a partir del seu índex.
println(fooMap["a"]) // => 8
/*
Les sequències representen col·leccions evaluades quan fan falta.
Podem crear una seqüencia amb la funció "generateSequence".
*/
val fooSequence = generateSequence(1, { it + 1 })
val x = fooSequence.take(10).toList()
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Per exemple amb aquesta seqüència es creen els números de Fibonacci:
fun fibonacciSequence(): Sequence<Long> {
var a = 0L
var b = 1L
fun next(): Long {
val result = a + b
a = b
b = result
return a
}
return generateSequence(::next)
}
val y = fibonacciSequence().take(10).toList()
println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
// Kotlin proporciona funcions de primer ordre per treballar amb
// col·leccions.
val z = (1..9).map {it * 3}
.filter {it < 20}
.groupBy {it % 2 == 0}
.mapKeys {if (it.key) "parell" else "senar"}
println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
// Es pot fer servir el bucle "for" amb qualsevol cosa que proporcioni
// un iterador.
for (c in "hello") {
println(c)
}
// els bucles "while" funcionen com en altres llenguatges.
var ctr = 0
while (ctr < 5) {
println(ctr)
ctr++
}
do {
println(ctr)
ctr++
} while (ctr < 10)
/*
"if" es pot fer servir com una expressió que retorna un valor.
Per això no cal l'operador ternari ?: en Kotlin.
*/
val num = 5
val message = if (num % 2 == 0) "parell" else "senar"
println("$num is $message") // => 5 is odd
// "when" es pot fer servir com alternativa a les cadenes "if-else if".
val i = 10
when {
i < 7 -> println("primer bloc")
fooString.startsWith("hola") -> println("segon bloc")
else -> println("bloc else")
}
// "when" es pot fer servir amb un argument.
when (i) {
0, 21 -> println("0 o 21")
in 1..20 -> println("en el rang 1 a 20")
else -> println("cap dels anteriors")
}
// "when" es pot fer servir com una funció que retorna valors.
var result = when (i) {
0, 21 -> "0 o 21"
in 1..20 -> "en el rang 1 a 20"
else -> "cap dels anteriors"
}
println(result)
/*
Es pot comprovar el tipus d'un objecte fent servir l'operador "is".
Si un objecte passa una comprovació es pot fer servir sense posar-hi
cap casting.
*/
fun smartCastExample(x: Any) : Boolean {
if (x is Boolean) {
// x es converteix automàticament a Booleà
return x
} else if (x is Int) {
// x es converteix automàticament a int
return x > 0
} else if (x is String) {
// x es converteix a string automàticament
return x.isNotEmpty()
} else {
return false
}
}
println(smartCastExample("Hola món!")) // => true
println(smartCastExample("")) // => false
println(smartCastExample(5)) // => true
println(smartCastExample(0)) // => false
println(smartCastExample(true)) // => true
// També es pot cridar smarcast en un bloc when
fun smartCastWhenExample(x: Any) = when (x) {
is Boolean -> x
is Int -> x > 0
is String -> x.isNotEmpty()
else -> false
}
/*
Les extensions són una forma d'afegir noves funcionalitats a una classe.
És semblant a les extensions de C#.
*/
fun String.remove(c: Char): String {
return this.filter {it != c}
}
println("Hola món!".remove('l')) // => Hoa, món!
println(EnumExample.A) // => A
println(ObjectExample.hello()) // => hola
}
// Les classes enumerades són semblants a les de Java
enum class EnumExample {
A, B, C
}
/*
El paràmetre "object" es pot fer servir per crear objectes singleton.
No es poden instanciar però es pot fer referència a la seva única instància
amb el seu nom.
Són similars als singletons d'Scala.
*/
object ObjectExample {
fun hello(): String {
return "hola"
}
}
fun useObject() {
ObjectExample.hello()
val someRef: Any = ObjectExample // podem fer servir el nom de l'objecte
}
```
### Per llegir més
* [tutorials de Kotlin](https://kotlinlang.org/docs/tutorials/)
* [Provar Kotlin en el navegador](http://try.kotlinlang.org/)
* [Llista de recursos de Kotlin](http://kotlin.link/)

File diff suppressed because it is too large Load Diff

View File

@@ -99,13 +99,13 @@ You'll want to be familiar with Clojure. Make sure you understand everything in
(list x) ; -> (4)
;; You can use # within ` to produce a gensym for each symbol automatically
(defmacro define-x-hygenically []
(defmacro define-x-hygienically []
`(do
(def x# 2)
(list x#)))
(def x 4)
(define-x-hygenically) ; -> (2)
(define-x-hygienically) ; -> (2)
(list x) ; -> (4)
;; It's typical to use helper functions with macros. Let's create a few to

View File

@@ -289,6 +289,19 @@ keymap ; => {:a 1, :b 2, :c 3}
(into [])) ;=> (into [] (filter odd? (map inc (range 10)))
; Result: [1 3 5 7 9]
; When you are in a situation where you want more freedom as where to
; put the result of previous data transformations in an
; expression, you can use the as-> macro. With it, you can assign a
; specific name to transformations' output and use it as a
; placeholder in your chained expressions:
(as-> [1 2 3] input
(map inc input);=> You can use last transform's output at the last position
(nth input 2) ;=> and at the second position, in the same expression
(conj [4 5 6] input [8 9 10])) ;=> or in the middle !
; Modules
;;;;;;;;;;;;;;;

176
cmake.html.markdown Normal file
View File

@@ -0,0 +1,176 @@
---
language: cmake
contributors:
- ["Bruno Alano", "https://github.com/brunoalano"]
filename: CMake
---
CMake is a cross-platform, open-source build system. This tool will allow you
to test, compile and create packages of your source code.
The problem that CMake tries to solve is the problem of Makefiles and
Autoconfigure on cross-platforms (different make interpreters have different
command) and the ease-of-use on linking 3rd party libraries.
CMake is an extensible, open-source system that manages the build process in
an operating system and compiler-independent manner. Unlike many
cross-platform systems, CMake is designed to be used in conjunction with the
native build environment. Simple configuration files placed in each source
directory (called CMakeLists.txt files) are used to generate standard build
files (e.g., makefiles on Unix and projects/workspaces in Windows MSVC) which
are used in the usual way.
```cmake
# In CMake, this is a comment
# To run our code, we will use these steps:
# - mkdir build && cd build
# - cmake ..
# - make
#
# With those steps, we will follow the best pratice to compile into a subdir
# and the second line will request to CMake to generate a new OS-dependant
# Makefile. Finally, run the native Make command.
#------------------------------------------------------------------------------
# Basic
#------------------------------------------------------------------------------
#
# The CMake file MUST be named as "CMakeLists.txt".
# Setup the minimum version required of CMake to generate the Makefile
cmake_minimum_required (VERSION 2.8)
# Raises a FATAL_ERROR if version < 2.8
cmake_minimum_required (VERSION 2.8 FATAL_ERROR)
# We setup the name for our project. After we do that, this will change some
# directories naming convention generated by CMake. We can send the LANG of
# code as second param
project (learncmake C)
# Set the project source dir (just convention)
set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} )
set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} )
# It's useful to setup the current version of our code in the build system
# using a `semver` style
set (LEARN_CMAKE_VERSION_MAJOR 1)
set (LEARN_CMAKE_VERSION_MINOR 0)
set (LEARN_CMAKE_VERSION_PATCH 0)
# Send the variables (version number) to source code header
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
# Include Directories
# In GCC, this will invoke the "-I" command
include_directories( include )
# Where are the additional libraries installed? Note: provide includes
# path here, subsequent checks will resolve everything else
set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
# Conditions
if ( CONDITION )
# Output!
# Incidental information
message(STATUS "My message")
# CMake Warning, continue processing
message(WARNING "My message")
# CMake Warning (dev), continue processing
message(AUTHOR_WARNING "My message")
# CMake Error, continue processing, but skip generation
message(SEND_ERROR "My message")
# CMake Error, stop processing and generation
message(FATAL_ERROR "My message")
endif()
if( CONDITION )
elseif( CONDITION )
else( CONDITION )
endif( CONDITION )
# Loops
foreach(loop_var arg1 arg2 ...)
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endforeach(loop_var)
foreach(loop_var RANGE total)
foreach(loop_var RANGE start stop [step])
foreach(loop_var IN [LISTS [list1 [...]]]
[ITEMS [item1 [...]]])
while(condition)
COMMAND1(ARGS ...)
COMMAND2(ARGS ...)
...
endwhile(condition)
# Logic Operations
if(FALSE AND (FALSE OR TRUE))
message("Don't display!")
endif()
# Set a normal, cache, or environment variable to a given value.
# If the PARENT_SCOPE option is given the variable will be set in the scope
# above the current scope.
# `set(<variable> <value>... [PARENT_SCOPE])`
# How to reference variables inside quoted and unquoted arguments
# A variable reference is replaced by the value of the variable, or by the
# empty string if the variable is not set
${variable_name}
# Lists
# Setup the list of source files
set( LEARN_CMAKE_SOURCES
src/main.c
src/imagem.c
src/pather.c
)
# Calls the compiler
#
# ${PROJECT_NAME} refers to Learn_CMake
add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} )
# Link the libraries
target_link_libraries( ${PROJECT_NAME} ${LIBS} m )
# Where are the additional libraries installed? Note: provide includes
# path here, subsequent checks will resolve everything else
set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" )
# Compiler Condition (gcc ; g++)
if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" )
message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" )
add_definitions( --std=c99 )
endif()
# Check for OS
if( UNIX )
set( LEARN_CMAKE_DEFINITIONS
"${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" )
endif()
```
### More Resources
+ [cmake tutorial](https://cmake.org/cmake-tutorial/)
+ [cmake documentation](https://cmake.org/documentation/)
+ [mastering cmake](http://amzn.com/1930934319/)

View File

@@ -6,15 +6,17 @@ contributors:
filename: coffeescript.coffee
---
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime.
CoffeeScript is a little language that compiles one-to-one into the equivalent
JavaScript, and there is no interpretation at runtime. As one of the successors
to JavaScript, CoffeeScript tries its best to output readable, pretty-printed
and smooth-running JavaScript code, which works well in every JavaScript runtime.
It also attempts to try and make JavaScript more in line with the trends of many
modern languages.
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
```coffeescript
# CoffeeScript is a hipster language.
# It goes with the trends of many modern languages.
# So comments are like Ruby and Python, they use number symbols.
# Comments are similar to Ruby and Python, using the hash symbol `#`
###
Block comments are like these, and they translate directly to '/ *'s and '* /'s

View File

@@ -13,7 +13,7 @@ ColdFusion is a scripting language for web development.
_**C**old**F**usion **M**arkup **L**anguage_
ColdFusion started as a tag-based language. Almost all functionality is available using tags.
```html
```cfm
<em>HTML tags have been provided for output readability</em>
<!--- Comments start with "<!---" and end with "--->" --->
@@ -232,7 +232,8 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl
<h1>Components</h1>
<em>Code for reference (Functions must return something to support IE)</em>
```
```cfs
<cfcomponent>
<cfset this.hello = "Hello" />
<cfset this.world = "world" />

553
crystal.html.markdown Normal file
View File

@@ -0,0 +1,553 @@
---
language: crystal
filename: learncrystal.cr
contributors:
- ["Vitalii Elenhaupt", "http://veelenga.com"]
- ["Arnaud Fernandés", "https://github.com/TechMagister/"]
---
```crystal
# This is a comment
# Everything is an object
nil.class #=> Nil
100.class #=> Int32
true.class #=> Bool
# Falsey values are: nil, false and null pointers
!nil #=> true : Bool
!false #=> true : Bool
!0 #=> false : Bool
# Integers
1.class #=> Int32
# Four signed integer types
1_i8.class #=> Int8
1_i16.class #=> Int16
1_i32.class #=> Int32
1_i64.class #=> Int64
# Four unsigned integer types
1_u8.class #=> UInt8
1_u16.class #=> UInt16
1_u32.class #=> UInt32
1_u64.class #=> UInt64
2147483648.class #=> Int64
9223372036854775808.class #=> UInt64
# Binary numbers
0b1101 #=> 13 : Int32
# Octal numbers
0o123 #=> 83 : Int32
# Hexadecimal numbers
0xFE012D #=> 16646445 : Int32
0xfe012d #=> 16646445 : Int32
# Floats
1.0.class #=> Float64
# There are two floating point types
1.0_f32.class #=> Float32
1_f32.class #=> Float32
1e10.class #=> Float64
1.5e10.class #=> Float64
1.5e-7.class #=> Float64
# Chars
'a'.class #=> Char
# Octal codepoint
'\101' #=> 'A' : Char
# Unicode codepoint
'\u0041' #=> 'A' : Char
# Strings
"s".class #=> String
# Strings are immutable
s = "hello, " #=> "hello, " : String
s.object_id #=> 134667712 : UInt64
s += "Crystal" #=> "hello, Crystal" : String
s.object_id #=> 142528472 : UInt64
# Supports interpolation
"sum = #{1 + 2}" #=> "sum = 3" : String
# Multiline string
"This is
multiline string"
# String with double quotes
%(hello "world") #=> "hello \"world\""
# Symbols
# Immutable, reusable constants represented internally as Int32 integer value.
# They're often used instead of strings to efficiently convey specific,
# meaningful values
:symbol.class #=> Symbol
sentence = :question? # :"question?" : Symbol
sentence == :question? #=> true : Bool
sentence == :exclamation! #=> false : Bool
sentence == "question?" #=> false : Bool
# Arrays
[1, 2, 3].class #=> Array(Int32)
[1, "hello", 'x'].class #=> Array(Int32 | String | Char)
# Empty arrays should specify a type
[] # Syntax error: for empty arrays use '[] of ElementType'
[] of Int32 #=> [] : Array(Int32)
Array(Int32).new #=> [] : Array(Int32)
# Arrays can be indexed
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] : Array(Int32)
array[0] #=> 1 : Int32
array[10] # raises IndexError
array[-6] # raises IndexError
array[10]? #=> nil : (Int32 | Nil)
array[-6]? #=> nil : (Int32 | Nil)
# From the end
array[-1] #=> 5
# With a start index and size
array[2, 3] #=> [3, 4, 5]
# Or with range
array[1..3] #=> [2, 3, 4]
# Add to an array
array << 6 #=> [1, 2, 3, 4, 5, 6]
# Remove from the end of the array
array.pop #=> 6
array #=> [1, 2, 3, 4, 5]
# Remove from the beginning of the array
array.shift #=> 1
array #=> [2, 3, 4, 5]
# Check if an item exists in an array
array.includes? 3 #=> true
# Special syntax for an array of string and an array of symbols
%w(one two three) #=> ["one", "two", "three"] : Array(String)
%i(one two three) #=> [:one, :two, :three] : Array(Symbol)
# There is a special array syntax with other types too, as long as
# they define a .new and a #<< method
set = Set{1, 2, 3} #=> [1, 2, 3]
set.class #=> Set(Int32)
# The above is equivalent to
set = Set(typeof(1, 2, 3)).new
set << 1
set << 2
set << 3
# Hashes
{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32)
{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32)
# Empty hashes should specify a type
{} # Syntax error
{} of Int32 => Int32 # {}
Hash(Int32, Int32).new # {}
# Hashes can be quickly looked up by key
hash = {"color" => "green", "number" => 5}
hash["color"] #=> "green"
hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError)
hash["no_such_key"]? #=> nil
# Check existence of keys hash
hash.has_key? "color" #=> true
# Special notation for symbol and string keys
{key1: 'a', key2: 'b'} # {:key1 => 'a', :key2 => 'b'}
{"key1": 'a', "key2": 'b'} # {"key1" => 'a', "key2" => 'b'}
# Special hash literal syntax with other types too, as long as
# they define a .new and a #[]= methods
class MyType
def []=(key, value)
puts "do stuff"
end
end
MyType{"foo" => "bar"}
# The above is equivalent to
tmp = MyType.new
tmp["foo"] = "bar"
tmp
# Ranges
1..10 #=> Range(Int32, Int32)
Range.new(1, 10).class #=> Range(Int32, Int32)
# Can be inclusive or exclusive
(3..5).to_a #=> [3, 4, 5]
(3...5).to_a #=> [3, 4]
# Check whether range includes the given value or not
(1..8).includes? 2 #=> true
# Tuples are a fixed-size, immutable, stack-allocated sequence of values of
# possibly different types.
{1, "hello", 'x'}.class #=> Tuple(Int32, String, Char)
# Acces tuple's value by its index
tuple = {:key1, :key2}
tuple[1] #=> :key2
tuple[2] #=> syntax error : Index out of bound
# Can be expanded into multiple variables
a, b, c = {:a, 'b', "c"}
a #=> :a
b #=> 'b'
c #=> "c"
# Procs represent a function pointer with an optional context (the closure data)
# It is typically created with a proc litteral
proc = ->(x : Int32) { x.to_s }
proc.class # Proc(Int32, String)
# Or using the new method
Proc(Int32, String).new { |x| x.to_s }
# Invoke proc with call method
proc.call 10 #=> "10"
# Control statements
if true
"if statement"
elsif false
"else-if, optional"
else
"else, also optional"
end
puts "if as a suffix" if true
# If as an expression
a = if 2 > 1
3
else
4
end
a #=> 3
# Ternary if
a = 1 > 2 ? 3 : 4 #=> 4
# Case statement
cmd = "move"
action = case cmd
when "create"
"Creating..."
when "copy"
"Copying..."
when "move"
"Moving..."
when "delete"
"Deleting..."
end
action #=> "Moving..."
# Loops
index = 0
while index <= 3
puts "Index: #{index}"
index += 1
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3
index = 0
until index > 3
puts "Index: #{index}"
index += 1
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3
# But the preferable way is to use each
(1..3).each do |index|
puts "Index: #{index}"
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3
# Variable's type depends on the type of the expression
# in control statements
if a < 3
a = "hello"
else
a = true
end
typeof a #=> (Bool | String)
if a && b
# here both a and b are guaranteed not to be Nil
end
if a.is_a? String
a.class #=> String
end
# Functions
def double(x)
x * 2
end
# Functions (and all blocks) implicitly return the value of the last statement
double(2) #=> 4
# Parentheses are optional where the call is unambiguous
double 3 #=> 6
double double 3 #=> 12
def sum(x, y)
x + y
end
# Method arguments are separated by a comma
sum 3, 4 #=> 7
sum sum(3, 4), 5 #=> 12
# yield
# All methods have an implicit, optional block parameter
# it can be called with the 'yield' keyword
def surround
puts '{'
yield
puts '}'
end
surround { puts "hello world" }
# {
# hello world
# }
# You can pass a block to a function
# "&" marks a reference to a passed block
def guests(&block)
block.call "some_argument"
end
# You can pass a list of arguments, which will be converted into an array
# That's what splat operator ("*") is for
def guests(*array)
array.each { |guest| puts guest }
end
# If a method returns an array, you can use destructuring assignment
def foods
["pancake", "sandwich", "quesadilla"]
end
breakfast, lunch, dinner = foods
breakfast #=> "pancake"
dinner #=> "quesadilla"
# By convention, all methods that return booleans end with a question mark
5.even? # false
5.odd? # true
# And if a method ends with an exclamation mark, it does something destructive
# like mutate the receiver. Some methods have a ! version to make a change, and
# a non-! version to just return a new changed version
company_name = "Dunder Mifflin"
company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin"
company_name #=> "Dunder Mifflin"
company_name.gsub! "Dunder", "Donald"
company_name #=> "Donald Mifflin"
# Define a class with the class keyword
class Human
# A class variable. It is shared by all instances of this class.
@@species = "H. sapiens"
# type of name is String
@name : String
# Basic initializer
# Assign the argument to the "name" instance variable for the instance
# If no age given, we will fall back to the default in the arguments list.
def initialize(@name, @age = 0)
end
# Basic setter method
def name=(name)
@name = name
end
# Basic getter method
def name
@name
end
# The above functionality can be encapsulated using the attr_accessor method as follows
property :name
# Getter/setter methods can also be created individually like this
getter :name
setter :name
# A class method uses self to distinguish from instance methods.
# It can only be called on the class, not an instance.
def self.say(msg)
puts msg
end
def species
@@species
end
end
# Instantiate a class
jim = Human.new("Jim Halpert")
dwight = Human.new("Dwight K. Schrute")
# Let's call a couple of methods
jim.species #=> "H. sapiens"
jim.name #=> "Jim Halpert"
jim.name = "Jim Halpert II" #=> "Jim Halpert II"
jim.name #=> "Jim Halpert II"
dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
# Call the class method
Human.say("Hi") #=> print Hi and returns nil
# Variables that start with @ have instance scope
class TestClass
@var = "I'm an instance var"
end
# Variables that start with @@ have class scope
class TestClass
@@var = "I'm a class var"
end
# Variables that start with a capital letter are constants
Var = "I'm a constant"
Var = "can't be updated" # Already initialized constant Var
# Class is also an object in crystal. So class can have instance variables.
# Class variable is shared among the class and all of its descendants.
# base class
class Human
@@foo = 0
def self.foo
@@foo
end
def self.foo=(value)
@@foo = value
end
end
# derived class
class Worker < Human
end
Human.foo #=> 0
Worker.foo #=> 0
Human.foo = 2 #=> 2
Worker.foo #=> 0
Worker.foo = 3 #=> 3
Human.foo #=> 2
Worker.foo #=> 3
module ModuleExample
def foo
"foo"
end
end
# Including modules binds their methods to the class instances
# Extending modules binds their methods to the class itself
class Person
include ModuleExample
end
class Book
extend ModuleExample
end
Person.foo # => undefined method 'foo' for Person:Class
Person.new.foo # => 'foo'
Book.foo # => 'foo'
Book.new.foo # => undefined method 'foo' for Book
# Exception handling
# Define new exception
class MyException < Exception
end
# Define another exception
class MyAnotherException < Exception; end
ex = begin
raise MyException.new
rescue ex1 : IndexError
"ex1"
rescue ex2 : MyException | MyAnotherException
"ex2"
rescue ex3 : Exception
"ex3"
rescue ex4 # catch any kind of exception
"ex4"
end
ex #=> "ex2"
```
## Additional resources
- [Official Documentation](http://crystal-lang.org/)

View File

@@ -0,0 +1,87 @@
---
language: brainfuck
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["Vojta Svoboda", "https://github.com/vojtasvoboda/"]
filename: learnbrainfuck-cz.bf
lang: cs-cz
---
Brainfuck (psaný bez kapitálek s vyjímkou začátku věty) je extrémně minimální
Turingovsky kompletní (ekvivalentní) programovací jazyk a má pouze 8 příkazů.
Můžete si ho vyzkoušet přímo v prohlížeči s [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
```
Jakýkoliv znak mimo "><+-.,[]" (bez uvozovek) je ignorován.
Brainfuck je reprezentován jako pole, které má 30.000 buněk s počátkem v nule
a datovým ukazatelem na aktuální buňce.
Můžeme využít těchto osm příkazů:
+ : Přičte k aktuální buňce jedničku.
- : Odečte od aktuální buňky jedničku.
> : Posune datový ukazatel na další buňku, která je napravo.
< : Posune datový ukazatel na předchozí buňku, která je nalevo.
. : Vytiskne ASCII hodnotu aktuální buňky (například 65 = 'A').
, : Načte jeden znak do aktuální buňky.
[ : Pokud je hodnota aktuální buňky nulová, přeskočí na buňku odpovídající ] .
Jinak skočí na další instrukci.
] : Pokud je hodnota aktuální buňky nulova, přeskočí na další instrukci.
Jinak skočí zpět na instrukci odpovídající [ .
[ a ] tak tvoří 'while' smyčku a tyto symboly musí tak být v páru.
Pojďme se mrknout na některé brainfuck programy.
++++++ [ > ++++++++++ < - ] > +++++ .
Tento program vypíše písmeno 'A' (v ASCII je to číslo 65). Nejdříve navýší
buňku #1 na hodnotu 6. Buňka #1 bude použita pro smyčku. Potom program vstoupí
do smyčky ([) a sníží hodnotu buňky #1 o jedničku. Ve smyčce zvýší hodnotu
buňky #2 desetkrát, vrátí ze zpět na buňku #1 a sníží její hodnotu o jedničku.
Toto se stane šestkrát (je potřeba šestkrát snížit hodnotu buňky #1, aby byla
nulová a program přeskočil na konec cyklu označený znakem ].
Na konci smyčky, kdy jsme na buňce #1 (která má hodnotu 0), tak má buňka #2
hodnotu 60. Přesuneme se na buňku #2 a pětkrát zvýšíme její hodnotu o jedničku
na hodnotu 65. Na konci vypíšeme hodnotu buňky #2 - 65, což je v ASCII znak 'A'
na terminálu.
, [ > + < - ] > .
Tento program přečte znak z uživatelského vstupu a zkopíruje ho do buňky #1.
Poté začne smyčka - přesun na buňku #2, zvýšení hodnoty buňky #2 o jedničku,
přesun zpět na buňku #1 a snížení její hodnoty o jedničku. Takto smyčka pokračuje
do té doby, než je buňka #1 nulová a buňka #2 nabyde původní hodnotu buňky #1.
Protože jsme na buňce #1, přesuneme se na buňku #2 a vytiskneme její hodnotu
v ASCII.
Je dobré vědět, že mezery jsou v programu uvedené pouze z důvodu čitelnosti.
Program je možné klidně zapsat i takto:
,[>+<-]>.
Nyní se podívejte na tento program a zkuste zjistit co dělá:
,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
Tento program vezme dvě čísla ze vstupu a vynásobí je.
Program nejdříve načte dvě vstupní hodnoty. Poté začíná smyčka řízená hodnotou
v buňce #1 - přesun na buňku #2 a start druhé vnořené smyčky, která je řízená
hodnotou v buňce #2 a zvyšuje hodnotu v buňce #3. Nicméně je zde problém
kdy na konci vnitřní smyčky je v buňce #2 nula a smyčka by tak znovu
napokračovala. Vyřešíme to tak, že zvyšujeme o jedničku i buňku #4 a její
hodnotu poté překopírujeme do buňky #2. Na konci programu je v buňce #3
výsledek.
```
A to je brainbuck. Zase tak složitý není, co? Zkuste si nyní napsat nějaký
vlastní brainfuck program a nebo interpretr v jiném jazyce, což není zase
tak složité, ale pokud jste opravdový masochista, zkuste si naprogramovat
interpretr jazyka brainfuck v jazyce... brainfuck :)

253
cs-cz/css.html.markdown Normal file
View File

@@ -0,0 +1,253 @@
---
language: css
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
lang: cs-cz
filename: learncss-cz.css
---
V ranných dobách webu se nevyskytovaly žádné vizuální elementy, pouze čistý text, ale s vývojem webových browserů se staly stránky plné grafických prvků běžné.
A právě proto vzniklo CSS, aby oddělilo obsah (HTML) od vzhledu webové stránky.
Pomocí CSS můžete označit různé elementy na HTML stránce a přiřadit jim různé vzhledové vlastnosti.
Tento návod byl napsán pro CSS 2, avšak CSS 3 se stalo velmi oblíbené a v dnešní době běžné.
**POZNÁMKA** Protože CSS produkuje vizuální výsledky, je nutné k jeho naučení všechno zkoušet třeba na [dabbletu](http://dabblet.com/).
Tento článek se zaměřuje hlavně na syntaxi a poskytue také pár obecných tipů.
```css
/* komentáře jsou ohraničeny lomítkem s hvězdičkou, přesně jako tyto dva
řádky, v CSS není nic jako jednořádkový komentář, pouze tenhle zápis */
/* ################
## SELEKTORY
################ */
/* Selektor se používá pro vybrání elementu na stránce:
selektor { vlastnost: hodnota; /* více vlastností... }*/
/*
Toto je náš element:
<div trida='trida1 trida2' id='nejakeID' attr='hodnota' otherAttr='cs-cz co neco' />
*/
/* Můžeme vybrat tento element třeba podle jeho třídy */
.trida1 { }
/* nebo obou tříd! */
.trida1.trida2 { }
/* nebo jeho jména */
div { }
/* nebo jeho id */
#nejakeID { }
/* nebo podle toho, že má atribut! */
[attr] { font-size:smaller; }
/* nebo že argument nabývá specifické hodnoty*/
[attr='hodnota'] { font-size:smaller; }
/* začíná nějakou hodnotou (CSS 3) */
[attr^='ho'] { font-size:smaller; }
/* nebo končí něčím (CSS 3) */
[attr$='ta'] { font-size:smaller; }
/* nebo obsahuje nějakou hodnotu, která je v atributu oddělená mezerami */
[otherAttr~='co'] { }
[otherAttr~='neco'] { }
/* nebo obsahuje hodnotu oddělenou pomlčkou - "-" (U+002D) */
[otherAttr|='cs'] { font-size:smaller; }
/* Můžeme spojit různé selektory, abychom získali specifičtější selektor.
Pozor, nedávejte mezi ně mezery! */
div.nejaka-trida[attr$='ta'] { }
/* Můžeme vybrat element, který je potomek jineho */
div.vnejsi-element > .jmeno-tridy { }
/* nebo zanořen ještě hlouběji. Potomci jsou přímo pod vnější třídou, pouze 1
úroveň pod rodičem. Tento selektor bude fungovat na jakékoliv úrovni pod
rodičem */
div.rodic .jmeno-tridy { }
/* Varování: stejný selektor bez mezery má úplně jiný význam
Vzpomínáte si jaký? */
div.rodic.jmeno-tridy { }
/* Možná budete chtít vybrat element, který leží přímo vedle */
.jsem-primo-pred + .timto-elementem { }
/* nebo kdekoliv na stejné úrovni stromu */
.jsem-kdekoliv-pred ~ .timto-elementem { }
/* Existují selektory nazvané pseudo třídy, kterými můžeme vybrat elementy,
když jsou v určitém stavu */
/* na příklad, když kurzor najede na element */
selektor:hover { }
/* nebo již navštívený odkaz */
selektor:visited { }
/* nebo nebyl navštíven */
selektor:link { }
/* nebo když je vybrán, např kliknutím do inputu*/
selektor:focus { }
/* element, ktery je prvni potomek rodiče */
selektor:first-child {}
/* element, který je poslední potomek rodiče */
selektor:last-child {}
/* Stejně jako pseudo třídy, umožňují pseudo elementy stylizovat určité
části dokumentu */
/* odpovídá virtuálnímu prvnímu potomku */
selektor::before {}
/* odpovídá virtuálnímu poslednímu potomku */
selektor::after {}
/* Na vhodném místě, může být použitá hvězdička jako žolík, který vybere každý element */
* { } /* všechny elementy */
.rodic * { } /* všechny vnořené elementy */
.rodic > * { } /* všichni potomci */
/* ####################
## VLASTNOSTI
#################### */
selektor {
/* Jednotky délky můžou být relativní nebo absolutní */
/* Relativní jednotky */
width: 50%; /* počet procent šířky rodičovského elementu */
font-size: 2em; /* násobek puvodní velikosti fontu elementu */
font-size: 2rem; /* nebo kořenového elementu */
font-size: 2vw; /* násobek 1% šířky zařízení (viewport) (CSS 3) */
font-size: 2vh; /* nebo jeho výšky */
font-size: 2vmin; /* násobek 1% výšky nebo šířky, dle toho, co je menší */
font-size: 2vmax; /* nebo větší */
/* Absolutní jednotky */
width: 200px; /* pixely */
font-size: 20pt; /* body */
width: 5cm; /* centimetry */
min-width: 50mm; /* milimetry */
max-width: 5in; /* palce */
/* Barvy */
color: #F6E; /* krátký hexadecimální formát */
color: #FF66EE; /* dlouhý hexadecimální formát */
color: tomato; /* pojmenovaná barva */
color: rgb(255, 255, 255); /* hodnoty rgb */
color: rgb(10%, 20%, 50%); /* procenta rgb */
color: rgba(255, 0, 0, 0.3); /* hodnoty rgba (CSS 3) Poznámka: 0 < a < 1 */
color: transparent; /* ekvivalentní jako nastavení alfy 0 */
color: hsl(0, 100%, 50%); /* procenta hsl (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* procenta hsl s alfou */
/* Obrázky jako pozadí elementu */
background-image: url(/cesta/k/obrazku.jpg); /* uvozovky jsou dobrovolné */
/* Fonty */
font-family: Arial;
/* když název fontu obsahuje mezeru, tak musí být v uvozovkách */
font-family: "Courier New";
/* když se první nenaleze, použije se další atd. */
font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
```
## Použití
Uložte CSS soubor s příponou `.css`.
```xml
<!-- Musíte vložit css soubor do hlavičky vaší stránky. Toto je
doporučená metoda. Viz http://stackoverflow.com/questions/8284365 -->
<link rel='stylesheet' type='text/css' href='cesta/k/stylu.css' />
<!-- Také lze vložit CSS přímo do HTML. -->
<style>
a { color: purple; }
</style>
<!-- Nebo přímo nastavit vlasnost elementu -->
<div style="border: 1px solid red;">
</div>
```
## Priorita nebo kaskáda
Element může být vybrán více selektory a jeho vlastnosti můžou být nastaveny více než jednou. V těchto případech, jedno zadání vlastnosti prioritu před druhým. Obecně platí, že více specifické selektory mají přednost před těmi méně specifickými.
Tento proces se nazývá kaskáda, proto i název kaskádové styly(Cascading Style Sheets).
Máme následující CSS
```css
/* A */
p.trida1[attr='hodnota']
/* B */
p.trida1 { }
/* C */
p.trida2 { }
/* D */
p { }
/* E */
p { vlastnost: hodnota !important; }
```
a tento element
```xml
<p style='/*F*/ vlastnost:hodnota;' trida='trida1 trida2' attr='hodnota' />
```
Priorita stylu je následující. Pamatujte, priorita pro každou **vlastnost**, ne pro celý blok.
* `E` nejvyšší prioritu kvůli slůvku `!important`. Je doporučováno se úplně vyhnout jeho použití.
* `F` je další, kvůli stylu zadanému přimo do elementu
* `A` je další, protože je více specifické, než cokoliv dalšího. 3 selektory: jméno elementu `p`, jeho třídu `trida1`, atribut `attr='hodnota'`.
* `C` je další, i když je stejně specifický jako `B`, protože je uveden po něm.
* `B` je další
* `D` je poslední
## Kompatibilita
Většina z možností v CSS 2 (a spousta v CSS 3) je dostupná napříč všemi browsery a zařízeními. Ale pořád je dobrá praxe, zkontrolovat dostupnost, před užitím nové vlastnosti/fičury.
## Zdroje
* Přehled dostupnosti [CanIUse](http://caniuse.com).
* CSS hřiště [Dabblet](http://dabblet.com/).
* [Mozilla Developer Network - CSS dokumentace](https://developer.mozilla.org/en-US/docs/Web/CSS)
* [Codrops](http://tympanus.net/codrops/css_reference/)
## Další čtení
* [Pochopení priority v CSS: specifičnost, děditelnost a kaskáda](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [Vybírání elementů pomocí atributů](https://css-tricks.com/almanac/selectors/a/attribute/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - překrývání obsahu](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
* [SASS](http://sass-lang.com/) a [LESS](http://lesscss.org/) pro CSS pre-processing
* [CSS-Triky](https://css-tricks.com)

373
cs-cz/elm.html.markdown Normal file
View File

@@ -0,0 +1,373 @@
---
language: Elm
contributors:
- ["Max Goldstein", "http://maxgoldste.in/"]
translators:
- ["Robin Pokorný", "http://robinpokorny.com/"]
filename: learnelm-cz.elm
lang: cs-cz
---
Elm je funkcionální reaktivní jazyk, který se kompiluje do (klientského) JavaScriptu.
Elm je silně typovaný, díky tomu je překladač schopen zachytit většinu chyb okamžitě a
vypsat snadno srozumitelná chybová hlášení.
Elm se hodí k tvorbě webových uživatelských rozhraní a her.
```haskell
-- Jednořádkové komentáře začínají dvěma pomlčkami.
{- Víceřádkové komentáře mohou být takto uzavřeny do bloku.
{- Mohou být i zanořeny. -}
-}
{-- Základy --}
-- Aritmetika
1 + 1 -- 2
8 - 1 -- 7
10 * 2 -- 20
-- Každé číslo bez desetinné tečky je typu Int nebo Float.
33 / 2 -- 16.5 s reálným dělením
33 // 2 -- 16 s celočíselným dělením
-- Umocňování
5 ^ 2 -- 25
-- Pravdivostní proměnné
not True -- False
not False -- True
1 == 1 -- True
1 /= 1 -- False
1 < 10 -- True
-- Řetězce a znaky
"Toto je textový řetězec, protože používá dvojité uvozovky."
'a' -- znak v jednoduchých uvozovkách
-- Řetězce lze spojovat.
"Ahoj " ++ "světe!" -- "Ahoj světe!"
{-- Seznamy (List), n-tice (Tuple) a Záznamy (Record) --}
-- Každá položka seznamu musí být stejného typu.
["příliš", "žluťoučký", "kůň", "úpěl"]
[1, 2, 3, 4, 5]
-- Druhý příklad lze zapsat také pomocí dvou teček.
List.range 1 5
-- Spojovat seznamy lze stejně jako řetězce.
List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True
-- K přidání položky do seznamu použijte funkci "cons".
0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5]
-- Funkce "head" pro získání první položky seznamu i funkce "tail" pro získání následujích položek
-- vrací typ Maybe. Místo zjišťování, jestli nějaká položka není null,
-- se s chybějcími hodnotami vypořádáme explicitně.
List.head (List.range 1 5) -- Just 1
List.tail (List.range 1 5) -- Just [2, 3, 4, 5]
List.head [] -- Nothing
-- List.nazevFunkce odkazuje na funkci, která žije v modulu List.
-- Každý prvek v n-tici může být jiného typu, ale n-tice má pevný počet prvků.
("elm", 42)
-- K získání hodnot z dvojice použijte funkce first a second.
-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
fst ("elm", 42) -- "elm"
snd ("elm", 42) -- 42
-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
-- Je to jediná hodnota svého typu, který se také nazývá "Unit".
()
-- Záznamy jsou podobné n-ticím, ale prvky jsou pojmenovány. Na pořadí nezáleží.
-- Povšimněte si, že hodnoty vlastností se přiřazují rovnítky, ne dvojtečkami.
{ x = 3, y = 7 }
-- K hodnotám se přistupuje pomocí tečky a názvu vlastnosti.
{ x = 3, y = 7 }.x -- 3
-- Nebo využitím přístupové funkce, což je jen tečka a název vlastnosti.
.y { x = 3, y = 7 } -- 7
-- Změna hodnoty vlastnosti v záznamu. (Záznam tuto vlastnost už musí mít.)
{ osoba |
jmeno = "Jiří" }
-- Změna více vlastností s využitím aktuálních hodnot.
{ hmotnyBod |
poloha = hmotnyBod.poloha + hmotnyBod.rychlost,
rychlost = hmotnyBod.rychlost + hmotnyBod.zrychleni }
{-- Řídicí struktury --}
-- Podmínky vždy musí mít větev "else" a obě větve musí být stejného typu.
if powerLevel > 9000 then
"PÁNI!"
else
"hmm"
-- Podmínky lze skládat za sebe.
if n < 0 then
"n je záporné"
else if n > 0 then
"n je kladné"
else
"n je nula"
-- Použíjte příkaz "case" k nalezení shody vzoru a různých možností.
case seznam of
[] -> "odpovídá práznému seznamu"
[x]-> "odpovídá seznamu o právě jedné položce, " ++ toString x
x::xs -> "odpovídá seznamu o alespoň jedné položce, jehož prvním prvkem je " ++ toString x
-- Shody se vyhodnocují v zapsaném pořadí. Kdybychom umístili [x] poslední, nikdy by nenastala shoda,
-- protože x::xs také odpovídá (xs by byl prázdný seznam). Shody "nepropadají".
-- Překladač vždy upozorní na chybějící nebo přebývající větve.
-- Větvení typu Maybe.
case List.head seznam of
Just x -> "První položka je " ++ toString x
Nothing -> "Seznam byl prázdný."
{-- Funkce --}
-- Syntaxe funkcí je v Elmu velmi úsporná, založená spíše na mezerách
-- než na závorkách. Neexistuje tu klíčové slovo "return".
-- Funkci definujeme jejím jménem, parametry, rovnítkem a tělem.
vynasob a b =
a * b
-- Funkci voláme předáním parametrů (bez oddělujících čárek).
vynasob 7 6 -- 42
-- Částečně aplikované funkci předáme pouze některé parametry.
-- Poté zvolíme nové jméno.
zdvoj =
vynasob 2
-- Konstanty jsou podobné, ale nepřijímají žádné parametry.
odpoved =
42
-- Předejte funkci jako parametr jiným funkcím.
List.map zdvoj (List.range 1 4) -- [2, 4, 6, 8]
-- Nebo použijte anonymní funkci.
List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8]
-- V definici funkce lze zapsat vzor, může-li nastat pouze jeden případ.
-- Tato funkce přijímá jednu dvojici místo dvou parametrů.
obsah (sirka, delka) =
sirka * delka
obsah (6, 7) -- 42
-- Složenými závorkami vytvořte vzor pro názvy vlastností v záznamu.
-- Použijte "let" k definici lokálních proměnných.
objem {sirka, delka, hloubka} =
let
obsah = sirka * delka
in
obsah * hloubka
objem { sirka = 3, delka = 2, hloubka = 7 } -- 42
-- Funkce mohou být rekurzivní.
fib n =
if n < 2 then
1
else
fib (n - 1) + fib (n - 2)
List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
-- Jiná rekurzivní funkce (v praxi použijte List.length).
delkaSeznamu seznam =
case seznam of
[] -> 0
x::xs -> 1 + delkaSeznamu xs
-- Funkce se volají před jakýmkoli infixovým operátorem. Závorky určují prioritu.
cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
-- Nejprve se aplikuje "degrees" na číslo 30, výsledek je pak předán trigonometrickým
-- funkcím, které jsou následně umocněny na druhou, na závěr proběhne sčítání.
{-- Typy a typové anotace --}
-- Překladač odvodí typ každé hodnoty ve vašem programu.
-- Typy vždy začínají velkým písmenem. Čtete x : T jako "x je typu T".
-- Některé běžné typy, které můžete videt v Elmovém REPLu.
5 : Int
6.7 : Float
"ahoj" : String
True : Bool
-- Funkce mají také typy. Čtěte "->" jako "vrací".
-- O typu na konci uvažujte jako návratovém typu, o ostatních jako typech argumentů.
not : Bool -> Bool
round : Float -> Int
-- Když definujete hodnotu, je dobrým zvykem zapsat nad ni její typ.
-- Anotace je formou dokumentace, která je ověřována překladačem.
zdvoj : Int -> Int
zdvoj x = x * 2
-- Funkce jako parametr je uzavřena v závorkách.
-- Typy s malým počátečním písmenem jsou typové proměnné:
-- mohou být libovolného typu, ale v každém volání musí být stejné.
List.map : (a -> b) -> List a -> List b
-- "List tečka map je typu a-vrací-b, vrací seznam-položek-typu-a, vrací seznam-položek-typu-b."
-- Existují tři speciální typové proměnné:
-- číslo (number), porovnatelné (comparable), and spojitelné (appendable).
-- Čísla dovolují použít aritmetiku na Int a Float.
-- Porovnatelné dovolují uspořádat čísla a řetězce, např. a < b.
-- Spojitelné lze zřetězit pomocí a ++ b.
{-- Typové aliasy a výčtové typy --}
-- Pro záznamy a n-tice již typy automaticky existují.
-- (Povšimněte si, že typ vlatnosti záznamu přiřazujeme dvojtečkou a hodnotu rovnítkem.)
pocatek : { x : Float, y : Float, z : Float }
pocatek =
{ x = 0, y = 0, z = 0 }
-- Stávajícím typům lze dávat jména využitím aliasů.
type alias Bod3D =
{ x : Float, y : Float, z : Float }
-- Alias pro záznam funguje také jako jeho konstruktor.
jinyPocatek : Bod3D
jinyPocatek =
Bod3D 0 0 0
-- Jedná se stále o stejný typ, lze je tedy porovnat.
pocatek == jinyPocatek -- True
-- Oproti tomu výčtový (union) typ definuje zcela nový typ.
-- Výčtový typ se takto jmenuje, protože může být jedním z několika vybraných možností.
-- Každá možnost je reprezentována jako "tag".
type Smer =
Sever | Jih | Vychod | Zapad
-- Tagy mohou obsahovat další hodnoty známých typů. Lze využít i rekurze.
type IntStrom =
Vrchol | Uzel Int IntStrom IntStrom
-- "Vrchol" i "Uzel" jsou tagy. Vše, co následuje za tagem, je typ.
-- Tagy lze použít jako hodnoty funkcí.
koren : IntStrom
koren =
Vrchol 7 List List
-- Výčtové typy (a typové aliasy) mohou obsahovat typové proměnné.
type Strom a =
Vrchol | Uzel a (Strom a) (Strom a)
-- "Typ strom-prvků-a je vrchol, nebo uzel obsahující a, strom-prvků-a a strom-prvků-a."
-- Vzory se shodují s tagy. Tagy s velkým počátečním písmenem odpovídají přesně.
-- Proměnné malým písmem odpovídají čemukoli. Podtržítko také odpovídá čemukoli,
-- ale určuje, že tuto hodnotu dále nechceme používat.
nejviceVlevo : Strom a -> Maybe a
nejviceVlevo strom =
case strom of
Vrchol -> Nothing
Uzel x Vrchol _ -> Just x
Uzel _ podstrom _ -> nejviceVlevo podstrom
-- To je víceméně vše o jazyku samotném.
-- Podívejme se nyní, jak organizovat a spouštět náš kód.
{-- Moduly a importování --}
-- Standardní knihovny jsou organizovány do modulů, stejně jako knihovny třetích stran,
-- které můžete využívat. Ve větších projektech můžete definovat vlastní moduly.
-- Vložte toto na začátek souboru. Pokud nic neuvedete, předpokládá se "Main".
module Jmeno where
-- Výchozím chováním je, že se exportuje vše.
-- Případně můžete definovat exportované vlastnosti explicitně.
module Jmeno (MujTyp, mojeHodnota) where
-- Běžný návrhový vzor je expotovat pouze výčtový typ bez jeho tagů.
-- Tento vzor je znám jako krycí typ a často se využívá v knihovnách.
-- Z jiných modulů lze importovat kód a použít jej v aktuálním modulu.
-- Nasledující umístí Dict do aktuálního scope, takže lze volat Dict.insert.
import Dict
-- Importuje modul Dict a typ Dict, takže v anotacích není nutné psát Dict.Dict.
-- Stále lze volat Dict.insert.
import Dict exposing (Dict)
-- Přejmenování importu.
import Graphics.Collage as C
{-- Porty --}
-- Port oznamuje, že budete komunikovat s vnějším světem.
-- Porty jsou dovoleny pouze v modulu Main.
-- Příchozí port je jen typová anotace.
port idKlienta : Int
-- Odchozí port má definici.
port objednavkaKlienta : List String
port objednavkaKlienta = ["Knihy", "Potraviny", "Nábytek"]
-- Nebudeme zacházet do detailů, ale v JavaScriptu se dají nastavit
-- callbacky pro zasílání na příchozí porty a čtení z odchozích portů.
{-- Nástroje pro příkazovou řádku --}
-- Kompilace souboru.
$ elm make MujSoubor.elm
-- Při prvním spuštění nainstaluje Elm standardní knihovny a vytvoří soubor
-- elm-package.json, kde jsou uloženy informace o vašem projektu.
-- Elm reactor je server, který překládá a spouští vaše soubory.
-- Kliknutím na klíč vedle názvu souboru spustíte debugger s cestovám v čase!
$ elm reactor
-- Zkoušejte si jednoduché příkazy v Read-Eval-Print Loop.
$ elm repl
-- Balíčky jsou určeny uživatelským jménem na GitHubu a názvem repozitáře.
-- Nainstalujte nový balíček a uložte jej v souboru elm-package.json.
$ elm package install evancz/elm-lang/html
-- Porovnejte změny mezi verzemi jednoho balíčku.
$ elm package diff elm-lang/html 1.1.0 2.0.0
-- Správce balíčků v Elmu vyžaduje sémantické verzování,
-- takže minor verze nikdy nerozbije váš build.
```
Jazyk Elm je překvapivě malý. Nyní se můžete podívat do skoro jakéhokoli zdrojového kódu
v Elmu a budete mít zběžnou představu o jeho fungování.
Ovšem možnosti, jak psát kód, který je odolný vůči chybám a snadno se refaktoruje, jsou neomezené!
Zde jsou některé užitečné zdroje (v angličtině).
* [Hlavní stránka Elmu](http://elm-lang.org/). Obsahuje:
* Odkazy na [instalátory](http://elm-lang.org/install)
* [Documentaci](http://elm-lang.org/docs), včetně [popisu syntaxe](http://elm-lang.org/docs/syntax)
* Spoustu nápomocných [příkladů](http://elm-lang.org/examples)
* Documentace pro [standardní knihovny Elmu](http://package.elm-lang.org/packages/elm-lang/core/latest/). Povšimněte si:
* [Základy](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), které jsou automaticky importovány
* Typ [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) a jeho bratranec typ [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), které se běžně používají pro chybějící hodnoty a ošetření chyb.
* Datové struktury jako [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict) a [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
* JSON [enkódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) a [dekódování](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
* [Architektura Elmu](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). Esej od tvůrce Elmu s příklady, jak organizovat kód do komponent.
* [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Všichni jsou přátelští a nápomocní.
* [Scope v Elmu](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) a [Jak číst typové anotace](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). Další komunitní návody o základech Elmu, psáno pro JavaScriptové vývojáře.
Běžte si zkusit něco napsat v Elmu!

431
cs-cz/go.html.markdown Normal file
View File

@@ -0,0 +1,431 @@
---
name: Go
category: language
language: Go
filename: learngo-cs.go
lang: cs-cz
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["Christopher Bess", "https://github.com/cbess"]
- ["Jesse Johnson", "https://github.com/holocronweaver"]
- ["Quint Guvernator", "https://github.com/qguv"]
- ["Jose Donizetti", "https://github.com/josedonizetti"]
- ["Alexej Friesen", "https://github.com/heyalexej"]
- ["Clayton Walker", "https://github.com/cwalk"]
translators:
- ["Ondra Linek", "https://github.com/defectus/"]
---
Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední
trend ve světě počítačové vědy, ale je to nejrychlejší a nejnovější způsob,
jak řešit realné problémy.
Go používá známé koncepty imperativních jazyků se statickým typováním.
Rychle se kompiluje a také rychle běží. Přidává snadno pochopitelnou
podporu konkurenčnosti, což umožňuje využít výhody multi-core procesorů a
jazyk také obsahuje utility, které pomáhají se škálovatelným programováním.
Go již v základu vynikající knihovnu a je s ním spojená nadšená komunita.
```go
// Jednořádkový komentář
/* Několika
řádkový komentář */
// Každý zdroják začíná deklarací balíčku (package)
// Main je vyhrazené jméno, které označuje spustitelný soubor,
// narozdíl od knihovny
package main
// Importní deklarace říkají, které knihovny budou použity v tomto souboru.
import (
"fmt" // Obsahuje formátovací funkce a tisk na konzolu
"io/ioutil" // Vstupně/výstupní funkce
m "math" // Odkaz na knihovnu math (matematické funkce) pod zkratkou m
"net/http" // Podpora http protokolu, klient i server.
"strconv" // Konverze řetězců, např. na čísla a zpět.
)
// Definice funkce. Funkce main je zvláštní, je to vstupní bod do programu.
// Ať se vám to líbí, nebo ne, Go používá složené závorky
func main() {
// Println vypisuje na stdout.
// Musí být kvalifikováno jménem svého balíčko, ftm.
fmt.Println("Hello world!")
// Zavoláme další funkci
svetPoHello()
}
// Funkce mají své parametry v závorkách
// Pokud funkce nemá parametry, tak musíme stejně závorky uvést.
func svetPoHello() {
var x int // Deklarace proměnné. Proměnné musí být před použitím deklarované
x = 3 // Přiřazení hodnoty do proměnné
// Existuje "krátká" deklarace := kde se typ proměnné odvodí,
// proměnná vytvoří a přiřadí se jí hodnota
y := 4
sum, prod := naucSeNasobit(x, y) // Funkce mohou vracet více hodnot
fmt.Println("sum:", sum, "prod:", prod) // Jednoduchý výstup
naucSeTypy() // < y minut je za námi, je čas učit se víc!
}
/* <- začátek mnohořádkového komentáře
Funkce mohou mít parametry a (několik) návratových hodnot.
V tomto případě jsou `x`, `y` parametry a `sum`, `prod` jsou návratové hodnoty.
Všiměte si, že `x` a `sum` jsou typu `int`.
*/
func naucSeNasobit(x, y int) (sum, prod int) {
return x + y, x * y // Vracíme dvě hodnoty
}
// zabudované typy a literáty.
func naucSeTypy() {
// Krátká deklarace většinou funguje
str := "Learn Go!" // typ řetězec.
s2 := `"surový" literát řetězce
může obsahovat nové řádky` // Opět typ řetězec.
// Můžeme použít ne ASCII znaky, Go používá UTF-8.
g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8
f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou.
c := 3 + 4i // complex128, interně uložené jako dva float64.
// takhle vypadá var s inicializací
var u uint = 7 // Číslo bez znaménka, jehož velikost záleží na implementaci,
// stejně jako int
var pi float32 = 22. / 7
// takto se převádí typy za pomoci krátké syntaxe
n := byte('\n') // byte je jiné jméno pro uint8.
// Pole mají fixní délku, které se určuje v době kompilace.
var a4 [4]int // Pole 4 intů, všechny nastaveny na 0.
a3 := [...]int{3, 1, 5} // Pole nastaveno na tři hodnoty
// elementy mají hodntu 3, 1 a 5
// Slicy mají dynamickou velikost. Pole i slacy mají své výhody,
// ale většinou se používají slicy.
s3 := []int{4, 5, 9} // Podobně jako a3, ale není tu výpustka.
s4 := make([]int, 4) // Alokuj slice 4 intů, všechny nastaveny na 0.
var d2 [][]float64 // Deklarace slicu, nic se nealokuje.
bs := []byte("a slice") // Přetypování na slice
// Protože jsou dynamické, můžeme ke slicům přidávat za běhu
// Přidat ke slicu můžeme pomocí zabudované funkce append().
// Prvním parametrem je slice, návratová hodnota je aktualizovaný slice.
s := []int{1, 2, 3} // Výsledkem je slice se 3 elementy.
s = append(s, 4, 5, 6) // Přidány další 3 elementy. Slice má teď velikost 6.
fmt.Println(s) // Slice má hodnoty [1 2 3 4 5 6]
// Pokud chceme k poli přičíst jiné pole, můžeme předat referenci na slice,
// nebo jeho literát a přidat výpustku, čímž se slicu "rozbalí" a přidá se k
// původnímu slicu.
s = append(s, []int{7, 8, 9}...) // druhým parametrem je literát slicu.
fmt.Println(s) // slice má teď hodnoty [1 2 3 4 5 6 7 8 9]
p, q := naucSePraciSPameti() // Deklarujeme p a q jako typ pointer na int.
fmt.Println(*p, *q) // * dereferencuje pointer. Tím se vypíší dva inty.
// Mapy jsou dynamické rostoucí asociativní pole, jako hashmapa, nebo slovník
// (dictionary) v jiných jazycích
m := map[string]int{"tri": 3, "ctyri": 4}
m["jedna"] = 1
// Napoužité proměnné jsou v Go chybou.
// Použijte podtržítko, abychom proměnno "použili".
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
// Výpis promenné se počítá jako použití.
fmt.Println(s, c, a4, s3, d2, m)
naucSeVetveníProgramu() // Zpátky do běhu.
}
// narozdíl od jiných jazyků, v Go je možné mít pojmenované návratové hodnoty.
// Tak můžeme vracet hodnoty z mnoha míst funkce, aniž bychom uváděli hodnoty v
// return.
func naucSePojmenovaneNavraty(x, y int) (z int) {
z = x * y
return // z je zde implicitní, jelikož bylo pojmenováno.
}
// Go má garbage collector. Používá pointery, ale neumožňuje jejich aritmetiku.
// Můžete tedy udělat chybu použitím nil odkazu, ale ne jeho posunutím.
func naucSePraciSPameti() (p, q *int) {
// Pojmenované parametry p a q mají typ odkaz na int.
p = new(int) // Zabudované funkce new alokuje paměť.
// Alokované místo pro int má hodnotu 0 a p už není nil.
s := make([]int, 20) // Alokujeme paměť pro 20 intů.
s[3] = 7 // Jednu z nich nastavíme.
r := -2 // Deklarujeme další lokální proměnnou.
return &s[3], &r // a vezmeme si jejich odkaz pomocí &.
}
func narocnyVypocet() float64 {
return m.Exp(10)
}
func naucSeVetveníProgramu() {
// Výraz if vyžaduje složené závorky, ale podmínka nemusí být v závorkách.
if true {
fmt.Println("říkal jsme ti to")
}
// Formátování je standardizované pomocí utility "go fmt".
if false {
// posměšek.
} else {
// úšklebek.
}
// Použij switch, když chceš zřetězit if.
x := 42.0
switch x {
case 0:
case 1:
case 42:
// jednotlivé case nepropadávají. není potřeba "break"
case 43:
// nedosažitelné, jelikož už bylo ošetřeno.
default:
// implicitní větev je nepovinná.
}
// Stejně jako if, for (smyčka) nepoužívá závorky.
// Proměnné definované ve for jsou lokální vůči smyčce.
for x := 0; x < 3; x++ { // ++ je výrazem.
fmt.Println("iterace", x)
}
// zde je x == 42.
// For je jediná smyčka v Go, ale má několik tvarů.
for { // Nekonečná smyčka
break // Dělám si legraci
continue // Sem se nedostaneme
}
// Můžete použít klíčové slovo range pro iteraci nad mapami, poli, slicy,
// řetězci a kanály.
// range vrací jednu (kanál) nebo dvě hodnoty (pole, slice, řetězec a mapa).
for key, value := range map[string]int{"jedna": 1, "dva": 2, "tri": 3} {
// pro každý pár (klíč a hodnota) je vypiš
fmt.Printf("klíč=%s, hodnota=%d\n", key, value)
}
// stejně jako for, := v podmínce if přiřazuje hodnotu
// nejříve nastavíme y a pak otestujeme, jestli je y větší než x.
if y := narocnyVypocet(); y > x {
x = y
}
// Funkční literáty jsou tzv. uzávěry (closure)
xBig := func() bool {
return x > 10000 // odkazuje na x deklarované ve příkladu použití switch
}
x = 99999
fmt.Println("xBig:", xBig()) // true
x = 1.3e3 // To udělá z x == 1300
fmt.Println("xBig:", xBig()) // teď už false.
// Dále je možné funkční literáty definovat a volat na místě jako parametr
// funkce, dokavaď:
// a) funkční literát je okamžitě volán pomocí (),
// b) výsledek se shoduje s očekávaným typem.
fmt.Println("Sečte + vynásobí dvě čísla: ",
func(a, b int) int {
return (a + b) * 2
}(10, 2)) // Voláno s parametry 10 a 2
// => Sečti a vynásob dvě čísla. 24
// Když to potřebujete, tak to milujete
goto miluji
miluji:
naučteSeFunkčníFactory() // funkce vracející funkce je zábava(3)(3)
naučteSeDefer() // malá zajížďka k důležitému klíčovému slovu.
naučteSeInterfacy() // Přichází dobré věci!
}
func naučteSeFunkčníFactory() {
// Následující dvě varianty jsou stejné, ale ta druhá je praktičtější
fmt.Println(větaFactory("létní")("Hezký", "den!"))
d := větaFactory("letní")
fmt.Println(d("Hezký", "den!"))
fmt.Println(d("Líný", "odpoledne!"))
}
// Dekorátory jsou běžné v jiných jazycích. To samé můžete udělat v Go
// pomocí parameterizovatelných funkčních literátů.
func větaFactory(můjŘetězec string) func(před, po string) string {
return func(před, po string) string {
return fmt.Sprintf("%s %s %s", před, můjŘetězec, po) // nový řetězec
}
}
func naučteSeDefer() (ok bool) {
// Odloží (defer) příkazy na okamžik těsně před opuštěním funkce.
// tedy poslední se provede první
defer fmt.Println("odložené příkazy jsou zpravovaná v LIFO pořadí.")
defer fmt.Println("\nProto je tato řádka vytištěna první")
// Defer se běžně používá k zavírání souborů a tím se zajistí, že soubor
// bude po ukončení funkce zavřen.
return true
}
// definuje typ interfacu s jednou metodou String()
type Stringer interface {
String() string
}
// Definuje pár jako strukturu se dvěma poli typu int x a y.
type pár struct {
x, y int
}
// Definuje method pár. Pár tedy implementuje interface Stringer.
func (p pár) String() string { // p je tu nazýváno "Receiver" - přijímač
// Sprintf je další veřejná funkce z balíčku fmt.
// Pomocí tečky přistupujeme k polím proměnné p
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
func naučteSeInterfacy() {
// Složené závorky jsou "strukturální literáty. Vyhodnotí a inicializuje
// strukturu. Syntaxe := deklaruje a inicializuje strukturu.
p := pár{3, 4}
fmt.Println(p.String()) // Volá metodu String na p typu pár.
var i Stringer // Deklaruje i jako proměnné typu Stringer.
i = p // Toto je možné, jelikož oba implementují Stringer
// zavolá metodu String(( typu Stringer a vytiskne to samé jako předchozí.
fmt.Println(i.String())
// Funkce ve balíčku fmt volají metodu String, když zjišťují, jak se má typ
// vytisknout.
fmt.Println(p) // Vytiskne to samé, jelikož Println volá String().
fmt.Println(i) // Ten samý výstup.
naučSeVariabilníParametry("super", "učit se", "tady!")
}
// Funcke mohou mít proměnlivé množství parametrů.
func naučSeVariabilníParametry(mojeŘetězce ...interface{}) {
// Iterujeme přes všechny parametry
// Potržítku tu slouží k ignorování indexu v poli.
for _, param := range mojeŘetězce {
fmt.Println("parameter:", param)
}
// Použít variadický parametr jako variadický parametr, nikoliv pole.
fmt.Println("parametery:", fmt.Sprintln(mojeŘetězce...))
naučSeOšetřovatChyby()
}
func naučSeOšetřovatChyby() {
// ", ok" je metodou na zjištění, jestli něco fungovalo, nebo ne.
m := map[int]string{3: "tri", 4: "ctyri"}
if x, ok := m[1]; !ok { // ok bude false, jelikož 1 není v mapě.
fmt.Println("není tu jedna")
} else {
fmt.Print(x) // x by bylo tou hodnotou, pokud by bylo v mapě.
}
// hodnota error není jen znamením OK, ale může říct více o chybě.
if _, err := strconv.Atoi("ne-int"); err != nil { // _ hodnotu zahodíme
// vytiskne 'strconv.ParseInt: parsing "non-int": invalid syntax'
fmt.Println(err)
}
// Znovu si povíme o interfacech, zatím se podíváme na
naučSeKonkurenčnost()
}
// c je kanál, způsob, jak bezpečně komunikovat v konkurenčním prostředí.
func zvyš(i int, c chan int) {
c <- i + 1 // <- znamená "pošli" a posílá data do kanálu na levé straně.
}
// Použijeme funkci zvyš a konkurečně budeme zvyšovat čísla.
func naučSeKonkurenčnost() {
// funkci make jsme již použili na slicy. make alokuje a inicializuje slidy,
// mapy a kanály.
c := make(chan int)
// nastartuj tři konkurenční go-rutiny. Čísla se budou zvyšovat
// pravděpodobně paralelně pokud je počítač takto nakonfigurován.
// Všechny tři zapisují do toho samého kanálu.
go zvyš(0, c) // go je výraz pro start nové go-rutiny.
go zvyš(10, c)
go zvyš(-805, c)
// Přečteme si tři výsledky a vytiskeneme je..
// Nemůžeme říct, v jakém pořadí výsledky přijdou!
fmt.Println(<-c, <-c, <-c) // pokud je kanál na pravo, jedná se o "přijmi".
cs := make(chan string) // Další kanál, tentokrát pro řetězce.
ccs := make(chan chan string) // Kanál kanálu řetězců.
go func() { c <- 84 }() // Start nové go-rutiny na posílání hodnot.
go func() { cs <- "wordy" }() // To samé s cs.
// Select má syntaxi jako switch, ale vztahuje se k operacím nad kanály.
// Náhodně vybere jeden case, který je připraven na komunikaci.
select {
case i := <-c: // Přijatá hodnota může být přiřazena proměnné.
fmt.Printf("je to typ %T", i)
case <-cs: // nebo může být zahozena
fmt.Println("je to řetězec")
case <-ccs: // prázdný kanál, nepřipraven ke komunikaci.
fmt.Println("to se nestane.")
}
// V tomto okamžiku máme hodnotu buď z kanálu c nabo cs. Jedna nebo druhá
// nastartovaná go-rutina skončila a další zůstane blokovaná.
naučSeProgramovatWeb() // Go to umí. A vy to chcete taky.
}
// jen jedna funkce z balíčku http spustí web server.
func naučSeProgramovatWeb() {
// První parametr ListenAndServe je TCP adresa, kde poslouchat.
// Druhý parametr je handler, implementující interace http.Handler.
go func() {
err := http.ListenAndServe(":8080", pár{})
fmt.Println(err) // neignoruj chyby
}()
requestServer()
}
// Umožní typ pár stát se http tím, že implementuje její jedinou metodu
// ServeHTTP.
func (p pár) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Servíruj data metodou http.ResponseWriter
w.Write([]byte("Naučil ses Go za y minut!"))
}
func requestServer() {
resp, err := http.Get("http://localhost:8080")
fmt.Println(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("\nWebserver řekl: `%s`", string(body))
}
```
## Kam dále
Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/).
Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení.
Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go
popis balíčků (package), dokumentaci příkazové řádky a historii releasů.
Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti
jiným současným jazyků.
Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX).
Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako
[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go.
Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/).
Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/)
tak se podíváte na dokumentaci.
Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/).
Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou
spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile)
pro více informací.

309
cs-cz/hack.html.markdown Normal file
View File

@@ -0,0 +1,309 @@
---
language: Hack
filename: learnhack-cs.hh
contributors:
- ["Stephen Holdaway", "https://github.com/stecman"]
translators:
- ["Vojta Svoboda", "https://github.com/vojtasvoboda/"]
lang: cs-cz
---
Hack je nadmnožinou PHP a běží v rámci virtuálního stroje zvaného HHVM. Hack
dokáže skoro plně spolupracovat s existujícím PHP a přidává několik vylepšení,
které známe ze staticky typovaných jazyků.
Níže jsou popsané pouze vlastnosti jazyka Hack. Detaily ohledně jazyka PHP a jeho
syntaxe pak najdete na těchto stránkách v samostatném
[článku o PHP](http://learnxinyminutes.com/docs/php/).
```php
<?hh
// Hack je aktivní pouze pro soubory, které začínají <?hh.
// TODO <?hh soubory nemohou být jendoduše přeloženy v HTML tak jako <?php.
// Použitím značky <?hh //strict zapnete striktní mód typové kontroly.
// Typování skalární parametrů
function repeat(string $word, int $count)
{
$word = trim($word);
return str_repeat($word . ' ', $count);
}
// Typování návratových hodnot
function add(...$numbers) : int
{
return array_sum($numbers);
}
// Funkce které nic nevrací jsou typované jako "void"
function truncate(resource $handle) : void
{
// ...
}
// U typování musíme explicitně povolit prázdné (null) hodnoty
function identity(?string $stringOrNull) : ?string
{
return $stringOrNull;
}
// Typování může být použito i na proměnné třídy
class TypeHintedProperties
{
public ?string $name;
protected int $id;
private float $score = 100.0;
// Typ proměnné si můžeme zadat přímo u definice proměnné v rámci třídy,
// ale pak ho snadně přetížit v konstruktoru metody.
public function __construct(int $id)
{
$this->id = $id;
}
}
// Stručné anonymní funkce (lambda funkce)
$multiplier = 5;
array_map($y ==> $y * $multiplier, [1, 2, 3]);
// Generika (generické funkce)
class Box<T>
{
protected T $data;
public function __construct(T $data) {
$this->data = $data;
}
public function getData(): T {
return $this->data;
}
}
function openBox(Box<int> $box) : int
{
return $box->getData();
}
// Tvary
//
// Hack zavádí koncept tvaru pro definování strukturovaných polí s garantovanou
// typovou kontrolou pro klíče.
type Point2D = shape('x' => int, 'y' => int);
function distance(Point2D $a, Point2D $b) : float
{
return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
}
distance(
shape('x' => -1, 'y' => 5),
shape('x' => 2, 'y' => 50)
);
// Type aliasing
//
// Hack přidává několik vylepšení pro lepší čitelnost komplexních typů
newtype VectorArray = array<int, Vector<int>>;
// Množina obsahující čísla
newtype Point = (int, int);
function addPoints(Point $p1, Point $p2) : Point
{
return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
}
addPoints(
tuple(1, 2),
tuple(5, 6)
);
// Výčtový typ
enum RoadType : int
{
Road = 0;
Street = 1;
Avenue = 2;
Boulevard = 3;
}
function getRoadType() : RoadType
{
return RoadType::Avenue;
}
// Automatické nastavení proměnných třídy
//
// Aby se nemuseli definovat proměnné třídy a její konstruktor,
// který pouze nastavuje třídní proměnné, můžeme v Hacku vše
// definovat najednou.
class ArgumentPromotion
{
public function __construct(public string $name,
protected int $age,
private bool $isAwesome) {}
}
// Takto by to vypadalo bez automatického nastavení proměnných
class WithoutArugmentPromotion
{
public string $name;
protected int $age;
private bool $isAwesome;
public function __construct(string $name, int $age, bool $isAwesome)
{
$this->name = $name;
$this->age = $age;
$this->isAwesome = $isAwesome;
}
}
// Ko-operativní multi-tasking
//
// Nová klíčová slova "async" and "await" mohou být použité pro spuštění mutli-taskingu
// Tato vlastnost ovšem zahrnuje vícevláknové zpracování, pouze povolí řízení přenosu
async function cooperativePrint(int $start, int $end) : Awaitable<void>
{
for ($i = $start; $i <= $end; $i++) {
echo "$i ";
// Dává ostatním úlohám šanci něco udělat
await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
}
}
// Toto vypíše "1 4 7 2 5 8 3 6 9"
AwaitAllWaitHandle::fromArray([
cooperativePrint(1, 3),
cooperativePrint(4, 6),
cooperativePrint(7, 9)
])->getWaitHandle()->join();
// Atributy
//
// Atributy jsou určitou formou metadat pro funkce. Hack přidává některé vestavěné
// atributy které aktivnují uživatečné chování funkcí.
// Speciální atribut __Memoize způsobí, že výsledek funkce je uložen do cache
<<__Memoize>>
function doExpensiveTask() : ?string
{
return file_get_contents('http://example.com');
}
// Tělo funkce je v tomto případě vykonáno pouze jednou:
doExpensiveTask();
doExpensiveTask();
// Speciální atribut __ConsistentConstruct signalizuje typové kontrole Hacku, že
// zápis __construct bude stejný pro všechny podtřídy.
<<__ConsistentConstruct>>
class ConsistentFoo
{
public function __construct(int $x, float $y)
{
// ...
}
public function someMethod()
{
// ...
}
}
class ConsistentBar extends ConsistentFoo
{
public function __construct(int $x, float $y)
{
// Typová kontrola Hacku zajistí volání konstruktoru rodičovské třídy
parent::__construct($x, $y);
// ...
}
// Anotace __Override je volitelný signál pro typovou kontrolu Hacku, že
// tato metoda přetěžuje metodu rodičovské třídy, nebo traitu. Bez uvedení
// této anotace vyhodí typová kontrola chybu.
<<__Override>>
public function someMethod()
{
// ...
}
}
class InvalidFooSubclass extends ConsistentFoo
{
// Nedodržení zápisu dle rodičovského konstruktoru způsobí syntaktickou chybu:
//
// "Tento objekt je typu ConsistentBaz a není kompatibilní v tímto objektem,
// který je typu ConsistentFoo protože některé jeho metody nejsou kompatibilní."
//
public function __construct(float $x)
{
// ...
}
// Použitím anotace __Override na nepřetíženou metodu způsobí chybu typové kontroly:
//
// "InvalidFooSubclass::otherMethod() je označená jako přetížená, ale nebyla nalezena
// taková rodičovská metoda, nebo rodič kterého přetěžujete není zapsán v <?hh kódu"
//
<<__Override>>
public function otherMethod()
{
// ...
}
}
// Traity mohou implementovat rozhraní, což standardní PHP neumí
interface KittenInterface
{
public function play() : void;
}
trait CatTrait implements KittenInterface
{
public function play() : void
{
// ...
}
}
class Samuel
{
use CatTrait;
}
$cat = new Samuel();
$cat instanceof KittenInterface === true; // True
```
## Více informací
Pro více informací navštivte [referenční příručku jazyka Hack](http://docs.hhvm.com/manual/en/hacklangref.php),
kde se dozvíte více detailu a vylepšení, které jazyk Hack přidává do PHP, a nebo navštivte [oficiální stránky jazyka Hack](http://hacklang.org/)
pro obecné informace.
Pro instrukce k instalaci jazyka Hack navštivte [oficiální HHVM stránky](http://hhvm.com/).
Pro více informací ohledně zpětné kompatibility s PHP navštivte článek o [nepodporovaných PHP vlastnostech Hacku](http://docs.hhvm.com/manual/en/hack.unsupported.php).

View File

@@ -0,0 +1,574 @@
---
language: javascript
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
- ["Ariel Krakowski", "http://www.learneroo.com"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
lang: cs-cz
filename: javascript-cz.js
---
JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně
zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk Javy,
která byla zamýšlena pro více komplexní webové aplikace, ale jeho úzké propojení
s webovými stránkami a vestavěná podpora v prohlížečích způsobila, že se stala
více běžná ve webovém frontendu než Java.
JavaScript není omezen pouze na webové prohlížeče, např. projekt Node.js,
který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z
Google Chrome se stává více a více oblíbený pro serverovou část webových aplikací.
Zpětná vazba je velmi ceněná. Autora článku můžete kontaktovat (anglicky) na
[@adambrenecki](https://twitter.com/adambrenecki), nebo
[adam@brenecki.id.au](mailto:adam@brenecki.id.au), nebo , jakožto překladatele,
na [martinek@ludis.me](mailto:martinek@ludis.me).
```js
// Komentáře jsou jako v zayku C. Jednořádkové komentáře začínájí dvojitým lomítkem,
/* a víceřádkové komentáře začínají lomítkem s hvězdičkou
a končí hvězdičkou s lomítkem */
// Vyrazu můžou být spuštěny pomocí ;
delejNeco();
// ... ale nemusí, středníky jsou automaticky vloženy kdekoliv,
// kde končí řádka, kromě pár speciálních případů
delejNeco()
// Protože tyto případy můžou způsobit neočekávané výsledky, budeme
// středníky v našem návodu používat.
/////////////////////////////////
// 1. Čísla, řetězce a operátory
// JavaScript má jeden číselný typ (čímž je 64-bitový IEEE 754 double).
// Double má 52-bit přesnost, což je dostatečně přesné pro ukládání celých čísel
// do 9✕10¹⁵.
3; // = 3
1.5; // = 1.5
// Základní matematické operace fungují, jak byste očekávali
1 + 1; // = 2
0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
// Včetně dělení
5 / 2; // = 2.5
// A také dělení modulo
10 % 2; // = 0
30 % 4; // = 2
18.5 % 7; // = 4.5
// Bitové operace také fungují; když provádíte bitové operace, desetinné číslo
// (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů
1 << 2; // = 4
// Přednost se vynucuje závorkami.
(1 + 3) * 2; // = 8
// Existují 3 hodnoty mimo obor reálných čísel
Infinity; // + nekonečno; výsledek např. 1/0
-Infinity; // - nekonečno; výsledek např. -1/0
NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number')
// Také existují hodnoty typu bool
true; // pravda
false; // nepravda
// Řetězce znaků jsou obaleny ' nebo ".
'abc';
"Ahoj světe!";
// Negace se tvoří pomocí !
!true; // = false
!false; // = true
// Rovnost se porovnává ===
1 === 1; // = true
2 === 1; // = false
// Nerovnost zase pomocí !==
1 !== 1; // = false
2 !== 1; // = true
// Další srovnávání
1 < 10; // = true
1 > 10; // = false
2 <= 2; // = true
2 >= 2; // = true
// Řetězce znaků se spojují pomocí +
"Ahoj " + "světe!"; // = "Ahoj světe!"
// ... což funguje nejenom s řetězci
"1, 2, " + 3; // = "1, 2, 3"
"Ahoj " + ["světe", "!"] // = "Ahoj světe,!"
// a porovnávají se pomocí < nebo >
"a" < "b"; // = true
// Rovnost s převodem typů se dělá pomocí == ...
"5" == 5; // = true
null == undefined; // = true
// ...dokud nepoužijete ===
"5" === 5; // = false
null === undefined; // = false
// ...což může občas způsobit divné chování...
13 + !0; // 14
"13" + !0; // '13true'
// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt`
"Toto je řetězec".charAt(0); // = 'T'
// ...nebo použít `substring` k získání podřetězce
"Ahoj světe".substring(0, 4); // = "Ahoj"
// `length` znamená délka a je to vlastnost, takže nepoužívejte ()
"Ahoj".length; // = 4
// Existují také typy `null` a `undefined`.
null; // značí, že žádnou hodnotu
undefined; // značí, že hodnota nebyla definovaná (ikdyž
// `undefined` je hodnota sama o sobě)
// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní
// vrací pravdu (true)..
// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0"
// vrací pravdu
///////////////////////////////////
// 2. Proměnné, pole a objekty
// Proměnné jsou deklarovány pomocí slůvka `var`. JavaScript je dynamicky
// typovaný, takže nemusíme specifikovat typ. K přiřazení hodnoty se používá
// znak `=`.
var promenna = 5;
// když vynecháte slůvko 'var' nedostanete chybovou hlášku...
jinaPromenna = 10;
// ...ale vaše proměnná bude vytvořena globálně, bude vytvořena v globálním
// oblasti působnosti, ne jenom v lokálním tam, kde jste ji vytvořili
// Proměnné vytvořené bez přiřazení obsahují hodnotu undefined.
var dalsiPromenna; // = undefined
// Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou
var someFourthVar = 2, someFifthVar = 4;
// Existuje kratší forma pro matematické operace na proměnné
promenna += 5; // se provede stejně jako promenna = promenna + 5;
// promenna je ted 10
promenna *= 10; // teď je promenna rovna 100
// a tohle je způsob, jak přičítat a odečítat 1
promenna++; // teď je promenna 101
promenna--; // zpět na 100
// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu
var mojePole = ["Ahoj", 45, true];
// Jednotlivé hodnoty jsou přístupné přes hranaté závorky.
// Členové pole se začínají počítat na nule.
myArray[1]; // = 45
// Pole je proměnlivé délky a členové se můžou měnit
myArray.push("Světe");
myArray.length; // = 4
// Přidání/změna na specifickém indexu
myArray[3] = "Hello";
// JavaScriptové objekty jsou stejné jako asociativní pole v jinných programovacích
// jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota.
var mujObjekt = {klic1: "Ahoj", klic2: "světe"};
// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní
// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu-
var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4};
// K hodnotám můžeme přistupovat opět pomocí hranatých závorek
myObj["muj jiny klic"]; // = 4
// ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k
// hodnotám i přes tečku
mujObjekt.klic; // = "mojeHodnota"
// Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče.
myObj.mujDalsiKlic = true;
// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined
myObj.dalsiKlic; // = undefined
///////////////////////////////////
// 3. Řízení toku programu
// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu
// `if` (když) funguje, jak byste čekali.
var pocet = 1;
if (pocet == 3){
// provede, když se pocet rovná 3
} else if (pocet == 4){
// provede, když se pocet rovná 4
} else {
// provede, když je pocet cokoliv jinného
}
// Stejně tak cyklus while
while (true){
// nekonečný cyklus
}
// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou
var vstup;
do {
vstup = nactiVstup();
} while (!jeValidni(vstup))
// Cyklus for je stejný jako v Javě nebo jazyku C
// inicializace; podmínka pro pokračování; iterace.
for (var i = 0; i < 3; i++){
// provede třikrát
}
// Cyklus For-in iteruje přes každo vlastnost prototypu
var popis = "";
var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18};
for (var x in osoba){
popis += osoba[x] + " ";
}
//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou
//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty()
var popis = "";
var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18};
for (var x in osoba){
if (osoba.hasOwnProperty(x)){
popis += osoba[x] + " ";
}
}
// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů.
// Neexistuje jistota, že for-in je vrátí ve správném pořadí.
// && je logické a, || je logické nebo
if (dum.velikost == "velký" && dum.barva == "modrá"){
dum.obsahuje = "medvěd";
}
if (barva == "červená" || barva == "modrá"){
// barva je červená nebo modtrá
}
// && a || jsou praktické i pro nastavení základních hodnot
var jmeno = nejakeJmeno || "default";
// `switch` zkoumá přesnou rovnost (===)
// Používejte 'break;' po každé možnosti, jinak se provede i možnost za ní.
znamka = 'B';
switch (znamka) {
case 'A':
console.log("Výborná práce");
break;
case 'B':
console.log("Dobrá práce");
break;
case 'C':
console.log("Dokážeš to i lépe");
break;
default:
console.log("Ale ne");
break;
}
////////////////////////////////////////////////////////
// 4. Funckce, Oblast platnosti (scope) a Vnitřní funkce
// JavaScriptové funkce jsou definovány slůvkem `function`.
function funkce(text){
return text.toUpperCase();
}
funkce("něco"); // = "NĚCO"
// Dávejte si pozor na to, že hodnota k vrácení musí začínat na stejné řádce
// jako slůvko return, jinak se vrátí 'undefined', kvůli automatickému vkládání
// středníků. Platí to zejména pro Allmanův styl zápisu.
function funkce()
{
return // <- zde je automaticky vložen středník
{
tohleJe: "vlastnost objektu"
}
}
funkce(); // = undefined
// JavaScriptové funkce jsou objekty, takže můžou být přiřazeny různým proměnným
// a předány dalším funkcím jako argumenty, na příklad:
function funkce(){
// tento kód bude zavolán za 5 vteřin
}
setTimeout(funkce, 5000);
// Poznámka: setTimeout není část JS jazyka, ale funkce poskytována
// prohlížeči a NodeJS
// Další funkce poskytovaná prohlížeči je je setInterval
function myFunction(){
// tento kód bude volán každých 5 vteřin
}
setInterval(myFunction, 5000);
// Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako
// ananymní funkci přímo vloženou jako argument
setTimeout(function(){
// tento kód bude zavolán za 5 vteřin
}, 5000);
// JavaScript má oblast platnosti funkce, funkce ho mají, ale jiné bloky ne
if (true){
var i = 5;
}
i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj
// rámec působnosti
// Toto je běžný model,který chrání před únikem dočasných proměnných do
//globální oblasti
(function(){
var docasna = 5;
// Můžeme přistupovat k globálního oblasti přes přiřazování globalním
// objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt
// může mít v jiných prostředích jako Node.js jinné jméno.
window.trvala = 10;
})();
docasna; // způsobí ReferenceError
trvala; // = 10
// Jedna z nejvice mocných vlastnosti JavaScriptu je vnitřní funkce. Je to funkce
// definovaná v jinné funkci, vnitřní funkce má přístup ke všem proměnným ve
// vnější funkci, dokonce i poté, co funkce skončí
function ahojPoPetiVterinach(jmeno){
var prompt = "Ahoj, " + jmeno + "!";
// Vnitřní funkce je dána do lokální oblasti platnosti, jako kdyby byla
// deklarovaná slůvkem 'var'
function vnitrni(){
alert(prompt);
}
setTimeout(vnitrni, 5000);
// setTimeout je asynchronní, takže funkce ahojPoPetiVterinach se ukončí
// okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak protože
// vnitrni je definována přes ahojPoPetiVterinach, má pořád přístup k
// proměnné prompt, když je konečně zavolána.
}
ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s
///////////////////////////////////////////////////
// 5. Více o objektech, konstuktorech a prototypech
// Objekty můžou obsahovat funkce
var mujObjekt = {
mojeFunkce: function(){
return "Ahoj světe!";
}
};
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
// Když jsou funkce z objektu zavolány, můžou přistupovat k objektu přes slůvko
// 'this''
var mujObjekt = {
text: "Ahoj světe!",
mojeFunkce: function(){
return this.text;
}
};
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
// Slůvko this je nastaveno k tomu, kde je voláno, ne k tomu, kde je definováno
// Takže naše funkce nebude fungovat, když nebude v kontextu objektu.
var mojeFunkce = mujObjekt.mojeFunkce;
mojeFunkce(); // = undefined
// Opačně, funkce může být přiřazena objektu a může přistupovat k objektu přes
// this, i když nebyla přímo v definici-
var mojeDalsiFunkce = function(){
return this.text.toUpperCase();
}
mujObjekt.mojeDalsiFunkce = mojeDalsiFunkce;
mujObjekt.mojeDalsiFunkce(); // = "AHOJ SVĚTE!"
// Můžeme také specifikovat, v jakém kontextu má být funkce volána pomocí
// `call` nebo `apply`.
var dalsiFunkce = function(s){
return this.text + s;
}
dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Ahoj světe! A ahoj měsíci!"
// Funkce `apply`je velmi podobná, akorát bere jako druhý argument pole argumentů
dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Ahoj světe! A ahoj slunce!"
// To je praktické, když pracujete s funkcí, která bere sekvenci argumentů a
// chcete předat pole.
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN
Math.min.apply(Math, [42, 6, 27]); // = 6
// Ale `call` a `apply` jsou pouze dočasné. Pokud je chcete připojit trvale
// použijte `bind`.
var pripojenaFunkce = dalsiFunkce.bind(mujObjekt);
pripojenaFunkce(" A ahoj Saturne!"); // = "Ahoj světe! A ahoj Saturne!"
// `bind` může být použito čatečně částečně i k používání
var nasobeni = function(a, b){ return a * b; }
var zdvojeni = nasobeni.bind(this, 2);
zdvojeni(8); // = 16
// Když zavoláte funkci se slůvkem 'new', vytvoří se nový objekt a
// a udělá se dostupný funkcím skrz slůvko 'this'. Funkcím volaným takto se říká
// konstruktory
var MujKonstruktor = function(){
this.mojeCislo = 5;
}
mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5}
mujObjekt.mojeCislo; // = 5
// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlasnosti
// objektu, který neexistuje na objektu, tak se JS koukne do prototypu.
// Některé JS implementace vám umožní přistupovat k prototypu přes magickou
// vlastnost '__proto__'. I když je toto užitečné k vysvětlování prototypů, není
// to součást standardu, ke standartní způsobu k používání prototypu se dostaneme
// později.
var mujObjekt = {
mujText: "Ahoj svete!"
};
var mujPrototyp = {
smyslZivota: 42,
mojeFunkce: function(){
return this.mujText.toLowerCase()
}
};
mujObjekt.__proto__ = mujPrototyp;
mujObjekt.smyslZivota; // = 42
// Toto funguje i pro funkce
mujObjekt.mojeFunkce(); // = "Ahoj světe!"
// Samozřejmě, pokud není vlastnost na vašem prototypu, tak se hledá na
// prototypu od prototypu atd.
mujPrototyp.__proto__ = {
mujBoolean: true
};
mujObjekt.mujBoolean; // = true
// Zde neni žádné kopírování; každý objekt ukládá referenci na svůj prototyp
// Toto znamená, že můžeme měnit prototyp a změny se projeví všude
mujPrototyp.smyslZivota = 43;
mujObjekt.smyslZivota // = 43
// Zmínili jsme již předtím, že '__proto__' není ve standardu a není cesta, jak
// měnit prototyp existujícího objektu. Avšak existují možnosti, jak vytvořit
// nový objekt s daným prototypem
// První je Object.create, což je nedávný přídavek do JS a není dostupný zatím
// ve všech implementacích.
var mujObjekt = Object.create(mujPrototyp);
mujObjekt.smyslZivota // = 43
// Druhý způsob, který funguje všude je pomocí konstuktoru. Konstruktor má
// vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale
// prototyp nového objektu.
MujKonstruktor.prototype = {
mojeCislo: 5,
ziskejMojeCislo: function(){
return this.mojeCislo;
}
};
var mujObjekt2 = new MujKonstruktor();
mujObjekt2.ziskejMojeCislo(); // = 5
mujObjekt2.mojeCislo = 6
mujObjekt2.ziskejMojeCislo(); // = 6
// Vestavěnné typy jako čísla nebo řetězce mají také konstruktory, které vytváří
// ekvivalentní obalovací objekty (wrappery).
var mojeCislo = 12;
var mojeCisloObj = new Number(12);
mojeCislo == mojeCisloObj; // = true
// Avšak nejsou úplně přesně stejné
typeof mojeCislo; // = 'number'
typeof mojeCisloObj; // = 'object'
mojeCislo === mojeCisloObj; // = false
if (0){
// Tento kód se nespustí, protože 0 je nepravdivá (false)
}
if (new Number(0)){
// Tento kód se spustí, protože obalená čísla jsou objekty,
// a objekty jsou vždy pravdivé
}
// Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže
// můžete přidat funkcionalitu k řetězci
String.prototype.prvniZnak = function(){
return this.charAt(0);
}
"abc".prvniZnak(); // = "a"
// Tento fakt je často používán v polyfillech, což je implementace novějších
// vlastností JavaScriptu do starších variant, takže je můžete používat třeba
// ve starých prohlížečích
// Pro příkklad, zmínili jsme, že Object.create není dostupný ve všech
// implementacích, můžeme si avšak přidat pomocí polyfillu
if (Object.create === undefined){ // nebudeme ho přepisovat, když existuje
Object.create = function(proto){
// vytvoříme dočasný konstruktor
var Constructor = function(){};
Constructor.prototype = proto;
// ten použijeme k vytvoření nového s prototypem
return new Constructor();
}
}
```
## Kam dál
[Mozilla Developer
Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) obsahuje
perfektní dokumentaci pro JavaScript, který je používaný v prohlížečích. Navíc
je to i wiki, takže jakmile se naučíte více, můžete pomoci ostatním, tím, že
přispějete svými znalostmi.
MDN's [A re-introduction to
JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
pojednává o konceptech vysvětlených zde v mnohem větší hloubce. Tento návod
pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit více, jak se používá
na webových stránkách, začněte tím, že se kouknete na [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto
návodu i s úkoly-
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka
příkladů těch nejvíce nepředvídatelných částí tohoto jazyka.
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/)
je klasická výuková kniha.
Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z
Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS
Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
z Mozilla Developer Network.

62
cs-cz/json.html.markdown Normal file
View File

@@ -0,0 +1,62 @@
---
language: json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
translators:
- ["Vojta Svoboda", "https://github.com/vojtasvoboda/"]
filename: learnjson-cz.json
lang: cs-cz
---
JSON je exterémně jednoduchý datově nezávislý formát a bude asi jeden z
nejjednodušších 'Learn X in Y Minutes' ze všech.
JSON nemá ve své nejzákladnější podobě žádné komentáře, ale většina parserů
umí pracovat s komentáři ve stylu jazyka C (`//`, `/* */`). Pro tyto účely
však budeme používat 100% validní JSON bez komentářů. Pojďme se podívat na
syntaxi formátu JSON:
```json
{
"klic": "value",
"hodnoty": "Musí být vždy uvozený v dvojitých uvozovkách",
"cisla": 0,
"retezce": "Hellø, wørld. Všechny unicode znaky jsou povolené, společně s \"escapováním\".",
"pravdivostni_hodnota": true,
"prazdna_hodnota": null,
"velke_cislo": 1.2e+100,
"objekt": {
"komentar": "Most of your structure will come from objects.",
"pole": [0, 1, 2, 3, "Pole nemusí být pouze homogenní.", 5],
"jiny_objekt": {
"comment": "Je povolené jakkoli hluboké zanoření."
}
},
"cokoli": [
{
"zdroje_drasliku": ["banány"]
},
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, "neo"],
[0, 0, 0, 1]
]
],
"alternativni_styl_zapisu": {
"komentar": "Mrkni se na toto!"
, "pozice_carky": "Na pozici čárky nezáleží - pokud je před hodnotou, ať už je kdekoli, tak je validní."
, "dalsi_komentar": "To je skvělé."
},
"to_bylo_rychle": "A tím jsme hotový. Nyní již víte vše, co může formát JSON nabídnout!"
}
```

View File

@@ -5,7 +5,7 @@ contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators:
- ["Michal Martinek", "https://github.com/MichalMartinek"]
filename: markdown.md
filename: markdown-cz.md
lang: cs-cz
---
@@ -53,7 +53,7 @@ __Stejně jako tento.__
**_Jako tento!_**
*__A tento!__*
<!-- Ve verzi Markdownu od Githubu, máme k dispozici taky prošktrnutí: -->
<!-- Ve verzi Markdownu od GitHubu, máme k dispozici taky prošktrnutí: -->
~~Tento text je prošktrnutý.~~
@@ -152,7 +152,7 @@ Tento box bude zašktrnutý
Jan nevědel, jak se dělá `go_to()` funkce!
<!-- V Markdownu od Githubu , můžete použít speciální syntaxi pro kód -->
<!-- V Markdownu od GitHubu , můžete použít speciální syntaxi pro kód -->
\`\`\`ruby <!-- vyjma zpětných lomítek, jenom ```ruby ! -->
def neco
@@ -160,7 +160,7 @@ def neco
end
\`\`\` <!-- zde taky, žádné zpětná lomítka, pouze ``` -->
<!-- Text výše nepotřebuje odsazení a navíc Github použije zvýraznění označeného
<!-- Text výše nepotřebuje odsazení a navíc GitHub použije zvýraznění označeného
jazyka. -->
<!-- Horizontální čára (<hr />) -->
@@ -232,13 +232,13 @@ Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a j
Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*.
<!-- Klávesové zkratky -->
<!-- V Markdownu od Githubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
<!-- V Markdownu od GitHubu, můžete použít tag <kbd> k reprezentování klaves na počítači -->
Váš počítač přestal pracovat? Zkuste
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
<!-- Tabulky -->
<!-- Tabulky jsou povolené pouze v Markdownu od Githubu a jsou trochu podivně,
<!-- Tabulky jsou povolené pouze v Markdownu od GitHubu a jsou trochu podivně,
ale když je opravdu chcete: -->
| Sloupec1 | Sloupec2 | Sloupec3 |

View File

@@ -7,7 +7,7 @@ contributors:
- ["Tomáš Bedřich", "http://tbedrich.cz"]
translators:
- ["Tomáš Bedřich", "http://tbedrich.cz"]
filename: learnpython3.py
filename: learnpython3-cz.py
lang: cs-cz
---

View File

@@ -8,6 +8,7 @@ contributors:
- ["Wouter Van Schandevijl", "http://github.com/laoujin"]
- ["Jo Pearce", "http://github.com/jdpearce"]
- ["Chris Zimmerman", "https://github.com/chriszimmerman"]
- ["Shawn McGuire", "https://github.com/bigbash"]
filename: LearnCSharp.cs
---
@@ -24,10 +25,12 @@ Multi-line comments look like this
/// This is an XML documentation comment which can be used to generate external
/// documentation or provide context help within an IDE
/// </summary>
//public void MethodOrClassOrOtherWithParsableHelp() {}
/// <param name="firstParam">This is some parameter documentation for firstParam</param>
/// <returns>Information on the returned value of a function</returns>
//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {}
// Specify the namespaces this source code will be using
// The namespaces below are all part of the standard .NET Framework Class Libary
// The namespaces below are all part of the standard .NET Framework Class Library
using System;
using System.Collections.Generic;
using System.Dynamic;
@@ -210,10 +213,10 @@ on a new line! ""Wow!"", the masses cried";
// Incrementations
int i = 0;
Console.WriteLine("\n->Inc/Dec-rementation");
Console.WriteLine(i++); //i = 1. Post-Incrementation
Console.WriteLine(++i); //i = 2. Pre-Incrementation
Console.WriteLine(i--); //i = 1. Post-Decrementation
Console.WriteLine(--i); //i = 0. Pre-Decrementation
Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation
Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation
Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation
Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation
///////////////////////////////////////
// Control Structures
@@ -544,28 +547,22 @@ on a new line! ""Wow!"", the masses cried";
// PARALLEL FRAMEWORK
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
var websites = new string[] {
"http://www.google.com", "http://www.reddit.com",
"http://www.shaunmccarthy.com"
};
var responses = new Dictionary<string, string>();
// Will spin up separate threads for each request, and join on them
// before going to the next step!
Parallel.ForEach(websites,
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
website =>
{
// Do something that takes a long time on the file
using (var r = WebRequest.Create(new Uri(website)).GetResponse())
var words = new List<string> {"dog", "cat", "horse", "pony"};
Parallel.ForEach(words,
new ParallelOptions() { MaxDegreeOfParallelism = 4 },
word =>
{
responses[website] = r.ContentType;
Console.WriteLine(word);
}
});
);
// This won't happen till after all requests have been completed
foreach (var key in responses.Keys)
Console.WriteLine("{0}:{1}", key, responses[key]);
//Running this will produce different outputs
//since each thread finishes at different times.
//Some example outputs are:
//cat dog horse pony
//dog horse pony cat
// DYNAMIC OBJECTS (great for working with other languages)
dynamic student = new ExpandoObject();
@@ -675,6 +672,10 @@ on a new line! ""Wow!"", the masses cried";
// can also use keyword private
public string Name { get; set; }
// Properties also have a special syntax for when you want a readonly property
// that simply returns the result of an expression
public string LongName => Name + " " + _speed + " speed";
// Enum is a value type that consists of a set of named constants
// It is really just mapping a name to a value (an int, unless specified otherwise).
// The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
@@ -692,7 +693,10 @@ on a new line! ""Wow!"", the masses cried";
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
// Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
[Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc
// Any class derived from Attribute can be used to decorate types, methods, parameters etc
// Bitwise operators & and | can be used to perform and/or operations
[Flags]
public enum BikeAccessories
{
None = 0,
@@ -820,7 +824,7 @@ on a new line! ""Wow!"", the masses cried";
}
// Methods can also be static. It can be useful for helper methods
public static bool DidWeCreateEnoughBycles()
public static bool DidWeCreateEnoughBicycles()
{
// Within a static method, we only can reference static class members
return BicyclesCreated > 9000;
@@ -879,8 +883,8 @@ on a new line! ""Wow!"", the masses cried";
bool Broken { get; } // interfaces can contain properties as well as methods & events
}
// Class can inherit only one other class, but can implement any amount of interfaces, however
// the base class name must be the first in the list and all interfaces follow
// Classes can inherit only one other class, but can implement any amount of interfaces,
// however the base class name must be the first in the list and all interfaces follow
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
@@ -942,13 +946,161 @@ on a new line! ""Wow!"", the masses cried";
A.A2();
}
}
// String interpolation by prefixing the string with $
// and wrapping the expression you want to interpolate with { braces }
public class Rectangle
{
public int Length { get; set; }
public int Width { get; set; }
}
class Program
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle { Length = 5, Width = 3 };
Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");
}
}
// New C# 6 features
class GlassBall : IJumpable, IBreakable
{
// Autoproperty initializers
public int Damage { get; private set; } = 0;
// Autoproperty initializers on getter-only properties
public string Name { get; } = "Glass ball";
// Getter-only autoproperty that is initialized in constructor
public string GenieName { get; }
public GlassBall(string genieName = null)
{
GenieName = genieName;
}
public void Jump(int meters)
{
if (meters < 0)
// New nameof() expression; compiler will check that the identifier exists
// nameof(x) == "x"
// Prevents e.g. parameter names changing but not updated in error messages
throw new ArgumentException("Cannot jump negative amount!", nameof(meters));
Damage += meters;
}
// Expression-bodied properties ...
public bool Broken
=> Damage > 100;
// ... and methods
public override string ToString()
// Interpolated string
=> $"{Name}. Damage taken: {Damage}";
public string SummonGenie()
// Null-conditional operators
// x?.y will return null immediately if x is null; y is not evaluated
=> GenieName?.ToUpper();
}
static class MagicService
{
private static bool LogException(Exception ex)
{
/* log exception somewhere */
return false;
}
public static bool CastSpell(string spell)
{
try
{
// Pretend we call API here
throw new MagicServiceException("Spell failed", 42);
// Spell succeeded
return true;
}
// Only catch if Code is 42 i.e. spell failed
catch(MagicServiceException ex) when (ex.Code == 42)
{
// Spell failed
return false;
}
// Other exceptions, or MagicServiceException where Code is not 42
catch(Exception ex) when (LogException(ex))
{
// Execution never reaches this block
// The stack is not unwound
}
return false;
// Note that catching a MagicServiceException and rethrowing if Code
// is not 42 or 117 is different, as then the final catch-all block
// will not catch the rethrown exception
}
}
public class MagicServiceException : Exception
{
public int Code { get; }
public MagicServiceException(string message, int code) : base(message)
{
Code = code;
}
}
public static class PragmaWarning {
// Obsolete attribute
[Obsolete("Use NewMethod instead", false)]
public static void ObsoleteMethod()
{
/* obsolete code */
}
public static void NewMethod()
{
/* new code */
}
public static void Main()
{
ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead'
#pragma warning disable CS0618
ObsoleteMethod(); // no warning
#pragma warning restore CS0618
ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead'
}
}
} // End Namespace
using System;
// C# 6, static using
using static System.Math;
namespace Learning.More.CSharp
{
class StaticUsing
{
static void Main()
{
// Without a static using statement..
Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4));
// With one
Console.WriteLine("The square root of 4 is {}.", Sqrt(4));
}
}
}
```
## Topics Not Covered
* Attributes
* async/await, pragma directives
* async/await
* Web Development
* ASP.NET MVC & WebApi (new)
* ASP.NET Web Forms (old)

View File

@@ -6,17 +6,24 @@ contributors:
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
- ["Brett Taylor", "https://github.com/glutnix"]
- ["Tyler Mumford", "https://tylermumford.com"]
filename: learncss.css
---
Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**.
Web pages are built with HTML, which specifies the content of a page.
CSS (Cascading Style Sheets) is a separate language which specifies
a page's **appearance**.
CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors.
CSS code is made of static *rules*. Each rule takes one or more *selectors* and
gives specific *values* to a number of visual *properties*. Those properties are
then applied to the page elements indicated by the selectors.
This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3.
This guide has been written with CSS 2 in mind, which is extended by the new
features of CSS 3.
**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/).
**NOTE:** Because CSS produces visual results, in order to learn it, you need to
try everything in a CSS playground like [dabblet](http://dabblet.com/).
The main focus of this article is on the syntax and some general tips.
## Syntax
@@ -66,7 +73,7 @@ div { }
[otherAttr~='foo'] { }
[otherAttr~='bar'] { }
/* or contains a value in a dash-separated list, ie, "-" (U+002D) */
/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
@@ -113,7 +120,8 @@ selector:first-child {}
/* any element that is the last child of its parent */
selector:last-child {}
/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
/* Just like pseudo classes, pseudo elements allow you to style certain parts of
a document */
/* matches a virtual first child of the selected element */
selector::before {}
@@ -162,6 +170,13 @@ selector {
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
/* Borders */
border-width:5px;
border-style:solid;
border-color:red; /* similar to how background-color is set */
border: 5px solid red; /* this is a short hand approach for the same */
border-radius:20px; /* this is a CSS3 property */
/* Images as backgrounds of elements */
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
@@ -178,10 +193,10 @@ selector {
Save a CSS stylesheet with the extension `.css`.
```xml
```html
<!-- You need to include the css file in your page's <head>. This is the
recommended method. Refer to http://stackoverflow.com/questions/8284365 -->
<link rel='stylesheet' type='text/css' href='path/to/style.css' />
<link rel='stylesheet' type='text/css' href='path/to/style.css'>
<!-- You can also include some CSS inline in your markup. -->
<style>
@@ -195,7 +210,13 @@ Save a CSS stylesheet with the extension `.css`.
## Precedence or Cascade
An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
An element may be targeted by multiple selectors and may have a property set on
it in more than once. In these cases, one of the rules takes precedence over
others. Rules with a more specific selector take precedence over a less specific
one, and a rule occurring later in the stylesheet overwrites a previous one
(which also means that if two different linked stylesheets contain rules for an
element and if the rules are of the same specificity, then order of linking
would take precedence and the sheet linked latest would govern styling) .
This process is called cascading, hence the name Cascading Style Sheets.
@@ -220,22 +241,71 @@ p { property: value !important; }
and the following markup:
```xml
<p style='/*F*/ property:value;' class='class1 class2' attr='value' />
```html
<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
```
The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block.
The precedence of style is as follows. Remember, the precedence is for each
**property**, not for the entire block.
* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage.
* `E` has the highest precedence because of the keyword `!important`. It is
recommended that you avoid its usage.
* `F` is next, because it is an inline style.
* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`.
* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`.
* `A` is next, because it is more "specific" than anything else. It has 3
specifiers: The name of the element `p`, its class `class1`, an attribute
`attr='value'`.
* `C` is next, even though it has the same specificity as `B`.
This is because it appears after `B`.
* `B` is next.
* `D` is the last one.
## Media Queries
CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specificity.
```css
/* A rule that will be used on all devices */
h1 {
font-size: 2em;
color: white;
background-color: black;
}
/* change the h1 to use less ink on a printer */
@media print {
h1 {
color: black;
background-color: white;
}
}
/* make the font bigger when shown on a screen at least 480px wide */
@media screen and (min-width: 480px) {
h1 {
font-size: 3em;
font-weight: normal;
}
}
```
Media queries can include these features:
`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Most of these features can be prefixed with `min-` or `max-`.
The `resolution` feature is not supported by older devices, instead use `device-pixel-ratio`.
Many smartphones and tablets will attempt to render the page as if it were on a desktop unless you provide a `viewport` meta-tag.
```html
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
</head>
```
## Compatibility
Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature.
Most of the features in CSS 2 (and many in CSS 3) are available across all
browsers and devices. But it's always good practice to check before using
a new feature.
## Resources

249
cypher.html.markdown Normal file
View File

@@ -0,0 +1,249 @@
---
language: cypher
filename: LearnCypher.cql
contributors:
- ["Théo Gauchoux", "https://github.com/TheoGauchoux"]
---
Cypher is the Neo4js query language to manipulate graphs easily. It reuses syntax from SQL and mixes it with kind of ascii-art to represent graphs.
This tutorial assumes that you already know graph concepts like nodes and relationships.
[Read more here.](https://neo4j.com/developer/cypher-query-language/)
Nodes
---
**Represents a record in a graph.**
```()```
It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query.
```(n)```
It's a *node* refered by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase.
```(p:Person)```
You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase.
```(p:Person:Manager)```
A node can have many *labels*.
```(p:Person {name : 'Théo Gauchoux', age : 22})```
A node can have some *properties*, here **name** and **age**. It begins with lowercase and uses camelCase.
The types allowed in properties :
- Numeric
- Boolean
- String
- List of previous primitive types
*Warning : there isn't datetime property in Cypher ! You can use String with a specific pattern or a Numeric from a specific date.*
```p.name```
You can access to a property with the dot style.
Relationships (or Edges)
---
**Connects two nodes**
```[:KNOWS]```
It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE.
```[k:KNOWS]```
The same *relationship*, refered by the variable **k**, reusable in the query, but it's not necessary.
```[k:KNOWS {since:2017}]```
The same *relationship*, with *properties* (like *node*), here **since**.
```[k:KNOWS*..4]```
It's a structural information to use in a *path* (seen later). Here, **\*..4** says "Match the pattern, with the relationship **k** which be repeated between 1 and 4 times.
Paths
---
**The way to mix nodes and relationships.**
```(a:Person)-[:KNOWS]-(b:Person)```
A path describing that **a** and **b** know each other.
```(a:Person)-[:MANAGES]->(b:Person)```
A path can be directed. This path describes that **a** is the manager of **b**.
```(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)```
You can chain multiple relationships. This path describes the friend of a friend.
```(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)```
A chain can also be directed. This path describes that **a** is the boss of **b** and the big boss of **c**.
Patterns often used (from Neo4j doc) :
```
// Friend-of-a-friend
(user)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
// Shortest path
path = shortestPath( (user)-[:KNOWS*..5]-(other) )
// Collaborative filtering
(user)-[:PURCHASED]->(product)<-[:PURCHASED]-()-[:PURCHASED]->(otherProduct)
// Tree navigation
(root)<-[:PARENT*]-(leaf:Category)-[:ITEM]->(data:Product)
```
Create queries
---
Create a new node
```
CREATE (a:Person {name:"Théo Gauchoux"})
RETURN a
```
*`RETURN` allows to have a result after the query. It can be multiple, as `RETURN a, b`.*
Create a new relationship (with 2 new nodes)
```
CREATE (a:Person)-[k:KNOWS]-(b:Person)
RETURN a,k,b
```
Match queries
---
Match all nodes
```
MATCH (n)
RETURN n
```
Match nodes by label
```
MATCH (a:Person)
RETURN a
```
Match nodes by label and property
```
MATCH (a:Person {name:"Théo Gauchoux"})
RETURN a
```
Match nodes according to relationships (undirected)
```
MATCH (a)-[:KNOWS]-(b)
RETURN a,b
```
Match nodes according to relationships (directed)
```
MATCH (a)-[:MANAGES]->(b)
RETURN a,b
```
Match nodes with a `WHERE` clause
```
MATCH (p:Person {name:"Théo Gauchoux"})-[s:LIVES_IN]->(city:City)
WHERE s.since = 2015
RETURN p,state
```
You can use `MATCH WHERE` clause with `CREATE` clause
```
MATCH (a), (b)
WHERE a.name = "Jacquie" AND b.name = "Michel"
CREATE (a)-[:KNOWS]-(b)
```
Update queries
---
Update a specific property of a node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
SET p.age = 23
```
Replace all properties of a node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
SET p = {name: "Michel", age: 23}
```
Add new property to a node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
SET p + = {studies: "IT Engineering"}
```
Add a label to a node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
SET p:Internship
```
Delete queries
---
Delete a specific node (linked relationships must be deleted before)
```
MATCH (p:Person)-[relationship]-()
WHERE p.name = "Théo Gauchoux"
DELETE relationship, p
```
Remove a property in a specific node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
REMOVE p.age
```
*Pay attention to the `REMOVE`keyword, it's not `DELETE` !*
Remove a label from a specific node
```
MATCH (p:Person)
WHERE p.name = "Théo Gauchoux"
DELETE p:Person
```
Delete entire database
```
MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n, r
```
*Seriously, it's the `rm -rf /` of Cypher !*
Other useful clauses
---
```PROFILE```
Before a query, show the execution plan of it.
```COUNT(e)```
Count entities (nodes or relationships) matching **e**.
```LIMIT x```
Limit the result to the x first results.
Special hints
---
- There is just single-line comments in Cypher, with double-slash : // Comments
- You can execute a Cypher script stored in a **.cql** file directly in Neo4j (it's an import). However, you can't have multiple statements in this file (separed by **;**).
- Use the Neo4j shell to write Cypher, it's really awesome.
- The Cypher will be the standard query language for all graph databases (known as **OpenCypher**).

View File

@@ -6,7 +6,7 @@ contributors:
lang: en
---
```c
```d
// You know what's coming...
module hello;
@@ -28,7 +28,7 @@ D is actively developed by a large group of super-smart people and is spearheade
[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu).
With all that out of the way, let's look at some examples!
```c
```d
import std.stdio;
void main() {
@@ -73,7 +73,7 @@ We can define new types with `struct`, `class`, `union`, and `enum`. Structs and
are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore,
we can use templates to parameterize all of these on both types and values!
```c
```d
// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java.
struct LinkedList(T) {
T data = null;
@@ -136,7 +136,7 @@ is roughly a function that may act like an lvalue, so we can
have the syntax of POD structures (`structure.x = 7`) with the semantics of
getter and setter methods (`object.setX(7)`)!
```c
```d
// Consider a class parameterized on types 'T' & 'U'.
class MyClass(T, U) {
T _data;
@@ -209,7 +209,7 @@ functions, and immutable data. In addition, all of your favorite
functional algorithms (map, filter, reduce and friends) can be
found in the wonderful `std.algorithm` module!
```c
```d
import std.algorithm : map, filter, reduce;
import std.range : iota; // builds an end-exclusive range
@@ -237,7 +237,7 @@ is of some type A on any expression of type A as a method.
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
```c
```d
// Let's say we want to populate a large array with the square root of all
// consecutive integers starting from 1 (up until the size of the array), and we
// want to do this concurrently taking advantage of as many cores as we have

View File

@@ -11,7 +11,7 @@ its JavaScript sibling. Like JavaScript, Dart aims for great browser integration
Dart's most controversial feature must be its Optional Typing.
```javascript
```dart
import "dart:collection";
import "dart:math" as DM;

View File

@@ -0,0 +1,125 @@
---
language: asciidoc
contributors:
- ["Ryan Mavilia", "http://unoriginality.rocks/"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
filename: asciidoc-de.md
lang: de-de
---
AsciiDoc ist eine Auszeichnungssprache ähnlich zu Markdown. Sie kann für alles verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart Rackham. Die Sprache ist simpel aber sie ermöglicht eine große Anzahl an Anpassungen.
Kopfzeile des Dokuments
Kopfzeilen sind optional und dürfen keine Leerzeilen besitzen. Sie müssen mindestens eine Leerzeile vom Inhalt versetzt sein.
Nur Titel
```
= Dokumententitel
Erster Satz des Dokuments.
```
Titel und Autor
```
= Dokumententitel
Vorname Nachname <Vorname.Nachname@learnxinyminutes.com>
Start des Dokuments.
```
Mehrere Autoren
```
= Dokumententitel
John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
Starte ein Dokument mit mehreren Autoren.
```
Revisionszeile (benötigt eine Autorzeile)
```
= Dokumententitel V1
Potato Man <chip@crunchy.com>
v1.0, 2016-01-13
Dieser Artikel über Chips wird Spaß machen.
```
Absätze
```
Du musst nichts besonderes machen für Absätze.
Füge eine Leerzeile zwischen zwei Absätze, um sie zu trennen.
Um eine Leerzeile zu erhalten musst du ein +
ergänzen und du erhälst einen Umbruch!
```
Textformatierung
```
_Unterstriche erstellt Kursivschrift_
*Sternchen für Fett gedruckt*
*_Kombinieren für extra Spaß_*
`Benutze Ticks um Monospace zu signalisieren`
`*Fett gedruckter Monospace*`
```
Abteilungstitel
```
= Level 0 (sollte nur in der Kopfzeile verwendet werden)
== Level 1 <h2>
=== Level 2 <h3>
==== Level 3 <h4>
===== Level 4 <h5>
====== Level 5 <h6>
======= Level 6 <h7>
```
Listen
Um eine Aufzählung zu erstellen verwendest du Sternchen.
```
* foo
* bar
* baz
```
Um eine nummerierte Liste zu erstellen verwendest du Punkte.
```
. item 1
. item 2
. item 3
```
Um Listen zu verschachteln musst du zusätzliche Sternchen und Punkte hinzufügen. Dies ist bis zu fünf Mal möglich.
```
* foo 1
** foo 2
*** foo 3
**** foo 4
***** foo 5
. foo 1
.. foo 2
... foo 3
.... foo 4
..... foo 5
```

View File

@@ -92,12 +92,12 @@ echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschl
echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat"
# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern:
if [ $NAME == "Steve" ] && [ $Alter -eq 15 ]
if [ "$NAME" == "Steve" ] && [ "$Alter" -eq 15 ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15."
fi
if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'."
fi
@@ -175,7 +175,7 @@ in
# Liste der Fälle, die unterschieden werden sollen
0) echo "Hier ist eine Null."
1) echo "Hier ist eine Eins."
*) echo "Das ist nicht Null."
*) echo "Das ist etwas anderes."
esac
# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten:

View File

@@ -0,0 +1,89 @@
---
language: brainfuck
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["urfuchs", "https://github.com/urfuchs"]
filename: brainfuck-de
lang: de-de
---
Brainfuck ist eine extrem minimalistische Turing-vollständige Programmiersprache
mit lediglich 8 Befehlen.
Mit dem [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/) kann
Brainfuck im Browser ausprobiert werden.
```
Alle Zeichen außer "><+-.,[]" (ohne die Klammern) werden ignoriert.
Brainfuck besteht aus einem Array mit unendlich vielen Elementen, die alle mit Null initalisiert
sind und einem Datenzeiger auf das aktuelle Element.
Es gibt acht Befehle:
+ : Erhöht den Wert an der aktuellen Stelle um Eins.
- : Verringert den Wert an der aktuellen Stelle um Eins.
> : Bewegt den Zeiger um eine Stelle weiter.
< : Bewegt den Zeiger um eine Stelle zurück.
. : Gibt den Wert der aktuellen Zelle als ASCII Wert aus (z.B. 65 = 'A').
, : Liest ein einzelnes Zeichen von der Standardeingabe und speichert dessen ASCII Wert in der aktuellen Zelle.
[ : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger hinter den
zugehörigen ]-Befehl.
Ansonsten, bewege den Zeiger ein Element weiter.
] : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger um eine Stelle
weiter.
Ansonsten, bewege den Zeiger hinter den zugehörigen [-Befehl.
[ und ] bilden eine while-Schleife. Offensichtlich müssen sie paarweise vorkommen.
Schauen wir uns einige grundlegende Programme an.
++++++ [ > ++++++++++ < - ] > +++++ .
Dieses Programm gibt den Buchstaben 'A' aus. Zunächst erhöht es den Wert der 1. Zelle auf 6.
Diese erste Zelle wird für die Schleife verwendet. Danach beginnt das Programm
die Schleife ([) und geht vor zu Zelle #2. Es erhöht den Zellwert inkrementell 10 Mal, geht dann zurück
zu Zelle #1, und verringert Zelle #1. Diese Schleife wird 6 Mal durchlaufen (nach 6
Durchläufen ist der Wert der Zelle #1 auf 0 reduziert, dadurch wird die Schleife abgebrochen
und das Programm hinter dem korrespondierenden ] fortgesetzt).
An dieser Stelle befinden wir uns an Zelle #1, die jetzt den Wert 0 hat, während Zelle #2
den Wert 60 hat. Wir gehen vor zu Zelle #2, inkrementieren 5 Mal, bis zum Wert 65,
und geben dann den Wert der Zelle #2 aus. 65 ist ein 'A' im ASCII Zeichensatz,
daher wird 'A' am Terminal ausgegeben..
, [ > + < - ] > .
Dieses Programm liest ein Zeichen von der Benutzereingabe und schreibt dessen Wert
in Zelle #1. Danach beginnt eine Schleife. Rücke vor auf Zelle #2, erhöhe den Wert der Zelle #2,
gehe zurück auf Zelle #1, verringere den Wert der Zelle #1. Dies geht solange bis
Zelle #1 den Wert 0 und Zelle #2 den alten Wert aus #1 hat. Da wir am Ende der Schleife
bie Zelle #1 sind, gehe vor zu Zelle #2 und gibt denb Wert als ASCII Zeichen aus.
Beachte biite, dass die Leerzeichen nur aus Gründen der Lesbarkeit geschrieben werden.
Man könnte genauso schreiben:
,[>+<-]>.
Versuche herauszufinden, was dieses Programm macht:
,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
Dieses Programm nimmt zwei Zahlen als Eingabe und multipliziert sie.
Im Wesentlichen liest es zunächst zwei Werte ein. Dann beginnt die äußere Schleife
mit Zelle #1 als Zähler. Danach geht das Programm zu Zelle #2 vor und startet die innere Schleife
mit Zelle #2 als Zähler. Diese zählt Zelle #3 hoch. Es gibt jedoch ein Problem:
Am Ende der inneren Schleife hat Zelle #2 den Wert Null. Daher würde die innere
Schleife beim nächsten Durchgang nicht mehr funktionieren. Daher wird auch Zelle #4
erhöht und anschließend in Zelle #2 zurückkopiert.
Am Ende steht in Zelle #3 das Ergebnis.
```
Das ist Brainfuck. Nicht so schwierig, oder? Zum Spaß kannst du dein eigenes Brainfuck
Programm schreiben oder du schreibst einen Brainfuck Interpreter in einer anderen
Programmiersprache. Der Interpreter lässt sich ziemlich einfach implementieren.
Falls du Masochist bist, kannst du auch versuchen, einen Brainfuck Interpreter in Brainfuck zu implementieren.

View File

@@ -149,10 +149,10 @@ selector {
## Benutzung
Speichere das CSS, das du benutzen willst mit der endung '.css'.
Speichere das CSS, das du benutzen willst, mit der Endung '.css'.
```xml
<!-- du musst die CSS-Datei im <head>-bereich der seite einbinden -->
<!-- du musst die CSS-Datei im <head>-bereich der Seite einbinden -->
<link rel='stylesheet' type='text/css' href='filepath/filename.css' />
<!-- Einbindung funktioniert auch inline, wobei diese Methode nicht
@@ -203,9 +203,9 @@ und das folgende Markup:
Die Spezifität der Stile ist wie folgt:
(die Spezifität gilt nur für **einzelne Eigenschaften**, nicht für ganze Blöcke)
* `E` hat die größte Spezifität wegen dem Schlüsselwort `!important`.
* `E` hat die größte Spezifität wegen des Schlüsselworts `!important`.
man sollte diese Form aber vermeiden.
* `F` ist als nächstes dran, da es direkt an dem element definiert ist.
* `F` ist als nächstes dran, da es direkt an dem Element definiert ist.
* Dann folgt `A`, da es "spezifischer" als alle anderen ist.
spezifischer = mehr Zuweisungen: 1 Tagname `p` +
Klassenname `klasse1` + 1 Attribut `attr='value'`

252
de-de/d-de.html.markdown Normal file
View File

@@ -0,0 +1,252 @@
---
language: D
filename: learnd-de.d
contributors:
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
translators:
- ["Dominik Süß", "www.thesuess.me"]
lang: de-de
---
```c
// Es war klar dass das kommt...
module hello;
import std.stdio;
// argumente sind optional
void main(string[] args) {
writeln("Hello, World!");
}
```
Wenn du so wie ich bist und viel zeit im Internet verbringst stehen die Chancen gut
das du schonmal über [D](http://dlang.org/) gehört hast.
Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von Low bis
High Level verwendet werden kann und dabei viele Stile anbietet.
D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue,
richtig coole leute. Da das jetzt alles aus dem weg ist - auf zu den Beispielen!
```c
import std.stdio;
void main() {
// Logische Ausdrücke und Schleifen funktionieren wie erwartet
for(int i = 0; i < 10000; i++) {
writeln(i);
}
auto n = 1; // auto um den typ vom Compiler bestimmen zu lassen
// Zahlenliterale können _ verwenden für lesbarkeit
while(n < 10_000) {
n += n;
}
do {
n -= (n / 2);
} while(n > 0);
// For und while sind ja schön und gut aber D bevorzugt foreach
// Die '..' erstellen eine Spanne von Zahlen, inklusive dem ersten Wert
// jedoch ohne dem letzten
foreach(i; 1..1_000_000) {
if(n % 2 == 0)
writeln(i);
}
// Es gibt auch ein 'foreach_reverse' wenn du rückwerts gehen willst.
foreach_reverse(i; 1..int.max) {
if(n % 2 == 1) {
writeln(i);
} else {
writeln("No!");
}
}
}
```
Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. Structs und unions
werden as-value (koppiert) an methoden übergeben wogegen Klassen als Referenz übergeben werden.
Templates können verwendet werden um alle typen zu parameterisieren.
```c
// Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++
struct LinkedList(T) {
T data = null;
LinkedList!(T)* next; // Das ! wird verwendet um T zu übergeben. (<T> in C#/Java/C++)
}
class BinTree(T) {
T data = null;
// Wenn es nur einen T parameter gibt können die Klammern um ihn weggelassen werden
BinTree!T left;
BinTree!T right;
}
enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
// Aliase können verwendet werden um die Entwicklung zu erleichtern
alias IntList = LinkedList!int;
alias NumTree = BinTree!double;
// Funktionen können genau so Templates beinhalten
T max(T)(T a, T b) {
if(a < b)
return b;
return a;
}
// Steht ref vor einem Parameter wird sichergestellt das er als Referenz übergeben wird.
// Selbst bei werten wird es immer eine Referenz sein.
void swap(T)(ref T a, ref T b) {
auto temp = a;
a = b;
b = temp;
}
// Templates können ebenso werte parameterisieren.
class Matrix(uint m, uint n, T = int) {
T[m] rows;
T[n] columns;
}
auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom typ Integer
```
Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property
ist eine Funktion die wie ein Wert agiert. Das gibt uns viel klarere Syntax
im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)`
```c
// Diese Klasse ist parameterisiert mit T, U
class MyClass(T, U) {
T _data;
U _other;
}
// Ihre Getter und Setter Methoden sehen so aus
class MyClass(T, U) {
T _data;
U _other;
// Konstruktoren heißen immer `this`
this(T t, U u) {
data = t;
other = u;
}
// getters
@property T data() {
return _data;
}
@property U other() {
return _other;
}
// setters
// @property kann genauso gut am ende der Methodensignatur stehen
void data(T t) @property {
_data = t;
}
void other(U u) @property {
_other = u;
}
}
// Und so kann man sie dann verwenden
void main() {
auto mc = MyClass!(int, string);
mc.data = 7;
mc.other = "seven";
writeln(mc.data);
writeln(mc.other);
}
```
Mit properties können wir sehr viel logik hinter unseren gettern
und settern hinter einer schönen syntax verstecken
Other object-oriented goodies at our disposal
Andere Objektorientierte features sind beispielsweise
`interface`s, `abstract class` und `override`.
Vererbung funktioniert in D wie in Java:
Erben von einer Klasse, so viele interfaces wie man will.
Jetzt haben wir Objektorientierung in D gesehen aber schauen
wir uns noch was anderes an.
D bietet funktionale programmierung mit _first-class functions_
puren funktionen und unveränderbare daten.
Zusätzlich können viele funktionale Algorithmen wie z.B
map, filter, reduce und friends im `std.algorithm` Modul gefunden werden!
```c
import std.algorithm : map, filter, reduce;
import std.range : iota; // builds an end-exclusive range
void main() {
// Wir wollen die summe aller quadratzahlen zwischen
// 1 und 100 ausgeben. Nichts leichter als das!
// Einfach eine lambda funktion als template parameter übergeben
// Es ist genau so gut möglich eine normale funktion hier zu übergeben
// Lambdas bieten sich hier aber an.
auto num = iota(1, 101).filter!(x => x % 2 == 0)
.map!(y => y ^^ 2)
.reduce!((a, b) => a + b);
writeln(num);
}
```
Ist dir aufgefallen wie wir eine Haskell-Style pipeline gebaut haben
um num zu berechnen?
Das war möglich durch die Uniform Function Call Syntax.
Mit UFCS können wir auswählen ob wir eine Funktion als Methode oder
als freie Funktion aufrufen. Walters artikel dazu findet ihr
[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
Kurzgesagt kann man Funktionen deren erster parameter vom typ A ist, als
Methode auf A anwenden.
Parrallel Computing ist eine Tolle sache, findest du nicht auch?
```c
import std.stdio;
import std.parallelism : parallel;
import std.math : sqrt;
void main() {
// Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen
// und dabei alle Kerne verwenden die wir zur verfügung haben
auto arr = new double[1_000_000];
// Wir verwenden den index und das element als referenz
// und rufen einfach parallel auf!
foreach(i, ref elem; parallel(arr)) {
ref = sqrt(i + 1.0);
}
}
```

View File

@@ -33,6 +33,7 @@ Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichn
* Ist offline einsetzbar.
* Einfache Kollaboration!
* Branching ist einfach!
* Branching ist schnell!
* Merging ist einfach!
* Git ist schnell.
* Git ist flexibel.
@@ -53,11 +54,11 @@ Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und meh
### Arbeitsverzeichnis (Teil des Repositorys)
Dies sind die Verzeichnisse und Dateien in deinem Repository.
Dies sind die Verzeichnisse und Dateien in deinem Repository, also z.B. dein Programmcode.
### Index (Teil des .git-Verzeichnisses)
Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht.
Der Index ist die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arbeitsverzeichnis vom Repository trennt. Sie gibt Entwicklern mehr Einfluss darüber, was ins Git-Repository eingeht.
### Commit
@@ -84,7 +85,7 @@ Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Reposito
### init
Erstelle ein leeres Git-Repository. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt.
Erstelle ein leeres Git-Repository im aktuellen Verzeichnis. Die Einstellungen, gespeicherte Informationen und mehr zu diesem Git-Repository werden in einem Verzeichnis namens *.git* angelegt.
```bash
$ git init
@@ -180,6 +181,8 @@ Bringt alle Dateien im Arbeitsverzeichnis auf den Stand des Index oder des angeg
```bash
# Ein Repo auschecken - wenn nicht anders angegeben ist das der master
$ git checkout
# Eine Datei auschecken - sie befindet sich dann auf dem aktuellen Stand im Repository
$ git checkout /path/to/file
# Einen bestimmten Branch auschecken
$ git checkout branchName
# Erstelle einen neuen Branch und wechsle zu ihm. Wie: "git branch <name>; git checkout <name>"
@@ -217,6 +220,9 @@ $ git diff --cached
# Unterschiede zwischen deinem Arbeitsverzeichnis und dem aktuellsten Commit anzeigen
$ git diff HEAD
# Unterschiede zwischen dem Index und dem aktuellsten Commit (betrifft nur Dateien im Index)
$ git diff --staged
```
### grep
@@ -374,3 +380,5 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
* [GitGuys](http://www.gitguys.com/)
* [gitflow - Ein Modell um mit Branches zu arbeiten](http://nvie.com/posts/a-successful-git-branching-model/)

View File

@@ -4,13 +4,14 @@ filename: learngo-de.go
contributors:
- ["Joseph Adams", "https://github.com/jcla1"]
- ["Dennis Keller", "https://github.com/denniskeller"]
translators:
- ["Jerome Meinke", "https://github.com/jmeinke"]
lang: de-de
---
Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007
benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele
Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und
benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente
Vorteile. Einerseits verzichtet Go auf Speicherarithmetik und
benutzt einen Garbage Collector. Andererseits enthält Go native Sprachelemente
für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen
Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten
erleichtert.

322
de-de/hack-de.html.markdown Normal file
View File

@@ -0,0 +1,322 @@
---
language: Hack
lang: de-de
contributors:
- ["Stephen Holdaway", "https://github.com/stecman"]
- ["David Lima", "https://github.com/davelima"]
translators:
- ["Jerome Meinke", "https://github.com/jmeinke"]
filename: learnhack-de.hh
---
Hack ist eine von Facebook neu entwickelte Programmiersprache auf Basis von PHP.
Sie wird von der HipHop Virtual Machine (HHVM) ausgeführt. Die HHVM kann
aufgrund der Ähnlichkeit der Programmiersprachen nicht nur Hack, sondern auch
PHP-Code ausführen. Der wesentliche Unterschied zu PHP besteht in der statischen
Typisierung der Sprache, die eine wesentlich höhere Performance erlaubt.
Hier werden nur Hack-spezifische Eigenschaften beschrieben. Details über PHP's
Syntax findet man im [PHP Artikel](http://learnxinyminutes.com/docs/php/) dieser
Seite.
```php
<?hh
// Hack-Syntax ist nur für Dateien aktiv, die mit dem <?hh Prefix starten.
// Der <?hh Prefix kann nicht wie <?php mit HTML gemischt werden.
// Benutzung von "<?hh //strict" aktiviert den Strikt-Modus des Type-Checkers.
// Typisierung für Funktions-Argumente
function repeat(string $word, int $count)
{
$word = trim($word);
return str_repeat($word . ' ', $count);
}
// Typisierung für Rückgabewerte
function add(...$numbers) : int
{
return array_sum($numbers);
}
// Funktionen ohne Rückgabewert, werden mit "void" typisiert
function truncate(resource $handle) : void
{
// ...
}
// Typisierung unterstützt die explizit optionale Ein- / Ausgabe von "null"
function identity(?string $stringOrNull) : ?string
{
return $stringOrNull;
}
// Typisierung von Klassen-Eigenschaften
class TypeHintedProperties
{
public ?string $name;
protected int $id;
private float $score = 100.0;
// Hack erfordert es, dass typisierte Eigenschaften (also "non-null")
// einen Default-Wert haben oder im Konstruktor initialisiert werden.
public function __construct(int $id)
{
$this->id = $id;
}
}
// Kurzgefasste anonyme Funktionen (lambdas)
$multiplier = 5;
array_map($y ==> $y * $multiplier, [1, 2, 3]);
// Weitere, spezielle Felder (Generics)
// Diese kann man sich als ein zugreifbares Interface vorstellen
class Box<T>
{
protected T $data;
public function __construct(T $data) {
$this->data = $data;
}
public function getData(): T {
return $this->data;
}
}
function openBox(Box<int> $box) : int
{
return $box->getData();
}
// Formen
//
// Hack fügt das Konzept von Formen hinzu, wie struct-ähnliche arrays
// mit einer typ-geprüften Menge von Schlüsseln
type Point2D = shape('x' => int, 'y' => int);
function distance(Point2D $a, Point2D $b) : float
{
return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
}
distance(
shape('x' => -1, 'y' => 5),
shape('x' => 2, 'y' => 50)
);
// Typen-Definition bzw. Aliasing
//
// Hack erlaubt es Typen zu definieren und sorgt somit für bessere Lesbarkeit
newtype VectorArray = array<int, Vector<int>>;
// Ein Tupel mit zwei Integern
newtype Point = (int, int);
function addPoints(Point $p1, Point $p2) : Point
{
return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
}
addPoints(
tuple(1, 2),
tuple(5, 6)
);
// Erstklassige Aufzählungen (enums)
enum RoadType : int
{
Road = 0;
Street = 1;
Avenue = 2;
Boulevard = 3;
}
function getRoadType() : RoadType
{
return RoadType::Avenue;
}
// Automatische Erstellung von Klassen-Eigenschaften durch Konstruktor-Argumente
//
// Wiederkehrende Definitionen von Klassen-Eigenschaften können durch die Hack-
// Syntax vermieden werden. Hack erlaubt es die Klassen-Eigenschaften über
// Argumente des Konstruktors zu definieren.
class ArgumentPromotion
{
public function __construct(public string $name,
protected int $age,
private bool $isAwesome) {}
}
class WithoutArgumentPromotion
{
public string $name;
protected int $age;
private bool $isAwesome;
public function __construct(string $name, int $age, bool $isAwesome)
{
$this->name = $name;
$this->age = $age;
$this->isAwesome = $isAwesome;
}
}
// Kooperatives Multitasking
//
// Die Schlüsselworte "async" and "await" führen Multitasking ein.
// Achtung, hier werden keine Threads benutzt, sondern nur Aktivität getauscht.
async function cooperativePrint(int $start, int $end) : Awaitable<void>
{
for ($i = $start; $i <= $end; $i++) {
echo "$i ";
// Geben anderen Tasks die Möglichkeit aktiv zu werden
await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
}
}
// Die Ausgabe von folgendem Code ist "1 4 7 2 5 8 3 6 9"
AwaitAllWaitHandle::fromArray([
cooperativePrint(1, 3),
cooperativePrint(4, 6),
cooperativePrint(7, 9)
])->getWaitHandle()->join();
// Attribute
//
// Attribute repräsentieren eine Form von Metadaten für Funktionen.
// Hack bietet Spezial-Attribute, die nützliche Eigenschaften mit sich bringen.
// Das __Memoize Attribut erlaubt es die Ausgabe einer Funktion zu cachen.
<<__Memoize>>
function doExpensiveTask() : ?string
{
return file_get_contents('http://example.com');
}
// Der Funktionsrumpf wird im Folgenden nur ein einziges mal ausgeführt:
doExpensiveTask();
doExpensiveTask();
// Das __ConsistentConstruct Attribut signalisiert dem type-checker, dass
// die Funktionsdeklaration von __construct für alle Unterklassen dieselbe ist.
<<__ConsistentConstruct>>
class ConsistentFoo
{
public function __construct(int $x, float $y)
{
// ...
}
public function someMethod()
{
// ...
}
}
class ConsistentBar extends ConsistentFoo
{
public function __construct(int $x, float $y)
{
// Der Type-checker erzwingt den Aufruf des Eltern-Klassen-Konstruktors
parent::__construct($x, $y);
// ...
}
// Das __Override Attribut ist ein optionales Signal an den Type-Checker,
// das erzwingt, dass die annotierte Methode die Methode der Eltern-Klasse
// oder des Traits verändert.
<<__Override>>
public function someMethod()
{
// ...
}
}
class InvalidFooSubclass extends ConsistentFoo
{
// Wenn der Konstruktor der Eltern-Klasse nicht übernommen wird,
// wird der Type-Checker einen Fehler ausgeben:
//
// "This object is of type ConsistentBaz. It is incompatible with this object
// of type ConsistentFoo because some of their methods are incompatible"
//
public function __construct(float $x)
{
// ...
}
// Auch bei der Benutzung des __Override Attributs für eine nicht veränderte
// Methode wird vom Type-Checker eine Fehler ausgegeben:
//
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
// parent definition found or overridden parent is defined in non-<?hh code"
//
<<__Override>>
public function otherMethod()
{
// ...
}
}
// Ein Trait ist ein Begriff aus der objektorientierten Programmierung und
// beschreibt eine wiederverwendbare Sammlung von Methoden und Attributen,
// ähnlich einer Klasse.
// Anders als in PHP können Traits auch als Schnittstellen (Interfaces)
// implementiert werden und selbst Schnittstellen implementieren.
interface KittenInterface
{
public function play() : void;
}
trait CatTrait implements KittenInterface
{
public function play() : void
{
// ...
}
}
class Samuel
{
use CatTrait;
}
$cat = new Samuel();
$cat instanceof KittenInterface === true; // True
```
## Weitere Informationen
Die Hack [Programmiersprachen-Referenz](http://docs.hhvm.com/manual/de/hacklangref.php)
erklärt die neuen Eigenschaften der Sprache detailliert auf Englisch. Für
allgemeine Informationen kann man auch die offizielle Webseite [hacklang.org](http://hacklang.org/)
besuchen.
Die offizielle Webseite [hhvm.com](http://hhvm.com/) bietet Infos zum Download
und zur Installation der HHVM.
Hack's [nicht-untersützte PHP Syntax-Elemente](http://docs.hhvm.com/manual/en/hack.unsupported.php)
werden im offiziellen Handbuch beschrieben.

156
de-de/haml-de.html.markdown Normal file
View File

@@ -0,0 +1,156 @@
---
language: haml
filename: learnhaml-de.haml
contributors:
- ["Simon Neveu", "https://github.com/sneveu"]
- ["Sol Bekic", "https://github.com/S0lll0s"]
lang: de-de
---
Haml ist eine Markup- und Templatingsprache, aufgesetzt auf Ruby, mit der HTML Dokumente einfach beschrieben werden können.
Haml vermindert Wiederholung und Fehleranfälligkeit, indem es Tags basierend auf der Markup-Struktur schließt und schachtelt.
Dadurch ergibt sich kurzes, präzises und logisches Markup.
Haml kann außerhalb eines Ruby-projekts verwendet werden. Mit dem installierten Haml gem kann man das Terminal benutzen um Haml zu HTML umzuwandeln:
$ haml input_file.haml output_file.html
```haml
/ -------------------------------------------
/ Einrückung
/ -------------------------------------------
/
Einrückung ist ein wichtiges Element des Haml Syntax, deswegen ist es
wichtig ein konsequentes Schema zu verwenden. Meistens werden zwei spaces
verwendet, solange die Einrückungen das gleiche Schema verfolgen können
aber auch andere Breiten und Tabs verwendet werden
/ -------------------------------------------
/ Kommentare
/ -------------------------------------------
/ Kommentare beginnen mit einem Slash
/
Mehrzeilige Kommentare werden eingerückt und mit einem Slash
eingeführt
-# Diese Zeile ist ein "stummes" Kommentar, es wird nicht mitgerendert
/ -------------------------------------------
/ HTML Elemente
/ -------------------------------------------
/ Tags werden durch ein Prozentzeichen und den Tagnamen erzeugt
%body
%header
%nav
/ Die Zeilen oben würden folgendes ergeben:
<body>
<header>
<nav></nav>
</header>
</body>
/ Text kann direkt nach dem Tagnamen eingefügt werden:
%h1 Headline copy
/ Mehrzeilige Inhalte müssen stattdessen eingerückt werden:
%p
This is a lot of content that we could probably split onto two
separate lines.
/
HTML kann mit &= escaped werden. So werden HTML-sensitive Zeichen
enkodiert. Zum Beispiel:
%p
&= "Ja & Nein"
/ würde 'Ja &amp; Nein' ergeben
/ HTML kann mit != dekodiert werden:
%p
!= "so schreibt man ein Paragraph-Tag: <p></p>"
/ ...was 'This is how you write a paragraph tag <p></p>' ergeben würde
/ CSS Klassen können mit '.classname' an Tags angehängt werden:
%div.foo.bar
/ oder über einen Ruby Hash:
%div{:class => 'foo bar'}
/ Das div Tag wird standardmäßig verwendet, divs können also verkürzt werden:
.foo
/ andere Attribute können über den Hash angegeben werden:
%a{:href => '#', :class => 'bar', :title => 'Bar'}
/ Booleesche Attribute können mit 'true' gesetzt werden:
%input{:selected => true}
/ data-Attribute können in einem eigenen Hash im :data key angegeben werden:
%div{:data => {:attribute => 'foo'}}
/ -------------------------------------------
/ Verwendung von Ruby
/ -------------------------------------------
/ Mit dem = Zeichen können Ruby-werte evaluiert und als Tag-text verwendet werden:
%h1= book.name
%p
= book.author
= book.publisher
/ Code nach einem Bindestrich wird ausgeführt aber nicht gerendert:
- books = ['book 1', 'book 2', 'book 3']
/ So können zum Beispiel auch Blöcke verwendet werden:
- books.shuffle.each_with_index do |book, index|
%h1= book
if book do
%p This is a book
/
Auch hier werden wieder keine End-Tags benötigt!
Diese ergeben sich aus der Einrückung.
/ -------------------------------------------
/ Inline Ruby / Ruby Interpolation
/ -------------------------------------------
/ Ruby variablen können mit #{} in Text interpoliert werden:
%p dein bestes Spiel ist #{best_game}
/ -------------------------------------------
/ Filter
/ -------------------------------------------
/
Mit dem Doppelpinkt können Haml Filter benutzt werden.
Zum Beispiel gibt es den :javascript Filter, mit dem inline JS
geschrieben werden kann:
:javascript
console.log('Dies ist ein <script>');
```
## Weitere Resourcen
- [What is HAML?](http://haml.info/) - Eine gute Einleitung auf der Haml homepage (englisch)
- [Official Docs](http://haml.info/docs/yardoc/file.REFERENCE.html) - Die offizielle Haml Referenz (englisch)

View File

@@ -100,7 +100,7 @@ not False -- True
[1..] !! 999 -- 1000
-- Haskell evaluiert nun die ersten 1 - 1000 Elemente, aber der Rest der Liste
-- bleibt unangetastet. Haskell wird sie solange nicht weiterevalieren
-- bleibt unangetastet. Haskell wird sie solange nicht weiterevaluieren
-- bis es muss.
-- Zwei Listen konkatenieren
@@ -115,7 +115,7 @@ tail [1..5] -- [2, 3, 4, 5]
init [1..5] -- [1, 2, 3, 4]
last [1..5] -- 5
-- list comprehensions | Listen erschaffen
-- Listen erschaffen ("list comprehensions")
[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
-- Mit Bedingungen
@@ -179,7 +179,7 @@ myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
-- Fold (`inject` in einigen Sprachen)
-- Foldl1 bedeutet: fold von links nach rechts und nehme den ersten
-- Wert der Liste als Basiswert f[r den Akkumulator.
-- Wert der Liste als Basiswert für den Akkumulator.
foldl1 (\acc x -> acc + x) [1..5] -- 15
----------------------------------------------------
@@ -201,7 +201,7 @@ foo 5 -- 15
-- Funktionskomposition
-- Die (.) Funktion verkettet Funktionen.
-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
-- Zum Beispiel, die Funktion Foo nimmt ein Argument, addiert 10 dazu und
-- multipliziert dieses Ergebnis mit 4.
foo = (*4) . (+10)
@@ -212,7 +212,7 @@ foo 5 -- 60
-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt.
-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist
-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator
-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt,
-- rechtsassoziativ und hat die Priorität 0. Dieses hat (i.d.R.) den Effekt,
-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die
-- Funktion auf der linken Seite verwendet wird.
-- Mit `.` und `$` kann man sich so viele Klammern ersparen.
@@ -283,7 +283,7 @@ for [0..5] $ \i -> show i
for [0..5] show
-- foldl oder foldr reduziren Listen auf einen Wert.
-- foldl <fn> <initial value> <list>
-- foldl <Funktion> <initialer Wert> <Liste>
foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
-- die Abarbeitung sieht so aus:
@@ -435,7 +435,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
```
Haskell ist sehr einfach zu installieren.
Hohl es dir von [hier](http://www.haskell.org/platform/).
Hol es dir von [hier](http://www.haskell.org/platform/).
Eine sehr viele langsamere Einführung findest du unter:
[Learn you a Haskell](http://learnyouahaskell.com/) oder

120
de-de/html-de.html.markdown Normal file
View File

@@ -0,0 +1,120 @@
---
language: html
contributors:
- ["Christophe THOMAS", "https://github.com/WinChris"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
filename: learnhtml-de.html
lang: de-de
---
HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache).
Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben..
Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien.
Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags.
Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt.
Wie viele andere Computersprachen auch, besitzt HTML viele Versionen. Wir werden hier über HTML5 reden.
**NOTE :** Du kannst die unterschiedlichen Tags und Elemente, während des Tutorials auf Seiten, wie [codepen](http://codepen.io/pen/) testen, um deren Effekte zu sehen und wie diese funktionieren. Auch kannst du dich damit besser mit der Sprache vertraut machen.
Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben.
```html
<!-- Kommentare werden wie in dieser Zeile geschrieben -->
<!-- #################### Die Tags #################### -->
<!-- Hier ist eine Beispiel HTML Datei, die wir analysieren werden -->
<!doctype html>
<html>
<head>
<title>Meine Website</title>
</head>
<body>
<h1>Hallo Welt!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">Komm schau was das hier anzeigt</a>
<p>Das ist ein Paragraf.</p>
<p>Das ist ein weiterer Paragraf.</p>
<ul>
<li>Das ist eine Item mit einer nicht-nummerierten Liste (Aufzählungsliste)</li>
<li>Das ist ein weiteres Item</li>
<li>Und das ist das letzte Item in der Liste</li>
</ul>
</body>
</html>
<!-- Jede HTML Datei startet damit dem Browser zu sagen, dass die Seite aus HTML besteht. -->
<!doctype html>
<!-- Danach startet sie mit einem Öffnungtag <html>. -->
<html>
<!-- Dieser wird am Ende der Datei mit</html> geschlossen. -->
</html>
<!-- Nichts sollte nach diesen finalen Tag erscheinen. -->
<!-- Dazwischen (Zwischen dem Öffnungs- und Schließungstag <html></html>) finden wir: -->
<!-- Ein Kopf wird definiert mit <head> (er muss mit </head> geschlossen werden). -->
<!-- Der Header beinhaltet Beschreibungen und zusätzliche Informationen, welche nicht dargestellt werden. Das sind Metadaten. -->
<head>
<title>Meine Seite</title><!-- Der <title> kennzeichnet dem Browser den Titel im Browserfenster und im Tabnamen anzuzeigen. -->
</head>
<!-- Nach dem <head> Bereich findet sich der <body> Tag -->
<!-- Bis zu diesen Punkt wird nichts im Browerfenster angezeigt. -->
<!-- Wir müssen den Body mit dem Inhalt füllen der angezeigt werden soll. -->
<body>
<h1>Hallo, Welt!</h1> <!-- Der h1 Tag erstellt einen Titel. -->
<!-- Es gibt auch Untertitel für <h1> von den wichtigsten <h2> zu den Unwichtigsten (h6). -->
<a href = "http://codepen.io/anon/pen/xwjLbZ">Komm, schaue was das zeigt</a> <!-- Eine URL wird zum Hyperlink, wenn es das Attribut href="" -->
<p>Das ist ein Absatz.</p> <!-- Der Tag <p> lässt uns Text auf die HTML Seite hinzufügen. -->
<p>Das ist ein anderer Absatz.</p>
<ul> <!-- Der <ul> Tag erstellt eine Aufzählungsliste. -->
<!-- Für eine nummerierte Liste sollten wir stattdessen <ol> verwenden. Das erste Element bekommt 1., das zweite 2. usw. -->
<li>Das ist ein Element in einer nicht Aufzählungsliste</li>
<li>Das ist ein anderes Item</li>
<li>Und das ist das letzte Element in der List</li>
</ul>
</body>
<!-- Und das war es. Eine HTML Datei kann so simpel sein. -->
<!-- Aber es ist möglich viele weitere zusätzliche HTML tags hinzuzufügen. -->
<!-- Um ein Bild hinzuzufügen. -->
<img src="http://i.imgur.com/XWG0O.gif"/> <!-- Die Quelle des Bildes wird gezeigt durch das Attribut src="" -->
<!-- Die Quelle kann eine URL sein oder ein Pfad zu deinem Computer. -->
<!-- Es ist ebenso möglich eine Tabelle zu erstellen. -->
<table> <!-- Wir öffnen ein <table> Element. -->
<tr> <!-- <tr> erlaubt es uns Reihe zu erstellen. -->
<th>Erster Tabellenkopf</th> <!-- <th> erlaubt es uns der Tabelle einen Titel zu geben. -->
<th>Zweiter Tabllenkopf</th>
</tr>
<tr>
<td>Erste Zeile, erste Spalte</td> <!-- <td> erlaubt es eine Tabellenzelle zu erstellen. -->
<td>Erste Zeile, zweite Spalte</td>
</tr>
<tr>
<td>Zweite Zeile, erste Spalte</td>
<td>Zweite Zeile, zweite Spalte</td>
</tr>
</table>
```
## Verwendung
HTML Dateien enden mit `.html`.
## Um mehr zu lernen
* [wikipedia (EN)](https://en.wikipedia.org/wiki/HTML)
* [HTML tutorial (EN)](https://developer.mozilla.org/en-US/docs/Web/HTML)
* [W3School (EN)](http://www.w3schools.com/html/html_intro.asp)

497
de-de/java-de.html.markdown Normal file
View File

@@ -0,0 +1,497 @@
---
language: java
filename: LearnJavaDe.java
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Jakukyo Friel", "http://weakish.github.io"]
- ["Madison Dickson", "http://github.com/mix3d"]
- ["Simon Morgan", "http://sjm.io/"]
translators:
- ["Michael Dähnert", "http://github.com/JaXt0r"]
lang: de-de
---
Java ist eine Programmiersprache für vielfältige Aufgaben. Sie ist imperative und objektorientiert.
Oftmals wird sie für Desktop- Webapplikationen sowie als Programmiersprache im Betriebssystem Android verwendet.
[Weitere Informationen \(Englisch\)](http://docs.oracle.com/javase/tutorial/java/)
```java
// Einzeilige Kommentare starten mit //
/*
Mehrzeilige Kommentare sehen so aus.
*/
/**
JavaDoc Kommentare haben dieses Format. Sie werden verwendet um Klassen, Attribute sowie Methoden zu beschreiben.
*/
// Importieren der Klasse ArrayList aus dem Paket java.util
import java.util.ArrayList;
// Importieren aller Klassen innerhalb des Paketes java.security
import java.security.*;
// Jede .java Datei besteht aus einer äußeren öffentlichen (public) Klasse.
// Der Name der Klasse muss identisch des Dateinamens sein.
public class LearnJavaDe {
// Ein Programm muss eine main Methode als Eintrittspunkt besitzen.
public static void main (String[] args) {
// System.out.println() wird zum Schreiben von zeilenweisen Ausgaben verwendet.
System.out.println("Hello World!");
System.out.println(
"Integer: " + 10 +
" Double: " + 3.14 +
" Boolean: " + true);
// Zum Schreiben von Ausgaben ohne Zeilenumbruch wird System.out.print() verwendet.
System.out.print("Hello ");
System.out.print("World");
///////////////////////////////////////
// Typen & Variablen
///////////////////////////////////////
// Zum Deklarieren einer Variable nutze <type> <name>
// Byte - 8-bit vorzeichenbehaftete (signed), binäre Ganzzahl
// (-128 <= byte <= 127)
byte fooByte = 100;
// Short - 16-bit vorzeichenbehaftete (signed), binäre Ganzzahl
// (-32,768 <= short <= 32,767)
short fooShort = 10000;
// Integer - 32-bit vorzeichenbehaftete (signed), binäre Ganzzahl
// (-2,147,483,648 <= int <= 2,147,483,647)
int fooInt = 1;
// Long - 64-bit vorzeichenbehaftete (signed), binäre Ganzzahl
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
long fooLong = 100000L;
// L wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ long ist.
// Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt.
// Hinweis: Java besitzt keine vorzeichenlosen (unsigned) Typen.
// Float - Typ mit einfacher Genauigkeit (Single-precision), 32-bit IEEE 754 Fließkommazahl
float fooFloat = 234.5f;
// f wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ float ist;
// Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt.
// Double - Typ mit doppelter Genauigkeit (Double-precision), 64-bit IEEE 754 Fließkommazahl
double fooDouble = 123.4;
// Boolean - Wahr & Falsch (true & false)
boolean fooBoolean = true;
boolean barBoolean = false;
// Char - Ein einfacher 16-bit Unicode Buchstabe
char fooChar = 'A';
// final Variablen können von einem anderen Objekt nicht erneut zugeordnet werden.
final int HOURS_I_WORK_PER_WEEK = 9001;
// Zeichenketten (Strings)
String fooString = "My String Is Here!";
// \n ist ein Escape Zeichen welcher eine neue Zeile startet.
String barString = "Schreiben auf einer neuen Zeile?\nKein Problem!";
// \t ist ein Escape Zeichen welcher einen Tab-Zeichen anhängt.
String bazString = "Möchtest du einen Tabulator anhängen?\tKein Problem!";
System.out.println(fooString);
System.out.println(barString);
System.out.println(bazString);
// Arrays
// Die Arraygröße muss bei Instanziierung entschieden werden.
// Das folgende Format funktioniert bei Deklaration eines Arrays
// <datentyp>[] <variablenname> = new <datentyp>[<arraygröße>];
// <datentyp> <variablenname>[] = new <datentyp>[<arraygröße>];
int[] intArray = new int[10];
String[] stringArray = new String[1];
boolean boolArray[] = new boolean[100];
// Eine weitere Möglichkeit ein Array zu deklarieren & initialisieren.
int[] y = {9000, 1000, 1337};
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
boolean bools[] = new boolean[] {true, false, false};
// Indexierung eines Arrays - Zugriff auf ein Element
System.out.println("intArray @ 0: " + intArray[0]);
// Arrays sind 0-indexiert und veränderbar.
intArray[1] = 1;
System.out.println("intArray @ 1: " + intArray[1]); // => 1
// Weitere nennenswerte Typen
// ArrayLists - Ähnlich Arrays, allerdings werden mehr Funktionen geboten,
// ebenso ist die Arraygröße verwänderbar
// LinkedLists - Implementierung einer doppelt verlinkten Liste.
// Alle Operationen funktioneren so, wie es von einer doppelt verlinkten Liste erwartet wird.
// Weitere Informationen: https://de.wikipedia.org/wiki/Liste_(Datenstruktur)#Doppelt_.28mehrfach.29_verkettete_Liste
// Maps - Eine Sammlung von Objekten, welche eine Verknüpfung von Schlüsseln zu Werten (key => value) vornimmt.
// Eine Map kann keine Duplikate enthalten; Jeder Schlüssel kann genau einen Wert beinhalten.
// HashMaps - Diese Klasse nutzt eine Hashtabelle zur Implementierung eines Map Interfaces.
// Dies erlaubt es zur Laufzeit Standardoperationen wie gib (get) und einfügen (insert)
// selbst für große Mengen in einer konstanten Zeit auszuführen (Laufzeitverhalten O(n)).
///////////////////////////////////////
// Operatoren
///////////////////////////////////////
System.out.println("\n->Operatoren");
int i1 = 1, i2 = 2; // Kurform zur Deklaration mehrerer Variablen.
// Arithmetische Operationen sind einfach nutzbar.
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 Nachkommazahl abgeschnitten)
// Modulo
System.out.println("11%3 = "+(11 % 3)); // => 2
// Vergleichsoperationen
System.out.println("3 == 2? " + (3 == 2)); // => false
System.out.println("3 != 2? " + (3 != 2)); // => true
System.out.println("3 > 2? " + (3 > 2)); // => true
System.out.println("3 < 2? " + (3 < 2)); // => false
System.out.println("2 <= 2? " + (2 <= 2)); // => true
System.out.println("2 >= 2? " + (2 >= 2)); // => true
// Bitwise Operatoren!
/*
~ Unäres (unary) bitweise Komplement
<< Vorzeichenbehaftete (signed) linke Verschiebung
>> Vorzeichenbehaftete (signed) rechte Verschiebung
>>> Vorzeichenlose (unsigned) linke Verschiebung
& Bitweise UND (AND)
^ Bitweise exklusive ODER (OR)
| Bitweise inklusive ODER (OR)
*/
// Inkrementierungen
int i = 0;
System.out.println("\n->Inc/Dec-rementierung");
// Die ++ und -- operatoren inkrementieren und dekrementieren jeweils um 1.
// Werden sie vor die Variable gesetzt, ink-/dekrementieren sie und geben anschließend ihren Wert zurück.
// Hinter der Variable geben sie ihren Wert zurück und ändern ihn anschließend.
System.out.println(i++); // i = 1, schreibt 0 (post-increment)
System.out.println(++i); // i = 2, schreibt 2 (pre-increment)
System.out.println(i--); // i = 1, schreibt 2 (post-decrement)
System.out.println(--i); // i = 0, schreibt 0 (pre-decrement)
///////////////////////////////////////
// Kontrollstrukturen
///////////////////////////////////////
System.out.println("\n->Kontrollstrukturen");
// If Bedingungen sind wie in den C-Sprachen aufgebaut
int j = 10;
if (j == 10){
System.out.println("Ich wurde geprinted");
} else if (j > 10) {
System.out.println("Ich nicht");
} else {
System.out.println("Ich auch nicht");
}
// While Schleife
int fooWhile = 0;
while(fooWhile < 100) {
System.out.println(fooWhile);
// Den Zähler inkrementieren
// 100x iterieren, fooWhile 0,1,2...99
fooWhile++;
}
System.out.println("fooWhile Wert: " + fooWhile);
// Do While Schleife
int fooDoWhile = 0;
do {
System.out.println(fooDoWhile);
// Den Zähler inkrementieren
// 99x iterieren, fooDoWhile 0->99
fooDoWhile++;
} while(fooDoWhile < 100);
System.out.println("fooDoWhile Wert: " + fooDoWhile);
// For Schleife
int fooFor;
// for Schleifenstruktur => for(<start_statement>; <Bedingung>; <Schritt>)
for (fooFor = 0; fooFor < 10; fooFor++) {
System.out.println(fooFor);
// 10x iterieren, fooFor 0->9
}
System.out.println("fooFor Wert: " + fooFor);
// For Each Schleife
// The for Schleife kann verwendet werden um über Arrays ebenso wie Objekte,
// welche das Interface Iterable implementieren zu iterieren.
int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// for each Schleifenstruktur => for (<Objekt> : <iterable>)
// Wird gelesen als: Iteriere für jedes Element im Iterable
// Hinweis: Der Objekttyp muss dem Elementtyp des Iterable entsprechen.
for (int bar : fooList) {
System.out.println(bar);
//9x iterieren und die Werte 1-9 auf jeweils einer neuen Zeile schreiben
}
// Switch Case
// A Schalter (switch) funktioniert mit den Datentypen byte, short, char und int.
// Ebenso kann er für Aufzählungen (Enums) verwendet werden (Enum Typen folgen weiter unten)
// der String Klasse (ab Java SE7) und ein paar spezielle Klassen, welche die primitiven Typen ummanteln (wrap):
// Character, Byte, Short, and Integer.
int monat = 3;
String monatsString;
switch (monat) {
case 1: monatsString = "Januar";
break;
case 2: monatsString = "Februar";
break;
case 3: monatsString = "März";
break;
default: monatsString = "Ein anderer Monat";
break;
}
System.out.println("Switch Case Ergebnis: " + monatsString);
// Bedingungsoperator (Conditional Shorthand)
// Der Operator '?' kann für schnelle Zuweisungen oder logische Verzweigungen genutzt werden.
// Er ist wie folgt zu lesen: Wenn die Bedingung wahr ist, nutze <erster Wert>
// ansonsten nutze <zweiter Wert>
int foo = 5;
String bar = (foo < 10) ? "A" : "B";
System.out.println(bar); // Schreibt A, denn die Bedingung ist wahr.
////////////////////////////////////////
// Typkonvertierung und Type-Casting
////////////////////////////////////////
// Konvertierung von Daten
// Konvertiere String nach Integer
Integer.parseInt("123");// Gibt die Integer Repräsentation von "123" zurück
// Konvertiere String nach Integer
Integer.toString(123);// Gibt die String Repräsentation von 123 zurück
// Für andere Konvertierungen sind die folgenden Klassen zu betrachten:
// Double
// Long
// String
// Tpe-Casting
// Java Objekte können benfalls konvertiert werden, hierbei gibt es vielfältige Konzepte.
// Weitere Informationen finden sich hier (englisch):
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
///////////////////////////////////////
// Klassen und Funktionen
///////////////////////////////////////
System.out.println("\n->Klassen & Funktionen");
// (Die Definition der Klasse Fahrrad folgt)
// Verwendung einer neuen Klasseninstanz
Fahrrad trek = new Fahrrad();
// Aufruf von Methoden des Objektes
trek.erhöheGeschwindigkeit(3); // Es sollten immer getter- und setter- Methoden verwendet werden
trek.setTrittfrequenz(100);
// toString gibt die StringRepräsentation des Objektes zurück.
System.out.println("trek info: " + trek.toString());
} // Ende der Main Methode
} // Ende der LearnJavaDe Klasse
// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äüßere Klassen vorhanden sein.
// Syntax der Klassendeklaration:
// <public/private/protected> class <Klassenname> {
// // Es folgen Datenfelder, Konstruktoren, Funktionen.
// // Funktionen werden in Java Methoden genannt.
// }
class Fahrrad {
// Felder/Variablen der Klasse Fahrrad
public int trittfrequenz; // Public: Kann von überall her angesprochen werden
private int geschwindigkeit; // Private: Nur innerhalb der Klasse sichtbar
protected int gang; // Protected: Erreichbar innerhalb der Klasse oder Subklassen (sub classes)
String name; // default: Nur innerhalb des Paketes verwendbar
// Eine Klasse kann mittelst Konstruktoren erstellt werden.
// Das ist ein Konstruktor
public Fahrrad() {
gang = 1;
trittfrequenz = 50;
geschwindigkeit = 5;
name = "Bontrager";
}
// Das ist ein Konstruktor mit Argumenten
public Bicycle(int initialTrittfrequenz, int initialGeschwindigkeit, int initialGang,
String name) {
this.gang = initialGang;
this.trittfrequenz = initialTrittfrequenz;
this.geschwindigkeit = initialGeschwindigkeit;
this.name = name;
}
// Syntax von Methoden (Funktionen):
// <public/private/protected> <Rückgabetyp> <Funktionsname>(<Argumente>)
// Java Klassen implementieren oftmals getter- und setter-Methoden ihrer Felder
// Syntax von Methodendeklarationen:
// <Sichtbarkeit> <Rückgabetyp> <Methodenname>(<Argumente>)
public int getTrittfrequenz() {
return tri;
}
// void Methoden benötigen kein return Statement.
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void erhöheGeschwindigkeit(int increment) {
speed += increment;
}
public void verringereGeschwindigkeit(int decrement) {
speed -= decrement;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
//Methode zur Darstellung der Attributwerte des Objektes.
@Override
public String toString() {
return "Gang: " + gang + " Trittfrequenz: " + trittfrequenz + " Geschwindigkeit: " + geschwindigkeit +
" name: " + name;
}
} // Ende der Klasse Fahrrad
// Hochrad ist eine Subklasse von Fahrrad
class Hochrad extends Fahrrad {
// (Hochräder sind Fahrräder mit einem extrem großen Vorderrad.
// Sie haben keine Gänge.)
public Hochrad(int initialTrittfrequenz, int initialGeschwindigkeit){
// Aufruf des Vater-Konstruktors (parent constructor) mit dem Wort super.
super(initialTrittfrequenz, initialGeschwindigkeit, 0, "Hochrad");
}
// Überschriebene Methoden sollten die Annotation @Override besitzen.
// Mehr zu Annotationen und deren Verwendungszwecken kann hier nachgelesen werden:
// (englisch) http://docs.oracle.com/javase/tutorial/java/annotations/
@Override
public void setGang(int gang) {
gang = 0;
}
}
// Schnittstellen (Interfaces)
// Interface Deklaration
// <Zugriffsrecht> interface <Name> extends <super-Interface> {
// // Konstanten
// // Methodendeklarationen
// }
// Beispiel - Nahrung:
public interface Essbar {
public void essen(); // Jede Klasse, die dieses Interface implementiert
// muss auch diese Methode implementieren.
}
public interface Verdaulich {
public void verdauen();
}
// Nun können wir eine Klasse erstellen, die beide Interfaces implementiert.
public class Frucht implements Essbar, Verdaulich {
@Override
public void essen() {
// ...
}
@Override
public void verdauen() {
// ...
}
}
// Mit Java kann man nur eine Klasse erweitern (extends) jedoch mehrere Interfaces implementieren.
// z.B.:
public class BeispielKlasse extends ParentBeispielKlasse implements InterfaceEins,
InterfaceZwei {
@Override
public void methodeInterfaceEins() {
}
@Override
public void methodeInterfaceZwei() {
}
}
```
## Weitere Informationen (in englisch)
Die folgenden Links dienen lediglich dazu Verständnis für die Kapitel aufzubauen.
Für tiefergreifende Fragen ist Google der beste Startpunkt.
**Offizielle Oracle Guides**:
* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
* [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
* [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
* [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
**Online Tutorials**
* [Learneroo.com - Learn Java](http://www.learneroo.com)
* [Codingbat.com](http://codingbat.com/java)
**Bücher**:
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
* [Thinking in Java](http://www.mindview.net/Books/TIJ/)
* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)

426
de-de/lua-de.html.markdown Normal file
View File

@@ -0,0 +1,426 @@
---
language: Lua
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
translators:
- ["Martin Schimandl", "https://github.com/Git-Jiro"]
filename: learnlua-de.lua
lang: de-de
---
```lua
-- Zwei Gedankenstriche starten ein einzeiliges Kommentar.
--[[
Fügt man zwei '[' und ']' hinzu,
erzeugt man einen mehrzeiligen Kommentar.
--]]
--------------------------------------------------------------------------------
-- 1. Variablen und Fluß-Kontrolle.
--------------------------------------------------------------------------------
num = 42 -- Alle Nummern sind vom Typ: Double.
-- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten
-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als
-- 52 Bit.
s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python.
t = "Doppelte Anführungszeichen sind auch OK"
u = [[ Doppelte eckige Klammern
beginnen und beenden
mehrzeilige Zeichenketten.]]
t = nil -- Undefineren von t; Lua hat einen Garbage Collection.
-- Blöcke werden durch Schlüsselwörter wie do/end markiert:
while num < 50 do
num = num + 1 -- Es gibt Keine Operatoren wie ++ oder +=
end
-- If Bedingungen:
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then -- ~= bedeutet ungleich
-- Gleichheits-Check == wie bei Python; OK für Zeichenketten.
io.write('not over 40\n') -- Standard ist stdout.
else
-- Variablen sind standardmäßig global.
thisIsGlobal = 5 -- Camel case ist üblich.
-- So macht man eine Variable lokal:
local line = io.read() -- Lies die nächste Zeile von stdin.
-- Zeichenketten zusammenführen mit dem .. Operator:
print('Winter is coming, ' .. line)
end
-- Undefinierte Variablen geben nil zurück.
-- Das ist kein Fehler:
foo = anUnknownVariable -- Nun ist foo = nil.
aBoolValue = false
-- Nur nil und false sind unwahr; 0 and '' sind wahr!
if not aBoolValue then print('was false') end
-- 'or' und 'and' sind "kurz-geschlossen". Das ist so ähnlich wie der a?b:c
-- operator in C/js:
-- in C/js:
ans = aBoolValue and 'yes' or 'no' --> 'no'
karlSum = 0
for i = 1, 100 do -- Ein Bereich inkludiert beide Enden.
karlSum = karlSum + i
end
-- Verwende "100, 1, -1" als Breich für Countdowns:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end
-- Im Allgemeinen besteht ein Bereich aus: Anfang, Ende, [, Schrittweite].
-- Ein anderes Schleifen-Konstrukt:
repeat
print('Der Weg der Zukunft')
num = num - 1
until num == 0
--------------------------------------------------------------------------------
-- 2. Funktionen.
--------------------------------------------------------------------------------
function fib(n)
if n < 2 then return n end
return fib(n - 2) + fib(n - 1)
end
-- Closures und anonyme Funktionen sind ok:
function adder(x)
-- Die zurückgegebene Funktion wird erzeugt wenn addr aufgerufen wird und merkt
-- sich den Wert von x:
return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16)) --> 25
print(a2(64)) --> 100
-- Rückgabewerte, Funktions-Aufrufe und Zuweisungen funktionieren alle mit
-- Listen die nicht immer gleich lang sein müssen. Überzählige Empfänger
-- bekommen nil; überzählige Sender werden ignoriert.
x, y, z = 1, 2, 3, 4
-- Nun ist x = 1, y = 2, z = 3, und 4 wird ignoriert.
function bar(a, b, c)
print(a, b, c)
return 4, 8, 15, 16, 23, 42
end
x, y = bar('zaphod') --> prints "zaphod nil nil"
-- Nun ist x = 4, y = 8, die Werte 15..42 werden ignoriert.
-- Funktionen sind erste Klasse, und können lokal oder global sein.
-- Das ist alles das Gleiche:
function f(x) return x * x end
f = function (x) return x * x end
-- Das auch:
local function g(x) return math.sin(x) end
local g = function(x) return math.sin(x) end
-- Äquivalent zu local function g(x)..., außer das Referenzen auf g im
-- Funktions-Körper nicht wie erwartet funktionieren.
local g; g = function (x) return math.sin(x) end
-- Die Deklaration 'local g' macht Selbst-Referenzen auf g OK.
-- Nebenbei gesagt, Trigonometrie-Funktionen verwenden Radianten.
-- Funktionsaufrufe mit nur einem Zeichenketten-Parameter brauch keine runden
-- Klammern.
print 'hello' -- Funktioniert wunderbar.
-- Funktionsaufrufe mit einem Tabellen-Parameter brauchen auch keine runden
-- Klammern. Mehr zu Tabellen kommt später.
print {} -- Funktioniert auch wunderbar.
--------------------------------------------------------------------------------
-- 3. Tabellen.
--------------------------------------------------------------------------------
-- Tabellen sind die einzige zusammengesetzte Struktur in Lua. Sie sind
-- assoziative Arrays. Sie sind so ähnlich wie PHP arrays oder JavaScript
-- Objekte. Sie sind Hash-Lookup-Dictionaries die auch als Listen verwendet
-- werden können.
-- Verwenden von Tabellen als Dictionaries oder Maps:
-- Dict-Literale haben standardmäßig Zeichenketten als Schlüssel:
t = {key1 = 'value1', key2 = false}
-- Zeichenketten-Schlüssel verwenden eine JavaScript ähnliche Punkt-Notation.
print(t.key1) -- Ausgabe 'value1'.
t.newKey = {} -- Neues Schlüssel/Wert-Paar hinzufügen.
t.key2 = nil -- key2 aus der Tabelle entfernen.
-- Literale notation für jeden (nicht-nil) Wert als Schlüssel:
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28]) -- Ausgabe "tau"
-- Schlüssel-Vergleiche funktionieren per Wert für Nummern und Zeichenketten,
-- aber über die Identität bei Tabellen.
a = u['@!#'] -- Nun ist a = 'qbert'.
b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil:
-- b = nil weil der Lookup fehlschlägt. Er schlägt Fehl, weil der Schlüssel
-- den wir verwendet haben nicht das gleiche Objekt ist das wir verwendet
-- haben um den original Wert zu speichern. Zahlen und Zeichnkette sind daher
-- die praktischeren Schlüssel.
-- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern.
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- Ausgabe 'Sonmi~451'.
for key, val in pairs(u) do -- Tabellen-Iteration.
print(key, val)
end
-- _G ist eine spezielle Tabelle die alles Globale enthält.
print(_G['_G'] == _G) -- Ausgabe 'true'.
-- Verwenden von Tabellen als Listen/Arrays:
-- Listen-Literale verwenden implizit Ganzzahlen als Schlüssel:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do -- #v ist die Größe von v für Listen.
print(v[i]) -- Indices beginnen mit 1 !! SO VERRÜCKT!
end
-- Eine 'Liste' ist kein echter Typ. v ist nur eine Tabelle mit fortlaufenden
-- Ganzzahlen als Schlüssel, die behandelt wird wie eine Liste.
--------------------------------------------------------------------------------
-- 3.1 Metatabellen und Metamethoden
--------------------------------------------------------------------------------
-- Eine Tabelle kann eine Metatabelle haben. Diese verleiht ihr so etwas wie
-- Tabellen-Operator-Überladungs-Verhalten. Später sehen wir wie
-- Metatabellen js-prototypen artiges Verhalten unterstützen.
f1 = {a = 1, b = 2} -- Repräsentiert den Bruch a/b.
f2 = {a = 2, b = 3}
-- Dies würde Fehlschlagen:
-- s = f1 + f2
metafraction = {}
function metafraction.__add(f1, f2)
local sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
end
setmetatable(f1, metafraction)
setmetatable(f2, metafraction)
s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf.
-- f1 und f2 haben keine Schlüssel für ihre Metatabellen, anders als bei js
-- Prototypen. Daher muss mithilfe von getmetatable(f1) darauf zugegriffen
-- werden. Eine Metatabelle ist wie eine normale Tabelle mit Schlüsseln die
-- Lua bekannt sind, so wie __add.
-- Die nächste Zeile schlägt fehl weil s keine Metatabelle hat:
-- t = s + s
-- Mihilfe von Klassen ähnlichen Mustern kann das gelöst werden.
-- Siehe weiter unten.
-- Ein __index einer Metatabelle überlädt Punkt-Lookups:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- Funktioniert dank Metatabelle!
--------------------------------------------------------------------------------
-- Direkte Tabellen-Lookups die fehlschlagen werden mithilfe von __index der
-- Metatabelle wiederholt. Das geschieht rekursiv.
-- __index kann auch eine Funktion mit der Form function(tbl, key) sein.
-- Damit kann man Lookups weiter anpassen.
-- Werte wie __index,add, .. werden Metamethoden genannt.
-- HIer eine vollständige Liste aller Metamethoden.
-- __add(a, b) für a + b
-- __sub(a, b) für a - b
-- __mul(a, b) für a * b
-- __div(a, b) für a / b
-- __mod(a, b) für a % b
-- __pow(a, b) für a ^ b
-- __unm(a) für -a
-- __concat(a, b) für a .. b
-- __len(a) für #a
-- __eq(a, b) für a == b
-- __lt(a, b) für a < b
-- __le(a, b) für a <= b
-- __index(a, b) <fn or a table> für a.b
-- __newindex(a, b, c) für a.b = c
-- __call(a, ...) für a(...)
--------------------------------------------------------------------------------
-- 3.2 Klassen-Artige Tabellen und Vererbung.
--------------------------------------------------------------------------------
-- Klassen sind in Lua nicht eingebaut. Es gibt verschieden Wege sie mithilfe
-- von Tabellen und Metatabellen zu erzeugen.
-- Die Erklärund des Beispiels erfolgt unterhalb.
Dog = {} -- 1.
function Dog:new() -- 2.
local newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end
function Dog:makeSound() -- 6.
print('I say ' .. self.sound)
end
mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8.
-- 1. Dog verhält sich wie eine Klasse; Ist aber eine Tabelle.
-- 2. "function tablename:fn(...)" ist das gleiche wie
-- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens
-- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt.
-- 3. newObj wird eine Instanz von Dog.
-- 4. "self" ist die zu Instanzierende Klasse. Meistern ist self = Dog, aber
-- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen
-- von self wenn wir die Metatabelle von newObj und __index von self auf
-- self setzen.
-- 5. Zur Erinnerung: setmetatable gibt sein erstes Argument zurück.
-- 6. Der Doppelpunkt funktioniert wie bei 2, aber dieses Mal erwarten wir das
-- self eine Instanz ist und keine Klasse.
-- 7. Das Selbe wie Dog.new(Dog), also self = Dog in new().
-- 8. Das Selbe wie mrDog.makeSound(mrDog); self = mrDog.
--------------------------------------------------------------------------------
-- Vererbungs-Beispiel:
LoudDog = Dog:new() -- 1.
function LoudDog:makeSound()
local s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end
seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4.
--------------------------------------------------------------------------------
-- 1. LoudDog bekommt die Methoden und Variablen von Dog.
-- 2. self hat einen 'sound' Schlüssel von new(), siehe 3.
-- 3. Das Gleiche wie "LoudDog.new(LoudDog)", und umgewandelt zu "Dog.new(LoudDog)"
-- denn LoudDog hat keinen 'new' Schlüssel, aber "__index = Dog" steht in der
-- Metatabelle.
-- Ergebnis: Die Metatabelle von seymour ist LoudDog und "LoudDog.__index = Dog".
-- Daher ist seymour.key gleich seymour.key, LoudDog.key, Dog.key, je nachdem
-- welche Tabelle als erstes einen passenden Schlüssel hat.
-- 4. Der 'makeSound' Schlüssel wird in LoudDog gefunden: Das ist das Gleiche
-- wie "LoudDog.makeSound(seymour)".
-- Wenn nötig, sieht new() einer Sub-Klasse genau so aus wie new() der
-- Basis-Klasse:
function LoudDog:new()
local newObj = {}
-- set up newObj
self.__index = self
return setmetatable(newObj, self)
end
--------------------------------------------------------------------------------
-- 4. Module.
--------------------------------------------------------------------------------
--[[ Dieser Abschnitt ist auskommentiert damit der Rest des Skripts lauffähig
-- bleibt.
```
```lua
-- Angenommen mod.lua sieht so aus:
local M = {}
local function sayMyName()
print('Hrunkner')
end
function M.sayHello()
print('Why hello there')
sayMyName()
end
return M
-- Eine andere Datei könnte die Funktionen in mod.lua so verwenden:
local mod = require('mod') -- Führe mod.lua aus.
-- require ist der Standard-Weg um Module zu inkludieren.
-- require verhält sich wie: (Wenn nicht gecached wird; siehe später)
local mod = (function ()
<Inhalt von mod.lua>
end)()
-- Es ist als ob mod.lua eine Funktion wäre, sodass lokale Variablen in
-- mod.lua ausserhalb unsichtbar sind.
-- Das funktioniert weil mod hier das Gleiche wie M in mod.lua ist:
mod.sayHello() -- Says hello to Hrunkner.
-- Das ist Falsch: sayMyName existiert nur in mod.lua:
mod.sayMyName() -- Fehler
-- Der Rückgabe-Wert von require wird zwischengespeichert. Sodass Module nur
-- einmal abgearbeitet werden, auch wenn sie mit require öfters eingebunden
-- werden.
-- Nehmen wir an mod2.lua enthält "print('Hi!')".
local a = require('mod2') -- Ausgabe Hi!
local b = require('mod2') -- Keine Ausgabe; a=b.
-- dofile ist wie require aber ohne Zwischenspeichern.
dofile('mod2') --> Hi!
dofile('mod2') --> Hi! (läuft nochmal, nicht wie require)
-- loadfile ladet eine lua Datei aber die Datei wird noch nicht abgearbeitet.
f = loadfile('mod2') -- Sobald f() aufgerufen wird läuft mod2.lua.
-- loadstring ist loadfile für Zeichenketten
g = loadstring('print(343)') -- Gibt eine Funktion zurück..
g() -- Ausgabe 343; Vorher kam keine Ausgabe.
--]]
```
## Referenzen
Ich war so begeistert Lua zu lernen, damit ich Spiele mit <a href="http://love2d.org/">Love 2D game engine</a> programmieren konnte.
Ich habe angefangen mit <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
Danach habe ich das offizielle Lua Buch gelesen: <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a>
Es kann auch hilfreich sein hier vorbeizuschauen: <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short
reference</a>
Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken:
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a>
* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table library</a>
* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math library</a>
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und
starte sie als "lua learn.lua" !
Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: <a href="https://gist.github.com/tylerneylon/5853042">github gist</a>. Viel Spaß mit Lua!

260
de-de/make-de.html.markdown Normal file
View File

@@ -0,0 +1,260 @@
---
language: make
contributors:
- ["Robert Steed", "https://github.com/robochat"]
translators:
- ["Martin Schimandl", "https://github.com/Git-Jiro"]
filename: Makefile-de
lang: de-de
---
Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele)
zu erzeugen. Es dient dazu die geringste Menge an Arbeit zu verrichten um
ein Ziel in einklang mit dem Quellcode zu bringen. Make wurde berühmterweise
von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer
sehr verbreitet (vorallem im Unix umfeld) obwohl es bereits sehr viel
Konkurrenz und Kritik zu Make gibt.
Es gibt eine vielzahl an Varianten von Make, dieser Artikel beschäftig sich
mit der Version GNU Make. Diese Version ist standard auf Linux.
```make
# Kommentare können so geschrieben werden.
# Dateien sollten Makefile heißen, denn dann können sie als `make <ziel>`
# aufgerufen werden. Ansonsten muss `make -f "dateiname" <ziel>` verwendet
# werden.
# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet
# werden. Niemals Leerzeichen!
#-----------------------------------------------------------------------
# Grundlagen
#-----------------------------------------------------------------------
# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt
# nicht existiert.
file0.txt:
echo "foo" > file0.txt
# Selbst Kommentare in der 'Rezept' Sektion werden an die Shell
# weitergegeben. Versuche `make file0.txt` oder einfach `make`
# die erste Regel ist die Standard-Regel.
# Diese Regel wird nur abgearbeitet wenn file0.txt aktueller als file1.txt ist.
file1.txt: file0.txt
cat file0.txt > file1.txt
# Verwende die selben Quoting-Regeln wie die Shell
@cat file0.txt >> file1.txt
# @ unterdrückt die Ausgabe des Befehls an stdout.
-@echo 'hello'
# - bedeutet das Make die Abarbeitung fortsetzt auch wenn Fehler passieren.
# Versuche `make file1.txt` auf der Kommandozeile.
# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben.
file2.txt file3.txt: file0.txt file1.txt
touch file2.txt
touch file3.txt
# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt.
# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
# Voraussetzungen hinzuzufügen.
#-----------------------------------------------------------------------
# Phony-Ziele
#-----------------------------------------------------------------------
# Ein Phony-Ziel ist ein Ziel das keine Datei ist.
# Es wird nie aktuell sein, daher wird Make immer versuchen es abzuarbeiten
all: maker process
# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren.
maker:
touch ex0.txt ex1.txt
# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den
# selben namen wie ein Phony-Ziel hat:
.PHONY: all maker process
# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon.
# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet
ex0.txt ex1.txt: maker
# Häufige Phony-Ziele sind: all make clean install ...
#-----------------------------------------------------------------------
# Automatische Variablen & Wildcards
#-----------------------------------------------------------------------
process: file*.txt # Eine Wildcard um Dateinamen zu Vergleichen
@echo $^ # $^ ist eine Variable die eine Liste aller
# Voraussetzungen enthält.
@echo $@ # Namen des Ziels ausgeben.
#(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung
#der Regel.)
@echo $< # Die erste Voraussetzung aus der Liste
@echo $? # Nur die Voraussetzungen die nicht aktuell sind.
@echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich)
#@echo $| # Alle 'order only' Voraussetzungen
# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden.
process: ex1.txt file0.txt
# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert.
#-----------------------------------------------------------------------
# Muster
#-----------------------------------------------------------------------
# Mit Mustern kann man make beibringen wie Dateien in andere Dateien
# umgewandelt werden.
%.png: %.svg
inkscape --export-png $^
# Muster-Vergleichs-Regeln werden nur abgearbeitet wenn make entscheidet das Ziel zu
# erzeugen
# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert.
# Aber make wird versuchen die am besten passende Regel zu verwenden.
small/%.png: %.svg
inkscape --export-png --export-dpi 30 $^
# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden die es
# findet.
%.png: %.svg
@echo this rule is chosen
# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden die das
# Ziel erzeugen kann.
%.png: %.ps
@echo this rule is not chosen if *.svg and *.ps are both present
# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel
# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt.
# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt
# Muster-Vergleichs-Regeln.
.png.ps:
@echo this rule is similar to a pattern rule.
# Aktivieren der Suffix-Regel
.SUFFIXES: .png
#-----------------------------------------------------------------------
# Variablen
#-----------------------------------------------------------------------
# auch Makros genannt.
# Variablen sind im Grunde genommen Zeichenketten-Typen.
name = Ted
name2="Sarah"
echo:
@echo $(name)
@echo ${name2}
@echo $name # Das funktioniert nicht, wird als $(n)ame behandelt.
@echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt.
# Es git 4 Stellen um Variablen zu setzen.
# In Reihenfolge der Priorität von höchster zu niedrigster:
# 1: Befehls-Zeilen Argumente
# 2: Makefile
# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch.
# 3: MAke hat einige vordefinierte Variablen.
name4 ?= Jean
# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch
# nicht gibt.
override name5 = David
# Verhindert das Kommando-Zeilen Argumente diese Variable ändern können.
name4 +=grey
# Werte an eine Variable anhängen (inkludiert Leerzeichen).
# Muster-Spezifische Variablen Werte (GNU Erweiterung).
echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
# rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören
# kann wenn es zu kompilizert wird!)
# Ein paar Variablen die von Make automatisch definiert werden.
echo_inbuilt:
echo $(CC)
echo ${CXX)}
echo $(FC)
echo ${CFLAGS)}
echo $(CPPFLAGS)
echo ${CXXFLAGS}
echo $(LDFLAGS)
echo ${LDLIBS}
#-----------------------------------------------------------------------
# Variablen 2
#-----------------------------------------------------------------------
# Der erste Typ von Variablen wird bei jeder verwendung ausgewertet.
# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen.
# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung)
var := hello
var2 ::= $(var) hello
#:= und ::= sind äquivalent.
# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie
# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache!
# Das funktioniert nicht
var3 ::= $(var4) and good luck
var4 ::= good night
#-----------------------------------------------------------------------
# Funktionen
#-----------------------------------------------------------------------
# Make verfügt über eine vielzahl von Funktionen.
sourcefiles = $(wildcard *.c */*.c)
objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
# Das Format ist $(func arg0,arg1,arg2...)
# Ein paar Beispiele
ls: * src/*
@echo $(filter %.txt, $^)
@echo $(notdir $^)
@echo $(join $(dir $^),$(notdir $^))
#-----------------------------------------------------------------------
# Direktiven
#-----------------------------------------------------------------------
# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code
include foo.mk
sport = tennis
# Konditionale kompiliereung
report:
ifeq ($(sport),tennis)
@echo 'game, set, match'
else
@echo "They think it's all over; it is now"
endif
# Es gibt auch ifneq, ifdef, ifndef
foo = true
ifdef $(foo)
bar = 'hello'
endif
```
### Mehr Resourcen
+ [gnu make documentation](https://www.gnu.org/software/make/manual/)
+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)

View File

@@ -56,7 +56,7 @@ __Genau wie dieser.__
**_Dieser auch!_**
*__Und dieser genau so!__*
<!-- In "Github Flavored Markdown", dem von Github verwendeten Dialekt / Parser,
<!-- In "GitHub Flavored Markdown", dem von GitHub verwendeten Dialekt / Parser,
gibt es auch noch durchgestrichenen Text: -->
~~Dieser Text wird durchgestrichen dargestellt.~~
@@ -148,7 +148,7 @@ indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst -->
Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte!
<!-- In "Github Flavored Markdown" gibt es für Code nocheinmal eine
<!-- In "GitHub Flavored Markdown" gibt es für Code nocheinmal eine
besondere Syntax -->
\`\`\`ruby <!-- in "echt" musst du die Backslashes entfernen: ```ruby ! -->
@@ -157,7 +157,7 @@ def foobar
end
\`\`\` <!-- hier auch keine Backslashes, nur ``` -->
<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt Github
<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt GitHub
Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu -->
<!-- Horizontale Linie (<hr />) -->
@@ -233,7 +233,7 @@ Ich würde *diesen Teil gerne mit Sternen umschließen*, doch ohne dass er kursi
wird. Also mache ich folgendes: \*Ich umschließe diesen Text mit Sternen\*!
<!-- Tabellen -->
<!-- Tabellen gibt es bis jetzt nur in "Github Flavored Markdown".
<!-- Tabellen gibt es bis jetzt nur in "GitHub Flavored Markdown".
Zudem sind sie ziemlich mühselig, aber wenn du es wirklich wissen willst: -->
| Spalte1 | Spalte2 | Spalte3 |
@@ -253,4 +253,4 @@ Ganz schön hässlich | vielleicht doch lieber | wieder aufhören
Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax)
und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
Infos zu Github Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).
Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).

169
de-de/perl-de.html.markdown Normal file
View File

@@ -0,0 +1,169 @@
---
language: perl
filename: learnperl-de.pl
contributors:
- ["Korjavin Ivan", "http://github.com/korjavin"]
translators:
- ["Martin Schimandl", "http://github.com/Git-Jiro"]
lang: de-de
---
Perl 5 ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl 5 ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
```perl
# Einzeilige Kommentare beginnen mit dem # Symbol.
#### Perl Variablen Typen
# Variablen beginnen mit einem Sigil, das ist ein Symbol das den Typ anzeigt.
# Ein erlaubter Variablen-Name beginnt mit einem Buchstaben oder einem
# Unterstrich, gefolgt von beliebig vielen weiteren Buchstaben, Zahlen und
# Unterstrichen.
### Perl hat drei Haupt-Typen von Variablen: $scalar, @array, und %hash.
## Scalare
# Ein Scalar repräsentiert einen einzelnen Wert:
my $animal = "camel";
my $answer = 42;
# Scalare Werte könnne Zeichenketten, Ganzzahlen und Gleitkomma-Zahlen sein.
# Perl convertiert automatisch zwischen diesen Werten wenn nötig.
## Arrays
# Ein Array repräsentiert eine Liste von Werten:
my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
## Hashes
# Ein Hash representiert ein Set von Schlüssel/Wert Paaren:
my %fruit_color = ("apple", "red", "banana", "yellow");
# Man kann Leerzeichen und den "=>" Operator verwenden um sie schön darzustellen:
my %fruit_color = (
apple => "red",
banana => "yellow",
);
# Scalare, Arrays und Hashes sind in perldata sehr genau dokumentiert.
# (perldoc perldata)
# Komplexere Daten-Typen können mit hilfe von Referenzen konstruiert werden.
# Dies erlaubt das erstellen von Listen und Hashes in Listen und Hashes.
#### Bedingte Ausführungs- und Schleifen-Konstrukte.
# Perl besitzt die üblichen Bedingte Ausführung- und Schleifen-Konstrukte
if ($var) {
...
} elsif ($var eq 'bar') {
...
} else {
...
}
unless (condition) {
...
}
# Dies ist die etwas leserliche Version von "if (!Bedingung)"
# Die Perl-Eigene Post-Bedingungs-Schreibweise
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
# while
while (condition) {
...
}
# Für Schleifen und Iterationen
for (my $i = 0; $i < $max; $i++) {
print "index is $i";
}
for (my $i = 0; $i < @elements; $i++) {
print "Current element is " . $elements[$i];
}
for my $element (@elements) {
print $element;
}
# Implizite Iteration
for (@elements) {
print;
}
# Die Perl-Eigene Post-Bedingungs-Schreibweise nochmals
print for @elements;
#### Reguläre Ausdrücke
# Die Unterstützung von Perl für reguläre Ausdrücke ist weit und tiefgreifend.
# Sie ist ausführlich in perlrequick, perlretut und sonstwo dokumentiert.
# Die Kurzfassung:
# Einfaches Vergleichen
if (/foo/) { ... } # Wahr wenn "foo" in $_ enthalten ist
if ($a =~ /foo/) { ... } # Wahr wenn "foo" in $a enthalten ist
# Einfache Substitution
$a =~ s/foo/bar/; # Ersetzt foo mit bar in $a
$a =~ s/foo/bar/g; # Ersetzt ALLE VORKOMMNISSE von foo mit bar in $a
#### Dateien und Ein-/Ausgabe
# Dateien werden mit der "open()" Funktion zur Ein- oder Ausgabe geöffnet.
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Von einem geöffneten Datei-Handle kann mit dem "<>" Operator gelesen werden.
# In einem Scalaren-Kontext liest man damit eine einzelnen Zeile vom Datei-Handle.
# In einem Listen-Kontext wird damit die komplette Datei eingelesen. Dabei
# entspricht jede Zeile einem Element der Liste:
my $line = <$in>;
my @lines = <$in>;
#### Schreiben von Subroutinen
# Subroutinen schreiben ist einfach:
sub logger {
my $logmessage = shift;
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
print $logfile $logmessage;
}
# Nun können wir die Subroutine genau wie eine eingebaute Funktion verwenden:
logger("We have a logger subroutine!");
```
#### Verwenden von Perl Modulen
Perl Module liefern eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten.
Perlfaq enthält Fragen und Antworten zu häufig vorkommenden Aufgaben. Sehr oft sind auch Vorschläge enthalten welches CPAN module am besten geeignet ist.
#### Weiterführende Literatur
- [perl-tutorial](http://perl-tutorial.org/)
- [Learn at www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- in Perl eingebaut : `perldoc perlintro`

View File

@@ -0,0 +1,655 @@
---
language: python3
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
translators:
- ["kultprok", "http:/www.kulturproktologie.de"]
- ["matthiaskern", "https://github.com/matthiaskern"]
filename: learnpython3-de.py
lang: de-de
---
Anmerkungen des ursprünglichen Autors:
Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode.
Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service].
Hinweis: Dieser Beitrag bezieht sich insplizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter.
```python
# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz)
""" Mehrzeilige Strings werden mit
drei '-Zeichen geschrieben und werden
oft als Kommentare genutzt.
"""
####################################################
## 1. Primitive Datentypen und Operatoren
####################################################
# Die Zahlen
3 #=> 3
# Mathematik funktioniert so, wie man das erwartet
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
# Außer Division, welche automatisch Gleitkommazahlen zurückgibt
35 / 5 # => 7.0
# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche
3 * 2.0 # => 6.0
# Der Rest einer Division
7 % 3 # => 1
# Potenz
2**4 # => 16
# Rangfolge wird mit Klammern erzwungen
(1 + 3) * 2 #=> 8
# Boolesche Ausdrücke sind primitive Datentypen
True
False
# Mit not wird negiert
not True #=> False
not False #=> True
# Boolesche Operatoren
# Hinweis: "and" und "or" müssen klein geschrieben werden
True and False #=> False
False or True #=> True
# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen
0 and 2 #=> 0
-5 or 0 #=> -5
0 == False #=> True
2 == True #=> False
1 == True #=> True
# Gleichheit ist ==
1 == 1 #=> True
2 == 1 #=> False
# Ungleichheit ist !=
1 != 1 #=> False
2 != 1 #=> True
# Ein paar weitere Vergleiche
1 < 10 #=> True
1 > 10 #=> False
2 <= 2 #=> True
2 >= 2 #=> True
# Vergleiche können verknüpft werden!
1 < 2 < 3 #=> True
2 < 3 < 2 #=> False
# Strings werden mit " oder ' gebildet
"Das ist ein String."
'Das ist auch ein String.'
# Strings können auch addiert werden! Vermeide dies aber lieber.
"Hallo " + "Welt!" #=> "Hallo Welt!"
# Strings können ohne "+" addiert werden
"Hallo " "welt!" # => "Hallo Welt!"
# Ein String kann wie eine Liste von Zeichen verwendet werden
"Das ist ein String"[0] #=> 'D'
# .format kann Strings formatieren
"{} können {} werden".format("Strings", "formatiert")
# Schneller geht das mit Wiederholungen
"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat")
#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat"
# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen.
"{name} will {food} essen".format(name="Bob", food="Lasagne")
#=> "Bob will Lasagne kochen"
#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden:
"%s können %s werden" % ("Strings", "interpoliert")
# None ist ein Objekt
None #=> None
# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen
# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität
"etc" is None #=> False
None is None #=> True
# None, 0, und leere Strings/Listen werden alle als False bewertet.
# Alle anderen Werte sind True
bool(0) # => False
bool("") # => False
bool([]) #=> False
bool({}) #=> False
####################################################
## 2. Variablen und Collections
####################################################
# Textausgabe ist sehr einfach
print "Ich bin Python. Schön, dich kennenzulernen!"
# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren.
some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
some_var #=> 5
# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
# Unter "Kontrollstruktur" kann noch mehr über
# Ausnahmebehandlung erfahren werden.
some_unknown_var # Löst einen NameError aus
# Listen speichern Sequenzen
li = []
# Wir können mit einer bereits gefüllten Liste anfangen
other_li = [4, 5, 6]
# append fügt Daten am Ende der Liste ein
li.append(1) #li ist jetzt [1]
li.append(2) #li ist jetzt [1, 2]
li.append(4) #li ist jetzt [1, 2, 4]
li.append(3) #li ist jetzt [1, 2, 4, 3]
# Vom Ende der Liste mit pop entfernen
li.pop() #=> 3 und li ist jetzt [1, 2, 4]
# und dann wieder hinzufügen
li.append(3) # li ist jetzt wieder [1, 2, 4, 3].
# Greife auf Listen wie auf Arrays zu
li[0] #=> 1
# Das letzte Element ansehen
li[-1] #=> 3
# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError
li[4] # Verursacht einen IndexError
# Wir können uns Ranges mit Slice-Syntax ansehen
li[1:3] #=> [2, 4]
# Den Anfang auslassen
li[2:] #=> [4, 3]
# Das Ende auslassen
li[:3] #=> [1, 2, 4]
# Jeden Zweiten Eintrag auswählen
li[::2] # =>[1, 4]
# Eine umgekehrte Kopie zurückgeben
li[::-1] # => [3, 4, 2, 1]
# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich
# li[Start:Ende:Schritt]
# Ein bestimmtes Element mit del aus der Liste entfernen
del li[2] # li ist jetzt [1, 2, 3]
# Listen können addiert werden
li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen
# Listen mit extend verknüpfen
li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6]
# Mit in auf Existenz eines Elements prüfen
1 in li #=> True
# Die Länge der Liste mit len ermitteln
len(li) #=> 6
# Tupel sind wie Listen, nur unveränderlich.
tup = (1, 2, 3)
tup[0] #=> 1
tup[0] = 3 # Löst einen TypeError aus
# Wir können all diese Listen-Dinge auch mit Tupeln anstellen
len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
2 in tup #=> True
# Wir können Tupel (oder Listen) in Variablen entpacken
a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
d, e, f = 4, 5, 6
# Es ist kinderleicht zwei Werte zu tauschen
e, d = d, e # d is now 5 and e is now 4
# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare
empty_dict = {}
# Hier ein gefülltes Wörterbuch
filled_dict = {"one": 1, "two": 2, "three": 3}
# Wir können Einträge mit [] nachschlagen
filled_dict["one"] #=> 1
# So holen wir alle Keys (Schlüssel) als Liste
list(filled_dict.keys()) #=> ["three", "two", "one"]
# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert.
# Einzelne Resultate können anders angeordnet sein.
# Alle Values (Werte) als Liste
list(filled_dict.values()) #=> [3, 2, 1]
# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln.
# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen
"one" in filled_dict #=> True
1 in filled_dict #=> False
# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus
filled_dict["four"] # KeyError
# Mit der get-Methode verhindern wir das
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen
filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt
filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5
# Einträge zu einem Wörterbuch hinzufügen
filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen
# Schlüssel von einem Wörterbuch entfernen
del filled_dict["one"] # Entfert den Schlüssel "one"
# Sets speichern Mengen
empty_set = set()
# Initialisieren wir ein Set mit ein paar Werten
some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4}
# Neue Variablen können einer Menge gleichgesetzt werden
filled_set = some_set
# Mehr Elemente hinzufügen
filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5}
# Schnittmengen werden mit & gebildet
other_set = {3, 4, 5, 6}
filled_set & other_set #=> {3, 4, 5}
# Mengen werden mit | vereinigt
filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
# Die Differenz einer Menge mit - bilden
{1,2,3,4} - {2,3,5} #=> {1, 4}
# Auf Vorhandensein von Elementen mit in prüfen
2 in filled_set #=> True
10 in filled_set #=> False
####################################################
## 3. Kontrollstruktur und Iteratoren
####################################################
# Erstellen wir mal eine Variable
some_var = 5
# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig!
# gibt "some_var ist kleiner als 10" aus
if some_var > 10:
print "some_var ist viel größer als 10."
elif some_var < 10: # Dieser elif-Absatz ist optional.
print "some_var ist kleiner als 10."
else: # Das hier ist auch optional.
print "some_var ist tatsächlich 10."
"""
For-Schleifen iterieren über Listen
Ausgabe:
hund ist ein Säugetier
katze ist ein Säugetier
maus ist ein Säugetier
"""
for animal in ["hund", "katze", "maus"]:
# Wir können Strings mit format() formatieren
print("{} ist ein Säugetier".format(animal))
"""
`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder
Ausgabe:
0
1
2
3
"""
for i in range(4):
print i
"""
"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus
Ausgabe:
4
5
6
7
"""
for i in range(4, 8):
print(i)
"""
While-Schleifen laufen, bis eine Bedingung erfüllt ist.
Ausgabe:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # Kurzform für x = x + 1
# Ausnahmebehandlung mit einem try/except-Block
try:
# Mit raise wird ein Fehler ausgegeben
raise IndexError("Das hier ist ein Index-Fehler")
except IndexError as e:
pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären.
except (TypeError, NameError):
pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich.
else: # Optional, hinter allen except-Blöcken
print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind
finally: # Wird immer ausgeführt
print("Hier können wir Ressourcen aufräumen")
# alternativ zu einem try/finally Block um Aufzuräumen:
with open("meineDatei.txt") as f:
for line in f:
print(line)
# Python bietet ein fundamentales Konzept der Iteration.
# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
# Die range Method gibt ein solches Objekt aus.
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt.
# Über dieses können wir auch iterieren
for i in our_iterable:
print(i) # Gibt one, two, three aus
# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben
our_iterable[1] # TypeError
# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft.
our_iterator = iter(our_iterable)
# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen.
# Das jeweeils nächste Objekt bekommen wir mit "next()"
next(our_iterator) #=> "one"
# Es hält den vorherigen Status
next(our_iterator) #=> "two"
next(our_iterator) #=> "three"
# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück
next(our_iterator) # Gibt StopIteration aus
# Alle Elemente können mit "list()" ausgegeben werden
list(filled_dict.keys()) #=> ["one", "two", "three"]
####################################################
## 4. Funktionen
####################################################
# Mit def neue Funktionen erstellen
def add(x, y):
print "x ist %s und y ist %s" % (x, y)
return x + y # Werte werden mit return zurückgegeben
# Funktionen mit Parametern aufrufen
add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück
# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente
add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden.
# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren
def varargs(*args):
return args
varargs(1, 2, 3) #=> (1,2,3)
# Wir können auch Funktionen mit beliebiger Anzahl
# Schlüsselwort-Argumenten definieren
def keyword_args(**kwargs):
return kwargs
# Rufen wir es mal auf, um zu sehen, was passiert
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
# Wir können beides gleichzeitig machem, wenn wir wollen
def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) Ausgabe:
(1, 2)
{"a": 3, "b": 4}
"""
# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen!
# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4)
all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4)
all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4)
# Anwendungsbereich von Funktionen
x = 5
def setX(num):
# lokale Variable x ist nicht die globale Variable x
x = num # => 43
print (x) # => 43
def setGlobalX(num):
global x
print (x) # => 5
x = num # globale Variable x ist jetzt 6
print (x) # => 6
setX(43)
setGlobalX(6)
# Python hat First-Class-Funktionen
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) #=> 13
# Es gibt auch anonyme Funktionen
(lambda x: x > 2)(3) #=> True
# Es gibt auch Funktionen höherer Ordnung als Built-Ins
map(add_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
####################################################
## 5. Klassen
####################################################
# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten.
class Human(object):
# Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt
species = "H. sapiens"
# Ein simpler Konstruktor
def __init__(self, name):
# Wir weisen das Argument name dem name-Attribut der Instanz zu
self.name = name
# Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument.
def say(self, msg):
return "{name}: {message}".format(name=self.name, message=msg)
# Eine Klassenmethode wird von allen Instanzen geteilt.
# Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen
@classmethod
def get_species(cls):
return cls.species
# Eine statische Methode wird ohne Klasse oder Instanz aufgerufen
@staticmethod
def grunt():
return "*grunt*"
# Eine Instanz einer Klasse erstellen
i = Human(name="Ian")
print i.say("hi") # gibt "Ian: hi" aus
j = Human("Joel")
print j.say("hello") #gibt "Joel: hello" aus
# Rufen wir mal unsere Klassenmethode auf
i.get_species() #=> "H. sapiens"
# Ändern wir mal das gemeinsame Attribut
Human.species = "H. neanderthalensis"
i.get_species() #=> "H. neanderthalensis"
j.get_species() #=> "H. neanderthalensis"
# Aufruf der statischen Methode
Human.grunt() #=> "*grunt*"
####################################################
## 6. Module
####################################################
# Wir können Module importieren
import math
print math.sqrt(16) #=> 4
# Wir können auch nur spezielle Funktionen eines Moduls importieren
from math import ceil, floor
print ceil(3.7) #=> 4.0
print floor(3.7) #=> 3.0
# Wir können auch alle Funktionen eines Moduls importieren
# Warnung: Dies wird nicht empfohlen
from math import *
# Wir können Modulnamen abkürzen
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
# Module sind in Python nur gewöhnliche Dateien. Wir
# können unsere eigenen schreiben und importieren. Der Name des
# Moduls ist der Dateiname.
# Wir können auch die Funktionen und Attribute eines
# Moduls herausfinden.
import math
dir(math)
####################################################
## 7. Fortgeschritten
####################################################
# Generatoren helfen um Code schnell und einfach zu schreiben
def double_numbers(iterable):
for i in iterable:
yield i + i
# Ein Generator erschafft Werte spontan
# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen.
# iteration. Das heißt, Werte größer als 15 werden nicht behandelt.
# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000
# würde das sehr viel Zeit in Anspruch nehmen.
# Wenn wir eine variable mit einem Namen erschaffen wollen, das
# normalerweise mit einem Python - Schlüsselwort kollidieren würde,
# benutzen wir einen Unterstrich nach dem Wort.
range_ = range(1, 900000000)
# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt
for i in double_numbers(range_):
print(i)
if i >= 30:
break
# Dekoratoren
# In diesem Beispiel die Methode beg umwickelt say
# Beim Aufruf von beg, say wird aufgerufen
# Falls say_please true ist, ändert sich die ausgegebene Nachricht
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
print(say()) # Can you buy me a beer?
print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
```
## Lust auf mehr?
### Kostenlos online (Englisch)
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
* [Ideas for Python Projects](http://pythonpracticeprojects.com)
* [The Official Docs](http://docs.python.org/3/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [Python Course](http://www.python-course.eu/index.php)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
### Totholz (Englisch)
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)

View File

@@ -13,6 +13,7 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
- ["Dennis Keller", "https://github.com/denniskeller"]
filename: ruby-de.rb
lang: de-de
---
@@ -195,7 +196,7 @@ array[12] #=> nil
array[-1] #=> 5
```
## Arrays können mit Stard Index und Länge indiziert werden
## Arrays können mit Start Index und Länge indiziert werden
```
array[2, 3] #=> [3, 4, 5]
```
@@ -219,8 +220,6 @@ array.include?(1) #=> true
# Hashes
Hashes sind das Hauptfeature um Key/Values zu speichern
```
## Ein Hash anlegen
```
hash = { 'color' => 'green', 'number' => 5 }
@@ -232,7 +231,7 @@ hash.keys #=> ['color', 'number']
hash['color'] #=> 'green'
hash['number'] #=> 5
hash['nothing here'] #=> nil
// Asking a hash for a key that doesn't exist returns nil:
// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
```
## Symbols können auch keys sein
@@ -247,7 +246,7 @@ new_hash.has_key?(:defcon) #=> true
new_hash.has_value?(3) #=> true
```
### Tip: Arrays und Hashes sind Enumerable
### Tipp: Arrays und Hashes sind Enumerable
### Und haben gemeinsame, hilfreiche Methoden wie:
### each, map, count, and more
@@ -339,7 +338,7 @@ end
=> "OK job"
```
# exception handling:
# Exception handling:
```
begin
# code here that might raise an exception
@@ -366,7 +365,7 @@ end
double(2) #=> 4
```
### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist
### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
```
double 3 #=> 6
double double 3 #=> 12

352
de-de/rust-de.html.markdown Normal file
View File

@@ -0,0 +1,352 @@
---
language: rust
contributors:
- ["P1start", "http://p1start.github.io/"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
lang: de-de
filename: lernerust-de.rs
---
Rust ist eine Programmiersprache von Mozilla Research.
Rust vereint Sicherheit, Nebenläufigkeit und eine hohe Praxistauglichkeit.
Sicherheit bedeuted, dass Programmierfehler ausgeschlossen werden, die zu
Speicherzugriffsfehlern führen könnten. Das funktioniert u.a. dadurch, dass
es keinen Garbage Collector gibt, sondern ein besonderes Typsystem.
Das erste Release von Rust, 0.1, wurde im Januar 2012 veröffentlicht.
In den nächsten drei Jahren wurde die Sprache so schnell und aktiv weiter-
entwickelt, dass es einfach keine stabile gab und geraten wurde den
nightly build zu nutzen.
Am 15. Mai 2015 wurde Rust 1.0 freigegeben, und zwar mit der Garantie einer
Abwärtskompatabilität. Verbesserungen der Kompilierzeit und andere Compiler
verbesserungen finden im Moment im nightly build statt. Von Rust gibt es im
Moment ungefähr alle sechs Wochen ein Release. Rust 1.1 beta wurde zusammen
mit dem 1.0 Release zur Verfügung gestellt.
Obwohl Rust eine ziemlich low-level Sprache ist, vereint sie Ansätze aus
der Welt der funktionalen, der objektorientierten und der nebenläufigen
Programmierung. Dadurch kann in Rust nicht nur schnell, sondern auch sehr
effizient entwickelt werden.
```rust
// Dies ist ein Kommentar. Ein einzeiliger...
/* ...und multi-zeilen Kommentare sehe so aus */
/////////////////////
// 0. Installation //
/////////////////////
// Stabile binaries gibt es unter https://www.rust-lang.org/downloads.html
// Programme werden in .rs Dateien geschrieben also zum Beispiel
// "main.rs" und dann kompiliert "rustc main.rs"
// Herauskommt eine ausführbare Datei "main"
// Für dieses Tutorial reicht das vollkommen aus. Für größere Projekte
// sollte das unten beschriebene Cargo angeschaut werden.
// Cargo
// Ein gängiges Tool um Rust Projekte zu verwalten ist Cargo. Es macht im
// wesentlichen drei Dinge: Code bauen, Dependencies laden und
// Dependencies bauen.
// Um ein vorhandenes Projekt zu cargo-ifyen müssen drei Dinge gemacht werden
// * Erstelle eine Cargo.toml Konfigurationsdatei
// * Verschiebe Source Code in ein src Verzeichnis
// * Lösche das alte Executable
//
// 'cargo build' baut den Code
// 'cargo run' baut und führt das Programm aus
///////////////
// 1. Basics //
///////////////
// Funktionen
// `i32` ist der Typ für einen 32-bit signed Integer
fn add2(x: i32, y: i32) -> i32 {
// Impliziter return (kein Semikolon)
x + y
}
// Main Funktion
fn main() {
// Zahlen //
// Unveränderliche Variable
let x: i32 = 1;
// Integer/float Suffixe
let y: i32 = 13i32;
let f: f64 = 1.3f64;
// Type inference
Meistens kann der Rust Compiler selbst schlussfolgern, von welchem
Typ eine Variable ist, so dass man den Typ nicht explizit angeben muss.
In diesem Tutorial werden Typen explizit angegeben, um zu demonstrieren,
welche Möglichkeiten es gibt. Wenn man damit vertraut ist, kann man die
Typen auch weglassen und die Type Inference hilft dann im Hintergrund.
let implicit_x = 1;
let implicit_f = 1.3;
// Arithmetik
let sum = x + y + 13;
// Veränderliche Variable
let mut mutable = 1;
mutable = 4;
mutable += 2;
// Strings //
// Strings gibt es in zwei Typen: &str und String
// Zunächst &str
let x: &str = "hello world!";
// Ausgabe
println!("{} {}", f, x); // 1.3 hello world
// Ein `String` heap-allokierter String
let s: String = "hello world".to_string();
// Ein string slice ist eigentlich ein unveränderlicher Pointer
// auf einen String er enthält nicht den Inhalt den String, sondern
// eben nur den Pointer auf etwas, dass den Inhalt kennt:
// (In diesem Fall, `s`)
let s_slice: &str = &s;
// Ausgabe
println!("{} {}", s, s_slice); // hello world hello world
// Vektoren/Arrays //
// Ein Array mit fester Größe
let vier_ints: [i32; 4] = [1, 2, 3, 4];
// Ein dynamisches Array (Vektorentor)
let mut vector: Vec<i32> = vec![1, 2, 3, 4];
vector.push(5);
// Ein slice eine unveränderliche Ansicht, oder Pointer auf einen
// Vektor oder ein Array. Wie bei Strings, nur eben bei Vektoren
let slice: &[i32] = &vector;
// Benutze `{:?}` um eine debug Ausgabe zu erzeugen
println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
// Tuples //
// Ein Tuple ist eine Liste mit fester Größe und kann Werte
// von unterschiedlichen Typen enthalten
let x: (i32, &str, f64) = (1, "hello", 3.4);
// Werte aus Vektor mit `let` destrukturieren
let (a, b, c) = x;
println!("{} {} {}", a, b, c); // 1 hello 3.4
// Vektor Indizes
println!("{}", x.1); // hello
//////////////
// 2. Typen //
//////////////
// Struct
struct Punkt {
x: i32,
y: i32,
}
let anfang: Punkt = Punkt { x: 0, y: 0 };
// Ein struct mit unbenannten Felder heisst tuple struct
struct Punkt2(i32, i32);
let anfang2 = Punkt2(0, 0);
// Einfache enum, so ähnlich wie in C
enum Richtung {
Links,
Rechts,
Hoch,
Runter,
}
let hoch = Richtung::Hoch;
// Enum mit Feldern
enum OptionalI32 {
EinI32(i32),
Nix,
}
let zwei: OptionalI32 = OptionalI32::EinI32(2);
let nix = OptionalI32::Nix;
// Generics //
struct Foo<T> { bar: T }
// In der Standard Bibliothek heisst das hier `Option`
enum Optional<T> {
EinWert(T),
KeinWert,
}
// Methoden //
impl<T> Foo<T> {
// Methoden erwarten einen `self` Parameter
fn get_bar(self) -> T {
self.bar
}
}
let a_foo = Foo { bar: 1 };
println!("{}", a_foo.get_bar()); // 1
// Traits (vergleichbar mit Interfaces oder Typklassen in anderen Sprachen)
// In Traits werden nur Method Signaturen erstellt.
// Die Implementierung findet im impl statt.
trait MacheIrgendwas<T> {
fn macheIrgendwas(self) -> Option<T>;
}
impl<T> MacheIrgendwas<T> for Foo<T> {
fn macheIrgendwas(self) -> Option<T> {
mache(self.bar)
}
}
let anderes_foo = Foo { bar: 1 };
println!("{:?}", anderes_foo.macheIrgendwas()); // mache(1)
/////////////////////////
// 3. Pattern matching //
/////////////////////////
let foo = OptionalI32::AnI32(1);
match foo {
OptionalI32::EinI32(n) => println!("hier ist ein i32: {}", n),
OptionalI32::Nix => println!("hier ist nix!"),
}
// Advanced pattern matching
struct FooBar { x: i32, y: OptionalI32 }
let bar = FooBar { x: 15, y: OptionalI32::EinI32(32) };
match bar {
FooBar { x: 0, y: OptionalI32::EinI32(0) } =>
println!("Beide Zahlen sind 0!"),
FooBar { x: n, y: OptionalI32::EinI32(m) } if n == m =>
println!("Beide Zahlen sind gleich"),
FooBar { x: n, y: OptionalI32::EinI32(m) } =>
println!("Zahlen sind unterschiedlich: {} {}", n, m),
FooBar { x: _, y: OptionalI32::Nix } =>
println!("Die zweite Zahl ist leer!"),
}
/////////////////////
// 4. Control //
/////////////////////
// `for` Schleife/Iterationen
let array = [1, 2, 3];
for i in array.iter() {
println!("{}", i);
}
// Ranges
for i in 0u32..10 {
print!("{} ", i);
}
println!("");
// gibt aus: `0 1 2 3 4 5 6 7 8 9 `
// `if`
if 1 == 1 {
println!("Mathe ist klappt!");
} else {
println!("Oh nein...");
}
// `if` als Ausdruck
let wert = if true {
"gut"
} else {
"schlecht"
};
// `while` Schleife
while 1 == 1 {
println!("Läuft...");
}
// Unendliche Schleifen
loop {
println!("Hello!");
}
/////////////////////////////////////
// 5. Speichersicherheit & Pointer //
/////////////////////////////////////
// Owned pointer nur eine Sache kann einen Pointer 'besitzen'.
// Das heisst, wenn das Objekt `Box` seinen scope verlässt oder verliert,
// wird es automatisch im Speicher de-allokiert.
let mut mine: Box<i32> = Box::new(3);
// Jetzt wird die Box dereferenziert
*mine = 5;
// Jetzt geht `mine` in den Besitz von `now_its_mine` über.
// `mine` wird verschoben.
let mut now_its_mine = mine;
*now_its_mine += 2;
println!("{}", now_its_mine); // ergibt 7
// Das würde nicht kompilieren, da `now_its_mine` jetzt den Pointer besitzt
// println!("{}", mine);
// Reference ein unveränderlicher Pointer der fremde Daten referenziert
// Wenn eine Referenz auf einen Wert gesetzt wird, heisst das, dass man den
// Wert ausleiht (borrowed).
// Ein ausgeliehener Wert ist unveränderlich und lebt solange wie der
// Scope existiert, in dem er erstellt wurde.
let mut var = 4;
var = 3;
let ref_var: &i32 = &var;
println!("{}", var); // Anders als `mine`, `var` kann hier weiter verwendet werden
println!("{}", *ref_var);
// var = 5; // das kompiliert nicht, da `var` ausgeliehen ist
// *ref_var = 6; // das kompiliert auch nicht, da `ref_var` eine unveränderliche Referenz ist
// Veränderliche Referenzen
// Solange ein Wert veränderlich geliehen wurde, kann man nicht darauf zugreifen
let mut var2 = 4;
let ref_var2: &mut i32 = &mut var2;
*ref_var2 += 2; // '*' wird benutzt um auf den veränderlich geliehenen Wert var2 zu zeigen
println!("{}", *ref_var2); // 6 , //var2 würde nicht kompilieren. //ref_var2 ist vom Typ &mut i32, also //stores a reference to an i32 not the value.
// var2 = 2; // würde das nicht kompilieren, da `var2` geliehen wurde.
}
```
## Weitere Informationen
Es gibt eine ganze Reihe mehr über Rust zu sagen. Dieser Text gibt nur einen
Einblick in die wichtigsten Sprachmerkmale.
Um mehr über Rust zu erfahren, sollte man mit den folgenden Stellen starten:
1. Englisch:
* [Die offizielle Rust Webseite](http://rust-lang.org)
* [The Rust Programming Language](https://doc.rust-lang.org/stable/book/README.html)
* [/r/rust](http://reddit.com/r/rust)
* the #rust channel on irc.mozilla.org
2. Deutsch
* [Rust Wikipedia](https://de.wikipedia.org/wiki/Rust_(Programmiersprache))
* [Artikel im LinuxMagazin](http://www.linux-magazin.de/Ausgaben/2015/08/Rust)

450
de-de/sass-de.html.markdown Normal file
View File

@@ -0,0 +1,450 @@
---
language: sass
filename: learnsass-de.scss
contributors:
- ["Laura Kyle", "https://github.com/LauraNK"]
- ["Sean Corrales", "https://github.com/droidenator"]
- ["Kyle Mendes", "https://github.com/pink401k"]
translators:
- ["Philipp Bochmann", "https://github.com/phbo85"]
lang: de-de
---
Sass ist eine CSS-erweiternde Sprache, welche Features wie Variablen, Verschachtelung, Mixins und mehr hinzufügt.
Sass (und andere Präprozessoren wie [Less](http://lesscss.org/)) helfen Entwicklern dabei ihren Code wartbar und DRY (Don't Repeat Yourself - wiederhole dich nicht) zu schreiben.
Sass hat zwei verschiedene Syntax-Optionen. SCSS, mit der gleichen Syntax wie CSS aber mit den zusätzlichen Features von Sass. Oder Sass (die originale Syntax), welche Einrückung statt geschweiften Klammern und Semikolons benutzt.
Dieses Tutorial wurde mit SCSS geschrieben.
Wenn du bereits mit CSS3 vertraut bist, wirst du dir Sass relativ schnell aneignen. Es bietet keine neuen Styling-Eigenschaft, sondern Werkzeuge mit denen du dein CSS effizienter schreiben kannst und die Wartung viel einfacher machst.
```scss
//Einzeilige Kommentare werden entfernt, wenn Sass zu CSS kompiliert wird.
/* Mehrzeilige Kommentare bleiben bestehen. */
/* Variablen
============================== */
/* Du kannst einen CSS-Wert (wie eine Farbe) in einer Variable speichern.
Benutze das '$'-Zeichen um eine Variable zu erstellen. */
$primary-color: #A3A4FF;
$secondary-color: #51527F;
$body-font: 'Roboto', sans-serif;
/* Du kannst die Variablen überall in deinem Stylesheet verwenden.
Wenn du nun eine Farbe ändern willst, musst du das nur einmal tun. */
body {
background-color: $primary-color;
color: $secondary-color;
font-family: $body-font;
}
/* Das wird kompiliert zu: */
body {
background-color: #A3A4FF;
color: #51527F;
font-family: 'Roboto', sans-serif;
}
/* Dies ist viel besser wartbar als die Farbe
an jeder Stelle im Stylesheet einzeln ändern zu müssen. */
/* Mixins
============================== */
/* Wenn du merkst, dass du den gleichen Code für mehr als ein
Element schreiben musst, kannst du ihn in einem mixin speichern.
Dazu benutzt du '@mixin' plus einem Namen für dein mixin. */
@mixin center {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
/* Du kannst das mixin mit '@include' und dem Namen des mixin benutzen. */
div {
@include center;
background-color: $primary-color;
}
/* Das kompiliert zu: */
div {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
background-color: #A3A4FF;
}
/* Du kannst Mixins benutzen, um shorthand Eigenschaften zu erstellen. */
@mixin size($width, $height) {
width: $width;
height: $height;
}
/* Diese kannst du aufrufen und width und height als Parameter übergeben. */
.rectangle {
@include size(100px, 60px);
}
.square {
@include size(40px, 40px);
}
/* Compiles to: */
.rectangle {
width: 100px;
height: 60px;
}
.square {
width: 40px;
height: 40px;
}
/* Funktionen
============================== */
/* Sass bietet Funktionen, welche benutzt werden können um eine Reihe
von Aufgaben zu bewältigen. Berücksichtige das Folgende: */
/* Funktionen können aufgerufen werden indem du ihren Namen benutzt
und die benötigten Parameter übergibst. */
body {
width: round(10.25px);
}
.footer {
background-color: fade_out(#000000, 0.25)
}
/* Kompiliert: */
body {
width: 10px;
}
.footer {
background-color: rgba(0, 0, 0, 0.75);
}
/* Du kannst auch deine eigenen Funktionen definieren. Funktionen ähneln
Mixins. Wenn du zwischen Funktionen und Mixins auswählen musst, denke
daran, dass Mixins am besten zur Generierung von CSS eignen, während
Funktionen besser für Logik in deinem Sass Code genutzt werden. Die
Beispiele mit in der Sektion "Mathematische Operatoren" sind ideale
Kandidaten für wiederverwendbare Funktionen. */
/* Diese Funktion errechnet den Prozentwert aus target-size und parent-size
und gibt diesen zurück. */
@function calculate-percentage($target-size, $parent-size) {
@return $target-size / $parent-size * 100%;
}
$main-content: calculate-percentage(600px, 960px);
.main-content {
width: $main-content;
}
.sidebar {
width: calculate-percentage(300px, 960px);
}
/* Kompiliert: */
.main-content {
width: 62.5%;
}
.sidebar {
width: 31.25%;
}
/* Extend (Vererbung)
============================== */
/* Extend ist ein Weg um Eigenschaften eines Selektoren mit einem anderem
zu teilen. */
.display {
@include size(5em, 5em);
border: 5px solid $secondary-color;
}
.display-success {
@extend .display;
border-color: #22df56;
}
/* Kompiliert: */
.display, .display-success {
width: 5em;
height: 5em;
border: 5px solid #51527F;
}
.display-success {
border-color: #22df56;
}
/* Aufgrund der Art wie Sass die Klassen zusammen gruppiert, welche
alle das gleiche Grund-Styling haben, ist Extend der Erstellung
eines Mixins vorzuziehen. Wenn dies mit einem Mixin gemacht worden
wäre, würden width, height und border für jedes Element dupliziert
werden, welches das Mixin aufruft. Dies beeinflusst zwar nicht
deinen Workflow, bläht aber die vom Sass-Compiler erzeugten Dateien
unnötige auf. */
/* Nesting (Verschachtelung)
============================== */
/* Sass erlaubt es Selektoren in Selektoren zu verschachteln. */
ul {
list-style-type: none;
margin-top: 2em;
li {
background-color: #FF0000;
}
}
/* '&' wird durch den übergeordneten Selektor ersetzt. */
/* Du kannst auch Pseudo-Klassen verschachteln. */
/* Denk daran, dass zu viel Verschachtelung deinen Code schlechter
wartbar macht.
Die Best Practices empfehlen nicht mehr als 3 Ebenen zu verschachteln.
Zum Beispiel: */
ul {
list-style-type: none;
margin-top: 2em;
li {
background-color: red;
&:hover {
background-color: blue;
}
a {
color: white;
}
}
}
/* Kompiliert: */
ul {
list-style-type: none;
margin-top: 2em;
}
ul li {
background-color: red;
}
ul li:hover {
background-color: blue;
}
ul li a {
color: white;
}
/* Partials und Imports
============================== */
/* Sass erlaubt dir das Erstellen partieller Dateien (partials).
Das hilft dir modularisierten Sass Code zu schreiben.
Partielle Dateien fangen mit einem '_' an, z.B. _reset.css.
Partielle Dateien werden nicht zu CSS generiert. */
/* Schau dir folgendes CSS an, was wir in einer Datei namens _reset.css haben */
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
/* Mit @import kannst du in Sass partielle Dateien importieren.
Dies unterscheidet sich vom traditionellen CSS @import Statement
welches einen neuen HTTP Request macht, um die zu importierende Datei
zu holen. Sass nimmt die importierte Datei und kombiniert sie mit
dem kompilierten Code. */
@import 'reset';
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/* Kompiliert: */
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/* Platzhalter Selektoren
============================== */
/* Platzhalter sind nützlich, um ein CSS Statement zum Erweitern zu
erstellen. Wenn du ein CSS Statement erstellst, welches du ausschließlich
zur Verwendung mit @extend nutzen willst, kannst du das mit einem
Platzhalter tun. Platzhalter fangen mit einem '%' statt einem '.'
oder '#' an und erscheinen nicht im kompilierten CSS. */
%content-window {
font-size: 14px;
padding: 10px;
color: #000;
border-radius: 4px;
}
.message-window {
@extend %content-window;
background-color: #0000ff;
}
/* Kompiliert: */
.message-window {
font-size: 14px;
padding: 10px;
color: #000;
border-radius: 4px;
}
.message-window {
background-color: #0000ff;
}
/* Mathematische Operationen
============================== */
/* Sass bietet die folgenden Operatoren: +, -, *, /, und %. Diese können
nützlich sein, wenn du Werte direkt in Sass berechnen willst, anstatt
vorher manuell errechnete Werte zu verwenden. Unten folgt ein Beispiel
für ein einfaches zweispaltiges Design. */
$content-area: 960px;
$main-content: 600px;
$sidebar-content: 300px;
$main-size: $main-content / $content-area * 100%;
$sidebar-size: $sidebar-content / $content-area * 100%;
$gutter: 100% - ($main-size + $sidebar-size);
body {
width: 100%;
}
.main-content {
width: $main-size;
}
.sidebar {
width: $sidebar-size;
}
.gutter {
width: $gutter;
}
/* Compiles to: */
body {
width: 100%;
}
.main-content {
width: 62.5%;
}
.sidebar {
width: 31.25%;
}
.gutter {
width: 6.25%;
}
```
## SASS oder Sass?
Hast du dich jemals gefragt, ob Sass ein Akronym ist oder nicht? Hast du wahrscheinlich nicht, aber ich sage es dir trotzdem. Der Name der Sprache ist ein Wort, "Sass", und kein Akronym.
Da die Leute durchgehend "SASS" geschrieben haben, hat der Ersteller der Sprache es scherzhaft "Syntactically Awesome StyleSheets" genannt.
## Sass üben
Wenn du mit Sass in deinem Browser spielen willst, schau dir [SassMeister](http://sassmeister.com/) an.
Du kannst beide Syntax-Optionen benutzen, gehe einfach in die Einstellungen und wähle entweder Sass oder SCSS.
## Kompatibilität
Sass kann in jedem Projekt verwendet werden, solange du ein Programm hast, um es in CSS zu kompilieren.
Du solltest verifizieren, dass das CSS, was du verwendest, mit deinen Ziel-Browsern kompatibel ist.
[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilät zu überpüfen.
## Literaturhinweise
* [Offizielle Dokumentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html)
* [The Sass Way](http://thesassway.com/) bietet Tutorials (Anfänger bis Fortgeschritten) und Artikel.

View File

@@ -538,8 +538,9 @@ res2: Boolean = true
scala> b.beissen
res3: Boolean = false
// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden
// Ein Trait kann auch als Mixin eingebunden werden. Die Klasse erbt vom
// ersten Trait mit dem Schlüsselwort "extends", während weitere Traits
// mit "with" verwendet werden können.
trait Bellen {
def bellen: String = "Woof"

View File

@@ -0,0 +1,591 @@
---
language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
- ["Christopher Bess", "http://github.com/cbess"]
- ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
translators:
- ["Jonas Wippermann", "http://vfuc.co"]
filename: learnswift-de.swift
lang: de-de
---
Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und OS X Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar.
Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar.
Außerdem hilfreich ist Apples [Getting Started Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), ein guter Einstiegspunkt mit komplettem Swift-Tutorial.
```swift
// importiere ein Modul
import UIKit
//
// MARK: Grundlagen
//
// Xcode unterstützt "Landmarks" um Code zu gliedern, sie werden in der Jump Bar aufgelistet
// MARK: Abschnitts-Markierung
// TODO: Zu erledigen
// FIXME: Zu beheben
// In Swift 2 wurden println und print zusammengefasst in eine print-Methode. Es wird automatisch ein Zeilenumbruch angehängt.
print("Hello, world!") // println ist jetzt print
print("Hello, world!", appendNewLine: false) // printen ohne Zeilenumbruch am Ende
// Variablen (var) können nach der Initialisierung verändert werden
// Konstanten (let) können nach der Initialisierung NICHT verändert werden
var myVariable = 42
let øπΩ = "value" // Unicode-Variablennamen
let π = 3.1415926
let convenience = "keyword" // Kontext-abhängiger Variablenname
let weak = "keyword"; let override = "another keyword" // Instruktionen können durch ein Semikolon aufgeteilt werden
let `class` = "keyword" // Nutze "Backticks" um Schlüsselwörter als Variablennamen zu verwenden
let explicitDouble: Double = 70 // Typ explizit festgelegt
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
let label = "some text " + String(myVariable) // Casting
let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String Interpolation
// Build-spezifische Werte
// benutzt -D build configuration
#if false
print("not printed")
let buildValue = 3
#else
let buildValue = 7
#endif
print("Build value: \(buildValue)") // Build value: 7
/*
Optionals ist ein Swift-Feature, welches ermöglicht, dass eine Variable entweder einen (`Some`) oder keinen (`None`) Wert hat
Da Swift von jeder property einen Wert erwartet, muss sogar nil explizit als Optional festgelegt werden.
Optional<T> ist ein Enum.
*/
var someOptionalString: String? = "optional" // Kann nil sein
// Genau wie oben, aber ? ist ein postfix operator (Syntax Candy)
var someOptionalString2: Optional<String> = "optional"
if someOptionalString != nil {
// Ich bin nicht nil
if someOptionalString!.hasPrefix("opt") {
print("has the prefix")
}
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
// Implizit entpackter Optionalwert
var unwrappedString: String! = "Value is expected."
// Genau wie oben, aber ! ist ein postfix operator (noch mehr Syntax Candy)
var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected."
if let someOptionalStringConstant = someOptionalString {
// hat einen (`Some`) Wert, nicht nil
if !someOptionalStringConstant.hasPrefix("ok") {
// hat keinen "ok"-Prefix
}
}
// Swift unterstützt das festlegen von Werten eines beliebigen Typens
// AnyObject == id
// Im Gegensatz zum Objective-C `id`, funktioniert AnyObject mit jeglichen Werten (Class, Int, struct, etc)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
Ein Kommentar
/*
Verschachtelte Kommentare sind ebenfalls unterstützt
*/
*/
//
// MARK: Collections
//
/*
Array und Dictionary-Typen sind structs.
Deswegen implizieren `let` und `var` bei der Initialisierung auch ob sie änderbar (var) oder unveränderlich (let) sind.
*/
// Array
var shoppingList = ["catfish", "water", "lemons"]
shoppingList[1] = "bottle of water"
let emptyArray = [String]() // let == unveränderlich
let emptyArray2 = Array<String>() // genau wie oben
var emptyMutableArray = [String]() // var == änderbar
// Dictionary
var occupations = [
"Malcolm": "Captain",
"kaylee": "Mechanic"
]
occupations["Jayne"] = "Public Relations"
let emptyDictionary = [String: Float]() // let == unveränderlich
let emptyDictionary2 = Dictionary<String, Float>() // genau wie oben
var emptyMutableDictionary = [String: Float]() // var == änderbar
//
// MARK: Kontrollstruktur
//
// for-Schleife (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
print("One!")
} else {
print("Not one!")
}
}
// for-Schleife mit Indizes (array)
for index in myArray.indices {
print("Value with index \(index) is \(myArray[index])")
}
// for-Schleife (dictionary)
var dict = ["one": 1, "two": 2]
for (key, value) in dict {
print("\(key): \(value)")
}
// for-Schleife (range)
for i in -1...shoppingList.count {
print(i)
}
shoppingList[1...2] = ["steak", "peacons"]
// ..< schließt letzte Nummer aus
// while-Schleife
var i = 1
while i < 1000 {
i *= 2
}
// do-while-Schleife
do {
print("hello")
} while 1 == 2
// Switch
// Sehr mächtig, wie `if` statement mit Syntax Candy
// Unterstützt Strings, Objekt-Instanzen und primitive Typen (Int, Double, etc)
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(localScopeValue)?"
default: // notwendig (um alle möglichen Eingaben zu verarbeiten)
let vegetableComment = "Everything tastes good in soup."
}
//
// MARK: Funktionen
//
// Funktionen sind ein sogenannter "first-class" Typ, was bedeutet, dass sie
// in Funktionen geschachtelt werden und "herumgereicht" werden können
// Funktion mit Swift header Dokumentation
/**
Eine Grüß-Funktion
- Ein Aufzählungspunkt
- Ein weiterer Aufzählungspunkt in der Dokumentation
:param: name Ein Name
:param: day Ein Tag
:returns: Ein String, der Name und Tag beinhält.
*/
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
// Ähnlich wie oben, bloß anderes Funktions-Parameter-Verhalten
func greet2(#requiredName: String, externalParamName localParamName: String) -> String {
return "Hello \(requiredName), the day is \(localParamName)"
}
greet2(requiredName:"John", externalParamName: "Sunday")
// Funktion, welche mehrere Werte in einem Tupel zurückgibt
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// Ignoriere Tupel-(oder andere)Werte mit _ (Unterstrich)
let (_, price1, _) = pricesTuple // price1 == 3.69
print(price1 == pricesTuple.1) // true
print("Gas price: \(price)")
// Variierende Argumente..
func setup(numbers: Int...) {
// .. liegen als Array vor
let number = numbers[0]
let argCount = numbers.count
}
// Funktionen übergeben und zurückgeben
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
// Übergabe via Referenz ("Pass by reference")
func swapTwoInts(inout a: Int, inout b: Int) {
let tempA = a
a = b
b = tempA
}
var someIntA = 7
var someIntB = 3
swapTwoInts(&someIntA, &someIntB)
print(someIntB) // 7
//
// MARK: Closures
//
var numbers = [1, 2, 6]
// Funktionen sind besondere Closures ({})
// Closure Beispiel
// `->` teilt Parameter und Rückgabe-Typ
// `in` teilt den Closure Header vom Body
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
// Wenn der Typ bekannt ist, wie oben, kann folgendes getan werden
numbers = numbers.map({ number in 3 * number })
// oder sogar dies
//numbers = numbers.map({ $0 * 3 })
print(numbers) // [3, 6, 18]
// "Schleppende Closure" (Trailing Closure)
numbers = sorted(numbers) { $0 > $1 }
print(numbers) // [18, 6, 3]
// Sehr verkürzt, da sich der Typ durch den < Operator ableiten lässt
numbers = sorted(numbers, < )
print(numbers) // [3, 6, 18]
//
// MARK: Strukturen
// (häufig einfach structs)
//
// Structures und Klassen haben sehr ähnliche Fähigkeiten
struct NamesTable {
let names = [String]()
// Eigendefiniertes subscript
subscript(index: Int) -> String {
return names[index]
}
}
// Strukturen haben eine automatisch generierte, designierte Initialisierungsfunktion
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
print("Name is \(name)") // Name is Them
//
// MARK: Klassen
//
// Klassen, Strukturen und deren Member haben drei Ebenen der Zugriffskontrolle
// Es gibt: internal (default), public, private
public class Shape {
public func getArea() -> Int {
return 0;
}
}
// Alle Methoden und Properties einer Klasse sind public
// Wenn das einfache Ziel ist, Daten in einem strukturierten Objekt zu halten,
// sollte ein `struct` verwendet werden
internal class Rect: Shape {
var sideLength: Int = 1
// Eigendefinierte Getter und Setter für die Property
private var perimeter: Int {
get {
return 4 * sideLength
}
set {
// `newValue` ist eine implizite Variable, welche in Settern verfügbar ist
sideLength = newValue / 4
}
}
// "Lazy" (faules) Laden einer Property, sie bleibt uninitialisiert (nil),
// bis sie aufgerufen wird
lazy var subShape = Rect(sideLength: 4)
// Wenn kein eigendefinierter Getter/Setter notwendig ist,
// aber trotzdem Code vor und nach dem Setzen eines Variablenwertes laufen soll,
// kann "willSet" und "didSet" benutzt werden
var identifier: String = "defaultID" {
// der `willSet` Parameter wird der Variablenname für den neuen Wert sein
willSet(someIdentifier) {
print(someIdentifier)
}
}
init(sideLength: Int) {
self.sideLength = sideLength
// super.init muss immer aufgerufen werden, wenn eigene Properties initialisiert werden
super.init()
}
func shrink() {
if sideLength > 0 {
sideLength -= 1
}
}
override func getArea() -> Int {
return sideLength * sideLength
}
}
// Eine simple `Square`-Klasse erbt von/erweitert `Rect`
class Square: Rect {
convenience init() {
self.init(sideLength: 5)
}
}
var mySquare = Square()
print(mySquare.getArea()) // 25
mySquare.shrink()
print(mySquare.sideLength) // 4
// Casten der Instanz
let aShape = mySquare as Shape
// Vergleiche Instanzen, nicht äquivalent zum == , welches Objekte vergleicht ("equal to")
if mySquare === mySquare {
print("Yep, it's mySquare")
}
// Optionale Initialisierung
class Circle: Shape {
var radius: Int
override func getArea() -> Int {
return 3 * radius * radius
}
// Ein Fragezeichen nach `init` ist eine optionale Initialisierung,
// welche nil zurückgeben kann
init?(radius: Int) {
self.radius = radius
super.init()
if radius <= 0 {
return nil
}
}
}
var myCircle = Circle(radius: 1)
print(myCircle?.getArea()) // Optional(3)
print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// wird nicht ausgeführt, da myEmptyCircle nil ist
print("circle is not nil")
}
//
// MARK: Enums
//
// Enums können optional einen eigenen Typen haben
// Wie Klassen auch können sie Methoden haben
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func getIcon() -> String {
switch self {
case .Spades: return "♤"
case .Hearts: return "♡"
case .Diamonds: return "♢"
case .Clubs: return "♧"
}
}
}
// Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ
// genannt werden, wenn die Variable explizit deklariert wurde
var suitValue: Suit = .Hearts
// Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte"
enum BookName: String {
case John = "John"
case Luke = "Luke"
}
print("Name: \(BookName.John.rawValue)")
// Enum mit assoziierten Werten
enum Furniture {
// mit Int assoziiert
case Desk(height: Int)
// mit String und Int assoziiert
case Chair(String, Int)
func description() -> String {
switch self {
case .Desk(let height):
return "Desk with \(height) cm"
case .Chair(let brand, let height):
return "Chair of \(brand) with \(height) cm"
}
}
}
var desk: Furniture = .Desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
//
// MARK: Protokolle
//
// Protokolle (`protocol`s) können verlangen, dass entsprechende
// Typen spezifische Instanz-Properties, Instanz/Klassen-Methoden,
// Operatoren oder Subscripts implementieren/haben
protocol ShapeGenerator {
var enabled: Bool { get set }
func buildShape() -> Shape
}
// Protocols mit @objc deklariert ermöglichen optionale Funktionen,
// welche es ermöglichen, abzufragen ob ein Typ einem Protokoll entspricht
@objc protocol TransformShape {
optional func reshaped()
optional func canReshape() -> Bool
}
class MyShape: Rect {
var delegate: TransformShape?
func grow() {
sideLength += 2
// Ein Fragezeichen nach einer optionalen Property, Methode oder Subscript
// ignoriert elegant Nil-Werte und geben nil zurück, anstatt einen Laufzeitfehler zu werfen
// Dies wird "optional Chaining" (optionale Verkettung) genannt
if let allow = self.delegate?.canReshape?() {
// frage erst nach delegate, dann nach Methode
self.delegate?.reshaped?()
}
}
}
//
// MARK: Sonstiges
//
// `extension`s: (Erweiterungen), erweitere Typen um zusätzliche Funktionalität
// Square entspricht jetzt dem `Printable` Protokoll
extension Square: Printable {
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
}
print("Square: \(mySquare)")
// Standardtypen können ebenfalls erweitert werden
extension Int {
var customProperty: String {
return "This is \(self)"
}
func multiplyBy(num: Int) -> Int {
return num * self
}
}
print(7.customProperty) // "This is 7"
print(14.multiplyBy(3)) // 42
//Generics: Ähnlich zu Java und C#. Nutze das `where` keyword um die Bedingung
// des Generics festzulegen
func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
if value == valueToFind {
return index
}
}
return nil
}
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
print(foundAtIndex == 2) // true
// Operatoren:
// Eigendefinierte Operatoren können mit diesen Zeichen beginnen:
// / = - + * % < > ! & | ^ . ~
// oder
// Unicode Mathematik, Symbole, Pfeile, Dingbat, und Linien/Box - Zeichen
prefix operator !!! {}
// Ein Prefix-Operator, welcher die Seitenlänge verdreifacht
prefix func !!! (inout shape: Square) -> Square {
shape.sideLength *= 3
return shape
}
// Aktueller Wert
print(mySquare.sideLength) // 4
// Wert nach verwendung des eigenen Operators
!!!mySquare
print(mySquare.sideLength) // 12
```

475
de-de/tcl-de.html.markdown Normal file
View File

@@ -0,0 +1,475 @@
---
language: Tcl
contributors:
- ["Poor Yorick", "http://pooryorick.com/"]
translators:
- ["Martin Schimandl", "https://github.com/Git-Jiro"]
filename: learntcl-de.tcl
lang: de-de
---
Tcl wurde kreiert von [John Ousterhout](http://wiki.tcl.tk/John Ousterout) als
eine wiederverwendbare Script-Sprache für Chip-Design Werkzeuge die er kreiert
hat. Im Jahre 1997 wurde er mit dem [ACM Software System
Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) für Tcl
ausgezeichnet. Tcl kann sowohl als eingebettete Scipt-Sprache als auch als
allgemeine Programmier-Sprache verwendet werden. Tcl kann auch als portable
C-Bibliothek verwendet werden. Sogar in Fällen in denen die Script-Fähigkeiten
nicht nötig sind. Denn Tcl stellt Daten-Strukturen wie dynamische Zeichenketten,
Listen und Hash-Tabellen bereit. Die C-Bilbiothek stellt auch portable
Funktionen zur Verfügung: Laden von dynamischen Bibliotheken, Zeichenketten
formatierung und Code Konversion, Dateisystem Operationen, Netzwerk Operationen
und mehr.
Verschiedenste herausragende Fähigkeiten von Tcl:
* Praktische Cross-Platform Netzwerk-API
* Vollständig virtualisiertes Dateisystem
* Stapelbare I/O Kanäle
* Asynchron bis zum Kern
* Vollständige Ko-Routinen
* Robustes und einfach zu verwendendes Thread-Modell
Wenn Lisp ein Listen-Prozessor ist, dann ist TCl ein Zeichenketten-Prozessor.
Alle Werte sind Zeichenketten. Eine Liste ist ein Zeichenketten-Format. Eine
Prozedur-Definition ist ein Zeichenketten-Format. Um leistungsfähig zu sein,
werden Tcl-intern diese Zeichenketten in Strukutierter-Form gepuffert. Ein
Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten
Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen
zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren-
beim-Schreiben-Design von Tcl erlaubt es Skript-Authoren mit großen Daten-
Strukturen zu arbeiten ohne zuätzlichen Speicher-Overhead. Prozeduren werden
automatisch byte-kompiliert außer sie verwenden dynamsiche Befehle wie zum
Beispiel "uplevel", "upvar und "trace".
Es ist eine freude in Tcl zu programmieren. Hacker-Typen werden gefallen daran
finden, wenn sie Lisp, Forth oder Smalltalk interessant finden. Tcl wird auch
Ingenieuren und Wissenshaftlern gefallen die nur den Job erledigen wollen,
und zwar mit Werkzeugen die sich ihrem Willen anpassen. Bei Tcl ist jegliche
funktionalität in Befehlen ausgeführt, selbst Dinge wie Schleifen und
Mathematische-Funktionen die bei anderen Sprachen normalerweise Teil der Syntax
sind. Das erlaubt Tcl in den Hintergrund von Domänen spezischen Sprachen zu
treten die das jeweilige Projekt gerade benötigt. Die Tcl-Syntax ist sehr
leichtgewichtig. Sie ist selbst leichtgewichtiger als die Syntax von Lisp.
Tcl steht dir einfach nicht im Weg.
```tcl
#! /bin/env tclsh
################################################################################
## 1. Richtlinien
################################################################################
# Tcl ist nicht Bash oder C! Das muss gesagt werden, denn standard Shell-Quoting
# funktioniert fast mit Tcl. Daher glauben viele sie können diese Syntax für
# Tcl übernehmen. Am Beginn funktioniert das meist, führt aber schnell zu
# Frustrationen wenn die Skripte komplexer werden.
# Eckige-Klammern sind nur Quoting-Mechanismen, keine Code-Block-Konstruktoren
# und auch keine Listen-Konstruktoren. In Tcl gibt es diese beiden Dinge nicht.
# Eckige-Klammern werden verwendet um Spezial-Zeichen in Prozeduren zu escapen
# und in Zeichenketten die als Listen formattiert sind.
################################################################################
## 2. Syntax
################################################################################
# Jede Zeile ist ein Befehl. Das erste Wort ist der Name des Befehls, jedes
# weitere Wort ist ein Argument des Befehls. Wörter sind begrenzt durch
# Leerzeichen. Da jedes Wort auch ein String ist, sind keine speziellen
# auszeichnungen wie Anführungs-Zeichen, Klammern oder Backslashes nötig.
# Selbst wenn Anführungs-Zeichen verwendet werden, denn sie sind ja keine
# String-Konstruktoren, sondern nur Escape-Zeichen.
set greeting1 Sal
set greeting2 ut
set greeting3 ations
# Strichpunkte begrenzen auch Befehle
set greeting1 Sal; set greeting2 ut; set greeting3 ations
# Das Dollar-Zeichen zeigt eine Variablen-Substitution an.
set greeting $greeting1$greeting2$greeting3
# Eckige-Klammern zeigen Befehls-Substitionen an. Das Ergebnis des Befehls wird an
# Stelle des Klammern-Ausdrucks eingefügt. Wenn man dem "set" Befehl nur den
# Namen einer Variablen übergibt, gibt er den Wert der Variablen zurück.
set greeting $greeting1$greeting2[set greeting3]
# Befehls-Substitution sollte eigentlich Script-Substitution heißen, denn ein
# komplettes Script, und nicht nur ein Befehl, kann zwischen die Eckigen-Klammern
# geschrieben werden. Der "incr" Befehl erhöht den Wert einer Variable um 1
# und gibt den neuen Wert der Variable zurück.
set greeting $greeting[
incr i
incr i
incr i
]
# Der Backslash unterdrück die Bedeutung von Sonderzeichen
set amount \$16.42
# Der Backslash macht bestimmte Zeichen zu Sonderzeichen
puts lots\nof\n\n\n\n\n\nnewlines
# Ein Wort das in geschweiften Klammern eingeschlossen wurde ist von jeglichen
# speziellen Interpretationen ausgeschlossen. Eine Ausnahme bilden Backslashes
# vor geschweiften Klammern, hiermit wird die geschweifte Klammer von der Suche
# nach der schließenden geschweiften Klammer ausgeschlossen.
set somevar {
Das ist ein literales $ Zeichen, diese geschweifte Klammer \} wird nicht
als Ende interpretiert.
}
# Bei einem Wort das in doppelten Anführungszeichen steht verlieren Leerzeichen
# ihre spezielle Bedeutung.
set name Neo
set greeting "Hallo, $name"
#Variablen-Namen können irgend eine Zeichenkette sein.
set {first name} New
# Die Geschweifte-Klammern-Form der Variablen-Substitution kann sehr komplexe
# Variblen-Namen handhaben.
set greeting "Hello, ${first name}"
# Der "set" Befehl kann immer anstatt einer Variablen-Substition verwendet
# werden.
set greeting "Hello, [set {first name}]"
# Mit dem Expansions-Operator "{*}" werden Wörter innerhalb eines Wortes wieder
# individuell als Teile des aktuellen Befehls behandelt.
set {*}{name Neo}
# Ist Äquivalent zu
set name Neo
# Ein Array ist eine spezielle Varible die also Kontainer für andere Variablen
# dient.
set person(name) Neo
set person(gender) male
set greeting "Hello, $person(name)"
# Ein Namensraum enthält Befehle und Variablen
namespace eval people {
namespace eval person1 {
variable name Neo
}
}
#Der volle Name einer Variablen beihaltet den/die umschließenden
# Namensraum/Namensräume begrenzt durch zwei Doppelpunkte.
set greeting "Hello $people::person1::name"
```
```tcl
################################################################################
## 3. Einige Notizen
################################################################################
# Jede weitere Funktion ist über Befehle implementiert. Von nun an kommt keine
# neue Syntax hinzu. Alles weitere das es über Tcl zu lernen gibt ist das
# Verhalten individueller Befehle und die bedeutung ihrer Argumente.
# Um einen Interpreter zu bekommen mit dem man nichts mehr machen kann, lösche
# einfach den globalen Namensraum. Das ist nicht sehr sinnvoll, zeigt aber die
# Natur von Tcl.
namespace delete ::
# Wegen des Verhaltens der Namens-Auflösung ist es sicherer den "variable"
# Befehl zu verwenden um in einem Namensraum einen Wert zu deklarieren oder
# zuzuweisen. Wenn eine Variable mit dem namen "name" bereits im globalen
# Namensraum existiert, bewirkt der "set" Befehl das der globalen Variable ein
# Wert zugewiesen wird, anstatt eine Variable im lokalen Namensraum zu erzeugen
namespace eval people {
namespace eval person1 {
variable name Neo
}
}
# Es kann immer der vollständige Name einer Variable verwendet werden, falls
# gewünscht.
set people::person1::name Neo
################################################################################
## 4. Befehle
################################################################################
# Berechnungen werde mit dem "expr" Befehl durchgeführt.
set a 3
set b 4
set c [expr {$a + $b}]
# Since "expr" performs variable substitution on its own, brace the expression
# to prevent Tcl from performing variable substitution first. See
# Da der "expr" Befehl eigene Variablen-Substitutionen durchführt, setze den
# zu berechnenden Ausdruck in Eckige-Klammern. Das hindert Tcl daran Variablen-
# Substitutionen durchzuführen. Für Details siehe:
# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions"
# Der "expr" Befehl versteht Variablen- und Befehls-Substitutionen
set c [expr {$a + [set b]}]
# Der "expr" Befehl stellt Mathematische-Funktionen zur Verfügung.
set c [expr {pow($a,$b)}]
# Mathematische Operatoren sind als Befehle auch im Namensraum
# ::tcl::mathop verfügbar.
::tcl::mathop::+ 5 3
# Befehle können aus anderen Namensräumen importiert werden.
namespace import ::tcl::mathop::+
set result [+ 5 3]
# Neu Befehle werden mit dem "proc" Befehl gebildet.
proc greet name {
return "Hello, $name!"
}
#Es können mehrere Parameter spezifiziert werden.
proc greet {greeting name} {
return "$greeting, $name!"
}
# Wie bereits erwähnt, geschwungene Klammern erzeugen keinen Code-Block.
# Jeder Wert, sogar das dritte Argument für den "proc" Befehl ist eine
# Zeichenkette. Der vorherige Befehl kann daher auch ohne
# geschwungene Klammern geschrieben werden:
proc greet greeting\ name return\ \"Hello,\ \$name!
# Wenn der letzte Parameter der literale Wert "args" ist, sammelt dieser Wert
# alle übrigen Argumente des Befehls ein wenn dieser aufgerufen wird.
proc fold {cmd args} {
set res 0
foreach arg $args {
set res [$cmd $res $arg]
}
}
fold ::tcl::mathop::* 5 3 3 ;# -> 45
# Bedingte Ausführung ist auch als Befehl implementiert
if {3 > 4} {
puts {This will never happen}
} elseif {4 > 4} {
puts {This will also never happen}
} else {
puts {This will always happen}
}
# Auch Schleifen sind Befehle. Das erste, zweite und dritte Argument des "for"
# Befehls wird als mathematischer Ausdruck behandelt.
for {set i 0} {$i < 10} {incr i} {
set res [expr {$res + $i}]
}
# Das erste Argument des "while" Befehls wird auch als mathematischer Ausdruck
# behandelt.
set i 0
while {$i < 10} {
incr i 2
}
# Eine Liste ist eine speziell formatierte Zeichenkette. Im einfachsten Fall
# genügen Leerzeichen als Trennzeichen zwischen den einzelnen Werten.
set amounts 10\ 33\ 18
set amount [lindex $amounts 1]
# Geschwungene Klammern und Backslashes können verwendet werden um komplexe
# Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript,
# allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre
# besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die
# folgende Liste enhtält drei Elemente.
set values {
one\ two
{three four}
five\{six
}
# Da Listen auch Zeichenketten sind, kann man Zeichenketten-Operationen auf
# ihnen anwenden. Allerdings mit dem Risiko die Formatierung der Liste zu
# beschädigen.
set values {one two three four}
set values [string map {two \{} $values] ;# $values is no-longer a \
properly-formatted listwell-formed list
# Der sicherste Weg korrekt formatierte Liste zu erzeugen, ist den "list"
# Befehl zu verwenden.
set values [list one \{ three four]
lappend values { } ;# Ein Leerzeichen als Element der Liste hinzufügen
# Mit "eval" können Werte als Skripts evaluiert weden.
eval {
set name Neo
set greeting "Hello, $name"
}
# Eine Liste kann immer an "eval" übergeben werden, solange die Liste einen
# einzigen Befehl entält.
eval {set name Neo}
eval [list set greeting "Hello, $name"]
# Daher: Wenn "eval" verwendet wird, verwende [list] um den gewünschten Befehl
# aufzubauen.
set command {set name}
lappend command {Archibald Sorbisol}
eval $command
# Es ist ein häufiger Fehler die Listen funktionen beim Aufbauen von Listen
# nicht zu verwenden.
set command {set name}
append command { Archibald Sorbisol}
eval $command ;# Hier passiert eine Fehler, denn der "set" Befehl hat nun zu \
viele Argumente {set name Archibald Sorbisol}
# Dieser Fehler kann auch leicht beim "subst" Befehl passieren.
set replacement {Archibald Sorbisol}
set command {set name $replacement}
set command [subst $command]
eval $command ;# The same error as before: too many arguments to "set" in \
{set name Archibald Sorbisol}
# Die korrekte Vorgangsweise ist es den substituierten Wert mit dem "list"
# Befehl zu formatieren.
set replacement [list {Archibald Sorbisol}]
set command {set name $replacement}
set command [subst $command]
eval $command
# Der "list" Befehl wird sehr häufig verwendet um Werte zu formatieren die
# in Tcl Skript Vorlagen substituiert werden. Es gibt dazu viele Beispiele,
# siehe unterhalb.
# Der "apply" Befehl evaluiert eine Zeichenkette als Befehl.
set cmd {{greeting name} {
return "$greeting, $name!"
}}
apply $cmd Whaddup Neo
# Der "uplevel" Befehl evaluiert ein Skript in einem höher liegenden
Gültigkeitsbereich.
proc greet {} {
uplevel {puts "$greeting, $name"}
}
proc set_double {varname value} {
if {[string is double $value]} {
uplevel [list variable $varname $value]
} else {
error [list {not a double} $value]
}
}
# Der "upvar" Befehl verknüpft eine Variable im aktuellen Gültigkeitsbereich
# mit einer Variable in einem höher liegenden Gültigkeitsbereich.
proc set_double {varname value} {
if {[string is double $value]} {
upvar 1 $varname var
set var $value
} else {
error [list {not a double} $value]
}
}
# Werde den eingebauten "while" Befehl los.
rename ::while {}
# Definieren einen neuen "while" Befehl mit hilfe des "proc" Befehls.
# Ausführlichere Fehler-Behandlung wird dem Leser als Übung überlassen.
proc while {condition script} {
if {[uplevel 1 [list expr $condition]]} {
uplevel 1 $script
tailcall [namespace which while] $condition $script
}
}
# Der "coroutine" Befehl erzeugt einen separaten Call-Stack, zusammen mit einem
# Befehl um diesem Call-Stack zu verwenden. Der "yield" Befehl unterbricht
# die Ausführung des aktuellen Call-Stacks.
proc countdown {} {
#send something back to the initial "coroutine" command
yield
set count 3
while {$count > 1} {
yield [incr count -1]
}
return 0
}
coroutine countdown1 countdown
coroutine countdown2 countdown
puts [countdown 1] ;# -> 2
puts [countdown 2] ;# -> 2
puts [countdown 1] ;# -> 1
puts [countdown 1] ;# -> 0
puts [coundown 1] ;# -> invalid command name "countdown1"
puts [countdown 2] ;# -> 1
```
## Referenzen
[Official Tcl Documentation](http://www.tcl.tk/man/tcl/)
[Tcl Wiki](http://wiki.tcl.tk)
[Tcl Subreddit](http://www.reddit.com/r/Tcl)

View File

@@ -10,7 +10,7 @@ lang: de-de
YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann.
YAML ist eine Erweiterung von JSON, mit der Erweiterung von syntaktisch wichtigen Zeilenumbrüche und Einrückung sowie in Python. Anders als in Python erlaubt YAML keine Tabulator-Zeichen.
YAML ist ein Erweiterung von von JSON mit der Erweiterung um syntaktisch wichtige Zeilenumbrüche und Einrückungen, ähnlich wie auch in Python. Anders als in Python allerdings erlaubt YAML keine Tabulator-Zeichen.
```yaml
# Kommentare in YAML schauen so aus.

View File

@@ -0,0 +1,51 @@
---
category: Algorithms & Data Structures
name: Dynamic Programming
contributors:
- ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
---
# Dynamic Programming
## Introduction
Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see. The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again.
Always remember!
"Those who can't remember the past are condemned to repeat it"
## Ways of solving such Problems
1. *Top-Down* : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization.
2. *Bottom-Up* : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming.
## Example of Dynamic Programming
The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence `S= {a1 , a2 , a3, a4, ............., an-1, an }` we have to find a longest subset such that for all `j` and `i`, `j<i` in the subset `aj<ai`.
First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all `j` such that `j<i` and `aj<ai`, we find Largest LSj and add it to LSi. Then algorithm take *O(n2)* time.
Pseudo-code for finding the length of the longest increasing subsequence:
This algorithms complexity could be reduced by using better data structure rather than array. Storing predecessor array and variable like largest_sequences_so_far and its index would save a lot time.
Similar concept could be applied in finding longest path in Directed acyclic graph.
```python
for i=0 to n-1
LS[i]=1
for j=0 to i-1
if (a[i] > a[j] and LS[i]<LS[j])
LS[i] = LS[j]+1
for i=0 to n-1
if (largest < LS[i])
```
### Some Famous DP Problems
- Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
- Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
## Online Resources
* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)

View File

@@ -14,7 +14,7 @@ Clojure, there are implementations of EDN for many other languages.
The main benefit of EDN over JSON and YAML is that it is extensible. We
will see how it is extended later on.
```Clojure
```clojure
; Comments start with a semicolon.
; Anything after the semicolon is ignored.

View File

@@ -6,28 +6,27 @@ filename: css-gr.html.markdown
lang: el-gr
---
Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
Η αρχική μορφή του Παγκόσμιου Ιστού αποτελείτο απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας
του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα,
γίναν καθημερινότητα.
έγιναν καθημερινότητα.
Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή.
Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ).
```css
/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
/* Τα σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ.
Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */
/* ####################
## ΚΑΝΟΝΕΣ
#################### */
/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector).
/* ένας κανόνας χρησιμοποιείται για να στοχεύσουμε ένα αντικείμενο (selector). */
selector { property: value; /* περισσότερες ιδιότητες...*/ }
/*
Αυτό είναι ενα παράδειγμα αντικειμένου¨
Αυτό είναι ενα παράδειγμα αντικειμένου
<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
*/

858
el-gr/java-gr.html.markdown Normal file
View File

@@ -0,0 +1,858 @@
---
language: java
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
- ["Jakukyo Friel", "http://weakish.github.io"]
- ["Madison Dickson", "http://github.com/mix3d"]
- ["Simon Morgan", "http://sjm.io/"]
- ["Zachary Ferguson", "http://github.com/zfergus2"]
- ["Cameron Schermerhorn", "http://github.com/cschermerhorn"]
- ["Rachel Stiyer", "https://github.com/rstiyer"]
filename: LearnJava-gr.java
translators:
- ["Andreas Loizou" , "https://github.com/lack3r/"]
lang: el-gr
---
H Java είναι μία γενικού-σκοπού, συντρέχων (concurrent), βασισμένη σε κλάσεις,
αντικειμενοστρεφής (object oriented) γλώσσα προγραμματισμού.
[Διαβάστε περισσότερα εδώ.](http://docs.oracle.com/javase/tutorial/java/)
```java
// Τα σχόλια μονής γραμμής ξεκινούν με //
/*
Τα σχόλια πολλών γραμμών μοιάζουν κάπως έτσι.
*/
/**
Τα σχόλια JavaDoc μοιάζουν κάπως έτσι. Χρησιμοποιούνται για να περιγράψουν την
Κλάση ή διάφορα χαρακτηριστικά της Κλάσης.
*/
// Εισαγωγή της κλάσης ArrayList η οποία βρίσκεται εντός του πακέτου java.util
import java.util.ArrayList;
// Εισαγωγή όλων των κλάσεων που βρίσκονται εντός του πακέτου java.security
import java.security.*;
// Κάθε αρχείο .java περιέχει μία δημόσια(public) κλάση εξωτερικού-επιπέδου
// (outer-level), η οποία έχει το ίδιο ονομα με το αρχείο.
public class LearnJava {
// Για να τρέξει ένα πρόγραμμα java, πρέπει να έχει μία κύρια μέθοδο (main
// method) ως αρχικό σημείο.
public static void main (String[] args) {
// Χρησιμοποιούμε τη μέθοδο System.out.println() για να τυπώσουμε
// γραμμές.
System.out.println("Hello World!");
System.out.println(
"Integer: " + 10 +
" Double: " + 3.14 +
" Boolean: " + true);
// Για να τυπώσουμε χωρίς να τυπωθεί αλλαγή γραμμής (newline),
// χρησιμοποιούμε System.out.print().
System.out.print("Hello ");
System.out.print("World");
// Χρησιμοποιούμε τη μέθοδο System.out.printf() για έυκολη μορφοποίηση
// της εκτύπωσης.
System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
///////////////////////////////////////
// Μεταβλητές(Variables)
///////////////////////////////////////
/*
* Δήλωση Μεταβλητών
*/
// Δηλώνουμε μία μεταβλητή χρησιμοποιώντας τη μορφή
// <Τύπος Μεταβλητής> <Όνομα Μεταβλητής>
int fooInt;
// Δηλώνουμε πολλαπλές μεταβλητές ίδιου τύπου χρησιμοποιώντας τη μορφή
// <Τύπος> <Όνομα1>, <Όνομα2>, <Όνομα3>
int fooInt1, fooInt2, fooInt3;
/*
* Αρχικοποίηση Μεταβλητών
*/
// Αρχικοποιούμε μια μεταβλητή χρησιμοποιώντας τη μορφή
// <τύπος> <όνομα> = <τιμή>
int fooInt = 1;
// Αρχικοποιούμε πολλαπλές μεταβλητές ιδίου τύπου με την ίδια τιμή
// χρησιμοποιώντας <τύπος> <Όνομα1>, <Όνομα2>, <Όνομα3> = <τιμή>
int fooInt1, fooInt2, fooInt3;
fooInt1 = fooInt2 = fooInt3 = 1;
/*
* Τύποι μεταβλητών
*/
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
// Short - 16-bit signed two's complement integer
// (-32,768 <= short <= 32,767)
short fooShort = 10000;
// Integer - 32-bit signed two's complement integer
// (-2,147,483,648 <= int <= 2,147,483,647)
int fooInt = 1;
// Long - 64-bit signed two's complement integer
// (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
long fooLong = 100000L;
// Το L χρησιμοποιείται για να δηλώσει ότι η συγκεκριμένη τιμή της
// μεταβλητής είναι τύπου Long;
// Ό,τιδήποτε χρησιμοποιείται χωρίς αυτό τυχαίνει μεταχείρισης όπως
// μία τιμή μεταβλητής integer by default.
// Σημείωση: Η Java δεν έχει unsigned τύπους.
// Float - Single-precision 32-bit IEEE 754 Floating Point
// 2^-149 <= float <= (2-2^-23) * 2^127
float fooFloat = 234.5f;
// f or F χρησιμοποιείται για να δηλώσει ότι η συγκεκριμένη τιμή
// μεταβλητής είναι τύπου float;
// αλλιώς τυγχαίνει μεταχείρισης όπως μία τιμή μεταβλητής double.
// Double - Double-precision 64-bit IEEE 754 Floating Point
// 2^-1074 <= x <= (2-2^-52) * 2^1023
double fooDouble = 123.4;
// Boolean - Αληθής και Ψευδής (true & false)
boolean fooBoolean = true;
boolean barBoolean = false;
// Char - Ένας μόνο χαρακτήρας 16-bit Unicode
char fooChar = 'A';
// Οι μεταβλητές final δεν μπορούν να πάρουν άλλη τιμή
// μετά την αρχικοποίηση τους,
final int HOURS_I_WORK_PER_WEEK = 9001;
// αλλά μπορούν να αρχικοποιηθούν αργότερα.
final double E;
E = 2.71828;
// BigInteger - Immutable αυθαίρετης-ακρίβειας ακέραιος
//
// Ο BigInteger είναι ένας τύπος δεδομένων ο οποίος επιτρέπει στους
// προγραμματιστές να χειρίζονται ακέραιους μεγαλύτερους από 64-bits.
// Οι ακέραιοι αποθηκεύονται ως πίνακας από bytes και τυχαίνουν
// επεξεργασίας χρησιμοποιώντας συναρτήσεις εσωματωμένες στην κλάση
// BigInteger
// Ένας BigInteger μπορεί να αρχικοποιηθεί χρησιμοποιώντας ένα πίνακα
// από bytes ή γραμματοσειρά (string).
BigInteger fooBigInteger = new BigInteger(fooByteArray);
// BigDecimal - Immutable, αυθαίρετης-ακρίβειας, εμπρόσημος (signed)
// δεκαδικός αριθμός
//
// Ένας BigDecimal παίρνει δύο μέρη: Μία αυθαίρετης ακρίβειας,
// ακέραια, unscaled τιμή και μία κλιμάκωση(scale) ως ένα 32-bit
// ακέραιο (integer).
//
// Ο BigDecimal επιτρέπει στον προγραμματιστή να έχει πλήρη έλεγχο
// όσον αφορά τη δεκαδική στρογγυλοποίηση (rounding). Προτείνεται η
// χρήση του BigDecimal με τιμές νομισμάτων και όπου απαιτείται η
// ακριβής δεκαδική ακρίβεια.
//
// Ο BigDecimal μπορεί να αρχικοποιηθεί με int, long, double ή String
// ή με την αρχικοποίηση της unscaled τιμής (BigInteger) και της
// κλίμακας (scale) (int).
BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
// Χρειάζεται να είμαστε προσεκτικοί με τον κατασκευαστή (constructor)
// ο οποίος παίρνει float ή double καθώς η ανακρίβεια του float/double
// θα αντιγραφεί στον BigDecimal.
// Είναι προτιμότερο να χρησιμοποιείται ο κατασκευαστής String (String
// constructor) όταν χρειάζεται ακριβής τιμή.
BigDecimal tenCents = new BigDecimal("0.1");
// Strings - Γραμματοσειρές
String fooString = "My String Is Here!";
// Ο χαρακτήρας \n είναι ένας χαρακτήρας διαφυγής (escaped character)
// ο οποίος ξεκινά μία νέα γραμμή
String barString = "Printing on a new line?\nNo Problem!";
// Ο χαρακτήρας \t είναι ένας χαρακτήρας διαφυγής (escaped character)
// ο οποίος προσθέτει ένα χαρακτήρα tab
String bazString = "Do you want to add a tab?\tNo Problem!";
System.out.println(fooString);
System.out.println(barString);
System.out.println(bazString);
// Πίνακες (Arrays)
// Το μέγεθος του πίνακα πρέπει να αποφασιστεί με την αρχικοποίηση του
// πίνακα
// Οι ακόλουθες μορφές μπορούν να χρησιμοποιηθούν για την δήλωση ενός
// πίνακα
// <Τυπος δεδομένων>[] <Όνομα Μεταβλητής> = new <Τύπος Δεδομένων>[<μέγεθος πίνακα>];
// <Τυπος δεδομένων> <Όνομα Μεταβλητής>[] = new <Τυπος δεδομένων>[<μέγεθος πίνακα>];
int[] intArray = new int[10];
String[] stringArray = new String[1];
boolean boolArray[] = new boolean[100];
// Ακόμη ένας τρόπος για να δηλώσεις (to declare) και να
// αρχικοποιήσεις ένα πίνακα
int[] y = {9000, 1000, 1337};
String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
boolean bools[] = new boolean[] {true, false, false};
// Ευρετηρίαση (indexing) ενός πίνακα - Πρόσβαση (accessing) ενός
// στοιχείου
System.out.println("intArray @ 0: " + intArray[0]);
// Οι πίνακες ξεκινούν από το μηδέν (zero-indexed) και είναι ευμετάβλητοι (mutable).
intArray[1] = 1;
System.out.println("intArray @ 1: " + intArray[1]); // => 1
// Παρόμοια
// ArrayLists - Παρόμοιοι με τους πίνακες με τη διαφορά ότι προσφέρουν
// περισσότερη λειτουργικότητα και το μέγεθος είναι ευμετάβλητο
// (mutable).
// LinkedLists - Υλοποίηση διπλά-συνδεδεμένης λίστας(doubly-linked
// list). Όλες οι λειτουργίες εκτελώνται όπως αναμένεται σε μία διπλά
// συνδεδεμένη (doubly-linked) λίστα.
// Maps - Ένα σύνολο αντικειμένων τα οποία συνδέου (map) κλειδιά (keys)
// σε τιμές (values). Ο Map είναι διεπαφή (interface) και συνεπώς δεν
// μπορεί να συγκεκριμενοποίηθεί (instantiated).
// Ο τύπος των κλειδιών και των τιμών τα οποία συμπεριλαμβάνονται σε
// ένα Map πρέπει να καθοριστεί κατά τη διάρκεια της
// συγκεκριμενοποίησης (instantiation) της κλάσης που υλοποιεί τη
// διεπαφή Map. Κάθε κλειδί (key) μπορεί να συνδεθεί (map) σε μόνο μία
// αντίστοιχη τιμή και κάθε κλειδί μπορεί να εμφανιστεί μόνο μία φορά
// (no duplicates).
// HashMaps - Η κλάση αυτή χρησιμοποιεί ένα πίνακα-κατακερματισμού
// (hashtable) για να υλοποιήσει τη διεπαφή Map. Αυτό επιτρέπει το
// χρόνο εκτέλεσης βασικών λειτουργιών, όπως της get και insert
// στοιχείου να παραμείνει σταθερός (constant) ακόμη και για μεγάλα
// σύνολα (sets.)
///////////////////////////////////////
// Τελεστές (Operators)
///////////////////////////////////////
System.out.println("\n->Operators");
int i1 = 1, i2 = 2; // Συντομογραφία για πολλαπλές δηλώσεις
// Οι αριθμητικοί τελεστές είναι απλοί
System.out.println("1+2 = " + (i1 + i2)); // => 3
System.out.println("2-1 = " + (i2 - i1)); // => 1
System.out.println("2*1 = " + (i2 * i1)); // => 2
System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5
// Υπόλοιπο (Modulo)
System.out.println("11%3 = "+(11 % 3)); // => 2
// Τελεστές σύγκρισης
System.out.println("3 == 2? " + (3 == 2)); // => false
System.out.println("3 != 2? " + (3 != 2)); // => true
System.out.println("3 > 2? " + (3 > 2)); // => true
System.out.println("3 < 2? " + (3 < 2)); // => false
System.out.println("2 <= 2? " + (2 <= 2)); // => true
System.out.println("2 >= 2? " + (2 >= 2)); // => true
// Λογικοί Τελεστές (Boolean)
System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
// Τελεστές πράξεων με bits (Bitwise)!
/*
~ bitwise τελεστής μοναδιαίου συμπληρώματος (Unary bitwise complement)
<< Προσημασμένη ολίσθηση αριστερά (Signed left shift)
>> Προσημασμένη/Αριθμητική ολίσθηση Δεξιά (Signed/Arithmetic right shift)
>>> Μη προσημασμένη/Λογική ολίσθηση δεξιά (Unsigned/Logical right shift)
& Διαδικός τελεστής AND (Bitwise AND)
^ Διαδικός τελεστής XOR (Bitwise exclusive OR)
| Διαδικός τελεστής OR (Bitwise inclusive OR)
*/
// Αυξητικοί τελεστές
int i = 0;
System.out.println("\n->Inc/Dec-rementation");
// Οι τελεστές ++ και -- μειώνουν και αυξάνουν κατά 1 αντίστοιχα.
// Εάν τοποθετητούν πριν τη μεταβλητή, αυξάνουν και μετά επιστρέφουν.
// Μετά τη μεταβλητή επιστρέφουν και μετά αυξάνουν.
System.out.println(i++); // i = 1, τυπώνει 0 (post-increment)
System.out.println(++i); // i = 2, τυπώνει 2 (pre-increment)
System.out.println(i--); // i = 1, τυπώνει 2 (post-decrement)
System.out.println(--i); // i = 0, τυπώνει 0 (pre-decrement)
///////////////////////////////////////
// Δομές ελέγχου (Control Structures)
///////////////////////////////////////
System.out.println("\n->Control Structures");
// Οι δηλώσεις If είναι c-like
int j = 10;
if (j == 10) {
System.out.println("I get printed");
} else if (j > 10) {
System.out.println("I don't");
} else {
System.out.println("I also don't");
}
// Επανάληψη While (While loop)
int fooWhile = 0;
while(fooWhile < 100) {
System.out.println(fooWhile);
// Άυξησε τον μετρητή
// Επανάλαβε 100 φορές, fooWhile 0,1,2...99
fooWhile++;
}
System.out.println("fooWhile Value: " + fooWhile);
// Επανάληψη Do While (Do While Loop)
int fooDoWhile = 0;
do {
System.out.println(fooDoWhile);
// Άυξησε το μετρητή(counter)
// Επανάλαβε 99 times, fooDoWhile 0->99
fooDoWhile++;
} while(fooDoWhile < 100);
System.out.println("fooDoWhile Value: " + fooDoWhile);
// Επανάληψη For (For Loop)
// Δομή επανάληψης for =>
// for(<Αρχική Δήλωση>; <προυπόθεση (conditional)>; <βήμα (step)>)
for (int fooFor = 0; fooFor < 10; fooFor++) {
System.out.println(fooFor);
// Iterated 10 times, fooFor 0->9
}
System.out.println("fooFor Value: " + fooFor);
// Έξοδος από εμφωλευμένη (nested) επανάληψη For με ετικέττα (Label)
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (i == 5 && j ==5) {
break outer;
// δραπετεύει εκτός της εξωτερικής(outer) επανάληψης αντί μόνο της εσωτερικής
}
}
}
// Επανάληψη For Each
// Η επανάληψη for είναι επίσης ικανή να επαναλαμβάνεται τόσο σε
// πίνακες όσο και σε αντικείμενα τα οποία υλοποιούν τη διεπαφή
// Iterable.
int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// Σύνταξη της επανάληψης for each => for (<αντικείμενο> : <iterable>)
// Διαβάζεται ως: Για κάθε αντικείμενο στο iterable
// Σημείωση: ο τύπος του αντικειμένου πρέπει να τεριάζει με τον τύπο του στοιχείου του iterable.
for (int bar : fooList) {
System.out.println(bar);
//Επαναλαμβάνεται 9 φορές και τυπώνει 1-9 σε καινούριες γραμμές
}
// Switch Case
// Ένα switch δουλέυει με byte, short, char, και int τύπους δεδομένων.
// Δουλέυει επίσης με τύπους enumerated (Συζήτηση στους τύπους Enum),
// τη κλάση String, και μερικές ειδικές περιπτώσεις οι οποίες
// περιλαμβάνουν primitive τύπους: Character, Byte, Short, and Integer.
int month = 3;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
default: monthString = "Some other month";
break;
}
System.out.println("Switch Case Result: " + monthString);
// Αρχίζοντας από τη Java 7, switching για Strings δουλεύει έτσι:
String myAnswer = "maybe";
switch(myAnswer) {
case "yes":
System.out.println("You answered yes.");
break;
case "no":
System.out.println("You answered no.");
break;
case "maybe":
System.out.println("You answered maybe.");
break;
default:
System.out.println("You answered " + myAnswer);
break;
}
// Συντομογραφία του Conditional
// Μπορείς να χρησιμοποιήσεις τον τελεστή '?' για γρήγορες αναθέσεις ή
// logic forks. Διαβάζεται ως "Αν η (πρόταση) είναι αληθής,
// χρησιμοποίησε <την πρώτη τιμή>, αλλιώς, χρησιμοποία <την δεύτερη
// τιμή>"
int foo = 5;
String bar = (foo < 10) ? "A" : "B";
System.out.println(bar); // Prints A, because the statement is true
////////////////////////////////////////
// Μετατροπή Τύπων Δεδομένων και Typecasting
////////////////////////////////////////
// Μετατροπή δεδομένων
// Μετατροπή από String σε Integer
Integer.parseInt("123");//returns an integer version of "123"
// Μετατροπή από Integer σε String
Integer.toString(123);//returns a string version of 123
// Για άλλες μετατροπές δες τις ακόλουθες κλάσεις:
// Double
// Long
// String
// Typecasting
// Μπορείς επίσης να κάνεις cast αντικείμενα Java. Υπάρχουν πολλές
// λεπτομέρειες και μερικές πραγματεύονται κάποιες πιο προχωρημένες
// ένοιες. Για δες εδώ:
// http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
///////////////////////////////////////
// Κλάσεις και Συναρτήσεις
///////////////////////////////////////
System.out.println("\n->Classes & Functions");
// (Ο ορισμός της κλάσης Bicycle ακολουθεί)
// Χρησιμοποία το new για να δημιουργήσεις ένα αντικείμενο μίας κλάσης
Bicycle trek = new Bicycle();
// Κλήση μεθόδων του αντικειμένου
trek.speedUp(3); // Πάντοτε πρέπει να χρησιμοποιείς μεθόδους setter
// και getter
trek.setCadence(100);
// Το toString επιστρέφει την αναπαράσταση σε String μορφή του
// αντικειμένου αυτού.
System.out.println("trek info: " + trek.toString());
// Double Brace Initialization
// Η Γλώσσα Java δεν έχει σύνταξη για το πως να δημιουργήσεις static
// Collections με κάποιο εύκολο τρόπο. Συνήθως θα το κάνεις αυτό με
// τον παρακάτω τρόπο:
private static final Set<String> COUNTRIES = new HashSet<String>();
static {
validCodes.add("DENMARK");
validCodes.add("SWEDEN");
validCodes.add("FINLAND");
}
// Αλλά υπάρχει ένας κομψός τρόπος να επιτύχεις το ίδιο πράγμα
// ευκολότερα, χρησιμοποιώντας κάτι το οποίο λέγεται Double Brace
// Initialization.
private static final Set<String> COUNTRIES = new HashSet<String>() {{
add("DENMARK");
add("SWEDEN");
add("FINLAND");
}}
// Η πρώτη αγκύλη δημιουργεί μία νέα AnonymousInnerClass και η
// δεύτερη δηλώνει ένα instance initializer block. Το block
// καλείται όταν η ανώνυμη εσωτερική κλάση δημιουργηθεί.
// Η μέθοδος αύτή δεν δουλεύει μόνο για τις Collections, αλλά για όλες
// τις non-final κλάσεις.
} // Τέλος μεθόδου main
} // Τέλος κλάσης LearnJava
// Μπορείς να κάνεις include άλλες, όχι-δημόσιες (non-public)
// εξωτερικού-επιπέδου (outer-level) κλάσεις σε ένα αρχείο .java, αλλά δεν
// είναι καλή πρακτική. Αντί αυτού, διαχώρησε τις κλάσεις σε ξεχωριστά αρχεία.
// Σύνταξη Δήλωσης Κλάσης (Class Declaration Syntax):
// <public/private/protected> class <class name> {
// // Συμπεριλαμβάνονται πεδία δεδομένων (data fields), κατασκευαστές (constructors), συναρτήσεις (functions) .
// // Οι συναρτήσεις ονομάζονται "μεθόδοι" στη Java.
// }
class Bicycle {
// Πεδία/μεταβλητές της Κλάσης Bicycle
// Public(Δημόσιες): Μπορούν να γίνουν προσβάσιμες από παντού
public int cadence;
// Private(Ιδιωτικές): Προσβάσιμες μόνο εντός της κλάσης
private int speed;
// Protected(Προστατευμένες): Προσβάσιμες από την κλάση και τις υποκλάσεις (subclasses) της
protected int gear;
String name; // Προκαθορισμένο: Προσβάσιμη μόνο εντός του πακέτου
static String className; // Static μεταβλητή κλάσης
// Static block
// H Java δεν υποστηρίζει υλοποίησεις στατικών κατασκευαστών (static
// constructors), αλλά έχει ένα static block το οποίο μπορεί να
// χρησιμοποιηθεί για να αρχικοποιήσει στατικές μεταβλητές (static
// variables). Το block αυτό θα καλεσθεί όταν η κλάση φορτωθεί.
static {
className = "Bicycle";
}
// Οι κατασκευαστές (constructors) είναι ένας τρόπος για δημιουργία κλάσεων
// Αυτός είναι ένας κατασκευαστής (constructor)
public Bicycle() {
// Μπορείς επίσης να καλέσεις άλλο κατασκευαστή:
// this(1, 50, 5, "Bontrager");
gear = 1;
cadence = 50;
speed = 5;
name = "Bontrager";
}
// Αυτός είναι ένας κατασκευαστής ο οποίος δέχεται arguments
public Bicycle(int startCadence, int startSpeed, int startGear,
String name) {
this.gear = startGear;
this.cadence = startCadence;
this.speed = startSpeed;
this.name = name;
}
// Οι μεθόδοι (Methods) συντάσσονται ως ακολούθως:
// <public/private/protected> <return type> <όνομα μεθόδου>(<args>)
// Οι κλάσεις Java συχνά υλοποιούν getters and setters for their fields
// Σύνταξη δήλωσης μεθόδου:
// <Προσδιοριστές πρόσβασης> <τύπος επιστροφής> <όνομα μεθόδου>(<args>)
public int getCadence() {
return cadence;
}
// Οι μεθόδοι void δεν απαιτούν return statement
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void speedUp(int increment) {
speed += increment;
}
public void slowDown(int decrement) {
speed -= decrement;
}
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
//Μέθοδος η οποία επιστρέφει ως String τις τιμές των χαρακτηριστικών του
// αντικειμένου.
@Override // Χρησιμοποιείται, καθώς η συγκεκριμένη μέθοδος κληρονομήθηκε από τη κλάση Object.
public String toString() {
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
" name: " + name;
}
} // Τέλος κλάσης Bicycle
// Η PennyFarthing είναι υποκλάση της Bicycle
class PennyFarthing extends Bicycle {
// (Tα Penny Farthings είναι τα ποδήλατα με τον μεγάλο μπροστινό τροχό.
// Δεν έχουν ταχύτητες.)
public PennyFarthing(int startCadence, int startSpeed) {
// Κάλεσε τον parent constructor χρησιμοποιώντας το super
super(startCadence, startSpeed, 0, "PennyFarthing");
}
// Χρειάζεται να μαρκάρεις τη μέθοδο την οποία κάνεις overriding
// χρησιμοποιώντας ένα @annotation.
// Για να μάθεις περισσότερα σχετικά με το τι είναι οι επισημάνσεις
// (annotations) και τον σκοπό τους δες αυτό:
// http://docs.oracle.com/javase/tutorial/java/annotations/
@Override
public void setGear(int gear) {
gear = 0;
}
}
// Διεπαφές (Interfaces)
// Σύνταξη δήλωσης διεπαφής
// <access-level> interface <interface-name> extends <super-interfaces> {
// // Σταθερές (Constants)
// // Δηλώσεις Μεθόδων (Method declarations)
// }
// Παράδειγμα - Food:
public interface Edible {
public void eat(); // Κάθε κλάση η οποία υλοποιεί τη διεπαφή αυτή πρέπει
// να υλοποιήσει τη συγκεκριμένη μέθοδο.
}
public interface Digestible {
public void digest();
}
// Μπορούμε να δημιουργήσουμε μία κλάση η οποία υλοποιεί και τις δύο αυτές διεπαφές.
public class Fruit implements Edible, Digestible {
@Override
public void eat() {
// ...
}
@Override
public void digest() {
// ...
}
}
// Στην Java, μπορείς να κληρονομήσεις (extend) από μόνο μία κλάση,
// αλλά μπορείς να υλοποιήσεις πολλές διεπαφές. Για παράδειγμα:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
public void InterfaceOneMethod() {
}
@Override
public void InterfaceTwoMethod() {
}
}
// Abstract (Αφηρημένες) Κλάσεις
// Σύνταξη Δήλωσης Abstract Κλάσης
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
// // Σταθερές και μεταβλητές
// // Δηλώσεις μεθόδων
// }
// Μαρκάροντας μία κλάση ως abstract σημαίνει ότι περιέχει abstract μεθόδους
// οι οποίες πρέπει να οριστούν σε μία κλάση παιδί (child class).
// Παρόμοια με τις διεπαφές (interfaces), οι abstract κλάσεις δεν μπορούν να
// γίνουν instantiated, αλλά αντί αυτού πρέπει να γίνει extend και οι abstract
// μεθόδοι πρέπει να οριστούν. Διαφορετικά από τις Διεπαφές, οι abstract
// κλάσεις μπορούν να περιέχουν τόσο υλοποιημένες όσο και abstract μεθόδους.
// Οι μεθόδοι σε μια Διεπαφή δεν μπορούν να έχουν σώμα (δεν είναι υλοποιημένες
// δηλαδή εκτός εάν η μέθοδος είναι στατική και οι μεταβλητές είναι final by
// default αντίθετα απο μία abstract κλάση. Επίσης, οι abstract κλάσεις
// ΜΠΟΡΟΥΝ να έχουν την μέθοδο "main".
public abstract class Animal
{
public abstract void makeSound();
// Οι μεθόδοι μπορούν να έχουν σώμα (body)
public void eat()
{
System.out.println("I am an animal and I am Eating.");
// Σημείωση: Μπορούμε να έχουμε πρόσβαση σε ιδιωτικές (private) μεταβλητές εδώ.
age = 30;
}
// Δεν χρειάζεται να αρχικοποιηθεί, εντούτοις σε ένα interface μία
// μεταβλητή είναι implicitly final και έτσι χρειάζεται να αρχικοποιηθεί
protected int age;
public void printAge()
{
System.out.println(age);
}
// Οι Abstract κλάσεις μπορούν να έχουν συνάρτηση main.
public static void main(String[] args)
{
System.out.println("I am abstract");
}
}
class Dog extends Animal
{
// Σημείωση ότι χρειάζεται να κάνουμε override τις abstract μεθόδους στην
// abstract κλάση.
@Override
public void makeSound()
{
System.out.println("Bark");
// age = 30; ==> ERROR! Το πεδίο age είναι private στο Animal
}
// ΣΗΜΕΙΩΣΗ: Θα πάρεις error εάν χρησιμοποίησεις το
// @Override annotation εδώ, καθώς η java δεν επιτρέπει
// να γίνονται override οι static μεθόδοι.
// Αυτό που γίνεται εδώ ονομάζεται METHOD HIDING.
// Για δες αυτό το εξαιρετικό ποστ στο SO (Stack Overflow): http://stackoverflow.com/questions/16313649/
public static void main(String[] args)
{
Dog pluto = new Dog();
pluto.makeSound();
pluto.eat();
pluto.printAge();
}
}
// Κλάσεις Final
// Σύνταξη δήλωσης μίας Final κλάσης
// <access-level> final <final-class-name> {
// // Σταθερές και μεταβλητές
// // Δήλωση μεθόδων
// }
// Οι κλάσεις Final είναι κλάσεις οι οποίες δεν μπορούν να κληρονομηθούν και
// συνεπώς είναι final child. In a way, final classes are the opposite of
// abstract classes because abstract classes must be extended, but final
// classes cannot be extended.
public final class SaberToothedCat extends Animal
{
// Σημείωση ότι χρειάζεται και πάλι να κάνουμε override τις abstract
// μεθόδους στην abstract κλάση.
@Override
public void makeSound()
{
System.out.println("Roar");
}
}
// Τελικές (Final) μεθόδοι
public abstract class Mammal()
{
// Σύνταξη μίας Final μεθόδου:
// <Προσδιοριστής πρόσβασης (access modifier)> final <τύπος επιστροφής> <Όνομα μεθόδου>(<args>)
// Οι Final μεθόδοι, όπως και οι final κλάσεις δεν μπορούν να γίνουν
// overridden από κλάση παιδί,
// και είναι συνεπώς η τελική υλοποίηση της μεθόδου.
public final boolean isWarmBlooded()
{
return true;
}
}
// Τύποι Enum
//
// Ένας τύπος enum είναι ένας ειδικός τύπος δεδομένων, ο οποίος επιτρέπει σε
// μια μεταβλητή να είναι ένα σύνολο από προκαθορισμένες σταθερές. Η μεταβλητή
// πρέπει να είναι ίση με μία από τις τιμές αυτές που έχουν προκαθοριστεί.
// Επειδή είναι σταθερές, τα ονόματα ενός enum πεδίου γράφονται με κεφαλαίους
// χαρακτήρες. Στην γλώσσα προγραμματισμού Java, ορίζεις ένα τύπο enum
// χρησιμοποιώντας τη δεσμευμένη λέξη enum. Για παράδειγμα, θα μπορούσες να
// καθορίσεις ένα τύπο enum με όνομα days-of-the-week ως:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
// Μπορούμε να χρησιμοποιήσουμε τον enum Day όπως παρακάτω:
public class EnumTest {
// Μεταβλητή Enum
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs(); // => Mondays are bad.
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs(); // => Midweek days are so-so.
}
}
// Οι τύποι Enum είναι πολύ πιο δυνατοί από όσο έχουμε δείξει πιο πάνω.
// Το σώμα του enum (enum body) μπορεί να περιέχει μεθόδους και άλλα πεδία.
// Μπορείς να δεις περισσότερα στο
// https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
```
## Επιπλέων διάβασμα
Οι σύνδεσμοι που παρέχονται εδώ είναι απλά για να κατανοήσεις περισσότερο το θέμα.
Σε προτρύνουμε να ψάξεις στο Google και να βρεις συγκεκριμένα παραδείγματα.
**Eπίσημοι Οδηγοί της Oracle**:
* [Φροντιστήριο εκμάθησης Java από τη Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
* [Τροποποιητές επιπέδου πρόσβασης(Access level modifiers) Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
* [Έννοιες αντικειμενοστραφούς (Object-Oriented) προγραμματισμού](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
* [Κληρονομικότητα (Inheritance)](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
* [Πολυμορφισμός (Polymorphism)](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
* [Αφαιρετικότητα (Abstraction)](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
* [Εξαιρέσεις (Exceptions)](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
* [Διεπαφές (Interfaces)](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
* [Συμβάσεις κώδικα Java (Code Conventions)](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
**Πρακτικές και Φροντιστήρια Online**
* [Learneroo.com - Μάθε Java](http://www.learneroo.com)
* [Codingbat.com](http://codingbat.com/java)
**Βιβλία**:
* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
* [Thinking in Java](http://www.mindview.net/Books/TIJ/)
* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)

View File

@@ -1,7 +1,7 @@
---
language: elisp
contributors:
- ["Bastien Guerry", "http://bzg.fr"]
- ["Bastien Guerry", "https://bzg.fr"]
- ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
filename: learn-emacs-lisp.el
---
@@ -9,8 +9,6 @@ filename: learn-emacs-lisp.el
```scheme
;; This gives an introduction to Emacs Lisp in 15 minutes (v0.2d)
;;
;; Author: Bastien / @bzg2 / http://bzg.fr
;;
;; First make sure you read this text by Peter Norvig:
;; http://norvig.com/21-days.html
;;
@@ -194,7 +192,7 @@ filename: learn-emacs-lisp.el
;; And evaluate it:
(greeting "you")
;; Some function are interactive:
;; Some functions are interactive:
(read-from-minibuffer "Enter your name: ")
;; Evaluating this function returns what you entered at the prompt.
@@ -225,6 +223,8 @@ filename: learn-emacs-lisp.el
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Let's store a list of names:
;; If you want to create a literal list of data, use ' to stop it from
;; being evaluated - literally, "quote" the data.
(setq list-of-names '("Sarah" "Chloe" "Mathilde"))
;; Get the first element of this list with `car':
@@ -301,7 +301,7 @@ filename: learn-emacs-lisp.el
(hello-to-bonjour)
;; Let's colorize the names:
;; Let's boldify the names:
(defun boldify-names ()
(switch-to-buffer-other-window "*test*")
@@ -342,13 +342,4 @@ filename: learn-emacs-lisp.el
;;
;; To read an online introduction to Emacs Lisp:
;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html
;; Thanks to these people for their feedback and suggestions:
;; - Wes Hardaker
;; - notbob
;; - Kevin Montuori
;; - Arne Babenhauserheide
;; - Alan Schmitt
;; - LinXitoW
;; - Aaron Meurer
```

View File

@@ -3,6 +3,7 @@ language: elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Ryan Plant", "https://github.com/ryanplant-au"]
filename: learnelixir.ex
---
@@ -96,6 +97,14 @@ string.
lower..upper = 1..10 # Can use pattern matching on ranges as well
[lower, upper] #=> [1, 10]
# Maps are key-value pairs
genders = %{"david" => "male", "gillian" => "female"}
genders["david"] #=> "male"
# Maps with atom keys can be used like this
genders = %{david: "male", gillian: "female"}
genders.gillian #=> "female"
## ---------------------------
## -- Operators
## ---------------------------
@@ -170,7 +179,7 @@ case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
"This will match and bind `x` to `:two`"
"This will match and bind `x` to `:two` in this clause"
_ ->
"This will match any value"
end
@@ -316,6 +325,14 @@ defmodule MyMod do
IO.inspect(@my_data) #=> 100
end
# The pipe operator |> allows you to pass the output of an expression
# as the first parameter into a function.
Range.new(1,10)
|> Enum.map(fn x -> x * x end)
|> Enum.filter(fn x -> rem(x, 2) == 0 end)
#=> [4, 16, 36, 64, 100]
## ---------------------------
## -- Structs and Exceptions
## ---------------------------
@@ -407,11 +424,28 @@ send pid, {:circle, 2}
# The shell is also a process, you can use `self` to get the current pid
self() #=> #PID<0.27.0>
## ---------------------------
## -- Agents
## ---------------------------
# An agent is a process that keeps track of some changing value
# Create an agent with `Agent.start_link`, passing in a function
# The initial state of the agent will be whatever that function returns
{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
# `Agent.get` takes an agent name and a `fn` that gets passed the current state
# Whatever that `fn` returns is what you'll get back
Agent.get(my_agent, fn colors -> colors end) #=> ["red", "green"]
# Update the agent's state the same way
Agent.update(my_agent, fn colors -> ["blue" | colors] end)
```
## References
* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org)
* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org)
* [Elixir Documentation](http://elixir-lang.org/docs/master/)
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)

View File

@@ -2,6 +2,7 @@
language: Elm
contributors:
- ["Max Goldstein", "http://maxgoldste.in/"]
filename: learnelm.elm
---
Elm is a functional reactive programming language that compiles to (client-side)
@@ -50,18 +51,18 @@ not False -- True
["the", "quick", "brown", "fox"]
[1, 2, 3, 4, 5]
-- The second example can also be written with two dots.
[1..5]
List.range 1 5
-- Append lists just like strings.
[1..5] ++ [6..10] == [1..10] -- True
List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True
-- To add one item, use "cons".
0 :: [1..5] -- [0, 1, 2, 3, 4, 5]
0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5]
-- The head and tail of a list are returned as a Maybe. Instead of checking
-- every value to see if it's null, you deal with missing values explicitly.
List.head [1..5] -- Just 1
List.tail [1..5] -- Just [2, 3, 4, 5]
List.head (List.range 1 5) -- Just 1
List.tail (List.range 1 5) -- Just [2, 3, 4, 5]
List.head [] -- Nothing
-- List.functionName means the function lives in the List module.
@@ -85,7 +86,7 @@ snd ("elm", 42) -- 42
-- Access a field with a dot and the field name.
{ x = 3, y = 7 }.x -- 3
-- Or with an accessor fuction, which is a dot and the field name on its own.
-- Or with an accessor function, which is a dot and the field name on its own.
.y { x = 3, y = 7 } -- 7
-- Update the fields of a record. (It must have the fields already.)
@@ -149,13 +150,14 @@ answer =
42
-- Pass functions as arguments to other functions.
List.map double [1..4] -- [2, 4, 6, 8]
List.map double (List.range 1 4) -- [2, 4, 6, 8]
-- Or write an anonymous function.
List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8]
List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8]
-- You can pattern match in function definitions when there's only one case.
-- This function takes one tuple rather than two arguments.
-- This is the way you'll usually unpack/extract values from tuples.
area (width, height) =
width * height
@@ -178,7 +180,7 @@ fib n =
else
fib (n - 1) + fib (n - 2)
List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
-- Another recursive function (use List.length in real code).
listLength aList =
@@ -309,7 +311,7 @@ import Graphics.Collage as C
-- An incoming port is just a type signature.
port clientID : Int
-- An outgoing port has a defintion.
-- An outgoing port has a definition.
port clientOrders : List String
port clientOrders = ["Books", "Groceries", "Furniture"]
@@ -333,16 +335,16 @@ $ elm repl
-- Packages are identified by GitHub username and repo name.
-- Install a new package, and record it in elm-package.json.
$ elm package install evancz/elm-html
$ elm package install elm-lang/html
-- See what changed between versions of a package.
$ elm package diff evancz/elm-html 3.0.0 4.0.2
$ elm package diff elm-lang/html 1.1.0 2.0.0
-- Elm's package manager enforces semantic versioning, so minor version bumps
-- will never break your build!
```
The Elm language is surprisingly small. You can now look through almost any Elm
source code and have a rough idea of what is going on. However, the possibilties
source code and have a rough idea of what is going on. However, the possibilities
for error-resistant and easy-to-refactor code are endless!
Here are some useful resources.

View File

@@ -183,9 +183,10 @@ is_pet(A) -> false.
% Warning: not all valid Erlang expressions can be used as guard expressions;
% in particular, our `is_cat` and `is_dog` functions cannot be used within the
% guard sequence in `is_pet`'s definition. For a description of the
% expressions allowed in guard sequences, refer to this
% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912)
% of the Erlang reference manual.
% expressions allowed in guard sequences, refer to the specific section
% in the Erlang reference manual:
% http://erlang.org/doc/reference_manual/expressions.html#guards
% Records provide a method for associating a name with a particular element in a
% tuple.

View File

@@ -190,7 +190,7 @@ Para usar el fichero creado en producción, simplemente intercambia `data-main`:
Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub.
### Tópicos no cubiertos en este tutorial
### Temas no cubiertos en este tutorial
* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html)
* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html)
* [Configuración avanzada](http://requirejs.org/docs/api.html#config)

View File

@@ -0,0 +1,171 @@
---
category: Algorithms & Data Structures
name: Asymptotic Notation
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
translators:
- ["Gerson Lázaro", "https://gersonlazaro.com"]
lang: es-es
---
# Notaciones asintóticas
## ¿Qué son?
Las notaciones asintóticas son lenguajes que nos permitan analizar el tiempo de
ejecución de un algoritmo identificando su comportamiento si el tamaño de
entrada para el algoritmo aumenta. Esto también se conoce como la tasa de
crecimiento de un algoritmo. ¿El algoritmo de repente se vuelve increíblemente
lento cuando el tamaño de entrada crece? ¿Tiende a mantener un rápido tiempo de
ejecución a medida que el tamaño de entrada aumenta? La notación asintótica nos
da la capacidad para responder a estas preguntas.
## ¿Hay alternativas que respondan a estas preguntas?
Una manera sería contar el número de operaciones primitivas en diferentes
tamaños de entrada. Aunque esta es una solución válida, la cantidad de trabajo
que esto conlleva, incluso para los algoritmos simples, no justifica su uso.
Otra manera es medir físicamente la cantidad de tiempo que un algoritmo toma
para completar su ejecución dados diferentes tamaños de entrada. Sin embargo,
la exactitud y la relatividad (los tiempos obtenidos sólo serían relativos a la
máquina sobre la cual se calcularon) de este método está ligado a variables
ambientales tales como especificaciones de hardware, capacidad de procesamiento,
etc.
## Tipos de Notación Asintótica
En la primera sección de este documento hemos descrito cómo una notación
asintótica identifica el comportamiento de un algoritmo ante los cambios en el
tamaño de la entrada. Imaginemos un algoritmo como una función f, con tamaño de
entrada n, y f(n) siendo el tiempo de ejecución. Así que para un algoritmo f
dado, con el tamaño de entrada n obtenemos algún tiempo de ejecución resultante
f(n). Esto resulta en un gráfico donde el eje Y es el tiempo de ejecución, el
eje X es el tamaño de la entrada y los puntos en el gráfico son los resultantes
de la cantidad de tiempo para un tamaño de entrada dado.
Puedes etiquetar una función, o un algoritmo, con una notación asintótica de
muchas maneras diferentes. Algunos ejemplos son describir un algoritmo por su
mejor caso, su peor caso, o el caso promedio. Lo más común es analizar un
algoritmo por su peor caso. Por lo general, no se evalúa el mejor caso, porque
no planeas el algoritmo para estas condiciones. Un muy buen ejemplo de esto son
los algoritmos de ordenamiento; específicamente, añadir elementos a un árbol.
El mejor caso para la mayoría de los algoritmos podría ser tan bajo como una
sola operación. Sin embargo, en la mayoría de los casos, el elemento que está
añadiendo tendrá que ser ordenado adecuadamente a través del árbol, lo que
podría significar examinar toda una rama. Este es el peor de los casos, y
para estos casos es que planeamos el algoritmo.
### Tipos de funciones, límites, y simplificación
```
Función logarítmica - log n
Función lineal - an + b
Función cuadrática - an^2 + bn + c
Función polinomicas - an^z + . . . + an^2 + a*n^1 + a*n^0, donde z es constante
Función exponencial - a^n, donde a es constante
```
Estas son algunas clasificaciones de funciones de crecimiento básicos utilizados
en varias notaciones. La lista comienza en la función de crecimiento menor
(logarítmica, el tiempo de ejecución mas rápido) y pasa a la de mayor
crecimiento (exponencial, el tiempo de ejecución mas lento). Observe como al
crecer 'n', o la entrada, en cada una de estas funciones, el resultado aumenta
claramente mucho más rápido en las cuadráticas, polinómicas y exponenciales,
en comparación con las logarítmicas y lineales.
Una anotación muy importante es que en las notaciones que se discutirán debes
hacer tu mejor esfuerzo por utilizar los términos más simples. Esto significa
hacer caso omiso de las constantes y terminos de orden inferior, porque a medida
que el tamaño de entrada (o n en f(n)) aumenta hacia el infinito (límites
matemáticos), los términos y constantes de orden inferior se vuelven de poca o
ninguna importancia. Dicho esto, si tienes constantes que son 2^9001,
o alguna otra cantidad ridícula, inimaginable, te daras cuenta de que la
simplificación sesgará la exactitud de la notación.
Como queremos algo simplificado, vamos a modificarlo un poco...
```
Logarítmico - log n
Lineal - n
Cuandrático - n^2
Polinómico - n^z, donde z es constante
Exponencial - a^n, donde a es constante
```
### O-grande (Big-O)
O-grande (Big-O), comúnmente escrito como O, es una notación asintótica para el
peor caso, o el techo de crecimiento para una función determinada. Si `f (n)`
es el tiempo de ejecución del algoritmo, y `g (n)` es un tiempo de complejidad
arbitraria que relacionas con el algoritmo, entonces `f (n)` es O(g(n)), si por
cualquier constante real c (c > 0), `f (n)` <= `c g(n)` para cada tamaño de
entrada n (n > 0 ).
*Ejemplo 1*
```
f(n) = 3log n + 100
g(n) = log n
```
`f(n)` es O(g(n))?
`3 log n + 100` es O(log n)?
Echemos un vistazo a la definición de O-grande.
```
3log n + 100 <= c * log n
```
¿Hay alguna constante c que satisface esto para todo n?
```
3log n + 100 <= 150 * log n, n > 2 (indefinido en n = 1)
```
¡Sí! La definición de O-grande se cumple, por lo tanto `f (n)` es O(g(n)).
*Ejemplo 2*
```
f(n) = 3*n^2
g(n) = n
```
`f(n)` es O(g(n))?
`3 * n^2` es O(n)?
Echemos un vistazo a la definición de O-grande.
```
3 * n^2 <= c * n
```
¿Hay alguna constante c que satisface esto para todo n?
No, no la hay. `f(n)` no es O(g(n)).
### Big-Omega
Big-Omega, comunmente escrito como Ω, es una notación asintótica para el mejor
caso, o el piso en el crecimiento para una función dada.
`f(n)` es Ω(g(n)), si para cualquier constante real c (c > 0),
`f(n)` es >= `c g(n)` para cualquier tamaño de entrada n (n > 0).
No dudes en dirigirte a los recursos adicionales para ejemplos sobre esto.
O-grande es la notación principal utilizada para la complejidad general de
tiempo algoritmico.
### Notas finales
Es difícil mantener este tipo de tema corto, y sin duda deberias revisar los
libros y recursos en línea en la lista. Entran en mucha mayor profundidad con
definiciones y ejemplos.
## Libros
* [Algoritmos (Algorithms)](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
* [Diseño de algoritmos (Algorithm Design)](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
## Recursos Online
* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf)
* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation)
* [Apuntes Facultad de Ingeniería](https://www.scribd.com/document/317979564/Apuntes-Sobre-Analisis-de-Algoritmos)

View File

@@ -1,5 +1,5 @@
---
language: brainfuck
language: bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]

View File

@@ -0,0 +1,68 @@
---
category: Algorithms & Data Structures
name: Binary Search
contributors:
- ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"]
translators:
- ["Gino Amaury", "https://github.com/ginoamaury"]
lang: es-es
---
# Búsqueda Binaria
## Por qué Búsqueda Binaria?
La búsqueda es uno de los problemas principales en el dominio de la ciencia de la computación. Hoy en dia hay mas de 1 billon de búsquedas por año, y necesitamos tener algoritmos que puedan hacer esto muy rápido. La búsqueda binaria es uno de los algoritmos fundamentales en la ciencia de la computación. Con el fin de explorarlo, vamos a construir por primera vez un esqueleto teórico y lo utilizaremos para implementar el algoritmo apropiadamente.
## Introducción
Un método sencillo para poner en práctica la búsqueda es hacer una búsqueda lineal, pero este método requiere mucho tiempo y este crece linealmente con la cantidad o el número de datos. es decir, empezar desde el elemento a la izquierda de la matriz [] y uno por uno compara x con cada elemento de la matriz [], si x coincide con un elemento, devuelve el índice. Si x no coincide con ninguno de los elementos, devuelve -1.
```
Búsqueda Lineal: O (n) Tiempo lineal
Búsqueda Binaria: O ( log(n) ) Tiempo logarítmico
```
```
def search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
```
## Algoritmo de Búsqueda Binaria
El requisito básico para que la búsqueda binaria funcione es que los datos a buscar deben estar ordenados (en cualquier orden).
### Algo
```
La idea de la búsqueda binaria es usar la información de que la matriz está ordenada y así reducir la complejidad del tiempo a O(Logn). Básicamente ignoramos la mitad de los elementos después de la primera comparación.
1) Compare x con el elemento del medio.
2) si x coincide con el elemento del medio , retornamos el índice del elemento del medio.
3) Si no coincide, si x es mayor que el elemento del medio, entonces x solo puede estar en la mitad derecha justo después del elemento del medio. Así que recurrimos a la mitad derecha.
4) Si no (x es más pequeño) recurrimos a la mitad izquierda.
Siguiendo la implementación recursiva de búsqueda binaria.
```
### Notas finales
Hay otra forma de búsqueda binaria que es muy útil.
## Libros
* [CLRS EN](https://mitpress.mit.edu/books/introduction-algorithms)
* [Algoritmos EN](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X)
* [Diseño de Algoritmos EN](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651)
## Recursos en línea
* [GeeksforGeeks EN](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/)
* [Topcoder Tutorial EN](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)

View File

@@ -1,6 +1,6 @@
---
language: c++
filename: learncpp.cpp
filename: learncpp-es.cpp
contributors:
- ["Steven Basart", "http://github.com/xksteven"]
- ["Matt Kline", "https://github.com/mrkline"]
@@ -392,7 +392,7 @@ void Dog::print() const
Dog::~Dog()
{
cout << "Adiós " << name << "\n";
std::cout << "Adiós " << name << "\n";
}
int main() {

View File

@@ -418,8 +418,18 @@ typedef void (*my_fnp_type)(char *);
## Otras lecturas
Lo mejor que puedes en contrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
Lo mejor que puedes encontrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language). Es *el*
libro de C, escrito por Dennis Ritchie, creador de C y Brian Kernighan. Aún así,
se cuidadoso, es antiguo, contiene algunas inexactitudes, y algunas prácticas
han cambiado.
Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/)
Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/).
Si tienes una pregunta, lee [compl.lang.c Frequently Asked Questions](http://c-faq.com).
Es muy importante utilizar el espaciado y la sangría apropiados y ser coherente
con su estilo de codificación en general. El código legible es mejor que el
código rápido. Para adoptar un buen estilo de codificación, vea el
[Estilo de codificación del kernel Linux] (https://www.kernel.org/doc/Documentation/CodingStyle).
Aparte de eso, Google es tu amigo.

327
es-es/css-es.html Normal file
View File

@@ -0,0 +1,327 @@
---
language: css
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["Geoffrey Liu", "https://github.com/g-liu"]
- ["Connor Shea", "https://github.com/connorshea"]
- ["Deepanshu Utkarsh", "https://github.com/duci9y"]
- ["Brett Taylor", "https://github.com/glutnix"]
- ["Tyler Mumford", "https://tylermumford.com"]
translators:
- ["miky ackerman", "https://github.com/mikyackerman"]
lang: es-es
filename: learncss-es.css
---
Paginas web estan contruidas en HTML, lo cual especifica el contenido de una pagina
CSS(Hoja de Estilos en Cascada) es un lenguaje separado el cual especifica
la **apariencia** de una pagina.
codigo CSS esta hecho de *reglas* estaticas. Cada regla toma uno o mas *selectores* y da *valores* especificos a un numero de *propiedades* visuales. Esas propiedades estan entonces aplicadas a los elementos indicados en una pagina por los selectores
Esta guia ha sido escrita con CSS 2 en mente, la cual es extendida por una nueva caracterica de CSS 3.
**NOTA:** Debido a que CSS produce resultados visuales, para aprenderlo, necesitas
Probar todo en un patio de juegos CSS como [dabblet] (http://dabblet.com/).
El objetivo principal de este artículo es la sintaxis y algunos consejos generales.
## Sintaxis
```css
/* Los comentarios aparecen dentro de un diagonal-asterisco, justo como esta linea
no hay "comentarios en una linea"; este es el unico estilo de comentario.*/
/* ####################
## SELECTORS
#################### */
/* el selector es usado para apuntar a un elemento de la pagina. */
selector { property: value; /* more properties...*/ }
/*
Here is an example element:
<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' />
*/
/* You can target it using one of its CSS classes */
.class1 { }
/* or both classes! */
.class1.class2 { }
/* or its name */
div { }
/* or its id */
#anID { }
/* or using the fact that it has an attribute! */
[attr] { font-size:smaller; }
/* or that the attribute has a specific value */
[attr='value'] { font-size:smaller; }
/* starts with a value (CSS 3) */
[attr^='val'] { font-size:smaller; }
/* or ends with a value (CSS 3) */
[attr$='ue'] { font-size:smaller; }
/* or contains a value in a space-separated list */
[otherAttr~='foo'] { }
[otherAttr~='bar'] { }
/* or contains a value in a dash-separated list, e.g., "-" (U+002D) */
[otherAttr|='en'] { font-size:smaller; }
/* You can combine different selectors to create a more focused selector. Don't
put spaces between them. */
div.some-class[attr$='ue'] { }
/* You can select an element which is a child of another element */
div.some-parent > .class-name { }
/* or a descendant of another element. Children are the direct descendants of
their parent element, only one level down the tree. Descendants can be any
level down the tree. */
div.some-parent .class-name { }
/* Warning: the same selector without a space has another meaning.
Can you guess what? */
div.some-parent.class-name { }
/* You may also select an element based on its adjacent sibling */
.i-am-just-before + .this-element { }
/* or any sibling preceding it */
.i-am-any-element-before ~ .this-element { }
/* There are some selectors called pseudo classes that can be used to select an
element only when it is in a particular state */
/* for example, when the cursor hovers over an element */
selector:hover { }
/* or a link has been visited */
selector:visited { }
/* or hasn't been visited */
selected:link { }
/* or an element is in focus */
selected:focus { }
/* any element that is the first child of its parent */
selector:first-child {}
/* any element that is the last child of its parent */
selector:last-child {}
/* Just like pseudo classes, pseudo elements allow you to style certain parts of
a document */
/* matches a virtual first child of the selected element */
selector::before {}
/* matches a virtual last child of the selected element */
selector::after {}
/* At appropriate places, an asterisk may be used as a wildcard to select every
element */
* { } /* all elements */
.parent * { } /* all descendants */
.parent > * { } /* all children */
/* ####################
## PROPERTIES
#################### */
selector {
/* Units of length can be absolute or relative. */
/* Relative units */
width: 50%; /* percentage of parent element width */
font-size: 2em; /* multiples of element's original font-size */
font-size: 2rem; /* or the root element's font-size */
font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */
font-size: 2vh; /* or its height */
font-size: 2vmin; /* whichever of a vh or a vw is smaller */
font-size: 2vmax; /* or greater */
/* Absolute units */
width: 200px; /* pixels */
font-size: 20pt; /* points */
width: 5cm; /* centimeters */
min-width: 50mm; /* millimeters */
max-width: 5in; /* inches */
/* Colors */
color: #F6E; /* short hex format */
color: #FF66EE; /* long hex format */
color: tomato; /* a named color */
color: rgb(255, 255, 255); /* as rgb values */
color: rgb(10%, 20%, 50%); /* as rgb percentages */
color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */
color: transparent; /* equivalent to setting the alpha to 0 */
color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */
color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */
/* Borders */
border-width:5px;
border-style:solid;
border-color:red; /* similar to how background-color is set */
border: 5px solid red; /* this is a short hand approach for the same */
border-radius:20px; /* this is a CSS3 property */
/* Images as backgrounds of elements */
background-image: url(/img-path/img.jpg); /* quotes inside url() optional */
/* Fonts */
font-family: Arial;
/* if the font family name has a space, it must be quoted */
font-family: "Courier New";
/* if the first one is not found, the browser uses the next, and so on */
font-family: "Courier New", Trebuchet, Arial, sans-serif;
}
```
## Usage
Save a CSS stylesheet with the extension `.css`.
```html
<!-- You need to include the css file in your page's <head>. This is the
recommended method. Refer to http://stackoverflow.com/questions/8284365 -->
<link rel='stylesheet' type='text/css' href='path/to/style.css'>
<!-- You can also include some CSS inline in your markup. -->
<style>
a { color: purple; }
</style>
<!-- Or directly set CSS properties on the element. -->
<div style="border: 1px solid red;">
</div>
```
## Precedence or Cascade
An element may be targeted by multiple selectors and may have a property set on
it in more than once. In these cases, one of the rules takes precedence over
others. Rules with a more specific selector take precedence over a less specific
one, and a rule occurring later in the stylesheet overwrites a previous one
(which also means that if two different linked stylesheets contain rules for an
element and if the rules are of the same specificity, then order of linking
would take precedence and the sheet linked latest would govern styling) .
This process is called cascading, hence the name Cascading Style Sheets.
Given the following CSS:
```css
/* A */
p.class1[attr='value']
/* B */
p.class1 { }
/* C */
p.class2 { }
/* D */
p { }
/* E */
p { property: value !important; }
```
and the following markup:
```html
<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
```
The precedence of style is as follows. Remember, the precedence is for each
**property**, not for the entire block.
* `E` has the highest precedence because of the keyword `!important`. It is
recommended that you avoid its usage.
* `F` is next, because it is an inline style.
* `A` is next, because it is more "specific" than anything else. It has 3
specifiers: The name of the element `p`, its class `class1`, an attribute
`attr='value'`.
* `C` is next, even though it has the same specificity as `B`.
This is because it appears after `B`.
* `B` is next.
* `D` is the last one.
## Media Queries
CSS Media Queries are a feature in CSS 3 which allows you to specify when certain CSS rules should be applied, such as when printed, or when on a screen with certain dimensions or pixel density. They do not add to the selector's specificity.
```css
/* A rule that will be used on all devices */
h1 {
font-size: 2em;
color: white;
background-color: black;
}
/* change the h1 to use less ink on a printer */
@media print {
h1 {
color: black;
background-color: white;
}
}
/* make the font bigger when shown on a screen at least 480px wide */
@media screen and (min-width: 480px) {
h1 {
font-size: 3em;
font-weight: normal;
}
}
```
Media queries can include these features:
`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Most of these features can be prefixed with `min-` or `max-`.
The `resolution` feature is not supported by older devices, instead use `device-pixel-ratio`.
Many smartphones and tablets will attempt to render the page as if it were on a desktop unless you provide a `viewport` meta-tag.
```html
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
</head>
```
## Compatibility
Most of the features in CSS 2 (and many in CSS 3) are available across all
browsers and devices. But it's always good practice to check before using
a new feature.
## Resources
* [CanIUse](http://caniuse.com) (Detailed compatibility info)
* [Dabblet](http://dabblet.com/) (CSS playground)
* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference)
* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference)
## Further Reading
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
* [CSS-Tricks](https://css-tricks.com)

View File

@@ -233,12 +233,21 @@ en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la
compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores
y dispositivos para los que desarrolles.
[QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto.
## Referencias
## Recursos
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com).
* CSS Playground [Dabblet](http://dabblet.com/).
* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS).
* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/).
## Otras lecturas
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/).
* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/).
* [QuirksMode CSS](http://www.quirksmode.org/css/).
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS.
* [CSS-Tricks](https://css-tricks.com).

View File

@@ -0,0 +1,54 @@
---
category: Algorithms & Data Structures
name: Dynamic Programming
contributors:
- ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
translators:
- ["Gino Amaury", "https://github.com/ginoamaury"]
lang: es-es
---
# programación dinámica
## Introducción
La programación dinámica es una técnica poderosa usada para resolver una clase particular de problemas como veremos más adelante. La idea es muy simple, si usted ha solucionado un problema con la entrada dada, entonces , guardaremos el resultado para una futura referencia, con el fin de evitar la solución del mismo problema de nuevo.
Recuerde siempre!!
"Aquellos que no pueden recordar el pasado están condenados a repetirlo"
## Formas de resolver este tipo de problemas
1.) De arriba hacia abajo : Empezamos resolviendo el problema dado descomponiendolo. Si ves que el problema fue resuelto, entonces retorna la respuesta guardada. si no se ha resuelto, resuélvelo y guarda la respuesta. Esto suele ser fácil pensar y muy intuitivo. Esto se conoce como memorización.
2.) De abajo hacia arriba : Analiza el problema y mira el orden en que los subproblemas deben ser resueltos y empieza resolviendo el subproblema más trivial, hacia el problema dado.En este proceso, se garantiza que los subproblemas se resuelven antes de resolver el problema. Esto se conoce como programación dinámica.
## Ejemplo de Programación Dinámica
El problema de la subsecuencia creciente máxima consiste en encontrar la subsecuencia creciente máxima en una secuencia dada . Dada la secuencia S= {a1 , a2 , a3, a4, ............., an-1, an } tenemos que encontrar un subconjunto más largo tal que para todo j y i, j <i en el subconjunto aj <ai.
En primer lugar tenemos que encontrar el valor de las subsecuencias más largas (LSI) en cada índice con el último elemento de la secuencia que es ai. El mayor LSi sería la subsecuencia más larga de la secuencia dada. Para empezar LSI es asignado a uno ya que ai es un elemento de la secuencia(El último elemento).Entonces, para todo j tal que j <i aj <ai, nos encontramos con Lsj más grande y lo agregamos a la LSI. A continuación, el algoritmo toma un tiempo de O (n2).
Pseudocódigo para encontrar la longitud de la más larga subsecuencia creciente:
La complejidad de este algoritmos podría reducirse mediante el uso de una mejor estructura de datos en lugar de una array. Almacenamiento de una matriz predecesora y una variable como Secuencia_mas_Grande_hasta_ahora y su índice podría ahorrar mucho tiempo.
concepto similar se podría aplicar en encontrar el camino más largo de grafo acíclico dirigido.
---------------------------------------------------------------------------
for i=0 to n-1
LS[i]=1
for j=0 to i-1
if (a[i] > a[j] and LS[i]<LS[j])
LS[i] = LS[j]+1
for i=0 to n-1
if (largest < LS[i])
### Algunos problemas famosos de Programación Dinámica (DP).
```
Algoritmo Floyd Warshall(EN) - Tutorial y código fuente del programa en C:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code
Problema de la Mochila(EN) - Tutorial y código fuente del programa en C: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem
Problema de Subsecuencia Común mas Larga(EN) - Tutorial y código fuente del programa en C : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence
## Recursos en línea
* [codechef EN](https://www.codechef.com/wiki/tutorial-dynamic-programming)

111
es-es/edn-es.html.markdown Normal file
View File

@@ -0,0 +1,111 @@
---
language: edn
filename: learnedn-es.edn
contributors:
- ["Jason Yeo", "https://github.com/jsyeo"]
translators:
- ["Gino Amaury", "https://github.com/ginoamaury"]
lang: es-es
---
La notación de datos extensible (Extensible Data Notation (EDN)) es un formato para serializar los datos.
La notación se utiliza internamente por Clojure para representar programas. También es
utilizado como un formato de transferencia de datos como JSON. A pesar de que se utiliza más comúnmente en
Clojure, existen implementaciones de EDN para muchos otros lenguajes.
El principal beneficio de EDN sobre JSON y YAML es que es extensible.
Vamos a ver cómo se extiende más adelante.
```clojure
; Los comentarios comienzan con un punto y coma.
; Cualquier cosa después del punto y coma es ignorado.
;;;;;;;;;;;;;;;;;;;
;;;Tipos Básicos;;;
;;;;;;;;;;;;;;;;;;;
nil ; También conocido en otros lenguajes como nulo (null).
; Booleanos
true
false
; Las cadenas se encierran entre comillas dobles
"desayuno húngaro"
"tortilla de queso del granjero"
; Los caracteres están precedidos por barras invertidas
\g \r \a \c \e
; Las palabras claves comienzan con dos puntos.Se comportan como las enumeraciones. Más o menos
; Como símbolos en Ruby
:huevos
:queso
:aceitunas
; Los símbolos se utilizan para representar los identificadores.Estos empiezan con #.
; puedes tener espacios usando el símbolo /. cualquier cosa precedida / es
; un espacio en el nombre.
#cuchara
#cocina/cuchara ; no es lo mismo que #spoon
#cocina/tenedor
#github/tenedor ; no se puede comer con este.
; Números enteros y flotantes
42
3.14159
; Las listas son secuencias de valores.
(:bollo :empanada-de-res 9 "yum!")
; Vectores permiten acceso aleatorio
[:helado 1 2 -2]
; Los mapas son estructuras de datos asociativos que se asocian con la clave de su valor.
{:huevos 2
:jugo-de-limon 3.5
:mantequilla 1}
; Usted no está restringido a usar palabras clave como claves.
{[1 2 3 4] "decirle a la gente lo que llevaba",
[5 6 7 8] "Entre mas tu ves, mas lo odias"}
; Puede usar comas para facilitar la lectura. Se tratan como espacios en blanco.
; Los conjuntos son colecciones que contienen elementos únicos.
#{:a :b 88 "huat"}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;Elementos de etiqueta ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; EDN puede ser extendido por elementos de etiqueta con el símbolo #.
#MyYelpClone/MenuItem {:nombre "huevos-Benedict" :clasificacion 10}
; Permíteme explicar esto con un ejemplo en colujre. Supongamos que quiero
; transformar ese pedazo de EDN en un registro del Menú.
(defrecord MenuItem [nombre clasificacion])
; Para transformar EDN en valores clojure, necesitaremos usar el constructor en EDN
; lectura, edn/read-string
(edn/read-string "{:huevos 2 :mantequilla 1 :harina 5}")
; -> {:huevos 2 :mantequilla 1 :harina 5}
; Para transformar los elementos de etiqueta, definir la función de lectura y pasar un mapa
; que asigna etiquetas a funciones del lector de edn/read-string al igual que.
(edn/read-string {:lectores {'MyYelpClone/MenuItem map->menu-item}}
"#MyYelpClone/MenuItem {:nombre \"huevos-benedict\" :clasificacion 10}")
; -> #user.MenuItem{:nombre "huevos-benedict", :clasificacion 10}
```
# Referencias
- [EDN spec (EN)](https://github.com/edn-format/edn)
- [Implementations (EN)](https://github.com/edn-format/edn/wiki/Implementations)
- [Tagged Elements (EN)](http://www.compoundtheory.com/clojure-edn-walkthrough/)

View File

@@ -0,0 +1,457 @@
---
language: elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Ryan Plant", "https://github.com/ryanplant-au"]
translator:
- ["Adrian Carrascal", "https://github.com/acarrascalgarcia"]
filename: learnelixir-es.ex
lang: es-es
---
Elixir es un lenguaje funcional moderno construido sobre la máquina virtual de Erlang.
Es completamente compatibe con Erlang, sin embargo, ofrece una sintaxis más estandar
y otras características más.
```elixir
# Los comentarios de única línea
# comienzan con un símbolo numérico.
# No hay comentarios multilinea,
# pero se pueden apilar varios comentarios.
# Para usar el shell de elixir se usa el comando `iex`.
# Los módulos se compilan con el comando `elixirc`.
# Ambos deberían estar en la ruta si elixir se instaló correctamente.
## ---------------------------
## -- Tipos básicos
## ---------------------------
# Hay números
3 # integer
0x1F # integer
3.0 # float
# Átomos, que son literales, una constante con nombre. Comienzan con `:`.
:hello # atom
# Tuples that are stored contiguously in memory.
# Tuplas que se almacenan contiguamente en memoria.
{1,2,3} # tuple
# Se puede acceder a un elemento de una tupla con la función `elem`:
elem({1, 2, 3}, 0) #=> 1
# Listas que se implementan como listas enlazadas.
[1,2,3] # list
# Se puede acceder al primer y último elemento de la lista como:
[head | tail] = [1,2,3]
head #=> 1
tail #=> [2,3]
# En elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
# no una asignación.
#
# This is how the above example of accessing the head and tail of a list works.
# Así es como el ejemplo anterior de acceder al
# primer y último elemento de una lista trabaja.
# Una coincidencia de patrón errará cuando los lados no coincidan, en este ejemplo
# las tuplas tienen diferentes tamaños.
# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
# También hay binarios
<<1,2,3>> # binary
# Cadenas y listas de caracteres
"hello" # string
'hello' # char list
# Cadenas de varias lineas
"""
I'm a multi-line
string.
"""
#=> "I'm a multi-line\nstring.\n"
# Todas las cadenas se codifican en UTF-8:
"héllò" #=> "héllò"
# Las cadenas son solo binarios realmente, y la lista de caracteres solo listas.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
# `?a` en elixir devuelve el valor ASCII para el caracter `a`
?a #=> 97
# Para concatenar listas se usa `++`, para binarios `<>`
[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
'hello ' ++ 'world' #=> 'hello world'
<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
"hello " <> "world" #=> "hello world"
# Los rangos se representan como `start..end` (Es inclusivo)
1..10 #=> 1..10
lower..upper = 1..10 # Se puede usar la coincidencia de patrones en los rangos también
[lower, upper] #=> [1, 10]
# Los mapas son pares de llave-valor
genders = %{"david" => "male", "gillian" => "female"}
genders["david"] #=> "male"
# Los mapas con llaves de tipo átomo se pueden usar como esto
genders = %{david: "male", gillian: "female"}
genders.gillian #=> "female"
## ---------------------------
## -- Opetadores
## ---------------------------
# Aritméticos
1 + 1 #=> 2
10 - 5 #=> 5
5 * 2 #=> 10
10 / 2 #=> 5.0
# En elixir el operador `/` siempre devuelve un número flotante
# Para hacer la división de número entero se debe usar `div`
div(10, 2) #=> 5
# Para obtener el residuo de la división se debe usar `rem`
rem(10, 3) #=> 1
# También hay operadores lógicos: `or`, `and` y `not`.
# Estos operadores esperan un boolean como su primer argumento.
true and true #=> true
false or true #=> true
# 1 and true #=> ** (ArgumentError) argument error
# Elixir también provee `||`, `&&` y `!` donde acepta argumentos de cualquier tipo.
# Todos los valores excepto `false` y `nil` se evaluarán como verdadero.
1 || true #=> 1
false && 1 #=> false
nil && 20 #=> nil
!true #=> false
# Para comparaciones se tiene: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` y `>`
1 == 1 #=> true
1 != 1 #=> false
1 < 2 #=> true
# `===` y `!==` son más estrictos cuando comparan números:
1 == 1.0 #=> true
1 === 1.0 #=> false
# También se puede comparar dos tipos de datos diferentes:
1 < :hello #=> true
# No se necesita memorizar el orden pero es importante tenerlo en cuenta:
# number < atom < reference < functions < port < pid < tuple < list < bit string
## ---------------------------
## -- Control de flujo
## ---------------------------
# Expresión `if`
if false do
"This will never be seen"
else
"This will"
end
# También está la expresión `unless`
unless true do
"This will never be seen"
else
"This will"
end
# Se acuerda de la coincidencia de patrones?
# Muchas estructuras de control de flujo en elixir confían en ella.
# `case` permite comparar un valor con muchos patrones:
case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
"This will match and bind `x` to `:two` in this clause"
_ ->
"This will match any value"
end
# Es común vincular el valor a `_` si no se necesita.
# Por ejemplo, si unicamente el primer elemento de la lista es importante:
[head | _] = [1,2,3]
head #=> 1
# Para una mejor lectura se puede hace lo siguiente:
[head | _tail] = [:a, :b, :c]
head #=> :a
# `cond` permite comprobar muchas condiciones al mismo tiempo.
# Usar `cond` en vez de muchas expresiones `if` anidadas.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
1 + 2 == 3 ->
"But I will"
end
# Es común estabecer la última condición como `true`, donde siempre va a coincidir.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
true ->
"But I will (this is essentially an else)"
end
# `try/catch` se usa para atrapar valores que se lanzan, también soporta una
# clausula `after` que se invoca sin importar si un valor se atrapó o no.
try do
throw(:hello)
catch
message -> "Got #{message}."
after
IO.puts("I'm the after clause.")
end
#=> I'm the after clause
# "Got :hello"
## ---------------------------
## -- Módulos y Funciones
## ---------------------------
# Anonymous functions (notice the dot)
# Funciones anónimas (Ver el punto `.`)
square = fn(x) -> x * x end
square.(5) #=> 25
# También aceptan muchas cláusulas y guards.
# Los guards permiten afinar las coincidencias de patrones,
# se indican por la palabra reservada `when`:
f = fn
x, y when x > 0 -> x + y
x, y -> x * y
end
f.(1, 3) #=> 4
f.(-1, 3) #=> -3
# Elixir también provee muchas funciones incorporadas.
# Esas están disponibles en el ámbito actual.
is_number(10) #=> true
is_list("hello") #=> false
elem({1,2,3}, 0) #=> 1
# Se pueden agrupar varias funciones en un módulo. Dentro de un módulo
# se usa `def` para definir las funciones.
defmodule Math do
def sum(a, b) do
a + b
end
def square(x) do
x * x
end
end
Math.sum(1, 2) #=> 3
Math.square(3) #=> 9
# Para compilar el módulo simple de Math se guarda como `math.ex` y se usa `elixirc`
# en la terminal: elixirc math.ex
# Dentro de un módulo se puede definir funciones con `def` y funciones privadas con `defp`.
# Una función definida con `def` está disponible para ser invocada desde otros módulos,
# una función privada se puede solo invocar localmente.
defmodule PrivateMath do
def sum(a, b) do
do_sum(a, b)
end
defp do_sum(a, b) do
a + b
end
end
PrivateMath.sum(1, 2) #=> 3
# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
# La declaración de funciones también soportan guards y múltiples cláusulas:
defmodule Geometry do
def area({:rectangle, w, h}) do
w * h
end
def area({:circle, r}) when is_number(r) do
3.14 * r * r
end
end
Geometry.area({:rectangle, 2, 3}) #=> 6
Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
# Debido a la inmutabilidad, la recursión es una gran parte de elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
end
def sum_list([], acc) do
acc
end
end
Recursion.sum_list([1,2,3], 0) #=> 6
# Los módulos de Elixir soportan atributos, hay atributos incorporados y
# se pueden agregar otros personalizados.
defmodule MyMod do
@moduledoc """
This is a built-in attribute on a example module.
"""
@my_data 100 # This is a custom attribute.
IO.inspect(@my_data) #=> 100
end
# El operador pipe |> permite que se pase la salida de una expresión
# como el primer parámetro en una función.
Range.new(1,10)
|> Enum.map(fn x -> x * x end)
|> Enum.filter(fn x -> rem(x, 2) == 0 end)
#=> [4, 16, 36, 64, 100]
## ---------------------------
## -- Structs and Excepciones
## ---------------------------
# Los Structs son extensiones de los mapas que traen valores por defecto,
# garantes en tiempo de compilación y polimorfismo en Elixir.
defmodule Person do
defstruct name: nil, age: 0, height: 0
end
joe_info = %Person{ name: "Joe", age: 30, height: 180 }
#=> %Person{age: 30, height: 180, name: "Joe"}
# Acceder al valor de name
joe_info.name #=> "Joe"
# Actualizar el valor de age
older_joe_info = %{ joe_info | age: 31 }
#=> %Person{age: 31, height: 180, name: "Joe"}
# El bloque `try` con la palabra reservada `rescue` se usa para manejar excepciones
try do
raise "some error"
rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
#=> "rescued a runtime error"
# Todas las excepciones tienen un mensaje
try do
raise "some error"
rescue
x in [RuntimeError] ->
x.message
end
#=> "some error"
## ---------------------------
## -- Concurrencia
## ---------------------------
# Elixir confía en el modelo actor para la concurrencia. Todo lo que se necesita para escribir
# programas concurrentes en elixir son tres primitivas: procesos de desove,
# envío de mensajes y recepción de mensajes.
# Para empezar un nuevo proceso se usa la función `spawn`,
# donde toma una función como argumento.
f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
spawn(f) #=> #PID<0.40.0>
# `spawn` devuelve un pid (identificador de proceso), se puede usar este pid para enviar
# mensajes para el proceso. Para hacer que un mensaje pase se usa el operador `send`.
# Para que todo esto se útil se necesita estar disponibles para recibir mensajes. Esto se
# alcanza con el mecanismo `receive`:
# El bloque `receive do` se usa para escuchar los mensajes y procesarlos
# cuando se reciben. Un bloque `receive do` solo procesará
# un mensaje recibido. Para procesar múltiples mensajes,
# una función con un bloque `receive do` tiene que llamarse recursivamente
# para entrar en el bloque `receive do` otra vez.
defmodule Geometry do
def area_loop do
receive do
{:rectangle, w, h} ->
IO.puts("Area = #{w * h}")
area_loop()
{:circle, r} ->
IO.puts("Area = #{3.14 * r * r}")
area_loop()
end
end
end
# Compilar el módulo y crear un proceso que evalue `area_loop` en el shell
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
# Como alternativa
pid = spawn(Geometry, :area_loop, [])
# Enviar un mensaje al `pid` que coincidirá con un patrón en el que recibe una sentencia
send pid, {:rectangle, 2, 3}
#=> Area = 6
# {:rectangle,2,3}
send pid, {:circle, 2}
#=> Area = 12.56000000000000049738
# {:circle,2}
# El shell también es un proceso, se puede usar `self` para obtener el pid actual
self() #=> #PID<0.27.0>
## ---------------------------
## -- Agentes
## ---------------------------
# Un agente es un proceso que mantiene el seguimiento de algún valor cambiante
# Un agente se crea con `Agent.start_link`, introducuendole una función
# El estado inicial del agente será lo que sea que la función devuelva
{ok, my_agent} = Agent.start_link(fn -> ["red, green"] end)
# `Agent.get` toma un nombre de agente y un `fn` que se pasa como el estado actual
# Lo que sea que este `fn` devuelva es lo que se obtendrá de vuelta
Agent.get(my_agent, fn colors -> colors end) #=> ["red, "green"]
# El estado del agente se actualiza de la misma manera
Agent.update(my_agent, fn colors -> ["blue" | colors] end)
```
## Referencias
* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org)
* [Elixir Documentation](http://elixir-lang.org/docs/master/)
* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas
* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert
* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong

View File

@@ -0,0 +1,226 @@
---
language: forth
contributors:
- ["Horse M.D.", "http://github.com/HorseMD/"]
translators:
- ["Zach Larsen", "http://zachariahlarsen.com/"]
lang: es-es
filename: learnforth-es.fs
---
Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativo, basado en pila y entorno de programación, siendo usado en proyectos como Open Firmware. También esta usado por NASA.
Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo
de lo que esta escrito aquí debe funcionar en otro sitio.
```
\ Este es un comentario
( Este es un comentario también pero solo esta usado cuando definiendo palabras. )
\ --------------------------------- Precursor ----------------------------------
\ Todo programación en Forth se hace manipulando el parámetro pila (mas
\ común se refiere como "el pila").
5 2 3 56 76 23 65 \ ok
\ estos números se añadieron al pila desde izquierda a derecho.
.s \ <7> 5 2 3 56 76 23 65 ok
\ En Forth, todo es o una palabra o un numero.
\ ------------------------------ Básico Aritmética ------------------------------
\ Aritmética (de hecho casi todas palabras que requieren datos) funciona manipulando datos
\ en el pila.
5 4 + \ ok
\ `.` saca lo alto resulto desde el pila:
. \ 9 ok
\ Mas ejemplos de aritmética:
6 7 * . \ 42 ok
1360 23 - . \ 1337 ok
12 12 / . \ 1 ok
13 2 mod . \ 1 ok
99 negate . \ -99 ok
-99 abs . \ 99 ok
52 23 max . \ 52 ok
52 23 min . \ 23 ok
\ ----------------------------- Pila Manipulación -----------------------------
\ Naturalmente, cuando trabajaremos con el pila, querremos algunos metidos útiles:
3 dup - \ duplicar el primero articulo (1ra ahora igual a 2da): 3 - 3
2 5 swap / \ intercambiar la primera con la segunda elemento: 5 / 2
6 4 5 rot .s \ rotar los tres primero elementos: 4 5 6
4 0 drop 2 / \ sacar el primero articulo (no imprima a la pantalla): 4 / 2
1 2 3 nip .s \ sacar el segundo articulo (similar a drop): 1 3
\ ---------------------- Mas Avanzado Pila Manipulación ----------------------
1 2 3 4 tuck \ duplicar el primero articulo en el segundo hueco: 1 2 4 3 4 ok
1 2 3 4 over \ duplicar el segundo articulo a la primera del pila: 1 2 3 4 3 ok
1 2 3 4 2 roll \ *mover* el articulo en este posición a la primera del pila: 1 3 4 2 ok
1 2 3 4 2 pick \ *duplicar* el articulo en este posición a la primera del pila: 1 2 3 4 2 ok
\ Cuando refiere a pila indices, ellos son basado en cero.
\ ------------------------------ Creando Palabras --------------------------------
\ La `:` palabra hace que Forth entra modo de compilar hasta que se ve la `;` palabra.
: cuadrado ( n -- n ) dup * ; \ ok
5 cuadrado . \ 25 ok
\ Podemos ver lo que hace una palabra también.:
see cuadrado \ : cuadrado dup * ; ok
\ -------------------------------- Condicionales --------------------------------
\ -1 == cierto, 0 == falso. No obstante, valores que no son cero es usualmente tratado como
\ siendo cierto:
42 42 = \ -1 ok
12 53 = \ 0 ok
\ `if` es una palabra que solamente compila. `if` <cosas para hacer> `then` <los de mas del programa>.
: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" then ; \ ok
100 ?>64 \ Mas que 64! ok
\ Else:
: ?>64 ( n -- n ) dup 64 > if ." Mas que 64!" else ." Menos que 64!" then ;
100 ?>64 \ Mas que 64! ok
20 ?>64 \ Menos que 64! ok
\ ------------------------------------ Loops -----------------------------------
\ `do` también es una palabra que solamente compila.
: miloop ( -- ) 5 0 do cr ." Hola!" loop ; \ ok
miloop
\ Hola!
\ Hola!
\ Hola!
\ Hola!
\ Hola! ok
\ `do` espera dos números en el pila: el último numero y el primero numero.
\ Podemos recibir el valor del indice mientras damos vuelta con `i`:
: uno-a-12 ( -- ) 12 0 do i . loop ; \ ok
uno-a-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
\ `?do` funciona similarmente, pero salta el loop si el último y primero
\ números son iguales.
: cuadrados ( n -- ) 0 ?do i cuadrado . loop ; \ ok
10 cuadrado \ 0 1 4 9 16 25 36 49 64 81 ok
\ cambiar el "paso" con `+loop`:
: treces ( n n -- ) ?do i . 3 +loop ; \ ok
15 0 treces \ 0 3 6 9 12 ok
\ Indefinido loops empiezan `begin` <cosas para hacer> <bandera> `until`:
: death ( -- ) begin ." Ya hemos llegado?" 0 until ; \ ok
\ ---------------------------- Variables y Memoria ----------------------------
\ Use `variable` declarar `edad` ser un variable.
variable edad \ ok
\ Ahora escribimos 21 a edad con la palabra `!`.
21 edad ! \ ok
\ Por fin podemos imprimir nuestro variable usando la "leer" palabra `@`, que agregue el
\ valor a la pila, or usa `?` que lee y imprime todo juntos.
edad @ . \ 21 ok
edad ? \ 21 ok
\ Constantes son muy similar, pero no nos importa los direcciones de memoria:
100 constant PUNTA-QUE-AQUA-HIERVA \ ok
PUNTA-QUE-AQUA-HIERVA . \ 100 ok
\ ----------------------------------- Arrays -----------------------------------
\ Creando arrays es similar a variables, pero necesitamos alocar mas
\ memoria a ellos.
\ Puede usar `2 cells allot` para crear un array que es sea 3 cédulas de tamaño:
variable minumeros 2 cells allot \ ok
\ Inicializar todos los valores a 0
minumeros 3 cells erase \ ok
\ Alternativamente podemos usar `fill`:
minumeros 3 cells 0 fill
\ o podemos saltar todo arriba y inicializar con valores específicos:
create minumeros 64 , 9001 , 1337 , \ ok (el último `,` es importante!)
\ ...que es equivalente a:
\ Manualmente escribiendo valores a cada indice:
64 minumeros 0 cells + ! \ ok
9001 minumeros 1 cells + ! \ ok
1337 minumeros 2 cells + ! \ ok
\ Leyendo valores en particular array indices:
0 cells minumeros + ? \ 64 ok
1 cells minumeros + ? \ 9001 ok
\ Podemos simplificar un poco cuando hacemos una palabra que ayuda cuando manipulando arrays:
: de-arr ( n n -- n ) cells + ; \ ok
minumeros 2 de-arr ? \ 1337 ok
\ Que podemos usar cuando escribimos también:
20 minumeros 1 de-arr ! \ ok
minumeros 1 de-arr ? \ 20 ok
\ ------------------------------ El Pila de Regreso ------------------------------
\ El pila de regreso se usa para retener punteros a cosas cuando palabras están
\ ejecutando otras palabras como loops.
\ Ya hemos visto un uso de esto: `i`, que duplica el primero del pila
\ de regreso. `i` es equivalente a `r@`.
: miloop ( -- ) 5 0 do r@ . loop ; \ ok
\ También como leyendo, podemos agregar al pila de regreso y sacarlo:
5 6 4 >r swap r> .s \ 6 5 4 ok
\ NOTA: Porque Forth usa el pila de regreso por punteros de palabras, `>r` debe
\ siempre ser seguido por un `r>`.
\ ------------------------- Flotante Punto Operaciones --------------------------
\ La mayoría Forths evitan el uso de flotante punto operaciones.
8.3e 0.8e f+ f. \ 9.1 ok
\ Usualmente agregamos al frente palabras con 'f' cuando usando flotantes:
variable miflotantevar \ ok
4.4e miflotantevar f! \ ok
miflotantevar f@ f. \ 4.4 ok
\ --------------------------------- Notas al Final --------------------------------
\ Usando una palabra que no existe vaciara el pila. No obstante, también hay una palabra
\ específicamente por esto:
clearstack
\ vaciar la pantalla:
page
\ Cargando Forth archivos:
\ s" archivodeforth.fs" included
\ Puede listar cada palabra en el diccionario de Forth (pero es una lista gigante!):
\ words
\ Terminando Gforth:
\ bye
```
##Listo Para Mas?
* [Starting Forth](http://www.forth.com/starting-forth/)
* [Simple Forth](http://www.murphywong.net/hello/simple.htm)
* [Thinking Forth](http://thinking-forth.sourceforge.net/)

View File

@@ -398,6 +398,10 @@ $ git rm /directorio/del/archivo/FooBar.c
* [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1)
* [Udemy tutorial de Git: Una guía completa](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
* [Inmersión Git - Una visita guiada caminando a través de los fundamentos de git](http://gitimmersion.com/)
* [git-scm - Video-tutoriales](http://git-scm.com/videos)
* [git-scm - Documentacion](http://git-scm.com/book/es)
@@ -407,3 +411,9 @@ $ git rm /directorio/del/archivo/FooBar.c
* [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
* [GitGuys](http://www.gitguys.com/)
* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html)
* [Pro Git](http://www.git-scm.com/book/en/v2)
* [Una introducción a Git y Github para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners)

View File

@@ -0,0 +1,434 @@
---
language: Groovy
contributors:
- ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
translators:
- ["Jhoon Saravia", "https://github.com/jhoon"]
lang: es-es
filename: groovy-es.html
---
Groovy - Un lenguaje dinámico para la plataforma Java [Leer más aquí.](http://www.groovy-lang.org/)
```groovy
/*
Hora de configurar:
1) Instala GVM - http://gvmtool.net/
2) Instala Groovy: gvm install groovy
3) Inicia la consola de groovy escribiendo: groovyConsole
*/
// Los comentarios de una sola línea inician con dos barras inclinadas
/*
Los comentarios multilínea se ven así.
*/
// Hola Mundo
println "Hola mundo!"
/*
Variables:
Puedes asignar valores a variables para usarlas después
*/
def x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x
x = false
println x
x = "Groovy!"
println x
/*
Mapas y Colecciones
*/
// Creando una lista vacía
def technologies = []
/*** Agregando elementos a la lista ***/
// Como si fuera Java
technologies.add("Grails")
// Doble símbolo de menor agrega un elemento y, además, retorna la lista
technologies << "Groovy"
// Agregando múltiples elementos
technologies.addAll(["Gradle","Griffon"])
/*** Quitando elementos de la lista ***/
// Como si fuera Java
technologies.remove("Griffon")
// La resta también funciona
technologies = technologies - 'Grails'
/*** Iterando Listas ***/
// Para iterar sobre los elementos de una Lista
technologies.each { println "Technology: $it"}
technologies.eachWithIndex { it, i -> println "$i: $it"}
/*** Revisando los contenidos de una Lista ***/
// Evaluar si la lista contiene elemento(s) (boolean)
contained = technologies.contains( 'Groovy' )
// O
contained = 'Groovy' in technologies
// Evaluar por múltiples contenidos
technologies.containsAll(['Groovy','Grails'])
/*** Ordenando Listas ***/
// Para ordenar una Lista (modifica la lista original)
technologies.sort()
// Para ordenarla sin modificar la original, se puede hacer:
sortedTechnologies = technologies.sort( false )
/*** Manipulando Listas ***/
// Reemplazar todos los elementos en la lista
Collections.replaceAll(technologies, 'Gradle', 'gradle')
// Mezclar una lista
Collections.shuffle(technologies, new Random())
// Limpiar una lista
technologies.clear()
// Creando un mapa vacío
def devMap = [:]
// Agregando valores
devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
devMap.put('lastName','Perez')
// Iterar sobre los elementos del mapa
devMap.each { println "$it.key: $it.value" }
devMap.eachWithIndex { it, i -> println "$i: $it"}
// Evaluar si el mapa contiene una llave
assert devMap.containsKey('name')
// Evaluar si el mapa contiene un valor
assert devMap.containsValue('Roberto')
// Para obtener las llaves del mapa
println devMap.keySet()
// Para obtener los valores del mapa
println devMap.values()
/*
Groovy Beans
GroovyBeans son JavaBeans pero usando una sintaxis mucho más simple
Cuando Groovy es compilado a código de bytes, las siguientes reglas son usadas:
* Si el nombre es declarado con un modificador de acceso (public, private o
protected), entonces se genera un campo.
* Un nombre declarado sin modificador de acceso genera un campo privado con
un getter y un setter públicos (ej: una propiedad)
* Si una propiedad es declarada como final, entonces el campo privado es creado
como final y no se genera un setter.
* Puedes declarar una propiedad y también sus propios getter y setter.
* Puedes declarar una propiedad y un campo del mismo nombre, en ese caso, la
propiedad usará ese campo.
* Si quieres una propiedad private o proteceted, tienes que proveer tus propios
getter y setter, los cuales deben ser declarados private o protected.
* Si accedes a una propiedad desde dentro de la clase, la propiedad es definida
en tiempo de compilación con this implícito o explícito (por ejemplo, this.foo
o simplemente foo), Groovy accederá al campo directamente en vez de usar el
getter y setter.
* Si accedes a una propiedad que no existe usando foo explícito o implícito, entonces
Groovy accederá a la propiedad a través de la clase meta, que puede fallar en
tiempo de ejecución.
*/
class Foo {
// propiedad de solo lectura
final String name = "Roberto"
// propiedad de solo lectura, con getter público y setter como protected
String language
protected void setLanguage(String language) { this.language = language }
// propiedad de tipo dinámico
def lastName
}
/*
Derivación Lógica e Iteraciones
*/
// Groovy soporta la clásica sintaxis de if - else
def x = 3
if(x==1) {
println "One"
} else if(x==2) {
println "Two"
} else {
println "X greater than Two"
}
// Groovy también soporta el uso del operador ternario:
def y = 10
def x = (y > 1) ? "worked" : "failed"
assert x == "worked"
// ¡Groovy también soporta 'El Operador Elvis'!
// En lugar de usar el operador ternario:
displayName = user.name ? user.name : 'Anonymous'
// Podemos escribirlo así:
displayName = user.name ?: 'Anonymous'
// Iteración con For
// Iterando en un rango numérico
def x = 0
for (i in 0 .. 30) {
x += i
}
// Iterando sobre una lista
x = 0
for( i in [5,3,2,1] ) {
x += i
}
// Iterando sobre un arreglo
array = (0..20).toArray()
x = 0
for (i in array) {
x += i
}
// Iterando sobre un mapa
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
x = 0
for ( e in map ) {
x += e.value
}
/*
Operadores
Para la lista de los operadores que Groovy soporta, visita:
http://www.groovy-lang.org/operators.html#Operator-Overloading
Operadores Groovy útiles
*/
// Operador de propagación: invocar una acción en todos los elementos de un objeto agregado.
def technologies = ['Groovy','Grails','Gradle']
technologies*.toUpperCase() // equivale a: technologies.collect { it?.toUpperCase() }
// Operador de navegación segura: usado para evitar un NullPointerException.
def user = User.get(1)
def username = user?.username
/*
Closures
Un Closure en Groovy es como un "bloque de código" o un puntero a un método. Es una
porci´øn de código que es definida y ejecutada en un punto futuro en el tiempo.
Más información en: http://www.groovy-lang.org/closures.html
*/
// Ejemplo:
def clos = { println "Hello World!" }
println "Executing the Closure:"
clos()
// Pasando parámetros a un closure
def sum = { a, b -> println a+b }
sum(2,4)
// Los Closures pueden referir a variables no listadas en sus listas de parámetros
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)
// Si tienes un Closure que toma un solo argumento, puedes omitir la
// definición del parámetro en el Closure
def clos = { print it }
clos( "hi" )
/*
Groovy puede memorizar los resultados de un Closure [1][2][3]
*/
def cl = {a, b ->
sleep(3000) // simula algún proceso que consume tiempo
a + b
}
mem = cl.memoize()
def callClosure(a, b) {
def start = System.currentTimeMillis()
mem(a, b)
println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."
}
callClosure(1, 2)
callClosure(1, 2)
callClosure(2, 3)
callClosure(2, 3)
callClosure(3, 4)
callClosure(3, 4)
callClosure(1, 2)
callClosure(2, 3)
callClosure(3, 4)
/*
Expando
La clase Expando es un bean dinámico para que podamos agregar propiedades y closures
como métodos a una instancia de esta clase
http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
*/
def user = new Expando(name:"Roberto")
assert 'Roberto' == user.name
user.lastName = 'Pérez'
assert 'Pérez' == user.lastName
user.showInfo = { out ->
out << "Name: $name"
out << ", Last name: $lastName"
}
def sw = new StringWriter()
println user.showInfo(sw)
/*
Metaprogramación (MOP)
*/
// Usando ExpandoMetaClass para agregar comportamiento
String.metaClass.testAdd = {
println "we added this"
}
String x = "test"
x?.testAdd()
// Interceptando llamadas a métodos
class Test implements GroovyInterceptable {
def sum(Integer x, Integer y) { x + y }
def invokeMethod(String name, args) {
System.out.println "Invoke method $name with args: $args"
}
}
def test = new Test()
test?.sum(2,3)
test?.multiply(2,3)
// Groovy soporta propertyMissing para lidiar con intentos de resolución de propiedades.
class Foo {
def propertyMissing(String name) { name }
}
def f = new Foo()
assertEquals "boo", f.boo
/*
TypeChecked y CompileStatic
Groovy, por naturaleza, es y siempre será un lenguaje dinámico pero soporta
typechecked y compilestatic
Más información: http://www.infoq.com/articles/new-groovy-20
*/
// TypeChecked
import groovy.transform.TypeChecked
void testMethod() {}
@TypeChecked
void test() {
testMeethod()
def name = "Roberto"
println naameee
}
// Otro ejemplo:
import groovy.transform.TypeChecked
@TypeChecked
Integer test() {
Integer num = "1"
Integer[] numbers = [1,2,3,4]
Date date = numbers[1]
return "Test"
}
// ejemplo de CompileStatic:
import groovy.transform.CompileStatic
@CompileStatic
int sum(int x, int y) {
x + y
}
assert sum(2,5) == 7
```
## Más recursos
[Documentación de Groovy](http://www.groovy-lang.org/documentation.html)
[Consola Web de Groovy](http://groovyconsole.appspot.com/)
Únete a un [Groovy user group](http://www.groovy-lang.org/usergroups.html)
## Libros
* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook)
* [Groovy in Action] (http://manning.com/koenig2/)
* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do)
[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html

307
es-es/hack-es.html.markdown Normal file
View File

@@ -0,0 +1,307 @@
---
language: Hack
contributors:
- ["Stephen Holdaway", "https://github.com/stecman"]
- ["David Lima", "https://github.com/davelima"]
translators:
- ["César Suárez", "https://github.com/csuarez"]
lang: es-es
filename: learnhack-es.hh
---
Hack es un superconjunto de PHP que se ejecuta en una máquina virtual llamada HHVM. Hack es casi totalmente compatible con código PHP ya existente y añade varias características típicas de los lenguajes de programación estáticamente tipados.
En este artículo sólo se cubren las características específicas de Hack. Los detalles sobre la sintaxis de PHP están en el [artículo sobre PHP](http://learnxinyminutes.com/docs/php/) de esta misma web.
```php
<?hh
// La sintaxis de Hack sólo se habilita para los ficheros que comienzan con
// un marcador <?hh. Estos marcadores no pueden intercalarse con código HTML,
// tal como se puede hacer con <?php. Al usar el marcador "<?hh //strict" el
// comprobador de tipado en modo estricto se pone en modo estricto.
// Indicando el tipo de parámetros escalares
function repeat(string $word, int $count)
{
$word = trim($word);
return str_repeat($word . ' ', $count);
}
// Indicando el tipo que devuelve una función
function add(...$numbers) : int
{
return array_sum($numbers);
}
// Las funciones que no devuelven nada usan el tipo "void"
function truncate(resource $handle) : void
{
// ...
}
// Al determinar un tipo, hay que indicar explícitamente si permite el valor
// NULL
function identity(?string $stringOrNull) : ?string
{
return $stringOrNull;
}
// Se puede especificar el tipo de las propiedades de una clase
class TypeHintedProperties
{
public ?string $name;
protected int $id;
private float $score = 100.0;
// El comprobador de tipos de Hack fuerza que las propiedades tipadas
// tengan un valor por defecto o que estén asignadas en el constructor
public function __construct(int $id)
{
$this->id = $id;
}
}
// Funciones anónimas concisas (lambdas)
$multiplier = 5;
array_map($y ==> $y * $multiplier, [1, 2, 3]);
// Genéricos
class Box<T>
{
protected T $data;
public function __construct(T $data) {
$this->data = $data;
}
public function getData(): T {
return $this->data;
}
}
function openBox(Box<int> $box) : int
{
return $box->getData();
}
// Shapes
//
// Hack añade el concepto de shape para definir estructuras similares a
// vectores, pero con un conjunto de claves garantizado y tipado
type Point2D = shape('x' => int, 'y' => int);
function distance(Point2D $a, Point2D $b) : float
{
return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
}
distance(
shape('x' => -1, 'y' => 5),
shape('x' => 2, 'y' => 50)
);
// Alias de tipos
//
// Hack permite crear alias para hacer que los tipos complejos sean más legibles
newtype VectorArray = array<int, Vector<int>>;
// Una tupla que contiene dos enteros
newtype Point = (int, int);
function addPoints(Point $p1, Point $p2) : Point
{
return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
}
addPoints(
tuple(1, 2),
tuple(5, 6)
);
// Enumerados de primera clase
enum RoadType : int
{
Road = 0;
Street = 1;
Avenue = 2;
Boulevard = 3;
}
function getRoadType() : RoadType
{
return RoadType::Avenue;
}
// Promoción de argumentos en constructores
//
// Para evitar repetir una y otra vez la definición de constructores que
// sólo asignan propiedades, Hack añade una sintaxis concisa para definir
// propiedades junto al constructor.
class ArgumentPromotion
{
public function __construct(public string $name,
protected int $age,
private bool $isAwesome) {}
}
class WithoutArgumentPromotion
{
public string $name;
protected int $age;
private bool $isAwesome;
public function __construct(string $name, int $age, bool $isAwesome)
{
$this->name = $name;
$this->age = $age;
$this->isAwesome = $isAwesome;
}
}
// Multitarea cooperativa
//
// "async" y "await" son dos palabras claves nuevas para realizar multi-tarea.
// Esto no implica que se usen hilos, sólo permiten transferir el control de la
// ejecución.
{
for ($i = $start; $i <= $end; $i++) {
echo "$i ";
// Da a otras tareas la oportunidad de hacer algo
await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
}
}
// Esto imprime "1 4 7 2 5 8 3 6 9"
AwaitAllWaitHandle::fromArray([
cooperativePrint(1, 3),
cooperativePrint(4, 6),
cooperativePrint(7, 9)
])->getWaitHandle()->join();
// Atributos
//
// Los atributos son una especie de metadatos para funciones. Hack implementa
// algunos atributos especiales para introducir esta característica.
// El atributo especial __Memoize hace que el resultado de la función se cacheé.
<<__Memoize>>
function doExpensiveTask() : ?string
{
return file_get_contents('http://example.com');
}
// Esta función se va a ejecutar sólo una vez:
doExpensiveTask();
doExpensiveTask();
// El atributo __ConsistentConstruct indica al comprobador de tipos de Hack que
// asegure que la signatura de __construct sea la misma para todas las
// subclases.
<<__ConsistentConstruct>>
class ConsistentFoo
{
public function __construct(int $x, float $y)
{
// ...
}
public function someMethod()
{
// ...
}
}
class ConsistentBar extends ConsistentFoo
{
public function __construct(int $x, float $y)
{
// El comprobador de tipos de Hack fuerza que los constructores de
// los padres sean llamados.
parent::__construct($x, $y);
// ...
}
// La anotación __Override es un atributo opcional para que el comprobador
// de tipos fuerce que ese método esté sobrecargando un método de un padre
// o de un trait. Sino, fallará.
<<__Override>>
public function someMethod()
{
// ...
}
}
class InvalidFooSubclass extends ConsistentFoo
{
// Este constructor no coincide con el padre y causará el siguiente error:
//
// "This object is of type ConsistentBaz. It is incompatible with this
// object of type ConsistentFoo because some of their methods are
// incompatible"
public function __construct(float $x)
{
// ...
}
// Usando la anotación __Override en un método que no sobrecarga nada se
// producirá el siguiente error:
//
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
// parent definition found or overridden parent is defined in non-<?hh
// code"
<<__Override>>
public function otherMethod()
{
// ...
}
}
// Los traits pueden implementar interfaces (PHP no soporta esto).
interface KittenInterface
{
public function play() : void;
}
trait CatTrait implements KittenInterface
{
public function play() : void
{
// ...
}
}
class Samuel
{
use CatTrait;
}
$cat = new Samuel();
$cat instanceof KittenInterface === true; // True
```
## Más información
Para obtener una explicación más detallada de las características que añade Hack a PHP visita la página de [referencia de Hack](http://docs.hhvm.com/manual/en/hacklangref.php) o la [página oficial de Hack](http://hacklang.org/) para información de caracter más general.
Visita la [página oficial de HHVM](http://hhvm.com/) para ver las instrucciones de su instalación.
También puedes visitar la [sección de características de PHP no soportadas por Hack](http://docs.hhvm.com/manual/en/hack.unsupported.php) para más detalles sobre la retrocompatibilidad entre Hack y PHP.

View File

@@ -0,0 +1,437 @@
---
language: Haskell
contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
- ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"]
filename: haskell-es.md
lang: es-es
---
Haskell fue diseñado como lenguaje de programación funcional práctico y puro. Es famoso por sus mónadas y su sistema de tipos, pero siempre regreso a él debido a su elegancia. Haskell hace la codificación una verdadera alegría para .
```haskell
-- Para comentar una sola línea utiliza dos guiones.
{- Para comentar múltiples líneas puedes encerrarlas
en un bloque como este.
-}
----------------------------------------------------
-- 1. Tipos de datos primitivos y Operadores
----------------------------------------------------
-- Tienes números a tu disposición
3 -- 3
-- Matématicas, es lo que esperas
1 + 1 -- 2
8 - 1 -- 7
10 * 2 -- 20
35 / 5 -- 7.0
-- Por defecto la división no devuelve un entero
35 / 4 -- 8.75
-- Para la división entera utiliza
35 `div` 4 -- 8
-- Valores booleanos
True
False
-- Operaciones booleanas
not True -- False
not False -- True
1 == 1 -- True
1 /= 1 -- False
1 < 10 -- True
-- En los ejemplos superiores, `not` es una función que toma un valor.
-- Haskell no necesita paréntisis para las llamadas a funciones...todos los argumentos
-- son enlistados después de la función. Entonces el patrón general es:
-- func arg1 arg2 arg3...
-- Observa la sección de funciones para obtener información de como escribir tu propia función.
-- Cadenas y caracteres
"Esto es una cadena."
'a' -- caracter
'No puedes utilizar comillas simples para cadenas.' -- ¡error!
-- Concatenación de cadenas
"¡Hola " ++ "mundo!" -- "¡Hola mundo!"
-- Una cadena es una lista de caracteres
['H', 'o', 'l', 'a'] -- "Hola"
"Esto es una cadena" !! 0 -- 'E'
----------------------------------------------------
-- 2. Listas y Tuplas
----------------------------------------------------
-- Cada elemento en una lista debe ser del mismo tipo.
-- Estas dos listas son iguales:
[1, 2, 3, 4, 5]
[1..5]
-- Los rangos son versátiles.
['A'..'F'] -- "ABCDEF"
-- Puedes crear un paso en un rango.
[0,2..10] -- [0, 2, 4, 6, 8, 10]
[5..1] -- Esto no funciona debido a que Haskell incrementa por defecto.
[5,4..1] -- [5, 4, 3, 2, 1]
-- indexación en una lista
[0..] !! 5 -- 5
-- También tienes listas infinitas en Haskell!
[1..] -- una lista de todos los números naturales
-- Las listas infinitas funcionan porque Haskell tiene "lazy evaluation". Esto significa
-- que Haskell solo evalúa las cosas cuando lo necesita. Así que puedes pedir
-- el elemento 1000 de tú lista y Haskell te devolverá:
[1..] !! 999 -- 1000
-- Y ahora Haskell ha evaluado elementos 1 - 1000 de esta lista...pero el
-- resto de los elementos de esta lista "infinita" ¡no existen todavía! Haskell no lo hará
-- en realidad los evalúa hasta que los necesita.
-- uniendo dos listas
[1..5] ++ [6..10]
-- añadiendo a la cabeza de la lista
0:[1..5] -- [0, 1, 2, 3, 4, 5]
-- más operaciones con listas
head [1..5] -- 1
tail [1..5] -- [2, 3, 4, 5]
init [1..5] -- [1, 2, 3, 4]
last [1..5] -- 5
-- Listas por comprensión
[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
-- Listas por comprensión utilizando condicionales
[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10]
-- Cada elemento en una tupla puede ser de diferente tipo, pero una tupla tiene
-- longitud fija.
-- Ejemplo de una tupla:
("haskell", 1)
-- acceder a los elementos (por ejemplo una tupla de longitud 2)
fst ("haskell", 1) -- "haskell"
snd ("haskell", 1) -- 1
----------------------------------------------------
-- 3. Funciones
----------------------------------------------------
-- Una función simple que recibe dos variables
add a b = a + b
-- Nota: Si estas utilizando ghci (el interprete de Haskell)
-- Necesitas utilizar `let`, por ejemplo
-- let add a b = a + b
-- Utilizando la función
add 1 2 -- 3
-- También puedes llamar a la función enmedio de dos argumentos
-- con acentos abiertos:
1 `add` 2 -- 3
-- ¡También puedes definir funciones sin tener que utilizar letras! De este modo
-- ¡Tú defines tus propios operadores! Aquí esta un operador que realiza
-- una división entera
(//) a b = a `div` b
35 // 4 -- 8
-- Guardas: son una manera fácil para ramificar funciones
fib x
| x < 2 = 1
| otherwise = fib (x - 1) + fib (x - 2)
-- La coincidencia de patrones es similar. Aquí hemos dado tres diferentes
-- definiciones para fib. Haskell llamará automáticamente la primer
-- función que coincide con el patrón del valor.
fib 1 = 1
fib 2 = 2
fib x = fib (x - 1) + fib (x - 2)
-- Coincidencia de patrones en tuplas:
foo (x, y) = (x + 1, y + 2)
-- Coincidencia de patrones en listas. Aquí `x` es el primer elemento
-- en una lista, y `xs` es el resto de la lista. Podemos escribir
-- nuestra propia función map:
myMap func [] = []
myMap func (x:xs) = func x:(myMap func xs)
-- Funciones anónimas son creadas con una diagonal invertida seguido de
-- todos los argumentos.
myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
-- utilizando pliegues (llamado `inject` en algunos lenguajes) con una función
-- anónima. foldl1 significa pliegue por la izquierda, y usa el primer valor
-- en la lista como el valor inicial para el acumulador.
foldl1 (\acc x -> acc + x) [1..5] -- 15
----------------------------------------------------
-- 4. Más funciones
----------------------------------------------------
-- aplicación parcial: si no quieres pasar todos los argumentos a una función,
-- esta es "parcialmente aplicada". Esto significa que retorna una función que toma
-- el resto de los argumentos.
add a b = a + b
foo = add 10 -- foo es actualmente una función que toma un número y suma 10 a esta
foo 5 -- 15
-- Otra manera de escribir los mismo
foo = (+10)
foo 5 -- 15
-- composición de funciones
-- el (.) encadena funciones.
-- Por ejemplo, aquí foo es una función que toma un valor. Y se le suma 10,
-- posteriormente multiplica el resultado por 5, y devuelve el resultado final.
foo = (*5) . (+10)
-- (5 + 10) * 5 = 75
foo 5 -- 75
-- fijación de precedencia
-- Haskell tiene otro operador llamado `$`. Este operador aplica a una función
-- para un parámetro dado. En contraste a la aplicación de función estándar,
-- la cúal tiene prioridad más alta posible de 10 y es asociativa por la izquierda,
-- el operador `$` tiene prioridad de 0 y es asociativa por la derecha. Tal que
-- una baja prioridad significa que la expresión a su derecha es aplicada como parámetro a la función a su izquierda.
-- antes
even (fib 7) -- false
-- equivalentemente
even $ fib 7 -- false
-- composición de funciones
even . fib $ 7 -- false
----------------------------------------------------
-- 5. Firma de tipos
----------------------------------------------------
-- Haskell tiene un fuerte sistema de tipado, y cada cosa tiene una firma de tipo.
-- Algunos tipos básicos:
5 :: Integer
"hola" :: String
True :: Bool
-- Las funciones tienen muchos tipos.
-- `not` toma un booleano y devuelve un booleano:
-- not :: Bool -> Bool
-- Aquí, esta función toma dos argumentos:
-- add :: Integer -> Integer -> Integer
-- Cuando defines un valor, es una buena práctica escribir su tipo en una línea superior:
double :: Integer -> Integer
double x = x * 2
----------------------------------------------------
-- 6. Control de flujo y Expresiones If
----------------------------------------------------
-- expressiones if en una sola línea
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
-- expressiones if en múltiples líneas, la identación es importante
haskell = if 1 == 1
then "awesome"
else "awful"
-- expressiones case: Aquí se muestra como analizar los argumentos
-- desde línea de comandos
case args of
"help" -> printHelp
"start" -> startProgram
_ -> putStrLn "bad args"
-- Haskell no tiene ciclos; en lugar de esto utiliza recursión.
-- map aplica una función sobre cada elemento en un arreglo
map (*2) [1..5] -- [2, 4, 6, 8, 10]
-- tú puedes crear una función utilizando map
for array func = map func array
-- y entonces utilizarla
for [0..5] $ \i -> show i
-- también podríamos haberlo escrito de esta manera:
for [0..5] show
-- Puedes utilizar foldl o foldr para reducir una lista
-- foldl <fn> <valor inicial> <lista>
foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
-- Esto es lo mismo que
(2 * (2 * (2 * 4 + 1) + 2) + 3)
-- foldl es izquierda, foldr es derecha
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
-- Esto es los mismo que
(2 * 1 + (2 * 2 + (2 * 3 + 4)))
----------------------------------------------------
-- 7. Tipos de datos
----------------------------------------------------
-- Por ejemplo, para crear tu propio tipo de dato en Haskell
data Color = Rojo | Azul | Verde
-- Ahora puedes utilizarlo en una función:
say :: Color -> String
say Rojo = "¡Es Rojo!"
say Azul = "¡Es Azul!"
say Verde = "¡Es Verde!"
-- Tus tipos de datos pueden tener parámetros también:
data Maybe a = Nothing | Just a
-- Estos son todos de tipo Maybe
Just "hello" -- de tipo `Maybe String`
Just 1 -- de tipo `Maybe Int`
Nothing -- de tipo `Maybe a` para cualquier `a`
----------------------------------------------------
-- 8. Haskell IO
----------------------------------------------------
-- Mientras que IO no puede ser explicado plenamente sin explicar las mónadas,
-- no es difícil explicar lo suficiente para ponerse en marcha.
-- Cuando un programa en Haskell se ejecuta, `main` es
-- llamado. Este debe devolver un valor de tipo `IO ()`. Por ejemplo:
main :: IO ()
main = putStrLn $ "¡Hola, cielo! " ++ (say Blue)
-- putStrLn tiene tipo String -> IO ()
-- Es más fácil de hacer IO si puedes implementar tu programa como
-- una función de String a String. La función
-- interact :: (String -> String) -> IO ()
-- recibe como entrada un texto, ejecuta una función e imprime
-- una salida.
countLines :: String -> String
countLines = show . length . lines
main' = interact countLines
-- Puedes pensar en el valor de tipo `IO ()` como la representación
-- de una secuencia de acciones que la computadora hace, al igual que
-- un programa escrito en un lenguaje imperativo. Podemos utilizar
-- la notación `do` para encadenar acciones. Por ejemplo:
sayHello :: IO ()
sayHello = do
putStrLn "¿Cual es tu nombre?"
name <- getLine -- obtenemos un valor y lo proporcionamos a "name"
putStrLn $ "Hola, " ++ name
-- Ejercicio: escribe tu propia version de `interact` que solo lea
-- una linea como entrada.
-- Nunca se ejecuta el código en `sayHello`, sin embargo. La única
-- acción que siempre se ejecuta es el valor de `main`.
-- Para ejecutar `sayHello` comenta la definición anterior de `main`
-- y sustituyela por:
-- main = sayHello
-- Vamos a entender mejor como funciona la función `getLine` cuando
-- la utilizamos. Su tipo es:
-- getLine :: IO String
-- Puedes pensar en el valor de tipo `IO a` como la representación
-- programa que generará un valor de tipo `a`
-- cuando es ejecutado (además de cualquier otra cosa que haga). Podemos
-- almacenar y reutilizar el valor usando `<-`. También podemos
-- crear nuestra propia acción de tipo `IO String`:
action :: IO String
action = do
putStrLn "Esta es una linea."
input1 <- getLine
input2 <- getLine
-- El tipo de la sentencia `do` es la de su última línea.
-- `return` no es una palabra clave, sino simplemente una función
return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
-- Podemos usar esto sólo como usabamos `getLine`:
main'' = do
putStrLn "¡Volveré a repetir dos líneas!"
result <- action
putStrLn result
putStrLn "Esto es todo, ¡amigos!"
-- El tipo `IO` es un ejemplo de una "mónada". La forma en que Haskell utiliza una monada
-- permite que sea un lenguaje puramente funcional. Cualquier función que
-- interactue con el mundo exterior (por ejemplo usar IO) obtiene una marca `IO`
-- como su firma de tipo. Esto nos permite pensar qué funciones son "puras"
-- (que no interactuan con el mundo exterior o modifican el estado) y que funciones no lo son.
-- Esta es una poderosa característica, porque es una manera fácil de ejecutar funciones puras
-- concurrentemente; entonces, la concurrencia en Haskell es muy fácil.
----------------------------------------------------
-- 9. El interprete de comandos de Haskell
----------------------------------------------------
-- Para comenzar escribe desde la terminal `ghci`.
-- Ahora puede escribir código en Haskell. Para cualquier valor nuevo
-- que necesites crear utiliza `let`:
let foo = 5
-- Puedes inspeccionar el tipo de cualquier valor con `:t`:
>:t foo
foo :: Integer
-- Puedes ejecutar acciones de tipo `IO ()`
> sayHello
¿Cual es tu nombre?
Amigo
Hola, Amigo
```
Existe mucho más de Haskell, incluyendo clases de tipos y mónadas. Estas son
las grandes ideas que hacen a Haskell divertido. Te dejamos un ejemplo final
de Haskell: una implementación del algoritmo QuickSort:
```haskell
qsort [] = []
qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
where lesser = filter (< p) xs
greater = filter (>= p) xs
```
Haskell es fácil de instalar. Obtenlo [aquí](http://www.haskell.org/platform/).
Usted puede encontrar más información en:
[Learn you a Haskell](http://learnyouahaskell.com/) o
[Real World Haskell](http://book.realworldhaskell.org/) o
[Aprende Haskell por el bien de todos](http://aprendehaskell.es/)

122
es-es/html-es.html.markdown Normal file
View File

@@ -0,0 +1,122 @@
---
language: html
filename: learnhtml-es.html
contributors:
- ["Christophe THOMAS", "https://github.com/WinChris"]
translators:
- ["Gino Amaury", "https://github.com/ginoamaury"]
lang: es-es
---
HTML significa Lenguaje de marcado de hipertexto (HyperText Markup Language).
Este es un lenguaje usado para escribir páginas en la web (WWW).
Este es un lenguaje de marcado, es usado para escribir páginas web usando código para indicar cómo se debe mostrar el texto y los datos.
En efecto, los archivos html son simples archivos de texto.
Qué es esto de marcado? es un método para organizar los datos de la página encerrandolos con etiquetas de apertura y cierre.
Este marcado sirve para darle significancia al texto que éste encierra.
Como en otros lenguajes computacionales, HTML tiene varias versiones. Aquí hablaremos acerca de HTML5.
**Nota :** Puedes probrar las diferentes etiquetas y elementos a medida que progresas en un tutorial en un sitio como [codepen](http://codepen.io/pen/) con el fin de ver sus efectos, entender como funcionan y familiarizarse con el lenguaje.
Este artículo está centrado principalmente en la sintaxis HTML y algunos tips de importancia.
```html
<!-- los comentarios están encerrados como en esta línea! -->
<!-- #################### Las Etiquetas #################### -->
<!-- Este es un ejemplo de un archivo HTML que analizaremos! -->
<!doctype html>
<html>
<head>
<title>Mi Sitio</title>
</head>
<body>
<h1>Hola, Mundo!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">ven mira lo que esto muestra. </a>
<p>Esto es un párrafo</p>
<p>Este es otro párrafo</p>
<ul>
<li>Este es un elemento de una lista no numerada (lista de viñetas)</li>
<li>Este es otro ítem</li>
<li>Y este es el último ítem de la lista</li>
</ul>
</body>
</html>
<!-- En un archivo HTML siempre inicia indicando le al buscador que esta es una página HTML. -->
<!doctype html>
<!-- Después de esto, iniciamos abriendo una etiqueta html <html> -->
<html>
<!-- Cuando termine el archivo cerraremos la etiqueta así </html>. -->
</html>
<!-- Después de la etiqueta final nada aparecerá o podrá aparecer -->
<!-- Dentro (Entre las etiquetas de apertura y cierre <html></html>), encontraremos: -->
<!-- Un encabezado definido por <head> (Este debe ser cerrado por </head>). -->
<!-- El encabezado contiene alguna descripción y información adicional que no se muestra; estos son los metadatos. -->
<head>
<title>Mi Sitio</title><!-- La etiqueta <title> Indica al buscador el título a mostrar en la ventana del buscador en la barra de título y en el nombre de la pestaña. -->
</head>
<!-- Después de la sección del encabezado <head> , Encontraremos la etiqueta de cuerpo - <body> -->
<!-- Hasta este punto. no hay nada descrito para que se muestre en la ventana del navegador -->
<!-- Debemos llenar el cuerpo con el contenido que se mostrará -->
<body>
<h1>Hola, Mundo!</h1> <!-- La etiqueta <h1> crea un título. -->
<!-- También tenemos subtítulos para <h1> desde la más importante <h2> a la más precisa <h6> -->
<a href = "http://codepen.io/anon/pen/xwjLbZ">ven mira lo que esto muestra.</a> <!-- Un hipervínculo a la URL dada por el atributo href="" -->
<p>Esto es un párrafo.</p> <!-- La etiqueta <p> nos permite incluir texto en nuestra página HTML -->
<p>Este es otro párrafo.</p>
<ul> <!-- La etiqueta <ul> crea una lista de viñetas -->
<!-- Para tener una lista numerada usamos la etiqueta <ol> dando 1. para el primer elemento, 2. para el segundo, etc. -->
<li>Este es un elemento de una lista no numerada (lista de viñetas)</li>
<li>Este es otro ítem</li>
<li>Y este es el último ítem de la lista</li>
</ul>
</body>
<!-- Y esto es todo, la creación de un archivo HTML puede ser muy simple. -->
<!-- Sin embargo, es posible añadir muchos otros tipos de etiquetas HTML -->
<!-- Para insertar una imagen -->
<img src="http://i.imgur.com/XWG0O.gif"/> <!-- La fuente donde se localiza la imagen se indica utilizando el atributo src=""-->
<!-- La fuente puede ser una URL o incluso una ruta a una archivo en tu computador. -->
<!-- También es posible crear una tabla -->
<table> <!-- Abrimos una etiqueta o elemento tabla <table> -->
<tr> <!-- <tr> Nos permite crear una fila. -->
<th>Primer encabezado</th> <!-- <th> Nos permite dar un título a una columna de una tabla -->
<th>Segundo encabezado</th>
</tr>
<tr>
<td>Primera fila, primera columna</td> <!-- <td> nos permite crear una celda -->
<td>Primera fila, segunda columna</td>
</tr>
<tr>
<td>Segunda fila, primera columna</td>
<td>Segunda fila, segunda columna</td>
</tr>
</table>
```
## Uso
HTML es escrito en archivos que terminan con (extensión) `.html`.
## Para aprender más!
* [wikipedia](https://es.wikipedia.org/wiki/HTML)
* [HTML tutorial](https://developer.mozilla.org/es/docs/Web/HTML)
* [W3School (EN)](http://www.w3schools.com/html/html_intro.asp)

View File

@@ -279,6 +279,19 @@ public class AprendeJava {
// 'toString' es una convención para mostrar los valores de este objeto.
System.out.println("informacion de la excursion: " + excursion.toString());
///////////////////////////////////////
// Genéricos
///////////////////////////////////////
// Utilizando genéricos (a partir de Java 1.5) es posible detectar en tiempo de
// compilación errores de tipado (en versiones anteriores se detectarían como error
// de ejecución)
List<String> v = new ArrayList<String>();
v.add("test");
String s = v.get(0); // Si intentamos recuperar s como otro tipo diferente a String
// (por ejemplo, un Integer) obtendríamos un error de compilación
} // Fin del método 'main'
} // Fin de la clase AprendeJava

View File

@@ -16,14 +16,16 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con
web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común
para front-end que Java.
Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
Sin embargo, JavaScript no sólo se limita a los navegadores web: Node.js, un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular.
¡La retroalimentación es bienvenida! Puedes encontrarme en:
[@adambrenecki](https://twitter.com/adambrenecki), o
[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
```js
// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //,
// Los comentarios en JavaScript son los mismos como comentarios en C.
//Los comentarios de una sola línea comienzan con //,
/* y los comentarios multilínea comienzan
y terminan con */
@@ -80,13 +82,13 @@ false;
!true; // = false
!false; // = true
// Para comprobar una igualdad se usa ==
1 == 1; // = true
2 == 1; // = false
// Para comprobar una igualdad se usa ===
1 === 1; // = true
2 === 1; // = false
// Para comprobar una desigualdad se usa !=
1 != 1; // = false
2 != 1; // = true
// Para comprobar una desigualdad se usa !==
1 !== 1; // = false
2 !== 1; // = true
// Más comparaciones
1 < 10; // = true

View File

@@ -0,0 +1,141 @@
---
category: tool
tool: jquery
contributors:
- ["Sawyer Charles", "https://github.com/xssc"]
translators:
- ["Ivan Alburquerque", "https://github.com/AlburIvan"]
lang: es-es
filename: jquery-es.js
---
jQuery es una librería de JavaScript que le ayuda a "hacer más y escribir menos". Esto hace que muchas de las tareas comunes de JavaScript sean más fáciles de escribir. jQuery es utilizado por muchas de las grandes empresas y desarrolladores de todo el mundo. Hace que AJAX, la gestión de eventos, la manipulación de documentos, y mucho más, sea más fácil y rápido.
Debido a que jQuery es una librería de JavaScript debes [aprender JavaScript primero](https://learnxinyminutes.com/docs/es-es/javascript-es/)
```js
///////////////////////////////////
// 1. Selectores
// Los selectores en jQuery son usados para seleccionar un elemento
var page = $(window); // Selecciona toda la ventana gráfica
// Los selectores también pueden ser selectores CSS
var paragraph = $('p'); // Selecciona todos los elementos de párrafo
var table1 = $('#table1'); // Selecciona el elemento con id 'tabla1'
var squares = $('.square'); // Selecciona todos los elementos con la clase "square"
var square_p = $('p.square') // Selecciona los párrafos con la clase "square"
///////////////////////////////////
// 2. Eventos y efectos
// Un evento muy común que se utiliza es el evento 'ready' en el documento
// Se puede utilizar el método de 'ready' para esperar hasta que el elemento haya terminado de cargar
$(document).ready(function(){
// El código no se ejecutará hasta que el documento haya terminado de cargar
});
// jQuery es muy bueno activando eventos
// Y también en el manejo de lo que ocurre cuando se activa un evento
$('#button').click(); // Dispara un evento click en $ ('# botón')
$('#button').click(function(){
// El código es ejecutado cuando se hace clic en el elemento de botón #
});
function onAction() {
// Esto se ejecuta cuando se activa el evento
}
// Algunos otros eventos comunes son:
$('#btn').dblclick(onAction); //Doble clic
$('#btn').hover(onAction); // Pasar el cursor por encima
$('#btn').focus(onAction); // Enfocado
$('#btn').blur(onAction); // Pierde enfoque
$('#btn').submit(onAction); // Enviado
$('#btn').select(onAction); // Cuando se selecciona un elemento
$('#btn').keydown(onAction); // Cuando una tecla es empujada hacia abajo
$('#btn').keyup(onAction); // Cuando se suelta una tecla
$('#btn').keypress(onAction); // Cuando se pulsa una tecla
$('#btn').mousemove(onAction); // Cuando se mueve el mouse
$('#btn').mouseenter(onAction); // El mouse entra en el elemento
$('#btn').mouseleave(onAction); // El mouse sale en el elemento
// También se puede utilizar una función anónima
$('#btn').hover(function(){
// Se ejecuta al pasar por encima
});
// Todos estos pueden también desencadenar el evento en lugar de manejarlo
// Simplemente no pasando ningún parámetro
$('#btn').dblclick(); // Dispara el evento de doble clic sobre el elemento
// Se puede manejar múltiples eventos, usando el selector una vez
$('#btn').on(
{dblclick: myFunction1} // Activado con doble clic
{blur: myFunction1} // Activo en la perdida de enfoque
);
// Puede mover y ocultar elementos con algunos métodos de efecto
$('.table').hide(); // Oculta el(los) elemento(s)
// Nota: llamar a una función en estos métodos aún oculta el elemento
$('.table').hide(function(){
// El elemento se oculta entonces función ejecutada
});
// Puedes almacenar los selectores en las variables
var tables = $('.table');
// Algunos métodos básicos de manipulación de documento son:
tables.hide(); // Oculta elemento(s)
tables.show(); // Muestra elemento(s)
tables.toggle(); // Cambia el estado de ocultar / mostrar
tables.fadeOut(); // Desvanece
tables.fadeIn(); // Fundirse
tables.fadeToggle(); // Desvanece dentro o fuera
tables.fadeTo(0.5); // Desvanece a una opacidad (entre 0 y 1)
tables.slideUp(); // Desliza hacia arriba
tables.slideDown(); // Desliza hacia abajo
tables.slideToggle(); // Desliza hacia arriba o hacia abajo
// Todo lo anterior toma una velocidad (milisegundos) y la función de devolución de llamada
tables.hide(1000, myFunction); // Animación de ocultar elemento a 1 segundo y luego la funcion de devolución
// 'fadeTo' requiere de una opacidad como su segundo parámetro
tables.fadeTo(2000, 0.1, myFunction); // 2 segundos. decolorar a opacidad de 0.1 luego la función
// Puede conseguir un efecto un poco más avanzado con el método 'animate'
tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction);
// El método 'animate' toma un objeto de CSS y los valores finales,
// Parámetro opcional de opciones para afinar la animación,
// Y por supuesto la función de devolución de llamada
///////////////////////////////////
// 3. Manipulación
// Estos son similares a los efectos, pero pueden hacer más
$('div').addClass('div') // Añade la clase div a todos los divs
// Métodos comunes de manipulación
$('p').append('Hola mundo'); // Añade al final del elemento
$('p').attr('class'); // Obtiene atributo
$('p').attr('class', 'content'); // Configura atributos
$('p').hasClass('div'); //Devuelve verdadero si tiene la clase
$('p').height(); // Obtiene la altura del elemento o define la altura
// Para muchos métodos de manipulación, obtener información sobre un elemento
// consigue solamente el primer elemento coincidente
$('p').height(); // Obtiene sólo la altura de la primera etiqueta 'p'
// Puedes utilizar 'each' para recorrer todos los elementos
var heights = [];
$('p').each(function() {
heights.push($(this).height()); // Añade todas las alturas "p" de la etiqueta a la matriz
});
```

View File

@@ -0,0 +1,361 @@
---
language: kotlin
contributors:
- ["S Webber", "https://github.com/s-webber"]
translators:
- ["Ivan Alburquerque", "https://github.com/AlburIvan"]
lang: es-es
filename: LearnKotlin-es.kt
---
Kotlin es un lenguaje estático tipado para la JVM, Android y el navegador. Es
100% interoperable con Java.
[Leer mas aqui.](https://kotlinlang.org/)
```java
// Los comentarios de una sóla línea comienzan con //
/*
Los comentarios multilínea lucen así
*/
// La palabra clave "package" funciona de la misma manera que Java.
/*
El punto de entrada para un programa de Kotlin es una función llamada "main".
A dicha función se le pasa un arreglo que contiene los argumentos de la linea de comando.
*/
fun main(args: Array<String>) {
/*
La declaración de valores se realiza utilizando tanto "var" como "val".
Las declaraciones "val" no pueden ser reasignadas, mientras que "var" sí.
*/
val fooVal = 10 // más adelante no podremos reasignar fooVal con un valor distinto.
var fooVar = 10
fooVar = 20 // fooVar puede ser reasignado
/*
En la mayoría de los casos, Kotlin puede determinar cuál es el tipo de una variable,
de tal manera que no tenemos que especificarlo explícitamente cada vez.
    Podemos declarar explícitamente el tipo de una variable así:
*/
val foo: Int = 7
/*
Las cadenas pueden ser representadas de la misma manera que Java.
El escape de caracteres se realiza con una barra invertida.
*/
val fooString = "Mi Cadena está aquí!";
val barString = "¿Imprimiendo en una nueva línea?\nNo hay problema!";
val bazString = "¿Quíeres agregar una tabulación?\tNo hay problema!";
println(fooString);
println(barString);
println(bazString);
/*
Una cadena está delimitada por comillas triple (""").
    Estas cadenas pueden contener saltos de línea y otros caracteres.
*/
val fooRawString = """
fun helloWorld(val name : String) {
println("Hola, mundo!")
}
"""
println(fooRawString)
/*
Las cadenas pueden contener interpolación de cadenas.
    La interpolación de cadenas comienza con un signo de dólar ($).
*/
val fooTemplateString = "$fooString tiene ${fooString.length} caracteres"
println(fooTemplateString)
/*
Para que una variable pueda aceptar valor nulo se debe especificar
explícitamente como anulable añadiendole ? a su tipo.
    Podemos acceder a una variable anulable mediante el uso del operador ?.
    Podemos utilizar el operador ?: para especificar un valor alternativo
a usar si una variable es nula.
*/
var fooNullable: String? = "abc"
println(fooNullable?.length) // => 3
println(fooNullable?.length ?: -1) // => 3
fooNullable = null
println(fooNullable?.length) // => null
println(fooNullable?.length ?: -1) // => -1
/*
Las funciones pueden ser declaras usando la palabra clave "fun".
Los argumentos de las funciones son especificados entre corchetes despues del nombre de la función.
Los argumentos de las funciones pueden tener opcionalmente un valor por defecto.
El tipo de retorno de las funciones, de ser requerido, es especificado despues del argumento.
*/
fun hello(name: String = "mundo") : String {
return "Hola, $name!"
}
println(hello("foo")) // => Hola, foo!
println(hello(name = "bar")) // => Hola, bar!
println(hello()) // => Hola, mundo!
/*
Un parametro de la función puede ser marcado con la palabra clave "vararg"
que permite que una función acepte un numero variable de argumentos.
*/
fun varargExample(vararg names: Int) {
println("Argument tiene ${names.size} elementos")
}
varargExample() // => Argument tiene 0 elementos
varargExample(1) // => Argument tiene 1 elementos
varargExample(1, 2, 3) // => Argument tiene 3 elementos
/*
Cuando una función consiste de una sola expresión entonces las llaves
pueden ser omitidas. El cuerpo es especificado despues del símbolo =
*/
fun odd(x: Int): Boolean = x % 2 == 1
println(odd(6)) // => false
println(odd(7)) // => true
// Si el tipo de retorno puede ser inferido entonces no se necesita
// especificarlo.
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
// Las funciones pueden tomar funciones como argumentos y
// retornar funciones.
fun not(f: (Int) -> Boolean) : (Int) -> Boolean {
return {n -> !f.invoke(n)}
}
// Las funciones con nombre pueden ser especificadas como argumentos
// utilizando el operador ::.
val notOdd = not(::odd)
val notEven = not(::even)
// Las funciones anónimas pueden ser especificadas como argumentos.
val notZero = not {n -> n == 0}
/*
Si una función anónima tiene un solo parametro entonces la declaración
puede ser omitida (junto con ->). El nombre del único parametro será "it".
*/
val notPositive = not {it > 0}
for (i in 0..4) {
println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
}
// La palabra clave "class" es usada para declarar clases.
class ExampleClass(val x: Int) {
fun memberFunction(y: Int) : Int {
return x + y
}
infix fun infixMemberFunction(y: Int) : Int {
return x * y
}
}
/*
Para crear una nueva instancia llamamos al constructor.
Nótese que Kotlin no usa la palabra clave "new".
*/
val fooExampleClass = ExampleClass(7)
// Las funciones miembros pueden ser llamadas usando la notación de punto (.)
println(fooExampleClass.memberFunction(4)) // => 11
/*
Si una función ha sido marcada con la palabra clave "infix" entonces
esta puede ser invocada usando la notación infija.
*/
println(fooExampleClass infixMemberFunction 4) // => 28
/*
Las clases "data" son una manera concisa de crear clases que solo contengan datos.
Los metodos "hashCode"/"equals" y "toString" son generados automáticamente.
*/
data class DataClassExample (val x: Int, val y: Int, val z: Int)
val fooData = DataClassExample(1, 2, 4)
println(fooData) // => DataClassExample(x=1, y=2, z=4)
// las clases de datos tienen una función "copy".
val fooCopy = fooData.copy(y = 100)
println(fooCopy) // => DataClassExample(x=1, y=100, z=4)
// Los objetos pueden ser estructurados en múltiples variables.
val (a, b, c) = fooCopy
println("$a $b $c") // => 1 100 4
// La función "with" es similar a la expresión de JavaScript "with".
data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
val fooMutableData = MutableDataClassExample(7, 4, 9)
with (fooMutableData) {
x -= 2
y += 2
z--
}
println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)
/*
Podemos crear una lista utilizando la función "listOf".
La lista será inmutable - los elementos no pueden ser añadidos o eliminados.
*/
val fooList = listOf("a", "b", "c")
println(fooList.size) // => 3
println(fooList.first()) // => a
println(fooList.last()) // => c
// Los elementos de una lista se pueden acceder a través de su índice.
println(fooList[1]) // => b
// Una lista mutable puede ser creada usando la función "mutableListOf".
val fooMutableList = mutableListOf("a", "b", "c")
fooMutableList.add("d")
println(fooMutableList.last()) // => d
println(fooMutableList.size) // => 4
// Podemos crear un set usando la función "setOf".
val fooSet = setOf("a", "b", "c")
println(fooSet.contains("a")) // => true
println(fooSet.contains("z")) // => false
// Podemos crear un mapa usando la función "mapOf".
val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
// Se puede acceder a los valores del mapa por su llave.
println(fooMap["a"]) // => 8
/*
Las secuencias representan colecciones evaluadas diferidamente.
Podemos crear una secuencia con la función "generateSequence".
*/
val fooSequence = generateSequence(1, {it + 1})
val x = fooSequence.take(10).toList()
println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Un ejemplo usando las secuencias para generar los números de Fibonacci:
fun fibonacciSequence() : Sequence<Long> {
var a = 0L
var b = 1L
fun next() : Long {
val result = a + b
a = b
b = result
return a
}
return generateSequence(::next)
}
val y = fibonacciSequence().take(10).toList()
println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
// Kotlin provee funciones de Orden-Mayor para trabajar con colecciones.
val z = (1..9).map {it * 3}
.filter {it < 20}
.groupBy {it % 2 == 0}
.mapKeys {if (it.key) "even" else "odd"}
println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}
// Un bucle "for" puede ser usado con cualquier cosa que provea un iterador.
for (c in "hello") {
println(c)
}
// El bucle "while" funciona de la misma manera que en los demás lenguajes.
var ctr = 0
while (ctr < 5) {
println(ctr)
ctr++
}
do {
println(ctr)
ctr++
} while (ctr < 10)
/*
"if" puede ser usado como una expresión que retorna un valor.
Por esta razón el operador ternario ?: no es necesario en Kotlin.
*/
val num = 5
val message = if (num % 2 == 0) "even" else "odd"
println("$num is $message") // => 5 is odd
// "when" puede ser usado como alternativa a cadenas de "if-else if".
val i = 10
when {
i < 7 -> println("primer bloque")
fooString.startsWith("hello") -> println("segundo bloque")
else -> println("else bloque")
}
// "when" puede ser usado con argumentos.
when (i) {
0, 21 -> println("0 or 21")
in 1..20 -> println("in the range 1 to 20")
else -> println("none of the above")
}
// "when" puede ser usado como una función que retorna un valor.
var result = when (i) {
0, 21 -> "0 or 21"
in 1..20 -> "in the range 1 to 20"
else -> "none of the above"
}
println(result)
/*
Podemos analizar si un objeto es de un tipo particular usando el operador "is".
Si un objeto pasa un chequeo de tipo entonces éste se puede utilizar como
ese tipo sin convertido de forma explícita.
*/
fun smartCastExample(x: Any) : Boolean {
if (x is Boolean) {
// x es automaticamente convertido a Boolean
return x
} else if (x is Int) {
// x es automaticamente convertido a Int
return x > 0
} else if (x is String) {
// x es automaticamente convertido a String
return x.isNotEmpty()
} else {
return false
}
}
println(smartCastExample("Hola, mundo!")) // => true
println(smartCastExample("")) // => false
println(smartCastExample(5)) // => true
println(smartCastExample(0)) // => false
println(smartCastExample(true)) // => true
/*
Las extensiones son una manera de añadir nuevas funcionalidades a una clase.
Estas son similares a la extensión de métodos en C#.
*/
fun String.remove(c: Char): String {
return this.filter {it != c}
}
println("Hola, mundo!".remove('l')) // => Hoa, mundo!
println(EnumExample.A) // => A
println(ObjectExample.hello()) // => hola
}
// Las clases "enum" son similares a los tipos "enum" de Java.
enum class EnumExample {
A, B, C
}
/*
La palabra clave "object" se puede utilizar para crear objetos únicos.
No podemos asignarlo a una variable, pero podemos hacer referencia a ella por su nombre.
Esto es similar a los objetos únicos de Scala
*/
object ObjectExample {
fun hello() : String {
return "hola"
}
}
```
### Lectura Adicional
* [Kotlin tutorials (EN)](https://kotlinlang.org/docs/tutorials/)
* [Try Kotlin in your browser (EN)](http://try.kotlinlang.org/)
* [A list of Kotlin resources (EN)](http://kotlin.link/)

393
es-es/less-es.html.markdown Normal file
View File

@@ -0,0 +1,393 @@
---
language: less
filename: learnless-es.less
lang: es-es
contributors:
- ["Saravanan Ganesh", "http://srrvnn.me"]
translators:
- ["César Suárez", "https://github.com/csuarez"]
---
Less es un pre-procesador CSS, que añade características como variables, anidación, mixins y más.
Less (y otros pre-procesadores como [Sass](http://sass-lang.com/) ayudan a los desarrolladores a escribir código mantenible y DRY (Don't Repeat Yourself).
```css
//Los comentarios de una línea son borrados cuando Less es compilado a CSS.
/* Los comentarios multi-línea se mantienen. */
/*Variables
==============================*/
/* Puedes almacenar un valor CSS (como un color) en una variable.
Usa el símbolo '@' para crear una variable. */
@primary-color: #a3a4ff;
@secondary-color: #51527f;
@body-font: 'Roboto', sans-serif;
/* Puedes usar las variables por toda tu hoja de estilos.
Ahora, si quieres cambiar un color, sólo lo tienes que hacer una vez.*/
body {
background-color: @primary-color;
color: @secondary-color;
font-family: @body-font;
}
/* Esto compilará en: */
body {
background-color: #a3a4ff;
color: #51527F;
font-family: 'Roboto', sans-serif;
}
/* Esto es mucho más mantenible que tener que cambiar el color
cada vez que aparece en tu hoja de estilos. */
/* Mixins
==============================*/
/* Si tienes el mismo código para más de un elemento, puede que
quieras reutilizarlo fácilmente. */
.center {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
/* Puedes usar un mixin simplemente añadiendo el selector como un estilo. */
div {
.center;
background-color: @primary-color;
}
/* Esto compilará en: */
.center {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
div {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
background-color: #a3a4ff;
}
/* Puedes omitir que se compile el código del mixin añadiendo un
paréntesis después del selector. */
.center() {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
div {
.center;
background-color: @primary-color;
}
/* Esto compilará en: */
div {
display: block;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
background-color: #a3a4ff;
}
/* Anidación
==============================*/
/* Less te permite anidar selectores dentro de otros selectores. */
ul {
list-style-type: none;
margin-top: 2em;
li {
background-color: #f00;
}
}
/* '&' es replazado por el selector padre. */
/* También se pueden anidar seudo clases. */
/* Ten en cuenta que anidar demasiado puede hacer tu código menos
mantenible. Las buenas prácticas recomiendan no tener más de 3 niveles de
anidación. Por ejemplo: */
ul {
list-style-type: none;
margin-top: 2em;
li {
background-color: red;
&:hover {
background-color: blue;
}
a {
color: white;
}
}
}
/* Compila en: */
ul {
list-style-type: none;
margin-top: 2em;
}
ul li {
background-color: red;
}
ul li:hover {
background-color: blue;
}
ul li a {
color: white;
}
/* Funciones
==============================*/
/* Less ofrece funciones que pueden ser usadas para cumplir una gran variedad
de tareas. Considera lo siguiente: */
/* Las funciones pueden ser llamadas usando su nombre y pasándole los argumentos
requeridos. */
body {
width: round(10.25px);
}
.header {
background-color: lighten(#000, 0.5);
}
.footer {
background-color: fadeout(#000, 0.25)
}
/* Compila en: */
body {
width: 10px;
}
.header {
background-color: #010101;
}
.footer {
background-color: rgba(0, 0, 0, 0.75);
}
/* Puedes definir tus propias funciones. Las funciones son muy similares a
los mixins. Cuando tengas que elegir entre una función y un mixin, recuerda
que los mixins son mejores para generar CSS, mientras que las funciones son
mejores para la lógica que puedas necesitar en tu código Sass. Los ejemplos
de la sección 'Operadores matemáticos' son candidatos ideales para ser
usados como una función reusable. */
/* Esta función calcula la media de dos números. */
.average(@x, @y) {
@average-result: ((@x + @y) / 2);
}
div {
.average(16px, 50px); // aquí se llama a la función
padding: @average-result; // y aquí se usa el valor "devuelto"
}
/* Compila en: */
div {
padding: 33px;
}
/* Extender (Herencia)
==============================*/
/* Extend es una manera de compartir propiedades de un selector con otro. */
.display {
height: 50px;
}
.display-success {
&:extend(.display);
border-color: #22df56;
}
/* Compila en: */
.display,
.display-success {
height: 50px;
}
.display-success {
border-color: #22df56;
}
/* Extender una declaración CSS es preferible a crear un mixin
debido a la manera en la que Sass agrupa las clases que comparten
los mismos estilos base. Si esto fuese hecho con un mixin, el ancho,
alto y el borden aparecerían duplicados para cada una de las declaraciones
que usasen el mixin. Esto no afectará a tu workflow, pero infla
innecesariamente los ficheros generados por el compilador Less. */
/*Partials and Imports
==============================*/
/* Less allows you to create partial files. This can help keep your Less
code modularized. Partial files conventionally begin with an '_',
e.g. _reset.less. and are imported into a main less file that gets
compiled into CSS */
/* Consider the following CSS which we'll put in a file called _reset.less */
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
/* Less ofrece @import para poder importar parciales a un fichero. Esto se
diferencia del @import de CSS en que no hace otra petición HTTP para
importar el fichero, sino que combina el código importado en el código
compilado. */
@import 'reset';
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/* Compila en: */
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-size: 16px;
font-family: Helvetica, Arial, Sans-serif;
}
/* Operaciones matemáticas
==============================*/
/* Less ofrece los siguientes operadores: +, -, *, / y %. Estos son útiles
para calcular valores directamente en tu código Less en vez de usar valores
calculados a mano. Mira el siguiente ejemplo que prepara un sencillo diseño
de dos columnas. */
@content-area: 960px;
@main-content: 600px;
@sidebar-content: 300px;
@main-size: @main-content / @content-area * 100%;
@sidebar-size: @sidebar-content / @content-area * 100%;
@gutter: 100% - (@main-size + @sidebar-size);
body {
width: 100%;
}
.main-content {
width: @main-size;
}
.sidebar {
width: @sidebar-size;
}
.gutter {
width: @gutter;
}
/* Compila en: */
body {
width: 100%;
}
.main-content {
width: 62.5%;
}
.sidebar {
width: 31.25%;
}
.gutter {
width: 6.25%;
}
```
## Practica Less
Si quieres probar Less en tu navegador, prueba:
* [Codepen](http://codepen.io/)
* [LESS2CSS](http://lesscss.org/less-preview/)
## Compatibilidad
Sass puede ser usado en cualquier proyecto mientras tengas un programa que lo compile en CSS. Quizás quieras comprobar si el CSS que estás usando es compatible con tus navegadores objetivo.
[QuirksMode CSS](http://www.quirksmode.org/css/) y [CanIUse](http://caniuse.com) son buenos recursos para comprobar la compatibilidad de navegadores.
## Más información
* [Documentación oficial (EN)](http://lesscss.org/features/)
* [Less CSS - Guía para principiantes (EN)](http://www.hongkiat.com/blog/less-basic/)

Some files were not shown because too many files have changed in this diff Show More