From bcb1b623b1db1057085982507399c62eaa053e7b Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Fri, 23 Jun 2017 13:35:19 -0700 Subject: [scala/en] Make return value example actually demonstrate issue Previously the `return z` didn't actually have any effect on the output, since the outer function just return the anon function's result directly. Updated to make the outer function do something to demonstrate the difference. Also renamed functions to make what they're doing easier to follow, and added a couple examples of behavior w/ explanations --- scala.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..e541f4b3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,16 +253,20 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def foo(x: Int): Int = { - val anonFunc: Int => Int = { z => +def addTenButMaybeTwelve(x: Int): Int = { + val anonMaybeAddTwo: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of addTenButMaybeTwelve! else z + 2 // This line is the return value of anonFunc } - anonFunc(x) // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of foo } +addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 +addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so + // last line doesn't get called and 10 is not added + ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3 From 23cee36b4c056dcd3c01676132cb9a6588fb75ad Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Thu, 29 Jun 2017 10:49:44 -0700 Subject: Update more function mentions in comments --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e541f4b3..192af953 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -258,9 +258,9 @@ def addTenButMaybeTwelve(x: Int): Int = { if (z > 5) return z // This line makes z the return value of addTenButMaybeTwelve! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonMaybeAddTwo } - anonMaybeAddTwo(x) + 10 // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of addTenButMaybeTwelve } addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 -- cgit v1.2.3 From 386c4882c849b423af907686a40af699cc663ce0 Mon Sep 17 00:00:00 2001 From: Jichao Ouyang Date: Sun, 24 Sep 2017 21:05:34 +0800 Subject: gnu make zh_cn --- zh-cn/make-cn.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 zh-cn/make-cn.html.markdown diff --git a/zh-cn/make-cn.html.markdown b/zh-cn/make-cn.html.markdown new file mode 100644 index 00000000..4a58f0b6 --- /dev/null +++ b/zh-cn/make-cn.html.markdown @@ -0,0 +1,261 @@ +--- +language: make +contributors: +- ["Robert Steed", "https://github.com/robochat"] +- ["Jichao Ouyang", "https://github.com/jcouyang"] +translators: +- ["Jichao Ouyang", "https://github.com/jcouyang"] +filename: Makefile +--- + +Makefile 用于定义如何创建目标文件, 比如如何从源码到可执行文件. 创建这一工具的目标是 +减少不必要的编译或者任务.是传说中的 Stuart Feldman 在 1976 年花了一个周末写出来的, +而今仍然使用广泛, 特别是在 Unix 和 Linux 系统上. + +虽然每个语言可能都有相应的或多或少提供 make 的功能, 比如 ruby 的 rake, node 的 gulp, broccoli +, scala 的 sbt 等等. 但是 make 的简洁与高效, 和只做一件事并做到极致的风格, 使其至今仍是无可替代的, +甚至与其他构建工具一起使用也并无冲突. + +尽管有许多的分支和变体, 这篇文章针对是标准的 GNU make. + +```make +# 这行表示注释 + +# 文件名一定要交 Makefile, 大小写区分, 使用 `make ` 生成 target +# 如果想要取别的名字, 可以用 `make -f "filename" `. + +# 重要的事情 - 只认识 TAB, 空格是不认的, 但是在 GNU Make 3.82 之后, 可以通过 +# 设置参数 .RECIPEPREFIX 进行修改 + +#----------------------------------------------------------------------- +# 初级 +#----------------------------------------------------------------------- + +# 创建一个 target 的规则非常简单 +# targets : prerequisites +# recipe +# … +# prerequisites(依赖) 是可选的, recipe(做法) 也可以多个或者不给. + +# 下面这个任务没有给 prerequisites, 只会在目标文件 file0.txt 文件不存在是跑 +file0.txt: + echo "foo" > file0.txt + # 试试 `make file0.txt` + # 或者直接 `make`, 因为第一个任务是默认任务. + # 注意: 即使是这些注释, 如果前面有 TAB, 也会发送给 shell, 注意看 `make file0.txt` 输出 + +# 如果提供 prerequisites, 则只有 prerequisites 比 target 新时会执行 +# 比如下面这个任务只有当 file1.txt 比 file0.txt 新时才会执行. +file1.txt: file0.txt + cat file0.txt > file1.txt + # 这里跟shell里的命令式一毛一样的. + @cat file0.txt >> file1.txt + # @ 不会把命令往 stdout 打印. + -@echo 'hello' + # - 意思是发生错误了也没关系. + # 试试 `make file1.txt` 吧. + +# targets 和 prerequisites 都可以是多个, 以空格分割 +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# 如果声明重复的 target, make 会给一个 warning, 后面会覆盖前面的 +# 比如重复定义 file2.txt 会得到这样的 warning +# Makefile:46: warning: overriding commands for target `file2.txt' +# Makefile:40: warning: ignoring old commands for target `file2.txt' +file2.txt: file0.txt + touch file2.txt + +# 但是如果不定义任何 recipe, 就不会冲突, 只是多了依赖关系 +file2.txt: file0.txt file3.txt + +#----------------------------------------------------------------------- +# Phony(假的) Targets +#----------------------------------------------------------------------- + +# phony targets 意思是 tagets 并不是文件, 可以想象成一个任务的名字而已. +# 因为不是文件, 无法比对是否有更新, 所以每次make都会执行. +all: maker process + +# 依赖于 phony target 的 target 也会每次 make 都执行, 即使 target 是文件 +ex0.txt ex1.txt: maker + +# target 的声明顺序并不重要, 比如上面的 all 的依赖 maker 现在才声明 +maker: + touch ex0.txt ex1.txt + +# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显示的指明哪些 targets 是 phony +.PHONY: all maker process +# This is a special target. There are several others. + +# 常用的 phony target 有: all clean install ... + +#----------------------------------------------------------------------- +# 变量与通配符 +#----------------------------------------------------------------------- + +process: file*.txt | dir/a.foo.b # 可以用通配符匹配多个文件作为prerequisites + @echo $^ # $^ 是 prerequisites + @echo $@ # $@ 代表 target, 如果 target 为多个, $@ 代表当前执行的那个 + @echo $< # $< prerequisite 中的第一个 + @echo $? # $? 需要更新的 prerequisite 文件列表 + @echo $+ # $+ 所有依赖, 包括重复的 + @echo $| # $| 竖线后面的 order-only prerequisites + +a.%.b: + @echo $* # $* match 的target % 那部分, 包括路径, 比如 `make dir/a.foo.b` 会打出 `dir/foo` + +# 即便分开定义依赖, $^ 依然能拿到 +process: ex1.txt file0.txt +# 非常智能的, ex1.txt 会被找到, file0.txt 会被去重. + +#----------------------------------------------------------------------- +# 模式匹配 +#----------------------------------------------------------------------- + +# 可以让 make 知道如何转换某些文件到别格式 +# 比如 从 svg 到 png +%.png: %.svg + inkscape --export-png $^ + +# 一旦有需要 foo.png 这个任务就会运行 + +# 路径会被忽略, 所以上面的 target 能匹配所有 png +# 但是如果加了路径, make 会找到最接近的匹配, 如果 +# make small/foo.png (在这之前要先有 small/foo.svg 这个文件) +# 则会匹配下面这个规则 +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +%.png: %.svg + @echo 重复定义会覆盖前面的, 现在 inkscape 没用了 + +# make 已经有一些内置的规则, 比如从 *.c 到 *.o + +#----------------------------------------------------------------------- +# 变量 +#----------------------------------------------------------------------- +# 其实是宏 macro + +# 变量都是字符串类型, 下面这俩是一样一样的 + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # 这个会被蠢蠢的解析成 $(n)ame. + @echo \"$(name3)\" # 为声明的变量或扩展成空字符串. + @echo $(name4) + @echo $(name5) +# 你可以通过4种方式设置变量. +# 按以下顺序由高到低: +# 1: 命令行参数. 比如试试 `make echo name3=JICHAO` +# 2: Makefile 里面的 +# 3: shell 中的环境变量 +# 4: make 预设的一些变量 + +name4 ?= Jean +# 问号意思是如果 name4 被设置过了, 就不设置了. + +override name5 = David +# 用 override 可以防止命令行参数设置的覆盖 + +name4 +=grey +# 用加号可以连接 (中间用空格分割). + +# 在依赖的地方设置变量 +echo: name2 = Sara2 + +# 还有一些内置的变量 +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# 变量 2 +#----------------------------------------------------------------------- + +# 加个冒号可以声明 Simply expanded variables 即时扩展变量, 即只在声明时扩展一次 +# 之前的等号声明时 recursively expanded 递归扩展 + +var := hello +var2 := $(var) hello + +# 这些变量会在其引用的顺序求值 +# 比如 var3 声明时找不到 var4, var3 会扩展成 `and good luck` +var3 := $(var4) and good luck +# 但是一般的变量会在调用时递归扩展, 先扩展 var5, 再扩展 var4, 所以是正常的 +var5 = $(var4) and good luck +var4 := good night + +echoSEV: + @echo $(var) + @echo $(var2) + @echo $(var3) + @echo $(var4) + @echo $(var5) + +#----------------------------------------------------------------------- +# 函数 +#----------------------------------------------------------------------- + +# make 自带了一些函数. +# wildcard 会将后面的通配符变成一串文件路径 +all_markdown: + @echo $(wildcard *.markdown) +# patsubst 可以做替换, 比如下面会把所有 markdown +# 后缀的文件重命名为 md 后缀 +substitue: * + @echo $(patsubst %.markdown,%.md,$* $^) + +# 函数调用格式是 $(func arg0,arg1,arg2...) + +# 试试 +ls: * + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# 可以用 include 引入别的 Makefile 文件 +# include foo.mk + +sport = tennis +# 一些逻辑语句 if else 什么的, 顶个写 +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# 还有 ifneq, ifdef, ifndef + +foo = true + +# 不只是 recipe, 还可以写在外面哟 +ifdef $(foo) +bar = 'bar' +endif + +hellobar: + @echo bar +``` + +### 资源 + ++ GNU Make 官方文档 [HTML](https://www.gnu.org/software/make/manual/) [PDF](https://www.gnu.org/software/make/manual/make.pdf) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From 24025fc252a3b4fff3d72572906ccfa6ba20d612 Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 15 Oct 2017 17:33:53 +0200 Subject: add Hungarian translation of Python entry --- hu-hu/python-hu.html.markdown | 816 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 816 insertions(+) create mode 100644 hu-hu/python-hu.html.markdown diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/python-hu.html.markdown new file mode 100644 index 00000000..9b55f8e2 --- /dev/null +++ b/hu-hu/python-hu.html.markdown @@ -0,0 +1,816 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learnpython-hu.py +lang: hu-hu +--- + +A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az +egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem +bele. Tulajdonképpen futtatható pszeudokód. + +Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) +vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen. + +Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve +általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz +támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az +ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/) +ajánlott. + +Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x +verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. +A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami +Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. + +```python + +# Az egysoros kommentek kettőskereszttel kezdődnek + +""" Többsoros stringeket három darab " közé + fogva lehet írni, ezeket gyakran használják + több soros kommentként. +""" + +#################################################### +# 1. Egyszerű adattípusok és operátorok +#################################################### + +# Használhatsz számokat +3 # => 3 + +# Az alapműveletek meglepetésektől mentesek +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része +# lesz az eredmény +5 / 2 # => 2 + +# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk +2.0 # Ez egy float +11.0 / 4.0 # => 2.75 áh... máris jobb + +# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # floatok esetén is +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Ha importáljuk a division modult (ld. 6. Modulok rész), +# akkor a '/' jellel pontos osztást tudunk végezni. +from __future__ import division + +11 / 4 # => 2.75 ...sima osztás +11 // 4 # => 2 ...egész osztás + +# Modulo művelet +7 % 3 # => 1 + +# Hatványozás (x az y. hatványra) +2 ** 4 # => 16 + +# A precedencia zárójelekkel befolyásolható +(1 + 3) * 2 # => 8 + +# Logikai operátorok +# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes +True and False # => False +False or True # => True + +# A logikai operátorok egészeken is használhatóak +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Negálni a not kulcsszóval lehet +not True # => False +not False # => True + +# Egyenlőségvizsgálat == +1 == 1 # => True +2 == 1 # => False + +# Egyenlőtlenség != +1 != 1 # => False +2 != 1 # => True + +# További összehasonlítások +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Az összehasonlítások láncolhatóak! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Stringeket " vagy ' jelek közt lehet megadni +"Ez egy string." +'Ez egy másik string.' + +# A stringek összeadhatóak! +"Hello " + "world!" # => "Hello world!" +# '+' jel nélkül is összeadhatóak +"Hello " "world!" # => "Hello world!" + +# ... illetve szorozhatóak +"Hello" * 3 # => "HelloHelloHello" + +# Kezelhető karakterek indexelhető listájaként +"This is a string"[0] # => 'T' + +# A string hosszát a len függvény adja meg +len("This is a string") # => 16 + +# String formázáshoz a % jel használható +# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog +# kerülni, de azért jó tudni, hogyan működik. +x = 'alma' +y = 'citrom' +z = "A kosárban levő elemek: %s és %s" % (x, y) + +# A string formázás újabb módja a format metódus használatával történik. +# Jelenleg ez a javasolt megoldás. +"{} egy {} szöveg".format("Ez", "helytartó") +"A {0} pedig {1}".format("string", "formázható") +# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. +"{name} kedvence a {food}".format(name="Bob", food="lasagna") + +# None egy objektum +None # => None + +# A None-nal való összehasonlításhoz ne használd a "==" jelet, +# használd az "is" kulcsszót helyette +"etc" is None # => False +None is None # => True + +# Az 'is' operátor objektum egyezést vizsgál. +# Primitív típusok esetén ez nem túl hasznos, +# objektumok esetén azonban annál inkább. + +# Bármilyen objektum használható logikai kontextusban. +# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): +# - None +# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) +# - üres sorozatok (pl. '', (), []) +# - üres konténerek (pl., {}, set()) +# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, +# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) +bool(0) # => False +bool("") # => False + + +#################################################### +# 2. Változók és kollekciók +#################################################### + +# Létezik egy print utasítás +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Így lehet egyszerűen bemenetet kérni a konzolról: +input_string_var = raw_input( + "Enter some data: ") # Visszatér a megadott stringgel +input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként +# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni +# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve + +# A változókat nem szükséges a használat előtt deklarálni +some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas +some_var # => 5 + +# Érték nélküli változóra hivatkozás hibát dob. +# Lásd a Control Flow szekciót a kivételkezelésről. +some_other_var # name error hibát dob + +# az if használható kifejezésként +# a C nyelv '?:' ternáris operátorával egyenértékűen +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# A listákban sorozatok tárolhatóak +li = [] +# Már inicializáláskor megadhatóak elemek +other_li = [4, 5, 6] + +# A lista végére az append metódus rak új elemet +li.append(1) # li jelenleg [1] +li.append(2) # li jelenleg [1, 2] +li.append(4) # li jelenleg [1, 2, 4] +li.append(3) # li jelenleg [1, 2, 4, 3] +# A végéről a pop metódus távolít el elemet +li.pop() # => 3 és li jelenleg [1, 2, 4] +# Rakjuk vissza +li.append(3) # li jelenleg [1, 2, 4, 3], újra. + +# A lista elemeket tömb indexeléssel lehet hivatkozni +li[0] # => 1 +# A már inicializált értékekhez a = jellel lehet új értéket rendelni +li[0] = 42 +li[0] # => 42 +li[0] = 1 # csak visszaállítjuk az eredeti értékére +# Így is lehet az utolsó elemre hivatkozni +li[-1] # => 3 + +# A túlindexelés eredménye IndexError +li[4] # IndexError hibát dob + +# A lista részeit a slice szintaxissal lehet kimetszeni +# (Matekosoknak ez egy zárt/nyitott intervallum.) +li[1:3] # => [2, 4] +# A lista eleje kihagyható így +li[2:] # => [4, 3] +# Kihagyható a vége +li[:3] # => [1, 2, 4] +# Minden második elem kiválasztása +li[::2] # =>[1, 4] +# A lista egy másolata, fordított sorrendben +li[::-1] # => [3, 4, 2, 1] +# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek +# li[start:end:step] + +# Listaelemek a "del" paranccsal törölhetőek +del li[2] # li jelenleg [1, 2, 3] + +# A listák összeadhatóak +li + other_li # => [1, 2, 3, 4, 5, 6] +# Megjegyzés: az eredeti li és other_li értékei változatlanok + +# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal +li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] + +# Egy elem első előfordulásának eltávolítása +li.remove(2) # li jelenleg [1, 3, 4, 5, 6] +li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában + +# Elemek beszúrhatóak tetszőleges helyre +li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét + +# Egy elem első előfordulási helye +li.index(2) # => 1 +li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában + +# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető +1 in li # => True + +# A lista hossza a "len()" függvénnyel +len(li) # => 6 + +# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hibát dob + +# Az összes lista-műveletet ezeken is használható +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Az N-esek (és listák) kicsomagolhatóak külön változókba +a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 +d, e, f = 4, 5, 6 # a zárójel elhagyható +# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik +g = 4, 5, 6 # => (4, 5, 6) +# Nézd, milyen egyszerű két értéket megcserélni +e, d = d, e # d most már 5 és az e 4 + +# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók +empty_dict = {} +# Ez pedig rögtön értékekkel van inicializálva +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Egy dictionary értékei [] jelek közt indexelhetőek +filled_dict["one"] # => 1 + +# A "keys()" metódus visszatér a kulcsok listájával +filled_dict.keys() # => ["three", "two", "one"] +# Megjegyzés: egy dictionary párjainak sorrendje nem garantált +# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. + +# Az értékek listája a "values()" metódussal kérhető le +filled_dict.values() # => [3, 2, 1] +# ld. a fenti megjegyzést az elemek sorrendjéről. + +# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben +"one" in filled_dict # => True +1 in filled_dict # => False + +# Nem létező kulcs hivatkozása KeyError hibát dob +filled_dict["four"] # KeyError + +# A "get()" metódus használatával elkerülhető a KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Megjegyzés: ettől még filled_dict.get("four") => None +# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) + +# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: +filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 + +# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva +filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re +filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 + +# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat +empty_set = set() +# Inicializáljuk ezt a halmazt néhány elemmel +some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) + +# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet +another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) + +# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Új halmaz-elemek hozzáadása +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Halmaz metszés a & operátorral +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Halmaz unió | operátorral +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Halmaz különbség - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Szimmetrikus differencia ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit +{1, 2} >= {1, 2, 3} # => False + +# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak +{1, 2} <= {1, 2, 3} # => True + +# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. Control Flow +#################################################### + +# Legyen egy változónk +some_var = 5 + +# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! +# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" +if some_var > 10: + print "some_var nagyobb, mint 10." +elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. + print "some_var kisebb 10-nél" +else: # Ez sem kötelező. + print "some_var kereken 10." + +""" +For ciklusokkal végigiterálhatunk listákon +a kimenet: + A(z) kutya emlős + A(z) macska emlős + A(z) egér emlős +""" +for animal in ["kutya", "macska", "egér"]: + # A {0} kifejezéssel formázzuk a stringet, ld. korábban. + print "A(z) {0} emlős".format(animal) + +""" +"range(number)" visszatér számok listájával 0-től number-ig +a kimenet: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" visszatér a lower és upper közti számok listájával +a kimenet: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +A while ciklus a feltétel hamissá válásáig fut. +a kimenet: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Rövidítés az x = x + 1 kifejezésre + +# A kivételek try/except blokkokkal kezelhetőek + +# Python 2.6-tól felfele: +try: + # A "raise" szóval lehet hibát dobni + raise IndexError("Ez egy index error") +except IndexError as e: + pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. +except (TypeError, NameError): + pass # Ha szükséges, egyszerre több hiba típus is kezelhető +else: # Az except blokk után opcionálisan megadható + print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák +finally: # Mindenképpen lefut + print "Itt felszabadíthatjuk az erőforrásokat például" + +# Az erőforrások felszabadításához try/finally helyett a with használható +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +# 4. Függvények +#################################################### + +# A "def" szóval hozhatunk létre új függvényt +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # A return szóval tudunk értékeket visszaadni + + +# Így hívunk függvényt paraméterekkel +add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 + +# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt +add(y=6, x=5) # Ez esetben a sorrendjük nem számít + + +# Változó számú paramétert fogadó függvény így definiálható. +# A * használatával a paramétereket egy N-esként kapjuk meg. +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Változó számú nevesített paramétert fogadó függvény is megadható, +# a ** használatával a paramétereket egy dictionary-ként kapjuk meg +def keyword_args(**kwargs): + return kwargs + + +# Nézzük meg, mi történik +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# A két módszer egyszerre is használható +def all_the_args(*args, **kwargs): + print args + print kwargs + + +""" +all_the_args(1, 2, a=3, b=4) kimenete: + (1, 2) + {"a": 3, "b": 4} +""" + +# Függvények hívásakor a fenti args és kwargs módszerek inverze használható +# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) +all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) +all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) + + +# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, +# a * illetve ** operátorokkal kifejtve +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Függvény scope +x = 5 + + +def set_x(num): + # A lokális x változó nem ugyanaz, mint a globális x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # a globális x-et 6-ra állítjuk + print x # => 6 + + +set_x(43) +set_global_x(6) + + +# A pythonban a függvény elsőrendű (ún. "first class") típus +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Névtelen függvények is definiálhatóak +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Léteznek beépített magasabb rendű függvények +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# halmaz és dictionary képzők is léteznek +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. Osztályok +#################################################### + +# Az object osztály egy alosztályát képezzük +class Human(object): + # Osztály szintű mező: az osztály összes példányában azonos + species = "H. sapiens" + + # Ez a függvény meghívódik az osztály példányosításakor. + # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python + # előre definiált, a nyelv által belsőleg használt, de a felhasználó által + # is látható objektumok és mezők neveire. + # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! + def __init__(self, name): + # A paramétert értékül adjuk a példány name attribútumának + self.name = name + + # Inicializálunk egy mezőt + self.age = 0 + + # Példány metódus. Minden metódus első paramétere a "self", a példány maga + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Egy osztálymetódus az osztály összes példány közt meg van osztva. + # Hívásukkor az első paraméter mindig a hívó osztály. + @classmethod + def get_species(cls): + return cls.species + + # Egy statikus metódus osztály és példányreferencia nélkül hívódik + @staticmethod + def grunt(): + return "*grunt*" + + # Egy property jelölésű függvény olyan, mint egy getter. + # Használatával az age mező egy csak-olvasható attribútummá válik. + @property + def age(self): + return self._age + + # Így lehet settert megadni egy mezőhöz + @age.setter + def age(self, age): + self._age = age + + # Így lehet egy mező törlését engedélyezni + @age.deleter + def age(self): + del self._age + + +# Példányosítsuk az osztályt +i = Human(name="Ian") +print i.say("hi") # kimenet: "Ian: hi" + +j = Human("Joel") +print j.say("hello") # kimenet: "Joel: hello" + +# Hívjuk az osztály metódusunkat +i.get_species() # => "H. sapiens" + +# Változtassuk meg az osztály szintű attribútumot +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Hívjuk meg a statikus metódust +Human.grunt() # => "*grunt*" + +# Adjunk új értéket a mezőnek +i.age = 42 + +# Kérjük le a mező értékét +i.age # => 42 + +# Töröljük a mezőt +del i.age +i.age # => AttributeError hibát dob + +#################################################### +# 6. Modulok +#################################################### + +# Modulokat így lehet importálni +import math + +print math.sqrt(16) # => 4 + +# Lehetséges csak bizonyos függvényeket importálni egy modulból +from math import ceil, floor + +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Egy modul összes függvénye is importálható +# Vigyázat: ez nem ajánlott. +from math import * + +# A modulok nevei lerövidíthetőek +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Meggyőződhetünk róla, hogy a függvények valóban azonosak +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# A Python modulok egyszerű fájlok. +# Írhatsz sajátot és importálhatod is. +# A modul neve azonos a tartalmazó fájl nevével. + +# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. +import math + +dir(math) + + +# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos +# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. +# A lokális mappa prioritást élvez a beépített könyvtárak felett. + + +#################################################### +# 7. Haladóknak +#################################################### + +# Generátorok +# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. + +# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, +# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk +# ezt a nagy listát a ciklus vezérléséhez. +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, +# amikor azt kérik tőle +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. +# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak +# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén +# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a +# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` +# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük +# - esetünkben a ciklus következő iterációjakor + +# A lista képzéshez hasonlóan generátor képzőket is használhatunk +# ("generator comprehensions"). +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # kimenet: -1 -2 -3 -4 -5 + +# Egy generátor összes generált elemét listaként is elkérhetjük: +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Dekorátorok +# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. +# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény +# kimenetébe beszúrja az 'Apple' elemet. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# A kimenet tartalmazza az 'Apple' elemet: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# Ebben a példában a beg dekorátorral látjuk el a say függvényt. +# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor +# megváltoztatja az eredmény mondatot. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Még több érdekel? + +### Ingyenes online tartalmak + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/) + +### Könyvek + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From b5a681fd6b159a5aece7e318ce01637fff3965f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20J=C3=BCrges?= Date: Wed, 18 Oct 2017 18:20:12 +0200 Subject: dynamic programming de translation --- de-de/dynamic-programming-de.html.markdown | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 de-de/dynamic-programming-de.html.markdown diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown new file mode 100644 index 00000000..d663400f --- /dev/null +++ b/de-de/dynamic-programming-de.html.markdown @@ -0,0 +1,54 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Henrik Jürges", "http://github.com/santifa"] +lang: de-de +--- + +# Dynamische Programmierung + +## Einführung +Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung einer bestimmten Klasse von Problemen verwendet wird. +Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu vermeiden, das gleiche Problem noch einmal zu lösen. + +Denken Sie immer daran! +"Diejenigen, die sich nicht an die Vergangenheit erinnern können, sind dazu verdammt, sie zu wiederholen." + +## Wege zur Lösung solcher Probleme + +1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr intuitiv. Er wird als Memoization bezeichnet. + +2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. Dies wird als Dynamische Programmierung bezeichnet. + +## Ein Beispiel für Dynamische Programmierung + +Das Problem mit der längsten ansteigenden Subsequenz besteht darin, die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden. +Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`, müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j a[j] and LS[i] Date: Wed, 18 Oct 2017 18:23:39 +0200 Subject: fixed line length --- de-de/dynamic-programming-de.html.markdown | 49 ++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index d663400f..801d2514 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -11,28 +11,51 @@ lang: de-de # Dynamische Programmierung ## Einführung -Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung einer bestimmten Klasse von Problemen verwendet wird. -Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu vermeiden, das gleiche Problem noch einmal zu lösen. +Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung +einer bestimmten Klasse von Problemen verwendet wird. +Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe +gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu +vermeiden, das gleiche Problem noch einmal zu lösen. Denken Sie immer daran! -"Diejenigen, die sich nicht an die Vergangenheit erinnern können, sind dazu verdammt, sie zu wiederholen." +"Diejenigen, die sich nicht an die Vergangenheit erinnern können, +sind dazu verdammt, sie zu wiederholen." ## Wege zur Lösung solcher Probleme -1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr intuitiv. Er wird als Memoization bezeichnet. +1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. +Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die +gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und +speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr +intuitiv. Er wird als Memoization bezeichnet. -2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. Dies wird als Dynamische Programmierung bezeichnet. +2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher +Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der +Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird +sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. +Dies wird als Dynamische Programmierung bezeichnet. ## Ein Beispiel für Dynamische Programmierung -Das Problem mit der längsten ansteigenden Subsequenz besteht darin, die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden. -Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`, müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j Date: Wed, 18 Oct 2017 23:55:43 -0700 Subject: Added lambda calculus --- lambda-calculus.html.markdown | 121 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 lambda-calculus.html.markdown diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown new file mode 100644 index 00000000..6103c015 --- /dev/null +++ b/lambda-calculus.html.markdown @@ -0,0 +1,121 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] +--- + +# Lambda Calculus + +Lambda calculus (λ-calculus), originally created by +[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +is the world's smallest programming language. +Despite not having numbers, strings, booleans, or any non-function datatype, +lambda calculus can be used to represent any Turing Machine! + +Lambda calculus is composed of 3 elements: **variables**, **functions**, and +**applications**. + + +| Name | Syntax | Example | Explanation | +|-------------|------------------------------------|-----------|-----------------------------------------------| +| Variable | `` | `x` | a variable named "x" | +| Function | `λ.` | `λx.x` | a function with parameter "x" and body "x" | +| Application | `` | `(λx.x)a` | calling the function "λx.x" with argument "a" | + +The most basic function is the identity function: `λx.x` which is equivalent to +`f(x) = x`. The first "x" is the function's argument, and the second is the +body of the function. + +## Free vs. Bound Variables: + +- In the function `λx.x`, "x" is called a bound variable because it is both in +the body of the function and a parameter. +- In `λx.y`, "y" is called a free variable because it is never declared before hand. + +## Evaluation: + +Evaluation is done via +[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +which is essentially lexically-scoped substitution. + +When evaluating the +expression `(λx.x)a`, we replace all occurences of "x" in the function's body +with "a". + +- `(λx.x)a` evaluates to: `a` +- `(λx.y)a` evaluates to: `y` + +You can even create higher-order functions: + +- `(λx.(λy.x))a` evaluates to: `λy.a` + +Although lambda calculus traditionally supports only single parameter +functions, we can create multi-parameter functions using a technique called +[currying](https://en.wikipedia.org/wiki/Currying). + +- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = x(y(z))` + +Sometimes `λxy.` is used interchangeably with: `λx.λy.` + +---- + +It's important to recognize that traditional **lambda calculus doesn't have +numbers, characters, or any non-function datatype!** + +## Boolean Logic: + +There is no "True" or "False" in lambda calculus. There isn't even a 1 or 0. + +Instead: + +`T` is represented by: `λx.λy.x` + +`F` is represented by: `λx.λy.y` + +First, we can define an "if" function `λbtf` that +returns `t` if `b` is True and `f` if `b` is False + +`IF` is equivalent to: `λb.λt.λf.b t f` + +Using `IF`, we can define the basic boolean logic operators: + +`a AND b` is equivalent to: `λab.IF a b F` + +`a OR b` is equivalent to: `λab.IF a T b` + +`a NOT b` is equivalent to: `λa.IF a F T` + +*Note: `IF a b c` is essentially saying: `IF(a(b(c)))`* + +## Numbers: + +Although there are no numbers in lambda calculus, we can encode numbers using +[Church numerals](https://en.wikipedia.org/wiki/Church_encoding). + +For any number n: n = λf.fn so: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +To increment a Church numeral, +we use the successor function `S(n) = n + 1` which is: + +`S = λn.λf.λx.f((n f) x)` + +Using successor, we can define add: + +`ADD = λab.(a S)n` + +**Challenge:** try defining your own multiplication function! + +## For more advanced reading: + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file -- cgit v1.2.3 From 35c2d3d242baed6a29d9d67d2db81ed0e02047ae Mon Sep 17 00:00:00 2001 From: Jeroen Deviaene Date: Thu, 19 Oct 2017 14:32:55 +0200 Subject: Added dutch translation for html --- nl-nl/html-nl.html.markdown | 97 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 nl-nl/html-nl.html.markdown diff --git a/nl-nl/html-nl.html.markdown b/nl-nl/html-nl.html.markdown new file mode 100644 index 00000000..612e9c37 --- /dev/null +++ b/nl-nl/html-nl.html.markdown @@ -0,0 +1,97 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] + - ["Jeroen Deviaene", "https://github.com/jerodev"] +--- + +HTML staat voor HyperText Markup Language. +Het is een taal die je toe staat pagina's te maken op het World Wide Web. +Het is een opmaak taal, dit staat de gebruiker toe om webpagina's te maken in code en zo aan te duiden hoe de pagina moet weergegeven worden. +Eigenlijk zijn html files zelfs simpele tekst bestanden. +Wat is deze opmaak? Het is een manier om de structuur en data op de pagina weer te geven met speciale html tags. +Deze tags dienen om de betekenis te geven aan de tekst die het bevat. +Zoals vele computer talen heeft html vele verschillende versies. Hier zullen we HTML5 bespreken. + +**Merk op:** Je kan de verschillende tags en elementen testen terwijl je door de tutorial gaat met een website zoals [codepen](http://codepen.io/pen/), zo kan je de effecten hier van live zien. +Dit artikel gaat vooral over de HTML syntax en enkele handige tips + + +```html + + + + + + + + + + Mijn Website + + +

Hello, world!

+ Neem een kijkje op deze link +

Dit is een paragraaf.

+

Dit is nog een paragraaf.

+
    +
  • Dit is een item in een niet genummerde lijst
  • +
  • Dit is nog zo een item
  • +
  • En dit is het laatste item van de lijst
  • +
+ + + + + + + + + + + + + + + + + + + + + Mijn Website + + + + + + + +

Hello, world!

+ + Neem een kijkje op deze link +

This is a paragraph.

+

This is another paragraph.

+
    + +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + +``` + +## Gebruik + +HTML wordt altijd opgeslagen in bestanden die eindigen in `.html`. + +## Meer weten + +* [wikipedia](https://nl.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 5c8c0186dcb8629396e5c82335cb7e9695ed8eec Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Thu, 19 Oct 2017 18:31:21 -0200 Subject: Translate latex to pt_BR --- pt-br/latex-pt.html.markdown | 291 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 pt-br/latex-pt.html.markdown diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown new file mode 100644 index 00000000..a9ed566e --- /dev/null +++ b/pt-br/latex-pt.html.markdown @@ -0,0 +1,291 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] + - ["Svetlana Golubeva", "https://attillax.github.io/"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br +filename: learn-latex-pt.tex +--- + +```tex +% Todas as linhas de comentários começam com % +% Não existem comentários multilinhas + +$ LaTeX não é um programa processador de textos "Visual" como +% MS Word ou OpenOffice Writer + +$ Todo comando LaTeX começa com uma barra invertida (\) + +% Documentos LaTeX começam com a definição do tipo que será % compilado +% Os tipos de documento podem ser livro, relatório, apresentação, etc. +% As opções para um documento aparecem entre [] chaves. Nesse caso +% está especificado que queremos o tamanho da fonte em 12pt. +\documentclass[12pt]{article} + +% Em seguida definimos os pacotes que o documento usa. +% Se você quiser incluir gráficos, texto colorido, ou código fonte de outra +% linguagem em outro arquivo em seu documento, você precisa ampliar as +% capacidade do LaTeX. Isso é feito adicionando-se pacotes. +% Serão incluídos os pacotes float e caption para imagens e hyperref +% para links. +\usepackage{caption} +\usepackage{float} +\usepackage{hyperref} + +% Para poder usar caracteres acentuados, use o seguinte pacote: +\usepackage[utf8]{inputenc} + +% Podemos definir algumas outras propriedades do documento também! +\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\ +Svetlana Golubeva} +\date{\today} +\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!} + +% Agora estamos pronto para começar o documento +% Tudo antes dessa linha é chamado "preâmbulo". +\begin{document} +% Se informarmos os campos author (autores), date (data), "title" (título), +% LaTeX poderá cria uma página inicial para nós. +\maketitle +% Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso, +% o documento deve ser compilado duas vezes, para que tudo apareça na ordem +% correta. +% É uma voa prática separar a tabela de conteúdo do corpo do documento. Para +% isso usa-se o comando \newpage +\newpage +\tableofcontents + +\newpage + +% Muitos artigos de pesquisa possuem um resumo, e pode-se isar comandos +% predefinidos para isso. +% Isso deve aparecer em sua ordem lógica, portanto, após o topo, +% mas antes das seções principais do corpo. +% Esse comando está disponível para os documentos do tipo artigo (article) +% e relatório (report). +\begin{abstract} + Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original! +\end{abstract} + +% Comandos para seções são intuitivos. +% Todos os títulos de seção são adicionados automaticamente à tabela de conteúdo. +\section{Introdução} +Olá, meu nome é Colton e juntos estamos explorando o mundo do \LaTeX! + +\section{Outra seção} +Esse é o texto para outra seção. Penso que precisamos de uma subseção. + +\subsection{Isso é uma subseção} % Subseções também são intuitivas. +Penso que precisamos de mais uma + +\subsubsection{Pythagoras} +Muito melhor agora. +\label{subsec:pythagoras} + +% Ao usar o asterisco nós impedimos a numeração automática. +% Isso funciona para outros comandos \LaTeX também. +\section*{Essa é uma seção não numerada} +Afinal nem todas as seções precisam ser numeradas! + +\section{Algumas notas sobre texto} +%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço. +\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve +ser posto. Se +uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash +\hspace{1pt} ao código de seu documento. \\ + +\section{Listas} +Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras +amanhã, então façamos uma lista de compras. +\begin{enumerate} % Isso cria o bloco "enumerate". + % \item faz com que o enumerate incremente + \item Salada. + \item 27 melancias. + \item Uma lebre. + % pode-se também sobrescrever o número do item usando [] + \item[quantas?] Pistolas de água médias. + + Não é um item da lista, mas faz parte do bloco enumerate. + + \end{enumerate} % Todos os blocos devem ter um final (end{}). + +\section{Matemática} + +Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos +acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é +necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\ + +A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado; +símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas +para mencionar alguns.\\ + +Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática. +Aqui está como você pode indicar como todo x que pertence +a X, $\forall$ x $\in$ X. \\ +% Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos. +% Isso é porque quando escrevendo, estamos em modo texto. +% Mas os símbolos de matemática só existem no modo matemática. +% Podemos entrar no modo matemática a partir do modo texto com os símbolos $. +% O oposto também pode ocorrer. Variáveis podem ser renderizadas no modo +% matemática. +% Também podemos entrar no modo matemática com \[\] + +\[a^2 + b^2 = c^2 \] + +Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$. +Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\ + +Operadores são parte essencial de um documento sobre matemática: +funções trigonométricas ($\sin$, $\cos$, $\tan$), +logaritmo e exponencial ($\log$, $\exp$), +limites ($\lim$), etc. +possuem comandos pré-definidos em LaTex. +Vamos escrever uma equação para ver como se faz: +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ + +Frações (numerador/denominador) podem ser escritas dessa forma: + +% 10 / 7 +$$ ^{10}/_{7} $$ + +% Frações relativamente complexas podem ser escritas como +% \frac{numerator}{denominator} +$$ \frac{n!}{k!(n - k)!} $$ \\ + +Também podemos escrever equações em um ``bloco de equação''. + +% Apresenta matemática com o 'bloco' equação +\begin{equation} % entra no modo matemática + c^2 = a^2 + b^2. + \label{eq:pythagoras} % para referência + \end{equation} % toda declaração \begin precisa de uma declaração end + +Podemos então referenciar nossa nova equação! +A equação~\ref{eq:pythagoras} é também conhecida como Teorema de Pitágoras que é +também assunto da Seção~\ref{subsec:pythagoras}. Muitas coisas podem ser +rotuladas: figuras, equações, seções, etc. + +Somatórios e Integrais são escritas com os comandos sum e int: + +% Alguns compiladores LaTeX irão reclamar se existirem linhas em branco +% em um bloco de equação. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuras} + +Insiramos uma Figura. O local para colocar a figura pode ser difícil +de determinar. Eu tenho sempre que verificar as opções toda vez. + +\begin{figure}[H] % H aqui é uma opção para o local da figura. + \centering % centra a figura na página + % Inclui uma figura com escala de 0.8 do tamanho da página. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Comentado para propósitos de compilação. Por favor, use sua imaginação. + \caption{Triângulo retângulo com lados $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabelas} +Também podemos incluir tabelas da mesma forma que figuras. + +\begin{table}[H] + \caption{Título para a Tabela.} + % os argumentos {} abaixo descrevem como cada linha da tabela é desenhada. + % Aqui também, Preciso ver isso. Toda. E. Cada. Vez. + \begin{tabular}{c|cc} + Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por & + \hline % uma linha horizontal + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)} +Digamos que precisamos incluir algum código dentro do nosso +documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt} +não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos +isso com o bloco verbatim. + +% Existem outros pacotes (por exemplo, minty, lstlisting, etc.) +% mas verbatim é o básico +\begin{verbatim} + print("Hello World!") + a%b; % olha só! Podemos usar os sinais % no bloco verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compilando} + +Imagino que agora você esteja pensando como compilar esse fantástico documento +e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf. +(sim, esse documento é compilável). \\ + +Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos: + \begin{enumerate} + \item Escrever o documento em texto puro (o ``código fonte''). + \item Compilar o código fonte para gerar um pdf. + Os passos para compilar se parecem (em Linux) com: \\ + \begin{verbatim} + > pdflatex learn-latex.tex + \end{verbatim} + \end{enumerate} + +Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo +sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por +completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar +referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o +passo 2 várias vezes, para gerar arquivos *.aux intermediários.}. +% É assim que você adiciona notas de rodapé em seus documentos! + +Você escreve toda a informação de formatação em texto puro, no passo 1. O +momento da compilação no passo 2 é responsável por produzir o documento no +formato que você definiu no passo 1. + +\section{Links} +Nós podemos inserir links em nosso documento. Para isso nós necessitamos incluir +o pacote hyperref no preâmbulo com o comando: +\begin{verbatim} + \usepackage{hyperref} +\end{verbatim} + +Existem dois tipos principais de links: URL visíveis \\ +\url{https://learnxinyminutes.com/docs/latex/}, ou +\href{https://learnxinyminutes.com/docs/latex/}{um texto alternativo} +% Você não pode adicionar espaços extras ou símbolos especiais no texto +% alternativo, pois isso causará problemas na compilação. + +Esse pacote também produz uma lista de thumbnails no documento pdf gerado e +ativa os links na tabela de conteúdo. + +\section{End} + +Por enquanto é isso! + +% Frequentemente você precisa de uma seção de referências em seu documento. +% A forma mais fácil de configurá-la é usando uma seção de bibliografia +\begin{thebibliography}{1} + % como em outras listas, o comando \bibitem pode ser usado para itens da lista + % cada entrada pode ser citada diretamente no corpo do texto + \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em +https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} +\end{thebibliography} + +% end the document +\end{document} +``` + +## Mais sobre 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 2e218f5dfbc2015cc429e9ae8e3a0e38c0e9098b Mon Sep 17 00:00:00 2001 From: Oleg Gromyak Date: Sat, 28 Oct 2017 20:13:12 +0300 Subject: [python/ua] Add Ukrainian translation --- uk-ua/python-ua.html.markdown | 818 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 818 insertions(+) create mode 100644 uk-ua/python-ua.html.markdown diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown new file mode 100644 index 00000000..2406678d --- /dev/null +++ b/uk-ua/python-ua.html.markdown @@ -0,0 +1,818 @@ +--- +language: python +lang: uk-ua +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Oleg Gromyak", "https://github.com/ogroleg"] +filename: learnpython-ua.py +--- + +Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з +найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому +синтаксису. Це майже як виконуваний псевдокод. + +З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) +або louiedinh [at] [поштовий сервіс від Google] + +Примітка: Ця стаття стосується Python 2.7, проте має працювати і +у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, +його підтримку припинять у 2020, тож наразі краще починати вивчення Python +з версії 3.x. +Аби вивчити Python 3.x, звертайтесь до статті по Python 3. + +```python +# Однорядкові коментарі починаються з символу решітки. + +""" Текст, що займає декілька рядків, + може бути записаний з використанням 3 знаків " і + зазвичай використовується у якості + вбудованої документації +""" + +#################################################### +## 1. Примітивні типи даних та оператори +#################################################### + +# У вас є числа +3 # => 3 + +# Математика працює досить передбачувано +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# А ось з діленням все трохи складніше. Воно цілочисельне і результат +# автоматично округлюється у меншу сторону. +5 / 2 # => 2 + +# Аби правильно ділити, спершу варто дізнатися про числа +# з плаваючою комою. +2.0 # Це число з плаваючою комою +11.0 / 4.0 # => 2.75 ох... Так набагато краще + +# Результат цілочисельного ділення округлюється у меншу сторону +# як для додатніх, так і для від'ємних чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, +# див. розділ Модулі +# аби звичне ділення працювало при використанні лише '/'. +from __future__ import division + +11 / 4 # => 2.75 ...звичне ділення +11 // 4 # => 2 ...цілочисельне ділення + +# Залишок від ділення +7 % 3 # => 1 + +# Піднесення до степеня +2 ** 4 # => 16 + +# Приорітет операцій вказується дужками +(1 + 3) * 2 # => 8 + +# Логічні оператори +# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв +True and False # => False +False or True # => True + +# Завважте, що логічні оператори також використовуються і з цілими числами +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Для заперечення використовується not +not True # => False +not False # => True + +# Рівність — це == +1 == 1 # => True +2 == 1 # => False + +# Нерівність — це != +1 != 1 # => False +2 != 1 # => True + +# Ще трохи порівнянь +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Порівняння можуть бути записані ланцюжком! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Рядки позначаються символом " або ' +"Це рядок." +'Це теж рядок.' + +# І рядки також можна додавати! +"Привіт " + "світ!" # => "Привіт світ!" +# Рядки можна додавати і без '+' +"Привіт " "світ!" # => "Привіт світ!" + +# ... або множити +"Привіт" * 3 # => "ПривітПривітПривіт" + +# З рядком можна працювати як зі списком символів +"Це рядок"[0] # => 'Ц' + +# Ви можете дізнатися довжину рядка +len("Це рядок") # => 8 + +# Символ % використовується для форматування рядків, наприклад: +"%s можуть бути %s" % ("рядки", "інтерпольовані") + +# Новий спосіб форматування рядків — використання методу format. +# Це бажаний спосіб. +"{} є {}".format("Це", "заповнювач") +"{0} можуть бути {1}".format("рядки", "форматовані") +# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. +"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") + +# None - це об'єкт +None # => None + +# Не використовуйте оператор рівності '=='' для порівняння +# об'єктів з None. Використовуйте для цього «is» +"etc" is None # => False +None is None # => True + +# Оператор 'is' перевіряє ідентичність об'єктів. Він не +# дуже корисний при роботі з примітивними типами, проте +# незамінний при роботі з об'єктами. + +# None, 0 і порожні рядки/списки рівні False. +# Всі інші значення рівні True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Змінні та колекції +#################################################### + +# В Python є оператор print +print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! + +# Отримати дані з консолі просто +input_string_var = raw_input( + "Введіть щось: ") # Повертає дані у вигляді рядка +input_var = input("Введіть щось: ") # Працює з даними як з кодом на python +# Застереження: будьте обережні при використанні методу input() + +# Оголошувати змінні перед ініціалізацією не потрібно. +some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями +some_var # => 5 + +# При спробі доступу до неініціалізованої змінної +# виникне виняткова ситуація. +# Див. розділ Потік управління, аби дізнатись про винятки більше. +some_other_var # Помилка в імені + +# if може використовуватися як вираз +# Такий запис еквівалентний тернарному оператору '?:' у мові С +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Списки зберігають послідовності +li = [] +# Можна одразу створити заповнений список +other_li = [4, 5, 6] + +# Об'єкти додаються у кінець списку за допомогою методу append +li.append(1) # li тепер дорівнює [1] +li.append(2) # li тепер дорівнює [1, 2] +li.append(4) # li тепер дорівнює [1, 2, 4] +li.append(3) # li тепер дорівнює [1, 2, 4, 3] +# І видаляються з кінця методом pop +li.pop() # => повертає 3 і li стає рівним [1, 2, 4] +# Повернемо елемент назад +li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] + +# Поводьтесь зі списком як зі звичайним масивом +li[0] # => 1 +# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення +# Звертаємось до останнього елементу +li[-1] # => 3 + +# Спроба вийти за границі масиву призводить до помилки в індексі +li[4] # помилка в індексі + +# Можна звертатися до діапазону, використовуючи так звані зрізи +# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). +li[1:3] # => [2, 4] +# Опускаємо початок +li[2:] # => [4, 3] +# Опускаємо кінець +li[:3] # => [1, 2, 4] +# Вибираємо кожен другий елемент +li[::2] # => [1, 4] +# Перевертаємо список +li[::-1] # => [3, 4, 2, 1] +# Використовуйте суміш вищеназваного для більш складних зрізів +# li[початок:кінець:крок] + +# Видаляємо довільні елементи зі списку оператором del +del li[2] # li тепер [1, 2, 3] + +# Ви можете додавати списки +li + other_li # => [1, 2, 3, 4, 5, 6] +# Зверніть увагу: значення li та other_li при цьому не змінились. + +# Поєднувати списки можна за допомогою методу extend +li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] + +# Видалити перше входження значення +li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] +li.remove(2) # Помилка значення, оскільки у списку li немає 2 + +# Вставити елемент за вказаним індексом +li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] + +# Отримати індекс першого знайденого елементу +li.index(2) # => 1 +li.index(7) # Помилка значення, оскільки у списку li немає 7 + +# Перевірити елемент на входження у список можна оператором in +1 in li # => True + +# Довжина списку обчислюється за допомогою функції len +len(li) # => 6 + +# Кортежі схожі на списки, лише незмінні +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Виникає помилка типу + +# Все те ж саме можна робити і з кортежами +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Ви можете розпаковувати кортежі (або списки) у змінні +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +d, e, f = 4, 5, 6 # дужки можна опустити +# Кортежі створюються за замовчуванням, якщо дужки опущено +g = 4, 5, 6 # => (4, 5, 6) +# Дивіться, як легко обміняти значення двох змінних +e, d = d, e # тепер d дорівнює 5, а e дорівнює 4 + +# Словники містять асоціативні масиви +empty_dict = {} +# Ось так описується попередньо заповнений словник +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значення можна отримати так само, як і зі списку +filled_dict["one"] # => 1 + +# Можна отримати всі ключі у виді списку за допомогою методу keys +filled_dict.keys() # => ["three", "two", "one"] +# Примітка: збереження порядку ключів у словників не гарантується +# Ваші результати можуть не співпадати з цими. + +# Можна отримати і всі значення у вигляді списку, використовуйте метод values +filled_dict.values() # => [3, 2, 1] +# Те ж зауваження щодо порядку ключів діє і тут + +# Отримуйте всі пари ключ-значення у вигляді списку кортежів +# за допомогою "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# За допомогою оператору in можна перевіряти ключі на входження у словник +"one" in filled_dict # => True +1 in filled_dict # => False + +# Спроба отримати значення за неіснуючим ключем викине помилку ключа +filled_dict["four"] # помилка ключа + +# Аби уникнути цього, використовуйте метод get() +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Метод get також приймає аргумент за замовчуванням, значення якого буде +# повернуто при відсутності вказаного ключа +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Зверніть увагу, що filled_dict.get("four") все ще => None +# (get не встановлює значення елементу словника) + +# Присвоюйте значення ключам так само, як і в списках +filled_dict["four"] = 4 # тепер filled_dict["four"] => 4 + +# Метод setdefault() вставляє пару ключ-значення лише +# за відсутності такого ключа +filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5 + + +# Множини містять... ну, загалом, множини +# (які схожі на списки, проте в них не може бути елементів, які повторюються) +empty_set = set() +# Ініціалізація множини набором значень +some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4]) + +# Порядок не гарантовано, хоча інколи множини виглядають відсортованими +another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4]) + +# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Додавання нових елементів у множину +filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5} + +# Перетин множин: & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Об'єднання множин: | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Різниця множин: - +{1,2,3,4} - {2,3,5} # => {1, 4} + +# Симетрична різниця множин: ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Перевіряємо чи множина зліва є надмножиною множини справа +{1, 2} >= {1, 2, 3} # => False + +# Перевіряємо чи множина зліва є підмножиною множини справа +{1, 2} <= {1, 2, 3} # => True + +# Перевірка на входження у множину: in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Потік управління +#################################################### + +# Для початку створимо змінну +some_var = 5 + +# Так виглядає вираз if. Відступи у python дуже важливі! +# результат: «some_var менше, ніж 10» +if some_var > 10: + print("some_var набагато більше, ніж 10.") +elif some_var < 10: # Вираз elif є необов'язковим. + print("some_var менше, ніж 10.") +else: # Це теж необов'язково. + print("some_var дорівнює 10.") + + +""" +Цикли For проходять по спискам + +Результат: + собака — це ссавець + кішка — це ссавець + миша — це ссавець +""" +for animal in ["собака", "кішка", "миша"]: + # Можете використовувати оператор {0} для інтерполяції форматованих рядків + print "{0} — це ссавець".format(animal) + +""" +"range(число)" повертає список чисел +від нуля до заданого числа +Друкує: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) +""" +"range(нижня_границя, верхня_границя)" повертає список чисел +від нижньої границі до верхньої +Друкує: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +Цикли while продовжуються до тих пір, поки вказана умова не стане хибною. +Друкує: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Короткий запис для x = x + 1 + +# Обробляйте винятки блоками try/except + +# Працює у Python 2.6 і вище: +try: + # Аби створити виняток, використовується raise + raise IndexError("Помилка у індексі!") +except IndexError as e: + pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається + # відновлення після помилки. +except (TypeError, NameError): + pass # Винятки можна обробляти групами, якщо потрібно. +else: # Необов'язковий вираз. Має слідувати за останнім блоком except + print("Все добре!") # Виконається лише якщо не було ніяких винятків +finally: # Виконується у будь-якому випадку + print "Тут ми можемо звільнити ресурси" + +# Замість try/finally для звільнення ресурсів +# ви можете використовувати вираз with +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +## 4. Функції +#################################################### + +# Використовуйте def для створення нових функцій +def add(x, y): + print "x дорівнює {0}, а y дорівнює {1}".format(x, y) + return x + y # Повертайте результат за допомогою ключового слова return + + +# Виклик функції з аргументами +add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11 + +# Інший спосіб виклику функції — виклик з іменованими аргументами +add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку + + +# Ви можете визначити функцію, яка приймає змінну кількість аргументів, +# які будуть інтерпретовані як кортеж, за допомогою * +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1,2,3) + + +# А також можете визначити функцію, яка приймає змінне число +# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою ** +def keyword_args(**kwargs): + return kwargs + + +# Давайте подивимось що з цього вийде +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + +# Якщо хочете, можете використовувати обидва способи одночасно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) + + +""" +all_the_args(1, 2, a=3, b=4) друкує: + (1, 2) + {"a": 3, "b": 4} +""" + +# Коли викликаєте функції, то можете зробити навпаки! +# Використовуйте символ * аби розпакувати позиційні аргументи і +# ** для іменованих аргументів +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # еквівалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # еквівалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4) + +# ви можете передавати довільне число позиційних або іменованих аргументів +# іншим функціям, які їх приймають, розпаковуючи за допомогою +# * або ** відповідно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Область визначення функцій +x = 5 + + +def set_x(num): + # Локальна змінна x - не те ж саме, що глобальна змінна x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # глобальна змінна x тепер дорівнює 6 + print x # => 6 + + +set_x(43) +set_global_x(6) + +# В Python функції є об'єктами першого класу +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Також є і анонімні функції +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Присутні вбудовані функції вищого порядку +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Для зручного відображення і фільтрації можна використовувати +# включення у вигляді списків +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Ви також можете скористатися включеннями множин та словників +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Класи +#################################################### + +# Аби отримати клас, ми наслідуємо object. +class Human(object): + # Атрибут класу. Він розділяється всіма екземплярами цього класу. + species = "H. sapiens" + + # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу + # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені + # використовується для позначення об'єктів та атрибутів, + # які використовуються Python, але знаходяться у просторах імен, + # якими керує користувач. Не варто вигадувати для них імена самостійно. + def __init__(self, name): + # Присвоєння значення аргумента атрибуту класу name + self.name = name + + # Ініціалізуємо властивість + self.age = 0 + + # Метод екземпляру. Всі методи приймають self у якості першого аргументу + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Методи класу розділяються між усіма екземплярами + # Вони викликаються з вказанням викликаючого класу + # у якості першого аргументу + @classmethod + def get_species(cls): + return cls.species + + # Статичний метод викликається без посилання на клас або екземпляр + @staticmethod + def grunt(): + return "*grunt*" + + # Властивість. + # Перетворює метод age() в атрибут тільки для читання + # з таким же ім'ям. + @property + def age(self): + return self._age + + # Це дозволяє змінювати значення властивості + @age.setter + def age(self, age): + self._age = age + + # Це дозволяє видаляти властивість + @age.deleter + def age(self): + del self._age + + +# Створюємо екземпляр класу +i = Human(name="Данило") +print(i.say("привіт")) # Друкує: «Данило: привіт» + +j = Human("Меланка") +print(j.say("Привіт")) # Друкує: «Меланка: привіт» + +# Виклик методу класу +i.get_species() # => "H. sapiens" + +# Зміна розділюваного атрибуту +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Виклик статичного методу +Human.grunt() # => "*grunt*" + +# Оновлюємо властивість +i.age = 42 + +# Отримуємо значення +i.age # => 42 + +# Видаляємо властивість +del i.age +i.age # => виникає помилка атрибуту + +#################################################### +## 6. Модулі +#################################################### + +# Ви можете імпортувати модулі +import math + +print(math.sqrt(16)) # => 4 + +# Ви можете імпортувати окремі функції з модуля +from math import ceil, floor + +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Можете імпортувати всі функції модуля. +# Попередження: краще так не робіть +from math import * + +# Можете скорочувати імена модулів +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Ви також можете переконатися, що функції еквівалентні +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Модулі в Python — це звичайні Python-файли. Ви +# можете писати свої модулі та імпортувати їх. Назва +# модуля співпадає з назвою файлу. + +# Ви можете дізнатися, які функції та атрибути визначені +# в модулі +import math + +dir(math) + + +# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що +# і ваш поточний скрипт, то файл math.py +# може бути завантажено замість вбудованого у Python модуля. +# Так трапляється, оскільки локальна папка має перевагу +# над вбудованими у Python бібліотеками. + +#################################################### +## 7. Додатково +#################################################### + +# Генератори +# Генератор "генерує" значення тоді, коли вони запитуються, замість того, +# щоб зберігати все одразу + +# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх +# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, +# аби перевірити умову +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Натомість ми можемо скористатися генератором, аби "згенерувати" +# подвійне значення, як тільки воно буде запитане +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по +# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються +# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми +# виходимо з циклу і більше не подвоюємо більшість значень, +# які отримали на вхід (НАБАГАТО ШВИДШЕ!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Між іншим: ви помітили використання `range` у `test_non_generator` і +# `xrange` у `test_generator`? +# Як `double_numbers_generator` є версією-генератором `double_numbers`, так +# і `xrange` є аналогом `range`, але у вигляді генератора. +# `range` поверне нам масив з 1000000 значень +# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, +# коли ми їх запитуємо / будемо проходитись по ним. + +# Аналогічно включенням у вигляді списків, ви можете створювати включення +# у вигляді генераторів. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # друкує -1 -2 -3 -4 -5 + +# Включення у вигляді генератора можна явно перетворити у список +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Декоратори +# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. +# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в +# список fruits, який повертає цільова функція get_fruits. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# У цьому прикладі beg обертає say +# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, +# що повертається, буде змінено. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Будь ласка! Я бідний :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Ви можете купити мені пива?" + return msg, say_please + + +print say() # Ви можете купити мені пива? +print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :( +``` + +## Готові до більшого? + +### Безкоштовні онлайн-матеріали + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Официальная документация](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платні + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + -- cgit v1.2.3 From 96436a33de166bef190cc59abef4be4e9004f131 Mon Sep 17 00:00:00 2001 From: Stephan Fuhrmann Date: Mon, 13 Nov 2017 15:59:58 +0100 Subject: Fix for wrong/mixed parenthesis usage. --- de-de/make-de.html.markdown | 7 ++++--- make.html.markdown | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown index 22c14a69..bc5c7bcb 100644 --- a/de-de/make-de.html.markdown +++ b/de-de/make-de.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] translators: - ["Martin Schimandl", "https://github.com/Git-Jiro"] filename: Makefile-de @@ -58,7 +59,7 @@ file2.txt file3.txt: file0.txt file1.txt touch file3.txt # Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt. -# Leere Rezepte zählen nicht und können dazu verwendet werden weitere +# Leere Rezepte zählen nicht und können dazu verwendet werden weitere # Voraussetzungen hinzuzufügen. #----------------------------------------------------------------------- @@ -182,9 +183,9 @@ echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb # Ein paar Variablen die von Make automatisch definiert werden. echo_inbuilt: echo $(CC) - echo ${CXX)} + echo ${CXX} echo $(FC) - echo ${CFLAGS)} + echo ${CFLAGS} echo $(CPPFLAGS) echo ${CXXFLAGS} echo $(LDFLAGS) diff --git a/make.html.markdown b/make.html.markdown index ab128475..45d020e9 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] filename: Makefile --- @@ -11,7 +12,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix and Linux) despite many competitors and criticisms. -There are many varieties of make in existence, however this article +There are many varieties of make in existence, however this article assumes that we are using GNU make which is the standard on Linux. ```make @@ -168,9 +169,9 @@ echo: name2 = Sara # True within the matching rule # Some variables defined automatically by make. echo_inbuilt: echo $(CC) - echo ${CXX)} + echo ${CXX} echo $(FC) - echo ${CFLAGS)} + echo ${CFLAGS} echo $(CPPFLAGS) echo ${CXXFLAGS} echo $(LDFLAGS) -- cgit v1.2.3 From 20af61ee8d723dd9c3b987495261a476d59eff60 Mon Sep 17 00:00:00 2001 From: Neinei0k Date: Tue, 14 Nov 2017 18:14:17 +0000 Subject: [vim/en] Add sorting, folding, change letter case. Replacing new line character to new line character is not practical but an interesting example which shows the difference between representation of new line character in search and replace patterns. --- vim.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/vim.html.markdown b/vim.html.markdown index 15144b8d..d5c4e865 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -21,6 +21,7 @@ specific points in the file, and for fast editing. :q # Quit vim :w # Save current file :wq # Save file and quit vim + ZZ # Save file and quit vim :q! # Quit vim without saving file # ! *forces* :q to execute, hence quiting vim without saving :x # Save file and quit vim, shorter version of :wq @@ -48,6 +49,7 @@ specific points in the file, and for fast editing. :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file :s/foo/bar/g # Change 'foo' to 'bar' on the current line + :%s/\n/\r/g # Replace new line characters with new line characters # Jumping to characters @@ -167,6 +169,20 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ddp # Swap position of consecutive lines, dd then p . # Repeat previous action :w !sudo tee % # Save the current file as root + :set syntax=c # Set syntax highlighting to 'c' + :sort # Sort all lines + :sort! # Sort all lines in reverse + :sort u # Sort all lines and remove duplicates + ~ # Toggle letter case of selected text + u # Selected text to lower case + U # Selected text to upper case + + # Fold text + zf # Create fold from selected text + zo # Open current fold + zc # Close current fold + zR # Open all folds + zM # Close all folds ``` ## Macros -- cgit v1.2.3 From 2dda26010ab52ecd5d54c6fa1b8701288aaaac2d Mon Sep 17 00:00:00 2001 From: Neinei0k Date: Tue, 14 Nov 2017 19:30:57 +0000 Subject: [bash/en] Add arrays and alias --- bash.html.markdown | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 0c097c27..3f3e49eb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -83,6 +83,25 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. +# Declare an array with 6 elements +array0=(one two three four five six) +# Print first element +echo $array0 # => "one" +# Print first element +echo ${array0[0]} # => "one" +# Print all elements +echo ${array0[@]} # => "one two three four five six" +# Print number of elements +echo ${#array0[@]} # => "6" +# Print number of characters in third element +echo ${#array0[2]} # => "5" +# Print 2 elements starting from forth +echo ${array0[@]:3:2} # => "four five" +# Print all elements. Each of them on new line. +for i in "${array0[@]}"; do + echo "$i" +done + # Brace Expansion { } # Used to generate arbitrary strings echo {1..10} # => 1 2 3 4 5 6 7 8 9 10 @@ -155,6 +174,13 @@ then echo "This will run if $Name is Daniya OR Zach." fi +# Redefine command 'ping' as alias to send only 5 packets +alias ping='ping -c 5' +# Escape alias and use command with this name instead +\ping 192.168.1.1 +# Print all aliases +alias -p + # Expressions are denoted with the following format: echo $(( 10 + 5 )) # => 15 -- cgit v1.2.3 From 0e0465218542ab81dbdde347d75aab5f907b4577 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Wed, 15 Nov 2017 21:57:30 +0800 Subject: Create PCRE-tw. --- zh-tw/pcre-tw.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 zh-tw/pcre-tw.html.markdown diff --git a/zh-tw/pcre-tw.html.markdown b/zh-tw/pcre-tw.html.markdown new file mode 100644 index 00000000..01870eaf --- /dev/null +++ b/zh-tw/pcre-tw.html.markdown @@ -0,0 +1,84 @@ +--- +language: PCRE +filename: pcre.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] +translators: + - ["Michael Yeh", "https://hinet60613.github.io/"] +filename: pcre-tw.py +lang: zh-tw +--- + +正規表達式(regular expression,或縮寫為regex, regexp)是一種用來表示搜尋模式的特殊字串。例如,你可以用`/^[a-z]+:/`來從網址`http://github.com`中擷取出`http:`這段http協定名稱。 + +相容Perl正規表達式(Perl Compatible Regular Expressions, PCRE)是一個實作正規表達式的C語言函式庫。此函式庫在1997年被開發出來,在當時面對複雜字串處理時大多會選擇使用Perl。也因為如此,PCRE大多的正規表達式語法都很酷似Perl。PCRE語法被廣泛運用在許多大專案中,包括PHP、Apache、R等。 + +PCRE中的超字元(metacharacter)主要可以分為以下兩類: +* 在中括號外會被辨識的字元 +``` + \ 通用跳脫字元 + ^ 字串開頭 或 行首 + $ 字串結尾 或 行尾 + . 除了換行符號外的任何字元 + [ 字元集合定義開始 + | 支流開始 + ( 子串模式定義開始 + ) 子串模式定義結束 + ? extends the meaning of ( + 同時為數量0或1配對 + also quantifier minimizer + * 量詞 至少0個 至多無限個 + + 量詞 至少1個 至多無限個 + 同時為佔有型量詞 + { 最大/最小量詞開始 +``` + +* 在中括號內會被辨識的超字元,在中括號外會被視為字元集合使用 + +``` + + \ 通用跳脫字元 + ^ 非字元集合的字,但只會抓到第一個符合的字元 + - 字元範圍 + [ POSIX字元集合(若後面接POSIX格式) + ] 字元集合定義結束 + +``` + +PCRE提供了一些通用的字元類型,可被當作字元集合使用 +``` + \d 任何數字字元 + \D 任何非數字字元 + \h 任何水平空白字元 + \H 任何非水平空白字元 + \s 任何空白字元 + \S 任何非空白至元 + \v 任何垂直空白字元 + \V 任何非垂直空白字元 + \w 任何英文字 + \W 任何非英文字 +``` + +## 範例 + +我們以字串 `66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"` 作為範例,這是一個標準的Apache存取記錄。 + +| 正規表達式 | 結果 | 說明 | +| :---- | :-------------- | :------ | +| GET | GET | GET 抓取 GET 字串 (會分別大小寫) | +| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` 抓取數字字元,數量由 `+` 定義為至少一個至多無限個。 `\.` 抓取 `.` 字元 | +| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` 會試著抓取剛好三次的 (`\d+\.`) | +| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` 抓取除了換行符號以外的任何字元, `.` 表示任意字元 | +| ^\S+ | 66.249.64.13 | `^` 為行首, `\S+` 抓取至少一個非空白字元 | +| \+[0-9]+ | +1000 | `\+` 抓取 `+` 字元。 `[0-9]` 字元集表示剛好一個數字字元。 可以用 `\+\d+` 達到相同效果。 | + +以上範例皆可在 https://regex101.com/ 測試,步驟如下: + +1. 複製範例字串到 `TEST STRING` 區域 +2. 複製正規表達式字串到 `Regular Expression` 區域 +3. 網頁會顯示自動表達式抓取結果 + + +## 更多資料 + + -- cgit v1.2.3 From 6c58f36fb4ebb6d1c346246c57c91940c5ea47f5 Mon Sep 17 00:00:00 2001 From: Alexandru Cazacu Date: Sat, 18 Nov 2017 23:02:50 +0100 Subject: [bf/it] Added italian translation for brainfuck --- bf-it.html.markdown | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 bf-it.html.markdown diff --git a/bf-it.html.markdown b/bf-it.html.markdown new file mode 100644 index 00000000..1f544a09 --- /dev/null +++ b/bf-it.html.markdown @@ -0,0 +1,88 @@ +--- +language: "Brainfuck" +filename: brainfuck.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] + - ["Alexandru Cazacu", "https://github.com/alexandru-cazacu"] +lang: it-it +--- + +Brainfuck (maiuscolo solo all'inizio di una frase) è un linguaggio di +programmazione Turing-completo estremamente minimalistico composto da soli 8 comandi. + +Potete provare brainfuck sul vostro browser tramite [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +```bf +Ciascun carattere tranne "><+-.,[]" (escluse le virgolette) è ignorato. + +Brainfuck è rappresentato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. + +Ci sono otto comandi: ++ : Incrementa il valore nella cella corrente di uno. +- : Decrementa il valore nella cella corrente di uno. +> : Muove il puntatore alla cella successiva (cella a destra). +< : Muove il puntatore alla cella precedente (cella a sinistra). +. : Stampa il valore ASCII nella cella corrente (es. 65 = 'A'). +, : Legge un singolo carattere in input nella cella corrente. +[ : Se il valore nella cella corrente è zero, salta al corrispondente ] . + Altrimenti vai alla prossima istruzione. +] : Se il valore nella cella corrente è zero, vai alla prossima istruzione. + Altrimenti salta al corrispondente [ . + +[ and ] formano un ciclo while. Ovviamente devono essere in numero uguale. + +Diamo un'occhiata ad alcuni programmi brainfuck basilari. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Questo programma stampa la lettera 'A'. Prima, incrementa la cella #1 a 6. +La cella #1 sarà usata per il ciclo. Poi, entra nel ciclo ([) e si sposta +alla cella #2. Incrementa la cella #2 10 volte, ritorna indietro alla cella #1 +e la decrementa. Questo ciclo avviene 6 volte (servo 6 decrementi affinchè +la cella #1 raggiunga 0, a quel punto salta al corrispondente ] e continua +l'esecuzione). + +A questo punto siamo nella cella #1, che ha un valore di 0, mentre la +cella #2 ha un valore di 60. Ci muoviamo alla cella #2, la incrementiamo +5 volte, per arrivare a 65 e poi stampiamo il valore della cella #2. +65 equivale ad 'A' in ASCII, quindi 'A' viene stampato nel terminale. + +, [ > + < - ] > . + +Questo programma legge un carattere immesso dall'utente e lo copia nella +cella #1. Poi inizi un loop. Si muove nella cella #2, incrementa il valore +della cella #2, si muove alla cella #1 e decrementa il suo valore. Questo +ciclo continua finchè la cella #1 non vale 0, e la cella #2 contiene il vecchio +valore della cella #1. Siccome siamo nella cella #1 alla fine del ciclo, +ci muoviamo alla cella #2 e stampiamo il valore ASCII. + +Tenete in mente che gli spazi sono puramente estetici. Si potrebbe benissimo +anche scrivere come: + +,[>+<-]>. + +Cercate di capire cosa fa questo programma: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Questo programma prende 2 numeri in input e li moltiplica. + +Per prima cosa prende in input 2 numeri. Poi inizia il ciclo esterno, +condizionato dalla cella #1. Poi si muove nella cella #2 e inizia il ciclo +interno, condizionato dalla cella #2, incrementando la cella #3. Però c'è +un problema: alla fine del ciclo interno la cella #2 è zero. In questo caso +il ciclo interno non funzionerà pià fino alla volta seguente. Per risolvere +il problema, incrementiamo la cella #4 e poi ricopiamo #4 in #2. La cella #3 +è il risultato. +``` +E questo è brainfuck. Non è così difficile, vero? Per passare il tempo +potreste provare a scrivere un pogramma in brainfuck, oppure potete +scrivere un interprete brainfuck in un altro linguaggio. L'interprete +è relativamente semplice da implementare, ma se siete masochisti, potete +provare a scrivere un interprete brainfuck... in brainfuck. +And that's brainfuck. Not that hard, eh? For fun, you can write your own +brainfuck programs, or you can write a brainfuck interpreter in another +language. The interpreter is fairly simple to implement, but if you're +a masochist, try writing a brainfuck interpreter… in brainfuck. -- cgit v1.2.3 From c6c6b8198818cdc6e53789ea8e11be1068c68e4c Mon Sep 17 00:00:00 2001 From: luke zhang Date: Thu, 23 Nov 2017 19:39:43 +0700 Subject: add ethfiddle --- solidity.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index c1f910fd..0b2f5f67 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -826,6 +826,7 @@ someContractAddress.callcode('function_name'); ## Additional resources - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/) - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) -- cgit v1.2.3 From 8d09ffb07020fad0d7d7c3197e0926b42b436e85 Mon Sep 17 00:00:00 2001 From: pimgeek Date: Thu, 30 Nov 2017 12:57:29 +0800 Subject: Update javascript-cn.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 建议修改概要部分的文字翻译。 --- zh-cn/javascript-cn.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index bdef0099..360f7c65 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -12,12 +12,9 @@ translators: lang: zh-cn --- -Javascript于1995年由网景公司的Brendan Eich发明。 -最初发明的目的是作为一个简单的网站脚本语言,来作为 -复杂网站应用java的补充。但由于它与网页结合度很高并且由浏览器内置支持, -所以javascript变得比java在前端更为流行了。 +Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为一种简单的,用于开发网站的脚本语言而被发明出来,是用于开发复杂网站的 Java 的补充。但由于它与网页结合度很高并且在浏览器中得到内置的支持,所以在网页前端领域 Javascript 变得比 Java 更流行了。 -不过 JavaScript 可不仅仅只用于浏览器: Node.js,一个基于Google Chrome V8引擎的独立运行时环境,也越来越流行。 +不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。 很欢迎来自您的反馈,您可以通过下列方式联系到我: [@adambrenecki](https://twitter.com/adambrenecki), 或者 -- cgit v1.2.3 From 973883c57cef5caa01e60856fbd0884fff26809c Mon Sep 17 00:00:00 2001 From: Michael Hirschler Date: Sun, 3 Dec 2017 11:23:03 +0100 Subject: unifies namespace variants in exception handling --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index f82cea7d..d4fbaa32 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -841,7 +841,7 @@ try { try { // Do something -} catch (\Exception $e) { +} catch (Exception $e) { // Handle exception } -- cgit v1.2.3 From 50dbc5e7799abbf4976bd1a26e72ce470abc4423 Mon Sep 17 00:00:00 2001 From: Ilya Sosnovsky Date: Mon, 4 Dec 2017 10:13:46 +0300 Subject: Update python3-ru.html.markdown Add multiplication of rows --- ru-ru/python3-ru.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index 2b6b59a7..bf80fed2 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -106,6 +106,9 @@ False or True #=> True # И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. "Привет " + "мир!" #=> "Привет мир!" +# Строки можно умножать. +"aa" * 4 #=> "aaaaaaaa" + # Со строкой можно работать, как со списком символов "Это строка"[0] #=> 'Э' -- cgit v1.2.3 From 3ed8f9c8afa2b84321eb0176061d860d482e96b1 Mon Sep 17 00:00:00 2001 From: Fatih Turan Date: Tue, 5 Dec 2017 00:33:15 +0300 Subject: [css/tr]Turkish translate for CSS documentation --- tr-tr/css.html.markdown | 304 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 304 insertions(+) create mode 100644 tr-tr/css.html.markdown diff --git a/tr-tr/css.html.markdown b/tr-tr/css.html.markdown new file mode 100644 index 00000000..baa47b3d --- /dev/null +++ b/tr-tr/css.html.markdown @@ -0,0 +1,304 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Brett Taylor", "https://github.com/glutnix"] + - ["Tyler Mumford", "https://tylermumford.com"] +filename: learncss.css +translators: + - ["Fatih Turan", "http://fatihturan.com"] +lang: tr-tr +--- + +Web sayfaları bir sayfanın içeriğini belirleyen HTML ile inşa edilirler. CSS (Basamaklı Biçim Sayfaları) ise bir sayfanın **görünümünü** belirleyen ayrı bir dildir. + +CSS kodu statik *kurallardan* oluşur. Her kural bir ya da daha fazla *seçici* alır ve görsel *özelliklere* belirli *değerleri* verir. Sonrasında bu özellikler seçiciler tarafından belirlenen sayfa unsurlarına uygulanır. + +Bu rehber, CSS 3'ün yeni özellikleri ile genişletilen CSS 2 ile dikkate alınarak yazılmıştır. + +**NOT:** CSS görsel sonuçlar ürettiğinden dolayı, öğrenmek için herşeyi bir CSS oyun alanı içinde ([dabblet](http://dabblet.com) gibi) denemeniz gerekmektedir. Bu makale sözdizimi kuralları ve genel ipuçları üzerine odaklanmaktadır. + +## Sözdizimi + +```css +/* yorumlar bu satırdaki gibi taksim-yıldız içinde görünür +CSS'te "tek satırlık yorumlar" bulunmamaktadır; bu sadece tek bir yorum yazma stilidir */ + +/* #################### + ## SEÇİCİLER + #################### */ + +/* seçici bir sayfadaki unsuru hedeflemek için kullanılır. */ +seçici { özellik: değer; /* daha fazla özellikler...*/ } + +/* +İşte bir örnek: + +
+*/ + +/* */ + +/* CSS sınıflarının birini kullanarak hedefleyebilirsiniz */ +.class1 { } + +/* veya her iki sınıfı birden!*/ +.class1.class2 { } + +/* veya sadece ögenin adını yazarak */ +div { } + +/* veya onun ID adını */ +#anID { } + +/* veya onun aldığı bir özelliği kullanarak! */ +[attr] { font-size:smaller; } + +/* veya onun aldığı özelliğin belirli bir değeri varsa */ +[attr='value'] { font-size:smaller; } + +/* bir değer ile başlıyorsa (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* veya bir değer ile bitiyorsa (CSS 3)*/ +[attr$='ue'] { font-size:smaller; } + +/* veya boşlukla ayrılmış liste içinde bir değer içeriyorsa */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* veya tire ile ayrılmış bir liste içinde bir değer içeriyorsa, örneğin: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + +/* Farklı seçicileri birleştirerek daha fazla odaklanmış bir seçici oluşturabilirsiniz. Seçiciler arasında boşluk bırakmayın. */ +div.some-class[attr$='ue'] { } + +/* Başka bir ögenin alt ögesi olan bir ögeyi seçebilirsiniz. */ +div.some-parent > .class-name { } + +/* veya bir başka ögeden türeyeni seçebilirsiniz. Alt ögeler onların ebeveynlerinin direkt türünden gelir, sadece ağacın bir alt ögeleridirler. Soyundan gelenler ağacın herhangi bir alt seviyesinde olabilir. */ + +div.some-parent .class-name { } + +/* Uyarı: Seçiciler arasında bir boşluk bırakmazsanız aynı seçicinin başka bir anlamı olur. +Ne olduğunu tahmin edebilir misiniz? */ + +div.some-parent.class-name { } + +/* Ayrıca bir ögenin bitişik kardeşini temel alarak bir ögeyi seçebilirsiniz. */ +.i-am-just-before + .this-element { } + +/* veya kendisinden önce gelen herhangi bir kardeş ögeyi */ +.i-am-any-element-before ~ .this-element { } + +/* Yalnızca belli bir durumda bir öge seçmek için kullanılan sahte sınıflar adı verilen bazı seçiciler vardır. */ + +/* Örneğin, imleç bir ögenin üzerine geldiğinde */ +selector:hover { } + +/* veya bir bağlantı ziyaret edildiğinde */ +selector:visited { } + +/* veya ziyaret edilmediğinde */ +selected:link { } + +/* veya bir ögeye odaklanıldığında */ +selected:focus { } + +/* Ebeveyninin ilk alt ögesi olan herhangi bir öge */ +selector:first-child {} + +/* Ebeveyninin son alt ögesi olan herhangi bir öge */ +selector:last-child {} + +/* Sahte sınıflar gibi sahte elementler de bir dokümanın belirli bir parçasına stil vermenize izin verir. */ + +/* Seçilen ögenin sanal ilk alt ögesiyle eşleşir. */ +selector::before {} + +/* Seçilen ögenin sanal son alt ögesiyle eşleşir. */ +selector::after {} + +/* Uygun yerlerde yıldız karakteri ile bütün ögeleri seçmek için joker olarak kullanılabilir. */ + +* { } /* Bütün ögeler */ +.parent * { } /* Tüm alt ögeler */ +.parent > * { } /* Tüm çocuk ögeler */ + +/* #################### + ## ÖZELLİKLER + #################### */ + +selector { + + /* Ölçü birimleri kesin veya göreceli olabilir.*/ + + /* Göreceli birimler */ + width: 50%; /* Ebeveyn elementin yüzdesel olarak genişliği */ + font-size: 2em; /* Öğenin özgün yazı tipi boyutunda katları */ + font-size: 2rem; /* veya kök ögenin yazı tipi boyutu */ + font-size: 2vw; /* Görüntüleme çerçevesinin genişliğinin %1 olarak katları (CSS 3) */ + font-size: 2vh; /* veya onun yüksekliğinin */ + font-size: 2vmin; /* Bir vh veya vw'nin hangisi küçükse */ + font-size: 2vmax; /* veya daha büyük... */ + + /* Kesin birimler */ + width: 200px; /* Piksel */ + font-size: 20pt; /* Nokta */ + width: 5cm; /* Santimetre */ + min-width: 50mm; /* Milimetre */ + max-width: 5in; /* İnç */ + + /* Renkler */ + color: #F6E; /* Kısa onaltılık (HEX) biçimi */ + color: #FF66EE; /* Uzun onaltılık (HEX) biçimi */ + color: tomato; /* Bir isim verilen renk */ + color: rgb(255, 255, 255); /* RGB değerleri verilen türde */ + color: rgb(10%, 20%, 50%); /* RGB yüzdeleri verilen türde */ + color: rgba(255, 0, 0, 0.3); /* RGBA değerleri verilen türde (CSS 3) Not: 0 <= a <= 1 */ + color: transparent; /* Şeffaflık değerinin sıfır olması ile eşdeğer */ + color: hsl(0, 100%, 50%); /* HSL yüzdeleri verilen türde (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* HSL ile beraber şeffaflık değeri verilen türde */ + + /* Kenarlıklar */ + border-width:5px; + border-style:solid; + border-color:red; /* background-color'ın ayarlanışına benzer şekilde */ + border: 5px solid red; /* Bu aynı şeyin kısayol ile yazılışıdır */ + border-radius:20px; /* Bu bir CSS3 özelliğidir */ + + /* Görseller ve Ögelerin Arkaplanları */ + background-image: url(/img-path/img.jpg); /* url() içindeki tırnak işaretleri isteğe bağlı */ + + /* Yazı tipleri */ + font-family: Arial; + /* Eğer yazı tipi ailesi isminde bir boşluk var ise tırnak işareti içine alınmalıdır. */ + font-family: "Courier New"; + /* Eğer ilk sıradaki bulunamazsa, tarayıcı bir sonrakini kullanır */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Kullanım + +CSS dosyasınızı `.css`uzantısı ile kaydedin. + +```html + + + + + + + +
+
+``` + +## Öncelik veya Basamak + +Bir öge birden çok seçici tarafından hedef alınabilir ve bir özellik kümesine birden fazla kez sahip olabilir. Bunun gibi durumlarda, kurallardan biri diğerlerine göre önceliklidir. Daha spesifik bir seçiciye sahip kurallar, daha az spesifik bir seçicinin önceliğini alır ve kural daha sonra stil sayfasında bir önceki kuralın üzerine yazar. + +Bu işleme geçiş denir ve olayısıyla Geçişli/Basamaklı Stil Sayfaları adı da buradan gelmiştir. + +Aşağıdaki CSS göz önüne alındığında: + +```css +/* A */ +p.class1[attr='değer'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { özellik: değer !important; } +``` + +ve aşağıdaki biçimlendirmeyi: + +```html +

+``` + +Stilin önceliği ise aşağıdaki gibidir. Unutmayın, öncelik **her bir özellik için ayrı ayrı geçerlidir**, tüm blok için geçerli değildir. + +* `E` `!important` kelimesi yüzünden en yüksek önceliğe sahiptir. Kullanımından kaçınmanız önerilir. +* `F` satıriçi stil olduğu için bir sonraki önceliğe sahiptir. +* `A` bir sonraki önceliğe sahiptir. Çünkü her şeyden daha "özgüdür". 3 belirteci vardır: `p` ögesinin adı, sınıf` class1`, bir öznitelik `attr = 'değer'. +* `C`, `B` ile aynı özdeşliğe sahip olsa da, bundan sonra geldiğinden dolayı öncelik hakkına sahiptir. +* `B` bir sonraki önceliğe sahiptir. +* Sonuncu önceliğe sahip olan`D`'dir. + +## Medya Sorguları + +CSS Medya Sorguları, CSS 3'te belirli CSS kurallarının ne zaman uygulanması gerektiğini (örneğin basılan zaman veya belirli boyutlar veya piksel yoğunluğu olan bir ekranda olduğunda) belirlemenize izin veren bir özelliktir. Medya Sorguları, seçicilere önceliğk eklemez. + +```css +/* Tüm cihazlarda kullanılacak olan bir kural */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* h1 ögesini değiştirip bir yazıcıda daha az mürekkep kullanın*/ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* En az 480 piksel genişliğinde bir ekran gösterildiğinde font yüksekliğini daha büyük yap */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` + +Medya sorguları aşağıdaki bu özellikleri içerebilir: +`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Bu özelliklerin birçoğunu `min-` veya `max-` öneki ile kullanabilirsiniz. + +`resolution` özelliği eski cihazlarda desteklenmediğinden ötürü `device-pixel-ratio` kullanın. + +Eğer `viewport` meta etiketi sağlanmadıkça birçok akıllı telefon ve tabletler, sayfayı masaüstü bilgisayardaymış gibi göstermeye çalışacaktır. + +```html + + + +``` + +## Uyumluluk + +CSS 2'deki çoğu özellik (ve CSS 3'deki birçoğu) bütün tarayıcılar ve cihazlar için bulunmaktadır. Ancak yeni bir özelliği kullanmadan önce kontrol etmek her zaman iyi bir uygulamadır. + +## Kaynaklar + +* [CanIUse](http://caniuse.com) (Detaylı uyumluluk bilgileri) +* [Dabblet](http://dabblet.com/) (CSS oyun alanı) +* [Mozilla Geliştirici Ağının CSS belgelendirmesi](https://developer.mozilla.org/en-US/docs/Web/CSS) (Eğitseller ve referanslar) +* [Codrops' CSS Referansı](http://tympanus.net/codrops/css_reference/) (Referans) + +## Daha Fazla Okuma + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) \ No newline at end of file -- cgit v1.2.3 From 3386171160dd7fc3e4e6e9aaf2d5abfebdb38d6f Mon Sep 17 00:00:00 2001 From: Aswin Sanakan Date: Tue, 5 Dec 2017 12:24:43 +0530 Subject: Fix omitting in list and clarified comments --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 37987582..153384de 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -209,9 +209,9 @@ li[4] # Raises an IndexError # The start index is included, the end index is not # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] -# Omit the end +# Omit the beginning and return the list li[2:] # => [4, 3] -# Omit the beginning +# Omit the end and return the list li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -- cgit v1.2.3 From c52ae61127b9b50f39e45876c672ed73ce4e2125 Mon Sep 17 00:00:00 2001 From: andys8 Date: Sat, 23 Dec 2017 11:57:45 +0100 Subject: [elm] Update code to access tuples --- cs-cz/elm.html.markdown | 4 ++-- elm.html.markdown | 4 ++-- pt-br/elm-pt.html.markdown | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown index f19f9e8b..42ec89e5 100644 --- a/cs-cz/elm.html.markdown +++ b/cs-cz/elm.html.markdown @@ -75,8 +75,8 @@ List.head [] -- Nothing -- K získání hodnot z dvojice použijte funkce first a second. -- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".) -fst ("elm", 42) -- "elm" -snd ("elm", 42) -- 42 +Tuple.first ("elm", 42) -- "elm" +Tuple.second ("elm", 42) -- 42 -- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol. -- Je to jediná hodnota svého typu, který se také nazývá "Unit". diff --git a/elm.html.markdown b/elm.html.markdown index 23ae9eeb..ad80adc9 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -72,8 +72,8 @@ List.head [] -- Nothing -- Access the elements of a pair with the first and second functions. -- (This is a shortcut; we'll come to the "real way" in a bit.) -fst ("elm", 42) -- "elm" -snd ("elm", 42) -- 42 +Tuple.first ("elm", 42) -- "elm" +Tuple.second ("elm", 42) -- 42 -- The empty tuple, or "unit", is sometimes used as a placeholder. -- It is the only value of its type, also called "Unit". diff --git a/pt-br/elm-pt.html.markdown b/pt-br/elm-pt.html.markdown index 78a4f1b7..d2469a93 100644 --- a/pt-br/elm-pt.html.markdown +++ b/pt-br/elm-pt.html.markdown @@ -76,8 +76,8 @@ List.head [] -- Nothing -- Acesse os elementos de um par com as funções first e second. -- (Este é um atalho; nós iremos para o "caminho real" em breve.) -fst ("elm", 42) -- "elm" -snd ("elm", 42) -- 42 +Tuple.first ("elm", 42) -- "elm" +Tuple.second ("elm", 42) -- 42 -- Uma tupla vazia ou "unidade" às vezes é utilizada como um placeholder. -- É o único valor de seu tipo, também chamado de "Unit". -- cgit v1.2.3 From 563e135e68223775e2db5bea3421afddc28d8c30 Mon Sep 17 00:00:00 2001 From: Donovan Glover Date: Wed, 27 Dec 2017 13:35:16 -0500 Subject: Fix the multiline Nim comment --- nim.html.markdown | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 30dfa94f..1e17d8f0 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -15,15 +15,9 @@ Nim is efficient, expressive, and elegant. # Single-line comments start with a # #[ - Multi-line comments begin with a #[ - ... and end with ]# - -They don't care about indentation - - #[ - and they can be nested - ]# - + This is a multiline comment. + In Nim, multiline comments can be nested, beginning with #[ + ... and ending with ]# ]# discard """ -- cgit v1.2.3 From 84881b3cda80339deb8102ed21fd7ab83b00ea75 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 28 Dec 2017 18:39:48 -0800 Subject: Initial update to latest solidity --- solidity.html.markdown | 204 +++++++++++++++++++++++++------------------------ 1 file changed, 104 insertions(+), 100 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index c1f910fd..705fb793 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -37,8 +37,8 @@ features are typically marked, and subject to change. Pull requests welcome. // simple_bank.sol (note .sol extension) /* **** START EXAMPLE **** */ -// Declare the source file compiler version. -pragma solidity ^0.4.2; +// Declare the source file compiler version +pragma solidity ^0.4.19; // Start with Natspec comment (the three slashes) // used for documentation - and as descriptive data for UI elements/actions @@ -65,7 +65,7 @@ contract SimpleBank { // CapWords event LogDepositMade(address accountAddress, uint amount); // Constructor, can receive one or many variables here; only one allowed - function SimpleBank() { + function SimpleBank() public { // msg provides details about the message that's sent to the contract // msg.sender is contract caller (address of contract creator) owner = msg.sender; @@ -73,7 +73,11 @@ contract SimpleBank { // CapWords /// @notice Deposit ether into bank /// @return The balance of the user after the deposit is made - function deposit() public returns (uint) { + function deposit() public payable returns (uint) { + // Use 'require' to test user inputs, 'assert' for internal invariants + // Here we are making sure that there isn't an overflow issue + require((balances[msg.sender] + msg.value) >= balances[msg.sender]); + balances[msg.sender] += msg.value; // no "this." or "self." required with state variable // all values set to data type's initial value by default @@ -88,18 +92,17 @@ contract SimpleBank { // CapWords /// @param withdrawAmount amount you want to withdraw /// @return The balance remaining for the user function withdraw(uint withdrawAmount) public returns (uint remainingBal) { - if(balances[msg.sender] >= withdrawAmount) { - // Note the way we deduct the balance right away, before sending - due to - // the risk of a recursive call that allows the caller to request an amount greater - // than their balance - balances[msg.sender] -= withdrawAmount; - - if (!msg.sender.send(withdrawAmount)) { - // increment back only on fail, as may be sending to contract that - // has overridden 'send' on the receipt end - balances[msg.sender] += withdrawAmount; - } - } + require(withdrawAmount <= balances[msg.sender]); + + // Note the way we deduct the balance right away, before sending + // Every .transfer/.send from this contract can call an external function + // This may allow the caller to request an amount greater + // than their balance using a recursive call + // Aim to commit state before calling external functions, including .transfer/.send + balances[msg.sender] -= withdrawAmount; + + // this automatically throws on a failure, which means the updated balance is reverted + msg.sender.transfer(withdrawAmount); return balances[msg.sender]; } @@ -108,18 +111,9 @@ contract SimpleBank { // CapWords /// @return The balance of the user // 'constant' prevents function from editing state variables; // allows function to run locally/off blockchain - function balance() constant returns (uint) { + function balance() constant public returns (uint) { return balances[msg.sender]; } - - // Fallback function - Called if other functions don't match call or - // sent ether without data - // Typically, called when invalid data is sent - // Added so ether sent to this contract is reverted if the contract fails - // otherwise, the sender's money is transferred to contract - function () { - throw; // throw reverts state to before call - } } // ** END EXAMPLE ** @@ -137,6 +131,11 @@ int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant // with 'constant', compiler replaces each occurrence with actual value +// All state variables (those outside a function) +// are by default 'internal' and accessible inside contract +// and in all contracts that inherit ONLY +// Need to explicitly set to 'public' to allow external contracts to access +int256 public a = 8; // For int and uint, can explicitly set space in steps of 8 up to 256 // e.g., int8, int16, int24 @@ -145,6 +144,12 @@ int64 c; uint248 e; // Be careful that you don't overflow, and protect against attacks that do +// For example, for an addition, you'd do: +uint256 c = a + b; +assert(c >= a); // assert tests for internal invariants; require is used for user inputs +// For more examples of common arithmetic issues, see Zeppelin's SafeMath library +// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol + // No random functions built in, use other contracts for randomness @@ -165,14 +170,14 @@ address public owner; // a getter is automatically created, but NOT a setter // All addresses can be sent ether -owner.send(SOME_BALANCE); // returns false on failure -if (owner.send) {} // REMEMBER: wrap in 'if', as contract addresses have +owner.transfer(SOME_BALANCE); // fails and reverts on failure + +// Can also do a lower level .send call, which returns a false if it failed +if (owner.send) {} // REMEMBER: wrap send in 'if', as contract addresses have // functions executed on send and these can fail // Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive // call that can drain the contract -// can override send by defining your own - // Can check balance owner.balance; // the balance of the owner (user or contract) @@ -213,7 +218,7 @@ uint x = 5; // Destructuring/Tuples -(x, y) = (2, 7); // assign/swap multiple value +(x, y) = (2, 7); // assign/swap multiple values // 2. DATA STRUCTURES @@ -250,7 +255,7 @@ delete balances; // sets all elements to 0 // mapping, without knowing source keys - can build data structure // on top to do this -// Structs and enums +// Structs struct Bank { address owner; uint balance; @@ -273,7 +278,7 @@ state = State.Created; // enums can be explicitly converted to ints uint createdState = uint(State.Created); // 0 -// Data locations: Memory vs. storage vs. stack - all complex types (arrays, +// Data locations: Memory vs. storage vs. calldata - all complex types (arrays, // structs) have a data location // 'memory' does not persist, 'storage' does // Default is 'storage' for local and state variables; 'memory' for func params @@ -292,13 +297,13 @@ uint createdState = uint(State.Created); // 0 // 4. Global Variables of note // ** this ** this; // address of contract -// often used at end of contract life to send remaining balance to party +// often used at end of contract life to transfer remaining balance to party this.balance; this.someFunction(); // calls func externally via call, not via internal jump // ** msg - Current message received by the contract ** ** msg.sender; // address of sender -msg.value; // amount of ether provided to this contract in wei +msg.value; // amount of ether provided to this contract in wei, the function should be marked "payable" msg.data; // bytes, complete call data msg.gas; // remaining gas @@ -308,6 +313,8 @@ tx.gasprice; // gas price of the transaction // ** block - Information about current block ** now; // current time (approximately), alias for block.timestamp (uses Unix time) +// Note that this can be manipulated by miners, so use carefully + block.number; // current block number block.difficulty; // current block difficulty block.blockhash(1); // returns bytes32, only works for most recent 256 blocks @@ -334,9 +341,10 @@ function increment(uint x, uint y) returns (uint x, uint y) { // Call previous functon uint (a,b) = increment(1,1); -// 'constant' indicates that function does not/cannot change persistent vars +// 'constant' (alias for 'view') +// indicates that function does not/cannot change persistent vars // Constant function execute locally, not on blockchain -uint y; +uint y = 1; function increment(uint x) constant returns (uint x) { x += 1; @@ -344,13 +352,21 @@ function increment(uint x) constant returns (uint x) { // y is a state variable, and can't be changed in a constant function } +// 'pure' is more strict than 'constant', and does not +// even allow reading of state vars +// The exact rules are more complicated, so see more about +// constant/pure: +// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions + // 'Function Visibility specifiers' // These can be placed where 'constant' is, including: -// public - visible externally and internally (default) -// external +// public - visible externally and internally (default for function) +// external - only visible externally (including a call made with this.) // private - only visible in the current contract // internal - only visible in current contract, and those deriving from it +// Generally, a good idea to mark each function explicitly + // Functions hoisted - and can assign a function to a variable function a() { var z = b; @@ -361,8 +377,15 @@ function b() { } +// All functions that receive ether must be marked 'payable' +function depositEther() public payable { + balances[msg.sender] += msg.value; +} + // Prefer loops to recursion (max call stack depth is 1024) +// Also, don't setup loops that you haven't bounded, +// as this can hit the gas limit // B. Events // Events are notify external parties; easy to search and @@ -378,7 +401,8 @@ event LogSent(address indexed from, address indexed to, uint amount); // note ca // Call Sent(from, to, amount); -// For an external party (a contract or external entity), to watch: +// For an external party (a contract or external entity), to watch using +// the Web3 Javascript library: Coin.Sent().watch({}, '', function(error, result) { if (!error) { console.log("Coin transfer: " + result.args.amount + @@ -398,10 +422,10 @@ Coin.Sent().watch({}, '', function(error, result) { // '_' (underscore) often included as last line in body, and indicates // function being called should be placed there -modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } -modifier onlyOwner { if (msg.sender == owner) _ } +modifier onlyAfter(uint _time) { require (now >= _time); _; } +modifier onlyOwner { require(msg.sender == owner) _; } // commonly used with state machines -modifier onlyIfState (State currState) { if (currState != State.A) _ } +modifier onlyIfStateA (State currState) { require(currState == State.A) _; } // Append right after function declaration function changeOwner(newOwner) @@ -415,12 +439,10 @@ onlyIfState(State.A) // underscore can be included before end of body, // but explicitly returning will skip, so use carefully modifier checkValue(uint amount) { - _ + _; if (msg.value > amount) { uint amountToRefund = amount - msg.value; - if (!msg.sender.send(amountToRefund)) { - throw; - } + msg.sender.transfer(amountToRefund); } } @@ -437,22 +459,21 @@ modifier checkValue(uint amount) { // amount of gas for a block of code - and will fail if that is exceeded // For example: for(uint x = 0; x < refundAddressList.length; x++) { - if (!refundAddressList[x].send(SOME_AMOUNT)) { - throw; - } + refundAddressList[x].transfer(SOME_AMOUNT); } // Two errors above: -// 1. A failure on send stops the loop from completing, tying up money +// 1. A failure on transfer stops the loop from completing, tying up money // 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and // therefore may always fail as it exceeds the max gas for a block // Instead, you should let people withdraw individually from their subaccount, and mark withdrawn +// e.g., favor pull payments over push payments // 7. OBJECTS/CONTRACTS // A. Calling external contract -contract infoFeed { +contract InfoFeed { function info() returns (uint ret) { return 42; } } @@ -502,23 +523,10 @@ function someAbstractFunction(uint x); import "filename"; import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; -// Importing under active development -// Cannot currently be done at command line - // 8. OTHER KEYWORDS -// A. Throwing -// Throwing -throw; // reverts unused money to sender, state is reverted -// Can't currently catch - -// Common design pattern is: -if (!addr.send(123)) { - throw; -} - -// B. Selfdestruct +// A. Selfdestruct // selfdestruct current contract, sending funds to address (often creator) selfdestruct(SOME_ADDRESS); @@ -543,7 +551,7 @@ function remove() { // that is private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment -sha3("some_bid_amount", "some secret"); // commit +keccak256("some_bid_amount", "some secret"); // commit // call contract's reveal function in the future // showing bid plus secret that hashes to SHA3 @@ -617,6 +625,7 @@ contract SomeOracle { // ** START EXAMPLE ** // CrowdFunder.sol +pragma solidity ^0.4.19; /// @title CrowdFunder /// @author nemild @@ -650,22 +659,20 @@ contract CrowdFunder { event LogWinnerPaid(address winnerAddress); modifier inState(State _state) { - if (state != _state) throw; - _ + require(state == _state); + _; } modifier isCreator() { - if (msg.sender != creator) throw; - _ + require(msg.sender == creator); + _; } - // Wait 6 months after final contract state before allowing contract destruction + // Wait 24 weeks after final contract state before allowing contract destruction modifier atEndOfLifecycle() { - if(!((state == State.ExpiredRefund || state == State.Successful) && - completeAt + 6 months < now)) { - throw; - } - _ + require(((state == State.ExpiredRefund || state == State.Successful) && + completeAt + 24 weeks < now)); + _; } function CrowdFunder( @@ -673,6 +680,7 @@ contract CrowdFunder { string _campaignUrl, address _fundRecipient, uint _minimumToRaise) + public { creator = msg.sender; fundRecipient = _fundRecipient; @@ -683,7 +691,9 @@ contract CrowdFunder { function contribute() public + payable inState(State.Fundraising) + returns(uint256 id) { contributions.push( Contribution({ @@ -699,7 +709,9 @@ contract CrowdFunder { return contributions.length - 1; // return id } - function checkIfFundingCompleteOrExpired() { + function checkIfFundingCompleteOrExpired() + public + { if (totalRaised > minimumToRaise) { state = State.Successful; payOut(); @@ -715,31 +727,23 @@ contract CrowdFunder { public inState(State.Successful) { - if(!fundRecipient.send(this.balance)) { - throw; - } - - + fundRecipient.transfer(this.balance); LogWinnerPaid(fundRecipient); } - function getRefund(id) - public + function getRefund(uint256 id) inState(State.ExpiredRefund) + public + returns(bool) { - if (contributions.length <= id || id < 0 || contributions[id].amount == 0 ) { - throw; - } + require(contributions.length > id && id >= 0 && contributions[id].amount != 0 ); - uint amountToRefund = contributions[id].amount; + uint256 amountToRefund = contributions[id].amount; contributions[id].amount = 0; - if(!contributions[id].contributor.send(amountToSend)) { - contributions[id].amount = amountToSend; - return false; - } + contributions[id].contributor.transfer(amountToRefund); - return true; + return true; } function removeContract() @@ -750,8 +754,6 @@ contract CrowdFunder { selfdestruct(msg.sender); // creator gets all money that hasn't be claimed } - - function () { throw; } } // ** END EXAMPLE ** @@ -798,6 +800,7 @@ someContractAddress.callcode('function_name'); // 13. STYLE NOTES // Based on Python's PEP8 style guide +// Full Style guide: http://solidity.readthedocs.io/en/develop/style-guide.html // Quick summary: // 4 spaces for indentation @@ -825,11 +828,15 @@ someContractAddress.callcode('function_name'); ## Additional resources - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) +- [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. -- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) +- [Browser-based Solidity Editor](https://remix.ethereum.org/) - [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) +## Important libraries +- [Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity/): Libraries that provide common contract patterns (crowdfuding, safemath, etc) + ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) @@ -841,9 +848,6 @@ someContractAddress.callcode('function_name'); - [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/) - [Hacking Distributed Blog](http://hackingdistributed.com/) -## Information purposefully excluded -- Libraries - ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy -- cgit v1.2.3 From d28abc39451bf1b075945d46ab372bb30f8b59fa Mon Sep 17 00:00:00 2001 From: suuuzi Date: Sun, 31 Dec 2017 14:35:07 -0200 Subject: updating BF translation --- pt-br/bf-pt.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pt-br/bf-pt.html.markdown b/pt-br/bf-pt.html.markdown index 52a5269e..53baa9a2 100644 --- a/pt-br/bf-pt.html.markdown +++ b/pt-br/bf-pt.html.markdown @@ -13,7 +13,9 @@ lang: pt-br Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de programação Turing-completa extremamente simples com apenas 8 comandos. -``` +Você pode experimentar brainfuck pelo seu browser com [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +```bf Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. Brainfuck é representado por um vetor com 30 000 células inicializadas em zero -- cgit v1.2.3 From 95d41ddf6c798131cd343099bcc6b3408657e8c6 Mon Sep 17 00:00:00 2001 From: 0x6a6f7368 Date: Thu, 4 Jan 2018 00:06:44 -0500 Subject: Update c.html.markdown Fixed and improved compiler flag default recommendations. --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 87a047be..cfb93aa8 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Marco Scannadinari", "https://marcoms.github.io"] - ["Zachary Ferguson", "https://github.io/zfergus2"] - ["himanshu", "https://github.com/himanshu81494"] + - ["Joshua Li", "https://github.com/JoshuaRLi"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -23,7 +24,7 @@ memory management and C will take you as far as you need to go. > stricter compiler flags is recommended. Here is an example you can > tweak to your liking: > -> `-Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11` +> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic` ```c // Single-line comments start with // - only available in C99 and later. -- cgit v1.2.3 From 81a637e1dd82ec4625a8e2f6eba3b5d06a7767be Mon Sep 17 00:00:00 2001 From: 0x6a6f7368 Date: Thu, 4 Jan 2018 00:15:28 -0500 Subject: Update c.html.markdown How to get information on compiler flags. --- c.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index cfb93aa8..0c6df413 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -20,11 +20,12 @@ memory management and C will take you as far as you need to go. > **About compiler flags** > > By default, gcc and clang are pretty quiet about compilation warnings and -> errors, which can be very useful information. Using some -> stricter compiler flags is recommended. Here is an example you can -> tweak to your liking: +> errors, which can be very useful information. Explicitly using stricter +> compiler flags is recommended. Here are some recommended defaults: > > `-Wall -Wextra -Werror -O2 -std=c99 -pedantic` +> +> For information on what these flags do as well as other flags, consult the man page for your C compiler (e.g. `man 1 gcc`) or just search online. ```c // Single-line comments start with // - only available in C99 and later. -- cgit v1.2.3 From 9999a30e045f59fe3347b8822f71fff32b3ffc27 Mon Sep 17 00:00:00 2001 From: Chris Wilson Date: Thu, 4 Jan 2018 15:49:43 -0600 Subject: Add `case` expression to SML docs Show an example of pattern-matching using the case expression. --- standard-ml.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 5db15b5c..b34f1c08 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -6,6 +6,7 @@ contributors: - ["David Pedersen", "http://lonelyproton.com/"] - ["James Baker", "http://www.jbaker.io/"] - ["Leo Zovic", "http://langnostic.inaimathi.ca/"] + - ["Chris Wilson", "http://sencjw.com/"] --- Standard ML is a functional programming language with type inference and some @@ -266,6 +267,16 @@ fun second_elem (x::y::xs) = y fun evenly_positioned_elems (odd::even::xs) = even::evenly_positioned_elems xs | evenly_positioned_elems [odd] = [] (* Base case: throw away *) | evenly_positioned_elems [] = [] (* Base case *) + +(* The case expression can also be used to pattern match and return a value *) +datatype temp = + C of real + | F of real + +fun temp_to_f t = + case t of + C x => x * (9.0 / 5.0) + 32.0 + | F x => x (* When matching on records, you must use their slot names, and you must bind every slot in a record. The order of the slots doesn't matter though. *) -- cgit v1.2.3 From 0d33508a4efb8a7b0887de0841342c2947dafc89 Mon Sep 17 00:00:00 2001 From: Colin-Colin <35017473+Colin-Colin@users.noreply.github.com> Date: Sat, 13 Jan 2018 21:17:47 -0600 Subject: fix typo switch 'tumbnails' to 'thumbnails' --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index a3866892..c9b1d8fb 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -255,7 +255,7 @@ There exists two main types of links: visible URL \\ % You can not add extra-spaces or special symbols into shadowing text since it % will cause mistakes during the compilation -This package also produces list of tumbnails in the output pdf document and +This package also produces list of thumbnails in the output pdf document and active links in the table of contents. \section{End} -- cgit v1.2.3 From 11e12b93fb9af08550da7245075290d36e05cec3 Mon Sep 17 00:00:00 2001 From: Bulat Musin <9249387+bmusin@users.noreply.github.com> Date: Thu, 18 Jan 2018 07:51:46 +0300 Subject: fix typo --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 2821f0d4..4723a55f 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1366,7 +1366,7 @@ sub add($a, $b) { $a + $b } say [[&add]] 1, 2, 3; #=> 6 ## * Zip meta-operator -## This one is an infix meta-operator than also can be used as a "normal" +## This one is an infix meta-operator that also can be used as a "normal" ## operator. It takes an optional binary function (by default, it just creates ## a pair), and will pop one value off of each array and call its binary ## function on these until it runs out of elements. It returns an array with -- cgit v1.2.3 From 654e0052915aadd897f01ddc6e0efc59446aeb10 Mon Sep 17 00:00:00 2001 From: Bulat Musin <9249387+bmusin@users.noreply.github.com> Date: Thu, 18 Jan 2018 09:31:56 +0300 Subject: [perl6/en]: fix spelling --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 2821f0d4..7da24951 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1659,7 +1659,7 @@ sub MAIN($name) { say "Hello, $name !" } ## Usage: ## t.pl -## And since it's a regular Perl 6 sub, you can haz multi-dispatch: +## And since it's a regular Perl 6 sub, you can have multi-dispatch: ## (using a "Bool" for the named argument so that we can do `--replace` ## instead of `--replace=1`) subset File of Str where *.IO.d; # convert to IO object to check the file exists -- cgit v1.2.3 From 5c6411ddafc6b27a3e2c866893775ac2c438750d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edward=20Tj=C3=B6rnhammar?= Date: Thu, 18 Jan 2018 17:06:10 +0100 Subject: [haskell/sv-se] initial --- sv-se/haskell-sv.html.markdown | 461 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 461 insertions(+) create mode 100644 sv-se/haskell-sv.html.markdown diff --git a/sv-se/haskell-sv.html.markdown b/sv-se/haskell-sv.html.markdown new file mode 100644 index 00000000..49a52069 --- /dev/null +++ b/sv-se/haskell-sv.html.markdown @@ -0,0 +1,461 @@ +--- +language: Haskell +filename: learnhaskell.hs +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Edward Tjörnhammar", "http://edwtjo.me"] +lang: sv-se +--- + +Haskell skapades för att vara ett praktiskt, rent, funktionellt +programmeringsspråk. Det är känt för sin använding av monader och dess +härledande typsystem men anledningen till att jag ständigt återbesöker språket +är på grund av dess elegans. Haskell gör programmering till ett rent nöje. + +```haskell +-- Radkommenterar börjar med två bindestreck. +{- Flerradskommentarer innesluts av vänster/höger måsvinge bindestreck +block på detta vis. +-} + +---------------------------------------------------- +-- 1. Fördefinierade datatyper och operatorer +---------------------------------------------------- + +-- Du har siffror +3 -- 3 + +-- Matte fungerar som förväntat +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Division är normalt inte heltalsdivision +35 / 4 -- 8.75 + +-- Heltalsdivision, här infix div +35 `div` 4 -- 8 + +-- Boolar (Sant och Falskt) är fördefinierade +True +False + +-- Samt dess operationer +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- I ovanstående exempel är `not` en funktion vilken bara tar ett argument. +-- Haskell behöver inte paranteser för sina funktionsanrop... alla argument +-- ges mellanslagsseparerade direkt efter funktionen. Det övergripande mönstret +-- är: +-- func arg1 arg2 arg3... +-- Se sektionen om funktioner för information om hur du skriver dina egna. + +-- Strängar och bokstäver +"Detta är en sträng" +'a' -- bokstav +'Du kan inte använda enkelfnutt för strängar.' -- fel! + +-- Strängar kan konkateneras +"Hej " ++ "världen!" -- "Hej världen!" + +-- En sträng är en lista av bokstäver +['H', 'e', 'j', 's', 'a', 'n'] -- "Hejsan" +"Detta är en sträng" !! 0 -- 'D' + + +---------------------------------------------------- +-- 2. Listor och Tupler +---------------------------------------------------- + +-- Varje element i en lista måste ha samma typ. +-- Dessa listor är ekvivalenta: +[1, 2, 3, 4, 5] +[1..5] + +-- Intervall är mångsidiga. +['A'..'F'] -- "ABCDEF" + +-- Man kan stega intervall. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- [] (Haskell förutsätter normalt inkrement) +[5,4..1] -- [5, 4, 3, 2, 1] + +-- Indexering in i en lista +[1..10] !! 3 -- 4 (nollindexerat) + +-- Man kan ha oändliga listor i Haskell! +[1..] -- listan över alla naturliga tal + +-- Oändliga listor fungerar enbart för att Haskell har "lat evaluering". +-- Det betyder att Haskell bara evaluerar de uttryck den måste. Du kan alltså +-- fråga efter det 1000:e elementet i en oändlig lista och Haskell kommer då ge +-- dig det: + +[1..] !! 999 -- 1000 + +-- Nu har Haskell evaluerat element 1 till 1000 i denna lista... men resten +-- av medlemmarna i denna oändliga lista existerar inte ännu! Haskell kommer +-- faktiskt inte utvärdera element den inte måste. + +-- Sammanslagning av två listor +[1..5] ++ [6..10] + +-- Lägg till 0 vid listhuvudet +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- fler listoperationer som huvud, svans, initiella samt sista +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- listomfattningar +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- med bivilkor +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Varje element i en tupel kan ha olika typ men en tupel kan bara ha en +-- fixerad, eller statisk, längd. +-- En tupel: +("haskell", 1) + +-- För att komma åt element i ett par, alltså en 2-tupel, finns +-- de fördefinierade funktionerna: +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Funktioner +---------------------------------------------------- +-- En enkel funktion med två parametrar +add a b = a + b + +-- Notera även att om du använder ghci (Haskellinterpretatorn) kommer du behöva +-- använda `let` namnbindning för att synliggöra din funktionsdeklaration, +-- alltså +let add a b = a + b + +-- För att använda funktionen +add 1 2 -- 3 + +-- Man kan även göra funktionsanropet infix, alltså mellan parametersättningen, +-- med hjälp av bakåtfnuttar: +1 `add` 2 -- 3 + +-- Du kan även definiera funktioner vars funktionsnamn avsaknar bokstäver! +-- Med hjälp av parenteser kan du därmed definiera operatorer (normalt infix)! +-- Följande är en operator för heltalsdivision, vilken förlitar sig på div: +(//) a b = a `div` b +35 // 4 -- 8 + +-- Funktionsvakter: ett enkelt sätt att grena ut dina funktioner +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- Mönstermatchning fungerar på liknande vis. Här ger vi tre olika +-- parametermatchningar för vårat fib-resulat. Haskell kommer automatiskt följa +-- första bästa träff, uppifrån ned, vars vänstra sida om likhetstecknet matchar +-- anroparens parametervärde. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Mönstermatchning på tupler: +foo (x, y) = (x + 1, y + 2) + +-- Mönstermatchning på listor. Här är `x` det första elementet i listan och `xs` +-- är resten av listan. Nu kan vi skriva våran egen map-funktion +minMap func [] = [] +minMap func (x:xs) = func x:(minMap func xs) + +-- Anonyma funktioner, eller lambdauttryck, skapas med hjälp av omvänt +-- snedstreck, följt av parametrarna +minMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Användning av fold (även kallad `inject`, `reduce`, osv.) tillsammans med en +-- anonym funktion. `fold1` är en vänstervikande funktion och använder första +-- värdet i listan som det initiella värdet för ackumulatorn. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Mer funktioner +---------------------------------------------------- + +-- Partiell applikation: +-- Om du inte anropar funktionen med alla sina argument +-- blir den partiellt applicerad. Det betyder att du erhåller en funktion där en +-- delmängd av parametrarna blivit värdesatta men några är fortfarande fria. +add a b = a + b +foo = add 10 -- foo är nu en funktion som tar ett nummer och lägger till 10 till + -- det +foo 5 -- 15 + +-- Ett annat sätt att skriva samma sak +foo = (10+) +foo 5 -- 15 + +-- Funktionskomposition: +-- Operatorn `.` kedjar ihop funktioner +-- Till exempel, nedan är `foo` en funktion som tar ett värde, den adderar 10 +-- till det, multiplicerar det resultatet med 4 och sen ersätts med det värdet. +foo = (4*) . (10+) + +-- 4*(10+5) = 60 +foo 5 -- 60 + +-- Precedensordning: +-- Haskell har en operator `$`. Denna operator applicerar en funktion till en +-- given parameter med dess precedens. I kontrast mot vanlig +-- funktionsapplikation, vilket har den högsta utvärderingsprioriteten 10 och +-- associerar till vänster, har denna prioritetsordning 0 och är +-- högerassociativ. Denna låga prioritet medför att parameteruttrycket till +-- höger om operatorn får det reducerat innan det appliceras till sin vänster. + +-- före +even (fib 7) -- falskt + +-- ekvivalent +even $ fib 7 -- falskt + +-- med funktionskomposition +even . fib $ 7 -- falskt + + +---------------------------------------------------- +-- 5. Typsignaturer +---------------------------------------------------- + +-- Haskell har ett väldigt starkt typsystem, alla giltiga uttryck har en typ. + +-- Några grundläggande typer: +5 :: Integer +"hello" :: String +True :: Bool + +-- Funktioner har också typer, +-- `not` tar en bool och returnerar en bool: +-- not :: Bool -> Bool + +-- Här är ett exempel på en funktionssignatur vilken beskriver en funktion som +-- reducerar två heltal till ett: +-- add :: Integer -> Integer -> Integer + +-- Trots att Haskell härleder typen på icke typsatta uttryck är det bra form att +-- explicit ange dessa för ens deklarerade funktioner: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Kontrollflöde och Ifsatser +---------------------------------------------------- + +-- if-sats +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- if-statser kan spridas över rader men indentering har betydelse +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case uttryck: följande är ett exempel på kommandoradsparsning +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell har inte loopar istället används recursion. +-- map applicerar en funktion över varje element i en lista + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- man kan deklarera en for funktion genom att använda map +for array func = map func array + +-- och därefter använda den tillsammans med en anonym funktion för att +-- efterlikna en loop +for [0..5] $ \i -> show i + +-- men vi kunde även ha skrivit på följande vis: +for [0..5] show + +-- Du kan använda foldl eller foldr för att reducera en lista +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Vilket är samma sak som +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl viker från vänster, foldr från höger +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Vilket alltså är samma sak som +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Datatyper +---------------------------------------------------- + +-- Såhär definierar du din egen datatyp i Haskell +data Color = Red | Blue | Green + +-- När du gjort det kan du använda den i funktionssignaturer och uttryck +say :: Color -> String +say Red = "Du är Rö!" +say Blue = "Du är Blå!" +say Green = "Du är Grön!" + +-- Dina datatyper kan även ta parametrar +data Maybe a = Nothing | Just a + +-- Följande uttryck är alla specialiseringar av typen Maybe +Just "hello" -- har typen `Maybe String` +Just 1 -- har typen `Maybe Int` +Nothing -- har typen `Maybe a` för alla `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Även om IO inte kan förstås fullt ut utan att först förklara monader är det +-- inte svårt att lära sig tillräckligt för att komma igång + +-- När ett Haskellprogram körs är det topnivåns main som körs. Main måste +-- returnerna ett värde av typen `IO a`, för någon typ `a`. Till exempel: + +main :: IO () +main = putStrLn $ "Hej, himmelen! " ++ (say Blue) +-- putStrLn har typen type String -> IO () + +-- Det är enkelt att göra IO om du kan implementera ditt program som en funktion +-- från String till String. Funktionen +-- interact :: (String -> String) -> IO () +-- tar denna funktion och matar den med strängdata från stdin och skriver ut +-- resultatet som en sträng på stdout + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Du kan tänka på värden av typen `IO ()` som att representera +-- händelsesekvenser du vill att din dator skall utföra, likt imperativa språk. +-- För att kedja ihop händelsesekvenser använder man ett syntaktiskt socker +-- kallat do-notation. Som exempel: + +sägHej :: IO () +sägHej = do + putStrLn "Vad heter du?" + namn <- getLine -- denna raden läser en rad från stdin och vi binder den till + -- funktionsnamnet `namn` + putStrLn $ "Hejsan, " ++ namn + +-- Övning: Skriv din egen version av interageringsfunktionen `interact` som bara +-- läser en rad från stdin, vanliga `interact` läser till EOF. + +-- Koden i sägHej kommer dock aldrig exekveras. Den enda handlingen som blir det +-- är som bekant utvärderingen av `main`. +-- För att köra `sägHej` kommentera ut definition av `main` ovan och +-- avkommentera nedanstående version: +-- main = sayHello + +-- Låt oss bättre förstå hur funktionen `getLine` vi just använde fungerar. Dess +-- typsignatur är: +-- getLine :: IO String +-- Du kan tänka på typen `IO a` som att representeras av ett datorprogram vilken +-- kommer generera ett värde av typen `a` när det exekveras (utöver allt annat +-- det kan tänkas göra). Vi kan därtill binda detta värde till ett namn för +-- återanvändning genom att använda `<-`. Vi kan även skapa våran egen handling +-- av typen `IO String`: + +handling :: IO String +handling = do + putStrLn "Detta är en rad, tihi" + input1 <- getLine + input2 <- getLine + -- Typen av hela `do` blocket är vad som står på sista raden. Här är även + -- `return` inte ett nyckelord i språket utan en funktion med en typsignatur + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Vi kan använda `return` på samma sätt som vi använde `getLine`: + +main'' = do + putStrLn "Jag kommer eka två rader!" + result <- handling + putStrLn result + putStrLn "Tack och hej leverpastej!" + +-- Typen `IO` är ett exempel på en monad. Sättet Haskell utnyttjar monader på är +-- anledningen till hur språket kan bibehålla sin renhet. En funktion vilken +-- interagerar med omvärlden (alltså gör IO) blir markerad med `IO` i sin +-- typsignatur. Detta låter oss enkelt upptäcka vilka funktioner som är "rena" +-- (inte interagerar med omvärlden eller är tillståndsoberoende) and vilka +-- funktioner som inte är det. + +-- Detta är ett mäktigt särdrag eftersom det är enkelt att köra rena funktioner +-- sammanlöpande; Samtidig programmering är enkel att göra i Haskell. + +---------------------------------------------------- +-- 9. Haskell REPL (kodtolk) +---------------------------------------------------- + +-- Efter installation av GHC kan vi starta tolken genom att skriva `ghci`. +-- Nu kan du mata in Haskellkod direkt i den. Nya värden måste introduceras med +-- `let` bindning: + +let foo = 5 + +-- Du kan även se typen av namnbindningen med `:t` + +> :t foo +foo :: Integer + +-- Operatorer, som `+`, `:` och `$` är funktioner. Deras typ kan inspekteras +-- genom att skriva operatorn mellan parenteser: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- Du kan få ytterliggare information om något namn genom att använda `:i` + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + +-- Du kan även köra alla handlingar av typen `IO ()` direkt i tolken + +> sägHej +Vad är ditt namn? +Kompis! +Hello, Kompis! + +``` + +Det finns mycket mer att upptäcka med Haskell, inklusive typklasser och monader. +Vilka är de stora idéerna som gör Haskell till det roliga programmeringsspråket +det är. Jag lämar dig med ett sista exempel; En implementation av quicksort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort mindre ++ [p] ++ qsort större + where mindre = filter (< p) xs + större = filter (>= p) xs +``` + +Det finns två populära sätt att installera Haskell på: Den traditionella [Cabal sättet](http://www.haskell.org/platform/), eller det nyare [Stack sättet](https://www.stackage.org/install). + +Du kan finna vänligare och/eller djupare introduktioner till Haskell på engelska +från: +[Learn you a Haskell](http://learnyouahaskell.com/), +[Happy Learn Haskell Tutorial](http://www.happylearnhaskelltutorial.com/) eller +[Real World Haskell](http://book.realworldhaskell.org/). -- cgit v1.2.3 From 1eb8534558ab8c5f60dcda5f50b518584fcdb5fa Mon Sep 17 00:00:00 2001 From: Tapmemer Date: Fri, 19 Jan 2018 09:43:50 +0100 Subject: typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix typo’s and other stuff --- nl-nl/bash-nl.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/nl-nl/bash-nl.html.markdown b/nl-nl/bash-nl.html.markdown index da47e2a9..af4a8cc8 100644 --- a/nl-nl/bash-nl.html.markdown +++ b/nl-nl/bash-nl.html.markdown @@ -17,8 +17,8 @@ lang: nl-nl filename: LearnBash-nl.sh --- -Bash is de naam van den unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X. -Bijna alle voorbeelden hier onder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell. +Bash is de naam van de unix shell, deze wordt gebruikt voor het GNU operating system en is de standaard shell op Linux en Mac OS X. +Bijna alle voorbeelden hieronder kunnen deel uitmaken van een shell script of kunnen uitgevoerd worden in de shell. [Lees er meer over hier.](http://www.gnu.org/software/bash/manual/bashref.html) @@ -28,23 +28,23 @@ Bijna alle voorbeelden hier onder kunnen deel uitmaken van een shell script of k # het script uitgevoerd moet worden: http://en.wikipedia.org/wiki/Shebang_(Unix) # Zoals je kan zien wordt # gebruikt om een commentaar lijn te starten. -# Simpel hello world voorbeeld: +# Een simpel hello world voorbeeld: echo Hello world! -# Elke command start op een nieuwe lijn, of achter een puntkomma (;): +# Elk commando start op een nieuwe lijn, of achter een puntkomma (;): echo 'Dit is de eerste lijn'; echo 'Dit is de tweede lijn' -# Een varialbe declareren gebeurt op volgende manier: +# Een variabele declareren gebeurt op volgende manier: Variabele="Een string" # Maar niet op deze manier: Variabele = "Een string" -# Bash ziet variable als een commando en zal een error geven omdat dit commando +# Bash ziet variabelen als een commando en zal een error geven omdat dit commando # niet bestaat. # Of op deze manier: Variabele= 'Een string' -# Bash zal 'Een string' zien als een commanda en een error geven omdat het niet +# Bash zal 'Een string' zien als een commando en een error geven omdat het niet # gevonden kan worden. # Variabelen gebruiken: @@ -83,7 +83,7 @@ echo "Wat is uw naam?" read Naam # Merk op dat we geen variabele gedeclareerd hebben echo Hallo, $Naam! -# We hebben ook if structuren +# We hebben ook logische if structuren # Gebruik 'man test' voor meer informatie over condities. if [ $Naam -ne $USER ] then -- cgit v1.2.3 From acf13c548b2ada661b6fe9616fbf4926659a6590 Mon Sep 17 00:00:00 2001 From: Tapmemer Date: Fri, 19 Jan 2018 10:02:36 +0100 Subject: copy copy D markdown to language folder for later translation --- nl-nl/d-nl.html.markdown | 260 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 nl-nl/d-nl.html.markdown diff --git a/nl-nl/d-nl.html.markdown b/nl-nl/d-nl.html.markdown new file mode 100644 index 00000000..d2a57cae --- /dev/null +++ b/nl-nl/d-nl.html.markdown @@ -0,0 +1,260 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] + +--- + +```d +// You know what's coming... +module hello; + +import std.stdio; + +// args is optional +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +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 +expressive high-level abstractions. + +D is actively developed by a large group of super-smart people and is spearheaded by +[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and +[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). +With all that out of the way, let's look at some examples! + +```d +import std.stdio; + +void main() { + + // Conditionals and loops work as expected. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // 'auto' can be used for inferring types. + auto n = 1; + + // Numeric literals can use '_' as a digit separator for clarity. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For and while are nice, but in D-land we prefer 'foreach' loops. + // The '..' creates a continuous range, including the first value + // but excluding the last. + foreach(n; 1..1_000_000) { + if(n % 2 == 0) + writeln(n); + } + + // There's also 'foreach_reverse' when you want to loop backwards. + foreach_reverse(n; 1..int.max) { + if(n % 2 == 1) { + writeln(n); + } else { + writeln("No!"); + } + } +} +``` + +We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions +are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore, +we can use templates to parameterize all of these on both types and values! + +```d +// Here, 'T' is a type parameter. Think '' from C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Use '!' to instantiate a parameterized type. Again, think ''. + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // If there is only one template parameter, we can omit the parentheses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Use alias to create abbreviations for types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// We can create function templates as well! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b' +// are value types, they will always be passed by reference to 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// With templates, we can also parameterize on values, not just types. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'. + +``` + +Speaking of classes, let's talk about properties for a second. A property +is roughly a function that may act like an lvalue, so we can +have the syntax of POD structures (`structure.x = 7`) with the semantics of +getter and setter methods (`object.setX(7)`)! + +```d +// Consider a class parameterized on types 'T' & 'U'. +class MyClass(T, U) { + T _data; + U _other; +} + +// And "getter" and "setter" methods like so: +class MyClass(T, U) { + T _data; + U _other; + + // Constructors are always named 'this'. + this(T t, U u) { + // This will call the setter methods below. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// And we use them in this manner: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Import the 'stdio' module from the standard library for writing to + // console (imports can be local to a scope). + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; + + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +With properties, we can add any amount of logic to +our getter and setter methods, and keep the clean syntax of +accessing members directly! + +Other object-oriented goodies at our disposal +include interfaces, abstract classes, +and overriding 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` +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! + +```d +import std.algorithm : map, filter, reduce; +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 function you like, but lambdas are convenient here. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(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 (UFCS). +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 +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! + +```d +// Let's say we want to populate a large array with the square root of all +// consecutive integers starting from 1 (up until the size of the array), and we +// want to do this concurrently taking advantage of as many cores as we have +// available. + +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // Create your large array + auto arr = new double[1_000_000]; + + // Use an index, access every array element by reference (because we're + // going to change each element) and just call parallel on the array! + foreach(i, ref elem; parallel(arr)) { + elem = sqrt(i + 1.0); + } +} +``` -- cgit v1.2.3 From 1cb515c563a654c09d94f7e962bd81290550a7bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edward=20Tj=C3=B6rnhammar?= Date: Thu, 18 Jan 2018 17:06:53 +0100 Subject: [nix/sv-se] initial --- sv-se/nix-sv.html.markdown | 368 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 sv-se/nix-sv.html.markdown diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown new file mode 100644 index 00000000..2a1af37e --- /dev/null +++ b/sv-se/nix-sv.html.markdown @@ -0,0 +1,368 @@ +--- +language: nix +filename: learn.nix +contributors: + - ["Chris Martin", "http://chris-martin.org/"] +translators: + - ["Edward Tjörnhammar", "http://edwtjo.me"] +lang: sv-se +--- + +Nix är ett enkelt funktionelt språk utvecklat för +[Nix pakethanteraren](https://nixos.org/nix/) och +[NixOS](https://nixos.org/) linuxdistributionen. + +Du kan utvärdera Nix uttryck genom att använda +[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) +eller [`nix-repl`](https://github.com/edolstra/nix-repl). + +``` +with builtins; [ + + # Kommentarer + #========================================= + + # Inlinekommentarer ser ut såhär. + + /* Flerradskommentarer ser ut + såhär. */ + + + # Booleaner + #========================================= + + (true && false) # Och + #=> false + + (true || false) # Eller + #=> true + + (if 3 < 4 then "a" else "b") # Villkorlig + #=> "a" + + + # Heltal + #========================================= + + # Heltal är den enda numeriska typen. + + 1 0 42 (-3) # Några heltal + + (4 + 6 + 12 - 2) # Addition + #=> 20 + + (7 / 2) # Division + #=> 3 + + + # Strängar + #========================================= + + "Stränglitteraler omgärdas av raka citationstecken." + + " + Stränglitteraler kan sträcka sig + över flera rader. + " + + '' + Detta kallas för en indenterad strängliteral, omgärdad av dubbla apostrofer + Den plockar intelligent bort ledande blanktecken. + '' + + '' + a + b + '' + #=> "a\n b" + + ("ab" + "cd") # Strängkonkatenering + #=> "abcd" + + # Antikvotering låter dig bädda in språkvärden i strängar. + ("Din hemkatalog är ${getEnv "HOME"}") + #=> "Din hemkatalog är /home/alice" + + + # Sökvägar + #========================================= + + # Nix har en primitiv, inbyggd, typ för sökvägar. + /tmp/tutorials/learn.nix + + # Relativa sökvägar förenas med sökvägen till dess definerande fils sökväg + # vid tolkningstillfället för att skapa dess absoluta sökväg. + + tutorials/learn.nix + #=> /the-base-path/tutorials/learn.nix + + # En sökväg måste innehålla åtminstonde ett snedstreck, så en relativ sökväg + # till en fil i samma katalog måste ges ett "./" prefix + + ./learn.nix + #=> /the-base-path/learn.nix + + # Divisionsoperatorn / måste omges av blanksteg om man vill att det skall + # tolkas som heltalsdivision + + 7/2 # Detta är en sökväg + (7 / 2) # Detta är heltalsdivision + + + # Importer + #========================================= + + # En nix fil innehåller ett enstaka topnivåuttryck utan fria variabler. + # Ett importuttryck evalueras till värdet på filen som den importerar. + (import /tmp/foo.nix) + + # Importer kan också specificeras med hjälp av strängar. + (import "/tmp/foo.nix") + + # Importsökvägar måste vara absoluta. Sökvägslitteraler härleds vid + # tolkningstillfället så följande är ok. + (import ./foo.nix) + + # Men detta är inte något som sker med strängar. + (import "./foo.nix") + #=> error: string ‘foo.nix’ doesn't represent an absolute path + + + # Let + #========================================= + + # `let` block tillåter oss att binda värden till namn. + (let x = "a"; in + x + x + x) + #=> "aaa" + + # Bindingar kan referera till varandra och deras ordning sinsemellan spelar + # ingen roll. + (let y = x + "b"; + x = "a"; in + y + "c") + #=> "abc" + + # Innre bindningar skuggar utanpåliggande bindingar. + (let a = 1; in + let a = 2; in + a) + #=> 2 + + + # Funktioner + #========================================= + + (n: n + 1) # En lambdafunktion som lägger till 1 + + ((n: n + 1) 5) # Samma funktion applicerad på 5 + #=> 6 + + # Det finns ingen syntax för direkt namngivna funktioner, istället binder man + # dessa med `let` block som andra värden. + (let succ = (n: n + 1); in succ 5) + #=> 6 + + # En funktion är en lambda med en parameter. Flera parameterar kan ges med + # hjälp av currying. + ((x: y: x + "-" + y) "a" "b") + #=> "a-b" + + # Vi kan också ha namngivna funktionsparametrar, vilket vi kommer komma till + # senare, efter att vi introducerat attributset. + + # Listor + #========================================= + + # Listor noteras med hakparenteser. + + (length [1 2 3 "x"]) + #=> 4 + + ([1 2 3] ++ [4 5]) + #=> [1 2 3 4 5] + + (concatLists [[1 2] [3 4] [5]]) + #=> [1 2 3 4 5] + + (head [1 2 3]) + #=> 1 + (tail [1 2 3]) + #=> [2 3] + + (elemAt ["a" "b" "c" "d"] 2) + #=> "c" + + (elem 2 [1 2 3]) + #=> true + (elem 5 [1 2 3]) + #=> false + + (filter (n: n < 3) [1 2 3 4]) + #=> [ 1 2 ] + + + # Mängder + #========================================= + + # Ett attributset är en oordnad mappning av strängnycklar och värden. + { foo = [1 2]; bar = "x"; } + + # Punktoperatorn . väljer ett värde från attributset:et + { a = 1; b = 2; }.a + #=> 1 + + # Frågeoperatorn ? testar om en nyckel är närvarande i ett attributset + ({ a = 1; b = 2; } ? a) + #=> true + ({ a = 1; b = 2; } ? c) + #=> false + + # Snedstrecksoperatorn // slår ihop två attributset:ar. + ({ a = 1; } // { b = 2; }) + #=> { a = 1; b = 2; } + + # Värden på höger skriver över värden till vänster. + ({ a = 1; b = 2; } // { a = 3; c = 4; }) + #=> { a = 3; b = 2; c = 4; } + + # Recursionsnyckelordet rec noterar ett rekursivt attributset (en fixpunkt) + # i vilket attributen kan referera till varandra. + (let a = 1; in { a = 2; b = a; }.b) + #=> 1 + (let a = 1; in rec { a = 2; b = a; }.b) + #=> 2 + + # Nästlade attributset:ar kan definieras bit för bit. + { + a.b = 1; + a.c.d = 2; + a.c.e = 3; + }.a.c + #=> { d = 2; e = 3; } + + # Ett attributsets barn kan inte tilldelas på detta vis om attributsetet + # självt blivit direkt tilldelat. + { + a = { b = 1; }; + a.c = 2; + } + #=> error: attribute ‘a’ already defined + + + # Bindningsintroduktion, `with` + #========================================= + + # Det attributset vilket återfinns i ett `with` uttryck kommer få sina + # värdebindningar introducerade i efterkommande uttryck. + (with { a = 1; b = 2; }; + a + b) + # => 3 + + # Innre bindningar skuggar yttre bindningar. + (with { a = 1; b = 2; }; + (with { a = 5; }; + a + b)) + #=> 7 + + # Första raden av detta exempel börjar med "with builtins;" eftersom builtins + # är ett attributset innehållande alla inbyggda hjälpfunktioner såsom + # (length, head, tail, filter, etc.). Detta sparar oss från att hela tiden + # referera in i det attributset:et , alltså du kan använda bara "length" + # istället för "builtins.length". + + + # Attributsetmönster + #========================================= + + # Attributset är användbara när vi skall skicka med flera värden till en + # funktion. + (args: args.x + "-" + args.y) { x = "a"; y = "b"; } + #=> "a-b" + + # Man kan använda attributsetmönster för ökad tydlighet. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; } + #=> "a-b" + + # Attributmönster misslyckas dock om det medskickade attributmönstret + # innehåller extra nycklar. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> error: anonymous function called with unexpected argument ‘z’ + + # Genom att lägga till ", ..." kan vi ignorera ytterliggare nycklar. + ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> "a-b" + + + # Felmeddelanden + #========================================= + + # `throw` gör att programtolken gör abort med dess tillhörande felmeddelande + causes evaluation to abort with an error message. + (2 + (throw "foo")) + #=> error: foo + + # `tryEval` fångar kastade fel `throw`. + (tryEval 42) + #=> { success = true; value = 42; } + (tryEval (2 + (throw "foo"))) + #=> { success = false; value = false; } + + # `abort` fungerar som `throw`, men är kritiskt och kan inte fångas. + (tryEval (abort "foo")) + #=> error: evaluation aborted with the following error message: ‘foo’ + + # `assert` utvärderas till det givna värdet om dess predikat är sant. + # annars skickar den ett fångbart fel. + (assert 1 < 2; 42) + #=> 42 + (assert 1 > 2; 42) + #=> error: assertion failed at (string):1:1 + (tryEval (assert 1 > 2; 42)) + #=> { success = false; value = false; } + + + # Orenhet + #========================================= + + # Eftersom repeterbarhet för byggen är en kritisk egenskap för + # Nix-pakethanteraren betonas funktionell renhet i Nix-programmeringsspråket. + # Men med det sagt existerar det källor till orenhet + + # Man kan referera till miljövariabler. + (getEnv "HOME") + #=> "/home/alice" + + # `trace` funktionen används för att debugga. Den skriver ut första argumentet + # till stderr och reduceras samtidigt till det andra argumentet. + (trace 1 2) + #=> trace: 1 + #=> 2 + + # Man kan skriva filer till Nix-store, lagringsplatsen för alla Nix-uttryck. + # Även om detta är orent beteende är det hyfsat säkert eftersom filens + # lagringsplats är härledd från dess innehåll och beroenden. Man kan läsa + # filer från precis överallt. I nedanstående exempel skriver vi en fil till + # Nix-store och sedan läser tillbaka den. + + (let filename = toFile "foo.txt" "hello!"; in + [filename (builtins.readFile filename)]) + #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] + + # Vi kan också ladda ned filer till Nix-store. + (fetchurl "https://example.com/package-1.2.3.tgz") + #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" + +] +``` + +### Vidare Läsning (eng) + +* [Nix Manual - Nix expression language] + (https://nixos.org/nix/manual/#ch-expression-language) + +* [James Fisher - Nix by example - Part 1: The Nix expression language] + (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) + +* [Susan Potter - Nix Cookbook - Nix By Example] + (http://funops.co/nix-cookbook/nix-by-example/) -- cgit v1.2.3 From 0d0b536b28d7f3ed8d35cc557142b15d52299526 Mon Sep 17 00:00:00 2001 From: Simon Siegert Date: Thu, 25 Jan 2018 20:56:33 +0100 Subject: Fix naming of constant --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 10f01ebc..acc258b4 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -29,7 +29,7 @@ let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean -// Use const keyword for constant variables +// Use const keyword for constants const numLivesForCat = 9; numLivesForCat = 1; // Error -- cgit v1.2.3 From 7cd43d8ad42b61948d2c571c202ee9b3d210e153 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Thu, 25 Jan 2018 13:51:15 -0800 Subject: [yaml/en] Use preferred style; add missing uses * YAML allows literal tabs in content, but not indentation. * Two space indent always preferred. * Note: YAML dumpers always use 2 space by default. * '- ...' doesn't need extra indentation. * Note: YAML dumpers don't use extra indentation. * There was no mention of single quoted strings. They are preferred and should be used except when double quote semantics are actually required. (Best practice). * Add flow form example for sets: `{a, b, c}` * Show collapsed form of seq-in-seq: `- - - foo`. --- yaml.html.markdown | 81 +++++++++++++++++++++++++++++------------------------- 1 file changed, 44 insertions(+), 37 deletions(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 3b32a069..52658453 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -2,8 +2,8 @@ language: yaml filename: learnyaml.yaml contributors: - - ["Adam Brenecki", "https://github.com/adambrenecki"] - - ["Suhas SG", "https://github.com/jargnar"] +- [Adam Brenecki, 'https://github.com/adambrenecki'] +- [Suhas SG, 'https://github.com/jargnar'] --- YAML is a data serialisation language designed to be directly writable and @@ -11,7 +11,7 @@ readable by humans. It's a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, -YAML doesn't allow literal tab characters at all. +YAML doesn't allow literal tab characters for indentation. ```yaml # Comments in YAML look like this. @@ -32,8 +32,10 @@ boolean: true null_value: null key with spaces: value # Notice that strings don't need to be quoted. However, they can be. -however: "A string, enclosed in quotes." -"Keys can be quoted too.": "Useful if you want to put a ':' in your key." +however: 'A string, enclosed in quotes.' +'Keys can be quoted too.': "Useful if you want to put a ':' in your key." +single quotes: 'have ''one'' escape pattern' +double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more." # Multiple-line strings can be written either as a 'literal block' (using |), # or a 'folded block' (using '>'). @@ -59,12 +61,12 @@ folded_style: > # COLLECTION TYPES # #################### -# Nesting is achieved by indentation. +# Nesting uses indentation. 2 space indent is preferred (but not required). a_nested_map: - key: value - another_key: Another Value - another_nested_map: - hello: hello + key: value + another_key: Another Value + another_nested_map: + hello: hello # Maps don't have to have string keys. 0.25: a float key @@ -72,8 +74,8 @@ a_nested_map: # Keys can also be complex, like multi-line objects # We use ? followed by a space to indicate the start of a complex key. ? | - This is a key - that has multiple lines + This is a key + that has multiple lines : and this is its value # YAML also allows mapping between sequences with the complex key syntax @@ -83,22 +85,26 @@ a_nested_map: - Real Madrid : [ 2001-01-01, 2002-02-02 ] -# Sequences (equivalent to lists or arrays) look like this: +# Sequences (equivalent to lists or arrays) look like this +# (note that the '-' counts as indentation): a_sequence: - - Item 1 - - Item 2 - - 0.5 # sequences can contain disparate types. - - Item 4 - - key: value - another_key: another_value - - - - This is a sequence - - inside another sequence +- Item 1 +- Item 2 +- 0.5 # sequences can contain disparate types. +- Item 4 +- key: value + another_key: another_value +- + - This is a sequence + - inside another sequence +- - - Nested sequence indicators + - can be collapsed # Since YAML is a superset of JSON, you can also write JSON-style maps and # sequences: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] +and quotes are optional: {key: [3, 2, 1, takeoff]} ####################### # EXTRA YAML FEATURES # @@ -111,15 +117,15 @@ other_anchor: *anchor_name # Anchors can be used to duplicate/inherit properties base: &base - name: Everyone has same name + name: Everyone has same name foo: &foo - <<: *base - age: 10 + <<: *base + age: 10 bar: &bar - <<: *base - age: 20 + <<: *base + age: 20 # foo and bar would also have name: Everyone has same name @@ -147,22 +153,23 @@ date: 2002-12-14 # The !!binary tag indicates that a string is actually a base64-encoded # representation of a binary blob. gif_file: !!binary | - R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 - OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ - +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC - AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= # YAML also has a set type, which looks like this: set: - ? item1 - ? item2 - ? item3 + ? item1 + ? item2 + ? item3 +or: {item1, item2, item3} # Like Python, sets are just maps with null values; the above is equivalent to: set2: - item1: null - item2: null - item3: null + item1: null + item2: null + item3: null ``` ### More Resources -- cgit v1.2.3 From 60fcfe86621980a2f98d19fee386c1d0cc4f61db Mon Sep 17 00:00:00 2001 From: Rommel Martinez Date: Sat, 3 Feb 2018 17:28:21 +0800 Subject: [python/en]: fix typo --- python.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 89fa7046..df1ca6f2 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -7,6 +7,7 @@ contributors: - ["evuez", "http://github.com/evuez"] - ["asyne", "https://github.com/justblah"] - ["habi", "http://github.com/habi"] + - ["Rommel Martinez", "https://ebzzry.io"] filename: learnpython.py --- @@ -508,9 +509,9 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand positional args and use ** to expand keyword args. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) # you can pass args and kwargs along to other functions that take args/kwargs -- cgit v1.2.3 From 213019c689323af7f5c531fb156c34abe8771960 Mon Sep 17 00:00:00 2001 From: Rommel Martinez Date: Sat, 3 Feb 2018 18:08:24 +0800 Subject: [python3/en]: fix typo --- python3.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 37987582..864228e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] filename: learnpython3.py --- @@ -546,9 +547,9 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): -- cgit v1.2.3 From 05f090fba414cde1b7dc48dca803b9a80cb17f63 Mon Sep 17 00:00:00 2001 From: saplf Date: Tue, 6 Feb 2018 13:44:31 +0800 Subject: More idiomaticallywq --- zh-cn/kotlin-cn.html.markdown | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown index 5d655029..f6dcd847 100644 --- a/zh-cn/kotlin-cn.html.markdown +++ b/zh-cn/kotlin-cn.html.markdown @@ -22,7 +22,7 @@ package com.learnxinyminutes.kotlin /* Kotlin程序的入口点是一个"main"函数 -该函数传递一个包含任何命令行参数的数组。 +该函数传递一个包含所有命令行参数的数组。 */ fun main(args: Array) { /* @@ -67,10 +67,10 @@ fun helloWorld(val name : String) { 模板表达式从一个美元符号($)开始。 */ val fooTemplateString = "$fooString has ${fooString.length} characters" - println(fooTemplateString) + println(fooTemplateString) // => 输出 My String Is Here! has 18 characters /* - 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 + 当某个变量的值可以为 null 的时候,我们必须明确指定它是可为空的。 在变量声明处的类型后面加上?来标识它是可为空的。 我们可以用?.操作符来访问可为空的变量。 我们可以用?:操作符来指定一个在变量为空时使用的替代值。 @@ -96,24 +96,24 @@ fun helloWorld(val name : String) { println(hello()) // => Hello, world! /* - 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数 + 函数的可变参数可使用 "vararg" 关键字来修饰 */ fun varargExample(vararg names: Int) { println("Argument has ${names.size} elements") } - varargExample() // => Argument has 0 elements - varargExample(1) // => Argument has 1 elements - varargExample(1, 2, 3) // => Argument has 3 elements + varargExample() // => 传入 0 个参数 + varargExample(1) // => 传入 1 个参数 + varargExample(1, 2, 3) // => 传入 3 个参数 /* - 当函数只包含一个单独的表达式时,大括号可以被省略。 - 函数体可以被指定在一个=符号后面。 + 当函数只包含一个单独的表达式时,大括号可以省略。 + 函数体可以写在一个=符号后面。 */ fun odd(x: Int): Boolean = x % 2 == 1 println(odd(6)) // => false println(odd(7)) // => true - // 如果返回值类型可以被推断,那么我们不需要指定它。 + // 如果返回值类型可以推断,那么我们不需要指定它。 fun even(x: Int) = x % 2 == 0 println(even(6)) // => true println(even(7)) // => false @@ -122,15 +122,14 @@ fun helloWorld(val name : String) { fun not(f: (Int) -> Boolean) : (Int) -> Boolean { return {n -> !f.invoke(n)} } - // 命名函数可以用::运算符被指定为参数。 + // 普通函数可以用::运算符传入引用作为函数参数。 val notOdd = not(::odd) val notEven = not(::even) - // 匿名函数可以被指定为参数。 + // lambda 表达式可以直接作为参数传递。 val notZero = not {n -> n == 0} /* - 如果一个匿名函数只有一个参数 - 那么它的声明可以被省略(连同->)。 - 这个参数的名字是"it"。 + 如果一个 lambda 表达式只有一个参数 + 那么它的声明可以省略(连同->),内部以 "it" 引用。 */ val notPositive = not {it > 0} for (i in 0..4) { @@ -152,7 +151,7 @@ fun helloWorld(val name : String) { 注意,Kotlin没有"new"关键字。 */ val fooExampleClass = ExampleClass(7) - // 可以使用一个点号来调用成员函数。 + // 可以使用一个点号来调用成员方法。 println(fooExampleClass.memberFunction(4)) // => 11 /* 如果使用"infix"关键字来标记一个函数 @@ -162,7 +161,7 @@ fun helloWorld(val name : String) { /* 数据类是创建只包含数据的类的一个简洁的方法。 - "hashCode"、"equals"和"toString"方法将被自动生成。 + "hashCode"、"equals"和"toString"方法将自动生成。 */ data class DataClassExample (val x: Int, val y: Int, val z: Int) val fooData = DataClassExample(1, 2, 4) -- cgit v1.2.3 From c90ee7202e5bb3a00fa4c7159b57586c3aef8ea8 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 15 Feb 2018 10:57:27 +0700 Subject: [go/en] Small typo Small typo in command line commad --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index e5263cf6..47d9c234 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -180,7 +180,7 @@ func learnFlowControl() { if true { fmt.Println("told ya") } - // Formatting is standardized by the command line command "go fmt." + // Formatting is standardized by the command line command "go fmt". if false { // Pout. } else { -- cgit v1.2.3 From daa8e8e695058aea5022813b15ff5476771e18f3 Mon Sep 17 00:00:00 2001 From: xuty Date: Sat, 17 Feb 2018 21:03:51 +0800 Subject: Translate --- zh-cn/crystal-cn.html.markdown | 567 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 567 insertions(+) create mode 100644 zh-cn/crystal-cn.html.markdown diff --git a/zh-cn/crystal-cn.html.markdown b/zh-cn/crystal-cn.html.markdown new file mode 100644 index 00000000..14805114 --- /dev/null +++ b/zh-cn/crystal-cn.html.markdown @@ -0,0 +1,567 @@ +--- +language: crystal +filename: learncrystal-cn.cr +contributors: + - ["Vitalii Elenhaupt", "http://veelenga.com"] + - ["Arnaud Fernandés", "https://github.com/TechMagister/"] +translators: + - ["Xuty", "https://github.com/xtyxtyx"] +lang: zh-cn +--- + +```crystal + +# 这是一行注释 + +# 一切都是对象(object) +nil.class #=> Nil +100.class #=> Int32 +true.class #=> Bool + +# nil, false 以及空指针是假值(falsey values) +!nil #=> true : Bool +!false #=> true : Bool +!0 #=> false : Bool + +# 整数类型 + +1.class #=> Int32 + +# 四种有符号整数 +1_i8.class #=> Int8 +1_i16.class #=> Int16 +1_i32.class #=> Int32 +1_i64.class #=> Int64 + +# 四种无符号整数 +1_u8.class #=> UInt8 +1_u16.class #=> UInt16 +1_u32.class #=> UInt32 +1_u64.class #=> UInt64 + +2147483648.class #=> Int64 +9223372036854775808.class #=> UInt64 + +# 二进制数 +0b1101 #=> 13 : Int32 + +# 八进制数 +0o123 #=> 83 : Int32 + +# 十六进制数 +0xFE012D #=> 16646445 : Int32 +0xfe012d #=> 16646445 : Int32 + +# 浮点数类型 + +1.0.class #=> Float64 + +# Crystal中有两种浮点数 +1.0_f32.class #=> Float32 +1_f32.class #=> Float32 + +1e10.class #=> Float64 +1.5e10.class #=> Float64 +1.5e-7.class #=> Float64 + +# 字符类型 + +'a'.class #=> Char + +# 八进制字符 +'\101' #=> 'A' : Char + +# Unicode字符 +'\u0041' #=> 'A' : Char + +# 字符串 + +"s".class #=> String + +# 字符串不可变(immutable) +s = "hello, " #=> "hello, " : String +s.object_id #=> 134667712 : UInt64 +s += "Crystal" #=> "hello, Crystal" : String +s.object_id #=> 142528472 : UInt64 + +# 支持字符串插值(interpolation) +"sum = #{1 + 2}" #=> "sum = 3" : String + +# 多行字符串 +"这是一个 + 多行字符串" + +# 书写带有引号的字符串 +%(hello "world") #=> "hello \"world\"" + +# 符号类型 +# 符号是不可变的常量,本质上是Int32类型 +# 符号通常被用来代替字符串,来高效地传递特定的值 + +:symbol.class #=> Symbol + +sentence = :question? # :"question?" : Symbol + +sentence == :question? #=> true : Bool +sentence == :exclamation! #=> false : Bool +sentence == "question?" #=> false : Bool + +# 数组类型(Array) + +[1, 2, 3].class #=> Array(Int32) +[1, "hello", 'x'].class #=> Array(Int32 | String | Char) + +# 必须为空数组指定类型 +[] # Syntax error: for empty arrays use '[] of ElementType' +[] of Int32 #=> [] : Array(Int32) +Array(Int32).new #=> [] : Array(Int32) + +# 数组可以通过下标访问 +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] : Array(Int32) +array[0] #=> 1 : Int32 +array[10] # raises IndexError +array[-6] # raises IndexError +array[10]? #=> nil : (Int32 | Nil) +array[-6]? #=> nil : (Int32 | Nil) + +# 使用负位置编号,从后往前访问数组 +array[-1] #=> 5 + +# With a start index and size +# 使用起始位置编号+大小 +array[2, 3] #=> [3, 4, 5] + +# 使用范围(range)访问数组 +array[1..3] #=> [2, 3, 4] + +# 向尾部添加元素 +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# 删除尾部元素 +array.pop #=> 6 +array #=> [1, 2, 3, 4, 5] + +# 删除首部元素 +array.shift #=> 1 +array #=> [2, 3, 4, 5] + +# 检查元素是否存在与数组之中 +array.includes? 3 #=> true + +# 一种特殊语法,用来创建字符串数组或符号数组 +%w(one two three) #=> ["one", "two", "three"] : Array(String) +%i(one two three) #=> [:one, :two, :three] : Array(Symbol) + +# 对于定义了`new`和`#<<`方法的类,可以用以下语法创建新对象 +set = Set{1, 2, 3} #=> [1, 2, 3] +set.class #=> Set(Int32) + +# 以下代码与上方等同 +set = Set(typeof(1, 2, 3)).new +set << 1 +set << 2 +set << 3 + +# 哈希表类型(Hash) + +{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32) +{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32) + +# 必须为空哈希表指定类型 +{} # Syntax error +{} of Int32 => Int32 # {} +Hash(Int32, Int32).new # {} + +# 可以使用键(key)快速查询哈希表 +hash = {"color" => "green", "number" => 5} +hash["color"] #=> "green" +hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError) +hash["no_such_key"]? #=> nil + +# 检查某一键哈希表中是否存在 +hash.has_key? "color" #=> true + +# 对于定义了`#[]=`方法的类,可以使用以下语法创建对象 +class MyType + def []=(key, value) + puts "do stuff" + end +end + +MyType{"foo" => "bar"} + +# 以上与下列代码等同 +tmp = MyType.new +tmp["foo"] = "bar" +tmp + +# 范围类型(Range) + +1..10 #=> Range(Int32, Int32) +Range.new(1, 10).class #=> Range(Int32, Int32) + +# 包含或不包含端点 +(3..5).to_a #=> [3, 4, 5] +(3...5).to_a #=> [3, 4] + +# 检查某一值是否在范围内 +(1..8).includes? 2 #=> true + +# 元组类型(Tuple) + +# 元组类型尺寸固定,不可变,储存在栈中 +# 元组可以有不同类型的对象组成 +{1, "hello", 'x'}.class #=> Tuple(Int32, String, Char) + +# 使用下标访问元组 +tuple = {:key1, :key2} +tuple[1] #=> :key2 +tuple[2] #=> syntax error : Index out of bound + +# 将元组中的元素赋值给变量 +a, b, c = {:a, 'b', "c"} +a #=> :a +b #=> 'b' +c #=> "c" + +# 命名元组类型(NamedTuple) + +tuple = {name: "Crystal", year: 2011} # NamedTuple(name: String, year: Int32) +tuple[:name] # => "Crystal" (String) +tuple[:year] # => 2011 (Int32) + +# 命名元组的键可以是字符串常量 +{"this is a key": 1} # => NamedTuple("this is a key": Int32) + +# 过程类型(Proc) +# 过程代表一个函数指针,以及可选的上下文(闭包) +# 过程通常使用字面值创建 +proc = ->(x : Int32) { x.to_s } +proc.class # Proc(Int32, String) + +# 或者使用`new`方法创建 +Proc(Int32, String).new { |x| x.to_s } + +# 使用`call`方法调用过程 +proc.call 10 #=> "10" + +# 控制语句(Control statements) + +if true + "if 语句" +elsif false + "else-if, 可选" +else + "else, 同样可选" +end + +puts "可以将if后置" if true + +# 将if作为表达式 +a = if 2 > 1 + 3 + else + 4 + end + +a #=> 3 + +# 条件表达式 +a = 1 > 2 ? 3 : 4 #=> 4 + +# `case`语句 +cmd = "move" + +action = case cmd + when "create" + "Creating..." + when "copy" + "Copying..." + when "move" + "Moving..." + when "delete" + "Deleting..." +end + +action #=> "Moving..." + +# 循环 +index = 0 +while index <= 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +index = 0 +until index > 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +# 更好的做法是使用`each` +(0..3).each do |index| + puts "Index: #{index}" +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +# 变量的类型取决于控制语句中表达式的类型 +if a < 3 + a = "hello" +else + a = true +end +typeof a #=> (Bool | String) + +if a && b + # 此处`a`与`b`均为Nil +end + +if a.is_a? String + a.class #=> String +end + +# 函数(Functions) + +def double(x) + x * 2 +end + +# 函数(以及所有代码块)均将最末尾表达式的值作为返回值 +double(2) #=> 4 + +# 在没有歧义的情况下,括号可以省略 +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# 使用逗号分隔参数 +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# 所有函数都有一个默认生成、可选的代码块(block)参数 +# 在函数中可以使用yield调用此代码块 + +def surround + puts '{' + yield + puts '}' +end + +surround { puts "hello world" } + +# { +# hello world +# } + + +# 可将代码块作为参数传给函数 +# "&" 表示对代码块参数的引用 +def guests(&block) + block.call "some_argument" +end + +# 使用星号"*"将参数转换成元组 +def guests(*array) + array.each { |guest| puts guest } +end + +# 如果函数返回数组,可以将其解构 +def foods + ["pancake", "sandwich", "quesadilla"] +end +breakfast, lunch, dinner = foods +breakfast #=> "pancake" +dinner #=> "quesadilla" + +# 按照约定,所有返回布尔值的方法都以问号结尾 +5.even? # false +5.odd? # true + +# 以感叹号结尾的方法,都有一些破坏性(destructive)行为,比如改变调用接收者(receiver) +# 对于某些方法,带有感叹号的版本将改变调用接收者,而不带有感叹号的版本返回新值 +company_name = "Dunder Mifflin" +company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin" +company_name #=> "Dunder Mifflin" +company_name.gsub! "Dunder", "Donald" +company_name #=> "Donald Mifflin" + + +# 使用`class`关键字来定义类(class) +class Human + + # 类变量,由类的所有实例所共享 + @@species = "H. sapiens" + + # `name`的类型为`String` + @name : String + + # 构造器方法(initializer) + # 其中@name、@age为简写,相当于 + # + # def initialize(name, age = 0) + # @name = name + # @age = age + # end + # + # `age`为可选参数,如果未指定,则使用默认值0 + def initialize(@name, @age = 0) + end + + # @name的setter方法 + def name=(name) + @name = name + end + + # @name的getter方法 + def name + @name + end + + # 上述getter与setter的定义可以用property宏简化 + property :name + + # 也可用getter与setter宏独立创建getter与setter + getter :name + setter :name + + # 此处的`self.`使`say`成为类方法 + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# 将类实例化 +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# 调用一些实例方法 +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# 调用类方法 +Human.say("Hi") #=> 输出 Hi ,返回 nil + +# 带有`@`前缀的变量为实例变量 +class TestClass + @var = "I'm an instance var" +end + +# 带有`@@`前缀的变量为类变量 +class TestClass + @@var = "I'm a class var" +end +# 首字母大写的变量为常量 +Var = "这是一个常量" +Var = "无法再次被赋值" # 常量`Var`已经被初始化 + +# 在crystal中类也是对象(object),因此类也有实例变量(instance variable) +# 类变量的定义由类以及类的派生类所共有,但类变量的值是独立的 + +# 基类 +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# 派生类 +class Worker < Human +end + +Human.foo #=> 0 +Worker.foo #=> 0 + +Human.foo = 2 #=> 2 +Worker.foo #=> 0 + +Worker.foo = 3 #=> 3 +Human.foo #=> 2 +Worker.foo #=> 3 + +module ModuleExample + def foo + "foo" + end +end + +# include 将模块(module)中的方法添加为实例方法 +# extend 将模块中的方法添加为类方法 + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => undefined method 'foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => undefined method 'foo' for Book + + +# 异常处理 + +# 定义新的异常类(exception) +class MyException < Exception +end + +# 再定义一个异常类 +class MyAnotherException < Exception; end + +ex = begin + raise MyException.new +rescue ex1 : IndexError + "ex1" +rescue ex2 : MyException | MyAnotherException + "ex2" +rescue ex3 : Exception + "ex3" +rescue ex4 # 捕捉任何类型的异常 + "ex4" +end + +ex #=> "ex2" + +``` + +## 参考资料 + +- [官方网站](https://crystal-lang.org/) +- [官方文档](https://crystal-lang.org/docs/overview/) +- [在线运行代码](https://play.crystal-lang.org/#/cr) +- [Github仓库](https://github.com/crystal-lang/crystal) -- cgit v1.2.3 From 999e0ce3d7bdcfdb87a9c0ca7515efce2eff50a2 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 20 Feb 2018 00:07:05 -0800 Subject: Delete bf-it.html.markdown Whoops! We already had a bf article. --- bf-it.html.markdown | 88 ----------------------------------------------------- 1 file changed, 88 deletions(-) delete mode 100644 bf-it.html.markdown diff --git a/bf-it.html.markdown b/bf-it.html.markdown deleted file mode 100644 index 1f544a09..00000000 --- a/bf-it.html.markdown +++ /dev/null @@ -1,88 +0,0 @@ ---- -language: "Brainfuck" -filename: brainfuck.bf -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] - - ["Alexandru Cazacu", "https://github.com/alexandru-cazacu"] -lang: it-it ---- - -Brainfuck (maiuscolo solo all'inizio di una frase) è un linguaggio di -programmazione Turing-completo estremamente minimalistico composto da soli 8 comandi. - -Potete provare brainfuck sul vostro browser tramite [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -```bf -Ciascun carattere tranne "><+-.,[]" (escluse le virgolette) è ignorato. - -Brainfuck è rappresentato da un array di 30,000 celle inizializzate a zero -e da un puntatore che punta alla cella corrente. - -Ci sono otto comandi: -+ : Incrementa il valore nella cella corrente di uno. -- : Decrementa il valore nella cella corrente di uno. -> : Muove il puntatore alla cella successiva (cella a destra). -< : Muove il puntatore alla cella precedente (cella a sinistra). -. : Stampa il valore ASCII nella cella corrente (es. 65 = 'A'). -, : Legge un singolo carattere in input nella cella corrente. -[ : Se il valore nella cella corrente è zero, salta al corrispondente ] . - Altrimenti vai alla prossima istruzione. -] : Se il valore nella cella corrente è zero, vai alla prossima istruzione. - Altrimenti salta al corrispondente [ . - -[ and ] formano un ciclo while. Ovviamente devono essere in numero uguale. - -Diamo un'occhiata ad alcuni programmi brainfuck basilari. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Questo programma stampa la lettera 'A'. Prima, incrementa la cella #1 a 6. -La cella #1 sarà usata per il ciclo. Poi, entra nel ciclo ([) e si sposta -alla cella #2. Incrementa la cella #2 10 volte, ritorna indietro alla cella #1 -e la decrementa. Questo ciclo avviene 6 volte (servo 6 decrementi affinchè -la cella #1 raggiunga 0, a quel punto salta al corrispondente ] e continua -l'esecuzione). - -A questo punto siamo nella cella #1, che ha un valore di 0, mentre la -cella #2 ha un valore di 60. Ci muoviamo alla cella #2, la incrementiamo -5 volte, per arrivare a 65 e poi stampiamo il valore della cella #2. -65 equivale ad 'A' in ASCII, quindi 'A' viene stampato nel terminale. - -, [ > + < - ] > . - -Questo programma legge un carattere immesso dall'utente e lo copia nella -cella #1. Poi inizi un loop. Si muove nella cella #2, incrementa il valore -della cella #2, si muove alla cella #1 e decrementa il suo valore. Questo -ciclo continua finchè la cella #1 non vale 0, e la cella #2 contiene il vecchio -valore della cella #1. Siccome siamo nella cella #1 alla fine del ciclo, -ci muoviamo alla cella #2 e stampiamo il valore ASCII. - -Tenete in mente che gli spazi sono puramente estetici. Si potrebbe benissimo -anche scrivere come: - -,[>+<-]>. - -Cercate di capire cosa fa questo programma: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Questo programma prende 2 numeri in input e li moltiplica. - -Per prima cosa prende in input 2 numeri. Poi inizia il ciclo esterno, -condizionato dalla cella #1. Poi si muove nella cella #2 e inizia il ciclo -interno, condizionato dalla cella #2, incrementando la cella #3. Però c'è -un problema: alla fine del ciclo interno la cella #2 è zero. In questo caso -il ciclo interno non funzionerà pià fino alla volta seguente. Per risolvere -il problema, incrementiamo la cella #4 e poi ricopiamo #4 in #2. La cella #3 -è il risultato. -``` -E questo è brainfuck. Non è così difficile, vero? Per passare il tempo -potreste provare a scrivere un pogramma in brainfuck, oppure potete -scrivere un interprete brainfuck in un altro linguaggio. L'interprete -è relativamente semplice da implementare, ma se siete masochisti, potete -provare a scrivere un interprete brainfuck... in brainfuck. -And that's brainfuck. Not that hard, eh? For fun, you can write your own -brainfuck programs, or you can write a brainfuck interpreter in another -language. The interpreter is fairly simple to implement, but if you're -a masochist, try writing a brainfuck interpreter… in brainfuck. -- cgit v1.2.3 From c1037971f83043bf30a73ba46cca0e8d3ade880e Mon Sep 17 00:00:00 2001 From: Tapmemer Date: Tue, 20 Feb 2018 09:36:50 +0100 Subject: shouldnt copy shouldnt copy if i dont do anything with it --- nl-nl/d-nl.html.markdown | 260 ----------------------------------------------- 1 file changed, 260 deletions(-) delete mode 100644 nl-nl/d-nl.html.markdown diff --git a/nl-nl/d-nl.html.markdown b/nl-nl/d-nl.html.markdown deleted file mode 100644 index d2a57cae..00000000 --- a/nl-nl/d-nl.html.markdown +++ /dev/null @@ -1,260 +0,0 @@ ---- -language: D -filename: learnd.d -contributors: - - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] - ---- - -```d -// You know what's coming... -module hello; - -import std.stdio; - -// args is optional -void main(string[] args) { - writeln("Hello, World!"); -} -``` - -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 -expressive high-level abstractions. - -D is actively developed by a large group of super-smart people and is spearheaded by -[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and -[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). -With all that out of the way, let's look at some examples! - -```d -import std.stdio; - -void main() { - - // Conditionals and loops work as expected. - for(int i = 0; i < 10000; i++) { - writeln(i); - } - - // 'auto' can be used for inferring types. - auto n = 1; - - // Numeric literals can use '_' as a digit separator for clarity. - while(n < 10_000) { - n += n; - } - - do { - n -= (n / 2); - } while(n > 0); - - // For and while are nice, but in D-land we prefer 'foreach' loops. - // The '..' creates a continuous range, including the first value - // but excluding the last. - foreach(n; 1..1_000_000) { - if(n % 2 == 0) - writeln(n); - } - - // There's also 'foreach_reverse' when you want to loop backwards. - foreach_reverse(n; 1..int.max) { - if(n % 2 == 1) { - writeln(n); - } else { - writeln("No!"); - } - } -} -``` - -We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions -are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore, -we can use templates to parameterize all of these on both types and values! - -```d -// Here, 'T' is a type parameter. Think '' from C++/C#/Java. -struct LinkedList(T) { - T data = null; - - // Use '!' to instantiate a parameterized type. Again, think ''. - LinkedList!(T)* next; -} - -class BinTree(T) { - T data = null; - - // If there is only one template parameter, we can omit the parentheses. - BinTree!T left; - BinTree!T right; -} - -enum Day { - Sunday, - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, -} - -// Use alias to create abbreviations for types. -alias IntList = LinkedList!int; -alias NumTree = BinTree!double; - -// We can create function templates as well! -T max(T)(T a, T b) { - if(a < b) - return b; - - return a; -} - -// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b' -// are value types, they will always be passed by reference to 'swap()'. -void swap(T)(ref T a, ref T b) { - auto temp = a; - - a = b; - b = temp; -} - -// With templates, we can also parameterize on values, not just types. -class Matrix(uint m, uint n, T = int) { - T[m] rows; - T[n] columns; -} - -auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'. - -``` - -Speaking of classes, let's talk about properties for a second. A property -is roughly a function that may act like an lvalue, so we can -have the syntax of POD structures (`structure.x = 7`) with the semantics of -getter and setter methods (`object.setX(7)`)! - -```d -// Consider a class parameterized on types 'T' & 'U'. -class MyClass(T, U) { - T _data; - U _other; -} - -// And "getter" and "setter" methods like so: -class MyClass(T, U) { - T _data; - U _other; - - // Constructors are always named 'this'. - this(T t, U u) { - // This will call the setter methods below. - data = t; - other = u; - } - - // getters - @property T data() { - return _data; - } - - @property U other() { - return _other; - } - - // setters - @property void data(T t) { - _data = t; - } - - @property void other(U u) { - _other = u; - } -} - -// And we use them in this manner: -void main() { - auto mc = new MyClass!(int, string)(7, "seven"); - - // Import the 'stdio' module from the standard library for writing to - // console (imports can be local to a scope). - import std.stdio; - - // Call the getters to fetch the values. - writefln("Earlier: data = %d, str = %s", mc.data, mc.other); - - // Call the setters to assign new values. - mc.data = 8; - mc.other = "eight"; - - // Call the getters again to fetch the new values. - writefln("Later: data = %d, str = %s", mc.data, mc.other); -} -``` - -With properties, we can add any amount of logic to -our getter and setter methods, and keep the clean syntax of -accessing members directly! - -Other object-oriented goodies at our disposal -include interfaces, abstract classes, -and overriding 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` -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! - -```d -import std.algorithm : map, filter, reduce; -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 function you like, but lambdas are convenient here. - auto num = iota(1, 101).filter!(x => x % 2 == 0) - .map!(y => y ^^ 2) - .reduce!((a, b) => a + b); - - writeln(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 (UFCS). -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 -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! - -```d -// Let's say we want to populate a large array with the square root of all -// consecutive integers starting from 1 (up until the size of the array), and we -// want to do this concurrently taking advantage of as many cores as we have -// available. - -import std.stdio; -import std.parallelism : parallel; -import std.math : sqrt; - -void main() { - // Create your large array - auto arr = new double[1_000_000]; - - // Use an index, access every array element by reference (because we're - // going to change each element) and just call parallel on the array! - foreach(i, ref elem; parallel(arr)) { - elem = sqrt(i + 1.0); - } -} -``` -- cgit v1.2.3 From 543a1b517b050912806588f4ec351d708961e1c0 Mon Sep 17 00:00:00 2001 From: Jimmy de Graaf Date: Fri, 23 Feb 2018 15:09:26 +0100 Subject: [prolog/en] Fixed typo in expected result, changed 'deterministic' jargon to its full name --- prolog.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/prolog.html.markdown b/prolog.html.markdown index 7a18a144..4f3984c7 100644 --- a/prolog.html.markdown +++ b/prolog.html.markdown @@ -104,7 +104,7 @@ magicNumber(42). ?- plus(1, 2, 3). % True ?- plus(1, 2, X). % X = 3 because 1+2 = X. ?- plus(1, X, 3). % X = 2 because 1+X = 3. -?- plus(X, 2, 3). % X = 1 because X+1 = 3. +?- plus(X, 2, 3). % X = 1 because X+2 = 3. ?- plus(X, 5, Y). % Error - although this could be solved, % the number of solutions is infinite, % which most predicates try to avoid. @@ -230,14 +230,14 @@ nearby3(X,Y) :- nearby2(X,Y). % Here is the structured comment declaration for nearby3: -%% nearby3(+X:Int, +Y:Int) is semidet. +%% nearby3(+X:Int, +Y:Int) is semideterministic. %% nearby3(+X:Int, -Y:Int) is multi. %% nearby3(-X:Int, +Y:Int) is multi. % For each variable we list a type. The + or - before the variable name % indicates if the parameter is bound (+) or free (-). The word after % "is" describes the behaviour of the predicate: -% semidet - can succeed once or fail +% semideterministic - can succeed once or fail % ( Two specific numbers are either nearby or not ) % multi - can succeed multiple times but cannot fail % ( One number surely has at least 3 nearby numbers ) @@ -267,8 +267,8 @@ character(darthVader). % Creates atom value darthVader % Note that below, writeln is used instead of print because print is % intended for debugging. -%% countTo(+X:Int) is det. -%% countUpTo(+Value:Int, +Limit:Int) is det. +%% countTo(+X:Int) is deterministic. +%% countUpTo(+Value:Int, +Limit:Int) is deterministic. countTo(X) :- countUpTo(1,X). countUpTo(Value, Limit) :- Value = Limit, writeln(Value), !. countUpTo(Value, Limit) :- Value \= Limit, writeln(Value), @@ -281,7 +281,7 @@ countUpTo(Value, Limit) :- Value \= Limit, writeln(Value), % IF test. If Value = Limit fails the second declaration is run. % There is also a more elegant syntax. -%% countUpTo2(+Value:Int, +Limit:Int) is det. +%% countUpTo2(+Value:Int, +Limit:Int) is deterministic. countUpTo2(Value, Limit) :- writeln(Value), Value = Limit -> true ; ( NextValue is Value+1, @@ -294,14 +294,14 @@ countUpTo2(Value, Limit) :- writeln(Value), % called a "failure-driven loop" to do this, but newer ones use a higher % order function. -%% countTo2(+X:Int) is det. +%% countTo2(+X:Int) is deterministic. countTo2(X) :- forall(between(1,X,Y),writeln(Y)). ?- countTo2(10). % Outputs 1 to 10 % Lists are given in square brackets. Use memberchk to check membership. % A group is safe if it doesn't include Joker or does include Batman. -%% safe(Group:list(atom)) is det. +%% safe(Group:list(atom)) is deterministic. safe(Group) :- memberchk(joker, Group) -> memberchk(batman, Group) ; true. ?- safe([robin]). % True -- cgit v1.2.3 From 3d847f5efeda8190f58a14ab17682e99340f894f Mon Sep 17 00:00:00 2001 From: Rene Meissner Date: Tue, 27 Feb 2018 12:55:14 +0100 Subject: Update go-de.html.markdown --- 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 817cb4ae..9409e181 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -94,7 +94,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // Arrays haben bei Kompile-Zeit festgelegte Größen var a4 [4]int // Ein Array mit 4 ints, alle mit Initialwert 0 - a3 := [...]int{3, 1, 5} // Ein Array mit 4 ints, Initialwerte wie angezeigt + a3 := [...]int{3, 1, 5} // Ein Array mit 3 ints, Initialwerte wie angezeigt // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre // Vorzüge, aber slices werden viel häufiger verwendet -- cgit v1.2.3 From 27bf16ac1289cde688066a624a264432ba4baffa Mon Sep 17 00:00:00 2001 From: Ben Quigley Date: Tue, 27 Feb 2018 09:38:40 -0500 Subject: IPython notebooks are Jupyter notebooks now IPython still exists, but the notebooks have been spun off into their own project called Jupyter. This file change: * updates the pip install queue so that Jupyter gets installed * removes the vague "get set up with IPython" (pip will install IPython with Jupyter), and * replaced the suggestion to work in "the IPython notebook" with "a Jupyter notebook". --- pythonstatcomp.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 79bbcd8d..6dde1cf0 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -13,10 +13,11 @@ This is a tutorial on how to do some typical statistical programming tasks using # 0. Getting set up ==== -""" Get set up with IPython and pip install the following: numpy, scipy, pandas, +""" To get started, pip install the following: jupyter, 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. + Make sure to do this tutorial in a Jupyter notebook so that you get + the inline plots and easy documentation lookup. The shell command to open + one is simply `jupyter notebook`, then click New -> Python. """ # 1. Data acquisition ==== -- cgit v1.2.3 From 01ab4a60cf2a85f9d4d0f2b3fb03e12129554964 Mon Sep 17 00:00:00 2001 From: louis Date: Tue, 27 Feb 2018 16:19:06 +0100 Subject: [crystal/en] Corrected mistake --- crystal.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/crystal.html.markdown b/crystal.html.markdown index ad9cf0f8..8210b443 100644 --- a/crystal.html.markdown +++ b/crystal.html.markdown @@ -301,7 +301,6 @@ end (1..3).each do |index| puts "Index: #{index}" end -# Index: 0 # Index: 1 # Index: 2 # Index: 3 -- cgit v1.2.3 From c0868506513421f6d748ca8faa7d1beaaff0a3af Mon Sep 17 00:00:00 2001 From: louis Date: Tue, 27 Feb 2018 16:27:32 +0100 Subject: [crystal/fr] Corrected mistake --- fr-fr/crystal-fr.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/fr-fr/crystal-fr.html.markdown b/fr-fr/crystal-fr.html.markdown index 2c4e3dad..2bb17fc5 100644 --- a/fr-fr/crystal-fr.html.markdown +++ b/fr-fr/crystal-fr.html.markdown @@ -305,7 +305,6 @@ end (1..3).each do |index| puts "Index: #{index}" end -# Index: 0 # Index: 1 # Index: 2 # Index: 3 -- cgit v1.2.3 From 2abfabae15fc8ee0ce2bdd7b61d65ff1c0375cc1 Mon Sep 17 00:00:00 2001 From: stanislaslegendre Date: Wed, 28 Feb 2018 08:53:14 +0100 Subject: removing false statement about classes (#3039) --- java.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index dd875c16..ab2be4a2 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -44,8 +44,6 @@ import java.util.ArrayList; // Import all classes inside of java.security package import java.security.*; -// Each .java file contains one outer-level public class, with the same name -// as the file. public class LearnJava { // In order to run a java program, it must have a main method as an entry -- cgit v1.2.3 From 960cf9866f8c58f043c73a501964b369d95d64c4 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 14:44:42 +0545 Subject: Update make-cn.html.markdown --- zh-cn/make-cn.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zh-cn/make-cn.html.markdown b/zh-cn/make-cn.html.markdown index 4a58f0b6..4cdf1e63 100644 --- a/zh-cn/make-cn.html.markdown +++ b/zh-cn/make-cn.html.markdown @@ -5,7 +5,8 @@ contributors: - ["Jichao Ouyang", "https://github.com/jcouyang"] translators: - ["Jichao Ouyang", "https://github.com/jcouyang"] -filename: Makefile +filename: Makefile-cn +lang: zh-cn --- Makefile 用于定义如何创建目标文件, 比如如何从源码到可执行文件. 创建这一工具的目标是 -- cgit v1.2.3 From 7ad8be6d97978a008c98bfbdc22e04b4d79c8fd9 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 14:48:12 +0545 Subject: Update html-nl.html.markdown --- nl-nl/html-nl.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nl-nl/html-nl.html.markdown b/nl-nl/html-nl.html.markdown index 612e9c37..54c81ed6 100644 --- a/nl-nl/html-nl.html.markdown +++ b/nl-nl/html-nl.html.markdown @@ -1,11 +1,12 @@ --- language: html -filename: learnhtml.html +filename: learnhtml-nl.html contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: - ["Robert Steed", "https://github.com/robochat"] - ["Jeroen Deviaene", "https://github.com/jerodev"] +lang: nl-nl --- HTML staat voor HyperText Markup Language. -- cgit v1.2.3 From 963331453fdacb968481c34fb93bcc909c39d0e3 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 15:09:56 +0545 Subject: Update pcre-tw.html.markdown --- zh-tw/pcre-tw.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zh-tw/pcre-tw.html.markdown b/zh-tw/pcre-tw.html.markdown index 01870eaf..c9cdc537 100644 --- a/zh-tw/pcre-tw.html.markdown +++ b/zh-tw/pcre-tw.html.markdown @@ -1,11 +1,10 @@ --- language: PCRE -filename: pcre.txt +filename: pcre-tw.txt contributors: - ["Sachin Divekar", "http://github.com/ssd532"] translators: - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: pcre-tw.py lang: zh-tw --- -- cgit v1.2.3 From bcd41be2233b722a14146a5f82d8365ab616a7e6 Mon Sep 17 00:00:00 2001 From: Matt Doherty Date: Wed, 28 Feb 2018 09:29:19 +0000 Subject: [kdb+/en] Updated external links to the KX wiki (#3008) * series of fixes and improvements * updated links to kx wiki --- kdb+.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 5ae86a4f..097f177b 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -76,7 +76,7 @@ floor 3.14159 / => 3 / ...getting the absolute value... abs -3.14159 / => 3.14159 / ...and many other things -/ see http://code.kx.com/wiki/Reference for more +/ see http://code.kx.com/q/ref/card/ for more / q has no operator precedence, everything is evaluated right to left / so results like this might take some getting used to @@ -174,7 +174,7 @@ t - 00:10:00.000 / => 00:50:00.000 d.year / => 2015i d.mm / => 12i d.dd / => 25i -/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Temporal_Data for more +/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#25-temporal-data for more / q also has an infinity value so div by zero will not throw an error 1%0 / => 0w @@ -183,7 +183,7 @@ d.dd / => 25i / And null types for representing missing values 0N / => null int 0n / => null float -/ see http://code.kx.com/wiki/JB:QforMortals2/atoms#Null_Values for more +/ see http://code.kx.com/q4m3/2_Basic_Data_Types_Atoms/#27-nulls for more / q has standard control structures / if is as you might expect (; separates the condition and instructions) @@ -642,7 +642,7 @@ kt upsert ([]name:`Thomas`Chester;age:33 58;height:175 179;sex:`f`m) / => Thomas 32 175 m / Most of the standard SQL joins are present in q-sql, plus a few new friends -/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Joins +/ see http://code.kx.com/q4m3/9_Queries_q-sql/#99-joins / the two most important (commonly used) are lj and aj / lj is basically the same as SQL LEFT JOIN @@ -669,7 +669,7 @@ aj[`time`sym;trades;quotes] / => 10:01:04 ge 150 / for each row in the trade table, the last (prevailing) quote (px) for that sym / is joined on. -/ see http://code.kx.com/wiki/JB:QforMortals2/queries_q_sql#Asof_Join +/ see http://code.kx.com/q4m3/9_Queries_q-sql/#998-as-of-joins //////////////////////////////////// ///// Extra/Advanced ////// @@ -716,7 +716,7 @@ first each (1 2 3;4 5 6;7 8 9) {x + y}/[1 2 3 4 5] / => 15 (only the final result) / There are other adverbs and uses, this is only intended as quick overview -/ http://code.kx.com/wiki/JB:QforMortals2/functions#Adverbs +/ http://code.kx.com/q4m3/6_Functions/#67-adverbs ////// Scripts ////// / q scripts can be loaded from a q session using the "\l" command @@ -756,7 +756,7 @@ select from splayed / (the columns are read from disk on request) / => 1 1 / => 2 2 / => 3 3 -/ see http://code.kx.com/wiki/JB:KdbplusForMortals/contents for more +/ see http://code.kx.com/q4m3/14_Introduction_to_Kdb+/ for more ////// Frameworks ////// / kdb+ is typically used for data capture and analysis. @@ -769,8 +769,8 @@ select from splayed / (the columns are read from disk on request) ## Want to know more? -* [*q for mortals* q language tutorial](http://code.kx.com/wiki/JB:QforMortals2/contents) -* [*kdb for mortals* on disk data tutorial](http://code.kx.com/wiki/JB:KdbplusForMortals/contents) -* [q language reference](http://code.kx.com/wiki/Reference) +* [*q for mortals* q language tutorial](http://code.kx.com/q4m3/) +* [*Introduction to Kdb+* on disk data tutorial](http://code.kx.com/q4m3/14_Introduction_to_Kdb+/) +* [q language reference](http://code.kx.com/q/ref/card/) * [Online training courses](http://training.aquaq.co.uk/) * [TorQ production framework](https://github.com/AquaQAnalytics/TorQ) -- cgit v1.2.3 From 9d70058be359883118c5ef3d7e4af552feb866b3 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 15:18:06 +0545 Subject: Update and rename css.html.markdown to css-tr.html.markdown --- tr-tr/css-tr.html.markdown | 304 +++++++++++++++++++++++++++++++++++++++++++++ tr-tr/css.html.markdown | 304 --------------------------------------------- 2 files changed, 304 insertions(+), 304 deletions(-) create mode 100644 tr-tr/css-tr.html.markdown delete mode 100644 tr-tr/css.html.markdown diff --git a/tr-tr/css-tr.html.markdown b/tr-tr/css-tr.html.markdown new file mode 100644 index 00000000..d13dadcc --- /dev/null +++ b/tr-tr/css-tr.html.markdown @@ -0,0 +1,304 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Brett Taylor", "https://github.com/glutnix"] + - ["Tyler Mumford", "https://tylermumford.com"] +filename: learncss-tr.css +translators: + - ["Fatih Turan", "http://fatihturan.com"] +lang: tr-tr +--- + +Web sayfaları bir sayfanın içeriğini belirleyen HTML ile inşa edilirler. CSS (Basamaklı Biçim Sayfaları) ise bir sayfanın **görünümünü** belirleyen ayrı bir dildir. + +CSS kodu statik *kurallardan* oluşur. Her kural bir ya da daha fazla *seçici* alır ve görsel *özelliklere* belirli *değerleri* verir. Sonrasında bu özellikler seçiciler tarafından belirlenen sayfa unsurlarına uygulanır. + +Bu rehber, CSS 3'ün yeni özellikleri ile genişletilen CSS 2 ile dikkate alınarak yazılmıştır. + +**NOT:** CSS görsel sonuçlar ürettiğinden dolayı, öğrenmek için herşeyi bir CSS oyun alanı içinde ([dabblet](http://dabblet.com) gibi) denemeniz gerekmektedir. Bu makale sözdizimi kuralları ve genel ipuçları üzerine odaklanmaktadır. + +## Sözdizimi + +```css +/* yorumlar bu satırdaki gibi taksim-yıldız içinde görünür +CSS'te "tek satırlık yorumlar" bulunmamaktadır; bu sadece tek bir yorum yazma stilidir */ + +/* #################### + ## SEÇİCİLER + #################### */ + +/* seçici bir sayfadaki unsuru hedeflemek için kullanılır. */ +seçici { özellik: değer; /* daha fazla özellikler...*/ } + +/* +İşte bir örnek: + +

+*/ + +/* */ + +/* CSS sınıflarının birini kullanarak hedefleyebilirsiniz */ +.class1 { } + +/* veya her iki sınıfı birden!*/ +.class1.class2 { } + +/* veya sadece ögenin adını yazarak */ +div { } + +/* veya onun ID adını */ +#anID { } + +/* veya onun aldığı bir özelliği kullanarak! */ +[attr] { font-size:smaller; } + +/* veya onun aldığı özelliğin belirli bir değeri varsa */ +[attr='value'] { font-size:smaller; } + +/* bir değer ile başlıyorsa (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* veya bir değer ile bitiyorsa (CSS 3)*/ +[attr$='ue'] { font-size:smaller; } + +/* veya boşlukla ayrılmış liste içinde bir değer içeriyorsa */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* veya tire ile ayrılmış bir liste içinde bir değer içeriyorsa, örneğin: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + +/* Farklı seçicileri birleştirerek daha fazla odaklanmış bir seçici oluşturabilirsiniz. Seçiciler arasında boşluk bırakmayın. */ +div.some-class[attr$='ue'] { } + +/* Başka bir ögenin alt ögesi olan bir ögeyi seçebilirsiniz. */ +div.some-parent > .class-name { } + +/* veya bir başka ögeden türeyeni seçebilirsiniz. Alt ögeler onların ebeveynlerinin direkt türünden gelir, sadece ağacın bir alt ögeleridirler. Soyundan gelenler ağacın herhangi bir alt seviyesinde olabilir. */ + +div.some-parent .class-name { } + +/* Uyarı: Seçiciler arasında bir boşluk bırakmazsanız aynı seçicinin başka bir anlamı olur. +Ne olduğunu tahmin edebilir misiniz? */ + +div.some-parent.class-name { } + +/* Ayrıca bir ögenin bitişik kardeşini temel alarak bir ögeyi seçebilirsiniz. */ +.i-am-just-before + .this-element { } + +/* veya kendisinden önce gelen herhangi bir kardeş ögeyi */ +.i-am-any-element-before ~ .this-element { } + +/* Yalnızca belli bir durumda bir öge seçmek için kullanılan sahte sınıflar adı verilen bazı seçiciler vardır. */ + +/* Örneğin, imleç bir ögenin üzerine geldiğinde */ +selector:hover { } + +/* veya bir bağlantı ziyaret edildiğinde */ +selector:visited { } + +/* veya ziyaret edilmediğinde */ +selected:link { } + +/* veya bir ögeye odaklanıldığında */ +selected:focus { } + +/* Ebeveyninin ilk alt ögesi olan herhangi bir öge */ +selector:first-child {} + +/* Ebeveyninin son alt ögesi olan herhangi bir öge */ +selector:last-child {} + +/* Sahte sınıflar gibi sahte elementler de bir dokümanın belirli bir parçasına stil vermenize izin verir. */ + +/* Seçilen ögenin sanal ilk alt ögesiyle eşleşir. */ +selector::before {} + +/* Seçilen ögenin sanal son alt ögesiyle eşleşir. */ +selector::after {} + +/* Uygun yerlerde yıldız karakteri ile bütün ögeleri seçmek için joker olarak kullanılabilir. */ + +* { } /* Bütün ögeler */ +.parent * { } /* Tüm alt ögeler */ +.parent > * { } /* Tüm çocuk ögeler */ + +/* #################### + ## ÖZELLİKLER + #################### */ + +selector { + + /* Ölçü birimleri kesin veya göreceli olabilir.*/ + + /* Göreceli birimler */ + width: 50%; /* Ebeveyn elementin yüzdesel olarak genişliği */ + font-size: 2em; /* Öğenin özgün yazı tipi boyutunda katları */ + font-size: 2rem; /* veya kök ögenin yazı tipi boyutu */ + font-size: 2vw; /* Görüntüleme çerçevesinin genişliğinin %1 olarak katları (CSS 3) */ + font-size: 2vh; /* veya onun yüksekliğinin */ + font-size: 2vmin; /* Bir vh veya vw'nin hangisi küçükse */ + font-size: 2vmax; /* veya daha büyük... */ + + /* Kesin birimler */ + width: 200px; /* Piksel */ + font-size: 20pt; /* Nokta */ + width: 5cm; /* Santimetre */ + min-width: 50mm; /* Milimetre */ + max-width: 5in; /* İnç */ + + /* Renkler */ + color: #F6E; /* Kısa onaltılık (HEX) biçimi */ + color: #FF66EE; /* Uzun onaltılık (HEX) biçimi */ + color: tomato; /* Bir isim verilen renk */ + color: rgb(255, 255, 255); /* RGB değerleri verilen türde */ + color: rgb(10%, 20%, 50%); /* RGB yüzdeleri verilen türde */ + color: rgba(255, 0, 0, 0.3); /* RGBA değerleri verilen türde (CSS 3) Not: 0 <= a <= 1 */ + color: transparent; /* Şeffaflık değerinin sıfır olması ile eşdeğer */ + color: hsl(0, 100%, 50%); /* HSL yüzdeleri verilen türde (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* HSL ile beraber şeffaflık değeri verilen türde */ + + /* Kenarlıklar */ + border-width:5px; + border-style:solid; + border-color:red; /* background-color'ın ayarlanışına benzer şekilde */ + border: 5px solid red; /* Bu aynı şeyin kısayol ile yazılışıdır */ + border-radius:20px; /* Bu bir CSS3 özelliğidir */ + + /* Görseller ve Ögelerin Arkaplanları */ + background-image: url(/img-path/img.jpg); /* url() içindeki tırnak işaretleri isteğe bağlı */ + + /* Yazı tipleri */ + font-family: Arial; + /* Eğer yazı tipi ailesi isminde bir boşluk var ise tırnak işareti içine alınmalıdır. */ + font-family: "Courier New"; + /* Eğer ilk sıradaki bulunamazsa, tarayıcı bir sonrakini kullanır */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Kullanım + +CSS dosyasınızı `.css`uzantısı ile kaydedin. + +```html + + + + + + + +
+
+``` + +## Öncelik veya Basamak + +Bir öge birden çok seçici tarafından hedef alınabilir ve bir özellik kümesine birden fazla kez sahip olabilir. Bunun gibi durumlarda, kurallardan biri diğerlerine göre önceliklidir. Daha spesifik bir seçiciye sahip kurallar, daha az spesifik bir seçicinin önceliğini alır ve kural daha sonra stil sayfasında bir önceki kuralın üzerine yazar. + +Bu işleme geçiş denir ve olayısıyla Geçişli/Basamaklı Stil Sayfaları adı da buradan gelmiştir. + +Aşağıdaki CSS göz önüne alındığında: + +```css +/* A */ +p.class1[attr='değer'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { özellik: değer !important; } +``` + +ve aşağıdaki biçimlendirmeyi: + +```html +

+``` + +Stilin önceliği ise aşağıdaki gibidir. Unutmayın, öncelik **her bir özellik için ayrı ayrı geçerlidir**, tüm blok için geçerli değildir. + +* `E` `!important` kelimesi yüzünden en yüksek önceliğe sahiptir. Kullanımından kaçınmanız önerilir. +* `F` satıriçi stil olduğu için bir sonraki önceliğe sahiptir. +* `A` bir sonraki önceliğe sahiptir. Çünkü her şeyden daha "özgüdür". 3 belirteci vardır: `p` ögesinin adı, sınıf` class1`, bir öznitelik `attr = 'değer'. +* `C`, `B` ile aynı özdeşliğe sahip olsa da, bundan sonra geldiğinden dolayı öncelik hakkına sahiptir. +* `B` bir sonraki önceliğe sahiptir. +* Sonuncu önceliğe sahip olan`D`'dir. + +## Medya Sorguları + +CSS Medya Sorguları, CSS 3'te belirli CSS kurallarının ne zaman uygulanması gerektiğini (örneğin basılan zaman veya belirli boyutlar veya piksel yoğunluğu olan bir ekranda olduğunda) belirlemenize izin veren bir özelliktir. Medya Sorguları, seçicilere önceliğk eklemez. + +```css +/* Tüm cihazlarda kullanılacak olan bir kural */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* h1 ögesini değiştirip bir yazıcıda daha az mürekkep kullanın*/ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* En az 480 piksel genişliğinde bir ekran gösterildiğinde font yüksekliğini daha büyük yap */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` + +Medya sorguları aşağıdaki bu özellikleri içerebilir: +`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Bu özelliklerin birçoğunu `min-` veya `max-` öneki ile kullanabilirsiniz. + +`resolution` özelliği eski cihazlarda desteklenmediğinden ötürü `device-pixel-ratio` kullanın. + +Eğer `viewport` meta etiketi sağlanmadıkça birçok akıllı telefon ve tabletler, sayfayı masaüstü bilgisayardaymış gibi göstermeye çalışacaktır. + +```html + + + +``` + +## Uyumluluk + +CSS 2'deki çoğu özellik (ve CSS 3'deki birçoğu) bütün tarayıcılar ve cihazlar için bulunmaktadır. Ancak yeni bir özelliği kullanmadan önce kontrol etmek her zaman iyi bir uygulamadır. + +## Kaynaklar + +* [CanIUse](http://caniuse.com) (Detaylı uyumluluk bilgileri) +* [Dabblet](http://dabblet.com/) (CSS oyun alanı) +* [Mozilla Geliştirici Ağının CSS belgelendirmesi](https://developer.mozilla.org/en-US/docs/Web/CSS) (Eğitseller ve referanslar) +* [Codrops' CSS Referansı](http://tympanus.net/codrops/css_reference/) (Referans) + +## Daha Fazla Okuma + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/tr-tr/css.html.markdown b/tr-tr/css.html.markdown deleted file mode 100644 index baa47b3d..00000000 --- a/tr-tr/css.html.markdown +++ /dev/null @@ -1,304 +0,0 @@ ---- -language: css -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] - - ["Marco Scannadinari", "https://github.com/marcoms"] - - ["Geoffrey Liu", "https://github.com/g-liu"] - - ["Connor Shea", "https://github.com/connorshea"] - - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - - ["Brett Taylor", "https://github.com/glutnix"] - - ["Tyler Mumford", "https://tylermumford.com"] -filename: learncss.css -translators: - - ["Fatih Turan", "http://fatihturan.com"] -lang: tr-tr ---- - -Web sayfaları bir sayfanın içeriğini belirleyen HTML ile inşa edilirler. CSS (Basamaklı Biçim Sayfaları) ise bir sayfanın **görünümünü** belirleyen ayrı bir dildir. - -CSS kodu statik *kurallardan* oluşur. Her kural bir ya da daha fazla *seçici* alır ve görsel *özelliklere* belirli *değerleri* verir. Sonrasında bu özellikler seçiciler tarafından belirlenen sayfa unsurlarına uygulanır. - -Bu rehber, CSS 3'ün yeni özellikleri ile genişletilen CSS 2 ile dikkate alınarak yazılmıştır. - -**NOT:** CSS görsel sonuçlar ürettiğinden dolayı, öğrenmek için herşeyi bir CSS oyun alanı içinde ([dabblet](http://dabblet.com) gibi) denemeniz gerekmektedir. Bu makale sözdizimi kuralları ve genel ipuçları üzerine odaklanmaktadır. - -## Sözdizimi - -```css -/* yorumlar bu satırdaki gibi taksim-yıldız içinde görünür -CSS'te "tek satırlık yorumlar" bulunmamaktadır; bu sadece tek bir yorum yazma stilidir */ - -/* #################### - ## SEÇİCİLER - #################### */ - -/* seçici bir sayfadaki unsuru hedeflemek için kullanılır. */ -seçici { özellik: değer; /* daha fazla özellikler...*/ } - -/* -İşte bir örnek: - -

-*/ - -/* */ - -/* CSS sınıflarının birini kullanarak hedefleyebilirsiniz */ -.class1 { } - -/* veya her iki sınıfı birden!*/ -.class1.class2 { } - -/* veya sadece ögenin adını yazarak */ -div { } - -/* veya onun ID adını */ -#anID { } - -/* veya onun aldığı bir özelliği kullanarak! */ -[attr] { font-size:smaller; } - -/* veya onun aldığı özelliğin belirli bir değeri varsa */ -[attr='value'] { font-size:smaller; } - -/* bir değer ile başlıyorsa (CSS 3) */ -[attr^='val'] { font-size:smaller; } - -/* veya bir değer ile bitiyorsa (CSS 3)*/ -[attr$='ue'] { font-size:smaller; } - -/* veya boşlukla ayrılmış liste içinde bir değer içeriyorsa */ -[otherAttr~='foo'] { } -[otherAttr~='bar'] { } - -/* veya tire ile ayrılmış bir liste içinde bir değer içeriyorsa, örneğin: "-" (U+002D) */ -[otherAttr|='en'] { font-size:smaller; } - -/* Farklı seçicileri birleştirerek daha fazla odaklanmış bir seçici oluşturabilirsiniz. Seçiciler arasında boşluk bırakmayın. */ -div.some-class[attr$='ue'] { } - -/* Başka bir ögenin alt ögesi olan bir ögeyi seçebilirsiniz. */ -div.some-parent > .class-name { } - -/* veya bir başka ögeden türeyeni seçebilirsiniz. Alt ögeler onların ebeveynlerinin direkt türünden gelir, sadece ağacın bir alt ögeleridirler. Soyundan gelenler ağacın herhangi bir alt seviyesinde olabilir. */ - -div.some-parent .class-name { } - -/* Uyarı: Seçiciler arasında bir boşluk bırakmazsanız aynı seçicinin başka bir anlamı olur. -Ne olduğunu tahmin edebilir misiniz? */ - -div.some-parent.class-name { } - -/* Ayrıca bir ögenin bitişik kardeşini temel alarak bir ögeyi seçebilirsiniz. */ -.i-am-just-before + .this-element { } - -/* veya kendisinden önce gelen herhangi bir kardeş ögeyi */ -.i-am-any-element-before ~ .this-element { } - -/* Yalnızca belli bir durumda bir öge seçmek için kullanılan sahte sınıflar adı verilen bazı seçiciler vardır. */ - -/* Örneğin, imleç bir ögenin üzerine geldiğinde */ -selector:hover { } - -/* veya bir bağlantı ziyaret edildiğinde */ -selector:visited { } - -/* veya ziyaret edilmediğinde */ -selected:link { } - -/* veya bir ögeye odaklanıldığında */ -selected:focus { } - -/* Ebeveyninin ilk alt ögesi olan herhangi bir öge */ -selector:first-child {} - -/* Ebeveyninin son alt ögesi olan herhangi bir öge */ -selector:last-child {} - -/* Sahte sınıflar gibi sahte elementler de bir dokümanın belirli bir parçasına stil vermenize izin verir. */ - -/* Seçilen ögenin sanal ilk alt ögesiyle eşleşir. */ -selector::before {} - -/* Seçilen ögenin sanal son alt ögesiyle eşleşir. */ -selector::after {} - -/* Uygun yerlerde yıldız karakteri ile bütün ögeleri seçmek için joker olarak kullanılabilir. */ - -* { } /* Bütün ögeler */ -.parent * { } /* Tüm alt ögeler */ -.parent > * { } /* Tüm çocuk ögeler */ - -/* #################### - ## ÖZELLİKLER - #################### */ - -selector { - - /* Ölçü birimleri kesin veya göreceli olabilir.*/ - - /* Göreceli birimler */ - width: 50%; /* Ebeveyn elementin yüzdesel olarak genişliği */ - font-size: 2em; /* Öğenin özgün yazı tipi boyutunda katları */ - font-size: 2rem; /* veya kök ögenin yazı tipi boyutu */ - font-size: 2vw; /* Görüntüleme çerçevesinin genişliğinin %1 olarak katları (CSS 3) */ - font-size: 2vh; /* veya onun yüksekliğinin */ - font-size: 2vmin; /* Bir vh veya vw'nin hangisi küçükse */ - font-size: 2vmax; /* veya daha büyük... */ - - /* Kesin birimler */ - width: 200px; /* Piksel */ - font-size: 20pt; /* Nokta */ - width: 5cm; /* Santimetre */ - min-width: 50mm; /* Milimetre */ - max-width: 5in; /* İnç */ - - /* Renkler */ - color: #F6E; /* Kısa onaltılık (HEX) biçimi */ - color: #FF66EE; /* Uzun onaltılık (HEX) biçimi */ - color: tomato; /* Bir isim verilen renk */ - color: rgb(255, 255, 255); /* RGB değerleri verilen türde */ - color: rgb(10%, 20%, 50%); /* RGB yüzdeleri verilen türde */ - color: rgba(255, 0, 0, 0.3); /* RGBA değerleri verilen türde (CSS 3) Not: 0 <= a <= 1 */ - color: transparent; /* Şeffaflık değerinin sıfır olması ile eşdeğer */ - color: hsl(0, 100%, 50%); /* HSL yüzdeleri verilen türde (CSS 3) */ - color: hsla(0, 100%, 50%, 0.3); /* HSL ile beraber şeffaflık değeri verilen türde */ - - /* Kenarlıklar */ - border-width:5px; - border-style:solid; - border-color:red; /* background-color'ın ayarlanışına benzer şekilde */ - border: 5px solid red; /* Bu aynı şeyin kısayol ile yazılışıdır */ - border-radius:20px; /* Bu bir CSS3 özelliğidir */ - - /* Görseller ve Ögelerin Arkaplanları */ - background-image: url(/img-path/img.jpg); /* url() içindeki tırnak işaretleri isteğe bağlı */ - - /* Yazı tipleri */ - font-family: Arial; - /* Eğer yazı tipi ailesi isminde bir boşluk var ise tırnak işareti içine alınmalıdır. */ - font-family: "Courier New"; - /* Eğer ilk sıradaki bulunamazsa, tarayıcı bir sonrakini kullanır */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; -} -``` - -## Kullanım - -CSS dosyasınızı `.css`uzantısı ile kaydedin. - -```html - - - - - - - -
-
-``` - -## Öncelik veya Basamak - -Bir öge birden çok seçici tarafından hedef alınabilir ve bir özellik kümesine birden fazla kez sahip olabilir. Bunun gibi durumlarda, kurallardan biri diğerlerine göre önceliklidir. Daha spesifik bir seçiciye sahip kurallar, daha az spesifik bir seçicinin önceliğini alır ve kural daha sonra stil sayfasında bir önceki kuralın üzerine yazar. - -Bu işleme geçiş denir ve olayısıyla Geçişli/Basamaklı Stil Sayfaları adı da buradan gelmiştir. - -Aşağıdaki CSS göz önüne alındığında: - -```css -/* A */ -p.class1[attr='değer'] - -/* B */ -p.class1 { } - -/* C */ -p.class2 { } - -/* D */ -p { } - -/* E */ -p { özellik: değer !important; } -``` - -ve aşağıdaki biçimlendirmeyi: - -```html -

-``` - -Stilin önceliği ise aşağıdaki gibidir. Unutmayın, öncelik **her bir özellik için ayrı ayrı geçerlidir**, tüm blok için geçerli değildir. - -* `E` `!important` kelimesi yüzünden en yüksek önceliğe sahiptir. Kullanımından kaçınmanız önerilir. -* `F` satıriçi stil olduğu için bir sonraki önceliğe sahiptir. -* `A` bir sonraki önceliğe sahiptir. Çünkü her şeyden daha "özgüdür". 3 belirteci vardır: `p` ögesinin adı, sınıf` class1`, bir öznitelik `attr = 'değer'. -* `C`, `B` ile aynı özdeşliğe sahip olsa da, bundan sonra geldiğinden dolayı öncelik hakkına sahiptir. -* `B` bir sonraki önceliğe sahiptir. -* Sonuncu önceliğe sahip olan`D`'dir. - -## Medya Sorguları - -CSS Medya Sorguları, CSS 3'te belirli CSS kurallarının ne zaman uygulanması gerektiğini (örneğin basılan zaman veya belirli boyutlar veya piksel yoğunluğu olan bir ekranda olduğunda) belirlemenize izin veren bir özelliktir. Medya Sorguları, seçicilere önceliğk eklemez. - -```css -/* Tüm cihazlarda kullanılacak olan bir kural */ -h1 { - font-size: 2em; - color: white; - background-color: black; -} - -/* h1 ögesini değiştirip bir yazıcıda daha az mürekkep kullanın*/ -@media print { - h1 { - color: black; - background-color: white; - } -} - -/* En az 480 piksel genişliğinde bir ekran gösterildiğinde font yüksekliğini daha büyük yap */ -@media screen and (min-width: 480px) { - h1 { - font-size: 3em; - font-weight: normal; - } -} -``` - -Medya sorguları aşağıdaki bu özellikleri içerebilir: -`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. Bu özelliklerin birçoğunu `min-` veya `max-` öneki ile kullanabilirsiniz. - -`resolution` özelliği eski cihazlarda desteklenmediğinden ötürü `device-pixel-ratio` kullanın. - -Eğer `viewport` meta etiketi sağlanmadıkça birçok akıllı telefon ve tabletler, sayfayı masaüstü bilgisayardaymış gibi göstermeye çalışacaktır. - -```html - - - -``` - -## Uyumluluk - -CSS 2'deki çoğu özellik (ve CSS 3'deki birçoğu) bütün tarayıcılar ve cihazlar için bulunmaktadır. Ancak yeni bir özelliği kullanmadan önce kontrol etmek her zaman iyi bir uygulamadır. - -## Kaynaklar - -* [CanIUse](http://caniuse.com) (Detaylı uyumluluk bilgileri) -* [Dabblet](http://dabblet.com/) (CSS oyun alanı) -* [Mozilla Geliştirici Ağının CSS belgelendirmesi](https://developer.mozilla.org/en-US/docs/Web/CSS) (Eğitseller ve referanslar) -* [Codrops' CSS Referansı](http://tympanus.net/codrops/css_reference/) (Referans) - -## Daha Fazla Okuma - -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) -* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing -* [CSS-Tricks](https://css-tricks.com) \ No newline at end of file -- cgit v1.2.3 From 8e65231b5c33277d195daaed4a86f9ce5f19c1c1 Mon Sep 17 00:00:00 2001 From: Ganesha Danu Enastika Date: Wed, 28 Feb 2018 17:01:47 +0700 Subject: [Pascal/en] Add pascal language (#3025) * added a pascal tutorial * added a pascal tutorial * add more operation --- pascal.html.markdown | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 pascal.html.markdown diff --git a/pascal.html.markdown b/pascal.html.markdown new file mode 100644 index 00000000..6877afef --- /dev/null +++ b/pascal.html.markdown @@ -0,0 +1,96 @@ +--- +language: Pascal +filename: learnpascal.pas +contributors: + - ["Ganesha Danu", "http://github.com/blinfoldking"] +--- + + +>Pascal is an imperative and procedural programming language, which Niklaus Wirth designed in 1968–69 and published in 1970, as a small, efficient language intended to encourage good programming practices using structured programming and data structuring. It is named in honor of the French mathematician, philosopher and physicist Blaise Pascal. +source : [wikipedia](https://en.wikipedia.org/wiki/Pascal_(programming_language)) + + + +to compile and run a pascal program you could use a free pascal compiler. [Download Here](https://www.freepascal.org/) + +```pascal +//Anathomy of a Pascal Program +//this is a comment +{ + this is a + multiline comment +} + +//name of the program +program learn_pascal; //<-- dont forget a semicolon + +type + { + this is where you should delcare a custom + data-types + } +var + { + this is where you should declare a variable + } + +//main program area +begin + { + area to declare your instruction + } +end. // End of a main program area should required a "." symbol +``` + +```pascal +//declaring variable +//you can do this +var a:integer; +var b:integer; +//or this +var + a : integer; + b : integer; +//or this +var a,b : integer; +``` +```pascal +program Learn_More; +//Lets learn about data types and their operations + +//Declaring variables +var + int : integer; // a variable that contains an integer number data types + ch : char; // a variable that contains a character data types + str : string; // a variable that contains a string data types + r : real; // a variable that contains a real number data types + bool : boolean; //a variables that contains a Boolean(True/False) value data types +Begin + int := 1;// how to assign a value to a variable + r := 3.14; + ch := 'a'; + str := 'apple'; + bool := true; + //pascal is not a case-sensitive language + //arithmethic operation + int := 1 + 1; // int = 2 overwriting the previous assignment + int := int + 1; // int = 2 + 1 = 3; + int := 4 div 2; //int = 2 a division operation which the result will be floored + int := 3 div 2; //int = 1 + int := 1 div 2; //int = 0 + + bool := true or false; // bool = true + bool := false and true; // bool = false + bool := true xor true; // bool = false + + r := 3 / 2; // a division operator for real + r := int; // you can assign an integer to a real variable but not the otherwise + + c := str[1]; // assign the first letter of str to c + str := 'hello' + 'world'; //combining strings +End. +``` + +```pascal + +``` \ No newline at end of file -- cgit v1.2.3 From d57fe66c4308f257af4141d135e446e1a1c383b8 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 16:08:29 +0545 Subject: Fix language name --- fr-fr/bf-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/bf-fr.html.markdown b/fr-fr/bf-fr.html.markdown index 0fae6032..d8c7c76a 100644 --- a/fr-fr/bf-fr.html.markdown +++ b/fr-fr/bf-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: bf +language: Brainfuck filename: learnbrainfuck-fr.bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] -- cgit v1.2.3 From a26d106ed72e7d4a391e73496cc65e0f7b559111 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 16:12:00 +0545 Subject: Fix language name --- pt-br/bf-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/bf-pt.html.markdown b/pt-br/bf-pt.html.markdown index 53baa9a2..c69995ab 100644 --- a/pt-br/bf-pt.html.markdown +++ b/pt-br/bf-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: bf +language: Brainfuck filename: learnbf-pt.bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] -- cgit v1.2.3 From e3b0f32c65f12b7095dddc7059e41c2f19d005d2 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 16:22:50 +0545 Subject: Update haskell-sv.html.markdown --- sv-se/haskell-sv.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sv-se/haskell-sv.html.markdown b/sv-se/haskell-sv.html.markdown index 49a52069..da2d6ab0 100644 --- a/sv-se/haskell-sv.html.markdown +++ b/sv-se/haskell-sv.html.markdown @@ -1,6 +1,6 @@ --- language: Haskell -filename: learnhaskell.hs +filename: learnhaskell-sv.hs contributors: - ["Adit Bhargava", "http://adit.io"] translators: -- cgit v1.2.3 From 93bd3ab9ddf30259c5c75c70a858f59e00062149 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 16:27:03 +0545 Subject: Update nix-sv.html.markdown --- sv-se/nix-sv.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown index 2a1af37e..15d9456b 100644 --- a/sv-se/nix-sv.html.markdown +++ b/sv-se/nix-sv.html.markdown @@ -1,6 +1,6 @@ --- language: nix -filename: learn.nix +filename: learn-sv.nix contributors: - ["Chris Martin", "http://chris-martin.org/"] translators: -- cgit v1.2.3 From 52a4a4ac95f3df89b574458ec8e951458b2f8f85 Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Wed, 28 Feb 2018 02:44:18 -0800 Subject: [scala/en] A few editing improvements as I read through (#2768) * A few editing improvements as I read through Take, leave, or modify as desired! Specifically: * Acknowledge weirdness of no parameters in `foreach println` * Mention what `Unit` is * Clarify abstract comments * Fix capitalization of George in example * Explicitly introduce regex * Re-iterate `s` in comments, it's gotten very separated * Reword explanation of foreach --- scala.html.markdown | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 78053b40..78893b30 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -276,6 +276,7 @@ r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English +// Why doesn't `println` need any parameters here? Stay tuned for Functional Programming below! (5 to 1 by -1) foreach (println) // A while loop @@ -299,7 +300,7 @@ do { // Recursion is the idiomatic way of repeating an action in Scala (as in most // other functional languages). // Recursive functions need an explicit return type, the compiler can't infer it. -// Here it's Unit. +// Here it's Unit, which is analagous to a `void` return type in Java def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) @@ -412,8 +413,8 @@ class Dog(br: String) { private def sleep(hours: Int) = println(s"I'm sleeping for $hours hours") - // Abstract methods are simply methods with no body. If we uncomment the next - // line, class Dog would need to be declared abstract + // Abstract methods are simply methods with no body. If we uncomment the + // def line below, class Dog would need to be declared abstract like so: // abstract class Dog(...) { ... } // def chaseAfter(what: String): String } @@ -455,7 +456,7 @@ george.phoneNumber // => "1234" Person("George", "1234") == Person("Kate", "1236") // => false // Easy way to copy -// otherGeorge == Person("george", "9876") +// otherGeorge == Person("George", "9876") val otherGeorge = george.copy(phoneNumber = "9876") // And many others. Case classes also get pattern matching for free, see below. @@ -523,7 +524,9 @@ def matchPerson(person: Person): String = person match { case Person(name, number) => "We matched someone : " + name + ", phone : " + number } -val email = "(.*)@(.*)".r // Define a regex for the next example. +// Regular expressions are also built in. +// Create a regex with the `r` method on a string: +val email = "(.*)@(.*)".r // Pattern matching might look familiar to the switch statements in the C family // of languages, but this is much more powerful. In Scala, you can match much @@ -589,6 +592,8 @@ List("Dom", "Bob", "Natalia") foreach println // Combinators +// Using `s` from above: +// val s = Set(1, 3, 7) s.map(sq) @@ -608,8 +613,8 @@ List( ).filter(_.age > 25) // List(Person("Bob", 30)) -// Scala a foreach method defined on certain collections that takes a type -// returning Unit (a void method) +// Certain collections (such as List) in Scala have a `foreach` method, +// which takes as an argument a type returning Unit - that is, a void method val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -- cgit v1.2.3 From 03b9fce5fa97b11931c3358964413591c0633f45 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 28 Feb 2018 11:44:53 +0100 Subject: follow-up for #2768 --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 78893b30..016e2b4f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -276,7 +276,8 @@ r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English -// Why doesn't `println` need any parameters here? Stay tuned for Functional Programming below! +// Why doesn't `println` need any parameters here? +// Stay tuned for first-class functions in the Functional Programming section below! (5 to 1 by -1) foreach (println) // A while loop -- cgit v1.2.3 From 7a90605db0a876cb44b7ab9883dbe7dce4683de3 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 16:56:32 +0545 Subject: Fix #3060 --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 85033aa6..9e28452f 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -98,7 +98,7 @@ false # You can put any Julia expression inside the parentheses. # Another way to format strings is the printf macro. -@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +@printf "%d is less than %f" 4.5 5.3 # 4.5 is less than 5.300000 # Printing is easy println("I'm Julia. Nice to meet you!") -- cgit v1.2.3 From 5fa3782b147daf6c401fab16337fa65e4af60bc5 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 17:01:12 +0545 Subject: Fix #3058 --- CHICKEN.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown index bb2f91f0..3f7cc2db 100644 --- a/CHICKEN.html.markdown +++ b/CHICKEN.html.markdown @@ -81,7 +81,7 @@ supports R5RS and R7RS (work in progress) standards and many extensions. (string-append "pine" "apple") ;; => "pineapple" (string-ref "tapioca" 3) ;; => #\i;; character 'i' is at index 3 (string->list "CHICKEN") ;; => (#\C #\H #\I #\C #\K #\E #\N) -(string->intersperse '("1" "2") ":") ;; => "1:2" +(string-intersperse '("1" "2") ":") ;; => "1:2" (string-split "1:2:3" ":") ;; => ("1" "2" "3") -- cgit v1.2.3 From 7d303e504235a68eca63ebb914872cdfea9469b6 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 17:06:06 +0545 Subject: Remove per the request #3017 --- ocaml.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index c087216c..74eb7993 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -375,4 +375,3 @@ sum_int_list t ;; * Visit the official website to get the compiler and read the docs: * Try interactive tutorials and a web-based interpreter by OCaml Pro: -* Read "OCaml for the skeptical" course: -- cgit v1.2.3 From eefc0a9c92f44655fd177920c9f1d40816afa119 Mon Sep 17 00:00:00 2001 From: Evert Heylen Date: Wed, 28 Feb 2018 12:41:09 +0100 Subject: [prolog/en] Corrected statement about unifying two free terms (#3033) * Corrected statement about unifying two free terms While the intricacies of unification would bring us too far, stating that assigning two free 'sides' is wrong. I tried to give a small description about how this works (without going into the details of occurrence checks or unification of more complex structures). * Fixed indentation * Replaced old style of structured comments --- prolog.html.markdown | 116 +++++++++++++++++++++++++++------------------------ 1 file changed, 62 insertions(+), 54 deletions(-) diff --git a/prolog.html.markdown b/prolog.html.markdown index 4f3984c7..f7b55ac6 100644 --- a/prolog.html.markdown +++ b/prolog.html.markdown @@ -38,9 +38,9 @@ magicNumber(42). % predicate names must start with lower case letters. We can now use % interactive mode to ask if it is true for different values: -?- magicNumber(7). % True -?- magicNumber(8). % False -?- magicNumber(9). % True +?- magicNumber(7). % True +?- magicNumber(8). % False +?- magicNumber(9). % True % Some older Prologs may display "Yes" and "No" instead of True and % False. @@ -50,7 +50,7 @@ magicNumber(42). % starting with a capital letter is a variable in Prolog. ?- magicNumber(Presto). % Presto = 7 ; - % Presto = 9 ; + % Presto = 9 ; % Presto = 42. % Prolog makes magicNumber true by assigning one of the valid numbers to @@ -66,26 +66,33 @@ magicNumber(42). % follows: % If both sides are bound (ie, defined), check equality. % If one side is free (ie, undefined), assign to match the other side. -% If both sides are free, abort because this can't be resolved. +% If both sides are free, the assignment is remembered. With some luck, +% one of the two sides will eventually be bound, but this isn't +% necessary. +% % The = sign in Prolog represents unification, so: ?- 2 = 3. % False - equality test -?- X = 3. % X = 3 - assignment -?- X = 2, X = Y. % X = Y = 2 - two assignments +?- X = 3. % X = 3 - assignment +?- X = 2, X = Y. % X = Y = 2 - two assignments % Note Y is assigned to, even though it is % on the right hand side, because it is free ?- X = 3, X = 2. % False - % First acts as assignment and binds X=3 - % Second acts as equality because X is bound + % First acts as assignment and binds X=3 + % Second acts as equality because X is bound % Since 3 does not equal 2, gives False % Thus in Prolog variables are immutable ?- X = 3+2. % X = 3+2 - unification can't do arithmetic ?- X is 3+2. % X = 5 - "is" does arithmetic. -?- 5 = X+2. % This is why = can't do arithmetic - +?- 5 = X+2. % This is why = can't do arithmetic - % because Prolog can't solve equations ?- 5 is X+2. % Error. Unlike =, the right hand side of IS % must always be bound, thus guaranteeing % no attempt to solve an equation. +?- X = Y, X = 2, Z is Y + 3. % X = Y, Y = 2, Z = 5. + % X = Y are both free, so Prolog remembers + % it. Therefore assigning X will also + % assign Y. % Any unification, and thus any predicate in Prolog, can either: % Succeed (return True) without changing anything, @@ -101,11 +108,11 @@ magicNumber(42). % example, Prolog has a built in predicate plus which represents % arithmetic addition but can reverse simple additions. -?- plus(1, 2, 3). % True +?- plus(1, 2, 3). % True ?- plus(1, 2, X). % X = 3 because 1+2 = X. -?- plus(1, X, 3). % X = 2 because 1+X = 3. -?- plus(X, 2, 3). % X = 1 because X+2 = 3. -?- plus(X, 5, Y). % Error - although this could be solved, +?- plus(1, X, 3). % X = 2 because 1+X = 3. +?- plus(X, 2, 3). % X = 1 because X+2 = 3. +?- plus(X, 5, Y). % Error - although this could be solved, % the number of solutions is infinite, % which most predicates try to avoid. @@ -129,9 +136,9 @@ magicNumber(42). ?- print("Hello"). % "Hello" true. ?- X = 2, print(X). % 2 true. -?- X = 2, print(X), X = 3. % 2 false - print happens immediately when - % it is encountered, even though the overall - % compound goal fails (because 2 != 3, +?- X = 2, print(X), X = 3. % 2 false - print happens immediately when + % it is encountered, even though the overall + % compound goal fails (because 2 != 3, % see the example above). % By using Print we can see what actually happens when we give a @@ -156,7 +163,7 @@ magicNumber(42). % the interactive prompt by pressing ;, for example: ?- magicNumber(X), print(X), X > 8. % 7 9 X = 9 ; - % 42 X = 42. + % 42 X = 42. % As you saw above we can define our own simple predicates as facts. % More complex predicates are defined as rules, like this: @@ -168,7 +175,7 @@ nearby(X,Y) :- Y is X-1. % nearby(X,Y) is true if Y is X plus or minus 1. % However this predicate could be improved. Here's why: -?- nearby(2,3). % True ; False. +?- nearby(2,3). % True ; False. % Because we have three possible definitions, Prolog sees this as 3 % possibilities. X = Y fails, so Y is X+1 is then tried and succeeds, % giving the True answer. But Prolog still remembers there are more @@ -177,11 +184,11 @@ nearby(X,Y) :- Y is X-1. % the option of rejecting the True answer, which doesn't make a whole % lot of sense. -?- nearby(4, X). % X = 4 ; - % X = 5 ; - % X = 3. Great, this works -?- nearby(X, 4). % X = 4 ; - % error +?- nearby(4, X). % X = 4 ; + % X = 5 ; + % X = 3. Great, this works +?- nearby(X, 4). % X = 4 ; + % error % After rejecting X = 4 prolog backtracks and tries "Y is X+1" which is % "4 is X+1" after substitution of parameters. But as we know from above % "is" requires its argument to be fully instantiated and it is not, so @@ -195,10 +202,10 @@ nearbychk(X,Y) :- Y is X+1, !. nearbychk(X,Y) :- Y is X-1. % This solves the first problem: -?- nearbychk(2,3). % True. +?- nearbychk(2,3). % True. % But unfortunately it has consequences: -?- nearbychk(2,X). % X = 2. +?- nearbychk(2,X). % X = 2. % Because Prolog cannot backtrack past the cut after X = Y, it cannot % try the possibilities "Y is X+1" and "Y is X-1", so it only generates % one solution when there should be 3. @@ -230,9 +237,9 @@ nearby3(X,Y) :- nearby2(X,Y). % Here is the structured comment declaration for nearby3: -%% nearby3(+X:Int, +Y:Int) is semideterministic. -%% nearby3(+X:Int, -Y:Int) is multi. -%% nearby3(-X:Int, +Y:Int) is multi. +%! nearby3(+X:Int, +Y:Int) is semideterministic. +%! nearby3(+X:Int, -Y:Int) is multi. +%! nearby3(-X:Int, +Y:Int) is multi. % For each variable we list a type. The + or - before the variable name % indicates if the parameter is bound (+) or free (-). The word after @@ -250,13 +257,13 @@ nearby3(X,Y) :- nearby2(X,Y). % An unusual feature of Prolog is its support for atoms. Atoms are % essentially members of an enumerated type that are created on demand % whenever an unquoted non variable value is used. For example: -character(batman). % Creates atom value batman -character(robin). % Creates atom value robin -character(joker). % Creates atom value joker -character(darthVader). % Creates atom value darthVader -?- batman = batman. % True - Once created value is reused -?- batman = batMan. % False - atoms are case sensitive -?- batman = darthVader. % False - atoms are distinct +character(batman). % Creates atom value batman +character(robin). % Creates atom value robin +character(joker). % Creates atom value joker +character(darthVader). % Creates atom value darthVader +?- batman = batman. % True - Once created value is reused +?- batman = batMan. % False - atoms are case sensitive +?- batman = darthVader. % False - atoms are distinct % Atoms are popular in examples but were created on the assumption that % Prolog would be used interactively by end users - they are less @@ -267,54 +274,55 @@ character(darthVader). % Creates atom value darthVader % Note that below, writeln is used instead of print because print is % intended for debugging. -%% countTo(+X:Int) is deterministic. -%% countUpTo(+Value:Int, +Limit:Int) is deterministic. +%! countTo(+X:Int) is deterministic. +%! countUpTo(+Value:Int, +Limit:Int) is deterministic. countTo(X) :- countUpTo(1,X). countUpTo(Value, Limit) :- Value = Limit, writeln(Value), !. countUpTo(Value, Limit) :- Value \= Limit, writeln(Value), - NextValue is Value+1, - countUpTo(NextValue, Limit). + NextValue is Value+1, + countUpTo(NextValue, Limit). -?- countTo(10). % Outputs 1 to 10 +?- countTo(10). % Outputs 1 to 10 % Note the use of multiple declarations in countUpTo to create an % IF test. If Value = Limit fails the second declaration is run. % There is also a more elegant syntax. -%% countUpTo2(+Value:Int, +Limit:Int) is deterministic. +%! countUpTo2(+Value:Int, +Limit:Int) is deterministic. countUpTo2(Value, Limit) :- writeln(Value), - Value = Limit -> true ; ( - NextValue is Value+1, - countUpTo2(NextValue, Limit)). + Value = Limit -> true ; ( + NextValue is Value+1, + countUpTo2(NextValue, Limit)). -?- countUpTo2(1,10). % Outputs 1 to 10 +?- countUpTo2(1,10). % Outputs 1 to 10 % If a predicate returns multiple times it is often useful to loop % through all the values it returns. Older Prologs used a hideous syntax % called a "failure-driven loop" to do this, but newer ones use a higher % order function. -%% countTo2(+X:Int) is deterministic. +%! countTo2(+X:Int) is deterministic. countTo2(X) :- forall(between(1,X,Y),writeln(Y)). -?- countTo2(10). % Outputs 1 to 10 +?- countTo2(10). % Outputs 1 to 10 % Lists are given in square brackets. Use memberchk to check membership. % A group is safe if it doesn't include Joker or does include Batman. -%% safe(Group:list(atom)) is deterministic. + +%! safe(Group:list(atom)) is deterministic. safe(Group) :- memberchk(joker, Group) -> memberchk(batman, Group) ; true. -?- safe([robin]). % True -?- safe([joker]). % False -?- safe([joker, batman]). % True +?- safe([robin]). % True +?- safe([joker]). % False +?- safe([joker, batman]). % True % The member predicate works like memberchk if both arguments are bound, % but can accept free variables and thus can be used to loop through % lists. -?- member(X, [1,2,3]). % X = 1 ; X = 2 ; X = 3 . +?- member(X, [1,2,3]). % X = 1 ; X = 2 ; X = 3 . ?- forall(member(X,[1,2,3]), - (Y is X+1, writeln(Y))). % 2 3 4 + (Y is X+1, writeln(Y))). % 2 3 4 % The maplist function can be used to generate lists based on other % lists. Note that the output list is a free variable, causing an -- cgit v1.2.3 From 5ae8ac9988522f290460e7341c303964fb4581bc Mon Sep 17 00:00:00 2001 From: Junior Damacena Date: Wed, 28 Feb 2018 11:21:47 -0300 Subject: [Dart/pt-br] Translated Dart to pt-BR (#3071) * Added PT-BR translation to Dart * Translation in progress * Translation in progress * Moving the file to the correct language folder * Translation in progress * Translation finished * Small adjustments * File renamed to follow the naming convention * Adjustments according to suggestions on the pull request --- pt-br/dart-pt.html.markdown | 508 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 pt-br/dart-pt.html.markdown diff --git a/pt-br/dart-pt.html.markdown b/pt-br/dart-pt.html.markdown new file mode 100644 index 00000000..c127034c --- /dev/null +++ b/pt-br/dart-pt.html.markdown @@ -0,0 +1,508 @@ +--- +language: dart +filename: learndart-pt.dart +contributors: + - ["Joao Pedrosa", "https://github.com/jpedrosa/"] +translators: + - ["Junior Damacena", "https://github.com/jdamacena/"] +lang: pt-br +--- + +Dart é uma novata no reino das linguagens de programação. +Ela empresta muito de outras linguagens mais conhecidas, e tem a meta de não se diferenciar muito de seu irmão, JavaScript. Assim como JavaScript, Dart foi pensada para oferecer grande integração com o Browser. + +A característica mais controversa da Dart é a sua Tipagem Opcional, ou seja, não é obrigatório declarar tipos. + +```dart +import "dart:collection"; +import "dart:math" as DM; + +// Bem vindo ao Aprenda Dart em 15 minutos. http://www.dartlang.org/ +// Este é um tutorial executável. Você pode rodar esse tutorial com Dart ou no +// site Try Dart!, é só copiar e colar este código lá. http://try.dartlang.org/ + +// Declarações de funções e métodos são iguais. Declarações de funções +// podem ser aninhadas. A declaração é feita das seguintes formas +// nome() {} ou nome() => expressaoDeUmaLinhaSo; +// A declaração feita com a seta tem um return implícito para o resultado da +// expressão. +example1() { + example1nested1() { + example1nested2() => print("Example1 nested 1 nested 2"); + example1nested2(); + } + example1nested1(); +} + +// Funções anônimas são criadas sem um nome. +example2() { + example2nested1(fn) { + fn(); + } + example2nested1(() => print("Example2 nested 1")); +} + +// Quando uma função é declarada como parâmetro, a declaração pode incluir o número +// de parâmetros que a função recebe, isso é feito especificando o nome de cada um dos +// parâmetros que serão recebidos pela função. +example3() { + example3nested1(fn(informSomething)) { + fn("Example3 nested 1"); + } + example3planB(fn) { // Ou não declare o número de parâmetros. + fn("Example3 plan B"); + } + example3nested1((s) => print(s)); + example3planB((s) => print(s)); +} + +// Funções têm acesso à variáveis fora de seu escopo +var example4Something = "Example4 nested 1"; +example4() { + example4nested1(fn(informSomething)) { + fn(example4Something); + } + example4nested1((s) => print(s)); +} + +// Declaração de classe com um método chamado sayIt, que também tem acesso +// à variável externa, como se fosse uma função como se viu antes. +var example5method = "Example5 sayIt"; +class Example5Class { + sayIt() { + print(example5method); + } +} +example5() { + // Criar uma instância anônima de Example5Class e chamar o método sayIt + // nela. + new Example5Class().sayIt(); +} + +// A declaração de uma classe é feita da seguinte maneira: class name { [classBody] }. +// onde classBody pode incluir métodos e variáveis de instância, assim como +// métodos e variáveis de classe. +class Example6Class { + var example6InstanceVariable = "Example6 instance variable"; + sayIt() { + print(example6InstanceVariable); + } +} +example6() { + new Example6Class().sayIt(); +} + +// Métodos e variáveis de classe são declarados como "static". +class Example7Class { + static var example7ClassVariable = "Example7 class variable"; + static sayItFromClass() { + print(example7ClassVariable); + } + sayItFromInstance() { + print(example7ClassVariable); + } +} +example7() { + Example7Class.sayItFromClass(); + new Example7Class().sayItFromInstance(); +} + +// Literais são ótimos, mas há uma limitação para o que eles podem ser +// quando estão fora do corpo de uma função/método. Literais fora do escopo da classe +// ou fora da classe têm que ser constantes. Strings e números são constantes +// por padrão. Mas arrays e mapas não. Eles podem ser declarados como constantes +// usando o comando "const". +var example8A = const ["Example8 const array"], + example8M = const {"someKey": "Example8 const map"}; +example8() { + print(example8A[0]); + print(example8M["someKey"]); +} + +// Loops em Dart são criados com for () {} ou while () {}, +// um pouco mais moderno temos for (.. in ..) {}, ou funções de callbacks com muitas +// funcionalidades, começando com o forEach. +var example9A = const ["a", "b"]; +example9() { + for (var i = 0; i < example9A.length; i++) { + print("Example9 for loop '${example9A[i]}'"); + } + var i = 0; + while (i < example9A.length) { + print("Example9 while loop '${example9A[i]}'"); + i++; + } + for (var e in example9A) { + print("Example9 for-in loop '${e}'"); + } + example9A.forEach((e) => print("Example9 forEach loop '${e}'")); +} + +// Para percorrer os caracteres de uma string ou extrair uma substring. +var example10S = "ab"; +example10() { + for (var i = 0; i < example10S.length; i++) { + print("Example10 String character loop '${example10S[i]}'"); + } + for (var i = 0; i < example10S.length; i++) { + print("Example10 substring loop '${example10S.substring(i, i + 1)}'"); + } +} + +// Int e double são os dois formatos de número suportados. +example11() { + var i = 1 + 320, d = 3.2 + 0.01; + print("Example11 int ${i}"); + print("Example11 double ${d}"); +} + +// DateTime traz operações com data/hora. +example12() { + var now = new DateTime.now(); + print("Example12 now '${now}'"); + now = now.add(new Duration(days: 1)); + print("Example12 tomorrow '${now}'"); +} + +// Expressões regulares são suportadas. +example13() { + var s1 = "some string", s2 = "some", re = new RegExp("^s.+?g\$"); + match(s) { + if (re.hasMatch(s)) { + print("Example13 regexp matches '${s}'"); + } else { + print("Example13 regexp doesn't match '${s}'"); + } + } + match(s1); + match(s2); +} + +// Expressões booleanas precisam retornar ou true ou false, já que +// Dart não faz a conversão implicitamente. +example14() { + var v = true; + if (v) { + print("Example14 value is true"); + } + v = null; + try { + if (v) { + // Nunca seria executada + } else { + // Nunca seria executada + } + } catch (e) { + print("Example14 null value causes an exception: '${e}'"); + } +} + +// try/catch/finally e throw são usados para tratamento de exceções. +// throw aceita qualquer objeto como parâmetro; +example15() { + try { + try { + throw "Some unexpected error."; + } catch (e) { + print("Example15 an exception: '${e}'"); + throw e; // Re-throw + } + } catch (e) { + print("Example15 catch exception being re-thrown: '${e}'"); + } finally { + print("Example15 Still run finally"); + } +} + +// Para mais eficiência ao criar strings longas dinamicamente, use o +// StringBuffer. Ou você pode também concatenar um array de strings. +example16() { + var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e; + for (e in a) { sb.write(e); } + print("Example16 dynamic string created with " + "StringBuffer '${sb.toString()}'"); + print("Example16 join string array '${a.join()}'"); +} + +// Strings podem ser concatenadas apenas colocando strings literais uma perto +// da outra, sem necessidade de nenhum outro operador. +example17() { + print("Example17 " + "concatenar " + "strings " + "é simples assim"); +} + +// Strings podem ser delimitadas por apóstrofos ou aspas e não há +// diferença entre os dois. Essa flexibilidade pode ser boa para +// evitar a necessidade de escapar conteúdos que contenham o delimitador da string. +// Por exemplo, aspas dos atributos HTMLse a string conter HTML. +example18() { + print('Example18 ' + "Don't can't I'm Etc" + ''); +} + +// Strings com três apóstrofos ou aspas podem +// ter muitas linhas e incluem os delimitadores de linha (ou seja, os enter). +example19() { + print('''Example19 +Example19 Don't can't I'm Etc +Example19 '''); +} + +// Strings têm a função de interpolação que é chamada com o caractere $. +// Com $ { [expression] }, o retorno da expressão é interpolado. +// $ seguido pelo nome de uma variável interpola o conteúdo dessa variável. +// $ pode ser escapedo assim \$. +example20() { + var s1 = "'\${s}'", s2 = "'\$s'"; + print("Example20 \$ interpolation ${s1} or $s2 works."); +} + +// A tipagem opcional permite que APIs usem anotações e também ajuda os +// IDEs na hora das refatorações, auto-complete e checagem de +// erros. Note que até agora não declaramos nenhum tipo e o programa está +// funcionando normalmente. De fato, os tipos são ignorados em tempo de execução. +// Os tipos podem até mesmo estarem errados e o programa ainda vai dar o +// benefício da dúvida e rodar, visto que os tipos não importam. +// Existe um parâmetro que checa erros de tipagem que é o +// checked mode, dizem que é útil enquanto se está desenvolvendo, +// mas também é mais lento devido às checagens extras e por isso +// é evitado em ambiente de produção. +class Example21 { + List _names; + Example21() { + _names = ["a", "b"]; + } + List get names => _names; + set names(List list) { + _names = list; + } + int get length => _names.length; + void add(String name) { + _names.add(name); + } +} +void example21() { + Example21 o = new Example21(); + o.add("c"); + print("Example21 names '${o.names}' and length '${o.length}'"); + o.names = ["d", "e"]; + print("Example21 names '${o.names}' and length '${o.length}'"); +} + +// Herança em classes é feito assim: class name extends AnotherClassName {}. +class Example22A { + var _name = "Some Name!"; + get name => _name; +} +class Example22B extends Example22A {} +example22() { + var o = new Example22B(); + print("Example22 class inheritance '${o.name}'"); +} + +// Mistura de classes também é possível, e é feito assim: +// class name extends SomeClass with AnotherClassName {} +// É necessário extender uma classe para poder misturar com outra. +// No momento, classes misturadas não podem ter construtor. +// Mistura de classes é mais usado para compartilhar métodos com classes distantes, então +// a herança comum não fica no caminho do reuso de código. +// As misturas aparecem após o comando "with" na declaração da classe. +class Example23A {} +class Example23Utils { + addTwo(n1, n2) { + return n1 + n2; + } +} +class Example23B extends Example23A with Example23Utils { + addThree(n1, n2, n3) { + return addTwo(n1, n2) + n3; + } +} +example23() { + var o = new Example23B(), r1 = o.addThree(1, 2, 3), + r2 = o.addTwo(1, 2); + print("Example23 addThree(1, 2, 3) results in '${r1}'"); + print("Example23 addTwo(1, 2) results in '${r2}'"); +} + +// O método construtor da classe usa o mesmo nome da classe e +// é feito assim SomeClass() : super() {}, onde a parte ": super()" +// é opcional e é usada para passar parâmetros estáticos para o +// construtor da classe pai. +class Example24A { + var _value; + Example24A({value: "someValue"}) { + _value = value; + } + get value => _value; +} +class Example24B extends Example24A { + Example24B({value: "someOtherValue"}) : super(value: value); +} +example24() { + var o1 = new Example24B(), + o2 = new Example24B(value: "evenMore"); + print("Example24 calling super during constructor '${o1.value}'"); + print("Example24 calling super during constructor '${o2.value}'"); +} + +// Há um atalho para passar parâmetros para o construtor no caso de classes mais simples. +// Simplesmente use o prefixo this.nomeDoParametro e isso irá passar o parâmetro para uma +// instância de variável de mesmo nome. +class Example25 { + var value, anotherValue; + Example25({this.value, this.anotherValue}); +} +example25() { + var o = new Example25(value: "a", anotherValue: "b"); + print("Example25 shortcut for constructor '${o.value}' and " + "'${o.anotherValue}'"); +} + +// Parâmetros com nome estão disponíveis quando declarados entre {}. +// Quando os parâmetros têm nomes, eles podem ser passados em qualquer ordem. +// Parâmetros declarados entre [] são opcionais. +example26() { + var _name, _surname, _email; + setConfig1({name, surname}) { + _name = name; + _surname = surname; + } + setConfig2(name, [surname, email]) { + _name = name; + _surname = surname; + _email = email; + } + setConfig1(surname: "Doe", name: "John"); + print("Example26 name '${_name}', surname '${_surname}', " + "email '${_email}'"); + setConfig2("Mary", "Jane"); + print("Example26 name '${_name}', surname '${_surname}', " + "email '${_email}'"); +} + +// Variáveis declaradas com um final só podem receber valor uma vez. +// No caso de classes, variáveis final podem ter valor atribuido através +// de um parâmetro no construtor +class Example27 { + final color1, color2; + // Um pouco de flexibilidade ao criar variáveis final com a sintaxe + // que é a seguinte: + Example27({this.color1, color2}) : color2 = color2; +} +example27() { + final color = "orange", o = new Example27(color1: "lilac", color2: "white"); + print("Example27 color is '${color}'"); + print("Example27 color is '${o.color1}' and '${o.color2}'"); +} + +// para importar uma biblioteca, use import "libraryPath" ou se for uma biblioteca da linguagem, +// import "dart:libraryName". Também tem o gerenciador de pacotes "pub"que tem +// sua própria convenção de import "package:packageName". +// Veja o import "dart:collection"; no início do arquivo. Imports devem vir no início +// do arquivo. IterableBase vem de dart:collection. +class Example28 extends IterableBase { + var names; + Example28() { + names = ["a", "b"]; + } + get iterator => names.iterator; +} +example28() { + var o = new Example28(); + o.forEach((name) => print("Example28 '${name}'")); +} + +// Para controle de fluxo nós temos: +// * switch com comandos break obrigatórios +// * if-else if-else e se-ternário ..?..:.. +// * closures e funções anônimas +// * comandos break, continue e return +example29() { + var v = true ? 30 : 60; + switch (v) { + case 30: + print("Example29 switch statement"); + break; + } + if (v < 30) { + } else if (v > 30) { + } else { + print("Example29 if-else statement"); + } + callItForMe(fn()) { + return fn(); + } + rand() { + v = new DM.Random().nextInt(50); + return v; + } + while (true) { + print("Example29 callItForMe(rand) '${callItForMe(rand)}'"); + if (v != 30) { + break; + } else { + continue; + } + // Nunca chega aqui. + } +} + +// Você pode converter string para int, double para int, ou só pegar a parte inteira da divisão +// usando o comando ~/. Vamos jogar um jogo de adivinhação. +example30() { + var gn, tooHigh = false, + n, n2 = (2.0).toInt(), top = int.parse("123") ~/ n2, bottom = 0; + top = top ~/ 6; + gn = new DM.Random().nextInt(top + 1); // +1 porque o máximo do nextInt conta o número passado - 1 + print("Example30 Diga um número entre 0 e ${top}"); + guessNumber(i) { + if (n == gn) { + print("Example30 Você acertou! O número é ${gn}"); + } else { + tooHigh = n > gn; + print("Example30 O número ${n} é muito " + "${tooHigh ? 'alto' : 'baixo'}. Tente de novo"); + } + return n == gn; + } + n = (top - bottom) ~/ 2; + while (!guessNumber(n)) { + if (tooHigh) { + top = n - 1; + } else { + bottom = n + 1; + } + n = bottom + ((top - bottom) ~/ 2); + } +} + +// Programas em Dart só têm um ponto de entrada, que é a função main. +// Nada será executado antes da funcão main de um programa. +// Isso ajuda a carregar o programa mais rapidamente, até mesmo quando o +// carregamento é "Lazy". +// O programa deve começar com: +main() { + print("Aprenda Dart em 15 minutos!"); + [example1, example2, example3, example4, example5, example6, example7, + example8, example9, example10, example11, example12, example13, example14, + example15, example16, example17, example18, example19, example20, + example21, example22, example23, example24, example25, example26, + example27, example28, example29, example30 + ].forEach((ef) => ef()); +} + +``` + +## Continue lendo + +Dart tem um site bastante fácil de entender. Ele tem os docs da API, tutoriais, artigos e muito mais, incluindo uma +opção muito útil de testar o Dart online. +http://www.dartlang.org/ +http://try.dartlang.org/ + + + -- cgit v1.2.3 From b0cbcaad2c00e179db2becf0e9dbece8bb3071d3 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 20:17:09 +0545 Subject: Fix URLs --- dart.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index 5027dc3e..0e1ded43 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -500,8 +500,8 @@ main() { Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a useful Try Dart online. -http://www.dartlang.org/ -http://try.dartlang.org/ +* [https://www.dartlang.org](https://www.dartlang.org) +* [https://try.dartlang.org](https://try.dartlang.org) -- cgit v1.2.3 From 784bc7a9bd18b78b344e5fa4057df430ba042e0e Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 20:18:45 +0545 Subject: Fix URLs --- pt-br/dart-pt.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pt-br/dart-pt.html.markdown b/pt-br/dart-pt.html.markdown index c127034c..e9d72850 100644 --- a/pt-br/dart-pt.html.markdown +++ b/pt-br/dart-pt.html.markdown @@ -501,8 +501,9 @@ main() { Dart tem um site bastante fácil de entender. Ele tem os docs da API, tutoriais, artigos e muito mais, incluindo uma opção muito útil de testar o Dart online. -http://www.dartlang.org/ -http://try.dartlang.org/ +* [https://www.dartlang.org](https://www.dartlang.org) +* [https://try.dartlang.org](https://try.dartlang.org) + -- cgit v1.2.3 From 02524e046eed0cd668a557d2eeb34ee86bd811b9 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 20:19:58 +0545 Subject: Fix URLs --- zh-cn/dart-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/dart-cn.html.markdown b/zh-cn/dart-cn.html.markdown index 6a6562bc..b0287f0c 100644 --- a/zh-cn/dart-cn.html.markdown +++ b/zh-cn/dart-cn.html.markdown @@ -492,8 +492,8 @@ main() { Dart 有一个综合性网站。它涵盖了 API 参考、入门向导、文章以及更多, 还包括一个有用的在线试用 Dart 页面。 -http://www.dartlang.org/ -http://try.dartlang.org/ +* [https://www.dartlang.org](https://www.dartlang.org) +* [https://try.dartlang.org](https://try.dartlang.org) -- cgit v1.2.3 From 9f33f260dc305a40b6476c081ea16e75ac2ced50 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Wed, 28 Feb 2018 20:25:03 +0545 Subject: Fix typo --- dart.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index 0e1ded43..76857306 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -500,8 +500,8 @@ main() { Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a useful Try Dart online. -* [https://www.dartlang.org](https://www.dartlang.org) -* [https://try.dartlang.org](https://try.dartlang.org) +[https://www.dartlang.org](https://www.dartlang.org) +[https://try.dartlang.org](https://try.dartlang.org) -- cgit v1.2.3 From 4d49a48d6cb23304112ce0de47689250ada225be Mon Sep 17 00:00:00 2001 From: Huiz <1057354161@qq.com> Date: Wed, 28 Feb 2018 22:57:32 +0800 Subject: [typescript/zh-cn] fix reference (#3040) --- zh-cn/typescript-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown index 2651b1cb..032f89e4 100644 --- a/zh-cn/typescript-cn.html.markdown +++ b/zh-cn/typescript-cn.html.markdown @@ -153,7 +153,7 @@ var pairToTuple = function(p: Pair) { var tuple = pairToTuple({ item1:"hello", item2:"world"}); // 引用定义文件 -// +/// // 模板字符串(使用反引号的字符串) // 嵌入变量的模板字符串 -- cgit v1.2.3 From 50f93a94d4337b5a4f268d0832bf0fea55f55c37 Mon Sep 17 00:00:00 2001 From: qzhangjhu Date: Wed, 28 Feb 2018 10:08:29 -0500 Subject: Corrections on Python3 page --- python3.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index b0f04a02..019934cb 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -790,11 +790,11 @@ class Superhero(Human): # This calls the parent class constructor: super().__init__(name) - # overload the sing method + # override the sing method def sing(self): return 'Dun, dun, DUN!' - # add an additional class method + # add an additional instance method def boast(self): for power in self.superpowers: print("I wield the power of {pow}!".format(pow=power)) @@ -817,7 +817,7 @@ if __name__ == '__main__': # Calls parent method but uses its own class attribute print(sup.get_species()) # => Superhuman - # Calls overloaded method + # Calls overridden method print(sup.sing()) # => Dun, dun, DUN! # Calls method from Human @@ -872,7 +872,7 @@ class Batman(Superhero, Bat): def __init__(self, *args, **kwargs): # Typically to inherit attributes you have to call super: - #super(Batman, self).__init__(*args, **kwargs) + # super(Batman, self).__init__(*args, **kwargs) # However we are dealing with multiple inheritance here, and super() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. @@ -901,7 +901,7 @@ if __name__ == '__main__': # Calls parent method but uses its own class attribute print(sup.get_species()) # => Superhuman - # Calls overloaded method + # Calls overridden method print(sup.sing()) # => nan nan nan nan nan batman! # Calls method from Human, because inheritance order matters -- cgit v1.2.3 From 6968c5724892ec0ea787929a307552d3dd211974 Mon Sep 17 00:00:00 2001 From: Rommel Martinez Date: Thu, 1 Mar 2018 21:25:04 +0800 Subject: [common-lisp/en]: clean up and add more information --- common-lisp.html.markdown | 662 +++++++++++++++++++++++++--------------------- 1 file changed, 360 insertions(+), 302 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 9a23bc26..5f6975b6 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -4,82 +4,91 @@ language: "Common Lisp" filename: commonlisp.lisp contributors: - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] --- -ANSI Common Lisp is a general purpose, multi-paradigm programming -language suited for a wide variety of industry applications. It is -frequently referred to as a programmable programming language. +Common Lisp is a general-purpose, multi-paradigm programming language suited for a wide variety of +industry applications. It is frequently referred to as a programmable programming language. -The classic starting point is [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) - -Another popular and recent book is -[Land of Lisp](http://landoflisp.com/). +The classic starting point is [Practical Common Lisp](http://www.gigamonkeys.com/book/). Another +popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book about best practices, +[Common Lisp Recipes](http://weitz.de/cl-recipes/), was recently published. ```common_lisp -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- ;;; 0. Syntax -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- -;;; General form. +;;; General form -;; Lisp has two fundamental pieces of syntax: the ATOM and the -;; S-expression. Typically, grouped S-expressions are called `forms`. +;;; CL has two fundamental pieces of syntax: ATOM and S-EXPRESSION. +;;; Typically, grouped S-expressions are called `forms`. -10 ; an atom; it evaluates to itself +10 ; an atom; it evaluates to itself +:thing ; another atom; evaluating to the symbol :thing +t ; another atom, denoting true +(+ 1 2 3 4) ; an s-expression +'(4 :foo t) ; another s-expression -:THING ;Another atom; evaluating to the symbol :thing. -t ; another atom, denoting true. +;;; Comments -(+ 1 2 3 4) ; an s-expression +;;; Single-line comments start with a semicolon; use four for file-level +;;; comments, three for section descriptions, two inside definitions, and one +;;; for single lines. For example, -'(4 :foo t) ;another one +;;;; life.lisp +;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph. +;;; Needed by the function LINULUKO. -;;; Comments +(defun meaning (life) + "Return the computed meaning of LIFE" + (let ((meh "abc")) + ;; Invoke krakaboom + (loop :for x :across meh + :collect x))) ; store values into x, then return it -;; Single line comments start with a semicolon; use two for normal -;; comments, three for section comments, and four for file-level -;; comments. +;;; Block comments, on the other hand, allow for free-form comments. They are +;;; delimited with #| and |# -#| Block comments - can span multiple lines and... +#| This is a block comment which + can span multiple lines and #| they can be nested! |# |# -;;; Environment. -;; A variety of implementations exist; most are -;; standard-conformant. CLISP is a good starting one. +;;; Environment -;; Libraries are managed through Quicklisp.org's Quicklisp system. +;;; A variety of implementations exist; most are standards-conformant. SBCL +;;; is a good starting point. Third party libraries can be easily installed with +;;; Quicklisp -;; Common Lisp is usually developed with a text editor and a REPL -;; (Read Evaluate Print Loop) running at the same time. The REPL -;; allows for interactive exploration of the program as it is "live" -;; in the system. +;;; CL is usually developed with a text editor and a Real Eval Print +;;; Loop (REPL) running at the same time. The REPL allows for interactive +;;; exploration of the program while it is running "live". -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; 1. Primitive Datatypes and Operators -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- +;;; 1. Primitive datatypes and operators +;;;----------------------------------------------------------------------------- ;;; Symbols 'foo ; => FOO Notice that the symbol is upper-cased automatically. -;; Intern manually creates a symbol from a string. +;;; INTERN manually creates a symbol from a string. -(intern "AAAA") ; => AAAA - -(intern "aaa") ; => |aaa| +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| ;;; Numbers + 9999999999999999999999 ; integers #b111 ; binary => 7 #o111 ; octal => 73 @@ -89,313 +98,362 @@ t ; another atom, denoting true. 1/2 ; ratios #C(1 2) ; complex numbers +;;; Function application are written as (f x y z ...) where f is a function and +;;; x, y, z, ... are the arguments. + +(+ 1 2) ; => 3 + +;;; If you want to create literal data, use QUOTE to prevent it from being +;;; evaluated + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; The shorthand for QUOTE is ' + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; Basic arithmetic operations + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Booleans + +t ; true; any non-NIL value is true +nil ; false; also, the empty list: () +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; Characters + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; Strings are fixed-length arrays of characters -;; Function application is written (f x y z ...) -;; where f is a function and x, y, z, ... are operands -;; If you want to create a literal list of data, use ' to stop it from -;; being evaluated - literally, "quote" the data. -'(+ 1 2) ; => (+ 1 2) -;; You can also call a function manually: -(funcall #'+ 1 2 3) ; => 6 -;; Some arithmetic operations -(+ 1 1) ; => 2 -(- 8 1) ; => 7 -(* 10 2) ; => 20 -(expt 2 3) ; => 8 -(mod 5 2) ; => 1 -(/ 35 5) ; => 7 -(/ 1 3) ; => 1/3 -(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) - - ;;; Booleans -t ; for true (any not-nil value is true) -nil ; for false - and the empty list -(not nil) ; => t -(and 0 t) ; => t -(or 0 nil) ; => 0 - - ;;; Characters -#\A ; => #\A -#\λ ; => #\GREEK_SMALL_LETTER_LAMDA -#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA - -;;; Strings are fixed-length arrays of characters. "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character -;; Strings can be concatenated too! -(concatenate 'string "Hello " "world!") ; => "Hello world!" +;;; Strings can be concatenated + +(concatenate 'string "Hello, " "world!") ; => "Hello, world!" + +;;; A string can be treated like a sequence of characters -;; A string can be treated like a sequence of characters (elt "Apple" 0) ; => #\A -;; format can be used to format strings: -(format nil "~a can be ~a" "strings" "formatted") +;;; FORMAT is used to create formatted output, which ranges from simple string +;;; interpolation to loops and conditionals. The first argument to FORMAT +;;; determines where will the formatted string go. If it is NIL, FORMAT +;;; simply returns the formatted string as a value; if it is T, FORMAT outputs +;;; to the standard output, usually the screen, then it returns NIL. + +(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!" +(format t "~A, ~A!" "Hello" "world") ; => NIL -;; Printing is pretty easy; ~% is the format specifier for newline. -(format t "Common Lisp is groovy. Dude.~%") +;;;----------------------------------------------------------------------------- +;;; 2. Variables +;;;----------------------------------------------------------------------------- -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 2. Variables -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; You can create a global (dynamically scoped) using defparameter -;; a variable name can use any character except: ()",'`;#|\ +;;; You can create a global (dynamically scoped) variable using DEFVAR and +;;; DEFPARAMETER. The variable name can use any character except: ()",'`;#|\ -;; Dynamically scoped variables should have earmuffs in their name! +;;; The difference between DEFVAR and DEFPARAMETER is that re-evaluating a +;;; DEFVAR expression doesn't change the value of the variable. DEFPARAMETER, +;;; on the other hand, does. + +;;; By convention, dynamically scoped variables have earmuffs in their name. (defparameter *some-var* 5) *some-var* ; => 5 -;; You can also use unicode characters. +;;; You can also use unicode characters. (defparameter *AΛB* nil) +;;; Accessing a previously unbound variable is an undefined behavior, but +;;; possible. Don't do it. + +;;; You can create local bindings with LET. In the following snippet, `me` is +;;; bound to "dance with you" only within the (let ...). LET always returns +;;; the value of the last `form` in the LET form. -;; Accessing a previously unbound variable is an -;; undefined behavior (but possible). Don't do it. +(let ((me "dance with you")) me) ; => "dance with you" -;; Local binding: `me` is bound to "dance with you" only within the -;; (let ...). Let always returns the value of the last `form` in the -;; let form. +;;;-----------------------------------------------------------------------------; +;;; 3. Structs and collections +;;;-----------------------------------------------------------------------------; -(let ((me "dance with you")) - me) -;; => "dance with you" -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. Structs and Collections -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; Structs -;; Structs (defstruct dog name breed age) (defparameter *rover* (make-dog :name "rover" :breed "collie" :age 5)) -*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. |# +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T (dog-name *rover*) ; => "rover" -;; Dog-p, make-dog, and dog-name are all created by defstruct! +;;; DOG-P, MAKE-DOG, and DOG-NAME are all automatically created by DEFSTRUCT + ;;; Pairs -;; `cons' constructs pairs, `car' and `cdr' extract the first -;; and second elements -(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) -(car (cons 'SUBJECT 'VERB)) ; => SUBJECT -(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; CONS constructs pairs. CAR and CDR return the head and tail of a CONS-pair. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + ;;; Lists -;; Lists are linked-list data structures, made of `cons' pairs and end -;; with a `nil' (or '()) to mark the end of the list -(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) -;; `list' is a convenience variadic constructor for lists -(list 1 2 3) ; => '(1 2 3) -;; and a quote can also be used for a literal list value -'(1 2 3) ; => '(1 2 3) +;;; Lists are linked-list data structures, made of CONS pairs and end with a +;;; NIL (or '()) to mark the end of the list + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; LIST is a convenience variadic constructor for lists + +(list 1 2 3) ; => '(1 2 3) -;; Can still use `cons' to add an item to the beginning of a list -(cons 4 '(1 2 3)) ; => '(4 1 2 3) +;;; When the first argument to CONS is an atom and the second argument is a +;;; list, CONS returns a new CONS-pair with the first argument as the first +;;; item and the second argument as the rest of the CONS-pair -;; Use `append' to - surprisingly - append lists together -(append '(1 2) '(3 4)) ; => '(1 2 3 4) +(cons 4 '(1 2 3)) ; => '(4 1 2 3) -;; Or use concatenate - +;;; Use APPEND to join lists -(concatenate 'list '(1 2) '(3 4)) +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Or CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Lists are a very central type, so there is a wide variety of functionality for +;;; them, a few examples: -;; Lists are a very central type, so there is a wide variety of functionality for -;; them, a few examples: (mapcar #'1+ '(1 2 3)) ; => '(2 3 4) (mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) (remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) -(every #'evenp '(1 2 3 4)) ; => nil +(every #'evenp '(1 2 3 4)) ; => NIL (some #'oddp '(1 2 3 4)) ; => T (butlast '(subject verb object)) ; => (SUBJECT VERB) ;;; Vectors -;; Vector's literals are fixed-length arrays -#(1 2 3) ; => #(1 2 3) - -;; Use concatenate to add vectors together -(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) +;;; Vector's literals are fixed-length arrays -;;; Arrays +#(1 2 3) ; => #(1 2 3) -;; Both vectors and strings are special-cases of arrays. +;;; Use CONCATENATE to add vectors together -;; 2D arrays +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) -(make-array (list 2 2)) -;; (make-array '(2 2)) works as well. +;;; Arrays -; => #2A((0 0) (0 0)) +;;; Both vectors and strings are special-cases of arrays. -(make-array (list 2 2 2)) +;;; 2D arrays -; => #3A(((0 0) (0 0)) ((0 0) (0 0))) +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) -;; Caution- the default initial values are -;; implementation-defined. Here's how to define them: +;;; Caution: the default initial values of MAKE-ARRAY are implementation-defined. +;;; To explicitly specify them: -(make-array '(2) :initial-element 'unset) +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) -; => #(UNSET UNSET) +;;; To access the element at 1, 1, 1: -;; And, to access the element at 1,1,1 - -(aref (make-array (list 2 2 2)) 1 1 1) +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 -; => 0 ;;; Adjustable vectors -;; Adjustable vectors have the same printed representation -;; as fixed-length vector's literals. +;;; Adjustable vectors have the same printed representation as +;;; fixed-length vector's literals. (defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) - :adjustable t :fill-pointer t)) - + :adjustable t :fill-pointer t)) *adjvec* ; => #(1 2 3) -;; Adding new element: -(vector-push-extend 4 *adjvec*) ; => 3 - -*adjvec* ; => #(1 2 3 4) +;;; Adding new elements +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) -;;; Naively, sets are just lists: +;;; Sets, naively, are just lists: -(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) -(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 -(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) -(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) -;; But you'll want to use a better data structure than a linked list -;; for performant work! +;;; However, you'll need a better data structure than linked lists when working +;;; with larger data sets ;;; Dictionaries are implemented as hash tables. -;; Create a hash table +;;; Create a hash table + (defparameter *m* (make-hash-table)) -;; set a value +;;; Set value + (setf (gethash 'a *m*) 1) -;; Retrieve a value -(gethash 'a *m*) ; => 1, t +;;; Retrieve value + +(gethash 'a *m*) ; => 1, T + +;;; CL expressions have the ability to return multiple values. + +(values 1 2) ; => 1, 2 + +;;; which can be bound with MULTIPLE-VALUE-BIND + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) -;; Detail - Common Lisp has multiple return values possible. gethash -;; returns t in the second value if anything was found, and nil if -;; not. +;;; GETHASH is an example of a function that returns multiple values. The first +;;; value it return is the value of the key in the hash table; if the key is +;;; not found it returns NIL. -;; Retrieving a non-present value returns nil - (gethash 'd *m*) ;=> nil, nil +;;; The second value determines if that key is indeed present in the hash +;;; table. If a key is not found in the table it returns NIL. This behavior +;;; allows us to check if the value of a key is actually NIL. + +;;; Retrieving a non-present value returns nil + +(gethash 'd *m*) ;=> NIL, NIL + +;;; You can provide a default value for missing keys -;; You can provide a default value for missing keys (gethash 'd *m* :not-found) ; => :NOT-FOUND -;; Let's handle the multiple return values here in code. +;;; Let's handle the multiple return values here in code. -(multiple-value-bind - (a b) +(multiple-value-bind (a b) (gethash 'd *m*) (list a b)) ; => (NIL NIL) -(multiple-value-bind - (a b) +(multiple-value-bind (a b) (gethash 'a *m*) (list a b)) ; => (1 T) -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 3. Functions -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Use `lambda' to create anonymous functions. -;; A function always returns the value of its last expression. -;; The exact printable representation of a function will vary... +;;;----------------------------------------------------------------------------- +;;; 3. Functions +;;;----------------------------------------------------------------------------- + +;;; Use LAMBDA to create anonymous functions. Functions always returns the +;;; value of the last expression. The exact printable representation of a +;;; function varies between implementations. (lambda () "Hello World") ; => # -;; Use funcall to call lambda functions -(funcall (lambda () "Hello World")) ; => "Hello World" +;;; Use FUNCALL to call anonymous functions + +(funcall (lambda () "Hello World")) ; => "Hello World" +(funcall #'+ 1 2 3) ; => 6 -;; Or Apply +;;; A call to FUNCALL is also implied when the lambda expression is the CAR of +;;; an unquoted list + +((lambda () "Hello World")) ; => "Hello World" +((lambda (val) val) "Hello World") ; => "Hello World" + +;;; FUNCALL is used when the arguments are known beforehand. Otherwise, use APPLY + +(apply #'+ '(1 2 3)) ; => 6 (apply (lambda () "Hello World") nil) ; => "Hello World" -;; De-anonymize the function -(defun hello-world () - "Hello World") +;;; To name a function, use DEFUN + +(defun hello-world () "Hello World") (hello-world) ; => "Hello World" -;; The () in the above is the list of arguments for the function -(defun hello (name) - (format nil "Hello, ~a" name)) +;;; The () in the definition above is the list of arguments +(defun hello (name) (format nil "Hello, ~A" name)) (hello "Steve") ; => "Hello, Steve" -;; Functions can have optional arguments; they default to nil +;;; Functions can have optional arguments; they default to NIL (defun hello (name &optional from) - (if from - (format t "Hello, ~a, from ~a" name from) - (format t "Hello, ~a" name))) - - (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + (if from + (format t "Hello, ~A, from ~A" name from) + (format t "Hello, ~A" name))) -;; And the defaults can be set... -(defun hello (name &optional (from "The world")) - (format t "Hello, ~a, from ~a" name from)) +(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas -(hello "Steve") -; => Hello, Steve, from The world +;;; The default values can also be specified -(hello "Steve" "the alpacas") -; => Hello, Steve, from the alpacas +(defun hello (name &optional (from "The world")) + (format nil "Hello, ~A, from ~A" name from)) +(hello "Steve") ; => Hello, Steve, from The world +(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas -;; And of course, keywords are allowed as well... usually more -;; flexible than &optional. +;;; Functions also have keyword arguments to allow non-positional arguments (defun generalized-greeter (name &key (from "the world") (honorific "Mx")) - (format t "Hello, ~a ~a, from ~a" honorific name from)) + (format t "Hello, ~A ~A, from ~A" honorific name from)) -(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world +(generalized-greeter "Jim") +; => Hello, Mx Jim, from the world (generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") ; => Hello, Mr Jim, from the alpacas you met last summer -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 4. Equality -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Common Lisp has a sophisticated equality system. A couple are covered here. +;;;----------------------------------------------------------------------------- +;;; 4. Equality +;;;----------------------------------------------------------------------------- + +;;; CL has a sophisticated equality system. Some are covered here. -;; for numbers use `=' -(= 3 3.0) ; => t -(= 2 1) ; => nil +;;; For numbers, use `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL -;; for object identity (approximately) use `eql` -(eql 3 3) ; => t -(eql 3 3.0) ; => nil -(eql (list 3) (list 3)) ; => nil +;;; For object identity (approximately) use EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL -;; for lists, strings, and bit-vectors use `equal' -(equal (list 'a 'b) (list 'a 'b)) ; => t -(equal (list 'a 'b) (list 'b 'a)) ; => nil +;;; for lists, strings, and bit-vectors use EQUAL +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Control Flow -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;;----------------------------------------------------------------------------- +;;; 5. Control Flow +;;;----------------------------------------------------------------------------- ;;; Conditionals @@ -404,71 +462,75 @@ nil ; for false - and the empty list "this is false") ; else expression ; => "this is true" -;; In conditionals, all non-nil values are treated as true +;;; In conditionals, all non-NIL values are treated as true + (member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) (if (member 'Groucho '(Harpo Groucho Zeppo)) 'yep 'nope) ; => 'YEP -;; `cond' chains a series of tests to select a result +;;; COND chains a series of tests to select a result (cond ((> 2 2) (error "wrong!")) ((< 2 2) (error "wrong again!")) (t 'ok)) ; => 'OK -;; Typecase switches on the type of the value +;;; TYPECASE switches on the type of the value (typecase 1 (string :string) (integer :int)) - ; => :int -;;; Iteration -;; Of course recursion is supported: +;;; Looping -(defun walker (n) - (if (zerop n) - :walked - (walker (- n 1)))) +;;; Recursion -(walker 5) ; => :walked +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) -;; Most of the time, we use DOLIST or LOOP +(fact 5) ; => 120 +;;; Iteration -(dolist (i '(1 2 3 4)) - (format t "~a" i)) +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) -; => 1234 +(fact 5) ; => 120 -(loop for i from 0 below 10 - collect i) +(loop :for x :across "abc" :collect x) +; => (#\a #\b #\c #\d) -; => (0 1 2 3 4 5 6 7 8 9) +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 6. Mutation -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- +;;; 6. Mutation +;;;----------------------------------------------------------------------------- -;; Use `setf' to assign a new value to an existing variable. This was -;; demonstrated earlier in the hash table example. +;;; Use SETF to assign a new value to an existing variable. This was +;;; demonstrated earlier in the hash table example. (let ((variable 10)) (setf variable 2)) - ; => 2 +; => 2 +;;; Good Lisp style is to minimize the use of destructive functions and to avoid +;;; mutation when reasonable. -;; Good Lisp style is to minimize destructive functions and to avoid -;; mutation when reasonable. -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 7. Classes and Objects -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;----------------------------------------------------------------------------- +;;; 7. Classes and objects +;;;----------------------------------------------------------------------------- -;; No more Animal classes, let's have Human-Powered Mechanical -;; Conveyances. +;;; No more animal classes. Let's have Human-Powered Mechanical +;;; Conveyances. (defclass human-powered-conveyance () ((velocity @@ -479,14 +541,16 @@ nil ; for false - and the empty list :initarg :average-efficiency)) (:documentation "A human powered conveyance")) -;; defclass, followed by name, followed by the superclass list, -;; followed by slot list, followed by optional qualities such as -;; :documentation. +;;; The arguments to DEFCLASS, in order are: +;;; 1. class name +;;; 2. superclass list +;;; 3. slot list +;;; 4. optional specifiers -;; When no superclass list is set, the empty list defaults to the -;; standard-object class. This *can* be changed, but not until you -;; know what you're doing. Look up the Art of the Metaobject Protocol -;; for more information. +;;; When no superclass list is set, the empty list defaults to the +;;; standard-object class. This *can* be changed, but not until you +;;; know what you're doing. Look up the Art of the Metaobject Protocol +;;; for more information. (defclass bicycle (human-powered-conveyance) ((wheel-size @@ -500,7 +564,7 @@ nil ; for false - and the empty list (defclass recumbent (bicycle) ((chain-type :accessor chain-type - :initarg :chain-type))) + :initarg :chain-type))) (defclass unicycle (human-powered-conveyance) nil) @@ -509,8 +573,7 @@ nil ; for false - and the empty list :accessor number-of-rowers :initarg :number-of-rowers))) - -;; Calling DESCRIBE on the human-powered-conveyance class in the REPL gives: +;;; Calling DESCRIBE on the HUMAN-POWERED-CONVEYANCE class in the REPL gives: (describe 'human-powered-conveyance) @@ -532,47 +595,42 @@ nil ; for false - and the empty list ; Readers: AVERAGE-EFFICIENCY ; Writers: (SETF AVERAGE-EFFICIENCY) -;; Note the reflective behavior available to you! Common Lisp is -;; designed to be an interactive system +;;; Note the reflective behavior available. CL was designed to be an +;;; interactive system -;; To define a method, let's find out what our circumference of the -;; bike wheel turns out to be using the equation: C = d * pi +;;; To define a method, let's find out what our circumference of the +;;; bike wheel turns out to be using the equation: C = d * pi (defmethod circumference ((object bicycle)) (* pi (wheel-size object))) -;; pi is defined in Lisp already for us! +;;; PI is defined as a built-in in CL -;; Let's suppose we find out that the efficiency value of the number -;; of rowers in a canoe is roughly logarithmic. This should probably be set -;; in the constructor/initializer. +;;; Let's suppose we find out that the efficiency value of the number +;;; of rowers in a canoe is roughly logarithmic. This should probably be set +;;; in the constructor/initializer. -;; Here's how to initialize your instance after Common Lisp gets done -;; constructing it: +;;; To initialize your instance after CL gets done constructing it: (defmethod initialize-instance :after ((object canoe) &rest args) (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) -;; Then to construct an instance and check the average efficiency... +;;; Then to construct an instance and check the average efficiency... (average-efficiency (make-instance 'canoe :number-of-rowers 15)) ; => 2.7725887 +;;;----------------------------------------------------------------------------- +;;; 8. Macros +;;;----------------------------------------------------------------------------- - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 8. Macros -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; Macros let you extend the syntax of the language - -;; Common Lisp doesn't come with a WHILE loop- let's add one. -;; If we obey our assembler instincts, we wind up with: +;;; Macros let you extend the syntax of the language. CL doesn't come +;;; with a WHILE loop, however, it's trivial to write one. If we obey our +;;; assembler instincts, we wind up with: (defmacro while (condition &body body) "While `condition` is true, `body` is executed. - `condition` is tested prior to each execution of `body`" (let ((block-name (gensym)) (done (gensym))) `(tagbody @@ -584,47 +642,47 @@ nil ; for false - and the empty list (go ,block-name) ,done))) -;; Let's look at the high-level version of this: - +;;; Let's look at the high-level version of this: (defmacro while (condition &body body) "While `condition` is true, `body` is executed. - `condition` is tested prior to each execution of `body`" `(loop while ,condition do (progn ,@body))) -;; However, with a modern compiler, this is not required; the LOOP -;; form compiles equally well and is easier to read. +;;; However, with a modern compiler, this is not required; the LOOP form +;;; compiles equally well and is easier to read. -;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator -;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting" -;; variables. @ interpolates lists. +;;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator +;;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting" +;;; variables. @ interpolates lists. -;; Gensym creates a unique symbol guaranteed to not exist elsewhere in -;; the system. This is because macros are expanded at compile time and -;; variables declared in the macro can collide with variables used in -;; regular code. +;;; GENSYM creates a unique symbol guaranteed to not exist elsewhere in +;;; the system. This is because macros are expanded at compile time and +;;; variables declared in the macro can collide with variables used in +;;; regular code. -;; See Practical Common Lisp for more information on macros. +;;; See Practical Common Lisp and On Lisp for more information on macros. ``` -## Further Reading +## Further reading + +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) -* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/) -* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) +## Extra information -## Extra Info +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) -* [CLiki](http://www.cliki.net/) -* [common-lisp.net](https://common-lisp.net/) -* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) -## Credits. +## Credits Lots of thanks to the Scheme people for rolling up a great starting point which could be easily moved to Common Lisp. -- cgit v1.2.3 From 7dd95d99f010f49c6d94499d13fdd6844dd35aec Mon Sep 17 00:00:00 2001 From: Rommel Martinez Date: Thu, 1 Mar 2018 21:45:50 +0800 Subject: [nix/en]: remove and update broken link --- nix.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nix.html.markdown b/nix.html.markdown index ba122a46..d078395a 100644 --- a/nix.html.markdown +++ b/nix.html.markdown @@ -3,6 +3,7 @@ language: nix filename: learn.nix contributors: - ["Chris Martin", "http://chris-martin.org/"] + - ["Rommel Martinez", "https://ebzzry.io"] --- Nix is a simple functional language developed for the @@ -356,5 +357,5 @@ with builtins; [ * [James Fisher - Nix by example - Part 1: The Nix expression language] (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) -* [Susan Potter - Nix Cookbook - Nix By Example] - (http://funops.co/nix-cookbook/nix-by-example/) +* [Rommel Martinez - A Gentle Introduction to the Nix Family] + (https://ebzzry.io/en/nix/#nix) -- cgit v1.2.3 From 9764b328d8e624456d93e0c411a29d339bc6c546 Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Sat, 3 Mar 2018 11:36:48 +0545 Subject: Fix #3074 --- html.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html.html.markdown b/html.html.markdown index 6516e5dd..04b9f501 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: learnhtml.html +filename: learnhtml.txt contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: -- cgit v1.2.3 From f4c124a9168b5864f9d6b211f9d8ece1c498468d Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Sat, 3 Mar 2018 12:21:26 +0545 Subject: Same filename with english version fix --- de-de/LOLCODE-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/LOLCODE-de.html.markdown b/de-de/LOLCODE-de.html.markdown index 155c5657..57eb0ff8 100644 --- a/de-de/LOLCODE-de.html.markdown +++ b/de-de/LOLCODE-de.html.markdown @@ -1,6 +1,6 @@ --- language: LOLCODE -filename: learnLOLCODE.lol +filename: learnLOLCODE-de.lol contributors: - ["abactel", "https://github.com/abactel"] translators: -- cgit v1.2.3 From caa8993076365c3e650e82a3c5c970dca25ed4c4 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 4 Mar 2018 19:48:44 -0800 Subject: Assorted fixes --- common-lisp.html.markdown | 2 +- de-de/markdown-de.html.markdown | 4 +-- fr-fr/markdown-fr.html.markdown | 2 +- markdown.html.markdown | 54 +++++++++++++++++++------------------- pt-br/common-lisp-pt.html.markdown | 2 +- visualbasic.html.markdown | 2 +- zh-cn/markdown-cn.html.markdown | 2 +- zh-cn/visualbasic-cn.html.markdown | 4 +-- 8 files changed, 36 insertions(+), 36 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 5f6975b6..e2cf62fb 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -16,7 +16,7 @@ popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book ab -```common_lisp +```common-lisp ;;;----------------------------------------------------------------------------- ;;; 0. Syntax diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown index 2c838660..cccf5e68 100644 --- a/de-de/markdown-de.html.markdown +++ b/de-de/markdown-de.html.markdown @@ -14,7 +14,7 @@ Syntax, in der sich Dokumente leicht schreiben *und* lesen lassen. Außerdem sollte Markdown sich leicht nach HTML (und in andere Formate) konvertieren lassen. -```markdown +```md You can create HTML elements `

` through `

` easily by prepending the text you want to be in that element by a number of hashes (#). -```markdown +```md # This is an

## This is an

### This is an

@@ -51,7 +51,7 @@ text you want to be in that element by a number of hashes (#). ``` Markdown also provides us with two alternative ways of indicating h1 and h2. -```markdown +```md This is an h1 ============= @@ -63,7 +63,7 @@ This is an h2 Text can be easily styled as italic or bold using markdown. -```markdown +```md *This text is in italics.* _And so is this text._ @@ -78,7 +78,7 @@ __And so is this text.__ In GitHub Flavored Markdown, which is used to render markdown files on GitHub, we also have strikethrough: -```markdown +```md ~~This text is rendered with strikethrough.~~ ``` ## Paragraphs @@ -86,7 +86,7 @@ GitHub, we also have strikethrough: Paragraphs are a one or multiple adjacent lines of text separated by one or multiple blank lines. -```markdown +```md This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. @@ -99,7 +99,7 @@ I'm in paragraph three! Should you ever want to insert an HTML `
` tag, you can end a paragraph with two or more spaces and then begin a new paragraph. -```markdown +```md I end with two spaces (highlight me to see them). There's a
above me! @@ -107,7 +107,7 @@ There's a
above me! Block quotes are easy and done with the > character. -```markdown +```md > This is a block quote. You can either > manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. > It doesn't make a difference so long as they start with a `>`. @@ -121,7 +121,7 @@ Block quotes are easy and done with the > character. ## Lists Unordered lists can be made using asterisks, pluses, or hyphens. -```markdown +```md * Item * Item * Another item @@ -141,7 +141,7 @@ or Ordered lists are done with a number followed by a period. -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -150,7 +150,7 @@ Ordered lists are done with a number followed by a period. You don't even have to label the items correctly and Markdown will still render the numbers in order, but this may not be a good idea. -```markdown +```md 1. Item one 1. Item two 1. Item three @@ -159,7 +159,7 @@ render the numbers in order, but this may not be a good idea. You can also use sublists -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -170,7 +170,7 @@ You can also use sublists There are even task lists. This creates HTML checkboxes. -```markdown +```md Boxes below without the 'x' are unchecked HTML checkboxes. - [ ] First task to complete. - [ ] Second task that needs done @@ -183,7 +183,7 @@ This checkbox below will be a checked HTML checkbox. You can indicate a code block (which uses the `` element) by indenting a line with four spaces or a tab. -```markdown +```md This is code So is this ``` @@ -191,7 +191,7 @@ a line with four spaces or a tab. You can also re-tab (or add an additional four spaces) for indentation inside your code -```markdown +```md my_array.each do |item| puts item end @@ -199,7 +199,7 @@ inside your code Inline code can be created using the backtick character ` -```markdown +```md John didn't even know what the `go_to()` function did! ``` @@ -220,7 +220,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. -```markdown +```md *** --- - - - @@ -232,17 +232,17 @@ hyphens, with or without spaces. One of the best things about markdown is how easy it is to make links. Put the text to display in hard brackets [] followed by the url in parentheses () -```markdown +```md [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. -```markdown +```md [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. -```markdown +```md [Go to music](/music/). ``` @@ -269,7 +269,7 @@ But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! -```markdown +```md ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` @@ -281,20 +281,20 @@ And reference style works as expected. ## Miscellany ### Auto-links -```markdown +```md is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails -```markdown +```md ``` ### Escaping characters -```markdown +```md I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. ``` @@ -304,7 +304,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. In GitHub Flavored Markdown, you can use a `` tag to represent keyboard keys. -```markdown +```md Your computer crashed? Try sending a Ctrl+Alt+Del ``` @@ -313,7 +313,7 @@ Your computer crashed? Try sending a Tables are only available in GitHub Flavored Markdown and are slightly cumbersome, but if you really want it: -```markdown +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | @@ -321,7 +321,7 @@ cumbersome, but if you really want it: ``` or, for the same results -```markdown +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index 03a7c15c..c3381824 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -19,7 +19,7 @@ Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). -```common_lisp +```common-lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. Sintaxe diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index cbeb36b5..041641d3 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnvisualbasic.vb --- -```vb +```vbnet Module Module1 Sub Main() diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 87ed46ad..e9a8aeb2 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -13,7 +13,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 欢迎您多多反馈以及分支和请求合并。 -```markdown +```md ClassName InstanceName +SomeRandomClass myObject // then instantiate later +//or +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor + +// Processing comes up with more collections (eg. - Dictionaries and Lists) by default, +// for the simplicity sake, I will leave them out of discussion here. + +/* ----------- + Maths + ------------ +*/ +// Arithmetic +1 + 1 // 2 +2 - 1 // 0 +2 * 3 // 6 +3 / 2 // 1 +3.0 / 2 // 1.5 +3.0 % 2 // 1.0 + +// Processing also comes with a set of functions that simplify mathematical operations. +float f = sq(3); // f = 9.0 +float p = pow(3, 3); // p = 27.0 +int a = abs(-13) // a = 13 +int r1 = round(3.1); // r1 = 3 +int r2 = round(3.7); // r2 = 4 +float sr = sqrt(25); // sr = 5.0 + +// Vectors +// Processing provides an easy way to implement vectors in its environment using PVector class. +// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) + +// Trigonometry +// Processing also supports trigonometric operations by supplying a set of functions. +// sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. +// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +float one = sin(PI/2); // one = 1.0 +// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From dd92983e8b2e85606c01c252e888c96fb43bb865 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:17:25 +0630 Subject: 2/7/18 11:17AM --- processing.html.markdown | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 83f774ee..f352b9c4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -108,7 +108,7 @@ ArrayList intArrayList = new ArrayList(); // Format --> ClassName InstanceName SomeRandomClass myObject // then instantiate later //or -SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. @@ -135,15 +135,18 @@ float sr = sqrt(25); // sr = 5.0 // Vectors // Processing provides an easy way to implement vectors in its environment using PVector class. -// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. -// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) +// It can describe a two or three dimensional vector and +// comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. +// (https://processing.org/reference/PVector.html) // Trigonometry // Processing also supports trigonometric operations by supplying a set of functions. // sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. -// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +// However, those functions take angle in radians as the parameter so it has to be converted beforehand. float one = sin(PI/2); // one = 1.0 -// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... +// As you may have noticed, there exists a set of constants for trigonometric uses; +// PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From e7603786a8fcb88508b1298053c2a78ad65c9ed7 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:50:32 +0630 Subject: 2/7/18 11:50AM --- processing.html.markdown | 73 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index f352b9c4..91d75cb4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -54,9 +54,9 @@ void draw() { // Now that we know how to write the working script and how to run it, // we will proceed to explore what data types and collections are supported in Processing. -/* ----------------------- - Datatypes & collections - ------------------------ +/* ------------------------ + Datatypes & collections + ------------------------ */ // According to Processing References, Processing supports 8 primitive datatypes as follows. @@ -113,10 +113,11 @@ SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. -/* ----------- - Maths - ------------ +/* ------------ + Maths + ------------ */ + // Arithmetic 1 + 1 // 2 2 - 1 // 0 @@ -148,6 +149,66 @@ float one = sin(PI/2); // one = 1.0 // As you may have noticed, there exists a set of constants for trigonometric uses; // PI, HALF_PI, QUARTER_PI and so on... +/* ------------- + Control Flow + ------------- +*/ + +// Conditional Statements +// If Statements - The same syntax as if statements in Java. +if (author.getAppearance().equals("hot")) { + print("Narcissism at its best!"); +} else { + // You can check for other conditions here. + print("Something is really wrong here!"); +} +// A shortcut for if-else statements can also be used. +int i = 3; +String value = (i > 5) ? "Big" : "Small"; // "Small" + +// Switch-case structure can be used to check multiple conditions more concisely. +int value = 2; +switch(value) { + case 0: + print("Nought!"); // This doesn't get executed. + break; // Jumps to the next statement + case 1: + print("Getting there..."); // This again doesn't get executed. + break; + case 2: + print("Bravo!"); // This line gets executed. + break; + default: + print("Not found!"); // This line gets executed if our value was some other value. + break; +} + +// Iterative statements +// For Statements - Again, the same syntax as in Java +for(int i = 0; i < 5; i ++){ + print(i); // prints from 0 to 4 +} + +// While Statements - Again, nothing new if you are familiar with Java syntax. +int j = 3; +while(j > 0) { + print(j); + j--; // This is important to prevent from the code running indefinitely. +} + +// loop()| noLoop() | redraw() | exit() +// These are more of Processing-specific functions to configure program flow. +loop(); // allows the draw() method to run forever while +noLoop(); // only allows it to run once. +redraw(); // runs the draw() method once more. +exit(); // This stops the program. It is useful for programs with draw() running continuously. +``` +Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. + +```processing + + + ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of -- cgit v1.2.3 From 90ee44541ef66d4f8d0507c1b2080cf409078064 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 12:15:25 +0630 Subject: 2/7/18 12:15PM --- processing.html.markdown | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 91d75cb4..6423baa7 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -203,9 +203,44 @@ noLoop(); // only allows it to run once. redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` +## Drawing with Processing Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. ```processing +/* ------ + Shapes + ------ +*/ + +// 2D Shapes + +// Point +point(x, y); // In 2D space +point(x, y, z); // In 3D space +// Draws a point in the coordinate space. + +// Line +line(x1, y1, x2, y2); // In 2D space +line(x1, y1, z1, x2, y2, z2); // In 3D space +// Draws a line connecting two points defined by (x1, y1) and (x2, y2) + +// Rectangle +rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners +rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +// Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. + +// Quad +quad(x,y,x2,y2,x3,y3,x4,y4) +// Draws a quadrilateral with parameters defining coordinates of each corner point. + +// Arc; +arc(x, y, width, height, start, stop, [mode]); +// While the first four parameters are self-explanatory, +// start and end defined the angles the arc starts and ends (in radians). +// Optional parameter [mode] defines the filling; +// PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes + + -- cgit v1.2.3 From fa305fc98763d4c2cd204cfe9b5f0bc59daefc14 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 14:55:22 +0630 Subject: 2/7/18 2:55PM --- processing.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 6423baa7..88c7c289 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -40,6 +40,8 @@ void setup() { // Normally, we put all the static codes inside the setup() method as the name suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. +background(color); // setting the background colour +size(width,height,[renderer]); // setting the canvas size with optional parameter defining renderer // You will see more of them throughout this document. // If you want to run the codes indefinitely, it has to be placed in draw() method. @@ -204,7 +206,7 @@ redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` ## Drawing with Processing -Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. +Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing /* ------ @@ -222,27 +224,99 @@ point(x, y, z); // In 3D space // Line line(x1, y1, x2, y2); // In 2D space line(x1, y1, z1, x2, y2, z2); // In 3D space -// Draws a line connecting two points defined by (x1, y1) and (x2, y2) +// Draws a line connecting two points defined by (x1, y1) and (x2, y2). + +// Triangle +triangle(x1, y1, x2, y2, x3, y3); +// Draws a triangle connecting three points defined by coordinate paramters. // Rectangle rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners -rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +rect(a, b, c, d, [tl, tr, br, bl]); // With optional set of parameters defining radius of each corner // Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. // Quad -quad(x,y,x2,y2,x3,y3,x4,y4) +quad(x, y, x2, y2, x3, y3, x4, y4); // Draws a quadrilateral with parameters defining coordinates of each corner point. -// Arc; +// Ellipse +ellipse(x, y, width, height); +// Draws an eclipse at point {x, y} with width and height specified. + +// Arc arc(x, y, width, height, start, stop, [mode]); // While the first four parameters are self-explanatory, // start and end defined the angles the arc starts and ends (in radians). // Optional parameter [mode] defines the filling; // PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes +// Curves +// Processing provides two implementation of curves; using curve() and bezier(). +// Since I plan to keep this simple I won't be discussing any further details. +// However, if you want to implement it in your sketch, here are the references: +// (https://processing.org/reference/curve_.html)(https://processing.org/reference/bezier_.html) + +// 3D Shapes + +// 3D space can be configured by setting "P3D" to the renderer parameter in size() method. +size(width, height, P3D); +// In 3D space, you will have to translate to the particular coordinate to render the 3D shapes. +// Box +box(size); // Cube with same length defined by size +box(w, h, d); // Box with width, height and depth separately defined +// Sphere +sphere(radius); // Its size is defined using the radius parameter +// Mechanism behind rendering spheres is implemented by tessellating triangles. +// That said, how much detail being rendered is controlled by function sphereDetail(res) +// More information here: (https://processing.org/reference/sphereDetail_.html) + +// Irregular Shapes +// What if you wanted to draw something that's not made available by Processing's functions? +// You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. +// More information here: (https://processing.org/reference/beginShape_.html) + +/* --------------- + Transformations + --------------- +*/ + +// Transformations are particularly useful to keep track of the coordinate space +// and the vertices of the shapes you have drawn. +// Particularly, matrix stack methods; pushMatrix(), popMatrix() and translate(x,y) +pushMatrix(); // Saves the current coordinate system to the stack +// ... apply all the transformations here ... +popMatrix(); // Restores the saved coordinate system +// Using them, the coordinate system can be preserved and visualized without causing any conflicts. + +// Translate +translate(x, y); // Translates to point{x, y} i.e. - setting origin to that point +translate(x, y, z); // 3D counterpart of the function + +// Rotate +rotate(angle); // Rotate the amount specified by the angle parameter +// It has 3 3D counterparts to perform rotation, each for every dimension, +// namely: rotateX(angle), rotateY(angle), rotateZ(angle) + +// Scale +scale(s); // Scale the coordinate system by either expanding or contracting it. + +/* -------------------- + Styling and Textures + -------------------- +*/ + + + +/* ------- + Imports + ------- +*/ +// The power of Processing can be further visualized when we import libraries and packages into our sketches. +// Import statement can be written as below at the top of the source code. +import processing.something.*; ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From 66c6297749cbff4272a12b852741c365bec9149a Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 15:18:30 +0630 Subject: 2/7/18 3:18PM --- processing.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 88c7c289..e3d83f80 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -209,6 +209,7 @@ exit(); // This stops the program. It is useful for programs with draw() running Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing + /* ------ Shapes ------ @@ -276,6 +277,7 @@ sphere(radius); // Its size is defined using the radius parameter // What if you wanted to draw something that's not made available by Processing's functions? // You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. // More information here: (https://processing.org/reference/beginShape_.html) +// You can also use custom made shapes using PShape class.(https://processing.org/reference/PShape.html) /* --------------- Transformations @@ -307,7 +309,30 @@ scale(s); // Scale the coordinate system by either expanding or contracting it. -------------------- */ +// Colours +// As I have discussed earlier, the background colour can be configured using background() function. +// You can define a color object beforehand and then pass it to the function as an argument. +color c = color(255, 255, 255); // WHITE! +// By default, Processing uses RGB colour scheme but it can be configured to HSB using colorMode(). +// Read here: (https://processing.org/reference/colorMode_.html) +background(color); // By now, the background colour should be white. +// You can use fill() function to select the colour for filling the shapes. +// It has to be configured before you start drawing shapes so the colours gets applied. +fill(color(0, 0, 0)); +// If you just want to colour the outlines of the shapes then you can use stroke() function. +stroke(255, 255, 255, 200); // stroke colour set to yellow with transparency set to a lower value. + +// Images +// Processing can render images and use them in several ways. Mostly stored as PImage datatype. +filter(shader); // Processing supports several filter functions for image manipulation. +texture(image); // PImage can be passed into arguments for texture-mapping the shapes. +``` +If you want to take things further, there are more things Processing is powered for. Rendering models, shaders and whatnot. +There's too much to cover in a short documentation, so I will leave them out here. Shoud you be interested, please check out the references. +```processing +// Before we move on, I will touch a little bit more on how to import libraries +// so you can extend Processing's functionality to another horizon. /* ------- Imports -- cgit v1.2.3 From fb78575d55b64860d781e651b3b958d8ba04bdf4 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 16:15:09 +0630 Subject: 2/7/18 4:14PM --- processing.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/processing.html.markdown b/processing.html.markdown index e3d83f80..84c2dee1 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -344,11 +344,76 @@ There's too much to cover in a short documentation, so I will leave them out her import processing.something.*; ``` +## DTC? + +Down To Code? Let's get our hands dirty! + +Let us see an example from openprocessing to visualize how much Processing is capable of within few lines of code. +Copy the code below into your Processing IDE and see the magic. + +```processing + +// Disclaimer: I did not write this program since I currently am occupied with internship and +// this sketch is adapted from openprocessing since it shows something cool with simple codes. +// Retrieved from: (https://www.openprocessing.org/sketch/559769) + +float theta; +float a; +float col; +float num; + +void setup() { + size(600,600); +} + +void draw() { + background(#F2F2F2); + translate(width/2, height/2); + theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6); + + float num=6; + for (int i=0; i30) { + pushMatrix(); + translate(0, -30); + rotate(theta); + branch(len); + popMatrix(); + + pushMatrix(); + translate(0, -30); + rotate(-theta); + branch(len); + popMatrix(); + + } +} + +``` + Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of the program flow. However, that does not apply when you introduce external libraries, packages and even your own classes. -(Trust me! Processing projects can get really large) +(Trust me! Processing projects can get real humongous...) ## What's Next? -- cgit v1.2.3 From c2e2fca15ce0d0398b341f3e4e8e0fcbc9987a65 Mon Sep 17 00:00:00 2001 From: luc4leone Date: Mon, 2 Jul 2018 14:15:02 +0200 Subject: Delete broken link to Eloquent Javascript - The Annotated Version by Gordon Zhu --- javascript.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index e7066291..52084e93 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -600,10 +600,6 @@ of the language. [Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal -[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great -derivative of Eloquent Javascript with extra explanations and clarifications for -some of the more complicated examples. - [Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. @@ -624,6 +620,5 @@ Mozilla Developer Network. [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: http://eloquentjavascript.net/ -[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version [10]: http://jstherightway.org/ [11]: https://javascript.info/ -- cgit v1.2.3 From e42e4b9b22d6d1e267d5c5931dd40f050401ba44 Mon Sep 17 00:00:00 2001 From: Fake4d Date: Tue, 3 Jul 2018 16:16:17 +0200 Subject: Update bash-de.html.markdown Variable was not initialised in this stage for this loop - Removed the $ --- de-de/bash-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 7928b136..7a0db157 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -180,7 +180,7 @@ esac # 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: # Der Inhalt von $Variable wird dreimal ausgedruckt. -for $Variable in {1..3} +for Variable in {1..3} do echo "$Variable" done -- cgit v1.2.3 From 626af76c4d38a705f35e0c07b877404c03fa6b1d Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 17:08:23 +0800 Subject: create learnawk-cn.awk --- zh-cn/awk-cn.html.markdown | 361 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 zh-cn/awk-cn.html.markdown diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown new file mode 100644 index 00000000..fcd17b4f --- /dev/null +++ b/zh-cn/awk-cn.html.markdown @@ -0,0 +1,361 @@ +--- +language: awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Tian Zhipeng", "https://github.com/tianzhipeng-git"] +filename: learnawk-cn.awk +lang: zh-cn +--- + +AWK is a standard tool on every POSIX-compliant UNIX system. It's like a +stripped-down Perl, perfect for text-processing tasks and other scripting +needs. It has a C-like syntax, but without semicolons, manual memory +management, or static typing. It excels at text processing. You can call to it +from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always +count on it, whereas Perl's future is in question. AWK is also easier to read +than Perl. For simple text-processing scripts, particularly ones that read +files line by line and split on delimiters, AWK is probably the right tool for +the job. + +```awk +#!/usr/bin/awk -f + +# Comments are like this + +# AWK programs consist of a collection of patterns and actions. The most +# important pattern is called BEGIN. Actions go into brace blocks. +BEGIN { + + # BEGIN will run at the beginning of the program. It's where you put all + # the preliminary set-up code, before you process any text files. If you + # have no text files, then think of BEGIN as the main entry point. + + # Variables are global. Just set them or use them, no need to declare.. + count = 0 + + # Operators just like in C and friends + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 # integer division + e = count % 1 # modulus + f = count ^ 1 # exponentiation + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementing and decrementing by one + a++ + b-- + + # As a prefix operator, it returns the incremented value + ++a + --b + + # Notice, also, no punctuation such as semicolons to terminate statements + + # Control statements + if (count == 0) + print "Starting with count of 0" + else + print "Huh?" + + # Or you could use the ternary operator + print (count == 0) ? "Starting with count of 0" : "Huh?" + + # Blocks consisting of multiple lines use braces + while (a < 10) { + print "String concatenation is done" " with a series" " of" + " space-separated strings" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Good ol' for loop" + + # As for comparisons, they're the standards: + a < b # Less than + a <= b # Less than or equal + a != b # Not equal + a == b # Equal + a > b # Greater than + a >= b # Greater than or equal + + # Logical operators as well + a && b # AND + a || b # OR + + # In addition, there's the super useful regular expression match + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Arrays + arr[0] = "foo" + arr[1] = "bar" + # Unfortunately, there is no other way to initialize an array. Ya just + # gotta chug through every value line by line like that. + + # You also have associative arrays + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # And multi-dimensional arrays, with some limitations I won't mention here + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # You can test for array membership + if ("foo" in assoc) + print "Fooey!" + + # You can also use the 'in' operator to traverse the keys of an array + for (key in assoc) + print assoc[key] + + # The command line is in a special array called ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # You can remove elements of an array + # This is particularly useful to prevent AWK from assuming the arguments + # are files for it to process + delete ARGV[1] + + # The number of command line arguments is in a variable called ARGC + print ARGC + + # AWK has several built-in functions. They fall into three categories. I'll + # demonstrate each of them in their own functions, defined later. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Here's how you define a function +function arithmetic_functions(a, b, c, d) { + + # Probably the most annoying part of AWK is that there are no local + # variables. Everything is global. For short scripts, this is fine, even + # useful, but for longer scripts, this can be a problem. + + # There is a work-around (ahem, hack). Function arguments are local to the + # function, and AWK allows you to define more function arguments than it + # needs. So just stick local variable in the function declaration, like I + # did above. As a convention, stick in some extra whitespace to distinguish + # between actual function parameters and local variables. In this example, + # a, b, and c are actual parameters, while d is merely a local variable. + + # Now, to demonstrate the arithmetic functions + + # Most AWK implementations have some standard trig functions + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arc tangent of b / a + + # And logarithmic stuff + localvar = exp(a) + localvar = log(a) + + # Square root + localvar = sqrt(a) + + # Truncate floating point to integer + localvar = int(5.34) # localvar => 5 + + # Random numbers + srand() # Supply a seed as an argument. By default, it uses the time of day + localvar = rand() # Random number between 0 and 1. + + # Here's how to return a value + return localvar +} + +function string_functions( localvar, arr) { + + # AWK, being a string-processing language, has several string-related + # functions, many of which rely heavily on regular expressions. + + # Search and replace, first instance (sub) or all instances (gsub) + # Both return number of matches replaced + localvar = "fooooobar" + sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" + gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + + # Search for a string that matches a regular expression + # index() does the same thing, but doesn't allow a regular expression + match(localvar, "t") # => 4, since the 't' is the fourth character + + # Split on a delimiter + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Other useful stuff + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # You've already seen print + print "Hello world" + + # There's also printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # AWK doesn't have file handles, per se. It will automatically open a file + # handle for you when you use something that needs one. The string you used + # for this can be treated as a file handle, for purposes of I/O. This makes + # it feel sort of like shell scripting: + + print "foobar" >"/tmp/foobar.txt" + + # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + close("/tmp/foobar.txt") + + # Here's how you run something in the shell + system("echo foobar") # => prints foobar + + # Reads a line from standard input and stores in localvar + getline localvar + + # Reads a line from a pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Reads a line from a file and stores in localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# As I said at the beginning, AWK programs consist of a collection of patterns +# and actions. You've already seen the all-important BEGIN pattern. Other +# patterns are used only if you're processing lines from files or standard +# input. +# +# When you pass arguments to AWK, they are treated as file names to process. +# It will process them all, in order. Think of it like an implicit for loop, +# iterating over the lines in these files. these patterns and actions are like +# switch statements inside the loop. + +/^fo+bar$/ { + + # This action will execute for every line that matches the regular + # expression, /^fo+bar$/, and will be skipped for any line that fails to + # match it. Let's just print the line: + + print + + # Whoa, no argument! That's because print has a default argument: $0. + # $0 is the name of the current line being processed. It is created + # automatically for you. + + # You can probably guess there are other $ variables. Every line is + # implicitly split before every action is called, much like the shell + # does. And, like the shell, each field can be access with a dollar sign + + # This will print the second and fourth fields in the line + print $2, $4 + + # AWK automatically defines many other variables to help you inspect and + # process each line. The most important one is NF + + # Prints the number of fields on this line + print NF + + # Print the last field on this line + print $NF +} + +# Every pattern is actually a true/false test. The regular expression in the +# last pattern is also a true/false test, but part of it was hidden. If you +# don't give it a string to test, it will assume $0, the line that it's +# currently processing. Thus, the complete version of it is this: + +$0 ~ /^fo+bar$/ { + print "Equivalent to the last pattern" +} + +a > 0 { + # This will execute once for each line, as long as a is positive +} + +# You get the idea. Processing text files, reading in a line at a time, and +# doing something with it, particularly splitting on a delimiter, is so common +# in UNIX that AWK is a scripting language that does all of it for you, without +# you needing to ask. All you have to do is write the patterns and actions +# based on what you expect of the input, and what you want to do with it. + +# Here's a quick example of a simple script, the sort of thing AWK is perfect +# for. It will read a name from standard input and then will print the average +# age of everyone with that first name. Let's say you supply as an argument the +# name of a this data file: +# +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Here's the script: + +BEGIN { + + # First, ask the user for the name + print "What name would you like the average age for?" + + # Get a line from standard input, not from files on the command line + getline name <"/dev/stdin" +} + +# Now, match every line whose first field is the given name +$1 == name { + + # Inside here, we have access to a number of useful variables, already + # pre-loaded for us: + # $0 is the entire line + # $3 is the third field, the age, which is what we're interested in here + # NF is the number of fields, which should be 3 + # NR is the number of records (lines) seen so far + # FILENAME is the name of the file being processed + # FS is the field separator being used, which is " " here + # ...etc. There are plenty more, documented in the man page. + + # Keep track of a running total and how many lines matched + sum += $3 + nlines++ +} + +# Another special pattern is called END. It will run after processing all the +# text files. Unlike BEGIN, it will only run if you've given it input to +# process. It will run after all the files have been read and processed +# according to the rules and actions you've provided. The purpose of it is +# usually to output some kind of final report, or do something with the +# aggregate of the data you've accumulated over the course of the script. + +END { + if (nlines) + print "The average age for " name " is " sum / nlines +} + +``` +Further Reading: + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. -- cgit v1.2.3 From 72ab89ea9a2fb41ca685248e6cac89c5e153d16b Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 21:56:04 +0800 Subject: translate awk to zh-cn --- zh-cn/awk-cn.html.markdown | 277 ++++++++++++++++++++------------------------- 1 file changed, 120 insertions(+), 157 deletions(-) diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index fcd17b4f..1fafa559 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -8,41 +8,35 @@ filename: learnawk-cn.awk lang: zh-cn --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read -than Perl. For simple text-processing scripts, particularly ones that read -files line by line and split on delimiters, AWK is probably the right tool for -the job. +AWK是POSIX兼容的UNIX系统中的标准工具. 它像简化版的Perl, 非常适用于文本处理任务和其他脚本类需求. +它有着C风格的语法, 但是没有分号, 没有手动内存管理, 没有静态类型. +他擅长于文本处理, 你可以通过shell脚本调用AWK, 也可以用作独立的脚本语言. + +为什么使用AWK而不是Perl, 大概是因为AWK是UNIX的一部分, 你总能依靠它, 而Perl已经前途未卜了. +AWK比Perl更易读. 对于简单的文本处理脚本, 特别是按行读取文件, 按分隔符分隔处理, AWK极可能是正确的工具. ```awk #!/usr/bin/awk -f -# Comments are like this +# 注释使用井号 -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. +# AWK程序由一系列 模式(patterns) 和 动作(actions) 组成. +# 最重要的模式叫做 BEGIN. 动作由大括号包围. BEGIN { - # BEGIN will run at the beginning of the program. It's where you put all - # the preliminary set-up code, before you process any text files. If you - # have no text files, then think of BEGIN as the main entry point. + # BEGIN在程序最开始运行. 在这里放一些在真正处理文件之前的准备和setup的代码. + # 如果没有文本文件要处理, 那就把BEGIN作为程序的主入口吧. - # Variables are global. Just set them or use them, no need to declare.. + # 变量是全局的. 直接赋值使用即可, 无需声明. count = 0 - # Operators just like in C and friends + # 运算符和C语言系一样 a = count + 1 b = count - 1 c = count * 1 - d = count / 1 # integer division - e = count % 1 # modulus - f = count ^ 1 # exponentiation + d = count / 1 # 整数除法 + e = count % 1 # 取余 + f = count ^ 1 # 取幂 a += 1 b -= 1 @@ -51,26 +45,26 @@ BEGIN { e %= 1 f ^= 1 - # Incrementing and decrementing by one + # 自增1, 自减1 a++ b-- - # As a prefix operator, it returns the incremented value + # 前置运算, 返回增加之后的值 ++a --b - # Notice, also, no punctuation such as semicolons to terminate statements + # 注意, 不需要分号之类的标点来分隔语句 - # Control statements + # 控制语句 if (count == 0) print "Starting with count of 0" else print "Huh?" - # Or you could use the ternary operator + # 或者三目运算符 print (count == 0) ? "Starting with count of 0" : "Huh?" - # Blocks consisting of multiple lines use braces + # 多行的代码块用大括号包围 while (a < 10) { print "String concatenation is done" " with a series" " of" " space-separated strings" @@ -82,126 +76,118 @@ BEGIN { for (i = 0; i < 10; i++) print "Good ol' for loop" - # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal + # 标准的比较运算符 + a < b # 小于 + a <= b # 小于或等于 + a != b # 不等于 + a == b # 等于 + a > b # 大于 + a >= b # 大于或等于 - # Logical operators as well - a && b # AND - a || b # OR + # 也有逻辑运算符 + a && b # 且 + a || b # 或 - # In addition, there's the super useful regular expression match + # 并且有超实用的正则表达式匹配 if ("foo" ~ "^fo+$") print "Fooey!" if ("boo" !~ "^fo+$") print "Boo!" - # Arrays + # 数组 arr[0] = "foo" arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. + # 不幸的是, 没有其他方式初始化数组. 必须像这样一行一行的赋值. - # You also have associative arrays + # 关联数组, 类似map或dict的用法. assoc["foo"] = "bar" assoc["bar"] = "baz" - # And multi-dimensional arrays, with some limitations I won't mention here + # 多维数组. 但是有一些局限性这里不提了. multidim[0,0] = "foo" multidim[0,1] = "bar" multidim[1,0] = "baz" multidim[1,1] = "boo" - # You can test for array membership + # 可以检测数组包含关系 if ("foo" in assoc) print "Fooey!" - # You can also use the 'in' operator to traverse the keys of an array + # 可以使用in遍历数组 for (key in assoc) print assoc[key] - # The command line is in a special array called ARGV + # 命令行参数是一个叫ARGV的数组 for (argnum in ARGV) print ARGV[argnum] - # You can remove elements of an array - # This is particularly useful to prevent AWK from assuming the arguments - # are files for it to process + # 可以从数组中移除元素 + # 在 防止awk把文件参数当做数据来处理 时delete功能很有用. delete ARGV[1] - # The number of command line arguments is in a variable called ARGC + # 命令行参数的个数是一个叫ARGC的变量 print ARGC - # AWK has several built-in functions. They fall into three categories. I'll - # demonstrate each of them in their own functions, defined later. + # AWK有很多内置函数, 分为三类, 会在接下来定义的各个函数中介绍. return_value = arithmetic_functions(a, b, c) string_functions() io_functions() } -# Here's how you define a function +# 定义函数 function arithmetic_functions(a, b, c, d) { - # Probably the most annoying part of AWK is that there are no local - # variables. Everything is global. For short scripts, this is fine, even - # useful, but for longer scripts, this can be a problem. + # 或许AWK最让人恼火的地方是没有局部变量, 所有东西都是全局的, + # 对于短的脚本还好, 对于长一些的就会成问题. - # There is a work-around (ahem, hack). Function arguments are local to the - # function, and AWK allows you to define more function arguments than it - # needs. So just stick local variable in the function declaration, like I - # did above. As a convention, stick in some extra whitespace to distinguish - # between actual function parameters and local variables. In this example, - # a, b, and c are actual parameters, while d is merely a local variable. + # 这里有一个技巧, 函数参数是对函数局部可见的, 并且AWK允许定义多余的参数, + # 因此可以像上面那样把局部变量插入到函数声明中. + # 为了方便区分普通参数(a,b,c)和局部变量(d), 可以多键入一些空格. - # Now, to demonstrate the arithmetic functions + # 现在介绍数学类函数 - # Most AWK implementations have some standard trig functions + # 多数AWK实现中包含标准的三角函数 localvar = sin(a) localvar = cos(a) localvar = atan2(a, b) # arc tangent of b / a - # And logarithmic stuff + # 对数 localvar = exp(a) localvar = log(a) - # Square root + # 平方根 localvar = sqrt(a) - # Truncate floating point to integer + # 浮点型转为整型 localvar = int(5.34) # localvar => 5 - # Random numbers - srand() # Supply a seed as an argument. By default, it uses the time of day - localvar = rand() # Random number between 0 and 1. + # 随机数 + srand() # 接受随机种子作为参数, 默认使用当天的时间 + localvar = rand() # 0到1之间随机 - # Here's how to return a value + # 函数返回 return localvar } function string_functions( localvar, arr) { - # AWK, being a string-processing language, has several string-related - # functions, many of which rely heavily on regular expressions. + # AWK, 作为字符处理语言, 有很多字符串相关函数, 其中大多数都严重依赖正则表达式. - # Search and replace, first instance (sub) or all instances (gsub) - # Both return number of matches replaced + # 搜索并替换, 第一个出现的 (sub) or 所有的 (gsub) + # 都是返回替换的个数 localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" - # Search for a string that matches a regular expression - # index() does the same thing, but doesn't allow a regular expression - match(localvar, "t") # => 4, since the 't' is the fourth character + # 搜索匹配正则的字符串 + # index() 也是搜索, 不支持正则 + match(localvar, "t") # => 4, 't'在4号位置. (译者注: awk是1开始计数的,不是常见的0-base) - # Split on a delimiter + # 按分隔符分隔 split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] - # Other useful stuff + # 其他有用的函数 sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" substr("foobar", 2, 3) # => "oob" substr("foobar", 4) # => "bar" @@ -212,99 +198,81 @@ function string_functions( localvar, arr) { function io_functions( localvar) { - # You've already seen print + # 你已经见过的print函数 print "Hello world" - # There's also printf + # 也有printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK doesn't have file handles, per se. It will automatically open a file - # handle for you when you use something that needs one. The string you used - # for this can be treated as a file handle, for purposes of I/O. This makes - # it feel sort of like shell scripting: - + # AWK本身没有文件句柄, 当你使用需要文件的东西时会自动打开文件, 做文件I/O时, 字符串就是打开的文件句柄. + # 这看起来像Shell print "foobar" >"/tmp/foobar.txt" - # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + # 现在"/tmp/foobar.txt"字符串是一个文件句柄, 你可以关闭它 close("/tmp/foobar.txt") - # Here's how you run something in the shell + # 在shell里运行一些东西 system("echo foobar") # => prints foobar - # Reads a line from standard input and stores in localvar + # 从标准输入中读一行, 并存储在localvar中 getline localvar - # Reads a line from a pipe + # 从管道中读一行, 并存储在localvar中 "echo foobar" | getline localvar # localvar => "foobar" close("echo foobar") - # Reads a line from a file and stores in localvar + # 从文件中读一行, 并存储在localvar中 getline localvar <"/tmp/foobar.txt" close("/tmp/foobar.txt") } -# As I said at the beginning, AWK programs consist of a collection of patterns -# and actions. You've already seen the all-important BEGIN pattern. Other -# patterns are used only if you're processing lines from files or standard -# input. -# -# When you pass arguments to AWK, they are treated as file names to process. -# It will process them all, in order. Think of it like an implicit for loop, -# iterating over the lines in these files. these patterns and actions are like -# switch statements inside the loop. +# 正如开头所说, AWK程序由一系列模式和动作组成. 你已经看见了重要的BEGIN pattern, +# 其他的pattern在你需要处理来自文件或标准输入的的数据行时才用到. +# +# 当你给AWK程序传参数时, 他们会被视为要处理文件的文件名, 按顺序全部会处理. +# 可以把这个过程看做一个隐式的循环, 遍历这些文件中的所有行. +# 然后这些模式和动作就是这个循环里的switch语句一样 /^fo+bar$/ { - # This action will execute for every line that matches the regular - # expression, /^fo+bar$/, and will be skipped for any line that fails to - # match it. Let's just print the line: - + # 这个动作会在匹配这个正则(/^fo+bar$/)的每一行上执行. 不匹配的则会跳过. + # 先让我们打印它: print - # Whoa, no argument! That's because print has a default argument: $0. - # $0 is the name of the current line being processed. It is created - # automatically for you. + # 哦, 没有参数, 那是因为print有一个默认参数 $0. + # $0 是当前正在处理的行, 自动被创建好了. - # You can probably guess there are other $ variables. Every line is - # implicitly split before every action is called, much like the shell - # does. And, like the shell, each field can be access with a dollar sign + # 你可能猜到有其他的$变量了. + # 每一行在动作执行前会被分隔符分隔. 像shell中一样, 每个字段都可以用$符访问 - # This will print the second and fourth fields in the line + # 这个会打印这行的第2和第4个字段 print $2, $4 - # AWK automatically defines many other variables to help you inspect and - # process each line. The most important one is NF - - # Prints the number of fields on this line + # AWK自动定义了许多其他的变量帮助你处理行. 最常用的是NF变量 + # 打印这一行的字段数 print NF - # Print the last field on this line + # 打印这一行的最后一个字段 print $NF } -# Every pattern is actually a true/false test. The regular expression in the -# last pattern is also a true/false test, but part of it was hidden. If you -# don't give it a string to test, it will assume $0, the line that it's -# currently processing. Thus, the complete version of it is this: +# 每一个模式其实是一个true/false判断, 上面那个正则其实也是一个true/false判断, 只不过被部分省略了. +# 没有指定时默认使用当前处理的整行($0)进行匹配. 因此, 完全版本是这样: $0 ~ /^fo+bar$/ { print "Equivalent to the last pattern" } a > 0 { - # This will execute once for each line, as long as a is positive + # 只要a是整数, 这块会在每一行上执行. } -# You get the idea. Processing text files, reading in a line at a time, and -# doing something with it, particularly splitting on a delimiter, is so common -# in UNIX that AWK is a scripting language that does all of it for you, without -# you needing to ask. All you have to do is write the patterns and actions -# based on what you expect of the input, and what you want to do with it. +# 就是这样, 处理文本文件, 一次读一行, 对行做一些操作. 按分隔符分隔, 这在UNIX中很常见, awk都帮你做好了. +# 你所需要做的是基于自己的需求写一些模式和动作. -# Here's a quick example of a simple script, the sort of thing AWK is perfect -# for. It will read a name from standard input and then will print the average -# age of everyone with that first name. Let's say you supply as an argument the -# name of a this data file: +# 这里有一个快速的例子, 展示了AWK所擅长做的事. +# 它从标准输入读一个名字, 打印这个first name下所有人的平均年龄. +# 示例数据: # # Bob Jones 32 # Jane Doe 22 @@ -312,41 +280,36 @@ a > 0 { # Bob Smith 29 # Bob Barker 72 # -# Here's the script: +# 示例脚本: BEGIN { - # First, ask the user for the name + # 首先, 问用户要一个名字 print "What name would you like the average age for?" - # Get a line from standard input, not from files on the command line + # 从标准输入获取名字 getline name <"/dev/stdin" } -# Now, match every line whose first field is the given name +# 然后, 用给定的名字匹配每一行的第一个字段. $1 == name { - # Inside here, we have access to a number of useful variables, already - # pre-loaded for us: - # $0 is the entire line - # $3 is the third field, the age, which is what we're interested in here - # NF is the number of fields, which should be 3 - # NR is the number of records (lines) seen so far - # FILENAME is the name of the file being processed - # FS is the field separator being used, which is " " here - # ...etc. There are plenty more, documented in the man page. - - # Keep track of a running total and how many lines matched + # 这里我们要使用几个有用的变量, 已经提前为我们加载好的: + # $0 是整行 + # $3 是第三个字段, 就是我们所感兴趣的年龄 + # NF 字段数, 这里是3 + # NR 至此为止的行数 + # FILENAME 在处理的文件名 + # FS 在使用的字段分隔符, 这里是空格" " + # ...等等, 还有很多, 在帮助文档中列出. + + # 跟踪 总和以及行数 sum += $3 nlines++ } -# Another special pattern is called END. It will run after processing all the -# text files. Unlike BEGIN, it will only run if you've given it input to -# process. It will run after all the files have been read and processed -# according to the rules and actions you've provided. The purpose of it is -# usually to output some kind of final report, or do something with the -# aggregate of the data you've accumulated over the course of the script. +# 另一个特殊的模式叫END. 它会在处理完所有行之后运行. 不像BEGIN, 它只会在有输入的时候运行. +# 它在所有文件依据给定的模式和动作处理完后运行, 目的通常是输出一些最终报告, 做一些数据聚合操作. END { if (nlines) @@ -354,8 +317,8 @@ END { } ``` -Further Reading: +更多: -* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) -* [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [Awk 教程](http://www.grymoire.com/Unix/Awk.html) +* [Awk 手册](https://linux.die.net/man/1/awk) +* [The GNU Awk 用户指南](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk在大多数Linux中预装 -- cgit v1.2.3 From b13b8af2345893ac0f6c94690c753e8a496c2df6 Mon Sep 17 00:00:00 2001 From: dhu23 <36485423+dhu23@users.noreply.github.com> Date: Fri, 6 Jul 2018 09:19:22 -0400 Subject: Update kdb+.html.markdown change the each-left and each right example to make them more distinguishable. --- kdb+.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 097f177b..5c6e66fd 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -689,14 +689,14 @@ first each (1 2 3;4 5 6;7 8 9) / each-left (\:) and each-right (/:) modify a two-argument function / to treat one of the arguments and individual variables instead of a list -1 2 3 +\: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 +1 2 3 +\: 11 22 33 +/ => 12 23 34 +/ => 13 24 35 +/ => 14 25 36 1 2 3 +/: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 +/ => 12 13 14 +/ => 23 24 25 +/ => 34 35 36 / The true alternatives to loops in q are the adverbs scan (\) and over (/) / their behaviour differs based on the number of arguments the function they -- cgit v1.2.3 From 779840f985125d2a39b14ffed15aab8ccc882f66 Mon Sep 17 00:00:00 2001 From: dhu23 <36485423+dhu23@users.noreply.github.com> Date: Fri, 6 Jul 2018 09:23:09 -0400 Subject: Update kdb+.html.markdown fixed typos --- kdb+.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 5c6e66fd..027b6571 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -693,7 +693,7 @@ first each (1 2 3;4 5 6;7 8 9) / => 12 23 34 / => 13 24 35 / => 14 25 36 -1 2 3 +/: 1 2 3 +1 2 3 +/: 11 22 33 / => 12 13 14 / => 23 24 25 / => 34 35 36 -- cgit v1.2.3 From a78942e8f3e2c8b728bdf0ba5e4f8117027b85a2 Mon Sep 17 00:00:00 2001 From: i Date: Fri, 6 Jul 2018 11:41:46 -0400 Subject: clear up wording --- go.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 47d9c234..df677894 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -15,15 +15,15 @@ contributors: --- Go was created out of the need to get work done. It's not the latest trend -in computer science, but it is the newest fastest way to solve real-world +in programming language theory, but it is a way to solve real-world problems. -It has familiar concepts of imperative languages with static typing. +It draws concepts from imperative languages with static typing. It's fast to compile and fast to execute, it adds easy-to-understand -concurrency to leverage today's multi-core CPUs, and has features to -help with large-scale programming. +concurrency because multi-core CPUs are now common, and it's used successfully +in large codebases (~100 million loc at Google, Inc.). -Go comes with a great standard library and an enthusiastic community. +Go comes with a good standard library and a sizeable community. ```go // Single line comment @@ -48,7 +48,7 @@ import ( // executable program. Love it or hate it, Go uses brace brackets. func main() { // Println outputs a line to stdout. - // Qualify it with the package name, fmt. + // It comes from the package fmt. fmt.Println("Hello world!") // Call another function within this package. -- cgit v1.2.3 From b3d8f0cdc7eef9659ad2fab04c4047c2851ab381 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sat, 7 Jul 2018 12:08:10 -0400 Subject: feat(mips.html.markdown): Started working on math --- mips.html.markdown | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/mips.html.markdown b/mips.html.markdown index 1c857ba4..b1ef40c4 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -37,7 +37,7 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string .text # Section that contains instructions and program logic .globl _main # Declares an instruction label as global, making it accessible to other files - _main: # MIPS programs execute instructions sequentially, where this will be executed first + _main: # MIPS programs execute instructions sequentially, where the code under this label will be executed firsts # Let's print "hello world" la $a0, hello_world # Load address of string stored in memory @@ -62,4 +62,12 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string sw $t0, 8($s0) # Store word value into address specified in $s0 and offset of 8 bytes # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist +### Math ### + _math: + # Remember to load your values into a register + lw $t0, num # From the data section + li $t0, 5 # Or from an immediate (constant) + li $t1, 6 + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + ``` \ No newline at end of file -- cgit v1.2.3 From 4c025bc12b9a204ff205281b0bd6048ae969140b Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 15:05:27 -0400 Subject: feat(mips.html.markdown): Added mathematical operations and logical operator examples --- mips.html.markdown | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index b1ef40c4..5e6a9c99 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -65,9 +65,30 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string ### Math ### _math: # Remember to load your values into a register - lw $t0, num # From the data section - li $t0, 5 # Or from an immediate (constant) + lw $t0, num # From the data section + li $t0, 5 # Or from an immediate (constant) li $t1, 6 - add $t2, $t0, $t1 # $t2 = $t0 + $t1 + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + sub $t2, $t0, $t1 # $t2 = $t0 - $t1 + mul $t2, $t0, $t1 # $t2 = $t0 * $t1 + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + + # Bitwise Shifting + sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in register + srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount in a register + + # Bitwise operators + and $t0, $t1, $t2 # Bitwise AND + andi $t0, $t1, 0xFFF # Bitwise AND with immediate + or $t0, $t1, $t2 # Bitwise OR + ori $t0, $t1, 0xFFF # Bitwise OR with immediate + xor $t0, $t1, $t2 # Bitwise XOR + xori $t0, $t1, 0xFFF # Bitwise XOR with immediate + nor $t0, $t1, $t2 # Bitwise NOR ``` \ No newline at end of file -- cgit v1.2.3 From 6f32ec9859005b370994402848547c8a90400de2 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 15:16:26 -0400 Subject: chore(mips.html.markdown): Fixed formatting of comments --- mips.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index 5e6a9c99..e40c4b64 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -68,27 +68,27 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string lw $t0, num # From the data section li $t0, 5 # Or from an immediate (constant) li $t1, 6 - add $t2, $t0, $t1 # $t2 = $t0 + $t1 - sub $t2, $t0, $t1 # $t2 = $t0 - $t1 - mul $t2, $t0, $t1 # $t2 = $t0 * $t1 - div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) - div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + sub $t2, $t0, $t1 # $t2 = $t0 - $t1 + mul $t2, $t0, $t1 # $t2 = $t0 * $t1 + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' # Bitwise Shifting - sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 - sllv $t0, $t1, $t2 # Shift left by a variable amount in register - srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) - srlv $t0, $t1, $t2 # Shift right by a variable amount in a register - sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) - srav $t0, $t1, $t2 # Shift right by a variable amount in a register + sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in register + srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount in a register # Bitwise operators - and $t0, $t1, $t2 # Bitwise AND - andi $t0, $t1, 0xFFF # Bitwise AND with immediate - or $t0, $t1, $t2 # Bitwise OR - ori $t0, $t1, 0xFFF # Bitwise OR with immediate - xor $t0, $t1, $t2 # Bitwise XOR - xori $t0, $t1, 0xFFF # Bitwise XOR with immediate - nor $t0, $t1, $t2 # Bitwise NOR + and $t0, $t1, $t2 # Bitwise AND + andi $t0, $t1, 0xFFF # Bitwise AND with immediate + or $t0, $t1, $t2 # Bitwise OR + ori $t0, $t1, 0xFFF # Bitwise OR with immediate + xor $t0, $t1, $t2 # Bitwise XOR + xori $t0, $t1, 0xFFF # Bitwise XOR with immediate + nor $t0, $t1, $t2 # Bitwise NOR ``` \ No newline at end of file -- cgit v1.2.3 From 119c4172bb4eec083b23a86f784809705276e51a Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:16:51 -0400 Subject: chore(mips.html.markdown): Content now wraps at 80 chars --- .vscode/settings.json | 3 ++ mips.html.markdown | 101 +++++++++++++++++++++++++++++++++++--------------- 2 files changed, 75 insertions(+), 29 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..ae758328 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "editor.rulers": [80, 120], +} \ No newline at end of file diff --git a/mips.html.markdown b/mips.html.markdown index e40c4b64..6a9a7c2a 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -5,7 +5,10 @@ contributors: - ["Stanley Lim", "https://github.com/Spiderpig86"] --- -The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language is designed to work with the MIPS microprocessor paradigm designed by J. L. Hennessy in 1981. These RISC processors are used in embedded systems such as gateways and routers. +The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language +is designed to work with the MIPS microprocessor paradigm designed by J. L. +Hennessy in 1981. These RISC processors are used in embedded systems such as +gateways and routers. [Read More](https://en.wikipedia.org/wiki/MIPS_architecture) @@ -16,14 +19,18 @@ The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language # Programs typically contain a .data and .text sections -.data # Section where data is stored in memory (allocated in RAM), similar to variables in higher level languages +.data # Section where data is stored in memory (allocated in RAM), similar to +variables in higher level languages # Declarations follow a ( label: .type value(s) ) form of declaration hello_world .asciiz "Hello World\n" # Declare a null terminated string - num1: .word 42 # Integers are referred to as words (32 bit value) + num1: .word 42 # Integers are referred to as words + # (32 bit value) + arr1: .word 1, 2, 3, 4, 5 # Array of words arr2: .byte 'a', 'b' # Array of chars (1 byte each) - buffer: .space 60 # Allocates space in the RAM (not cleared to 0) + buffer: .space 60 # Allocates space in the RAM + # (not cleared to 0) # Datatype sizes _byte: .byte 'a' # 1 byte @@ -32,34 +39,62 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string _float: .float 3.14 # 4 bytes _double: .double 7.0 # 8 bytes - .align 2 # Memory alignment of data, where number indicates byte alignment in powers of 2. (.align 2 represents word alignment since 2^2 = 4 bytes) + .align 2 # Memory alignment of data, where + # number indicates byte alignment in + # powers of 2. (.align 2 represents + #word alignment since 2^2 = 4 bytes) -.text # Section that contains instructions and program logic -.globl _main # Declares an instruction label as global, making it accessible to other files +.text # Section that contains instructions + # and program logic +.globl _main # Declares an instruction label as + # global, making it accessible to + # other files - _main: # MIPS programs execute instructions sequentially, where the code under this label will be executed firsts + _main: # MIPS programs execute instructions + # sequentially, where the code under + # this label will be executed firsts # Let's print "hello world" - la $a0, hello_world # Load address of string stored in memory - li $v0, 4 # Load the syscall value (indicating type of functionality) - syscall # Perform the specified syscall with the given argument ($a0) + la $a0, hello_world # Load address of string stored in + # memory + li $v0, 4 # Load the syscall value (indicating + # type of functionality) + syscall # Perform the specified syscall with + # the given argument ($a0) # Registers (used to hold data during program execution) - # $t0 - $t9 # Temporary registers used for intermediate calculations inside subroutines (not saved across function calls) - # $s0 - $s7 # Saved registers where values are saved across subroutine calls. Typically saved in stack - # $a0 - $a3 # Argument registers for passing in arguments for subroutines - # $v0 - $v1 # Return registers for returning values to caller function + # $t0 - $t9 # Temporary registers used for + # intermediate calculations inside + # subroutines (not saved across + # function calls) + + # $s0 - $s7 # Saved registers where values are + # saved across subroutine calls. + # Typically saved in stack + + # $a0 - $a3 # Argument registers for passing in + # arguments for subroutines + # $v0 - $v1 # Return registers for returning + # values to caller function # Types of load/store instructions - la $t0, label # Copy the address of a value in memory specified by the label into register $t0 + la $t0, label # Copy the address of a value in + # memory specified by the label into + # register $t0 lw $t0, label # Copy a word value from memory - lw $t1, 4($s0) # Copy a word value from an address stored in a register with an offset of 4 bytes (addr + 4) - lb $t2, label # Copy a byte value to the lower order portion of the register $t2 - lb $t2, 0($s0) # Copy a byte value from the source address in $s0 with offset 0 + lw $t1, 4($s0) # Copy a word value from an address + # stored in a register with an offset + # of 4 bytes (addr + 4) + lb $t2, label # Copy a byte value to the lower order + # portion of the register $t2 + lb $t2, 0($s0) # Copy a byte value from the source + # address in $s0 with offset 0 # Same idea with 'lh' for halfwords - sw $t0, label # Store word value into memory address mapped by label - sw $t0, 8($s0) # Store word value into address specified in $s0 and offset of 8 bytes + sw $t0, label # Store word value into memory address + # mapped by label + sw $t0, 8($s0) # Store word value into address + # specified in $s0 and offset of 8 bytes # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist ### Math ### @@ -71,16 +106,24 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string add $t2, $t0, $t1 # $t2 = $t0 + $t1 sub $t2, $t0, $t1 # $t2 = $t0 - $t1 mul $t2, $t0, $t1 # $t2 = $t0 * $t1 - div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) - div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be + # supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient + # using 'mflo' and remainder using 'mfhi' # Bitwise Shifting - sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 - sllv $t0, $t1, $t2 # Shift left by a variable amount in register - srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) - srlv $t0, $t1, $t2 # Shift right by a variable amount in a register - sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) - srav $t0, $t1, $t2 # Shift right by a variable amount in a register + sll $t0, $t0, 2 # Bitwise shift to the left with + # immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in + # register + srl $t0, $t0, 5 # Bitwise shift to the right (does + # not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in + # a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right + # (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount + # in a register # Bitwise operators and $t0, $t1, $t2 # Bitwise AND -- cgit v1.2.3 From e566cee6c046fe680c7be0a745d447c3818420d9 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:32:51 -0400 Subject: chore(mips.html.markdown): Fixed minor space issue --- mips.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index 6a9a7c2a..dd7bc7b5 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -1,6 +1,6 @@ --- -language: "MIPS" -filename: MIPS.mips +language: "MIPS Assembly" +filename: MIPS.asm contributors: - ["Stanley Lim", "https://github.com/Spiderpig86"] --- @@ -42,7 +42,7 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string .align 2 # Memory alignment of data, where # number indicates byte alignment in # powers of 2. (.align 2 represents - #word alignment since 2^2 = 4 bytes) + # word alignment since 2^2 = 4 bytes) .text # Section that contains instructions # and program logic -- cgit v1.2.3 From 3315df63f9d28f52d23fd16d907554f1655366e2 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:34:28 -0400 Subject: chore(.vscode): Removed config folder --- .vscode/settings.json | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index ae758328..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "editor.rulers": [80, 120], -} \ No newline at end of file -- cgit v1.2.3 From 8c30522d58e6c006274952a75c5acd4d104c8828 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:12:23 -0700 Subject: added info about tuples, integrated wild card use into a function definition --- haskell.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 266cf11b..cad036f1 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -124,6 +124,9 @@ last [1..5] -- 5 fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 +-- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) +snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this + ---------------------------------------------------- -- 3. Functions ---------------------------------------------------- @@ -159,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples: -foo (x, y) = (x + 1, y + 2) +-- Pattern matching on tuples, using wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -203,9 +206,9 @@ foo = (4*) . (10+) foo 5 -- 60 -- fixing precedence --- Haskell has an operator called `$`. This operator applies a function --- to a given parameter. In contrast to standard function application, which --- has highest possible priority of 10 and is left-associative, the `$` operator +-- Haskell has an operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that -- the expression on its right is applied as the parameter to the function on its left. @@ -223,7 +226,7 @@ even . fib $ 7 -- false -- 5. Type signatures ---------------------------------------------------- --- Haskell has a very strong type system, and every valid expression has a type. +-- Haskell has a very strong type system, and every valid expression has a type. -- Some basic types: 5 :: Integer -- cgit v1.2.3 From 093e6b62a1aae230f965ad8d1ee2ff8a6b128055 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:15:26 -0700 Subject: moved comment on sndOfTriple --- haskell.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index cad036f1..6a48b60c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -162,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples, using wild card (_) to bypass naming an unused value -sndOfTriple (_, y, _) = y +-- Pattern matching on tuples +sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write -- cgit v1.2.3 From c421b1bd0d18ab57c88665bd14b289e75724cf37 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:34:42 -0700 Subject: trimmed loc over 80 chars --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6a48b60c..e9ddf54d 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -125,7 +125,7 @@ fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 -- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) -snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this +snd ("snd", "can't touch this", "da na na na") -- error! see function below ---------------------------------------------------- -- 3. Functions @@ -163,7 +163,7 @@ fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) -- Pattern matching on tuples -sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- use a wild card (_) to bypass naming unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -210,7 +210,7 @@ foo 5 -- 60 -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that --- the expression on its right is applied as the parameter to the function on its left. +-- the expression on its right is applied as parameter to function on its left. -- before even (fib 7) -- false -- cgit v1.2.3 From 1298dfef8f89092faca9789a6044e835f6b82bd8 Mon Sep 17 00:00:00 2001 From: Ali Mohammad Pur Date: Sat, 14 Jul 2018 19:17:46 +0430 Subject: [Citron/en] Add basic explanations --- citron.html.markdown | 212 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 citron.html.markdown diff --git a/citron.html.markdown b/citron.html.markdown new file mode 100644 index 00000000..bd3c398c --- /dev/null +++ b/citron.html.markdown @@ -0,0 +1,212 @@ +--- +language: citron +filename: learncitron.ctr +contributors: + - ["AnotherTest", ""] +lang: en-us +--- +```ruby +# Comments start with a '#' +# All comments encompass a single line + +########################################### +## 1. Primitive Data types and Operators +########################################### + +# You have numbers +3. # 3 + +# Numbers are all doubles in interpreted mode + +# Mathematical operator precedence is not respected. +# binary 'operators' are evaluated in ltr order +1 + 1. # 2 +8 - 4. # 4 +10 + 2 * 3. # 36 + +# Division is always floating division +35 / 2 # 17.5. + +# Integer division is non-trivial, you may use floor +(35 / 2) floor # 17. + +# Booleans are primitives +True. +False. + +# Boolean messages +True not. # False +False not. # True +1 = 1. # True +1 !=: 1. # False +1 < 10. # True + +# Here, `not` is a unary message to the object `Boolean` +# Messages are comparable to instance method calls +# And they have three different forms: +# 1. Unary messages: Length > 1, and they take no arguments: + False not. +# 2. Binary Messages: Length = 1, and they take a single argument: + False & True. +# 3. Keyword messages: must have at least one ':', they take as many arguments +# as they have `:` s + False either: 1 or: 2. # 2 + +# Strings +'This is a string'. +'There are no character types exposed to the user'. +# "You cannot use double quotes for strings" <- Error + +# Strins can be summed +'Hello, ' + 'World!'. # 'Hello, World!' + +# Strings allow access to their characters +'This is a beautiful string' at: 0. # 'T' + +########################################### +## intermission: Basic Assignment +########################################### + +# You may assign values to the current scope: +var name is value. # assignes `value` into `name` + +# You may also assign values into the current object's namespace +my name is value. # assigns `value` into the current object's `name` property + +# Please note that these names are checked at compile (read parse if in interpreted mode) time +# but you may treat them as dynamic assignments anyway + +########################################### +## 2. Lists(Arrays?) and Tuples +########################################### + +# Arrays are allowed to have multiple types +Array new < 1 ; 2 ; 'string' ; Nil. # Array new < 1 ; 2 ; 'string' ; Nil + +# Tuples act like arrays, but are immutable. +# Any shenanigans degrade them to arrays, however +[1, 2, 'string']. # [1, 2, 'string'] + +# They can interoperate with arrays +[1, 'string'] + (Array new < 'wat'). # Array new < 1 ; 'string' ; 'wat' + +# Indexing into them +[1, 2, 3] at: 1. # 2 + +# Some array operations +var arr is Array new < 1 ; 2 ; 3. + +arr head. # 1 +arr tail. # Array new < 2 ; 3. +arr init. # Array new < 1 ; 2. +arr last. # 3 +arr push: 4. # Array new < 1 ; 2 ; 3 ; 4. +arr pop. # 4 +arr pop: 1. # 2, `arr` is rebound to Array new < 1 ; 3. + +# List comprehensions +[x * 2 + y,, arr, arr + [4, 5],, x > 1]. # Array ← 7 ; 9 ; 10 ; 11 +# fresh variable names are bound as they are encountered, +# so `x` is bound to the values in `arr` +# and `y` is bound to the values in `arr + [4, 5]` +# +# The general format is: [expr,, bindings*,, predicates*] + + +#################################### +## 3. Functions +#################################### + +# A simple function that takes two variables +var add is {:a:b ^a + b.}. + +# this function will resolve all its names except the formal arguments +# in the context it is called in. + +# Using the function +add applyTo: 3 and: 5. # 8 +add applyAll: [3, 5]. # 8 + +# Also a (customizable -- more on this later) pseudo-operator allows for a shorthand +# of function calls +# By default it is REF[args] + +add[3, 5]. # 8 + +# To customize this behaviour, you may simply use a compiler pragma: +#:callShorthand () + +# And then you may use the specified operator. +# Note that the allowed 'operator' can only be made of any of these: []{}() +# And you may mix-and-match (why would anyone do that?) + +add(3, 5). # 8 + +# You may also use functions as operators in the following way: + +3 `add` 5. # 8 +# This call binds as such: add[(3), 5] +# because the default fixity is left, and the default precedance is 1 + +# You may change the precedence/fixity of this operator with a pragma +#:declare infixr 1 add + +3 `add` 5. # 8 +# now this binds as such: add[3, (5)]. + +# There is another form of functions too +# So far, the functions were resolved in a dynamic fashion +# But a lexically scoped block is also possible +var sillyAdd is {\:x:y add[x,y].}. + +# In these blocks, you are not allowed to declare new variables +# Except with the use of Object::'letEqual:in:` +# And the last expression is implicitly returned. + +# You may also use a shorthand for lambda expressions +var mul is \:x:y x * y. + +# These capture the named bindings that are not present in their +# formal parameters, and retain them. (by ref) + +########################################### +## 5. Control Flow +########################################### + +# inline conditional-expressions +var citron is 1 = 1 either: 'awesome' or: 'awful'. # citron is 'awesome' + +# multiple lines is fine too +var citron is 1 = 1 + either: 'awesome' + or: 'awful'. + +# looping +10 times: {:x + Pen writeln: x. +}. # 10. -- side effect: 10 lines in stdout, with numbers 0 through 9 in them + +# Citron properly supports tail-call recursion in lexically scoped blocks +# So use those to your heart's desire + +# mapping most data structures is as simple as `fmap:` +[1, 2, 3, 4] fmap: \:x x + 1. # [2, 3, 4, 5] + +# You can use `foldl:accumulator:` to fold a list/tuple +[1, 2, 3, 4] foldl: (\:acc:x acc * 2 + x) accumulator: 4. # 90 + +# That expression is the same as +(2 * (2 * (2 * (2 * 4 + 1) + 2) + 3) + 4) + +################################### +## 6. IO +################################### + +# IO is quite simple +# With `Pen` being used for console output +# and Program::'input' and Program::'waitForInput' being used for console input + +Pen writeln: 'Hello, ocean!' # prints 'Hello, ocean!\n' to the terminal + +Pen writeln: Program waitForInput. # reads a line and prints it back +``` -- cgit v1.2.3 From 3ab2e88b4af9d072fbd2e0e2b9c0fe849d46892b Mon Sep 17 00:00:00 2001 From: YAN HUI HANG Date: Sun, 15 Jul 2018 15:33:01 +0800 Subject: SKI, SK and Iota --- lambda-calculus.html.markdown | 95 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 6103c015..72ed78ba 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -3,6 +3,7 @@ category: Algorithms & Data Structures name: Lambda Calculus contributors: - ["Max Sun", "http://github.com/maxsun"] + - ["Yan Hui Hang", "http://github.com/yanhh0"] --- # Lambda Calculus @@ -114,8 +115,100 @@ Using successor, we can define add: **Challenge:** try defining your own multiplication function! +## Get even smaller: SKI, SK and Iota + +### SKI Combinator Calculus + +Let S, K, I be the following functions: + +`I x = x` + +`K x y = x` + +`S x y z = x z (y z)` + +We can convert an expression in the lambda calculus to an expression +in the SKI combinator calculus: + +1. `λx.x = I` +2. `λx.c = Kc` +3. `λx.(y z) = S (λx.y) (λx.z)` + +Take the church number 2 for example: + +`2 = λf.λx.f(f x)` + +For the inner part `λx.f(f x)`: +``` + λx.f(f x) += S (λx.f) (λx.(f x)) (case 3) += S (K f) (S (λx.f) (λx.x)) (case 2, 3) += S (K f) (S (K f) I) (case 2, 1) +``` + +So: +``` + 2 += λf.λx.f(f x) += λf.(S (K f) (S (K f) I)) += λf.((S (K f)) (S (K f) I)) += S (λf.(S (K f))) (λf.(S (K f) I)) (case 3) +``` + +For the first argument `λf.(S (K f))`: +``` + λf.(S (K f)) += S (λf.S) (λf.(K f)) (case 3) += S (K S) (S (λf.K) (λf.f)) (case 2, 3) += S (K S) (S (K K) I) (case 2, 3) +``` + +For the second argument `λf.(S (K f) I)`: +``` + λf.(S (K f) I) += λf.((S (K f)) I) += S (λf.(S (K f))) (λf.I) (case 3) += S (S (λf.S) (λf.(K f))) (K I) (case 2, 3) += S (S (K S) (S (λf.K) (λf.f))) (K I) (case 1, 3) += S (S (K S) (S (K K) I)) (K I) (case 1, 2) +``` + +Merging them up: +``` + 2 += S (λf.(S (K f))) (λf.(S (K f) I)) += S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I)) +``` + +Expanding this, we would end up with the same expression for the +church number 2 again. + +### SK Combinator Calculus + +The SKI combinator calculus can still be reduced further. We can +remove the I combinator by noting that `I = SKK`. We can substitute +all `I`'s with `SKK`. + +### Iota Combinator + +The SK combinator calculus is still not minimal. Defining: + +``` +ι = λf.((f S) K) +``` + +We have: + +``` +I = ιι +K = ι(ιI) = ι(ι(ιι)) +S = ι(K) = ι(ι(ι(ιι))) +``` + ## For more advanced reading: 1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) 2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) -3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) +5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) -- cgit v1.2.3 From f6300aad29005e9b5f95bf63fdfbfbb8cc3dca7d Mon Sep 17 00:00:00 2001 From: Vitalie Lazu Date: Fri, 20 Jul 2018 16:22:47 +0300 Subject: Added Romanian translation for Elixir --- ro-ro/elixir-ro.html.markdown | 459 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 459 insertions(+) create mode 100644 ro-ro/elixir-ro.html.markdown diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown new file mode 100644 index 00000000..d8b261af --- /dev/null +++ b/ro-ro/elixir-ro.html.markdown @@ -0,0 +1,459 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] + - ["Ev Bogdanov", "https://github.com/evbogdanov"] +translators: + - ["Vitalie Lazu", "https://github.com/vitaliel"] + +filename: learnelixir-ro.ex +--- + +Elixir este un limbaj funcțional modern construit pe baza mașinii virtuale Erlang. +E total compatibil cu Erlang, dar are o sintaxă mai prietenoasă și propune mai multe +posibilități. + +```elixir + +# Comentariile de o linie încep cu simbolul diez. + +# Pentru comentarii pe mai multe linii nu există sintaxă separată, +# de aceea folosiți mai multe linii cu comentarii. + +# Pentru a folosi shell-ul elixir utilizați comanda `iex`. +# Compilați modulele cu comanda `elixirc`. + +# Ambele comenzi vor lucra în terminal, dacă ați instalat Elixir corect. + +## --------------------------- +## -- Tipuri de bază +## --------------------------- + +# Numere +3 # număr întreg +0x1F # număr întreg +3.0 # număr cu virgulă mobilă + +# Atomii, sunt constante nenumerice. Ei încep cu `:`. +:salut # atom + +# Tuplele sunt păstrate în memorie consecutiv. +{1,2,3} # tuple + +# Putem accesa elementul tuplelui folosind funcția `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listele sunt implementate ca liste înlănțuite. +[1,2,3] # listă + +# Fiecare listă ne vidă are cap (primul element al listei) +# și coadă (restul elementelor). +# Putem accesa capul și coada listei cum urmează: +[cap | coadă] = [1,2,3] +cap #=> 1 +coadă #=> [2, 3] + +# În Elixir, ca și în Erlang, simbolul `=` denotă potrivirea șabloanelor și +# nu atribuire. +# +# Aceasta înseamnă că expresia din stînga (șablonul) se potrivește cu +# expresia din dreaptă. +# +# În modul acesta exemplul de mai sus lucrează accesînd capul și coada unei liste. + +# Potrivirea șablonului va da eroare cînd expresiile din stînga și dreapta nu se +# potrivesc, în exemplu acesta tuplele au lungime diferită. +{a, b, c} = {1, 2} #=> ** (MatchError) + +# Există și date binare +<<1,2,3>> + +# Sunt două tipuri de șiruri de caractere +"salut" # șir de caractere Elixir +'salut' # listă de caractere Erlang + +# Șir de caractere pe mai multe linii +""" +Sunt un șir de caractere +pe mai multe linii. +""" +#=> "Sunt un șir de caractere\npe mai multe linii..\n" + +# Șirurile de caractere sunt codificate în UTF-8: +"Bună dimineața" #=> "Bună dimineața" + +# Șirurile de caractere sunt date binare, listele de caractere doar liste. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` în Elixir întoarce codul ASCII pentru litera `a` +?a #=> 97 + +# Pentru a concatena listele folosiți `++`, pentru date binare - `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'Salut ' ++ 'lume' #=> 'Salut lume' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"Salut " <> "lume" #=> "Salut lume" + +# Diapazoanele sunt reprezentate ca `început..sfîrșit` (inclusiv) +1..10 #=> 1..10 +început..sfîrșit = 1..10 # Putem folosi potrivirea șabloanelor cu diapazoane de asemenea +[început, sfîrșit] #=> [1, 10] + +# Dicţionarele stochează chei şi o valoare pentru fiecare cheie +genuri = %{"Ion" => "bărbat", "Maria" => "femeie"} +genuri["Ion"] #=> "bărbat" + +# Dicționare cu chei de tip atom au sintaxă specială +genuri = %{ion: "bărbat", maria: "femeie"} +genuri.ion #=> "bărbat" + +## --------------------------- +## -- Operatori +## --------------------------- + +# Operații matematice +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# În Elixir operatorul `/` întotdeauna întoarce un număr cu virgulă mobilă. + +# Folosiți `div` pentru împărțirea numerelor întregi +div(10, 2) #=> 5 + +# Pentru a obține restul de la împărțire utilizați `rem` +rem(10, 3) #=> 1 + +# Există și operatori booleni: `or`, `and` and `not`. +# Acești operatori așteaptă ca primul argument o expresie booleană. +true and true #=> true +false or true #=> true +1 and true #=> ** (BadBooleanError) + +# Elixir de asemenea oferă `||`, `&&` și `!` care acceptă argumente de orice tip. +# Toate valorile în afară de `false` și `nil` se vor evalua ca `true`. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Operatori de comparație: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` și `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` și `!==` au strictețe mai mare cînd comparăm numere întregi și reale: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Putem compara de asemenea și date de diferite tipuri: +1 < :salut #=> true + +# La compararea diferitor tipuri folosiți următoare prioritate: +# număr < atom < referință < funcție < port < proces < tuple < listă < șir de caractere + +# Cităm pe Joe Armstrong în acest caz: "Ordinea actuală nu e importantă, +dar că ordinea totală este bine definită este important." + +## --------------------------- +## -- Ordinea execuției +## --------------------------- + +# expresia `if` +if false do + "Aceasta nu veți vedea niciodată" +else + "Aceasta veți vedea" +end + +# expresia opusă `unless` +unless true do + "Aceasta nu veți vedea niciodată" +else + "Aceasta veți vedea" +end + +# Țineți minte potrivirea șabloanelor? Multe structuri în Elixir se bazează pe ea. + +# `case` ne permite să comparăm o valoare cu multe șabloane: +case {:unu, :doi} do + {:patru, :cinci} -> + "Aceasta nu se potrivește" + {:unu, x} -> + "Aceasta se potrivește și atribuie lui `x` `:doi` în acest bloc" + _ -> + "Aceasta se va potrivi cu orice valoare" +end + +# Simbolul `_` se numește variabila anonimă. +# Folosiți-l pentru valori ce nu vă interesează. +# De exemplu, dacă doar capul listei ne intereseaza: +[cap | _] = [1,2,3] +cap #=> 1 + +# Pentru o citire mai bună putem scri: +[cap | _coadă] = [:a, :b, :c] +cap #=> :a + +# `cond` ne permite să verificăm multe condiții de odată. +# Folosiți `cond` în schimbul la multe expresii `if`. +cond do + 1 + 1 == 3 -> + "Aceasta nu veți vedea niciodată" + 2 * 5 == 12 -> + "Pe mine la fel" + 1 + 2 == 3 -> + "Aceasta veți vedea" +end + +# Este obușnuit de setat ultima condiție cu `true`, care se va potrivi întotdeauna. +cond do + 1 + 1 == 3 -> + "Aceasta nu veți vedea niciodată" + 2 * 5 == 12 -> + "Pe mine la fel" + true -> + "Aceasta veți vedea (este else în esență)" +end + +# Blocul `try/catch` se foloște pentru prelucrarea excepțiilor. +# Elixir suportă blocul `after` care se execută în orice caz. +try do + throw(:salut) +catch + mesaj -> "Am primit #{mesaj}." +after + IO.puts("Sunt în blocul after.") +end +#=> Sunt în blocul after. +# "Am primit salut" + +## --------------------------- +## -- Module și Funcții +## --------------------------- + +# Funcții anonime (atenție la punct la apelarea funcției) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Ele de asemenea aceptă multe clauze și expresii de gardă. +# Expresiile de gardă vă permit să acordați potrivirea șabloanelor, +# ele sunt indicate după cuvîntul cheie `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir de asemenea oferă multe funcții incorporate. +# Ele sunt accesibile în scopul curent. +is_number(10) #=> true +is_list("salut") #=> false +elem({1,2,3}, 0) #=> 1 + +# Puteți grupa cîteva funcții într-un modul. În interiorul modulului folosiți `def` +# pentru a defini funcțiile necesare. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Pentru a compila modulul nostru simplu Math îl salvăm ca `math.ex` și utilizăm `elixirc`. +# în terminal: elixirc math.ex + +# În interiorul modulului putem defini funcții cu `def` și funcții private cu `defp`. +defmodule PrivateMath do + # O funcție definită cu `def` este accesibilă pentru apelare din alte module, + def sum(a, b) do + do_sum(a, b) + end + + # O funcție privată poate fi apelată doar local. + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Declarația funcției de asemenea suportă expresii de gardă și multe clauze: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +Geometry.area({:circle, "not_a_number"}) #=> ** (FunctionClauseError) + +# Din cauza variabilelor imutabile, un rol important îl ocupă funcțiile recursive +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Modulele în Elixir suportă atribute, există atribute incorporate și +# puteți adăuga altele. +defmodule MyMod do + @moduledoc """ + Este un atribut incorporat + """ + + @my_data 100 # Acesta e atributul nostru + IO.inspect(@my_data) #=> 100 +end + +# Operatorul |> permite transferarea rezultatului unei expresii din stînga +# ca primul argument al unei funcții din dreapta. +Range.new(1,10) +|> Enum.map(fn x -> x * x end) +|> Enum.filter(fn x -> rem(x, 2) == 0 end) +#=> [4, 16, 36, 64, 100] + +## --------------------------- +## -- Structuri și Excepții +## --------------------------- + +# Structurile sunt extensii a dicționarelor ce au valori implicite, +# verificări în timpul compilării și polimorfism +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end + +joe_info = %Person{ name: "Joe", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Joe"} + +# Acesarea cîmpului din structură +joe_info.name #=> "Joe" + +# Actualizarea valorii cîmpului +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} + +# Blocul `try` cu cuvîntul cheie `rescue` e folosit pentru a prinde excepții +try do + raise "o eroare" +rescue + RuntimeError -> "a fost prinsă o eroare runtime" + _error -> "aici vor fi prinse toate erorile" +end +#=> "a fost prinsă o eroare runtime" + +# Toate excepțiile au un mesaj +try do + raise "o eroare" +rescue + x in [RuntimeError] -> + x.message +end +#=> "o eroare" + +## --------------------------- +## -- Concurența +## --------------------------- + +# Concurența în Elixir se bazează pe modelul actor. Pentru a scrie programe +# concurente avem nevoie de trei lucruri: +# 1. Crearea proceselor +# 2. Trimiterea mesajelor +# 3. Primirea mesajelor + +# Un nou proces se crează folosind funcția `spawn`, care primește o funcție +# ca argument. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` întoarce identificatorul procesului pid, îl puteți folosi pentru +# a trimite mesaje procesului. Mesajele se transmit folosind operatorul `send`. +# Pentru primirea mesajelor se folosește mecanismul `receive`: + +# Blocul `receive do` este folosit pentru așteptarea mesajelor și prelucrarea lor +# cînd au fost primite. Blocul `receive do` va procesa doar un singur mesaj primit. +# Pentru a procesa mai multe mesaje, funcția cu blocul `receive do` trebuie +# recursiv să se auto apeleze. + +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Aria = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Aria = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compilați modulul și creați un proces +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Un alt mod +pid = spawn(Geometry, :area_loop, []) + +# Trimiteți un mesaj către `pid` care se va potrivi cu un șablon din blocul `receive` +send pid, {:rectangle, 2, 3} +#=> Aria = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Aria = 12.56000000000000049738 +# {:circle,2} + +# Interpretatorul este de asemenea un proces, puteți folosi `self` +# pentru a primi identificatorul de proces: +self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agenții +## --------------------------- + +# Un agent este un proces care urmărește careva valori ce se schimbă. + +# Creați un agent cu `Agent.start_link`, transmițînd o funcție. +# Stare inițială a agentului va fi rezultatul funcției. +{ok, my_agent} = Agent.start_link(fn -> ["roșu", "verde"] end) + +# `Agent.get` primește numele agentului și o `fn` care primește starea curentă +# Orice va întoarce `fn` este ceea ce veți primi înapoi: +Agent.get(my_agent, fn colors -> colors end) #=> ["roșu", "verde"] + +# Actualizați starea agentului în acelaș mod: +Agent.update(my_agent, fn colors -> ["albastru" | colors] end) +``` + +## Link-uri utile + +* [Primii pași](http://elixir-lang.org/getting-started/introduction.html) de pe [situl Elixir](http://elixir-lang.org) +* [Documentația oficială Elixir](http://elixir-lang.org/docs/master/) +* [Un mic conspect pe Elixir](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* [Cartea "Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) de Dave Thomas +* [Cartea "Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) de Fred Hebert +* [Cartea "Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) de Joe Armstrong -- cgit v1.2.3 From 81f9f0fec80b3c459937dd59be8384433251e3f8 Mon Sep 17 00:00:00 2001 From: Stanley Lim Date: Fri, 20 Jul 2018 10:39:43 -0400 Subject: feat(mips.html.markdown): Added examples for branching and conditionals --- mips.html.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/mips.html.markdown b/mips.html.markdown index dd7bc7b5..418761bf 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -134,4 +134,68 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string xori $t0, $t1, 0xFFF # Bitwise XOR with immediate nor $t0, $t1, $t2 # Bitwise NOR -``` \ No newline at end of file +## BRANCHING ## + _branching: + # The basic format of these branching instructions typically follow + #