From ff3b464026313e6ca2a11a9671c27c43b340da8f Mon Sep 17 00:00:00 2001
From: Elena Bolshakova
Date: Fri, 28 Nov 2014 11:36:41 +0300
Subject: [perl/ru] Russian translation for Perl 5
---
ru-ru/perl-ru.html.markdown | 169 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 169 insertions(+)
create mode 100644 ru-ru/perl-ru.html.markdown
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
new file mode 100644
index 00000000..9e9c7748
--- /dev/null
+++ b/ru-ru/perl-ru.html.markdown
@@ -0,0 +1,169 @@
+---
+category: language
+language: perl
+filename: learnperl-ru.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+translators:
+ - ["Elena Bolshakova", "http://github.com/liruoko"]
+lang: ru-ru
+---
+
+Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
+
+Perl 5 работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
+
+```perl
+# Комментарии начинаются с символа решетки.
+
+
+#### Типы переменных в Perl
+
+# Скалярные переменные начинаются с знака доллара $.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
+
+### В Perl три основных типа переменных: скаляры, массивы, хеши.
+
+## Скаляры
+# Скаляр хранит отдельное значение:
+my $animal = "camel";
+my $answer = 42;
+
+# Скаляры могут быть строками, целыми и вещественными числами.
+# Когда требуется, Perl автоматически выполняет преобразования к нужному типу.
+
+## Массивы
+# Массив хранит список значений:
+my @animals = ("camel", "llama", "owl");
+my @numbers = (23, 42, 69);
+my @mixed = ("camel", 42, 1.23);
+
+
+## Хеши
+# Хеш хранит набор пар ключ/значение:
+
+my %fruit_color = ("apple", "red", "banana", "yellow");
+
+# Можно использовать оператор "=>" для большей наглядности:
+
+my %fruit_color = (
+ apple => "red",
+ banana => "yellow",
+ );
+
+# Важно: вставка и поиск в хеше выполняются за константное время,
+# независимо от его размера.
+
+# Скаляры, массивы и хеши подробно описаны в разделе perldata
+# (perldoc perldata).
+
+# Более сложные структуры данных можно получить, если использовать ссылки.
+# С помощью ссылок можно получить массив массивов хешей, в которых хранятся другие хеши.
+
+#### Условные операторы и циклы
+
+# В Perl есть большинсво привычных условных и циклических конструкций.
+
+if ( $var ) {
+ ...
+} elsif ( $var eq 'bar' ) {
+ ...
+} else {
+ ...
+}
+
+unless ( condition ) {
+ ...
+ }
+# Это более читаемый вариант для "if (!condition)"
+
+# Специфические Perl-овые пост-условия:
+print "Yow!" if $zippy;
+print "We have no bananas" unless $bananas;
+
+# while
+ while ( condition ) {
+ ...
+ }
+
+
+# for, foreach
+for ($i = 0; $i <= $max; $i++) {
+ ...
+ }
+
+foreach (@array) {
+ print "This element is $_\n";
+ }
+
+for my $el (@array) {
+ print "This element is $el\n";
+ }
+
+#### Регулярные выражения
+
+# Регулярные выражения занимают важное место вPerl-е,
+# и подробно описаны в разделах документации perlrequick, perlretut и других.
+# Вкратце:
+
+# Сопоставление с образцом
+if (/foo/) { ... } # выполняется, если $_ содержит "foo"
+if ($a =~ /foo/) { ... } # выполняется, если $a содержит "foo"
+
+# Простые замены
+
+$a =~ s/foo/bar/; # заменяет foo на bar в строке $a
+$a =~ s/foo/bar/g; # заменяет ВСЕ ВХОЖДЕНИЯ foo на bar в строке $a
+
+
+#### Файлы и ввод-вывод
+
+# Открыть файл на чтение или запись можно с помощью функции "open()".
+
+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: $!";
+
+# Читать из файлового дескриптора можно с помощью оператора "<>".
+# В скалярном контексте он читает одру строку из файла, в списковом --
+# читает сразу весь файл, сохраняя по одной строке в элементе массива:
+
+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("We have a logger subroutine!");
+```
+
+#### Perl-модули
+
+Perl-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
+поставку Perl.
+
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
+задачах, и часто предлагает подходящие CPAN-модули.
+
+#### Смотрите также
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [обучающий раздел на www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc в вебе](http://perldoc.perl.org/)
+ - встроенная справка : `perldoc perlintro`
--
cgit v1.2.3
From 4196b7addd156b3b7f1621c0c0a1e38654897acf Mon Sep 17 00:00:00 2001
From: e99n09
Date: Sun, 8 Mar 2015 20:21:26 -0400
Subject: Create statcomppython
This is a tutorial on how to use Python for the stuff people normally do in R, MATLAB, or Stata. It's designed for someone comfortable with programming, basically familiar with Python, and experienced with a statistical programming language. Scraping the web, reading CSV files, summarizing columns, basic charts and plotting options, plus an extended data cleaning and exploratory data analysis example using a table of Holy Roman Emperors.
---
statcomppython | 234 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 234 insertions(+)
create mode 100644 statcomppython
diff --git a/statcomppython b/statcomppython
new file mode 100644
index 00000000..1f71bf6e
--- /dev/null
+++ b/statcomppython
@@ -0,0 +1,234 @@
+---
+language: Statistical computing with Python
+contributors:
+ - ["e99n09", "https://github.com/e99n09"]
+filename: statcomppython.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.
+
+```python
+
+# 0. Getting set up ====
+
+""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
+ matplotlib, seaborn, requests.
+ Make sure to do this tutorial in the IPython notebook so that you get
+ the inline plots and easy documentation lookup.
+"""
+
+# 1. Data acquisition ====
+
+""" One reason people choose Python over R is that they intend to interact a lot
+ with the web, either by scraping pages directly or requesting data through
+ an API. You can do those things in R, but in the context of a project
+ already using Python, there's a benefit to sticking with one language.
+"""
+
+import requests # for HTTP requests (web scraping, APIs)
+import os
+
+# web scraping
+r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
+r.status_code # if 200, request was successful
+r.text # raw page source
+print(r.text) # prettily formatted
+# save the page source in a file:
+os.getcwd() # check what's the working directory
+f = open("learnxinyminutes.html","wb")
+f.write(r.text.encode("UTF-8"))
+f.close()
+
+# downloading a 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()
+
+""" for more on the requests module, including APIs, see
+ http://docs.python-requests.org/en/latest/user/quickstart/
+"""
+
+# 2. Reading a CSV file ====
+
+""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If
+ you've used R, you will be familiar with the idea of the "data.frame" already.
+"""
+
+import pandas as pd, numpy as np, scipy as sp
+pets = pd.read_csv(fn)
+pets
+# name age weight species
+# 0 fluffy 3 14 cat
+# 1 vesuvius 6 23 fish
+# 2 rex 5 34 dog
+
+""" R users: note that Python, like most normal programming languages, starts
+ indexing from 0. R is the unusual one for starting from 1.
+"""
+
+# two different ways to print out a column
+pets.age
+pets["age"]
+
+pets.head(2) # prints first 2 rows
+pets.tail(1) # prints last row
+
+pets.name[1] # 'vesuvius'
+pets.species[0] # 'cat'
+pets["weight"][2] # 34
+
+# in R, you would expect to get 3 rows doing this, but here you get 2:
+pets.age[0:2]
+# 0 3
+# 1 6
+
+sum(pets.age)*2 # 28
+max(pets.weight) - min(pets.weight) # 20
+
+""" If you are doing some serious linear algebra and number-crunching, you may
+ just want arrays, not DataFrames. DataFrames are ideal for combining columns
+ of different types.
+"""
+
+# 3. Charts ====
+
+import matplotlib as mpl, matplotlib.pyplot as plt
+%matplotlib inline
+
+# To do data vizualization in Python, use matplotlib
+
+plt.hist(pets.age);
+
+plt.boxplot(pets.weight);
+
+plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+
+# seaborn sits atop matplotlib and makes plots prettier
+
+import seaborn as sns
+
+plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+
+# there are also some seaborn-specific plotting functions
+# notice how seaborn automatically labels the x-axis on this barplot
+sns.barplot(pets["age"])
+
+# R veterans can still use ggplot
+from ggplot import *
+ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
+# source: https://pypi.python.org/pypi/ggplot
+
+# there's even a d3.js port: https://github.com/mikedewar/d3py
+
+# 4. Simple data cleaning and exploratory analysis ====
+
+""" Here's a more complicated example that demonstrates a basic data
+ cleaning workflow leading to the creation of some exploratory plots
+ and the running of a linear regression.
+ The data set was transcribed from Wikipedia by hand. It contains
+ all the Holy Roman Emperors and the important milestones in their lives
+ (birth, death, coronation, etc.).
+ The goal of the analysis will be to explore whether a relationship
+ exists between emperor birth year and emperor lifespan.
+ data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
+"""
+
+# load some data on Holy Roman Emperors
+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
+"""
+
+# clean the Birth and Death columns
+
+import re # module for regular expressions
+
+rx = re.compile(r'\d+$') # match trailing digits
+
+""" This function applies the regular expression to an input column (here Birth,
+ Death), flattens the resulting list, converts it to a Series object, and
+ finally converts the type of the Series object from string to integer. For
+ more information into what different parts of the code do, see:
+ - 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)
+
+# make a column telling estimated age
+hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
+
+# simple scatterplot, no trend line, color represents dynasty
+sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False);
+
+# use scipy to run a linear regression
+from scipy import stats
+(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge)
+# code source: http://wiki.scipy.org/Cookbook/LinearRegression
+
+# check the slope
+slope # 0.0057672618839073328
+
+# check the R^2 value:
+rval**2 # 0.020363950027333586
+
+# check the p-value
+pval # 0.34971812581498452
+
+# use seaborn to make a scatterplot and plot the linear regression trend line
+sns.lmplot("BirthY", "EstAge", data=hre);
+
+""" For more information on seaborn, see
+ - http://web.stanford.edu/~mwaskom/software/seaborn/
+ - https://github.com/mwaskom/seaborn
+ For more information on SciPy, see
+ - http://wiki.scipy.org/SciPy
+ - http://wiki.scipy.org/Cookbook/
+ To see a version of the Holy Roman Emperors analysis using R, see
+ - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
+"""
+```
+
+If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial.
+
+You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers.
+
+Some more modules to research:
+ - text analysis and natural language processing: nltk, http://www.nltk.org
+ - social network analysis: igraph, http://igraph.org/python/
--
cgit v1.2.3
From e65582d459e5770d1a3ac3c5e5826dc10b546344 Mon Sep 17 00:00:00 2001
From: e99n09
Date: Sun, 8 Mar 2015 22:34:12 -0400
Subject: Update and rename statcomppython to pythonstatcomp.markdown.html
---
pythonstatcomp.markdown.html | 234 +++++++++++++++++++++++++++++++++++++++++++
statcomppython | 234 -------------------------------------------
2 files changed, 234 insertions(+), 234 deletions(-)
create mode 100644 pythonstatcomp.markdown.html
delete mode 100644 statcomppython
diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.markdown.html
new file mode 100644
index 00000000..78b62e33
--- /dev/null
+++ b/pythonstatcomp.markdown.html
@@ -0,0 +1,234 @@
+---
+language: 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.
+
+```python
+
+# 0. Getting set up ====
+
+""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
+ matplotlib, seaborn, requests.
+ Make sure to do this tutorial in the IPython notebook so that you get
+ the inline plots and easy documentation lookup.
+"""
+
+# 1. Data acquisition ====
+
+""" One reason people choose Python over R is that they intend to interact a lot
+ with the web, either by scraping pages directly or requesting data through
+ an API. You can do those things in R, but in the context of a project
+ already using Python, there's a benefit to sticking with one language.
+"""
+
+import requests # for HTTP requests (web scraping, APIs)
+import os
+
+# web scraping
+r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
+r.status_code # if 200, request was successful
+r.text # raw page source
+print(r.text) # prettily formatted
+# save the page source in a file:
+os.getcwd() # check what's the working directory
+f = open("learnxinyminutes.html","wb")
+f.write(r.text.encode("UTF-8"))
+f.close()
+
+# downloading a 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()
+
+""" for more on the requests module, including APIs, see
+ http://docs.python-requests.org/en/latest/user/quickstart/
+"""
+
+# 2. Reading a CSV file ====
+
+""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If
+ you've used R, you will be familiar with the idea of the "data.frame" already.
+"""
+
+import pandas as pd, numpy as np, scipy as sp
+pets = pd.read_csv(fn)
+pets
+# name age weight species
+# 0 fluffy 3 14 cat
+# 1 vesuvius 6 23 fish
+# 2 rex 5 34 dog
+
+""" R users: note that Python, like most normal programming languages, starts
+ indexing from 0. R is the unusual one for starting from 1.
+"""
+
+# two different ways to print out a column
+pets.age
+pets["age"]
+
+pets.head(2) # prints first 2 rows
+pets.tail(1) # prints last row
+
+pets.name[1] # 'vesuvius'
+pets.species[0] # 'cat'
+pets["weight"][2] # 34
+
+# in R, you would expect to get 3 rows doing this, but here you get 2:
+pets.age[0:2]
+# 0 3
+# 1 6
+
+sum(pets.age)*2 # 28
+max(pets.weight) - min(pets.weight) # 20
+
+""" If you are doing some serious linear algebra and number-crunching, you may
+ just want arrays, not DataFrames. DataFrames are ideal for combining columns
+ of different types.
+"""
+
+# 3. Charts ====
+
+import matplotlib as mpl, matplotlib.pyplot as plt
+%matplotlib inline
+
+# To do data vizualization in Python, use matplotlib
+
+plt.hist(pets.age);
+
+plt.boxplot(pets.weight);
+
+plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+
+# seaborn sits atop matplotlib and makes plots prettier
+
+import seaborn as sns
+
+plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
+
+# there are also some seaborn-specific plotting functions
+# notice how seaborn automatically labels the x-axis on this barplot
+sns.barplot(pets["age"])
+
+# R veterans can still use ggplot
+from ggplot import *
+ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
+# source: https://pypi.python.org/pypi/ggplot
+
+# there's even a d3.js port: https://github.com/mikedewar/d3py
+
+# 4. Simple data cleaning and exploratory analysis ====
+
+""" Here's a more complicated example that demonstrates a basic data
+ cleaning workflow leading to the creation of some exploratory plots
+ and the running of a linear regression.
+ The data set was transcribed from Wikipedia by hand. It contains
+ all the Holy Roman Emperors and the important milestones in their lives
+ (birth, death, coronation, etc.).
+ The goal of the analysis will be to explore whether a relationship
+ exists between emperor birth year and emperor lifespan.
+ data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
+"""
+
+# load some data on Holy Roman Emperors
+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
+"""
+
+# clean the Birth and Death columns
+
+import re # module for regular expressions
+
+rx = re.compile(r'\d+$') # match trailing digits
+
+""" This function applies the regular expression to an input column (here Birth,
+ Death), flattens the resulting list, converts it to a Series object, and
+ finally converts the type of the Series object from string to integer. For
+ more information into what different parts of the code do, see:
+ - 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)
+
+# make a column telling estimated age
+hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
+
+# simple scatterplot, no trend line, color represents dynasty
+sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False);
+
+# use scipy to run a linear regression
+from scipy import stats
+(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge)
+# code source: http://wiki.scipy.org/Cookbook/LinearRegression
+
+# check the slope
+slope # 0.0057672618839073328
+
+# check the R^2 value:
+rval**2 # 0.020363950027333586
+
+# check the p-value
+pval # 0.34971812581498452
+
+# use seaborn to make a scatterplot and plot the linear regression trend line
+sns.lmplot("BirthY", "EstAge", data=hre);
+
+""" For more information on seaborn, see
+ - http://web.stanford.edu/~mwaskom/software/seaborn/
+ - https://github.com/mwaskom/seaborn
+ For more information on SciPy, see
+ - http://wiki.scipy.org/SciPy
+ - http://wiki.scipy.org/Cookbook/
+ To see a version of the Holy Roman Emperors analysis using R, see
+ - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
+"""
+```
+
+If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial.
+
+You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers.
+
+Some more modules to research:
+ - text analysis and natural language processing: nltk, http://www.nltk.org
+ - social network analysis: igraph, http://igraph.org/python/
diff --git a/statcomppython b/statcomppython
deleted file mode 100644
index 1f71bf6e..00000000
--- a/statcomppython
+++ /dev/null
@@ -1,234 +0,0 @@
----
-language: Statistical computing with Python
-contributors:
- - ["e99n09", "https://github.com/e99n09"]
-filename: statcomppython.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.
-
-```python
-
-# 0. Getting set up ====
-
-""" Get set up with IPython and pip install the following: numpy, scipy, pandas,
- matplotlib, seaborn, requests.
- Make sure to do this tutorial in the IPython notebook so that you get
- the inline plots and easy documentation lookup.
-"""
-
-# 1. Data acquisition ====
-
-""" One reason people choose Python over R is that they intend to interact a lot
- with the web, either by scraping pages directly or requesting data through
- an API. You can do those things in R, but in the context of a project
- already using Python, there's a benefit to sticking with one language.
-"""
-
-import requests # for HTTP requests (web scraping, APIs)
-import os
-
-# web scraping
-r = requests.get("https://github.com/adambard/learnxinyminutes-docs")
-r.status_code # if 200, request was successful
-r.text # raw page source
-print(r.text) # prettily formatted
-# save the page source in a file:
-os.getcwd() # check what's the working directory
-f = open("learnxinyminutes.html","wb")
-f.write(r.text.encode("UTF-8"))
-f.close()
-
-# downloading a 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()
-
-""" for more on the requests module, including APIs, see
- http://docs.python-requests.org/en/latest/user/quickstart/
-"""
-
-# 2. Reading a CSV file ====
-
-""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If
- you've used R, you will be familiar with the idea of the "data.frame" already.
-"""
-
-import pandas as pd, numpy as np, scipy as sp
-pets = pd.read_csv(fn)
-pets
-# name age weight species
-# 0 fluffy 3 14 cat
-# 1 vesuvius 6 23 fish
-# 2 rex 5 34 dog
-
-""" R users: note that Python, like most normal programming languages, starts
- indexing from 0. R is the unusual one for starting from 1.
-"""
-
-# two different ways to print out a column
-pets.age
-pets["age"]
-
-pets.head(2) # prints first 2 rows
-pets.tail(1) # prints last row
-
-pets.name[1] # 'vesuvius'
-pets.species[0] # 'cat'
-pets["weight"][2] # 34
-
-# in R, you would expect to get 3 rows doing this, but here you get 2:
-pets.age[0:2]
-# 0 3
-# 1 6
-
-sum(pets.age)*2 # 28
-max(pets.weight) - min(pets.weight) # 20
-
-""" If you are doing some serious linear algebra and number-crunching, you may
- just want arrays, not DataFrames. DataFrames are ideal for combining columns
- of different types.
-"""
-
-# 3. Charts ====
-
-import matplotlib as mpl, matplotlib.pyplot as plt
-%matplotlib inline
-
-# To do data vizualization in Python, use matplotlib
-
-plt.hist(pets.age);
-
-plt.boxplot(pets.weight);
-
-plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
-
-# seaborn sits atop matplotlib and makes plots prettier
-
-import seaborn as sns
-
-plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight");
-
-# there are also some seaborn-specific plotting functions
-# notice how seaborn automatically labels the x-axis on this barplot
-sns.barplot(pets["age"])
-
-# R veterans can still use ggplot
-from ggplot import *
-ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets")
-# source: https://pypi.python.org/pypi/ggplot
-
-# there's even a d3.js port: https://github.com/mikedewar/d3py
-
-# 4. Simple data cleaning and exploratory analysis ====
-
-""" Here's a more complicated example that demonstrates a basic data
- cleaning workflow leading to the creation of some exploratory plots
- and the running of a linear regression.
- The data set was transcribed from Wikipedia by hand. It contains
- all the Holy Roman Emperors and the important milestones in their lives
- (birth, death, coronation, etc.).
- The goal of the analysis will be to explore whether a relationship
- exists between emperor birth year and emperor lifespan.
- data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor
-"""
-
-# load some data on Holy Roman Emperors
-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
-"""
-
-# clean the Birth and Death columns
-
-import re # module for regular expressions
-
-rx = re.compile(r'\d+$') # match trailing digits
-
-""" This function applies the regular expression to an input column (here Birth,
- Death), flattens the resulting list, converts it to a Series object, and
- finally converts the type of the Series object from string to integer. For
- more information into what different parts of the code do, see:
- - 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)
-
-# make a column telling estimated age
-hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int)
-
-# simple scatterplot, no trend line, color represents dynasty
-sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False);
-
-# use scipy to run a linear regression
-from scipy import stats
-(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge)
-# code source: http://wiki.scipy.org/Cookbook/LinearRegression
-
-# check the slope
-slope # 0.0057672618839073328
-
-# check the R^2 value:
-rval**2 # 0.020363950027333586
-
-# check the p-value
-pval # 0.34971812581498452
-
-# use seaborn to make a scatterplot and plot the linear regression trend line
-sns.lmplot("BirthY", "EstAge", data=hre);
-
-""" For more information on seaborn, see
- - http://web.stanford.edu/~mwaskom/software/seaborn/
- - https://github.com/mwaskom/seaborn
- For more information on SciPy, see
- - http://wiki.scipy.org/SciPy
- - http://wiki.scipy.org/Cookbook/
- To see a version of the Holy Roman Emperors analysis using R, see
- - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R
-"""
-```
-
-If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial.
-
-You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers.
-
-Some more modules to research:
- - text analysis and natural language processing: nltk, http://www.nltk.org
- - social network analysis: igraph, http://igraph.org/python/
--
cgit v1.2.3
From 01d17a3ea485c8b1d73145e1c2886fb3b2dde5b8 Mon Sep 17 00:00:00 2001
From: Geoff Liu
Date: Thu, 12 Mar 2015 12:56:58 -0600
Subject: First attempt at page text translation
---
template-translations.yaml | 15 +++++++++++++++
1 file changed, 15 insertions(+)
create mode 100644 template-translations.yaml
diff --git a/template-translations.yaml b/template-translations.yaml
new file mode 100644
index 00000000..15149fd5
--- /dev/null
+++ b/template-translations.yaml
@@ -0,0 +1,15 @@
+default:
+ title: Learn X in Y minutes
+ where: Where
+ codeLink: "Get the code:"
+ shareText: Share this page
+ suggestionsText: "Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!"
+ contributorText: "Originally contributed by %s, and updated by %d contributors"
+
+zh_CN:
+ title: Y分钟速成X
+ where: 当
+ codeLink: 源代码下载:
+ shareText: 分享此页
+ suggestionsText: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!"
+ contributorText: "原著%s,并由%d个好心人修改。"
--
cgit v1.2.3
From 74226d7153043c2e8dc7213b11d506ce4269a8a6 Mon Sep 17 00:00:00 2001
From: Geoff Liu
Date: Thu, 12 Mar 2015 13:00:13 -0600
Subject: minor naming change
---
template-translations.yaml | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/template-translations.yaml b/template-translations.yaml
index 15149fd5..019bed1a 100644
--- a/template-translations.yaml
+++ b/template-translations.yaml
@@ -1,15 +1,15 @@
default:
title: Learn X in Y minutes
where: Where
- codeLink: "Get the code:"
- shareText: Share this page
- suggestionsText: "Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!"
- contributorText: "Originally contributed by %s, and updated by %d contributors"
+ getCode: "Get the code:"
+ share: Share this page
+ suggestions: "Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!"
+ contributor: "Originally contributed by %s, and updated by %d contributors."
zh_CN:
title: Y分钟速成X
where: 当
- codeLink: 源代码下载:
- shareText: 分享此页
- suggestionsText: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!"
- contributorText: "原著%s,并由%d个好心人修改。"
+ getCode: 源代码下载:
+ share: 分享此页
+ suggestions: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!"
+ contributor: "原著%s,并由%d个好心人修改。"
--
cgit v1.2.3
From 4e8f60600f9f178c8f5cf80f56caef1fac73e0df Mon Sep 17 00:00:00 2001
From: Geoff Liu
Date: Thu, 12 Mar 2015 13:08:44 -0600
Subject: .
---
template-translations.yaml | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/template-translations.yaml b/template-translations.yaml
index 019bed1a..f7c02aea 100644
--- a/template-translations.yaml
+++ b/template-translations.yaml
@@ -1,14 +1,14 @@
default:
title: Learn X in Y minutes
- where: Where
+ where: Where X=
getCode: "Get the code:"
share: Share this page
suggestions: "Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!"
contributor: "Originally contributed by %s, and updated by %d contributors."
zh_CN:
- title: Y分钟速成X
- where: 当
+ title: X分钟速成Y
+ where: 当Y=
getCode: 源代码下载:
share: 分享此页
suggestions: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!"
--
cgit v1.2.3
From 61510ee92caaca9c841da6e40c8e1d680d1b7e34 Mon Sep 17 00:00:00 2001
From: Geoff Liu
Date: Sat, 28 Mar 2015 23:45:05 -0600
Subject: minor change
---
template-translations.yaml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/template-translations.yaml b/template-translations.yaml
index f7c02aea..527de122 100644
--- a/template-translations.yaml
+++ b/template-translations.yaml
@@ -8,7 +8,7 @@ default:
zh_CN:
title: X分钟速成Y
- where: 当Y=
+ where: 其中 Y=
getCode: 源代码下载:
share: 分享此页
suggestions: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!"
--
cgit v1.2.3
From a3818d119ea677e1992fa05d5ab130a012086a56 Mon Sep 17 00:00:00 2001
From: Chaitanya Krishna Ande
Date: Thu, 23 Apr 2015 13:54:52 +0200
Subject: initial version for latex
---
latex.html.markdown | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 133 insertions(+)
create mode 100644 latex.html.markdown
diff --git a/latex.html.markdown b/latex.html.markdown
new file mode 100644
index 00000000..cc1d99cb
--- /dev/null
+++ b/latex.html.markdown
@@ -0,0 +1,133 @@
+---
+language: latex
+contributors:
+ - ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+filename: learn-latex.tex
+---
+
+LaTeX is known to create aesthetically pleasing documents without you worrying
+about the formatting. It is also great if one wants to create documents
+containing a lot of mathematics. Getting a good document is very easy, but
+getting it to behave exactly the way you want can be a bit hairy.
+
+
+```latex
+% All comment lines start with %
+% There are no multi-line comments
+
+% LaTeX is NOT a ``What You See Is What You Get'' word processing software like
+% MS Word, or OpenOffice Writer
+
+% Getting to the final document using LaTeX consists of the following steps:
+% 1. Write the document in plain text
+% 2. Compile plain text document to produce a pdf
+% The compilation step looks something like this:
+% $ pdflatex your-tex-file.tex your-tex-file.pdf
+% A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
+% software. So, you get to see Step 1, but not Step 2 completely.
+% Step 2 is still happening behind the scenes.
+
+% You write all your formatting information in plain text in Step 1.
+% The compilation part in Step 2 takes care of producing the document in the
+% format you defined in Step 1.
+
+% For Step 1, it is best if you get a good text editor
+% On Windows, probably Notepad++
+% For Step 2, you will need to get a TeX distribution
+% Windows: MikTeX
+% MacOS: MacTeX
+% Linux: Should be available from your package manager
+
+% Let's get to the final pdf document as soon as possible
+
+% Choose the kind of document you want to write.
+% You can replace article with book, report, etc.
+\documentclass{article}
+% begin the document
+\begin{document}
+% end the document
+\end{document}
+% Compile to pdf
+% Now, you already have a final document which of course it is empty.
+% Everything that you write is between the
+% \begin{document}
+% \end{document}
+
+% Start a new document from here.
+% Let's do a decent document
+\documentclass{article}
+% required for inserting images
+\usepackage{graphicx}
+% begin the document
+\begin{document}
+% set the title (optional)
+\title{Title of the document}
+% set the author (optional)
+\author{Chaitanya Krishna Ande}
+
+% make the title (optional)
+\maketitle
+
+% start the first section
+\section{Introduction}
+
+% write your text
+This is the introduction.
+
+% start another section
+\section{Another section}
+This is the text for another section.
+
+% another section with subsection
+\section{Section with sub-section}
+Text for the section.
+\subsection{Sub-section}
+Let's discuss the Pythagoras theorem.
+\subsubsection{Pythagoras Theorm}
+% for cross-reference
+\label{subsec:pythagoras}
+
+% notice how the sections and sub-sections are automatically numbered
+
+% Some math
+% Inline math within $ $
+For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, $b$ and $c$, where $c$ is the
+hypotenuse, the following holds:
+% Display math with the equation 'environment'
+\begin{equation}
+ c^2 = a^2 + b^2.
+ % for cross-reference
+ \label{eq:pythagoras}
+\end{equation}
+
+% Let's cross-reference the equation
+Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
+the subject of Sec.~\ref{subsec:pythagoras}.
+
+\subsubsection{Figure}
+Let's insert a Figure.
+
+\begin{figure}
+ \centering
+ \includegraphics[width=0.8\linewidth]{right-triangle.png}
+ \caption{Right triangle with sides a, b, c}
+ \label{fig:right-triangle}
+\end{figure}
+
+
+\subsubsection{Table}
+Let's insert a Table.
+
+\begin{table}
+\caption{Caption for the Table.}
+\begin{tabular}{ccc}
+Number & Last Name & First Name \\
+\hline
+1 & Biggus & Dickus \\
+2 & Monty & Python
+\end{tabular}
+\end{table}
+
+% end the document
+\end{document}
+```
--
cgit v1.2.3
From be761f49ef2b99302e8f1d86c4a7d9e3e0b8cbe4 Mon Sep 17 00:00:00 2001
From: Jack Union
Date: Sun, 7 Jun 2015 12:03:50 +0300
Subject: css/ru translation
---
ru-ru/css-ru.html.markdown | 250 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 250 insertions(+)
create mode 100644 ru-ru/css-ru.html.markdown
diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown
new file mode 100644
index 00000000..2e2d40b7
--- /dev/null
+++ b/ru-ru/css-ru.html.markdown
@@ -0,0 +1,250 @@
+---
+language: css
+contributors:
+ - ["Mohammad Valipour", "https://github.com/mvalipour"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
+filename: learncss-ru.css
+lang: ru-ru
+---
+
+В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров
+веб-страницы с графическими элементами стали обычным делом.
+CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц.
+
+Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные
+HTML элементы и определять их внешний вид.
+
+Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую,
+но самую поддерживаемую и распространенную версию.
+
+**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида
+элементов, постарайтесь использовать CSS-песочницы при изучении языка.
+Например [dabblet](http://dabblet.com/).
+В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации.
+
+
+```css
+/* Для комментариев используется слеш-астериск, как на этой строчке.
+ В CSS нет однострочных комментариев; все комментарии записываются таким способом */
+
+/* ####################
+ ## СЕЛЕКТОРЫ
+ #################### */
+
+/* Выражения в CSS очень просты */
+селектор { атрибут: значение; /* другие атрибуты...*/ }
+
+/* селекторы используются для выбора элементов на странице
+
+Чтобы выбрать все элементы, используйте астериск: */
+* { color:red; }
+
+/*
+Если на странице присутствует такой элемент:
+
+
+*/
+
+/* его можно выбрать по одному классу */
+.some-class { }
+
+/* или по обоим классам */
+.some-class.class2 { }
+
+/* по названию тега */
+div { }
+
+/* по идентификатору */
+#someId { }
+
+/* по имеющемуся атрибуту */
+[attr] { font-size:smaller; }
+
+/* или по атрибуту с определенным значением */
+[attr='value'] { font-size:smaller; }
+
+/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */
+[attr^='val'] { font-size:smaller; }
+
+/* или заканчивающиеся определенным значением (CSS3) */
+[attr$='ue'] { font-size:smaller; }
+
+/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */
+[otherAttr~='foo'] { font-size:smaller; }
+
+/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */
+[otherAttr|='en'] { font-size:smaller; }
+
+
+/* Более того, все это можно использовать вместе - между разными частями
+не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */
+div.some-class[attr$='ue'] { }
+
+/* Вы можете выбрать элемент по его родителю */
+
+/* прямой потомок другого элемента (выбранного с помощью селектора) */
+div.some-parent > .class-name {}
+
+/* потомок любого родителя в дереве элементов
+ следующая строка означает: "любой элемент класса "class-name",
+ являющийся потомком div-элемента класса "some-parent"
+ НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */
+div.some-parent .class-name {}
+
+/* важно: этот же селектор без пробелов имеет иное значение
+ можете догадаться, какое? */
+div.some-parent.class-name {}
+
+/* вы можете выбрать элемент по первому предшествующему
+ родственному элементу */
+.i-am-before + .this-element { }
+
+/* или любому предшествующему родственнику перед элементом */
+.i-am-any-before ~ .this-element {}
+
+
+/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента
+ в зависимости от событий, произошедших с элементом */
+
+/* например, когда курсор наведен на элемент */
+element:hover {}
+
+/* когда пользователь проходил по ссылке ранее */
+element:visited {}
+
+/* или еще не проходил по ней */
+element:link {}
+
+/* выбранное поле воода (input) */
+element:focus {}
+
+
+/* ####################
+ ## АТРИБУТЫ
+ #################### */
+
+selector {
+
+ /* Единицы измерения */
+ width: 50%; /* проценты */
+ font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */
+ width: 200px; /* пиксели */
+ font-size: 20pt; /* пункты */
+ width: 5cm; /* сантиметры */
+ min-width: 50mm; /* милиметры */
+ max-width: 5in; /* дюймы */
+ height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */
+ width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */
+ min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */
+ max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */
+
+ /* Цвета */
+ background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */
+ background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */
+ background-color: tomato; /* название цвета */
+ background-color: rgb(255, 255, 255); /* цветовая модель rgb */
+ background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */
+ background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */
+ background-color: transparent; /* прозрачный цвет */
+ background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */
+ background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (CSS3) */
+
+
+ /* Изображения */
+ background-image: url(/path-to-image/image.jpg); /* кавычки внутри url() опциональны */
+
+ /* Шрифты */
+ font-family: Arial;
+ font-family: "Courier New"; /* если в названии есть пробелы, заключите его в кавычки */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif; /* если шрифт не найден,
+ будет использован следующий за ним в списке */
+}
+
+```
+
+## Использование
+
+Сохраните готовый файл с расширением .css
+
+```xml
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+## Приоритет
+
+Как вы заметили, внешний вид элемента может определяться несколькими селекторами,
+а значение атрибута элемента может быть установлено больше одного раза.
+В подобных случаях одно из значений оказывается приоритетнее остальных.
+
+Если взять следующую таблицу стилей:
+
+```css
+/*A*/
+p.class1[attr='value']
+
+/*B*/
+p.class1 {}
+
+/*C*/
+p.class2 {}
+
+/*D*/
+p {}
+
+/*E*/
+p { property: value !important; }
+
+```
+
+и следующую разметку:
+
+```xml
+
+
+```
+
+Приоритет стилей будет таким:
+Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей.
+
+* `E` имеет наивысший приоритет благодаря ключевому слову `!important`.
+ Используйте только в случае крайней необходимости.
+* `F` идет следующим, так как является встроенным стилем.
+* `A` следующий, как самый конкретизированный.
+ конкретизированный == большее количество определителей.
+ В этом примере 3 определителя: 1 тег `p` +
+ название класса `class1` + 1 атрибут `attr='value'`
+* `C` следующий. Несмотря на одинаковое с `B` количество определителей,
+ `C` определен позже.
+* Затем `B`
+* И последний `D`.
+
+## Совместимость
+
+Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми
+браузерами и устройствами, не забывайте проверять совместимость CSS-правил
+с современными браузерами.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого.
+
+To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+
+## Ресурсы для самостоятельного изучения
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
--
cgit v1.2.3
From 30cff7bcefd708638e99c7a9917ca2534fb38fd5 Mon Sep 17 00:00:00 2001
From: Elena Bolshakova
Date: Wed, 10 Jun 2015 11:00:00 +0300
Subject: typo
---
ru-ru/perl-ru.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
index 9e9c7748..e9ba6ff8 100644
--- a/ru-ru/perl-ru.html.markdown
+++ b/ru-ru/perl-ru.html.markdown
@@ -106,7 +106,7 @@ for my $el (@array) {
#### Регулярные выражения
-# Регулярные выражения занимают важное место вPerl-е,
+# Регулярные выражения занимают важное место в Perl-е,
# и подробно описаны в разделах документации perlrequick, perlretut и других.
# Вкратце:
--
cgit v1.2.3
From 676568cca8731d0dbb2d2bdeff08cc092d283177 Mon Sep 17 00:00:00 2001
From: Elena Bolshakova
Date: Wed, 10 Jun 2015 11:27:02 +0300
Subject: [perl/ru]: basic info on Unicode support; use strict; use warnings;
---
ru-ru/perl-ru.html.markdown | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
index e9ba6ff8..0e68116c 100644
--- a/ru-ru/perl-ru.html.markdown
+++ b/ru-ru/perl-ru.html.markdown
@@ -161,6 +161,32 @@ Perl-овые модули предоставляют широкий набор
Раздел документации perlfaq содержит вопросы и ответы о многих частых
задачах, и часто предлагает подходящие CPAN-модули.
+
+#### Unicode
+
+Вам наверняка понадобится работать с не-ASCII текстами.
+Добавьте эти прагмы в начало скрипта:
+
+```perl
+use utf8;
+use open ':std' => ':utf8';
+```
+
+Подробнее читайте в perldoc, разделы perlunicode и open.
+
+
+#### strict, warnings
+
+Прагмы strict и warnings включают полезные проверки во время компиляции:
+
+```perl
+use strict;
+use warnings;
+```
+
+Подробнее смотрите perldoc strict и perldoc warnings.
+
+
#### Смотрите также
- [perl-tutorial](http://perl-tutorial.org/)
--
cgit v1.2.3
From 938720074b8b18a9ada93fb8a040b9ca1a813747 Mon Sep 17 00:00:00 2001
From: Ian Bertolacci
Date: Mon, 17 Aug 2015 14:19:41 -0700
Subject: Update to Chapel
A reader/writer sync example was missing a "Reader: " notem
---
chapel.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index c8489371..8a88a652 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -960,7 +960,7 @@ proc main(){
begin { // Reader task
writeln( "Reader: waiting to read." );
var read_sync = someSyncVar$;
- writeln( "value is ", read_sync );
+ writeln( "Reader: value is ", read_sync );
}
begin { // Writer task
@@ -1100,4 +1100,4 @@ Notable arguments:
* `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable.
* `--set =`: set config param `` to `` at compile-time.
* `--main-module `: use the main() procedure found in the module `` as the executable's main.
- * `--module-dir `: includes `` in the module search path.
\ No newline at end of file
+ * `--module-dir `: includes `` in the module search path.
--
cgit v1.2.3
From a9febbeb223269f4cfa88287aeb13b0688537504 Mon Sep 17 00:00:00 2001
From: JustBlah
Date: Thu, 24 Sep 2015 17:11:45 +0300
Subject: +Translation, *Russian auto-translate text fixed
+ Added more English to Russian translation
* Auto translated Russian text changed to have more sense and readability
---
ru-ru/objective-c-ru.html.markdown | 26 +++++++++++++-------------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index ddff2e5c..7209b3bb 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -381,20 +381,20 @@ if ([myClass respondsToSelector:selectorVar]) { // Проверяет содер
NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar));
}
-// Имплементируйте методы в файле МойКласс.m:
+// Имплементируйте методы в файле MyClass.m:
@implementation MyClass {
long distance; // Переменная экземпляра с закрытым (private) доступом
NSNumber height;
}
-// To access a public variable from the interface file, use '_' followed by variable name:
-_count = 5; // References "int count" from MyClass interface
-// Access variables defined in implementation file:
-distance = 18; // References "long distance" from MyClass implementation
-// To use @property variable in implementation, use @synthesize to create accessor variable:
-@synthesize roString = _roString; // _roString available now in @implementation
+// Для доступа к public переменной, объявленной в интерфейсе используйте '_' перед названием переменной:
+_count = 5; // Ссылается на "int count" из интерфейса MyClass
+// Получение доступа к переменной, объявленной в имлементации происходит следующим образом:
+distance = 18; // Ссылается на "long distance" из имлементации MyClass
+// Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property, следует использовать @synthesize для создания переменной аксессора:
+@synthesize roString = _roString; // Теперь _roString доступна в @implementation (имплементации интерфейса)
-// Called before calling any class methods or instantiating any objects
+// Вызывается в первую очередь, перед вызовом других медотов класса или инициализации других объектов
+ (void)initialize
{
if (self == [MyClass class]) {
@@ -505,10 +505,10 @@ distance = 18; // References "long distance" from MyClass implementation
@end
-// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет
-// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить
-// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим
-// категорию для добавления его очистительных методов:
+// Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что
+// изменит функционал Car и позволит вести себя подобно грузовику. Но что если мы хотим только добавить
+// определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим
+// категорию, которая добавит несколько методов для чистки автомобиля в класс Car:
// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h)
#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения.
@@ -794,7 +794,7 @@ MyClass *arcMyClass = [[MyClass alloc] init];
// weakVar-свойство автоматически примет значение nil,
// во избежание падения приложения
@property (strong) MyClass *strongVar; // 'strong' принимает право на владение
-// объектом. Гарантирует, что объект останится в памяти для использования
+// объектом. Гарантирует, что объект останется в памяти для использования
// Для обычных переменных (не объявленных с помощью @property), используйте
// следующий способ:
--
cgit v1.2.3
From 652285e9dfe2df2dbbc61b49abdc0ca22bf435f6 Mon Sep 17 00:00:00 2001
From: JustBlah
Date: Thu, 24 Sep 2015 17:23:49 +0300
Subject: Multiline commentary split
Long commentary was split into two strings
---
ru-ru/objective-c-ru.html.markdown | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 7209b3bb..bebd36d3 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -391,7 +391,8 @@ if ([myClass respondsToSelector:selectorVar]) { // Проверяет содер
_count = 5; // Ссылается на "int count" из интерфейса MyClass
// Получение доступа к переменной, объявленной в имлементации происходит следующим образом:
distance = 18; // Ссылается на "long distance" из имлементации MyClass
-// Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property, следует использовать @synthesize для создания переменной аксессора:
+// Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property,
+// следует использовать @synthesize для создания переменной аксессора:
@synthesize roString = _roString; // Теперь _roString доступна в @implementation (имплементации интерфейса)
// Вызывается в первую очередь, перед вызовом других медотов класса или инициализации других объектов
--
cgit v1.2.3
From 5282918d9959ba5f02f952bff500f205db9f6dd5 Mon Sep 17 00:00:00 2001
From: Taff
Date: Tue, 29 Sep 2015 01:31:50 +0800
Subject: fix error
---
zh-cn/haskell-cn.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index 8904970f..b0b1183f 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -200,13 +200,13 @@ foo 5 -- 75
-- 你可以使用 `$` 来移除多余的括号。
-- 修改前
-(even (fib 7)) -- true
+(even (fib 7)) -- False
-- 修改后
-even . fib $ 7 -- true
+even . fib $ 7 -- False
-- 等价地
-even $ fib 7 -- true
+even $ fib 7 -- False
----------------------------------------------------
-- 5. 类型声明
--
cgit v1.2.3
From 510eeb7684748afc83eb14e27d95a6b6c65deff4 Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Wed, 30 Sep 2015 22:40:46 -0300
Subject: [javascript pt-br] : first part
---
pt-br/javascript-pt.html.markdown | 533 ++++++++++++++++++++++++++++++++++++++
1 file changed, 533 insertions(+)
create mode 100644 pt-br/javascript-pt.html.markdown
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
new file mode 100644
index 00000000..c4115b3e
--- /dev/null
+++ b/pt-br/javascript-pt.html.markdown
@@ -0,0 +1,533 @@
+---
+language: javascript
+contributors:
+ - ["Adam Brenecki", "http://adam.brenecki.id.au"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+filename: javascript.js
+---
+
+JavaScript foi criada por Brendan Eich, funcionário da Netscape, em 1995. Ela
+foi originalmente criada para ser uma linguagem de script para websites,
+complementando o uso de Java para aplicações web mais complexas, mas a sua
+integração com páginas web e seu suporte nativo nos browsers fez com que
+ela se tornasse mais comum que Java no frontend web.
+
+Javascript não é somente limitado a browsers web, no entanto: existe o Node.js,
+que é um projeto que fornece um interpretador baseado no motor V8 do Google
+Chrome e está se tornando cada vez mais famoso.
+
+
+Feedback são muito apreciados! Você me encontrar em
+[@adambrenecki](https://twitter.com/adambrenecki), ou
+[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
+
+```js
+// Comentários são como em C. Comentários de uma linha começam com duas barras,
+/* e comentários de múltplas linhas começam com barra-asterisco
+ e fecham com asterisco-barra */
+
+// comandos podem ser terminados com ;
+facaAlgo();
+
+// ... mas eles não precisam ser, assim como o ponto-e-vírgula é automaticamente
+// inserido quando há uma nova linha, exceto alguns casos.
+facaAlgo()
+
+// Porque esses casos podem causar resultados inesperados, vamos continuar
+// a usar ponto-e-vírgula neste guia.
+
+///////////////////////////////////
+// 1. Numbers, Strings and Operators
+
+// JavaScript has one number type (which is a 64-bit IEEE 754 double).
+// Doubles have a 52-bit mantissa, which is enough to store integers
+// up to about 9✕10¹⁵ precisely.
+3; // = 3
+1.5; // = 1.5
+
+// Some basic arithmetic works as you'd expect.
+1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Including uneven division.
+5 / 2; // = 2.5
+
+// Bitwise operations also work; when you perform a bitwise operation your float
+// is converted to a signed int *up to* 32 bits.
+1 << 2; // = 4
+
+// Precedence is enforced with parentheses.
+(1 + 3) * 2; // = 8
+
+// There are three special not-a-real-number values:
+Infinity; // result of e.g. 1/0
+-Infinity; // result of e.g. -1/0
+NaN; // result of e.g. 0/0
+
+// There's also a boolean type.
+true;
+false;
+
+// Strings are created with ' or ".
+'abc';
+"Hello, world";
+
+// Negation uses the ! symbol
+!true; // = false
+!false; // = true
+
+// Equality is ===
+1 === 1; // = true
+2 === 1; // = false
+
+// Inequality is !==
+1 !== 1; // = false
+2 !== 1; // = true
+
+// More comparisons
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Strings are concatenated with +
+"Hello " + "world!"; // = "Hello world!"
+
+// and are compared with < and >
+"a" < "b"; // = true
+
+// Type coercion is performed for comparisons with double equals...
+"5" == 5; // = true
+null == undefined; // = true
+
+// ...unless you use ===
+"5" === 5; // = false
+null === undefined; // = false
+
+// ...which can result in some weird behaviour...
+13 + !0; // 14
+"13" + !0; // '13true'
+
+// You can access characters in a string with `charAt`
+"This is a string".charAt(0); // = 'T'
+
+// ...or use `substring` to get larger pieces.
+"Hello world".substring(0, 5); // = "Hello"
+
+// `length` is a property, so don't use ().
+"Hello".length; // = 5
+
+// There's also `null` and `undefined`.
+null; // used to indicate a deliberate non-value
+undefined; // used to indicate a value is not currently present (although
+ // `undefined` is actually a value itself)
+
+// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.
+// Note that 0 is falsy and "0" is truthy, even though 0 == "0".
+
+///////////////////////////////////
+// 2. Variables, Arrays and Objects
+
+// Variables are declared with the `var` keyword. JavaScript is dynamically
+// typed, so you don't need to specify type. Assignment uses a single `=`
+// character.
+var someVar = 5;
+
+// if you leave the var keyword off, you won't get an error...
+someOtherVar = 10;
+
+// ...but your variable will be created in the global scope, not in the scope
+// you defined it in.
+
+// Variables declared without being assigned to are set to undefined.
+var someThirdVar; // = undefined
+
+// There's shorthand for performing math operations on variables:
+someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
+someVar *= 10; // now someVar is 100
+
+// and an even-shorter-hand for adding or subtracting 1
+someVar++; // now someVar is 101
+someVar--; // back to 100
+
+// Arrays are ordered lists of values, of any type.
+var myArray = ["Hello", 45, true];
+
+// Their members can be accessed using the square-brackets subscript syntax.
+// Array indices start at zero.
+myArray[1]; // = 45
+
+// Arrays are mutable and of variable length.
+myArray.push("World");
+myArray.length; // = 4
+
+// Add/Modify at specific index
+myArray[3] = "Hello";
+
+// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
+// languages: an unordered collection of key-value pairs.
+var myObj = {key1: "Hello", key2: "World"};
+
+// Keys are strings, but quotes aren't required if they're a valid
+// JavaScript identifier. Values can be any type.
+var myObj = {myKey: "myValue", "my other key": 4};
+
+// Object attributes can also be accessed using the subscript syntax,
+myObj["my other key"]; // = 4
+
+// ... or using the dot syntax, provided the key is a valid identifier.
+myObj.myKey; // = "myValue"
+
+// Objects are mutable; values can be changed and new keys added.
+myObj.myThirdKey = true;
+
+// If you try to access a value that's not yet set, you'll get undefined.
+myObj.myFourthKey; // = undefined
+
+///////////////////////////////////
+// 3. Logic and Control Structures
+
+// The syntax for this section is almost identical to Java's.
+
+// The `if` structure works as you'd expect.
+var count = 1;
+if (count == 3){
+ // evaluated if count is 3
+} else if (count == 4){
+ // evaluated if count is 4
+} else {
+ // evaluated if it's not either 3 or 4
+}
+
+// As does `while`.
+while (true){
+ // An infinite loop!
+}
+
+// Do-while loops are like while loops, except they always run at least once.
+var input;
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// The `for` loop is the same as C and Java:
+// initialisation; continue condition; iteration.
+for (var i = 0; i < 5; i++){
+ // will run 5 times
+}
+
+// && is logical and, || is logical or
+if (house.size == "big" && house.colour == "blue"){
+ house.contains = "bear";
+}
+if (colour == "red" || colour == "blue"){
+ // colour is either red or blue
+}
+
+// && and || "short circuit", which is useful for setting default values.
+var name = otherName || "default";
+
+
+// The `switch` statement checks for equality with `===`.
+// use 'break' after each case
+// or the cases after the correct one will be executed too.
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log("Great job");
+ break;
+ case 'B':
+ console.log("OK job");
+ break;
+ case 'C':
+ console.log("You can do better");
+ break;
+ default:
+ console.log("Oy vey");
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Functions, Scope and Closures
+
+// JavaScript functions are declared with the `function` keyword.
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction("foo"); // = "FOO"
+
+// Note that the value to be returned must start on the same line as the
+// `return` keyword, otherwise you'll always return `undefined` due to
+// automatic semicolon insertion. Watch out for this when using Allman style.
+function myFunction()
+{
+ return // <- semicolon automatically inserted here
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
+// JavaScript functions are first class objects, so they can be reassigned to
+// different variable names and passed to other functions as arguments - for
+// example, when supplying an event handler:
+function myFunction(){
+ // this code will be called in 5 seconds' time
+}
+setTimeout(myFunction, 5000);
+// Note: setTimeout isn't part of the JS language, but is provided by browsers
+// and Node.js.
+
+// Function objects don't even have to be declared with a name - you can write
+// an anonymous function definition directly into the arguments of another.
+setTimeout(function(){
+ // this code will be called in 5 seconds' time
+}, 5000);
+
+// JavaScript has function scope; functions get their own scope but other blocks
+// do not.
+if (true){
+ var i = 5;
+}
+i; // = 5 - not undefined as you'd expect in a block-scoped language
+
+// This has led to a common pattern of "immediately-executing anonymous
+// functions", which prevent temporary variables from leaking into the global
+// scope.
+(function(){
+ var temporary = 5;
+ // We can access the global scope by assiging to the "global object", which
+ // in a web browser is always `window`. The global object may have a
+ // different name in non-browser environments such as Node.js.
+ window.permanent = 10;
+})();
+temporary; // raises ReferenceError
+permanent; // = 10
+
+// One of JavaScript's most powerful features is closures. If a function is
+// defined inside another function, the inner function has access to all the
+// outer function's variables, even after the outer function exits.
+function sayHelloInFiveSeconds(name){
+ var prompt = "Hello, " + name + "!";
+ // Inner functions are put in the local scope by default, as if they were
+ // declared with `var`.
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
+ // exit immediately, and setTimeout will call inner afterwards. However,
+ // because inner is "closed over" sayHelloInFiveSeconds, inner still has
+ // access to the `prompt` variable when it is finally called.
+}
+sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
+
+///////////////////////////////////
+// 5. More about Objects; Constructors and Prototypes
+
+// Objects can contain functions.
+var myObj = {
+ myFunc: function(){
+ return "Hello world!";
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// When functions attached to an object are called, they can access the object
+// they're attached to using the `this` keyword.
+myObj = {
+ myString: "Hello world!",
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = "Hello world!"
+
+// What this is set to has to do with how the function is called, not where
+// it's defined. So, our function doesn't work if it isn't called in the
+// context of the object.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// Inversely, a function can be assigned to the object and gain access to it
+// through `this`, even if it wasn't attached when it was defined.
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = "HELLO WORLD!"
+
+// We can also specify a context for a function to execute in when we invoke it
+// using `call` or `apply`.
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// The `apply` function is nearly identical, but takes an array for an argument
+// list.
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// This is useful when working with a function that accepts a sequence of
+// arguments and you want to pass an array.
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// But, `call` and `apply` are only temporary. When we want it to stick, we can
+// use `bind`.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// `bind` can also be used to partially apply (curry) a function.
+
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// When you call a function with the `new` keyword, a new object is created, and
+// made available to the function via the this keyword. Functions designed to be
+// called like that are called constructors.
+
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Every JavaScript object has a 'prototype'. When you go to access a property
+// on an object that doesn't exist on the actual object, the interpreter will
+// look at its prototype.
+
+// Some JS implementations let you access an object's prototype on the magic
+// property `__proto__`. While this is useful for explaining prototypes it's not
+// part of the standard; we'll get to standard ways of using prototypes later.
+var myObj = {
+ myString: "Hello world!"
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+
+// This works for functions, too.
+myObj.myFunc(); // = "hello world!"
+
+// Of course, if your property isn't on your prototype, the prototype's
+// prototype is searched, and so on.
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+// There's no copying involved here; each object stores a reference to its
+// prototype. This means we can alter the prototype and our changes will be
+// reflected everywhere.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// We mentioned that `__proto__` was non-standard, and there's no standard way to
+// change the prototype of an existing object. However, there are two ways to
+// create a new object with a given prototype.
+
+// The first is Object.create, which is a recent addition to JS, and therefore
+// not available in all implementations yet.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// The second way, which works anywhere, has to do with constructors.
+// Constructors have a property called prototype. This is *not* the prototype of
+// the constructor function itself; instead, it's the prototype that new objects
+// are given when they're created with that constructor and the new keyword.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Built-in types like strings and numbers also have constructors that create
+// equivalent wrapper objects.
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// Except, they aren't exactly equivalent.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // This code won't execute, because 0 is falsy.
+}
+if (Number(0)){
+ // This code *will* execute, because Number(0) is truthy.
+}
+
+// However, the wrapper objects and the regular builtins share a prototype, so
+// you can actually add functionality to a string, for instance.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+"abc".firstCharacter(); // = "a"
+
+// This fact is often used in "polyfilling", which is implementing newer
+// features of JavaScript in an older subset of JavaScript, so that they can be
+// used in older environments such as outdated browsers.
+
+// For instance, we mentioned that Object.create isn't yet available in all
+// implementations, but we can still use it with this polyfill:
+if (Object.create === undefined){ // don't overwrite it if it exists
+ Object.create = function(proto){
+ // make a temporary constructor with the right prototype
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // then use it to create a new, appropriately-prototyped object
+ return new Constructor();
+ }
+}
+```
+
+## Further Reading
+
+The [Mozilla Developer
+Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
+excellent documentation for JavaScript as it's used in browsers. Plus, it's a
+wiki, so as you learn more you can help others out by sharing your own
+knowledge.
+
+MDN's [A re-introduction to
+JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+covers much of the concepts covered here in more detail. This guide has quite
+deliberately only covered the JavaScript language itself; if you want to learn
+more about how to use JavaScript in web pages, start by learning about the
+[Document Object
+Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
+
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
+
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
+guide of all the counter-intuitive parts of the language.
+
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
+
+In addition to direct contributors to this article, some content is adapted
+from Louie Dinh's Python tutorial on this site, and the [JS
+Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+on the Mozilla Developer Network.
--
cgit v1.2.3
From ed2bc5a84c4dfc1af45c05ea8b1a20122ac72620 Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Thu, 1 Oct 2015 22:23:18 -0300
Subject: =?UTF-8?q?[javascript=20pt-br]=20:=201.=20N=C3=BAmeros,=20Strings?=
=?UTF-8?q?=20e=20Operadores?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
pt-br/javascript-pt.html.markdown | 75 ++++++++++++++++++++-------------------
1 file changed, 39 insertions(+), 36 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index c4115b3e..72f4cf0f 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -37,96 +37,99 @@ facaAlgo()
// a usar ponto-e-vírgula neste guia.
///////////////////////////////////
-// 1. Numbers, Strings and Operators
+// 1. Números, Strings e Operadores
-// JavaScript has one number type (which is a 64-bit IEEE 754 double).
-// Doubles have a 52-bit mantissa, which is enough to store integers
-// up to about 9✕10¹⁵ precisely.
+// Javascript tem um tipo de número (que é o 64-bit IEEE 754 double).
+// Doublas tem uma mantissa 52-bit, que é suficiente para guardar inteiros
+// acima de 9✕10¹⁵ precisamente.
3; // = 3
1.5; // = 1.5
-// Some basic arithmetic works as you'd expect.
+// A aritmética básica funciona seria de esperar.
1 + 1; // = 2
0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
-// Including uneven division.
+// Inclusive divisão desigual.
5 / 2; // = 2.5
-// Bitwise operations also work; when you perform a bitwise operation your float
-// is converted to a signed int *up to* 32 bits.
+// Operadores Bitwise também funcionam; quando você faz uma operação bitwise
+// seu float é convertido para um int de até 32 bits.
1 << 2; // = 4
-// Precedence is enforced with parentheses.
+// A precedência é aplicada com parênteses.
(1 + 3) * 2; // = 8
// There are three special not-a-real-number values:
-Infinity; // result of e.g. 1/0
--Infinity; // result of e.g. -1/0
-NaN; // result of e.g. 0/0
+// Existem três especiais valores não-é-número-real:
+Infinity; // resultado de 1/0
+-Infinity; // resultado de -1/0
+NaN; // resultado de 0/0
-// There's also a boolean type.
+// Existe também o tipo booleano.
true;
false;
-// Strings are created with ' or ".
+// Strings são criados com ' ou ".
'abc';
-"Hello, world";
+"Olá, mundo";
// Negation uses the ! symbol
+// Negação usa o símbolo !
!true; // = false
!false; // = true
-// Equality is ===
+// Igualdade é ===
1 === 1; // = true
2 === 1; // = false
-// Inequality is !==
+// Desigualdade é !==
1 !== 1; // = false
2 !== 1; // = true
-// More comparisons
+// Mais comparações
1 < 10; // = true
1 > 10; // = false
2 <= 2; // = true
2 >= 2; // = true
-// Strings are concatenated with +
-"Hello " + "world!"; // = "Hello world!"
+// Strings são concatenadas com +
+"Olá " + "mundo!"; // = "Olá mundo!"
-// and are compared with < and >
+// e comparadas com < e >
"a" < "b"; // = true
-// Type coercion is performed for comparisons with double equals...
+// A coerção de tipos é feita para comparações com dois iguais...
"5" == 5; // = true
null == undefined; // = true
-// ...unless you use ===
+// ...a menos que use ===
"5" === 5; // = false
null === undefined; // = false
-// ...which can result in some weird behaviour...
+// ...que irá resultar num comportamento estranho...
13 + !0; // 14
"13" + !0; // '13true'
-// You can access characters in a string with `charAt`
-"This is a string".charAt(0); // = 'T'
+// Você pode acessar caracteres de uma String usando o `charAt`
+"Isto é uma String".charAt(0); // = 'I'
-// ...or use `substring` to get larger pieces.
-"Hello world".substring(0, 5); // = "Hello"
+// ...ou usar `substring` para pegar pedaços maiores.
+"Olá mundo".substring(0, 3); // = "Olá"
-// `length` is a property, so don't use ().
-"Hello".length; // = 5
+// `length` é uma propriedade, portanto não use ().
+"Olá".length; // = 3
-// There's also `null` and `undefined`.
-null; // used to indicate a deliberate non-value
-undefined; // used to indicate a value is not currently present (although
- // `undefined` is actually a value itself)
+// Existe também o `null` e o `undefined`.
+null; // usado para indicar um valor não considerado
+undefined; // usado para indicar um valor que não é a atualmente definido
+ // (entretando `undefined` é usado como um próprio valor
-// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.
-// Note that 0 is falsy and "0" is truthy, even though 0 == "0".
+// false, null, undefined, NaN, 0 and "" são valores falsy;
+// qualquer outro valor é truthy
+// Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0".
///////////////////////////////////
// 2. Variables, Arrays and Objects
--
cgit v1.2.3
From 716e0ced466ef98f7fb9d78d15a5ab606b6b755c Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Thu, 1 Oct 2015 23:48:05 -0300
Subject: =?UTF-8?q?[javascript=20pt-br]=20:=202.=20Vari=C3=A1veis,=20Array?=
=?UTF-8?q?s=20e=20Objetos?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
pt-br/javascript-pt.html.markdown | 57 ++++++++++++++++++++-------------------
1 file changed, 30 insertions(+), 27 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 72f4cf0f..6667a77d 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -132,62 +132,65 @@ undefined; // usado para indicar um valor que não é a atualmente definido
// Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0".
///////////////////////////////////
-// 2. Variables, Arrays and Objects
+// 2. Variáveis, Arrays e Objetos
-// Variables are declared with the `var` keyword. JavaScript is dynamically
-// typed, so you don't need to specify type. Assignment uses a single `=`
-// character.
+// Variáveis são declarados com a palavra-chave `var`. O Javascript é
+// dinâmicamente tipado, portanto você não precisa especificar o tipo.
+// Atribuições usam um simples caracter de `=`.
var someVar = 5;
-// if you leave the var keyword off, you won't get an error...
+// se você deixar de colocar a palavra-chave var, você não receber um erro...
someOtherVar = 10;
-// ...but your variable will be created in the global scope, not in the scope
-// you defined it in.
+// ...mas sua variável será criada no escopo global, não no escopo em que você
+// definiu ela.
-// Variables declared without being assigned to are set to undefined.
+// Variáveis declaradas sem receberem um valor são definidas como `undefined`.
var someThirdVar; // = undefined
-// There's shorthand for performing math operations on variables:
-someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
-someVar *= 10; // now someVar is 100
+// Existe um shorthad para operações matemáticas em variáveis:
+someVar += 5; // equivalente a someVar = someVar + 5; someVar é 10 agora
+someVar *= 10; // agora someVar é 100
-// and an even-shorter-hand for adding or subtracting 1
+// e um para adição e subtração de 1
someVar++; // now someVar is 101
someVar--; // back to 100
-// Arrays are ordered lists of values, of any type.
-var myArray = ["Hello", 45, true];
+// Arrays são listas ordenadas de valores, de qualquer tipo.
+var myArray = ["Olá", 45, true];
-// Their members can be accessed using the square-brackets subscript syntax.
-// Array indices start at zero.
+// Seus membros podem ser acessados usando a sintaxe de colchetes.
+// O indíce de um Array começa pelo 0.
myArray[1]; // = 45
-// Arrays are mutable and of variable length.
+// Arrays são mutáveis e de tamanho variável.
myArray.push("World");
myArray.length; // = 4
-// Add/Modify at specific index
+// Adicionar/modificar em um índice específico
myArray[3] = "Hello";
-// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
-// languages: an unordered collection of key-value pairs.
-var myObj = {key1: "Hello", key2: "World"};
+// Objetos de Javascript são equivalentes aos dicionários ou maps de outras
+// linguagens: uma coleção não ordenada de pares chave-valor.
+var myObj = {chave1: "Olá", chave2: "Mundo"};
-// Keys are strings, but quotes aren't required if they're a valid
-// JavaScript identifier. Values can be any type.
+// Chaves são strings, mas as aspas não são necessárias se elas são
+// identificadores válidos no Javascript. Valores podem ser de qualquer tipo.
var myObj = {myKey: "myValue", "my other key": 4};
-// Object attributes can also be accessed using the subscript syntax,
+// Atributos de objetos também podem ser acessados com a sintaxe de colchetes.
myObj["my other key"]; // = 4
-// ... or using the dot syntax, provided the key is a valid identifier.
+// ... ou usando a sintaxe de ponto, passando a chave que é um identificador
+// válido.
myObj.myKey; // = "myValue"
-// Objects are mutable; values can be changed and new keys added.
+// Objetos são mutáveis, valores podem ser modificados e novas chaves
+// adicionadas.
myObj.myThirdKey = true;
-// If you try to access a value that's not yet set, you'll get undefined.
+// Se você tentar acessar um valor que não foi determinado ainda, você irá
+// receber `undefined`.
myObj.myFourthKey; // = undefined
///////////////////////////////////
--
cgit v1.2.3
From 32caaabe05e2d920c4be42c278e2e6d51ddea6ed Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Fri, 2 Oct 2015 01:05:31 -0300
Subject: =?UTF-8?q?[javascript=20pt-br]=20:=203.=20L=C3=B3gica=20e=20Estru?=
=?UTF-8?q?turas=20de=20Controle?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
pt-br/javascript-pt.html.markdown | 42 ++++++++++++++++++++-------------------
1 file changed, 22 insertions(+), 20 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 6667a77d..14d82146 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -194,52 +194,54 @@ myObj.myThirdKey = true;
myObj.myFourthKey; // = undefined
///////////////////////////////////
-// 3. Logic and Control Structures
+// 3. Lógica e Estruturas de Controle
-// The syntax for this section is almost identical to Java's.
+// A sintaxe para essa seção é quase idêntica a maioria das linguagens.
// The `if` structure works as you'd expect.
-var count = 1;
+// A estrutura `if` funciona como deveria ser.
+var count = 1
if (count == 3){
- // evaluated if count is 3
+ // executa se count é 3
} else if (count == 4){
- // evaluated if count is 4
+ // executa se count é 4
} else {
- // evaluated if it's not either 3 or 4
+ // executa se count não é 3 nem 4
}
-// As does `while`.
+// Como se faz `while`.
while (true){
- // An infinite loop!
+ // Um loop infinito!
}
-// Do-while loops are like while loops, except they always run at least once.
-var input;
+// Os loops do-while são como os loops de while, exceto quando eles sempre
+// executam pelo menos uma vez.
do {
input = getInput();
} while (!isValid(input))
// The `for` loop is the same as C and Java:
// initialisation; continue condition; iteration.
+
+// O loop `for` é o mesmo de C e Java:
+// inicialização, condição de continuar; iteração
for (var i = 0; i < 5; i++){
- // will run 5 times
+ // vai rodar cinco vezes
}
-// && is logical and, || is logical or
+// && é o `e` lógico , || é o `ou` lógico
if (house.size == "big" && house.colour == "blue"){
house.contains = "bear";
}
-if (colour == "red" || colour == "blue"){
- // colour is either red or blue
+if (cor == "red" || cor == "blue"){
+ // cor é vermelha OU azul
}
-// && and || "short circuit", which is useful for setting default values.
-var name = otherName || "default";
-
+// && e || "pequeno circuito", é útil para determinar valores padrões.
+var name = otherName || "padrão";
-// The `switch` statement checks for equality with `===`.
-// use 'break' after each case
-// or the cases after the correct one will be executed too.
+// O `switch` checa pela igualdade com `===`.
+// Use `break` após cada `case`
grade = 'B';
switch (grade) {
case 'A':
--
cgit v1.2.3
From 2534c71c4f5cc8f6b806914857da11b8ae89f45d Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Fri, 2 Oct 2015 01:23:46 -0300
Subject: =?UTF-8?q?[javascript=20pt-br]=20:=20Fun=C3=A7=C3=B5es,=20Escopos?=
=?UTF-8?q?=20e=20Closures?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
pt-br/javascript-pt.html.markdown | 79 +++++++++++++++++++++------------------
1 file changed, 42 insertions(+), 37 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 14d82146..08448d0b 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -209,7 +209,7 @@ if (count == 3){
// executa se count não é 3 nem 4
}
-// Como se faz `while`.
+// Como se faz um `while`.
while (true){
// Um loop infinito!
}
@@ -224,7 +224,7 @@ do {
// initialisation; continue condition; iteration.
// O loop `for` é o mesmo de C e Java:
-// inicialização, condição de continuar; iteração
+// inicialização, condição para continuar; iteração
for (var i = 0; i < 5; i++){
// vai rodar cinco vezes
}
@@ -260,79 +260,84 @@ switch (grade) {
///////////////////////////////////
-// 4. Functions, Scope and Closures
+// 4. Funções, Escopos e Closures
-// JavaScript functions are declared with the `function` keyword.
+// Funções Javascript são declaradas com a palavra-chave `function`.
function myFunction(thing){
return thing.toUpperCase();
}
myFunction("foo"); // = "FOO"
-// Note that the value to be returned must start on the same line as the
-// `return` keyword, otherwise you'll always return `undefined` due to
-// automatic semicolon insertion. Watch out for this when using Allman style.
+// Repare que o valor a ser retornado deve começar na mesma linha que
+// a palavra-chave `return`, senão você sempre irá retornar `undefined`
+// visto que o ponto-e-vírgula é inserido automáticamente nas quebras de
+// linha. Preste atenção quando usar o estilo Allman.
function myFunction()
{
- return // <- semicolon automatically inserted here
+ return // <- ponto-e-vírgula adicionado automaticamente aqui
{
thisIsAn: 'object literal'
}
}
myFunction(); // = undefined
-// JavaScript functions are first class objects, so they can be reassigned to
-// different variable names and passed to other functions as arguments - for
-// example, when supplying an event handler:
+// Funções Javascript são objetos de primeira classe, portanto elas podem
+// ser atribuídas a nomes de variáveis e serem passadas para outras funções
+// como argumentos - por exemplo, quando criamos um manipulador de eventos:
function myFunction(){
- // this code will be called in 5 seconds' time
+ // este código será chamado em 5 segundos
}
setTimeout(myFunction, 5000);
-// Note: setTimeout isn't part of the JS language, but is provided by browsers
-// and Node.js.
+// Nota: `setTimeout` não é parte da linguagem Javascript, mas é provido pelos
+// browsers e o Node.js.
-// Function objects don't even have to be declared with a name - you can write
-// an anonymous function definition directly into the arguments of another.
+// Objetos de funções não precisam nem serem declarados com nome - você pode
+// escrever a definição de uma função anônima diretamente nos argumentos de
+// outra função.
setTimeout(function(){
- // this code will be called in 5 seconds' time
+ // este código será chamado em 5 segundos
}, 5000);
-// JavaScript has function scope; functions get their own scope but other blocks
-// do not.
+// O Javascript tem escopo de função; as funções tem seu próprio escopo,
+// mas outros blocos não.
if (true){
var i = 5;
}
-i; // = 5 - not undefined as you'd expect in a block-scoped language
+i; // = 5 - não `undefined` como você esperaria numa linguagem de blogo-escopo
-// This has led to a common pattern of "immediately-executing anonymous
-// functions", which prevent temporary variables from leaking into the global
-// scope.
+// Isso levou a padrão comum chamado de IIFE (Imediately Invoked Function
+// Expression) ou (Expressão de Função Invocada Imediatamente), que previne
+// que variáveis temporárias vazem para o escopo global.
(function(){
var temporary = 5;
- // We can access the global scope by assiging to the "global object", which
- // in a web browser is always `window`. The global object may have a
- // different name in non-browser environments such as Node.js.
+ // Nós podemos acessar o escopo global definindo o "objeto global", que
+ // no browser vai ser sempre `window`. O objeto global pode ter um nome
+ // diferente para ambiente não-browser como o Node.js.
window.permanent = 10;
})();
-temporary; // raises ReferenceError
+temporary; // levanta um erro de referência inexiste
permanent; // = 10
-// One of JavaScript's most powerful features is closures. If a function is
-// defined inside another function, the inner function has access to all the
-// outer function's variables, even after the outer function exits.
+// Uma das principais características do Javascript é a closure. Que é
+// uma função definida dentro de outra função, a função interna pode acessar
+// todas as variáveis da função externa, mesmo depois da função de fora
+// finalizar sua execução.
function sayHelloInFiveSeconds(name){
var prompt = "Hello, " + name + "!";
- // Inner functions are put in the local scope by default, as if they were
- // declared with `var`.
+
+ // Funções internas são colocadas no escopo local por padrão, assim como
+ // se fossem declaradas com `var`.
function inner(){
alert(prompt);
}
setTimeout(inner, 5000);
- // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
- // exit immediately, and setTimeout will call inner afterwards. However,
- // because inner is "closed over" sayHelloInFiveSeconds, inner still has
- // access to the `prompt` variable when it is finally called.
+ // `setTimeout` é assíncrono, portanto a função `sayHelloInFiveSeconds`
+ // vai sair imediatamente, e o `setTimeout` irá chamar a interna depois.
+ // Entretanto. como a interna é fechada dentro de "sayHelloInFiveSeconds",
+ // a interna permanece podendo acessar a variável `prompt` quando depois
+ // de chamada.
}
-sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
+sayHelloInFiveSeconds("Adam"); // Vai abrir um popup com "Hello, Adam!" em 5s
///////////////////////////////////
// 5. More about Objects; Constructors and Prototypes
--
cgit v1.2.3
From 93c8348f3e25cbe2274e8762b3759c61e4375cdc Mon Sep 17 00:00:00 2001
From: Adolfo Jayme Barrientos
Date: Fri, 2 Oct 2015 08:30:17 -0500
Subject: [visualbasic/es] Create Spanish translation of VB tutorial
---
es-es/visualbasic-es.html.markdown | 286 +++++++++++++++++++++++++++++++++++++
1 file changed, 286 insertions(+)
create mode 100644 es-es/visualbasic-es.html.markdown
diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown
new file mode 100644
index 00000000..0702c01e
--- /dev/null
+++ b/es-es/visualbasic-es.html.markdown
@@ -0,0 +1,286 @@
+---
+language: Visual Basic
+contributors:
+ - ["Brian Martin", "http://brianmartin.biz"]
+translators:
+ - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"]
+author: Brian Martin
+author_url: http://brianmartin.biz
+filename: learnvisualbasic-es.vb
+lang: es-es
+---
+
+```vb
+Module Module1
+
+ Sub Main()
+ ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes
+ ' de que profundicemos en el tema.
+ ' El apóstrofo inicia una línea de comentario.
+ ' Para explorar este tutorial dentro del Compilador de Visual Basic,
+ ' he creado un sistema de navegación.
+ ' Dicho sistema se explicará a medida que avancemos en este
+ ' tutorial; gradualmente entenderás lo que significa todo.
+ Console.Title = ("Aprende X en Y minutos")
+ Console.WriteLine("NAVEGACIÓN") 'Mostrar
+ Console.WriteLine("")
+ Console.ForegroundColor = ConsoleColor.Green
+ Console.WriteLine("1. Salida «Hola, mundo»")
+ Console.WriteLine("2. Entrada «Hola, mundo»")
+ Console.WriteLine("3. Calcular números enteros")
+ Console.WriteLine("4. Calcular números decimales")
+ Console.WriteLine("5. Una calculadora funcional")
+ Console.WriteLine("6. Uso de bucles «Do While»")
+ Console.WriteLine("7. Uso de bucles «For While»")
+ Console.WriteLine("8. Declaraciones condicionales")
+ Console.WriteLine("9. Selecciona una bebida")
+ Console.WriteLine("50. Acerca de")
+ Console.WriteLine("Elige un número de la lista anterior")
+ Dim selection As String = Console.ReadLine
+ Select Case selection
+ Case "1" 'Salida «hola, mundo»
+ Console.Clear() 'Limpia la consola y abre la subrutina privada
+ SalidaHolaMundo() 'Abre la subrutina privada nombrada
+ Case "2" 'Entrada «hola, mundo»
+ Console.Clear()
+ EntradaHolaMundo()
+ Case "3" 'Calcular números enteros
+ Console.Clear()
+ CalcularNumerosEnteros()
+ Case "4" 'Calcular números decimales
+ Console.Clear()
+ CalcularNumerosDecimales()
+ Case "5" 'Una calculadora funcional
+ Console.Clear()
+ CalculadoraFuncional()
+ Case "6" 'Uso de bucles «Do While»
+ Console.Clear()
+ UsoBuclesDoWhile()
+ Case "7" 'Uso de bucles «For While»
+ Console.Clear()
+ UsoBuclesFor()
+ Case "8" 'Declaraciones condicionales
+ Console.Clear()
+ DeclaracionCondicional()
+ Case "9" 'Declaración «If/Else»
+ Console.Clear()
+ DeclaracionIfElse() 'Selecciona una bebida
+ Case "50" 'Cuadro de mensaje «Acerca de»
+ Console.Clear()
+ Console.Title = ("Aprende X en Y minutos :: Acerca de")
+ MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn")
+ Console.Clear()
+ Main()
+ Console.ReadLine()
+
+ End Select
+ End Sub
+
+ 'Uno - He usado números para guiarme por el sistema de navegación anterior
+ 'cuando regrese posteriormente a implementarlo.
+
+ 'Usamos subrutinas privadas para separar distintas secciones del programa.
+ Private Sub SalidaHolaMundo()
+ 'Título de la aplicación de consola
+ Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos"
+ 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas.
+ 'Seguido por Console.Read(), o bien, Console.Readline()
+ 'Console.ReadLine() muestra la salida en la consola.
+ Console.WriteLine("Hola, mundo")
+ Console.ReadLine()
+ End Sub
+
+ 'Dos
+ Private Sub EntradaHolaMundo()
+ Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos"
+ ' Variables
+ ' Los datos que introduzca un usuario deben almacenarse.
+ ' Las variables también empiezan por Dim y terminan por As VariableType.
+
+ ' En este tutorial queremos conocer tu nombre y hacer que el programa
+ ' responda a este.
+ Dim nombredeusuario As String
+ 'Usamos «string» porque es una variable basada en texto.
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario.
+ Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre
+ Console.ReadLine() 'Muestra lo anterior.
+ 'El código anterior te hará una pregunta y mostrará la respuesta.
+ 'Entre otras variables está Integer, la cual usaremos para números enteros.
+ End Sub
+
+ 'Tres
+ Private Sub CalcularNumerosEnteros()
+ Console.Title = "Calcular números enteros | Aprende X en Y minutos"
+ Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc
+ Dim a As Integer = Console.ReadLine()
+ Console.Write("Segundo número: ") 'Escribe otro número entero.
+ Dim b As Integer = Console.ReadLine()
+ Dim c As Integer = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Lo anterior es una calculadora sencilla
+ End Sub
+
+ 'Cuatro
+ Private Sub CalcularNumerosDecimales()
+ Console.Title = "Calcular con tipo doble | Aprende X en Y minutos"
+ 'Por supuesto, nos gustaría sumar decimales.
+ 'Por ello podríamos cambiar del tipo Integer al Double.
+
+ 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ") 'Escribe el segundo número.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Console.WriteLine(c)
+ Console.ReadLine()
+ 'Este programa puede sumar 1.1 y 2.2
+ End Sub
+
+ 'Cinco
+ Private Sub CalculadoraFuncional()
+ Console.Title = "La calculadora funcional | Aprende X en Y minutos"
+ 'Pero si quieres que la calculadora reste, divida, multiplique y
+ 'sume.
+ 'Copia y pega lo anterior.
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ 'Mediante las líneas siguientes podremos restar,
+ 'multiplicar y dividir los valores a y b
+ Console.Write(a.ToString() + " + " + b.ToString())
+ 'Queremos dar un margen izquierdo de 3 espacios a los resultados.
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+
+ End Sub
+
+ 'Seis
+ Private Sub UsoBuclesDoWhile()
+ 'Igual que la subrutina privada anterior
+ 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?)
+ 'Usamos el bucle Do While porque no sabemos si el usuario quiere
+ 'usar el programa más de una vez.
+ Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos"
+ Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto
+ Do 'Comenzamos el programa con
+ Console.Write("Primer número: ")
+ Dim a As Double = Console.ReadLine
+ Console.Write("Segundo número: ")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ Console.Write(a.ToString() + " + " + b.ToString())
+ Console.WriteLine(" = " + c.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " * " + b.ToString())
+ Console.WriteLine(" = " + d.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " - " + b.ToString())
+ Console.WriteLine(" = " + e.ToString.PadLeft(3))
+ Console.Write(a.ToString() + " / " + b.ToString())
+ Console.WriteLine(" = " + f.ToString.PadLeft(3))
+ Console.ReadLine()
+ 'Preguntar si el usuario quiere continuar. Desafortunadamente,
+ 'distingue entre mayúsculas y minúsculas.
+ Console.Write("¿Quieres continuar? (s / n)")
+ 'El programa toma la variable, la muestra y comienza de nuevo.
+ respuesta = Console.ReadLine
+ 'La orden que hará funcionar esta variable es en este caso «s»
+ Loop While respuesta = "s"
+
+ End Sub
+
+ 'Siete
+ Private Sub UsoBuclesFor()
+ 'A veces el programa debe ejecutarse solo una vez.
+ 'En este programa contaremos a partir de 10.
+
+ Console.Title = "Uso de bucles «For» | Aprende X en Y minutos"
+ 'Declarar Variable y desde qué número debe contar en Step -1,
+ 'Step -2, Step -3, etc.
+ For i As Integer = 10 To 0 Step -1
+ Console.WriteLine(i.ToString) 'Muestra el valor del contador
+ Next i 'Calcular el valor nuevo
+ Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!!
+ Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :)
+ End Sub
+
+ 'Ocho
+ Private Sub DeclaracionCondicional()
+ Console.Title = "Declaraciones condicionales | Aprende X en Y minutos"
+ Dim nombredeUsuario As String = Console.ReadLine
+ Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario.
+ nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario.
+ If nombredeUsuario = "Adam" Then
+ Console.WriteLine("Hola, Adam")
+ Console.WriteLine("Gracias por crear este útil sitio web")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Hola, " + nombredeUsuario)
+ Console.WriteLine("¿Has visitado www.learnxinyminutes.com?")
+ Console.ReadLine() 'Termina y muestra la declaración anterior.
+ End If
+ End Sub
+
+ 'Nueve
+ Private Sub DeclaracionIfElse()
+ Console.Title = "Declaración «If / Else» | Aprende X en Y minutos"
+ 'A veces es importante considerar más de dos alternativas.
+ 'A veces, algunas de estas son mejores.
+ 'Cuando esto sucede, necesitaríamos más de una declaración «if».
+ 'Una declaración «if» es adecuada para máquinas expendedoras.
+ 'En las que el usuario escribe un código (A1, A2, A3) para elegir.
+ 'Pueden combinarse todas las elecciones en una sola declaración «if».
+
+ Dim seleccion As String = Console.ReadLine 'Valor de la selección
+ Console.WriteLine("A1. para 7Up")
+ Console.WriteLine("A2. para Fanta")
+ Console.WriteLine("A3. para Dr. Pepper")
+ Console.WriteLine("A4. para Coca-Cola")
+ Console.ReadLine()
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ Console.ReadLine()
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ Console.ReadLine()
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ Console.ReadLine()
+ ElseIf selection = "A4" Then
+ Console.WriteLine("coca-cola")
+ Console.ReadLine()
+ Else
+ Console.WriteLine("Selecciona un producto")
+ Console.ReadLine()
+ End If
+
+ End Sub
+
+End Module
+
+```
+
+## Referencias
+
+Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad.
+
+He creado un tutorial de Visual Basic más exhaustivo para quienes quieran saber más.
+
+Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa.
--
cgit v1.2.3
From acc9a73c018a28a9c8ead7b108dd1fdfee7a797b Mon Sep 17 00:00:00 2001
From: ksami
Date: Fri, 2 Oct 2015 22:08:27 +0800
Subject: [bash/en] Improved descriptions
---
bash.html.markdown | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/bash.html.markdown b/bash.html.markdown
index 08182c2c..d4f3d424 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -51,7 +51,7 @@ echo $Variable
echo "$Variable"
echo '$Variable'
# When you use the variable itself — assign it, export it, or else — you write
-# its name without $. If you want to use variable's value, you should use $.
+# its name without $. If you want to use the variable's value, you should use $.
# Note that ' (single quote) won't expand the variables!
# String substitution in variables
@@ -70,11 +70,11 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# Builtin variables:
# There are some useful builtin variables, like
-echo "Last program return value: $?"
+echo "Last program's return value: $?"
echo "Script's PID: $$"
-echo "Number of arguments: $#"
-echo "Scripts arguments: $@"
-echo "Scripts arguments separated in different variables: $1 $2..."
+echo "Number of arguments passed to script: $#"
+echo "All arguments passed to script: $@"
+echo "Script's arguments separated into different variables: $1 $2..."
# Reading a value from input:
echo "What's your name?"
@@ -108,8 +108,8 @@ fi
# Expressions are denoted with the following format:
echo $(( 10 + 5 ))
-# Unlike other programming languages, bash is a shell — so it works in a context
-# of current directory. You can list files and directories in the current
+# Unlike other programming languages, bash is a shell so it works in the context
+# of a current directory. You can list files and directories in the current
# directory with the ls command:
ls
--
cgit v1.2.3
From 0ad95b119d1f0135bf3a9fd55cebf24d63692c11 Mon Sep 17 00:00:00 2001
From: Michele Orselli
Date: Fri, 2 Oct 2015 18:24:45 +0200
Subject: adds some new php operators
---
php.html.markdown | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/php.html.markdown b/php.html.markdown
index 52ea2a95..53be5391 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -215,6 +215,14 @@ assert($a !== $d);
assert(1 === '1');
assert(1 !== '1');
+// spaceship operator since PHP 7
+$a = 100;
+$b = 1000;
+
+echo $a <=> $a; // 0 since they are equal
+echo $a <=> $b; // -1 since $a < $b
+echo $b <=> $a; // 1 since $b > $a
+
// Variables can be converted between types, depending on their usage.
$integer = 1;
@@ -264,6 +272,18 @@ if (false) {
// ternary operator
print (false ? 'Does not get printed' : 'Does');
+// ternary shortcut operator since PHP 5.3
+// equivalent of "$x ? $x : 'Does'""
+$x = false;
+print($x ?: 'Does');
+
+// null coalesce operator since php 7
+$a = null;
+$b = 'Does print';
+echo $a ?? 'a is not set'; // prints 'a is not set'
+echo $b ?? 'b is not set'; // prints 'Does print'
+
+
$x = 0;
if ($x === '0') {
print 'Does not print';
--
cgit v1.2.3
From 57ea4af17c7ab17e9c32096c2579e0a985e44781 Mon Sep 17 00:00:00 2001
From: Ian Bertolacci
Date: Fri, 2 Oct 2015 10:31:25 -0600
Subject: Updated info for Chapel 1.12.0
---
chapel.html.markdown | 196 +++++++++++++++++++++++++--------------------------
1 file changed, 98 insertions(+), 98 deletions(-)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index 8a88a652..1d0abe6e 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -27,7 +27,7 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" );
stdout.writeln( "This goes to standard output, just like plain writeln() does");
stderr.writeln( "This goes to standard error" );
-// Variables don't have to be explicitly typed as long as
+// Variables don't have to be explicitly typed as long as
// the compiler can figure out the type that it will hold.
var myVar = 10; // 10 is an int, so myVar is implicitly an int
myVar = -10;
@@ -65,9 +65,9 @@ const almostPi: real = 22.0/7.0;
param compileTimeConst: int = 16;
// The config modifier allows values to be set at the command line
-// and is much easier than the usual getOpts debacle
+// and is much easier than the usual getOpts debacle
// config vars and consts can be changed through the command line at run time
-config var varCmdLineArg: int = -123;
+config var varCmdLineArg: int = -123;
config const constCmdLineArg: int = 777;
// Set with --VarName=Value or --VarName Value at run time
@@ -119,9 +119,9 @@ a *= thatInt; // Times-equals ( a = a * thatInt; )
b &&= thatBool; // Logical-and-equals ( b = b && thatBool; )
a <<= 3; // Left-bit-shift-equals ( a = a << 10; )
// and many, many more.
-// Unlike other C family languages there are no
+// Unlike other C family languages there are no
// pre/post-increment/decrement operators like
-// ++j, --j, j++, j--
+// ++j, --j, j++, j--
// Swap operator
var old_this = thisInt;
@@ -155,7 +155,7 @@ writeln( (a,b,thisInt,thatInt,thisBool,thatBool) );
// Type aliasing
type chroma = int; // Type of a single hue
-type RGBColor = 3*chroma; // Type representing a full color
+type RGBColor = 3*chroma; // Type representing a full color
var black: RGBColor = ( 0,0,0 );
var white: RGBColor = ( 255, 255, 255 );
@@ -198,7 +198,7 @@ select( inputOption ){
writeln( "Chose 'otherOption'" );
writeln( "Which has a body" );
}
- otherwise {
+ otherwise {
writeln( "Any other Input" );
writeln( "the otherwise case doesn't need a do if the body is one line" );
}
@@ -221,7 +221,7 @@ do{
writeln( jSum );
// For loops are much like those in python in that they iterate over a range.
-// Ranges themselves are types, and can be stuffed into variables
+// Ranges themselves are types, and can be stuffed into variables
// (more about that later)
for i in 1..10 do write( i , ", ") ;
writeln( );
@@ -240,28 +240,28 @@ for x in 1..10 {
}
// Ranges and Domains
-// For-loops and arrays both use ranges and domains to
+// For-loops and arrays both use ranges and domains to
// define an index set that can be iterated over.
// Ranges are single dimensional
-// Domains can be multi-dimensional and can
+// Domains can be multi-dimensional and can
// represent indices of different types as well.
// They are first-class citizen types, and can be assigned into variables
var range1to10: range = 1..10; // 1, 2, 3, ..., 10
var range2to11 = 2..11; // 2, 3, 4, ..., 11
var rangeThistoThat: range = thisInt..thatInt; // using variables
-var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices
+var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices
-// Ranges can be unbounded
-var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ;
+// Ranges can be unbounded
+var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ;
// 1, 2, 3, 4, 5, ...
-// Note: the range(boundedType= ... ) is only
+// Note: the range(boundedType= ... ) is only
// necessary if we explicitly type the variable
var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1
// Ranges can be strided using the 'by' operator.
var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10
-// Note: the range(stridable=true) is only
+// Note: the range(stridable=true) is only
// necessary if we explicitly type the variable
// Use by to create a reverse range
@@ -275,9 +275,9 @@ var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5
writeln( rangeCountBy );
// Can query properties of the range
-// Print the first index, last index, number of indices,
+// Print the first index, last index, number of indices,
// stride, and ask if 2 is include in the range
-writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length,
+writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length,
rangeCountBy.stride, rangeCountBy.member( 2 ) ) );
for i in rangeCountBy{
@@ -309,7 +309,7 @@ stringSet += "b";
stringSet += "c";
stringSet += "a"; // Redundant add "a"
stringSet -= "c"; // Remove "c"
-writeln( stringSet );
+writeln( stringSet );
// Both ranges and domains can be sliced to produce a range or domain with the
// intersection of indices
@@ -332,13 +332,13 @@ var intArray2: [{1..10}] int; //equivalent
for i in 1..10 do
intArray[i] = -i;
writeln( intArray );
-// We cannot access intArray[0] because it exists outside
+// We cannot access intArray[0] because it exists outside
// of the index set, {1..10}, we defined it to have.
// intArray[11] is illegal for the same reason.
var realDomain: domain(2) = {1..5,1..7};
var realArray: [realDomain] real;
-var realArray2: [1..5,1..7] real; // Equivalent
+var realArray2: [1..5,1..7] real; // Equivalent
var realArray3: [{1..5,1..7}] real; // Equivalent
for i in 1..5 {
@@ -350,7 +350,7 @@ for i in 1..5 {
}
// Arrays have domains as members that we can iterate over
-for idx in realArray.domain { // Again, idx is a 2*int tuple
+for idx in realArray.domain { // Again, idx is a 2*int tuple
realArray[idx] = 1 / realArray[idx[1],idx[2]]; // Access by tuple and list
}
@@ -377,7 +377,7 @@ var thatArray : [{0..5}] int;
// Simply assign one to the other.
// This copies thisArray into thatArray, instead of just creating a reference.
// Modifying thisArray does not also modify thatArray.
-thatArray = thisArray;
+thatArray = thisArray;
thatArray[1] = -1;
writeln( (thisArray, thatArray) );
@@ -389,12 +389,12 @@ writeln( (thisArray, thatArray) );
var thisPlusThat = thisArray + thatArray;
writeln( thisPlusThat );
-// Arrays and loops can also be expressions, where loop
+// Arrays and loops can also be expressions, where loop
// body's expression is the result of each iteration.
var arrayFromLoop = for i in 1..10 do i;
writeln( arrayFromLoop );
-// An expression can result in nothing,
+// An expression can result in nothing,
// such as when filtering with an if-expression
var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i;
@@ -407,7 +407,7 @@ var evensOrFivesAgain = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i;
// Or over the values of the array
arrayFromLoop = [ value in arrayFromLoop ] value + 1;
-// Note: this notation can get somewhat tricky. For example:
+// Note: this notation can get somewhat tricky. For example:
// evensOrFives = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i;
// would break.
// The reasons for this are explained in depth when discussing zipped iterators.
@@ -431,7 +431,7 @@ proc addThree( n ) {
doublePrint( addThree( fibonacci( 20 ) ) );
// Can also take 'unlimited' number of parameters
-proc maxOf( x ...?k ) {
+proc maxOf( x ...?k ) {
// x refers to a tuple of one type, with k elements
var maximum = x[1];
for i in 2..k do maximum = if (maximum < x[i]) then x[i] else maximum;
@@ -439,7 +439,7 @@ proc maxOf( x ...?k ) {
}
writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) );
-// The ? operator is called the query operator, and is used to take
+// The ? operator is called the query operator, and is used to take
// undetermined values (like tuple or array sizes, and generic types).
// Taking arrays as parameters.
@@ -463,7 +463,7 @@ writeln( defaultsProc( x=11 ) );
writeln( defaultsProc( x=12, y=5.432 ) );
writeln( defaultsProc( y=9.876, x=13 ) );
-// Intent modifiers on the arguments convey how
+// Intent modifiers on the arguments convey how
// those arguments are passed to the procedure
// in: copy arg in, but not out
// out: copy arg out, but not in
@@ -489,18 +489,18 @@ writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) );
// Similarly we can define intents on the return type
// refElement returns a reference to an element of array
proc refElement( array : [?D] ?T, idx ) ref : T {
- return array[ idx ]; // returns a reference to
+ return array[ idx ]; // returns a reference to
}
var myChangingArray : [1..5] int = [1,2,3,4,5];
writeln( myChangingArray );
-// Store reference to element in ref variable
-ref refToElem = refElement( myChangingArray, 5 );
+// Store reference to element in ref variable
+ref refToElem = refElement( myChangingArray, 5 );
writeln( refToElem );
refToElem = -2; // modify reference which modifies actual value in array
writeln( refToElem );
writeln( myChangingArray );
-// This makes more practical sense for class methods where references to
+// This makes more practical sense for class methods where references to
// elements in a data-structure are returned via a method or iterator
// We can query the type of arguments to generic procedures
@@ -520,7 +520,7 @@ genericProc( 1.0+2.0i, 3.0+4.0i );
// We can also enforce a form of polymorphism with the 'where' clause
// This allows the compiler to decide which function to use.
-// Note: that means that all information needs to be known at compile-time.
+// Note: that means that all information needs to be known at compile-time.
// The param modifier on the arg is used to enforce this constraint.
proc whereProc( param N : int ): void
where ( N > 0 ) {
@@ -534,7 +534,7 @@ proc whereProc( param N : int ): void
whereProc( 10 );
whereProc( -1 );
-// whereProc( 0 ) would result in a compiler error because there
+// whereProc( 0 ) would result in a compiler error because there
// are no functions that satisfy the where clause's condition.
// We could have defined a whereProc without a where clause that would then have
// served as a catch all for all the other cases (of which there is only one).
@@ -543,7 +543,7 @@ whereProc( -1 );
// We can define the unary operators:
// + - ! ~
// and the binary operators:
-// + - * / % ** == <= >= < > << >> & | ˆ by
+// + - * / % ** == <= >= < > << >> & | ˆ by
// += -= *= /= %= **= &= |= ˆ= <<= >>= <=>
// Boolean exclusive or operator
@@ -569,14 +569,14 @@ Note: You could break everything if you get careless with your overloads.
This here will break everything. Don't do it.
proc +( left: int, right: int ): int{
return left - right;
-}
+}
*/
-// Iterators are a sisters to the procedure, and almost
+// Iterators are a sisters to the procedure, and almost
// everything about procedures also applies to iterators
-// However, instead of returning a single value,
+// However, instead of returning a single value,
// iterators yield many values to a loop.
-// This is useful when a complicated set or order of iterations is needed but
+// This is useful when a complicated set or order of iterations is needed but
// allows the code defining the iterations to be separate from the loop body.
iter oddsThenEvens( N: int ): int {
for i in 1..N by 2 do
@@ -601,15 +601,15 @@ for i in absolutelyNothing( 10 ){
writeln( "Woa there! absolutelyNothing yielded ", i );
}
-// We can zipper together two or more iterators (who have the same number
-// of iterations) using zip() to create a single zipped iterator, where each
-// iteration of the zipped iterator yields a tuple of one value yielded
+// We can zipper together two or more iterators (who have the same number
+// of iterations) using zip() to create a single zipped iterator, where each
+// iteration of the zipped iterator yields a tuple of one value yielded
// from each iterator.
// Ranges have implicit iterators
-for (positive, negative) in zip( 1..5, -5..-1) do
+for (positive, negative) in zip( 1..5, -5..-1) do
writeln( (positive, negative) );
-// Zipper iteration is quite important in the assignment of arrays,
+// Zipper iteration is quite important in the assignment of arrays,
// slices of arrays, and array/loop expressions.
var fromThatArray : [1..#5] int = [1,2,3,4,5];
var toThisArray : [100..#5] int;
@@ -629,10 +629,10 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){
}
writeln( toThisArray );
-// This is all very important in undestanding why the statement
+// This is all very important in undestanding why the statement
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
// exhibits a runtime error.
-// Even though the domain of the array and the loop-expression are
+// Even though the domain of the array and the loop-expression are
// the same size, the body of the expression can be though of as an iterator.
// Because iterators can yield nothing, that iterator yields a different number
// of things than the domain of the array or loop, which is not allowed.
@@ -641,8 +641,8 @@ writeln( toThisArray );
// They currently lack privatization
class MyClass {
// Member variables
- var memberInt : int;
- var memberBool : bool = true;
+ var memberInt : int;
+ var memberBool : bool = true;
// Classes have default constructors that don't need to be coded (see below)
// Our explicitly defined constructor
@@ -659,28 +659,28 @@ class MyClass {
proc setMemberInt( val: int ){
this.memberInt = val;
}
-
+
proc setMemberBool( val: bool ){
this.memberBool = val;
}
- proc getMemberInt( ): int{
+ proc getMemberInt( ): int{
return this.memberInt;
}
proc getMemberBool( ): bool {
return this.memberBool;
}
-
+
}
-
+
// Construct using default constructor, using default values
var myObject = new MyClass( 10 );
myObject = new MyClass( memberInt = 10 ); // Equivalent
writeln( myObject.getMemberInt( ) );
// ... using our values
var myDiffObject = new MyClass( -1, true );
- myDiffObject = new MyClass( memberInt = -1,
+ myDiffObject = new MyClass( memberInt = -1,
memberBool = true ); // Equivalent
writeln( myDiffObject );
@@ -689,7 +689,7 @@ var myOtherObject = new MyClass( 1.95 );
myOtherObject = new MyClass( val = 1.95 ); // Equivalent
writeln( myOtherObject.getMemberInt( ) );
-// We can define an operator on our class as well but
+// We can define an operator on our class as well but
// the definition has to be outside the class definition
proc +( A : MyClass, B : MyClass) : MyClass {
return new MyClass( memberInt = A.getMemberInt( ) + B.getMemberInt( ),
@@ -715,46 +715,46 @@ class GenericClass {
type classType;
var classDomain: domain(1);
var classArray: [classDomain] classType;
-
+
// Explicit constructor
proc GenericClass( type classType, elements : int ){
this.classDomain = {1..#elements};
}
-
+
// Copy constructor
- // Note: We still have to put the type as an argument, but we can
+ // Note: We still have to put the type as an argument, but we can
// default to the type of the other object using the query (?) operator
// Further, we can take advantage of this to allow our copy constructor
// to copy classes of different types and cast on the fly
- proc GenericClass( other : GenericClass(?otherType),
+ proc GenericClass( other : GenericClass(?otherType),
type classType = otherType ) {
this.classDomain = other.classDomain;
// Copy and cast
- for idx in this.classDomain do this[ idx ] = other[ idx ] : classType;
+ for idx in this.classDomain do this[ idx ] = other[ idx ] : classType;
}
-
- // Define bracket notation on a GenericClass
+
+ // Define bracket notation on a GenericClass
// object so it can behave like a normal array
// i.e. objVar[ i ] or objVar( i )
proc this( i : int ) ref : classType {
return this.classArray[ i ];
}
-
- // Define an implicit iterator for the class
+
+ // Define an implicit iterator for the class
// to yield values from the array to a loop
// i.e. for i in objVar do ....
iter these( ) ref : classType {
for i in this.classDomain do
yield this[i];
}
-
+
}
var realList = new GenericClass( real, 10 );
-// We can assign to the member array of the object using the bracket
+// We can assign to the member array of the object using the bracket
// notation that we defined ( proc this( i: int ){ ... } )
for i in realList.classDomain do realList[i] = i + 1.0;
-// We can iterate over the values in our list with the iterator
+// We can iterate over the values in our list with the iterator
// we defined ( iter these( ){ ... } )
for value in realList do write( value, ", " );
writeln( );
@@ -777,23 +777,23 @@ writeln( );
module OurModule {
// We can use modules inside of other modules.
use Time; // Time is one of the standard modules.
-
+
// We'll use this procedure in the parallelism section.
proc countdown( seconds: int ){
for i in 1..seconds by -1 {
writeln( i );
sleep( 1 );
}
- }
-
- // Submodules of OurModule
+ }
+
+ // Submodules of OurModule
// It is possible to create arbitrarily deep module nests.
module ChildModule {
proc foo(){
writeln( "ChildModule.foo()");
}
}
-
+
module SiblingModule {
proc foo(){
writeln( "SiblingModule.foo()" );
@@ -806,7 +806,7 @@ module OurModule {
use OurModule;
// At this point we have not used ChildModule or SiblingModule so their symbols
-// (i.e. foo ) are not available to us.
+// (i.e. foo ) are not available to us.
// However, the module names are, and we can explicitly call foo() through them.
SiblingModule.foo(); // Calls SiblingModule.foo()
@@ -821,13 +821,13 @@ foo(); // Less explicit call on ChildModule.foo()
proc main(){
// Parallelism
- // In other languages, parallelism is typically done with
+ // In other languages, parallelism is typically done with
// complicated libraries and strange class structure hierarchies.
// Chapel has it baked right into the language.
- // A begin statement will spin the body of that statement off
+ // A begin statement will spin the body of that statement off
// into one new task.
- // A sync statement will ensure that the progress of the main
+ // A sync statement will ensure that the progress of the main
// task will not progress until the children have synced back up.
sync {
begin { // Start of new task's body
@@ -848,7 +848,7 @@ proc main(){
printFibb( 20 ); // new task
printFibb( 10 ); // new task
printFibb( 5 ); // new task
- {
+ {
// This is a nested statement body and thus is a single statement
// to the parent statement and is executed by a single task
writeln( "this gets" );
@@ -867,26 +867,26 @@ proc main(){
// NOTE! coforall should be used only for creating tasks!
// Using it to iterating over a structure is very a bad idea!
- // forall loops are another parallel loop, but only create a smaller number
+ // forall loops are another parallel loop, but only create a smaller number
// of tasks, specifically --dataParTasksPerLocale=number of task
forall i in 1..100 {
write( i, ", ");
}
writeln( );
- // Here we see that there are sections that are in order, followed by
+ // Here we see that there are sections that are in order, followed by
// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ).
// This is because each task is taking on a chunk of the range 1..10
// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens
// in parallel.
// Your results may depend on your machine and configuration
- // For both the forall and coforall loops, the execution of the
+ // For both the forall and coforall loops, the execution of the
// parent task will not continue until all the children sync up.
// forall loops are particularly useful for parallel iteration over arrays.
// Lets run an experiment to see how much faster a parallel loop is
use Time; // Import the Time module to use Timer objects
- var timer: Timer;
+ var timer: Timer;
var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into
// Serial Experiment
@@ -906,7 +906,7 @@ proc main(){
timer.stop( ); // Stop timer
writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time
timer.clear( );
- // You may have noticed that (depending on how many cores you have)
+ // You may have noticed that (depending on how many cores you have)
// that the parallel loop went faster than the serial loop
// The bracket style loop-expression described
@@ -926,15 +926,15 @@ proc main(){
writeln( uranium.read() );
var replaceWith = 239;
- var was = uranium.exchange( replaceWith );
+ var was = uranium.exchange( replaceWith );
writeln( "uranium was ", was, " but is now ", replaceWith );
var isEqualTo = 235;
if ( uranium.compareExchange( isEqualTo, replaceWith ) ) {
- writeln( "uranium was equal to ", isEqualTo,
+ writeln( "uranium was equal to ", isEqualTo,
" so replaced value with ", replaceWith );
} else {
- writeln( "uranium was not equal to ", isEqualTo,
+ writeln( "uranium was not equal to ", isEqualTo,
" so value stays the same... whatever it was" );
}
@@ -989,14 +989,14 @@ proc main(){
}
}
- // Heres an example of using atomics and a synch variable to create a
+ // Heres an example of using atomics and a synch variable to create a
// count-down mutex (also known as a multiplexer)
var count: atomic int; // our counter
var lock$: sync bool; // the mutex lock
count.write( 2 ); // Only let two tasks in at a time.
lock$.writeXF( true ); // Set lock$ to full (unlocked)
- // Note: The value doesnt actually matter, just the state
+ // Note: The value doesnt actually matter, just the state
// (full:unlocked / empty:locked)
// Also, writeXF() fills (F) the sync var regardless of its state (X)
@@ -1005,10 +1005,10 @@ proc main(){
do{
lock$; // Read lock$ (wait)
}while ( count.read() < 1 ); // Keep waiting until a spot opens up
-
+
count.sub(1); // decrement the counter
lock$.writeXF( true ); // Set lock$ to full (signal)
-
+
// Actual 'work'
writeln( "Task #", task, " doing work." );
sleep( 2 );
@@ -1027,13 +1027,13 @@ proc main(){
// 'maxloc' gives max value and index of the max value
// Note: We have to zip the array and domain together with the zip iterator
- var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues,
+ var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues,
listOfValues.domain);
-
+
writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) );
// Scans apply the operation incrementally and return an array of the
- // value of the operation at that index as it progressed through the
+ // value of the operation at that index as it progressed through the
// array from array.domain.low to array.domain.high
var runningSumOfValues = + scan listOfValues;
var maxScan = max scan listOfValues;
@@ -1046,14 +1046,14 @@ Who is this tutorial for?
-------------------------
This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another.
-It won't teach you how to develop amazingly performant code, and it's not exhaustive.
+It won't teach you how to develop amazingly performant code, and it's not exhaustive.
Refer to the [language specification](http://chapel.cray.com/language.html) and the [module documentation](http://chapel.cray.com/docs/latest/) for more details.
Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created.
### What this tutorial is lacking:
- * Exposition of the standard modules
+ * Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html)
* Multiple Locales (distributed memory system)
* Records
* Parallel iterators
@@ -1061,11 +1061,11 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to
Your input, questions, and discoveries are important to the developers!
-----------------------------------------------------------------------
-The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features.
+The Chapel language is still in-development (version 1.12.0), so there are occasional hiccups with performance and language features.
The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes.
Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman).
-If you're really interested in the development of the compiler or contributing to the project,
+If you're really interested in the development of the compiler or contributing to the project,
[check out the master Github repository](https://github.com/chapel-lang/chapel).
It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0).
@@ -1074,10 +1074,10 @@ Installing the Compiler
Chapel can be built and installed on your average 'nix machine (and cygwin).
[Download the latest release version](https://github.com/chapel-lang/chapel/releases/)
-and its as easy as
+and its as easy as
- 1. `tar -xvf chapel-1.11.0.tar.gz`
- 2. `cd chapel-1.11.0`
+ 1. `tar -xvf chapel-1.12.0.tar.gz`
+ 2. `cd chapel-1.12.0`
3. `make`
4. `source util/setchplenv.bash # or .sh or .csh or .fish`
--
cgit v1.2.3
From 795583521a81868ac96db53533fab4dd0c6a7285 Mon Sep 17 00:00:00 2001
From: Eric McCormick
Date: Fri, 2 Oct 2015 13:50:07 -0500
Subject: fixed missing ! to create an actual comment
... which was causing everything subsequently to be rendered as code block, as the triple back tick (which should be inside a comment) wasn't being escaped as part of a comment
---
markdown.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 6d19710f..acb808ea 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -160,7 +160,7 @@ def foobar
end
\`\`\`
-<-- The above text doesn't require indenting, plus Github will use syntax
+
--
cgit v1.2.3
From fb43ef2942f29ece285be3e8944c91bde6306095 Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:12:15 -0500
Subject: Added example of when string concatenation can also be helpful with
combination of strings with html tags as this is important to understand when
templating say output code from a database transaction.
---
php.html.markdown | 2 ++
1 file changed, 2 insertions(+)
diff --git a/php.html.markdown b/php.html.markdown
index 3fcce264..86fb14e5 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -102,6 +102,8 @@ END;
// String concatenation is done with .
echo 'This string ' . 'is concatenated';
+// Strings concatenation can also be combined with html elements
+echo 'This string is' . '' . 'bold with strong tags ' . '.'
/********************************
--
cgit v1.2.3
From 8e388cd3344b90cfdc02741359850a2352a8f9b7 Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:30:45 -0500
Subject: Added section on how to declare and initialize both single varible
and multiple varibles with the same value. Important concept for large
structured programs. Seperated this a little bit.
---
java.html.markdown | 24 ++++++++++++++++++++++--
1 file changed, 22 insertions(+), 2 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 928eb39f..0f5b39af 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -47,10 +47,30 @@ public class LearnJava {
///////////////////////////////////////
- // Types & Variables
+ // Variables
///////////////////////////////////////
-
+
+ /*
+ * Variable Declaration
+ */
// Declare a variable using
+ int fooInt;
+ // Declare multiple variables of same type , ,
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Variable Initialization
+ */
+
+ // Initialize a variable using =
+ int fooInt = 1;
+ // Initialize multiple variables of same type with same value , , =
+ int fooInt1, fooInt2, fooInt3;
+ fooInt1 = fooInt2 = fooInt3 = 1;
+
+ /*
+ * Variable types
+ */
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
--
cgit v1.2.3
From 231cd629cab3553d126f8cca04a034c995c4668f Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:45:25 -0500
Subject: Update java.html.markdown
---
java.html.markdown | 104 ++++++++---------------------------------------------
1 file changed, 14 insertions(+), 90 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 0f5b39af..745741f8 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -1,18 +1,3 @@
----
-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/"]
-filename: LearnJava.java
----
-
-Java is a general-purpose, concurrent, class-based, object-oriented computer
-programming language.
-[Read more here.](http://docs.oracle.com/javase/tutorial/java/)
-
-```java
// Single-line comments start with //
/*
Multi-line comments look like this.
@@ -47,30 +32,10 @@ public class LearnJava {
///////////////////////////////////////
- // Variables
+ // Types & Variables
///////////////////////////////////////
-
- /*
- * Variable Declaration
- */
- // Declare a variable using
- int fooInt;
- // Declare multiple variables of same type , ,
- int fooInt1, fooInt2, fooInt3;
- /*
- * Variable Initialization
- */
-
- // Initialize a variable using =
- int fooInt = 1;
- // Initialize multiple variables of same type with same value , , =
- int fooInt1, fooInt2, fooInt3;
- fooInt1 = fooInt2 = fooInt3 = 1;
-
- /*
- * Variable types
- */
+ // Declare a variable using
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
@@ -437,26 +402,26 @@ class PennyFarthing extends Bicycle {
// Example - Food:
public interface Edible {
- public void eat(); // Any class that implements this interface, must
+ public void eat(); // Any class that implements this interface, must
// implement this method.
}
public interface Digestible {
- public void digest();
+ public void digest();
}
// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
@Override
- public void eat() {
- // ...
- }
+ public void eat() {
+ // ...
+ }
@Override
- public void digest() {
- // ...
- }
+ public void digest() {
+ // ...
+ }
}
// In Java, you can extend only one class, but you can implement many
@@ -464,51 +429,10 @@ public class Fruit implements Edible, Digestible {
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
- public void InterfaceOneMethod() {
- }
+ public void InterfaceOneMethod() {
+ }
@Override
- public void InterfaceTwoMethod() {
- }
+ public void InterfaceTwoMethod() {
+ }
}
-```
-
-## Further Reading
-
-The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
-
-**Official Oracle Guides**:
-
-* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
-
-* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
-
-* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
- * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
- * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
- * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
-
-* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
-
-* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
-
-* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
-
-* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
-
-**Online Practice and Tutorials**
-
-* [Learneroo.com - Learn Java](http://www.learneroo.com)
-
-* [Codingbat.com](http://codingbat.com/java)
-
-
-**Books**:
-
-* [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)
--
cgit v1.2.3
From c7240369b6465f2a736cb61d1bff89c971e76929 Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:47:17 -0500
Subject: Update java.html.markdown
---
java.html.markdown | 80 ++++++++++++++++++++++++++++++++++++++++++++++--------
1 file changed, 68 insertions(+), 12 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 745741f8..928eb39f 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -1,3 +1,18 @@
+---
+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/"]
+filename: LearnJava.java
+---
+
+Java is a general-purpose, concurrent, class-based, object-oriented computer
+programming language.
+[Read more here.](http://docs.oracle.com/javase/tutorial/java/)
+
+```java
// Single-line comments start with //
/*
Multi-line comments look like this.
@@ -402,26 +417,26 @@ class PennyFarthing extends Bicycle {
// Example - Food:
public interface Edible {
- public void eat(); // Any class that implements this interface, must
+ public void eat(); // Any class that implements this interface, must
// implement this method.
}
public interface Digestible {
- public void digest();
+ public void digest();
}
// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
@Override
- public void eat() {
- // ...
- }
+ public void eat() {
+ // ...
+ }
@Override
- public void digest() {
- // ...
- }
+ public void digest() {
+ // ...
+ }
}
// In Java, you can extend only one class, but you can implement many
@@ -429,10 +444,51 @@ public class Fruit implements Edible, Digestible {
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
- public void InterfaceOneMethod() {
- }
+ public void InterfaceOneMethod() {
+ }
@Override
- public void InterfaceTwoMethod() {
- }
+ public void InterfaceTwoMethod() {
+ }
}
+```
+
+## Further Reading
+
+The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
+
+**Official Oracle Guides**:
+
+* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+
+* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+
+**Online Practice and Tutorials**
+
+* [Learneroo.com - Learn Java](http://www.learneroo.com)
+
+* [Codingbat.com](http://codingbat.com/java)
+
+
+**Books**:
+
+* [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)
--
cgit v1.2.3
From 63793af2e955f8a8abe698c4a70809cfbff63452 Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:54:09 -0500
Subject: Added section on how to declare and initialize both single varible
and multiple varibles with the same value. Important concept for large
structured programs. Seperated this a little bit.
---
java.html.markdown | 24 ++++++++++++++++++++++--
php.html.markdown | 4 +---
2 files changed, 23 insertions(+), 5 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 928eb39f..1aa06570 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -47,10 +47,30 @@ public class LearnJava {
///////////////////////////////////////
- // Types & Variables
+ // Variables
///////////////////////////////////////
-
+
+ /*
+ * Variable Declaration
+ */
// Declare a variable using
+ int fooInt;
+ // Declare multiple variables of the same type , ,
+ int fooInt1, fooInt2, fooInt3;
+
+ /*
+ * Variable Initialization
+ */
+
+ // Initialize a variable using =
+ int fooInt = 1;
+ // Initialize multiple variables of same type with same value , , =
+ int fooInt1, fooInt2, fooInt3;
+ fooInt1 = fooInt2 = fooInt3 = 1;
+
+ /*
+ * Variable types
+ */
// Byte - 8-bit signed two's complement integer
// (-128 <= byte <= 127)
byte fooByte = 100;
diff --git a/php.html.markdown b/php.html.markdown
index 86fb14e5..1c2204fd 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -101,9 +101,7 @@ $sgl_quotes
END;
// String concatenation is done with .
-echo 'This string ' . 'is concatenated';
-// Strings concatenation can also be combined with html elements
-echo 'This string is' . '' . 'bold with strong tags ' . '.'
+echo 'This string ' . 'is concatenated';
/********************************
--
cgit v1.2.3
From 4e139ae2f528a08eb47427ea790bd176092e1bf0 Mon Sep 17 00:00:00 2001
From: Dhwani Shah
Date: Fri, 2 Oct 2015 14:57:39 -0500
Subject: unneeded change fixed
---
php.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/php.html.markdown b/php.html.markdown
index 1c2204fd..d4131992 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -101,7 +101,7 @@ $sgl_quotes
END;
// String concatenation is done with .
-echo 'This string ' . 'is concatenated';
+echo 'This string ' . 'is concatenated';
/********************************
@@ -689,4 +689,4 @@ If you're coming from a language with good package management, check out
[Composer](http://getcomposer.org/).
For common standards, visit the PHP Framework Interoperability Group's
-[PSR standards](https://github.com/php-fig/fig-standards).
+[PSR standards](https://github.com/php-fig/fig-standards).
\ No newline at end of file
--
cgit v1.2.3
From 18058567c4e7570ca7fd053299eefd0d36658329 Mon Sep 17 00:00:00 2001
From: Matteo Taroli
Date: Fri, 2 Oct 2015 22:17:16 +0200
Subject: Add French translation for Perl 5
---
fr-fr/perl-fr.html.markdown | 166 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 166 insertions(+)
create mode 100644 fr-fr/perl-fr.html.markdown
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
new file mode 100644
index 00000000..7a061da7
--- /dev/null
+++ b/fr-fr/perl-fr.html.markdown
@@ -0,0 +1,166 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-fr.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+translators:
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+lang: fr-fr
+---
+Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+
+Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
+
+```perl
+# Les commentaires en une ligne commencent par un dièse
+
+
+#### Types de variables de Perl
+
+# Les variables comment par un symbole précisant le type.
+# Un nom de variable valide commence par une lettre ou un underscore,
+# suivi d'un nombre quelconque de lettres, chiffres ou underscores.
+
+### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
+
+## Scalaires
+# Un scalaire représente une valeure unique :
+my $animal = "chameau";
+my $reponse = 42;
+
+# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante
+# et Perl les convertira automatiquement entre elles quand nécessaire.
+
+## Tableaux
+# Un tableau représente une liste de valeurs :
+my @animaux = ("chameau", "lama", "chouette");
+my @nombres = (23, 42, 69);
+my @melange = ("chameau", 42, 1.23);
+
+## Hashes
+# Un hash représente un ensemble de paires de clé/valeur :
+my %fruit_couleur = ("pomme", "rouge", "banane", "jaune");
+
+# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment :
+
+my %fruit_couleur = (
+ pomme => "rouge",
+ banane => "jaune"
+);
+
+# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata
+# (perldoc perldata)
+
+# Des types de données plus complexes peuvent être construits en utilisant des références,
+# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes.
+
+#### Conditions et boucles
+
+# Perl possède la plupart des conditions et boucles habituelles.
+
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (condition) {
+ ...
+}
+# Ceci est fourni en tant que version plus lisible de "if (!condition)"
+
+# la postcondition à la sauce Perl
+
+print "Yow!" if $zippy;
+print "Nous n'avons pas de banane." unless $bananes;
+
+# while
+while (condition) {
+ ...
+}
+
+# boucle for et iteration
+for (my $i = 0; $i < $max; $i++) {
+ print "l'index est $i";
+}
+
+for (my $i = 0; $i < @elements; $i++) {
+ print "L'élément courant est " . $elements[$i];
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+# implicitement
+
+for (@elements) {
+ print;
+}
+
+
+#### Expressions régulières
+
+# Le support des expressions régulières par Perl est aussi large que profond
+# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs.
+# Cependant, pour faire court :
+
+# Simple correspondance
+if (/foo/) { ... } # vrai si $_ contient "foo"
+if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
+
+# Simple substitution
+
+$a =~ s/foo/bar/; # remplace foo par bar dans $a
+$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
+
+
+#### Fichiers and E/S
+
+# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
+
+open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!";
+open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!";
+open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
+
+# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>".
+# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier
+# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un
+# élément de la liste :
+
+my $ligne = <$in>
+my $lignes = <$in>
+
+#### Ecrire des sous-programmes
+
+# Ecrire des sous-programmes est facile :
+
+sub logger {
+ my $logmessage = shift;
+
+ open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!";
+
+ print $logfile $logmessage;
+}
+
+# Maintenant, nous pouvons utiliser le sous-programme comme n'importe quelle fonction intégrée :
+
+logger("On a un sous-programme de logging!!");
+```
+
+#### Utiliser des modules Perl
+
+Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl.
+
+Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser.
+
+#### Pour en savoir plus
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn at www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - and perl built-in : `perldoc perlintro`
--
cgit v1.2.3
From 7184d7b61d99d2de93e19edb129ea3d17809be7f Mon Sep 17 00:00:00 2001
From: Zachary Ferguson
Date: Fri, 2 Oct 2015 17:24:36 -0400
Subject: Changed [python3/en]
Compared is and ==.
Noted that tuples of length 1 require an ending
comma.
Discussed that keys of dictionaries have to be immutable.
Added
that elements of a set have to be immutable.
Included an explanation of
returning multiple values with tuple assignments.
Added some clarifying
remarks to comments.
---
python3.html.markdown | 51 ++++++++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 48 insertions(+), 3 deletions(-)
diff --git a/python3.html.markdown b/python3.html.markdown
index b3acb122..d70c5462 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -4,6 +4,7 @@ contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
filename: learnpython3.py
---
@@ -36,7 +37,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
8 - 1 # => 7
10 * 2 # => 20
-# Except division which returns floats by default
+# Except division which returns floats, real numbers, by default
35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative.
@@ -51,13 +52,13 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
# Modulo operation
7 % 3 # => 1
-# Exponentiation (x to the yth power)
+# Exponentiation (x**y, x to the yth power)
2**4 # => 16
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
-# Boolean values are primitives
+# Boolean values are primitives (Note: the capitalization)
True
False
@@ -95,6 +96,16 @@ False or True #=> True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
+# (is vs. ==) is checks if two variable refer to the same object, but == checks
+# if the objects pointed to have the same values.
+a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b = a # Point b at what a is pointing to
+b is a # => True, a and b refer to the same object
+b == a # => True, a's and b's objects are equal
+b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b is a # => False, a and b do not refer to the same object
+b == a # => True, a's and b's objects are equal
+
# Strings are created with " or '
"This is a string."
'This is also a string.'
@@ -145,6 +156,10 @@ bool({}) #=> False
# Python has a print function
print("I'm Python. Nice to meet you!")
+# By default the print function also prints out a newline at the end.
+# Use the optional argument end to change the end character.
+print("I'm Python. Nice to meet you!", end="")
+
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
some_var = 5
@@ -191,6 +206,9 @@ li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
+# Make a one layer deep copy using slices
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
@@ -213,6 +231,12 @@ tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # Raises a TypeError
+# Note that a tuple of length one has to have a comma after the last element but
+# tuples of other lengths, even zero, do not.
+type((1)) # =>
+type((1,)) # =>
+type(()) # =>
+
# You can do most of the list operations on tuples too
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
@@ -232,6 +256,12 @@ empty_dict = {}
# Here is a prefilled dictionary
filled_dict = {"one": 1, "two": 2, "three": 3}
+# Note keys for dictionaries have to be immutable types. This is to ensure that
+# the key can be converted to a constant hash value for quick look-ups.
+# Immutable types include ints, floats, strings, tuples.
+invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+
# Look up values with []
filled_dict["one"] # => 1
@@ -278,6 +308,10 @@ empty_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+# Similar to keys of a dictionary, elements of a set have to be immutable.
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
+
# Can set new variables to a set
filled_set = some_set
@@ -299,6 +333,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6}
10 in filled_set # => False
+
####################################################
## 3. Control Flow and Iterables
####################################################
@@ -464,6 +499,16 @@ all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+# Returning multiple values (with tuple assignments)
+def swap(x, y):
+ return y, x # Return multiple values as a tuple
+ # (Note: parenthesis have been excluded but can be included)
+# return (y, x) # Just as valid as the above example.
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included.
# Function Scope
x = 5
--
cgit v1.2.3
From e77db2429dcc3422517763edf69efa3aaf234c05 Mon Sep 17 00:00:00 2001
From: Deivuh
Date: Fri, 2 Oct 2015 16:47:19 -0600
Subject: Added es-es translation to Swift
---
es-es/swift-es.html.markdown | 584 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 584 insertions(+)
create mode 100644 es-es/swift-es.html.markdown
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
new file mode 100644
index 00000000..81191841
--- /dev/null
+++ b/es-es/swift-es.html.markdown
@@ -0,0 +1,584 @@
+---
+language: swift
+contributors:
+ - ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Anthony Nguyen", "http://github.com/anthonyn60"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: learnswift.swift
+---
+
+Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia de desarrolladores de Apple.
+
+Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
+
+The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
+El libro oficial de Apple, [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329), se encuentra disponible en iBooks.
+
+Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), el cual tiene un completo tutorial de Swift.
+
+
+```swift
+// Importar un módulo
+import UIKit
+
+//
+// MARK: Básicos
+//
+
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la barra de saltos.
+// MARK: Marca de sección
+// TODO: Hacer algo pronto
+// FIXME: Arreglar este código
+
+// En Swift 2, println y print fueron combinados en un solo método print. Print añade una nueva línea automáticamente.
+print("Hola, mundo") // println ahora es print
+print("Hola, mundo", appendNewLine: false) // print sin agregar una nueva línea
+
+// Valores de variables (var) pueden cambiar después de ser asignados
+// Valores de constrantes (let) no pueden cambiarse después de ser asignados
+
+var myVariable = 42
+let øπΩ = "value" // nombres de variable unicode
+let π = 3.1415926
+let convenience = "keyword" // nombre de variable contextual
+let weak = "keyword"; let override = "another keyword" // declaraciones pueden ser separadas por punto y coma
+let `class` = "keyword" // Acentos abiertos permite utilizar palabras clave como nombres de variable
+let explicitDouble: Double = 70
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Conversión (casting)
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
+
+// Valos específicos de la construcción (build)
+// utiliza la configuración -D
+#if false
+ print("No impreso")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+print("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Las opcionales son un aspecto del lenguaje Swift que permite el almacenamiento de un valor `Some` (algo) o `None` (nada).
+
+ Debido a que Swift requiere que cada propiedad tenga un valor, hasta un valor 'nil' debe de ser explicitamente almacenado como un valor opcional.
+
+ Optional es un enum.
+*/
+var someOptionalString: String? = "opcional" // Puede ser nil
+// Al igual que lo anterior, pero ? es un operador postfix (sufijo)
+var someOptionalString2: Optional = "opcional"
+
+if someOptionalString != nil {
+ // No soy nil
+ if someOptionalString!.hasPrefix("opt") {
+ print("Tiene el prefijo")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// Opcional implícitamente desenvuelto
+var unwrappedString: String! = "Un valor esperado."
+// Al igual que lo anterior, pero ! es un operador postfix (sufijo)
+var unwrappedString2: ImplicitlyUnwrappedOptional = "Un valor esperado."
+
+if let someOptionalStringConstant = someOptionalString {
+ // tiene valor `Some` (algo), no nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // No tiene el prefijo
+ }
+}
+
+// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
+// AnyObject == id
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier valor (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
+
+/*
+ Comentar aquí
+
+ /*
+ Comentarios anidados también son soportados
+ */
+*/
+
+//
+// MARK: Colecciones
+//
+
+/*
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras). Así que `let` y `var` también indican si son mudables (var) o inmutables (let) durante la declaración de sus tipos.
+*/
+
+// Array (arreglo)
+var shoppingList = ["catfish", "water", "lemons"]
+shoppingList[1] = "bottle of water"
+let emptyArray = [String]() // let == inmutable
+let emptyArray2 = Array() // igual que lo anterior
+var emptyMutableArray = [String]() // var == mudable
+
+
+// Dictionary (diccionario)
+var occupations = [
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
+]
+occupations["Jayne"] = "Public Relations"
+let emptyDictionary = [String: Float]() // let == inmutable
+let emptyDictionary2 = Dictionary() // igual que lo anterior
+var emptyMutableDictionary = [String: Float]() // var == mudable
+
+
+//
+// MARK: Flujo de control
+//
+
+// Ciclo for (array)
+let myArray = [1, 1, 2, 3, 5]
+for value in myArray {
+ if value == 1 {
+ print("Uno!")
+ } else {
+ print("No es uno!")
+ }
+}
+
+// Ciclo for (dictionary)
+var dict = ["uno": 1, "dos": 2]
+for (key, value) in dict {
+ print("\(key): \(value)")
+}
+
+// Ciclo for (range)
+for i in -1...shoppingList.count {
+ print(i)
+}
+shoppingList[1...2] = ["steak", "peacons"]
+// Utilizar ..< para excluir el último valor
+
+// Ciclo while
+var i = 1
+while i < 1000 {
+ i *= 2
+}
+
+// Ciclo do-while
+do {
+ print("Hola")
+} while 1 == 2
+
+// Switch
+// Muy potente, se puede pensar como declaraciones `if`
+// Very powerful, think `if` statements with con azúcar sintáctico
+// Soportan String, instancias de objetos, y primitivos (Int, Double, etc)
+let vegetable = "red pepper"
+switch vegetable {
+case "celery":
+ let vegetableComment = "Add some raisins and make ants on a log."
+case "cucumber", "watercress":
+ let vegetableComment = "That would make a good tea sandwich."
+case let localScopeValue where localScopeValue.hasSuffix("pepper"):
+ let vegetableComment = "Is it a spicy \(localScopeValue)?"
+default: // required (in order to cover all possible input)
+ let vegetableComment = "Everything tastes good in soup."
+}
+
+
+//
+// MARK: Funciones
+//
+
+// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados
+// en funciones y pueden ser pasados como parámetros
+
+// Función en documentación de cabeceras Swift (formato reStructedText)
+
+/**
+ Una operación de saludo
+
+ - Una viñeta en la documentación
+ - Otra viñeta en la documentación
+
+ :param: name Un nombre
+ :param: day Un día
+ :returns: Un string que contiene el valor de name y day
+*/
+func greet(name: String, day: String) -> String {
+ return "Hola \(name), hoy es \(day)."
+}
+greet("Bob", "Martes")
+
+// Similar a lo anterior, a excepción del compartamiento de los parámetros de la función
+func greet2(requiredName: String, externalParamName localParamName: String) -> String {
+ return "Hola \(requiredName), hoy es el día \(localParamName)"
+}
+greet2(requiredName:"John", externalParamName: "Domingo")
+
+// Función que devuelve múltiples valores en una tupla
+func getGasPrices() -> (Double, Double, Double) {
+ return (3.59, 3.69, 3.79)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignorar tupla (u otros) valores utilizando _ (guión bajo)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
+
+// Cantidad variable de argumentos
+func setup(numbers: Int...) {
+ // Es un arreglo
+ let number = numbers[0]
+ let argCount = numbers.count
+}
+
+// Pasando y devolviendo funciones
+func makeIncrementer() -> (Int -> Int) {
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
+}
+var increment = makeIncrementer()
+increment(7)
+
+// Pasando como referencia
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+print(someIntB) // 7
+
+
+//
+// MARK: Closures
+//
+var numbers = [1, 2, 6]
+
+// Las funciones son un caso especial de closure ({})
+
+// Ejemplo de closure.
+// `->` Separa los argumentos del tipo de retorno
+// `in` Separa la cabecera del cuerpo del closure
+numbers.map({
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
+
+// Cuando se conoce el tipo, cono en lo anterior, se puede hacer esto
+numbers = numbers.map({ number in 3 * number })
+// o esto
+//numbers = numbers.map({ $0 * 3 })
+
+print(numbers) // [3, 6, 18]
+
+// Closure restante
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Bastante corto, debido a que el operador < infiere los tipos
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
+
+//
+// MARK: Estructuras
+//
+
+// Las estructuras y las clases tienen capacidades similares
+struct NamesTable {
+ let names = [String]()
+
+ // Subscript personalizado
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+// Las estructuras tienen un inicializador designado autogenerado (implícitamente)
+let namesTable = NamesTable(names: ["Me", "Them"])
+let name = namesTable[1]
+print("Name is \(name)") // Name is Them
+
+//
+// MARK: Clases
+//
+
+// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso
+// Éstos son: internal (predeterminado), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
+// Todos los métodos y las propiedades de una clase son public (públicas)
+// Si solo necesitas almacenar datos en un objecto estructurado,
+// debes de utilizar `struct`
+
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Getter y setter personalizado
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` es una variable implícita disponible para los setters
+ sideLength = newValue / 4
+ }
+ }
+
+ // Lazily loading (inicialización bajo demanda) a una propiedad
+ // subShape queda como nil (sin inicializar) hasta que getter es llamado
+ lazy var subShape = Rect(sideLength: 4)
+
+ // Si no necesitas un getter y setter personalizado
+ // pero aún quieres ejecutar código antes y después de hacer get o set
+ // a una propiedad, puedes utilizar `willSet` y `didSet`
+ var identifier: String = "defaultID" {
+ // El argumento `willSet` será el nombre de variable para el nuevo valor
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
+ }
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // Siempre poner super.init de último al momento de inicializar propiedades personalizadas
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
+ }
+}
+
+// Una clase simple `Square` que extiende de `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
+}
+
+var mySquare = Square()
+print(mySquare.getArea()) // 25
+mySquare.shrink()
+print(mySquare.sideLength) // 4
+
+// Conversión de tipo de instancia
+let aShape = mySquare as Shape
+
+// Comparar instancias, no es igual a == que compara objetos (equal to)
+if mySquare === mySquare {
+ print("Yep, it's mySquare")
+}
+
+// Inicialización (init) opcional
+class Circle: Shape {
+ var radius: Int
+ override func getArea() -> Int {
+ return 3 * radius * radius
+ }
+
+ // Un signo de interrogación como sufijo después de `init` es un init opcional
+ // que puede devolver nil
+ init?(radius: Int) {
+ self.radius = radius
+ super.init()
+
+ if radius <= 0 {
+ return nil
+ }
+ }
+}
+
+var myCircle = Circle(radius: 1)
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
+var myEmptyCircle = Circle(radius: -1)
+print(myEmptyCircle?.getArea()) // "nil"
+if let circle = myEmptyCircle {
+ // no será ejecutado debido a que myEmptyCircle es nil
+ print("circle is not nil")
+}
+
+
+//
+// MARK: Enums
+//
+
+
+// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo
+// Al igual que las clases, pueden contener métodos
+
+enum Suit {
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
+ }
+}
+
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner el tipo del enum
+// cuando la variable es declarada de manera explícita
+var suitValue: Suit = .Hearts
+
+// Enums de tipo no-entero requiere asignaciones de valores crudas directas
+enum BookName: String {
+ case John = "John"
+ case Luke = "Luke"
+}
+print("Name: \(BookName.John.rawValue)")
+
+// Enum con valores asociados
+enum Furniture {
+ // Asociación con Int
+ case Desk(height: Int)
+ // Asociación con String e Int
+ case Chair(String, Int)
+
+ func description() -> String {
+ switch self {
+ case .Desk(let height):
+ return "Desk with \(height) cm"
+ case .Chair(let brand, let height):
+ return "Chair of \(brand) with \(height) cm"
+ }
+ }
+}
+
+var desk: Furniture = .Desk(height: 80)
+print(desk.description()) // "Desk with 80 cm"
+var chair = Furniture.Chair("Foo", 40)
+print(chair.description()) // "Chair of Foo with 40 cm"
+
+
+//
+// MARK: Protocolos
+//
+
+// `protocol` puede requerir que los tipos tengan propiedades
+// de instancia específicas, métodos de instancia, métodos de tipo,
+// operadores, y subscripts
+
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+// Protocolos declarados con @objc permiten funciones opcionales,
+// que te permite evaluar conformidad
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ // Pon un signo de interrogación después de la propiedad opcional, método, o
+ // subscript para ignorar un valor nil y devolver nil en lugar de
+ // tirar un error de tiempo de ejecución ("optional chaining")
+ if let allow = self.delegate?.canReshape?() {
+ // test for delegate then for method
+ self.delegate?.reshaped?()
+ }
+ }
+}
+
+
+//
+// MARK: Otros
+//
+
+// `extension`: Agrega funcionalidades a tipos existentes
+
+// Square ahora se "conforma" al protocolo `Printable`
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+print("Square: \(mySquare)")
+
+// También puedes hacer extend a tipos prefabricados (built-in)
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
+
+// Generics: Similar Java y C#. Utiliza la palabra clave `where` para especificar
+// los requerimientos de los genéricos.
+
+func findIndex(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+print(foundAtIndex == 2) // true
+
+// Operadores:
+// Operadores personalizados puede empezar con los siguientes caracteres:
+// / = - + * % < > ! & | ^ . ~
+// o
+// Caracteres unicode: math, symbol, arrow, dingbat, y line/box.
+prefix operator !!! {}
+
+// Un operador prefix que triplica la longitud del lado cuando es utilizado
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// Valor actual
+print(mySquare.sideLength) // 4
+
+// Cambiar la longitud del lado utilizando el operador !!!, incrementa el tamaño por 3
+!!!mySquare
+print(mySquare.sideLength) // 12
+```
--
cgit v1.2.3
From f64a678b5c357f6ae9a82bfdb8feca8520c4d2b0 Mon Sep 17 00:00:00 2001
From: Deivuh
Date: Fri, 2 Oct 2015 16:53:39 -0600
Subject: Fixed Swift/es-es line lengths
---
es-es/swift-es.html.markdown | 63 ++++++++++++++++++++++++++------------------
1 file changed, 38 insertions(+), 25 deletions(-)
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
index 81191841..86f0aab6 100644
--- a/es-es/swift-es.html.markdown
+++ b/es-es/swift-es.html.markdown
@@ -11,12 +11,10 @@ lang: es-es
filename: learnswift.swift
---
-Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia de desarrolladores de Apple.
-
-Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
-
-The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
-El libro oficial de Apple, [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329), se encuentra disponible en iBooks.
+Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
+por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
+el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
+de desarrolladores de Apple.
Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), el cual tiene un completo tutorial de Swift.
@@ -29,14 +27,16 @@ import UIKit
// MARK: Básicos
//
-// XCode soporta referencias para anotar tu código y agregarlos a lista de la barra de saltos.
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la
+// barra de saltos.
// MARK: Marca de sección
// TODO: Hacer algo pronto
// FIXME: Arreglar este código
-// En Swift 2, println y print fueron combinados en un solo método print. Print añade una nueva línea automáticamente.
+// En Swift 2, println y print fueron combinados en un solo método print.
+// Print añade una nueva línea automáticamente.
print("Hola, mundo") // println ahora es print
-print("Hola, mundo", appendNewLine: false) // print sin agregar una nueva línea
+print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
// Valores de variables (var) pueden cambiar después de ser asignados
// Valores de constrantes (let) no pueden cambiarse después de ser asignados
@@ -45,8 +45,11 @@ var myVariable = 42
let øπΩ = "value" // nombres de variable unicode
let π = 3.1415926
let convenience = "keyword" // nombre de variable contextual
-let weak = "keyword"; let override = "another keyword" // declaraciones pueden ser separadas por punto y coma
-let `class` = "keyword" // Acentos abiertos permite utilizar palabras clave como nombres de variable
+// Las declaraciones pueden ser separadas por punto y coma (;)
+let weak = "keyword"; let override = "another keyword"
+// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
+// variable
+let `class` = "keyword"
let explicitDouble: Double = 70
let intValue = 0007 // 7
let largeIntValue = 77_000 // 77000
@@ -64,9 +67,12 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
print("Build value: \(buildValue)") // Build value: 7
/*
- Las opcionales son un aspecto del lenguaje Swift que permite el almacenamiento de un valor `Some` (algo) o `None` (nada).
+ Las opcionales son un aspecto del lenguaje Swift que permite el
+ almacenamiento de un valor `Some` (algo) o `None` (nada).
- Debido a que Swift requiere que cada propiedad tenga un valor, hasta un valor 'nil' debe de ser explicitamente almacenado como un valor opcional.
+ Debido a que Swift requiere que cada propiedad tenga un valor,
+ hasta un valor 'nil' debe de ser explicitamente almacenado como un
+ valor opcional.
Optional es un enum.
*/
@@ -98,7 +104,8 @@ if let someOptionalStringConstant = someOptionalString {
// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
// AnyObject == id
-// A diferencia de Objective-C `id`, AnyObject funciona con cualquier valor (Class, Int, struct, etc)
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
+// valor (Class, Int, struct, etc)
var anyObjectVar: AnyObject = 7
anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
@@ -115,7 +122,9 @@ anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible.
//
/*
- Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras). Así que `let` y `var` también indican si son mudables (var) o inmutables (let) durante la declaración de sus tipos.
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
+ Así que `let` y `var` también indican si son mudables (var) o
+ inmutables (let) durante la declaración de sus tipos.
*/
// Array (arreglo)
@@ -216,7 +225,8 @@ func greet(name: String, day: String) -> String {
}
greet("Bob", "Martes")
-// Similar a lo anterior, a excepción del compartamiento de los parámetros de la función
+// Similar a lo anterior, a excepción del compartamiento de los parámetros
+// de la función
func greet2(requiredName: String, externalParamName localParamName: String) -> String {
return "Hola \(requiredName), hoy es el día \(localParamName)"
}
@@ -362,7 +372,8 @@ internal class Rect: Shape {
init(sideLength: Int) {
self.sideLength = sideLength
- // Siempre poner super.init de último al momento de inicializar propiedades personalizadas
+ // Siempre poner super.init de último al momento de inicializar propiedades
+ // personalizadas
super.init()
}
@@ -447,8 +458,8 @@ enum Suit {
}
}
-// Los valores de enum permite la sintaxis corta, sin necesidad de poner el tipo del enum
-// cuando la variable es declarada de manera explícita
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner
+// el tipo del enum cuando la variable es declarada de manera explícita
var suitValue: Suit = .Hearts
// Enums de tipo no-entero requiere asignaciones de valores crudas directas
@@ -508,9 +519,10 @@ class MyShape: Rect {
func grow() {
sideLength += 2
- // Pon un signo de interrogación después de la propiedad opcional, método, o
- // subscript para ignorar un valor nil y devolver nil en lugar de
- // tirar un error de tiempo de ejecución ("optional chaining")
+ // Pon un signo de interrogación después de la propiedad opcional,
+ // método, o subscript para ignorar un valor nil y devolver nil
+ // en lugar de tirar un error de tiempo de ejecución
+ // ("optional chaining")
if let allow = self.delegate?.canReshape?() {
// test for delegate then for method
self.delegate?.reshaped?()
@@ -548,8 +560,8 @@ extension Int {
print(7.customProperty) // "This is 7"
print(14.multiplyBy(3)) // 42
-// Generics: Similar Java y C#. Utiliza la palabra clave `where` para especificar
-// los requerimientos de los genéricos.
+// Generics: Similar Java y C#. Utiliza la palabra clave `where` para
+// especificar los requerimientos de los genéricos.
func findIndex(array: [T], valueToFind: T) -> Int? {
for (index, value) in enumerate(array) {
@@ -578,7 +590,8 @@ prefix func !!! (inout shape: Square) -> Square {
// Valor actual
print(mySquare.sideLength) // 4
-// Cambiar la longitud del lado utilizando el operador !!!, incrementa el tamaño por 3
+// Cambiar la longitud del lado utilizando el operador !!!,
+// incrementa el tamaño por 3
!!!mySquare
print(mySquare.sideLength) // 12
```
--
cgit v1.2.3
From b98afb4be5e5457b1f42b57eaa20599fabb461fa Mon Sep 17 00:00:00 2001
From: Jesus Tinoco
Date: Sat, 3 Oct 2015 10:43:25 +0200
Subject: Fixing typo in python3-es.html.markdown
---
es-es/python3-es.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown
index 1c69481a..3b997145 100644
--- a/es-es/python3-es.html.markdown
+++ b/es-es/python3-es.html.markdown
@@ -97,7 +97,7 @@ not False # => True
None # => None
# No uses el símbolo de igualdad `==` para comparar objetos con None
-# Usa `is` en lugar de
+# Usa `is` en su lugar
"etc" is None #=> False
None is None #=> True
@@ -383,7 +383,7 @@ def keyword_args(**kwargs):
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
-# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres
+# Puedes hacer ambas a la vez si quieres
def todos_los_argumentos(*args, **kwargs):
print args
print kwargs
@@ -511,7 +511,7 @@ def duplicar_numeros(iterable):
for i in iterable:
yield i + i
-# Un generador cera valores sobre la marcha.
+# Un generador crea valores sobre la marcha.
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
--
cgit v1.2.3
From b917d1524a06ca94b73d885bb678a4f4cd00a808 Mon Sep 17 00:00:00 2001
From: Jesus Tinoco
Date: Sat, 3 Oct 2015 10:50:48 +0200
Subject: Typos fixed in ruby-es.html.markdown
---
es-es/ruby-es.html.markdown | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown
index 66a5d0fe..1cf334e3 100644
--- a/es-es/ruby-es.html.markdown
+++ b/es-es/ruby-es.html.markdown
@@ -19,7 +19,7 @@ Nadie los usa.
Tu tampoco deberías
=end
-# Lo primero y principal: Todo es un objeto
+# En primer lugar: Todo es un objeto
# Los números son objetos
@@ -97,13 +97,13 @@ y #=> 10
# Por convención, usa snake_case para nombres de variables
snake_case = true
-# Usa nombres de variables descriptivos
+# Usa nombres de variables descriptivas
ruta_para_la_raiz_de_un_projecto = '/buen/nombre/'
ruta = '/mal/nombre/'
# Los símbolos (son objetos)
# Los símbolos son inmutables, constantes reusables representadas internamente por un
-# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
+# valor entero. Son normalmente usados en vez de strings para expresar eficientemente
# valores específicos y significativos
:pendiente.class #=> Symbol
@@ -130,7 +130,7 @@ arreglo = [1, "hola", false] #=> => [1, "hola", false]
arreglo[0] #=> 1
arreglo[12] #=> nil
-# Tal como la aritmética, el acceso como variable[índice]
+# Al igual que en aritmética, el acceso como variable[índice]
# es sólo azúcar sintáctica
# para llamar el método [] de un objeto
arreglo.[] 0 #=> 1
--
cgit v1.2.3
From 97c3800ea0ae11769c3661f3ab2cfa926e03d866 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Joa=CC=83o=20Costa?=
Date: Sat, 3 Oct 2015 16:18:03 +0100
Subject: Add pt-pt translation for Scala tutorial
---
pt-pt/scala-pt.html.markdown | 651 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 651 insertions(+)
create mode 100644 pt-pt/scala-pt.html.markdown
diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown
new file mode 100644
index 00000000..68f7b12a
--- /dev/null
+++ b/pt-pt/scala-pt.html.markdown
@@ -0,0 +1,651 @@
+---
+language: Scala
+filename: learnscala.scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
+ - ["Ha-Duong Nguyen", "http://reference-error.org"]
+translators:
+ - ["João Costa", "http://joaocosta.eu"]
+lang: pt-pt
+filename: learn-pt.scala
+---
+
+Scala - a linguagem escalável
+
+```scala
+
+/*
+ Prepare tudo:
+
+ 1) Faça Download do Scala - http://www.scala-lang.org/downloads
+ 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na
+ variável de ambiente `PATH`
+ 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer:
+
+ scala>
+
+ Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete).
+ Pode escrever qualquer expressão de Scala e o resultado será imprimido.
+ Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já,
+ vamos começar com os básicos.
+
+*/
+
+
+/////////////////////////////////////////////////
+// 1. Basicos
+/////////////////////////////////////////////////
+
+// Uma linha de comentários é marcada com duas barras
+
+/*
+ Comentários de multiplas linhas, como se pode ver neste exemplo, são assim.
+*/
+
+// Imprimir, forçando uma nova linha no final
+println("Hello world!")
+println(10)
+
+// Imprimir, sem forçar uma nova linha no final
+print("Hello world")
+
+// Valores são declarados com var ou val.
+// As declarações val são imutáveis, enquanto que vars são mutáveis.
+// A immutabilidade é uma propriedade geralmente vantajosa.
+val x = 10 // x é agora 10
+x = 20 // erro: reatribuição de um val
+var y = 10
+y = 20 // y é agora 12
+
+/*
+ Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima
+ não especificamos um tipo. Isto é devido a uma funcionalidade chamada
+ inferência de tipos. Na maior parte dos casos, o compilador de scala consegue
+ inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre.
+ Podemos declarar o tipo de uma variável da seguinte forma:
+*/
+val z: Int = 10
+val a: Double = 1.0
+
+// Note a conversão automática de Int para Double: o resultado é 10.0, não 10
+val b: Double = 10
+
+// Valores booleanos
+true
+false
+
+// Operações booleanas
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+// A matemática funciona da maneira habitual
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
+
+
+// Avaliar expressões na REPL dá o tipo e valor do resultado
+
+1 + 7
+
+/* A linha acima resulta em:
+
+ scala> 1 + 7
+ res29: Int = 8
+
+ Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com
+ o valor 8.
+
+ Note que "res29" é um nome de uma variavel gerado sequencialmente para
+ armazenar os resultados das expressões que escreveu, por isso o resultado
+ pode ser ligeiramente diferente.
+*/
+
+"Strings em scala são rodeadas por aspas"
+'a' // Um caracter de Scala
+// 'Strings entre plicas não existem' <= Isto causa um erro
+
+// Strings tem os métodos de Java habituais definidos
+"olá mundo".length
+"olá mundo".substring(2, 6)
+"olá mundo".replace("á", "é")
+
+// Para além disso, também possuem métodos de Scala.
+// Ver: scala.collection.immutable.StringOps
+"olá mundo".take(5)
+"olá mundo".drop(5)
+
+// Interpolação de Strings: repare no prefixo "s"
+val n = 45
+s"Temos $n maçãs" // => "Temos 45 maçãs"
+
+// Expressões dentro de Strings interpoladas também são possíveis
+val a = Array(11, 9, 6)
+s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos."
+s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs."
+s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4"
+
+// Strings interpoladas são formatadas com o prefixo "f"
+f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25"
+f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454"
+
+// Strings prefixadas com "raw" ignoram caracteres especiais
+raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r."
+
+// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string:
+"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown""
+
+// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas
+val html = """"""
+
+
+/////////////////////////////////////////////////
+// 2. Funções
+/////////////////////////////////////////////////
+
+// Funções são definidas como:
+//
+// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... }
+//
+// Se vem de linugagens mais tradicionais, repare na omissão da palavra
+// return keyword. Em Scala, a ultima expressão de um bloco é o seu
+// valor de retorno
+def somaQuadrados(x: Int, y: Int): Int = {
+ val x2 = x * x
+ val y2 = y * y
+ x2 + y2
+}
+
+// As { } podem ser omitidas se o corpo da função for apenas uma expressão:
+def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y
+
+// A sintaxe para chamar funções deve ser familiar:
+somaQuadrados(3, 4) // => 25
+
+// Na maior parte dos casos (sendo funções recursivas a principal excepção), o
+// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos
+// é aplicada aos valores de retorno
+def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int
+
+// Funções podem ter parâmetros por omissão:
+def somaComOmissão(x: Int, y: Int = 5) = x + y
+somaComOmissão(1, 2) // => 3
+somaComOmissão(1) // => 6
+
+
+// Funções anónimas são definidas da seguinte forma:
+(x: Int) => x * x
+
+// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido
+// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma
+// funão que recebe Int e retorna Int.
+val quadrado: Int => Int = x => x * x
+
+// Funcões anónimas são chamadas como funções normais:
+quadrado(10) // => 100
+
+// Se cada argumento de uma função anónima for usado apenas uma vez, existe
+// uma forma ainda mais curta de os definir. Estas funções anónumas são
+// extremamente comuns, como será visto na secção sobre estruturas de dados.
+val somaUm: Int => Int = _ + 1
+val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3)
+
+somaUm(5) // => 6
+somaEstranha(2, 4) // => 16
+
+
+// O código return existe em Scala, mas apenas retorna do def mais interior
+// que o rodeia.
+// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros.
+// Não tem qualquer efeito em funções anónimas, por exemplo:
+def foo(x: Int): Int = {
+ val funcAnon: Int => Int = { z =>
+ if (z > 5)
+ return z // Esta linha faz com que z seja o retorno de foo!
+ else
+ z + 2 // Esta linha define o retorno de funcAnon
+ }
+ funcAnon(x) // Esta linha define o valor de retorno de foo
+}
+
+
+/////////////////////////////////////////////////
+// 3. Controlo de fluxo
+/////////////////////////////////////////////////
+
+1 to 5
+val r = 1 to 5
+r.foreach(println)
+
+r foreach println
+// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as
+// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis
+
+(5 to 1 by -1) foreach (println)
+
+// Ciclos while
+var i = 0
+while (i < 10) { println("i " + i); i += 1 }
+
+while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê?
+
+i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico -
+ // executa sequencialmente enquanto muda uma variável. Ciclos while são
+ // rápidos, por vezes até mais que ciclos de Java, mas combinadores e
+ // compreensões (usados anteriormente) são mais fáceis de entender e
+ // paralelizar
+
+// Um ciclo do while
+do {
+ println("x ainda é menor que 10")
+ x = x + 1
+} while (x < 10)
+
+// A forma idiomática em Scala de definir acções recorrentes é através de
+// recursão em cauda.
+// Funções recursivas necessitam de um tipo de retorno definido explicitamente.
+// Neste caso, é Unit.
+def mostraNumerosEntre(a: Int, b: Int): Unit = {
+ print(a)
+ if (a < b)
+ mostraNumerosEntre(a + 1, b)
+}
+mostraNumerosEntre(1, 14)
+
+
+// Condicionais
+
+val x = 10
+
+if (x == 1) println("yeah")
+if (x == 10) println("yeah")
+if (x == 11) println("yeah")
+if (x == 11) println ("yeah") else println("nay")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+
+/////////////////////////////////////////////////
+// 4. Estruturas de dados
+/////////////////////////////////////////////////
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Lança uma excepção
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Lança uma excepção
+
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+val s = Set(1, 3, 7)
+s(0)
+s(1)
+
+/* Veja a documentação de mapas de scala em -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+ * e verifique que a consegue aceder
+ */
+
+
+// Tuplos
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "três")
+
+(a, 2, "três")
+
+// Porquê ter isto?
+val divideInts = (x: Int, y: Int) => (x / y, x % y)
+
+divideInts(10, 3) // A função divideInts returna o resultado e o resto
+
+// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice
+// (começado em 1) do elemento
+val d = divideInts(10, 3)
+
+d._1
+
+d._2
+
+
+/////////////////////////////////////////////////
+// 5. Programação Orientada a Objectos
+/////////////////////////////////////////////////
+
+/*
+ Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples
+ (valores, funções, etc). Estas expressões são suficientes para executar no
+ interpretador da linha de comandos para testes rápidos, mas não podem existir
+ isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um
+ ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas
+ construções de topo permitidas são:
+
+ - object
+ - class
+ - case class
+ - trait
+
+ Vamos agora explicar o que são:
+*/
+
+// Classes são semelhantes a classes noutras linguagens. Os argumentos do
+// construtor são declarados após o nome da classe, sendo a inicialização feita
+// no corpo da classe.
+class Cão(rc: String) {
+ // Código de construção
+ var raça: String = rc
+
+ // Define um método chamado "ladra", que retorna uma String
+ def ladra = "Woof, woof!"
+
+ // Valores e métodos são assumidos como públicos, mas é possivel usar
+ // os códigos "protected" and "private".
+ private def dormir(horas: Int) =
+ println(s"Vou dormir por $horas horas")
+
+ // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima
+ // linha, a classe Cão é declarada como abstracta
+ // abstract class Cão(...) { ... }
+ // def persegue(oQue: String): String
+}
+
+val oMeuCão = new Cão("greyhound")
+println(oMeuCão.raça) // => "greyhound"
+println(oMeuCão.ladra) // => "Woof, woof!"
+
+
+// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum
+// que classes de Scala possuam um "objecto companheiro", onde o comportamento
+// por instância é capturado nas classes, equanto que o comportamento
+// relacionado com todas as instancias dessa classe ficam no objecto.
+// A diferença é semelhante a métodos de classes e métodos estáticos noutras
+// linguagens. Note que objectos e classes podem ter o mesmo nome.
+object Cão {
+ def raçasConhecidas = List("pitbull", "shepherd", "retriever")
+ def criarCão(raça: String) = new Cão(raça)
+}
+
+
+// Case classes são classes com funcionalidades extra incluidas. Uma questão
+// comum de iniciantes de scala é quando devem usar classes e quando devem usar
+// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se
+// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes
+// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal
+// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos
+// métods, sendo que estes raramente possuem efeitos secundários.
+case class Pessoa(nome: String, telefone: String)
+
+// Cria uma nova instancia. De notar que case classes não precisam de "new"
+val jorge = Pessoa("Jorge", "1234")
+val cátia = Pessoa("Cátia", "4567")
+
+// Case classes trazem algumas vantagens de borla, como acessores:
+jorge.telefone // => "1234"
+
+// Igualdade por campo (não é preciso fazer override do .equals)
+Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false
+
+// Cópia simples
+// outroJorge == Person("jorge", "9876")
+val outroJorge = jorge.copy(telefone = "9876")
+
+// Entre outras. Case classes também suportam correspondência de padrões de
+// borla, como pode ser visto de seguida.
+
+
+// Traits em breve!
+
+
+/////////////////////////////////////////////////
+// 6. Correspondência de Padrões
+/////////////////////////////////////////////////
+
+// A correspondência de padrões é uma funcionalidade poderosa e bastante
+// utilizada em Scala. Eis como fazer correspondência de padrões numa case class:
+// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de
+// breaks, a computação termina no primeiro sucesso.
+
+def reconhecePessoa(pessoa: Pessoa): String = pessoa match {
+ // Agora, especifique os padrões:
+ case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel
+ case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel
+ case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel
+}
+
+val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo.
+
+// A correspondência de padrões pode parecer familiar aos switches em linguagens
+// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer
+// correspondências com muito mais:
+def correspondeTudo(obj: Any): String = obj match {
+ // Pode-se corresponder valores:
+ case "Olá mundo" => "Recebi uma string Olá mundo."
+
+ // Corresponder por tipo:
+ case x: Double => "Recebi um Double: " + x
+
+ // Corresponder tendo em conta condições especificas:
+ case x: Int if x > 10000 => "Recebi um número bem grande!"
+
+ // Fazer correspondências com case classes (visto anteriormente):
+ case Pessoa(nome, tel) => s"Recebi o contacto para $nome!"
+
+ // Fazer correspondência com expressões regulares:
+ case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio"
+
+ // Corresponder tuplos:
+ case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c"
+
+ // Corresponder estruturas de dados:
+ case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c"
+
+ // Combinar padrões:
+ case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo"
+}
+
+// Na realidade, é possível fazer correspondência com qualquer objecto que
+// defina o método "unapply". Esta funcionalidade é tão poderosa que permite
+// definir funções sob a forma de padrões:
+val funcPaddrao: Pessoa => String = {
+ case Pessoa("Jorge", tel) => s"Número do Jorge: $tel"
+ case Pessoa(nome, tel) => s"Número de alguém: $tel"
+}
+
+
+/////////////////////////////////////////////////
+// 7. Programação Funcional
+/////////////////////////////////////////////////
+
+// Scala permite que funções e métodos retornem, ou recebam como parámetros,
+// outras funções ou métodos
+
+val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int
+List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento
+
+// Funções anónimas também podem ser usadas
+List(1, 2, 3) map (x => x + 10)
+
+// Sendo que o símbolo _ também pode ser usado se a função anónima só receber
+// um argumento. Este fica com o valor da variável
+List(1, 2, 3) map (_ + 10)
+
+// Se tanto o bloco como a função apenas receberem um argumento, o próprio
+// _ pode ser omitido
+List("Dom", "Bob", "Natalia") foreach println
+
+
+// Combinadores
+
+s.map(quadrado)
+
+val sQuadrado = s.map(quadrado)
+
+sQuadrado.filter(_ < 10)
+
+sQuadrado.reduce (_+_)
+
+// O método filter recebe um predicado (uma função de A => Boolean) e escolhe
+// todos os elementos que satisfazem o predicado
+List(1, 2, 3) filter (_ > 2) // List(3)
+case class Pessoa(nome: String, idade: Int)
+List(
+ Pessoa(nome = "Dom", idade = 23),
+ Pessoa(nome = "Bob", idade = 30)
+).filter(_.idade > 25) // List(Pessoa("Bob", 30))
+
+
+// O método foreach recebe uma função de A => Unit, executando essa função em
+// cada elemento da colecção
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// Compreensões For
+
+for { n <- s } yield quadrado(n)
+
+val nQuadrado2 = for { n <- s } yield quadrado(n)
+
+for { n <- nQuadrado2 if n < 10 } yield n
+
+for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado
+
+/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto
+ que uma compreensão define a relação entre dois conjuntos de dados. */
+
+
+/////////////////////////////////////////////////
+// 8. Implicitos
+/////////////////////////////////////////////////
+
+/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito
+ * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem
+ * resistir a tentação de usá-los até que compreendam não só como funcionam,
+ * mas também as melhores práticas. Apenas incluimos esta secção no tutorial
+ * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas
+ * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve
+ * para compreender como trabalhar com implicitos, não como declará-los.
+*/
+
+// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como
+// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5
+// nestes exemplos
+
+implicit val oMeuIntImplicito = 100
+implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça)
+
+// Por si só, a palavra implicit não altera o comportamento de um valor, sendo
+// que estes podem ser usados da forma habitual.
+oMeuIntImplicito + 2 // => 102
+aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull"
+
+// A diferença é que estes valores podem ser utilizados quando outro pedaço de
+// código "necessite" de uma valor implicito. Um exemplo são argumentos
+// implicitos de funções:
+def enviaCumprimentos(aQuem: String)(implicit quantos: Int) =
+ s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!"
+
+// Se dermos um valor a "quantos", a função comporta-se normalmente
+enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!"
+
+// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é
+// usado, neste caso, "oMeuInteiroImplicito"
+enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!"
+
+// Parâmentros implicitos de funções permitem-nos simular classes de tipos de
+// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação.
+// As seguintes linhas representam a mesma coisa
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
+
+
+// Outra situação em que o compilador prouca um implicito é se encontrar uma
+// expressão
+// obj.método(...)
+// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma
+// conversão implicita A => B, onde A é o tipo de obj, e B possui um método
+// chamado "método", a conversão é aplicada. Ou seja, tendo
+// aMinhaFunçãoImplicita definida, podemos dizer
+"Retriever".raça // => "Golden Retriever"
+"Sheperd".ladra // => "Woof, woof!"
+
+// Neste caso, a String é primeiro convertida para Cão usando a nossa funão,
+// sendo depois chamado o método apropriado. Esta é uma funcionalidade
+// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade,
+// ao definir a função implicita, o compilador deve lançar um aviso a insisitir
+// que só deve definir a função se souber o que está a fazer.
+
+
+/////////////////////////////////////////////////
+// 9. Misc
+/////////////////////////////////////////////////
+
+// Importar coisas
+import scala.collection.immutable.List
+
+// Importar todos os "sub pacotes"
+import scala.collection.immutable._
+
+// Importar multiplas classes numa linha
+import scala.collection.immutable.{List, Map}
+
+// Renomear uma classe importada usando '=>'
+import scala.collection.immutable.{List => ImmutableList}
+
+// Importar todas as classes excepto algumas. Set e Map são excluidos:
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala
+// com um método main:
+object Aplicação {
+ def main(args: Array[String]): Unit = {
+ // código aqui.
+ }
+}
+
+// Ficheiros podem conter várias classes o objectos. Compilar com scalac
+
+
+
+
+// Input e output
+
+// Ler um ficheiro linha a linha
+import scala.io.Source
+for(linha <- Source.fromFile("ficheiro.txt").getLines())
+ println(linha)
+
+// Escrever um ficheiro usando o PrintWriter de Java
+val writer = new PrintWriter("ficheiro.txt")
+writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator)
+writer.write("Outra linha aqui" + util.Properties.lineSeparator)
+writer.close()
+
+```
+
+## Mais recursos
+
+* [Scala for the impatient](http://horstmann.com/scala/)
+* [Twitter Scala school](http://twitter.github.io/scala_school/)
+* [The scala documentation](http://docs.scala-lang.org/)
+* [Try Scala in your browser](http://scalatutorials.com/tour/)
+* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
--
cgit v1.2.3
From 2e05ec8d955b62fef844bd460f5bb455e351d1d0 Mon Sep 17 00:00:00 2001
From: edholland
Date: Fri, 2 Oct 2015 02:26:04 +0200
Subject: Add clarification on bind / match with = op in erlang. Fixes #1139
---
erlang.html.markdown | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 8b67a76a..d0af7f05 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -25,6 +25,7 @@ filename: learnerlang.erl
%% 1. Variables and pattern matching.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% In Erlang new variables are bound with an `=` statement.
Num = 42. % All variable names must start with an uppercase letter.
% Erlang has single-assignment variables; if you try to assign a different
@@ -32,9 +33,11 @@ Num = 42. % All variable names must start with an uppercase letter.
Num = 43. % ** exception error: no match of right hand side value 43
% In most languages, `=` denotes an assignment statement. In Erlang, however,
-% `=` denotes a pattern-matching operation. `Lhs = Rhs` really means this:
-% evaluate the right side (`Rhs`), and then match the result against the
-% pattern on the left side (`Lhs`).
+% `=` denotes a pattern-matching operation. When an empty variable is used on the
+% left hand side of the `=` operator to is bound (assigned), but when a bound
+% varaible is used on the left hand side the following behaviour is observed.
+% `Lhs = Rhs` really means this: evaluate the right side (`Rhs`), and then
+% match the result against the pattern on the left side (`Lhs`).
Num = 7 * 6.
% Floating-point number.
--
cgit v1.2.3
From 61597e603f78dc0645517a13b0b258236e5a3563 Mon Sep 17 00:00:00 2001
From: Ed Holland
Date: Fri, 2 Oct 2015 01:11:10 +0100
Subject: Add section on eunit in erlang doc
---
erlang.html.markdown | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 8b67a76a..31cdcdab 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -299,6 +299,39 @@ CalculateArea ! {circle, 2}. % 12.56000000000000049738
% The shell is also a process; you can use `self` to get the current pid.
self(). % <0.41.0>
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 5. Testing with EUnit
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Unit tests can be written using EUnits's test generators and assert macros
+-module(fib).
+ -export([fib/1]).
+ -include_lib("eunit/include/eunit.hrl").
+
+ fib(0) -> 1;
+ fib(1) -> 1;
+ fib(N) when N > 1 -> fib(N-1) + fib(N-2).
+
+ fib_test_() ->
+ [?_assert(fib(0) =:= 1),
+ ?_assert(fib(1) =:= 1),
+ ?_assert(fib(2) =:= 2),
+ ?_assert(fib(3) =:= 3),
+ ?_assert(fib(4) =:= 5),
+ ?_assert(fib(5) =:= 8),
+ ?_assertException(error, function_clause, fib(-1)),
+ ?_assert(fib(31) =:= 2178309)
+ ].
+
+% EUnit will automatically export to a test() fucntion to allo running the tests
+% in the erlang shell
+fib:test()
+
+% The popular erlang build tool Rebar is also compatible with EUnit
+% ```
+% rebar eunit
+% ```
+
```
## References
--
cgit v1.2.3
From 466b51d9fa4a223014b0d1d79d3d55709c32373d Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Sat, 3 Oct 2015 13:49:07 -0300
Subject: [javascript pt-br] : 5. More about Objects; Constructors and
Prototypes
---
pt-br/javascript-pt.html.markdown | 134 ++++++++++++++++++++------------------
1 file changed, 69 insertions(+), 65 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 08448d0b..097a1a8e 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -340,75 +340,74 @@ function sayHelloInFiveSeconds(name){
sayHelloInFiveSeconds("Adam"); // Vai abrir um popup com "Hello, Adam!" em 5s
///////////////////////////////////
-// 5. More about Objects; Constructors and Prototypes
+// 5. Mais sobre Objetos; Construtores e Prototypes
-// Objects can contain functions.
+// Objetos podem conter funções.
var myObj = {
myFunc: function(){
- return "Hello world!";
+ return "Olá mundo!";
}
};
-myObj.myFunc(); // = "Hello world!"
+myObj.myFunc(); // = "Olá mundo!"
-// When functions attached to an object are called, they can access the object
-// they're attached to using the `this` keyword.
+// Quando uma função ligada a um objeto é chamada, ela pode acessar o objeto
+// da qual foi ligada usando a palavra-chave `this`.
myObj = {
- myString: "Hello world!",
+ myString: "Olá mundo!",
myFunc: function(){
return this.myString;
}
};
-myObj.myFunc(); // = "Hello world!"
+myObj.myFunc(); // = "Olá mundo!"
-// What this is set to has to do with how the function is called, not where
-// it's defined. So, our function doesn't work if it isn't called in the
-// context of the object.
+// O `this` só funciona para dentro do escopo do objeto, portanto, se chamarmos
+// um método do objeto fora de seu escopo, este não irá funcionar.
var myFunc = myObj.myFunc;
myFunc(); // = undefined
-// Inversely, a function can be assigned to the object and gain access to it
-// through `this`, even if it wasn't attached when it was defined.
+// Inversamente, uma função pode ser atribuída a um objeto e ganhar a acesso
+// através do `this`, até mesmo se ela não for chamada quando foi definida.
var myOtherFunc = function(){
return this.myString.toUpperCase();
}
myObj.myOtherFunc = myOtherFunc;
-myObj.myOtherFunc(); // = "HELLO WORLD!"
+myObj.myOtherFunc(); // = "OLÁ MUNDO!"
-// We can also specify a context for a function to execute in when we invoke it
-// using `call` or `apply`.
+// Nós podemos também especificar um contexto onde a função irá executar,
+// usando o `call` ou `apply`.
var anotherFunc = function(s){
return this.myString + s;
}
-anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+anotherFunc.call(myObj, " E Olá Lua!"); // = "Olá mundo! E Olá Lua!"
-// The `apply` function is nearly identical, but takes an array for an argument
-// list.
+// A função `apply` é praticamente a mesma coisa, mas ela pega um array
+// como lista de argumentos.
-anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+anotherFunc.apply(myObj, [" E Olá Sol!"]); // = "Olá mundo! E Olá Sol!"
-// This is useful when working with a function that accepts a sequence of
-// arguments and you want to pass an array.
+// Isto é util quando trabalhamos com uma função que aceita uma sequência de
+// argumentos e você quer passar um array.
Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6
-// But, `call` and `apply` are only temporary. When we want it to stick, we can
-// use `bind`.
+// Mas, o `call` e `apply` são somente temporários. Quando você quiser que
+// permaneça sempre no escopo, use `bind`.
var boundFunc = anotherFunc.bind(myObj);
-boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+boundFunc(" E Olá Saturno!"); // = "Olá mundo! E Olá Saturno!"
-// `bind` can also be used to partially apply (curry) a function.
+// `bind` também pode ser usado para parcialmente aplicar (curry) uma função.
var product = function(a, b){ return a * b; }
var doubler = product.bind(this, 2);
doubler(8); // = 16
-// When you call a function with the `new` keyword, a new object is created, and
-// made available to the function via the this keyword. Functions designed to be
-// called like that are called constructors.
+// Quando você invoca uma função com a palavra-chave `new`, um novo objeto
+// é criado, e fica disponível para a função pela palavra-chave `this`.
+// Funções são desenhadas para serem invocadas como se invocam os construtores.
var MyConstructor = function(){
this.myNumber = 5;
@@ -416,15 +415,17 @@ var MyConstructor = function(){
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5
-// Every JavaScript object has a 'prototype'. When you go to access a property
-// on an object that doesn't exist on the actual object, the interpreter will
-// look at its prototype.
+// Todo objeto JavaScript possui um `prototype`. Quando você tenta acessar
+// uma propriedade de um objeto que não existe no objeto atual, o interpretador
+// vai olhar imediatamente para o seu prototype.
+
+// Algumas implementações em JS deixam você acessar o objeto prototype com a
+// propriedade mágica `__proto__`. Enquanto isso é util para explicar
+// prototypes, não é parte de um padrão; nós vamos falar de algumas formas de
+// usar prototypes depois.
-// Some JS implementations let you access an object's prototype on the magic
-// property `__proto__`. While this is useful for explaining prototypes it's not
-// part of the standard; we'll get to standard ways of using prototypes later.
var myObj = {
- myString: "Hello world!"
+ myString: "Olá Mundo!"
};
var myPrototype = {
meaningOfLife: 42,
@@ -437,34 +438,36 @@ myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42
// This works for functions, too.
-myObj.myFunc(); // = "hello world!"
+// Isto funciona para funções, também.
+myObj.myFunc(); // = "olá mundo!"
-// Of course, if your property isn't on your prototype, the prototype's
-// prototype is searched, and so on.
+// É claro, se sua propriedade não está em seu prototype,
+// o prototype do prototype será procurado e por aí vai.
myPrototype.__proto__ = {
myBoolean: true
};
myObj.myBoolean; // = true
-// There's no copying involved here; each object stores a reference to its
-// prototype. This means we can alter the prototype and our changes will be
-// reflected everywhere.
+// Não há cópia envolvida aqui; cada objeto guarda uma referência do
+// prototype. Isso significa que podemos alterar o prototype e nossas mudanças
+// serão refletidas em qualquer lugar.
myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43
-// We mentioned that `__proto__` was non-standard, and there's no standard way to
-// change the prototype of an existing object. However, there are two ways to
-// create a new object with a given prototype.
-// The first is Object.create, which is a recent addition to JS, and therefore
-// not available in all implementations yet.
+// Nós mencionamos que o `__proto__` não é uma forma padrão, e não há uma
+// forma padrão de mudar o prototype de um objeto já existente. Entretanto,
+// existem duas formas de se criar um objeto com um dado prototype.
+
+// A primeira forma é `Object.create`, que é uma adição recente do JS,
+// e ainda não está disponível em todas as implementações.
var myObj = Object.create(myPrototype);
myObj.meaningOfLife; // = 43
-// The second way, which works anywhere, has to do with constructors.
-// Constructors have a property called prototype. This is *not* the prototype of
-// the constructor function itself; instead, it's the prototype that new objects
-// are given when they're created with that constructor and the new keyword.
+// A segunda forma, que funciona em qualquer lugar, é feita com construtores.
+// Construtores tem uma propriedade chamada prototype. Este *não* é o prototype
+// do construtor em si; ao invés disso, ele é o prototype dos novos objetos
+// criados pelo construtor.
MyConstructor.prototype = {
myNumber: 5,
getMyNumber: function(){
@@ -476,42 +479,43 @@ myNewObj2.getMyNumber(); // = 5
myNewObj2.myNumber = 6
myNewObj2.getMyNumber(); // = 6
-// Built-in types like strings and numbers also have constructors that create
-// equivalent wrapper objects.
+// Tipos originais da linguagem como strings e números também possuem
+// construtores equivalentes.
var myNumber = 12;
var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true
-// Except, they aren't exactly equivalent.
+// Exceto, que eles não são totalmente equivalentes.
typeof myNumber; // = 'number'
typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
- // This code won't execute, because 0 is falsy.
+ // O código não vai executar, porque 0 é um valor falso.
}
if (Number(0)){
- // This code *will* execute, because Number(0) is truthy.
+ // O código *vai* executar, porque `Number(0)` é um valor verdadeiro.
}
-// However, the wrapper objects and the regular builtins share a prototype, so
-// you can actually add functionality to a string, for instance.
+// Entretanto, esses objetos encapsulados e as funções originais compartilham
+// um mesmo prototype, portanto você pode adicionar funcionalidades a uma string,
+// por exemplo.
String.prototype.firstCharacter = function(){
return this.charAt(0);
}
"abc".firstCharacter(); // = "a"
-// This fact is often used in "polyfilling", which is implementing newer
-// features of JavaScript in an older subset of JavaScript, so that they can be
-// used in older environments such as outdated browsers.
+// Esse fato é usado para criar os chamados `polyfills`, que implementam
+// uma nova característica do Javascript em uma versão mais velha, para que
+// assim funcionem em ambientes mais velhos como browsers ultrapassados.
-// For instance, we mentioned that Object.create isn't yet available in all
-// implementations, but we can still use it with this polyfill:
+// Havíamos mencionado que `Object.create` não estava ainda disponível em
+// todos as implementações, mas nós podemos usá-lo com esse polyfill:
if (Object.create === undefined){ // don't overwrite it if it exists
Object.create = function(proto){
- // make a temporary constructor with the right prototype
+ // faz um construtor temporário com o prototype certo
var Constructor = function(){};
Constructor.prototype = proto;
- // then use it to create a new, appropriately-prototyped object
+ // então utiliza o new para criar um objeto prototype apropriado
return new Constructor();
}
}
--
cgit v1.2.3
From 46d509077f10fc9b04aaf69829526d4b8297798d Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Sat, 3 Oct 2015 14:03:54 -0300
Subject: [javascript pt-br] : Leitura Adicional
---
pt-br/javascript-pt.html.markdown | 43 ++++++++++++++++++++-------------------
1 file changed, 22 insertions(+), 21 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index 097a1a8e..f4b5ed2c 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -521,30 +521,31 @@ if (Object.create === undefined){ // don't overwrite it if it exists
}
```
-## Further Reading
-
-The [Mozilla Developer
-Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides
-excellent documentation for JavaScript as it's used in browsers. Plus, it's a
-wiki, so as you learn more you can help others out by sharing your own
-knowledge.
-
-MDN's [A re-introduction to
-JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-covers much of the concepts covered here in more detail. This guide has quite
-deliberately only covered the JavaScript language itself; if you want to learn
-more about how to use JavaScript in web pages, start by learning about the
+## Leitura Adicional
+
+O [Mozilla Developer
+Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma
+excelente documentação sobre Javascript e seu uso nos browsers. E mais,
+é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando
+os outros compartilhando do seu conhecimento.
+
+[Uma re-introdução do JavaScript pela MDN]
+(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala
+somente sobre a linguagem JavaScript em si; se você quiser aprender mais
+sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre
[Document Object
Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
-[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges.
+[Aprenda Javascript por Exemplos e com Desafios](http://www.learneroo.com/modules/64/nodes/350) é uma
+variação desse guia com desafios.
-[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
-guide of all the counter-intuitive parts of the language.
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia
+profundo de todas as partes do JavaScript.
-[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book.
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) é o guia clássico
+/ livro de referência.
-In addition to direct contributors to this article, some content is adapted
-from Louie Dinh's Python tutorial on this site, and the [JS
-Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
-on the Mozilla Developer Network.
+Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está
+nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+da Mozilla Developer Network.
--
cgit v1.2.3
From 261f7a249f13f3f13f5619f2a3202d0273010df2 Mon Sep 17 00:00:00 2001
From: DPS
Date: Sat, 3 Oct 2015 20:00:47 +0200
Subject: [git/de] fixed typo
---
de-de/git-de.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown
index c7b6ad86..43939129 100644
--- a/de-de/git-de.html.markdown
+++ b/de-de/git-de.html.markdown
@@ -48,7 +48,7 @@ Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichni
### .git-Verzeichnis (Teil des Repositorys)
-Das .git-Verzeichnis enth? alle Einstellung, Logs, Branches, den HEAD und mehr.
+Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und mehr.
[Ausführliche Übersicht](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
### Arbeitsverzeichnis (Teil des Repositorys)
--
cgit v1.2.3
From 4719d4707cbda05daab4e05e1c85655ff7abf2fd Mon Sep 17 00:00:00 2001
From: DPS
Date: Sat, 3 Oct 2015 20:20:03 +0200
Subject: [go/de] fixed typo
---
de-de/go-de.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index 83d59c8b..765372e0 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -312,7 +312,7 @@ Dokumentation lesen.
Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr
kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen
ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/).
-Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
+Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil
verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen
in der [offiziellen Dokumentation von Go](http://golang.org/pkg/).
--
cgit v1.2.3
From 6f29bcc20175a348f3b1dd606d8a0ace5d48fe54 Mon Sep 17 00:00:00 2001
From: Matthias Bussonnier
Date: Sat, 3 Oct 2015 15:39:37 -0700
Subject: Update Python-fr.html.markdown
Add Link to Python3 English article.
---
fr-fr/python-fr.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown
index 58a036ba..26cab55f 100644
--- a/fr-fr/python-fr.html.markdown
+++ b/fr-fr/python-fr.html.markdown
@@ -15,7 +15,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu
Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x
-Vous pourrez bientôt trouver un article pour Python 3!
+Vous pourrez bientôt trouver un article pour Python 3 an Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/).
```python
# Une ligne simple de commentaire commence par un dièse
--
cgit v1.2.3
From 998fdfdfcdff05cb0721841215addbcdd94d30b0 Mon Sep 17 00:00:00 2001
From: Matthias Bussonnier
Date: Sat, 3 Oct 2015 15:40:41 -0700
Subject: typo
---
fr-fr/python-fr.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown
index 26cab55f..5a03ecfc 100644
--- a/fr-fr/python-fr.html.markdown
+++ b/fr-fr/python-fr.html.markdown
@@ -15,7 +15,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu
Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service]
NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x
-Vous pourrez bientôt trouver un article pour Python 3 an Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/).
+Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/).
```python
# Une ligne simple de commentaire commence par un dièse
--
cgit v1.2.3
From 0d2863186231324b14e8d3a1d25aa8e44078aa68 Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Sat, 3 Oct 2015 21:03:58 -0300
Subject: Sync pt with original js
---
pt-br/javascript-pt.html.markdown | 3 ---
1 file changed, 3 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index f4b5ed2c..e39c6c8e 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -492,9 +492,6 @@ myNumber === myNumberObj; // = false
if (0){
// O código não vai executar, porque 0 é um valor falso.
}
-if (Number(0)){
- // O código *vai* executar, porque `Number(0)` é um valor verdadeiro.
-}
// Entretanto, esses objetos encapsulados e as funções originais compartilham
// um mesmo prototype, portanto você pode adicionar funcionalidades a uma string,
--
cgit v1.2.3
From 4206b4ccd04c8343e6becd58a2c9549e9593cbd6 Mon Sep 17 00:00:00 2001
From: David Stockton
Date: Sat, 3 Oct 2015 19:35:42 -0600
Subject: Correct usage of "it's" in javascript doc
---
json.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/json.html.markdown b/json.html.markdown
index f57b82b8..47a8cb21 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -49,7 +49,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
"alternative style": {
"comment": "check this out!"
- , "comma position": "doesn't matter - as long as its before the value, then its valid"
+ , "comma position": "doesn't matter - as long as it's before the value, then it's valid"
, "another comment": "how nice"
},
--
cgit v1.2.3
From eb35f7748a11e04f15cb9901a86702f881155b14 Mon Sep 17 00:00:00 2001
From: David Stockton
Date: Sat, 3 Oct 2015 19:40:02 -0600
Subject: Fix usage of "it's" in example comment for chapel
---
chapel.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index c8489371..05e5b867 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -1074,14 +1074,14 @@ Installing the Compiler
Chapel can be built and installed on your average 'nix machine (and cygwin).
[Download the latest release version](https://github.com/chapel-lang/chapel/releases/)
-and its as easy as
+and it's as easy as
1. `tar -xvf chapel-1.11.0.tar.gz`
2. `cd chapel-1.11.0`
3. `make`
4. `source util/setchplenv.bash # or .sh or .csh or .fish`
-You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc).
+You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop that command in a script that will get executed on startup (like .bashrc).
Chapel is easily installed with Brew for OS X
@@ -1100,4 +1100,4 @@ Notable arguments:
* `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable.
* `--set =`: set config param `` to `` at compile-time.
* `--main-module `: use the main() procedure found in the module `` as the executable's main.
- * `--module-dir `: includes `` in the module search path.
\ No newline at end of file
+ * `--module-dir `: includes `` in the module search path.
--
cgit v1.2.3
From 2ede63f54cb59b99c0d3da712814f5556a979660 Mon Sep 17 00:00:00 2001
From: David Stockton
Date: Sat, 3 Oct 2015 19:41:52 -0600
Subject: Fix incorrect "its" to "it is" in visual basic doc
---
visualbasic.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index 00d61843..f9906e96 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -236,7 +236,7 @@ Module Module1
'Nine
Private Sub IfElseStatement()
Console.Title = "If / Else Statement | Learn X in Y Minutes"
- 'Sometimes its important to consider more than two alternatives.
+ 'Sometimes it is important to consider more than two alternatives.
'Sometimes there are a good few others.
'When this is the case, more than one if statement would be required.
'An if statement is great for vending machines. Where the user enters a code.
--
cgit v1.2.3
From 9bc553c46ce9b7154ec7c82451d71608f4beda82 Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Sun, 4 Oct 2015 10:12:55 +0530
Subject: Update c++.html.markdown
Regarding issue #1216, Better explaining the Reference 'fooRef'.
---
c++.html.markdown | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/c++.html.markdown b/c++.html.markdown
index 4acc1b9d..bbd2f9a9 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -245,7 +245,13 @@ cout << fooRef; // Prints "I am foo. Hi!"
// Doesn't reassign "fooRef". This is the same as "foo = bar", and
// foo == "I am bar"
// after this line.
+cout << &fooRef << endl; //Prints address of fooRef
fooRef = bar;
+cout << &fooRef << endl; //Prints address of fooRef, AGAIN
+cout << fooRef; // Prints "I am bar"
+
+//The address of fooRef remains the same, i.e. it is still referring to foo.
+
const string& barRef = bar; // Create a const reference to bar.
// Like C, const values (and pointers and references) cannot be modified.
--
cgit v1.2.3
From c7e552c448c5a562a3ff5f442a7ed834aec04d9e Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Sun, 4 Oct 2015 10:34:31 +0530
Subject: Variable size array, user size input added. #1170
Fixed Issue #1170
Variable size array, user size input added.
---
c.html.markdown | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/c.html.markdown b/c.html.markdown
index 8e631de4..36621a9e 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -130,7 +130,9 @@ int main(void) {
// 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
- char buf[0x100];
+ int size;
+ scanf("%d", &size);
+ char buf[size];
fgets(buf, sizeof buf, stdin);
// strtoul parses a string to an unsigned integer
--
cgit v1.2.3
From 9b00510c452a24197f7b8d30dee1a5f170e3cdee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gerson=20L=C3=A1zaro?=
Date: Sun, 4 Oct 2015 00:09:26 -0500
Subject: =?UTF-8?q?[c++/es]=20a=C3=B1adido?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
es-es/c++-es.html.markdown | 829 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 829 insertions(+)
create mode 100644 es-es/c++-es.html.markdown
diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown
new file mode 100644
index 00000000..bcc775e5
--- /dev/null
+++ b/es-es/c++-es.html.markdown
@@ -0,0 +1,829 @@
+---
+language: c++
+filename: learncpp.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:
+ - ["Gerson Lázaro", "https://gersonlazaro.com"]
+lang: es-es
+---
+
+C++ es un lenguaje de programación de sistemas que,
+[de acuerdo a su inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
+fue diseñado para
+
+- ser un "mejor C"
+- soportar abstracción de datos
+- soportar programación orientada a objetos
+- soportar programación genérica
+
+Aunque su sintaxis puede ser más difícil o compleja que los nuevos lenguajes,
+es ampliamente utilizado, ya que compila instrucciones nativas que pueden ser
+directamente ejecutadas por el procesador y ofrece un estricto control sobre
+el hardware (como C), mientras ofrece características de alto nivel como
+genericidad, excepciones, y clases. Esta combinación de velocidad y
+funcionalidad hace de C ++ uno de los lenguajes de programación más utilizados.
+
+```c++
+////////////////////
+// Comparación con C
+////////////////////
+
+// C ++ es _casi_ un superconjunto de C y comparte su sintaxis básica para las
+// declaraciones de variables, tipos primitivos y funciones.
+
+// Al igual que en C, el punto de entrada de tu programa es una función llamada
+// main con un retorno de tipo entero.
+// Este valor sirve como código de salida del programa.
+// Mira http://en.wikipedia.org/wiki/Exit_status para mayor información.
+int main(int argc, char** argv)
+{
+ // Los argumentos de la línea de comandos se pasan por argc y argv de la
+ // misma manera que en C.
+ // argc indica el número de argumentos,
+ // y argv es un arreglo de strings de estilo C (char*)
+ // representando los argumentos.
+ // El primer argumento es el nombre con el que el programa es llamado.
+ // argc y argv pueden omitirse si no te preocupan los argumentos,
+ // dejando la definición de la función como int main ()
+
+ // Un estado de salida 0 indica éxito.
+ return 0;
+}
+
+// Sin embargo, C ++ varía en algunas de las siguientes maneras:
+
+// En C++, los caracteres literales son caracteres
+sizeof('c') == sizeof(char) == 1
+
+// En C, los caracteres literales son enteros
+sizeof('c') == sizeof(int)
+
+
+// C++ tiene prototipado estricto
+void func(); // función que no acepta argumentos
+
+// En C
+void func(); // función que puede aceptar cualquier número de argumentos
+
+// Use nullptr en lugar de NULL en C++
+int* ip = nullptr;
+
+// Las cabeceras (headers) estándar de C están disponibles en C ++,
+// pero tienen el prefijo "c" y no tienen sufijo .h.
+#include
+
+int main()
+{
+ printf("Hola mundo!\n");
+ return 0;
+}
+
+//////////////////////////
+// Sobrecarga de funciones
+//////////////////////////
+
+// C++ soporta sobrecarga de funciones
+// siempre que cada función tenga diferentes parámetros.
+
+void print(char const* myString)
+{
+ printf("String %s\n", myString);
+}
+
+void print(int myInt)
+{
+ printf("Mi entero es %d", myInt);
+}
+
+int main()
+{
+ print("Hello"); // Resolves to void print(const char*)
+ print(15); // Resolves to void print(int)
+}
+
+////////////////////////////////////
+// Argumentos de función por defecto
+////////////////////////////////////
+
+// Puedes proporcionar argumentos por defecto para una función si no son
+// proporcionados por quien la llama.
+
+void doSomethingWithInts(int a = 1, int b = 4)
+{
+ // Hacer algo con los enteros aqui
+}
+
+int main()
+{
+ doSomethingWithInts(); // a = 1, b = 4
+ doSomethingWithInts(20); // a = 20, b = 4
+ doSomethingWithInts(20, 5); // a = 20, b = 5
+}
+
+// Los argumentos predeterminados deben estar al final de la lista de argumentos.
+
+void invalidDeclaration(int a = 1, int b) // Error!
+{
+}
+
+/////////////////////
+// Espacios de nombre
+/////////////////////
+
+// Espacios de nombres proporcionan ámbitos separados para variable, función y
+// otras declaraciones.
+// Los espacios de nombres se pueden anidar.
+
+namespace First {
+ namespace Nested {
+ void foo()
+ {
+ printf("Esto es First::Nested::foo\n");
+ }
+ } // fin del nombre de espacio Nested
+} // fin del nombre de espacio First
+
+namespace Second {
+ void foo()
+ {
+ printf("Esto es Second::foo\n")
+ }
+}
+
+void foo()
+{
+ printf("Este es global: foo\n");
+}
+
+int main()
+{
+
+ // Incluye todos los símbolos del espacio de nombre Second en el ámbito
+ // actual. Tenga en cuenta que simplemente foo() no funciona, ya que ahora
+ // es ambigua si estamos llamando a foo en espacio de nombres Second o en
+ // el nivel superior.
+ using namespace Second;
+
+ Second::foo(); // imprime "Esto es Second::foo"
+ First::Nested::foo(); // imprime "Esto es First::Nested::foo"
+ ::foo(); // imprime "Este es global: foo"
+}
+
+/////////////////
+// Entrada/Salida
+/////////////////
+
+// La entrada y salida de C++ utiliza flujos (streams)
+// cin, cout, y cerr representan a stdin, stdout, y stderr.
+// << es el operador de inserción >> es el operador de extracción.
+
+
+#include // Incluir para el flujo de entrada/salida
+
+using namespace std; // Los streams estan en std namespace (libreria estandar)
+
+int main()
+{
+ int myInt;
+
+ // Imprime a la stdout (o terminal/pantalla)
+ cout << "Ingresa tu número favorito:\n";
+ // Toma una entrada
+ cin >> myInt;
+
+ // cout puede también ser formateado
+ cout << "Tu número favorito es " << myInt << "\n";
+ // imprime "Tu número favorito es "
+
+ cerr << "Usado para mensajes de error";
+}
+////////////////////
+// Cadenas (Strings)
+////////////////////
+
+// Las cadenas en C++ son objetos y tienen muchas funciones
+#include
+
+using namespace std; // Strings también estan en namespace std
+
+string myString = "Hola";
+string myOtherString = " Mundo";
+
+// + es usado para concatenar.
+cout << myString + myOtherString; // "Hola Mundo"
+
+cout << myString + " Tu"; // "Hola Tu"
+
+// Las cadenas en C++ son mutables y tienen valor semántico.
+myString.append(" Perro");
+cout << myString; // "Hola Perro"
+
+
+//////////////
+// Referencias
+//////////////
+
+// Además de punteros como los de C,
+// C++ tiene _references_.
+// Estos tipos de puntero no pueden ser reasignados una vez establecidos
+// Y no pueden ser nulos.
+// También tienen la misma sintaxis que la propia variable:
+// No es necesaria * para eliminar la referencia y
+// & (dirección) no se utiliza para la asignación.
+
+using namespace std;
+
+string foo = "Yo soy foo";
+string bar = "Yo soy bar";
+
+string& fooRef = foo; // Crea una referencia a foo.
+fooRef += ". Hola!"; // Modifica foo través de la referencia
+cout << fooRef; // Imprime "Yo soy foo. Hola!"
+
+// No trate de reasignar "fooRef". Esto es lo mismo que "foo = bar", y
+// foo == "Yo soy bar"
+// después de esta linea.
+fooRef = bar;
+
+const string& barRef = bar; // Crea una referencia constante a bar.
+// Como en C, los valores constantes (y punteros y referencias) no pueden ser
+// modificados.
+barRef += ". Hola!"; // Error, referencia constante no puede ser modificada.
+
+// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un
+// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código:
+string tempObjectFun() { ... }
+string retVal = tempObjectFun();
+
+// Lo que pasa en la segunda línea es en realidad:
+// - Un objeto de cadena es retornado desde tempObjectFun
+// - Una nueva cadena se construye con el objeto devuelto como argumento al
+// constructor
+// - El objeto devuelto es destruido
+// El objeto devuelto se llama objeto temporal. Objetos temporales son
+// creados cada vez que una función devuelve un objeto, y es destruido en el
+// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la
+// norma dice, pero los compiladores están autorizados a cambiar este
+// comportamiento. Busca "return value optimization" para ver mas detalles).
+// Así que en este código:
+foo(bar(tempObjectFun()))
+
+// Suponiendo que foo y bar existen, el objeto retornado de tempObjectFun es
+// pasado al bar, y se destruye antes de llamar foo.
+
+// Ahora, de vuelta a las referencias. La excepción a la regla "en el extremo
+// de la expresión encerrada" es si un objeto temporal se une a una
+// referencia constante, en cuyo caso su vida se extiende al ámbito actual:
+
+void constReferenceTempObjectFun() {
+ // ConstRef obtiene el objeto temporal, y es válido hasta el final de esta
+ // función.
+ const string& constRef = tempObjectFun();
+ ...
+}
+
+// Otro tipo de referencia introducida en C ++ 11 es específicamente para
+// objetos temporales. No se puede tener una variable de este tipo, pero tiene
+// prioridad en resolución de sobrecarga:
+
+void someFun(string& s) { ... } // Referencia regular
+void someFun(string&& s) { ... } // Referencia a objeto temporal
+
+string foo;
+someFun(foo); // Llama la función con referencia regular
+someFun(tempObjectFun()); // Llama la versión con referencia temporal
+
+// Por ejemplo, puedes ver estas dos versiones de constructores para
+// std::basic_string:
+basic_string(const basic_string& other);
+basic_string(basic_string&& other);
+
+// La idea es que si estamos construyendo una nueva cadena de un objeto temporal
+// (que va a ser destruido pronto de todos modos), podemos tener un constructor
+// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este
+// Concepto denominado "movimiento semántico".
+
+////////////////////////////////////////////
+// Clases y programación orientada a objetos
+////////////////////////////////////////////
+
+// Primer ejemplo de clases
+#include
+
+// Declara una clase.
+// Las clases son usualmente declaradas en archivos de cabeceras (.h o .hpp)
+class Dog {
+ // Variables y funciones de la clase son privados por defecto.
+ std::string name;
+ int weight;
+
+// Todos los miembros siguientes de este son públicos
+// Hasta que se encuentre "private" o "protected".
+// All members following this are public
+// until "private:" or "protected:" is found.
+public:
+
+ // Constructor por defecto
+ Dog();
+
+ // Declaraciones de funciones de la clase (implementaciones a seguir)
+ // Nota que usamos std::string aquí en lugar de colocar
+ // using namespace std;
+ // arriba.
+ // Nunca ponga una declaración "using namespace" en un encabezado.
+ void setName(const std::string& dogsName);
+
+ void setWeight(int dogsWeight);
+ // Funciones que no modifican el estado del objeto
+ // Deben marcarse como const.
+ // Esto le permite llamarlas si se envia una referencia constante al objeto.
+ // También tenga en cuenta que las funciones deben ser declaradas
+ // explícitamente como _virtual_ para que sea reemplazada en las clases
+ // derivadas.
+ // Las funciones no son virtuales por defecto por razones de rendimiento.
+ virtual void print() const;
+
+ // Las funciones también se pueden definir en el interior
+ // del cuerpo de la clase.
+ // Funciones definidas como tales están entre líneas automáticamente.
+ void bark() const { std::cout << name << " barks!\n"; }
+
+ // Junto a los constructores, C++ proporciona destructores.
+ // Estos son llamados cuando un objeto se elimina o está fuera del ámbito.
+ // Esto permite paradigmas potentes como RAII
+ // (mira abajo)
+ // El destructor debe ser virtual si una clase es dervada desde el;
+ // Si no es virtual, entonces la clase derivada destructor
+ // No será llamada si el objeto se destruye a través de una referencia de
+ // la clase base o puntero.
+ virtual ~Dog();
+
+
+
+}; // Un punto y coma debe seguir la definición de clase.
+
+// Las funciones de una clase son normalmente implementados en archivos .cpp.
+Dog::Dog()
+{
+ std::cout << "Un perro ha sido construido\n";
+}
+
+// Objetos (tales como cadenas) deben ser pasados por referencia
+// Si los estas modificando o referencia constante en caso contrario.
+void Dog::setName(const std::string& dogsName)
+{
+ name = dogsName;
+}
+
+void Dog::setWeight(int dogsWeight)
+{
+ weight = dogsWeight;
+}
+
+// Nota que "virtual" sólo se necesita en la declaración, no en la definición.
+void Dog::print() const
+{
+ std::cout << "El perro es " << name << " y pesa " << weight << "kg\n";
+}
+
+Dog::~Dog()
+{
+ cout << "Adiós " << name << "\n";
+}
+
+int main() {
+ Dog myDog; // imprime "Un perro ha sido construido"
+ myDog.setName("Barkley");
+ myDog.setWeight(10);
+ myDog.print(); // imprime "El perro es Barkley y pesa 10 kg"
+ return 0;
+} // imprime "Adiós Barkley"
+
+// Herencia:
+
+// Esta clase hereda todo lo público y protegido de la clase Dog
+class OwnedDog : public Dog {
+
+ void setOwner(const std::string& dogsOwner);
+
+ // Reemplaza el comportamiento de la función de impresión
+ // de todos los OwnedDogs. Mira
+ // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
+ // Para una introducción más general si no está familiarizado con el
+ // polimorfismo de subtipo.
+ // La palabra clave override es opcional, pero asegura que estás
+ // reemplazando el método de una clase base.
+ void print() const override;
+
+private:
+ std::string owner;
+};
+
+// Mientras tanto, en el archivo .cpp correspondiente:
+
+void OwnedDog::setOwner(const std::string& dogsOwner)
+{
+ owner = dogsOwner;
+}
+
+void OwnedDog::print() const
+{
+ Dog::print(); // Llama a la función de impresión en la clase base Dog
+ std::cout << "El perro es de " << owner << "\n";
+ // Imprime "El perro es y pesa "
+ // "El perro es de "
+}
+
+////////////////////////////////////////////
+// Inicialización y sobrecarga de operadores
+////////////////////////////////////////////
+
+// En C ++ se puede sobrecargar el comportamiento
+// de los operadores como +, -, *, /, etc.
+// Esto se hace mediante la definición de una función que es llamada
+// cada vez que se utiliza el operador.
+
+#include
+using namespace std;
+
+class Point {
+public:
+ // Las variables de la clase pueden dar valores por defecto de esta manera.
+ double x = 0;
+ double y = 0;
+
+ // Define un constructor por defecto que no hace nada
+ // pero inicializa el punto al valor por defecto (0, 0)
+ Point() { };
+
+ // The following syntax is known as an initialization list
+ // and is the proper way to initialize class member values
+ Point (double a, double b) :
+ x(a),
+ y(b)
+ { /* No hace nada excepto inicializar los valores */ }
+
+ // Sobrecarga el operador +
+ Point operator+(const Point& rhs) const;
+
+ // Sobrecarga el operador +=
+ Point& operator+=(const Point& rhs);
+
+ // También tendría sentido añadir los operadores - y -=,
+ // Pero vamos a omitirlos por razones de brevedad.
+};
+
+Point Point::operator+(const Point& rhs) const
+{
+ // Crea un nuevo punto que es la suma de este y 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);
+ // Llama al operador + de Point
+ // Point llama la función + con right como parámetro
+ Point result = up + right;
+ // Prints "Result is upright (1,1)"
+ cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
+ return 0;
+}
+
+/////////////////////////
+// Plantillas (Templates)
+/////////////////////////
+
+// Las plantillas en C++ se utilizan sobre todo en la programación genérica,
+// a pesar de que son mucho más poderoso que los constructores genéricos
+// en otros lenguajes. Ellos también soportan especialización explícita y
+// parcial y clases de tipo estilo funcional; de hecho, son un lenguaje
+// funcional Turing-completo incrustado en C ++!
+
+// Empezamos con el tipo de programación genérica que podría estar
+// familiarizado.
+// Para definir una clase o función que toma un parámetro de tipo:
+template
+class Box {
+public:
+ // En este caso, T puede ser usado como cualquier otro tipo.
+ void insert(const T&) { ... }
+};
+
+// Durante la compilación, el compilador realmente genera copias de cada
+// plantilla con parámetros sustituidos, por lo que la definición completa
+// de la clase debe estar presente en cada invocación.
+// Es por esto que usted verá clases de plantilla definidas
+// Enteramente en archivos de cabecera.
+
+//Para crear una instancia de una clase de plantilla en la pila:
+Box intBox;
+
+y puedes utilizarlo como era de esperar:
+intBox.insert(123);
+
+// Puedes, por supuesto, anidar plantillas:
+Box > boxOfBox;
+boxOfBox.insert(intBox);
+
+// Hasta C++11, había que colocar un espacio entre los dos '>'s,
+// de lo contrario '>>' serían analizados como el operador de desplazamiento
+// a la derecha.
+
+
+// A veces verás
+// template
+// en su lugar. La palabra clave "class" y las palabras clave "typename" son
+// mayormente intercambiables en este caso. Para la explicación completa, mira
+// http://en.wikipedia.org/wiki/Typename
+// (sí, esa palabra clave tiene su propia página de Wikipedia).
+
+// Del mismo modo, una plantilla de función:
+template
+void barkThreeTimes(const T& input)
+{
+ input.bark();
+ input.bark();
+ input.bark();
+}
+
+// Observe que no se especifica nada acerca de los tipos de parámetros aquí.
+// El compilador generará y comprobará cada invocación de la plantilla,
+// por lo que la función anterior funciona con cualquier tipo "T"
+// que tenga un método 'bark' constante!
+
+
+Dog fluffy;
+fluffy.setName("Fluffy")
+barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces.
+
+Los parámetros de la plantilla no tienen que ser las clases:
+template
+void printMessage() {
+ cout << "Aprende C++ en " << Y << " minutos!" << endl;
+}
+
+// Y usted puede especializar explícitamente plantillas
+// para código más eficiente.
+// Por supuesto, la mayor parte del mundo real que utiliza una especialización
+// no son tan triviales como esta.
+// Tenga en cuenta que usted todavía tiene que declarar la función (o clase)
+// como plantilla incluso si ha especificado de forma explícita todos
+// los parámetros.
+
+template<>
+void printMessage<10>() {
+ cout << "Aprende C++ rapido en solo 10 minutos!" << endl;
+}
+
+printMessage<20>(); // Prints "Aprende C++ en 20 minutos!"
+printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!"
+
+
+/////////////////////
+// Manejador de excepciones
+/////////////////////
+
+// La biblioteca estándar proporciona algunos tipos de excepción
+// (mira http://en.cppreference.com/w/cpp/error/exception)
+// pero cualquier tipo puede ser lanzado como una excepción
+#include
+#include
+
+//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser
+// capturados por los siguientes manejadores _catch_.
+try {
+ // No asignar excepciones en el heap usando _new_.
+ throw std::runtime_error("Ocurrió un problema");
+}
+
+// Captura excepciones por referencia const si son objetos
+catch (const std::exception& ex)
+{
+ std::cout << ex.what();
+}
+********************************************************************************
+// Captura cualquier excepción no capturada por bloques _catch_ anteriores
+catch (...)
+{
+ std::cout << "Excepción desconocida capturada";
+ throw; // Re-lanza la excepción
+}
+
+///////
+// RAII
+///////
+
+// RAII significa "Resource Acquisition Is Initialization"
+// (Adquisición de recursos es inicialización).
+// A menudo se considera el paradigma más poderoso en C++
+// Y el concepto es simple: un constructor de un objeto
+// Adquiere recursos de ese objeto y el destructor les libera.
+
+// Para entender cómo esto es útil,
+// Considere una función que utiliza un identificador de archivo C:
+void doSomethingWithAFile(const char* filename)
+{
+ // Para empezar, asuma que nada puede fallar.
+
+ FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura
+
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+ fclose(fh); // Cierra el manejador de archivos
+}
+
+// Por desgracia, las cosas se complican rápidamente por el control de errores.
+// Supongamos que fopen puede fallar, y que doSomethingWithTheFile y
+// DoSomethingElseWithIt retornan códigos de error si fallan.
+// (Excepciones son la mejor forma de manejar los fallos,
+// pero algunos programadores, especialmente los que tienen un fondo C,
+// estan en desacuerdo sobre la utilidad de las excepciones).
+// Ahora tenemos que comprobar cada llamado por fallos y cerrar el manejador
+// del archivo si se ha producido un problema.
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura
+ if (fh == nullptr) // El puntero retornado es nulo o falla.
+ return false; // Reporta el fallo a quien hizo el llamado.
+
+ // Asume que cada función retorna falso si falla
+ if (!doSomethingWithTheFile(fh)) {
+ fclose(fh); // Cierre el manejador de archivo para que no se filtre.
+ return false; // Propaga el error.
+ }
+ if (!doSomethingElseWithIt(fh)) {
+ fclose(fh); // Cierre el manejador de archivo para que no se filtre.
+ return false; // Propaga el error.
+ }
+
+ fclose(fh); // Cierre el archivo.
+ return true; // Indica que todo funcionó correctamente.
+}
+
+// Programadores C suelen limpiar esto un poco usando 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); // Cierre el archivo.
+ return true; // Indica que todo funcionó correctamente.
+
+failure:
+ fclose(fh);
+ return false; // Propagate el error
+}
+
+// Si las funciones indican errores mediante excepciones,
+// Las cosas son un poco más claras, pero pueden optimizarse mas.
+void doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura
+ if (fh == nullptr)
+ throw std::runtime_error("No puede abrirse el archivo.");
+
+ try {
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+ }
+ catch (...) {
+ fclose(fh); // Asegúrese de cerrar el archivo si se produce un error.
+ throw; // Luego vuelve a lanzar la excepción.
+ }
+
+ fclose(fh); // Cierra el archivo
+}
+
+// Compare esto con el uso de la clase de flujo de archivos de C++ (fstream)
+// fstream utiliza su destructor para cerrar el archivo.
+// Los destructores son llamados automáticamente
+// cuando un objeto queda fuera del ámbito.
+void doSomethingWithAFile(const std::string& filename)
+{
+ // ifstream es la abreviatura de el input file stream
+ std::ifstream fh(filename); // Abre el archivo
+
+ // Hacer algo con el archivo
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+} // El archivo se cierra automáticamente aquí por el destructor
+
+
+// Esto tiene ventajas _enormes_:
+// 1. No importa lo que pase,
+// El recurso (en este caso el manejador de archivo) será limpiado.
+// Una vez que escribes el destructor correctamente,
+// Es _imposible_ olvidar cerrar el identificador y permitir
+// fugas del recurso.
+// 2. Tenga en cuenta que el código es mucho más limpio.
+// El destructor se encarga de cerrar el archivo detrás de cámaras
+// Sin que tenga que preocuparse por ello.
+// 3. El código es seguro.
+// Una excepción puede ser lanzado en cualquier lugar de la función
+// y la limpieza ocurrirá.
+
+// Todo el código idiomático C++ utiliza RAII ampliamente para todos los
+// recursos.
+// Otros ejemplos incluyen
+// - Memoria usando unique_ptr y shared_ptr
+// - Contenedores (Containers) - la biblioteca estándar linked list,
+// vector (es decir, array con auto-cambio de tamaño), hash maps, etc.
+// Destruimos todos sus contenidos de forma automática
+// cuando quedan fuera del ámbito.
+// - Mutex utilizando lock_guard y unique_lock
+
+
+/////////////////////
+// Cosas divertidas
+/////////////////////
+
+// Aspectos de C ++ que pueden sorprender a los recién llegados
+// (e incluso algunos veteranos).
+// Esta sección es, por desgracia, salvajemente incompleta;
+// C++ es uno de los lenguajes con los que mas facil te disparas en el pie.
+
+// Tu puedes sobreescribir métodos privados!
+class Foo {
+ virtual void bar();
+};
+class FooSub : public Foo {
+ virtual void bar(); // Sobreescribe Foo::bar!
+};
+
+
+// 0 == false == NULL (La mayoria de las veces)!
+bool* pt = new bool;
+*pt = 0; // Establece los puntos de valor de 'pt' en falso.
+pt = 0; // Establece 'pt' al apuntador nulo. Ambas lineas compilan sin error.
+
+// nullptr se supone que arregla un poco de ese tema:
+int* pt2 = new int;
+*pt2 = nullptr; // No compila
+pt2 = nullptr; // Establece pt2 como null.
+
+// Hay una excepción para los valores bool.
+// Esto es para permitir poner a prueba punteros nulos con if (!ptr),
+// pero como consecuencia se puede asignar nullptr a un bool directamente!
+*pt = nullptr; // Esto todavía compila, a pesar de que '*pt' es un bool!
+
+// '=' != '=' != '='!
+// Llama Foo::Foo(const Foo&) o alguna variante (mira movimientos semanticos)
+// copia del constructor.
+Foo f2;
+Foo f1 = f2;
+
+// Llama Foo::Foo(const Foo&) o variante, pero solo copia el 'Foo' parte de
+// 'fooSub'. Cualquier miembro extra de 'fooSub' se descarta. Este
+// comportamiento horrible se llama "Corte de objetos."
+FooSub fooSub;
+Foo f1 = fooSub;
+
+// Llama a Foo::operator=(Foo&) o variantes.
+Foo f1;
+f1 = f2;
+
+
+// Cómo borrar realmente un contenedor:
+class Foo { ... };
+vector v;
+for (int i = 0; i < 10; ++i)
+ v.push_back(Foo());
+// La siguiente línea establece el tamaño de v en 0,
+// pero los destructores no son llamados y los recursos no se liberan!
+
+v.empty();
+v.push_back(Foo()); // Nuevo valor se copia en el primer Foo que insertamos
+
+// En verdad destruye todos los valores en v.
+// Consulta la sección acerca de los objetos temporales para la
+// explicación de por qué esto funciona.
+v.swap(vector());
+
+```
+Otras lecturas:
+
+Una referencia del lenguaje hasta a la fecha se puede encontrar en
+
+
+Recursos adicionales se pueden encontrar en
--
cgit v1.2.3
From 224d4e9c7f8b13da852662edcf57f83d7f78c278 Mon Sep 17 00:00:00 2001
From: Jesus Tinoco
Date: Sun, 4 Oct 2015 13:17:50 +0200
Subject: Fixing typo in git-es.html.markdown
---
es-es/git-es.html.markdown | 64 +++++++++++++++++++++++-----------------------
1 file changed, 32 insertions(+), 32 deletions(-)
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 73853a9d..f370aa4d 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -11,15 +11,15 @@ lang: es-es
---
Git es un sistema de control de versiones distribuido diseñado para manejar
-cualquier tipo de proyecto ya sea largos o pequeños, con velocidad y eficiencia.
+cualquier tipo de proyect,o ya sea largo o pequeño, con velocidad y eficiencia.
Git realiza esto haciendo "snapshots" del proyecto, con ello permite
versionar y administrar nuestro código fuente.
## Versionamiento, conceptos.
-### Que es el control de versiones?
-El control de versiones es un sistema que guarda todos los cambios realizados a
+### Qué es el control de versiones?
+El control de versiones es un sistema que guarda todos los cambios realizados en
uno o varios archivos, a lo largo del tiempo.
### Versionamiento centralizado vs Versionamiento Distribuido.
@@ -31,15 +31,15 @@ uno o varios archivos, a lo largo del tiempo.
+ El versionamiento distribuido no tiene una estructura definida, incluso se
puede mantener el estilo de los repositorios SVN con git.
-[Informacion adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
+[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
-### Por que usar Git?
+### Por qué usar Git?
* Se puede trabajar sin conexion.
* Colaborar con otros es sencillo!.
-* Derivar, Crear ramas del proyecto (aka: Branching) es facil!.
+* Derivar, Crear ramas del proyecto (aka: Branching) es fácil!.
* Combinar (aka: Merging)
-* Git es rapido.
+* Git es rápido.
* Git es flexible.
## Arquitectura de Git.
@@ -48,10 +48,10 @@ uno o varios archivos, a lo largo del tiempo.
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
-y que sus atributos otorgan acceso al historial del elemento, ademas de otras
+y que sus atributos otorgan acceso al historial del elemento, además de otras
cosas.
-Un repositorio esta compuesto por la carpeta .git y un "arbol de trabajo".
+Un repositorio esta compuesto por la carpeta .git y un "árbol de trabajo".
### Directorio .git (componentes del repositorio)
@@ -62,38 +62,38 @@ y mas.
### Directorio de trabajo (componentes del repositorio)
-Es basicamente los directorios y archivos dentro del repositorio. La mayorioa de
+Es basicamente los directorios y archivos dentro del repositorio. La mayoría de
las veces se le llama "directorio de trabajo".
-### Inidice (componentes del directorio .git)
+### Índice (componentes del directorio .git)
-El inidice es la area de inicio en git. Es basicamente la capa que separa el
+El índice es el área de inicio en git. Es basicamente la capa que separa el
directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores
-mas poder sobre lo que envia y recibe en el repositorio.
+mas poder sobre lo que envía y recibe en el repositorio.
### Commit (aka: cambios)
Un commit es una captura de un conjunto de cambios, o modificaciones hechas en
el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2,
-estos cambios se almacenaran en un commit (aka: captura). Este commit puede ser o
+estos cambios se almacenarán en un commit (aka: captura). Este commit puede ser o
no ser enviado (aka: "pusheado") hacia un repositorio.
### Branch (rama)
-Un "branch", es escencialmente un apuntador hacia el ultimo commit (cambio
-registrado) que se ha realizado. A medida que se realizan mas commits, este
-apuntador se actualizara automaticamente hacia el ultimo commit.
+Un "branch", es escencialmente un apuntador hacia el último commit (cambio
+registrado) que se ha realizado. A medida que se realizan más commits, este
+apuntador se actualizará automaticamente hacia el ultimo commit.
### "HEAD" y "head" (component of .git dir)
"HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un
repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a
-cualquier commit realizado, un repositorio puede tener cualquier numero de
+cualquier commit realizado, un repositorio puede tener cualquier número de
"heads".
### conceptos - recursos.
-* [Git para informaticos](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git para informáticos](http://eagain.net/articles/git-for-computer-scientists/)
* [Git para diseñadores](http://hoth.entp.com/output/git_for_designers.html)
@@ -102,8 +102,8 @@ cualquier commit realizado, un repositorio puede tener cualquier numero de
### init
-Crear un repositorio de git vacio. Las configuraciones, informacion almacenada y
-demas son almacenadas en el directorio ".git".
+Crear un repositorio de git vacio. Las configuraciones, información almacenada y
+demás son almacenadas en el directorio ".git".
```bash
$ git init
@@ -127,7 +127,7 @@ $ git config --global user.name "nombre"
### help
-Otorga un accceso rapido a una guia extremadamente detallada de cada comando en
+Otorga un accceso rápido a una guía extremadamente detallada de cada comando en
git. O puede ser usada simplemente como un recordatorio de estos.
```bash
@@ -146,7 +146,7 @@ $ git help init
### status
-Muestra las diferencias entre el archivo indice y el commit al cual apunta el
+Muestra las diferencias entre el archivo índice y el commit al cual apunta el
HEAD actualmente.
@@ -163,7 +163,7 @@ $ git help status
Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se
utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por
-lo que no se incluiran en los commits (cambios).
+lo que no se incluirán en los commits (cambios).
```bash
# Añade un archivo en el directorio de trabajo actual.
@@ -202,7 +202,7 @@ $ git branch master --edit-description
### checkout
Actualiza todos los archivos en el directorio de trabajo para que sean igual que
-las versiones almacenadas en el indice, o en un arbol de trabajo especificado.
+las versiones almacenadas en el índice, o en un árbol de trabajo especificado.
```bash
# Despachar un repositorio. - Por defecto la master branch. (la rama principal llamada 'master')
@@ -215,8 +215,8 @@ $ git checkout -b jdei
### clone
-Clona, o copia, una repo existente en un nuevo directorio. Tambien añada el
-seguimiento hacia las ramas existentes del repo que ha sido clonada, lo que
+Clona, o copia, un repositorio existente en un nuevo directorio. También añade el
+seguimiento hacia las ramas existentes del repositorio que ha sido clonado, lo que
permite subir (push) los archivos hacia una rama remota.
```bash
@@ -226,8 +226,8 @@ $ git clone https://github.com/jquery/jquery.git
### commit
-Almacena los cambios que almacenados en el indice en un nuevo "commit". Este
-commit contiene los cambios hechos mas un resumen hecho por el desarrollador.
+Almacena el contenido actual del índice en un nuevo "commit". Este
+commit contiene los cambios hechos más un resumen proporcionado por el desarrollador.
```bash
# commit with a message
@@ -237,8 +237,8 @@ $ git commit -m "jedi anakin wil be - jedis.list"
### diff
-Muestra las diferencias entre un archivo en el directorio de trabajo, el indice
-y commits.
+Muestra las diferencias entre un archivo en el directorio de trabajo, el índice
+y los commits.
```bash
# Muestra la diferencia entre un directorio de trabajo y el indice.
@@ -253,7 +253,7 @@ $ git diff HEAD
### grep
-Permite realizar una busqueda rapida en un repositorio.
+Permite realizar una busqueda rápida en un repositorio.
Configuracion opcionales:
--
cgit v1.2.3
From f7cfb3b194ff4fb590173cb7e790c4effc1656c0 Mon Sep 17 00:00:00 2001
From: edholland
Date: Sun, 4 Oct 2015 13:18:06 +0200
Subject: Fix poor formatting and typos
---
erlang.html.markdown | 38 +++++++++++++++++++-------------------
1 file changed, 19 insertions(+), 19 deletions(-)
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 64330867..48cee6ec 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -308,25 +308,25 @@ self(). % <0.41.0>
% Unit tests can be written using EUnits's test generators and assert macros
-module(fib).
- -export([fib/1]).
- -include_lib("eunit/include/eunit.hrl").
-
- fib(0) -> 1;
- fib(1) -> 1;
- fib(N) when N > 1 -> fib(N-1) + fib(N-2).
-
- fib_test_() ->
- [?_assert(fib(0) =:= 1),
- ?_assert(fib(1) =:= 1),
- ?_assert(fib(2) =:= 2),
- ?_assert(fib(3) =:= 3),
- ?_assert(fib(4) =:= 5),
- ?_assert(fib(5) =:= 8),
- ?_assertException(error, function_clause, fib(-1)),
- ?_assert(fib(31) =:= 2178309)
- ].
-
-% EUnit will automatically export to a test() fucntion to allo running the tests
+-export([fib/1]).
+-include_lib("eunit/include/eunit.hrl").
+
+fib(0) -> 1;
+fib(1) -> 1;
+fib(N) when N > 1 -> fib(N-1) + fib(N-2).
+
+fib_test_() ->
+ [?_assert(fib(0) =:= 1),
+ ?_assert(fib(1) =:= 1),
+ ?_assert(fib(2) =:= 2),
+ ?_assert(fib(3) =:= 3),
+ ?_assert(fib(4) =:= 5),
+ ?_assert(fib(5) =:= 8),
+ ?_assertException(error, function_clause, fib(-1)),
+ ?_assert(fib(31) =:= 2178309)
+ ].
+
+% EUnit will automatically export to a test() function to allow running the tests
% in the erlang shell
fib:test()
--
cgit v1.2.3
From 8aec122beaffc6d7d8e108aa4bbe4a2218062a46 Mon Sep 17 00:00:00 2001
From: Jesus Tinoco
Date: Sun, 4 Oct 2015 13:19:34 +0200
Subject: Typos fixed in git-es.html.markdown
---
es-es/git-es.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index f370aa4d..51812447 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -11,7 +11,7 @@ lang: es-es
---
Git es un sistema de control de versiones distribuido diseñado para manejar
-cualquier tipo de proyect,o ya sea largo o pequeño, con velocidad y eficiencia.
+cualquier tipo de proyecto, ya sea largo o pequeño, con velocidad y eficiencia.
Git realiza esto haciendo "snapshots" del proyecto, con ello permite
versionar y administrar nuestro código fuente.
--
cgit v1.2.3
From 6b6f88c64d9a4b2d26de5725dee24f3c459fb93c Mon Sep 17 00:00:00 2001
From: bk2dcradle
Date: Sun, 4 Oct 2015 01:47:09 +0530
Subject: Added abstract classes
---
java.html.markdown | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
diff --git a/java.html.markdown b/java.html.markdown
index 928eb39f..2f41be81 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -451,6 +451,74 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
public void InterfaceTwoMethod() {
}
}
+
+
+// Abstract Classes
+// Abstract Class declaration syntax
+// abstract extends {
+// // Constants and variables
+// // Method declarations
+// }
+
+// Methods can't have bodies in an interface, unless the method is
+// static. Also variables are NOT final by default, unlike an interface.
+// Also abstract classes CAN have the "main" method.
+// Abstract classes solve these problems.
+
+public abstract class Animal
+{
+ public abstract void makeSound();
+
+ // Method can have a body
+ public void eat()
+ {
+ System.out.println("I am an animal and I am Eating.");
+ // Note: We can access private variable here.
+ age = 30;
+ }
+
+ // No need to initialise, however in an interface
+ // a variable is implicitly final and hence has
+ // to be initialised.
+ private int age;
+
+ public void printAge()
+ {
+ System.out.println(age);
+ }
+
+ // Abstract classes can have main function.
+ public static void main(String[] args)
+ {
+ System.out.println("I am abstract");
+ }
+}
+
+class Dog extends Animal
+{
+ // Note still have to override the abstract methods in the
+ // abstract class.
+ @Override
+ public void makeSound()
+ {
+ System.out.println("Bark");
+ // age = 30; ==> ERROR! age is private to Animal
+ }
+
+ // NOTE: You will get an error if you used the
+ // @Override annotation here, since java doesn't allow
+ // overriding of static methods.
+ // What is happening here is called METHOD HIDING.
+ // Check out this awesome SO post: (http://stackoverflow.com/questions/16313649/)
+ public static void main(String[] args)
+ {
+ Dog pluto = new Dog();
+ pluto.makeSound();
+ pluto.eat();
+ pluto.printAge();
+ }
+}
+
```
## Further Reading
--
cgit v1.2.3
From f1a90a4e636616ce91a271504eee3f374bfd7094 Mon Sep 17 00:00:00 2001
From: Guntbert Reiter
Date: Sun, 4 Oct 2015 16:44:24 +0200
Subject: Put demonstrative condition into ternary expression
It should be made clear that the part before the ternary operator is
indeed a condition, most often created as some comparison expression.
---
csharp.html.markdown | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 479b7f01..222ba0d2 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -236,7 +236,8 @@ on a new line! ""Wow!"", the masses cried";
// Ternary operators
// A simple if/else can be written as follows
// ? :
- string isTrue = (true) ? "True" : "False";
+ int toCompare = 17;
+ string isTrue = toCompare == 17 ? "True" : "False";
// While loop
int fooWhile = 0;
--
cgit v1.2.3
From ff1b91d463938a0809f4115c20c6f9fc89e24cfc Mon Sep 17 00:00:00 2001
From: David Lima
Date: Sun, 4 Oct 2015 11:55:16 -0300
Subject: [hack/en] Fixed some typos
---
hack.html.markdown | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/hack.html.markdown b/hack.html.markdown
index 632fc705..b9730dc0 100644
--- a/hack.html.markdown
+++ b/hack.html.markdown
@@ -2,6 +2,7 @@
language: Hack
contributors:
- ["Stephen Holdaway", "https://github.com/stecman"]
+ - ["David Lima", "https://github.com/davelima"]
filename: learnhack.hh
---
@@ -152,7 +153,7 @@ class ArgumentPromotion
private bool $isAwesome) {}
}
-class WithoutArugmentPromotion
+class WithoutArgumentPromotion
{
public string $name;
@@ -169,9 +170,9 @@ class WithoutArugmentPromotion
}
-// Co-oprerative multi-tasking
+// Co-operative multi-tasking
//
-// Two new keywords "async" and "await" can be used to perform mutli-tasking
+// Two new keywords "async" and "await" can be used to perform multi-tasking
// Note that this does not involve threads - it just allows transfer of control
async function cooperativePrint(int $start, int $end) : Awaitable
{
--
cgit v1.2.3
From 29ea66dbef66944f59b5a7abe68b7113e1679791 Mon Sep 17 00:00:00 2001
From: David Lima
Date: Sun, 4 Oct 2015 12:02:20 -0300
Subject: [hack/pt-br] Add pt-br translation
---
pt-br/hack-pt.html.markdown | 316 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 316 insertions(+)
create mode 100644 pt-br/hack-pt.html.markdown
diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown
new file mode 100644
index 00000000..3efa5f0a
--- /dev/null
+++ b/pt-br/hack-pt.html.markdown
@@ -0,0 +1,316 @@
+---
+language: Hack
+contributors:
+ - ["Stephen Holdaway", "https://github.com/stecman"]
+ - ["David Lima", "https://github.com/davelima"]
+translators:
+ - ["David Lima", "https://github.com/davelima"]
+lang: pt-br
+filename: learnhack.hh
+---
+
+Hack é uma linguagem baseada no PHP e roda numa máquina virtual chamada HHVM.
+Hack é quase completamente interoperável com códigos PHP existentes e adiciona
+alguns recursos úteis de linguagens estaticamente tipadas.
+
+Somente recursos específicos da linguagem Hack serão abordados aqui. Detalhes
+sobre a sintaxe do PHP estão disponíveis no
+[artigo PHP](http://learnxinyminutes.com/docs/php/) neste site.
+
+```php
+id = $id;
+ }
+}
+
+
+// Funções anônimas (lambdas)
+$multiplicador = 5;
+array_map($y ==> $y * $multiplicador, [1, 2, 3]);
+
+
+// Genéricos
+class Caixa
+{
+ protected T $dados;
+
+ public function __construct(T $dados) {
+ $this->dados = $dados;
+ }
+
+ public function pegaDados(): T {
+ return $this->dados;
+ }
+}
+
+function abreCaixa(Caixa $caixa) : int
+{
+ return $caixa->pegaDados();
+}
+
+
+// Formas
+//
+// Hack adiciona o conceito de formas para definir arrays com uma estrutura
+// e tipos de dados garantidos
+type Point2D = shape('x' => int, 'y' => int);
+
+function distancia(Point2D $a, Point2D $b) : float
+{
+ return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2));
+}
+
+distancia(
+ shape('x' => -1, 'y' => 5),
+ shape('x' => 2, 'y' => 50)
+);
+
+
+// Pseudônimos de tipos
+//
+// Hack adiciona vários recursos para criação de pseudônimos, tornando tipos complexos
+// mais fáceis de entender
+newtype VectorArray = array>;
+
+// Um tuple contendo dois inteiros
+newtype Point = (int, int);
+
+function adicionaPontos(Point $p1, Point $p2) : Point
+{
+ return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]);
+}
+
+adicionaPontos(
+ tuple(1, 2),
+ tuple(5, 6)
+);
+
+
+// enums em classes
+enum TipoDePista : int
+{
+ Estrada = 0;
+ Rua = 1;
+ Alameda = 2;
+ Avenida = 3;
+}
+
+function getTipoDePista() : TipoDePista
+{
+ return TipoDePista::Alameda;
+}
+
+
+// Especificação de argumentos no construtor (Argument Promotion)
+//
+// Para evitar que propriedades sejam definidas em mais de um lugar, e
+// construtores que só definem propriedades, o Hack adiciona uma sintaxe para
+// definir as propriedades e o construtor ao mesmo tempo.
+class ArgumentPromotion
+{
+ public function __construct(public string $nome,
+ protected int $idade,
+ private bool $legal) {}
+}
+
+class SemArgumentPromotion
+{
+ public string $nome;
+
+ protected int $idade;
+
+ private bool $legal;
+
+ public function __construct(string $nome, int $idade, bool $legal)
+ {
+ $this->nome = $nome;
+ $this->idade = $idade;
+ $this->legal = $legal;
+ }
+}
+
+
+// Multi-tarefas cooperativo
+//
+// Duas novas palavras-chave ("async" e "await") podem ser usadas para
+// trabalhar com multi-tarefas.
+// Obs. Isto não envolve threads - apenas permite a transferência de controle
+async function printCooperativo(int $inicio, int $fim) : Awaitable
+{
+ for ($i = $inicio; $i <= $fim; $i++) {
+ echo "$i ";
+
+ // Permite que outras tarefas façam algo
+ await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0);
+ }
+}
+
+// Imprime "1 4 7 2 5 8 3 6 9"
+AwaitAllWaitHandle::fromArray([
+ printCooperativo(1, 3),
+ printCooperativo(4, 6),
+ printCooperativo(7, 9)
+])->getWaitHandle()->join();
+
+
+// Atributos
+//
+// Atributos são uma forma de definir metadados para funções.
+// Hack tem alguns atributos especiais que possuem comportamentos úteis.
+
+// O atributo especial __Memoize faz com que o resultado da função fique em cache
+<<__Memoize>>
+function tarefaDemorada() : ?string
+{
+ return file_get_contents('http://exemplo.com');
+}
+
+// O corpo da função só é executado uma vez aqui:
+tarefaDemorada();
+tarefaDemorada();
+
+
+// O atributo especial __ConsistentConstruct faz com que o Hack certifique-se
+// de que a assinatura do construtor seja a mesma em todas as subclasses
+<<__ConsistentConstruct>>
+class FooConsistente
+{
+ public function __construct(int $x, float $y)
+ {
+ // ...
+ }
+
+ public function algumMetodo()
+ {
+ // ...
+ }
+}
+
+class BarConsistente extends FooConsistente
+{
+ public function __construct(int $x, float $y)
+ {
+ // O verificador de tipos do Hack exige que os construtores pai
+ // sejam chamados
+ parent::__construct($x, $y);
+
+ // ...
+ }
+
+ // A anotação __Override é uma anotação opcional que faz com que o
+ // verificador de tipos do Hack sobrescreva um método em uma classe pai
+ // ou um trait. Sem __Override, definir este método causará um erro,
+ // pois ele já foi definido na classe pai (FooConsistente):
+ <<__Override>>
+ public function algumMetodo()
+ {
+ // ...
+ }
+}
+
+class SubclasseFooInvalida extends FooConsistente
+{
+ // Caso o construtor não combine com o construtor da classe pai, o
+ // verificador de tipos acusará um erro:
+ //
+ // "Este objeto é incompatível com o objeto FooConsistente porque algum(ns)
+ // dos seus métodos são incompatíveis"
+ //
+ public function __construct(float $x)
+ {
+ // ...
+ }
+
+ // Usar a anotação __Override em um método que não existe na classe pai
+ // causará um erro do verificador de tipos:
+ // "SubclasseFooInvalida::outroMetodo() está marcada para sobrescrever;
+ // nenhuma definição não-privada foi encontrada ou a classe pai foi
+ // definida em código não->
+ public function outroMetodo()
+ {
+ // ...
+ }
+}
+
+
+// Traits podem implementar interfaces (não suportado pelo PHP)
+interface InterfaceGatinho
+{
+ public function brinca() : void;
+}
+
+trait TraitGato implements GatinhoInterface
+{
+ public function brinca() : void
+ {
+ // ...
+ }
+}
+
+class Samuel
+{
+ use TraitGato;
+}
+
+
+$gato = new Samuel();
+$gato instanceof GatinhoInterface === true; // True
+
+```
+
+## Mais informações
+
+Visite a [documentação do Hack](http://docs.hhvm.com/manual/en/hacklangref.php)
+para ver explicações detalhadas dos recursos que Hack adiciona ao PHP, ou o [site oficial do Hack](http://hanlang.org/)
+para outras informações.
+
+Visite o [site oficial do HHVM](http://hhvm.com/) para aprender a instalar o HHVM.
+
+Visite [este artigo](http://docs.hhvm.com/manual/en/hack.unsupported.php) para ver
+os recursos do PHP que o Hack não suporta e ver incompatibilidades entre Hack e PHP.
--
cgit v1.2.3
From 09f8a34244af976f7ca29efc620a6bd51ad4ffa7 Mon Sep 17 00:00:00 2001
From: David Lima
Date: Sun, 4 Oct 2015 12:05:07 -0300
Subject: [hack/pt-br] Fixed some typos
---
pt-br/hack-pt.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown
index 3efa5f0a..2f9d3c1b 100644
--- a/pt-br/hack-pt.html.markdown
+++ b/pt-br/hack-pt.html.markdown
@@ -285,7 +285,7 @@ interface InterfaceGatinho
public function brinca() : void;
}
-trait TraitGato implements GatinhoInterface
+trait TraitGato implements InterfaceGatinho
{
public function brinca() : void
{
@@ -300,7 +300,7 @@ class Samuel
$gato = new Samuel();
-$gato instanceof GatinhoInterface === true; // True
+$gato instanceof InterfaceGatinho === true; // True
```
--
cgit v1.2.3
From fbd07f268cd6e64c65912ccc27f2ec9e222ec536 Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Sun, 4 Oct 2015 21:24:57 +0530
Subject: Issue #1157
Comment explaining '-p', in line 178.
---
common-lisp.html.markdown | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index f9f64d68..e3bb61cf 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -175,7 +175,8 @@ nil ; for false - and the empty list
:age 5))
*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
-(dog-p *rover*) ; => t ;; ewww)
+(dog-p *rover*) ; => true #| -p signifies "predicate". It's used to
+ check if *rover* is an instance of dog.|#
(dog-name *rover*) ; => "rover"
;; Dog-p, make-dog, and dog-name are all created by defstruct!
--
cgit v1.2.3
From c57868703a6462a0ad64b27d3887b970272ebb4d Mon Sep 17 00:00:00 2001
From: jig08
Date: Sun, 4 Oct 2015 22:14:31 +0530
Subject: Adding smalltalk tut
---
ko-kr/.Rhistory | 0
smalltalk.html.markdown | 959 +++++++++++++++++++++++++++++++++++++++++++++++
smalltalk.html.markdown~ | 959 +++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 1918 insertions(+)
create mode 100644 ko-kr/.Rhistory
create mode 100644 smalltalk.html.markdown
create mode 100644 smalltalk.html.markdown~
diff --git a/ko-kr/.Rhistory b/ko-kr/.Rhistory
new file mode 100644
index 00000000..e69de29b
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
new file mode 100644
index 00000000..61e5a94c
--- /dev/null
+++ b/smalltalk.html.markdown
@@ -0,0 +1,959 @@
+---
+language: smalltalk
+contributors:
+ - ["Jigyasa Grover", "https://github.com/jig08"]
+---
+
+- Smalltalk is an object-oriented, dynamically typed, reflective programming language.
+- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis."
+- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s.
+
+Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`.
+
+```
+
+"************************************************************************
+ * Allowable characters: *
+ * - a-z *
+ * - A-Z *
+ * - 0-9 *
+ * - .+/\*~<>@%|&? *
+ * - blank, tab, cr, ff, lf *
+ * *
+ * Variables: *
+ * - variables must be declared before use *
+ * - shared vars must begin with uppercase *
+ * - local vars must begin with lowercase *
+ * - reserved names: nil, true, false, self, super, and Smalltalk *
+ * *
+ * Variable scope: *
+ * - Global: defined in Dictionary Smalltalk and accessible by all *
+ * objects in system *
+ * - Special: (reserved) Smalltalk, super, self, true, false, & nil *
+ * - Method Temporary: local to a method *
+ * - Block Temporary: local to a block *
+ * - Pool: variables in a Dictionary object *
+ * - Method Parameters: automatic local vars created as a result of *
+ * message call with params *
+ * - Block Parameters: automatic local vars created as a result of *
+ * value: message call *
+ * - Class: shared with all instances of one class & its subclasses *
+ * - Class Instance: unique to each instance of a class *
+ * - Instance Variables: unique to each instance *
+ ************************************************************************"
+"Comments are enclosed in quotes"
+"Period (.) is the statement seperator"
+
+"************************************************************************
+ * Transcript: *
+ ************************************************************************"
+Transcript clear. "clear to transcript window"
+Transcript show: 'Hello World'. "output string in transcript window"
+Transcript nextPutAll: 'Hello World'. "output string in transcript window"
+Transcript nextPut: $A. "output character in transcript window"
+Transcript space. "output space character in transcript window"
+Transcript tab. "output tab character in transcript window"
+Transcript cr. "carriage return / linefeed"
+'Hello' printOn: Transcript. "append print string into the window"
+'Hello' storeOn: Transcript. "append store string into the window"
+Transcript endEntry. "flush the output buffer"
+
+"************************************************************************
+ * Assignment: *
+ ************************************************************************"
+| x y |
+x _ 4. "assignment (Squeak) <-"
+x := 5. "assignment"
+x := y := z := 6. "compound assignment"
+x := (y := 6) + 1.
+x := Object new. "bind to allocated instance of a class"
+x := 123 class. "discover the object class"
+x := Integer superclass. "discover the superclass of a class"
+x := Object allInstances. "get an array of all instances of a class"
+x := Integer allSuperclasses. "get all superclasses of a class"
+x := 1.2 hash. "hash value for object"
+y := x copy. "copy object"
+y := x shallowCopy. "copy object (not overridden)"
+y := x deepCopy. "copy object and instance vars"
+y := x veryDeepCopy. "complete tree copy using a dictionary"
+
+"************************************************************************
+ * Constants: *
+ ************************************************************************"
+| b |
+b := true. "true constant"
+b := false. "false constant"
+x := nil. "nil object constant"
+x := 1. "integer constants"
+x := 3.14. "float constants"
+x := 2e-2. "fractional constants"
+x := 16r0F. "hex constant".
+x := -1. "negative constants"
+x := 'Hello'. "string constant"
+x := 'I''m here'. "single quote escape"
+x := $A. "character constant"
+x := $ . "character constant (space)"
+x := #aSymbol. "symbol constants"
+x := #(3 2 1). "array constants"
+x := #('abc' 2 $a). "mixing of types allowed"
+
+"************************************************************************
+ * Booleans: *
+ ************************************************************************"
+| b x y |
+x := 1. y := 2.
+b := (x = y). "equals"
+b := (x ~= y). "not equals"
+b := (x == y). "identical"
+b := (x ~~ y). "not identical"
+b := (x > y). "greater than"
+b := (x < y). "less than"
+b := (x >= y). "greater than or equal"
+b := (x <= y). "less than or equal"
+b := b not. "boolean not"
+b := (x < 5) & (y > 1). "boolean and"
+b := (x < 5) | (y > 1). "boolean or"
+b := (x < 5) and: [y > 1]. "boolean and (short-circuit)"
+b := (x < 5) or: [y > 1]. "boolean or (short-circuit)"
+b := (x < 5) eqv: (y > 1). "test if both true or both false"
+b := (x < 5) xor: (y > 1). "test if one true and other false"
+b := 5 between: 3 and: 12. "between (inclusive)"
+b := 123 isKindOf: Number. "test if object is class or subclass of"
+b := 123 isMemberOf: SmallInteger. "test if object is type of class"
+b := 123 respondsTo: sqrt. "test if object responds to message"
+b := x isNil. "test if object is nil"
+b := x isZero. "test if number is zero"
+b := x positive. "test if number is positive"
+b := x strictlyPositive. "test if number is greater than zero"
+b := x negative. "test if number is negative"
+b := x even. "test if number is even"
+b := x odd. "test if number is odd"
+b := x isLiteral. "test if literal constant"
+b := x isInteger. "test if object is integer"
+b := x isFloat. "test if object is float"
+b := x isNumber. "test if object is number"
+b := $A isUppercase. "test if upper case character"
+b := $A isLowercase. "test if lower case character"
+
+"************************************************************************
+ * Arithmetic expressions: *
+ ************************************************************************"
+| x |
+x := 6 + 3. "addition"
+x := 6 - 3. "subtraction"
+x := 6 * 3. "multiplication"
+x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3"
+x := 5 / 3. "division with fractional result"
+x := 5.0 / 3.0. "division with float result"
+x := 5.0 // 3.0. "integer divide"
+x := 5.0 \\ 3.0. "integer remainder"
+x := -5. "unary minus"
+x := 5 sign. "numeric sign (1, -1 or 0)"
+x := 5 negated. "negate receiver"
+x := 1.2 integerPart. "integer part of number (1.0)"
+x := 1.2 fractionPart. "fractional part of number (0.2)"
+x := 5 reciprocal. "reciprocal function"
+x := 6 * 3.1. "auto convert to float"
+x := 5 squared. "square function"
+x := 25 sqrt. "square root"
+x := 5 raisedTo: 2. "power function"
+x := 5 raisedToInteger: 2. "power function with integer"
+x := 5 exp. "exponential"
+x := -5 abs. "absolute value"
+x := 3.99 rounded. "round"
+x := 3.99 truncated. "truncate"
+x := 3.99 roundTo: 1. "round to specified decimal places"
+x := 3.99 truncateTo: 1. "truncate to specified decimal places"
+x := 3.99 floor. "truncate"
+x := 3.99 ceiling. "round up"
+x := 5 factorial. "factorial"
+x := -5 quo: 3. "integer divide rounded toward zero"
+x := -5 rem: 3. "integer remainder rounded toward zero"
+x := 28 gcd: 12. "greatest common denominator"
+x := 28 lcm: 12. "least common multiple"
+x := 100 ln. "natural logarithm"
+x := 100 log. "base 10 logarithm"
+x := 100 log: 10. "logarithm with specified base"
+x := 100 floorLog: 10. "floor of the log"
+x := 180 degreesToRadians. "convert degrees to radians"
+x := 3.14 radiansToDegrees. "convert radians to degrees"
+x := 0.7 sin. "sine"
+x := 0.7 cos. "cosine"
+x := 0.7 tan. "tangent"
+x := 0.7 arcSin. "arcsine"
+x := 0.7 arcCos. "arccosine"
+x := 0.7 arcTan. "arctangent"
+x := 10 max: 20. "get maximum of two numbers"
+x := 10 min: 20. "get minimum of two numbers"
+x := Float pi. "pi"
+x := Float e. "exp constant"
+x := Float infinity. "infinity"
+x := Float nan. "not-a-number"
+x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)
+x := 100 atRandom. "quick random number"
+
+"************************************************************************
+ * Bitwise Manipulation: *
+ ************************************************************************"
+| b x |
+x := 16rFF bitAnd: 16r0F. "and bits"
+x := 16rF0 bitOr: 16r0F. "or bits"
+x := 16rFF bitXor: 16r0F. "xor bits"
+x := 16rFF bitInvert. "invert bits"
+x := 16r0F bitShift: 4. "left shift"
+x := 16rF0 bitShift: -4. "right shift"
+"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]"
+x := 16r80 highbit. "position of highest bit set"
+b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver"
+b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver"
+b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver"
+
+"************************************************************************
+ * Conversion: *
+ ************************************************************************"
+| x |
+x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
+x := 3.99 asFraction. "convert number to fraction"
+x := 3 asFloat. "convert number to float"
+x := 65 asCharacter. "convert integer to character"
+x := $A asciiValue. "convert character to integer"
+x := 3.99 printString. "convert object to string via printOn:"
+x := 3.99 storeString. "convert object to string via storeOn:"
+x := 15 radix: 16. "convert to string in given base"
+x := 15 printStringBase: 16.
+x := 15 storeStringBase: 16.
+
+"************************************************************************
+ * Blocks: *
+ * - blocks are objects and may be assigned to a variable *
+ * - value is last expression evaluated unless explicit return *
+ * - blocks may be nested *
+ * - specification [ arguments | | localvars | expressions ] *
+ * - Squeak does not currently support localvars in blocks *
+ * - max of three arguments allowed *
+ * - ^expression terminates block & method (exits all nested blocks) *
+ * - blocks intended for long term storage should not contain ^ *
+ ************************************************************************"
+| x y z |
+x := [ y := 1. z := 2. ]. x value. "simple block usage"
+x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing"
+Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing"
+"x := [ | z | z := 1.]. localvars not available in squeak blocks"
+
+"************************************************************************
+ * Method calls: *
+ * - unary methods are messages with no arguments *
+ * - binary methods *
+ * - keyword methods are messages with selectors including colons *
+ * *
+ * standard categories/protocols: *
+ * - initialize-release (methods called for new instance) *
+ * - accessing (get/set methods) *
+ * - testing (boolean tests - is) *
+ * - comparing (boolean tests with parameter *
+ * - displaying (gui related methods) *
+ * - printing (methods for printing) *
+ * - updating (receive notification of changes) *
+ * - private (methods private to class) *
+ * - instance-creation (class methods for creating instance) *
+ ************************************************************************"
+| x |
+x := 2 sqrt. "unary message"
+x := 2 raisedTo: 10. "keyword message"
+x := 194 * 9. "binary message"
+Transcript show: (194 * 9) printString; cr. "combination (chaining)"
+x := 2 perform: #sqrt. "indirect method invocation"
+Transcript "Cascading - send multiple messages to receiver"
+ show: 'hello ';
+ show: 'world';
+ cr.
+x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)"
+
+"************************************************************************
+ * Conditional Statements: *
+ ************************************************************************"
+| x |
+x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then"
+x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else"
+x > 10 "if then else"
+ ifTrue: [Transcript show: 'ifTrue'; cr]
+ ifFalse: [Transcript show: 'ifFalse'; cr].
+x > 10 "if else then"
+ ifFalse: [Transcript show: 'ifFalse'; cr]
+ ifTrue: [Transcript show: 'ifTrue'; cr].
+Transcript
+ show:
+ (x > 10
+ ifTrue: ['ifTrue']
+ ifFalse: ['ifFalse']);
+ cr.
+Transcript "nested if then else"
+ show:
+ (x > 10
+ ifTrue: [x > 5
+ ifTrue: ['A']
+ ifFalse: ['B']]
+ ifFalse: ['C']);
+ cr.
+switch := Dictionary new. "switch functionality"
+switch at: $A put: [Transcript show: 'Case A'; cr].
+switch at: $B put: [Transcript show: 'Case B'; cr].
+switch at: $C put: [Transcript show: 'Case C'; cr].
+result := (switch at: $B) value.
+
+"************************************************************************
+ * Iteration statements: *
+ ************************************************************************"
+| x y |
+x := 4. y := 1.
+[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop"
+[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop"
+x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)"
+1 to: x do: [:a | y := y * 2]. "for loop"
+1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment"
+#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
+
+"************************************************************************
+ * Character: *
+ ************************************************************************"
+| x y |
+x := $A. "character assignment"
+y := x isLowercase. "test if lower case"
+y := x isUppercase. "test if upper case"
+y := x isLetter. "test if letter"
+y := x isDigit. "test if digit"
+y := x isAlphaNumeric. "test if alphanumeric"
+y := x isSeparator. "test if seperator char"
+y := x isVowel. "test if vowel"
+y := x digitValue. "convert to numeric digit value"
+y := x asLowercase. "convert to lower case"
+y := x asUppercase. "convert to upper case"
+y := x asciiValue. "convert to numeric ascii value"
+y := x asString. "convert to string"
+b := $A <= $B. "comparison"
+y := $A max: $B.
+
+"************************************************************************
+ * Symbol: *
+ ************************************************************************"
+| b x y |
+x := #Hello. "symbol assignment"
+y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
+b := x isEmpty. "test if symbol is empty"
+y := x size. "string size"
+y := x at: 2. "char at location"
+y := x copyFrom: 2 to: 4. "substring"
+y := x indexOf: $e ifAbsent: [0]. "first position of character within string"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
+b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
+y := x select: [:a | a > $a]. "return all elements that meet condition"
+y := x asString. "convert symbol to string"
+y := x asText. "convert symbol to text"
+y := x asArray. "convert symbol to array"
+y := x asOrderedCollection. "convert symbol to ordered collection"
+y := x asSortedCollection. "convert symbol to sorted collection"
+y := x asBag. "convert symbol to bag collection"
+y := x asSet. "convert symbol to set collection"
+
+"************************************************************************
+ * String: *
+ ************************************************************************"
+| b x y |
+x := 'This is a string'. "string assignment"
+x := 'String', 'Concatenation'. "string concatenation"
+b := x isEmpty. "test if string is empty"
+y := x size. "string size"
+y := x at: 2. "char at location"
+y := x copyFrom: 2 to: 4. "substring"
+y := x indexOf: $a ifAbsent: [0]. "first position of character within string"
+x := String new: 4. "allocate string object"
+x "set string elements"
+ at: 1 put: $a;
+ at: 2 put: $b;
+ at: 3 put: $c;
+ at: 4 put: $e.
+x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
+b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
+y := x select: [:a | a > $a]. "return all elements that meet condition"
+y := x asSymbol. "convert string to symbol"
+y := x asArray. "convert string to array"
+x := 'ABCD' asByteArray. "convert string to byte array"
+y := x asOrderedCollection. "convert string to ordered collection"
+y := x asSortedCollection. "convert string to sorted collection"
+y := x asBag. "convert string to bag collection"
+y := x asSet. "convert string to set collection"
+y := x shuffled. "randomly shuffle string"
+
+"************************************************************************
+ * Array: Fixed length collection *
+ * ByteArray: Array limited to byte elements (0-255) *
+ * WordArray: Array limited to word elements (0-2^32) *
+ ************************************************************************"
+| b x y sum max |
+x := #(4 3 2 1). "constant array"
+x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements"
+x := Array new: 4. "allocate an array with specified size"
+x "set array elements"
+ at: 1 put: 5;
+ at: 2 put: 4;
+ at: 3 put: 3;
+ at: 4 put: 2.
+b := x isEmpty. "test if array is empty"
+y := x size. "array size"
+y := x at: 4. "get array element at index"
+b := x includes: 3. "test if element is in array"
+y := x copyFrom: 2 to: 4. "subarray"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within array"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the array"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum array elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in array"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x shuffled. "randomly shuffle collection"
+y := x asArray. "convert to array"
+"y := x asByteArray." "note: this instruction not available on Squeak"
+y := x asWordArray. "convert to word array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * OrderedCollection: acts like an expandable array *
+ ************************************************************************"
+| b x y sum max |
+x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := OrderedCollection new. "allocate collection"
+x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
+y := x addFirst: 5. "add element at beginning of collection"
+y := x removeFirst. "remove first element in collection"
+y := x addLast: 6. "add element at end of collection"
+y := x removeLast. "remove last element in collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+x at: 2 put: 3. "set element at index"
+y := x remove: 5 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: 2. "retrieve element at index"
+y := x first. "retrieve first element in collection"
+y := x last. "retrieve last element in collection"
+b := x includes: 5. "test if element is in collection"
+y := x copyFrom: 2 to: 3. "subcollection"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x shuffled. "randomly shuffle collection"
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * SortedCollection: like OrderedCollection except order of elements *
+ * determined by sorting criteria *
+ ************************************************************************"
+| b x y sum max |
+x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := SortedCollection new. "allocate collection"
+x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria"
+x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
+y := x addFirst: 5. "add element at beginning of collection"
+y := x removeFirst. "remove first element in collection"
+y := x addLast: 6. "add element at end of collection"
+y := x removeLast. "remove last element in collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 5 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: 2. "retrieve element at index"
+y := x first. "retrieve first element in collection"
+y := x last. "retrieve last element in collection"
+b := x includes: 4. "test if element is in collection"
+y := x copyFrom: 2 to: 3. "subcollection"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Bag: like OrderedCollection except elements are in no *
+ * particular order *
+ ************************************************************************"
+| b x y sum max |
+x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := Bag new. "allocate collection"
+x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
+x add: 3 withOccurrences: 2. "add multiple copies to collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 4 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+b := x includes: 3. "test if element is in collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Set: like Bag except duplicates not allowed *
+ * IdentitySet: uses identity test (== rather than =) *
+ ************************************************************************"
+| b x y sum max |
+x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := Set new. "allocate collection"
+x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 4 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+x includes: 4. "test if element is in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Interval: *
+ ************************************************************************"
+| b x y sum max |
+x := Interval from: 5 to: 10. "create interval object"
+x := 5 to: 10.
+x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment"
+x := 5 to: 10 by: 2.
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+x includes: 9. "test if element is in collection"
+x do: [:k | Transcript show: k printString; cr]. "iterate over interval"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 7]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Associations: *
+ ************************************************************************"
+| x y |
+x := #myVar->'hello'.
+y := x key.
+y := x value.
+
+"************************************************************************
+ * Dictionary: *
+ * IdentityDictionary: uses identity test (== rather than =) *
+ ************************************************************************"
+| b x y |
+x := Dictionary new. "allocate collection"
+x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection"
+x at: #e put: 3. "set element at index"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: #a ifAbsent: []. "retrieve element at index"
+y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block"
+y := x removeKey: #e ifAbsent: []. "remove element from collection"
+b := x includes: 3. "test if element is in values collection"
+b := x includesKey: #a. "test if element is in keys collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+y := x keys. "set of keys"
+y := x values. "bag of values"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection"
+x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection"
+x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations"
+x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values"
+ show: aKey printString; space;
+ show: aValue printString; cr].
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary"
+x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary"
+Transcript show: (CMRGlobal printString). "entries are directly accessible by name"
+Smalltalk keys do: [ :k | "print out all classes"
+ ((Smalltalk at: k) isKindOf: Class)
+ ifFalse: [Transcript show: k printString; cr]].
+Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary"
+CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary"
+CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo"
+CMRDictionary size. "dictionary size"
+CMRDictionary keys do: [ :k | "print out keys in dictionary"
+ Transcript show: k printString; cr].
+CMRDictionary values do: [ :k | "print out values in dictionary"
+ Transcript show: k printString; cr].
+CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values"
+ Transcript
+ show: aKey printString;
+ space;
+ show: aValue printString;
+ cr].
+CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values"
+ Transcript show: aKeyValue printString; cr].
+Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary"
+Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary"
+
+"************************************************************************
+ * Internal Stream: *
+ ************************************************************************"
+| b x ios |
+ios := ReadStream on: 'Hello read stream'.
+ios := ReadStream on: 'Hello read stream' from: 1 to: 5.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 3.
+ios position.
+x := ios next.
+x := ios peek.
+x := ios contents.
+b := ios atEnd.
+
+ios := ReadWriteStream on: 'Hello read stream'.
+ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5.
+ios := ReadWriteStream with: 'Hello read stream'.
+ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10.
+ios position: 0.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 6.
+ios position.
+ios nextPutAll: 'Chris'.
+x := ios next.
+x := ios peek.
+x := ios contents.
+b := ios atEnd.
+
+"************************************************************************
+ * FileStream: *
+ ************************************************************************"
+| b x ios |
+ios := FileStream newFileNamed: 'ios.txt'.
+ios nextPut: $H; cr.
+ios nextPutAll: 'Hello File'; cr.
+'Hello File' printOn: ios.
+'Hello File' storeOn: ios.
+ios close.
+
+ios := FileStream oldFileNamed: 'ios.txt'.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 3.
+x := ios position.
+x := ios next.
+x := ios peek.
+b := ios atEnd.
+ios close.
+
+"************************************************************************
+ * Date: *
+ ************************************************************************"
+| x y |
+x := Date today. "create date for today"
+x := Date dateAndTimeNow. "create date from current time/date"
+x := Date readFromString: '01/02/1999'. "create date from formatted string"
+x := Date newDay: 12 month: #July year: 1999 "create date from parts"
+x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901"
+y := Date dayOfWeek: #Monday. "day of week as int (1-7)"
+y := Date indexOfMonth: #January. "month of year as int (1-12)"
+y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)"
+y := Date daysInYear: 1996. "days in year (365|366)"
+y := Date nameOfDay: 1 "weekday name (#Monday,...)"
+y := Date nameOfMonth: 1. "month name (#January,...)"
+y := Date leapYear: 1996. "1 if leap year; 0 if not leap year"
+y := x weekday. "day of week (#Monday,...)"
+y := x previous: #Monday. "date for previous day of week"
+y := x dayOfMonth. "day of month (1-31)"
+y := x day. "day of year (1-366)"
+y := x firstDayOfMonth. "day of year for first day of month"
+y := x monthName. "month of year (#January,...)"
+y := x monthIndex. "month of year (1-12)"
+y := x daysInMonth. "days in month (1-31)"
+y := x year. "year (19xx)"
+y := x daysInYear. "days in year (365|366)"
+y := x daysLeftInYear. "days left in year (364|365)"
+y := x asSeconds. "seconds elapsed since 1/1/1901"
+y := x addDays: 10. "add days to date object"
+y := x subtractDays: 10. "subtract days to date object"
+y := x subtractDate: (Date today). "subtract date (result in days)"
+y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date"
+b := (x <= Date today). "comparison"
+
+"************************************************************************
+ * Time: *
+ ************************************************************************"
+| x y |
+x := Time now. "create time from current time"
+x := Time dateAndTimeNow. "create time from current time/date"
+x := Time readFromString: '3:47:26 pm'. "create time from formatted string"
+x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight"
+y := Time millisecondClockValue. "milliseconds since midnight"
+y := Time totalSeconds. "total seconds since 1/1/1901"
+y := x seconds. "seconds past minute (0-59)"
+y := x minutes. "minutes past hour (0-59)"
+y := x hours. "hours past midnight (0-23)"
+y := x addTime: (Time now). "add time to time object"
+y := x subtractTime: (Time now). "subtract time to time object"
+y := x asSeconds. "convert time to seconds"
+x := Time millisecondsToRun: [ "timing facility"
+ 1 to: 1000 do: [:index | y := 3.14 * index]].
+b := (x <= Time now). "comparison"
+
+"************************************************************************
+ * Point: *
+ ************************************************************************"
+| x y |
+x := 200@100. "obtain a new point"
+y := x x. "x coordinate"
+y := x y. "y coordinate"
+x := 200@100 negated. "negates x and y"
+x := (-200@-100) abs. "absolute value of x and y"
+x := (200.5@100.5) rounded. "round x and y"
+x := (200.5@100.5) truncated. "truncate x and y"
+x := 200@100 + 100. "add scale to both x and y"
+x := 200@100 - 100. "subtract scale from both x and y"
+x := 200@100 * 2. "multiply x and y by scale"
+x := 200@100 / 2. "divide x and y by scale"
+x := 200@100 // 2. "divide x and y by scale"
+x := 200@100 \\ 3. "remainder of x and y by scale"
+x := 200@100 + 50@25. "add points"
+x := 200@100 - 50@25. "subtract points"
+x := 200@100 * 3@4. "multiply points"
+x := 200@100 // 3@4. "divide points"
+x := 200@100 max: 50@200. "max x and y"
+x := 200@100 min: 50@200. "min x and y"
+x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)"
+
+"************************************************************************
+ * Rectangle: *
+ ************************************************************************"
+Rectangle fromUser.
+
+"************************************************************************
+ * Pen: *
+ ************************************************************************"
+| myPen |
+Display restoreAfter: [
+ Display fillWhite.
+
+myPen := Pen new. "get graphic pen"
+myPen squareNib: 1.
+myPen color: (Color blue). "set pen color"
+myPen home. "position pen at center of display"
+myPen up. "makes nib unable to draw"
+myPen down. "enable the nib to draw"
+myPen north. "points direction towards top"
+myPen turn: -180. "add specified degrees to direction"
+myPen direction. "get current angle of pen"
+myPen go: 50. "move pen specified number of pixels"
+myPen location. "get the pen position"
+myPen goto: 200@200. "move to specified point"
+myPen place: 250@250. "move to specified point without drawing"
+myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1).
+Display extent. "get display width@height"
+Display width. "get display width"
+Display height. "get display height"
+
+].
+
+"************************************************************************
+ * Dynamic Message Calling/Compiling: *
+ ************************************************************************"
+| receiver message result argument keyword1 keyword2 argument1 argument2 |
+"unary message"
+receiver := 5.
+message := 'factorial' asSymbol.
+result := receiver perform: message.
+result := Compiler evaluate: ((receiver storeString), ' ', message).
+result := (Message new setSelector: message arguments: #()) sentTo: receiver.
+
+"binary message"
+receiver := 1.
+message := '+' asSymbol.
+argument := 2.
+result := receiver perform: message withArguments: (Array with: argument).
+result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)).
+result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver.
+
+"keyword messages"
+receiver := 12.
+keyword1 := 'between:' asSymbol.
+keyword2 := 'and:' asSymbol.
+argument1 := 10.
+argument2 := 20.
+result := receiver
+ perform: (keyword1, keyword2) asSymbol
+ withArguments: (Array with: argument1 with: argument2).
+result := Compiler evaluate:
+ ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)).
+result := (Message
+ new
+ setSelector: (keyword1, keyword2) asSymbol
+ arguments: (Array with: argument1 with: argument2))
+ sentTo: receiver.
+
+"************************************************************************
+ * class/meta-class: *
+ ************************************************************************"
+| b x |
+x := String name. "class name"
+x := String category. "organization category"
+x := String comment. "class comment"
+x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc"
+x := String definition. "class definition"
+x := String instVarNames. "immediate instance variable names"
+x := String allInstVarNames. "accumulated instance variable names"
+x := String classVarNames. "immediate class variable names"
+x := String allClassVarNames. "accumulated class variable names"
+x := String sharedPools. "immediate dictionaries used as shared pools"
+x := String allSharedPools. "accumulated dictionaries used as shared pools"
+x := String selectors. "message selectors for class"
+x := String sourceCodeAt: #size. "source code for specified method"
+x := String allInstances. "collection of all instances of class"
+x := String superclass. "immediate superclass"
+x := String allSuperclasses. "accumulated superclasses"
+x := String withAllSuperclasses. "receiver class and accumulated superclasses"
+x := String subclasses. "immediate subclasses"
+x := String allSubclasses. "accumulated subclasses"
+x := String withAllSubclasses. "receiver class and accumulated subclasses"
+b := String instSize. "number of named instance variables"
+b := String isFixed. "true if no indexed instance variables"
+b := String isVariable. "true if has indexed instance variables"
+b := String isPointers. "true if index instance vars contain objects"
+b := String isBits. "true if index instance vars contain bytes/words"
+b := String isBytes. "true if index instance vars contain bytes"
+b := String isWords. true if index instance vars contain words"
+Object withAllSubclasses size. "get total number of class entries"
+
+"************************************************************************
+ * debuging: *
+ ************************************************************************"
+| a b x |
+x yourself. "returns receiver"
+String browse. "browse specified class"
+x inspect. "open object inspector window"
+x confirm: 'Is this correct?'.
+x halt. "breakpoint to open debugger window"
+x halt: 'Halt message'.
+x notify: 'Notify text'.
+x error: 'Error string'. "open up error window with title"
+x doesNotUnderstand: #cmrMessage. "flag message is not handled"
+x shouldNotImplement. "flag message should not be implemented"
+x subclassResponsibility. "flag message as abstract"
+x errorImproperStore. "flag an improper store into indexable object"
+x errorNonIntegerIndex. "flag only integers should be used as index"
+x errorSubscriptBounds. "flag subscript out of bounds"
+x primitiveFailed. "system primitive failed"
+
+a := 'A1'. b := 'B2'. a become: b. "switch two objects"
+Transcript show: a, b; cr.
+
+"************************************************************************
+ * Misc. *
+ ************************************************************************"
+| x |
+"Smalltalk condenseChanges." "compress the change file"
+x := FillInTheBlank request: 'Prompt Me'. "prompt user for input"
+Utilities openCommandKeyHelp
+
+
+
+
+```
+
+## Ready For More?
+
+### 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)
+* [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/)
diff --git a/smalltalk.html.markdown~ b/smalltalk.html.markdown~
new file mode 100644
index 00000000..61e5a94c
--- /dev/null
+++ b/smalltalk.html.markdown~
@@ -0,0 +1,959 @@
+---
+language: smalltalk
+contributors:
+ - ["Jigyasa Grover", "https://github.com/jig08"]
+---
+
+- Smalltalk is an object-oriented, dynamically typed, reflective programming language.
+- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis."
+- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s.
+
+Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`.
+
+```
+
+"************************************************************************
+ * Allowable characters: *
+ * - a-z *
+ * - A-Z *
+ * - 0-9 *
+ * - .+/\*~<>@%|&? *
+ * - blank, tab, cr, ff, lf *
+ * *
+ * Variables: *
+ * - variables must be declared before use *
+ * - shared vars must begin with uppercase *
+ * - local vars must begin with lowercase *
+ * - reserved names: nil, true, false, self, super, and Smalltalk *
+ * *
+ * Variable scope: *
+ * - Global: defined in Dictionary Smalltalk and accessible by all *
+ * objects in system *
+ * - Special: (reserved) Smalltalk, super, self, true, false, & nil *
+ * - Method Temporary: local to a method *
+ * - Block Temporary: local to a block *
+ * - Pool: variables in a Dictionary object *
+ * - Method Parameters: automatic local vars created as a result of *
+ * message call with params *
+ * - Block Parameters: automatic local vars created as a result of *
+ * value: message call *
+ * - Class: shared with all instances of one class & its subclasses *
+ * - Class Instance: unique to each instance of a class *
+ * - Instance Variables: unique to each instance *
+ ************************************************************************"
+"Comments are enclosed in quotes"
+"Period (.) is the statement seperator"
+
+"************************************************************************
+ * Transcript: *
+ ************************************************************************"
+Transcript clear. "clear to transcript window"
+Transcript show: 'Hello World'. "output string in transcript window"
+Transcript nextPutAll: 'Hello World'. "output string in transcript window"
+Transcript nextPut: $A. "output character in transcript window"
+Transcript space. "output space character in transcript window"
+Transcript tab. "output tab character in transcript window"
+Transcript cr. "carriage return / linefeed"
+'Hello' printOn: Transcript. "append print string into the window"
+'Hello' storeOn: Transcript. "append store string into the window"
+Transcript endEntry. "flush the output buffer"
+
+"************************************************************************
+ * Assignment: *
+ ************************************************************************"
+| x y |
+x _ 4. "assignment (Squeak) <-"
+x := 5. "assignment"
+x := y := z := 6. "compound assignment"
+x := (y := 6) + 1.
+x := Object new. "bind to allocated instance of a class"
+x := 123 class. "discover the object class"
+x := Integer superclass. "discover the superclass of a class"
+x := Object allInstances. "get an array of all instances of a class"
+x := Integer allSuperclasses. "get all superclasses of a class"
+x := 1.2 hash. "hash value for object"
+y := x copy. "copy object"
+y := x shallowCopy. "copy object (not overridden)"
+y := x deepCopy. "copy object and instance vars"
+y := x veryDeepCopy. "complete tree copy using a dictionary"
+
+"************************************************************************
+ * Constants: *
+ ************************************************************************"
+| b |
+b := true. "true constant"
+b := false. "false constant"
+x := nil. "nil object constant"
+x := 1. "integer constants"
+x := 3.14. "float constants"
+x := 2e-2. "fractional constants"
+x := 16r0F. "hex constant".
+x := -1. "negative constants"
+x := 'Hello'. "string constant"
+x := 'I''m here'. "single quote escape"
+x := $A. "character constant"
+x := $ . "character constant (space)"
+x := #aSymbol. "symbol constants"
+x := #(3 2 1). "array constants"
+x := #('abc' 2 $a). "mixing of types allowed"
+
+"************************************************************************
+ * Booleans: *
+ ************************************************************************"
+| b x y |
+x := 1. y := 2.
+b := (x = y). "equals"
+b := (x ~= y). "not equals"
+b := (x == y). "identical"
+b := (x ~~ y). "not identical"
+b := (x > y). "greater than"
+b := (x < y). "less than"
+b := (x >= y). "greater than or equal"
+b := (x <= y). "less than or equal"
+b := b not. "boolean not"
+b := (x < 5) & (y > 1). "boolean and"
+b := (x < 5) | (y > 1). "boolean or"
+b := (x < 5) and: [y > 1]. "boolean and (short-circuit)"
+b := (x < 5) or: [y > 1]. "boolean or (short-circuit)"
+b := (x < 5) eqv: (y > 1). "test if both true or both false"
+b := (x < 5) xor: (y > 1). "test if one true and other false"
+b := 5 between: 3 and: 12. "between (inclusive)"
+b := 123 isKindOf: Number. "test if object is class or subclass of"
+b := 123 isMemberOf: SmallInteger. "test if object is type of class"
+b := 123 respondsTo: sqrt. "test if object responds to message"
+b := x isNil. "test if object is nil"
+b := x isZero. "test if number is zero"
+b := x positive. "test if number is positive"
+b := x strictlyPositive. "test if number is greater than zero"
+b := x negative. "test if number is negative"
+b := x even. "test if number is even"
+b := x odd. "test if number is odd"
+b := x isLiteral. "test if literal constant"
+b := x isInteger. "test if object is integer"
+b := x isFloat. "test if object is float"
+b := x isNumber. "test if object is number"
+b := $A isUppercase. "test if upper case character"
+b := $A isLowercase. "test if lower case character"
+
+"************************************************************************
+ * Arithmetic expressions: *
+ ************************************************************************"
+| x |
+x := 6 + 3. "addition"
+x := 6 - 3. "subtraction"
+x := 6 * 3. "multiplication"
+x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3"
+x := 5 / 3. "division with fractional result"
+x := 5.0 / 3.0. "division with float result"
+x := 5.0 // 3.0. "integer divide"
+x := 5.0 \\ 3.0. "integer remainder"
+x := -5. "unary minus"
+x := 5 sign. "numeric sign (1, -1 or 0)"
+x := 5 negated. "negate receiver"
+x := 1.2 integerPart. "integer part of number (1.0)"
+x := 1.2 fractionPart. "fractional part of number (0.2)"
+x := 5 reciprocal. "reciprocal function"
+x := 6 * 3.1. "auto convert to float"
+x := 5 squared. "square function"
+x := 25 sqrt. "square root"
+x := 5 raisedTo: 2. "power function"
+x := 5 raisedToInteger: 2. "power function with integer"
+x := 5 exp. "exponential"
+x := -5 abs. "absolute value"
+x := 3.99 rounded. "round"
+x := 3.99 truncated. "truncate"
+x := 3.99 roundTo: 1. "round to specified decimal places"
+x := 3.99 truncateTo: 1. "truncate to specified decimal places"
+x := 3.99 floor. "truncate"
+x := 3.99 ceiling. "round up"
+x := 5 factorial. "factorial"
+x := -5 quo: 3. "integer divide rounded toward zero"
+x := -5 rem: 3. "integer remainder rounded toward zero"
+x := 28 gcd: 12. "greatest common denominator"
+x := 28 lcm: 12. "least common multiple"
+x := 100 ln. "natural logarithm"
+x := 100 log. "base 10 logarithm"
+x := 100 log: 10. "logarithm with specified base"
+x := 100 floorLog: 10. "floor of the log"
+x := 180 degreesToRadians. "convert degrees to radians"
+x := 3.14 radiansToDegrees. "convert radians to degrees"
+x := 0.7 sin. "sine"
+x := 0.7 cos. "cosine"
+x := 0.7 tan. "tangent"
+x := 0.7 arcSin. "arcsine"
+x := 0.7 arcCos. "arccosine"
+x := 0.7 arcTan. "arctangent"
+x := 10 max: 20. "get maximum of two numbers"
+x := 10 min: 20. "get minimum of two numbers"
+x := Float pi. "pi"
+x := Float e. "exp constant"
+x := Float infinity. "infinity"
+x := Float nan. "not-a-number"
+x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)
+x := 100 atRandom. "quick random number"
+
+"************************************************************************
+ * Bitwise Manipulation: *
+ ************************************************************************"
+| b x |
+x := 16rFF bitAnd: 16r0F. "and bits"
+x := 16rF0 bitOr: 16r0F. "or bits"
+x := 16rFF bitXor: 16r0F. "xor bits"
+x := 16rFF bitInvert. "invert bits"
+x := 16r0F bitShift: 4. "left shift"
+x := 16rF0 bitShift: -4. "right shift"
+"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]"
+x := 16r80 highbit. "position of highest bit set"
+b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver"
+b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver"
+b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver"
+
+"************************************************************************
+ * Conversion: *
+ ************************************************************************"
+| x |
+x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
+x := 3.99 asFraction. "convert number to fraction"
+x := 3 asFloat. "convert number to float"
+x := 65 asCharacter. "convert integer to character"
+x := $A asciiValue. "convert character to integer"
+x := 3.99 printString. "convert object to string via printOn:"
+x := 3.99 storeString. "convert object to string via storeOn:"
+x := 15 radix: 16. "convert to string in given base"
+x := 15 printStringBase: 16.
+x := 15 storeStringBase: 16.
+
+"************************************************************************
+ * Blocks: *
+ * - blocks are objects and may be assigned to a variable *
+ * - value is last expression evaluated unless explicit return *
+ * - blocks may be nested *
+ * - specification [ arguments | | localvars | expressions ] *
+ * - Squeak does not currently support localvars in blocks *
+ * - max of three arguments allowed *
+ * - ^expression terminates block & method (exits all nested blocks) *
+ * - blocks intended for long term storage should not contain ^ *
+ ************************************************************************"
+| x y z |
+x := [ y := 1. z := 2. ]. x value. "simple block usage"
+x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing"
+Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing"
+"x := [ | z | z := 1.]. localvars not available in squeak blocks"
+
+"************************************************************************
+ * Method calls: *
+ * - unary methods are messages with no arguments *
+ * - binary methods *
+ * - keyword methods are messages with selectors including colons *
+ * *
+ * standard categories/protocols: *
+ * - initialize-release (methods called for new instance) *
+ * - accessing (get/set methods) *
+ * - testing (boolean tests - is) *
+ * - comparing (boolean tests with parameter *
+ * - displaying (gui related methods) *
+ * - printing (methods for printing) *
+ * - updating (receive notification of changes) *
+ * - private (methods private to class) *
+ * - instance-creation (class methods for creating instance) *
+ ************************************************************************"
+| x |
+x := 2 sqrt. "unary message"
+x := 2 raisedTo: 10. "keyword message"
+x := 194 * 9. "binary message"
+Transcript show: (194 * 9) printString; cr. "combination (chaining)"
+x := 2 perform: #sqrt. "indirect method invocation"
+Transcript "Cascading - send multiple messages to receiver"
+ show: 'hello ';
+ show: 'world';
+ cr.
+x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)"
+
+"************************************************************************
+ * Conditional Statements: *
+ ************************************************************************"
+| x |
+x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then"
+x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else"
+x > 10 "if then else"
+ ifTrue: [Transcript show: 'ifTrue'; cr]
+ ifFalse: [Transcript show: 'ifFalse'; cr].
+x > 10 "if else then"
+ ifFalse: [Transcript show: 'ifFalse'; cr]
+ ifTrue: [Transcript show: 'ifTrue'; cr].
+Transcript
+ show:
+ (x > 10
+ ifTrue: ['ifTrue']
+ ifFalse: ['ifFalse']);
+ cr.
+Transcript "nested if then else"
+ show:
+ (x > 10
+ ifTrue: [x > 5
+ ifTrue: ['A']
+ ifFalse: ['B']]
+ ifFalse: ['C']);
+ cr.
+switch := Dictionary new. "switch functionality"
+switch at: $A put: [Transcript show: 'Case A'; cr].
+switch at: $B put: [Transcript show: 'Case B'; cr].
+switch at: $C put: [Transcript show: 'Case C'; cr].
+result := (switch at: $B) value.
+
+"************************************************************************
+ * Iteration statements: *
+ ************************************************************************"
+| x y |
+x := 4. y := 1.
+[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop"
+[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop"
+x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)"
+1 to: x do: [:a | y := y * 2]. "for loop"
+1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment"
+#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
+
+"************************************************************************
+ * Character: *
+ ************************************************************************"
+| x y |
+x := $A. "character assignment"
+y := x isLowercase. "test if lower case"
+y := x isUppercase. "test if upper case"
+y := x isLetter. "test if letter"
+y := x isDigit. "test if digit"
+y := x isAlphaNumeric. "test if alphanumeric"
+y := x isSeparator. "test if seperator char"
+y := x isVowel. "test if vowel"
+y := x digitValue. "convert to numeric digit value"
+y := x asLowercase. "convert to lower case"
+y := x asUppercase. "convert to upper case"
+y := x asciiValue. "convert to numeric ascii value"
+y := x asString. "convert to string"
+b := $A <= $B. "comparison"
+y := $A max: $B.
+
+"************************************************************************
+ * Symbol: *
+ ************************************************************************"
+| b x y |
+x := #Hello. "symbol assignment"
+y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
+b := x isEmpty. "test if symbol is empty"
+y := x size. "string size"
+y := x at: 2. "char at location"
+y := x copyFrom: 2 to: 4. "substring"
+y := x indexOf: $e ifAbsent: [0]. "first position of character within string"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
+b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
+y := x select: [:a | a > $a]. "return all elements that meet condition"
+y := x asString. "convert symbol to string"
+y := x asText. "convert symbol to text"
+y := x asArray. "convert symbol to array"
+y := x asOrderedCollection. "convert symbol to ordered collection"
+y := x asSortedCollection. "convert symbol to sorted collection"
+y := x asBag. "convert symbol to bag collection"
+y := x asSet. "convert symbol to set collection"
+
+"************************************************************************
+ * String: *
+ ************************************************************************"
+| b x y |
+x := 'This is a string'. "string assignment"
+x := 'String', 'Concatenation'. "string concatenation"
+b := x isEmpty. "test if string is empty"
+y := x size. "string size"
+y := x at: 2. "char at location"
+y := x copyFrom: 2 to: 4. "substring"
+y := x indexOf: $a ifAbsent: [0]. "first position of character within string"
+x := String new: 4. "allocate string object"
+x "set string elements"
+ at: 1 put: $a;
+ at: 2 put: $b;
+ at: 3 put: $c;
+ at: 4 put: $e.
+x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
+b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
+y := x select: [:a | a > $a]. "return all elements that meet condition"
+y := x asSymbol. "convert string to symbol"
+y := x asArray. "convert string to array"
+x := 'ABCD' asByteArray. "convert string to byte array"
+y := x asOrderedCollection. "convert string to ordered collection"
+y := x asSortedCollection. "convert string to sorted collection"
+y := x asBag. "convert string to bag collection"
+y := x asSet. "convert string to set collection"
+y := x shuffled. "randomly shuffle string"
+
+"************************************************************************
+ * Array: Fixed length collection *
+ * ByteArray: Array limited to byte elements (0-255) *
+ * WordArray: Array limited to word elements (0-2^32) *
+ ************************************************************************"
+| b x y sum max |
+x := #(4 3 2 1). "constant array"
+x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements"
+x := Array new: 4. "allocate an array with specified size"
+x "set array elements"
+ at: 1 put: 5;
+ at: 2 put: 4;
+ at: 3 put: 3;
+ at: 4 put: 2.
+b := x isEmpty. "test if array is empty"
+y := x size. "array size"
+y := x at: 4. "get array element at index"
+b := x includes: 3. "test if element is in array"
+y := x copyFrom: 2 to: 4. "subarray"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within array"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the array"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum array elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in array"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x shuffled. "randomly shuffle collection"
+y := x asArray. "convert to array"
+"y := x asByteArray." "note: this instruction not available on Squeak"
+y := x asWordArray. "convert to word array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * OrderedCollection: acts like an expandable array *
+ ************************************************************************"
+| b x y sum max |
+x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := OrderedCollection new. "allocate collection"
+x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
+y := x addFirst: 5. "add element at beginning of collection"
+y := x removeFirst. "remove first element in collection"
+y := x addLast: 6. "add element at end of collection"
+y := x removeLast. "remove last element in collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+x at: 2 put: 3. "set element at index"
+y := x remove: 5 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: 2. "retrieve element at index"
+y := x first. "retrieve first element in collection"
+y := x last. "retrieve last element in collection"
+b := x includes: 5. "test if element is in collection"
+y := x copyFrom: 2 to: 3. "subcollection"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x shuffled. "randomly shuffle collection"
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * SortedCollection: like OrderedCollection except order of elements *
+ * determined by sorting criteria *
+ ************************************************************************"
+| b x y sum max |
+x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := SortedCollection new. "allocate collection"
+x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria"
+x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
+y := x addFirst: 5. "add element at beginning of collection"
+y := x removeFirst. "remove first element in collection"
+y := x addLast: 6. "add element at end of collection"
+y := x removeLast. "remove last element in collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 5 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: 2. "retrieve element at index"
+y := x first. "retrieve first element in collection"
+y := x last. "retrieve last element in collection"
+b := x includes: 4. "test if element is in collection"
+y := x copyFrom: 2 to: 3. "subcollection"
+y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Bag: like OrderedCollection except elements are in no *
+ * particular order *
+ ************************************************************************"
+| b x y sum max |
+x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := Bag new. "allocate collection"
+x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
+x add: 3 withOccurrences: 2. "add multiple copies to collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 4 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+b := x includes: 3. "test if element is in collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Set: like Bag except duplicates not allowed *
+ * IdentitySet: uses identity test (== rather than =) *
+ ************************************************************************"
+| b x y sum max |
+x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
+x := Set new. "allocate collection"
+x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
+y := x addAll: #(7 8 9). "add multiple elements to collection"
+y := x removeAll: #(7 8 9). "remove multiple elements from collection"
+y := x remove: 4 ifAbsent: []. "remove element from collection"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+x includes: 4. "test if element is in collection"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Interval: *
+ ************************************************************************"
+| b x y sum max |
+x := Interval from: 5 to: 10. "create interval object"
+x := 5 to: 10.
+x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment"
+x := 5 to: 10 by: 2.
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+x includes: 9. "test if element is in collection"
+x do: [:k | Transcript show: k printString; cr]. "iterate over interval"
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 7]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+"************************************************************************
+ * Associations: *
+ ************************************************************************"
+| x y |
+x := #myVar->'hello'.
+y := x key.
+y := x value.
+
+"************************************************************************
+ * Dictionary: *
+ * IdentityDictionary: uses identity test (== rather than =) *
+ ************************************************************************"
+| b x y |
+x := Dictionary new. "allocate collection"
+x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection"
+x at: #e put: 3. "set element at index"
+b := x isEmpty. "test if empty"
+y := x size. "number of elements"
+y := x at: #a ifAbsent: []. "retrieve element at index"
+y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block"
+y := x removeKey: #e ifAbsent: []. "remove element from collection"
+b := x includes: 3. "test if element is in values collection"
+b := x includesKey: #a. "test if element is in keys collection"
+y := x occurrencesOf: 3. "number of times object in collection"
+y := x keys. "set of keys"
+y := x values. "bag of values"
+x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection"
+x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection"
+x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations"
+x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values"
+ show: aKey printString; space;
+ show: aValue printString; cr].
+b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
+y := x select: [:a | a > 2]. "return collection of elements that pass test"
+y := x reject: [:a | a < 2]. "return collection of elements that fail test"
+y := x collect: [:a | a + a]. "transform each element for new collection"
+y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
+sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
+sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
+max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
+ ifTrue: [a]
+ ifFalse: [c]].
+y := x asArray. "convert to array"
+y := x asOrderedCollection. "convert to ordered collection"
+y := x asSortedCollection. "convert to sorted collection"
+y := x asBag. "convert to bag collection"
+y := x asSet. "convert to set collection"
+
+Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary"
+x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary"
+Transcript show: (CMRGlobal printString). "entries are directly accessible by name"
+Smalltalk keys do: [ :k | "print out all classes"
+ ((Smalltalk at: k) isKindOf: Class)
+ ifFalse: [Transcript show: k printString; cr]].
+Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary"
+CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary"
+CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo"
+CMRDictionary size. "dictionary size"
+CMRDictionary keys do: [ :k | "print out keys in dictionary"
+ Transcript show: k printString; cr].
+CMRDictionary values do: [ :k | "print out values in dictionary"
+ Transcript show: k printString; cr].
+CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values"
+ Transcript
+ show: aKey printString;
+ space;
+ show: aValue printString;
+ cr].
+CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values"
+ Transcript show: aKeyValue printString; cr].
+Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary"
+Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary"
+
+"************************************************************************
+ * Internal Stream: *
+ ************************************************************************"
+| b x ios |
+ios := ReadStream on: 'Hello read stream'.
+ios := ReadStream on: 'Hello read stream' from: 1 to: 5.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 3.
+ios position.
+x := ios next.
+x := ios peek.
+x := ios contents.
+b := ios atEnd.
+
+ios := ReadWriteStream on: 'Hello read stream'.
+ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5.
+ios := ReadWriteStream with: 'Hello read stream'.
+ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10.
+ios position: 0.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 6.
+ios position.
+ios nextPutAll: 'Chris'.
+x := ios next.
+x := ios peek.
+x := ios contents.
+b := ios atEnd.
+
+"************************************************************************
+ * FileStream: *
+ ************************************************************************"
+| b x ios |
+ios := FileStream newFileNamed: 'ios.txt'.
+ios nextPut: $H; cr.
+ios nextPutAll: 'Hello File'; cr.
+'Hello File' printOn: ios.
+'Hello File' storeOn: ios.
+ios close.
+
+ios := FileStream oldFileNamed: 'ios.txt'.
+[(x := ios nextLine) notNil]
+ whileTrue: [Transcript show: x; cr].
+ios position: 3.
+x := ios position.
+x := ios next.
+x := ios peek.
+b := ios atEnd.
+ios close.
+
+"************************************************************************
+ * Date: *
+ ************************************************************************"
+| x y |
+x := Date today. "create date for today"
+x := Date dateAndTimeNow. "create date from current time/date"
+x := Date readFromString: '01/02/1999'. "create date from formatted string"
+x := Date newDay: 12 month: #July year: 1999 "create date from parts"
+x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901"
+y := Date dayOfWeek: #Monday. "day of week as int (1-7)"
+y := Date indexOfMonth: #January. "month of year as int (1-12)"
+y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)"
+y := Date daysInYear: 1996. "days in year (365|366)"
+y := Date nameOfDay: 1 "weekday name (#Monday,...)"
+y := Date nameOfMonth: 1. "month name (#January,...)"
+y := Date leapYear: 1996. "1 if leap year; 0 if not leap year"
+y := x weekday. "day of week (#Monday,...)"
+y := x previous: #Monday. "date for previous day of week"
+y := x dayOfMonth. "day of month (1-31)"
+y := x day. "day of year (1-366)"
+y := x firstDayOfMonth. "day of year for first day of month"
+y := x monthName. "month of year (#January,...)"
+y := x monthIndex. "month of year (1-12)"
+y := x daysInMonth. "days in month (1-31)"
+y := x year. "year (19xx)"
+y := x daysInYear. "days in year (365|366)"
+y := x daysLeftInYear. "days left in year (364|365)"
+y := x asSeconds. "seconds elapsed since 1/1/1901"
+y := x addDays: 10. "add days to date object"
+y := x subtractDays: 10. "subtract days to date object"
+y := x subtractDate: (Date today). "subtract date (result in days)"
+y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date"
+b := (x <= Date today). "comparison"
+
+"************************************************************************
+ * Time: *
+ ************************************************************************"
+| x y |
+x := Time now. "create time from current time"
+x := Time dateAndTimeNow. "create time from current time/date"
+x := Time readFromString: '3:47:26 pm'. "create time from formatted string"
+x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight"
+y := Time millisecondClockValue. "milliseconds since midnight"
+y := Time totalSeconds. "total seconds since 1/1/1901"
+y := x seconds. "seconds past minute (0-59)"
+y := x minutes. "minutes past hour (0-59)"
+y := x hours. "hours past midnight (0-23)"
+y := x addTime: (Time now). "add time to time object"
+y := x subtractTime: (Time now). "subtract time to time object"
+y := x asSeconds. "convert time to seconds"
+x := Time millisecondsToRun: [ "timing facility"
+ 1 to: 1000 do: [:index | y := 3.14 * index]].
+b := (x <= Time now). "comparison"
+
+"************************************************************************
+ * Point: *
+ ************************************************************************"
+| x y |
+x := 200@100. "obtain a new point"
+y := x x. "x coordinate"
+y := x y. "y coordinate"
+x := 200@100 negated. "negates x and y"
+x := (-200@-100) abs. "absolute value of x and y"
+x := (200.5@100.5) rounded. "round x and y"
+x := (200.5@100.5) truncated. "truncate x and y"
+x := 200@100 + 100. "add scale to both x and y"
+x := 200@100 - 100. "subtract scale from both x and y"
+x := 200@100 * 2. "multiply x and y by scale"
+x := 200@100 / 2. "divide x and y by scale"
+x := 200@100 // 2. "divide x and y by scale"
+x := 200@100 \\ 3. "remainder of x and y by scale"
+x := 200@100 + 50@25. "add points"
+x := 200@100 - 50@25. "subtract points"
+x := 200@100 * 3@4. "multiply points"
+x := 200@100 // 3@4. "divide points"
+x := 200@100 max: 50@200. "max x and y"
+x := 200@100 min: 50@200. "min x and y"
+x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)"
+
+"************************************************************************
+ * Rectangle: *
+ ************************************************************************"
+Rectangle fromUser.
+
+"************************************************************************
+ * Pen: *
+ ************************************************************************"
+| myPen |
+Display restoreAfter: [
+ Display fillWhite.
+
+myPen := Pen new. "get graphic pen"
+myPen squareNib: 1.
+myPen color: (Color blue). "set pen color"
+myPen home. "position pen at center of display"
+myPen up. "makes nib unable to draw"
+myPen down. "enable the nib to draw"
+myPen north. "points direction towards top"
+myPen turn: -180. "add specified degrees to direction"
+myPen direction. "get current angle of pen"
+myPen go: 50. "move pen specified number of pixels"
+myPen location. "get the pen position"
+myPen goto: 200@200. "move to specified point"
+myPen place: 250@250. "move to specified point without drawing"
+myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1).
+Display extent. "get display width@height"
+Display width. "get display width"
+Display height. "get display height"
+
+].
+
+"************************************************************************
+ * Dynamic Message Calling/Compiling: *
+ ************************************************************************"
+| receiver message result argument keyword1 keyword2 argument1 argument2 |
+"unary message"
+receiver := 5.
+message := 'factorial' asSymbol.
+result := receiver perform: message.
+result := Compiler evaluate: ((receiver storeString), ' ', message).
+result := (Message new setSelector: message arguments: #()) sentTo: receiver.
+
+"binary message"
+receiver := 1.
+message := '+' asSymbol.
+argument := 2.
+result := receiver perform: message withArguments: (Array with: argument).
+result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)).
+result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver.
+
+"keyword messages"
+receiver := 12.
+keyword1 := 'between:' asSymbol.
+keyword2 := 'and:' asSymbol.
+argument1 := 10.
+argument2 := 20.
+result := receiver
+ perform: (keyword1, keyword2) asSymbol
+ withArguments: (Array with: argument1 with: argument2).
+result := Compiler evaluate:
+ ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)).
+result := (Message
+ new
+ setSelector: (keyword1, keyword2) asSymbol
+ arguments: (Array with: argument1 with: argument2))
+ sentTo: receiver.
+
+"************************************************************************
+ * class/meta-class: *
+ ************************************************************************"
+| b x |
+x := String name. "class name"
+x := String category. "organization category"
+x := String comment. "class comment"
+x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc"
+x := String definition. "class definition"
+x := String instVarNames. "immediate instance variable names"
+x := String allInstVarNames. "accumulated instance variable names"
+x := String classVarNames. "immediate class variable names"
+x := String allClassVarNames. "accumulated class variable names"
+x := String sharedPools. "immediate dictionaries used as shared pools"
+x := String allSharedPools. "accumulated dictionaries used as shared pools"
+x := String selectors. "message selectors for class"
+x := String sourceCodeAt: #size. "source code for specified method"
+x := String allInstances. "collection of all instances of class"
+x := String superclass. "immediate superclass"
+x := String allSuperclasses. "accumulated superclasses"
+x := String withAllSuperclasses. "receiver class and accumulated superclasses"
+x := String subclasses. "immediate subclasses"
+x := String allSubclasses. "accumulated subclasses"
+x := String withAllSubclasses. "receiver class and accumulated subclasses"
+b := String instSize. "number of named instance variables"
+b := String isFixed. "true if no indexed instance variables"
+b := String isVariable. "true if has indexed instance variables"
+b := String isPointers. "true if index instance vars contain objects"
+b := String isBits. "true if index instance vars contain bytes/words"
+b := String isBytes. "true if index instance vars contain bytes"
+b := String isWords. true if index instance vars contain words"
+Object withAllSubclasses size. "get total number of class entries"
+
+"************************************************************************
+ * debuging: *
+ ************************************************************************"
+| a b x |
+x yourself. "returns receiver"
+String browse. "browse specified class"
+x inspect. "open object inspector window"
+x confirm: 'Is this correct?'.
+x halt. "breakpoint to open debugger window"
+x halt: 'Halt message'.
+x notify: 'Notify text'.
+x error: 'Error string'. "open up error window with title"
+x doesNotUnderstand: #cmrMessage. "flag message is not handled"
+x shouldNotImplement. "flag message should not be implemented"
+x subclassResponsibility. "flag message as abstract"
+x errorImproperStore. "flag an improper store into indexable object"
+x errorNonIntegerIndex. "flag only integers should be used as index"
+x errorSubscriptBounds. "flag subscript out of bounds"
+x primitiveFailed. "system primitive failed"
+
+a := 'A1'. b := 'B2'. a become: b. "switch two objects"
+Transcript show: a, b; cr.
+
+"************************************************************************
+ * Misc. *
+ ************************************************************************"
+| x |
+"Smalltalk condenseChanges." "compress the change file"
+x := FillInTheBlank request: 'Prompt Me'. "prompt user for input"
+Utilities openCommandKeyHelp
+
+
+
+
+```
+
+## Ready For More?
+
+### 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)
+* [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/)
--
cgit v1.2.3
From d704d06976f003faf06eb68764b06508044b7500 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:15:46 +0530
Subject: Delete .Rhistory
---
ko-kr/.Rhistory | 0
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 ko-kr/.Rhistory
diff --git a/ko-kr/.Rhistory b/ko-kr/.Rhistory
deleted file mode 100644
index e69de29b..00000000
--
cgit v1.2.3
From add1edbeb23ca058c1652b6031a3bf2f8f3c5191 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:16:17 +0530
Subject: Delete smalltalk.html.markdown~
---
smalltalk.html.markdown~ | 959 -----------------------------------------------
1 file changed, 959 deletions(-)
delete mode 100644 smalltalk.html.markdown~
diff --git a/smalltalk.html.markdown~ b/smalltalk.html.markdown~
deleted file mode 100644
index 61e5a94c..00000000
--- a/smalltalk.html.markdown~
+++ /dev/null
@@ -1,959 +0,0 @@
----
-language: smalltalk
-contributors:
- - ["Jigyasa Grover", "https://github.com/jig08"]
----
-
-- Smalltalk is an object-oriented, dynamically typed, reflective programming language.
-- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis."
-- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s.
-
-Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`.
-
-```
-
-"************************************************************************
- * Allowable characters: *
- * - a-z *
- * - A-Z *
- * - 0-9 *
- * - .+/\*~<>@%|&? *
- * - blank, tab, cr, ff, lf *
- * *
- * Variables: *
- * - variables must be declared before use *
- * - shared vars must begin with uppercase *
- * - local vars must begin with lowercase *
- * - reserved names: nil, true, false, self, super, and Smalltalk *
- * *
- * Variable scope: *
- * - Global: defined in Dictionary Smalltalk and accessible by all *
- * objects in system *
- * - Special: (reserved) Smalltalk, super, self, true, false, & nil *
- * - Method Temporary: local to a method *
- * - Block Temporary: local to a block *
- * - Pool: variables in a Dictionary object *
- * - Method Parameters: automatic local vars created as a result of *
- * message call with params *
- * - Block Parameters: automatic local vars created as a result of *
- * value: message call *
- * - Class: shared with all instances of one class & its subclasses *
- * - Class Instance: unique to each instance of a class *
- * - Instance Variables: unique to each instance *
- ************************************************************************"
-"Comments are enclosed in quotes"
-"Period (.) is the statement seperator"
-
-"************************************************************************
- * Transcript: *
- ************************************************************************"
-Transcript clear. "clear to transcript window"
-Transcript show: 'Hello World'. "output string in transcript window"
-Transcript nextPutAll: 'Hello World'. "output string in transcript window"
-Transcript nextPut: $A. "output character in transcript window"
-Transcript space. "output space character in transcript window"
-Transcript tab. "output tab character in transcript window"
-Transcript cr. "carriage return / linefeed"
-'Hello' printOn: Transcript. "append print string into the window"
-'Hello' storeOn: Transcript. "append store string into the window"
-Transcript endEntry. "flush the output buffer"
-
-"************************************************************************
- * Assignment: *
- ************************************************************************"
-| x y |
-x _ 4. "assignment (Squeak) <-"
-x := 5. "assignment"
-x := y := z := 6. "compound assignment"
-x := (y := 6) + 1.
-x := Object new. "bind to allocated instance of a class"
-x := 123 class. "discover the object class"
-x := Integer superclass. "discover the superclass of a class"
-x := Object allInstances. "get an array of all instances of a class"
-x := Integer allSuperclasses. "get all superclasses of a class"
-x := 1.2 hash. "hash value for object"
-y := x copy. "copy object"
-y := x shallowCopy. "copy object (not overridden)"
-y := x deepCopy. "copy object and instance vars"
-y := x veryDeepCopy. "complete tree copy using a dictionary"
-
-"************************************************************************
- * Constants: *
- ************************************************************************"
-| b |
-b := true. "true constant"
-b := false. "false constant"
-x := nil. "nil object constant"
-x := 1. "integer constants"
-x := 3.14. "float constants"
-x := 2e-2. "fractional constants"
-x := 16r0F. "hex constant".
-x := -1. "negative constants"
-x := 'Hello'. "string constant"
-x := 'I''m here'. "single quote escape"
-x := $A. "character constant"
-x := $ . "character constant (space)"
-x := #aSymbol. "symbol constants"
-x := #(3 2 1). "array constants"
-x := #('abc' 2 $a). "mixing of types allowed"
-
-"************************************************************************
- * Booleans: *
- ************************************************************************"
-| b x y |
-x := 1. y := 2.
-b := (x = y). "equals"
-b := (x ~= y). "not equals"
-b := (x == y). "identical"
-b := (x ~~ y). "not identical"
-b := (x > y). "greater than"
-b := (x < y). "less than"
-b := (x >= y). "greater than or equal"
-b := (x <= y). "less than or equal"
-b := b not. "boolean not"
-b := (x < 5) & (y > 1). "boolean and"
-b := (x < 5) | (y > 1). "boolean or"
-b := (x < 5) and: [y > 1]. "boolean and (short-circuit)"
-b := (x < 5) or: [y > 1]. "boolean or (short-circuit)"
-b := (x < 5) eqv: (y > 1). "test if both true or both false"
-b := (x < 5) xor: (y > 1). "test if one true and other false"
-b := 5 between: 3 and: 12. "between (inclusive)"
-b := 123 isKindOf: Number. "test if object is class or subclass of"
-b := 123 isMemberOf: SmallInteger. "test if object is type of class"
-b := 123 respondsTo: sqrt. "test if object responds to message"
-b := x isNil. "test if object is nil"
-b := x isZero. "test if number is zero"
-b := x positive. "test if number is positive"
-b := x strictlyPositive. "test if number is greater than zero"
-b := x negative. "test if number is negative"
-b := x even. "test if number is even"
-b := x odd. "test if number is odd"
-b := x isLiteral. "test if literal constant"
-b := x isInteger. "test if object is integer"
-b := x isFloat. "test if object is float"
-b := x isNumber. "test if object is number"
-b := $A isUppercase. "test if upper case character"
-b := $A isLowercase. "test if lower case character"
-
-"************************************************************************
- * Arithmetic expressions: *
- ************************************************************************"
-| x |
-x := 6 + 3. "addition"
-x := 6 - 3. "subtraction"
-x := 6 * 3. "multiplication"
-x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3"
-x := 5 / 3. "division with fractional result"
-x := 5.0 / 3.0. "division with float result"
-x := 5.0 // 3.0. "integer divide"
-x := 5.0 \\ 3.0. "integer remainder"
-x := -5. "unary minus"
-x := 5 sign. "numeric sign (1, -1 or 0)"
-x := 5 negated. "negate receiver"
-x := 1.2 integerPart. "integer part of number (1.0)"
-x := 1.2 fractionPart. "fractional part of number (0.2)"
-x := 5 reciprocal. "reciprocal function"
-x := 6 * 3.1. "auto convert to float"
-x := 5 squared. "square function"
-x := 25 sqrt. "square root"
-x := 5 raisedTo: 2. "power function"
-x := 5 raisedToInteger: 2. "power function with integer"
-x := 5 exp. "exponential"
-x := -5 abs. "absolute value"
-x := 3.99 rounded. "round"
-x := 3.99 truncated. "truncate"
-x := 3.99 roundTo: 1. "round to specified decimal places"
-x := 3.99 truncateTo: 1. "truncate to specified decimal places"
-x := 3.99 floor. "truncate"
-x := 3.99 ceiling. "round up"
-x := 5 factorial. "factorial"
-x := -5 quo: 3. "integer divide rounded toward zero"
-x := -5 rem: 3. "integer remainder rounded toward zero"
-x := 28 gcd: 12. "greatest common denominator"
-x := 28 lcm: 12. "least common multiple"
-x := 100 ln. "natural logarithm"
-x := 100 log. "base 10 logarithm"
-x := 100 log: 10. "logarithm with specified base"
-x := 100 floorLog: 10. "floor of the log"
-x := 180 degreesToRadians. "convert degrees to radians"
-x := 3.14 radiansToDegrees. "convert radians to degrees"
-x := 0.7 sin. "sine"
-x := 0.7 cos. "cosine"
-x := 0.7 tan. "tangent"
-x := 0.7 arcSin. "arcsine"
-x := 0.7 arcCos. "arccosine"
-x := 0.7 arcTan. "arctangent"
-x := 10 max: 20. "get maximum of two numbers"
-x := 10 min: 20. "get minimum of two numbers"
-x := Float pi. "pi"
-x := Float e. "exp constant"
-x := Float infinity. "infinity"
-x := Float nan. "not-a-number"
-x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)
-x := 100 atRandom. "quick random number"
-
-"************************************************************************
- * Bitwise Manipulation: *
- ************************************************************************"
-| b x |
-x := 16rFF bitAnd: 16r0F. "and bits"
-x := 16rF0 bitOr: 16r0F. "or bits"
-x := 16rFF bitXor: 16r0F. "xor bits"
-x := 16rFF bitInvert. "invert bits"
-x := 16r0F bitShift: 4. "left shift"
-x := 16rF0 bitShift: -4. "right shift"
-"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]"
-x := 16r80 highbit. "position of highest bit set"
-b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver"
-b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver"
-b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver"
-
-"************************************************************************
- * Conversion: *
- ************************************************************************"
-| x |
-x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
-x := 3.99 asFraction. "convert number to fraction"
-x := 3 asFloat. "convert number to float"
-x := 65 asCharacter. "convert integer to character"
-x := $A asciiValue. "convert character to integer"
-x := 3.99 printString. "convert object to string via printOn:"
-x := 3.99 storeString. "convert object to string via storeOn:"
-x := 15 radix: 16. "convert to string in given base"
-x := 15 printStringBase: 16.
-x := 15 storeStringBase: 16.
-
-"************************************************************************
- * Blocks: *
- * - blocks are objects and may be assigned to a variable *
- * - value is last expression evaluated unless explicit return *
- * - blocks may be nested *
- * - specification [ arguments | | localvars | expressions ] *
- * - Squeak does not currently support localvars in blocks *
- * - max of three arguments allowed *
- * - ^expression terminates block & method (exits all nested blocks) *
- * - blocks intended for long term storage should not contain ^ *
- ************************************************************************"
-| x y z |
-x := [ y := 1. z := 2. ]. x value. "simple block usage"
-x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing"
-Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing"
-"x := [ | z | z := 1.]. localvars not available in squeak blocks"
-
-"************************************************************************
- * Method calls: *
- * - unary methods are messages with no arguments *
- * - binary methods *
- * - keyword methods are messages with selectors including colons *
- * *
- * standard categories/protocols: *
- * - initialize-release (methods called for new instance) *
- * - accessing (get/set methods) *
- * - testing (boolean tests - is) *
- * - comparing (boolean tests with parameter *
- * - displaying (gui related methods) *
- * - printing (methods for printing) *
- * - updating (receive notification of changes) *
- * - private (methods private to class) *
- * - instance-creation (class methods for creating instance) *
- ************************************************************************"
-| x |
-x := 2 sqrt. "unary message"
-x := 2 raisedTo: 10. "keyword message"
-x := 194 * 9. "binary message"
-Transcript show: (194 * 9) printString; cr. "combination (chaining)"
-x := 2 perform: #sqrt. "indirect method invocation"
-Transcript "Cascading - send multiple messages to receiver"
- show: 'hello ';
- show: 'world';
- cr.
-x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)"
-
-"************************************************************************
- * Conditional Statements: *
- ************************************************************************"
-| x |
-x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then"
-x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else"
-x > 10 "if then else"
- ifTrue: [Transcript show: 'ifTrue'; cr]
- ifFalse: [Transcript show: 'ifFalse'; cr].
-x > 10 "if else then"
- ifFalse: [Transcript show: 'ifFalse'; cr]
- ifTrue: [Transcript show: 'ifTrue'; cr].
-Transcript
- show:
- (x > 10
- ifTrue: ['ifTrue']
- ifFalse: ['ifFalse']);
- cr.
-Transcript "nested if then else"
- show:
- (x > 10
- ifTrue: [x > 5
- ifTrue: ['A']
- ifFalse: ['B']]
- ifFalse: ['C']);
- cr.
-switch := Dictionary new. "switch functionality"
-switch at: $A put: [Transcript show: 'Case A'; cr].
-switch at: $B put: [Transcript show: 'Case B'; cr].
-switch at: $C put: [Transcript show: 'Case C'; cr].
-result := (switch at: $B) value.
-
-"************************************************************************
- * Iteration statements: *
- ************************************************************************"
-| x y |
-x := 4. y := 1.
-[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop"
-[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop"
-x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)"
-1 to: x do: [:a | y := y * 2]. "for loop"
-1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment"
-#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
-
-"************************************************************************
- * Character: *
- ************************************************************************"
-| x y |
-x := $A. "character assignment"
-y := x isLowercase. "test if lower case"
-y := x isUppercase. "test if upper case"
-y := x isLetter. "test if letter"
-y := x isDigit. "test if digit"
-y := x isAlphaNumeric. "test if alphanumeric"
-y := x isSeparator. "test if seperator char"
-y := x isVowel. "test if vowel"
-y := x digitValue. "convert to numeric digit value"
-y := x asLowercase. "convert to lower case"
-y := x asUppercase. "convert to upper case"
-y := x asciiValue. "convert to numeric ascii value"
-y := x asString. "convert to string"
-b := $A <= $B. "comparison"
-y := $A max: $B.
-
-"************************************************************************
- * Symbol: *
- ************************************************************************"
-| b x y |
-x := #Hello. "symbol assignment"
-y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
-b := x isEmpty. "test if symbol is empty"
-y := x size. "string size"
-y := x at: 2. "char at location"
-y := x copyFrom: 2 to: 4. "substring"
-y := x indexOf: $e ifAbsent: [0]. "first position of character within string"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
-b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
-y := x select: [:a | a > $a]. "return all elements that meet condition"
-y := x asString. "convert symbol to string"
-y := x asText. "convert symbol to text"
-y := x asArray. "convert symbol to array"
-y := x asOrderedCollection. "convert symbol to ordered collection"
-y := x asSortedCollection. "convert symbol to sorted collection"
-y := x asBag. "convert symbol to bag collection"
-y := x asSet. "convert symbol to set collection"
-
-"************************************************************************
- * String: *
- ************************************************************************"
-| b x y |
-x := 'This is a string'. "string assignment"
-x := 'String', 'Concatenation'. "string concatenation"
-b := x isEmpty. "test if string is empty"
-y := x size. "string size"
-y := x at: 2. "char at location"
-y := x copyFrom: 2 to: 4. "substring"
-y := x indexOf: $a ifAbsent: [0]. "first position of character within string"
-x := String new: 4. "allocate string object"
-x "set string elements"
- at: 1 put: $a;
- at: 2 put: $b;
- at: 3 put: $c;
- at: 4 put: $e.
-x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the string"
-b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition"
-y := x select: [:a | a > $a]. "return all elements that meet condition"
-y := x asSymbol. "convert string to symbol"
-y := x asArray. "convert string to array"
-x := 'ABCD' asByteArray. "convert string to byte array"
-y := x asOrderedCollection. "convert string to ordered collection"
-y := x asSortedCollection. "convert string to sorted collection"
-y := x asBag. "convert string to bag collection"
-y := x asSet. "convert string to set collection"
-y := x shuffled. "randomly shuffle string"
-
-"************************************************************************
- * Array: Fixed length collection *
- * ByteArray: Array limited to byte elements (0-255) *
- * WordArray: Array limited to word elements (0-2^32) *
- ************************************************************************"
-| b x y sum max |
-x := #(4 3 2 1). "constant array"
-x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements"
-x := Array new: 4. "allocate an array with specified size"
-x "set array elements"
- at: 1 put: 5;
- at: 2 put: 4;
- at: 3 put: 3;
- at: 4 put: 2.
-b := x isEmpty. "test if array is empty"
-y := x size. "array size"
-y := x at: 4. "get array element at index"
-b := x includes: 3. "test if element is in array"
-y := x copyFrom: 2 to: 4. "subarray"
-y := x indexOf: 3 ifAbsent: [0]. "first position of element within array"
-y := x occurrencesOf: 3. "number of times object in collection"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the array"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements"
-sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum array elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in array"
- ifTrue: [a]
- ifFalse: [c]].
-y := x shuffled. "randomly shuffle collection"
-y := x asArray. "convert to array"
-"y := x asByteArray." "note: this instruction not available on Squeak"
-y := x asWordArray. "convert to word array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * OrderedCollection: acts like an expandable array *
- ************************************************************************"
-| b x y sum max |
-x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
-x := OrderedCollection new. "allocate collection"
-x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
-y := x addFirst: 5. "add element at beginning of collection"
-y := x removeFirst. "remove first element in collection"
-y := x addLast: 6. "add element at end of collection"
-y := x removeLast. "remove last element in collection"
-y := x addAll: #(7 8 9). "add multiple elements to collection"
-y := x removeAll: #(7 8 9). "remove multiple elements from collection"
-x at: 2 put: 3. "set element at index"
-y := x remove: 5 ifAbsent: []. "remove element from collection"
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-y := x at: 2. "retrieve element at index"
-y := x first. "retrieve first element in collection"
-y := x last. "retrieve last element in collection"
-b := x includes: 5. "test if element is in collection"
-y := x copyFrom: 2 to: 3. "subcollection"
-y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
-y := x occurrencesOf: 3. "number of times object in collection"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x shuffled. "randomly shuffle collection"
-y := x asArray. "convert to array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * SortedCollection: like OrderedCollection except order of elements *
- * determined by sorting criteria *
- ************************************************************************"
-| b x y sum max |
-x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
-x := SortedCollection new. "allocate collection"
-x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria"
-x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection"
-y := x addFirst: 5. "add element at beginning of collection"
-y := x removeFirst. "remove first element in collection"
-y := x addLast: 6. "add element at end of collection"
-y := x removeLast. "remove last element in collection"
-y := x addAll: #(7 8 9). "add multiple elements to collection"
-y := x removeAll: #(7 8 9). "remove multiple elements from collection"
-y := x remove: 5 ifAbsent: []. "remove element from collection"
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-y := x at: 2. "retrieve element at index"
-y := x first. "retrieve first element in collection"
-y := x last. "retrieve last element in collection"
-b := x includes: 4. "test if element is in collection"
-y := x copyFrom: 2 to: 3. "subcollection"
-y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection"
-y := x occurrencesOf: 3. "number of times object in collection"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x asArray. "convert to array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * Bag: like OrderedCollection except elements are in no *
- * particular order *
- ************************************************************************"
-| b x y sum max |
-x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
-x := Bag new. "allocate collection"
-x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
-x add: 3 withOccurrences: 2. "add multiple copies to collection"
-y := x addAll: #(7 8 9). "add multiple elements to collection"
-y := x removeAll: #(7 8 9). "remove multiple elements from collection"
-y := x remove: 4 ifAbsent: []. "remove element from collection"
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-b := x includes: 3. "test if element is in collection"
-y := x occurrencesOf: 3. "number of times object in collection"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * Set: like Bag except duplicates not allowed *
- * IdentitySet: uses identity test (== rather than =) *
- ************************************************************************"
-| b x y sum max |
-x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
-x := Set new. "allocate collection"
-x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection"
-y := x addAll: #(7 8 9). "add multiple elements to collection"
-y := x removeAll: #(7 8 9). "remove multiple elements from collection"
-y := x remove: 4 ifAbsent: []. "remove element from collection"
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-x includes: 4. "test if element is in collection"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the collection"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x asArray. "convert to array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * Interval: *
- ************************************************************************"
-| b x y sum max |
-x := Interval from: 5 to: 10. "create interval object"
-x := 5 to: 10.
-x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment"
-x := 5 to: 10 by: 2.
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-x includes: 9. "test if element is in collection"
-x do: [:k | Transcript show: k printString; cr]. "iterate over interval"
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 7]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x asArray. "convert to array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-"************************************************************************
- * Associations: *
- ************************************************************************"
-| x y |
-x := #myVar->'hello'.
-y := x key.
-y := x value.
-
-"************************************************************************
- * Dictionary: *
- * IdentityDictionary: uses identity test (== rather than =) *
- ************************************************************************"
-| b x y |
-x := Dictionary new. "allocate collection"
-x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection"
-x at: #e put: 3. "set element at index"
-b := x isEmpty. "test if empty"
-y := x size. "number of elements"
-y := x at: #a ifAbsent: []. "retrieve element at index"
-y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block"
-y := x removeKey: #e ifAbsent: []. "remove element from collection"
-b := x includes: 3. "test if element is in values collection"
-b := x includesKey: #a. "test if element is in keys collection"
-y := x occurrencesOf: 3. "number of times object in collection"
-y := x keys. "set of keys"
-y := x values. "bag of values"
-x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection"
-x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection"
-x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations"
-x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values"
- show: aKey printString; space;
- show: aValue printString; cr].
-b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition"
-y := x select: [:a | a > 2]. "return collection of elements that pass test"
-y := x reject: [:a | a < 2]. "return collection of elements that fail test"
-y := x collect: [:a | a + a]. "transform each element for new collection"
-y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test"
-sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements"
-sum := x inject: 0 into: [:a :c | a + c]. "sum elements"
-max := x inject: 0 into: [:a :c | (a > c) "find max element in collection"
- ifTrue: [a]
- ifFalse: [c]].
-y := x asArray. "convert to array"
-y := x asOrderedCollection. "convert to ordered collection"
-y := x asSortedCollection. "convert to sorted collection"
-y := x asBag. "convert to bag collection"
-y := x asSet. "convert to set collection"
-
-Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary"
-x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary"
-Transcript show: (CMRGlobal printString). "entries are directly accessible by name"
-Smalltalk keys do: [ :k | "print out all classes"
- ((Smalltalk at: k) isKindOf: Class)
- ifFalse: [Transcript show: k printString; cr]].
-Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary"
-CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary"
-CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo"
-CMRDictionary size. "dictionary size"
-CMRDictionary keys do: [ :k | "print out keys in dictionary"
- Transcript show: k printString; cr].
-CMRDictionary values do: [ :k | "print out values in dictionary"
- Transcript show: k printString; cr].
-CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values"
- Transcript
- show: aKey printString;
- space;
- show: aValue printString;
- cr].
-CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values"
- Transcript show: aKeyValue printString; cr].
-Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary"
-Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary"
-
-"************************************************************************
- * Internal Stream: *
- ************************************************************************"
-| b x ios |
-ios := ReadStream on: 'Hello read stream'.
-ios := ReadStream on: 'Hello read stream' from: 1 to: 5.
-[(x := ios nextLine) notNil]
- whileTrue: [Transcript show: x; cr].
-ios position: 3.
-ios position.
-x := ios next.
-x := ios peek.
-x := ios contents.
-b := ios atEnd.
-
-ios := ReadWriteStream on: 'Hello read stream'.
-ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5.
-ios := ReadWriteStream with: 'Hello read stream'.
-ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10.
-ios position: 0.
-[(x := ios nextLine) notNil]
- whileTrue: [Transcript show: x; cr].
-ios position: 6.
-ios position.
-ios nextPutAll: 'Chris'.
-x := ios next.
-x := ios peek.
-x := ios contents.
-b := ios atEnd.
-
-"************************************************************************
- * FileStream: *
- ************************************************************************"
-| b x ios |
-ios := FileStream newFileNamed: 'ios.txt'.
-ios nextPut: $H; cr.
-ios nextPutAll: 'Hello File'; cr.
-'Hello File' printOn: ios.
-'Hello File' storeOn: ios.
-ios close.
-
-ios := FileStream oldFileNamed: 'ios.txt'.
-[(x := ios nextLine) notNil]
- whileTrue: [Transcript show: x; cr].
-ios position: 3.
-x := ios position.
-x := ios next.
-x := ios peek.
-b := ios atEnd.
-ios close.
-
-"************************************************************************
- * Date: *
- ************************************************************************"
-| x y |
-x := Date today. "create date for today"
-x := Date dateAndTimeNow. "create date from current time/date"
-x := Date readFromString: '01/02/1999'. "create date from formatted string"
-x := Date newDay: 12 month: #July year: 1999 "create date from parts"
-x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901"
-y := Date dayOfWeek: #Monday. "day of week as int (1-7)"
-y := Date indexOfMonth: #January. "month of year as int (1-12)"
-y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)"
-y := Date daysInYear: 1996. "days in year (365|366)"
-y := Date nameOfDay: 1 "weekday name (#Monday,...)"
-y := Date nameOfMonth: 1. "month name (#January,...)"
-y := Date leapYear: 1996. "1 if leap year; 0 if not leap year"
-y := x weekday. "day of week (#Monday,...)"
-y := x previous: #Monday. "date for previous day of week"
-y := x dayOfMonth. "day of month (1-31)"
-y := x day. "day of year (1-366)"
-y := x firstDayOfMonth. "day of year for first day of month"
-y := x monthName. "month of year (#January,...)"
-y := x monthIndex. "month of year (1-12)"
-y := x daysInMonth. "days in month (1-31)"
-y := x year. "year (19xx)"
-y := x daysInYear. "days in year (365|366)"
-y := x daysLeftInYear. "days left in year (364|365)"
-y := x asSeconds. "seconds elapsed since 1/1/1901"
-y := x addDays: 10. "add days to date object"
-y := x subtractDays: 10. "subtract days to date object"
-y := x subtractDate: (Date today). "subtract date (result in days)"
-y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date"
-b := (x <= Date today). "comparison"
-
-"************************************************************************
- * Time: *
- ************************************************************************"
-| x y |
-x := Time now. "create time from current time"
-x := Time dateAndTimeNow. "create time from current time/date"
-x := Time readFromString: '3:47:26 pm'. "create time from formatted string"
-x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight"
-y := Time millisecondClockValue. "milliseconds since midnight"
-y := Time totalSeconds. "total seconds since 1/1/1901"
-y := x seconds. "seconds past minute (0-59)"
-y := x minutes. "minutes past hour (0-59)"
-y := x hours. "hours past midnight (0-23)"
-y := x addTime: (Time now). "add time to time object"
-y := x subtractTime: (Time now). "subtract time to time object"
-y := x asSeconds. "convert time to seconds"
-x := Time millisecondsToRun: [ "timing facility"
- 1 to: 1000 do: [:index | y := 3.14 * index]].
-b := (x <= Time now). "comparison"
-
-"************************************************************************
- * Point: *
- ************************************************************************"
-| x y |
-x := 200@100. "obtain a new point"
-y := x x. "x coordinate"
-y := x y. "y coordinate"
-x := 200@100 negated. "negates x and y"
-x := (-200@-100) abs. "absolute value of x and y"
-x := (200.5@100.5) rounded. "round x and y"
-x := (200.5@100.5) truncated. "truncate x and y"
-x := 200@100 + 100. "add scale to both x and y"
-x := 200@100 - 100. "subtract scale from both x and y"
-x := 200@100 * 2. "multiply x and y by scale"
-x := 200@100 / 2. "divide x and y by scale"
-x := 200@100 // 2. "divide x and y by scale"
-x := 200@100 \\ 3. "remainder of x and y by scale"
-x := 200@100 + 50@25. "add points"
-x := 200@100 - 50@25. "subtract points"
-x := 200@100 * 3@4. "multiply points"
-x := 200@100 // 3@4. "divide points"
-x := 200@100 max: 50@200. "max x and y"
-x := 200@100 min: 50@200. "min x and y"
-x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)"
-
-"************************************************************************
- * Rectangle: *
- ************************************************************************"
-Rectangle fromUser.
-
-"************************************************************************
- * Pen: *
- ************************************************************************"
-| myPen |
-Display restoreAfter: [
- Display fillWhite.
-
-myPen := Pen new. "get graphic pen"
-myPen squareNib: 1.
-myPen color: (Color blue). "set pen color"
-myPen home. "position pen at center of display"
-myPen up. "makes nib unable to draw"
-myPen down. "enable the nib to draw"
-myPen north. "points direction towards top"
-myPen turn: -180. "add specified degrees to direction"
-myPen direction. "get current angle of pen"
-myPen go: 50. "move pen specified number of pixels"
-myPen location. "get the pen position"
-myPen goto: 200@200. "move to specified point"
-myPen place: 250@250. "move to specified point without drawing"
-myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1).
-Display extent. "get display width@height"
-Display width. "get display width"
-Display height. "get display height"
-
-].
-
-"************************************************************************
- * Dynamic Message Calling/Compiling: *
- ************************************************************************"
-| receiver message result argument keyword1 keyword2 argument1 argument2 |
-"unary message"
-receiver := 5.
-message := 'factorial' asSymbol.
-result := receiver perform: message.
-result := Compiler evaluate: ((receiver storeString), ' ', message).
-result := (Message new setSelector: message arguments: #()) sentTo: receiver.
-
-"binary message"
-receiver := 1.
-message := '+' asSymbol.
-argument := 2.
-result := receiver perform: message withArguments: (Array with: argument).
-result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)).
-result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver.
-
-"keyword messages"
-receiver := 12.
-keyword1 := 'between:' asSymbol.
-keyword2 := 'and:' asSymbol.
-argument1 := 10.
-argument2 := 20.
-result := receiver
- perform: (keyword1, keyword2) asSymbol
- withArguments: (Array with: argument1 with: argument2).
-result := Compiler evaluate:
- ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)).
-result := (Message
- new
- setSelector: (keyword1, keyword2) asSymbol
- arguments: (Array with: argument1 with: argument2))
- sentTo: receiver.
-
-"************************************************************************
- * class/meta-class: *
- ************************************************************************"
-| b x |
-x := String name. "class name"
-x := String category. "organization category"
-x := String comment. "class comment"
-x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc"
-x := String definition. "class definition"
-x := String instVarNames. "immediate instance variable names"
-x := String allInstVarNames. "accumulated instance variable names"
-x := String classVarNames. "immediate class variable names"
-x := String allClassVarNames. "accumulated class variable names"
-x := String sharedPools. "immediate dictionaries used as shared pools"
-x := String allSharedPools. "accumulated dictionaries used as shared pools"
-x := String selectors. "message selectors for class"
-x := String sourceCodeAt: #size. "source code for specified method"
-x := String allInstances. "collection of all instances of class"
-x := String superclass. "immediate superclass"
-x := String allSuperclasses. "accumulated superclasses"
-x := String withAllSuperclasses. "receiver class and accumulated superclasses"
-x := String subclasses. "immediate subclasses"
-x := String allSubclasses. "accumulated subclasses"
-x := String withAllSubclasses. "receiver class and accumulated subclasses"
-b := String instSize. "number of named instance variables"
-b := String isFixed. "true if no indexed instance variables"
-b := String isVariable. "true if has indexed instance variables"
-b := String isPointers. "true if index instance vars contain objects"
-b := String isBits. "true if index instance vars contain bytes/words"
-b := String isBytes. "true if index instance vars contain bytes"
-b := String isWords. true if index instance vars contain words"
-Object withAllSubclasses size. "get total number of class entries"
-
-"************************************************************************
- * debuging: *
- ************************************************************************"
-| a b x |
-x yourself. "returns receiver"
-String browse. "browse specified class"
-x inspect. "open object inspector window"
-x confirm: 'Is this correct?'.
-x halt. "breakpoint to open debugger window"
-x halt: 'Halt message'.
-x notify: 'Notify text'.
-x error: 'Error string'. "open up error window with title"
-x doesNotUnderstand: #cmrMessage. "flag message is not handled"
-x shouldNotImplement. "flag message should not be implemented"
-x subclassResponsibility. "flag message as abstract"
-x errorImproperStore. "flag an improper store into indexable object"
-x errorNonIntegerIndex. "flag only integers should be used as index"
-x errorSubscriptBounds. "flag subscript out of bounds"
-x primitiveFailed. "system primitive failed"
-
-a := 'A1'. b := 'B2'. a become: b. "switch two objects"
-Transcript show: a, b; cr.
-
-"************************************************************************
- * Misc. *
- ************************************************************************"
-| x |
-"Smalltalk condenseChanges." "compress the change file"
-x := FillInTheBlank request: 'Prompt Me'. "prompt user for input"
-Utilities openCommandKeyHelp
-
-
-
-
-```
-
-## Ready For More?
-
-### 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)
-* [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/)
--
cgit v1.2.3
From 2cf31d970603d2fe52a2c652f889556046e3330e Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:22:53 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 63 ++++++++++++++++++++++---------------------------
1 file changed, 28 insertions(+), 35 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 61e5a94c..5f1e7430 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -8,41 +8,34 @@ contributors:
- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis."
- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s.
-Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or `grover.jigyasa1@gmail.com`.
-
-```
-
-"************************************************************************
- * Allowable characters: *
- * - a-z *
- * - A-Z *
- * - 0-9 *
- * - .+/\*~<>@%|&? *
- * - blank, tab, cr, ff, lf *
- * *
- * Variables: *
- * - variables must be declared before use *
- * - shared vars must begin with uppercase *
- * - local vars must begin with lowercase *
- * - reserved names: nil, true, false, self, super, and Smalltalk *
- * *
- * Variable scope: *
- * - Global: defined in Dictionary Smalltalk and accessible by all *
- * objects in system *
- * - Special: (reserved) Smalltalk, super, self, true, false, & nil *
- * - Method Temporary: local to a method *
- * - Block Temporary: local to a block *
- * - Pool: variables in a Dictionary object *
- * - Method Parameters: automatic local vars created as a result of *
- * message call with params *
- * - Block Parameters: automatic local vars created as a result of *
- * value: message call *
- * - Class: shared with all instances of one class & its subclasses *
- * - Class Instance: unique to each instance of a class *
- * - Instance Variables: unique to each instance *
- ************************************************************************"
-"Comments are enclosed in quotes"
-"Period (.) is the statement seperator"
+Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`.
+
+
+##Allowable characters:
+- a-z
+- A-Z
+- 0-9
+- .+/\*~<>@%|&?
+- blank, tab, cr, ff, lf
+
+##Variables:
+- variables must be declared before use
+- shared vars must begin with uppercase
+- local vars must begin with lowercase
+- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
+
+##Variable scope:
+- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
+- Method Temporary: local to a method
+- Block Temporary: local to a block
+- Pool: variables in a Dictionary object
+- Method Parameters: automatic local vars created as a result of message call with params - Block Parameters: automatic local vars created as a result of value: message call - Class: shared with all instances of one class & its subclasses
+ - Class Instance: unique to each instance of a class
+- Instance Variables: unique to each instance
+
+`"Comments are enclosed in quotes"`
+
+`"Period (.) is the statement seperator"`
"************************************************************************
* Transcript: *
--
cgit v1.2.3
From 67a2c46bca8362e8cc3c4a360f6a2065bfa7c0f1 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:23:36 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 2 --
1 file changed, 2 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 5f1e7430..e9e5a56c 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -936,8 +936,6 @@ Utilities openCommandKeyHelp
-```
-
## Ready For More?
### Free Online
--
cgit v1.2.3
From 40489d4352ada61f3e788190bc07689825aedf14 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:28:20 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index e9e5a56c..2c2ee3f7 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -37,9 +37,8 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j
`"Period (.) is the statement seperator"`
-"************************************************************************
- * Transcript: *
- ************************************************************************"
+## Transcript:
+```
Transcript clear. "clear to transcript window"
Transcript show: 'Hello World'. "output string in transcript window"
Transcript nextPutAll: 'Hello World'. "output string in transcript window"
@@ -50,6 +49,7 @@ Transcript cr. "carriage return / l
'Hello' printOn: Transcript. "append print string into the window"
'Hello' storeOn: Transcript. "append store string into the window"
Transcript endEntry. "flush the output buffer"
+```
"************************************************************************
* Assignment: *
--
cgit v1.2.3
From 5bf5f1268654e637e0fa08001396e4ea179e0ef9 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:44:20 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 254 ++++++++++++++++++++++++------------------------
1 file changed, 128 insertions(+), 126 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 2c2ee3f7..175810d7 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -51,9 +51,8 @@ Transcript cr. "carriage return / l
Transcript endEntry. "flush the output buffer"
```
-"************************************************************************
- * Assignment: *
- ************************************************************************"
+##Assignment:
+```
| x y |
x _ 4. "assignment (Squeak) <-"
x := 5. "assignment"
@@ -69,10 +68,10 @@ y := x copy. "copy object"
y := x shallowCopy. "copy object (not overridden)"
y := x deepCopy. "copy object and instance vars"
y := x veryDeepCopy. "complete tree copy using a dictionary"
+```
-"************************************************************************
- * Constants: *
- ************************************************************************"
+##Constants:
+```
| b |
b := true. "true constant"
b := false. "false constant"
@@ -90,9 +89,10 @@ x := #aSymbol. "symbol constants"
x := #(3 2 1). "array constants"
x := #('abc' 2 $a). "mixing of types allowed"
-"************************************************************************
- * Booleans: *
- ************************************************************************"
+```
+
+## Booleans:
+```
| b x y |
x := 1. y := 2.
b := (x = y). "equals"
@@ -128,9 +128,10 @@ b := x isNumber. "test if object is n
b := $A isUppercase. "test if upper case character"
b := $A isLowercase. "test if lower case character"
-"************************************************************************
- * Arithmetic expressions: *
- ************************************************************************"
+```
+
+## Arithmetic expressions:
+```
| x |
x := 6 + 3. "addition"
x := 6 - 3. "subtraction"
@@ -185,9 +186,10 @@ x := Float nan. "not-a-number"
x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)
x := 100 atRandom. "quick random number"
-"************************************************************************
- * Bitwise Manipulation: *
- ************************************************************************"
+```
+
+##Bitwise Manipulation:
+```
| b x |
x := 16rFF bitAnd: 16r0F. "and bits"
x := 16rF0 bitOr: 16r0F. "or bits"
@@ -201,9 +203,10 @@ b := 16rFF allMask: 16r0F. "test if all bits se
b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver"
b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver"
-"************************************************************************
- * Conversion: *
- ************************************************************************"
+```
+
+## Conversion:
+```
| x |
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
x := 3.99 asFraction. "convert number to fraction"
@@ -216,40 +219,39 @@ x := 15 radix: 16. "convert to string i
x := 15 printStringBase: 16.
x := 15 storeStringBase: 16.
-"************************************************************************
- * Blocks: *
- * - blocks are objects and may be assigned to a variable *
- * - value is last expression evaluated unless explicit return *
- * - blocks may be nested *
- * - specification [ arguments | | localvars | expressions ] *
- * - Squeak does not currently support localvars in blocks *
- * - max of three arguments allowed *
- * - ^expression terminates block & method (exits all nested blocks) *
- * - blocks intended for long term storage should not contain ^ *
- ************************************************************************"
+```
+
+## Blocks:
+- blocks are objects and may be assigned to a variable
+- value is last expression evaluated unless explicit return
+- blocks may be nested
+- specification [ arguments | | localvars | expressions ]
+- Squeak does not currently support localvars in blocks
+- max of three arguments allowed
+- `^`expression terminates block & method (exits all nested blocks)
+- blocks intended for long term storage should not contain `^`
+
+```
| x y z |
x := [ y := 1. z := 2. ]. x value. "simple block usage"
x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing"
Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing"
-"x := [ | z | z := 1.]. localvars not available in squeak blocks"
-
-"************************************************************************
- * Method calls: *
- * - unary methods are messages with no arguments *
- * - binary methods *
- * - keyword methods are messages with selectors including colons *
- * *
- * standard categories/protocols: *
- * - initialize-release (methods called for new instance) *
- * - accessing (get/set methods) *
- * - testing (boolean tests - is) *
- * - comparing (boolean tests with parameter *
- * - displaying (gui related methods) *
- * - printing (methods for printing) *
- * - updating (receive notification of changes) *
- * - private (methods private to class) *
- * - instance-creation (class methods for creating instance) *
- ************************************************************************"
+"x := [ | z | z := 1.]. *** localvars not available in squeak blocks"
+```
+
+## Method calls:
+- unary methods are messages with no arguments
+- binary methods
+- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
+- accessing (get/set methods)
+- testing (boolean tests - is)
+- comparing (boolean tests with parameter
+- displaying (gui related methods)
+- printing (methods for printing)
+- updating (receive notification of changes)
+- private (methods private to class)
+- instance-creation (class methods for creating instance)
+```
| x |
x := 2 sqrt. "unary message"
x := 2 raisedTo: 10. "keyword message"
@@ -261,10 +263,10 @@ Transcript "Cascading - send mu
show: 'world';
cr.
x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)"
+```
-"************************************************************************
- * Conditional Statements: *
- ************************************************************************"
+##Conditional Statements:
+```
| x |
x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then"
x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else"
@@ -293,10 +295,10 @@ switch at: $A put: [Transcript show: 'Case A'; cr].
switch at: $B put: [Transcript show: 'Case B'; cr].
switch at: $C put: [Transcript show: 'Case C'; cr].
result := (switch at: $B) value.
+```
-"************************************************************************
- * Iteration statements: *
- ************************************************************************"
+## Iteration statements:
+```
| x y |
x := 4. y := 1.
[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop"
@@ -305,10 +307,10 @@ x timesRepeat: [y := y * 2]. "times repear loop (
1 to: x do: [:a | y := y * 2]. "for loop"
1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment"
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
+```
-"************************************************************************
- * Character: *
- ************************************************************************"
+## Character:
+```
| x y |
x := $A. "character assignment"
y := x isLowercase. "test if lower case"
@@ -326,9 +328,10 @@ y := x asString. "convert to string"
b := $A <= $B. "comparison"
y := $A max: $B.
-"************************************************************************
- * Symbol: *
- ************************************************************************"
+```
+
+## Symbol:
+```
| b x y |
x := #Hello. "symbol assignment"
y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
@@ -347,10 +350,10 @@ y := x asOrderedCollection. "convert symbol to o
y := x asSortedCollection. "convert symbol to sorted collection"
y := x asBag. "convert symbol to bag collection"
y := x asSet. "convert symbol to set collection"
+```
-"************************************************************************
- * String: *
- ************************************************************************"
+## String:
+```
| b x y |
x := 'This is a string'. "string assignment"
x := 'String', 'Concatenation'. "string concatenation"
@@ -377,12 +380,12 @@ y := x asSortedCollection. "convert string to s
y := x asBag. "convert string to bag collection"
y := x asSet. "convert string to set collection"
y := x shuffled. "randomly shuffle string"
+```
-"************************************************************************
- * Array: Fixed length collection *
- * ByteArray: Array limited to byte elements (0-255) *
- * WordArray: Array limited to word elements (0-2^32) *
- ************************************************************************"
+## Array: Fixed length collection
+## ByteArray: Array limited to byte elements (0-255)
+## WordArray: Array limited to word elements (0-2^32)
+```
| b x y sum max |
x := #(4 3 2 1). "constant array"
x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements"
@@ -419,10 +422,10 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * OrderedCollection: acts like an expandable array *
- ************************************************************************"
+##OrderedCollection: acts like an expandable array
+```
| b x y sum max |
x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
x := OrderedCollection new. "allocate collection"
@@ -462,11 +465,10 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * SortedCollection: like OrderedCollection except order of elements *
- * determined by sorting criteria *
- ************************************************************************"
+## SortedCollection: like OrderedCollection except order of elements determined by sorting criteria
+```
| b x y sum max |
x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
x := SortedCollection new. "allocate collection"
@@ -505,11 +507,10 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * Bag: like OrderedCollection except elements are in no *
- * particular order *
- ************************************************************************"
+## Bag: like OrderedCollection except elements are in no particular order
+```
| b x y sum max |
x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
x := Bag new. "allocate collection"
@@ -537,11 +538,11 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * Set: like Bag except duplicates not allowed *
- * IdentitySet: uses identity test (== rather than =) *
- ************************************************************************"
+## Set: like Bag except duplicates not allowed
+## IdentitySet: uses identity test (== rather than =)
+```
| b x y sum max |
x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
x := Set new. "allocate collection"
@@ -568,10 +569,10 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * Interval: *
- ************************************************************************"
+## Interval:
+```
| b x y sum max |
x := Interval from: 5 to: 10. "create interval object"
x := 5 to: 10.
@@ -597,19 +598,19 @@ y := x asOrderedCollection. "convert to ordered
y := x asSortedCollection. "convert to sorted collection"
y := x asBag. "convert to bag collection"
y := x asSet. "convert to set collection"
+```
-"************************************************************************
- * Associations: *
- ************************************************************************"
+##Associations:
+```
| x y |
x := #myVar->'hello'.
y := x key.
y := x value.
+```
-"************************************************************************
- * Dictionary: *
- * IdentityDictionary: uses identity test (== rather than =) *
- ************************************************************************"
+## Dictionary:
+## IdentityDictionary: uses identity test (== rather than =)
+```
| b x y |
x := Dictionary new. "allocate collection"
x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection"
@@ -670,10 +671,10 @@ CMRDictionary associationsDo: [:aKeyValue | "another iterator fo
Transcript show: aKeyValue printString; cr].
Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary"
Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary"
+```
-"************************************************************************
- * Internal Stream: *
- ************************************************************************"
+## Internal Stream:
+```
| b x ios |
ios := ReadStream on: 'Hello read stream'.
ios := ReadStream on: 'Hello read stream' from: 1 to: 5.
@@ -700,10 +701,10 @@ x := ios next.
x := ios peek.
x := ios contents.
b := ios atEnd.
+```
-"************************************************************************
- * FileStream: *
- ************************************************************************"
+## FileStream:
+```
| b x ios |
ios := FileStream newFileNamed: 'ios.txt'.
ios nextPut: $H; cr.
@@ -721,10 +722,10 @@ x := ios next.
x := ios peek.
b := ios atEnd.
ios close.
+```
-"************************************************************************
- * Date: *
- ************************************************************************"
+## Date:
+```
| x y |
x := Date today. "create date for today"
x := Date dateAndTimeNow. "create date from current time/date"
@@ -755,10 +756,10 @@ y := x subtractDays: 10. "subtract days to da
y := x subtractDate: (Date today). "subtract date (result in days)"
y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date"
b := (x <= Date today). "comparison"
+```
-"************************************************************************
- * Time: *
- ************************************************************************"
+## Time:
+```
| x y |
x := Time now. "create time from current time"
x := Time dateAndTimeNow. "create time from current time/date"
@@ -775,10 +776,10 @@ y := x asSeconds. "convert time to sec
x := Time millisecondsToRun: [ "timing facility"
1 to: 1000 do: [:index | y := 3.14 * index]].
b := (x <= Time now). "comparison"
+```
-"************************************************************************
- * Point: *
- ************************************************************************"
+## Point:
+```
| x y |
x := 200@100. "obtain a new point"
y := x x. "x coordinate"
@@ -800,15 +801,15 @@ x := 200@100 // 3@4. "divide points"
x := 200@100 max: 50@200. "max x and y"
x := 200@100 min: 50@200. "min x and y"
x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)"
+```
-"************************************************************************
- * Rectangle: *
- ************************************************************************"
+## Rectangle:
+```
Rectangle fromUser.
+```
-"************************************************************************
- * Pen: *
- ************************************************************************"
+## Pen:
+```
| myPen |
Display restoreAfter: [
Display fillWhite.
@@ -832,10 +833,10 @@ Display width. "get display width"
Display height. "get display height"
].
+```
-"************************************************************************
- * Dynamic Message Calling/Compiling: *
- ************************************************************************"
+## Dynamic Message Calling/Compiling:
+```
| receiver message result argument keyword1 keyword2 argument1 argument2 |
"unary message"
receiver := 5.
@@ -868,10 +869,10 @@ result := (Message
setSelector: (keyword1, keyword2) asSymbol
arguments: (Array with: argument1 with: argument2))
sentTo: receiver.
+```
-"************************************************************************
- * class/meta-class: *
- ************************************************************************"
+## Class/Meta-class:
+```
| b x |
x := String name. "class name"
x := String category. "organization category"
@@ -901,10 +902,10 @@ b := String isBits. "true if index insta
b := String isBytes. "true if index instance vars contain bytes"
b := String isWords. true if index instance vars contain words"
Object withAllSubclasses size. "get total number of class entries"
+```
-"************************************************************************
- * debuging: *
- ************************************************************************"
+## Debuging:
+```
| a b x |
x yourself. "returns receiver"
String browse. "browse specified class"
@@ -924,14 +925,15 @@ x primitiveFailed. "system primitive fa
a := 'A1'. b := 'B2'. a become: b. "switch two objects"
Transcript show: a, b; cr.
+```
-"************************************************************************
- * Misc. *
- ************************************************************************"
+## Misc
+```
| x |
"Smalltalk condenseChanges." "compress the change file"
x := FillInTheBlank request: 'Prompt Me'. "prompt user for input"
Utilities openCommandKeyHelp
+```
--
cgit v1.2.3
From 5a0b443ef243f7a6d0568adba1d8d972d67b9a62 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:48:04 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 175810d7..2095a72e 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -383,8 +383,9 @@ y := x shuffled. "randomly shuffle st
```
## Array: Fixed length collection
-## ByteArray: Array limited to byte elements (0-255)
-## WordArray: Array limited to word elements (0-2^32)
+- ByteArray: Array limited to byte elements (0-255)
+- WordArray: Array limited to word elements (0-2^32)
+
```
| b x y sum max |
x := #(4 3 2 1). "constant array"
--
cgit v1.2.3
From c220cced91bd05efda5120990973ce65b0d857b2 Mon Sep 17 00:00:00 2001
From: Jigyasa Grover
Date: Sun, 4 Oct 2015 22:54:24 +0530
Subject: Update smalltalk.html.markdown
---
smalltalk.html.markdown | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index 2095a72e..a434a1ad 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -29,8 +29,10 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j
- Method Temporary: local to a method
- Block Temporary: local to a block
- Pool: variables in a Dictionary object
-- Method Parameters: automatic local vars created as a result of message call with params - Block Parameters: automatic local vars created as a result of value: message call - Class: shared with all instances of one class & its subclasses
- - Class Instance: unique to each instance of a class
+- Method Parameters: automatic local vars created as a result of message call with params
+- Block Parameters: automatic local vars created as a result of value: message call
+- Class: shared with all instances of one class & its subclasses
+- Class Instance: unique to each instance of a class
- Instance Variables: unique to each instance
`"Comments are enclosed in quotes"`
--
cgit v1.2.3
From 87e8e77e5fd8d84a252dbb6d6697202118378774 Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Mon, 5 Oct 2015 00:13:54 +0530
Subject: Fixed a mistake from previous commit.
Better explained reference address.
---
c++.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/c++.html.markdown b/c++.html.markdown
index bbd2f9a9..bd86e9e5 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -245,9 +245,9 @@ cout << fooRef; // Prints "I am foo. Hi!"
// Doesn't reassign "fooRef". This is the same as "foo = bar", and
// foo == "I am bar"
// after this line.
-cout << &fooRef << endl; //Prints address of fooRef
+cout << &fooRef << endl; //Prints address of foo
fooRef = bar;
-cout << &fooRef << endl; //Prints address of fooRef, AGAIN
+cout << &fooRef << endl; //Still prints address of foo
cout << fooRef; // Prints "I am bar"
//The address of fooRef remains the same, i.e. it is still referring to foo.
--
cgit v1.2.3
From f72588075d0cd200d53893ad51129844df17aea7 Mon Sep 17 00:00:00 2001
From: ozgur sahin
Date: Sun, 4 Oct 2015 22:01:10 +0300
Subject: swift-tr.html.markdown
Translated some English sentences.
---
tr-tr/swift-tr.html.markdown | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown
index 41835e13..c13f5ecf 100644
--- a/tr-tr/swift-tr.html.markdown
+++ b/tr-tr/swift-tr.html.markdown
@@ -3,16 +3,14 @@ language: swift
contributors:
- ["Özgür Şahin", "https://github.com/ozgurshn/"]
filename: learnswift.swift
+lang: tr-tr
---
Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi.
-
-The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
+
Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı.
-See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift.
-
Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var.
@@ -243,7 +241,7 @@ print("Benzin fiyatı: \(fiyat)")
// Çeşitli Argümanlar
func ayarla(sayilar: Int...) {
- // its an array
+ // bu bir dizidir
let sayi = sayilar[0]
let argumanSAyisi = sayilar.count
}
--
cgit v1.2.3
From 3b246fd869564b0a7f7c847f44aecac82d318c78 Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Mon, 5 Oct 2015 00:32:34 +0530
Subject: Grammar
the address
---
c++.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/c++.html.markdown b/c++.html.markdown
index bd86e9e5..8ee964ca 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -245,9 +245,9 @@ cout << fooRef; // Prints "I am foo. Hi!"
// Doesn't reassign "fooRef". This is the same as "foo = bar", and
// foo == "I am bar"
// after this line.
-cout << &fooRef << endl; //Prints address of foo
+cout << &fooRef << endl; //Prints the address of foo
fooRef = bar;
-cout << &fooRef << endl; //Still prints address of foo
+cout << &fooRef << endl; //Still prints the address of foo
cout << fooRef; // Prints "I am bar"
//The address of fooRef remains the same, i.e. it is still referring to foo.
--
cgit v1.2.3
From 68fc9b5c1f71adcbbbd53711e9a5692a8372b8cf Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Mon, 5 Oct 2015 00:35:49 +0530
Subject: fixed the comment format
---
common-lisp.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index e3bb61cf..e0597e94 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -176,7 +176,7 @@ nil ; for false - and the empty list
*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
(dog-p *rover*) ; => true #| -p signifies "predicate". It's used to
- check if *rover* is an instance of dog.|#
+ check if *rover* is an instance of dog. |#
(dog-name *rover*) ; => "rover"
;; Dog-p, make-dog, and dog-name are all created by defstruct!
--
cgit v1.2.3
From 1194e9456f2f1302614f8086349c01f4797d34c0 Mon Sep 17 00:00:00 2001
From: willianjusten
Date: Sun, 4 Oct 2015 16:13:11 -0300
Subject: Fixing some typos
---
pt-br/javascript-pt.html.markdown | 45 +++++++++++++++++++--------------------
1 file changed, 22 insertions(+), 23 deletions(-)
diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown
index e39c6c8e..406042fa 100644
--- a/pt-br/javascript-pt.html.markdown
+++ b/pt-br/javascript-pt.html.markdown
@@ -3,20 +3,21 @@ language: javascript
contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
- ["Ariel Krakowski", "http://www.learneroo.com"]
-filename: javascript.js
+translators:
+ - ["Willian Justen", "http://willianjusten.com.br"]
+lang: pt-br
---
-JavaScript foi criada por Brendan Eich, funcionário da Netscape, em 1995. Ela
+JavaScript foi criada por Brendan Eich, funcionário da Netscape na época, em 1995. Ela
foi originalmente criada para ser uma linguagem de script para websites,
complementando o uso de Java para aplicações web mais complexas, mas a sua
integração com páginas web e seu suporte nativo nos browsers fez com que
ela se tornasse mais comum que Java no frontend web.
-Javascript não é somente limitado a browsers web, no entanto: existe o Node.js,
+Javascript não é somente limitada a browsers web, existindo o Node.js,
que é um projeto que fornece um interpretador baseado no motor V8 do Google
Chrome e está se tornando cada vez mais famoso.
-
Feedback são muito apreciados! Você me encontrar em
[@adambrenecki](https://twitter.com/adambrenecki), ou
[adam@brenecki.id.au](mailto:adam@brenecki.id.au).
@@ -29,23 +30,23 @@ Feedback são muito apreciados! Você me encontrar em
// comandos podem ser terminados com ;
facaAlgo();
-// ... mas eles não precisam ser, assim como o ponto-e-vírgula é automaticamente
+// ... mas eles não precisam ser, o ponto-e-vírgula é automaticamente
// inserido quando há uma nova linha, exceto alguns casos.
facaAlgo()
-// Porque esses casos podem causar resultados inesperados, vamos continuar
+// Como esses casos podem causar resultados inesperados, vamos continuar
// a usar ponto-e-vírgula neste guia.
///////////////////////////////////
// 1. Números, Strings e Operadores
// Javascript tem um tipo de número (que é o 64-bit IEEE 754 double).
-// Doublas tem uma mantissa 52-bit, que é suficiente para guardar inteiros
+// Doubles tem uma mantissa 52-bit, que é suficiente para guardar inteiros
// acima de 9✕10¹⁵ precisamente.
3; // = 3
1.5; // = 1.5
-// A aritmética básica funciona seria de esperar.
+// A aritmética básica funciona como seria de se esperar.
1 + 1; // = 2
0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
@@ -62,7 +63,6 @@ facaAlgo()
// A precedência é aplicada com parênteses.
(1 + 3) * 2; // = 8
-// There are three special not-a-real-number values:
// Existem três especiais valores não-é-número-real:
Infinity; // resultado de 1/0
-Infinity; // resultado de -1/0
@@ -76,16 +76,15 @@ false;
'abc';
"Olá, mundo";
-// Negation uses the ! symbol
// Negação usa o símbolo !
!true; // = false
!false; // = true
-// Igualdade é ===
+// Igualdade é o sinal de ===
1 === 1; // = true
2 === 1; // = false
-// Desigualdade é !==
+// Desigualdade é o sinal de !==
1 !== 1; // = false
2 !== 1; // = true
@@ -101,7 +100,7 @@ false;
// e comparadas com < e >
"a" < "b"; // = true
-// A coerção de tipos é feita para comparações com dois iguais...
+// A comparação de tipos não é feita com o uso de ==...
"5" == 5; // = true
null == undefined; // = true
@@ -109,7 +108,7 @@ null == undefined; // = true
"5" === 5; // = false
null === undefined; // = false
-// ...que irá resultar num comportamento estranho...
+// ...isso pode resultar em comportamentos estranhos...
13 + !0; // 14
"13" + !0; // '13true'
@@ -125,21 +124,21 @@ null === undefined; // = false
// Existe também o `null` e o `undefined`.
null; // usado para indicar um valor não considerado
undefined; // usado para indicar um valor que não é a atualmente definido
- // (entretando `undefined` é usado como um próprio valor
+ // (entretando `undefined` é considerado de fato um valor
-// false, null, undefined, NaN, 0 and "" são valores falsy;
-// qualquer outro valor é truthy
-// Note que 0 é falsy e "0" é truthy, até mesmo 0 == "0".
+// false, null, undefined, NaN, 0 and "" são valores falsos;
+// qualquer outro valor é verdadeiro
+// Note que 0 é falso e "0" é verdadeiro, até mesmo 0 == "0".
///////////////////////////////////
// 2. Variáveis, Arrays e Objetos
-// Variáveis são declarados com a palavra-chave `var`. O Javascript é
+// Variáveis são declaradas com a palavra-chave `var`. O Javascript é
// dinâmicamente tipado, portanto você não precisa especificar o tipo.
// Atribuições usam um simples caracter de `=`.
var someVar = 5;
-// se você deixar de colocar a palavra-chave var, você não receber um erro...
+// se você deixar de colocar a palavra-chave var, você não irá receber um erro...
someOtherVar = 10;
// ...mas sua variável será criada no escopo global, não no escopo em que você
@@ -148,13 +147,13 @@ someOtherVar = 10;
// Variáveis declaradas sem receberem um valor são definidas como `undefined`.
var someThirdVar; // = undefined
-// Existe um shorthad para operações matemáticas em variáveis:
+// Existe um shorthand para operações matemáticas em variáveis:
someVar += 5; // equivalente a someVar = someVar + 5; someVar é 10 agora
someVar *= 10; // agora someVar é 100
// e um para adição e subtração de 1
-someVar++; // now someVar is 101
-someVar--; // back to 100
+someVar++; // agora someVar é 101
+someVar--; // volta para 100
// Arrays são listas ordenadas de valores, de qualquer tipo.
var myArray = ["Olá", 45, true];
--
cgit v1.2.3
From 2e987df42225e6bdf824584058467aaffc73fb49 Mon Sep 17 00:00:00 2001
From: Pushkar Sharma
Date: Mon, 5 Oct 2015 00:52:47 +0530
Subject: replaced scanf with fscanf.
---
c.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/c.html.markdown b/c.html.markdown
index 36621a9e..db2ac930 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -131,7 +131,7 @@ int main(void) {
// time constant:
printf("Enter the array size: "); // ask the user for an array size
int size;
- scanf("%d", &size);
+ fscanf(stdin, "%d", &size);
char buf[size];
fgets(buf, sizeof buf, stdin);
--
cgit v1.2.3
From d2fde6512424b754e0d45ac484d86472a99da3ef Mon Sep 17 00:00:00 2001
From: David Lima
Date: Sun, 4 Oct 2015 16:30:42 -0300
Subject: Including '-pt' suffix on filename
---
pt-br/hack-pt.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown
index 2f9d3c1b..7c938149 100644
--- a/pt-br/hack-pt.html.markdown
+++ b/pt-br/hack-pt.html.markdown
@@ -6,7 +6,7 @@ contributors:
translators:
- ["David Lima", "https://github.com/davelima"]
lang: pt-br
-filename: learnhack.hh
+filename: learnhack-pt.hh
---
Hack é uma linguagem baseada no PHP e roda numa máquina virtual chamada HHVM.
--
cgit v1.2.3
From b1984042c845a73333972715e88a3d7a2e8cfdd7 Mon Sep 17 00:00:00 2001
From: Guntbert Reiter
Date: Sun, 4 Oct 2015 16:44:24 +0200
Subject: Put demonstrative condition into ternary expression
It should be made clear that the part before the ternary operator is
indeed a condition, most often created as some comparison expression.
---
de-de/csharp-de.html.markdown | 5 +++--
fr-fr/csharp-fr.html.markdown | 3 ++-
tr-tr/csharp-tr.html.markdown | 3 ++-
zh-cn/csharp-cn.html.markdown | 3 ++-
4 files changed, 9 insertions(+), 5 deletions(-)
diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
index dc77dda0..8ad7d71f 100644
--- a/de-de/csharp-de.html.markdown
+++ b/de-de/csharp-de.html.markdown
@@ -248,7 +248,8 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
// Ternärer Operator
// Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
// ? :
- string isTrue = true ? "Ja" : "Nein";
+ int zumVergleich = 17;
+ string isTrue = zumVergleich == 17 ? "Ja" : "Nein";
// while-Schleife
int fooWhile = 0;
@@ -886,4 +887,4 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
-[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
\ No newline at end of file
+[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown
index e51eacc8..58b3f386 100644
--- a/fr-fr/csharp-fr.html.markdown
+++ b/fr-fr/csharp-fr.html.markdown
@@ -239,7 +239,8 @@ sur une nouvelle ligne! ""Wow!"", quel style";
// Opérateur ternaire
// Un simple if/else peut s'écrire :
// ? :
- string isTrue = (true) ? "True" : "False";
+ int toCompare = 17;
+ string isTrue = toCompare == 17 ? "True" : "False";
// Boucle while
int fooWhile = 0;
diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown
index a68026a5..91c7c269 100644
--- a/tr-tr/csharp-tr.html.markdown
+++ b/tr-tr/csharp-tr.html.markdown
@@ -234,7 +234,8 @@ on a new line! ""Wow!"", the masses cried";
// Üçlü operatörler
// Basit bir if/else ifadesi şöyle yazılabilir
// ? :
- string isTrue = (true) ? "True" : "False";
+ int toCompare = 17;
+ string isTrue = toCompare == 17 ? "True" : "False";
// While döngüsü
int fooWhile = 0;
diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown
index a3cda5b3..971c1be9 100644
--- a/zh-cn/csharp-cn.html.markdown
+++ b/zh-cn/csharp-cn.html.markdown
@@ -232,7 +232,8 @@ on a new line! ""Wow!"", the masses cried";
// 三元表达式
// 简单的 if/else 语句可以写成:
// <条件> ? <真> : <假>
- string isTrue = (true) ? "True" : "False";
+ int toCompare = 17;
+ string isTrue = toCompare == 17 ? "True" : "False";
// While 循环
int fooWhile = 0;
--
cgit v1.2.3
From d8efd3ba3416669177683887b2822eb5d56c157b Mon Sep 17 00:00:00 2001
From: bk2dcradle
Date: Mon, 5 Oct 2015 01:38:02 +0530
Subject: Modified as said to by a Collaborator
---
java.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 2f41be81..89a710ee 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -477,9 +477,9 @@ public abstract class Animal
age = 30;
}
- // No need to initialise, however in an interface
+ // No need to initialize, however in an interface
// a variable is implicitly final and hence has
- // to be initialised.
+ // to be initialized.
private int age;
public void printAge()
@@ -509,7 +509,7 @@ class Dog extends Animal
// @Override annotation here, since java doesn't allow
// overriding of static methods.
// What is happening here is called METHOD HIDING.
- // Check out this awesome SO post: (http://stackoverflow.com/questions/16313649/)
+ // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
public static void main(String[] args)
{
Dog pluto = new Dog();
--
cgit v1.2.3
From e7a50adb78d4babdf77039ee58c59f5bc7d241c4 Mon Sep 17 00:00:00 2001
From: ven
Date: Sun, 4 Oct 2015 22:44:34 +0200
Subject: Fix #1289
---
id-id/xml-id.html.markdown | 1 +
1 file changed, 1 insertion(+)
diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown
index 8e8cdf4e..c1e985aa 100644
--- a/id-id/xml-id.html.markdown
+++ b/id-id/xml-id.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["João Farias", "https://github.com/JoaoGFarias"]
translators:
- ["Rizky Luthfianto", "https://github.com/rilut"]
+lang: id-id
---
XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data.
--
cgit v1.2.3
From 82bdd1b1c8c5eaa49289d9a683bf87ed85b99be9 Mon Sep 17 00:00:00 2001
From: VeerpalB
Date: Sun, 4 Oct 2015 19:41:13 -0400
Subject: Add step parameter to range function
A description of the step parameter of the range function is added. An example of its use in a for loop is also given.
---
python3.html.markdown | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/python3.html.markdown b/python3.html.markdown
index b3acb122..4696ae1c 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -352,6 +352,18 @@ for i in range(4, 8):
print(i)
"""
+"range(lower, upper, step)" returns an iterable of numbers
+from the lower number to the upper number, while incrementing
+by step. If step is not indicated, the default value is 1.
+prints:
+ 4
+ 6
+ 8
+"""
+for i in range(4, 8, 2):
+ print(i)
+"""
+
While loops go until a condition is no longer met.
prints:
0
--
cgit v1.2.3
From 52253720456acfef35cbbcf1ea1b3d98816c0961 Mon Sep 17 00:00:00 2001
From: Zachary Ferguson
Date: Sun, 4 Oct 2015 19:58:14 -0400
Subject: Fixed whitespaces
Fixed the spacing to conform with standards.
---
python3.html.markdown | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/python3.html.markdown b/python3.html.markdown
index d70c5462..7b6edae7 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
- ["Andre Polykanine", "https://github.com/Oire"]
- - ["Zachary Ferguson", "http://github.com/zfergus2"]
+ - ["Zachary Ferguson", "http://github.com/zfergus2"]
filename: learnpython3.py
---
@@ -158,7 +158,7 @@ print("I'm Python. Nice to meet you!")
# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end character.
-print("I'm Python. Nice to meet you!", end="")
+print("Hello, World", end="!") # => Hello, World!
# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
@@ -501,10 +501,9 @@ all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# Returning multiple values (with tuple assignments)
def swap(x, y):
- return y, x # Return multiple values as a tuple
- # (Note: parenthesis have been excluded but can be included)
-# return (y, x) # Just as valid as the above example.
-
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
+
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
--
cgit v1.2.3
From a009095c2f408928e3c75ed64ff31094230f0827 Mon Sep 17 00:00:00 2001
From: connorshea
Date: Sun, 4 Oct 2015 18:53:55 -0600
Subject: Added some Further Reading Links for CSS
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
And changed CanIUse to “Can I Use…”
---
css.html.markdown | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/css.html.markdown b/css.html.markdown
index 7224d80a..e217906f 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -4,6 +4,7 @@ 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"]
filename: learncss.css
---
@@ -238,10 +239,13 @@ of what you use in CSS with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
-To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource.
## Further Reading
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
--
cgit v1.2.3
From 0a3bdcd6a5864bdfb6641f883d3f3e2f4545548c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ale=20Mu=C3=B1oz?=
Date: Mon, 5 Oct 2015 11:50:44 +0200
Subject: Fixed some typos
---
es-es/git-es.html.markdown | 108 ++++++++++++++++++++++-----------------------
1 file changed, 53 insertions(+), 55 deletions(-)
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 51812447..18b544b4 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -11,7 +11,7 @@ lang: es-es
---
Git es un sistema de control de versiones distribuido diseñado para manejar
-cualquier tipo de proyecto, ya sea largo o pequeño, con velocidad y eficiencia.
+cualquier tipo de proyecto, ya sea grande o pequeño, con velocidad y eficiencia.
Git realiza esto haciendo "snapshots" del proyecto, con ello permite
versionar y administrar nuestro código fuente.
@@ -36,8 +36,8 @@ uno o varios archivos, a lo largo del tiempo.
### Por qué usar Git?
* Se puede trabajar sin conexion.
-* Colaborar con otros es sencillo!.
-* Derivar, Crear ramas del proyecto (aka: Branching) es fácil!.
+* ¡Colaborar con otros es sencillo!.
+* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
* Combinar (aka: Merging)
* Git es rápido.
* Git es flexible.
@@ -48,7 +48,7 @@ uno o varios archivos, a lo largo del tiempo.
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
-y que sus atributos otorgan acceso al historial del elemento, además de otras
+y que sus atributos otorgan acceso al historial del elemento, además de otras
cosas.
Un repositorio esta compuesto por la carpeta .git y un "árbol de trabajo".
@@ -68,13 +68,13 @@ las veces se le llama "directorio de trabajo".
### Índice (componentes del directorio .git)
El índice es el área de inicio en git. Es basicamente la capa que separa el
-directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores
-mas poder sobre lo que envía y recibe en el repositorio.
+directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
+más poder sobre lo que se envía y se recibe del repositorio.
### Commit (aka: cambios)
Un commit es una captura de un conjunto de cambios, o modificaciones hechas en
-el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2,
+el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se eliminan 2,
estos cambios se almacenarán en un commit (aka: captura). Este commit puede ser o
no ser enviado (aka: "pusheado") hacia un repositorio.
@@ -84,7 +84,7 @@ Un "branch", es escencialmente un apuntador hacia el último commit (cambio
registrado) que se ha realizado. A medida que se realizan más commits, este
apuntador se actualizará automaticamente hacia el ultimo commit.
-### "HEAD" y "head" (component of .git dir)
+### "HEAD" y "head" (componentes del directorio .git)
"HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un
repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a
@@ -115,7 +115,7 @@ Se utiliza para configurar las opciones ya sea globalmente, o solamente en el
repositorio.
```bash
-# Imprime y guarda algunas variables de configuracion basicas. (Globalmente)
+# Imprime y guarda algunas variables de configuracion básicas. (Globalmente)
$ git config --global user.email
$ git config --global user.name
@@ -123,7 +123,7 @@ $ git config --global user.email "corre@gmail.com"
$ git config --global user.name "nombre"
```
-[Mas sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git)
+[Más sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git)
### help
@@ -131,7 +131,7 @@ Otorga un accceso rápido a una guía extremadamente detallada de cada comando e
git. O puede ser usada simplemente como un recordatorio de estos.
```bash
-# Una vista rapido de los comandos disponibles.
+# Una vista rápida de los comandos disponibles.
$ git help
# Chequear todos los comandos disponibles
@@ -151,7 +151,7 @@ HEAD actualmente.
```bash
-# Mostrara el "branch", archivos sin añadir a la repo, cambios y otras
+# Mostrará el "branch", archivos sin añadir al repo, cambios y otras
# diferencias
$ git status
@@ -161,8 +161,8 @@ $ git help status
### add
-Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se
-utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por
+Para añadir archivos al árbol (directorio, repositorio) de trabajo. Si no se
+utiliza `git add`, los nuevos archivos no se añadirán al arbol de trabajo, por
lo que no se incluirán en los commits (cambios).
```bash
@@ -178,24 +178,24 @@ $ git add ./*.py
### branch
-Administra las ramas del repositorios ("branches"). Puedes ver, editar, crear y
+Administra las ramas del repositorio ("branches"). Puedes ver, editar, crear y
borrar ramas ("branches"), usando este comando.
```bash
# lista todas las ramas (remotas y locales)
$ git branch -a
-# Añada una nueva rama ("branch").
+# Añadir una nueva rama ("branch").
$ git branch branchNueva
# Eliminar una rama.
$ git branch -d branchFoo
-# Renombra una rama.
+# Renombrar una rama.
# git branch -m
$ git branch -m youngling padawan
-# Edita la descripcion de la rama.
+# Editar la descripcion de la rama.
$ git branch master --edit-description
```
@@ -230,7 +230,6 @@ Almacena el contenido actual del índice en un nuevo "commit". Este
commit contiene los cambios hechos más un resumen proporcionado por el desarrollador.
```bash
-# commit with a message
# realizar un commit y añadirle un mensaje.
$ git commit -m "jedi anakin wil be - jedis.list"
```
@@ -241,13 +240,13 @@ Muestra las diferencias entre un archivo en el directorio de trabajo, el índice
y los commits.
```bash
-# Muestra la diferencia entre un directorio de trabajo y el indice.
+# Muestra la diferencia entre un directorio de trabajo y el índice.
$ git diff
-# Muestra la diferencia entre el indice y los commits mas recientes.
+# Muestra la diferencia entre el índice y los commits más recientes.
$ git diff --cached
-# Muestra la diferencia entre el directorio de trabajo y el commit mas reciente.
+# Muestra la diferencia entre el directorio de trabajo y el commit más reciente.
$ git diff HEAD
```
@@ -255,31 +254,32 @@ $ git diff HEAD
Permite realizar una busqueda rápida en un repositorio.
-Configuracion opcionales:
+Configuraciones opcionales:
```bash
# Gracias a Travis Jeffery por compartir lo siguiente.
# Permite mostrar numeros de lineas en la salida de grep.
$ git config --global grep.lineNumber true
-# Realiza una busqueda mas lejible, incluyendo agrupacion.
+# Realiza una búsqueda mas legible, incluyendo agrupación.
$ git config --global alias.g "grep --break --heading --line-number"
```
```bash
-# Busca por "unaVariable" en todos los archivos ,java
+# Busca por "unaVariable" en todos los archivos .java
$ git grep 'unaVariable' -- '*.java'
-# Busca por una linea que contenga "nombreArreglo" y , "agregar" o "remover"
+# Busca por una línea que contenga "nombreArreglo" y "agregar" o "remover"
$ git grep -e 'nombreArreglo' --and \( -e agregar -e remover \)
```
-Mas ejemplos:
-[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+Más ejemplos:
+
+- [Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
### log
-Muestra los commits (cambios) registrados en el repositotrio.
+Muestra los commits (cambios) registrados en el repositorio.
```bash
# Muestra todos los commits.
@@ -288,7 +288,7 @@ $ git log
# Muestra un numero x de commits.
$ git log -n 10
-# Muestra solo los commits que se han combinado en el hisotrial
+# Muestra solo los commits que se han combinado en el historial.
$ git log --merges
```
@@ -301,7 +301,7 @@ que se trabaja.
# Combina la rama especificada en la rama actual.
$ git merge jediMaster
-# Siempre genere un solo merge commit cuando se utilizar merge.
+# Siempre genere un solo merge commit cuando se utiliza merge.
$ git merge --no-ff jediMaster
```
@@ -310,7 +310,7 @@ $ git merge --no-ff jediMaster
Renombra o mueve un archivo
```bash
-# Renombrando un archivo
+# Renombrando un archivo.
$ git mv HolaMundo.c AdiosMundo.c
# Moviendo un archivo.
@@ -322,33 +322,31 @@ $ git mv -f archivoA archivoB
### pull
-Sube (Empuja) de un repositorio y lo combina en otro en una rama diferente.
+Trae los cambios de un repositorio y los combina en otro en una rama diferente.
```bash
-# Actualiza el repositorio local, combinando los nuevos cambios.
+# Actualiza el repositorio local, combinando los nuevos cambios
# de las ramas remotas "origin" y "master".
-# from the remote "origin" and "master" branch.
# git pull
$ git pull origin master
```
### push
-Push and merge changes from a branch to a remote & branch.
+Envía y combina los cambios de un repositorio local a un repositorio y rama remotos.
```bash
-# Push and merge changes from a local repo to a
-# Empuja y combina cambios de un repositorio local hacian un repositorio remoto
+# Envía y combina cambios de un repositorio local hacia un repositorio remoto
# llamados "origin" y "master", respectivamente.
# git push
# git push => por defecto es lo mismo que poner => git push origin master
$ git push origin master
```
+### rebase
Toma todos los cambios que fueron registrados en una rama, y los repite dentro
-de otra rama.
-*No reescribe los commits que se han empujado antes a un repositorio publico*
+de otra rama. *No reescribe los commits que se han empujado antes a un repositorio público.*
```bash
# Integrar ramaExperimento dentro de la rama "master"
@@ -356,47 +354,47 @@ de otra rama.
$ git rebase master experimentBranch
```
-[Informacion adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar)
+[Información adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar)
-### reset (precaucion)
+### reset (precaución)
-Reinicia el cabezal actual hacia un estado especificado. Esto permite desacer
-combinaciones (merges), pulls, commits, adds y mas. Es un comando util, pero
-tambien peligrosa si no se sabe lo que se hace.
+Reinicia el HEAD actual hacia un estado especificado. Esto permite deshacer
+combinaciones (merges), pulls, commits, adds y más. Es un comando útil, pero
+tambien peligroso si no se sabe lo que se hace.
```bash
-# Reinica el area principal, con el ultimo cambio registrado. (deja los
+# Reinicia el área principal, con el último cambio registrado. (deja los
# directorios sin cambios)
$ git reset
-# Reinica el area principal, con el ultimo cambio registrado, y reescribe el
+# Reinicia el área principal, con el último cambio registrado, y reescribe el
# directorio de trabajo.
$ git reset --hard
# Mueve la rama actual hacia el commit especificado (no realiza cambios a los
-# directorios), todos los cambios aun existen el directorio.
+# directorios), todos los cambios aún existen el directorio.
$ git reset 31f2bb1
-# Mueve la rama actual devuelta a un commit especificado asi como el
-# directorios (borra todos los cambios que no fueron registros y todos los
-# cambios realizados despues del commit especificado).
+# Mueve la rama actual devuelta a un commit especificado, así como el
+# directorio (borra todos los cambios que no fueron registrados y todos los
+# cambios realizados después del commit especificado).
$ git reset --hard 31f2bb1
```
### rm
-Lo contrario de git add, git rm remueve los archivos del directorio de trabajo
+Lo contrario de git add, git rm elimina los archivos del directorio de trabajo
actual.
```bash
-# Remueve FooBar.c
+# Elimina FooBar.c
$ git rm FooBar.c
-# Remueve un archivo de un directorio.
+# Elimina un archivo de un directorio.
$ git rm /directorio/del/archivo/FooBar.c
```
-## Informacion Adicional
+## Información Adicional
* [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1)
--
cgit v1.2.3
From 142d33340aec0e3d85154a4feeb958f722693023 Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 15:31:46 +0530
Subject: Update ruby-ru.html.markdown
---
ru-ru/ruby-ru.html.markdown | 1 +
1 file changed, 1 insertion(+)
diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown
index 318e0e09..69b5fb46 100644
--- a/ru-ru/ruby-ru.html.markdown
+++ b/ru-ru/ruby-ru.html.markdown
@@ -158,6 +158,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6]
hash = {'color' => 'green', 'number' => 5}
hash.keys #=> ['color', 'number']
+hash.values #=> ['green', 5]
# Значение в хэше легко может быть найдено по ключу:
hash['color'] #=> 'green'
--
cgit v1.2.3
From 41d49490ba093a74d0d691538b8342682feb997f Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 15:46:46 +0530
Subject: Update python-ru.html.markdown
---
ru-ru/python-ru.html.markdown | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index a0e2b474..162675bb 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -238,6 +238,15 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
+#take input of integers in a single line
+#if input 1 2 3
+input = map(int,raw_input().split()) #integer
+
+input #=>[1, 2, 3]
+
+input = map(str,raw_input().split()) #string
+
+input #=>['1', '2', '3']
# Словари содержат ассоциативные массивы
empty_dict = {}
--
cgit v1.2.3
From dca1300e57600f6707d3aa3778a24d9b1626b9b9 Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 17:33:38 +0530
Subject: Update python-ru.html.markdown
---
ru-ru/python-ru.html.markdown | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 162675bb..ec4fff41 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -238,13 +238,13 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
-#take input of integers in a single line
-#if input 1 2 3
-input = map(int,raw_input().split()) #integer
+#принять ввод чисел в одной строке
+#если вход 1 2 3
+input = map(int,raw_input().split()) #целое число
input #=>[1, 2, 3]
-input = map(str,raw_input().split()) #string
+input = map(str,raw_input().split()) #строка
input #=>['1', '2', '3']
--
cgit v1.2.3
From cae1960ca3a5c25d8db458234ac0a6e97ab87ed5 Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 17:51:23 +0530
Subject: Reverse an array
---
ruby.html.markdown | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 7bd28d86..4e8dcc8f 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -168,6 +168,10 @@ array[-1] #=> 5
# With a start index and length
array[2, 3] #=> [3, 4, 5]
+# Reverse an Array
+# array = [1,2,3]
+array.reverse #=> [3,2,1]
+
# Or with a range
array[1..3] #=> [2, 3, 4]
--
cgit v1.2.3
From 51e3bd21e29ac19884eca57c6f4f1defbd78ea3a Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 20:22:07 +0530
Subject: Reverse a list
---
ruby.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 4e8dcc8f..b6d0e44d 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -169,8 +169,8 @@ array[-1] #=> 5
array[2, 3] #=> [3, 4, 5]
# Reverse an Array
-# array = [1,2,3]
-array.reverse #=> [3,2,1]
+a=[1,2,3]
+a[::-1] #=> [3,2,1]
# Or with a range
array[1..3] #=> [2, 3, 4]
--
cgit v1.2.3
From 0beb78ac436d232ce73986848f354fc4e7210dfb Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 20:32:00 +0530
Subject: Reverse an array
---
ruby.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/ruby.html.markdown b/ruby.html.markdown
index b6d0e44d..8f23b2e6 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -170,7 +170,7 @@ array[2, 3] #=> [3, 4, 5]
# Reverse an Array
a=[1,2,3]
-a[::-1] #=> [3,2,1]
+a.reverse! #=> [3,2,1]
# Or with a range
array[1..3] #=> [2, 3, 4]
--
cgit v1.2.3
From e1abb317dd2526a7352b59c20f9cd37c1a369f55 Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Mon, 5 Oct 2015 20:44:43 +0530
Subject: String to list characters
---
ru-ru/python-ru.html.markdown | 14 ++++----------
1 file changed, 4 insertions(+), 10 deletions(-)
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index ec4fff41..699d1393 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -167,6 +167,10 @@ li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
+#Строка в список
+a="adambard"
+list(a) #=> ['a','d','a','m','b','a','r','d']
+
# Объекты добавляются в конец списка методом append
li.append(1) # [1]
li.append(2) # [1, 2]
@@ -238,16 +242,6 @@ d, e, f = 4, 5, 6
# Обратите внимание, как легко поменять местами значения двух переменных
e, d = d, e # теперь d == 5, а e == 4
-#принять ввод чисел в одной строке
-#если вход 1 2 3
-input = map(int,raw_input().split()) #целое число
-
-input #=>[1, 2, 3]
-
-input = map(str,raw_input().split()) #строка
-
-input #=>['1', '2', '3']
-
# Словари содержат ассоциативные массивы
empty_dict = {}
# Вот так описывается предзаполненный словарь
--
cgit v1.2.3
From 62c6f95e9d161967cfffa43a3f9b3f8d73e2ef5f Mon Sep 17 00:00:00 2001
From: Sean Corrales
Date: Mon, 5 Oct 2015 10:51:27 -0500
Subject: Initial work on learn Sass file.
---
sass.html.markdown | 234 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 234 insertions(+)
create mode 100644 sass.html.markdown
diff --git a/sass.html.markdown b/sass.html.markdown
new file mode 100644
index 00000000..35af1e67
--- /dev/null
+++ b/sass.html.markdown
@@ -0,0 +1,234 @@
+---
+language: sass
+contributors:
+ - ["Sean Corrales", "https://github.com/droidenator"]
+filename: learnsass.scss
+---
+
+Sass is a CSS pre-processor. It adds several features that plain
+CSS lacks such as variables, mixins, basic math, and inheritance.
+
+Initially, Sass was written using spacing and indention instead
+of brackets and semi-colons; these files use the extension '.sass'.
+Sass was later revised to use brackets and semi-colons and become
+a superset of CSS3. This new version uses the extension ".scss".
+Using ".scss" means that any valid CSS3 file can be converted to
+Sass by simply changing the file extension to '.scss'.
+
+If you're already familiar with CSS3, you'll be able to pick up Sass
+relatively quickly. It does not provide any new styling options but rather
+the tools to write your CSS more efficiently and make maintenance much
+easier.
+
+Sass files must be compiled into CSS. You can use any number of commandline
+tools to compile Sass into CSS. Many IDEs also offer Sass compilation, as well.
+
+
+```sass
+/* Like CSS, Sass uses slash-asterisk to denote comments */
+
+/* ####################
+ ## VARIABLES
+ #################### */
+
+/* Sass allows you to define variables that can be used throughout
+ your stylesheets. Variables are defined by placing a '$' in front
+ of a string. Many users like to keep their variables in a single file */
+$primary-color: #0000ff;
+$headline-size: 24px;
+
+/* Variables can be used in any CSS declaration. This allows you to change
+ a single value in one place. */
+a {
+ color: $primary-color;
+}
+
+h1 {
+ color: $primary-color;
+ font-size: $headline-size;
+}
+
+/* After compiling the Sass files into CSS, you'll have the following code
+ in your generated CSS file */
+
+a {
+ color: #0000ff;
+}
+
+h1 {
+ color: #0000ff;
+ font-size: 24px;
+}
+
+/* ####################
+ ## NESTING
+ #################### */
+
+/* Nesting allows you to easily group together statements and nest them
+ in a way that indicates their hierarchy */
+article {
+ font-size: 14px;
+
+ a {
+ text-decoration: underline;
+ }
+
+ ul {
+ list-style-type: disc;
+
+ li {
+ text-indent: 3em;
+ }
+ }
+
+ pre, img {
+ display: inline-block;
+ float: left;
+ }
+}
+
+/* The above will compile into the following CSS */
+article {
+ font-size: 14px;
+}
+
+article a {
+ text-decoration: underline;
+}
+
+article ul {
+ list-style-type: disc;
+}
+
+article ul li {
+ text-indent: 3em;
+}
+
+article pre,
+article img {
+ display: inline-block;
+ float: left;
+}
+
+/* It is recommended to not nest too deeply as this can cause issues with
+ specificity and make your CSS harder to work with and maintain. Best practices
+ recommend going no more than 3 levels deep when nesting. */
+
+/* ####################
+ ## MIXINS
+ #################### */
+/* Mixins allow you to define reusable chunks of CSS. They can take one or more
+ arguments to allow you to make reusable pieces of styling. */
+@mixin form-button($color, $size, $border-radius) {
+ color: $color;
+ font-size: $size;
+ border-radius: $border-radius;
+}
+
+/* Mixins are invoked within a CSS declaration. */
+.user-form .submit {
+ @include form-button(#0000ff, 16px, 4px);
+ margin: 10px;
+}
+
+/* The above mixin will compile into the following css */
+.user-form .submit {
+ color: #0000ff;
+ font-size: 16px;
+ border-radius: 4px;
+ margin: 10px;
+}
+
+/* ####################
+ ## EXTEND/INHERITANCE
+ #################### */
+
+/* ####################
+ ## MATH OPERATIONS
+ #################### */
+
+```
+
+## Usage
+
+Save any CSS you want in a file with extension `.css`.
+
+```xml
+
+
+
+
+
+
+
+
+
+
+```
+
+## Precedence
+
+As you noticed an element may be targetted by more than one selector.
+and may have a property set on it in more than one.
+In these cases, one of the rules takes precedence over others.
+
+Given the following CSS:
+
+```css
+/*A*/
+p.class1[attr='value']
+
+/*B*/
+p.class1 {}
+
+/*C*/
+p.class2 {}
+
+/*D*/
+p {}
+
+/*E*/
+p { property: value !important; }
+
+```
+
+and the following markup:
+
+```xml
+
+
+```
+
+The precedence of style is as followed:
+Remember, the precedence is for each **property**, not for the entire block.
+
+* `E` has the highest precedence because of the keyword `!important`.
+ It is recommended to avoid this unless it is strictly necessary to use.
+* `F` is next, because it is inline style.
+* `A` is next, because it is more "specific" than anything else.
+ more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
+ class name `class1` + 1 attribute `attr='value'`
+* `C` is next. although it has the same specificness as `B`
+ but it appears last.
+* Then is `B`
+* and lastly is `D`.
+
+## Compatibility
+
+Most of the features in CSS2 (and gradually in CSS3) are compatible across
+all browsers and devices. But it's always vital to have in mind the compatibility
+of what you use in CSS with your target browsers.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
+
+To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+
+## Further Reading
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
--
cgit v1.2.3
From 1d43bd50c3e9305abfe95eade590ef5828f9ad5c Mon Sep 17 00:00:00 2001
From: wboka
Date: Mon, 5 Oct 2015 12:29:08 -0400
Subject: Initial placeholder
---
coldfusion.html.markdown | 1 +
1 file changed, 1 insertion(+)
create mode 100644 coldfusion.html.markdown
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
new file mode 100644
index 00000000..3c0b0b06
--- /dev/null
+++ b/coldfusion.html.markdown
@@ -0,0 +1 @@
+Coming soon
--
cgit v1.2.3
From 8b456426407997fdbb8a0befb4181a513e585231 Mon Sep 17 00:00:00 2001
From: Per Lilja
Date: Mon, 5 Oct 2015 20:29:05 +0200
Subject: Added description for Double Brace Initialization
---
java.html.markdown | 27 +++++++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/java.html.markdown b/java.html.markdown
index e4234a39..b4757962 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -325,6 +325,33 @@ public class LearnJava {
// toString returns this Object's string representation.
System.out.println("trek info: " + trek.toString());
+
+ // Double Brace Initialization
+ // The Java Language has no syntax for how to create static Collections
+ // in an easy way. Usually you end up in the following way:
+
+ private static final Set COUNTRIES = new HashSet();
+ static {
+ validCodes.add("DENMARK");
+ validCodes.add("SWEDEN");
+ validCodes.add("FINLAND");
+ }
+
+ // But there's a nifty way to achive the same thing in an
+ // easier way, buy using something that is called Double Brace
+ // Initialization.
+
+ private static final Set COUNTRIES = HashSet() {{
+ add("DENMARK");
+ add("SWEDEN");
+ add("FINLAND");
+ }}
+
+ // The first brace is creating an new AnonymousInnerClass and the
+ // second one declares and instance initializer block. This block
+ // is called with the anonymous inner class is created.
+ // This does not only work for Collections, it works for all
+ // non-final classes.
} // End main method
} // End LearnJava class
--
cgit v1.2.3
From 1bc457737577a01af47a8be5879904dd23bcc410 Mon Sep 17 00:00:00 2001
From: Sean Corrales
Date: Mon, 5 Oct 2015 13:52:53 -0500
Subject: Finishing up documentation for additional Sass functionality.
Removing CSS specific instructions from usage, compatibility, and further
reading sections.
---
sass.html.markdown | 300 +++++++++++++++++++++++++++++++++++++++++------------
1 file changed, 232 insertions(+), 68 deletions(-)
diff --git a/sass.html.markdown b/sass.html.markdown
index 35af1e67..d1e0721f 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -25,7 +25,11 @@ tools to compile Sass into CSS. Many IDEs also offer Sass compilation, as well.
```sass
-/* Like CSS, Sass uses slash-asterisk to denote comments */
+/* Like CSS, Sass uses slash-asterisk to denote comments. Slash-asterisk comments
+ can span multiple lines. These comments will appear in your compiled CSS */
+
+// Sass also supports single line comments that use double slashes. These comments will
+// not be rendered in your compiled CSS
/* ####################
## VARIABLES
@@ -113,12 +117,52 @@ article img {
/* It is recommended to not nest too deeply as this can cause issues with
specificity and make your CSS harder to work with and maintain. Best practices
recommend going no more than 3 levels deep when nesting. */
+
+/* ###############################
+ ## REFERENCE PARENT SELECTORS
+ ############################### */
+
+/* Reference parent selectors are used when you're nesting statements and want to
+ reference the parent selector from within the nested statements. You can reference
+ a parent using & */
+
+a {
+ text-decoration: none;
+ color: #ff0000;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ body.noLinks & {
+ display: none;
+ }
+}
+
+/* The above Sass will compile into the CSS below */
+
+a {
+ text-decoration: none;
+ color: #ff0000;
+}
+
+a:hover {
+ text-decoration: underline;
+}
+
+body.noLinks a {
+ display: none;
+}
+
/* ####################
## MIXINS
#################### */
+
/* Mixins allow you to define reusable chunks of CSS. They can take one or more
- arguments to allow you to make reusable pieces of styling. */
+ arguments to allow you to make reusable pieces of styling. Mixins can also
+ be very helpful when dealing with vendor prefixes. */
+
@mixin form-button($color, $size, $border-radius) {
color: $color;
font-size: $size;
@@ -126,109 +170,229 @@ article img {
}
/* Mixins are invoked within a CSS declaration. */
+
.user-form .submit {
@include form-button(#0000ff, 16px, 4px);
- margin: 10px;
}
/* The above mixin will compile into the following css */
+
.user-form .submit {
color: #0000ff;
font-size: 16px;
border-radius: 4px;
- margin: 10px;
}
/* ####################
- ## EXTEND/INHERITANCE
+ ## FUNCTIONS
#################### */
-
+
+/* Sass provides functions that can be used to accomplish a variety of tasks. Consider the following */
+
+body {
+ width: round(10.25px);
+}
+
+.footer {
+ background-color: fade_out(#000000, 0.25)
+}
+
+/* The above Sass will compile into the following CSS */
+
+body {
+ width: 10px;
+}
+
+.footer {
+ background-color: rgba(0, 0, 0, 0.75);
+}
+
+/* You may also define your own functions. Functions are very similar to mixins. When trying to choose between
+ a function or a mixin, remember that functions are best for returning values while mixins are best for
+ generating CSS while functions are better for logic that might be used throughout your Sass code. The
+ examples in the Math Operators' section are ideal candidates for becoming a reusable function. */
+
+/* This function will take a target size and the parent size and calculate and return the percentage */
+
+@function calculate-percentage($target-size, $parent-size) {
+ @return $target-size / $parent-size * 100%;
+}
+
+/* Functions can be invoked by using their name and passing in the required arguments */
+
+$main-content: calculate-percentage(600px, 960px);
+
+.main-content {
+ width: $main-content;
+}
+
+.sidebar {
+ width: calculate-percentage(300px, 960px);
+}
+
+/* The above Sass will compile into the following CSS */
+
+.main-content {
+ width: 62.5%;
+}
+
+.sidebar {
+ width: 31.25%;
+}
+
/* ####################
- ## MATH OPERATIONS
- #################### */
+ ## EXTEND/INHERITANCE
+ #################### */
-```
+/* Sass allows you to extend an existing CSS statement. This makes it
+ very easy to write CSS that does not violate DRY principles. Any
+ CSS statement can be extended */
+
+.content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
-## Usage
+.message-window {
+ @extend .content-window;
+ background-color: #0000ff;
+}
-Save any CSS you want in a file with extension `.css`.
+.notification-window {
+ @extend .content-window;
+ background-color: #ff0000;
+}
-```xml
-
-
+.settings-window {
+ @extend .content-window;
+ background-color: #ccc;
+}
-
-
+/* The above Sass will be compile into the following CSS */
-
-
-
+.content-window,
+.message-window,
+.notification-window,
+.settings-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
-```
+.message-window {
+ background-color: #0000ff;
+}
+
+.notification-window {
+ background-color: #ff0000;
+}
+
+.settings-window {
+ background-color: #ccc;
+}
+
+/* Extending a CSS statement is preferable to creating a mixin
+ because of the way it groups together the classes that all share
+ the same base styling. If this was done with a mixin, the font-size,
+ padding, color, and border-radius would be duplicated for each statement
+ that called the mixin. While it won't affect your workflow, it will
+ add unnecessary bloat to the files created by the Sass compiler. */
+
+/* #########################
+ ## PLACEHOLDER SELECTORS
+ ######################### */
+
+/* Placeholders are useful when creating a CSS statement to extend. If you wanted to create
+ a CSS statement that was exclusively used with @extend, you can do so using a placeholder.
+ Placeholders begin with a '%' instead of '.' or '#'. Placeholders will not appear in the
+ compiled CSS. */
+
+%content-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
+
+.message-window {
+ @extend %content-window;
+ background-color: #0000ff;
+}
-## Precedence
+/* The above Sass would compile to the following CSS */
-As you noticed an element may be targetted by more than one selector.
-and may have a property set on it in more than one.
-In these cases, one of the rules takes precedence over others.
+.message-window {
+ font-size: 14px;
+ padding: 10px;
+ color: #000;
+ border-radius: 4px;
+}
-Given the following CSS:
+.message-window {
+ background-color: #0000ff;
+}
+
+/* ####################
+ ## MATH OPERATIONS
+ #################### */
+
+/* Sass provides the following operators: +, -, *, /, and %. These can
+ be useful for calculating values directly in your Sass files instead
+ of using values that you've already calculated by hand. Below is an example
+ of a setting up a simple two column design. */
+
+$content-area: 960px;
+$main-content: 600px;
+$sidebar-content: 300px;
-```css
-/*A*/
-p.class1[attr='value']
+$main-size: $main-content / $content-area * 100%;
+$sidebar-size: $sidebar-content / $content-area * 100%;
+$gutter: 100% - ($main-size + $sidebar-size);
-/*B*/
-p.class1 {}
+body {
+ width: 100%;
+}
-/*C*/
-p.class2 {}
+.main-content {
+ width: $main-size;
+}
-/*D*/
-p {}
+.sidebar {
+ width: $sidebar-size;
+}
-/*E*/
-p { property: value !important; }
+.gutter {
+ width: $gutter;
+}
-```
+/* The above Sass would compile to the CSS below */
-and the following markup:
+body {
+ width: 100%;
+}
-```xml
-
-
-```
+.main-content {
+ width: 62.5%;
+}
-The precedence of style is as followed:
-Remember, the precedence is for each **property**, not for the entire block.
+.sidebar {
+ width: 31.25%;
+}
-* `E` has the highest precedence because of the keyword `!important`.
- It is recommended to avoid this unless it is strictly necessary to use.
-* `F` is next, because it is inline style.
-* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
- class name `class1` + 1 attribute `attr='value'`
-* `C` is next. although it has the same specificness as `B`
- but it appears last.
-* Then is `B`
-* and lastly is `D`.
+.gutter {
+ width: 6.25%;
+}
+
+```
-## Compatibility
+## Usage
-Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatibility
-of what you use in CSS with your target browsers.
-[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
-To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+## Compatibility
-## Further Reading
-* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
-* [QuirksMode CSS](http://www.quirksmode.org/css/)
-* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
+## Further Reading
--
cgit v1.2.3
From 6611db502aafc9768254efb45495a9fb20a79c81 Mon Sep 17 00:00:00 2001
From: Ayush
Date: Tue, 6 Oct 2015 00:44:05 +0530
Subject: Git: removed some clutter
---
git.html.markdown | 68 ++++++++++++++++++++++++++++++-------------------------
1 file changed, 37 insertions(+), 31 deletions(-)
diff --git a/git.html.markdown b/git.html.markdown
index bf8fce0c..3b83218c 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -8,17 +8,17 @@ contributors:
filename: LearnGit.txt
---
-Git is a distributed version control and source code management system.
+Git is a distributed version control and source code management system.
-It does this through a series of snapshots of your project, and it works
-with those snapshots to provide you with functionality to version and
+It does this through a series of snapshots of your project, and it works
+with those snapshots to provide you with functionality to version and
manage your source code.
## Versioning Concepts
### What is version control?
-Version control is a system that records changes to a file, or set of files, over time.
+Version control is a system that records changes to a file(s), over time.
### Centralized Versioning VS Distributed Versioning
@@ -42,8 +42,9 @@ Version control is a system that records changes to a file, or set of files, ove
### Repository
-A set of files, directories, historical records, commits, and heads. Imagine it as a source code data structure,
-with the attribute that each source code "element" gives you access to its revision history, among other things.
+A set of files, directories, historical records, commits, and heads. Imagine it
+as a source code data structure, with the attribute that each source code
+"element" gives you access to its revision history, among other things.
A git repository is comprised of the .git directory & working tree.
@@ -54,32 +55,33 @@ The .git directory contains all the configurations, logs, branches, HEAD, and mo
### Working Tree (component of repository)
-This is basically the directories and files in your repository. It is often referred to
-as your working directory.
+This is basically the directories and files in your repository. It is often
+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.
+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
-A branch is essentially a pointer that points to the last commit you made. As you commit,
-this pointer will automatically update and point to the latest commit.
+A branch is essentially a pointer to the last commit you made. As you go on
+committing, this pointer will automatically update to ooint the latest commit.
### 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.
-###Stages of Git
+### Stages of Git
* 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
@@ -95,7 +97,7 @@ head is a pointer that points to any commit. A repository can have any number of
### init
-Create an empty Git repository. The Git repository's settings, stored information,
+Create an empty Git repository. The Git repository's settings, stored information,
and more is stored in a directory (a folder) named ".git".
```bash
@@ -144,8 +146,8 @@ $ git init --help
### status
-To show differences between the index file (basically your working copy/repo) and the current
-HEAD commit.
+To show differences between the index file (basically your working copy/repo)
+and the current HEAD commit.
```bash
@@ -172,7 +174,8 @@ $ git add /path/to/file/HelloWorld.c
$ git add ./*.java
```
-This only adds a file to the staging area/index, it doesn't commit it to the working directory/repo.
+This only adds a file to the staging area/index, it doesn't commit it to the
+working directory/repo.
### branch
@@ -205,7 +208,8 @@ Updates all files in the working tree to match the version in the index, or spec
$ git checkout
# Checkout a specified branch
$ git checkout branchName
-# Create a new branch & switch to it, like: "git branch ; git checkout "
+# Create a new branch & switch to it
+# equivalent to "git branch ; git checkout "
$ git checkout -b newBranch
```
@@ -268,7 +272,7 @@ $ git config --global alias.g "grep --break --heading --line-number"
$ git grep 'variableName' -- '*.java'
# Search for a line that contains "arrayListName" and, "add" or "remove"
-$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
```
Google is your friend; for more examples
@@ -303,7 +307,7 @@ $ git merge --no-ff branchName
### mv
-Rename or move a file
+Rename or move a file
```bash
# Renaming a file
@@ -338,7 +342,7 @@ $ git pull origin master --rebase
Push and merge changes from a branch to a remote & branch.
```bash
-# Push and merge changes from a local repo to a
+# Push and merge changes from a local repo to a
# remote named "origin" and "master" branch.
# git push
# git push => implicitly defaults to => git push origin master
@@ -347,23 +351,25 @@ $ git push origin master
# To link up current local branch with a remote branch, add -u flag:
$ git push -u origin master
# Now, anytime you want to push from that same local branch, use shortcut:
-$ git push
+$ 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 are not able to run `git pull`.
-Instead, you can run `git stash` to save your changes onto a stack!
+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
+are not able to run `git pull`. Instead, you can run `git stash` to save your
+changes onto a stack!
```bash
$ git stash
Saved working directory and index state \
"WIP on master: 049d078 added the index file"
HEAD is now at 049d078 added the index file
- (To restore them type "git stash apply")
+ (To restore them type "git stash apply")
```
Now you can pull!
@@ -410,7 +416,7 @@ Now you're ready to get back to work on your stuff!
[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing)
-### rebase (caution)
+### rebase (caution)
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*.
--
cgit v1.2.3
From 7b7ce666b66e897c115879d505104330923919ec Mon Sep 17 00:00:00 2001
From: Ayush
Date: Tue, 6 Oct 2015 00:45:40 +0530
Subject: Git: added para for gitignore
---
git.html.markdown | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/git.html.markdown b/git.html.markdown
index 3b83218c..c32d9c5d 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -144,6 +144,16 @@ $ git commit --help
$ git init --help
```
+### ignore (set of) files
+
+To intentionally untrack file(s) & folder(s) from git. Typically meant for
+private & temp files which would otherwise be shared in the repository.
+```bash
+$ echo "temp/" >> .gitignore
+$ echo "private_key" >> .gitignore
+```
+
+
### status
To show differences between the index file (basically your working copy/repo)
--
cgit v1.2.3
From 037ff22ef63c5f37b6657e806695bb52f46a7ec3 Mon Sep 17 00:00:00 2001
From: Ayush
Date: Tue, 6 Oct 2015 00:46:53 +0530
Subject: Git: added more clone options
---
git.html.markdown | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/git.html.markdown b/git.html.markdown
index c32d9c5d..66b890c1 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -232,6 +232,10 @@ 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
--
cgit v1.2.3
From e75a9e031bde60fae2c1972b5f6b18571acd4d99 Mon Sep 17 00:00:00 2001
From: Ayush
Date: Tue, 6 Oct 2015 00:56:08 +0530
Subject: Git: added few random things
---
git.html.markdown | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/git.html.markdown b/git.html.markdown
index 66b890c1..e20a4b88 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -106,15 +106,12 @@ $ git init
### config
-To configure settings. Whether it be for the repository, the system itself, or global
-configurations.
+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
-$ git config --global user.name
-
$ git config --global user.email "MyEmail@Zoho.com"
$ git config --global user.name "My Name"
```
@@ -249,6 +246,9 @@ $ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
# automatically stage modified or deleted files, except new files, and then commit
$ git commit -a -m "Modified foo.php and removed bar.php"
+
+# change last commit (this deletes previous commit with a fresh commit)
+$ git commit --amend -m "Correct message"
```
### diff
@@ -300,8 +300,8 @@ Display commits to the repository.
# Show all commits
$ git log
-# Show X number of commits
-$ git log -n 10
+# Show only commit message & ref
+$ git log --oneline
# Show merge commits only
$ git log --merges
--
cgit v1.2.3
From ab2ef777e2c73699a864e5c4869b285f3443c3f4 Mon Sep 17 00:00:00 2001
From: Rodrigo Muniz
Date: Mon, 5 Oct 2015 16:34:58 -0300
Subject: Corrigidos erros de ortografia
---
pt-br/brainfuck-pt.html.markdown | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown
index c7ce55ee..9e4b458d 100644
--- a/pt-br/brainfuck-pt.html.markdown
+++ b/pt-br/brainfuck-pt.html.markdown
@@ -5,10 +5,11 @@ contributors:
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["Suzane Sant Ana", "http://github.com/suuuzi"]
+ - ["Rodrigo Muniz", "http://github.com/muniz95"]
lang: pt-br
---
-Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de
+Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de
programação Turing-completa extremamente simples com apenas 8 comandos.
```
@@ -18,7 +19,7 @@ Brainfuck é representado por um vetor com 30 000 células inicializadas em zero
e um ponteiro de dados que aponta para a célula atual.
Existem 8 comandos:
-+ : Incrementa o vaor da célula atual em 1.
++ : Incrementa o valor da célula atual em 1.
- : Decrementa o valor da célula atual em 1.
> : Move o ponteiro de dados para a célula seguinte (célula à direita).
< : Move o ponteiro de dados para a célula anterior (célula à esquerda).
--
cgit v1.2.3
From 9e605ee35ced12a77f0c0c666c0019d40eaaeea6 Mon Sep 17 00:00:00 2001
From: Ayush
Date: Tue, 6 Oct 2015 01:06:15 +0530
Subject: Git: fixed typo
---
git.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/git.html.markdown b/git.html.markdown
index e20a4b88..b1347309 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -74,7 +74,7 @@ other repositories, or not!
### Branch
A branch is essentially a pointer to the last commit you made. As you go on
-committing, this pointer will automatically update to ooint the latest commit.
+committing, this pointer will automatically update to point the latest commit.
### HEAD and head (component of .git dir)
@@ -141,7 +141,7 @@ $ git commit --help
$ git init --help
```
-### ignore (set of) files
+### ignore files
To intentionally untrack file(s) & folder(s) from git. Typically meant for
private & temp files which would otherwise be shared in the repository.
--
cgit v1.2.3
From e848adf9d53e8af5863497438753d704d30f7c5c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gerson=20L=C3=A1zaro?=
Date: Mon, 5 Oct 2015 15:20:35 -0500
Subject: Fix for issue #1248 [fa-ir, zh-cn, ko-kr, es-es, ru-ru, fr-fr, de-de]
---
de-de/javascript-de.html.markdown | 3 ---
es-es/javascript-es.html.markdown | 3 ---
fa-ir/javascript.html.markdown | 3 ---
fr-fr/javascript-fr.html.markdown | 3 ---
ko-kr/javascript-kr.html.markdown | 3 ---
ru-ru/javascript-ru.html.markdown | 3 ---
zh-cn/javascript-cn.html.markdown | 3 ---
7 files changed, 21 deletions(-)
diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown
index a295c1c2..f3917506 100644
--- a/de-de/javascript-de.html.markdown
+++ b/de-de/javascript-de.html.markdown
@@ -479,9 +479,6 @@ myNumber === myNumberObj; // = false
if (0){
// Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
}
-if (Number(0)){
- // Dieser Teil des Codes wird ausgeführt, weil Number(0) zu wahr evaluiert.
-}
// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen
// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index fd01e7b9..036d7082 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -478,9 +478,6 @@ miNumero === miNumeroObjeyo; // = false
if (0){
// Este código no se ejecutara porque 0 es false.
}
-if (Number(0)){
- // Este código sí se ejecutara, puesto que Number(0) es true.
-}
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
// un prototipo. así que puedes agregar funcionalidades a un string de la
diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown
index 5c64d24a..fe3555af 100644
--- a/fa-ir/javascript.html.markdown
+++ b/fa-ir/javascript.html.markdown
@@ -499,9 +499,6 @@ myNumber === myNumberObj; // = false
if (0){
// This code won't execute, because 0 is falsy.
}
-if (Number(0)){
- // This code *will* execute, because Number(0) is truthy.
-}
```
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
index 2e18d0be..15478cdb 100644
--- a/fr-fr/javascript-fr.html.markdown
+++ b/fr-fr/javascript-fr.html.markdown
@@ -469,9 +469,6 @@ myNumber === myNumberObj; // = false
if (0){
// 0 est falsy, le code ne fonctionnera pas.
}
-if (Number(0)){
- // Parce que Number(0) est truthy, le code fonctionnera
-}
// Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à
// cette particularité.
diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown
index 4ca3bb5c..9561e80c 100644
--- a/ko-kr/javascript-kr.html.markdown
+++ b/ko-kr/javascript-kr.html.markdown
@@ -387,9 +387,6 @@ myNumber === myNumberObj // = false
if (0){
// 0은 거짓이라서 이 코드는 실행되지 않습니다.
}
-if (Number(0)){
- // Number(0)은 참이라서 이 코드는 *실행됩니다*.
-}
// 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에
// 가령 문자열에 실제로 기능을 추가할 수 있습니다.
diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown
index 79844565..8655ae4a 100644
--- a/ru-ru/javascript-ru.html.markdown
+++ b/ru-ru/javascript-ru.html.markdown
@@ -470,9 +470,6 @@ myNumber === myNumberObj; // = false
if (0) {
// Этот код не выполнится, потому что 0 - это ложь.
}
-if (Number(0)) {
- // Этот код *выполнится*, потому что Number(0) истинно.
-}
// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы,
// поэтому вы можете расширить функционал строк, например:
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index dfeb2012..bdef0099 100644
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -447,9 +447,6 @@ myNumber === myNumberObj; // = false
if (0){
// 这段代码不会执行,因为0代表假
}
-if (Number(0)){
- // 这段代码*会*执行,因为Number(0)代表真
-}
// 不过,包装类型和内置类型共享一个原型,
// 所以你实际可以给内置类型也增加一些功能,例如对string:
--
cgit v1.2.3
From 9d33f091701013236055b553d7eb7a8dba3df65e Mon Sep 17 00:00:00 2001
From: wboka
Date: Mon, 5 Oct 2015 16:52:07 -0400
Subject: Update coldfusion.html.markdown
Adds variable declaration, comparison operators, and if/else control structures
---
coldfusion.html.markdown | 395 ++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 394 insertions(+), 1 deletion(-)
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index 3c0b0b06..4c734920 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -1 +1,394 @@
-Coming soon
+---
+language: ColdFusion
+contributors:
+ - ["Wayne Boka", "http://wboka.github.io"]
+filename: LearnColdFusion.cfm
+---
+
+ColdFusion is a scripting language for web development.
+[Read more here.](http://www.adobe.com/products/coldfusion-family.html)
+
+```ColdFusion
+" --->
+
+
+
+
+
+
+
+
+
+
+#myVariable#
+#myNumber#
+
+
+
+
+
+
+
+
+
+
+
+
+
+#1 + 1# = 2
+#10 - 8# = 2
+#1 * 2# = 2
+#10 / 5# = 2
+#12 % 5# = 0
+
+
+#1 eq 1#
+#15 neq 1#
+#10 gt 8#
+#1 lt 2#
+#10 gte 5#
+#1 lte 5#
+
+
+
+
+ #myCondition#
+
+ #myCondition#. Proceed Carefully!!!
+
+ myCondition is unknown
+
+```
+
+
+## Further Reading
+
+The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
--
cgit v1.2.3
From 1e7f639755042211ce0f10953153d6d341dbecab Mon Sep 17 00:00:00 2001
From: wboka
Date: Mon, 5 Oct 2015 16:52:47 -0400
Subject: Update coldfusion.html.markdown
Fixes a typo
---
coldfusion.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index 4c734920..be08733e 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -26,7 +26,7 @@ ColdFusion is a scripting language for web development.
#myVariable#
-#myNumber#
+#myNumber#
--
cgit v1.2.3
From 8d57b90efe51c980d63abae4b5537631fb2f2eab Mon Sep 17 00:00:00 2001
From: Mariane Siqueira Machado
Date: Mon, 5 Oct 2015 17:59:30 -0300
Subject: Translates another line
---
pt-br/swift-pt.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown
index 72a57e4a..e840b8cf 100644
--- a/pt-br/swift-pt.html.markdown
+++ b/pt-br/swift-pt.html.markdown
@@ -221,7 +221,7 @@ println("Gas price: \(price)")
// Número variável de argumentos
func setup(numbers: Int...) {
- // its an array
+ // é um array
let number = numbers[0]
let argCount = numbers.count
}
--
cgit v1.2.3
From c7c9ea674dbe3af1e2e1c09cffb36a40c6553e80 Mon Sep 17 00:00:00 2001
From: Chashmeet Singh
Date: Tue, 6 Oct 2015 05:38:40 +0530
Subject: Update python-ru.html.markdown
---
ru-ru/python-ru.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 699d1393..3852a550 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -167,7 +167,7 @@ li = []
# Можно сразу начать с заполненного списка
other_li = [4, 5, 6]
-#Строка в список
+# строка разделена в список
a="adambard"
list(a) #=> ['a','d','a','m','b','a','r','d']
--
cgit v1.2.3
From b8ad751cc020c07796832c1689cca7b84970b4e9 Mon Sep 17 00:00:00 2001
From: wboka
Date: Mon, 5 Oct 2015 21:07:13 -0400
Subject: Update coldfusion.html.markdown
Adds a few more examples
---
coldfusion.html.markdown | 87 ++++++++++++++++++++----------------------------
1 file changed, 37 insertions(+), 50 deletions(-)
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index be08733e..b8fe9359 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -10,9 +10,9 @@ ColdFusion is a scripting language for web development.
```ColdFusion
" --->
-
@@ -25,8 +25,10 @@ ColdFusion is a scripting language for web development.
-#myVariable#
-#myNumber#
+#myVariable#
+#myNumber#
+
+
@@ -40,19 +42,23 @@ ColdFusion is a scripting language for web development.
-#1 + 1# = 2
-#10 - 8# = 2
-#1 * 2# = 2
-#10 / 5# = 2
-#12 % 5# = 0
+#1 + 1# = 2
+#10 - 8# = 2
+#1 * 2# = 2
+#10 / 5# = 2
+#12 % 5# = 0
+
+
-#1 eq 1#
-#15 neq 1#
-#10 gt 8#
-#1 lt 2#
-#10 gte 5#
-#1 lte 5#
+#1 eq 1#
+#15 neq 1#
+#10 gt 8#
+#1 lt 2#
+#10 gte 5#
+#1 lte 5#
+
+
@@ -63,36 +69,17 @@ ColdFusion is a scripting language for web development.
myCondition is unknown
-```
-
+
+ #i#
+
+
+
+```
+" --->
-
+
Simple Variables
+
Set myVariable to "myValue"
+
Set myNumber to 3.14
-#myVariable#
-#myNumber#
+
Display myVariable: #myVariable#
+
Display myNumber: #myNumber#
+
Complex Variables
+
Set myArray1 to an array of 1 dimension using literal or bracket notation
+
Set myArray2 to an array of 1 dimension using function notation
+
- #myCondition#
+ #myCondition#. We're testing.#myCondition#. Proceed Carefully!!!
@@ -73,54 +101,53 @@ ColdFusion is a scripting language for web development.
+
Loops
+
For Loop
- #i#
+
Index equals #i#
+
+
+
For Each Loop (Complex Variables)
+
+
Set myArray3 to [5, 15, 99, 45, 100]
+
+
+
+
+
Index equals #i#
+
+
+
Set myArray4 to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]
+
+
+
+
+
Index equals #s#
+
+
+
Switch Statement
+
+
Set myArray5 to [5, 15, 99, 45, 100]
+
+
+
+
+
+
+
#i# is a multiple of 5.
+
+
+
#i# is ninety-nine.
+
+
+
#i# is not 5, 15, 45, or 99.
+
+
```
-
-
@@ -186,8 +186,8 @@ This has to be avoided as much as you can. -->
## Precedence
-As you noticed an element may be targetted by more than one selector.
-and may have a property set on it in more than one.
+As you noticed an element may be targetted by more than one selector.
+and may have a property set on it in more than one.
In these cases, one of the rules takes precedence over others.
Given the following CSS:
@@ -217,24 +217,24 @@ and the following markup:
```
-The precedence of style is as followed:
+The precedence of style is as followed:
Remember, the precedence is for each **property**, not for the entire block.
-* `E` has the highest precedence because of the keyword `!important`.
+* `E` has the highest precedence because of the keyword `!important`.
It is recommended to avoid this unless it is strictly necessary to use.
* `F` is next, because it is inline style.
-* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
+* `A` is next, because it is more "specific" than anything else.
+ more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
class name `class1` + 1 attribute `attr='value'`
-* `C` is next. although it has the same specificness as `B`
+* `C` is next. although it has the same specificness as `B`
but it appears last.
* Then is `B`
* and lastly is `D`.
## Compatibility
-Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatibility
+Most of the features in CSS2 (and gradually in CSS3) are compatible across
+all browsers and devices. But it's always vital to have in mind the compatibility
of what you use in CSS with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
diff --git a/d.html.markdown b/d.html.markdown
index daba8020..ba24b60f 100644
--- a/d.html.markdown
+++ b/d.html.markdown
@@ -1,6 +1,6 @@
---
-language: D
-filename: learnd.d
+language: D
+filename: learnd.d
contributors:
- ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
lang: en
@@ -18,9 +18,9 @@ void main(string[] args) {
}
```
-If you're like me and spend way too much time on the internet, odds are you've heard
+If you're like me and spend way too much time on the internet, odds are you've heard
about [D](http://dlang.org/). The D programming language is a modern, general-purpose,
-multi-paradigm language with support for everything from low-level features to
+multi-paradigm language with support for everything from low-level features to
expressive high-level abstractions.
D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool
@@ -37,7 +37,7 @@ void main() {
}
auto n = 1; // use auto for type inferred variables
-
+
// Numeric literals can use _ as a digit seperator for clarity
while(n < 10_000) {
n += n;
@@ -49,7 +49,7 @@ void main() {
// For and while are nice, but in D-land we prefer foreach
// The .. creates a continuous range, excluding the end
- foreach(i; 1..1_000_000) {
+ foreach(i; 1..1_000_000) {
if(n % 2 == 0)
writeln(i);
}
@@ -72,12 +72,12 @@ we can use templates to parameterize all of these on both types and values!
// Here, T is a type parameter. Think from C++/C#/Java
struct LinkedList(T) {
T data = null;
- LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think
+ LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think
}
class BinTree(T) {
T data = null;
-
+
// If there is only one template parameter, we can omit parens
BinTree!T left;
BinTree!T right;
@@ -101,7 +101,7 @@ alias NumTree = BinTree!double;
// We can create function templates as well!
T max(T)(T a, T b) {
- if(a < b)
+ if(a < b)
return b;
return a;
@@ -114,7 +114,7 @@ void swap(T)(ref T a, ref T b) {
auto temp = a;
a = b;
- b = temp;
+ b = temp;
}
// With templates, we can also parameterize on values, not just types
@@ -145,13 +145,13 @@ class MyClass(T, U) {
class MyClass(T, U) {
T _data;
U _other;
-
+
// Constructors are always named `this`
this(T t, U u) {
data = t;
other = u;
}
-
+
// getters
@property T data() {
return _data;
@@ -161,7 +161,7 @@ class MyClass(T, U) {
return _other;
}
- // setters
+ // setters
@property void data(T t) {
_data = t;
}
@@ -177,7 +177,7 @@ void main() {
mc.data = 7;
mc.other = "seven";
-
+
writeln(mc.data);
writeln(mc.other);
}
@@ -193,7 +193,7 @@ and `override`ing methods. D does inheritance just like Java:
Extend one class, implement as many interfaces as you please.
We've seen D's OOP facilities, but let's switch gears. D offers
-functional programming with first-class functions, `pure`
+functional programming with first-class functions, `pure`
functions, and immutable data. In addition, all of your favorite
functional algorithms (map, filter, reduce and friends) can be
found in the wonderful `std.algorithm` module!
@@ -205,7 +205,7 @@ import std.range : iota; // builds an end-exclusive range
void main() {
// We want to print the sum of a list of squares of even ints
// from 1 to 100. Easy!
-
+
// Just pass lambda expressions as template parameters!
// You can pass any old function you like, but lambdas are convenient here.
auto num = iota(1, 101).filter!(x => x % 2 == 0)
@@ -216,12 +216,12 @@ void main() {
}
```
-Notice how we got to build a nice Haskellian pipeline to compute num?
+Notice how we got to build a nice Haskellian pipeline to compute num?
That's thanks to a D innovation know as Uniform Function Call Syntax.
With UFCS, we can choose whether to write a function call as a method
or free function call! Walter wrote a nice article on this
-[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
-In short, you can call functions whose first parameter
+[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+In short, you can call functions whose first parameter
is of some type A on any expression of type A as a method.
I like parallelism. Anyone else like parallelism? Sure you do. Let's do some!
diff --git a/dart.html.markdown b/dart.html.markdown
index 34d1c6a8..f7601271 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -81,7 +81,7 @@ example5() {
// Where classBody can include instance methods and variables, but also
// class methods and variables.
class Example6Class {
- var example6InstanceVariable = "Example6 instance variable";
+ var example6InstanceVariable = "Example6 instance variable";
sayIt() {
print(example6InstanceVariable);
}
@@ -92,7 +92,7 @@ example6() {
// Class methods and variables are declared with "static" terms.
class Example7Class {
- static var example7ClassVariable = "Example7 class variable";
+ static var example7ClassVariable = "Example7 class variable";
static sayItFromClass() {
print(example7ClassVariable);
}
@@ -111,7 +111,7 @@ example7() {
// by default. But arrays and maps are not. They can be made constant by
// declaring them "const".
var example8A = const ["Example8 const array"],
- example8M = const {"someKey": "Example8 const map"};
+ example8M = const {"someKey": "Example8 const map"};
example8() {
print(example8A[0]);
print(example8M["someKey"]);
@@ -245,7 +245,7 @@ example18() {
// Strings with triple single-quotes or triple double-quotes span
// multiple lines and include line delimiters.
example19() {
- print('''Example19
+ print('''Example19
Example19 Don't can't I'm Etc
Example19 ''');
}
@@ -272,7 +272,7 @@ example20() {
class Example21 {
List _names;
Example21() {
- _names = ["a", "b"];
+ _names = ["a", "b"];
}
List get names => _names;
set names(List list) {
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 4e2f1d84..d6ed7b86 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -292,7 +292,7 @@ calculateArea() ->
_ ->
io:format("We can only calculate area of rectangles or circles.")
end.
-
+
% Compile the module and create a process that evaluates `calculateArea` in the
% shell.
c(calculateGeometry).
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 49951c78..62118006 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -5,7 +5,7 @@ contributors:
filename: learnfsharp.fs
---
-F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
+F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more.
It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language.
@@ -90,7 +90,7 @@ let simplePatternMatch =
| _ -> printfn "x is something else" // underscore matches anything
// F# doesn't allow nulls by default -- you must use an Option type
-// and then pattern match.
+// and then pattern match.
// Some(..) and None are roughly analogous to Nullable wrappers
let validValue = Some(99)
let invalidValue = None
@@ -115,7 +115,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
// into a string, similar to String.Format in C#.
// ================================================
-// More on functions
+// More on functions
// ================================================
// F# is a true functional language -- functions are first
@@ -124,30 +124,30 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
// Modules are used to group functions together
// Indentation is needed for each nested module.
-module FunctionExamples =
+module FunctionExamples =
// define a simple adding function
let add x y = x + y
-
+
// basic usage of a function
let a = add 1 2
printfn "1+2 = %i" a
-
+
// partial application to "bake in" parameters
let add42 = add 42
let b = add42 1
printfn "42+1 = %i" b
-
+
// composition to combine functions
let add1 = add 1
let add2 = add 2
let add3 = add1 >> add2
let c = add3 7
printfn "3+7 = %i" c
-
+
// higher order functions
[1..10] |> List.map add3 |> printfn "new list is %A"
-
+
// lists of functions, and more
let add6 = [add1; add2; add3] |> List.reduce (>>)
let d = add6 7
@@ -158,54 +158,54 @@ module FunctionExamples =
// ================================================
// There are three types of ordered collection:
-// * Lists are most basic immutable collection.
-// * Arrays are mutable and more efficient when needed.
-// * Sequences are lazy and infinite (e.g. an enumerator).
+// * Lists are most basic immutable collection.
+// * Arrays are mutable and more efficient when needed.
+// * Sequences are lazy and infinite (e.g. an enumerator).
//
// Other collections include immutable maps and sets
// plus all the standard .NET collections
-module ListExamples =
+module ListExamples =
- // lists use square brackets
+ // lists use square brackets
let list1 = ["a";"b"]
let list2 = "c" :: list1 // :: is prepending
let list3 = list1 @ list2 // @ is concat
-
+
// list comprehensions (aka generators)
- let squares = [for i in 1..10 do yield i*i]
+ let squares = [for i in 1..10 do yield i*i]
// prime number generator
let rec sieve = function
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
| [] -> []
let primes = sieve [2..50]
- printfn "%A" primes
-
+ printfn "%A" primes
+
// pattern matching for lists
- let listMatcher aList =
+ let listMatcher aList =
match aList with
- | [] -> printfn "the list is empty"
- | [first] -> printfn "the list has one element %A " first
- | [first; second] -> printfn "list is %A and %A" first second
- | _ -> printfn "the list has more than two elements"
+ | [] -> printfn "the list is empty"
+ | [first] -> printfn "the list has one element %A " first
+ | [first; second] -> printfn "list is %A and %A" first second
+ | _ -> printfn "the list has more than two elements"
listMatcher [1;2;3;4]
listMatcher [1;2]
listMatcher [1]
- listMatcher []
+ listMatcher []
// recursion using lists
- let rec sum aList =
+ let rec sum aList =
match aList with
| [] -> 0
| x::xs -> x + sum xs
sum [1..10]
-
- // -----------------------------------------
- // Standard library functions
+
+ // -----------------------------------------
+ // Standard library functions
// -----------------------------------------
-
+
// map
let add3 x = x + 3
[1..10] |> List.map add3
@@ -213,68 +213,68 @@ module ListExamples =
// filter
let even x = x % 2 = 0
[1..10] |> List.filter even
-
+
// many more -- see documentation
-
-module ArrayExamples =
+
+module ArrayExamples =
// arrays use square brackets with bar
let array1 = [| "a";"b" |]
let first = array1.[0] // indexed access using dot
-
+
// pattern matching for arrays is same as for lists
- let arrayMatcher aList =
+ let arrayMatcher aList =
match aList with
- | [| |] -> printfn "the array is empty"
- | [| first |] -> printfn "the array has one element %A " first
- | [| first; second |] -> printfn "array is %A and %A" first second
- | _ -> printfn "the array has more than two elements"
+ | [| |] -> printfn "the array is empty"
+ | [| first |] -> printfn "the array has one element %A " first
+ | [| first; second |] -> printfn "array is %A and %A" first second
+ | _ -> printfn "the array has more than two elements"
arrayMatcher [| 1;2;3;4 |]
// Standard library functions just as for List
-
- [| 1..10 |]
+
+ [| 1..10 |]
|> Array.map (fun i -> i+3)
|> Array.filter (fun i -> i%2 = 0)
|> Array.iter (printfn "value is %i. ")
-
-
-module SequenceExamples =
+
+
+module SequenceExamples =
// sequences use curly braces
let seq1 = seq { yield "a"; yield "b" }
-
- // sequences can use yield and
+
+ // sequences can use yield and
// can contain subsequences
let strange = seq {
// "yield! adds one element
yield 1; yield 2;
-
+
// "yield!" adds a whole subsequence
- yield! [5..10]
+ yield! [5..10]
yield! seq {
- for i in 1..10 do
+ for i in 1..10 do
if i%2 = 0 then yield i }}
- // test
- strange |> Seq.toList
-
+ // test
+ strange |> Seq.toList
+
// Sequences can be created using "unfold"
// Here's the fibonacci series
let fib = Seq.unfold (fun (fst,snd) ->
Some(fst + snd, (snd, fst + snd))) (0,1)
- // test
+ // test
let fib10 = fib |> Seq.take 10 |> Seq.toList
- printf "first 10 fibs are %A" fib10
-
-
+ printf "first 10 fibs are %A" fib10
+
+
// ================================================
-// Data Types
+// Data Types
// ================================================
-module DataTypeExamples =
+module DataTypeExamples =
// All data is immutable by default
@@ -282,33 +282,33 @@ module DataTypeExamples =
// -- Use a comma to create a tuple
let twoTuple = 1,2
let threeTuple = "a",2,true
-
+
// Pattern match to unpack
let x,y = twoTuple //sets x=1 y=2
- // ------------------------------------
- // Record types have named fields
- // ------------------------------------
+ // ------------------------------------
+ // Record types have named fields
+ // ------------------------------------
// Use "type" with curly braces to define a record type
type Person = {First:string; Last:string}
-
- // Use "let" with curly braces to create a record
+
+ // Use "let" with curly braces to create a record
let person1 = {First="John"; Last="Doe"}
// Pattern match to unpack
let {First=first} = person1 //sets first="john"
- // ------------------------------------
+ // ------------------------------------
// Union types (aka variants) have a set of choices
// Only case can be valid at a time.
- // ------------------------------------
+ // ------------------------------------
// Use "type" with bar/pipe to define a union type
- type Temp =
+ type Temp =
| DegreesC of float
| DegreesF of float
-
+
// Use one of the cases to create one
let temp1 = DegreesF 98.6
let temp2 = DegreesC 37.0
@@ -317,29 +317,29 @@ module DataTypeExamples =
let printTemp = function
| DegreesC t -> printfn "%f degC" t
| DegreesF t -> printfn "%f degF" t
-
- printTemp temp1
+
+ printTemp temp1
printTemp temp2
- // ------------------------------------
+ // ------------------------------------
// Recursive types
- // ------------------------------------
+ // ------------------------------------
- // Types can be combined recursively in complex ways
+ // Types can be combined recursively in complex ways
// without having to create subclasses
- type Employee =
+ type Employee =
| Worker of Person
| Manager of Employee list
let jdoe = {First="John";Last="Doe"}
let worker = Worker jdoe
-
- // ------------------------------------
+
+ // ------------------------------------
// Modelling with types
- // ------------------------------------
-
+ // ------------------------------------
+
// Union types are great for modelling state without using flags
- type EmailAddress =
+ type EmailAddress =
| ValidEmailAddress of string
| InvalidEmailAddress of string
@@ -350,40 +350,40 @@ module DataTypeExamples =
// The combination of union types and record types together
// provide a great foundation for domain driven design.
- // You can create hundreds of little types that accurately
+ // You can create hundreds of little types that accurately
// reflect the domain.
type CartItem = { ProductCode: string; Qty: int }
type Payment = Payment of float
type ActiveCartData = { UnpaidItems: CartItem list }
type PaidCartData = { PaidItems: CartItem list; Payment: Payment}
-
- type ShoppingCart =
+
+ type ShoppingCart =
| EmptyCart // no data
| ActiveCart of ActiveCartData
- | PaidCart of PaidCartData
+ | PaidCart of PaidCartData
- // ------------------------------------
+ // ------------------------------------
// Built in behavior for types
- // ------------------------------------
+ // ------------------------------------
// Core types have useful "out-of-the-box" behavior, no coding needed.
// * Immutability
// * Pretty printing when debugging
// * Equality and comparison
// * Serialization
-
+
// Pretty printing using %A
- printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
+ printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A"
twoTuple person1 temp1 worker
// Equality and comparison built in.
// Here's an example with cards.
type Suit = Club | Diamond | Spade | Heart
- type Rank = Two | Three | Four | Five | Six | Seven | Eight
- | Nine | Ten | Jack | Queen | King | Ace
+ type Rank = Two | Three | Four | Five | Six | Seven | Eight
+ | Nine | Ten | Jack | Queen | King | Ace
- let hand = [ Club,Ace; Heart,Three; Heart,Ace;
+ let hand = [ Club,Ace; Heart,Three; Heart,Ace;
Spade,Jack; Diamond,Two; Diamond,Ace ]
// sorting
@@ -391,27 +391,27 @@ module DataTypeExamples =
List.max hand |> printfn "high card is %A"
List.min hand |> printfn "low card is %A"
-
+
// ================================================
// Active patterns
// ================================================
-module ActivePatternExamples =
+module ActivePatternExamples =
- // F# has a special type of pattern matching called "active patterns"
- // where the pattern can be parsed or detected dynamically.
+ // F# has a special type of pattern matching called "active patterns"
+ // where the pattern can be parsed or detected dynamically.
// "banana clips" are the syntax for active patterns
-
+
// for example, define an "active" pattern to match character types...
- let (|Digit|Letter|Whitespace|Other|) ch =
+ let (|Digit|Letter|Whitespace|Other|) ch =
if System.Char.IsDigit(ch) then Digit
else if System.Char.IsLetter(ch) then Letter
else if System.Char.IsWhiteSpace(ch) then Whitespace
- else Other
+ else Other
// ... and then use it to make parsing logic much clearer
- let printChar ch =
+ let printChar ch =
match ch with
| Digit -> printfn "%c is a Digit" ch
| Letter -> printfn "%c is a Letter" ch
@@ -424,52 +424,52 @@ module ActivePatternExamples =
// -----------------------------------
// FizzBuzz using active patterns
// -----------------------------------
-
+
// You can create partial matching patterns as well
// Just use undercore in the defintion, and return Some if matched.
let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None
let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None
// the main function
- let fizzBuzz i =
+ let fizzBuzz i =
match i with
- | MultOf3 & MultOf5 -> printf "FizzBuzz, "
- | MultOf3 -> printf "Fizz, "
- | MultOf5 -> printf "Buzz, "
+ | MultOf3 & MultOf5 -> printf "FizzBuzz, "
+ | MultOf3 -> printf "Fizz, "
+ | MultOf5 -> printf "Buzz, "
| _ -> printf "%i, " i
-
+
// test
- [1..20] |> List.iter fizzBuzz
-
+ [1..20] |> List.iter fizzBuzz
+
// ================================================
-// Conciseness
+// Conciseness
// ================================================
-module AlgorithmExamples =
+module AlgorithmExamples =
- // F# has a high signal/noise ratio, so code reads
+ // F# has a high signal/noise ratio, so code reads
// almost like the actual algorithm
// ------ Example: define sumOfSquares function ------
- let sumOfSquares n =
+ let sumOfSquares n =
[1..n] // 1) take all the numbers from 1 to n
|> List.map square // 2) square each one
|> List.sum // 3) sum the results
- // test
- sumOfSquares 100 |> printfn "Sum of squares = %A"
-
- // ------ Example: define a sort function ------
+ // test
+ sumOfSquares 100 |> printfn "Sum of squares = %A"
+
+ // ------ Example: define a sort function ------
let rec sort list =
match list with
- // If the list is empty
- | [] ->
+ // If the list is empty
+ | [] ->
[] // return an empty list
- // If the list is not empty
- | firstElem::otherElements -> // take the first element
- let smallerElements = // extract the smaller elements
+ // If the list is not empty
+ | firstElem::otherElements -> // take the first element
+ let smallerElements = // extract the smaller elements
otherElements // from the remaining ones
- |> List.filter (fun e -> e < firstElem)
+ |> List.filter (fun e -> e < firstElem)
|> sort // and sort them
let largerElements = // extract the larger ones
otherElements // from the remaining ones
@@ -479,13 +479,13 @@ module AlgorithmExamples =
List.concat [smallerElements; [firstElem]; largerElements]
// test
- sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
+ sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A"
// ================================================
// Asynchronous Code
// ================================================
-module AsyncExample =
+module AsyncExample =
// F# has built-in features to help with async code
// without encountering the "pyramid of doom"
@@ -495,23 +495,23 @@ module AsyncExample =
open System.Net
open System
open System.IO
- open Microsoft.FSharp.Control.CommonExtensions
+ open Microsoft.FSharp.Control.CommonExtensions
// Fetch the contents of a URL asynchronously
- let fetchUrlAsync url =
- async { // "async" keyword and curly braces
+ let fetchUrlAsync url =
+ async { // "async" keyword and curly braces
// creates an "async" object
- let req = WebRequest.Create(Uri(url))
- use! resp = req.AsyncGetResponse()
+ let req = WebRequest.Create(Uri(url))
+ use! resp = req.AsyncGetResponse()
// use! is async assignment
- use stream = resp.GetResponseStream()
+ use stream = resp.GetResponseStream()
// "use" triggers automatic close()
// on resource at end of scope
- use reader = new IO.StreamReader(stream)
- let html = reader.ReadToEnd()
- printfn "finished downloading %s" url
+ use reader = new IO.StreamReader(stream)
+ let html = reader.ReadToEnd()
+ printfn "finished downloading %s" url
}
-
+
// a list of sites to fetch
let sites = ["http://www.bing.com";
"http://www.google.com";
@@ -520,7 +520,7 @@ module AsyncExample =
"http://www.yahoo.com"]
// do it
- sites
+ sites
|> List.map fetchUrlAsync // make a list of async tasks
|> Async.Parallel // set up the tasks to run in parallel
|> Async.RunSynchronously // start them off
@@ -529,58 +529,58 @@ module AsyncExample =
// .NET compatability
// ================================================
-module NetCompatibilityExamples =
+module NetCompatibilityExamples =
// F# can do almost everything C# can do, and it integrates
// seamlessly with .NET or Mono libraries.
// ------- work with existing library functions -------
-
+
let (i1success,i1) = System.Int32.TryParse("123");
if i1success then printfn "parsed as %i" i1 else printfn "parse failed"
// ------- Implement interfaces on the fly! -------
-
+
// create a new object that implements IDisposable
- let makeResource name =
- { new System.IDisposable
+ let makeResource name =
+ { new System.IDisposable
with member this.Dispose() = printfn "%s disposed" name }
- let useAndDisposeResources =
+ let useAndDisposeResources =
use r1 = makeResource "first resource"
- printfn "using first resource"
+ printfn "using first resource"
for i in [1..3] do
let resourceName = sprintf "\tinner resource %d" i
- use temp = makeResource resourceName
- printfn "\tdo something with %s" resourceName
+ use temp = makeResource resourceName
+ printfn "\tdo something with %s" resourceName
use r2 = makeResource "second resource"
- printfn "using second resource"
- printfn "done."
+ printfn "using second resource"
+ printfn "done."
// ------- Object oriented code -------
-
+
// F# is also a fully fledged OO language.
// It supports classes, inheritance, virtual methods, etc.
// interface with generic type
- type IEnumerator<'a> =
+ type IEnumerator<'a> =
abstract member Current : 'a
- abstract MoveNext : unit -> bool
+ abstract MoveNext : unit -> bool
// abstract base class with virtual methods
[]
- type Shape() =
+ type Shape() =
//readonly properties
abstract member Width : int with get
abstract member Height : int with get
//non-virtual method
member this.BoundingArea = this.Height * this.Width
//virtual method with base implementation
- abstract member Print : unit -> unit
+ abstract member Print : unit -> unit
default this.Print () = printfn "I'm a shape"
- // concrete class that inherits from base class and overrides
- type Rectangle(x:int, y:int) =
+ // concrete class that inherits from base class and overrides
+ type Rectangle(x:int, y:int) =
inherit Shape()
override this.Width = x
override this.Height = y
@@ -590,20 +590,20 @@ module NetCompatibilityExamples =
let r = Rectangle(2,3)
printfn "The width is %i" r.Width
printfn "The area is %i" r.BoundingArea
- r.Print()
+ r.Print()
// ------- extension methods -------
-
+
//Just as in C#, F# can extend existing classes with extension methods.
type System.String with
member this.StartsWithA = this.StartsWith "A"
//test
let s = "Alice"
- printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
-
+ printfn "'%s' starts with an 'A' = %A" s s.StartsWithA
+
// ------- events -------
-
+
type MyButton() =
let clickEvent = new Event<_>()
@@ -615,11 +615,11 @@ module NetCompatibilityExamples =
// test
let myButton = new MyButton()
- myButton.OnClick.Add(fun (sender, arg) ->
+ myButton.OnClick.Add(fun (sender, arg) ->
printfn "Click event with arg=%O" arg)
myButton.TestEvent("Hello World!")
-
+
```
## More Information
diff --git a/hack.html.markdown b/hack.html.markdown
index b9730dc0..b3d19f8e 100644
--- a/hack.html.markdown
+++ b/hack.html.markdown
@@ -51,7 +51,7 @@ function identity(?string $stringOrNull) : ?string
class TypeHintedProperties
{
public ?string $name;
-
+
protected int $id;
private float $score = 100.0;
@@ -91,7 +91,7 @@ function openBox(Box $box) : int
// Shapes
-//
+//
// Hack adds the concept of shapes for defining struct-like arrays with a
// guaranteed, type-checked set of keys
type Point2D = shape('x' => int, 'y' => int);
@@ -108,7 +108,7 @@ distance(
// Type aliasing
-//
+//
// Hack adds a bunch of type aliasing features for making complex types readable
newtype VectorArray = array>;
@@ -142,7 +142,7 @@ function getRoadType() : RoadType
// Constructor argument promotion
-//
+//
// To avoid boilerplate property and constructor definitions that only set
// properties, Hack adds a concise syntax for defining properties and a
// constructor at the same time.
@@ -171,12 +171,12 @@ class WithoutArgumentPromotion
// Co-operative multi-tasking
-//
+//
// Two new keywords "async" and "await" can be used to perform multi-tasking
// Note that this does not involve threads - it just allows transfer of control
async function cooperativePrint(int $start, int $end) : Awaitable
{
- for ($i = $start; $i <= $end; $i++) {
+ for ($i = $start; $i <= $end; $i++) {
echo "$i ";
// Give other tasks a chance to do something
@@ -193,9 +193,9 @@ AwaitAllWaitHandle::fromArray([
// Attributes
-//
+//
// Attributes are a form of metadata for functions. Hack provides some
-// special built-in attributes that introduce useful behaviour.
+// special built-in attributes that introduce useful behaviour.
// The __Memoize special attribute causes the result of a function to be cached
<<__Memoize>>
@@ -248,7 +248,7 @@ class ConsistentBar extends ConsistentFoo
class InvalidFooSubclass extends ConsistentFoo
{
// Not matching the parent constructor will cause a type checker error:
- //
+ //
// "This object is of type ConsistentBaz. It is incompatible with this object
// of type ConsistentFoo because some of their methods are incompatible"
//
@@ -259,7 +259,7 @@ class InvalidFooSubclass extends ConsistentFoo
// Using the __Override annotation on a non-overriden method will cause a
// type checker error:
- //
+ //
// "InvalidFooSubclass::otherMethod() is marked as override; no non-private
// parent definition found or overridden parent is defined in non- COUNTRIES = new HashSet();
static {
validCodes.add("DENMARK");
validCodes.add("SWEDEN");
validCodes.add("FINLAND");
}
-
+
// But there's a nifty way to achive the same thing in an
// easier way, by using something that is called Double Brace
// Initialization.
-
+
private static final Set COUNTRIES = HashSet() {{
add("DENMARK");
add("SWEDEN");
- add("FINLAND");
+ add("FINLAND");
}}
-
- // The first brace is creating an new AnonymousInnerClass and the
+
+ // The first brace is creating an new AnonymousInnerClass and the
// second one declares and instance initializer block. This block
// is called with the anonymous inner class is created.
// This does not only work for Collections, it works for all
@@ -500,7 +500,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
}
-// Abstract Classes
+// Abstract Classes
// Abstract Class declaration syntax
// abstract extends {
// // Constants and variables
@@ -512,26 +512,26 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
// Also abstract classes CAN have the "main" method.
// Abstract classes solve these problems.
-public abstract class Animal
+public abstract class Animal
{
public abstract void makeSound();
// Method can have a body
public void eat()
{
- System.out.println("I am an animal and I am Eating.");
+ System.out.println("I am an animal and I am Eating.");
// Note: We can access private variable here.
age = 30;
}
- // No need to initialize, however in an interface
+ // No need to initialize, however in an interface
// a variable is implicitly final and hence has
// to be initialized.
private int age;
public void printAge()
{
- System.out.println(age);
+ System.out.println(age);
}
// Abstract classes can have main function.
@@ -552,7 +552,7 @@ class Dog extends Animal
// age = 30; ==> ERROR! age is private to Animal
}
- // NOTE: You will get an error if you used the
+ // NOTE: You will get an error if you used the
// @Override annotation here, since java doesn't allow
// overriding of static methods.
// What is happening here is called METHOD HIDING.
diff --git a/json.html.markdown b/json.html.markdown
index 47a8cb21..6aff2ce2 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -16,7 +16,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
```json
{
"key": "value",
-
+
"keys": "must always be enclosed in double quotes",
"numbers": 0,
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
@@ -46,7 +46,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
[0, 0, 0, 1]
]
],
-
+
"alternative style": {
"comment": "check this out!"
, "comma position": "doesn't matter - as long as it's before the value, then it's valid"
diff --git a/julia.html.markdown b/julia.html.markdown
index 5ccd6484..66329feb 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -14,7 +14,7 @@ This is based on Julia 0.3.
# Single line comments start with a hash (pound) symbol.
#= Multiline comments can be written
- by putting '#=' before the text and '=#'
+ by putting '#=' before the text and '=#'
after the text. They can also be nested.
=#
@@ -670,7 +670,7 @@ square_area(l) = l * l # square_area (generic function with 1 method)
square_area(5) #25
# What happens when we feed square_area an integer?
-code_native(square_area, (Int32,))
+code_native(square_area, (Int32,))
# .section __TEXT,__text,regular,pure_instructions
# Filename: none
# Source line: 1 # Prologue
@@ -703,10 +703,10 @@ code_native(square_area, (Float64,))
# vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX)
# pop RBP
# ret
- #
+ #
# Note that julia will use floating point instructions if any of the
# arguements are floats.
-# Let's calculate the area of a circle
+# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
@@ -737,7 +737,7 @@ code_native(circle_area, (Float64,))
# vmulsd XMM0, XMM1, XMM0
# pop RBP
# ret
- #
+ #
```
## Further Reading
diff --git a/livescript.html.markdown b/livescript.html.markdown
index e64f7719..9235f5ce 100644
--- a/livescript.html.markdown
+++ b/livescript.html.markdown
@@ -166,7 +166,7 @@ not false # => true
########################################################################
## 3. Functions
-########################################################################
+########################################################################
# Since LiveScript is functional, you'd expect functions to get a nice
# treatment. In LiveScript it's even more apparent that functions are
@@ -229,7 +229,7 @@ double-minus-one = (- 1) . (* 2)
# Other than the usual `f . g` mathematical formulae, you get the `>>`
# and `<<` operators, that describe how the flow of values through the
-# functions.
+# functions.
double-minus-one = (* 2) >> (- 1)
double-minus-one = (- 1) << (* 2)
@@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*"
## Further reading
There's just so much more to LiveScript, but this should be enough to
-get you started writing little functional things in it. The
+get you started writing little functional things in it. The
[official website](http://livescript.net/) has a lot of information on the
language, and a nice online compiler for you to try stuff out!
diff --git a/make.html.markdown b/make.html.markdown
index 75543dcd..563139d1 100644
--- a/make.html.markdown
+++ b/make.html.markdown
@@ -31,7 +31,7 @@ we are using GNU make which is the standard on Linux.
file0.txt:
echo "foo" > file0.txt
# Even comments in these 'recipe' sections get passed to the shell.
- # Try `make file0.txt` or simply `make` - first rule is the default.
+ # Try `make file0.txt` or simply `make` - first rule is the default.
# This rule will only run if file0.txt is newer than file1.txt.
@@ -49,7 +49,7 @@ file2.txt file3.txt: file0.txt file1.txt
touch file2.txt
touch file3.txt
-# Make will complain about multiple recipes for the same rule. Empty
+# Make will complain about multiple recipes for the same rule. Empty
# recipes don't count though and can be used to add new dependencies.
#-----------------------------------------------------------------------
@@ -115,7 +115,7 @@ small/%.png: %.svg
%.png: %.ps
@echo this rule is not chosen if *.svg and *.ps are both present
-# make already has some pattern rules built-in. For instance, it knows
+# make already has some pattern rules built-in. For instance, it knows
# how to turn *.c files into *.o files.
# Older makefiles might use suffix rules instead of pattern rules
@@ -185,7 +185,7 @@ var := hello
var2 ::= $(var) hello
#:= and ::= are equivalent.
-# These variables are evaluated procedurely (in the order that they
+# These variables are evaluated procedurely (in the order that they
# appear), thus breaking with the rest of the language !
# This doesn't work
diff --git a/markdown.html.markdown b/markdown.html.markdown
index acb808ea..2333110f 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -70,7 +70,7 @@ I'm in paragraph three!
-I end with two spaces (highlight me to see them).
+I end with two spaces (highlight me to see them).
There's a above me!
@@ -97,7 +97,7 @@ or
+ Item
+ One more item
-or
+or
- Item
- Item
@@ -129,7 +129,7 @@ render the numbers in order, but this may not be a good idea -->
Boxes below without the 'x' are unchecked HTML checkboxes.
-- [ ] First task to complete.
+- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
@@ -169,7 +169,7 @@ with or without spaces. -->
***
---
-- - -
+- - -
****************
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 00f4c53a..02fe5962 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -6,7 +6,7 @@ contributors:
---
-MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
+MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics.
If you have any feedback please feel free to reach me at
[@the_ozzinator](https://twitter.com/the_ozzinator), or
@@ -16,7 +16,7 @@ If you have any feedback please feel free to reach me at
% Comments start with a percent sign.
%{
-Multi line comments look
+Multi line comments look
something
like
this
@@ -62,10 +62,10 @@ disp('text') % print "text" to the screen
% Variables & Expressions
myVariable = 4 % Notice Workspace pane shows newly created variable
myVariable = 4; % Semi colon suppresses output to the Command Window
-4 + 6 % ans = 10
-8 * myVariable % ans = 32
-2 ^ 3 % ans = 8
-a = 2; b = 3;
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+2 ^ 3 % ans = 8
+a = 2; b = 3;
c = exp(a)*sin(pi/2) % c = 7.3891
% Calling functions can be done in either of two ways:
@@ -73,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
% Command syntax:
load myFile.mat y % no parentheses, and spaces instead of commas
-% Note the lack of quote marks in command form: inputs are always passed as
+% Note the lack of quote marks in command form: inputs are always passed as
% literal text - cannot pass variable values. Also, can't receive output:
[V,D] = eig(A); % this has no equivalent in command form
[~,D] = eig(A); % if you only want D and not V
@@ -103,7 +103,7 @@ a(2) % ans = y
% Cells
-a = {'one', 'two', 'three'}
+a = {'one', 'two', 'three'}
a(1) % ans = 'one' - returns a cell
char(a(1)) % ans = one - returns a string
@@ -113,7 +113,7 @@ A.c = [1 2];
A.d.e = false;
% Vectors
-x = [4 32 53 7 1]
+x = [4 32 53 7 1]
x(2) % ans = 32, indices in Matlab start 1, not 0
x(2:3) % ans = 32 53
x(2:end) % ans = 32 53 7 1
@@ -123,7 +123,7 @@ x = [4; 32; 53; 7; 1] % Column vector
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
% Matrices
-A = [1 2 3; 4 5 6; 7 8 9]
+A = [1 2 3; 4 5 6; 7 8 9]
% Rows are separated by a semicolon; elements are separated with space or comma
% A =
@@ -132,7 +132,7 @@ A = [1 2 3; 4 5 6; 7 8 9]
% 7 8 9
A(2,3) % ans = 6, A(row, column)
-A(6) % ans = 8
+A(6) % ans = 8
% (implicitly concatenates columns into vector, then indexes into that)
@@ -171,7 +171,7 @@ A(1,:) % All columns in row 1
% 4 5 42
% 7 8 9
-% this is the same as
+% this is the same as
vertcat(A,A);
@@ -183,7 +183,7 @@ vertcat(A,A);
% 4 5 42 4 5 42
% 7 8 9 7 8 9
-% this is the same as
+% this is the same as
horzcat(A,A);
@@ -201,21 +201,21 @@ A(:, 1) =[] % Delete the first column of the matrix
transpose(A) % Transpose the matrix, which is the same as:
A one
-ctranspose(A) % Hermitian transpose the matrix
+ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
-% Element by Element Arithmetic vs. Matrix Arithmetic
+% Element by Element Arithmetic vs. Matrix Arithmetic
% On their own, the arithmetic operators act on whole matrices. When preceded
% by a period, they act on each element instead. For example:
A * B % Matrix multiplication
A .* B % Multiple each element in A by its corresponding element in B
-% There are several pairs of functions, where one acts on each element, and
+% There are several pairs of functions, where one acts on each element, and
% the other (whose name ends in m) acts on the whole matrix.
-exp(A) % exponentiate each element
+exp(A) % exponentiate each element
expm(A) % calculate the matrix exponential
sqrt(A) % take the square root of each element
sqrtm(A) % find the matrix whose square is A
@@ -233,7 +233,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1
plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot
legend('Line 1 label', 'Line 2 label') % Label curves with a legend
-% Alternative method to plot multiple functions in one plot.
+% Alternative method to plot multiple functions in one plot.
% while 'hold' is on, commands add to existing graph rather than replacing it
plot(x, y)
hold on
@@ -271,9 +271,9 @@ clf clear % clear current figure window, and reset most figure properties
% Properties can be set and changed through a figure handle.
% You can save a handle to a figure when you create it.
-% The function gcf returns a handle to the current figure
+% The function gcf returns a handle to the current figure
h = plot(x, y); % you can save a handle to a figure when you create it
-set(h, 'Color', 'r')
+set(h, 'Color', 'r')
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
set(h, 'LineStyle', '--')
% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line
@@ -298,8 +298,8 @@ cd /path/to/move/into % change directory
% Variables can be saved to .mat files
-save('myFileName.mat') % Save the variables in your Workspace
-load('myFileName.mat') % Load saved variables into Workspace
+save('myFileName.mat') % Save the variables in your Workspace
+load('myFileName.mat') % Load saved variables into Workspace
% M-file Scripts
% A script file is an external file that contains a sequence of statements.
@@ -312,11 +312,11 @@ load('myFileName.mat') % Load saved variables into Workspace
% Also, they have their own workspace (ie. different variable scope).
% Function name should match file name (so save this example as double_input.m).
% 'help double_input.m' returns the comments under line beginning function
-function output = double_input(x)
+function output = double_input(x)
%double_input(x) returns twice the value of x
output = 2*x;
end
-double_input(6) % ans = 12
+double_input(6) % ans = 12
% You can also have subfunctions and nested functions.
@@ -325,8 +325,8 @@ double_input(6) % ans = 12
% functions, and have access to both its workspace and their own workspace.
% If you want to create a function without creating a new file you can use an
-% anonymous function. Useful when quickly defining a function to pass to
-% another function (eg. plot with fplot, evaluate an indefinite integral
+% anonymous function. Useful when quickly defining a function to pass to
+% another function (eg. plot with fplot, evaluate an indefinite integral
% with quad, find roots with fzero, or find minimum with fminsearch).
% Example that returns the square of it's input, assigned to to the handle sqr:
sqr = @(x) x.^2;
@@ -336,12 +336,12 @@ doc function_handle % find out more
% User input
a = input('Enter the value: ')
-% Stops execution of file and gives control to the keyboard: user can examine
+% Stops execution of file and gives control to the keyboard: user can examine
% or change variables. Type 'return' to continue execution, or 'dbquit' to exit
keyboard
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files)
-fopen(filename)
+fopen(filename)
% Output
disp(a) % Print out the value of variable a
@@ -363,8 +363,8 @@ end
for k = 1:5
disp(k)
end
-
-k = 0;
+
+k = 0;
while (k < 5)
k = k + 1;
end
@@ -382,7 +382,7 @@ password = 'root';
driver = 'com.mysql.jdbc.Driver';
dburl = ['jdbc:mysql://localhost:8889/' dbname];
javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/
-conn = database(dbname, username, password, driver, dburl);
+conn = database(dbname, username, password, driver, dburl);
sql = ['SELECT * from table_name where id = 22'] % Example sql statement
a = fetch(conn, sql) %a will contain your data
@@ -394,7 +394,7 @@ tan(x)
asin(x)
acos(x)
atan(x)
-exp(x)
+exp(x)
sqrt(x)
log(x)
log10(x)
@@ -426,7 +426,7 @@ pinv(A) % calculate the pseudo-inverse
zeros(m,n) % m x n matrix of 0's
ones(m,n) % m x n matrix of 1's
diag(A) % Extracts the diagonal elements of a matrix A
-diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
+diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere
eye(m,n) % Identity matrix
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2
inv(A) % Inverse of matrix A
@@ -452,15 +452,15 @@ flipud(A) % Flip matrix up to down
[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order
% Common vector functions
-max % largest component
-min % smallest component
+max % largest component
+min % smallest component
length % length of a vector
-sort % sort in ascending order
-sum % sum of elements
+sort % sort in ascending order
+sum % sum of elements
prod % product of elements
mode % modal value
-median % median value
-mean % mean value
+median % median value
+mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
diff --git a/neat.html.markdown b/neat.html.markdown
index e99d1e0e..f02461ee 100644
--- a/neat.html.markdown
+++ b/neat.html.markdown
@@ -47,18 +47,18 @@ void main(string[] args) {
// There are no one-value tuples though.
// So you can always use () in the mathematical sense.
// (string) arg; <- is an error
-
+
/*
byte: 8 bit signed integer
char: 8 bit UTF-8 byte component.
short: 16 bit signed integer
int: 32 bit signed integer
long: 64 bit signed integer
-
+
float: 32 bit floating point
double: 64 bit floating point
real: biggest native size floating point (80 bit on x86).
-
+
bool: true or false
*/
int a = 5;
@@ -139,14 +139,14 @@ void main(string[] args) {
assert !(hewo is s);
// same as
assert (hewo !is s);
-
+
// Allocate arrays using "new array length"
int[] integers = new int[] 10;
assert(integers.length == 10);
assert(integers[0] == 0); // zero is default initializer
integers = integers ~ 5; // This allocates a new array!
assert(integers.length == 11);
-
+
// This is an appender array.
// Instead of (length, pointer), it tracks (capacity, length, pointer).
// When you append to it, it will use the free capacity if it can.
@@ -156,13 +156,13 @@ void main(string[] args) {
appender ~= 2;
appender ~= 3;
appender.free(); // same as {mem.free(appender.ptr); appender = null;}
-
+
// Scope variables are automatically freed at the end of the current scope.
scope int[auto~] someOtherAppender;
// This is the same as:
int[auto~] someOtherAppender2;
onExit { someOtherAppender2.free; }
-
+
// You can do a C for loop too
// - but why would you want to?
for (int i = 0; i < 5; ++i) { }
@@ -178,23 +178,23 @@ void main(string[] args) {
assert(i == 5);
break; // otherwise we'd go back up to do {
}
-
+
// This is a nested function.
// Nested functions can access the surrounding function.
string returnS() { return s; }
writeln returnS();
-
+
// Take the address of a function using &
// The type of a global function is ReturnType function(ParameterTypeTuple).
void function() foop = &foo;
-
+
// Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple).
string delegate() returnSp = &returnS;
writeln returnSp();
// Class member functions and struct member functions also fit into delegate variables.
// In general, delegates are functions that carry an additional context pointer.
// ("fat pointers" in C)
-
+
// Allocate a "snapshot" with "new delegate".
// Snapshots are not closures! I used to call them closures too,
// but then my Haskell-using friends yelled at me so I had to stop.
@@ -232,8 +232,8 @@ void main(string[] args) {
auto nestfun = λ() { } // There is NO semicolon needed here!
// "}" can always substitute for "};".
// This provides syntactic consistency with built-in statements.
-
-
+
+
// This is a class.
// Note: almost all elements of Neat can be used on the module level
// or just as well inside a function.
@@ -268,7 +268,7 @@ void main(string[] args) {
E e = E:cd; // dynamic class cast!
e.doE();
writeln "$e"; // all interfaces convert to Object implicitly.
-
+
// Templates!
// Templates are parameterized namespaces, taking a type as a parameter.
template Templ(T) {
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 407ba3c8..89901308 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -11,7 +11,7 @@ filename: LearnObjectiveC.m
---
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
-It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
+It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
```objective_c
// Single-line comments start with //
@@ -41,15 +41,15 @@ int main (int argc, const char * argv[])
// Use NSLog to print lines to the console
NSLog(@"Hello World!"); // Print the string "Hello World!"
-
+
///////////////////////////////////////
// Types & Variables
///////////////////////////////////////
-
+
// Primitive declarations
int myPrimitive1 = 1;
long myPrimitive2 = 234554664565;
-
+
// Object declarations
// Put the * in front of the variable names for strongly-typed object declarations
MyClass *myObject1 = nil; // Strong typing
@@ -57,15 +57,15 @@ int main (int argc, const char * argv[])
// %@ is an object
// 'description' is a convention to display the value of the Objects
NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)"
-
+
// String
NSString *worldString = @"World";
- NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
+ NSLog(@"Hello %@!", worldString); // prints => "Hello World!"
// NSMutableString is a mutable version of the NSString object
NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
[mutableString appendString:@" World!"];
NSLog(@"%@", mutableString); // prints => "Hello World!"
-
+
// Character literals
NSNumber *theLetterZNumber = @'Z';
char theLetterZ = [theLetterZNumber charValue]; // or 'Z'
@@ -75,11 +75,11 @@ int main (int argc, const char * argv[])
NSNumber *fortyTwoNumber = @42;
int fortyTwo = [fortyTwoNumber intValue]; // or 42
NSLog(@"%i", fortyTwo);
-
+
NSNumber *fortyTwoUnsignedNumber = @42U;
unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
NSLog(@"%u", fortyTwoUnsigned);
-
+
NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42
NSLog(@"%hi", fortyTwoShort);
@@ -87,7 +87,7 @@ int main (int argc, const char * argv[])
NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41];
unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
NSLog(@"%u", fortyOneUnsigned);
-
+
NSNumber *fortyTwoLongNumber = @42L;
long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42
NSLog(@"%li", fortyTwoLong);
@@ -101,7 +101,7 @@ int main (int argc, const char * argv[])
float piFloat = [piFloatNumber floatValue]; // or 3.141592654f
NSLog(@"%f", piFloat); // prints => 3.141592654
NSLog(@"%5.2f", piFloat); // prints => " 3.14"
-
+
NSNumber *piDoubleNumber = @3.1415926535;
double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535
NSLog(@"%f", piDouble);
@@ -111,7 +111,7 @@ int main (int argc, const char * argv[])
NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
- [oneDecNum decimalNumberByAdding:twoDecNum];
+ [oneDecNum decimalNumberByAdding:twoDecNum];
[oneDecNum decimalNumberBySubtracting:twoDecNum];
[oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
[oneDecNum decimalNumberByDividingBy:twoDecNum];
@@ -130,8 +130,8 @@ int main (int argc, const char * argv[])
NSArray *anArray = @[@1, @2, @3, @4];
NSNumber *thirdNumber = anArray[2];
NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3"
- // NSMutableArray is a mutable version of NSArray, allowing you to change
- // the items in the array and to extend or shrink the array object.
+ // NSMutableArray is a mutable version of NSArray, allowing you to change
+ // the items in the array and to extend or shrink the array object.
// Convenient, but not as efficient as NSArray.
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
[mutableArray addObject:@"Hello"];
@@ -161,7 +161,7 @@ int main (int argc, const char * argv[])
///////////////////////////////////////
// Operators
///////////////////////////////////////
-
+
// The operators works like in the C language
// For example:
2 + 5; // => 7
@@ -206,13 +206,13 @@ int main (int argc, const char * argv[])
NSLog(@"I print");
} break;
}
-
+
// While loops statements
int ii = 0;
while (ii < 4)
{
NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
@@ -222,25 +222,25 @@ int main (int argc, const char * argv[])
for (jj=0; jj < 4; jj++)
{
NSLog(@"%d,", jj);
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
-
- // Foreach statements
+
+ // Foreach statements
NSArray *values = @[@0, @1, @2, @3];
for (NSNumber *value in values)
{
NSLog(@"%@,", value);
- } // prints => "0,"
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
// Object for loop statement. Can be used with any Objective-C object type
- for (id item in values) {
- NSLog(@"%@,", item);
- } // prints => "0,"
+ for (id item in values) {
+ NSLog(@"%@,", item);
+ } // prints => "0,"
// "1,"
// "2,"
// "3,"
@@ -251,7 +251,7 @@ int main (int argc, const char * argv[])
// Your statements here
@throw [NSException exceptionWithName:@"FileNotFoundException"
reason:@"File Not Found on System" userInfo:nil];
- } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
+ } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
{
NSLog(@"Exception: %@", e);
} @finally
@@ -260,17 +260,17 @@ int main (int argc, const char * argv[])
} // prints => "Exception: File Not Found on System"
// "Finally. Time to clean up."
- // NSError objects are useful for function arguments to populate on user mistakes.
+ // NSError objects are useful for function arguments to populate on user mistakes.
NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];
-
+
///////////////////////////////////////
// Objects
///////////////////////////////////////
-
+
// Create an object instance by allocating memory and initializing it
// An object is not fully functional until both steps have been completed
MyClass *myObject = [[MyClass alloc] init];
-
+
// The Objective-C model of object-oriented programming is based on message
// passing to object instances
// In Objective-C one does not simply call a method; one sends a message
@@ -281,7 +281,7 @@ int main (int argc, const char * argv[])
// End of @autoreleasepool
}
-
+
// End the program
return 0;
}
@@ -302,9 +302,9 @@ int main (int argc, const char * argv[])
@interface MyClass : NSObject // NSObject is Objective-C's base object class.
{
// Instance variable declarations (can exist in either interface or implementation file)
- int count; // Protected access by default.
+ int count; // Protected access by default.
@private id data; // Private access (More convenient to declare in implementation file)
- NSString *name;
+ NSString *name;
}
// Convenient notation for public access variables to auto generate a setter method
// By default, setter method name is 'set' followed by @property variable name
@@ -314,7 +314,7 @@ int main (int argc, const char * argv[])
@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor
// You can customize the getter and setter names instead of using default 'set' name:
@property (getter=lengthGet, setter=lengthSet:) int length;
-
+
// Methods
+/- (return type)methodSignature:(Parameter Type *)parameterName;
@@ -336,7 +336,7 @@ int main (int argc, const char * argv[])
// To access public variables from the implementation file, @property generates a setter method
// automatically. Method name is 'set' followed by @property variable name:
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
-[myClass setCount:10];
+[myClass setCount:10];
NSLog(@"%d", [myClass count]); // prints => 10
// Or using the custom getter and setter method defined in @interface:
[myClass lengthSet:32];
@@ -359,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell
// as a variable
// SEL is the data type. @selector() returns a selector from method name provided
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
-SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
+SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
// Must put all method arguments into one object to send to performSelector function
NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
@@ -383,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation
@synthesize roString = _roString; // _roString available now in @implementation
// Called before calling any class methods or instantiating any objects
-+ (void)initialize
++ (void)initialize
{
if (self == [MyClass class]) {
distance = 0;
@@ -393,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation
// Counterpart to initialize method. Called when an object's reference count is zero
- (void)dealloc
{
- [height release]; // If not using ARC, make sure to release class variable objects
+ [height release]; // If not using ARC, make sure to release class variable objects
[super dealloc]; // and call parent class dealloc
}
@@ -408,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation
return self;
}
// Can create constructors that contain arguments:
-- (id)initWithDistance:(int)defaultDistance
+- (id)initWithDistance:(int)defaultDistance
{
distance = defaultDistance;
return self;
@@ -419,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation
return @"Some string";
}
-+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
{
height = defaultHeight;
return [[self alloc] init];
@@ -435,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation
return @42;
}
-// Objective-C does not have private method declarations, but you can simulate them.
+// Objective-C does not have private method declarations, but you can simulate them.
// To simulate a private method, create the method in the @implementation but not in the @interface.
- (NSNumber *)secretPrivateMethod {
return @72;
@@ -454,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation
// Categories
///////////////////////////////////////
// A category is a group of methods designed to extend a class. They allow you to add new methods
-// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
-// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
+// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
+// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
// functionality to an object.
// Categories allow you to:
// -- Add methods to an existing class for organizational purposes.
// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
-// -- Add ability to create protected and private methods to classes.
-// NOTE: Do not override methods of the base class in a category even though you have the ability
-// to. Overriding methods may cause compiler errors later between different categories and it
+// -- Add ability to create protected and private methods to classes.
+// NOTE: Do not override methods of the base class in a category even though you have the ability
+// to. Overriding methods may cause compiler errors later between different categories and it
// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.
// Here is a simple Car base class.
@@ -494,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation
@end
// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
-// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
-// functionality to this existing Car. A good example would be to clean the car. So we would create
+// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
+// functionality to this existing Car. A good example would be to clean the car. So we would create
// a category to add these cleaning methods:
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
#import "Car.h" // Make sure to import base class to extend.
@@ -519,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation
NSLog(@"Waxed.");
}
-@end
+@end
// Any Car object instance has the ability to use a category. All they need to do is import it:
#import "Car+Clean.h" // Import as many different categories as you want to use.
@@ -534,7 +534,7 @@ int main (int argc, const char * argv[]) {
[mustang turnOn]; // Use methods from base Car class.
[mustang washWindows]; // Use methods from Car's Clean category.
}
- return 0;
+ return 0;
}
// Objective-C does not have protected method declarations but you can simulate them.
@@ -548,7 +548,7 @@ int main (int argc, const char * argv[]) {
//To use protected methods, import the category, then implement the methods:
#import "Car+Protected.h" // Remember, import in the @implementation file only.
-@implementation Car
+@implementation Car
- (void)lockCar {
NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
@@ -571,8 +571,8 @@ int main (int argc, const char * argv[]) {
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
// @implementation filename: Shape.m
#import "Shape.h"
-// Extensions live in the same file as the class @implementation.
-@interface Shape () // () after base class name declares an extension.
+// Extensions live in the same file as the class @implementation.
+@interface Shape () // () after base class name declares an extension.
@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
@@ -580,7 +580,7 @@ int main (int argc, const char * argv[]) {
@end
// The main @implementation:
-@implementation Shape
+@implementation Shape
@synthesize numOfSides = _numOfSides;
@@ -604,14 +604,14 @@ int main (int argc, const char * argv[]) {
@property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
- (void)turnOnEngine; // all defined methods.
@end
-// Below is an example class implementing the protocol.
+// Below is an example class implementing the protocol.
#import "CarUtilities.h" // Import the @protocol file.
@interface Car : NSObject // Name of protocol goes inside <>
// You don't need the @property or method names here for CarUtilities. Only @implementation does.
- (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too.
@end
-// The @implementation needs to implement the @properties and methods for the protocol.
+// The @implementation needs to implement the @properties and methods for the protocol.
@implementation Car : NSObject
@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
@@ -620,14 +620,14 @@ int main (int argc, const char * argv[]) {
_engineOn = YES; // how you implement a method, it just requires that you do implement it.
}
// You may use a protocol as data as you know what methods and variables it has implemented.
-- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind {
+- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind {
[objectOfSomeKind engineOn]; // You have access to object variables
- [objectOfSomeKind turnOnEngine]; // and the methods inside.
+ [objectOfSomeKind turnOnEngine]; // and the methods inside.
[objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
}
@end
-// Instances of Car now have access to the protocol.
+// Instances of Car now have access to the protocol.
Car *carInstance = [[Car alloc] init];
[carInstance setEngineOn:NO];
[carInstance turnOnEngine];
@@ -656,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
// See the problem is that Sister relies on Brother, and Brother relies on Sister.
#import "Sister.h"
-@protocol Sister; // These lines stop the recursion, resolving the issue.
+@protocol Sister; // These lines stop the recursion, resolving the issue.
@protocol Brother
-
+
- (void)beNiceToSister:(id )sister;
@end
@@ -668,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
///////////////////////////////////////
// Blocks
///////////////////////////////////////
-// Blocks are statements of code, just like a function, that are able to be used as data.
+// Blocks are statements of code, just like a function, that are able to be used as data.
// Below is a simple block with an integer argument that returns the argument plus 4.
-int (^addUp)(int n); // Declare a variable to store the block.
-void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
+int (^addUp)(int n); // Declare a variable to store the block.
+void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
// Blocks have access to variables in the same scope. But the variables are readonly and the
-// value passed to the block is the value of the variable when the block is created.
+// value passed to the block is the value of the variable when the block is created.
int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17.
__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar.
-addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
+addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
NSLog(@"You may have as many lines in a block as you would like.");
NSSet *blockSet; // Also, you can declare local variables.
mutableVar = 32; // Assigning new value to __block variable.
- return n + outsideVar; // Return statements are optional.
+ return n + outsideVar; // Return statements are optional.
}
-int addUp = add(10 + 16); // Calls block code with arguments.
+int addUp = add(10 + 16); // Calls block code with arguments.
// Blocks are often used as arguments to functions to be called later, or for callbacks.
-@implementation BlockExample : NSObject
-
+@implementation BlockExample : NSObject
+
- (void)runBlock:(void (^)(NSString))block {
NSLog(@"Block argument returns nothing and takes in a NSString object.");
block(@"Argument given to block to execute."); // Calling block.
@@ -697,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments.
///////////////////////////////////////
// Memory Management
///////////////////////////////////////
-/*
+/*
For each object used in an application, memory must be allocated for that object. When the application
-is done using that object, memory must be deallocated to ensure application efficiency.
-Objective-C does not use garbage collection and instead uses reference counting. As long as
+is done using that object, memory must be deallocated to ensure application efficiency.
+Objective-C does not use garbage collection and instead uses reference counting. As long as
there is at least one reference to an object (also called "owning" an object), then the object
-will be available to use (known as "ownership").
+will be available to use (known as "ownership").
When an instance owns an object, its reference counter is increments by one. When the
object is released, the reference counter decrements by one. When reference count is zero,
-the object is removed from memory.
+the object is removed from memory.
-With all object interactions, follow the pattern of:
-(1) create the object, (2) use the object, (3) then free the object from memory.
+With all object interactions, follow the pattern of:
+(1) create the object, (2) use the object, (3) then free the object from memory.
*/
MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object
@@ -724,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still
// Automatic Reference Counting (ARC)
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
-// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
+// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
// you must not use retain, relase, or autorelease
-MyClass *arcMyClass = [[MyClass alloc] init];
+MyClass *arcMyClass = [[MyClass alloc] init];
// ... code using arcMyClass
-// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
+// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
// there is no need. It will insert this release statement for you
// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
index b0027fea..02435e4d 100644
--- a/ocaml.html.markdown
+++ b/ocaml.html.markdown
@@ -34,13 +34,13 @@ For a source file you can use "ocamlc -i /path/to/file.ml" command
to print all names and type signatures.
```
-$ cat sigtest.ml
+$ cat sigtest.ml
let inc x = x + 1
let add x y = x + y
-let a = 1
+let a = 1
-$ ocamlc -i ./sigtest.ml
+$ ocamlc -i ./sigtest.ml
val inc : int -> int
val add : int -> int -> int
val a : int
@@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;;
let sqr2 = sqr (-2) ;;
(* Every function must have at least one argument.
- Since some funcions naturally don't take any arguments, there's
+ Since some funcions naturally don't take any arguments, there's
"unit" type for it that has the only one value written as "()" *)
let print_hello () = print_endline "hello world" ;;
@@ -301,7 +301,7 @@ let l = IntList (1, EmptyList) ;;
(* Pattern matching is somewhat similar to switch statement in imperative
languages, but offers a lot more expressive power.
- Even though it may look complicated, it really boils down to matching
+ Even though it may look complicated, it really boils down to matching
an argument against an exact value, a predicate, or a type constructor.
The type system is what makes it so powerful. *)
@@ -320,7 +320,7 @@ let is_one = function
;;
(* Matching predicates, aka "guarded pattern matching". *)
-let abs x =
+let abs x =
match x with
| x when x < 0 -> -x
| _ -> x
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 8d425f7d..63c0830a 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -7,11 +7,11 @@ contributors:
- ["Nami-Doc", "http://github.com/Nami-Doc"]
---
-Perl 6 is a highly capable, feature-rich programming language made for at
+Perl 6 is a highly capable, feature-rich programming language made for at
least the next hundred years.
The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on
-the JVM and [the MoarVM](http://moarvm.com) and
+the JVM and [the MoarVM](http://moarvm.com) and
[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/),
[the Parrot VM](http://parrot.org/).
@@ -143,7 +143,7 @@ sub with-mandatory-named(:$str!) {
say "$str !";
}
with-mandatory-named(str => "My String"); #=> My String !
-with-mandatory-named; # run time error: "Required named parameter not passed"
+with-mandatory-named; # run time error: "Required named parameter not passed"
with-mandatory-named(3); # run time error: "Too many positional parameters passed"
## If a sub takes a named boolean argument ...
@@ -290,7 +290,7 @@ for @array -> $variable {
# That means you can use `when` in a `for` just like you were in a `given`.
for @array {
say "I've got $_";
-
+
.say; # This is also allowed.
# A dot call with no "topic" (receiver) is sent to `$_` by default
$_.say; # the above and this are equivalent.
@@ -378,8 +378,8 @@ say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
-# You can use that in most places you'd expect, even assigning to an array
-my @numbers = ^20;
+# You can use that in most places you'd expect, even assigning to an array
+my @numbers = ^20;
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99
@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite,
# only the 15 needed values will be calculated.
@@ -634,14 +634,14 @@ class A {
method get-value {
$.field + $!private-field;
}
-
+
method set-value($n) {
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
$!field = $n; # This works, because `$!` is always mutable.
-
+
$.other-field = 5; # This works, because `$.other-field` is `rw`.
}
-
+
method !private-method {
say "This method is private to the class !";
}
@@ -660,19 +660,19 @@ $a.other-field = 10; # This, however, works, because the public field
class A {
has $.val;
-
+
submethod not-inherited {
say "This method won't be available on B.";
say "This is most useful for BUILD, which we'll see later";
}
-
+
method bar { $.val * 5 }
}
class B is A { # inheritance uses `is`
method foo {
say $.val;
}
-
+
method bar { $.val * 10 } # this shadows A's `bar`
}
@@ -699,20 +699,20 @@ role PrintableVal {
# you "import" a mixin (a "role") with "does":
class Item does PrintableVal {
has $.val;
-
+
# When `does`-ed, a `role` literally "mixes in" the class:
# the methods and fields are put together, which means a class can access
# the private fields/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
-
+
# However, this:
# method print {}
# is ONLY valid when `print` isn't a `multi` with the same dispatch.
# (this means a parent class can shadow a child class's `multi print() {}`,
# but it's an error if a role does)
-
+
# NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
# will be shadowed, since the compiler will consider `ROLE` to be a class.
}
@@ -812,7 +812,7 @@ module Foo::Bar {
say "Can't access me from outside, I'm my !";
}
}
-
+
say ++$n; # lexically-scoped variables are still available
}
say $Foo::Bar::n; #=> 1
@@ -1075,8 +1075,8 @@ say [//] Nil, Any, False, 1, 5; #=> False
# Default value examples:
-say [*] (); #=> 1
-say [+] (); #=> 0
+say [*] (); #=> 1
+say [+] (); #=> 0
# meaningless values, since N*1=N and N+0=N.
say [//]; #=> (Any)
# There's no "default value" for `//`.
@@ -1335,7 +1335,7 @@ sub MAIN($name) { say "Hello, $name !" }
# This produces:
# $ perl6 cli.pl
# Usage:
-# t.pl
+# t.pl
# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
# (using a "Bool" for the named argument so that we can do `--replace`
@@ -1348,7 +1348,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
# This produces:
# $ perl 6 cli.pl
# Usage:
-# t.pl [--replace] add
+# t.pl [--replace] add
# t.pl remove
# t.pl [--as=] import (File)
# As you can see, this is *very* powerful.
@@ -1400,7 +1400,7 @@ for {
# (explained in details below).
.say
}
-
+
if rand == 0 ff rand == 1 { # compare variables other than `$_`
say "This ... probably will never run ...";
}
diff --git a/php.html.markdown b/php.html.markdown
index 93066284..2b1fe1dc 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -515,7 +515,7 @@ class MyClass
}
}
-// Class constants can always be accessed statically
+// Class constants can always be accessed statically
echo MyClass::MY_CONST; // Outputs 'value';
echo MyClass::$staticVar; // Outputs 'static';
diff --git a/purescript.html.markdown b/purescript.html.markdown
index 6bff7545..a006cdff 100644
--- a/purescript.html.markdown
+++ b/purescript.html.markdown
@@ -70,12 +70,12 @@ true && (9 >= 19 || 1 < 2) -- true
-- Safe access return Maybe a
head [1,2,3] -- Just (1)
-tail [3,2,1] -- Just ([2,1])
+tail [3,2,1] -- Just ([2,1])
init [1,2,3] -- Just ([1,2])
last [3,2,1] -- Just (1)
-- Random access - indexing
[3,4,5,6,7] !! 2 -- Just (5)
--- Range
+-- Range
1..5 -- [1,2,3,4,5]
length [2,2,2] -- 3
drop 3 [5,4,3,2,1] -- [2,1]
@@ -129,10 +129,10 @@ first :: [Number] -> Number
first (x:_) = x
first [3,4,5] -- 3
second :: [Number] -> Number
-second (_:y:_) = y
+second (_:y:_) = y
second [3,4,5] -- 4
sumTwo :: [Number] -> [Number]
-sumTwo (x:y:rest) = (x+y) : rest
+sumTwo (x:y:rest) = (x+y) : rest
sumTwo [2,3,4,5,6] -- [5,4,5,6]
-- sumTwo doesn't handle when the array is empty or just have one
@@ -161,7 +161,7 @@ ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
-- Lambda expressions
(\x -> x*x) 3 -- 9
-(\x y -> x*x + y*y) 4 5 -- 41
+(\x y -> x*x + y*y) 4 5 -- 41
sqr = \x -> x*x
-- Currying
@@ -187,7 +187,7 @@ foldr (+) 0 (1..10) -- 55
sum (1..10) -- 55
product (1..10) -- 3628800
--- Testing with predicate
+-- Testing with predicate
any even [1,2,3] -- true
all even [1,2,3] -- false
diff --git a/python3.html.markdown b/python3.html.markdown
index 971ca0a4..acd6187c 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -96,7 +96,7 @@ False or True #=> True
1 < 2 < 3 # => True
2 < 3 < 2 # => False
-# (is vs. ==) is checks if two variable refer to the same object, but == checks
+# (is vs. ==) is checks if two variable refer to the same object, but == checks
# if the objects pointed to have the same values.
a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
b = a # Point b at what a is pointing to
@@ -256,8 +256,8 @@ empty_dict = {}
# Here is a prefilled dictionary
filled_dict = {"one": 1, "two": 2, "three": 3}
-# Note keys for dictionaries have to be immutable types. This is to ensure that
-# the key can be converted to a constant hash value for quick look-ups.
+# Note keys for dictionaries have to be immutable types. This is to ensure that
+# the key can be converted to a constant hash value for quick look-ups.
# Immutable types include ints, floats, strings, tuples.
invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
@@ -423,7 +423,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
-
+
# Instead of try/finally to cleanup resources you can use a with statement
with open("myfile.txt") as f:
for line in f:
diff --git a/r.html.markdown b/r.html.markdown
index d3d725d3..93751df5 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -36,8 +36,8 @@ head(rivers) # peek at the data set
length(rivers) # how many rivers were measured?
# 141
summary(rivers) # what are some summary statistics?
-# Min. 1st Qu. Median Mean 3rd Qu. Max.
-# 135.0 310.0 425.0 591.2 680.0 3710.0
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
# make a stem-and-leaf plot (a histogram-like data visualization)
stem(rivers)
@@ -54,14 +54,14 @@ stem(rivers)
# 14 | 56
# 16 | 7
# 18 | 9
-# 20 |
+# 20 |
# 22 | 25
# 24 | 3
-# 26 |
-# 28 |
-# 30 |
-# 32 |
-# 34 |
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
# 36 | 1
stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
@@ -70,7 +70,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# The decimal point is 1 digit(s) to the left of the |
#
# 48 | 1
-# 50 |
+# 50 |
# 52 | 15578
# 54 | 44571222466689
# 56 | 023334677000124455789
@@ -85,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 74 | 84
# 76 | 56
# 78 | 4
-# 80 |
+# 80 |
# 82 | 2
# make a histogram:
@@ -108,7 +108,7 @@ sort(discoveries)
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
stem(discoveries, scale=2)
-#
+#
# The decimal point is at the |
#
# 0 | 000000000
@@ -122,14 +122,14 @@ stem(discoveries, scale=2)
# 8 | 0
# 9 | 0
# 10 | 0
-# 11 |
+# 11 |
# 12 | 0
max(discoveries)
# 12
summary(discoveries)
-# Min. 1st Qu. Median Mean 3rd Qu. Max.
-# 0.0 2.0 3.0 3.1 4.0 12.0
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
round(runif(7, min=.5, max=6.5))
@@ -262,7 +262,7 @@ class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
parakeet
# =>
-# [1] "beak" "feathers" "wings" "eyes"
+# [1] "beak" "feathers" "wings" "eyes"
parakeet <- NULL
parakeet
# =>
@@ -279,7 +279,7 @@ as.numeric("Bilbo")
# =>
# [1] NA
# Warning message:
-# NAs introduced by coercion
+# NAs introduced by coercion
# Also note: those were just the basic data types
# There are many more data types, such as for dates, time series, etc.
@@ -419,10 +419,10 @@ mat %*% t(mat)
mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
mat2
# =>
-# [,1] [,2]
-# [1,] "1" "dog"
-# [2,] "2" "cat"
-# [3,] "3" "bird"
+# [,1] [,2]
+# [1,] "1" "dog"
+# [2,] "2" "cat"
+# [3,] "3" "bird"
# [4,] "4" "dog"
class(mat2) # matrix
# Again, note what happened!
diff --git a/racket.html.markdown b/racket.html.markdown
index e345db8b..0fe3f030 100644
--- a/racket.html.markdown
+++ b/racket.html.markdown
@@ -285,7 +285,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(= 3 3.0) ; => #t
(= 2 1) ; => #f
-;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
+;; `eq?' returns #t if 2 arguments refer to the same object (in memory),
;; #f otherwise.
;; In other words, it's a simple pointer comparison.
(eq? '() '()) ; => #t, since there exists only one empty list in memory
@@ -320,7 +320,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f
;; `equal?' supports the comparison of the following datatypes:
-;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
+;; strings, byte strings, pairs, mutable pairs, vectors, boxes,
;; hash tables, and inspectable structures.
;; for other datatypes, `equal?' and `eqv?' return the same result.
(equal? 3 3.0) ; => #f
diff --git a/red.html.markdown b/red.html.markdown
index f33060c4..05da3c3f 100644
--- a/red.html.markdown
+++ b/red.html.markdown
@@ -8,31 +8,31 @@ contributors:
---
-Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
+Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks.
It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language.
Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in.
-Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
-Red/System, covers the more basic needs of programming like C can, being closer to the metal.
+Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon,
+Red/System, covers the more basic needs of programming like C can, being closer to the metal.
-Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
-from the metal to the meta without the aid of other stack tools.
-Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
+Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level
+from the metal to the meta without the aid of other stack tools.
+Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain
from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB.
Ready to learn your first Red?
```
-All text before the header will be treated as comment, as long as you avoid using the
-word "red" starting with a capital "R" in this pre-header text. This is a temporary
-shortcoming of the used lexer but most of the time you start your script or program
-with the header itself.
-The header of a red script is the capitalized word "red" followed by a
+All text before the header will be treated as comment, as long as you avoid using the
+word "red" starting with a capital "R" in this pre-header text. This is a temporary
+shortcoming of the used lexer but most of the time you start your script or program
+with the header itself.
+The header of a red script is the capitalized word "red" followed by a
whitespace character followed by a block of square brackets [].
-The block of brackets can be filled with useful information about this script or
+The block of brackets can be filled with useful information about this script or
program: the author's name, the filename, the version, the license, a summary of
what the program does or any other files it needs.
-The red/System header is just like the red header, only saying "red/System" and
+The red/System header is just like the red header, only saying "red/System" and
not "red".
Red []
@@ -49,21 +49,21 @@ comment {
; Your program's entry point is the first executable code that is found
; no need to restrict this to a 'main' function.
-; Valid variable names start with a letter and can contain numbers,
-; variables containing only capital A thru F and numbers and ending with 'h' are
-; forbidden, because that is how hexadecimal numbers are expressed in Red and
+; Valid variable names start with a letter and can contain numbers,
+; variables containing only capital A thru F and numbers and ending with 'h' are
+; forbidden, because that is how hexadecimal numbers are expressed in Red and
; Red/System.
; assign a value to a variable using a colon ":"
my-name: "Red"
-reason-for-using-the-colon: {Assigning values using the colon makes
- the equality sign "=" exclusively usable for comparisons purposes,
- exactly what "=" was intended for in the first place!
+reason-for-using-the-colon: {Assigning values using the colon makes
+ the equality sign "=" exclusively usable for comparisons purposes,
+ exactly what "=" was intended for in the first place!
Remember this y = x + 1 and x = 1 => y = 2 stuff from school?
}
is-this-name-valid?: true
-; print output using print, or prin for printing without a newline or linefeed at the
+; print output using print, or prin for printing without a newline or linefeed at the
; end of the printed text.
prin " My name is " print my-name
@@ -77,20 +77,20 @@ My name is Red
;
; Datatypes
;
-; If you know Rebol, you probably have noticed it has lots of datatypes. Red
-; does not have yet all those types, but as Red want to be close to Rebol it
+; If you know Rebol, you probably have noticed it has lots of datatypes. Red
+; does not have yet all those types, but as Red want to be close to Rebol it
; will have a lot of datatypes.
-; You can recognize types by the exclamation sign at the end. But beware
-; names ending with an exclamation sign are allowed.
-; Some of the available types are integer! string! block!
-
-; Declaring variables before using them?
-; Red knows by itself what variable is best to use for the data you want to use it
-; for.
-; A variable declaration is not always necessary.
+; You can recognize types by the exclamation sign at the end. But beware
+; names ending with an exclamation sign are allowed.
+; Some of the available types are integer! string! block!
+
+; Declaring variables before using them?
+; Red knows by itself what variable is best to use for the data you want to use it
+; for.
+; A variable declaration is not always necessary.
; It is considered good coding practise to declare your variables,
; but it is not forced upon you by Red.
-; You can declare a variable and specify its type. a variable's type determines its
+; You can declare a variable and specify its type. a variable's type determines its
; size in bytes.
; Variables of integer! type are usually 4 bytes or 32 bits
@@ -101,7 +101,7 @@ my-integer: 0
type? my-integer
integer!
-; A variable can be initialized using another variable that gets initialized
+; A variable can be initialized using another variable that gets initialized
; at the same time.
i2: 1 + i1: 1
@@ -111,9 +111,9 @@ i2 - i1 ; result 1
i2 * i1 ; result 2
i1 / i2 ; result 0 (0.5, but truncated towards 0)
-; Comparison operators are probably familiar, and unlike in other languages you
+; Comparison operators are probably familiar, and unlike in other languages you
; only need a single '=' sign for comparison.
-; There is a boolean like type in Red. It has values true and false, but also the
+; There is a boolean like type in Red. It has values true and false, but also the
; values on/off or yes/no can be used
3 = 2 ; result false
@@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0)
;
; Control Structures
-;
+;
; if
-; Evaluate a block of code if a given condition is true. IF does not return any value,
+; Evaluate a block of code if a given condition is true. IF does not return any value,
; so cannot be used in an expression.
if a < 0 [print "a is negative"]
; either
-; Evaluate a block of code if a given condition is true, else evaluate an alternative
-; block of code. If the last expressions in both blocks have the same type, EITHER can
+; Evaluate a block of code if a given condition is true, else evaluate an alternative
+; block of code. If the last expressions in both blocks have the same type, EITHER can
; be used inside an expression.
either a < 0 [
either a = 0 [
@@ -147,7 +147,7 @@ either a < 0 [
print ["a is " msg lf]
-; There is an alternative way to write this
+; There is an alternative way to write this
; (Which is allowed because all code paths return a value of the same type):
msg: either a < 0 [
@@ -162,7 +162,7 @@ msg: either a < 0 [
print ["a is " msg lf]
; until
-; Loop over a block of code until the condition at end of block, is met.
+; Loop over a block of code until the condition at end of block, is met.
; UNTIL does not return any value, so it cannot be used in an expression.
c: 5
until [
@@ -172,11 +172,11 @@ until [
]
; will output:
ooooo
-; Note that the loop will always be evaluated at least once, even if the condition is
+; Note that the loop will always be evaluated at least once, even if the condition is
; not met from the beginning.
; while
-; While a given condition is met, evaluate a block of code.
+; While a given condition is met, evaluate a block of code.
; WHILE does not return any value, so it cannot be used in an expression.
c: 5
while [c > 0][
@@ -206,7 +206,7 @@ print twice b ; will output 6.
## Further Reading
-The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
+The main source for information about Red is the [Red language homepage](http://www.red-lang.org).
The source can be found on [github](https://github.com/red/red).
@@ -218,4 +218,4 @@ Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/r
Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl).
-You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
+You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html).
diff --git a/rust.html.markdown b/rust.html.markdown
index 3157fcf4..b2854b0c 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -6,20 +6,20 @@ filename: learnrust.rs
---
Rust is a programming language developed by Mozilla Research.
-Rust combines low-level control over performance with high-level convenience and
-safety guarantees.
+Rust combines low-level control over performance with high-level convenience and
+safety guarantees.
-It achieves these goals without requiring a garbage collector or runtime, making
+It achieves these goals without requiring a garbage collector or runtime, making
it possible to use Rust libraries as a "drop-in replacement" for C.
-Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
+Rust’s first release, 0.1, occurred in January 2012, and for 3 years development
moved so quickly that until recently the use of stable releases was discouraged
-and instead the general advice was to use nightly builds.
+and instead the general advice was to use nightly builds.
-On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
+On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward
compatibility. Improvements to compile times and other aspects of the compiler are
currently available in the nightly builds. Rust has adopted a train-based release
-model with regular releases every six weeks. Rust 1.1 beta was made available at
+model with regular releases every six weeks. Rust 1.1 beta was made available at
the same time of the release of Rust 1.0.
Although Rust is a relatively low-level language, Rust has some functional
diff --git a/self.html.markdown b/self.html.markdown
index 69524a84..9290a0c9 100644
--- a/self.html.markdown
+++ b/self.html.markdown
@@ -5,13 +5,13 @@ contributors:
filename: learnself.self
---
-Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
+Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots.
# Constructing objects
-The inbuild Self parser can construct objects, including method objects.
+The inbuild Self parser can construct objects, including method objects.
```
"This is a comment"
@@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects.
x <- 20.
|)
-"An object which understands the method 'doubleX' which
+"An object which understands the method 'doubleX' which
doubles the value of x and then returns the object"
(|
x <- 20.
doubleX = (x: x * 2. self)
|)
-"An object which understands all the messages
-that 'traits point' understands". The parser
-looks up 'traits point' by sending the messages
-'traits' then 'point' to a known object called
-the 'lobby'. It looks up the 'true' object by
+"An object which understands all the messages
+that 'traits point' understands". The parser
+looks up 'traits point' by sending the messages
+'traits' then 'point' to a known object called
+the 'lobby'. It looks up the 'true' object by
also sending the message 'true' to the lobby."
(| parent* = traits point.
x = 7.
@@ -63,19 +63,19 @@ also sending the message 'true' to the lobby."
Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
```
-"unary message, sends 'printLine' to the object '23'
+"unary message, sends 'printLine' to the object '23'
which prints the string '23' to stdout and returns the receiving object (ie 23)"
23 printLine
"sends the message '+' with '7' to '23', then the message '*' with '8' to the result"
-(23 + 7) * 8
+(23 + 7) * 8
"sends 'power:' to '2' with '8' returns 256"
-2 power: 8
+2 power: 8
-"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
+"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
Returns 1, the index of 'e' in 'hello'."
-'hello' keyOf: 'e' IfAbsent: -1
+'hello' keyOf: 'e' IfAbsent: -1
```
# Blocks
@@ -90,13 +90,13 @@ Examples of the use of a block:
```
"returns 'HELLO'"
-'hello' copyMutable mapBy: [|:c| c capitalize]
+'hello' copyMutable mapBy: [|:c| c capitalize]
"returns 'Nah'"
-'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
+'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
"returns 'HaLLO'"
-'hello' copyMutable mapBy: [|:c|
+'hello' copyMutable mapBy: [|:c|
c = 'e' ifTrue: [c capitalize]
False: ['a']]
```
@@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately.
```
"returns An 'E'! How icky!"
-'hello' copyMutable mapBy: [|:c. tmp <- ''|
+'hello' copyMutable mapBy: [|:c. tmp <- ''|
tmp: c capitalize.
tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
c capitalize
@@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t
x: 15.
"Repeatedly sends 'value' to the first block while the result of sending 'value' to the
second block is the 'true' object"
- [x > 0] whileTrue: [x: x - 1].
+ [x > 0] whileTrue: [x: x - 1].
x
] value
```
@@ -130,12 +130,12 @@ Methods are like blocks but they are not within a context but instead are stored
```
"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'.
-Sending the message 'reduceXTo: 10' to this object will put
+Sending the message 'reduceXTo: 10' to this object will put
the object '10' in the 'x' slot and return the original object"
-(|
+(|
x <- 50.
reduceXTo: y = (
- [x > y] whileTrue: [x: x - 1].
+ [x > y] whileTrue: [x: x - 1].
self)
|)
.
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index a434a1ad..3b388505 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -11,28 +11,28 @@ contributors:
Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`.
-##Allowable characters:
-- a-z
-- A-Z
-- 0-9
+##Allowable characters:
+- a-z
+- A-Z
+- 0-9
- .+/\*~<>@%|&?
- blank, tab, cr, ff, lf
##Variables:
-- variables must be declared before use
-- shared vars must begin with uppercase
-- local vars must begin with lowercase
+- variables must be declared before use
+- shared vars must begin with uppercase
+- local vars must begin with lowercase
- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk`
-##Variable scope:
-- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
-- Method Temporary: local to a method
-- Block Temporary: local to a block
-- Pool: variables in a Dictionary object
+##Variable scope:
+- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil`
+- Method Temporary: local to a method
+- Block Temporary: local to a block
+- Pool: variables in a Dictionary object
- Method Parameters: automatic local vars created as a result of message call with params
- Block Parameters: automatic local vars created as a result of value: message call
-- Class: shared with all instances of one class & its subclasses
-- Class Instance: unique to each instance of a class
+- Class: shared with all instances of one class & its subclasses
+- Class Instance: unique to each instance of a class
- Instance Variables: unique to each instance
`"Comments are enclosed in quotes"`
@@ -53,7 +53,7 @@ Transcript cr. "carriage return / l
Transcript endEntry. "flush the output buffer"
```
-##Assignment:
+##Assignment:
```
| x y |
x _ 4. "assignment (Squeak) <-"
@@ -72,7 +72,7 @@ y := x deepCopy. "copy object and ins
y := x veryDeepCopy. "complete tree copy using a dictionary"
```
-##Constants:
+##Constants:
```
| b |
b := true. "true constant"
@@ -93,7 +93,7 @@ x := #('abc' 2 $a). "mixing of types all
```
-## Booleans:
+## Booleans:
```
| b x y |
x := 1. y := 2.
@@ -132,7 +132,7 @@ b := $A isLowercase. "test if lower case
```
-## Arithmetic expressions:
+## Arithmetic expressions:
```
| x |
x := 6 + 3. "addition"
@@ -190,7 +190,7 @@ x := 100 atRandom. "quick random number
```
-##Bitwise Manipulation:
+##Bitwise Manipulation:
```
| b x |
x := 16rFF bitAnd: 16r0F. "and bits"
@@ -207,7 +207,7 @@ b := 16rFF noMask: 16r0F. "test if all bits se
```
-## Conversion:
+## Conversion:
```
| x |
x := 3.99 asInteger. "convert number to integer (truncates in Squeak)"
@@ -223,15 +223,15 @@ x := 15 storeStringBase: 16.
```
-## Blocks:
-- blocks are objects and may be assigned to a variable
-- value is last expression evaluated unless explicit return
-- blocks may be nested
-- specification [ arguments | | localvars | expressions ]
-- Squeak does not currently support localvars in blocks
-- max of three arguments allowed
-- `^`expression terminates block & method (exits all nested blocks)
-- blocks intended for long term storage should not contain `^`
+## Blocks:
+- blocks are objects and may be assigned to a variable
+- value is last expression evaluated unless explicit return
+- blocks may be nested
+- specification [ arguments | | localvars | expressions ]
+- Squeak does not currently support localvars in blocks
+- max of three arguments allowed
+- `^`expression terminates block & method (exits all nested blocks)
+- blocks intended for long term storage should not contain `^`
```
| x y z |
@@ -241,18 +241,18 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu
"x := [ | z | z := 1.]. *** localvars not available in squeak blocks"
```
-## Method calls:
-- unary methods are messages with no arguments
-- binary methods
-- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
-- accessing (get/set methods)
-- testing (boolean tests - is)
-- comparing (boolean tests with parameter
-- displaying (gui related methods)
-- printing (methods for printing)
-- updating (receive notification of changes)
-- private (methods private to class)
-- instance-creation (class methods for creating instance)
+## Method calls:
+- unary methods are messages with no arguments
+- binary methods
+- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance)
+- accessing (get/set methods)
+- testing (boolean tests - is)
+- comparing (boolean tests with parameter
+- displaying (gui related methods)
+- printing (methods for printing)
+- updating (receive notification of changes)
+- private (methods private to class)
+- instance-creation (class methods for creating instance)
```
| x |
x := 2 sqrt. "unary message"
@@ -299,7 +299,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr].
result := (switch at: $B) value.
```
-## Iteration statements:
+## Iteration statements:
```
| x y |
x := 4. y := 1.
@@ -311,7 +311,7 @@ x timesRepeat: [y := y * 2]. "times repear loop (
#(5 4 3) do: [:a | x := x + a]. "iterate over array elements"
```
-## Character:
+## Character:
```
| x y |
x := $A. "character assignment"
@@ -544,7 +544,7 @@ y := x asSet. "convert to set coll
```
## Set: like Bag except duplicates not allowed
-## IdentitySet: uses identity test (== rather than =)
+## IdentitySet: uses identity test (== rather than =)
```
| b x y sum max |
x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements"
@@ -603,7 +603,7 @@ y := x asBag. "convert to bag coll
y := x asSet. "convert to set collection"
```
-##Associations:
+##Associations:
```
| x y |
x := #myVar->'hello'.
diff --git a/swift.html.markdown b/swift.html.markdown
index 86a0b89a..a40e86c8 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -3,7 +3,7 @@ language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
- ["Christopher Bess", "http://github.com/cbess"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
filename: learnswift.swift
---
@@ -74,7 +74,7 @@ if someOptionalString != nil {
if someOptionalString!.hasPrefix("opt") {
print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
@@ -99,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
Comment here
-
+
/*
Nested comments are also supported
*/
@@ -298,7 +298,7 @@ print(numbers) // [3, 6, 18]
// Structures and classes have very similar capabilites
struct NamesTable {
let names = [String]()
-
+
// Custom subscript
subscript(index: Int) -> String {
return names[index]
@@ -329,7 +329,7 @@ public class Shape {
internal class Rect: Shape {
var sideLength: Int = 1
-
+
// Custom getter and setter property
private var perimeter: Int {
get {
@@ -340,11 +340,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// Lazily load a property
// subShape remains nil (uninitialized) until getter called
lazy var subShape = Rect(sideLength: 4)
-
+
// If you don't need a custom getter and setter,
// but still want to run code before and after getting or setting
// a property, you can use `willSet` and `didSet`
@@ -354,19 +354,19 @@ internal class Rect: Shape {
print(someIdentifier)
}
}
-
+
init(sideLength: Int) {
self.sideLength = sideLength
// always super.init last when init custom properties
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
override func getArea() -> Int {
return sideLength * sideLength
}
@@ -398,13 +398,13 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// Place a question mark postfix after `init` is an optional init
// which can return nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -458,7 +458,7 @@ enum Furniture {
case Desk(height: Int)
// Associate with String and Int
case Chair(String, Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -497,7 +497,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -532,7 +532,7 @@ extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
diff --git a/tcl.html.markdown b/tcl.html.markdown
index 3982807f..b90bd690 100644
--- a/tcl.html.markdown
+++ b/tcl.html.markdown
@@ -14,7 +14,7 @@ programming language. It can also be used as a portable C library, even in
cases where no scripting capability is needed, as it provides data structures
such as dynamic strings, lists, and hash tables. The C library also provides
portable functionality for loading dynamic libraries, string formatting and
-code conversion, filesystem operations, network operations, and more.
+code conversion, filesystem operations, network operations, and more.
Various features of Tcl stand out:
* Convenient cross-platform networking API
@@ -58,14 +58,14 @@ lighter that that of Lisp, just gets out of the way.
#! /bin/env tclsh
################################################################################
-## 1. Guidelines
+## 1. Guidelines
################################################################################
# Tcl is not Bash or C! This needs to be said because standard shell quoting
# habits almost work in Tcl and it is common for people to pick up Tcl and try
# to get by with syntax they know from another language. It works at first,
# but soon leads to frustration with more complex scripts.
-
+
# Braces are just a quoting mechanism, not a code block constructor or a list
# constructor. Tcl doesn't have either of those things. Braces are used,
# though, to escape special characters in procedure bodies and in strings that
@@ -73,7 +73,7 @@ lighter that that of Lisp, just gets out of the way.
################################################################################
-## 2. Syntax
+## 2. Syntax
################################################################################
# Every line is a command. The first word is the name of the command, and
@@ -83,13 +83,13 @@ lighter that that of Lisp, just gets out of the way.
# are used, they are not a string constructor, but just another escaping
# character.
-set greeting1 Sal
+set greeting1 Sal
set greeting2 ut
set greeting3 ations
#semicolon also delimits commands
-set greeting1 Sal; set greeting2 ut; set greeting3 ations
+set greeting1 Sal; set greeting2 ut; set greeting3 ations
# Dollar sign introduces variable substitution
@@ -126,11 +126,11 @@ puts lots\nof\n\n\n\n\n\nnewlines
set somevar {
This is a literal $ sign, and this \} escaped
brace remains uninterpreted
-}
+}
# In a word enclosed in double quotes, whitespace characters lose their special
-# meaning
+# meaning
set name Neo
set greeting "Hello, $name"
@@ -178,7 +178,7 @@ set greeting "Hello $people::person1::name"
################################################################################
-## 3. A Few Notes
+## 3. A Few Notes
################################################################################
# All other functionality is implemented via commands. From this point on,
@@ -193,8 +193,8 @@ set greeting "Hello $people::person1::name"
namespace delete ::
-# Because of name resolution behaviour, it's safer to use the "variable" command to
-# declare or to assign a value to a namespace. If a variable called "name" already
+# Because of name resolution behaviour, it's safer to use the "variable" command to
+# declare or to assign a value to a namespace. If a variable called "name" already
# exists in the global namespace, using "set" here will assign a value to the global variable
# instead of creating a new variable in the local namespace.
namespace eval people {
@@ -210,7 +210,7 @@ set people::person1::name Neo
################################################################################
-## 4. Commands
+## 4. Commands
################################################################################
# Math can be done with the "expr" command.
@@ -295,7 +295,7 @@ while {$i < 10} {
# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values
-set amounts 10\ 33\ 18
+set amounts 10\ 33\ 18
set amount [lindex $amounts 1]
@@ -339,7 +339,7 @@ eval {set name Neo}
eval [list set greeting "Hello, $name"]
-# Therefore, when using "eval", use [list] to build up a desired command
+# Therefore, when using "eval", use [list] to build up a desired command
set command {set name}
lappend command {Archibald Sorbisol}
eval $command
@@ -355,7 +355,7 @@ eval $command ;# There is an error here, because there are too many arguments \
# This mistake can easily occur with the "subst" command.
set replacement {Archibald Sorbisol}
set command {set name $replacement}
-set command [subst $command]
+set command [subst $command]
eval $command ;# The same error as before: too many arguments to "set" in \
{set name Archibald Sorbisol}
@@ -364,12 +364,12 @@ eval $command ;# The same error as before: too many arguments to "set" in \
# command.
set replacement [list {Archibald Sorbisol}]
set command {set name $replacement}
-set command [subst $command]
+set command [subst $command]
eval $command
# It is extremely common to see the "list" command being used to properly
-# format values that are substituted into Tcl script templates. There are
+# format values that are substituted into Tcl script templates. There are
# several examples of this, below.
@@ -422,12 +422,12 @@ proc while {condition script} {
# The "coroutine" command creates a separate call stack, along with a command
# to enter that call stack. The "yield" command suspends execution in that
-# stack.
+# stack.
proc countdown {} {
#send something back to the initial "coroutine" command
yield
- set count 3
+ set count 3
while {$count > 1} {
yield [incr count -1]
}
@@ -435,12 +435,12 @@ proc countdown {} {
}
coroutine countdown1 countdown
coroutine countdown2 countdown
-puts [countdown 1] ;# -> 2
-puts [countdown 2] ;# -> 2
-puts [countdown 1] ;# -> 1
-puts [countdown 1] ;# -> 0
+puts [countdown 1] ;# -> 2
+puts [countdown 2] ;# -> 2
+puts [countdown 1] ;# -> 1
+puts [countdown 1] ;# -> 0
puts [coundown 1] ;# -> invalid command name "countdown1"
-puts [countdown 2] ;# -> 1
+puts [countdown 2] ;# -> 1
```
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index f9906e96..bdfdcc10 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -17,7 +17,7 @@ Module Module1
' This navigation system is explained however as we go deeper into this
' tutorial, you'll understand what it all means.
Console.Title = ("Learn X in Y Minutes")
- Console.WriteLine("NAVIGATION") 'Display
+ Console.WriteLine("NAVIGATION") 'Display
Console.WriteLine("")
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine("1. Hello World Output")
@@ -39,13 +39,13 @@ Module Module1
Case "2" 'Hello Input
Console.Clear()
HelloWorldInput()
- Case "3" 'Calculating Whole Numbers
+ Case "3" 'Calculating Whole Numbers
Console.Clear()
CalculatingWholeNumbers()
- Case "4" 'Calculting Decimal Numbers
+ Case "4" 'Calculting Decimal Numbers
Console.Clear()
CalculatingDecimalNumbers()
- Case "5" 'Working Calcculator
+ Case "5" 'Working Calcculator
Console.Clear()
WorkingCalculator()
Case "6" 'Using Do While Loops
@@ -74,7 +74,7 @@ Module Module1
'One - I'm using numbers to help with the above navigation when I come back
'later to build it.
- 'We use private subs to seperate different sections of the program.
+ 'We use private subs to seperate different sections of the program.
Private Sub HelloWorldOutput()
'Title of Console Application
Console.Title = "Hello World Ouput | Learn X in Y Minutes"
@@ -172,7 +172,7 @@ Module Module1
'program more than once.
Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes"
Dim answer As String 'We use the variable "String" as the answer is text
- Do 'We start the program with
+ Do 'We start the program with
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
Console.Write("Second number: ")
@@ -192,7 +192,7 @@ Module Module1
Console.WriteLine(" = " + f.ToString.PadLeft(3))
Console.ReadLine()
'Ask the question, does the user wish to continue? Unfortunately it
- 'is case sensitive.
+ 'is case sensitive.
Console.Write("Would you like to continue? (yes / no)")
'The program grabs the variable and prints and starts again.
answer = Console.ReadLine
@@ -208,8 +208,8 @@ Module Module1
Console.Title = "Using For Loops | Learn X in Y Minutes"
'Declare Variable and what number it should count down in Step -1,
- 'Step -2, Step -3 ect.
- For i As Integer = 10 To 0 Step -1
+ 'Step -2, Step -3 ect.
+ For i As Integer = 10 To 0 Step -1
Console.WriteLine(i.ToString) 'Print the value of the counter
Next i 'Calculate new value
Console.WriteLine("Start") 'Lets start the program baby!!
@@ -274,8 +274,8 @@ End Module
## References
-I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
+I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily.
-I created a more indepth Visual Basic tutorial for those who would like to learn more.
+I created a more indepth Visual Basic tutorial for those who would like to learn more.
-The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
+The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program.
diff --git a/xml.html.markdown b/xml.html.markdown
index 059ea132..d407512d 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -38,10 +38,10 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
@@ -54,8 +54,8 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
2 - Elements -> That's pure data.
That's what the parser will retrieve from the XML file.
Elements appear between the open and close tags. -->
-
-
+
+
computer.gif
@@ -68,14 +68,14 @@ A XML document is well-formated if it is syntactically correct.
However, it is possible to inject more constraints in the document,
using document definitions, such as DTD and XML Schema.
-A XML document which follows a document definition is called valid,
-regarding that document.
+A XML document which follows a document definition is called valid,
+regarding that document.
With this tool, you can check the XML data outside the application logic.
```xml
-
--
cgit v1.2.3
From e1ac6209a8d3f43e7a018d79454fb1095b3314c0 Mon Sep 17 00:00:00 2001
From: Zachary Ferguson
Date: Wed, 7 Oct 2015 23:45:01 -0400
Subject: [c/en] Added a section for header files.
Added a section for header files.
Included a discussion of what belongs in a header file and what does
not.
---
c.html.markdown | 50 +++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 49 insertions(+), 1 deletion(-)
diff --git a/c.html.markdown b/c.html.markdown
index db2ac930..f1201eac 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -6,7 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
-
+ - ["Zachary Ferguson", "https://github.io/zfergus2"]
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -630,6 +630,54 @@ typedef void (*my_fnp_type)(char *);
```
+Header files are an important part of c as they allow for the connection of c
+source files and can simplify code and definitions by seperating them into
+seperate files.
+
+Header files are syntaxtically similar to c source files but reside in ".h"
+files. They can be included in your c source file by using the precompiler
+command #include "example.h", given that example.h exists in the same directory
+as the c file.
+
+```c
+/* A safe guard to prevent the header from being defined too many times. This */
+/* happens in the case of circle dependency, the contents of the header is */
+/* already defined. */
+#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
+#define EXAMPLE_H /* Define the macro EXAMPLE_H. */
+
+/* Other headers can be included in headers and therefore transitively */
+/* included into files that include this header. */
+#include
+
+/* Like c source files macros can be defined in headers and used in files */
+/* that include this header file. */
+#define EXAMPLE_NAME "Dennis Ritchie"
+/* Function macros can also be defined. */
+#define ADD(a, b) (a + b)
+
+/* Structs and typedefs can be used for consistency between files. */
+typedef struct node
+{
+ int val;
+ struct node *next;
+} Node;
+
+/* So can enumerations. */
+enum traffic_light_state {GREEN, YELLOW, RED};
+
+/* Function prototypes can also be defined here for use in multiple files, */
+/* but it is bad practice to define the function in the header. Definitions */
+/* should instead be put in a c file. */
+Node createLinkedList(int *vals, int len);
+
+/* Beyond the above elements, other definitions should be left to a c source */
+/* file. Excessive includeds or definitions should, also not be contained in */
+/* a header file but instead put into separate headers or a c file. */
+
+#endif /* End of the if precompiler directive. */
+
+```
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
--
cgit v1.2.3
From 3c02fdb8e496816b0fd615e029fad4a8ed9f4585 Mon Sep 17 00:00:00 2001
From: Zachary Ferguson
Date: Wed, 7 Oct 2015 23:49:46 -0400
Subject: Revert "[c/en] Added a section for header files."
This reverts commit e1ac6209a8d3f43e7a018d79454fb1095b3314c0.
---
c.html.markdown | 50 +-------------------------------------------------
1 file changed, 1 insertion(+), 49 deletions(-)
diff --git a/c.html.markdown b/c.html.markdown
index f1201eac..db2ac930 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -6,7 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
- - ["Zachary Ferguson", "https://github.io/zfergus2"]
+
---
Ah, C. Still **the** language of modern high-performance computing.
@@ -630,54 +630,6 @@ typedef void (*my_fnp_type)(char *);
```
-Header files are an important part of c as they allow for the connection of c
-source files and can simplify code and definitions by seperating them into
-seperate files.
-
-Header files are syntaxtically similar to c source files but reside in ".h"
-files. They can be included in your c source file by using the precompiler
-command #include "example.h", given that example.h exists in the same directory
-as the c file.
-
-```c
-/* A safe guard to prevent the header from being defined too many times. This */
-/* happens in the case of circle dependency, the contents of the header is */
-/* already defined. */
-#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
-#define EXAMPLE_H /* Define the macro EXAMPLE_H. */
-
-/* Other headers can be included in headers and therefore transitively */
-/* included into files that include this header. */
-#include
-
-/* Like c source files macros can be defined in headers and used in files */
-/* that include this header file. */
-#define EXAMPLE_NAME "Dennis Ritchie"
-/* Function macros can also be defined. */
-#define ADD(a, b) (a + b)
-
-/* Structs and typedefs can be used for consistency between files. */
-typedef struct node
-{
- int val;
- struct node *next;
-} Node;
-
-/* So can enumerations. */
-enum traffic_light_state {GREEN, YELLOW, RED};
-
-/* Function prototypes can also be defined here for use in multiple files, */
-/* but it is bad practice to define the function in the header. Definitions */
-/* should instead be put in a c file. */
-Node createLinkedList(int *vals, int len);
-
-/* Beyond the above elements, other definitions should be left to a c source */
-/* file. Excessive includeds or definitions should, also not be contained in */
-/* a header file but instead put into separate headers or a c file. */
-
-#endif /* End of the if precompiler directive. */
-
-```
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
--
cgit v1.2.3
From 7aca9100a042f3813d383f979f8c32a95ecc4bbb Mon Sep 17 00:00:00 2001
From: Zachary Ferguson
Date: Thu, 8 Oct 2015 00:00:37 -0400
Subject: [java/en] Fixed repitions
---
java.html.markdown | 59 ++----------------------------------------------------
1 file changed, 2 insertions(+), 57 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index 61478968..ba602d2e 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -513,12 +513,8 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
}
}
-<<<<<<< HEAD
-// Abstract Classes
-=======
-
// Abstract Classes
->>>>>>> adambard/master
+
// Abstract Class declaration syntax
// abstract extends {
// // Constants and variables
@@ -535,7 +531,6 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
public abstract class Animal
{
-<<<<<<< HEAD
public abstract void makeSound();
// Method can have a body
@@ -561,38 +556,10 @@ public abstract class Animal
{
System.out.println("I am abstract");
}
-=======
- public abstract void makeSound();
-
- // Method can have a body
- public void eat()
- {
- System.out.println("I am an animal and I am Eating.");
- // Note: We can access private variable here.
- age = 30;
- }
-
- // No need to initialize, however in an interface
- // a variable is implicitly final and hence has
- // to be initialized.
- private int age;
-
- public void printAge()
- {
- System.out.println(age);
- }
-
- // Abstract classes can have main function.
- public static void main(String[] args)
- {
- System.out.println("I am abstract");
- }
->>>>>>> adambard/master
}
class Dog extends Animal
{
-<<<<<<< HEAD
// Note still have to override the abstract methods in the
// abstract class.
@Override
@@ -614,32 +581,10 @@ class Dog extends Animal
pluto.eat();
pluto.printAge();
}
-=======
- // Note still have to override the abstract methods in the
- // abstract class.
- @Override
- public void makeSound()
- {
- System.out.println("Bark");
- // age = 30; ==> ERROR! age is private to Animal
- }
-
- // NOTE: You will get an error if you used the
- // @Override annotation here, since java doesn't allow
- // overriding of static methods.
- // What is happening here is called METHOD HIDING.
- // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
- public static void main(String[] args)
- {
- Dog pluto = new Dog();
- pluto.makeSound();
- pluto.eat();
- pluto.printAge();
- }
->>>>>>> adambard/master
}
// Final Classes
+
// Final Class declaration syntax
// final {
// // Constants and variables
--
cgit v1.2.3
From 707c8db171cb5239682332f14fd2098901741c63 Mon Sep 17 00:00:00 2001
From: Valentine Silvansky
Date: Thu, 8 Oct 2015 10:00:13 +0300
Subject: Add generics operator in Swift
---
swift.html.markdown | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/swift.html.markdown b/swift.html.markdown
index a40e86c8..75535e43 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -574,4 +574,18 @@ print(mySquare.sideLength) // 4
// change side length using custom !!! operator, increases size by 3
!!!mySquare
print(mySquare.sideLength) // 12
+
+// Operators can also be generics
+infix operator <-> {}
+func <-> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
```
--
cgit v1.2.3
From 9796759379d77a848ef84f8c1019672b87b90822 Mon Sep 17 00:00:00 2001
From: himanshu81494
Date: Thu, 8 Oct 2015 14:44:10 +0530
Subject: Update c.html.markdown
---
c.html.markdown | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)
diff --git a/c.html.markdown b/c.html.markdown
index db2ac930..b99cfe84 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -472,7 +472,22 @@ char c[] = "This is a test.";
str_reverse(c);
printf("%s\n", c); // => ".tset a si sihT"
*/
-
+//as we can return return only one variable
+//to change values of more than one variables we use call by reference
+void swapTwoNumbers(int *a, int *b)
+{
+int temp = *a;
+*a = *b;
+*b = temp;
+}
+/*
+int first = 10;
+int second = 20;
+printf("first: %d\nsecond: %d\n", first, second);
+swapTwoNumbers(&first, &second);
+printf("first: %d\nsecond: %d\n", first, second);
+// values will be swapped
+*/
// if referring to external variables outside function, must use extern keyword.
int i = 0;
void testFunc() {
--
cgit v1.2.3
From 626ee03fc3ca27698044db118bd53f563d22ccd0 Mon Sep 17 00:00:00 2001
From: himanshu81494
Date: Thu, 8 Oct 2015 14:45:16 +0530
Subject: Update c.html.markdown
---
c.html.markdown | 1 +
1 file changed, 1 insertion(+)
diff --git a/c.html.markdown b/c.html.markdown
index b99cfe84..8e1675bb 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
- ["Marco Scannadinari", "https://marcoms.github.io"]
+ - ["himanshu", "https://github.com/himanshu81494"]
---
--
cgit v1.2.3
From e8248af13431ca87786fff17a605189c69aacf15 Mon Sep 17 00:00:00 2001
From: himanshu81494
Date: Thu, 8 Oct 2015 15:31:40 +0530
Subject: Update c.html.markdown
---
c.html.markdown | 20 +++++++++++++++++++-
1 file changed, 19 insertions(+), 1 deletion(-)
diff --git a/c.html.markdown b/c.html.markdown
index 8e1675bb..29bc5a5b 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -307,7 +307,25 @@ int main(void) {
exit(-1);
break;
}
-
+
+ // using "goto"
+ typedef enum { false, true } bool;
+ // for C don't have bool as data type :(
+ bool disaster = false;
+ int i, j;
+ for(i=0;i<100;++i)
+ for(j=0;j<100;++j)
+ {
+ if((i + j) >= 150)
+ disaster = true;
+ if(disaster)
+ goto error;
+ }
+ error :
+ printf("Error occured at i = %d & j = %d.\n", i, j);
+ // this will print out "Error occured at i = 52 & j = 99."
+
+
///////////////////////////////////////
// Typecasting
///////////////////////////////////////
--
cgit v1.2.3
From 617599a527a7ee9e3d01a21f11338a1cba3e1eb5 Mon Sep 17 00:00:00 2001
From: himanshu81494
Date: Thu, 8 Oct 2015 15:49:51 +0530
Subject: Update json.html.markdown
---
json.html.markdown | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/json.html.markdown b/json.html.markdown
index 6aff2ce2..f4adfc8b 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -4,6 +4,7 @@ filename: learnjson.json
contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["himanshu", "https://github.com/himanshu81494"]
---
As JSON is an extremely simple data-interchange format, this is most likely going
@@ -13,6 +14,11 @@ JSON in its purest form has no actual comments, but most parsers will accept
C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+Data types supported by JSON includes: numbers, string, boolean, array, object and null.
+Supporting browsers are: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
+JSON file type for JSON files is ".json". The MIME type for JSON text is "application/json"
+Drawbacks of JSON include lack of type definition and some sort of DTD.
+
```json
{
"key": "value",
--
cgit v1.2.3
From b723d3284bbccbcbf5e7ecedee3469b87f4d5959 Mon Sep 17 00:00:00 2001
From: Matteo Taroli
Date: Thu, 8 Oct 2015 12:38:19 +0200
Subject: Add explanation about $_ and fix typos
---
fr-fr/perl-fr.html.markdown | 24 ++++++++++++++++--------
1 file changed, 16 insertions(+), 8 deletions(-)
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
index 7a061da7..e737b7aa 100644
--- a/fr-fr/perl-fr.html.markdown
+++ b/fr-fr/perl-fr.html.markdown
@@ -5,6 +5,7 @@ language: perl
filename: learnperl-fr.pl
contributors:
- ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
translators:
- ["Matteo Taroli", "http://www.matteotaroli.be"]
lang: fr-fr
@@ -27,7 +28,7 @@ est autant adapté à un prototypage rapide qu'à des projets de grande envergur
### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
## Scalaires
-# Un scalaire représente une valeure unique :
+# Un scalaire représente une valeur unique :
my $animal = "chameau";
my $reponse = 42;
@@ -99,8 +100,15 @@ for my $element (@elements) {
# implicitement
+# La variable de contexte scalaire $_ est utilisée par défaut dans différentes
+# situations, comme par exemple dans la boucle foreach ou en argument par défaut
+# de la plupart des fonctions pour en simplifier l'écriture.
+
+# Dans l'exemple suivant, $_ prends successivement la valeur de
+# chaque élément de la liste.
+
for (@elements) {
- print;
+ print; # affiche le contenu de $_
}
@@ -116,11 +124,11 @@ if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
# Simple substitution
-$a =~ s/foo/bar/; # remplace foo par bar dans $a
+$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a
$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
-#### Fichiers and E/S
+#### Fichiers et E/S
# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
@@ -136,9 +144,9 @@ open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
my $ligne = <$in>
my $lignes = <$in>
-#### Ecrire des sous-programmes
+#### Ecrire des fonctions
-# Ecrire des sous-programmes est facile :
+# Ecrire des fonctions est facile :
sub logger {
my $logmessage = shift;
@@ -148,9 +156,9 @@ sub logger {
print $logfile $logmessage;
}
-# Maintenant, nous pouvons utiliser le sous-programme comme n'importe quelle fonction intégrée :
+# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée :
-logger("On a un sous-programme de logging!!");
+logger("On a une fonction de logging!!");
```
#### Utiliser des modules Perl
--
cgit v1.2.3
From 6f2d38155930911159bfb4e169b4a4430fed2e72 Mon Sep 17 00:00:00 2001
From: Tim Heaney
Date: Thu, 8 Oct 2015 07:14:24 -0400
Subject: Typo: "thought of" not "though of"
---
chapel.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/chapel.html.markdown b/chapel.html.markdown
index e20be998..7252a3e4 100644
--- a/chapel.html.markdown
+++ b/chapel.html.markdown
@@ -633,7 +633,7 @@ writeln( toThisArray );
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
// exhibits a runtime error.
// Even though the domain of the array and the loop-expression are
-// the same size, the body of the expression can be though of as an iterator.
+// the same size, the body of the expression can be thought of as an iterator.
// Because iterators can yield nothing, that iterator yields a different number
// of things than the domain of the array or loop, which is not allowed.
--
cgit v1.2.3
From c39264fd881d9a7e39dbba1f37ec9de15cf11eea Mon Sep 17 00:00:00 2001
From: Tim Heaney
Date: Thu, 8 Oct 2015 09:00:59 -0400
Subject: Typo: "easily" rather than "easy"
---
fsharp.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index 62118006..76318d7d 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -119,7 +119,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
// ================================================
// F# is a true functional language -- functions are first
-// class entities and can be combined easy to make powerful
+// class entities and can be combined easily to make powerful
// constructs
// Modules are used to group functions together
--
cgit v1.2.3
From 4b74a7a76d5840cee8f713605347a6cad245d4bb Mon Sep 17 00:00:00 2001
From: Tom Samstag
Date: Thu, 8 Oct 2015 08:46:54 -0700
Subject: fix the output of ff example
---
perl6.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 63c0830a..26373c28 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1429,7 +1429,7 @@ for {
# A flip-flop can change state as many times as needed:
for {
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
- #=> "print this printing again"
+ #=> "print it print again"
}
# you might also use a Whatever Star,
--
cgit v1.2.3
From 6d3f52b7f01409818853de6148abf1d8fe57fab0 Mon Sep 17 00:00:00 2001
From: "Todd M. Guerra"
Date: Thu, 8 Oct 2015 11:53:19 -0400
Subject: Fix some grammar, spelling and indentation
Just some quick cleanup to make the code correctly formatted in parts
and fixed some typos.
---
java.html.markdown | 30 ++++++++++++++++--------------
1 file changed, 16 insertions(+), 14 deletions(-)
diff --git a/java.html.markdown b/java.html.markdown
index fc7948d6..e020885c 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -337,7 +337,7 @@ public class LearnJava {
validCodes.add("FINLAND");
}
- // But there's a nifty way to achive the same thing in an
+ // But there's a nifty way to achieve the same thing in an
// easier way, by using something that is called Double Brace
// Initialization.
@@ -347,9 +347,9 @@ public class LearnJava {
add("FINLAND");
}}
- // The first brace is creating an new AnonymousInnerClass and the
- // second one declares and instance initializer block. This block
- // is called with the anonymous inner class is created.
+ // The first brace is creating a new AnonymousInnerClass and the
+ // second one declares an instance initializer block. This block
+ // is called when the anonymous inner class is created.
// This does not only work for Collections, it works for all
// non-final classes.
@@ -476,14 +476,14 @@ public interface Digestible {
// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
@Override
- public void eat() {
- // ...
- }
+ public void eat() {
+ // awesome code goes here
+ }
@Override
- public void digest() {
- // ...
- }
+ public void digest() {
+ // awesome code goes here
+ }
}
// In Java, you can extend only one class, but you can implement many
@@ -491,12 +491,14 @@ public class Fruit implements Edible, Digestible {
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
InterfaceTwo {
@Override
- public void InterfaceOneMethod() {
- }
+ public void InterfaceOneMethod() {
+ // awesome code goes here
+ }
@Override
- public void InterfaceTwoMethod() {
- }
+ public void InterfaceTwoMethod() {
+ // awesome code goes here
+ }
}
--
cgit v1.2.3
From 79cee63879088757cdd5c05c8d51d83a725b794d Mon Sep 17 00:00:00 2001
From: Colton Kohnke
Date: Thu, 8 Oct 2015 21:20:37 +0200
Subject: [matlab/en] Added simple class example to Matlab
---
matlab.html.markdown | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 54 insertions(+)
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 02fe5962..0cbc6f57 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -3,6 +3,7 @@ language: Matlab
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
---
@@ -464,6 +465,59 @@ mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
+
+% Classes
+% Matlab can support object-oriented programming.
+% Classes must be put in a file of the class name with a .m extension.
+% To begin, we create a simple class to store GPS waypoints.
+% Begin WaypointClass.m
+classdef WaypointClass % The class name.
+ properties % The properties of the class behave like Structures
+ latitude
+ longitude
+ end
+ methods
+ % This method that has the same name of the class is the constructor.
+ function obj = WaypointClass(lat, lon)
+ obj.latitude = lat;
+ obj.longitude = lon;
+ end
+
+ % Other functions that use the Waypoint object
+ function r = multiplyLatBy(obj, n)
+ r = n*[obj.latitude];
+ end
+
+ % If we want to add two Waypoint objects together without calling
+ % a special function we can overload Matlab's arithmetic like so:
+ function r = plus(o1,o2)
+ r = WaypointClass([o1.latitude] +[o2.latitude], ...
+ [o1.longitude]+[o2.longitude]);
+ end
+ end
+end
+% End WaypointClass.m
+
+% We can create an object of the class using the constructor
+a = WaypointClass(45.0, 45.0)
+
+% Class properties behave exactly like Matlab Structures.
+a.latitude = 70.0
+a.longitude = 25.0
+
+% Methods can be called in the same way as functions
+ans = multiplyLatBy(a,3)
+
+% The method can also be called using dot notation. In this case, the object
+% does not need to be passed to the method.
+ans = a.multiplyLatBy(a,1/3)
+
+% Matlab functions can be overloaded to handle objects.
+% In the method above, we have overloaded how Matlab handles
+% the addition of two Waypoint objects.
+b = WaypointClass(15.0, 32.0)
+c = a + b
+
```
## More on Matlab
--
cgit v1.2.3
From 25d5d07dd342dc57831785032b813b3c2b3a5a9e Mon Sep 17 00:00:00 2001
From: Sean Corrales
Date: Thu, 8 Oct 2015 15:37:54 -0500
Subject: Updating function instructions.
---
sass.html.markdown | 19 ++++++++++---------
1 file changed, 10 insertions(+), 9 deletions(-)
diff --git a/sass.html.markdown b/sass.html.markdown
index d1e0721f..9bc72478 100644
--- a/sass.html.markdown
+++ b/sass.html.markdown
@@ -188,7 +188,8 @@ body.noLinks a {
#################### */
/* Sass provides functions that can be used to accomplish a variety of tasks. Consider the following */
-
+
+/* Functions can be invoked by using their name and passing in the required arguments */
body {
width: round(10.25px);
}
@@ -207,19 +208,19 @@ body {
background-color: rgba(0, 0, 0, 0.75);
}
-/* You may also define your own functions. Functions are very similar to mixins. When trying to choose between
- a function or a mixin, remember that functions are best for returning values while mixins are best for
- generating CSS while functions are better for logic that might be used throughout your Sass code. The
- examples in the Math Operators' section are ideal candidates for becoming a reusable function. */
-
-/* This function will take a target size and the parent size and calculate and return the percentage */
+/* You may also define your own functions. Functions are very similar to mixins. When trying
+ to choose between a function or a mixin, remember that functions are best for returning
+ values while mixins are best for generating CSS while functions are better for logic that
+ might be used throughout your Sass code. The examples in the Math Operators' section are
+ ideal candidates for becoming a reusable function. */
+
+/* This function will take a target size and the parent size and calculate and return
+ the percentage */
@function calculate-percentage($target-size, $parent-size) {
@return $target-size / $parent-size * 100%;
}
-/* Functions can be invoked by using their name and passing in the required arguments */
-
$main-content: calculate-percentage(600px, 960px);
.main-content {
--
cgit v1.2.3
From c7f02d174a72f1f1d807c57e030ba3c8f066c27b Mon Sep 17 00:00:00 2001
From: Colton Kohnke
Date: Thu, 8 Oct 2015 23:07:05 +0200
Subject: [latex/en] Initial latex whirlwind showcase
---
latex.html.markdown | 191 +++++++++++++++++++++++++++++-----------------------
1 file changed, 106 insertions(+), 85 deletions(-)
diff --git a/latex.html.markdown b/latex.html.markdown
index cc1d99cb..c8f21a83 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -2,6 +2,7 @@
language: latex
contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
+ - ["Colton Kohnke", "http://github.com/voltnor"]
filename: learn-latex.tex
---
@@ -12,122 +13,142 @@ getting it to behave exactly the way you want can be a bit hairy.
```latex
+
% All comment lines start with %
% There are no multi-line comments
% LaTeX is NOT a ``What You See Is What You Get'' word processing software like
% MS Word, or OpenOffice Writer
-% Getting to the final document using LaTeX consists of the following steps:
-% 1. Write the document in plain text
-% 2. Compile plain text document to produce a pdf
-% The compilation step looks something like this:
-% $ pdflatex your-tex-file.tex your-tex-file.pdf
-% A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
-% software. So, you get to see Step 1, but not Step 2 completely.
-% Step 2 is still happening behind the scenes.
-
-% You write all your formatting information in plain text in Step 1.
-% The compilation part in Step 2 takes care of producing the document in the
-% format you defined in Step 1.
-
-% For Step 1, it is best if you get a good text editor
-% On Windows, probably Notepad++
-% For Step 2, you will need to get a TeX distribution
-% Windows: MikTeX
-% MacOS: MacTeX
-% Linux: Should be available from your package manager
-
-% Let's get to the final pdf document as soon as possible
-
-% Choose the kind of document you want to write.
-% You can replace article with book, report, etc.
-\documentclass{article}
-% begin the document
-\begin{document}
-% end the document
-\end{document}
-% Compile to pdf
-% Now, you already have a final document which of course it is empty.
-% Everything that you write is between the
-% \begin{document}
-% \end{document}
-
-% Start a new document from here.
-% Let's do a decent document
-\documentclass{article}
-% required for inserting images
-\usepackage{graphicx}
-% begin the document
-\begin{document}
-% set the title (optional)
-\title{Title of the document}
-% set the author (optional)
-\author{Chaitanya Krishna Ande}
-
-% make the title (optional)
+% LaTeX documents start with a defining the type of document it's compiling
+% Other document types include book, report, presentations, etc.
+\documentclass[12pt]{article}
+
+% Next we define the packages the document uses.
+% I'm going to include the float and caption packages for figures.
+\usepackage{caption}
+\usepackage{float}
+
+% We can define some other document properties too!
+\author{Chaitanya Krishna Ande \& Colton Kohnke}
+\date{\today}
+\title{Learn LaTeX in Y Minutes!}
+
+% Now we're ready to begin the document
+% Everything before this line is called "The Preamble"
+\begin{document}
+% if we set the author, date, title fields, we can have LaTeX
+% create a title page fo us.
\maketitle
-% start the first section
\section{Introduction}
+Hello, my name is Colton and together we're going to explore LaTeX !
-% write your text
-This is the introduction.
-
-% start another section
\section{Another section}
-This is the text for another section.
-
-% another section with subsection
-\section{Section with sub-section}
-Text for the section.
-\subsection{Sub-section}
-Let's discuss the Pythagoras theorem.
-\subsubsection{Pythagoras Theorm}
-% for cross-reference
+This is the text for another section. I think it needs a subsection.
+
+\subsection{This is a subsection}
+I think we need another one
+
+\subsubsection{Pythagoras}
+Much better now.
\label{subsec:pythagoras}
-% notice how the sections and sub-sections are automatically numbered
+\section*{This is an unnumbered section}
+However not all sections have to be numbered!
-% Some math
-% Inline math within $ $
-For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$, $b$ and $c$, where $c$ is the
-hypotenuse, the following holds:
+\section{Some Text notes}
+LaTeX is generally pretty good about placing text where it should go. If
+a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to
+the text. In case you haven't noticed the \textbackslash is the character
+the tells the LaTeX compiler it should pay attention to what's next.
+
+\section{Math}
+
+One of the primary uses for LaTeX is to produce academic article or
+technical papers. Usually in the realm of math and science. As such,
+we need to be able to add special symbols to our paper! \\
+
+My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+Notice how I needed to add \$ signs before and after the symbols. This is
+because when writing, we are in text-mode. However, the math symbols only exist
+in math-mode. We can enter math-mode from text mode with the \$ signs.
+The opposite also holds true. Variable can also be rendered in math-mode. \\
+
+% We can also add references
+For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$,
+ $b$ and $c$, where $c$ is the hypotenuse, the following holds:
% Display math with the equation 'environment'
-\begin{equation}
+\begin{equation} % enters math-mode
c^2 = a^2 + b^2.
% for cross-reference
\label{eq:pythagoras}
-\end{equation}
+\end{equation} % all \begin statments must have an end statement
-% Let's cross-reference the equation
Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
the subject of Sec.~\ref{subsec:pythagoras}.
-\subsubsection{Figure}
-Let's insert a Figure.
-\begin{figure}
+\section{Figures}
+
+Let's insert a Figure. Figure placement can get a little tricky.
+I definately have to lookup the placement options each time.
+
+\begin{figure}[H]
\centering
- \includegraphics[width=0.8\linewidth]{right-triangle.png}
- \caption{Right triangle with sides a, b, c}
+ %\includegraphics[width=0.8\linewidth]{right-triangle.png}
+ % Commented out for compilation purposes. Use your imagination.
+ \caption{Right triangle with sides $a$, $b$, $c$}
\label{fig:right-triangle}
\end{figure}
-
-\subsubsection{Table}
+\subsection{Table}
Let's insert a Table.
-\begin{table}
-\caption{Caption for the Table.}
-\begin{tabular}{ccc}
-Number & Last Name & First Name \\
-\hline
-1 & Biggus & Dickus \\
-2 & Monty & Python
-\end{tabular}
+\begin{table}[H]
+ \caption{Caption for the Table.}
+ \begin{tabular}{ccc}
+ Number & Last Name & First Name \\
+ \hline
+ 1 & Biggus & Dickus \\
+ 2 & Monty & Python
+ \end{tabular}
\end{table}
+
+\section{Compiling}
+
+By now you're probably wondering how to compile this fabulous document
+(yes, it actually compiles). \\
+Getting to the final document using LaTeX consists of the following steps:
+ \begin{enumerate} % we can also created numbered lists!
+ \item Write the document in plain text
+ \item Compile plain text document to produce a pdf.
+ The compilation step looks something like this: \\
+ % Verbatim tells the compiler to not interpret.
+ \begin{verbatim}
+ $pdflatex learn-latex.tex learn-latex.pdf
+ \end{verbatim}
+ \end{enumerate}
+
+A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of
+software. So, you get to see Step 1, but not Step 2 completely.
+Step 2 is still happening behind the scenes.
+
+You write all your formatting information in plain text in Step 1.
+The compilation part in Step 2 takes care of producing the document in the
+format you defined in Step 1.
+
+\section{End}
+
+That's all for now!
+
% end the document
\end{document}
```
+## More on LaTeX
+
+* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX)
+* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/)
+
+
--
cgit v1.2.3
From c3914e277bafb320a37617c4a41984462be1a20d Mon Sep 17 00:00:00 2001
From: Raphael Nascimento
Date: Thu, 8 Oct 2015 18:34:03 -0300
Subject: Added for/in loop JavaScript
Fixing code style
---
javascript.html.markdown | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/javascript.html.markdown b/javascript.html.markdown
index f7a662a4..0e38be8f 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -221,7 +221,7 @@ for (var i = 0; i < 5; i++){
//The For/In statement loops iterates over every property across the entire prototype chain
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
-for (var x in person) {
+for (var x in person){
description += person[x] + " ";
}
@@ -229,8 +229,8 @@ for (var x in person) {
//and not its prototypes use hasOwnProperty() check
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
-for (var x in person) {
- if( person.hasOwnProperty( x ) ) {
+for (var x in person){
+ if (person.hasOwnProperty(x)){
description += person[x] + " ";
}
}
--
cgit v1.2.3
From 8f5f1240eb14919deed89c54f0b322bc11e1469c Mon Sep 17 00:00:00 2001
From: Heather Fenton
Date: Thu, 8 Oct 2015 19:18:07 -0400
Subject: Git: Add Git Immersion tutorial as a resource
---
git.html.markdown | 2 ++
1 file changed, 2 insertions(+)
diff --git a/git.html.markdown b/git.html.markdown
index b1347309..72079f6c 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -484,6 +484,8 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
+* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
+
* [git-scm - Video Tutorials](http://git-scm.com/videos)
* [git-scm - Documentation](http://git-scm.com/docs)
--
cgit v1.2.3
From 16c7f5e3b1260b9ae20613ae02728bf7090b0b9f Mon Sep 17 00:00:00 2001
From: Zsolt Prontvai
Date: Fri, 9 Oct 2015 02:41:08 +0200
Subject: Ruby hungarian translation
---
hu-hu/ruby.html.markdown | 555 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 555 insertions(+)
create mode 100644 hu-hu/ruby.html.markdown
diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby.html.markdown
new file mode 100644
index 00000000..169f2b8e
--- /dev/null
+++ b/hu-hu/ruby.html.markdown
@@ -0,0 +1,555 @@
+---
+language: ruby
+lang: hu-hu
+filenev: learnruby.rb
+contributors:
+ - ["David Underwood", "http://theflyingdeveloper.com"]
+ - ["Joel Walden", "http://joelwalden.net"]
+ - ["Luke Holder", "http://twitter.com/lukeholder"]
+ - ["Tristan Hume", "http://thume.ca/"]
+ - ["Nick LaMuro", "https://github.com/NickLaMuro"]
+ - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
+ - ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ translators:
+ - ["Zsolt Prontvai", "https://github.com/prozsolt"]
+---
+
+```ruby
+# Ez egy komment
+
+=begin
+Ez egy többsoros komment
+Senki sem használja
+Neked sem kellene
+=end
+
+# Először is: Minden objektum
+
+# A számok objektumok
+
+3.class #=> Fixnum
+
+3.to_s #=> "3"
+
+
+# Néhány alapvető számtani művelet
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+35 / 5 #=> 7
+2**5 #=> 32
+
+# A számtani művelet csak szintaktikus cukor
+# az objektumon történő függvény hívásra
+1.+(3) #=> 4
+10.* 5 #=> 50
+
+# A speciális értékek objektumok
+nil # Nincs itt semmi látnivaló
+true # igaz
+false # hamis
+
+nil.class #=> NilClass
+true.class #=> TrueClass
+false.class #=> FalseClass
+
+# Egyenlőség
+1 == 1 #=> true
+2 == 1 #=> false
+
+# Egyenlőtlenség
+1 != 1 #=> false
+2 != 1 #=> true
+
+# A false-on kívül, nil az egyetlen hamis érték
+
+!nil #=> true
+!false #=> true
+!0 #=> false
+
+# Még több összehasonlítás
+1 < 10 #=> true
+1 > 10 #=> false
+2 <= 2 #=> true
+2 >= 2 #=> true
+
+# Logikai operátorok
+true && false #=> false
+true || false #=> true
+!true #=> false
+
+# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb
+# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak
+# amíg egyikük igaz vagy hamis értékkel nem tér vissza.
+
+# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel
+# tért vissza.
+csinalj_valamit() and csinalj_valami_mast()
+# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel
+# tért vissza.
+csinalj_valamit() or log_error()
+
+
+# A sztringek objektumok
+
+'Én egy sztring vagyok'.class #=> String
+"Én is egy sztring vagyok".class #=> String
+
+helykitolto = 'interpolációt használhatok'
+"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem"
+#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem"
+
+# A szimpla idézőjelet preferáljuk, ahol csak lehet,
+# mert a dupla idézőjel extra számításokat végez.
+
+# Kombinálhatunk sztringeket, de nem számokkal
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
+
+# kiírás a kimenetre
+puts "Írok"
+
+# Változók
+x = 25 #=> 25
+x #=> 25
+
+# Értékadás az adott értékkel tér vissza
+# Ez azt jelenti, hogy használhatunk többszörös értékadást:
+
+x = y = 10 #=> 10
+x #=> 10
+y #=> 10
+
+# Konvencióból, snake_case változó neveket használj
+snake_case = true
+
+# Leíró változó neveket használj
+ut_a_projekt_gyokerehez = '/jo/nev/'
+ut = '/rossz/nev/'
+
+# A szimbólumok (objektumok)
+# A szimbólumok megváltoztathatatlan, újra felhasználható konstans,
+# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják,
+# hogy effektíven közvetítsünk konkrét, értelmes értékeket
+
+:fuggoben.class #=> Symbol
+
+statusz = :fuggoben
+
+statusz == :fuggoben #=> true
+
+statusz == 'fuggoben' #=> false
+
+statusz == :jovahagyott #=> false
+
+# Tömbök
+
+# Ez egy tömb
+tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
+
+# A tömmbök különböző tipusú dolgokat tartalmazhat
+
+[1, 'hello', false] #=> [1, "hello", false]
+
+# Tömbök indexelhetőek
+# Az elejéről
+tomb[0] #=> 1
+tomb[12] #=> nil
+
+# Akárcsak a számtani műveletek [var] hozzáférés
+# is csak szintaktikus cukor
+# a [] függvény hívására az objektumon
+tomb.[] 0 #=> 1
+tomb.[] 12 #=> nil
+
+# A végéről
+tomb[-1] #=> 5
+
+# Kezdőértékkel és hosszal
+tomb[2, 3] #=> [3, 4, 5]
+
+# Tömb megfordítása
+a=[1,2,3]
+a.reverse! #=> [3,2,1]
+
+# Vagy tartománnyal
+tomb[1..3] #=> [2, 3, 4]
+
+# Így adhatunk a tömbhöz
+tomb << 6 #=> [1, 2, 3, 4, 5, 6]
+# Vagy így
+tomb.push(6) #=> [1, 2, 3, 4, 5, 6]
+
+# Ellenőrízük, hogy a tömb tartalmaz egy elemet
+tomb.include?(1) #=> true
+
+# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal
+# Hash-eket kapcsos zárójellel jelöljük
+hash = { 'szin' => 'zold', 'szam' => 5 }
+
+hash.keys #=> ['szin', 'szam']
+
+# Hash-ekben könnyen kreshetünk a kulcs segítségével:
+hash['szin'] #=> 'zold'
+hash['szam'] #=> 5
+
+# Nem létező kulcsra keresve nil-t kapunk:
+hash['nincs itt semmi'] #=> nil
+
+# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot
+# használunk kulcsnak
+
+uj_hash = { defcon: 3, action: true }
+
+uj_hash.keys #=> [:defcon, :action]
+
+# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben
+uj_hash.has_key?(:defcon) #=> true
+uj_hash.has_value?(3) #=> true
+
+# Tip: A tömbök és hash-ek is felsorolhatóak
+# Sok közös függvényük van, akár az each, map, count, és több
+
+# Kontroll Struktúrák
+
+if true
+ 'ha állítás'
+elsif false
+ 'különben ha, opcionális'
+else
+ 'különben, szintén opcionális'
+end
+
+for szamlalo in 1..5
+ puts "iteracio #{szamlalo}"
+end
+#=> iteracio 1
+#=> iteracio 2
+#=> iteracio 3
+#=> iteracio 4
+#=> iteracio 5
+
+# HOWEVER, No-one uses for loops.
+# Instead you should use the "each" method and pass it a block.
+# A block is a bunch of code that you can pass to a method like "each".
+# It is analogous to lambdas, anonymous functions or closures in other
+# programming languages.
+#
+# The "each" method of a range runs the block once for each element of the range.
+# The block is passed a counter as a parameter.
+# Calling the "each" method with a block looks like this:
+
+(1..5).each do |counter|
+ puts "iteration #{counter}"
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+# You can also surround blocks in curly brackets:
+(1..5).each { |counter| puts "iteration #{counter}" }
+
+# The contents of data structures can also be iterated using each.
+array.each do |element|
+ puts "#{element} is part of the array"
+end
+hash.each do |key, value|
+ puts "#{key} is #{value}"
+end
+
+counter = 1
+while counter <= 5 do
+ puts "iteration #{counter}"
+ counter += 1
+end
+#=> iteration 1
+#=> iteration 2
+#=> iteration 3
+#=> iteration 4
+#=> iteration 5
+
+jegy = '4'
+
+case jegy
+when '5'
+ puts 'Kitünő'
+when '4'
+ puts 'Jó'
+when '3'
+ puts 'Közepes'
+when '2'
+ puts 'Elégsége'
+when '1'
+ puts 'Elégtelen'
+else
+ puts 'Alternatív értékelés, hm?'
+end
+#=> "Jó"
+
+# case-ek tartományokat is használhatnak
+jegy = 82
+case jegy
+when 90..100
+ puts 'Hurrá!'
+when 80...90
+ puts 'Jó munka'
+else
+ puts 'Megbuktál!'
+end
+#=> "Jó munka"
+
+# kivétel kezelés:
+begin
+ # kód ami kivételt dobhat
+ raise NoMemoryError, 'Megtelt a memória'
+rescue NoMemoryError => kivetel_valtozo
+ puts 'NoMemoryError-t dobott', kivetel_valtozo
+rescue RuntimeError => mas_kivetel_valtozo
+ puts 'RuntimeError dobott most'
+else
+ puts 'Ez akkor fut ha nem dob kivételt'
+ensure
+ puts 'Ez a kód mindenképpen lefut'
+end
+
+# Függvények
+
+def ketszeres(x)
+ x * 2
+end
+
+# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel
+ketszeres(2) #=> 4
+
+# Zárójelezés opcionális, ha az eredmény félreérthetetlen
+ketszeres 3 #=> 6
+
+ketszeres ketszeres 3 #=> 12
+
+def osszeg(x, y)
+ x + y
+end
+
+# Függvény argumentumait vesszővel választjuk el.
+osszeg 3, 4 #=> 7
+
+osszeg osszeg(3, 4), 5 #=> 12
+
+# yield
+# Minden függvénynek van egy implicit, opcionális block paramétere
+# 'yield' kulcsszóval hívhatjuk
+
+def korulvesz
+ puts '{'
+ yield
+ puts '}'
+end
+
+korulvesz { puts 'hello world' }
+
+# {
+# hello world
+# }
+
+
+# Fuggvénynek átadhatunk blokkot
+# "&" jelöli az átadott blokk referenciáját
+def vendegek(&block)
+ block.call 'valami_argumentum'
+end
+
+# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva
+# Erre való a splat operátor ("*")
+def vendegek(*array)
+ array.each { |vendeg| puts vendeg }
+end
+
+# Osztályt a class kulcsszóval definiálhatunk
+class Ember
+
+ # Az osztály változó. Az osztály minden példánnyával megvan osztva
+ @@faj = 'H. sapiens'
+
+ # Alap inicializáló
+ def initialize(nev, kor = 0)
+ # Hozzárendeli az argumentumot a "nev" példány változóhoz
+ @nev = nev
+ # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni
+ @kor = kor
+ end
+
+ # Alap setter függvény
+ def nev=(nev)
+ @nev = nev
+ end
+
+ # Alap getter függvény
+ def nev
+ @nev
+ end
+
+ # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük
+ attr_accessor :nev
+
+ # Getter/setter függvények egyenként is kreálhatóak
+ attr_reader :nev
+ attr_writer :nev
+
+ # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a
+ # példány függvényektől
+ # Az osztályn hívhatóak, nem a példányon
+ def self.mond(uzenet)
+ puts uzenet
+ end
+
+ def faj
+ @@faj
+ end
+end
+
+
+# Példányosítsuk az osztályt
+jim = Ember.new('Jim Halpert')
+
+dwight = Ember.new('Dwight K. Schrute')
+
+# Hívjunk meg pár függvényt
+jim.faj #=> "H. sapiens"
+jim.nev #=> "Jim Halpert"
+jim.nev = "Jim Halpert II" #=> "Jim Halpert II"
+jim.nev #=> "Jim Halpert II"
+dwight.faj #=> "H. sapiens"
+dwight.nev #=> "Dwight K. Schrute"
+
+# Hívjuk meg az osztály függvényt
+Ember.mond('Hi') #=> "Hi"
+
+# Változók szókjait az elnevezésük definiálja
+# $ kezdetű változók globálisak
+$var = "Én egy globális változó vagyok"
+defined? $var #=> "global-variable"
+
+# Változók amik @-al kezdődnek példány szkópjuk van
+@var = "Én egy példány változó vagyok"
+defined? @var #=> "instance-variable"
+
+# Változók amik @@-al kezdődnek példány szkópjuk van
+@@var = "Én egy osztály változó vagyok"
+defined? @@var #=> "class variable"
+
+# Változók amik nagy betűvel kezdődnek a konstansok
+Var = "Konstans vagyok"
+defined? Var #=> "constant"
+
+# Az osztály is objetum. Tehát az osztálynak lehet példány változója
+# Az osztályváltozón osztozik minden pédány és leszármazott
+
+# Ős osztály
+class Ember
+ @@foo = 0
+
+ def self.foo
+ @@foo
+ end
+
+ def self.foo=(ertek)
+ @@foo = ertek
+ end
+end
+
+# Leszarmazott osztály
+class Dolgozo < Ember
+end
+
+Ember.foo # 0
+Dolgozo.foo # 0
+
+Ember.foo = 2 # 2
+Dolgozo.foo # 2
+
+# Az osztálynak példány változóját nem látja az osztály leszármazottja.
+
+class Ember
+ @bar = 0
+
+ def self.bar
+ @bar
+ end
+
+ def self.bar=(ertek)
+ @bar = ertek
+ end
+end
+
+class Doctor < Ember
+end
+
+Ember.bar # 0
+Doctor.bar # nil
+
+module ModulePelda
+ def foo
+ 'foo'
+ end
+end
+
+# Modulok include-olása a fügvényeiket az osztály példányaihoz köti.
+# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti.
+
+class Szemely
+ include ModulePelda
+end
+
+class Konyv
+ extend ModulePelda
+end
+
+Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class
+Szemely.new.foo # => 'foo'
+Konyv.foo # => 'foo'
+Konyv.new.foo # => NoMethodError: undefined method `foo'
+
+# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult
+
+module ConcernPelda
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
+ end
+ end
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
+ end
+end
+
+class Valami
+ include ConcernPelda
+end
+
+Valami.bar # => 'bar'
+Valami.qux # => NoMethodError: undefined method `qux'
+Valami.new.bar # => NoMethodError: undefined method `bar'
+Valami.new.qux # => 'qux'
+```
+
+## Egyéb források
+
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338)
+- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide)
--
cgit v1.2.3
From d1b75f63352338bcbb1af6731c9a47b977a6be24 Mon Sep 17 00:00:00 2001
From: Raphael Nascimento
Date: Thu, 8 Oct 2015 23:39:00 -0300
Subject: translation clojure-macros to pt br
---
pt-br/clojure-macros-pt.html.markdown | 154 ++++++++++++++++++++++++++++++++++
1 file changed, 154 insertions(+)
create mode 100644 pt-br/clojure-macros-pt.html.markdown
diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown
new file mode 100644
index 00000000..dbc0c25c
--- /dev/null
+++ b/pt-br/clojure-macros-pt.html.markdown
@@ -0,0 +1,154 @@
+---
+language: clojure
+filename: learnclojure-pt.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Raphael Bezerra do Nascimento"]
+lang: pt-br
+---
+
+Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic)
+do Clojure lhe dá acesso a toda a extensão da linguagem
+para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem
+às suas necessidades.
+
+Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas
+quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado.
+
+Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em
+[Clojure em Y Minutos](/docs/clojure/).
+
+```clojure
+;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa
+;; ser avaliada como codigo Clojure.
+;;
+;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World")
+(defmacro my-first-macro []
+ (list reverse "Hello World"))
+
+;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1.
+;;
+;; Note que a chamada deve utilizar aspas simples.
+(macroexpand '(my-first-macro))
+;; -> (# "Hello World")
+
+;; Você pode avaliar o resultad de macroexpand diretamente:
+(eval (macroexpand '(my-first-macro)))
+; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; mas você deve usar esse mais suscinto, sintax como de função:
+(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H)
+
+;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta
+;; para criar listas nas suas macros:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hello World"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hello World")
+;; Note que reverse não é mais uma função objeto, mas um simbolo.
+
+;; Macros podem ter argumentos.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o
+;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples
+;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Lembrar o do!
+
+(macroexpand '(unless true (reverse "Hello World")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hello World")))
+
+;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso.
+;; caso contrario, retorna nil
+
+(unless true "Hello") ; -> nil
+(unless false "Hello") ; -> "Hello"
+
+;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;;s Para evitar isso, use gensym para receber um identificador unico
+(gensym 'x) ; -> x1281 (ou outra coisa)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente
+(defmacro define-x-hygenically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygenically) ; -> (2)
+(list x) ; -> (4)
+
+;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco
+;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida)
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Given args [x (+ y)], return (+ x y)"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Podemos testar isso imediatamente, sem criar uma macro
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação
+(defmacro inline-2 [form]
+ (inline-2-helper form)))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com /
+
+### Leitura adicional
+
+Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/)
+[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/)
+
+Documentos oficiais
+[http://clojure.org/macros](http://clojure.org/macros)
+
+Quando utilizar macros?
+[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html)
--
cgit v1.2.3
From bc065831ce25467ba06d3cf6e6ad159eed16a525 Mon Sep 17 00:00:00 2001
From: Clayton Walker
Date: Thu, 8 Oct 2015 23:24:25 -0400
Subject: Added suggested changes
---
go.html.markdown | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/go.html.markdown b/go.html.markdown
index f9821a0c..646a5650 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -408,8 +408,8 @@ func requestServer() {
The root of all things Go is the [official Go web site](http://golang.org/).
There you can follow the tutorial, play interactively, and read lots.
-Aside from a tour, [the docs](https://golang.org/doc/) contain how to write
-clean and effective Go code, package and command docs, and release history.
+Aside from a tour, [the docs](https://golang.org/doc/) contain information on
+how to write clean and effective Go code, package and command docs, and release history.
The language definition itself is highly recommended. It's easy to read
and amazingly short (as language definitions go these days.)
--
cgit v1.2.3
From b4860de42f2bbf0ab97ef28085eb40accb030657 Mon Sep 17 00:00:00 2001
From: Clayton Walker
Date: Thu, 8 Oct 2015 23:27:19 -0400
Subject: Suggested changes
---
swift.html.markdown | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/swift.html.markdown b/swift.html.markdown
index 46e5e6d4..9f0019d8 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -58,8 +58,8 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals are a Swift language feature that either contains a value,
- or contains nil (no value) to indicate that a value is missing.
+ Optionals are a Swift language feature that either contains a value,
+ or contains nil (no value) to indicate that a value is missing.
A question mark (?) after the type marks the value as optional.
Because Swift requires every property to have a value, even nil must be
@@ -82,9 +82,9 @@ if someOptionalString != nil {
someOptionalString = nil
/*
- To get the underlying type from an optional, you unwrap it using the
- force unwrap operator (!). Only use the unwrap operator if you're sure
- the underlying value isn't nil.
+ Trying to use ! to access a non-existent optional value triggers a runtime
+ error. Always make sure that an optional contains a non-nil value before
+ using ! to force-unwrap its value.
*/
// implicitly unwrapped optional
--
cgit v1.2.3
From 7fd149485e0cbef6fc57206cb1377f261ed70278 Mon Sep 17 00:00:00 2001
From: Martin N
Date: Fri, 9 Oct 2015 07:39:22 +0000
Subject: Mention of trailing commas in JSON and that they should be avoided
---
json.html.markdown | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/json.html.markdown b/json.html.markdown
index 6aff2ce2..a85cecc4 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -10,8 +10,11 @@ As JSON is an extremely simple data-interchange format, this is most likely goin
to be the simplest Learn X in Y Minutes ever.
JSON in its purest form has no actual comments, but most parsers will accept
-C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
-going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
+(i.e. a comma after the last element of an array or the after the last property of an object),
+but they should be avoided for better compatibility.
+
+For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
```json
{
--
cgit v1.2.3
From 4c27047a9748c0d3197dc63de34cc8bebf03633f Mon Sep 17 00:00:00 2001
From: Vojta Svoboda
Date: Fri, 9 Oct 2015 11:27:19 +0200
Subject: [json/en] Typo
---
json.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/json.html.markdown b/json.html.markdown
index a85cecc4..a1629137 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -14,7 +14,7 @@ C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
(i.e. a comma after the last element of an array or the after the last property of an object),
but they should be avoided for better compatibility.
-For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
+For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
```json
{
--
cgit v1.2.3
From ab8267f4273d6fa2c3027775e353d95e7d5f1493 Mon Sep 17 00:00:00 2001
From: payet-s
Date: Thu, 8 Oct 2015 16:48:50 +0200
Subject: [yaml/fr] Fix typos
---
fr-fr/yaml-fr.html.markdown | 92 +++++++++++++++++++++++----------------------
1 file changed, 48 insertions(+), 44 deletions(-)
diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
index 43b1df54..1e8296d3 100644
--- a/fr-fr/yaml-fr.html.markdown
+++ b/fr-fr/yaml-fr.html.markdown
@@ -8,113 +8,117 @@ lang: fr-fr
Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
représentation de données par sérialisation, conçu pour être aisément
-éditable et lisible par nous même, les humains.
+modifiable et lisible par nous-mêmes, les humains.
-YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages.
+YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le
+découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont
+il est un parent naturel. Toutefois, YAML emprunte également des idées et
+concepts de Python, et s'intègre bien avec bon nombre de langages.
+Contrairement à ce dernier, YAML interdit l'utilisation des tabulations.
```yaml
-# les Commentaires sont précédés d'un signe "#", comme cette ligne.
+# Les commentaires sont précédés d'un signe "#", comme cette ligne.
#############
# SCALAIRES #
#############
-# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
-# ( listes ou tableaux associatifs ).
+# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
+# (listes ou tableaux associatifs).
-# Notre objet root ( racine ), sera une map ( carte ) et englobera
-# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
+# Notre objet root (racine), sera une map (carte) et englobera
+# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
# hash ou objet dans d'autres langages.
clé: valeur
-aurtre_clé: une autre valeur
+autre_clé: une autre valeur
valeur_numérique: 100
notation_scientifique: 1e+12
-boolean: true
+booléen: true
valeur_null: null
clé avec espaces: valeur
-# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
+# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères
# entre guillemets, cela reste possible, et parfois utile.
toutefois: "Une chaîne, peut être contenue entre guillemets."
-"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé."
+"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé."
-# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
-# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ).
+# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
+# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>').
bloc_littéral: |
- Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral',
- avec préservation des retours à la ligne. ( chaque ligne vide à
- l'intérieur du même bloc, sera remplacée par "\n\n" )
+ Tout ce bloc de texte sera la valeur de la clé "bloc_littéral",
+ avec préservation des retours à la ligne.
Le littéral continue jusqu'à ce que l'indentation soit annulée.
- Toutes lignes qui serait "d'avantage indentées" conservent leur
+ Toutes lignes qui seraient "davantage indentées" conservent leur
indentation, constituée de 4 espaces.
bloc_replié: >
- Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais
- cette fois ci, toutes les nouvelles lignes deviendront un simple espace.
+ Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais
+ cette fois-ci, toutes les nouvelles lignes deviendront un simple espace.
- Les lignes vides, comme ci-dessus, seront converties en caractère "\n".
+ Les lignes vides, comme ci-dessus, seront converties en caractère de
+ nouvelle ligne.
- Les lignes 'plus-indentées' gardent leurs retours à la ligne -
+ Les lignes "plus-indentées" gardent leurs retours à la ligne -
ce texte apparaîtra sur deux lignes.
###############
# COLLECTIONS #
###############
-# l'Imbrication est créée par indentation.
+# L'imbrication est créée par indentation.
une_map_imbriquée:
clé: valeur
autre_clé: autre valeur
autre_map_imbriquée:
bonjour: bonjour
-# les Clés des Maps ne sont pas nécessairement des chaînes de caractères.
-0.25: une clé de type float
+# Les clés des maps ne sont pas nécessairement des chaînes de caractères.
+0.25: une clé de type flottant
-# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
+# Les clés peuvent également être des objets s'étendant sur plusieurs lignes,
# en utilisant le signe "?" pour indiquer le début de la clé.
? |
- ceci est une Clé
+ ceci est une clé
sur de multiples lignes
-: et ceci est sa Valeur
+: et ceci est sa valeur
# YAML autorise aussi l'usage des collections à l'intérieur des clés,
# mais certains langages de programmation ne le tolère pas si bien.
-# les Séquences (équivalent des listes ou tableaux) ressemblent à cela:
+# Les séquences (équivalent des listes ou tableaux) ressemblent à cela :
une_séquence:
- - Item 1
- - Item 2
+ - Objet 1
+ - Objet 2
- 0.5 # les séquences peuvent contenir des types variés.
- - Item 4
+ - Objet 4
- clé: valeur
autre_clé: autre_valeur
-
- Ceci est une séquence
- dans une autre séquence
-# YAML étant un proche parent de JSON, vous pouvez écrire directement
+# YAML étant un proche parent de JSON, vous pouvez écrire directement
# des maps et séquences façon JSON
json_map: {"clé": "valeur"}
json_seq: [1, 2, 3, "soleil"]
-#################################
+################################
# AUTRES FONCTIONNALITÉES YAML #
-#################################
+################################
-# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci
+# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci
# vous permet de dupliquer aisément du contenu au sein de votre document.
-# Les deux clés suivantes auront la même valeur:
+# Les deux clés suivantes auront la même valeur :
contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
autre_ancre: *nom_ancre
-# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données.
+# Avec les tags YAML, vous pouvez explicitement déclarer des types de données.
chaine_explicite: !!str 0.5
-# Certains parsers implémentent des tags spécifiques à d'autres langages,
-# comme par exemple le "complex number" de Python.
+# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à
+# d'autres langages, comme par exemple celui des nombres complexes de Python.
python_complex_number: !!python/complex 1+2j
#####################
@@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j
#####################
# YAML interprète également les données formatées ISO de type date et datetime,
-# pas seulement les chaînes et nombres.
+# pas seulement les chaînes et nombres.
datetime: 2001-12-15T02:59:43.1Z
datetime_avec_espaces: 2001-12-14 21:59:43.10 -5
date: 2002-12-14
@@ -135,14 +139,14 @@ fichier_gif: !!binary |
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
-# YAML a de même un type "set", qui ressemble à cela:
+# YAML a de même un type "set", semblable à ceci :
set:
? item1
? item2
? item3
# Comme dans Python, les sets ne sont que des maps contenant des valeurs null ;
-# le set précédent est l'équivalent du suivant:
+# le set précédent est l'équivalent du suivant :
set2:
item1: null
item2: null
@@ -152,6 +156,6 @@ set2:
Quelques références et outils :
-- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
+- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
-- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
+- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
--
cgit v1.2.3
From bf7d33037f64ea9f80f106a37929e3fdf20bd24d Mon Sep 17 00:00:00 2001
From: Cameron Schermerhorn
Date: Fri, 9 Oct 2015 08:14:11 -0400
Subject: Add space to comment prior to switch string
+ Add space to comment (after //) prior to switch on string example
---
java.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/java.html.markdown b/java.html.markdown
index e567b049..eb8b23e9 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -277,7 +277,7 @@ public class LearnJava {
}
System.out.println("Switch Case Result: " + monthString);
- //Starting in Java 7 and above, switching Strings works like this:
+ // Starting in Java 7 and above, switching Strings works like this:
String myAnswer = "maybe";
switch(myAnswer){
case "yes":
--
cgit v1.2.3
From 1f68a9645573e54354d672709605ed9975e4843b Mon Sep 17 00:00:00 2001
From: wboka
Date: Fri, 9 Oct 2015 08:43:12 -0400
Subject: Update coldfusion.html.markdown
Adds conversion table and example of a very basic component. Adds a link to the official Adobe ColdFusion developer reference.
---
coldfusion.html.markdown | 413 +++++++++++++++++++----------------------------
1 file changed, 163 insertions(+), 250 deletions(-)
diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown
index 6a9b69f0..e2f0737d 100644
--- a/coldfusion.html.markdown
+++ b/coldfusion.html.markdown
@@ -146,263 +146,176 @@ ColdFusion is a scripting language for web development.
-```
-
+
Components
+
+Code for reference (Functions must return something to support IE)
+
+
+```
## Further Reading
The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples.
+
+1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html)
--
cgit v1.2.3
From c1c7a96378d79d379e68084780eecd91731fa4bb Mon Sep 17 00:00:00 2001
From: Himanshu81494
Date: Fri, 9 Oct 2015 19:57:06 +0530
Subject: typo in readme
---
README.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.markdown b/README.markdown
index 774797d5..28fa5093 100644
--- a/README.markdown
+++ b/README.markdown
@@ -8,7 +8,7 @@ commented code and explained as they go.
... to write more inline code tutorials. Just grab an existing file from
this repo and copy the formatting (don't worry, it's all very simple).
-Make a new file, send a pull request, and if it passes muster I'll get it up pronto.
+Make a new file, send a pull request, and if it passes master I'll get it up pronto.
Remember to fill in the "contributors" fields so you get credited
properly!
--
cgit v1.2.3
From 1e90e7da1d042dfc46a5be11117a4e45e460bcf8 Mon Sep 17 00:00:00 2001
From: Andy B
Date: Fri, 9 Oct 2015 15:32:05 +0100
Subject: [objective-c/en-fr-ru-tr-vn] Enable syntax highlighting
---
fr-fr/objective-c-fr.html.markdown | 2 +-
objective-c.html.markdown | 2 +-
ru-ru/objective-c-ru.html.markdown | 2 +-
tr-tr/objective-c-tr.html.markdown | 2 +-
vi-vn/objective-c-vi.html.markdown | 2 +-
5 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index 69f4d8f9..4e31c4bf 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -14,7 +14,7 @@ lang: fr-fr
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
-```objective_c
+```objective-c
// Les commentaires sur une seule ligne commencent par //
/*
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 89901308..cf6bf780 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -13,7 +13,7 @@ filename: LearnObjectiveC.m
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
-```objective_c
+```objective-c
// Single-line comments start with //
/*
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index ddff2e5c..8eac4ddb 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -17,7 +17,7 @@ Cocoa Touch.
Он является объектно-ориентированным языком программирования общего назначения,
который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C.
-```objective_c
+```objective-c
// Однострочные комментарии начинаются с //
/*
diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown
index f27cbf08..727f973e 100644
--- a/tr-tr/objective-c-tr.html.markdown
+++ b/tr-tr/objective-c-tr.html.markdown
@@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di
Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C
programlama diline Smalltalk stilinde mesajlaşma ekler.
-```objective_c
+```objective-c
// Tek satır yorum // işaretleri ile başlar
/*
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index c97bb560..38e418e9 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
--
cgit v1.2.3
From a67d9d9e0ed3d351ce0139de18a4b212b47ab9cb Mon Sep 17 00:00:00 2001
From: Andy B
Date: Fri, 9 Oct 2015 15:36:51 +0100
Subject: [coffeescript/en] Fixed grammar
---
coffeescript.html.markdown | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index 85a5f81f..106854bd 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -7,7 +7,7 @@ filename: coffeescript.coffee
---
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
-As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
+As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime.
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
--
cgit v1.2.3
From e8e8b9c76fb578d3f8e90b90b3c8a1c59cf0e901 Mon Sep 17 00:00:00 2001
From: Andy B
Date: Fri, 9 Oct 2015 15:48:21 +0100
Subject: [C/en] Accessing command line arguments in main
---
c.html.markdown | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/c.html.markdown b/c.html.markdown
index db2ac930..345dca7f 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -27,6 +27,7 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line...
*/ // ...not this one!
// Constants: #define
+// Constants are written in all-caps out of convention, not requirement
#define DAYS_IN_YEAR 365
// Enumeration constants are also ways to declare constants.
@@ -56,6 +57,15 @@ int add_two_ints(int x1, int x2); // function prototype
// Your program's entry point is a function called
// main with an integer return type.
int main(void) {
+ // your program
+}
+
+// The command line arguments used to run your program are also passed to main
+// argc being the number of arguments - your program's name counts as 1
+// argv is an array of character arrays - containing the arguments themselves
+// argv[0] = name of your program, argv[1] = first argument, etc.
+int main (int argc, char** argv)
+{
// print output using printf, for "print formatted"
// %d is an integer, \n is a newline
printf("%d\n", 0); // => Prints 0
--
cgit v1.2.3
From 53a0264029dbaaf5909110c0a390753b276ac324 Mon Sep 17 00:00:00 2001
From: Sricharan Chiruvolu
Date: Fri, 9 Oct 2015 20:30:57 +0530
Subject: Update latex.html.markdown
---
latex.html.markdown | 53 +++++++++++++++++++++++++++++++++++++++++++++++------
1 file changed, 47 insertions(+), 6 deletions(-)
diff --git a/latex.html.markdown b/latex.html.markdown
index c8f21a83..f0646941 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -3,6 +3,7 @@ language: latex
contributors:
- ["Chaitanya Krishna Ande", "http://icymist.github.io"]
- ["Colton Kohnke", "http://github.com/voltnor"]
+ - ["Sricharan Chiruvolu", "http://sricharan.xyz"]
filename: learn-latex.tex
---
@@ -25,12 +26,15 @@ getting it to behave exactly the way you want can be a bit hairy.
\documentclass[12pt]{article}
% Next we define the packages the document uses.
+% If you want to include graphics, colored text or
+% source code from a file into your document,
+% you need to enhance the capabilities of LaTeX. This is done by adding packages.
% I'm going to include the float and caption packages for figures.
\usepackage{caption}
\usepackage{float}
% We can define some other document properties too!
-\author{Chaitanya Krishna Ande \& Colton Kohnke}
+\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu}
\date{\today}
\title{Learn LaTeX in Y Minutes!}
@@ -41,6 +45,16 @@ getting it to behave exactly the way you want can be a bit hairy.
% create a title page fo us.
\maketitle
+% Most research papers have abstract, you can use the predefined commands for this.
+% This should appear in its logical order, therefore, after the top matter,
+% but before the main sections of the body.
+% This command is available in document classes article and report.
+\begin{abstract}
+ LaTex documentation written as LaTex! How novel and totally not my idea!
+\end{abstract}
+
+% Section commands are intuitive.
+% All the titles of the sections are added automatically to the table of contents.
\section{Introduction}
Hello, my name is Colton and together we're going to explore LaTeX !
@@ -69,15 +83,34 @@ One of the primary uses for LaTeX is to produce academic article or
technical papers. Usually in the realm of math and science. As such,
we need to be able to add special symbols to our paper! \\
-My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+Math has many symbols, far beyond what you can find on a keyboard.
+Set and relation symbols, arrows, operators, Greek letters to name a few. \\
+
+
+Sets and relations play a vital role in many mathematical research papers.
+Here's how you state all y that belong to X, $\forall$ x $\in$ X.
Notice how I needed to add \$ signs before and after the symbols. This is
because when writing, we are in text-mode. However, the math symbols only exist
in math-mode. We can enter math-mode from text mode with the \$ signs.
The opposite also holds true. Variable can also be rendered in math-mode. \\
-% We can also add references
-For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$,
- $b$ and $c$, where $c$ is the hypotenuse, the following holds:
+My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$.
+
+Operators are essential parts of a mathematical document: trigonometric functions
+(sin, cos, tan), logarithms and exponentials (log, exp), limits (lim) e.t.c. have
+pre-defined LaTeX commands. Let's write an equation to see how it's done: \\
+
+$\cos$ (2$\theta$) = $\cos$^2 $\theta$ - $\sin$^2 $\theta$
+
+Fractions(Numerator-denominators) can be written in these forms:
+
+% 10 / 7
+^10/_7
+
+% Relatively complex fractions can be written as
+% \frac{numerator}{denominator}
+$\frac{n!}{k!(n - k)!}$
+
% Display math with the equation 'environment'
\begin{equation} % enters math-mode
c^2 = a^2 + b^2.
@@ -88,11 +121,17 @@ For a right angled triangle (see Fig.~\ref{fig:right-triangle}) with sides $a$,
Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also
the subject of Sec.~\ref{subsec:pythagoras}.
+Summations and Integrals are written with sum and int commands:
+\begin{equation} % enters math-mode
+\sum_{i=0}^{5} f_i
+
+\int_0^\infty \mathrm{e}^{-x}\,\mathrm{d}x
+\end{equation}
\section{Figures}
Let's insert a Figure. Figure placement can get a little tricky.
-I definately have to lookup the placement options each time.
+I definitely have to lookup the placement options each time.
\begin{figure}[H]
\centering
@@ -115,6 +154,8 @@ Let's insert a Table.
\end{tabular}
\end{table}
+% \section{Hyperlinks}
+
\section{Compiling}
--
cgit v1.2.3
From bb8eeb53ef01b6bfbdf64d6f1dc067f9cf4b8f8d Mon Sep 17 00:00:00 2001
From: Andy B
Date: Fri, 9 Oct 2015 16:05:21 +0100
Subject: [xml/en] Grammar fixes
---
xml.html.markdown | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/xml.html.markdown b/xml.html.markdown
index d407512d..4d33e614 100644
--- a/xml.html.markdown
+++ b/xml.html.markdown
@@ -40,13 +40,14 @@ Unlike HTML, XML does not specify how to display or to format data, just carry i
It starts with a declaration, informing some metadata (optional).
XML uses a tree structure. Above, the root node is 'bookstore', which has
- three child nodes, all 'books'. Those nodes has more child nodes, and so on...
+ three child nodes, all 'books'. Those nodes have more child nodes (or
+ children), and so on...
- Nodes are created using open/close tags, and childs are just nodes between
+ Nodes are created using open/close tags, and children are just nodes between
the open and close tags.-->
-
+
-
+
-
+
-
```
-## Precedence
+## Precedence or Cascade
-As you noticed an element may be targetted by more than one selector.
-and may have a property set on it in more than one.
-In these cases, one of the rules takes precedence over others.
+An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one.
+
+This process is called cascading, hence the name Cascading Style Sheets.
Given the following CSS:
```css
-/*A*/
+/* A */
p.class1[attr='value']
-/*B*/
-p.class1 {}
+/* B */
+p.class1 { }
-/*C*/
-p.class2 {}
+/* C */
+p.class2 { }
-/*D*/
-p {}
+/* D */
+p { }
-/*E*/
+/* E */
p { property: value !important; }
-
```
and the following markup:
```xml
-
-
+
```
-The precedence of style is as followed:
-Remember, the precedence is for each **property**, not for the entire block.
+The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block.
-* `E` has the highest precedence because of the keyword `!important`.
- It is recommended to avoid this unless it is strictly necessary to use.
-* `F` is next, because it is inline style.
-* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
- class name `class1` + 1 attribute `attr='value'`
-* `C` is next. although it has the same specificness as `B`
- but it appears last.
-* Then is `B`
-* and lastly is `D`.
+* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage.
+* `F` is next, because it is an inline style.
+* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`.
+* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`.
+* `B` is next.
+* `D` is the last one.
## Compatibility
-Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatibility
-of what you use in CSS with your target browsers.
+Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature.
-[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
+## Resources
-To run a quick compatibility check, [Can I Use...](http://caniuse.com) is a great resource.
+* To run a quick compatibility check, [CanIUse](http://caniuse.com).
+* CSS Playground [Dabblet](http://dabblet.com/).
+* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
+* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
## Further Reading
-* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS)
-* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/)
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-* [SCSS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing
+* [CSS-Tricks](https://css-tricks.com)
--
cgit v1.2.3
From a65d0fb99ad7faa7469da576938b8d37aca6f859 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?C=C3=A9sar=20Su=C3=A1rez?=
Date: Sat, 10 Oct 2015 13:07:10 +0200
Subject: Update and fix Spanish brainfuck article
---
es-es/brainfuck-es.html.markdown | 18 ++++++++++--------
1 file changed, 10 insertions(+), 8 deletions(-)
diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown
index e33d672d..550511da 100644
--- a/es-es/brainfuck-es.html.markdown
+++ b/es-es/brainfuck-es.html.markdown
@@ -9,8 +9,10 @@ lang: es-es
---
Brainfuck (con mayúscula sólo al inicio de una oración) es un
-lenguaje de programación mínimo, computacionalmente universal
-en tamaño con sólo 8 comandos.
+lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos.
+
+Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
```
@@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
será ignorado.
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
-en cero y un apuntador en la celda actual.
+en cero y un puntero apuntando la celda actual.
Existen ocho comandos:
@@ -26,7 +28,7 @@ Existen ocho comandos:
- : Decrementa 1 al valor de la celda actual.
> : Mueve el apuntador a la siguiente celda. (a la derecha)
< : Mueve el apuntador a la celda anterior. (a la izquierda)
-. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
+. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A')
, : Lee un caracter como input y lo escribe en la celda actual.
[ : Si el valor en la celda actual es cero mueve el apuntador
hasta el primer ']' que encuentre. Si no es cero sigue a la
@@ -37,7 +39,7 @@ Existen ocho comandos:
[ y ] forman un while. Obviamente, deben estar balanceados.
-Ahora unos ejemplos de programas escritos con brainfuck.
+Estos son algunos ejemplos de programas escritos con brainfuck.
++++++ [ > ++++++++++ < - ] > +++++ .
@@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
-Ten en mente que los espacios son sólo para fines de legibilidad.
+Ten en cuenta que los espacios son sólo para fines de legibilidad.
Es lo mismo escribir el ejemplo de arriba que esto:
,[>+<-]>.
@@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
el resultado.
```
-Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
+Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
-intenta construir tu proprio intérprete de brainfuck... en brainfuck.
+puedes intentar construir tu propio intérprete de brainfuck... en brainfuck.
--
cgit v1.2.3
From 622d4485ab9efd265be83d16abbe8cb12da7934c Mon Sep 17 00:00:00 2001
From: Kara Kincaid
Date: Sat, 10 Oct 2015 08:20:03 -0400
Subject: [css/en] Added more pseudo-classes and pseudo-elements examples
---
css.html.markdown | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/css.html.markdown b/css.html.markdown
index 811767e6..4c459f7f 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -119,6 +119,19 @@ selected:link {}
/* or an input element which is focused */
selected:focus {}
+/* any element that is the first child of its parent */
+selector:first-child {}
+
+/* any element that is the last child of its parent */
+selector:last-child {}
+
+/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */
+
+/* matches a virtual first child of the selected element */
+selector::before {}
+
+/* matches a virtual last child of the selected element */
+selector::after {}
/* ####################
## PROPERTIES
--
cgit v1.2.3
From 7c2c4480600b6c817418d5ba04315bca3c5a400d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Joa=CC=83o=20Costa?=
Date: Sat, 10 Oct 2015 16:49:53 +0100
Subject: Fix compile errors of the English and French Scala tutorials
---
fr-fr/scala.html.markdown | 9 ++++++---
scala.html.markdown | 12 ++++++------
2 files changed, 12 insertions(+), 9 deletions(-)
diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown
index a43edf16..c6d06361 100644
--- a/fr-fr/scala.html.markdown
+++ b/fr-fr/scala.html.markdown
@@ -208,6 +208,7 @@ sSquared.reduce (_+_)
// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et
// sélectionne tous les éléments qui satisfont ce prédicat
List(1, 2, 3) filter (_ > 2) // List(3)
+case class Person(name: String, age: Int)
List(
Person(name = "Dom", age = 23),
Person(name = "Bob", age = 30)
@@ -217,6 +218,7 @@ List(
// Scala a une méthode foreach définie pour certaines collections
// qui prend en argument une fonction renvoyant Unit (une méthode void)
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
aListOfNumbers foreach (x => println(x))
aListOfNumbers foreach println
@@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique.
// mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus
// facile pour comprendre et pour faire la parallélisation
+i = 0
// La boucle do while
do {
println("x is still less then 10");
- x += 1
-} while (x < 10)
+ i += 1
+} while (i < 10)
// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala.
@@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com"
"Les chaînes de caractères Scala sont entourées de doubles guillements"
'a' // Un caractère de Scala
-'Les simples guillemets n'existent pas en Scala // Erreur
+// 'Les simples guillemets n'existent pas en Scala' // Erreur
"Les chaînes de caractères possèdent les méthodes usuelles de Java".length
"Il y a aussi quelques méthodes extra de Scala.".reverse
diff --git a/scala.html.markdown b/scala.html.markdown
index 7189be10..7f545196 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -6,7 +6,6 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
- ["Geoff Liu", "http://geoffliu.me"]
- ["Ha-Duong Nguyen", "http://reference-error.org"]
-filename: learn.scala
---
Scala - the scalable language
@@ -244,10 +243,11 @@ i // Show the value of i. Note that while is a loop in the classical sense -
// comprehensions above is easier to understand and parallelize
// A do while loop
+i = 0
do {
- println("x is still less than 10")
- x += 1
-} while (x < 10)
+ println("i is still less than 10")
+ i += 1
+} while (i < 10)
// Tail recursion is an idiomatic way of doing recurring things in Scala.
// Recursive functions need an explicit return type, the compiler can't infer it.
@@ -566,8 +566,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
// Implicit function parameters enable us to simulate type classes in other
// functional languages. It is so often used that it gets its own shorthand. The
// following two lines mean the same thing:
-def foo[T](implicit c: C[T]) = ...
-def foo[T : C] = ...
+// def foo[T](implicit c: C[T]) = ...
+// def foo[T : C] = ...
// Another situation in which the compiler looks for an implicit is if you have
--
cgit v1.2.3
From ae7dee12a5fef665e9c5bb3ae1ebc9eece9c7648 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Joa=CC=83o=20Costa?=
Date: Sat, 10 Oct 2015 16:51:07 +0100
Subject: [scala-pt] Fix variable names on while cycle
---
pt-pt/scala-pt.html.markdown | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown
index 270fb01e..a4c1c02b 100644
--- a/pt-pt/scala-pt.html.markdown
+++ b/pt-pt/scala-pt.html.markdown
@@ -245,10 +245,11 @@ i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico -
// paralelizar
// Um ciclo do while
+i = 0
do {
- println("x ainda é menor que 10")
- x = x + 1
-} while (x < 10)
+ println("i ainda é menor que 10")
+ i += 1
+} while (i < 10)
// A forma idiomática em Scala de definir acções recorrentes é através de
// recursão em cauda.
--
cgit v1.2.3
From 77f0219cc6fd64f9c4dbd3007fa395b2242a6e49 Mon Sep 17 00:00:00 2001
From: Ratan
Date: Sat, 10 Oct 2015 12:10:27 -0400
Subject: change String to AbstractString as per 0.4 spec
---
julia.html.markdown | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/julia.html.markdown b/julia.html.markdown
index 66329feb..7ca2d492 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -78,7 +78,7 @@ false
1 < 2 < 3 # => true
2 < 3 < 2 # => false
-# Strings are created with "
+# AbstractStrings are created with "
"This is a string."
# Character literals are written with '
@@ -314,7 +314,7 @@ end
# For loops iterate over iterables.
-# Iterable types include Range, Array, Set, Dict, and String.
+# Iterable types include Range, Array, Set, Dict, and AbstractString.
for animal=["dog", "cat", "mouse"]
println("$animal is a mammal")
# You can use $ to interpolate variables or expression into strings
@@ -550,13 +550,13 @@ super(Any) # => Any
# <: is the subtyping operator
type Lion <: Cat # Lion is a subtype of Cat
mane_color
- roar::String
+ roar::AbstractString
end
# You can define more constructors for your type
# Just define a function of the same name as the type
# and call an existing constructor to get a value of the correct type
-Lion(roar::String) = Lion("green",roar)
+Lion(roar::AbstractString) = Lion("green",roar)
# This is an outer constructor because it's outside the type definition
type Panther <: Cat # Panther is also a subtype of Cat
--
cgit v1.2.3
From 7281681a3e45e8103b771933b40920a292fc2818 Mon Sep 17 00:00:00 2001
From: Thibault iTech
Date: Sat, 10 Oct 2015 18:58:25 +0200
Subject: Added translation in french for the HAML article
---
fr-fr/haml-fr.html.markdown | 156 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 156 insertions(+)
create mode 100644 fr-fr/haml-fr.html.markdown
diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown
new file mode 100644
index 00000000..0267a380
--- /dev/null
+++ b/fr-fr/haml-fr.html.markdown
@@ -0,0 +1,156 @@
+---
+language: haml
+filename: learnhaml.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+ - ["Thibault", "https://github.com/iTech-"]
+---
+
+Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage.
+
+Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire.
+
+Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes.
+
+$ haml fichier_entree.haml fichier_sortie.html
+
+
+```haml
+/ -------------------------------------------
+/ Indentation
+/ -------------------------------------------
+
+/
+ A cause de l'importance de l'indentation sur la manière dont votre code sera
+ converti, l'indentation doit être constante à travers votre document. Un
+ simple changement d'indentation entrainera une erreur. En général, on utilise
+ deux espaces, mais ce genre de décision sur l'indentation vous appartient, du
+ moment que vous vous y tenez.
+
+/ -------------------------------------------
+/ Commentaires
+/ -------------------------------------------
+
+/ Ceci est un commentaire en Haml.
+
+/
+ Pour écrire un commentaire sur plusieurs lignes, indentez votre code
+ commenté en le commençant par un slash
+
+-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier
+
+
+/ -------------------------------------------
+/ Eléments HTML
+/ -------------------------------------------
+
+/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise
+%body
+ %header
+ %nav
+
+/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci
+
+
+
+
+
+
+/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci
+.balise
+
+/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration
+%h1 Titre contenu
+
+/ Pour écrire du contenu sur plusieurs lignes, imbriquez le
+%p
+ Ce paragraphe contient beaucoup de contenu qui pourrait
+ probablement tenir sur deux lignes séparées.
+
+/
+ Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va
+ convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple
+
+%p
+ &= "Oui & oui"
+
+/ Produira 'Oui & oui'
+
+/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant !=
+%p
+ != "Voici comment écrire une balise de paragraphe "
+
+/ Cela produira 'Voici comment écrire une balise de paragraphe '
+
+/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe
+%div.truc.machin
+
+/ ou en utilisant un hash de Ruby
+%div{:class => 'truc machin'}
+
+/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash
+%a{:href => '#', :class => 'machin', :title => 'Titre machin'}
+
+/ Pour affecter une valeur à un booléen, utilisez 'true'
+%input{:selected => true}
+
+/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash
+%div{:data => {:attribute => 'machin'}}
+
+
+/ -------------------------------------------
+/ Insérer du Ruby
+/ -------------------------------------------
+
+/
+ Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le
+ signe égal suivi du code Ruby
+
+%h1= livre.titre
+
+%p
+ = livre.auteur
+ = livre.editeur
+
+
+/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union
+- livres = ['livre 1', 'livre 2', 'livre 3']
+
+/ Ceci vous permet de faire des choses géniales comme des blocs Ruby
+- livre.shuffle.each_with_index do |livre, index|
+ %h1= livre
+
+ if livre do
+ %p Ceci est un livre
+
+/
+ Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même
+ pour Ruby.
+ L'indentation le fera pour vous.
+
+
+/ -------------------------------------------
+/ Ruby en-ligne / Interpolation en Ruby
+/ -------------------------------------------
+
+/ Inclure une variable Ruby dans une ligne en utilisant #{}
+%p Votre meilleur score est #{record}
+
+
+/ -------------------------------------------
+/ Filtres
+/ -------------------------------------------
+
+/
+ Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple
+ utiliser un filtre :javascript pour écrire du contenu en-ligne js
+
+:javascript
+ console.log('Ceci est la balise en-ligne
+
+