From 1f4bcf8a7a23cd2ea687e3a197f65508b4d1b919 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 12:58:17 +0800 Subject: Create markdown-cn.html.markdown initiate --- zh-cn/markdown-cn.html.markdown | 246 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 zh-cn/markdown-cn.html.markdown diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown new file mode 100644 index 00000000..9a863bac --- /dev/null +++ b/zh-cn/markdown-cn.html.markdown @@ -0,0 +1,246 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: markdown.md +--- + +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). + +Give me as much feedback as you want! / Feel free to fork and pull request! + + +``` + + + + + + +# This is an

+## This is an

+### This is an

+#### This is an

+##### This is an

+###### This is an
+ + +This is an h1 +============= + +This is an h2 +------------- + + + + +*This text is in italics.* +_And so is this text._ + +**This text is in bold.** +__And so is this text.__ + +***This text is in both.*** +**_As is this!_** +*__And this!__* + + + +~~This text is rendered with strikethrough.~~ + + + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! + + +I'm in paragraph three! + + + +I end with two spaces (highlight me to see them). + +There's a
above me! + + + +> 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 `>`. + +> You can also use more than one level +>> of indentation? +> How neat is that? + + + + +* Item +* Item +* Another item + +or + ++ Item ++ Item ++ One more item + +or + +- Item +- Item +- One last item + + + +1. Item one +2. Item two +3. Item three + + + +1. Item one +1. Item two +1. Item three + + + + +1. Item one +2. Item two +3. Item three + * Sub-item + * Sub-item +4. Item four + + + + + This is code + So is this + + + + my_array.each do |item| + puts item + end + + + +John didn't even know what the `go_to()` function did! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + +<-- The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Click me!](http://test.com/) + + + +[Click me!](http://test.com/ "Link to Test.com") + + + +[Go to music](/music/). + + + +[Click this link][link1] for more info about it! +[Also check out this link][foobar] if you want to. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + + + + + +[This][] is a link. + +[this]: http://thisisalink.com/ + + + + + + +![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") + + + +![This is the hover-text.][myimage] + +[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" + + + + + is equivalent to +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +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\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Left-aligned | Centered | Right-aligned | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop + + + +``` + +For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 1e18c52f615c05343de77edf0ce364b9c3437764 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:00:39 +0800 Subject: Updated the file head --- zh-cn/markdown-cn.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 9a863bac..68f2e909 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -2,7 +2,10 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Fangzhou Chen", "http://binarythink.net"] filename: markdown.md +lang: zh-cn --- Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -- cgit v1.2.3 From 62e5ab350acd1803dea8f52ffd5b437c04cf7f84 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:01:14 +0800 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 68f2e909..1e463287 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -3,7 +3,7 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Fangzhou Chen", "http://binarythink.net"] + - ["Fangzhou Chen"] filename: markdown.md lang: zh-cn --- -- cgit v1.2.3 From 821464185ac044a0812584ac794049947d25b736 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 13:24:22 +0800 Subject: 2nd para --- zh-cn/markdown-cn.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 1e463287..f27722ba 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -8,17 +8,16 @@ filename: markdown.md lang: zh-cn --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成HTML(以及其他很多)格式。 -Give me as much feedback as you want! / Feel free to fork and pull request! +欢迎您多多反馈以及分支和请求合并。 ``` - + - - - - -# This is an

-## This is an

-### This is an

-#### This is an

-##### This is an

-###### This is an
- - -This is an h1 + + + + +# 这是一个

+## 这是一个

+### 这是一个

+#### 这是一个

+##### 这是一个

+###### 这是一个
+ + +这是一个 h1 ============= -This is an h2 +这是一个 h2 ------------- - - + + -*This text is in italics.* -_And so is this text._ +*此文本为斜体。* +_此文本也是。_ -**This text is in bold.** -__And so is this text.__ +**此文本为粗体。** +__此文本也是__ -***This text is in both.*** -**_As is this!_** -*__And this!__* +***此文本是斜体加粗体。*** +**_或者这样。_** +*__这个也是!__* - + -~~This text is rendered with strikethrough.~~ +~~此文本为删除线效果。~~ - + -This is a paragraph. I'm typing in a paragraph isn't this fun? +这是第一段落. 这句话在同一个段落里,好玩么? -Now I'm in paragraph 2. -I'm still in paragraph 2 too! +现在我是第二段落。 +这句话也在第二段落! +这句话在第三段落! -I'm in paragraph three! + - +此段落结尾有两个空格(选中以显示)。 -I end with two spaces (highlight me to see them). +上文有一个
! -There's a
above me! + - +> 这是一个段落引用. 你可以 +> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 +> 只要你的文字以“>” 字符开头,两种方式无异。 -> 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 `>`. +> 你也对文本进行 +>> 多层引用 +> 这多机智啊! -> You can also use more than one level ->> of indentation? -> How neat is that? + + - - +* 项目 +* 项目 +* 另一个项目 -* Item -* Item -* Another item +或者 -or ++ 项目 ++ 项目 ++ 另一个项目 -+ Item -+ Item -+ One more item +或者 -or +- 项目 +- 项目 +- 最后一个项目 -- Item -- Item -- One last item + - +1. 项目一 +2. 项目二 +3. 项目三 -1. Item one -2. Item two -3. Item three + - +1. 项目一 +1. 项目二 +1. 项目三 + -1. Item one -1. Item two -1. Item three - + - +1. 项目一 +2. 项目二 +3. 项目三 + * 子项目 + * 子项目 +4. 项目四 -1. Item one -2. Item two -3. Item three - * Sub-item - * Sub-item -4. Item four - - - + + This is code So is this - + my_array.each do |item| puts item end - + John didn't even know what the `go_to()` function did! -- cgit v1.2.3 From e98b62883cd0ef08d72a9da5384df7f5402cb180 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 16:55:29 +0800 Subject: Finally Done --- zh-cn/markdown-cn.html.markdown | 115 ++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 4f4b4c51..5de5f75b 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -19,10 +19,13 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 并不会被Markdown解析器所影响。不过如果你在Markdown文件内创建了HTML元素, 你将无法在HTML元素的内容中使用Markdown语法。--> - + - + + # 这是一个

## 这是一个

### 这是一个

