diff options
65 files changed, 9079 insertions, 1041 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..dd41ec4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +**/*~ +**/*# +**/#*# +**/*.swp +**/*.swo +**/*.bak +**/*.log* +**/*.sublime-workspace +**/.DS_Store +**/.DS_Store? +**/._* +**/.Spotlight-V100 +**/.Trashes +**/ehthumbs.db +**/Thumbs.db +**/desktop.ini
\ No newline at end of file diff --git a/bash.html.markdown b/bash.html.markdown index f3c9cccc..02d7f31e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -270,7 +270,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # if you literally want to search for the string, # and not the regex, use fgrep (or grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "foobar" file.txt # Read Bash shell builtins documentation with the bash 'help' builtin: diff --git a/bg-bg/perl-bg.html.markdown b/bg-bg/perl-bg.html.markdown new file mode 100644 index 00000000..babd2d4d --- /dev/null +++ b/bg-bg/perl-bg.html.markdown @@ -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` + diff --git a/c.html.markdown b/c.html.markdown index 7c9dd590..babf0954 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -143,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: @@ -238,7 +238,7 @@ int main (int argc, char** argv) // 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. + 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. // same with j-- and --j @@ -779,4 +779,4 @@ Readable code is better than clever code and fast code. For a good, sane coding 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
\ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member diff --git a/cmake.html.markdown b/cmake.html.markdown new file mode 100644 index 00000000..e13e7f67 --- /dev/null +++ b/cmake.html.markdown @@ -0,0 +1,176 @@ +--- +language: cmake +contributors: + - ["Bruno Alano", "https://github.com/brunoalano"] +filename: CMake +--- + +CMake it's 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 it's the problem of Makefiles and +Autoconfigure on cross-platform (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 in a 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 genearted 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/) diff --git a/cs-cz/css.html.markdown b/cs-cz/css.html.markdown new file mode 100644 index 00000000..54a0a08e --- /dev/null +++ b/cs-cz/css.html.markdown @@ -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ě už 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, má 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` má 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. Má 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 až 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) diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown new file mode 100644 index 00000000..babd46a2 --- /dev/null +++ b/cs-cz/elm.html.markdown @@ -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. +[1..5] + +-- Spojovat seznamy lze stejně jako řetězce. +[1..5] ++ [6..10] == [1..10] -- True + +-- K přidání položky do seznamu použijte funkci "cons". +0 :: [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 [1..5] -- Just 1 +List.tail [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 [1..4] -- [2, 4, 6, 8] + +-- Nebo použijte anonymní funkci. +List.map (\a -> a * 2) [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 [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-html + +-- Porovnejte změny mezi verzemi jednoho balíčku. +$ elm package diff evancz/elm-html 3.0.0 4.0.2 +-- 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! diff --git a/cs-cz/hack.html.markdown b/cs-cz/hack.html.markdown new file mode 100644 index 00000000..736ad7e0 --- /dev/null +++ b/cs-cz/hack.html.markdown @@ -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). diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown new file mode 100644 index 00000000..0b053595 --- /dev/null +++ b/cs-cz/javascript.html.markdown @@ -0,0 +1,551 @@ +--- +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 mě, 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 + +// 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!" + +// 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á 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 + +// 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 + +// 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) +} + +// 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. diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index b498046a..581ed3a3 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -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 --- diff --git a/csharp.html.markdown b/csharp.html.markdown index 7be34fb9..8d185462 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -212,10 +212,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 diff --git a/css.html.markdown b/css.html.markdown index 4ec95f8b..5dae06ca 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,17 +7,23 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - ["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 @@ -67,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; } @@ -114,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 {} @@ -133,9 +140,9 @@ selector::after {} #################### */ 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 */ @@ -144,14 +151,14 @@ selector { 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 */ @@ -162,10 +169,10 @@ selector { 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 */ - + /* 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 */ @@ -196,7 +203,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 (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) . +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. @@ -225,18 +238,25 @@ and the following markup: <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. ## 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 diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown new file mode 100644 index 00000000..ae036d70 --- /dev/null +++ b/de-de/d-de.html.markdown @@ -0,0 +1,250 @@ +--- +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 + // .. erstellt eine spanne von zahlen, exklusive dem Ende + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + 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); + } +} + +``` diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown new file mode 100644 index 00000000..2b1471a8 --- /dev/null +++ b/de-de/rust-de.html.markdown @@ -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 `box`, `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) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown index 327dc1a0..9404679c 100644 --- a/el-gr/css-gr.html.markdown +++ b/el-gr/css-gr.html.markdown @@ -22,12 +22,11 @@ lang: el-gr ## ΚΑΝΟΝΕΣ #################### */ -/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). +/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). */ selector { property: value; /* περισσότερες ιδιότητες...*/ } /* -Αυτό είναι ενα παράδειγμα αντικειμένου¨ - +Αυτό είναι ενα παράδειγμα αντικειμένου <div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> */ diff --git a/el-gr/java-gr.html.markdown b/el-gr/java-gr.html.markdown new file mode 100644 index 00000000..21c4023b --- /dev/null +++ b/el-gr/java-gr.html.markdown @@ -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) diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown new file mode 100644 index 00000000..f3fe1614 --- /dev/null +++ b/es-es/asymptotic-notation-es.html.markdown @@ -0,0 +1,170 @@ +--- +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) diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index bcc775e5..07c8bc03 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -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"] diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown index 05dc0cc5..edc5d38c 100644 --- a/es-es/forth-es.html.markdown +++ b/es-es/forth-es.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: forth contributors: - ["Horse M.D.", "http://github.com/HorseMD/"] diff --git a/es-es/groovy-es.html.markdown b/es-es/groovy-es.html.markdown new file mode 100644 index 00000000..799fc609 --- /dev/null +++ b/es-es/groovy-es.html.markdown @@ -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 diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 34428f42..31512dc4 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -16,7 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. -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 @@ -82,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 diff --git a/es-es/pythonstatcomp-es.html.markdown b/es-es/pythonstatcomp-es.html.markdown new file mode 100644 index 00000000..0130b72a --- /dev/null +++ b/es-es/pythonstatcomp-es.html.markdown @@ -0,0 +1,238 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp-es.py +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + +Este es un tutorial de como realizar tareas típicas de programación estadística usando Python. Está destinado a personas con cierta familiaridad con Python y con experiencia en programación estadística en lenguajes como R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Cómo configurar ==== + +""" Configurar con IPython y pip install lo siguiente: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Asegúrese de realizar este tutorial con el IPython notebook para tener fácil + acceso a las ayudas en tiempo real y la documentación respectiva. +""" + +# 1. Captura de datos ==== + +""" Muchos prefieren Python sobre R ya que quieren interactuar mucho + con la web, bien sea haciendo webscraping o solicitando datos mediante + un API. Esto se puede hacer en R, pero en el contexto de un proyecto + que ya usa Python, existen beneficios al mantener un solo lenguaje. +""" + +import requests # para llamados HTTP (webscraping, APIs) +import os + +# webscraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # si es 200, el llamado ha sido exitoso +r.text # código fuente de la página +print(r.text) # formateado y embellecido +# graba el código fuente en un fichero: +os.getcwd() # verifica cual es el directorio de trabajo +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# descargando un csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" para saber más del módulo de peticiones, incluyendo APIs, ver + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Leyendo un fichero CSV ==== + +""" El paquete pandas de Wes McKinney brinda objetos 'DataFrame' en Python. Si + has usado R, ya estarás familiarizado con la idea de "data.frame". +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# nombre edad peso especies +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" Usuarios de R: notar que Python, al igual que otros lenguajes de programación + normales, comienza indexando desde 0. R de forma inusual comienza desde 1. +""" + +# dos formas distintas de imprimir una columna +pets.age +pets["age"] + +pets.head(2) # imprime las primeras dos filas +pets.tail(1) # imprime la última fila + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# en R, puedes esperar obtener 3 filas haciendo esto, pero aquí obtienes 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" Si estás procesando grandes cantidades de cálculos de álgebra lineal, podrías + querer usar matrices, no DataFrames. Los DataFrames son ideales para combinar + columnas de diferentes tipos. +""" + +# 3. Gráficas ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# Para hacer virtualización de datos en Python, usa matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn está por encima de matplotlib y logra mejores gráficos + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# también hay algunas funciones gráficas específicas de seaborn +# nota como seaborn etiqueta automáticamente el eje x en este gráfico de barras +sns.barplot(pets["age"]) + +# los veteranos de R pueden seguir usando ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# fuente: https://pypi.python.org/pypi/ggplot + +# incluso hay un porteo d3.js: https://github.com/mikedewar/d3py + +# 4. Limpieza simple de datos y análisis exploratorio ==== + +""" Tenemos ahora un ejemplo más complicado que demuestra un flujo básico para + limpieza de datos que lleva a la creación de algunos gráficos exploratorios + y la ejecución de una regresión lineal. + El conjunto de datos fue transcrito de Wikipedia a mano. Contiene + todos los Emperadores Romanos Sagrados y fechas claves en sus vidas + (nacimiento, muerte, coronación, etc.). + El objetivo del análisis es explorar si existe alguna relación + entre el año de nacimiento del Emperador y su tiempo de vida. + fuente de datos: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# cargar algunos datos de los Emperadores Romanos Sagrados +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# limpiar las columnas de Nacimiento y Muerte + +import re # módulo para expresiones regulares + +rx = re.compile(r'\d+$') # coincidencia de últimos dígitos + +""" Esta función aplica una expresión regular a una columna de entrada (Birth, + Death), nivela la lista resultante, la convierte en un objeto Series, y + finalmente convierte el tipo del objeto Series de string a entero. Para + más información sobre que hace cada parte del código, ver: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# hacer una columna decir la edad estimada +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# gráfica de dispersión simple, sin línea de tendencia, el color representa dinastía +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# usa scipy para hacer regresiones lineales +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# código fuente: http://wiki.scipy.org/Cookbook/LinearRegression + +# verifica la pendiente (slope) +slope # 0.0057672618839073328 + +# verifica el valor R^2 : +rval**2 # 0.020363950027333586 + +# verifica el valor p +pval # 0.34971812581498452 + +# usa seaborn para hacer un gráfico de dispersión y dibujar una regresión lineal +# de la tendencia +sns.lmplot("BirthY", "EstAge", data=hre); + +""" Para más información sobre seaborn, ver + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + Para más información sobre SciPy, ver + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + Para ver una versión del análisis de los Emperadores Romanos usando R, ver + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +Si quieres aprender más, obtén _Python for Data Analysis_ por Wes McKinney. Es un extraordinario recurso usado como referencia para escribir este tutorial. + +También puedes encontrar gran cantidad de tutoriales interactivos de IPython en temas específicos a tus intereses, como Pilon de Cam Davidson <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Probabilistic Programming and Bayesian Methods for Hackers">Probabilistic Programming and Bayesian Methods for Hackers</a>. + +Ver más módulos para investigar: + - análisis de texto y procesamiento natural del lenguaje: nltk, http://www.nltk.org + - análisis de redes sociales: igraph, http://igraph.org/python/ diff --git a/es-es/self-es.html.markdown b/es-es/self-es.html.markdown new file mode 100644 index 00000000..11972214 --- /dev/null +++ b/es-es/self-es.html.markdown @@ -0,0 +1,163 @@ +--- +language: self +contributors: + - ["Russell Allen", "http://github.com/russellallen"] +filename: learnself-es.self +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + +Self es un lenguaje OO basado en prototipo rápido que corre en su propio vm JIT. La mayoría del desarrollo se hace a través de la interacción con objetos vivos en un entorno de desarrollo visual llamado *morphic* que tiene integrado navegador y depurador. + +Todo en Self es un objeto. Todos los cómputos son hechos enviando mensajes a los objetos. En Self se puede entender por Objetos a los conjuntos de pares clave-valor. + +# Construyendo objetos + +El intérprete incorporado de Self puede construir objetos, incluyendo objetos-métodos. + +``` +"Esto es un comentario" + +"Una cadena de caracteres (string):" +'Esto es un string con \'caracteres\' escapados.\n' + +"Un entero de 30 bits" +23 + +"Un decimal de 30 bits" +3.2 + +"-20" +-14r16 + +"Un objeto que solo entiende un mensaje, 'x' que regresa 20" +(| + x = 20. +|) + +"Un objeto que además entiende 'x:' que establece la posición x" +(| + x <- 20. +|) + +"Un objeto que entiende el método 'doubleX' el cual +duplica el valor de x y luego regresa el objeto" +(| + x <- 20. + doubleX = (x: x * 2. self) +|) + +"Un objeto que entiende todos los mensajes +que 'traits point' entiende". El intérprete +mira a 'traits point' enviando los mensajes +'traits' y luego 'point' a un objeto conocido llamado +el 'lobby'. El mira el objeto 'true' enviando +también el mensaje 'true' al lobby." +(| parent* = traits point. + x = 7. + y <- 5. + isNice = true. +|) +``` + +# Enviando mensajes a los objetos + +Los mensajes pueden ser unarios, binarios o palabras clave. La precedencia es en ese orden. A diferencia de Smalltalk, la precedencia de los mensajes binarios debe ser especificada, y todas las palabras clave después de la primera deben comenzar con una letra mayúscula. Los mensajes se separan de sus destinos mediante espacios en blanco. + +``` +"mensaje unario, envía 'printLine' al objeto '23' +que imprime el string '23' en stdout y regresa el objeto recibido (ejem 23)" +23 printLine + +"envía el mensaje '+' con '7' para '23', luego el mensaje '*' con '8' para el resultado" +(23 + 7) * 8 + +"envía 'power:' para '2' con '8' regresa 256" +2 power: 8 + +"envía 'keyOf:IfAbsent:' para 'hello' con los argumentos 'e' y '-1'. +Regresa 1, el índice de 'e' en 'hello'." +'hello' keyOf: 'e' IfAbsent: -1 +``` + +# Bloques + +Self define el control de flujo como Smalltalk y Ruby mediante bloques Los bloques son cómputos demorados de la forma.: + +``` +[|:x. localVar| x doSomething with: localVar] +``` + +Ejemplos del uso de bloques: + +``` +"regresa 'HELLO'" +'hello' copyMutable mapBy: [|:c| c capitalize] + +"regresa 'Nah'" +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] + +"regresa 'HaLLO'" +'hello' copyMutable mapBy: [|:c| + c = 'e' ifTrue: [c capitalize] + False: ['a']] +``` + +Las expresiones múltiples son separadas por un punto. ^ retorna inmediatamente. + +``` +"returns An 'E'! How icky!" +'hello' copyMutable mapBy: [|:c. tmp <- ''| + tmp: c capitalize. + tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. + c capitalize + ] +``` + +Los bloques son ejecutados al enviales el mensaje 'value' y son inherentes (delegados a) sus contextos: +``` +"returns 0" +[|x| + x: 15. + "Envía repetidamente 'value' al primer bloque mientras el resultado de enviar 'value' al segundo bloque es el objeto 'true'" + [x > 0] whileTrue: [x: x - 1]. + x +] value +``` + +# Métodos + +Los métodos son como los bloques pero no están dentro de un contexto sino que son almacenados como valores de ranuras. A diferencia de Smalltalk, los métodos no regresan por defecto 'self' sino su valor final. + +``` +"Aquí tenemos un objeto con una ranura asignable 'x' y un método 'reduceXTo: y'. +Enviando el mensaje 'reduceXTo: 10' a este objeto pondrá +el objeto '10' en la ranura 'x' y regresará el objeto original" +(| + x <- 50. + reduceXTo: y = ( + [x > y] whileTrue: [x: x - 1]. + self) +|) +. +``` + +# Prototipos + +Self no posee clases. La forma de acceder a un objeto es encontrando un prototipo y copiándolo. + +``` +| d | +d: dictionary copy. +d at: 'hello' Put: 23 + 8. +d at: 'goodbye' Put: 'No!. +"Prints No!" +( d at: 'goodbye' IfAbsent: 'Yes! ) printLine. +"Prints 31" +( d at: 'hello' IfAbsent: -1 ) printLine. +``` + +# Para mayor información + +El [Manual de Self](http://handbook.selflanguage.org) tiene mucha más información, y nada mejor que experiencia de primera mano con Self descargándolo de su [página web](http://www.selflanguage.org). diff --git a/es-es/typescript-es.html.markdown b/es-es/typescript-es.html.markdown new file mode 100644 index 00000000..c42da4a4 --- /dev/null +++ b/es-es/typescript-es.html.markdown @@ -0,0 +1,172 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript-es.ts +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + +TypeScript es un lenguaje cuyo objetivo es facilitar el desarrollo de aplicaciones a gran escala escritas en JavaScript. +TypeScript añade conceptos comunes como clases, módulos, interfaces, genéricos y (opcionalmente) tipeo estático a JavaScript. +Es un superset de JavaScript: todo el código JavaScript es código válido en TypeScript de manera que se puede integrar fácilmente a cualquier proyecto . El compilador TypeScript emite JavaScript. + +Este artículo se enfocará solo en la sintáxis extra de TypeScript, y no en [JavaScript] (../javascript/). + +Para probar el compilador de TypeScript, diríjase al [Área de Pruebas] (http://www.typescriptlang.org/Playground) donde podrá tipear código, y ver como se auto-completa al tiempo que ve el código emitido JavaScript. + +```js +// Existen 3 tipos básicos en TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Cuando es imposible de saber, tenemos el tipo "Any" +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okey, definitivamente un boolean + +// Para colecciones, hay matrices de tipos y matrices genéricas +var list: number[] = [1, 2, 3]; +// Alternativamente, usando la matriz genérica +var list: Array<number> = [1, 2, 3]; + +// Para enumeradores: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Finalmente, "void" es usado para el caso especial de una función que no retorna nada +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Las funciones son ciudadanos de primera clase, soportan la sintáxis lambda "fat arrow" y +// usan el tipo inferencia + +// Lo siguiente es equivalante, la misma firma será inferida por el +// compilador, y el mismo JavaScript será emitido +var f1 = function(i: number): number { return i * i; } +// Retorna tipo inferido +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Retorna tipo inferido +var f4 = (i: number) => { return i * i; } +// Retorna tipo inferido, one-liner significa que no es necesario que regresen palabras claves +var f5 = (i: number) => i * i; + +// Las interfaces son estructurales, todo lo que tenga las propiedades cumple con +// la interfase +interface Person { + name: string; + // Propiedades opcionales, marcadas con un "?" + age?: number; + // Y por supuesto funciones + move(): void; +} + +// Objeto que implementa la interfase "Persona" +// Puede ser tratada como Persona ya que posee las propiedades name y move +var p: Persona = { name: "Bobby", move: () => {} }; +// Objetos que tienen propiedades opcionales: +var validPersona: Persona = { name: "Bobby", age: 42, move: () => {} }; +// No es una persona porque su edad no es un número +var invalidPersona: Persona = { name: "Bobby", age: true }; + +// Las interfases también pueden describir un tipo de función +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Solo los tipos de parámetros son importantes, los nombres no son importantes. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Clases - los miembros son públicos por defecto +class Point { + // Properties + x: number; + + // Constructor - las palabras clave public/private en este contexto generarán + // un código boiler plate para la propiedad y la inicialización en el + // constructor. + // En este ejemplo, "y" debe ser definida al igual que "x" lo es, pero con menos código + // También son soportados valores por defecto + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funciones + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Miembros estáticos + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y será 0 + +// Herencia +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Un llamado explícito al constructor de la super clase es indispensable + } + + // Sobrescribir + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Módulos, los "." pueden ser usados como separadores para los submódulos +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Un alias local para referirse a un módulo +import G = Geometry; + +var s2 = new G.Square(10); + +// Genéricos +// Clases +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfases +interface Pair<T> { + item1: T; + item2: T; +} + +// Y funciones +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Incluyendo referencias a un archivo de definición: +/// <reference path="jquery.d.ts" /> + +``` + +## Para mayor información + * [Sitio Oficial de TypeScript] (http://www.typescriptlang.org/) + * [Especificaciones del lenguaje TypeScript (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introduciendo TypeScript en Canal 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Código fuente en GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repositorio para definiciones de tipo] (http://definitelytyped.org/) diff --git a/git.html.markdown b/git.html.markdown index 282abbd2..47bac3ba 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Betsy Lorton" , "http://github.com/schbetsy"] - ["Bruno Volcov", "http://github.com/volcov"] - ["Andrew Taylor", "http://github.com/andrewjt71"] + - ["Jason Stathopulos", "http://github.com/SpiritBreaker226"] filename: LearnGit.txt --- @@ -24,9 +25,12 @@ Version control is a system that records changes to a file(s), over time. ### Centralized Versioning VS Distributed Versioning -* Centralized version control focuses on synchronizing, tracking, and backing up files. -* Distributed version control focuses on sharing changes. Every change has a unique id. -* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. +* Centralized version control focuses on synchronizing, tracking, and backing +up files. +* Distributed version control focuses on sharing changes. Every change has a +unique id. +* Distributed systems have no defined structure. You could easily have a SVN +style, centralized system, with git. [Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -42,7 +46,6 @@ Version control is a system that records changes to a file(s), over time. ## Git Architecture - ### Repository A set of files, directories, historical records, commits, and heads. Imagine it @@ -53,7 +56,8 @@ A git repository is comprised of the .git directory & working tree. ### .git Directory (component of repository) -The .git directory contains all the configurations, logs, branches, HEAD, and more. +The .git directory contains all the configurations, logs, branches, HEAD, and +more. [Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) ### Working Tree (component of repository) @@ -63,16 +67,16 @@ referred to as your working directory. ### Index (component of .git dir) -The Index is the staging area in git. It's basically a layer that separates your working tree -from the Git repository. This gives developers more power over what gets sent -to the Git repository. +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power +over what gets sent to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your Working -Tree. For example, if you added 5 files, and removed 2 others, these changes -will be contained in a commit (or snapshot). This commit can then be pushed to -other repositories, or not! +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be +pushed to other repositories, or not! ### Branch @@ -86,11 +90,14 @@ functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) -HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. -head is a pointer that points to any commit. A repository can have any number of heads. +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number +of heads. ### Stages of Git -* Modified - Changes have been made to a file but file has not been committed to Git Database yet +* Modified - Changes have been made to a file but file has not been committed +to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot * Committed - Files have been committed to the Git Database @@ -99,14 +106,12 @@ head is a pointer that points to any commit. A repository can have any number of * [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) * [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) - ## Commands - ### init -Create an empty Git repository. The Git repository's settings, stored information, -and more is stored in a directory (a folder) named ".git". +Create an empty Git repository. The Git repository's settings, stored +information, and more is stored in a directory (a folder) named ".git". ```bash $ git init @@ -117,7 +122,6 @@ $ git init To configure settings. Whether it be for the repository, the system itself, or global configurations ( global config file is `~/.gitconfig` ). - ```bash # Print & Set Some Basic Config Variables (Global) $ git config --global user.email "MyEmail@Zoho.com" @@ -158,13 +162,11 @@ $ echo "temp/" >> .gitignore $ echo "private_key" >> .gitignore ``` - ### status To show differences between the index file (basically your working copy/repo) and the current HEAD commit. - ```bash # Will display the branch, untracked files, changes and other differences $ git status @@ -175,8 +177,8 @@ $ git help status ### add -To add files to the staging area/index. If you do not `git add` new files to the -staging area/index, they will not be included in commits! +To add files to the staging area/index. If you do not `git add` new files to +the staging area/index, they will not be included in commits! ```bash # add a file in your current working directory @@ -194,7 +196,8 @@ working directory/repo. ### branch -Manage your branches. You can view, edit, create, delete branches using this command. +Manage your branches. You can view, edit, create, delete branches using this +command. ```bash # list existing branches & remotes @@ -221,54 +224,64 @@ Manage your tags ```bash # List tags $ git tag + # Create a annotated tag # The -m specifies a tagging message,which is stored with the tag. # If you don’t specify a message for an annotated tag, # Git launches your editor so you can type it in. $ git tag -a v2.0 -m 'my version 2.0' + # Show info about tag # That shows the tagger information, the date the commit was tagged, # and the annotation message before showing the commit information. $ git show v2.0 + # Push a single tag to remote $ git push origin v2.0 + # Push a lot of tags to remote $ git push origin --tags ``` ### checkout -Updates all files in the working tree to match the version in the index, or specified tree. +Updates all files in the working tree to match the version in the index, or +specified tree. ```bash # Checkout a repo - defaults to master branch $ git checkout + # Checkout a specified branch $ git checkout branchName + # Create a new branch & switch to it # equivalent to "git branch <name>; git checkout <name>" + $ git checkout -b newBranch ``` ### clone Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you to push -to a remote branch. +remote-tracking branches for each branch in the cloned repo, which allows you +to push to a remote branch. ```bash # Clone learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git + # shallow clone - faster cloning that pulls only latest snapshot $ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + # clone only a specific branch $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch ``` ### commit -Stores the current contents of the index in a new "commit." This commit contains -the changes made and a message created by the user. +Stores the current contents of the index in a new "commit." This commit +contains the changes made and a message created by the user. ```bash # commit with a message @@ -383,7 +396,8 @@ $ git pull origin master $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git pull <remote> <branch>, git rebase <branch>" +# branch commits onto your local repo, like: "git fetch <remote> <branch>, git +# rebase <remote>/<branch>" $ git pull origin master --rebase ``` @@ -409,8 +423,8 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a stack -of unfinished changes that you can reapply at any time. +Stashing takes the dirty state of your working directory and saves it on a +stack of unfinished changes that you can reapply at any time. Let's say you've been doing some work in your git repo, but you want to pull from the remote. Since you have dirty (uncommited) changes to some files, you @@ -441,7 +455,8 @@ nothing to commit, working directory clean ``` You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +change will be at top. ```bash $ git stash list @@ -471,7 +486,8 @@ Now you're ready to get back to work on your stuff! ### rebase (caution) -Take all changes that were committed on one branch, and replay them onto another branch. +Take all changes that were committed on one branch, and replay them onto +another branch. *Do not rebase commits that you have pushed to a public repo*. ```bash @@ -485,8 +501,8 @@ $ git rebase master experimentBranch ### reset (caution) Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you don't -know what you are doing. +pulls, commits, adds, and more. It's a great command but also dangerous if you +don't know what you are doing. ```bash # Reset the staging area, to match the latest commit (leaves dir unchanged) @@ -504,11 +520,37 @@ $ git reset 31f2bb1 # after the specified commit). $ git reset --hard 31f2bb1 ``` + +### reflog (caution) + +Reflog will list most of the git commands you have done for a given time period, +default 90 days. + +This give you the a change to reverse any git commands that have gone wrong +for instance if a rebase is has broken your application. + +You can do this: + +1. `git reflog` to list all of the git commands for the rebase +``` +38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog +38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators +4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown +34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) +ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) +2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d +``` +2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` +3. 'git reset --hard HEAD@{5}' this will reset your repo to that head +4. You can start the rebase again or leave it alone. + +[Additional Reading.](https://git-scm.com/docs/git-reflog) + ### revert -Revert can be used to undo a commit. It should not be confused with reset which restores -the state of a project to a previous point. Revert will add a new commit which is the -inverse of the specified commit, thus reverting it. +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new +commit which is the inverse of the specified commit, thus reverting it. ```bash # Revert a specified commit @@ -550,4 +592,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) * [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) - diff --git a/groovy.html.markdown b/groovy.html.markdown index 94678c39..a3a45757 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -99,7 +99,7 @@ technologies.sort() // To sort without mutating original, you can do: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/e +/*** Manipulating Lists ***/ //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown index 52e61449..ca346f6c 100644 --- a/id-id/json-id.html.markdown +++ b/id-id/json-id.html.markdown @@ -1,11 +1,12 @@ --- language: json -filename: learnjson.json +filename: learnjson-id.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -translators +translators: - ["Rizky Luthfianto", "https://github.com/rilut"] +lang: id-id --- JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, diff --git a/id-id/ruby-id.html.markdown b/id-id/ruby-id.html.markdown new file mode 100644 index 00000000..28135da1 --- /dev/null +++ b/id-id/ruby-id.html.markdown @@ -0,0 +1,622 @@ +--- +language: ruby +filename: learnruby-id.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] +translators: + - ["Ukaza Perdana", "https://github.com/ukazap"] +lang: id-id +--- + +```ruby +# Ini adalah sebuah komentar + +=begin +Ini adalah komentar multibaris +Tak seorang pun menggunakannya +Kamu juga tidak perlu +=end + +# Pertama-tama dan yang terpenting: Semuanya adalah objek. + +# Angka adalah objek + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Beberapa aritmetika dasar +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# Operator-operator bitwise +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Aritmetika tidak lain adalah pemanis sintaks (syntactic sugar) +# untuk memanggil sebuah metode pada suatu objek +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Nilai-nilai khusus adalah objek +nil # setara dengan "null" di bahasa-bahasa lain +true # kebenaran +false # ketidakbenaran + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Kesamaan +1 == 1 #=> true +2 == 1 #=> false + +# Ketidaksamaan +1 != 1 #=> false +2 != 1 #=> true + +# selain false itu sendiri, nil adalah nilai lain yang "salah" +!nil #=> true +!false #=> true +!0 #=> false + +# Perbandingan lain +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Operator pembanding yang dikombinasikan ("spaceship operator") +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Operator-operator logika +true && false #=> false +true || false #=> true +!true #=> false + +# Terdapat versi-versi operator logika yang berbeda dengan lebih sedikit awalan. +# Mereka digunakan sebagai kendali alur untuk merangkai beberapa pernyataan +# hingga salah satunya mengembalikan (return) nilai true atau false. + +# `lakukan_suatu_lainnya` hanya dipanggil jika `lakukan_sesuatu` berhasil. +lakukan_sesuatu() and lakukan_suatu_lainnya() +# `catat_error` hanya dipanggil jika `lakukan_sesuatu` gagal. +lakukan_sesuatu() or catat_error() + + +# String adalah objek + +'Aku adalah string'.class #=> String +"Aku juga adalah string".class #=> String + +wadah = 'menggunakan string interpolation' +"Aku bisa #{wadah} ketika memakai tanda kutip ganda" +#=> "Aku bisa menggunakan string interpolation ketika memakai tanda kutip ganda" + +# Gunakan tanda kutip tunggal daripada tanda kutip ganda jika memungkinkan +# String bertanda kutip ganda melakukan kalkulasi tambahan di dalam + +# Kombinasikan string, tapi tidak dengan angka +'halo ' + 'dunia' #=> "halo dunia" +'halo ' + 3 #=> TypeError: can't convert Fixnum into String +'halo ' + 3.to_s #=> "halo 3" + +# Kombinasikan string dengan operator +'halo ' * 3 #=> "halo halo halo " + +# Membubuhkan ke string +'halo' << ' dunia' #=> "halo dunia" + +# cetak ke output dan buat baris baru (newline) di akhir +puts "Aku mencetak!" +#=> Aku mencetak! +#=> nil + +# cetak ke output tanpa baris baru +print "Aku mencetak!" +#=> Aku mencetak! => nil + +# Variabel +x = 25 #=> 25 +x #=> 25 + +# Catat bahwa pemberian nilai mengembalikan nilai yang diberikan +# Artinya kamu bisa melakukan pemberian nilai secara jamak: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Berdasarkan adat, gunakan gaya snake_case untuk menulis nama variabel +snake_case = true + +# Gunakan nama variabel yang deskriptif +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Simbol (adalah objek) +# Simbol adalah konstanta yang dapat didaur ulang yang tidak dapat diubah +# (immutable), secara internal diwakili oleh nilai integer. Seringkali +# digunakan sebagai pengganti string untuk menyampaikan nilai yang mengandung +# makna spesifik secara efisien. + +:menunggu.class #=> Symbol + +status = :menunggu + +status == :menunggu #=> true + +status == 'menunggu' #=> false + +status == :diterima #=> false + +# Array + +# Ini adalah sebuah array +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Array bisa menampung item dengan beragam tipe + +[1, 'halo', false] #=> [1, "halo", false] + +# Array bisa di-indeks-kan +# Dari depan +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + +# Sama dengan aritmetika, pengaksesan [var] +# hanyalah pemanis sintaks +# untuk memanggil metode [] pada suatu objek +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Dari belakang +array[-1] #=> 5 +array.last #=> 5 + +# Dengan indeks awal dan panjang (jumlah item) +array[2, 3] #=> [3, 4, 5] + +# Membalik sebuah Array +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Atau menggunakan jangkauan (range) +array[1..3] #=> [2, 3, 4] + +# Tambahkan ke array seperti ini +array << 6 #=> [1, 2, 3, 4, 5, 6] +# Atau seperti ini +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Periksa apakah suatu item ada dalam sebuah array +array.include?(1) #=> true + +# Hash adalah kamus utama Ruby berupa pasangan kunci/nilai (key/value pair). +# Hash ditandai dengan kurung kurawal: +hash = { 'warna' => 'hijau', 'angka' => 5 } + +hash.keys #=> ['warna', 'angka'] + +# Nilai dalam Hash bisa diperoleh menggunakan kunci: +hash['warna'] #=> 'hijau' +hash['angka'] #=> 5 + +# Meminta hash untuk kunci yang tidak ada akan mengembalikan nil: +hash['tidak ada di sini'] #=> nil + +# Sejak Ruby 1.9, ada sintaks khusus ketika menggunakan simbol sebagai kunci: + +hash_baru = { defcon: 3, action: true } + +hash_baru.keys #=> [:defcon, :action] + +# Periksa ada/atau tidaknya kunci dan nilai dalam hash +hash_baru.key?(:defcon) #=> true +hash_baru.value?(3) #=> true + +# Tip: Baik array maupun hash adalah Enumerable +# Mereka berbagi banyak metode yang berguna diantaranya each, map, count, dll. + +# Struktur-struktur kendali + +if true + 'pernyataan if' +elsif false + 'else if, opsional' +else + 'else, opsional juga' +end + +for penghitung in 1..5 + puts "iterasi #{penghitung}" +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# NAMUN, tidak ada orang yang menggunakan pengulangan for. +# Sebagai ganti, gunakan metode "each" dan memberinya sebuah blok (block). +# Blok adalah serangkaian kode yang bisa dimasukkan ke metode seperti "each". +# Ia serupa dengan lambda, fungsi anonim atau closure di bahasa lainnya. +# +# Metode "each" dari range menjalankan blok untuk setiap elemen dari range. +# Bloknya diberikan penghitung sebagai parameter. +# Memanggil metode "each" dengan blok terlihat seperti ini: + +(1..5).each do |penghitung| + puts "iterasi #{penghitung}" +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# Kamu juga bisa mengurung blok dalam kurung kurawal: +(1..5).each { |penghitung| puts "iterasi #{penghitung}" } + +# Isi dari struktur-struktur data juga bisa di-iterasi menggunakan each. +array.each do |elemen| + puts "#{elemen} adalah bagian dari array" +end +hash.each do |kunci, nilai| + puts "#{kunci} adalah #{nilai}" +end + +# Jika kamu masih membutuhkan indeks, bisa menggunakan "each_with_index" +# dan definisikan variabel indeks +array.each_with_index do |elemen, indeks| + puts "#{elemen} adalah nomor #{indeks} dalam array" +end + +penghitung = 1 +while penghitung <= 5 do + puts "iterasi #{penghitung}" + penghitung += 1 +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# Ada kumpulan fungsi pengulangan lainnya yang berguna di Ruby, +# contohnya "map", "reduce", "inject", daftarnya sangat panjang. Map, +# misalnya, mengambil array yang di-iterasi-nya, melakukan sesuatu pada +# setiap elemen sesuai definisi pada blok, dan mengembalikan array baru. +array = [1,2,3,4,5] +berganda = array.map do |elemen| + elemen * 2 +end +puts berganda +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +nilai = 'B' + +case nilai +when 'A' + puts 'Pertahankan, nak' +when 'B' + puts 'Semoga lebih beruntung di lain waktu' +when 'C' + puts 'Kamu bisa lebih baik' +when 'D' + puts 'Susah payah' +when 'F' + puts 'Kamu gagal!' +else + puts 'Sistem penilaian lainnya, heh?' +end +#=> "Semoga lebih beruntung di lain waktu" + +# case juga bisa menggunakan range +nilai = 82 +case nilai +when 90..100 + puts 'Hore!' +when 80...90 + puts 'Cukup bagus' +else + puts 'Kamu gagal!' +end +#=> "Cukup bagus" + +# penanganan kesalahan (exception handling): +begin + # kode di sini yang mungkin membangkitkan exception + raise NoMemoryError, 'Kamu kehabisan memori.' +rescue NoMemoryError => variabel_exception + puts 'NoMemoryError dibangkitkan', variabel_exception +rescue RuntimeError => variabel_exception_lainnya + puts 'RuntimeError dibangkitkan sekarang' +else + puts 'Ini dijalankan bila tidak ada exceptions sama sekali' +ensure + puts 'Kode ini akan berjalan bagaimanapun juga' +end + +# Fungsi (atau metode) + +def gandakan(x) + x * 2 +end + +# Fungsi dan semua blok secara tersirat mengembalikan nilai pernyataan terakhir +gandakan(2) #=> 4 + +# Tanda kurung bersifat optional, boleh ditiadakan jika tidak ambigu +gandakan 3 #=> 6 + +gandakan gandakan 3 #=> 12 + +def jumlah(x, y) + x + y +end + +# Argumen-argumen dari metode dipisahkan dengan koma +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Semua metode secara tersirat mempunyai parameter blok opsional +# yang bisa dipanggil dengan kata kunci 'yield' + +def kurung + puts '{' + yield + puts '}' +end + +kurung { puts 'halo dunia' } + +# { +# halo dunia +# } + + +# Kamu bisa memasukkan blok ke sebuah fungsi +# "&" adalah penanda blok yang masuk +def tamu_tamu(&blok) + blok.call 'beberapa_argumen' +end + +# Kamu bisa memasukkan daftar argumen yang akan dikonversi menjadi array +# Itulah gunanya operator splat ("*") +def tamu_tamu(*array) + array.each { |tamu| puts tamu } +end + +# Bila metode mengembalikan array, bisa memberi nilai dengan destrukturisasi +# (destructuring assignment): +def makanan + ['tempe penyet', 'sayur asam', 'nasi goreng'] +end +sarapan, makan_siang, makan_malam = makanan +sarapan #=> 'tempe penyet' +makan_malam #=> 'nasi goreng' + +# Menurut adat, nama metode yang mengembalikan boolean diakhiri tanda tanya +5.even? # false +5.odd? # true + +# Dan jika suatu metode berakhiran tanda seru, ia melakukan sesuatu yang merusak +# seperti mengubah penerimanya. Banyak metode mempunyai versi ! untuk melakukan +# perubahan dan versi non-! untuk sekedar mengembalikan perubahannya +nama_perusahaan = "Putra Sejahtera" +nama_perusahaan.upcase #=> "PUTRA SEJAHTERA" +nama_perusahaan #=> "Putra Sejahtera" +nama_perusahaan.upcase! # kali ini kita benar-benar mengubah nama_perusahaan! +nama_perusahaan #=> "PUTRA SEJAHTERA" + + +# Definisikan kelas menggunakan kata kunci class +class Manusia + + # Variabel kelas. Ini dibagi oleh semua instans (instance) dari kelas ini. + @@spesies = 'H. sapiens' + + # Inisialisasi dasar + def initialize(nama, usia = 0) + # Berikan argumen ke variabel instans "nama" dalam instans ini + @nama = nama + # Jika tidak diberi usia, nilai default dalam daftar argumen digunakan. + @usia = usia + end + + # Metode setter dasar + def nama=(nama) + @nama = nama + end + + # Metode getter dasar + def nama + @nama + end + + # Fungsi di atas bisa disingkat dengan metode attr_accessor sebagai berikut + attr_accessor :nama + + # Metode getter/setter juga bisa dibuat secara terpisah seperti ini + attr_reader :nama + attr_writer :nama + + # Metode kelas menggunakan self untuk membedakannya dari metode instans. + # Ia hanya bisa dipanggil pada kelas, bukan pada instans-nya. + def self.katakan(pesan) + puts pesan + end + + def spesies + @@spesies + end +end + + +# Membuat instans kelas +jim = Manusia.new('Jim Halpert') + +dwight = Manusia.new('Dwight K. Schrute') + +# Mari panggil beberapa metode +jim.spesies #=> "H. sapiens" +jim.nama #=> "Jim Halpert" +jim.nama = "Jim Halpert II" #=> "Jim Halpert II" +jim.nama #=> "Jim Halpert II" +dwight.spesies #=> "H. sapiens" +dwight.nama #=> "Dwight K. Schrute" + +# Panggil metode kelas +Manusia.katakan('Hai') #=> "Hai" + +# Lingkup variabel didefinisikan berdasarkan bagaimana kita memberikannya nama +# Variabel yang berawalan $ memiliki lingkup global +$var = "Aku adalah variabel global" +defined? $var #=> "global-variable" + +# Variabel yang berawalan @ memiliki lingkup instans +@var = "Aku adalah variabel instans" +defined? @var #=> "instance-variable" + +# Variabel yang berawalan @@ memiliki lingkup kelas +@@var = "Aku adalah variabel kelas" +defined? @@var #=> "class variable" + +# Variabel yang berawalan huruf kapital adalah konstanta +Var = "Aku adalah konstanta" +defined? Var #=> "constant" + +# Kelas juga adalah objek sehingga kelas bisa memiliki variabel instans. +# Variabel kelas dibagi diantara kelas dan semua pewarisnya. + +# kelas dasar +class Manusia + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(nilai) + @@foo = nilai + end +end + +# kelas turunan +class Buruh < Manusia +end + +Manusia.foo # 0 +Buruh.foo # 0 + +Manusia.foo = 2 # 2 +Buruh.foo # 2 + +# Variabel instans milik kelas tidak dibagikan dengan pewaris kelas tersebut. + +class Manusia + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(nilai) + @bar = nilai + end +end + +class Dokter < Manusia +end + +Manusia.bar # 0 +Dokter.bar # nil + +module ContohModul + def foo + 'foo' + end +end + +# Include modul mengikat metode-metodenya pada instans-instans kelas +# Extend modul mengikat metode-metodenya pada kelas + +class Orang + include ContohModul +end + +class Buku + extend ContohModul +end + +Orang.foo # => NoMethodError: undefined method `foo' for Orang:Class +Orang.new.foo # => 'foo' +Buku.foo # => 'foo' +Buku.new.foo # => NoMethodError: undefined method `foo' + +# Callbacks dijalankan ketika meng-include dan meng-extend sebuah modul + +module ContohUrusan + def self.included(base) + base.extend(MetodeKelas) + base.send(:include, MetodeInstans) + end + + module MetodeKelas + def bar + 'bar' + end + end + + module MetodeInstans + def qux + 'qux' + end + end +end + +class Sesuatu + include ContohUrusan +end + +Sesuatu.bar # => 'bar' +Sesuatu.qux # => NoMethodError: undefined method `qux' +Sesuatu.new.bar # => NoMethodError: undefined method `bar' +Sesuatu.new.qux # => 'qux' +``` + +## Sumber tambahan + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Varian dari referensi ini dengan tantangan dalam browser. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Belajar Ruby melalui serangkaian tutorial interaktif. +- [Dokumentasi resmi](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas. +- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser. diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index af8823c4..d535babc 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -10,7 +10,7 @@ contributors: - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] -filename: LearnBash.sh +filename: LearnBash-it.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown new file mode 100644 index 00000000..d745399b --- /dev/null +++ b/it-it/ruby-ecosystem-it.html.markdown @@ -0,0 +1,145 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Cristian Achille", "http://github.com/blackdev1l/"] +lang: it-it +--- + +Generalmente chi usa ruby ha l'esigenza di avere differenti versioni di Ruby +installate, gestire le proprie gemme, e le loro dipendenze. + +## Manager Ruby + +Alcune piattaforme hanno Ruby pre-installato o disponibile come pacchetto. +Molti sviluppatori Ruby non usano questi pacchetti, o se lo fanno, li usano solo +per installare dei manager Ruby, i quali permettono di installare e gestire più +versioni di Ruby in base al progetto su cui si lavora. + +Di seguito i più famosi manager Ruby: + +* [RVM](https://rvm.io/) - Installa e permette di utilizzare diverse versioni di + Ruby. RVM Ha anche il concetto di gemsets i quali isolano completamente l'ambiente di sviluppo del progetto. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Installa solamente + multiple versioni di ruby. Usa questo se vuoi maggior controllo sull'installazione di Ruby. +* [rbenv](https://github.com/sstephenson/rbenv) - + Permette solo la scelta di quale versione Ruby utilizzare. Usato insieme a ruby-build. + Utilizza questo per un maggior controllo su quale versione di Ruby utilizzare. +* [chruby](https://github.com/postmodern/chruby) - + Permette solo la scelta di quale Ruby utilizzare, simile a rbenv. + +## Ruby Versions + +Ruby fu creato da Yukihiro "Matz" Matsumoto, il [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), +(acronimo inglese che sta per "Benevolo dittatore a vita") , seppur +ultimamente non è più del tutto vera; l'implementazione di Ruby +è detta MRI (Matz' Reference Implementation), e dunque quando si legge di una +versione Ruby, essa si riferisce sempre al rilascio di una MRI + +Le tre maggiori versioni di Ruby in uso sono: + +* 2.0.0 - Rilasciata nel febbraio 2013. La maggior parte delle librerie e + framework supportano la 2.0.0 +* 1.9.3 - Rilasciata nel ottobre 2011. QUesta è la versione che molti + svluppatori usano, il supporto è + [concluso](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Il supporto per Ruby 1.8.7 è + [concluso](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +I cambiamenti tra la 1.8.7 a la 1.9.x sono maggiori di quelli tra la 1.9.3 a la +2.0.0. Per esempio, nella 1.9 vengono introdotti encodings e bytecode VM. +Esistono ancora dei progetti basati sulla 1.8.7, ma stanno diventando una +minoranza man mano che la community si trasferisce alle versioni 1.92 e +1.9.3 + +## Ruby Implementations + +L'ecosistema Ruby gode di molte implementazioni differenti di Ruby, ognuna con +particolari punti di forza, da chiarire che ogni implementazione è scritta con +un linguaggio diverso, ma esse *sono tutte Ruby*. Ogni implementazione ha +feature extra ma tutte esse possono eseguire file ruby. Per esempio, JRuby è +scritto in Java, ma non devi conoscere java per usarlo. + +Implementazioni mature e compatibili: + +* [MRI](https://github.com/ruby/ruby) - Scritto in C, Questa è l'implementazione + standard di Ruby, per definizione è 100% compatibile (con se stessa). Tutte le + altre implemetazioni mantengono la compatibilità con MRI + (vedere [RubySpec](#rubyspec) sotto). +* [JRuby](http://jruby.org/) - Scritto in Java e Ruby, Questa implementazione è + molto veloce e robusta, la forza di JRuby consiste nell'interoperabilità + tra JVM/Java, permettendo l'utilizzo di struemnti Java già esistenti, progetti + e linguaggi +* [Rubinius](http://rubini.us/) - Scritto principalmente in Ruby con un + c++ bytecode VM, molto matura e veloce, permette alcune feature riguardo VM. + +Mediamente mature e compatibili: + +* [Maglev](http://maglev.github.io/) - Sviluppata sui Gemstone, è una Smalltalk +VM, Smalltalk è degli strumenti molto utili, e questo progetto cerca di portare +questi strumenti nello sviluppo Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Porta ruby nello sviluppo iOS. + +Poco mature e compatibili: + +* [Topaz](http://topazruby.com/) - Scritto in RPython (usando PyPy come + toolchain) Topaz è un progetto ancora giovane e non compatibile, ha le + possibilità di diventare una implementazione Ruby molto performante +* [IronRuby](http://ironruby.net/) - Scritto in C# e prendendo di mira la + piattaforma .NET, lo sviluppo sembra fermo da quando Microsoft ha rimosso il + suo supporto. + +Le implementazioni Ruby possono avere una propria versione, ma hanno sempre come +target una specifica versione di MRI. Molte implementazioni hanno l'abilità di +selezionare una versione specifica di MRI. + +##RubySpec + +La maggior parte delle implementazioni Ruby dipendono pesantemente su +[RubySpec](http://rubyspec.org/). Ruby non ha una specifica ufficiale, quindi la +community ha scritto una specifica eseguibile in Ruby per testare la compatibilità +con MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) è un package manager gestito dalla communtiy +per Ruby. Rubygems viene installato con Ruby, quindi non c'è bisogno di +scaricarlo separatamente. + +I pacchetti Ruby sono chiamate "gemme", e possono essere hostate dalla community +su RubyGems.org . Ogni gemma contiene il codice sorgente e del metadata, tra cui +la versione, le dipendenze, autor* e licenz*. + +## Bundler + +[Bundler](http://bundler.io/) è un risolvitore di dipendenze, Esso usa il Gemfile +di un progetto per cercare le dipendenze, dopo di che ottiene le dipendenze delle +dipendenze ricorsivamente, Questo procedimento viene eseguito finchè tutte le +dipendenze sono state risolte e scaricate, o si fermerà se un conflitto verrà +trovato. + +Bundler genererà un error se troverà dipendenze in conflitto, Per esempio, +se la gemma A richiede la versione 3 o maggiore della gemma Z, ma la gemma B +richiede la versione 2, Bundler ti notificherà del conflitto. Questo diventa +di aiuto nel momento in cui si hanno molte gemme nel progetto, il che porta a +un grande grafo di dipendenza da risolvere. + +# Testing + +Il testing è un pezzo fondamentale della cultura Ruby, Ruby viene installato con +il proprio testing framework chiamato minitest (O TestUnit per ruby 1.8.x). +Esistono molte librerie con obiettivi differenti + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Testing frameowrk rilasciato insieme a Ruby 1.8.x +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Testing frameowrk rilasciato insieme a Ruby 1.9/2.0 +* [RSpec](http://rspec.info/) - Un testing framework che si concentra nella chiarezza +* [Cucumber](http://cukes.info/) - Un BDD testing framework che estrapola testo formattato in Gherkin + +## Sii cordiale + +La community Ruby è orgogliosa di essere una communtiy aperta, accogliente e +variegata. Matz stesso è estremamente amichevole, e la generosità degli sviluppatori +Ruby è fantastica. diff --git a/java.html.markdown b/java.html.markdown index 48e6ec75..a025bbba 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -407,9 +407,9 @@ public class LearnJava { // in an easy way. Usually you end up in the following way: private static final Set<String> COUNTRIES = new HashSet<String>(); static { - validCodes.add("DENMARK"); - validCodes.add("SWEDEN"); - validCodes.add("FINLAND"); + COUNTRIES.add("DENMARK"); + COUNTRIES.add("SWEDEN"); + COUNTRIES.add("FINLAND"); } // But there's a nifty way to achieve the same thing in an @@ -734,7 +734,7 @@ public class EnumTest { // Enum types are much more powerful than we show above. // The enum body can include methods and other fields. -// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ``` @@ -775,4 +775,4 @@ The links provided here below are just to get an understanding of the topic, fee * [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)
\ No newline at end of file +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index ae0123a7..7b1475a8 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -9,7 +9,7 @@ Kotlin is a Statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java. [Read more here.](https://kotlinlang.org/) -```kotlin +```java // Single-line comments start with // /* Multi-line comments look like this. @@ -133,7 +133,7 @@ fun helloWorld(val name : String) { The name of the single parameter will be "it". */ val notPositive = not {it > 0} - for (i in (0..4)) { + for (i in 0..4) { println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") } @@ -317,5 +317,6 @@ object ObjectExample { ### Further Reading -A web-based mini-IDE for Kotlin: -[http://try.kotlinlang.org/) +* [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/) +* [Try Kotlin in your browser](http://try.kotlinlang.org/) +* [A list of Kotlin resources](http://kotlin.link/) diff --git a/latex.html.markdown b/latex.html.markdown index d41f6b2f..81c0d24c 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -178,7 +178,7 @@ We can also insert Tables in the same way as figures. % the {} arguments below describe how each row of the table is drawn. % Again, I have to look these up. Each. And. Every. Time. \begin{tabular}{c|cc} - Number & Last Name & First Name \\ % Column rows are separated by $ + Number & Last Name & First Name \\ % Column rows are separated by & \hline % a horizontal line 1 & Biggus & Dickus \\ 2 & Monty & Python @@ -212,7 +212,7 @@ Getting to the final document using LaTeX consists of the following steps: \item Compile source code to produce a pdf. The compilation step looks something like this (in Linux): \\ \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + > pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown index 8c97e598..50e52a7a 100644 --- a/lt-lt/json-lt.html.markdown +++ b/lt-lt/json-lt.html.markdown @@ -1,6 +1,6 @@ --- language: json -filename: learnjson.json +filename: learnjson-lt.json lang: lt-lt contributors: - ["Zygimantus", "https://github.com/zygimantus"] diff --git a/markdown.html.markdown b/markdown.html.markdown index b4ad3202..bdf42368 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -7,7 +7,9 @@ filename: markdown.md --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown was created by John Gruber in 2004. It's meant to be an easy to read +and write syntax which converts easily to HTML (and now many other formats as +well). Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are @@ -28,9 +30,10 @@ specific to a certain parser. Markdown is a superset of HTML, so any HTML file is valid Markdown. ```markdown -<!--This means we can use HTML elements in Markdown, such as the comment element, -and they won't be affected by a markdown parser. However, if you create an HTML element -in your markdown file, you cannot use markdown syntax within that element's contents.--> +<!--This means we can use HTML elements in Markdown, such as the comment +element, and they won't be affected by a markdown parser. However, if you +create an HTML element in your markdown file, you cannot use markdown syntax +within that element's contents.--> ``` ## Headings @@ -214,8 +217,8 @@ highlighting of the language you specify after the \`\`\` ## Horizontal rule -Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens, -with or without spaces. +Horizontal rules (`<hr/>`) are easily added with three or more asterisks or +hyphens, with or without spaces. ```markdown *** @@ -298,7 +301,8 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys -In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys. +In GitHub Flavored Markdown, you can use a `<kbd>` tag to represent keyboard +keys. ```markdown Your computer crashed? Try sending a diff --git a/nim.html.markdown b/nim.html.markdown index 4901ebfe..5d00304d 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```javascript +```nim var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" diff --git a/nix.html.markdown b/nix.html.markdown new file mode 100644 index 00000000..ef59a135 --- /dev/null +++ b/nix.html.markdown @@ -0,0 +1,354 @@ +--- +language: nix +filename: learn.nix +contributors: + - ["Chris Martin", "http://chris-martin.org/"] +--- + +Nix is a simple functional language developed for the +[Nix package manager](https://nixos.org/nix/) and +[NixOS](https://nixos.org/). + +You can evaluate Nix expressions using +[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) +or [`nix-repl`](https://github.com/edolstra/nix-repl). + +``` +with builtins; [ + + # Comments + #========================================= + + # Inline comments look like this. + + /* Multi-line comments + look like this. */ + + + # Booleans + #========================================= + + (true && false) # And + #=> false + + (true || false) # Or + #=> true + + (if 3 < 4 then "a" else "b") # Conditional + #=> "a" + + + # Integers + #========================================= + + # Integers are the only numeric type. + + 1 0 42 (-3) # Some integers + + (4 + 6 + 12 - 2) # Addition + #=> 20 + + (7 / 2) # Division + #=> 3 + + + # Strings + #========================================= + + "Strings literals are in double quotes." + + " + String literals can span + multiple lines. + " + + '' + This is called an "indented string" literal. + It intelligently strips leading whitespace. + '' + + '' + a + b + '' + #=> "a\n b" + + ("ab" + "cd") # String concatenation + #=> "abcd" + + # Antiquotation lets you embed values into strings. + ("Your home directory is ${getEnv "HOME"}") + #=> "Your home directory is /home/alice" + + + # Paths + #========================================= + + # Nix has a primitive data type for paths. + /tmp/tutorials/learn.nix + + # A relative path is resolved to an absolute path at parse + # time, relative to the file in which it occurs. + tutorials/learn.nix + #=> /the-base-path/tutorials/learn.nix + + # A path must contain at least one slash, so a relative + # path for a file in the same directory needs a ./ prefix, + ./learn.nix + #=> /the-base-path/learn.nix + + # The / operator must be surrounded by whitespace if + # you want it to signify division. + + 7/2 # This is a path literal + (7 / 2) # This is integer division + + + # Imports + #========================================= + + # A nix file contains a single top-level expression with no free + # variables. An import expression evaluates to the value of the + # file that it imports. + (import /tmp/foo.nix) + + # Imports can also be specified by strings. + (import "/tmp/foo.nix") + + # Import paths must be absolute. Path literals + # are automatically resolved, so this is fine. + (import ./foo.nix) + + # But this does not happen with strings. + (import "./foo.nix") + #=> error: string ‘foo.nix’ doesn't represent an absolute path + + + # Let + #========================================= + + # `let` blocks allow us to bind values to variables. + (let x = "a"; in + x + x + x) + #=> "aaa" + + # Bindings can refer to each other, and their order does not matter. + (let y = x + "b"; + x = "a"; in + y + "c") + #=> "abc" + + # Inner bindings shadow outer bindings. + (let a = 1; in + let a = 2; in + a) + #=> 2 + + + # Functions + #========================================= + + (n: n + 1) # Function that adds 1 + + ((n: n + 1) 5) # That same function, applied to 5 + #=> 6 + + # There is no syntax for named functions, but they + # can be bound by `let` blocks like any other value. + (let succ = (n: n + 1); in succ 5) + #=> 6 + + # A function has exactly one argument. + # Multiple arguments can be achieved with currying. + ((x: y: x + "-" + y) "a" "b") + #=> "a-b" + + # We can also have named function arguments, + # which we'll get to later after we introduce sets. + + + # Lists + #========================================= + + # Lists are denoted by square brackets. + + (length [1 2 3 "x"]) + #=> 4 + + ([1 2 3] ++ [4 5]) + #=> [1 2 3 4 5] + + (concatLists [[1 2] [3 4] [5]]) + #=> [1 2 3 4 5] + + (head [1 2 3]) + #=> 1 + (tail [1 2 3]) + #=> [2 3] + + (elemAt ["a" "b" "c" "d"] 2) + #=> "c" + + (elem 2 [1 2 3]) + #=> true + (elem 5 [1 2 3]) + #=> false + + (filter (n: n < 3) [1 2 3 4]) + #=> [ 1 2 ] + + + # Sets + #========================================= + + # A "set" is an unordered mapping with string keys. + { foo = [1 2]; bar = "x"; } + + # The . operator pulls a value out of a set. + { a = 1; b = 2; }.a + #=> 1 + + # The // operator merges two sets. + ({ a = 1; } // { b = 2; }) + #=> { a = 1; b = 2; } + + # Values on the right override values on the left. + ({ a = 1; b = 2; } // { a = 3; c = 4; }) + #=> { a = 3; b = 2; c = 4; } + + # The rec keyword denotes a "recursive set", + # in which attributes can refer to each other. + (let a = 1; in { a = 2; b = a; }.b) + #=> 1 + (let a = 1; in rec { a = 2; b = a; }.b) + #=> 2 + + # Nested sets can be defined in a piecewise fashion. + { + a.b = 1; + a.c.d = 2; + a.c.e = 3; + }.a.c + #=> { d = 2; e = 3; } + + # An attribute's descendants cannot be assigned in this + # way if the attribute itself has been directly assigned. + { + a = { b = 1; }; + a.c = 2; + } + #=> error: attribute ‘a’ already defined + + + # With + #========================================= + + # The body of a `with` block is evaluated with + # a set's mappings bound to variables. + (with { a = 1; b = 2; }; + a + b) + # => 3 + + # Inner bindings shadow outer bindings. + (with { a = 1; b = 2; }; + (with { a = 5; }; + a + b)) + #=> 7 + + # This first line of tutorial starts with "with builtins;" + # because builtins is a set the contains all of the built-in + # functions (length, head, tail, filter, etc.). This saves + # us from having to write, for example, "builtins.length" + # instead of just "length". + + + # Set patterns + #========================================= + + # Sets are useful when we need to pass multiple values + # to a function. + (args: args.x + "-" + args.y) { x = "a"; y = "b"; } + #=> "a-b" + + # This can be written more clearly using set patterns. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; } + #=> "a-b" + + # By default, the pattern fails on sets containing extra keys. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> error: anonymous function called with unexpected argument ‘z’ + + # Adding ", ..." allows ignoring extra keys. + ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> "a-b" + + + # Errors + #========================================= + + # `throw` causes evaluation to abort with an error message. + (2 + (throw "foo")) + #=> error: foo + + # `tryEval` catches thrown errors. + (tryEval 42) + #=> { success = true; value = 42; } + (tryEval (2 + (throw "foo"))) + #=> { success = false; value = false; } + + # `abort` is like throw, but it's fatal; it cannot be caught. + (tryEval (abort "foo")) + #=> error: evaluation aborted with the following error message: ‘foo’ + + # `assert` evaluates to the given value if true; + # otherwise it throws a catchable exception. + (assert 1 < 2; 42) + #=> 42 + (assert 1 > 2; 42) + #=> error: assertion failed at (string):1:1 + (tryEval (assert 1 > 2; 42)) + #=> { success = false; value = false; } + + + # Impurity + #========================================= + + # Because repeatability of builds is critical to the Nix package + # manager, in which, functional purity is emphasized in the Nix + # language. But there are a few impurities. + + # You can refer to environment variables. + (getEnv "HOME") + #=> "/home/alice" + + # The trace function is used for debugging. It prints the first + # argument to stderr and evaluates to the second argument. + (trace 1 2) + #=> trace: 1 + #=> 2 + + # You can write files into the Nix store. Although impure, this is + # fairly safe because the file name is derived from the hash of + # its contents. You can read files from anywhere. In this example, + # we write a file into the store, and then read it back out. + (let filename = toFile "foo.txt" "hello!"; in + [filename (builtins.readFile filename)]) + #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] + + # We can also download files into the Nix store. + (fetchurl "https://example.com/package-1.2.3.tgz") + #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" + +] +``` + +### Further Reading + +* [Nix Manual - Nix expression language] + (https://nixos.org/nix/manual/#ch-expression-language) + +* [James Fisher - Nix by example - Part 1: The Nix expression language] + (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) + +* [Susan Potter - Nix Cookbook - Nix By Example] + (http://funops.co/nix-cookbook/nix-by-example/) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 097cb846..0dbb3ae3 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -110,7 +110,7 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" - // NSDecimalNumber is a fixed-point class that's more precise then float or double + // NSDecimalNumber is a fixed-point class that's more precise than float or double NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: @@ -700,7 +700,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { // NOTE: If two or more protocols rely on each other, make sure to forward-declare them: #import "Brother.h" -@protocol Brother; // Forward-declare statement. Without it, compiler would through error. +@protocol Brother; // Forward-declare statement. Without it, compiler will throw error. @protocol Sister <NSObject> diff --git a/ocaml.html.markdown b/ocaml.html.markdown index a346550c..59ead9ec 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -216,7 +216,7 @@ List.nth my_list 1 ;; (* There are higher-order functions for lists such as map and filter. *) List.map (fun x -> x * 2) [1; 2; 3] ;; -List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;; +List.filter (fun x -> x mod 2 = 0) [1; 2; 3; 4] ;; (* You can add an item to the beginning of a list with the "::" constructor often referred to as "cons". *) diff --git a/perl.html.markdown b/perl.html.markdown index 61e8cd0e..3cbd2801 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -21,9 +21,9 @@ use strict; use warnings; # All perl scripts and modules should include these lines. Strict causes -# compilation to fail in cases like misspelled variable names, and warnings -# will print warning messages in case of common pitfalls like concatenating -# to an undefined value. +# compilation to fail in cases like misspelled variable names, and +# warnings will print warning messages in case of common pitfalls like +# concatenating to an undefined value. #### Perl variable types @@ -47,8 +47,8 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); -# Array elements are accessed using square brackets, with a $ to indicate -# one value will be returned. +# Array elements are accessed using square brackets, with a $ to +# indicate one value will be returned. my $second = $animals[1]; ## Hashes @@ -56,7 +56,8 @@ my $second = $animals[1]; my %fruit_color = ("apple", "red", "banana", "yellow"); -# You can use whitespace and the "=>" operator to lay them out more nicely: +# You can use whitespace and the "=>" operator to lay them out more +# nicely: my %fruit_color = ( apple => "red", @@ -71,8 +72,8 @@ my $color = $fruit_color{apple}; #### References -# More complex data types can be constructed using references, which allow -# you to build arrays and hashes within arrays and hashes. +# More complex data types can be constructed using references, which +# allow you to build arrays and hashes within arrays and hashes. my $array_ref = \@array; my $hash_ref = \%hash; @@ -88,13 +89,14 @@ my $colors = {apple => "red", banana => "yellow"}; my @fruits_array = @$fruits; my %colors_hash = %$colors; -# As a shortcut, the arrow operator can be used to dereference and access a -# single value. +# As a shortcut, the arrow operator can be used to dereference and +# access a single value. my $first = $array_ref->[0]; my $value = $hash_ref->{banana}; -# See perlreftut and perlref for more in-depth documentation on references. +# See perlreftut and perlref for more in-depth documentation on +# references. #### Conditional and looping constructs @@ -150,18 +152,18 @@ print $hash_ref->{$_} for keys %$hash_ref; #### Regular expressions -# Perl's regular expression support is both broad and deep, and is the subject -# of lengthy documentation in perlrequick, perlretut, and elsewhere. -# However, in short: +# Perl's regular expression support is both broad and deep, and is the +# subject of lengthy documentation in perlrequick, perlretut, and +# elsewhere. However, in short: # Simple matching if (/foo/) { ... } # true if $_ contains "foo" -if ($a =~ /foo/) { ... } # true if $a contains "foo" +if ($x =~ /foo/) { ... } # true if $x contains "foo" # Simple substitution -$a =~ s/foo/bar/; # replaces foo with bar in $a -$a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a +$x =~ s/foo/bar/; # replaces foo with bar in $x +$x =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $x #### Files and I/O @@ -172,9 +174,10 @@ 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: $!"; -# You can read from an open filehandle using the "<>" operator. In scalar -# context it reads a single line from the filehandle, and in list context it -# reads the whole file in, assigning each line to an element of the list: +# You can read from an open filehandle using the "<>" operator. In +# scalar context it reads a single line from the filehandle, and in list +# context it reads the whole file in, assigning each line to an element +# of the list: my $line = <$in>; my @lines = <$in>; @@ -197,9 +200,9 @@ logger("We have a logger subroutine!"); #### Modules -# A module is a set of Perl code, usually subroutines, which can be used in -# other Perl code. It is usually stored in a file with the extension .pm so -# that Perl can find it. +# A module is a set of Perl code, usually subroutines, which can be used +# in other Perl code. It is usually stored in a file with the extension +# .pm so that Perl can find it. package MyModule; use strict; @@ -219,24 +222,25 @@ sub trim { use MyModule; MyModule::trim($string); -# The Exporter module can help with making subroutines exportable, so they -# can be used like this: +# The Exporter module can help with making subroutines exportable, so +# they can be used like this: use MyModule 'trim'; trim($string); -# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and -# provide a range of features to help you avoid reinventing the wheel. A -# number of popular modules like Exporter are included with the Perl -# distribution itself. See perlmod for more details on modules in Perl. +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) +# and provide a range of features to help you avoid reinventing the +# wheel. A number of popular modules like Exporter are included with +# the Perl distribution itself. See perlmod for more details on modules +# in Perl. #### Objects -# Objects in Perl are just references that know which class (package) they -# belong to, so that methods (subroutines) called on it can be found there. -# The bless function is used in constructors (usually new) to set this up. -# However, you never need to call it yourself if you use a module like Moose -# or Moo (see below). +# Objects in Perl are just references that know which class (package) +# they belong to, so that methods (subroutines) called on it can be +# found there. The bless function is used in constructors (usually new) +# to set this up. However, you never need to call it yourself if you use +# a module like Moose or Moo (see below). package MyCounter; use strict; @@ -260,7 +264,8 @@ sub increment { 1; -# Methods can be called on a class or object instance with the arrow operator. +# Methods can be called on a class or object instance with the arrow +# operator. use MyCounter; my $counter = MyCounter->new; @@ -268,9 +273,9 @@ print $counter->count, "\n"; # 0 $counter->increment; print $counter->count, "\n"; # 1 -# The modules Moose and Moo from CPAN can help you set up your object classes. -# They provide a constructor and simple syntax for declaring attributes. This -# class can be used equivalently to the one above. +# The modules Moose and Moo from CPAN can help you set up your object +# classes. They provide a constructor and simple syntax for declaring +# attributes. This class can be used equivalently to the one above. package MyCounter; use Moo; # imports strict and warnings @@ -284,8 +289,8 @@ sub increment { 1; -# Object-oriented programming is covered more thoroughly in perlootut, and its -# low-level implementation in Perl is covered in perlobj. +# Object-oriented programming is covered more thoroughly in perlootut, +# and its low-level implementation in Perl is covered in perlobj. ``` #### FAQ diff --git a/perl6.html.markdown b/perl6.html.markdown index 5082a433..b5a25a41 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -824,7 +824,7 @@ say why-not[^5]; #=> 5 15 25 35 45 # (they exist in other langages such as C as `static`) sub fixed-rand { state $val = rand; - say $rand; + say $val; } fixed-rand for ^10; # will print the same number 10 times diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 61e267f5..31a3110c 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -581,6 +581,31 @@ void doSomethingWithAFile(const std::string& filename) // vetor (i.e. array de autodimensionamento), mapas hash, e assim por diante // tudo é automaticamente destruído quando eles saem de escopo // - Mutex usa lock_guard e unique_lock + + +///////////////////// +// Templates +///////////////////// + +// Templates em C++ são utilizados para programação genérica, ou seja, +// utilizar um tipo de dado genérico onde possa suportar qualquer entrada. +// Por exemplo, invés de criar uma função que apenas some inteiros, você +// poderá fazer uma função que soma double, float e inteiros em uma única +// definição para reutilizar código. + +// Definimos um função que utiliza um "typename" +template<class T> +T soma(T a, T b) { + return A + B; +} + +// E agora para executá-la +int i=5, j=6, k; +double f=2.0, g=0.5, h; +k=sum<int>(i,j); +h=sum<double>(f,g); + +// Deste modo, não precisamos fazer overload nas funções! (: ``` Leitura Adicional: diff --git a/python.html.markdown b/python.html.markdown index 12be4be1..28b0a7ae 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,20 +8,22 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +or louiedinh [at] [google's email service] -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, -it is though recommended to start learning Python with Python 3. -For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with +Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, -using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. +It is also possible to write Python code which is compatible with Python 2.7 +and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the +Python 3 tutorial. ```python @@ -32,6 +34,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt as comments """ + #################################################### ## 1. Primitive Datatypes and Operators #################################################### @@ -188,6 +191,7 @@ some_other_var # Raises a name error # Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list @@ -441,6 +445,7 @@ with open("myfile.txt") as f: for line in f: print line + #################################################### ## 4. Functions #################################################### @@ -464,7 +469,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): @@ -698,7 +702,6 @@ for i in double_numbers(xrange_): # message from functools import wraps - def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): @@ -709,13 +712,11 @@ def beg(target_function): 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 :( ``` diff --git a/python3.html.markdown b/python3.html.markdown index ea29fdba..2e37fccb 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -587,12 +587,11 @@ add_10(3) # => 13 (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -# TODO - Fix for iterables # There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] # We can use list comprehensions for nice maps and filters # List comprehension stores the output as a list which can itself be a nested list diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 0b02dca8..8ee3aa64 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -1,8 +1,8 @@ --- -language: Statistical computing with Python +category: tool +tool: Statistical Computing with Python contributors: - ["e99n09", "https://github.com/e99n09"] -filename: pythonstatcomp.py --- This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. diff --git a/r.html.markdown~ b/r.html.markdown~ deleted file mode 100644 index ee9e7c90..00000000 --- a/r.html.markdown~ +++ /dev/null @@ -1,807 +0,0 @@ ---- -language: R -contributors: - - ["e99n09", "http://github.com/e99n09"] -<<<<<<< HEAD -======= - - ["isomorphismes", "http://twitter.com/isomorphisms"] - - ["kalinn", "http://github.com/kalinn"] ->>>>>>> 6e38442b857a9d8178b6ce6713b96c52bf4426eb -filename: learnr.r ---- - -R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document. - -```r - -# Comments start with number symbols. - -# You can't make multi-line comments, -# but you can stack multiple comments like so. - -# in Windows you can use CTRL-ENTER to execute a line. -# on Mac it is COMMAND-ENTER - - - -############################################################################# -# Stuff you can do without understanding anything about programming -############################################################################# - -# In this section, we show off some of the cool stuff you can do in -# R without understanding anything about programming. Do not worry -# about understanding everything the code does. Just enjoy! - -data() # browse pre-loaded data sets -data(rivers) # get this one: "Lengths of Major North American Rivers" -ls() # notice that "rivers" now appears in the workspace -head(rivers) # peek at the data set -# 735 320 325 392 524 450 - -length(rivers) # how many rivers were measured? -# 141 -summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 - -# make a stem-and-leaf plot (a histogram-like data visualization) -stem(rivers) - -# The decimal point is 2 digit(s) to the right of the | -# -# 0 | 4 -# 2 | 011223334555566667778888899900001111223333344455555666688888999 -# 4 | 111222333445566779001233344567 -# 6 | 000112233578012234468 -# 8 | 045790018 -# 10 | 04507 -# 12 | 1471 -# 14 | 56 -# 16 | 7 -# 18 | 9 -# 20 | -# 22 | 25 -# 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | -# 36 | 1 - -stem(log(rivers)) # Notice that the data are neither normal nor log-normal! -# Take that, Bell curve fundamentalists. - -# The decimal point is 1 digit(s) to the left of the | -# -# 48 | 1 -# 50 | -# 52 | 15578 -# 54 | 44571222466689 -# 56 | 023334677000124455789 -# 58 | 00122366666999933445777 -# 60 | 122445567800133459 -# 62 | 112666799035 -# 64 | 00011334581257889 -# 66 | 003683579 -# 68 | 0019156 -# 70 | 079357 -# 72 | 89 -# 74 | 84 -# 76 | 56 -# 78 | 4 -# 80 | -# 82 | 2 - -# make a histogram: -hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters -hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later - -# Here's another neat data set that comes pre-loaded. R has tons of these. -data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", - main="Number of important discoveries per year") -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", - main="Number of important discoveries per year") - -# Rather than leaving the default ordering (by year), -# we could also sort to see what's typical: -sort(discoveries) -# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 -# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 -# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 -# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 - -stem(discoveries, scale=2) -# -# The decimal point is at the | -# -# 0 | 000000000 -# 1 | 000000000000 -# 2 | 00000000000000000000000000 -# 3 | 00000000000000000000 -# 4 | 000000000000 -# 5 | 0000000 -# 6 | 000000 -# 7 | 0000 -# 8 | 0 -# 9 | 0 -# 10 | 0 -# 11 | -# 12 | 0 - -max(discoveries) -# 12 -summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 - -# Roll a die a few times -round(runif(7, min=.5, max=6.5)) -# 1 4 6 1 4 6 4 -# Your numbers will differ from mine unless we set the same random.seed(31337) - -# Draw from a standard Gaussian 9 times -rnorm(9) -# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 -# [7] -0.59975593 0.57629164 1.08455362 - - - -################################################## -# Data types and basic arithmetic -################################################## - -# Now for the programming-oriented part of the tutorial. -# In this section you will meet the important data types of R: -# integers, numerics, characters, logicals, and factors. -# There are others, but these are the bare minimum you need to -# get started. - -# INTEGERS -# Long-storage integers are written with L -5L # 5 -class(5L) # "integer" -# (Try ?class for more information on the class() function.) -# In R, every single value, like 5L, is considered a vector of length 1 -length(5L) # 1 -# You can have an integer vector with length > 1 too: -c(4L, 5L, 8L, 3L) # 4 5 8 3 -length(c(4L, 5L, 8L, 3L)) # 4 -class(c(4L, 5L, 8L, 3L)) # "integer" - -# NUMERICS -# A "numeric" is a double-precision floating-point number -5 # 5 -class(5) # "numeric" -# Again, everything in R is a vector; -# you can make a numeric vector with more than one element -c(3,3,3,2,2,1) # 3 3 3 2 2 1 -# You can use scientific notation too -5e4 # 50000 -6.02e23 # Avogadro's number -1.6e-35 # Planck length -# You can also have infinitely large or small numbers -class(Inf) # "numeric" -class(-Inf) # "numeric" -# You might use "Inf", for example, in integrate(dnorm, 3, Inf); -# this obviates Z-score tables. - -# BASIC ARITHMETIC -# You can do arithmetic with numbers -# Doing arithmetic on a mix of integers and numerics gives you another numeric -10L + 66L # 76 # integer plus integer gives integer -53.2 - 4 # 49.2 # numeric minus numeric gives numeric -2.0 * 2L # 4 # numeric times integer gives numeric -3L / 4 # 0.75 # integer over numeric gives numeric -3 %% 2 # 1 # the remainder of two numerics is another numeric -# Illegal arithmetic yeilds you a "not-a-number": -0 / 0 # NaN -class(NaN) # "numeric" -# You can do arithmetic on two vectors with length greater than 1, -# so long as the larger vector's length is an integer multiple of the smaller -c(1,2,3) + c(1,2,3) # 2 4 6 -# Since a single number is a vector of length one, scalars are applied -# elementwise to vectors -(4 * c(1,2,3) - 2) / 2 # 1 3 5 -# Except for scalars, use caution when performing arithmetic on vectors with -# different lengths. Although it can be done, -c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 -# Matching lengths is better practice and easier to read -c(1,2,3,1,2,3) * c(1,2,1,2,1,2) - -# CHARACTERS -# There's no difference between strings and characters in R -"Horatio" # "Horatio" -class("Horatio") # "character" -class('H') # "character" -# Those were both character vectors of length 1 -# Here is a longer one: -c('alef', 'bet', 'gimmel', 'dalet', 'he') -# => -# "alef" "bet" "gimmel" "dalet" "he" -length(c("Call","me","Ishmael")) # 3 -# You can do regex operations on character vectors: -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " -gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." -# R has several built-in character vectors: -letters -# => -# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" -# [20] "t" "u" "v" "w" "x" "y" "z" -month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" - -# LOGICALS -# In R, a "logical" is a boolean -class(TRUE) # "logical" -class(FALSE) # "logical" -# Their behavior is normal -TRUE == TRUE # TRUE -TRUE == FALSE # FALSE -FALSE != FALSE # FALSE -FALSE != TRUE # TRUE -# Missing data (NA) is logical, too -class(NA) # "logical" -# Use | and & for logic operations. -# OR -TRUE | FALSE # TRUE -# AND -TRUE & FALSE # FALSE -# Applying | and & to vectors returns elementwise logic operations -c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE -c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE -# You can test if x is TRUE -isTRUE(TRUE) # TRUE -# Here we get a logical vector with many elements: -c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE -c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE - -# FACTORS -# The factor class is for categorical data -# Factors can be ordered (like childrens' grade levels) or unordered (like gender) -factor(c("female", "female", "male", NA, "female")) -# female female male <NA> female -# Levels: female male -# The "levels" are the values the categorical data can take -# Note that missing data does not enter the levels -levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" -# If a factor vector has length 1, its levels will have length 1, too -length(factor("male")) # 1 -length(levels(factor("male"))) # 1 -# Factors are commonly seen in data frames, a data structure we will cover later -data(infert) # "Infertility after Spontaneous and Induced Abortion" -levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" - -# NULL -# "NULL" is a weird one; use it to "blank out" a vector -class(NULL) # NULL -parakeet = c("beak", "feathers", "wings", "eyes") -parakeet -# => -# [1] "beak" "feathers" "wings" "eyes" -parakeet <- NULL -parakeet -# => -# NULL - -# TYPE COERCION -# Type-coercion is when you force a value to take on a different type -as.character(c(6, 8)) # "6" "8" -as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE -# If you put elements of different types into a vector, weird coercions happen: -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" -as.numeric("Bilbo") -# => -# [1] NA -# Warning message: -# NAs introduced by coercion - -# Also note: those were just the basic data types -# There are many more data types, such as for dates, time series, etc. - - - -################################################## -# Variables, loops, if/else -################################################## - -# A variable is like a box you store a value in for later use. -# We call this "assigning" the value to the variable. -# Having variables lets us write loops, functions, and if/else statements - -# VARIABLES -# Lots of way to assign stuff: -x = 5 # this is possible -y <- "1" # this is preferred -TRUE -> z # this works but is weird - -# LOOPS -# We've got for loops -for (i in 1:4) { - print(i) -} -# We've got while loops -a <- 10 -while (a > 4) { - cat(a, "...", sep = "") - a <- a - 1 -} -# Keep in mind that for and while loops run slowly in R -# Operations on entire vectors (i.e. a whole row, a whole column) -# or apply()-type functions (we'll discuss later) are preferred - -# IF/ELSE -# Again, pretty standard -if (4 > 3) { - print("4 is greater than 3") -} else { - print("4 is not greater than 3") -} -# => -# [1] "4 is greater than 3" - -# FUNCTIONS -# Defined like so: -jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise - return(x) -} -# Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 - - - -########################################################################### -# Data structures: Vectors, matrices, data frames, and arrays -########################################################################### - -# ONE-DIMENSIONAL - -# Let's start from the very beginning, and with something you already know: vectors. -vec <- c(8, 9, 10, 11) -vec # 8 9 10 11 -# We ask for specific elements by subsetting with square brackets -# (Note that R starts counting from 1) -vec[1] # 8 -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 -# We can also search for the indices of specific components, -which(vec %% 2 == 0) # 1 3 -# grab just the first or last few entries in the vector, -head(vec, 1) # 8 -tail(vec, 2) # 10 11 -# or figure out if a certain value is in the vector -any(vec == 10) # TRUE -# If an index "goes over" you'll get NA: -vec[6] # NA -# You can find the length of your vector with length() -length(vec) # 4 -# You can perform operations on entire vectors or subsets of vectors -vec * 4 # 16 20 24 28 -vec[2:3] * 5 # 25 30 -any(vec[2:3] == 8) # FALSE -# and R has many built-in functions to summarize vectors -mean(vec) # 9.5 -var(vec) # 1.666667 -sd(vec) # 1.290994 -max(vec) # 11 -min(vec) # 8 -sum(vec) # 38 -# Some more nice built-ins: -5:15 # 5 6 7 8 9 10 11 12 13 14 15 -seq(from=0, to=31337, by=1337) -# => -# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 -# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 - -# TWO-DIMENSIONAL (ALL ONE CLASS) - -# You can make a matrix out of entries all of the same type like so: -mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# Unlike a vector, the class of a matrix is "matrix", no matter what's in it -class(mat) # => "matrix" -# Ask for the first row -mat[1,] # 1 4 -# Perform operation on the first column -3 * mat[,1] # 3 6 9 -# Ask for a specific cell -mat[3,2] # 6 - -# Transpose the whole matrix -t(mat) -# => -# [,1] [,2] [,3] -# [1,] 1 2 3 -# [2,] 4 5 6 - -# Matrix multiplication -mat %*% t(mat) -# => -# [,1] [,2] [,3] -# [1,] 17 22 27 -# [2,] 22 29 36 -# [3,] 27 36 45 - -# cbind() sticks vectors together column-wise to make a matrix -mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) -mat2 -# => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" -# [4,] "4" "dog" -class(mat2) # matrix -# Again, note what happened! -# Because matrices must contain entries all of the same class, -# everything got converted to the character class -c(class(mat2[,1]), class(mat2[,2])) - -# rbind() sticks vectors together row-wise to make a matrix -mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) -mat3 -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 2 4 5 -# [2,] 6 7 0 4 -# Ah, everything of the same class. No coercions. Much better. - -# TWO-DIMENSIONAL (DIFFERENT CLASSES) - -# For columns of different types, use a data frame -# This data structure is so useful for statistical programming, -# a version of it was added to Python in the package "pandas". - -students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), - c(3,2,2,1,0,-1), - c("H", "G", "G", "R", "S", "G")) -names(students) <- c("name", "year", "house") # name the columns -class(students) # "data.frame" -students -# => -# name year house -# 1 Cedric 3 H -# 2 Fred 2 G -# 3 George 2 G -# 4 Cho 1 R -# 5 Draco 0 S -# 6 Ginny -1 G -class(students$year) # "numeric" -class(students[,3]) # "factor" -# find the dimensions -nrow(students) # 6 -ncol(students) # 3 -dim(students) # 6 3 -# The data.frame() function converts character vectors to factor vectors -# by default; turn this off by setting stringsAsFactors = FALSE when -# you create the data.frame -?data.frame - -# There are many twisty ways to subset data frames, all subtly unalike -students$year # 3 2 2 1 0 -1 -students[,2] # 3 2 2 1 0 -1 -students[,"year"] # 3 2 2 1 0 -1 - -# An augmented version of the data.frame structure is the data.table -# If you're working with huge or panel data, or need to merge a few data -# sets, data.table can be a good choice. Here's a whirlwind tour: -install.packages("data.table") # download the package from CRAN -require(data.table) # load it -students <- as.data.table(students) -students # note the slightly different print-out -# => -# name year house -# 1: Cedric 3 H -# 2: Fred 2 G -# 3: George 2 G -# 4: Cho 1 R -# 5: Draco 0 S -# 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" -# => -# name year house -# 1: Ginny -1 G -students[year==2] # get rows with year == 2 -# => -# name year house -# 1: Fred 2 G -# 2: George 2 G -# data.table makes merging two data sets easy -# let's make another data.table to merge with students -founders <- data.table(house=c("G","H","R","S"), - founder=c("Godric","Helga","Rowena","Salazar")) -founders -# => -# house founder -# 1: G Godric -# 2: H Helga -# 3: R Rowena -# 4: S Salazar -setkey(students, house) -setkey(founders, house) -students <- founders[students] # merge the two data sets by matching "house" -setnames(students, c("house","houseFounderName","studentName","year")) -students[,order(c("name","year","house","houseFounderName")), with=F] -# => -# studentName year house houseFounderName -# 1: Fred 2 G Godric -# 2: George 2 G Godric -# 3: Ginny -1 G Godric -# 4: Cedric 3 H Helga -# 5: Cho 1 R Rowena -# 6: Draco 0 S Salazar - -# data.table makes summary tables easy -students[,sum(year),by=house] -# => -# house V1 -# 1: G 3 -# 2: H 3 -# 3: R 1 -# 4: S 0 - -# To drop a column from a data.frame or data.table, -# assign it the NULL value -students$houseFounderName <- NULL -students -# => -# studentName year house -# 1: Fred 2 G -# 2: George 2 G -# 3: Ginny -1 G -# 4: Cedric 3 H -# 5: Cho 1 R -# 6: Draco 0 S - -# Drop a row by subsetting -# Using data.table: -students[studentName != "Draco"] -# => -# house studentName year -# 1: G Fred 2 -# 2: G George 2 -# 3: G Ginny -1 -# 4: H Cedric 3 -# 5: R Cho 1 -# Using data.frame: -students <- as.data.frame(students) -students[students$house != "G",] -# => -# house houseFounderName studentName year -# 4 H Helga Cedric 3 -# 5 R Rowena Cho 1 -# 6 S Salazar Draco 0 - -# MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE) - -# Arrays creates n-dimensional tables -# All elements must be of the same type -# You can make a two-dimensional table (sort of like a matrix) -array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) -# => -# [,1] [,2] [,3] [,4] -# [1,] 1 4 8 3 -# [2,] 2 5 9 6 -# You can use array to make three-dimensional matrices too -array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) -# => -# , , 1 -# -# [,1] [,2] -# [1,] 2 8 -# [2,] 300 9 -# [3,] 4 0 -# -# , , 2 -# -# [,1] [,2] -# [1,] 5 66 -# [2,] 60 7 -# [3,] 0 847 - -# LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES) - -# Finally, R has lists (of vectors) -list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # random -list1 -# You can get items in the list like so -list1$time # one way -list1[["time"]] # another way -list1[[1]] # yet another way -# => -# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 -# [34] 34 35 36 37 38 39 40 -# You can subset list items like any other vector -list1$price[4] - -# Lists are not the most efficient data structure to work with in R; -# unless you have a very good reason, you should stick to data.frames -# Lists are often returned by functions that perform linear regressions - -################################################## -# The apply() family of functions -################################################## - -# Remember mat? -mat -# => -# [,1] [,2] -# [1,] 1 4 -# [2,] 2 5 -# [3,] 3 6 -# Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X -# over rows (MAR = 1) or columns (MAR = 2) -# That is, R does FUN to each row (or column) of X, much faster than a -# for or while loop would do -apply(mat, MAR = 2, jiggle) -# => -# [,1] [,2] -# [1,] 3 15 -# [2,] 7 19 -# [3,] 11 23 -# Other functions: ?lapply, ?sapply - -# Don't feel too intimidated; everyone agrees they are rather confusing - -# The plyr package aims to replace (and improve upon!) the *apply() family. -install.packages("plyr") -require(plyr) -?plyr - - - -######################### -# Loading data -######################### - -# "pets.csv" is a file on the internet -# (but it could just as easily be be a file on your own computer) -pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") -pets -head(pets, 2) # first two rows -tail(pets, 1) # last row - -# To save a data frame or matrix as a .csv file -write.csv(pets, "pets2.csv") # to make a new .csv file -# set working directory with setwd(), look it up with getwd() - -# Try ?read.csv and ?write.csv for more information - - - -######################### -# Statistical Analysis -######################### - -# Linear regression! -linearModel <- lm(price ~ time, data = list1) -linearModel # outputs result of regression -# => -# Call: -# lm(formula = price ~ time, data = list1) -# -# Coefficients: -# (Intercept) time -# 0.1453 0.4943 -summary(linearModel) # more verbose output from the regression -# => -# Call: -# lm(formula = price ~ time, data = list1) -# -# Residuals: -# Min 1Q Median 3Q Max -# -8.3134 -3.0131 -0.3606 2.8016 10.3992 -# -# Coefficients: -# Estimate Std. Error t value Pr(>|t|) -# (Intercept) 0.14527 1.50084 0.097 0.923 -# time 0.49435 0.06379 7.749 2.44e-09 *** -# --- -# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 -# -# Residual standard error: 4.657 on 38 degrees of freedom -# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 -# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 -coef(linearModel) # extract estimated parameters -# => -# (Intercept) time -# 0.1452662 0.4943490 -summary(linearModel)$coefficients # another way to extract results -# => -# Estimate Std. Error t value Pr(>|t|) -# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 -# time 0.4943490 0.06379348 7.74920901 2.440008e-09 -summary(linearModel)$coefficients[,4] # the p-values -# => -# (Intercept) time -# 9.234021e-01 2.440008e-09 - -# GENERAL LINEAR MODELS -# Logistic regression -set.seed(1) -list1$success = rbinom(length(list1$time), 1, .5) # random binary -glModel <- glm(success ~ time, data = list1, - family=binomial(link="logit")) -glModel # outputs result of logistic regression -# => -# Call: glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) -# -# Coefficients: -# (Intercept) time -# 0.17018 -0.01321 -# -# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual -# Null Deviance: 55.35 -# Residual Deviance: 55.12 AIC: 59.12 -summary(glModel) # more verbose output from the regression -# => -# Call: -# glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) - -# Deviance Residuals: -# Min 1Q Median 3Q Max -# -1.245 -1.118 -1.035 1.202 1.327 -# -# Coefficients: -# Estimate Std. Error z value Pr(>|z|) -# (Intercept) 0.17018 0.64621 0.263 0.792 -# time -0.01321 0.02757 -0.479 0.632 -# -# (Dispersion parameter for binomial family taken to be 1) -# -# Null deviance: 55.352 on 39 degrees of freedom -# Residual deviance: 55.121 on 38 degrees of freedom -# AIC: 59.121 -# -# Number of Fisher Scoring iterations: 3 - - -######################### -# Plots -######################### - -# BUILT-IN PLOTTING FUNCTIONS -# Scatterplots! -plot(list1$time, list1$price, main = "fake data") -# Plot regression line on existing plot -abline(linearModel, col = "red") -# Get a variety of nice diagnostics -plot(linearModel) -# Histograms! -hist(rpois(n = 10000, lambda = 5), col = "thistle") -# Barplots! -barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) - -# GGPLOT2 -# But these are not even the prettiest of R's plots -# Try the ggplot2 package for more and better graphics -install.packages("ggplot2") -require(ggplot2) -?ggplot2 -pp <- ggplot(students, aes(x=house)) -pp + geom_histogram() -ll <- as.data.table(list1) -pp <- ggplot(ll, aes(x=time,price)) -pp + geom_point() -# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) - - - -``` - -## How do I get R? - -* Get R and the R GUI from [http://www.r-project.org/](http://www.r-project.org/) -* [RStudio](http://www.rstudio.com/ide/) is another GUI diff --git a/ro-ro/haskell-ro.html.markdown b/ro-ro/haskell-ro.html.markdown new file mode 100644 index 00000000..082f138b --- /dev/null +++ b/ro-ro/haskell-ro.html.markdown @@ -0,0 +1,455 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +lang: ro-ro +filename: haskell-ro.html +--- + +Haskell este un limbaj de programare practic, pur funcțional. + +```haskell +-- Comentariile pe o singura linie incep cu 2 cratime. +{- Comentariile multilinie + se scriu astfel. +-} + +---------------------------------------------------- +-- 1. Tipuri de date primitive si operatori +---------------------------------------------------- + +-- Exista numere +3 -- 3 + +-- Matematica functioneaza ca de obicei +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Impartirea este cu virgula +35 / 4 -- 8.75 + +-- Impartirea cu rest +35 `div` 4 -- 8 + +-- Valorile booleene sunt primitive +True +False + +-- Operatii logice +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- In exemplele de mai sus, `not` este o functie ce primeste o valoare. +-- In Haskell nu se pun paranteze pentru apelurile de functie. Toate +-- argumentele sunt insirate dupa numele functiei. Sablonul general este: +-- func arg1 arg2 arg3 +-- Vedeti sectiunea despre functii pentru a afla cum sa scrieti propria functie. + +-- Caractere si siruri de caractere +"Acesta este un sir de caractere" +'a' -- un caracter +'Nu se pot folosi apostroafe pentru siruri.' -- eroare! + +-- Sirurile pot fi concatenate +"Hello " ++ "world!" -- "Hello world!" + +-- Un string e de fapt o lista de caractere +['H', 'e', 'l', 'l', 'o'] -- "Hello" +"Acesta este un string" !! 0 -- 'A' + + +---------------------------------------------------- +-- Liste si tupli +---------------------------------------------------- + +-- Fiecare element dintr-o lista trebuie sa aiba acelasi tip. +-- Urmatoarele liste sunt identice. +[1, 2, 3, 4, 5] +[1..5] + +-- Intervalele sunt versatile. +['A'..'F'] -- "ABCDEF" + +-- Se poate specifica un pas pentru intervale. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- Aceasta nu functioneaza deoarece pasul implicit este incrementarea. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexarea intr-o lista este de la zero +[1..10] !! 3 -- se obtine 4 + +-- Se pot crea liste infinite +[1..] -- lista tuturor numerelor naturale + +-- Listele infinite functioneaza pentru ca Haskell foloseste "evaluare lenesa" +-- adica evalueaza lucrurile doar cand este nevoie de ele. Deci se poate +-- cere al 1000-lea element din lista infinita a numerelor naturale astfel: + +[1..] !! 999 -- rezulta 1000 + +-- Haskell a evaluat elementele 1 - 1000 din lista... dar restul elementelor +-- acestei liste "infinite" nu exista inca! Haskell nu le va evalua pana +-- nu va fi nevoie de ele. + +-- concatenarea a doua liste +[1..5] ++ [6..10] + +-- alipirea la capul listei +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- operatii cu liste +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- intelegerea listelor +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- folosind o conditie +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Fiecare element dintr-un tuplu poate fi de un tip diferit +-- dar un tuplu are lungime fixa +-- Un tuplu: +("haskell", 1) + +-- accesarea elementelor unui tuplu pereche +fst ("haskell", 1) -- "haskell" (first) +snd ("haskell", 1) -- 1 (second) + +---------------------------------------------------- +-- 3. Functii +---------------------------------------------------- +-- O functie simpla ce sumeaza doua variabile +add a b = a + b + +-- Aveti in vedere ca daca folositi ghci (interpretorul Haskell) +-- trebuie sa scrieti in fata si `let`, adica +-- let add a b = a + b + +-- Apelarea functiei +add 1 2 -- rezulta 3 + +-- Numele functiei se poate pune si intre argumente +-- folosind apostrof intors: +1 `add` 2 -- 3 + +-- Se pot defini functii fara litere in denumire! Astfel se pot +-- defini noi operatori! De exemplu, iata un operator care realizeaza +-- impartirea intreaga +(//) a b = a `div` b +35 // 4 -- rezulta 8 + +-- Guards: o metoda usoara de a crea ramuri de executie +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- Potrivirea sirurilor se face similar. Aici am definit 3 definitii +-- pentru fib. Haskell o va alege automat pe prima care se potriveste +-- cu sablonul valorii. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Potrivirea in tupli: +foo (x, y) = (x + 1, y + 2) + +-- Potrivirea in liste. Aici `x` este primul element al listei, +-- iar `xs` este restul litei. Putem scrie propria functie +-- de mapare +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Functiile anonime sunt create folosind un backslash urmat +-- de toate argumentele. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- utilizarea fold (denumit `inject` in alte limbaje) cu o functie +-- anonima. foldl1 inseamna pliere la stanga, folosind prima valoare +-- din lista drept valoarea initiala pentru acumulator +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Mai multe functii +---------------------------------------------------- + +-- aplicare partiala; daca nu se introduc toate argumentele unei functii, +-- este "aplicata partial", adica returneaza o noua functie ce primeste +-- restul argumentelor, avand deja setate argumentele introduse + +add a b = a + b +foo = add 10 -- foo este o functie ce primeste un numar si ii aduna 10 +foo 5 -- 15 + +-- alta maniera de a scrie acelasi lucru +foo = (10+) +foo 5 -- 15 + +-- compunerea functiilor +-- operatorul `.` inlantuieste functiile. +-- De exeplu, aici foo este o functie care aduna 10 unui numar, il inmul +-- teste cu 4 si returneaza rezultatul calcului +foo = (4*) . (10+) + +-- 4*(10 + 5) = 60 +foo 5 -- 60 + +-- alterarea precedentei +-- Haskell detine un operator numit `$`. Acest operator aplica o functie +-- unui parametru dat. Fata de aplicarea standard a functiilor, care +-- foloseste prioritatea maxim posibila 10 si este asociativa la stanga, +-- operatorul `$` are prioritatea 0 si este asociativ la dreapta. +-- Aceasta inseamna ca expresia de la dreapta este aplicata ca parametru +-- functiei din stanga + +-- inainte +even (fib 7) -- false + +-- echivalent +even $ fib 7 -- false + +-- compunerea functiilor +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Type signatures +---------------------------------------------------- + +-- Haskell are un sistem de tipuri de date foarte puternic; fiecare expresie +-- valida are un tip. + +-- Cateva tipuri de baza: +5 :: Integer +"hello" :: String +True :: Bool + +-- Functiile au tipuri de asemenea. +-- `not` primeste un boolean si returneaza un boolean. +-- not :: Bool -> Bool + +-- Iata o functie ce primeste doi intregi +-- add :: Integer -> Integer -> Integer + +-- Cand se defineste o valoare, este bine sa se precizeze tipul ei deasupra. +double :: Integer -> Integer +double x = x * 2 + +--------------------------------------------------------- +-- 6. Controlul executiei si instructiunile conditionale +--------------------------------------------------------- + +-- expresia conditionala if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- cand expresiile sunt pe mai multe linii, este importanta indentarea +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- expresiile de tip case; iata cum se verifica argumentele programului +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell nu foloseste cicluri, ci recursie +-- map aplica o functie fiecarui element dintr-o lista + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- se poate face o functie for folosind map +for array func = map func array + +-- si apoi se poate folosi astfel: +for [0..5] $ \i -> show i + +-- se poate scrie si asa: +for [0..5] show + +-- Se poate folosi foldl sau foldr pentru a reduce o lista +-- foldl <fn> <valoare initiala> <lista> +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Acelasi lucru ca a scrie +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl functioneaza spre stanga, foldr spre dreapta +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Acealsi lucru ca: +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Tipuri de date +---------------------------------------------------- + +-- Iata cum se creeaza un tip de date in Haskell + +data Culoare = Rosu | Albastru | Verde + +-- Acum poate fi folosit in functii + + +spune :: Culoare -> String +spune Rosu = "Esti Rosu!" +spune Albastru = "Esti Albastru!" +spune Verde = "Esti Verde!" + +-- Tipul de date poate avea si parametri. + +data Maybe a = Nothing | Just a + +-- Toate acestea sunt de tipul Maybe +Just "hello" -- de tipul `Maybe String` +Just 1 -- de tipul `Maybe Int` +Nothing -- de tipul `Maybe a` pentru oricare `a` + +---------------------------------------------------- +-- 8. IO in Haskell +---------------------------------------------------- + +-- Desi IO nu se poate explica intru totul fara a explica monadele, +-- nu este atat de greu de explicat pentru o idee de baza. + +-- Cand se executa un program Haskell, se apeleaza `main`. +-- Trebuie sa returneze o valoare de tio `IO a` pentru un anumit tip `a`. +-- De exemplu: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- putStrLn are tipul String -> IO () + +-- Cel mai usor se lucreaza cu IO daca se implementeaza programul +-- ca o functie de la String la String. Functia +-- interact :: (String -> String) -> IO () +-- citeste un text, executa o functie asupra ei, apoi afiseaza +-- iesirea. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- O valoare de tipul `IO ()` poate fi privita ca reprezentand +-- o secventa de actiuni pe care care computerul sa le execute, +-- similar cu felul in care un program este scris intr-un limbaj +-- imperativ. Putem folosi notatia `do` pentru a inlantui actiunile. +-- De exemplu: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- citeste o linie + putStrLn $ "Hello, " ++ name + +-- Exercise: Scrieti propria functie `interact` care citeste +-- o singura linie de la intrare. + + +-- Codul din `sayHello` nu va fi niciodata executat. Singura actiunile +-- care este executata este valoarea lui `main`. +-- Pentru a rula `sayHello.`, eliminati definitia de mai sus a `main`. +-- si inlocuiti-o cu +-- main = sayHello + +-- Sa intelegem mai bine cum functioneaza functia `getLine`. +-- Tipul ei este: +-- getLine :: IO String +-- Pueti privi o valoare de tipul `IO a` ca fiind un program +-- de computer care va genera o valoare de tipul `a` cand +-- este executata (pe langa orice altceva face). O putem denumi +-- si refolosi utilizand `<-`. De asemenea putem face propriile +-- actiuni te tipul `IO String`: + +action :: IO String +action = do + putStrLn "Aceasta e o linie." + input1 <- getLine + input2 <- getLine + --Tipul instructiunii `do` este cel de pe ultima sa linie. + -- `return` nu este un cuvant cheie, ci o functie + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Putem folosi aceasta exact cum am folosit `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- Tipul `IO` este un exemplu de "monada". Felul in care Haskell foloseste +-- o monada pentru a realiza opeartii de intrare si iesire il face un limbaj +-- pur functional. Orice functie care interactioneaza cu exteriorul (adica +-- realieaza IO) este marcata ca `IO` in semnatura ei. Aceasta ne permite +-- sa spunem ce functii sunt "pure", adica nu interactioneaza cu exteriorul. + +-- Aceasta este o facilitate foarte puternica, deoarece este usor sa +-- se ruleze functii pure concurent; asadar, concurenta in Haskell se face usor + +---------------------------------------------------- +-- 9. REPL in Haskell +---------------------------------------------------- + +-- Se porneste introducand `ghci`. +-- Dupa aceasta, se poate introduce cod Haskell. +-- Toate valorile noi trebuie precedate de `let`. + +let foo = 5 + +-- Puteti vedea tipul oricarei valori sau expresii cu `:t`. + +> :t foo +foo :: Integer + +-- Operatorii, precum `+`, `:` si `$` sunt functii. +-- Tipul lor poate fi observat punand operatorii intre paranteze. + +> :t (:) +(:) :: a -> [a] -> [a] + +-- Se pot obtine informatii despre fiecare nume folosind `:i` + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + +--De asemenea se poate executa orice actiune de tipul `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` +Mai sunt multe de spus despre Haskell, printre care typclasses și monade. +Acestea sunt marile idei care fac programarea în Haskell atât de interesantă. +Vă las un exemplu final în Haskell: o variantă de implementare a sortării rapide +(quicksort) în Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Există două maniere populare de a instala Haskell: prin [instalarea bazată pe Cabal](http://www.haskell.org/platform/), și prin mai noul [proces bazat pe Stack](https://www.stackage.org/install). + +Se poate găsi o introducere în Haskell mult mai blândă la adresele +[Learn you a Haskell](http://learnyouahaskell.com/) sau +[Real World Haskell](http://book.realworldhaskell.org/). diff --git a/ro-ro/latex.html.markdown b/ro-ro/latex-ro.html.markdown index 35651e28..f661db0a 100644 --- a/ro-ro/latex.html.markdown +++ b/ro-ro/latex-ro.html.markdown @@ -7,7 +7,6 @@ contributors: - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] -filename: brainfuck-ro.clj filename: learn-latex-ro.tex lang: ro-ro --- @@ -43,19 +42,18 @@ lang: ro-ro \usepackage[utf8]{inputenc} % De asemenea, putem defini și alte proprietăți pentru documente. -% We can define some other document properties too! \author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu} \date{\today} \title{Învățați LaTeX în Y minute!} % Suntem gata să începem documentul. % Tot ce se află înaintea acestei linii se numește "Preambul" -\begin{document} +\begin{document} % dacă am setat autorul, data și titlul, putem cere LaTeX să % creeze o pagină de titlu \maketitle -% Cele mai multe documente științifice au un abstract; puteți folosi comenzile +% Cele mai multe documente științifice au un rezumat; puteți folosi comenzile % predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic, % după titlu, dar înainte de secțiunile principale ale corpului. % Această comandă este disponibilă în clasele de document article și report. @@ -71,7 +69,7 @@ Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX! \section{Altă secțiune} Acesta este textul pentru altă secțiune. Vom face o subsecțiune. -\subsection{Aceasta este o subsecțiune} % Subsecțiunile sunt și ele intuitive. +\subsection{Aceasta este o subsecțiune} Și încă una. \subsubsection{Pitagora} @@ -80,7 +78,7 @@ Mult mai bine. % Folosind asteriscul putem suprima numărătoarea automată a LaTeX. % Aceasta funcționează și pentru alte comenzi LaTeX. -\section*{Secțiune fără numerotare} +\section*{Secțiune fără numerotare} Totuși nu toate secțiunile trebuie să fie nenumerotate! \section{Note despre text} @@ -89,7 +87,7 @@ nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash la codul sursă. \section{Liste} -Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la +Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la cumpărături așa că fac o listă: \begin{enumerate} % Aceasta creează un mediu "enumerate" % \item spune mediului "enumerate" să incrementeze @@ -101,20 +99,20 @@ cumpărături așa că fac o listă: Nu este un element din listă, dar încă face parte din "enumerate". -\end{enumerate} % All environments must have an end. +\end{enumerate} % Toate mediile trebuie să aibă o instrucțiune de încheiere. \section{Matematică} Una dintre principalele întrebuințări ale LaTeX este realizarea -articolelor academice sau a foilor tehnice, de obicei aflate în +articolelor academice sau a fișelor tehnice, de obicei aflate în universul matematicii și științelor exacte. Astfel, trebuie să putem -adăuga simboluri speciale în documentului nostru! \\ +adăuga simboluri speciale în documentul nostru! \\ Matematica are multe simboluri, mult mai multe decât se găsesc pe o tastatură - printre ele, simboluri pentru mulțimi și relații, săgeți, operatori și litere grecești.\\ -Mulțimile și relațiile sunt de bază în lucrările științifce matematice. +Mulțimile și relațiile sunt esențiale în lucrările științifce matematice. Iată cum se scrie: toți y aparținând lui X.\\ $\forall$ x $\in$ X. \\ @@ -127,13 +125,13 @@ $\forall$ x $\in$ X. \\ \[a^2 + b^2 = c^2 \] -Litera mea grecească este $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și +Îmi place litera $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și $\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX! -Operatorii sunt exențiali într-un document matematic! -funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), -logaritmii și exponențialele ($\log$, $\exp$), -limitele ($\lim$), etc. +Operatorii sunt esențiali într-un document matematic! +funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), +logaritmii și exponențialele ($\log$, $\exp$), +limitele ($\lim$), etc. au comenzi definite în LaTeX pentru fiecare. Să vedem cum scriem o ecuație: \\ @@ -156,20 +154,20 @@ Putem insera ecuații și într-un "mediu pentru ecuații". \end{equation} % toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end -Putem referenția noua nosatră ecuație! +Putem referenția noua noastră ecuație! ~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate: figuri, ecuații, secțiuni, etc. Sumele discrete și integralele se scriu cu comenzile sum și int. -% Unele compilatoare LaTeX nu acceptă să există linii goala +% Unele compilatoare LaTeX nu acceptă să existe linii goale % într-un mediu pentru ecuații. -\begin{equation} +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Figuri} @@ -179,7 +177,7 @@ Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată. \begin{figure}[H] % H denumește opțiunle de așezare \centering % centrează figura pe pagină % Inserează o figură scalată la 0.8 din lățimea paginii. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Comentat pentru a nu împiedica fișierul să compileze. \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$} \label{fig:right-triangle} @@ -191,7 +189,7 @@ Putem insera tabele la fel cum inserăm figuri. \begin{table}[H] \caption{Descriere pentru tabel} % argumentele {} controlează cum vor fi afișate coloanele - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $ \hline % a linie orizonală 1 & Popescu & Ion \\ @@ -208,27 +206,27 @@ ci doar să îl redea în document. Vom face asta cu un mediu verbatim. % Există și alte pachete (i.e. minty, lstlisting, etc.) % dar verbatim este pachetul cel mai simplu. -\begin{verbatim} +\begin{verbatim} print("Salut lume!") a%b; % hei! putem folosi % în verbatim - random = 4; + random = 4; \end{verbatim} -\section{Compilarea} +\section{Compilarea} Acum vă întrebați cum se compilează acest document minunat și să vă -minunați de rezultatul, un PDF LaTeX. (da, documentul acesta chiar +minunați de rezultat, un PDF LaTeX. (da, documentul acesta chiar compilează). \\ Realizarea documentului cu LaTeX va parcurge următorii pași: \begin{enumerate} \item Se scrie documentul în text simplu. (codul sursă) \item Se compilează documentul pentru a produce un PDF. Compilarea arată cam așa în Linux:\\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -Anumiți editor pentru LaTeX combină pașii 1 și 2 în același produs software. +Anumite editoare pentru LaTeX combină pașii 1 și 2 în același produs software. Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate realiza "în spate". diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown new file mode 100644 index 00000000..0cf580d5 --- /dev/null +++ b/ru-ru/c++-ru.html.markdown @@ -0,0 +1,892 @@ +--- +language: c++ +filename: learncpp-ru.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] +translators: + - ["Bohdan Shtepan", "http://modern-dev.com"] +lang: ru-ru +--- + +C++ - компилируемый, статически типизированный язык программирования общего назначения, который, +[как заявляет создатель языка Бьёрн Страуструп](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +был разработан как + +- "лучшая замена C" +- язык с поддержкой абстракции данных +- язык с поддержкой объектно-ориентированого программирования +- язык с поддержкой обобщенного программирования + +Хотя его синтаксис может показаться более трудным или сложным для понимания, чем в более современных языках, +он широко применяется, так как код, написанный на C++, компилируется в набор инструкций, которые могут быть выполнены напрямую +процессором. C++ широко используется для разработки программного обеспечения, являясь одним из самых популярных языков +программирования. Область его применения включает создание операционных систем, разнообразных прикладных программ, драйверов +устройств, приложений для встраиваемых систем, высокопроизводительных серверов, а также развлекательных приложений (игр). + +```c++ +////////////////// +// Сравнение с C +////////////////// + +// C++ практически представляет собой надмножество C и имеет схожий синтаксис +// для объявления переменных, примитивов и функций. + +// Так же, как и в С, точкой входа в программу является функция с именем main, +// которая возвращает целочисленное значение. +// Это значение является кодом ответа программы. +// Смотрите https://goo.gl/JYGKyv для более подробной информации. +int main(int argc, char** argv) +{ + // Аргументы командной строки, переданные в программу, хранятся в переменных + // argc и argv, так же, как и в C. + // argc указывает на количество аргументов, + // а argv является массивом C-подобных строк (char*), который непосредсвенно + // содержит аргументы. + // Первым аргументом всегда передается имя программы. + // argc и argv могут быть опущены, если вы не планируете работать с аругментами + // коммандной строки. + // Тогда сигнатура функции будет иметь следующий вид: int main() + + // Возвращаемое значение 0 указывает на успешное завершение программы. + return 0; +} + +// Тем не менее, C++ имеет свои отличия: + +// В C++ символьные литералы имеют тип char. +sizeof('c') == sizeof(char) == 1 + +// В C символьные литералы - целые числа. +sizeof('c') == sizeof(int) + + +// C++ имеет строгое прототипирование. +void func(); // функция, которая не принимает аргументов. + +// В языке C +void func(); // функция, которая может принять сколько угодно аргументов. + +// Использование nullptr вместо NULL в C++. +int* ip = nullptr; + +// Стандартные заголовочные файлы С доступны в С++, +// но с префиксом "с" и не имеют суффикса .h. +#include <cstdio> + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// Перегрузка функций +/////////////////////// + +// С++ поддерживает перегрузку функций, при условии, +// что каждая функция принимает различные параметры. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Использование void print(const char*) + print(15); // Использование void print(int) +} + +///////////////////////////// +// Аргументы функций по умолчанию +///////////////////////////// + +// Вы можете предоставить аргументы по умолчанию для функции, +// если они не предоставлены при вызове функции. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Здесь что-то делаем с числами +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Аргументы по умолчанию должны быть в конце списка аргументов. + +void invalidDeclaration(int a = 1, int b) // Ошибка! +{ +} + + +///////////// +// Пространства имен +///////////// + +// Пространства имен предоставляют отдельные области для переменной, +// функции и других объявлений. +// Пространства имен могут быть вложенными. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // конец пространства имен Nested +} // конец пространства имен First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // Включает все функци из пространства имен Second в текущую область видимости. + // Обратите внимание, что простой вызов foo() больше не работает, + // так как теперь не ясно, вызываем ли мы foo из пространства имен Second, или + // из глобальной области видимости. + using namespace Second; + + Second::foo(); // напечатает "This is Second::foo" + First::Nested::foo(); // напечатает "This is First::Nested::foo" + ::foo(); // напечатает "This is global foo" +} + +/////////////// +// Ввод и вывод +/////////////// + +// Ввод и вывод в C++ использует потоки +// cin, cout и cerr представляют потоки stdin, stdout и stderr. +// << - оператор вставки, >> - оператор извлечения. + +#include <iostream> // Включение файла для работы с потоками Ввода\Вывода. + +using namespace std; // Потоки доступны в пространстве имен std (стандартная библиотека) + +int main() +{ + int myInt; + + // Выводит в stdout (или в терминал/на экран) + cout << "Enter your favorite number:\n"; + // Принимает ввод + cin >> myInt; + + // cout может принимать форматирование + cout << "Your favorite number is " << myInt << "\n"; + // напечатает "Your favorite number is <myInt>" + + cerr << "Used for error messages"; +} + +////////// +// Строки +////////// + +// Строки в C++ являются объектами и имеют много функций-членов. +#include <string> + +using namespace std; // Строки также доступны в пространстве имен std (стандартная библиотека) + +string myString = "Hello"; +string myOtherString = " World"; + +// + используется для конкатенации строк. +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// Строки в C++ могут изменяться и имеют семантику значений. +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// Ссылки +///////////// + +// Кроме указателей, доступных в C, +// C++ имеет _ссылки_. +// Это такой тип указателя, который не может быть переназначен после инициализации +// и не может иметь значения null. +// Ссылки имеют схожий с переменными синтаксис: +// * больше не используется для разыменования и +// & (адрес) не используется для назначения. + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // Здесь создается ссылка на foo. +fooRef += ". Hi!"; // Изменяет foo по ссылке +cout << fooRef; // Печатает "I am foo. Hi!" + +// Не переназначает "fooRef". Это то же самое, что и "foo = bar", и +// foo == "I am bar" +// после этой строчки. +cout << &fooRef << endl; // Печатает адрес foo +fooRef = bar; +cout << &fooRef << endl; // По-прежнему печатает адрес foo +cout << fooRef; // Печатает "I am bar" + +// Адрес fooRef остается тем же, то есть он по-прежнему ссылается на foo. + + +const string& barRef = bar; // Создает константную ссылку. +// Так же, как и в C, константные значения (а также указатели и ссылки) не могут быть изменены. +barRef += ". Hi!"; // Ошибка, константная ссылка не может быть изменена. + +// Обходной путь: Прежде чем мы рассмотрим указатели более детально, нам нужно ознакомиться +// с концепцией, известной как "временный объект". Представьте, что мы имеем следующий код +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Вот что на самом деле происходит во второй строке: +// - tempObjectFun возвращает строковый объект +// - из возвращаемого объекта создается новая строка в качестве аргумента конструктору +// - возвращаемый объект уничтожается +// Возвращаемый объект называется временным объектом. Временные объекты создаются, +// когда функция возвращает объект, и уничтожаются в конце выполнения обрамляющего +// выражения (По крайней мере, так это описывает спецификация, хотя компиляторы могут +// изменять это поведение. Для более подробной информации смотрите "оптимизация +// возвращаемого значения".) Таким образом в этом коде: +foo(bar(tempObjectFun())) + +// предполагая, что foo и bar существуют, объект, возвращаемый tempObjectFun, передается +// в bar, и уничтожается перед вызовом foo. + +// Возвращаемся к указателям. Исключением для правила "в конце выполнения обрамляющего +// выражения" является временный объект, привязанный к ссылке const, в этом случае +// его жизненный цикл продлевается до текущей области видимости: + +void constReferenceTempObjectFun() { + // constRef получает временный объект, и он действителен до конца этой функции. + const string& constRef = tempObjectFun(); + ... +} + +// В C++11 предоставлен еще один тип ссылок специально для временных объектов. +// objects. Вы не можете объявить переменную этого типа, но он имеет приоритет +// в резолюции перегрузки: + +void someFun(string& s) { ... } // Обычная ссылка +void someFun(string&& s) { ... } // Ссылка на временный объект + +string foo; +someFun(foo); // Выполняет версию с обычной ссылкой +someFun(tempObjectFun()); // Выполняет версию с временной ссылкой. + +// Например, существуют следующие две версии конструктора std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// Идея в том, что если мы конструируем новую строку из временного объекта (который +// так или иначе будет уничтожен), мы можем использовать более эффективный конструктор, +// который "спасает" части этой временной строки. Эта концепция была названа +// "move semantics". + +///////////////////// +// Перечисления +///////////////////// + +// Перечисления - способ объявления констант и установки их значений, в основном +// использующийся для упрощения чтения кода. +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// На момент выхода C++11 есть простой способ назначения типа перечисления, что +// полезно в случае сериализации данных и преобразований между конечным типом и +// соответствующими константами. +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Сериализуем InputValue в файл +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Перечисление неявно преобразуется в uint8_t из-за ранее объявленного + // типа перечисления. + WriteByteToFile(InputCarType); +} + +// С другой стороны, чтобы избежать случайного приведения к целочисленному типу или +// другому перечислению, вы можете создать класс перечисления, который не будет +// преобразовываться неявно. +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Сериализуем InputValue в файл +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Хотя ECarTypes имеет тип uint8_t, код не будет скомпилирован из-за того, + // что перечисление было объявлено как класс перечисления. + WriteByteToFile(InputCarType); +} + +////////////////////////////////////////// +// Классы и объектно-ориентированное программирование +////////////////////////////////////////// + +// Пример классов +#include <iostream> + +// Объявление класса. +// Обычно классы объявляют в заголовочном (.h или .hpp) файле. +class Dog { + // Переменные-члены и функции являются приватными по умолчанию. + std::string name; + int weight; + +// Все члены после этой сроки являются открытыми +// пока "private:" или "protected:" не будет объявлено. +public: + + // Конструктор по умолчанию + Dog(); + + // Объявление функций-членов + // Обратите внимание, мы используем std::string здесь вместо использования + // using namespace std; + // выше. + // Никогда не размещайте выражение "using namespace" в заголовке. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Функции, которые не изменяют состояние объекта, + // должны быть помечены как const. + // Это позволяет вызывать их, если дана const ссылка на объект. + // Обратите внимание, функции должны быть явно объявлены как _virtual_, + // если вы хотите перегрузить их в производных классах. + // Функции не являются виртуальными по умолчанию для повышения производительности. + virtual void print() const; + + // Также функции могут быть определены внутри тела класса. + // Функции, определенные следующим образом, автоматически встроены. + void bark() const { std::cout << name << " barks!\n"; } + + // Наряду с конструкторами, в C++ есть деструкторы. + // Они вызываются, когда объект удаляется или выпадает из области видимости. + // Это активирует мощную парадигму программирования, известную как RAII + // (смотрите ниже) + // Деструктор должен быть виртуальным, если класс будет производным. + // Если он не виртуальный, тогда деструктор производного класса не будет вызван, + // если объект удален по ссылке или указателю базового класса. + virtual ~Dog(); + +}; // Определение класса должно завершаться точкой с запятой. + +// Функции-члены класса, как правило, реализуются в .cpp файлах. +Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Объекты (такие как строки) должны передаваться по ссылке если вы будете +// изменять их, или const-ссылке если нет. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Обратите внимание, "virtual" требуется только в объявлении, не в определении. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // Печатает "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // Печатает "Dog is Barkley and weighs 10 kg" + return 0; +} // Печатает "Goodbye Barkley" + +// Интерфейсы: + +// Этот класс наследует все открытые и защищенные члены класса Dog +// так же, как и все закрытые, но не может непосредственно получить доступ к закрытым +// членам\методам без открытых или защищенных методов для этого. +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner); + + // Переопределяем поведение функции печати для всех OwnedDog. Смотрите + // https://goo.gl/3kuH2x для боле общего введения, если вы не знакомы + // с концепцией полиморфизма подтипов (включения). + // Ключевое слово override является необязательным, но указывает, что метод + // на самом деле перегружается в базовом классе. + void print() const override; + +private: + std::string owner; +}; + +// Тем временем, в соответствующем .cpp файле: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Вызывает функцию print в базовом классе Dog + std::cout << "Dog is owned by " << owner << "\n"; + // Печатает "Dog is <name> and weights <weight>" + // "Dog is owned by <owner>" +} + +////////////////////////////////////////// +// Инициализация и перегрузка операторов. +////////////////////////////////////////// + +// В C++ вы можете перегрузить поведение таких операторов: +, -, *, / и др.. +// Это делается путем определения функции, которая вызывается, +// когда используется оператор. + +#include <iostream> +using namespace std; + +class Point { +public: + // Значения по умолчанию для переменных-членов могут быть установлены + // следующим образом. + double x = 0; + double y = 0; + + // Определяем новый конструктор, который инициализирует Point со значениями + // по умолчанию (0, 0) + Point() { }; + + // Следующий синтаксис известен как список инициализации и является верным способом + // инициализировать значения членов класса. + Point (double a, double b) : + x(a), + y(b) + { /* Ничего не делайте, кроме инициализации значений */ } + + // Перегружаем оператор +. + Point operator+(const Point& rhs) const; + + // Перегружаем оператор +=. + Point& operator+=(const Point& rhs); + + // Имеет смысл добавить перегрузку операторов - и -=, + // но для краткости мы опустим эти детали. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Создает новую точку, которая является суммой этой точки и rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // Здесь происходит вызов оператора + класса Point + // Точка "up" вызывает + (функция) с параметром "right" + Point result = up + right; + // Печатает "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////// +// Шаблоны +///////////////////// + +// Шаблоны в С++, в основном, используются для обобщенного программирования, хотя +// они гораздо более мощны, чем дженерики в других языках. Они также поддерживают +// явные, частные и функциональные типы классов; на самом деле, они являются +// тьюринг-полным языком, встроенным в C++! + +// Мы начнем с наиболее распространенного типа обобщенного программирования. Чтобы +// определить класс или функцию, которая принимает параметр типа: +template<class T> +class Box { +public: + // В этом классе T может быть любого типа. + void insert(const T&) { ... } +}; + +// Во время компиляции компилятор фактически генерирует копии каждого шаблона +// с замещенными параметрами, поэтому полное определение класса должно присутствовать +// при каждом вызове. Именно поэтому классы шаблонов полностью определены в +// заголовочных файлах. + +// Чтобы создать экземпляр класса шаблона на стеке: +Box<int> intBox; + +// и вы можете использовать его, как и ожидалось: +intBox.insert(123); + +// Вы, конечно, можете использовать вложенные шаблоны: +Box<Box<int> > boxOfBox; +boxOfBox.insert(intBox); + +// Вплоть до С++11, вы должны были ставить пробел между двумя символами '>', иначе '>>' +// принимался парсером, как оператор сдвига вправо. + +// Иногда вы можете увидеть +// template<typename T> +// вместо этого. В этом случае ключевые слова 'class' и 'typename' _в основном_ +// взаимозаменяемыми. Для более подробной информации смотрите +// http://en.wikipedia.org/wiki/Typename +// (да-да, это ключевое слово имеет собственную страничку на вики). + +// Аналогичным образом, шаблонная функция: +template<class T> +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Обратите внимание, что здесь ничего не указано о типе параметра. Компилятор +// будет генерировать и затем проверять на тип каждый вызов шаблона, поэтому +// данная функция работает с любым типом 'T', который имеет метод 'bark'. + +Dog fluffy; +fluffy.setName("Fluffy"); +barkThreeTimes(fluffy); // Печатает "Fluffy barks" три раза. + +//Параметры шаблона не должны быть классами: +template<int Y> +void printMessage() { + cout << "Learn C++ in " << Y << " minutes!" << endl; +} + +// В конце концов, вы можете явно специализировать шаблоны для более эффективного +// кода. Конечно, большинство реальных случаев использования специализации +// не так тривиально, как это. Обратите внимание, вам все еще нужно явно объявить +// функцию (или класс) в качестве шаблона, даже если вы явно указали все параметры. +template<> +void printMessage<10>() { + cout << "Learn C++ faster in only 10 minutes!" << endl; +} + +printMessage<20>(); // Печатает "Learn C++ in 20 minutes!" +printMessage<10>(); // Печатает "Learn C++ faster in only 10 minutes!" + + +///////////////////// +// Обработка исключений +///////////////////// + +// Стандартная библиотека предоставляет несколько типов исключений +// (смотрите http://en.cppreference.com/w/cpp/error/exception) +// но, в принципе, любой тип может быть брошен в качестве исключения. +#include <exception> +#include <stdexcept> + +// Все исключения, брошенные в блоке _try_ могут быть пойманы в последующем блоке +// _catch_. +try { + // Не выделяйте память в куче для исключений с помощью ключевого слова _new_. + throw std::runtime_error("A problem occurred"); +} + +// Поймайте исключение по константной ссылке, если оно является объектом +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} + +// Ловит любое исключение, не пойманное предыдущим блоком _catch_ +catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Повторный выброс исключения +} + +/////// +// Получение ресурса есть инициализация (RAII) +/////// + +// Программная идиома объектно-ориентированного программирования, смысл которой +// заключается в том, что с помощью тех или иных программных механизмов получение +// некоторого ресурса неразрывно совмещается с инициализацией, а освобождение - +// с уничтожением объекта. + +// Чтобы понять, на сколько это полезно, +// рассмотрим функцию, которая использует обработчик файлов в С: +void doSomethingWithAFile(const char* filename) +{ + // Для начала, предположим, ничего не может потерпеть неудачу. + + FILE* fh = fopen(filename, "r"); // Открываем файл в режиме чтения. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Закрываем обработчик файла. +} + +// К сожалению, вещи быстро осложняются обработкой ошибок. +// Предположим, fopen может потерпеть неудачу, тогда doSomethingWithTheFile и +// doSomethingElseWithIt вернут коды ошибок, если потерпят неудачу. +// (Исключения являются предпочтительным способом обработки ошибок, +// но некоторые программисты, особенно те, кто имеет большой опыт работы с С, +// не согласны с аргументами о полезности исключений). +// Теперь мы должны проверить каждый вызов на наличие ошибок и закрыть обработчик +// файла, если он есть. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Открывает файл в режиме чтения + if (fh == nullptr) // В случае неудачи возвращаемый указатель принимает значение null. + return false; // Сообщает о неудаче вызывающему. + + // Предположим, каждая функция возвращает false в случае неудачи + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек + return false; // Сообщает об ошибке. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек + return false; // Сообщает об ошибке. + } + + fclose(fh); // Закрываем обработчик файла, чтобы не было утечек + return true; // Указывает на успех +} + +// C-программисты часто упорядочивают это с помощью goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Закрываем файл. + return true; // Указывает на успех + +failure: + fclose(fh); + return false; // Сообщает об ошибке. +} + +// Если функции указывают на ошибки с помощью исключений, вещи становятся проще, +// но все еще не оптимальны. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Открываем файл в режиме чтения + if (fh == nullptr) + throw std::runtime_error("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Убедитесь, что закрываете файл, если происходит ошибка. + throw; // Затем повторно бросает исключение. + } + + fclose(fh); // Закрываем файл. + // Успех +} + +// Сравните это с использованием класса потока файла (fstream) в С++, который +// использует свой деструктор, чтобы закрыть файл. Еще раз взгляните выше, +// деструктор вызывается автоматически, когда объект выпадает из области видимости. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream определяет файловый поток + std::ifstream fh(filename); // Открыть файл + + // Что-то делать с файлом + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // Здесь файл автоматически закрывается в деструкторе. + +// Это имеет _огромнейшие_ преимущества: +// 1. Неважно, что произойдет, +// ресурсы (в данном случае дескриптор файла) будут очищены. +// После того, как вы правильно напишете деструктор, +// Больше будет _невозможно_ закрыть обработчик файлов или допустить утечку. +// 2. Обратите внимание, что код намного проще. +// Деструктор закрывает файловый поток "за кулисами", и вам больше не нужно об +// этом беспокоиться. +// 3. Код устойчив к исключениям. +// Исключение может быть брошено в любом месте в функции, и это никак не повлияет +// на очистку. + +// Весь идиоматический код на С++ широко использует RAII для всех ресурсов. +// Дополнительные примеры включат: +// - Использование памяти unique_ptr и shared_ptr +// - Контейнеры - стандартная библиотека связанных списков, векторы +// (т.е. самоизменяемые массивы), хэш-таблицы и все остальное автоматически +// уничтожается сразу же, когда выходит за пределы области видимости. +// - Ипользование мьютексов lock_guard и unique_lock + +// Контейнеры с пользовательскими классами в качестве ключей требуют +// сравнивающих функций в самом объекте или как указатель на функцию. Примитивы +// имеют компараторы по умолчанию, но вы можете перегрузить их. +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +// это не допускается (хотя это может варьироваться в зависимости от компилятора) +// std::map<Foo, int> fooMap; +std::map<Foo, int, compareFunction> fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true + +///////////////////// +// Веселые вещи +///////////////////// + +// Аспекты С++, которые могут быть удивительными для новичков (и даже для некоторых +// ветеранов). Этот раздел, к сожалению, очень неполон. С++ является одним из самых +// простых языков, где очень легко выстрелить себе в ногу. + +// Вы можете перегрузить приватные методы! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Перегружает Foo::bar! +}; + + +// 0 == false == NULL (в основном)! +bool* pt = new bool; +*pt = 0; // Устанавливает значение указателя 'pt' в false. +pt = 0; // Устанавливает значение 'pt' в нулевой указатель. Обе строки проходят + // компиляцию без ошибок. + +// nullptr приходит на помощь: +int* pt2 = new int; +*pt2 = nullptr; // Не пройдет компиляцию +pt2 = nullptr; // Устанавливает pt2 в null. + +// Существует исключение для булевых значений. +// Это позволит вам проверить указатели с помощью if(!ptr), +// но как следствие вы можете установить nullptr в bool напрямую! +*pt = nullptr; // Это по прежнему проходит компиляцию, даже если '*pt' - bool! + + +// '=' != '=' != '='! +// Вызывает Foo::Foo(const Foo&) или некий вариант (смотрите "move semantics") +// копирования конструктора. +Foo f2; +Foo f1 = f2; + +// Вызывает Foo::Foo(const Foo&) или вариант, но копирует только часть 'Foo' из +// 'fooSub'. Любые другие члены 'fooSub' пропускаются. Иногда это ужасное поведение +// называют "object slicing." +FooSub fooSub; +Foo f1 = fooSub; + +// Вызывает Foo::operator=(Foo&) или вариант. +Foo f1; +f1 = f2; + + +// Как по-настоящему очистить контейнер: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// В следующей точке размер v устанавливается в 0, но деструктор не вызывается +// и не происходит очистка ресурсов! +v.empty(); +v.push_back(Foo()); // Новые значения копируются в первый вставленный Foo + +// Настоящее уничтожение всех значений v. Смотрите раздел о временном объекте +// для объяснения того, как это работает. +v.swap(vector<Foo>()); + +``` +## Дальнейшее чтение: + +Наиболее полное и обновленное руководство по С++ можно найти на +<http://cppreference.com/w/cpp> + +Дополнительные ресурсы могут быть найдены на <http://cplusplus.com> diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 5988b159..5e967181 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -202,7 +202,7 @@ int main() { int ii = 0; while (ii < 10) { printf("%d, ", ii++); // инкрементация происходит после того как - // знаечние ii передано ("postincrement") + // значение ii передано ("postincrement") } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -212,7 +212,7 @@ int main() { do { printf("%d, ", kk); } while (++kk < 10); // инкрементация происходит перед тем как - // передаётся знаечние kk ("preincrement") + // передаётся значение kk ("preincrement") // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); @@ -285,7 +285,7 @@ int main() { printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); // => Напечатает "8, 4" в 64 битной системе - // Для того, чтобы получить знаечние по адресу, напечатайте * перед именем. + // Для того, чтобы получить значение по адресу, напечатайте * перед именем. // Да, использование * при объявлении указателя и получении значения по адресу // немного запутано, но вы привыкнете. printf("%d\n", *px); // => Напечаатет 0, значение перемененной x @@ -422,7 +422,7 @@ void function_1() { // Вы можете объявить указатель на структуру struct rectangle *my_rec_ptr = &my_rec; - // Можно доступаться к структуре и через указатель + // Можно получить доступ к структуре и через указатель (*my_rec_ptr).width = 30; // ... или ещё лучше: используйте оператор -> для лучшей читабельночти @@ -436,7 +436,7 @@ int area(rect r) { return r.width * r.height; } -// Если вы имеете большую структуру, можно доступаться к ней "по указателю", +// Если вы имеете большую структуру, можно получить доступ к ней "по указателю", // чтобы избежать копирования всей структуры. int area(const rect *r) { return r->width * r->height; diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index d17f24fc..42c4d360 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -451,7 +451,7 @@ $value = include 'my-include.php'; class MyClass { - const MY_CONST = 'value'; // A constant + const MY_CONST = 'value'; // Константа static $staticVar = 'static'; diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 2c17b753..cc7ab84c 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -946,10 +946,11 @@ Utilities openCommandKeyHelp ### Free Online * [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) -* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) +* [smalltalk dot org](http://www.smalltalk.org/) * [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) * [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) * [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) * [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) * [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) * [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) +* [Smalltalk Programming Resources](http://www.whoishostingthis.com/resources/smalltalk/) diff --git a/tcl.html.markdown b/tcl.html.markdown index b90bd690..4ff1d3cc 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -105,12 +105,14 @@ set greeting $greeting1$greeting2[set greeting3] # Command substitution should really be called script substitution, because an # entire script, not just a command, can be placed between the brackets. The # "incr" command increments the value of a variable and returns its value. + +set i 0 set greeting $greeting[ incr i incr i incr i ] - +# i is now 3 # backslash suppresses the special meaning of characters set amount \$16.42 @@ -149,9 +151,6 @@ set greeting "Hello, [set {first name}]" # To promote the words within a word to individual words of the current # command, use the expansion operator, "{*}". -``` - -```tcl set {*}{name Neo} # is equivalent to @@ -261,10 +260,11 @@ proc greet greeting\ name return\ \"Hello,\ \$name! # When the last parameter is the literal value, "args", it collects all extra # arguments when the command is invoked proc fold {cmd args} { - set res 0 + set res 1 foreach arg $args { set res [$cmd $res $arg] } + return res } fold ::tcl::mathop::* 5 3 3 ;# -> 45 diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown new file mode 100644 index 00000000..8c47397c --- /dev/null +++ b/tr-tr/fsharp-tr.html.markdown @@ -0,0 +1,631 @@ +--- +language: F# +contributors: + - ["Scott Wlaschin", "http://fsharpforfunandprofit.com/"] +translators: + - ["Mustafa Zengin", "http://zengin.github.com/"] +filename: learnfsharp-tr.fs +lang: tr-tr +--- + +F# fonksiyonel ve nesne yönelimli, genel amaçlı bir programlama dilidir. Bedava ve açık kaynaklıdır ve Linux, Mac, Windows ve dahasında çalışır. + +Hataları derleme zamanında yakalayan çok güçlü bir tip sistemine sahiptir, ancak tip çıkarımı yaptığından dinamik bir dil gibi görünür. + +F#'ın söz dizimi C-stili dillerden farklıdır: + +* Küme parantezi kod bloklarını ayırmak için kullanılmaz. Bunun yerine Python'da olduğu gibi girinti kullanılır. +* Parametreleri birbirinden ayırmak için virgül yerine boşluk karakteri kullanılır. + +Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.org/Create)'a gidin be interaktif REPL'e kodu yapıştırın. + +```csharp + +// tek satır yorumlar ikili bölme işareti ile başlar +(* çok satırlı yorumlar ( * . . . * ) ikilisini kullanır + +-çok satırlı yorumun sonu- *) + +// ================================================ +// Temel Söz Dizimi +// ================================================ + +// ------ "Değişkenler" (tam da değil) ------ +// "let" anahtar kelimesi (değişmez) değer tanımlar +let tamsayım = 5 +let ondalığım = 3.14 +let stringim = "merhaba" // tip bilgisi olmamasına dikkat + +// ------ Listeler ------ +let ikidenBeşe = [2; 3; 4; 5] // Köşeli parantezler listeleri oluşturur, + // değerler ise noktalı virgülle ayrılır. +let birdenBeşe = 1 :: ikidenBeşe // :: yeni birinci elemanı olan bir liste oluşturur. +// Sonuç: [1; 2; 3; 4; 5] +let sıfırdanBeşe = [0; 1] @ ikidenBeşe // @ iki listeyi birbirine ekler. + +// ÖNEMLİ: virgüller hiçbir zaman ayraç olarak kullanılmaz, sadece noktalı virgüller! + +// ------ Fonksiyonlar ------ +// "let" anahtar kelimesi isimlendirilmiş fonksiyonları da tanımlar. +let kare x = x * x // Parantez kullanılmadığına dikkat. +kare 3 // Şimdi fonksiyonu uygulayın. Yine parantez yok. + +let topla x y = x + y // topla (x,y) kullanmayın! Bu tamamen başka bir anlama geliyor. +topla 2 3 // Şimdi fonksiyonu uygulayın. + +// çok satırlı bir fonksiyon tanımlamak için sadece girinti kullanın. Noktalı virgül gerekmez. +let çiftler liste = + let çiftMi x = x % 2 = 0 // "çiftMi"yi alt fonksiyon olarak tanımlayın + List.filter çiftMi liste // List.filter 'boolean bir fonksiyon' ve + // 'üzerinde çalışılacak bir liste' parametrelerinden oluşan + // bir kütüphane fonksiyonu + +çiftler birdenBeşe // Şimdi fonksiyonu uygula. + +// Parantezleri önceliği netleştirmek için kullanabilirsiniz. Bu örnek +// "map"i önce iki argümana, sonra sonuç üzerinde "ekle" uyguluyor. +// Parantezler olmasaydı, "List.map" List.sum'ın ilk argümanı olurdu. +let yüzeKadarKarelerinToplamı = + List.sum ( List.map kare [1..100] ) + +// Bir operasyonun sonucunu bir sonrakine "|>" kullanarak besleyebilirsin. +// Veri beslemek F#'ta UNIX'te olduğu gibi yaygındır.. + +// Burada yüzeKadarKarelerinToplamı fonksiyonunun veri beslemeyle yazılmış hali var: +let veriBeslemeyleYüzeKadarKarelerinToplamı = + [1..100] |> List.map kare |> List.sum // "kare" önceden tanımlanmıştı + +// Lambda'ları (anonim fonksiyonları) "fun" anahtar kelimesiyle tanımlayabilirsin +let funlaYüzeKadarKarelerinToplamı = + [1..100] |> List.map (fun x -> x * x) |> List.sum + +// F#'ta "return" anahtar kelimesi yoktur. Bir fonksiyon +// her zaman son kullanılan ifadeyi döndürür. + +// ------ Kalıp eşleştirme ------ +// Match..with.. çok güçlü bir case/switch türevidir. +let basitKalıpEşleştirme = + let x = "a" + match x with + | "a" -> printfn "x a'dır" + | "b" -> printfn "x b'dir" + | _ -> printfn "x başka bir şeydir" // alt çizgi bütün kalıplarla eşleşir + +// F# varsayılan olarak null'lara izin vermez -- Option tipini kullanıp +// kalıp eşleştirme yapmalısın. +// Some(..) ve None, Nullable tipler gibidir. +let geçerliDeğer = Some(99) +let geçersizDeğer = None + +// Bu örnekte, match..with "Some" ve "None"la eşleştirme yapıyor, +// ve ayrıca "Some" içerisindeki değeri de çıkarıyor. +let optionKalıpEşleştirme input = + match input with + | Some i -> printfn "input is an int=%d" i + | None -> printfn "input is missing" + +optionKalıpEşleştirme geçerliDeğer +optionKalıpEşleştirme geçersizDeğer + +// ------ Yazdırma ------ +// printf/printfn fonksiyonları C#'taki +// Console.Write/WriteLine fonksiyonlarına benzer. +printfn "Bir tamsayı %i, bir ondalık %f, bir boolean %b yazdırma" 1 2.0 true +printfn "Bir string %s, ve jenerik bir tip %A" "merhaba" [1; 2; 3; 4] + +// sprintf/sprintfn fonksiyonları ise veriyi string'e +// çevirmek içindir, C#'taki String.Format gibi. + +// ================================================ +// Fonksiyonlar hakkında dahası +// ================================================ + +// F# gerçek bir fonksiyonel dildir. Fonksiyonlar birinci +// sınıf varlıklardır ve güçlü yapılar oluşturmak için +// birleştirilebilirler. + +// Modüller fonksiyonları gruplamak için kullanılır. +// Her bir modül için girinti gerekir. +module FonksiyonOrnekleri = + + // Temel bir ekleme fonksiyonu tanımla + let topla x y = x + y + + // Bir fonksiyonun temel kullanımı + let a = topla 1 2 + printfn "1 + 2 = %i" a + + // Parametreleri kaynaklamak için parçalı uygulama + let kırkİkiEkle = topla 42 + let b = kırkİkiEkle 1 + printfn "42 + 1 = %i" b + + // Fonksiyonları birleştirmek için kompozisyon + let birEkle = topla 1 + let ikiEkle = topla 2 + let üçEkle = birEkle >> ikiEkle + let c = üçEkle 7 + printfn "3 + 7 = %i" c + + // Yüksek dereceli fonksiyonlar + [1..10] |> List.map üçEkle |> printfn "yeni liste: %A" + + // Fonksiyonlar listesi ve dahası + let altıEkle = [birEkle; ikiEkle; üçEkle] |> List.reduce (>>) + let d = altıEkle 7 + printfn "1 + 2 + 3 + 7 = %i" d + +// ================================================ +// Listeler ve kolleksiyonlar +// ================================================ + +// Üç çesit sıralı fonksiyon vardır: +// * Listeler en temel değiştirilemez kolleksiyonlardır. +// * Diziler değiştirilebilir ve gerektiğinde daha verimlidirler. +// * Seriler tembel (lazy evaluation) ve sonsuzdurlar (Enumeratörler gibi). +// +// Değiştirilmez map'ler ve kümeler ve bütün .NET kolleksiyonları +// diğer kolleksiyon türleridir. + +module ListeÖrnekleri = + + // listeler köşeli parantez kullanır + let liste1 = ["a"; "b"] + let liste2 = "c" :: liste1 // :: başa eleman ekler + let liste3 = liste1 @ liste2 // @ listeleri birbirine ekler + + // Liste comprehension'ları (jeneratörler olarak da bilinir) + let kareler = [for i in 1..10 do yield i * i] + + // asal sayı jeneratörü + let rec elek = function + | (p::xler) -> p :: elek [ for x in xler do if x % p > 0 then yield x ] + | [] -> [] + let asallar = elek [2..50] + printfn "%A" asallar + + // Listelerle kalıp eşleştirme + let listeEşleyici liste = + match liste with + | [] -> printfn "liste boş" + | [birinci] -> printfn "listede sadece bir eleman var: %A " birinci + | [birinci; ikinci] -> printfn "liste: %A ve %A" birinci ikinci + | _ -> printfn "listede ikiden fazla eleman var" + + listeEşleyici [1; 2; 3; 4] + listeEşleyici [1; 2] + listeEşleyici [1] + listeEşleyici [] + + // Listeleri kullanarak recursion + let rec ekle liste = + match liste with + | [] -> 0 + | x::xler -> x + ekle xler + ekle [1..10] + + // ----------------------------------------- + // Standart kütüphane fonksiyonları + // ----------------------------------------- + + // map + let üçEkle x = x + 3 + [1..10] |> List.map üçEkle + + // filter + let çift x = x % 2 = 0 + [1..10] |> List.filter çift + + // ve dahası -- dökümantasyona bakınız + +module DiziÖrnekleri = + + // Diziler köşeli parantezle birlikte çubuk karakterini kullanır + let dizi1 = [| "a"; "b" |] + let birinci = dizi1.[0] // nokta kullanarak indeks erişimi + + // Diziler için kalıp eşleştirme listlerle aynıdır + let diziEşleştirici liste = + match liste with + | [| |] -> printfn "dizi boş" + | [| birinci |] -> printfn "dizide sadece bir eleman var: %A " birinci + | [| birinci; ikinci |] -> printfn "dizi: %A ve %A" birinci ikinci + | _ -> printfn "dizide ikiden fazla eleman var" + + diziEşleştirici [| 1; 2; 3; 4 |] + + // Listede olduğu gibi kütüphane fonksiyonları + + [| 1..10 |] + |> Array.map (fun i -> i + 3) + |> Array.filter (fun i -> i % 2 = 0) + |> Array.iter (printfn "değer: %i. ") + + +module SeriÖrnekleri = + + // seriler kıvrık parantez kullanır + let seri1 = seq { yield "a"; yield "b" } + + // seriler yield'ı kullanabilir + // ve alt seriler barındırabilir + let garip = seq { + // "yield" bir eleman ekliyor + yield 1; yield 2; + + // "yield!" bütün bir alt seriyi ekliyor + yield! [5..10] + yield! seq { + for i in 1..10 do + if i % 2 = 0 then yield i }} + // test + garip |> Seq.toList + + + // Seriler "unfold" kullanılarak oluşturulabilir + // Fibonacci serisi örneği + let fib = Seq.unfold (fun (birinci,ikinci) -> + Some(birinci + ikinci, (ikinci, birinci + ikinci))) (0,1) + + // test + let fib10 = fib |> Seq.take 10 |> Seq.toList + printf "ilk 10 fibonacci sayısı: %A" fib10 + + +// ================================================ +// Veri Tipleri +// ================================================ + +module VeriTipiÖrnekleri = + + // Bütün veriler varsayılan olarak değiştirilemezdir. + + // -- Tuple oluşturmak için virgül kullan + let ikiliTuple = 1, 2 + let üçlüTuple = "a", 2, true + + // Tuple'lar çabuk ve kolay anonim tiplerdir. + // paketi açmak için kalıp eşleştirme kullan + let x, y = ikiliTuple // x = 1, y = 2 + + // ------------------------------------ + // Record tipi isimlendirilmiş alanlara sahiptir + // ------------------------------------ + + // "type" ile kıvrık parantezleri record tipi oluşturmak için kullan + type Kişi = {Ad:string; Soyad:string} + + // "let" ile kıvrık parantezi record tipi oluşturmak için kullan + let kişi1 = {Ad="Falanca"; Soyad="Kişi"} + + // paketi açmak için kalıp eşleştirme kullan + let {Ad = Ad} = kişi1 // birinci="John" + + // ------------------------------------ + // Union tipleri (değişkenler olarak da bilinir) birden fazla + // seçeneğe sahiptir. Belli bir zamanda sadece bir tanesi geçerlidir. + // ------------------------------------ + + // "type" ile çubuk karakterini union tipi tanımlamak için kullan + type Sıcaklık = + | Santigrat of float + | Fahrenhayt of float + + // Seçeneklerden birini kullan + let derece1 = Fahrenhayt 98.6 + let derece2 = Santigrat 37.0 + + // Paketi açmak için bütün seçenekler üzerinde kalıp eşleştirme kullan + let dereceYazdır = function + | Santigrat t -> printfn "%f C" t + | Fahrenhayt t -> printfn "%f F" t + + dereceYazdır derece1 + dereceYazdır derece2 + + // ------------------------------------ + // Yinelgen (Recursive) tipler + // ------------------------------------ + + // Tipler alt sınıflar oluşturmadan karmaşık şekillerde + // yinelgen olarak birleştirilebilirler. + type Çalışan = + | İşçi of Kişi + | Yönetici of Çalışan list + + let falancaKişi = {Ad="Falanca"; Soyad="Kişi"} + let işçi = İşçi falancaKişi + + // ------------------------------------ + // Tipleri Kullanarak Modelleme + // ------------------------------------ + + // Union tipleri bayrak kullanmadan durum modelleme için harikadır. + type EpostaAdresi = + | GeçerliEpostaAdresi of string + | GeçersizEpostaAdresi of string + + let epostaGöndermeyiDene eposta = + match eposta with // kalıp eşleştirme kullan + | GeçerliEpostaAdresi adres -> () // gönder + | GeçersizEpostaAdresi adres -> () // gönderme + + // Union tiplerin record tiplerle birleşimi + // domain driven design için iyi bir temel oluşturur. + // Domain'i yansıtan yüzlerce ufak tip oluşturabilirsiniz. + + type Ürün = { ÜrünKodu: string; Miktar: int } + type Ödeme = Ödeme of float + type AktifSepetVerisi = { ÖdenmemişÜrünler: Ürün list } + type ÖdenmişSepetVerisi = { ÖdenmişÜrünler: Ürün list; Ödeme: Ödeme} + + type AlışverişSepeti = + | BosSepet // veri yok + | AktifSepet of AktifSepetVerisi + | ÖdenmişSepet of ÖdenmişSepetVerisi + + // ------------------------------------ + // Tipler için içgüdüsel davranış + // ------------------------------------ + + // Çekirdek tipler kendinden çok kullanışlı özelliklere sahiptir + // Ek kodlama gerektirmez + // * Değişmezlik + // * Debug ederken yazdırma + // * Eşitlik ve kıyaslama + // * Serialization + + // %A kullanarak yazdırma + printfn "ikiliTuple=%A,\nKişi=%A,\Sıcaklık=%A,\nÇalışan=%A" + ikiliTuple kişi1 derece1 işçi + + // Eşitlik ve kıyaslama içgüdüseldir. + // İskambil kartlarıyla bir örnek + type Simge = Sinek | Karo | Maça | Kupa + type Sıra = İki | Üç | Dört | Beş | Altı | Yedi | Sekiz + | Dokuz | On | Bacak | Kız | Papaz | As + + let el = [ Sinek, As; Kupa, Üç; Kupa, As; + Maça, Bacak; Karo, İki; Karo, As ] + + // Sıralama + List.sort el |> printfn "artarak dizilen el: %A" + List.max el |> printfn "en yüksek kart: %A" + List.min el |> printfn "en düşük kart: %A" + + +// ================================================ +// Aktif Kalıplar +// ================================================ + +module AktifKalıpÖrnekleri = + + // F# "aktif kalıplar" denen bir kalıp eşleştirmeye sahiptir. + // Kalıplar dinamik bir şekilde tespit edilip eşleştirilebilir. + + // Aktif kalıplar için söz dizimi (| ... |) şeklindedir + + // Örneğin, karakter tiplerini eşleyen bir "aktif" kalıp tanımlayın... + let (|Rakam|Harf|Boşluk|Diğer|) karakter = + if System.Char.IsDigit(karakter) then Rakam + else if System.Char.IsLetter(karakter) then Harf + else if System.Char.IsWhiteSpace(karakter) then Boşluk + else Diğer + + // ... daha sonra eşleme mantığı çok daha net yapmak için bunu kullanın + let karakterYazdır karakter = + match karakter with + | Rakam -> printfn "%c bir rakamdır" karakter + | Harf -> printfn "%c bir harftir" karakter + | Boşluk -> printfn "%c bir boşluktur" karakter + | _ -> printfn "%c başka bir şeydir" karakter + + // Bir liste yazdırma + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter karakterYazdır + + // ----------------------------------- + // Aktif Kalıpları Kullanarak FizzBuzz + // ----------------------------------- + + // Parçalı eşleşen kalıplar da oluşturabilirsiniz + // Tanımda alt çizgi karakterini kullanın ve eşleşince Some döndürün. + let (|ÜçünKatı|_|) i = if i % 3 = 0 then Some ÜçünKatı else None + let (|BeşinKatı|_|) i = if i % 5 = 0 then Some BeşinKatı else None + + // Ana fonksiyon + let fizzBuzz i = + match i with + | ÜçünKatı & BeşinKatı -> printf "FizzBuzz, " + | ÜçünKatı -> printf "Fizz, " + | BeşinKatı -> printf "Buzz, " + | _ -> printf "%i, " i + + // test + [1..20] |> List.iter fizzBuzz + +// ================================================ +// Sadelik +// ================================================ + +module AlgoritmaÖrnekleri = + + // F#'ın sinyal/gürültü oranı yüksektir, dolayısıyla + // kod algoritmayla hemen hemen aynı görünür. + + // ------ Örnek: karelerToplami fonksiyonunu tanımla ------ + let karelerToplamı n = + [1..n] // 1) 1'den n'e kadar bütün sayıları al + |> List.map kare // 2) hepsinin karesini al + |> List.sum // 3) sonuçları topla + + // test + karelerToplamı 100 |> printfn "kareler toplamı = %A" + + // ------ Örnek: bir sıralama fonksiyonu tanımla ------ + let rec sırala liste = + match liste with + // Liste boşsa + | [] -> + [] // boş listeyi döndür + // Liste boş değilse + | ilkEleman::diğerElemanlar -> // İlk elemanı al + let küçükElemanlar = // Daha küçük elemanları + diğerElemanlar // diğerlerinden ayır + |> List.filter (fun e -> e < ilkEleman) + |> sırala // ve sırala + let büyükElemanlar = // Daha büyük elemanları + diğerElemanlar // diğerlerinden ayır + |> List.filter (fun e -> e >= ilkEleman) + |> sırala // ve sırala + // 3 parçayı birbirine ekle ve listeyi döndür + List.concat [küçükElemanlar; [ilkEleman]; büyükElemanlar] + + // test + sırala [1; 5; 23; 18; 9; 1; 3] |> printfn "Sırala = %A" + +// ================================================ +// Eşzamansız kod +// ================================================ + +module EşzamansızÖrneği = + + // F# "pyramid of doom" durumuyla karşılaştırmayacak şekilde + // içgüdüsel eşzamansız özelliklere sahiptir. + // + // Bir sonraki örnek bir web sayfasını paralel bir şekilde indirir. + + open System.Net + open System + open System.IO + open Microsoft.FSharp.Control.CommonExtensions + + // İçeriği eşzamansız bir şekilde getir + let eşzamansızUrlGetir url = + async { // "async" anahtar kelimesi ve kıvrık parantez + // "async (eşzamansız)" nesneyi oluşturur + let istek = WebRequest.Create(Uri(url)) + use! cevap = istek.AsyncGetResponse() + // use! eşzamansız atamadır + use akış = cevap.GetResponseStream() + // "use" kullanılan bloğun dışına çıkınca + // close()'u otomatik olarak tetikler + use okuyucu = new IO.StreamReader(akış) + let html = okuyucu.ReadToEnd() + printfn "İndirme tamamlandı: %s" url + } + + // İndirmek için bir web sitesi listesi + let siteler = ["http://www.bing.com"; + "http://www.google.com"; + "http://www.microsoft.com"; + "http://www.amazon.com"; + "http://www.yahoo.com"] + + // İndir + siteler + |> List.map eşzamansızUrlGetir // eşzamansız görevlerden oluşan bir liste yap + |> Async.Parallel // bu görevleri paralel çalışacak şekilde ayarla + |> Async.RunSynchronously // başlat + +// ================================================ +// .NET uyumluluğu +// ================================================ + +module NetUyumlulukÖrnekleri = + + // F#, C#'ın yapabildiği hemen herşeyi yapabilir, + // ve .NET ve Mono kütüphaneleriyle tereyağından kıl çeker gibi çalışır. + + // ------- var olan kütüphane fonksiyonları ile çalışma ------- + + let (i1başarılı, i1) = System.Int32.TryParse("123"); + if i1başarılı then printfn "%i olarak dönüştürüldü" i1 else printfn "dönüştürme başarısız" + + // ------- Arayüzleri yol üstünde tanımlayın! ------- + + // IDisposable'ı sağlayan yeni bir nesne oluştur + let kaynakOluştur isim = + { new System.IDisposable + with member this.Dispose() = printfn "%s atıldı" isim } + + let kaynakKullanVeAt = + use r1 = kaynakOluştur "birinci kaynak" + printfn "birinci kaynağı kullanıyor" + for i in [1..3] do + let kaynakİsmi = sprintf "\tiç kaynak %d" i + use geçici = kaynakOluştur kaynakİsmi + printfn "\t%s ile bir şey yap" kaynakİsmi + use r2 = kaynakOluştur "ikinci kaynak" + printfn "ikinci kaynağı kullanıyor" + printfn "bitti." + + // ------- Nesne yönelimli kod ------- + + // F# aynı zamanda tam bir nesne yönelimli dildir. + // Sınıfları, kalıtımı ve sanal metotları destekler. + + // Genel tipli bir arayüz + type IEnumerator<'a> = + abstract member Şimdiki : 'a + abstract SonrakineGeç : unit -> bool + + // Sanal metotları olan soyut temel sınıflar + [<AbstractClass>] + type Şekil() = + // sadece okunabilir özellikler + abstract member Genişlik : int with get + abstract member Yükseklik : int with get + // sanal olmayan metot + member this.ÇevreleyenAlan = this.Yükseklik * this.Genişlik + // temel uygulamasıyla bir sanal metot + abstract member Yazdır : unit -> unit + default this.Yazdır () = printfn "Ben bir şekil (önümden çekil!)" + + // Somut bir sınıfın soyut sınıftan kalıtımı + type Dikdörtgen(x:int, y:int) = + inherit Şekil() + override this.Genişlik = x + override this.Yükseklik = y + override this.Yazdır () = printfn "Ben bir dikdörtgenim" + + // test + let r = Dikdörtgen(2, 3) + printfn "Genişlik: %i" r.Genişlik + printfn "Çevreleyen Alan: %i" r.ÇevreleyenAlan + r.Yazdır() + + // ------- ekleme metotları ------- + + // C#'ta olduğu gibi F# da var olan sınıfları ekleme metotları ile genişletebilir. + type System.String with + member this.StartsWithA = this.StartsWith "A" + + // test + let s = "Ahmet" + printfn "'%s' 'A' ile başlar = %A" s s.StartsWithA + + // ------- olaylar ------- + + type Butonum() = + let tıklamaOlayı = new Event<_>() + + [<CLIEvent>] + member this.OnClick = tıklamaOlayı.Publish + + member this.DenemeOlayı(arg) = + tıklamaOlayı.Trigger(this, arg) + + // test + let butonum = new Butonum() + butonum.OnClick.Add(fun (sender, arg) -> + printfn "arg=%O ile beraber bir tıklama olayı" arg) + + butonum.DenemeOlayı("Merhaba Dünya!") + +``` + +## Daha fazla bilgi + +F# hakkında daha fazla demo için [Try F#](http://www.tryfsharp.org/Learn) sitesine gidin, veya benim (yazarın) [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/) serimi okuyun. + +F# hakkında daha fazla bilgi için: [fsharp.org](http://fsharp.org/). diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index c7de2922..e53d5568 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -618,14 +618,19 @@ print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayana ### Ücretsiz Online +* [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/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) ### Kitaplar diff --git a/tr-tr/typescript-tr.html.markdown b/tr-tr/typescript-tr.html.markdown new file mode 100644 index 00000000..1bf674c6 --- /dev/null +++ b/tr-tr/typescript-tr.html.markdown @@ -0,0 +1,180 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Mustafa Zengin", "http://zengin.github.com"] +filename: learntypescript-tr.ts +lang: tr-tr +--- + +TypeScript, JavaScript'le yazılmış büyük ölçekli uygulamaların geliştirilmesini kolaylaştırmayı hedefleyen bir dildir. +TypeScript, JavaScript'e sınıflar, modüller, arayüzler, jenerik tipler ve (isteğe bağlı) static tipleme gibi genel konseptler ekler. +JavaScript, TypeScript'in bir alt kümesidir: Bütün JavaScript kodları geçerli birer TypeScript kodudur ve sorunsuz herhangi bir projeye eklenebilirler. TypeScript derleyici JavaScript kodu üretir. + +Bu makale sadece TypeScript'e ait ekstra söz dizimini konu alır, JavaScript için bkz: [JavaScript] (../javascript/). + +TypeScript derleyiciyi test etmek için [Playground] (http://www.typescriptlang.org/Playground)'a gidin. Orada otomatik tamamlama ile kod yazabilecek ve üretilen JavaScript'i görebileceksiniz. + +```js +// TypeScript'te üç ana tip vardır. +var bittiMi: boolean = false; +var satırlar: number = 42; +var isim: string = "Anders"; + +// Tipin bilinmediği zamanlar için "Any" tipi +var bilinmiyor: any = 4; +bilinmiyor = "belki de bir string'dir"; +bilinmiyor = false; // tamam, boolean olsun + +// Kolleksiyon olarak, tipli ve jenerik diziler +var liste: number[] = [1, 2, 3]; +// Alternatif olarak jenerik Array tipi +var liste: Array<number> = [1, 2, 3]; + +// 'enum' tipleri: +enum Renk {Kırmızı, Yeşil, Mavi}; +var r: Renk = Renk.Yeşil; + +// Son olarak, "void" hiç bir şey döndürmeyen fonksiyonlarda kullanılan tiptir. +function çokFeciBirUyarı(): void { + alert("Ben biraz sinir bozucuyum!"); +} + +// Fonksiyonlar birinci sınıf vatandaşlardır ve "kalın ok" lambda söz dizimi "=>" +// ve tip çıkarımı kullanırlar. +// Aşağıda listelenenler birbirinin aynısı ve derleyici aynı fonksiyon yapısını +// çıkaracak ve aynı JavaScript kodunu üretecektir +var f1 = function(i: number): number { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +var f4 = (i: number) => { return i * i; } +// Döndürülen tip tip çıkarımıyla belirlendi +// Tek satırlık yazımda "return" anahtar kelimesine ihtiyaç yok. +var f5 = (i: number) => i * i; + +// Arayüzler yapısaldır, listelenen özelliklere sahip her şey arayüzle uyumludur. +interface Kişi { + isim: string; + // İsteğe bağlı özellikler "?" ile işaretlenir + yaş?: number; + // Ve fonksiyonlar... + hareketEt(): void; +} + +// "Kişi" arayüzünü kullanan bir nesne +// isim ve hareketEt özelliklerine sahip olduğu için Kişi olarak kullanılabilir. +var p: Kişi = { isim: "Anders", hareketEt: () => {} }; +// İsteğe bağlı özelliğe sahip bir Kişi +var geçerliKişi: Kişi = { isim: "Anders", yaş: 42, hareketEt: () => {} }; +// Geçersiz bir kişi, çünkü yaş bir sayı (number) tipi değil +var geçersizKişi: Kişi = { isim: "Anders", yaş: true }; + +// Arayüzler bir fonksiyon tipi de ifade edebilirler +interface aramaFonksiyonu { + (kaynak: string, altString: string): boolean; +} + +// Parametrelerin sadece tipleri önemli, isimleri önemli değil +var benimAramam: aramaFonksiyonu; +benimAramam = function(kynk: string, alt: string) { + return kynk.search(alt) != -1; +} + +// Sınıflar - üyeler (members) varsayılan olarak public'tir. +class Nokta { + // Özellikler + x: number; + + // Yapıcı (constructor) - bu bağlamdaki public/private anahtar kelimeleri + // özellikler için gerekli demirbaş kodu oluşturur ve ilk değerlerin + // atanmasını sağlar. + // Bu örnekte, "y" de "x" gibi tanımlanacak is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Fonksiyonlar + mesafe() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statik üyeler + static orijin = new Nokta(0, 0); +} + +var p1 = new Nokta(10 ,20); +var p2 = new Nokta(25); //y = 0 + +// Kalıtım +class Nokta3Boyutlu extends Nokta { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // süper sınıfın yapıcısını çağırmak zorunlu + } + + // yeniden tanımlama + mesafe() { + var d = super.mesafe(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modüller, "." alt modülleri ayırmak için kullanılabilir +module Geometri { + export class Kare { + constructor(public kenarUzunluğu: number = 0) { + } + alan() { + return Math.pow(this.kenarUzunluğu, 2); + } + } +} + +var s1 = new Geometri.Kare(5); + +// Modüle atıfta bulunmak için yerel takma ad +import G = Geometri; + +var s2 = new G.Kare(10); + +// Jenerik Tipler +// Sınıflar +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// Arayüzler +interface Çift<T> { + item1: T; + item2: T; +} + +// Ve fonksiyonlar +var çifttenTupleÜret = function<T>(p: Çift<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = çifttenTupleÜret({ item1:"merhaba", item2:"dünya"}); + +// Tanım dosyasına atıfta bulunma: +/// <reference path="jquery.d.ts" /> + +// Şablon Stringleri (ters apostrof kullanan stringler) +// Şablon Stringlerinin kullanımı +var isim = 'Anders'; +var selamlama = `Merhaba ${isim}, nasılsın?` +// Şablon Stringleri ile çok satırlı stringler +var çokSatırlıString = `Bu çok satırlı +bir string örneği`; + +``` + +## Daha fazlası + * [TypeScript Resmi Sitesi] (http://www.typescriptlang.org/) + * [TypeScript dil spesifikasyonu (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Channel 9'da TypeScript'e Giriş] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [GitHub'ta Açık Kaynak Kodu] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - tip tanımları için kaynak] (http://definitelytyped.org/) diff --git a/typescript.html.markdown b/typescript.html.markdown index 47e41405..21f1ce7d 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -171,7 +171,7 @@ of a multiline string`; ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) - * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [TypeScript language specifications] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 9614f9ca..a84eba67 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -3,6 +3,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["clearsense", "https://github.com/clearsense"] filename: javascript-uk.js translators: - ["Ivan", "https://github.com/IvanEh"] @@ -350,6 +351,7 @@ myFunc(); // = undefined // Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до // цього об’єкта через this var myOtherFunc = function() { + return this.myString.toUpperCase(); } myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO, WORLD!" @@ -407,7 +409,7 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 // Аналогічно для функцій -myObj.myFunc(); // = "Hello, world!" +myObj.myFunc(); // = "hello, world!" // Якщо інтерпретатор не знайде властивості в прототипі, то він продовжить пошук // в прототипі прототипа і так далі @@ -432,7 +434,7 @@ myObj.meaningOfLife; // = 43 // Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* // прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені -// цим конструктором і ключового слова new. +// цим конструктором і ключовим словом new. MyConstructor.prototype = { myNumber: 5, getMyNumber: function() { @@ -454,9 +456,6 @@ myNumber == myNumberObj; // = true typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false -if (0) { - // Цей код не виконається, тому що 0 - це хиба. -} // Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому // ви можете розширити функціонал рядків: @@ -484,12 +483,12 @@ if (Object.create === undefined) { // не перезаписуємо метод ## Що почитати -[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript -[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core -[4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ -[6]: http://www.amazon.com/gp/product/0596805527/ -[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[8]: http://eloquentjavascript.net/ -[9]: http://jstherightway.org/ +* [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +* [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +* [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +* [4]: http://www.learneroo.com/modules/64/nodes/350 +* [5]: http://bonsaiden.github.io/JavaScript-Garden/ +* [6]: http://www.amazon.com/gp/product/0596805527/ +* [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +* [8]: http://eloquentjavascript.net/ +* [9]: http://jstherightway.org/ diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index 38e418e9..8bc334ab 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -1,12 +1,10 @@ ---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
lang: vi-vn
filename: LearnObjectiveC-vi.m
-
---
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
diff --git a/vim.html.markdown b/vim.html.markdown new file mode 100644 index 00000000..80c5835a --- /dev/null +++ b/vim.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +filename: LearnVim.txt +--- + + +[Vim](www.vim.org) +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a a text +editor designed for speed and increased productivity, and is ubiquitous in most +unix-based systems. It has numerous keybindings for speedy navigation to +specific points in the file, and for fast editing. + +## Basics of navigating Vim + +``` + vim <filename> # Open <filename> in vim + :q # Quit vim + :w # Save current file + :wq # Save file and quit vim + :q! # Quit vim without saving file + # ! *forces* :q to execute, hence quiting vim without saving + :x # Save file and quit vim, shorter version of :wq + + u # Undo + CTRL+R # Redo + + h # Move left one character + j # Move down one line + k # Move up one line + l # Move right one character + + # Moving within the line + + 0 # Move to beginning of line + $ # Move to end of line + ^ # Move to first non-blank character in line + + # Searching in the text + + /word # Highlights all occurences of word after cursor + ?word # Highlights all occurences of word before cursor + n # Moves cursor to next occurence of word after search + N # Moves cursor to previous occerence of word + + :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file + :s/foo/bar/g # Change 'foo' to 'bar' on the current line + + # Jumping to characters + + f<character> # Jump forward and land on <character> + t<character> # Jump forward and land right before <character> + + # For example, + f< # Jump forward and land on < + t< # Jump forward and land right before < + + # Moving by word + + w # Move forward by one word + b # Move back by one word + e # Move to end of current word + + # Other characters for moving around + + gg # Go to the top of the file + G # Go to the bottom of the file + :NUM # Go to line number NUM (NUM is any number) + H # Move to the top of the screen + M # Move to the middle of the screen + L # Move to the bottom of the screen +``` + +## Modes: + +Vim is based on the concept on **modes**. + +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them +Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands + +``` + i # Puts vim into insert mode, before the cursor position + a # Puts vim into insert mode, after the cursor position + v # Puts vim into visual mode + : # Puts vim into ex mode + <esc> # 'Escapes' from whichever mode you're in, into Command mode + + # Copying and pasting text + + y # Yank whatever is selected + yy # Yank the current line + d # Delete whatever is selected + dd # Delete the current line + p # Paste the copied text after the current cursor position + P # Paste the copied text before the current cursor position + x # Deleting character under current cursor position +``` + +## The 'Grammar' of vim + +Vim can be thought of as a set of commands in a +'Verb-Modifier-Noun' format, where: + +Verb - your action +Modifier - how you're doing your action +Noun - the object on which your action acts on + +A few important examples of 'Verbs, 'Modifiers', and 'Nouns': + +``` + # 'Verbs' + + d # Delete + c # Change + y # Yank (copy) + v # Visually select + + # 'Modifiers' + + i # Inside + a # Around + NUM # Number (NUM is any number) + f # Searches for something and lands on it + t # Searches for something and stops before it + / # Finds a string from cursor onwards + ? # Finds a string before cursor + + # 'Nouns' + + w # Word + s # Sentence + p # Paragraph + b # Block + + # Sample 'sentences' or commands + + d2w # Delete 2 words + cis # Change inside sentence + yip # Yank inside paragraph (copy the para you're in) + ct< # Change to open bracket + # Change the text from where you are to the next open bracket + d$ # Delete till end of line +``` + +## Some shortcuts and tricks + + <!--TODO: Add more!--> +``` + > # Indent selection by one block + < # Dedent selection by one block + :earlier 15m # Reverts the document back to how it was 15 minutes ago + :later 15m # Reverse above command + ddp # Swap position of consecutive lines, dd then p + . # Repeat previous action +``` + +## Macros + +Macros are basically recordable actions. +When you start recording a macro, it records **every** action and command +you use, until you stop recording. On invoking a macro, it applies the exact +same sequence of actions and commands again on the text selection. + +``` + qa # Start recording a macro named 'a' + q # Stop recording + @a # Play back the macro +``` + +### Configuring ~/.vimrc + +The .vimrc file can be used to configure Vim on startup. + +Here's a sample ~/.vimrc file: + +``` +" Example ~/.vimrc +" 2015.10 + +" Required for vim to be iMproved +set nocompatible + +" Determines filetype from name to allow intelligent auto-indenting, etc. +filetype indent plugin on + +" Enable syntax highlighting +syntax on + +" Better command-line completion +set wildmenu + +" Use case insensitive search except when using capital letters +set ignorecase +set smartcase + +" When opening a new line and no file-specific indenting is enabled, +" keep same indent as the line you're currently on +set autoindent + +" Display line numbers on the left +set number + +" Indentation options, change according to personal preference + +" Number of visual spaces per TAB +set tabstop=4 + +" Number of spaces in TAB when editing +set softtabstop=4 + +" Number of spaces indented when reindent operations (>> and <<) are used +set shiftwidth=4 + +" Convert TABs to spaces +set expandtab + +" Enable intelligent tabbing and spacing for indentation and alignment +set smarttab +``` + +### References + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) diff --git a/yaml.html.markdown b/yaml.html.markdown index 507c4d1f..a1ef0d38 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -164,3 +164,8 @@ set2: item2: null item3: null ``` + +### More Resources + ++ [YAML official website](http://yaml.org/) ++ [Online YAML Validator](http://codebeautify.org/yaml-validator) diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown index b82829a9..c7fe7e2c 100644 --- a/zh-cn/common-lisp-cn.html.markdown +++ b/zh-cn/common-lisp-cn.html.markdown @@ -14,6 +14,8 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范 免费的经典的入门书籍[《实用 Common Lisp 编程》](http://www.gigamonkeys.com/book/) +许多人都抱怨上面这本书的翻译。[《ANSI Common Lisp》](http://acl.readthedocs.org/en/latest/)也许对中文读者更友好一些。 + 另外还有一本热门的近期出版的 [Land of Lisp](http://landoflisp.com/). diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index f7065445..6736dc2a 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -416,7 +416,7 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a> 顺便说一下,整个文件是可运行的Lua; -保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! +保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧! 本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown new file mode 100644 index 00000000..2651b1cb --- /dev/null +++ b/zh-cn/typescript-cn.html.markdown @@ -0,0 +1,173 @@ +--- +language: TypeScript +category: language +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Shawn Zhang", "https://github.com/shawnzhang009"] +filename: learntypescript-cn.ts +lang: zh-cn +--- + +TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。 + +本文只关注TypeScript额外增加的区别于[JavaScript](../javascript-cn/)的语法,. + +如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。 + +```js +// TypeScript有三种基本类型 +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// 如果不知道是什么类型,可以使用"any"(任意)类型 +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // 亦可,定义为布尔型 + +// 对于集合的声明, 有类型化数组和泛型数组 +var list: number[] = [1, 2, 3]; +// 另外一种,使用泛型数组 +var list: Array<number> = [1, 2, 3]; + +// 枚举: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// 最后,"void"用于函数没有任何返回的特殊情况下 +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// 函数是"第一等公民"(first class citizens), 支持使用箭头表达式和类型推断 + +// 以下是相等的,TypeScript编译器会把它们编译成相同的JavaScript代码 +var f1 = function(i: number): number { return i * i; } +// 返回推断类型的值 +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// 返回推断类型的值 +var f4 = (i: number) => { return i * i; } +// 返回推断类型的值, 单行程式可以不需要return关键字和大括号 +var f5 = (i: number) => i * i; + +// 接口是结构化的,任何具有这些属性的对象都与该接口兼容 +interface Person { + name: string; + // 可选属性,使用"?"标识 + age?: number; + // 函数 + move(): void; +} + +// 实现"Person"接口的对象,当它有了"name"和"move"方法之后可被视为一个"Person" +var p: Person = { name: "Bobby", move: () => {} }; +// 带了可选参数的对象 +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// 因为"age"不是"number"类型所以这不是一个"Person" +var invalidPerson: Person = { name: "Bobby", age: true }; + +// 接口同样可以描述一个函数的类型 +interface SearchFunc { + (source: string, subString: string): boolean; +} +// 参数名并不重要,参数类型才是重要的 +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// 类 - 成员默认为公共的(public) +class Point { + // 属性 + x: number; + + // 构造器 - 这里面的public/private关键字会为属性生成样板代码和初始化值 + // 这个例子中,y会被同x一样定义,不需要额外代码 + // 同样支持默认值 + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // 函数 + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // 静态成员 + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y为0 + +// 继承 +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // 必须显式调用父类的构造器 + } + + // 重写 + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// 模块, "."可以作为子模块的分隔符 +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// 引入模块并定义本地别名 +import G = Geometry; + +var s2 = new G.Square(10); + +// 泛型 +// 类 +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// 接口 +interface Pair<T> { + item1: T; + item2: T; +} + +// 以及函数 +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// 引用定义文件 +// <reference path="jquery.d.ts" /> + +// 模板字符串(使用反引号的字符串) +// 嵌入变量的模板字符串 +var name = 'Tyrone'; +var greeting = `Hi ${name}, how are you?` +// 有多行内容的模板字符串 +var multiline = `This is an example +of a multiline string`; + +``` + +## 参考资料 + * [TypeScript官网](http://www.typescriptlang.org/) + * [TypeScript语言规范说明书(pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - TypeScript介绍](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [GitHub源码](https://github.com/Microsoft/TypeScript) + * [Definitely Typed - 类型定义仓库](http://definitelytyped.org/) diff --git a/zh-tw/elixir-tw.html.markdown b/zh-tw/elixir-tw.html.markdown new file mode 100644 index 00000000..c15f90c1 --- /dev/null +++ b/zh-tw/elixir-tw.html.markdown @@ -0,0 +1,413 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tai An Su", "https://github.com/taiansu"] +filename: learnelixir-tw.ex +lang: zh-tw +--- + +Elixir 是一門建構在 Erlang 虛擬機上的現代函數式語言。它完全與 Erlang 相容,但 +採行了比較常見的語法,並提供更多的功能。 + +```elixir + +# 單行註解以井字號開頭 + +# 沒有多行註解的功能 +# 但你可以連續使用多個單行 + +# 用 `iex` 來進入 elixir shell +# 用 `elixirc` 來編譯你的模組 + +# 如果你已成功安裝 elixir 的話,這兩個命令應已在你的 path 下。 + +## --------------------------- +## -- 基本型別 +## --------------------------- + +# 數字 +3 # 整數 +0x1F # 整數 +3.0 # 浮點數 + +# 原子 (Atoms) 是不可變的字面常數,以 `:` 開頭。 +:hello # atom + +# 元組(Tuples) 會存在記憶體連續的區段裡。 +{1,2,3} # tuple + +# 我們可以用 `elem` 函式來取得 tuple 中的元素。 +elem({1, 2, 3}, 0) #=> 1 + +# 串列 (List) 是用連結串列實作的。 +[1,2,3] # list + +# 我們可以這樣取得串列的頭尾元素: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# 在 elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。 +# +# 這代表將使用左手邊的模式 (pattern) 去與右手邊的值進行比對。 +# +# 這也是先前取得串列的頭尾元素的運作原理 + +# 當模式比對無法找到合適的配對時,將會回報錯誤,如下例中兩個 tuple 的大小不一致。 +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# 還有二進位的型別 +<<1,2,3>> # binary + +# 字串與字母串列 +"hello" # string +'hello' # char list + +# 多行字串 +""" +I'm a multi-line +string. +""" +#=> "I'm a multi-line\nstring.\n" + +# 字串皆使用 UTF-8 編碼 +"héllò" #=> "héllò" + +# 字串其實是以二進位實作,而字母串列就只是單純的串列。 +<<?a, ?b, ?c>> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` 在 elixir 中會回傳字母 `a` 的 ASCII 整數 +?a #=> 97 + +# 用 `++` 來合併串列,而合併二進位則要用 `<>` +[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" + +# 範圍 (Ranges) 則是以 `開頭..結尾`來宣告 (頭尾都包含在內) +1..10 #=> 1..10 +lower..upper = 1..10 # 可以對 range 進行模式比對 +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- 運算元 +## --------------------------- + +# 簡單算數 +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# 在 elixir 中, `/` 運算元永遠回傳浮點數。 + +# 若需要回傳整數的除法,用 `div` +div(10, 2) #=> 5 + +# 要得到除法的餘數時,用 `rem` +rem(10, 3) #=> 1 + +# 還有布林運算元: `or`, `and` and `not`. +# 這些運算元要求第一個參數必需為布林值。 +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir 也提供了 `||`, `&&` 及 `!`,它們接受任何型別的參數。 +# 除了 `false` 與 `nil` 之外的值都會被當做 true。 +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# 用來比較的運算元有:`==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` 和 `!==` 會嚴格比較整數與浮點數 +1 == 1.0 #=> true +1 === 1.0 #=> false + +# 兩個不同的型別也可以比較 +1 < :hello #=> true + +# 所有型別的排序如下: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# 引用 Joe Armstrong 的話: "實際排序的先後並不重要, 但有明確排出全體順序的定 +# 義才是重要的。" + +## --------------------------- +## -- 控制流程 +## --------------------------- + +# `if` 表達式 +if false do + "This will never be seen" +else + "This will" +end + +# 也有 `unless` +unless true do + "This will never be seen" +else + "This will" +end + +# 還記得模式比對嗎?Elixir 中許多控制流程的結構都依賴模式比對來運作。 + +# `case` 讓我們可以將一個值與許多模式進行比對: +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 + +# 當我們不需要某個值的時候,通常會將它比對成 `_`。 +# 例如我們只關心串列的第一個值的情況時: +[head | _] = [1,2,3] +head #=> 1 + +# 若希望程式更好懂時,我們會這樣處理: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` 讓我們可以同時檢測多個不同的值。 +# 用 `cond` 來代替巢狀的 `if` 表達式 +cond do + 1 + 1 == 3 -> + "I will never be seen" + 2 * 5 == 12 -> + "Me neither" + 1 + 2 == 3 -> + "But I will" +end + +# 把最後一個條件設為 `true` 來捕捉剩下的所有情況是很常見的作法。 +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` 用來捕捉拋出的值,它也提供 `after` 子句,無論是否有接到拋出的值, +# 最後都會調用其下的程式。 +try do + throw(:hello) +catch + message -> "Got #{message}." +after + IO.puts("I'm the after clause.") +end +#=> I'm the after clause +# "Got :hello" + +## --------------------------- +## -- 模組與函式 +## --------------------------- + +# 匿名函式 (注意那個句點) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# 匿名函式也接受多個子句及防衛(guards) +# Guards 可以進行模式比對 +# 用 `when` 來描述 guards +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir 也提供許多內建的函式 +# 這些在預設的作用域下都可以使用 +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# 你可以用模組將多個的函式集合在一起。在模組裡,用 `def` 來定義函式。 +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 + +# 要編譯我們的 Math 模組時,先將它存成 `math.ex`,再用 `elixirc` 進行編譯。 +# 在終端機輸入: elixirc math.ex + +# 在模組中我們可以用 `def` 宣告函式,及用 `defp` 宣告私有 (private) 函式。 +# 使用 `def` 定義的函式可以在其它的模組中被調用。 +# 私有的函式只能在這個模組內部調用。 +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) + +# 函式宣告也支援用防衛條件及多個條件子句 +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 + +# 由於不可變特性 (immutability),遞迴在 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 + +# Elixir 模組也支援屬性,模組有內建一些屬性,而你也可以定義自己的屬性。 +defmodule MyMod do + @moduledoc """ + 這是內建的屬性,模組文件 + """ + + @my_data 100 # 這是自訂的屬性 + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- 結構與例外 (Structs and Exceptions) +## --------------------------- + +# 結構 (structs) 是 maps 的擴展。是 Elixir 裡可以有預設值,編譯期檢查及 +# 多形 (polymorphism) 的資料結構。 +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"} + +# 取得 name 的值 +joe_info.name #=> "Joe" + +# 更新 age 的值 +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} + +# The `try` block with the `rescue` keyword is used to handle exceptions +# 帶有 `rescue` 關鍵字的 `try` 區塊是用來進行例外處理的。 +try do + raise "some error" +rescue + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" +end +#=> "rescued a runtime error" + +# 所有的異常都有帶著一個訊息 +try do + raise "some error" +rescue + x in [RuntimeError] -> + x.message +end +#=> "some error" + +## --------------------------- +## -- 平行處理 +## --------------------------- + +# Elixir 依靠 actor 模式來進行平行處理。在 elixir 中要寫出平行處理程式, +# 只需要三個基本要素:建立行程,發送訊息及接收訊息。 + +# 我們用 `spawn` 函式來建立行程,它接收一個函式當參數。 +f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> +spawn(f) #=> #PID<0.40.0> + +# `spawn` 會回傳一個 pid (行程識別碼),你可以利用這個 pid 來對該行程傳送訊息。 +# 我們會使用 `send` 運算元來傳送訊息。但首先我們要讓該行程可以接收訊息。這要用 +# 到 `receive` 機制來達成。 + +# `receive` 區塊能讓行程監聽接收到的訊息。每個 `receive do` 區塊只能接收一條 +# 訊息。若要接收多條訊息時,含有 `receive do` 的函式必須要在接到訊息後,遞迴呼 +# 叫自己以再次進入 `receive do` 區塊。 + +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 + +# 編譯模組,並在 shell 中創造一個行程來執行 `area_loop`。 +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# 更簡潔的替代寫法 +pid = spawn(Geometry, :area_loop, []) + +# 對 `pid` 傳送訊息,則會與接收區塊進行樣式比對。 +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# The shell is also a process, you can use `self` to get the current pid +# shell 也是一個行程 (process),你可以用 `self` 拿到目前的 pid +self() #=> #PID<0.27.0> +``` + +## 參考資料 + +* [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 |