@@ -54,7 +57,7 @@ __此文本也是__ ~~此文本为删除线效果。~~ - + 这是第一段落. 这句话在同一个段落里,好玩么? @@ -70,7 +73,7 @@ __此文本也是__ 上文有一个
! - + > 这是一个段落引用. 你可以 > 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 @@ -105,7 +108,8 @@ __此文本也是__ 2. 项目二 3. 项目三 - + 1. 项目一 1. 项目二 @@ -122,7 +126,8 @@ __此文本也是__ 4. 项目四 - + This is code So is this @@ -135,105 +140,101 @@ __此文本也是__ -John didn't even know what the `go_to()` function did! +John 甚至不知道 `go_to()` 方程是干嘛的! - + -\`\`\`ruby +\`\`\`ruby def foobar puts "Hello world!" end -\`\`\` +\`\`\` -<-- The above text doesn't require indenting, plus Github will use syntax -highlighting of the language you specify after the ``` --> + - - + + *** --- - - - **************** - - + + -[Click me!](http://test.com/) +[点我点我!](http://test.com/) - + -[Click me!](http://test.com/ "Link to Test.com") +[点我点我!](http://test.com/ "连接到Test.com") - + -[Go to music](/music/). +[去 music](/music/). - + -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. +[点此链接][link1]以获取更多信息! +[看一看这个链接][foobar] 如果你愿意的话. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - + - + [This][] is a link. [this]: http://thisisalink.com/ - + - - + + -![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title") +![这是我图像的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") - + -![This is the hover-text.][myimage] +![这是我的悬停文本.][myimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +[myimage]: relative/urls/cool/image.jpg "在此输入标题" - - + + - is equivalent to -[http://testwebsite.com/](http://testwebsite.com/) + 与 +[http://testwebsite.com/](http://testwebsite.com/) 等同 - + - + -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\*. +我希望 *将这段文字置于星号之间* 但是我不希望它被 +斜体化, 所以我就: \*这段置文字于星号之间\*。 - - + + -| Col1 | Col2 | Col3 | -| :----------- | :------: | ------------: | -| Left-aligned | Centered | Right-aligned | -| blah | blah | blah | +| 第一列 | 第二列 | 第三列 | +| :---------- | :------: | ---------: | +| 左对齐 | 居个中 | 右对齐 | +| 某某某 | 某某某 | 某某某 | - + -Col 1 | Col2 | Col3 +第一列 | 第二列 | 第三列 :-- | :-: | --: -Ugh this is so ugly | make it | stop +这太丑了 | 药不能 | 停 - + ``` -For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From fd010c57e08336d108d979ecad9a82ef30980ed3 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:01:22 +0800 Subject: Proofread and checked style --- zh-cn/markdown-cn.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 5de5f75b..f82ebcea 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -1,25 +1,25 @@ --- -language: markdown +language: Markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: markdown.md +filename: Markdown.md lang: zh-cn --- -Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成HTML(以及其他很多)格式。 +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。 欢迎您多多反馈以及分支和请求合并。 ``` - + - @@ -41,7 +41,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 ------------- - + *此文本为斜体。* _此文本也是。_ @@ -53,7 +53,7 @@ __此文本也是__ **_或者这样。_** *__这个也是!__* - + ~~此文本为删除线效果。~~ @@ -66,7 +66,7 @@ __此文本也是__ 这句话在第三段落! - 此段落结尾有两个空格(选中以显示)。 @@ -108,7 +108,7 @@ __此文本也是__ 2. 项目二 3. 项目三 - 1. 项目一 @@ -126,7 +126,7 @@ __此文本也是__ 4. 项目四 - This is code @@ -150,7 +150,7 @@ def foobar end \`\`\` - + @@ -161,7 +161,7 @@ end **************** - [点我点我!](http://test.com/) @@ -220,10 +220,10 @@ end 斜体化, 所以我就: \*这段置文字于星号之间\*。 - + | 第一列 | 第二列 | 第三列 | -| :---------- | :------: | ---------: | +| :---------- | :------: | ----------: | | 左对齐 | 居个中 | 右对齐 | | 某某某 | 某某某 | 某某某 | @@ -237,4 +237,4 @@ end ``` -更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/Markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 3b55d56287ca64e3f8504a6de01d45a305aef90f Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:03:38 +0800 Subject: typo correction --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index f82ebcea..95aef8e2 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -41,7 +41,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 ------------- - + *此文本为斜体。* _此文本也是。_ -- cgit v1.2.3 From ed8da6c3a70e93958d71e0d4ae79f1ae7f1ab114 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:06:11 +0800 Subject: Footnote corrected --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 95aef8e2..d0d84d31 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -237,4 +237,4 @@ end ``` -更多信息, 请见John Gruber 关于语法的官方帖子[此处](http://daringfireball.net/projects/Markdown/syntax)以及 Adam Pritchard 的摘要笔记 [此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet). +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet)。 参见 Adam Pritchard 的摘要笔记。 -- cgit v1.2.3 From 731026a038c7f9322ade73d3b4fee3c22cb84640 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Mon, 7 Jul 2014 17:13:48 +0800 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index d0d84d31..96b0244c 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -237,4 +237,4 @@ end ``` -更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet)。 参见 Adam Pritchard 的摘要笔记。 +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 -- cgit v1.2.3 From d587d9b1c45d545ff9dc7eea99dcb8d649d598f3 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Sat, 26 Jul 2014 01:36:47 +0800 Subject: Changed filename --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 96b0244c..58ef2d6d 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: Markdown.md +filename: Markdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 615ee2794184949591f49ff36b3e58c5e166ed39 Mon Sep 17 00:00:00 2001 From: Kevin Fangzhou Chen Date: Tue, 29 Jul 2014 12:08:24 +0800 Subject: updated the filename into learnmarkdown-cn.md --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 58ef2d6d..975ebcb5 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen"] -filename: Markdown-cn.md +filename: learnmarkdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 0078b03707eeccf50e5bb1d7230e88b4ce3d36be Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Mon, 4 Aug 2014 22:38:53 +0200 Subject: Array initialization disambiguation - fixes #257 simply added proposed comment, which seems fine --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index a1be08af..6c4d88bd 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -92,7 +92,8 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. + a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three + //elements, with values 3,1, and 5 // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. -- cgit v1.2.3 From c0d49cdb88a41ecea12cc98ca8ee04956b9c0d7b Mon Sep 17 00:00:00 2001 From: Jean-Christophe Bohin Date: Thu, 7 Aug 2014 22:37:52 +0200 Subject: Fixing missing space and dot. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 6c4d88bd..5247ecf8 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -93,7 +93,7 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three - //elements, with values 3,1, and 5 + // elements, with values 3, 1, and 5. // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. -- cgit v1.2.3 From b249363a998d08aff750d2722370e648c59cf70f Mon Sep 17 00:00:00 2001 From: Dzianis Dashkevich Date: Tue, 19 Aug 2014 12:06:52 +0300 Subject: Make style fixes to conform to ruby style guide Made style fixes to conform to Ruby style guide. Added a reference to a community-driven Ruby coding style guide. --- ruby.html.markdown | 102 ++++++++++++++++++++++++++--------------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 962853a2..3c67de2e 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Nick LaMuro", "https://github.com/NickLaMuro"] - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] --- @@ -35,7 +36,7 @@ You shouldn't either 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -2 ** 5 #=> 32 +2**5 #=> 32 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -78,14 +79,17 @@ false.class #=> FalseClass 'I am a string'.class #=> String "I am a string too".class #=> String -placeholder = "use string interpolation" +placeholder = 'use string interpolation' "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +# Prefer single quoted strings to double quoted ones where possible +# Double quoted strings perform additional inner calculations + # Combine strings, but not with numbers -"hello " + "world" #=> "hello world" -"hello " + 3 #=> TypeError: can't convert Fixnum into String -"hello " + 3.to_s #=> "hello 3" +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" # print to the output puts "I'm printing!" @@ -130,7 +134,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can contain different types of items -[1, "hello", false] #=> [1, "hello", false] +[1, 'hello', false] #=> [1, "hello", false] # Arrays can be indexed # From the front @@ -157,7 +161,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: -hash = {'color' => 'green', 'number' => 5} +hash = { 'color' => 'green', 'number' => 5 } hash.keys #=> ['color', 'number'] @@ -170,7 +174,7 @@ hash['nothing here'] #=> nil # Since Ruby 1.9, there's a special syntax when using symbols as keys: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] @@ -180,11 +184,11 @@ new_hash.keys #=> [:defcon, :action] # Control structures if true - "if statement" + 'if statement' elsif false - "else if, optional" + 'else if, optional' else - "else, also optional" + 'else, also optional' end for counter in 1..5 @@ -216,7 +220,7 @@ end #=> iteration 5 # You can also surround blocks in curly brackets: -(1..5).each {|counter| puts "iteration #{counter}"} +(1..5).each { |counter| puts "iteration #{counter}" } # The contents of data structures can also be iterated using each. array.each do |element| @@ -241,32 +245,30 @@ grade = 'B' case grade when 'A' - puts "Way to go kiddo" + puts 'Way to go kiddo' when 'B' - puts "Better luck next time" + puts 'Better luck next time' when 'C' - puts "You can do better" + puts 'You can do better' when 'D' - puts "Scraping through" + puts 'Scraping through' when 'F' - puts "You failed!" + puts 'You failed!' else - puts "Alternative grading system, eh?" + puts 'Alternative grading system, eh?' end - #=> "Better luck next time" # cases can also use ranges grade = 82 case grade - when 90..100 - puts "Hooray!" - when 80...90 - puts "OK job" - else - puts "You failed!" +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' end - #=> "OK job" @@ -284,23 +286,23 @@ double 3 #=> 6 double double 3 #=> 12 -def sum(x,y) +def sum(x, y) x + y end # Method arguments are separated by a comma sum 3, 4 #=> 7 -sum sum(3,4), 5 #=> 12 +sum sum(3, 4), 5 #=> 12 # yield # All methods have an implicit, optional block parameter # it can be called with the 'yield' keyword def surround - puts "{" + puts '{' yield - puts "}" + puts '}' end surround { puts 'hello world' } @@ -311,25 +313,25 @@ surround { puts 'hello world' } # You can pass a block to a function -# "&" marks a reference to a passed block +# "&" marks a reference to a passed block def guests(&block) - block.call "some_argument" + block.call 'some_argument' end - + # You can pass a list of arguments, which will be converted into an array -# That's what splat operator ("*") is for +# That's what splat operator ("*") is for def guests(*array) - array.each { |guest| puts "#{guest}" } + array.each { |guest| puts guest } end # Define a class with the class keyword class Human # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" + @@species = 'H. sapiens' # Basic initializer - def initialize(name, age=0) + def initialize(name, age = 0) # Assign the argument to the "name" instance variable for the instance @name = name # If no age given, we will fall back to the default in the arguments list. @@ -356,20 +358,19 @@ class Human # A class method uses self to distinguish from instance methods. # It can only be called on the class, not an instance. def self.say(msg) - puts "#{msg}" + puts msg end def species @@species end - end # Instantiate a class -jim = Human.new("Jim Halpert") +jim = Human.new('Jim Halpert') -dwight = Human.new("Dwight K. Schrute") +dwight = Human.new('Dwight K. Schrute') # Let's call a couple of methods jim.species #=> "H. sapiens" @@ -380,7 +381,7 @@ dwight.species #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" # Call the class method -Human.say("Hi") #=> "Hi" +Human.say('Hi') #=> "Hi" # Variable's scopes are defined by the way we name them. # Variables that start with $ have global scope @@ -399,7 +400,7 @@ defined? @@var #=> "class variable" Var = "I'm a constant" defined? Var #=> "constant" -# Class also is object in ruby. So class can have instance variables. +# Class is also an object in ruby. So class can have instance variables. # Class variable is shared among the class and all of its descendants. # base class @@ -415,7 +416,7 @@ class Human end end -# derived class +# derived class class Worker < Human end @@ -451,8 +452,8 @@ module ModuleExample end end -# Including modules binds the methods to the object instance -# Extending modules binds the methods to the class instance +# Including modules binds their methods to the class instances +# Extending modules binds their methods to the class itself class Person include ModuleExample @@ -467,7 +468,7 @@ Person.new.foo # => 'foo' Book.foo # => 'foo' Book.new.foo # => NoMethodError: undefined method `foo' -# Callbacks when including and extending a module are executed +# Callbacks are executed when including and extending a module module ConcernExample def self.included(base) @@ -500,9 +501,8 @@ Something.new.qux # => 'qux' ## Additional resources -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - - +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From ddd4db06cabe4371b5cf6802b70995ac3b4a4db6 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 02:01:40 +0200 Subject: Added French translation for Javascript --- fr-fr/javascript-fr.html.markdown | 508 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 508 insertions(+) create mode 100644 fr-fr/javascript-fr.html.markdown diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown new file mode 100644 index 00000000..598fb6af --- /dev/null +++ b/fr-fr/javascript-fr.html.markdown @@ -0,0 +1,508 @@ +--- +language: javascript +contributors: + - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Ariel Krakowski', 'http://www.learneroo.com'] +filename: javascript-fr.js +translators: + - ['@nbrugneaux', 'https://nicolasbrugneaux.me'] +lang: fr-fr +--- + +JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. +Le langage avait à l'origine pour but d'être un langage de scripting simple +pour les sites web, complétant le Java pour des applications web complexes. Mais +son intégration très proche et simple des pages web, ainsi que le support natif +des navigateurs a rendu le JavaScript incontournable aujourd'hui tant bien dans +le front-end que dans le back-end. + +En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à +Node.JS, un projet qui offre un environnement indépendant dans lequel un +interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome, +peut être utilisé directement côté serveur pour exécuter des programmes écrits +en JavaScript. + +```js +// Les commentaires sont comme en C. Les commentaires en ligne commencent par 2 slashs, +/* et les commentaires sur plusieurs lignes commencent avec slash-étoile + et finissent avec étoile-slash */ + +// Toutes les expressions peuvent finir par ; +doStuff(); + +// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés +// lors de l’interprétation aux sauts de ligne, sauf exceptions +doStuff() + +// Parce que ces cas peuvent produire des effets inattendus, nous utiliserons +// des point-virgules dans ce guide. + +/////////////////////////////////// +// 1. Nombres, Chaines de caractères et Opérateurs + +// JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux)) +// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers): les +// doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à +// 9 x 10¹⁵ exactement. +3; // = 3 +1.5; // = 1.5 + +// L'arithmétique de base fonctionne comme vous vous y attendriez +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Ainsi que les divisions non-entières +5 / 2; // = 2.5 + +// Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération +// bits à bits , votre nombre décimal est converti en entier *jusqu'à* 32 bits. +1 << 2; // = 4 + +// Comme en mathématiques, la priorité est donnée aux parenthèses. +(1 + 3) * 2; // = 8 + +// Il existe 3 valeurs spéciales pour les nombres: +Infinity; // le résultat de 1/0 par exemple +-Infinity; // le résultat de -1/0 par exemple +NaN; // le résultat de 0/0 par exemple + +// Il existe également le type booléen. +true; // vrai +false; // faux + +// Les chaines de caractères (strings) sont crées avec ' ou ' indifféremment, la seule +// raison de choisir l'un ou l'autre est la consistance dans votre code. +'abc'; +'Hello, world'; + +// La négation utilise le symbole ! +!true; // = false +!false; // = true + +// L'égalité est === ou == +// === compare la valeur exacte 2 === '2' // = false +// == convertit la valeur pour comparer 2 === '2' // = true +// En général, il vaut mieux utiliser === pour ne pas faire d'erreurs. +1 === 1; // = true +2 === 1; // = false + +// L'inégalité est !== ou !=, basé sur le même principe qu'avant. +1 !== 1; // = false +2 !== 1; // = true + +// Plus de comparaisons: +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Les strings se concatènent avec + +'Hello ' + 'world!'; // = 'Hello world!' + +// et peuvent être comparées avec < et > +'a' < 'b'; // = true + +// Vous pouvez accéder les caractères dans une string avec charAt +'This is a string'.charAt(0); // = 'T' + +// .. ou utiliser substring pour avoir un plus gros morceau +'Hello world'.substring(0, 5); // = 'Hello' + +// la longueur, length, est une propriété, donc n'utilisez pas de () +'Hello'.length; // = 5 + +// Il y a également null et undefined +null; // utilisé pour une non-valeur +undefined; // utilisé pour une valeur actuellement non présente (cependant, + // undefined est aussi une valeur valide) + +// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste +// est 'presque-vrai' (truthy) +// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0') + + +/////////////////////////////////// +// 2. Variables, Tableaux et Objets + +// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est +// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =. +var someVar = 5; + +// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict) +someOtherVar = 10; + +// ... mais la variable sera crée dans l’environnement global, et non l’environnement +// local dans lequel vous l'avez défini. + +// Les variables déclarées et non assignées sont undefined par défaut +var someThirdVar; +var someThirdVar = undefined; + +// ... sont deux déclarations identiques. + +// Il y a des raccourcis pour les opérations mathématiques: +someVar += 5; // équivalent pour someVar = someVar + 5; +someVar *= 10; // de même, someVar = someVar * 100; +someVar++; // = someVar += 1; +someVar--; // = someVar -= 1; + +// Les tableaux (Arrays) sont des listes ordonnées de valeurs, de tous types. +var myArray = ['Hello', 45, true]; + +// Leurs membres peuvent être accédés en utilisant les crochets +// Les indices commencent à 0. +myArray[1]; // = 45 + +// Les tableaux sont modifiables, ainsi que leurs longueurs +myArray.push( 'World' ); +myArray.length; // = 4 + +// Ajout/Modification à un index spécifique +myArray[3] = 'Hello'; + +// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres +// langages: ils sont une liste non-ordonnée de paires clé-valeur. +var myObj = {key1: 'Hello', key2: 'World'}; + +// Les clés sont des strings, mais les ' ou " sont optionels si elles sont des +// noms valides en JavaScript. Les valeurs peuvent être de n'importe quel type. +var myObj = {myKey: 'myValue', 'my other key': 4}; + +// Les attributs d'objets peuvent être accédés avec les crochets +myObj['my other key']; // = 4 + +// .. ou avec un point si la clé est un identifiant valide. +myObj.myKey; // = 'myValue' + +// Les objets sont eux aussi modifiables. +myObj.myThirdKey = true; + +// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logique et structures de contrôle + +// La syntaxe de cette section est identique au Java. + +// Les si (if) fonctionnent comme vous vous y attendez. +var count = 1; +if (count === 3) { + // seulement quand count est 3 +} +else if (count === 4) { + // uniquement quand count est 4 +} +else { + // le reste du temps, si ni 3, ni 4. +} + +// De même pour while. +while (true) { + // Une boucle infinie ! +} + +// Les boucles do-while sont pareilles, mais sont exécutées au moins une fois. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// La boucle for est la même qu'en C ou en Java: +// initialisation; condition pour continuer; itération +for (var i = 0; i < 5; i++){ + // sera exécutée 5 fois +} + +// && est le "et" logique, || est le "ou" logique +if (house.size === 'big' && house.colour === 'blue'){ + house.contains = 'bear'; +} +if (colour === 'red' || colour === 'blue'){ + // colour est soit 'red' soit 'blue' +} + +// Les raccourcis && et || sont pratiques pour instancier des valeurs par defaut. +var name = otherName || 'default'; + +// Ceci est l'équivalent de +var name = otherName; +if (!name){ + name = 'default'; +} + +// Le switch vérifie les égalités avec === +// utilisez un "break" à la fin de chaque cas +// ou les cas suivants seront eux aussi exécutés +grade = 'B'; +switch (grade) { + case 'A': + console.log('Great job'); + break; + case 'B': + console.log('OK job'); + break; + case 'C': + console.log('You can do better'); + break; + default: + console.log('Oy vey'); + break; +} + + +/////////////////////////////////// +// 4. Fonctions, Scope (Environnement) et Closures + +// Les fonctions sont déclarées avec le mot clé function +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction('foo'); // = 'FOO' + +// Les fonctions JavaScript sont des objets de première classe, donc peuvent +// être réassignées à d'autres variables et passées en tant que paramètres pour +// d'autres fonctions +function myFunction(){ + // ce code s'exécutera dans 5 secondes +} +setTimeout(myFunction, 5000); +// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi +// que Node.js le rendent disponible + +// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être +// anonymes +setTimeout(function(){ + // ce code s'exécutera dans 5 secondes +}, 5000); + +// Le Javascript crée uniquement un scope dans les fonctions, pas dans les +// autres blocs. +if (true){ + var i = 5; +} +i; // = 5 - et non undefined comme vous pourriez vous y attendre + +// Cela a mené à un style comment de fonctions anonymes immédiatement exécutée; +// ou "immediately-executing anonymous functions" +(function(){ + var temporary = 5; + // Nous pouvons accéder au scope global en assignant à l'objet global, + // qui dans les navigateurs est "window". Il est différent dans Node.js. + window.permanent = 10; +})(); +// Cela permet de ne pas avoir de fuites de variables qui polluent +// l’environnement global. +temporary; // raises ReferenceError +permanent; // = 10 + +// Une des particularité les plus puissantes de Javascript est le système de +// closures. Si une fonction est définie dans une autre fonction, alors la +// fonction interne aura accès aux variables de la fonction parente, même si +// celle-ci a déjà finie son exécution. +function sayHelloInFiveSeconds(name){ + var prompt = 'Hello, ' + name + '!'; + // Fonction interne + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchrone, donc la fonction sayHelloInFiveSeconds quittera + // immédiatement, et setTimeout appelera inner après. +} +sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec + +/////////////////////////////////// +// 5. Encore plus à propos des Objets; Constructeurs and Prototypes + +// Les objets peuvent contenir des fonctions. +var myObj = { + myFunc: function(){ + return 'Hello world!'; + } +}; +myObj.myFunc(); // = 'Hello world!' + +// Lorsqu'une fonction attachée à un objet est appelée, elle peut accéder à +// l'objet avec le mot clé this. +myObj = { + myString: 'Hello world!', + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = 'Hello world!' + +// LA valeur de "this" change de par l'endroit où la fonction est appelée, et +// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle +// est appelée hors du contexte l'objet. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// A l'inverse, une fonction peut être attachée à un objet et y gagner l'accès +// au travers de "this" +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} + +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = 'HELLO WORLD!' + +// Nous pouvons aussi spécifier un contexte pour une fonction quand elle est +// appelée grâce à "call" ou "apply". +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, ' And Hello Moon!'); // = 'Hello World! And Hello Moon!' + +// 'apply' est presque identique, mais prend un tableau comme liste d’arguments. + +anotherFunc.apply(myObj, [' And Hello Sun!']); // = 'Hello World! And Hello Sun!' + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Mais, "call" and "apply" sont temporaires. Pour lier le contexte de façon +// permanente, nous pouvons utiliser "bind" +var boundFunc = anotherFunc.bind(myObj); +boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!' + +// "bind" peut aussi être utilisé pour créer une application partielle de la +// fonction (curry) +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est +// crée et mis à disposition de la fonction via "this". Ces fonctions sont +// communément appelées constructeurs. +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à +// une propriété que n'a pas l'objet, l'interpréteur regarder son prototype. + +// Quelque implémentations de JS vous laissent accéder au prototype avec la +// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard +// et ne fonctionne pas dans les navigateurs actuels. +var myObj = { + myString: 'Hello world!' +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 +myObj.myFunc(); // = 'hello world!' + +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Il n'y a pas de copie ici. Chacun des objets stocke une référence à son +// prototype. Cela veut dire que l'on peut le modifier et cela se répercutera +// partout. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être +// utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype +// donné. + +// Le premier est Object.create, mais c'est assez récent et risque de ne pas +// fonctionner dans tous les navigateurs. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Le deuxième moyen, qui marche partout, fonctionne avec les constructeurs. +// Les constructeurs ont un propriété appelée prototype. Ce n'est *pas* le +// prototype du constructeur de la fonction elle-même, c'est le prototype que +// les nouveaux objets crées grâce à ce constructeur avec "new" auront. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Les types pré-définis tels que les strings ou nombres ont aussi des +// constructeurs +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// ... mais ils ne sont pas exactement équivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // 0 est falsy, le code ne fonctionnera pas. +} +if (Number(0)){ + // Parce que Number(0) est truthy, le code fonctionnera +} + +// Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à +// cette particularité. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +'abc'.firstCharacter(); // = 'a' + +// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles +// fonctionnalités de JavaScript dans de plus anciens environnements, tels que +// les vieux navigateurs. + +//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à +// ce polyfill +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} + +## Pour aller plus loin (en anglais) + +The [Mozilla Developer +Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une +excellente documentation pour le Javascript dans les navigateurs. Et contient +également un wiki pour s'entraider. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +recouvre les principaux sujets vus ici. Le guide est délibérément uniquement +à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous +plutôt ici : +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +un guide pour vous éviter les faux-amis dans le JavaScript. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire. + +En addition aux contributeurs de cet article, du contenu provient du +"Python tutorial" de Louie Dinh, et de [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +sur le réseau Mozilla. -- cgit v1.2.3 From 1d4e0929ff82d7205b09da2f30b37541464dc029 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 02:03:01 +0200 Subject: Update javascript-fr.html.markdown --- fr-fr/javascript-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 598fb6af..1dc4f8db 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -479,6 +479,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists return new Constructor(); } } +``` ## Pour aller plus loin (en anglais) -- cgit v1.2.3 From 1421ef08f5aa7de56a413753d9017693d3b44187 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 10:12:21 +0200 Subject: Updated the part that I forgot to translate. --- fr-fr/javascript-fr.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 1dc4f8db..55f7858c 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -37,6 +37,7 @@ doStuff() // Parce que ces cas peuvent produire des effets inattendus, nous utiliserons // des point-virgules dans ce guide. + /////////////////////////////////// // 1. Nombres, Chaines de caractères et Opérateurs @@ -182,6 +183,7 @@ myObj.myThirdKey = true; // Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined myObj.myFourthKey; // = undefined + /////////////////////////////////// // 3. Logique et structures de contrôle @@ -314,6 +316,7 @@ function sayHelloInFiveSeconds(name){ } sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec + /////////////////////////////////// // 5. Encore plus à propos des Objets; Constructeurs and Prototypes @@ -470,12 +473,12 @@ String.prototype.firstCharacter = function(){ //Par exemple, Object.create est assez récent, mais peut être implémenté grâce à // ce polyfill -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà Object.create = function(proto){ - // make a temporary constructor with the right prototype + // créer un constructeur temporaire avec le bon prototype var Constructor = function(){}; Constructor.prototype = proto; - // then use it to create a new, appropriately-prototyped object + // puis on utilise "new" pour créer un object avec ce prototype return new Constructor(); } } -- cgit v1.2.3 From f6367016949df3576e9cce4b96148da1f867464c Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 12:10:15 +0200 Subject: =?UTF-8?q?Translatated=20strings=20to=20"chaines=20de=20caract?= =?UTF-8?q?=C3=A8res"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/javascript-fr.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 55f7858c..9e69a038 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -73,9 +73,9 @@ NaN; // le résultat de 0/0 par exemple true; // vrai false; // faux -// Les chaines de caractères (strings) sont crées avec ' ou ' indifféremment, la seule +// Les chaines de caractères (strings) sont crées avec " ou ' indifféremment, la seule // raison de choisir l'un ou l'autre est la consistance dans votre code. -'abc'; +"abc"; 'Hello, world'; // La négation utilise le symbole ! @@ -99,10 +99,10 @@ false; // faux 2 <= 2; // = true 2 >= 2; // = true -// Les strings se concatènent avec + +// Les chaines de caractères se concatènent avec + 'Hello ' + 'world!'; // = 'Hello world!' -// et peuvent être comparées avec < et > +// et peuvent être comparées alphabétiquement avec < et > 'a' < 'b'; // = true // Vous pouvez accéder les caractères dans une string avec charAt @@ -475,10 +475,10 @@ String.prototype.firstCharacter = function(){ // ce polyfill if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà Object.create = function(proto){ - // créer un constructeur temporaire avec le bon prototype + // on crée un constructeur temporaire avec le bon prototype var Constructor = function(){}; Constructor.prototype = proto; - // puis on utilise "new" pour créer un object avec ce prototype + // puis on utilise "new" pour créer un object avec ce même prototype return new Constructor(); } } -- cgit v1.2.3 From 7367cd9ae801bf0b8fdcef0ab57212e23057869b Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:08:18 +0200 Subject: Updated according to the review. --- fr-fr/javascript-fr.html.markdown | 64 +++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 9e69a038..21c8b5ae 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -11,10 +11,11 @@ lang: fr-fr JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. Le langage avait à l'origine pour but d'être un langage de scripting simple -pour les sites web, complétant le Java pour des applications web complexes. Mais -son intégration très proche et simple des pages web, ainsi que le support natif -des navigateurs a rendu le JavaScript incontournable aujourd'hui tant bien dans -le front-end que dans le back-end. +pour les sites web, complétant le Java (à ne pas confondre avec JavaScript) +pour des applications web complexes. Mais son intégration très proche et +simple des pages web, ainsi que le support natif des navigateurs a rendu +le JavaScript incontournable aujourd'hui tant bien dans le front-end que +dans le back-end. En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à Node.JS, un projet qui offre un environnement indépendant dans lequel un @@ -23,7 +24,7 @@ peut être utilisé directement côté serveur pour exécuter des programmes éc en JavaScript. ```js -// Les commentaires sont comme en C. Les commentaires en ligne commencent par 2 slashs, +// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs, /* et les commentaires sur plusieurs lignes commencent avec slash-étoile et finissent avec étoile-slash */ @@ -42,7 +43,7 @@ doStuff() // 1. Nombres, Chaines de caractères et Opérateurs // JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux)) -// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers): les +// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers) : les // doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à // 9 x 10¹⁵ exactement. 3; // = 3 @@ -58,7 +59,7 @@ doStuff() 5 / 2; // = 2.5 // Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération -// bits à bits , votre nombre décimal est converti en entier *jusqu'à* 32 bits. +// bits à bits, votre nombre décimal est converti en entier *jusqu'à* 32 bits. 1 << 2; // = 4 // Comme en mathématiques, la priorité est donnée aux parenthèses. @@ -73,8 +74,8 @@ NaN; // le résultat de 0/0 par exemple true; // vrai false; // faux -// Les chaines de caractères (strings) sont crées avec " ou ' indifféremment, la seule -// raison de choisir l'un ou l'autre est la consistance dans votre code. +// Les chaines de caractères (strings) sont créees avec " ou ' indifféremment, la seule +// raison de choisir l'un ou l'autre est la cohérence dans votre code. "abc"; 'Hello, world'; @@ -85,7 +86,7 @@ false; // faux // L'égalité est === ou == // === compare la valeur exacte 2 === '2' // = false // == convertit la valeur pour comparer 2 === '2' // = true -// En général, il vaut mieux utiliser === pour ne pas faire d'erreurs. +// En général, il vaut mieux utiliser === pour ne pas faire d'erreur. 1 === 1; // = true 2 === 1; // = false @@ -93,7 +94,7 @@ false; // faux 1 !== 1; // = false 2 !== 1; // = true -// Plus de comparaisons: +// Plus de comparaisons : 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true @@ -108,7 +109,7 @@ false; // faux // Vous pouvez accéder les caractères dans une string avec charAt 'This is a string'.charAt(0); // = 'T' -// .. ou utiliser substring pour avoir un plus gros morceau +// ... ou utiliser substring pour avoir un plus gros morceau 'Hello world'.substring(0, 5); // = 'Hello' // la longueur, length, est une propriété, donc n'utilisez pas de () @@ -164,7 +165,7 @@ myArray.length; // = 4 myArray[3] = 'Hello'; // Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres -// langages: ils sont une liste non-ordonnée de paires clé-valeur. +// langages : ils sont une liste non-ordonnée de paires clé-valeur. var myObj = {key1: 'Hello', key2: 'World'}; // Les clés sont des strings, mais les ' ou " sont optionels si elles sont des @@ -187,8 +188,6 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logique et structures de contrôle -// La syntaxe de cette section est identique au Java. - // Les si (if) fonctionnent comme vous vous y attendez. var count = 1; if (count === 3) { @@ -287,12 +286,14 @@ if (true){ } i; // = 5 - et non undefined comme vous pourriez vous y attendre -// Cela a mené à un style comment de fonctions anonymes immédiatement exécutée; +// Cela a mené à un style commun de fonctions anonymes immédiatement exécutée; // ou "immediately-executing anonymous functions" (function(){ var temporary = 5; // Nous pouvons accéder au scope global en assignant à l'objet global, - // qui dans les navigateurs est "window". Il est différent dans Node.js. + // qui dans les navigateurs est "window". Il est différent dans Node.js, + // le scope global sera en fait local au module dans lequel vous + // vous trouvez. http://nodejs.org/api/globals.html window.permanent = 10; })(); // Cela permet de ne pas avoir de fuites de variables qui polluent @@ -300,7 +301,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre temporary; // raises ReferenceError permanent; // = 10 -// Une des particularité les plus puissantes de Javascript est le système de +// Une des fonctionnalités les plus puissantes de Javascript est le système de // closures. Si une fonction est définie dans une autre fonction, alors la // fonction interne aura accès aux variables de la fonction parente, même si // celle-ci a déjà finie son exécution. @@ -338,7 +339,7 @@ myObj = { }; myObj.myFunc(); // = 'Hello world!' -// LA valeur de "this" change de par l'endroit où la fonction est appelée, et +// La valeur de "this" change de par l'endroit où la fonction est appelée, et // non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle // est appelée hors du contexte l'objet. var myFunc = myObj.myFunc; @@ -353,8 +354,9 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = 'HELLO WORLD!' -// Nous pouvons aussi spécifier un contexte pour une fonction quand elle est -// appelée grâce à "call" ou "apply". +// Le contexte correspond à la valeur de "this". +// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this, +// pour une fonction quand elle est appelée grâce à "call" ou "apply". var anotherFunc = function(s){ return this.myString + s; } @@ -368,8 +370,9 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Mais, "call" and "apply" sont temporaires. Pour lier le contexte de façon -// permanente, nous pouvons utiliser "bind" +// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la +// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser +// "bind" pour garder une référence à la fonction avec ce "this". var boundFunc = anotherFunc.bind(myObj); boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!' @@ -389,11 +392,11 @@ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 // Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à -// une propriété que n'a pas l'objet, l'interpréteur regarder son prototype. +// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype. -// Quelque implémentations de JS vous laissent accéder au prototype avec la +// Quelques implémentations de JS vous laissent accéder au prototype avec la // propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard -// et ne fonctionne pas dans les navigateurs actuels. +// et ne fonctionne pas dans certains des navigateurs actuels. var myObj = { myString: 'Hello world!' }; @@ -413,12 +416,21 @@ myPrototype.__proto__ = { }; myObj.myBoolean; // = true + +// Pour obtenir le prototype il existe également Object.getPrototypeOf +Object.getPrototypeOf( myObj ) // = {meaningOfLife: 42, myFunc: function} + // Il n'y a pas de copie ici. Chacun des objets stocke une référence à son // prototype. Cela veut dire que l'on peut le modifier et cela se répercutera // partout. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change +// pas la chaine prototypale. +myObj.lonelyProperty = true; +myPrototype.lonelyProperty; // = undefined + // Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être // utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype // donné. -- cgit v1.2.3 From 210d9eba8df66ac7298d4bdea386428fe1a1009f Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:13:53 +0200 Subject: better example. --- fr-fr/javascript-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 21c8b5ae..dd12d89f 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -428,8 +428,8 @@ myObj.meaningOfLife; // = 43 // L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change // pas la chaine prototypale. -myObj.lonelyProperty = true; -myPrototype.lonelyProperty; // = undefined +myObj.meaningOfLife = 42; +myPrototype.meaningOfLife; // = 43 // Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être // utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype -- cgit v1.2.3 From ffd5e7e149cf1da87abce5e56cdf32626eede22a Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 19:39:19 +0200 Subject: Typo --- fr-fr/javascript-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index dd12d89f..e15f70a3 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -9,7 +9,7 @@ translators: lang: fr-fr --- -JavaScript a été crée par Brendan Eich, travaillant alors a Netscape, en 1995. +JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995. Le langage avait à l'origine pour but d'être un langage de scripting simple pour les sites web, complétant le Java (à ne pas confondre avec JavaScript) pour des applications web complexes. Mais son intégration très proche et -- cgit v1.2.3 From d15c9674a9005b544427c206424cc900bda48106 Mon Sep 17 00:00:00 2001 From: Nicolas Brugneaux Date: Wed, 20 Aug 2014 20:57:40 +0200 Subject: Updated scope part. --- fr-fr/javascript-fr.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index e15f70a3..2e18d0be 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -135,8 +135,9 @@ var someVar = 5; // si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict) someOtherVar = 10; -// ... mais la variable sera crée dans l’environnement global, et non l’environnement -// local dans lequel vous l'avez défini. +// ... mais la variable aura une portée globale (plus communément trouvé en tant +// que "global scope" en anglais), et non pas une portée limitée à la fonction +// dans laquelle vous l'aviez définie. // Les variables déclarées et non assignées sont undefined par défaut var someThirdVar; @@ -279,8 +280,8 @@ setTimeout(function(){ // ce code s'exécutera dans 5 secondes }, 5000); -// Le Javascript crée uniquement un scope dans les fonctions, pas dans les -// autres blocs. +// Le Javascript crée uniquement un scope, une portée d'action limitée, pour +// les fonctions, et pas dans les autres blocs. if (true){ var i = 5; } -- cgit v1.2.3 From 328a4f1babe167e94858b92faaa9caa19aa8aade Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 23 Aug 2014 22:48:10 -0500 Subject: - add more examples; update examples - now runs in the Xcode 6 b6 playground - add MARK sections --- swift.html.markdown | 206 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 135 insertions(+), 71 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..5ba160b8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,6 +2,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] filename: learnswift.swift --- @@ -11,21 +12,34 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre ```js // -// Basics +// MARK: Basics // println("Hello, world") + var myVariable = 42 +//let fƒ∆ = "value" // unicode in variable names let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(myConstant)" // String interpolation var optionalString: String? = "optional" // Can be nil optionalString = nil +/* +Comment here + /* + Nested comment here + */ +*/ // -// Arrays and Dictionaries +// MARK: Collections // // Array @@ -35,65 +49,66 @@ let emptyArray = [String]() // Dictionary var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() // -// Control Flow +// MARK: Control Flow // // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + println("One!") + } else { + println("Not one!") + } } // for loop (dictionary) +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + println("\(key): \(value)") } // for loop (range) for i in -1...1 { // [-1, 0, 1] - println(i) + println(i) } // use ..< to exclude the last number // while loop var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while loop do { - println("hello") + println("hello") } while 1 == 2 // Switch let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." + let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" + let vegetableComment = "Is it a spicy \(x)?" default: // required (in order to cover all possible input) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "Everything tastes good in soup." } // -// Functions +// MARK: Functions // // Functions are a first-class type, meaning they can be nested @@ -101,31 +116,31 @@ default: // required (in order to cover all possible input) // Function func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) + return (3.59, 3.69, 3.79) } -// Args +// Variadic Args func setup(numbers: Int...) {} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) // -// Closures +// MARK: Closures // var numbers = [1, 2, 6] @@ -135,93 +150,142 @@ var numbers = [1, 2, 6] // `->` separates the arguments and return type // `in` separates the closure header from the closure body numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) // When the type is known, like above, we can do this numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this //numbers = numbers.map({ $0 * 3 }) print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] // -// Classes +// MARK: Classes // +class Shape { + func getArea() -> Int { + return 0; + } +} + // All methods and properties of a class are public. // If you just need to store data in a // structured object, you should use a `struct` // A simple class `Square` extends `Shape` class Rect: Shape { - var sideLength: Int = 1 - - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } } - set { - sideLength = newValue / 4 + + // If you don't need a custom getter and setter, + // but still want to run code before and after getting or setting + // a property, you can use `willSet` and `didSet` + var identifier: String = "defaultID" { + willSet(someIdentifier) { + print(someIdentifier) + } } - } - - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } - - func shrink() { - if sideLength > 0 { - --sideLength + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } } - } + + override func getArea() -> Int { + return sideLength * sideLength + } +} - override func getArea() -> Int { - return sideLength * sideLength - } +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` - // -// Enums +// MARK: Enums // // Enums can optionally be of a specific type or on their own. // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } } - } } // -// Other +// MARK: Other // // `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +protocol ShapeGenerator { + func buildShape() -> Shape +} + +// `extension`s: Add extra functionality to an already existing type +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} + ``` -- cgit v1.2.3 From 6b34ef65a3aea7af638145be83c1d3699caa353b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 00:48:54 -0500 Subject: - more examples - add custom operator example --- swift.html.markdown | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 5ba160b8..6ce60cf5 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant)" // String interpolation -var optionalString: String? = "optional" // Can be nil +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation +var optionalString: String? = "optional" // Can be nil optionalString = nil /* @@ -114,7 +114,17 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function +// Function with Swift docs +/** + A greet operation + + - A bullet in docs + - Another bullet in the docs + + :param: name A name + :param: day A day + :returns: A string containing the name and day value. +*/ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } @@ -237,6 +247,11 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 +// compare instances, not the same as == which compares objects (equal to) +if mySquare === mySquare { + println("Yep its mySquare") +} + // // MARK: Enums @@ -276,6 +291,20 @@ extension Square: Printable { println("Square: \(mySquare)") +// You can also extend built-in types +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. @@ -288,4 +317,21 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } + +// Operators: +// Custom operators can start with the characters: +// / = - + * % < > ! & | ^ . ~ +// or +// Unicode math, symbol, arrow, dingbat, and line/box drawing characters. +prefix operator !!! {} + +// An operator that triples the side length when used +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +let bigSquare = !!!mySquare +println(bigSquare.sideLength) + ``` -- cgit v1.2.3 From 2a5a4ebf64593009002053514deb057f37d7b693 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 14:37:09 -0500 Subject: - add landmark notes --- swift.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 6ce60cf5..600eedcf 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -15,6 +15,11 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre // MARK: Basics // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code + println("Hello, world") var myVariable = 42 @@ -114,7 +119,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift docs +// Function with Swift function docs /** A greet operation -- cgit v1.2.3 From b50d4443cdca87e3342e2364c9e6afd2d7fce7d2 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 18:33:16 -0500 Subject: - add more examples; add book link - add link to official Swift book from Apple - add examples of access control and structures - update protocols --- swift.html.markdown | 95 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 14 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 600eedcf..f8fa31fe 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -8,6 +8,8 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```js @@ -23,7 +25,7 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre println("Hello, world") var myVariable = 42 -//let fƒ∆ = "value" // unicode in variable names +let øπΩ = "value" // unicode variable names let myConstant = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon @@ -39,7 +41,7 @@ optionalString = nil /* Comment here /* - Nested comment here + Nested comments are also supported */ */ @@ -119,7 +121,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift function docs +// Function with Swift header docs (format as reStructedText) /** A greet operation @@ -188,12 +190,34 @@ numbers = sorted(numbers, < ) print(numbers) // [3, 6, 18] +// +// MARK: Structures +// + +// Structures and classes have very similar capabilites +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + // // MARK: Classes // -class Shape { - func getArea() -> Int { +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { + public func getArea() -> Int { return 0; } } @@ -203,23 +227,29 @@ class Shape { // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +internal class Rect: Shape { var sideLength: Int = 1 // Custom getter and setter property - var perimeter: Int { + private var perimeter: Int { get { return 4 * sideLength } set { + // `newValue` is an implicit variable available to setters sideLength = newValue / 4 } } + + // Lazily load a property + // subShape remains nil (uninitialized) until getter called + lazy var subShape = Rect(sideLength: 4) // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` var identifier: String = "defaultID" { + // the `willSet` arg will be the variable name for the new value willSet(someIdentifier) { print(someIdentifier) } @@ -254,7 +284,7 @@ print(mySquare.sideLength) // 4 // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep its mySquare") + println("Yep, it's mySquare") } @@ -279,15 +309,47 @@ enum Suit { // -// MARK: Other +// MARK: Protocols // -// `protocol`: Similar to Java interfaces. +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods, +// operators, and subscripts. + protocol ShapeGenerator { + var enabled: Bool { get set } func buildShape() -> Shape } +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} +*/ + +// +// MARK: Other +// + // `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol extension Square: Printable { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" @@ -321,7 +383,8 @@ func findIndex(array: [T], valueToFind: T) -> Int? { } return nil } - +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -330,13 +393,17 @@ func findIndex(array: [T], valueToFind: T) -> Int? { // Unicode math, symbol, arrow, dingbat, and line/box drawing characters. prefix operator !!! {} -// An operator that triples the side length when used +// A prefix operator that triples the side length when used prefix func !!! (inout shape: Square) -> Square { shape.sideLength *= 3 return shape } -let bigSquare = !!!mySquare -println(bigSquare.sideLength) +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 29e602675c6ec91c719bd072e70c81f3c067e5ce Mon Sep 17 00:00:00 2001 From: boston Date: Tue, 2 Sep 2014 11:41:31 +0600 Subject: =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA=20=D1=80?= =?UTF-8?q?=D1=83=D1=81=D1=81=D0=BA=D0=BE=D0=B3=D0=BE=20=D1=8F=D0=B7=D1=8B?= =?UTF-8?q?=D0=BA=D0=B0=20/=20Typo=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Исправлены синтаксические и пунктуационные ошибки русского языка --- ru-ru/go-ru.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 5b9d8ebf..44a22b45 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -13,11 +13,11 @@ lang: ru-ru --- Go - это язык общего назначения, целью которого является удобство, простота, -конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый +конкурентность. Это не тренд в компьютерных науках, а новейший и быстрый способ решать насущные проблемы. Концепции Go схожи с другими императивными статически типизированными языками. -Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции +Быстро компилируется и быстро исполняется, имеет лёгкие в понимании конструкции для создания масштабируемых и многопоточных программ. Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным @@ -57,7 +57,7 @@ func main() { func beyondHello() { var x int // Переменные должны быть объявлены до их использования. x = 3 // Присвоение значения переменной. - // Краткое определение := позволяет объявить перменную с автоматической + // Краткое определение := позволяет объявить переменную с автоматической // подстановкой типа из значения. y := 4 sum, prod := learnMultiple(x, y) // Функция возвращает два значения. @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } -// Некотрые встроенные типы и литералы. +// Некоторые встроенные типы и литералы. func learnTypes() { // Краткое определение переменной говорит само за себя. s := "Learn Go!" // Тип string. @@ -97,7 +97,7 @@ func learnTypes() { // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще. - s3 := []int{4, 5, 9} // Сравните с a3. Тут нет троеточия. + s3 := []int{4, 5, 9} // Сравните с a3, тут нет троеточия. s4 := make([]int, 4) // Выделение памяти для слайса из 4-х int (нули). var d2 [][]float64 // Только объявление, память не выделяется. bs := []byte("a slice") // Синтаксис приведения типов. @@ -113,7 +113,7 @@ func learnTypes() { delete(m, "three") // Встроенная функция, удаляет элемент из map-а. // Неиспользуемые переменные в Go являются ошибкой. - // Нижнее подчеркивание позволяет игнорировать такие переменные. + // Нижнее подчёркивание позволяет игнорировать такие переменные. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной. fmt.Println(s, c, a4, s3, d2, m) @@ -121,16 +121,16 @@ func learnTypes() { learnFlowControl() // Идем дальше. } -// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики +// У Go есть полноценный сборщик мусора. В нем есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя. func learnMemory() (p, q *int) { // Именованные возвращаемые значения p и q являются указателями на int. p = new(int) // Встроенная функция new выделяет память. - // Выделенный int проинициализирован нулем, p больше не содержит nil. + // Выделенный int проинициализирован нулём, p больше не содержит nil. s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов. s[3] = 7 // Присвоить значение одному из них. - r := -2 // Определить еще одну локальную переменную. + r := -2 // Определить ещё одну локальную переменную. return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной. } @@ -139,7 +139,7 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // If-ы всегда требуют наличине фигурных скобок, но не круглых. + // If-ы всегда требуют наличие фигурных скобок, но не круглых. if true { fmt.Println("told ya") } @@ -178,7 +178,7 @@ func learnFlowControl() { } // Функции являются замыканиями. xBig := func() bool { - return x > 10000 // Ссылается на x, объявленый выше switch. + return x > 10000 // Ссылается на x, объявленный выше switch. } fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10). x = 1.3e3 // Тут х == 1300 @@ -189,7 +189,7 @@ func learnFlowControl() { love: learnDefer() // Быстрый обзор важного ключевого слова. - learnInterfaces() // О! Интерфейсы, идем далее. + learnInterfaces() // О! Интерфейсы, идём далее. } func learnDefer() (ok bool) { @@ -214,7 +214,7 @@ type pair struct { // Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer. func (p pair) String() string { // p в данном случае называют receiver-ом. - // Sprintf – еще одна функция из пакета fmt. + // Sprintf – ещё одна функция из пакета fmt. // Обращение к полям p через точку. return fmt.Sprintf("(%d, %d)", p.x, p.y) } @@ -234,7 +234,7 @@ func learnInterfaces() { fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String. fmt.Println(i) // Вывод такой же, что и выше. - learnVariadicParams("Учиться", "учиться", "и еще раз учиться!") + learnVariadicParams("Учиться", "учиться", "и ещё раз учиться!") } // Функции могут иметь варьируемое количество параметров. @@ -263,22 +263,22 @@ func learnErrorHandling() { // выведет "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } - // Мы еще обратимся к интерфейсам чуть позже, а пока... + // Мы ещё обратимся к интерфейсам чуть позже, а пока... learnConcurrency() } -// c – это тип данных channel (канал), объект для конкуррентного взаимодействия. +// c – это тип данных channel (канал), объект для конкурентного взаимодействия. func inc(i int, c chan int) { c <- i + 1 // когда channel слева, <- являтся оператором "отправки". } -// Будем использовать функцию inc для конкуррентной инкрементации чисел. +// Будем использовать функцию inc для конкурентной инкрементации чисел. func learnConcurrency() { // Тот же make, что и в случае со slice. Он предназначен для выделения // памяти и инициализации типов slice, map и channel. c := make(chan int) - // Старт трех конкуррентных goroutine. Числа будут инкрементированы - // конкуррентно и, может быть параллельно, если машина правильно + // Старт трех конкурентных goroutine. Числа будут инкрементированы + // конкурентно и, может быть параллельно, если машина правильно // сконфигурирована и позволяет это делать. Все они будут отправлены в один // и тот же канал. go inc(0, c) // go начинает новую горутину. @@ -291,7 +291,7 @@ func learnConcurrency() { cs := make(chan string) // другой канал, содержит строки. cc := make(chan chan string) // канал каналов со строками. go func() { c <- 84 }() // пуск новой горутины для отправки значения - go func() { cs <- "wordy" }() // еще раз, теперь для cs + go func() { cs <- "wordy" }() // ещё раз, теперь для cs // Select тоже что и switch, но работает с каналами. Он случайно выбирает // готовый для взаимодействия канал. select { @@ -327,7 +327,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { Основа всех основ в Go это [официальный веб сайт](http://golang.org/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать -объемную документацию. +объёмную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она -- cgit v1.2.3 From 7d52148acf1ca5228e7882769345bc4da36c787f Mon Sep 17 00:00:00 2001 From: Ben Eysenbach Date: Wed, 3 Sep 2014 20:33:55 -0400 Subject: Matlab syntax error --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index d9a82890..9dae8ef2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas % Logicals can be applied to matrices: A > 5 % for each element, if condition is true, that element is 1 in returned matrix -A[ A > 5 ] +A( A > 5 ) % returns a vector containing the elements in A for which condition is true % Strings -- cgit v1.2.3 From c0c77e850c051a28afafcd1e71710c4eebebcccc Mon Sep 17 00:00:00 2001 From: Ben Eysenbach Date: Wed, 3 Sep 2014 22:46:50 -0400 Subject: Clarified C Octal Character This fixes issue #658 --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 8e170300..79b7aec7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -573,7 +573,7 @@ typedef void (*my_fnp_type)(char *); '\''; // single quote '\"'; // double quote '\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo'; // octal number. Example: '\013' = vertical tab character +'\0oo'; // octal number. Example: '\013' = vertical tab character //print formatting: "%d"; // integer -- cgit v1.2.3 From 0846eaa0e71cdcd651edf1c58b459520be844567 Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Fri, 5 Sep 2014 15:05:13 +0200 Subject: EDOUBLEDSPACE My *fake* ocd kicked in --- go.html.markdown | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index c85209e0..bedc3042 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -12,7 +12,7 @@ contributors: - ["Alexej Friesen", "https://github.com/heyalexej"] --- -Go was created out of the need to get work done. It's not the latest trend +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 problems. @@ -26,7 +26,7 @@ Go comes with a great standard library and an enthusiastic community. ```go // Single line comment /* Multi- - line comment */ + line comment */ // A package clause starts every source file. // Main is a special name declaring an executable rather than a library. @@ -41,8 +41,8 @@ import ( "strconv" // String conversions. ) -// A function definition. Main is special. It is the entry point for the -// executable program. Love it or hate it, Go uses brace brackets. +// A function definition. Main is special. It is the entry point for the +// 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. @@ -77,7 +77,7 @@ func learnTypes() { s2 := `A "raw" string literal can include line breaks.` // Same string type. - // Non-ASCII literal. Go source is UTF-8. + // Non-ASCII literal. Go source is UTF-8. g := 'Σ' // rune type, an alias for int32, holds a unicode code point. f := 3.14195 // float64, an IEEE-754 64-bit floating point number. @@ -94,9 +94,9 @@ can include line breaks.` // Same string type. var a4 [4]int // An array of 4 ints, initialized to all 0. a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. - // Slices have dynamic size. Arrays and slices each have advantages + // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. @@ -116,7 +116,7 @@ can include line breaks.` // Same string type. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. // Maps are a dynamically growable associative array type, like the // hash or dictionary types of some other languages. @@ -142,7 +142,7 @@ func learnNamedReturns(x, y int) (z int) { return // z is implicit here, because we named it earlier. } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. @@ -220,7 +220,7 @@ func learnFlowControl() { func(a, b int) int { return (a + b) * 2 }(10, 2)) // Called with args 10 and 2 - // => Add + double two numbers: 24 + // => Add + double two numbers: 24 // When you need it, you'll love it. goto love @@ -267,7 +267,7 @@ type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. +// Define a method on type pair. Pair now implements Stringer. func (p pair) String() string { // p is called the "receiver" // Sprintf is another public function in package fmt. // Dot syntax references fields of p. @@ -275,13 +275,13 @@ func (p pair) String() string { // p is called the "receiver" } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. p := pair{3, 4} fmt.Println(p.String()) // Call String method of p, of type pair. var i Stringer // Declare i of interface type Stringer. i = p // Valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + // Call String method of i, of type Stringer. Output same as above. fmt.Println(i.String()) // Functions in the fmt package call the String method to ask an object @@ -319,7 +319,7 @@ func learnErrorHandling() { // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // We'll revisit interfaces a little later. Meanwhile, learnConcurrency() } @@ -330,12 +330,12 @@ func inc(i int, c chan int) { // We'll use inc to increment some numbers concurrently. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and + // Same make function used earlier to make a slice. Make allocates and // initializes slices, maps, and channels. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented + // Start three concurrent goroutines. Numbers will be incremented // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. + // properly configured. All three send to the same channel. go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) @@ -348,7 +348,7 @@ func learnConcurrency() { go func() { c <- 84 }() // Start a new goroutine just to send a value. go func() { cs <- "wordy" }() // Again, for cs this time. // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases + // a channel operation. It selects a case at random out of the cases // that are ready to communicate. select { case i := <-c: // The value received can be assigned to a variable, @@ -358,7 +358,7 @@ func learnConcurrency() { case <-ccs: // Empty channel, not ready for communication. fmt.Println("didn't happen.") } - // At this point a value was taken from either c or cs. One of the two + // At this point a value was taken from either c or cs. One of the two // goroutines started above has completed, the other will remain blocked. learnWebProgramming() // Go does it. You want to do it too. @@ -397,15 +397,15 @@ func requestServer() { The root of all things Go is the [official Go web site](http://golang.org/). There you can follow the tutorial, play interactively, and read lots. -The language definition itself is highly recommended. It's easy to read +The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it +library](http://golang.org/src/pkg/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the +idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). -- cgit v1.2.3 From c040acba1a8c389d1e4da7332eb4ba2cc58d7edb Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 5 Sep 2014 22:56:25 +0200 Subject: Added compojure --- compojure.html.markdown | 225 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 compojure.html.markdown diff --git a/compojure.html.markdown b/compojure.html.markdown new file mode 100644 index 00000000..56f43cb7 --- /dev/null +++ b/compojure.html.markdown @@ -0,0 +1,225 @@ +--- +category: tool +tool: compojure +contributors: + - ["Adam Bard", "http://adambard.com/"] +filename: learncompojure.clj +--- + +## Getting Started with Compojure + +Compojure is a DSL for *quickly* creating *performant* web applications +in Clojure with minimal effort: + +```clojure +(ns myapp.core + (:require [compojure.core :refer :all] + [org.httpkit.server :refer [run-server]])) ; httpkit is a server + +(defroutes myapp + (GET "/" [] "Hello World")) + +(defn -main [] + (run-server myapp {:port 5000})) +``` + +Create a project with [Leiningen](http://leiningen.org/): + +``` +lein new myapp +``` + +Add your dependencies: + +``` +[compojure "1.1.8"] +[http-kit "2.1.16"] +``` + +And run: + +``` +lein run -m myapp.core +``` + +View at: + +Compojure apps will run on any ring-compatible server, but we recommend +[http-kit](http://http-kit.org/) for its performance and +[massive concurrency](http://http-kit.org/600k-concurrent-connection-http-kit.html). + +### Routes + +In compojure, each route is an HTTP method paired with a URL-matching pattern, +an argument list, and a body. + +```clojure +(defroutes myapp + (GET "/" [] "Show something") + (POST "/" [] "Create something") + (PUT "/" [] "Replace something") + (PATCH "/" [] "Modify Something") + (DELETE "/" [] "Annihilate something") + (OPTIONS "/" [] "Appease something") + (HEAD "/" [] "Preview something")) +``` + +Compojure route definitions are just functions which +[accept request maps and return response maps](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(myapp {:uri "/" :request-method :post}) +; => {:status 200 +; :headers {"Content-Type" "text/html; charset=utf-8} +; :body "Create Something"} +``` + +The body may be a function, which must accept the request as a parameter: + +```clojure +(defroutes myapp + (GET "/" [] (fn [req] "Do something with req"))) +``` + +Route patterns may include named parameters, + +```clojure +(defroutes myapp + (GET "/hello/:name" [name] (str "Hello " name))) +``` + +You can match entire paths with * + +```clojure +(defroutes myapp + (GET "/file/*.*" [*] (str *))) +``` + +Handlers may utilize query parameters: + +```clojure +(defroutes myapp + (GET "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + " Do something with title and author")))) +``` + +Or, for POST and PUT requests, form parameters + +```clojure +(defroutes myapp + (POST "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + "Do something with title and author")))) +``` + + +### Return values + +The return value of a route block determines at least the response body +passed on to the HTTP client, or at least the next middleware in the +ring stack. Most commonly, this is a string, as in the above examples. +But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(defroutes myapp + (GET "/" [] + {:status 200 :body "Hello World"}) + (GET "/is-403" [] + {:status 403 :body ""}) + (GET "/is-json" [] + {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) +``` + +### Static Files + +To serve up static files, use `compojure.route.resources`. +Resources will be served from your project's `resources/` folder. + +```clojure +(require '[compojure.route :as route]) + +(defroutes myapp + (GET "/") + (route/resources "/")) ; Serve static resources at the root path + +(myapp {:uri "/js/script.js" :request-method :get}) +; => Contents of resources/public/js/script.js +``` + +### Views / Templates + +To use templating with Compojure, you'll need a template library. Here are a few: + +#### [Stencil](https://github.com/davidsantiago/stencil) + +[Stencil](https://github.com/davidsantiago/stencil) is a [Mustache](http://mustache.github.com/) template library: + +```clojure +(require '[stencil.core :refer [render-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string "Hello {{name}}" {:name name}))) +``` + +You can easily read in templates from your resources directory. Here's a helper function + +```clojure +(require 'clojure.java.io) + +(defn read-template [filename] + (slurp (clojure.java.io/resource filename))) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string (read-template "templates/hello.html") {:name name}))) +``` + +#### [Selmer](https://github.com/yogthos/Selmer) + +[Selmer](https://github.com/yogthos/Selmer) is a Django and Jinja2-inspired templating language: + +```clojure +(require '[selmer.parser :refer [render-file]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-file "templates/hello.html" {:name name}))) +``` + +#### [Hiccup](https://github.com/weavejester/hiccup) + +[Hiccup](https://github.com/weavejester/hiccup) is a library for representing HTML as Clojure code + +```clojure +(require '[hiccup.core :as hiccup]) + +(defroutes myapp + (GET "/hello/:name" [name] + (hiccup/html + [:html + [:body + [:h1 {:class "title"} + (str "Hello " name)]]]))) +``` + +#### [Markdown](https://github.com/yogthos/markdown-clj) + +[Markdown-clj](https://github.com/yogthos/markdown-clj) is a Markdown implementation. + +```clojure +(require '[markdown.core :refer [md-to-html-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (md-to-html-string "## Hello, world"))) +``` + +Further reading: + +[Clojure for the Brave and True](http://www.braveclojure.com/) -- cgit v1.2.3 From fc84512fa651d89b0e6acbd248e0b078706e7268 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 5 Sep 2014 22:58:40 +0200 Subject: Fix learntmux --- LearnTmux.txt | 71 ------------------------------------------------- learntmux.html.markdown | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 71 deletions(-) delete mode 100644 LearnTmux.txt create mode 100644 learntmux.html.markdown diff --git a/LearnTmux.txt b/LearnTmux.txt deleted file mode 100644 index eaf3fd25..00000000 --- a/LearnTmux.txt +++ /dev/null @@ -1,71 +0,0 @@ ---- -category: tool -tool: tmux -contributors: - - ["kaernyk", "http://github.com/kaernyk"] -filename: LearnTmux.txt ---- - - - tmux is a terminal multiplexer: it enables a number of terminals to be -created, accessed, and controlled from a single screen. tmux may be detached -from a screen and continue running in the background, then later reattached. - - Once you feel comfortable manipulating tmux to suit your needs, I strongly -suggest you read the man pages. - - - -``` -# Session Management - - tmux new Create new session - -s "Session" Create named session - -n "Window" Create named Window - -c "/dir" Start in target directory - - C^b $ Rename current session - C^b d Detach current session - C^b D Select session to detach - - tmux attach Attach last/available session - -t "#" Attach target session - -d Detach the session from other instances - - tmux ls List open sessions - C^b s Select new session for attached client interactively - - kill-session Kill current session - -t "#" Kill target session - -a Kill all sessions - -a -t "#" Kill all sessions but the target - - -# Window Management - - C^b c Create another window - C^b " Split Horizontally - C^b % Split Vertically - C^b M-(1-5) 1) Tile vertically - 2) Tile horizontally - 3) Tile Vertically /w large horizontal - 4) Tile horizontally /w large vertical - 5) Tile all windows evenly - - C^b q Briefly display pane indexes - C^# Choose current window by # - C^b w Choose current window interactively - C^b n Change to next window - C^b p Change to previous window - C^b Up, Right Change to pane in selected direction - Down, left - C^b { Swap current/previous window - C^b } Swap current/next window - - C^b C-Up, Right Resize in steps of one cell - Down, left - C^b M-Up, Right resize in steps of five cells - Down, left - - exit or C^b x Kill the current window -``` diff --git a/learntmux.html.markdown b/learntmux.html.markdown new file mode 100644 index 00000000..eaf3fd25 --- /dev/null +++ b/learntmux.html.markdown @@ -0,0 +1,71 @@ +--- +category: tool +tool: tmux +contributors: + - ["kaernyk", "http://github.com/kaernyk"] +filename: LearnTmux.txt +--- + + + tmux is a terminal multiplexer: it enables a number of terminals to be +created, accessed, and controlled from a single screen. tmux may be detached +from a screen and continue running in the background, then later reattached. + + Once you feel comfortable manipulating tmux to suit your needs, I strongly +suggest you read the man pages. + + + +``` +# Session Management + + tmux new Create new session + -s "Session" Create named session + -n "Window" Create named Window + -c "/dir" Start in target directory + + C^b $ Rename current session + C^b d Detach current session + C^b D Select session to detach + + tmux attach Attach last/available session + -t "#" Attach target session + -d Detach the session from other instances + + tmux ls List open sessions + C^b s Select new session for attached client interactively + + kill-session Kill current session + -t "#" Kill target session + -a Kill all sessions + -a -t "#" Kill all sessions but the target + + +# Window Management + + C^b c Create another window + C^b " Split Horizontally + C^b % Split Vertically + C^b M-(1-5) 1) Tile vertically + 2) Tile horizontally + 3) Tile Vertically /w large horizontal + 4) Tile horizontally /w large vertical + 5) Tile all windows evenly + + C^b q Briefly display pane indexes + C^# Choose current window by # + C^b w Choose current window interactively + C^b n Change to next window + C^b p Change to previous window + C^b Up, Right Change to pane in selected direction + Down, left + C^b { Swap current/previous window + C^b } Swap current/next window + + C^b C-Up, Right Resize in steps of one cell + Down, left + C^b M-Up, Right resize in steps of five cells + Down, left + + exit or C^b x Kill the current window +``` -- cgit v1.2.3 From cd7ed4f9f9590f82acf953bba8d6032e1f62fa0c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:47:18 -0500 Subject: Couple changes to C to close https://github.com/adambard/learnxinyminutes-docs/pull/594 --- c.html.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 79b7aec7..cbb6d289 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -4,6 +4,7 @@ filename: learnc.c contributors: - ["Adam Bard", "http://adambard.com/"] - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] + - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] --- @@ -175,6 +176,9 @@ int main() { i2 * i1; // => 2 i1 / i2; // => 0 (0.5, but truncated towards 0) + // You need to cast at least one integer to float to get a floating-point result + (float)i1 / i2 // => 0.5f + i1 / (double)i2 // => 0.5 // Same with double f1 / f2; // => 0.5, plus or minus epsilon // Floating-point numbers and calculations are not exact @@ -194,9 +198,11 @@ int main() { 2 >= 2; // => 1 // C is not Python - comparisons don't chain. - // WRONG: - //int between_0_and_2 = 0 < a < 2; - // Correct: + // Warning: The line below will compile, but it means `(0 < a) < 2`. + // This expression is always true, because (0 < a) could be either 1 or 0. + // In this case it's 1, because (0 < 1). + int between_0_and_2 = 0 < a < 2; + // Instead use: int between_0_and_2 = 0 < a && a < 2; // Logic works on ints -- cgit v1.2.3 From 64c1ee391f4e03f363fd829ce658fc881bcffb6f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:48:42 -0500 Subject: Add lua-cn filename to close https://github.com/adambard/learnxinyminutes-docs/pull/610/files --- zh-cn/lua-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 95a94c76..3ba098ec 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Amr Tamimi", "https://amrtamimi.com"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] +filename: lua-cn.lua --- ```lua -- cgit v1.2.3 From eefa3add633ef1e80fb7403eec7854da1077188b Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:51:48 -0500 Subject: Add traditional for loop bash example to close https://github.com/adambard/learnxinyminutes-docs/pull/654 --- bash.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 57fb5c55..dc7d32b6 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Denis Arh", "https://github.com/darh"] - ["akirahirose", "https://twitter.com/akirahirose"] - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] filename: LearnBash.sh --- @@ -140,6 +141,12 @@ do echo "$VARIABLE" done +# Or write it the "traditional for loop" way: +for ((a=1; a <= 3; a++)) +do + echo $a +done + # They can also be used to act on files.. # This will run the command 'cat' on file1 and file2 for VARIABLE in file1 file2 -- cgit v1.2.3 From b35ccf01af17b52447c98d7101ee932e7f089c52 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 20:59:37 -0500 Subject: Add FZSS's GitHub profile link to close https://github.com/adambard/learnxinyminutes-docs/pull/666 --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 975ebcb5..f1166a04 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -3,7 +3,7 @@ language: Markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Fangzhou Chen"] + - ["Fangzhou Chen","https://github.com/FZSS"] filename: learnmarkdown-cn.md lang: zh-cn --- -- cgit v1.2.3 From 291f6f6b22acf7962a180e6e12234aebcb20c5bd Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 5 Sep 2014 21:02:38 -0500 Subject: Fix "initialized" typo. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 758c9ff4..b4c6afff 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -92,7 +92,7 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three + a3 := [...]int{3, 1, 5} // An array initialized with a fixed size of three // elements, with values 3, 1, and 5. // Slices have dynamic size. Arrays and slices each have advantages -- cgit v1.2.3 From 014262f5c62ae1904b5e70135aca8c56540abc78 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 6 Sep 2014 10:18:31 +0200 Subject: Updated compojure per weavejester's suggestions --- compojure.html.markdown | 60 ++++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 56f43cb7..1644dfb7 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -81,18 +81,26 @@ The body may be a function, which must accept the request as a parameter: (GET "/" [] (fn [req] "Do something with req"))) ``` -Route patterns may include named parameters, +Or, you can just use the request directly: + +```clojure +(defroutes myapp + (GET "/" req "Do something with req")) +``` + +Route patterns may include named parameters: ```clojure (defroutes myapp (GET "/hello/:name" [name] (str "Hello " name))) ``` -You can match entire paths with * +You can adjust what each parameter matches by supplying a regex: ```clojure (defroutes myapp - (GET "/file/*.*" [*] (str *))) + (GET ["/file/:name.:ext" :name #".*", :ext #".*"] [name ext] + (str "File: " name ext)) ``` Handlers may utilize query parameters: @@ -100,10 +108,10 @@ Handlers may utilize query parameters: ```clojure (defroutes myapp (GET "/posts" [] - (fn [req] - (let [title (get (:params req) "title") - author (get (:params req) "title")] - " Do something with title and author")))) + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + " Do something with title and author")))) ``` Or, for POST and PUT requests, form parameters @@ -111,10 +119,10 @@ Or, for POST and PUT requests, form parameters ```clojure (defroutes myapp (POST "/posts" [] - (fn [req] - (let [title (get (:params req) "title") - author (get (:params req) "title")] - "Do something with title and author")))) + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + "Do something with title and author")))) ``` @@ -123,16 +131,16 @@ Or, for POST and PUT requests, form parameters The return value of a route block determines at least the response body passed on to the HTTP client, or at least the next middleware in the ring stack. Most commonly, this is a string, as in the above examples. -But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): +But, you may also return a [response map](https://github.com/mmcgrana/ring/blob/master/SPEC): ```clojure (defroutes myapp (GET "/" [] - {:status 200 :body "Hello World"}) + {:status 200 :body "Hello World"}) (GET "/is-403" [] - {:status 403 :body ""}) + {:status 403 :body ""}) (GET "/is-json" [] - {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) + {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) ``` ### Static Files @@ -164,7 +172,7 @@ To use templating with Compojure, you'll need a template library. Here are a few (defroutes myapp (GET "/hello/:name" [name] - (render-string "Hello {{name}}" {:name name}))) + (render-string "Hello {{name}}" {:name name}))) ``` You can easily read in templates from your resources directory. Here's a helper function @@ -177,7 +185,7 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (render-string (read-template "templates/hello.html") {:name name}))) + (render-string (read-template "templates/hello.html") {:name name}))) ``` #### [Selmer](https://github.com/yogthos/Selmer) @@ -189,7 +197,7 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (render-file "templates/hello.html" {:name name}))) + (render-file "templates/hello.html" {:name name}))) ``` #### [Hiccup](https://github.com/weavejester/hiccup) @@ -201,11 +209,11 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (hiccup/html - [:html - [:body - [:h1 {:class "title"} - (str "Hello " name)]]]))) + (hiccup/html + [:html + [:body + [:h1 {:class "title"} + (str "Hello " name)]]]))) ``` #### [Markdown](https://github.com/yogthos/markdown-clj) @@ -217,9 +225,11 @@ You can easily read in templates from your resources directory. Here's a helper (defroutes myapp (GET "/hello/:name" [name] - (md-to-html-string "## Hello, world"))) + (md-to-html-string "## Hello, world"))) ``` Further reading: -[Clojure for the Brave and True](http://www.braveclojure.com/) +* [Official Compojure Documentation](https://github.com/weavejester/compojure/wiki) + +* [Clojure for the Brave and True](http://www.braveclojure.com/) -- cgit v1.2.3 From c0d8a18b08d114dd0142a09f6787c7221b423802 Mon Sep 17 00:00:00 2001 From: Adam Date: Sat, 6 Sep 2014 10:28:58 +0200 Subject: Made beginning easier --- compojure.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/compojure.html.markdown b/compojure.html.markdown index 1644dfb7..96555273 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -23,20 +23,22 @@ in Clojure with minimal effort: (run-server myapp {:port 5000})) ``` -Create a project with [Leiningen](http://leiningen.org/): +**Step 1:** Create a project with [Leiningen](http://leiningen.org/): ``` lein new myapp ``` -Add your dependencies: +**Step 2:** Put the above code in `src/myapp/core.clj` + +**Step 3:** Add some dependencies to `project.clj`: ``` [compojure "1.1.8"] [http-kit "2.1.16"] ``` -And run: +**Step 4:** Run: ``` lein run -m myapp.core -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- coffeescript.html.markdown | 2 +- common-lisp.html.markdown | 2 +- es-es/markdown-es.html.markdown | 2 +- fr-fr/objective-c-fr.html.markdown | 2 +- ja-jp/r-jp.html.markdown | 4 ++-- markdown.html.markdown | 2 +- objective-c.html.markdown | 2 +- pt-br/markdown-pt.html.markdown | 2 +- r.html.markdown | 2 +- ru-ru/objective-c-ru.html.markdown | 2 +- scala.html.markdown | 2 +- swift.html.markdown | 2 +- tr-tr/objective-c-tr.html.markdown | 2 +- typescript.html.markdown | 2 +- vi-vn/objective-c-vi.html.markdown | 2 +- zh-cn/common-lisp-cn.html.markdown | 2 +- zh-cn/markdown-cn.html.markdown | 2 +- zh-cn/r-cn.html.markdown | 2 +- zh-cn/scala-cn.html.markdown | 2 +- zh-cn/swift-cn.html.markdown | 2 +- 20 files changed, 21 insertions(+), 21 deletions(-) diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index d96eed39..6af692b9 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -11,7 +11,7 @@ As one of the succeeders of JavaScript, CoffeeScript tries its best to output re See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. -``` coffeescript +```coffeescript # CoffeeScript is a hipster language. # It goes with the trends of many modern languages. # So comments are like Ruby and Python, they use number symbols. diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 8de81549..08134e35 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -17,7 +17,7 @@ Another popular and recent book is -```scheme +```common_lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. Syntax diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index 3865126c..d90e3eb5 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también). ¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! -``` +```markdown