From 8f990317b79d17953755269d3383d3f94e9c5f7f Mon Sep 17 00:00:00 2001 From: Jakob Rieck Date: Mon, 25 Sep 2017 16:12:53 +0200 Subject: [c/en] Correct off-by-one error --- c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 1ff8658c..87a047be 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -348,7 +348,7 @@ int main (int argc, char** argv) printf("Error occurred at i = %d & j = %d.\n", i, j); /* https://ideone.com/GuPhd6 - this will print out "Error occurred at i = 52 & j = 99." + this will print out "Error occurred at i = 51 & j = 99." */ /////////////////////////////////////// -- cgit v1.2.3 From f70e1e3518026b9e9d660a9ffc25ca3424ebe365 Mon Sep 17 00:00:00 2001 From: Ale46 Date: Mon, 2 Oct 2017 02:10:53 +0200 Subject: [html/it-it] adds Italian translation for html --- it-it/html-it.html.markdown | 120 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 it-it/html-it.html.markdown diff --git a/it-it/html-it.html.markdown b/it-it/html-it.html.markdown new file mode 100644 index 00000000..1d2a0618 --- /dev/null +++ b/it-it/html-it.html.markdown @@ -0,0 +1,120 @@ +--- +language: html +filename: learnhtml-it.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Ale46", "http://github.com/Ale46/"] +--- + +HTML sta per HyperText Markup Language (linguaggio a marcatori per ipertesti). +È un linguaggio che consente di scrivere pagine web per il world wide web. +È un linguaggio di markup, che permette di scrivere pagine web usando del codice che indica come il testo ed i dati devono essere mostrati. +Infatti, i files html sono semplici file di testo. +Cos'è il markup? È un metodo per organizzare i dati della pagina circondandoli con tag di apertura e tag di chiusura. +Questo markup serve a dare significato al testo che racchiude. +Come altri linguaggi di programmazione, HTML ha molte versioni. Qui discuteremo di HTML5. + +**NOTA :** Puoi testare i differenti tags ed elementi man mano che prosegui nel tutorial in un sito come [codepen](http://codepen.io/pen/) per vedere i loro effetti, capire come lavorano e familiarizzare con il linguaggio. +Questo articolo riguarda principalmente la sintassi HTML ed alcuni suggerimenti utili. + + +```html + + + + + + + + + + Il mio sito + + +

Ciao, mondo!

+ Vieni a vedere ciò che mostra +

Questo è un paragrafo.

+

Questo è un altro paragrafo.

+ + + + + + + + + + + + + + + + + + + + + + Il mio sito + + + + + + + +

Ciao, mondo!

+ + Vieni a vedere ciò che mostra +

Questo è un paragrafo.

+

Questo è un altro paragrafo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Prima intestazione Seconda intestazione
prima riga, prima colonna prima riga, seconda colonna
seconda riga, prima colonnaseconda riga, seconda colonna
+ +``` + +## Uso + +HTML è scritto in files che finiscono con `.html`. + +## Per saperne di più + +* [wikipedia](https://it.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/it/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From c80eeab9cc143598444dec87a3e2a48cb8ad3626 Mon Sep 17 00:00:00 2001 From: Haydar Ali Ismail Date: Tue, 3 Oct 2017 18:57:53 +0800 Subject: [rst/id-id] Add Indonesian translation for RST --- id-id/rst-id.html.markdown | 122 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 id-id/rst-id.html.markdown diff --git a/id-id/rst-id.html.markdown b/id-id/rst-id.html.markdown new file mode 100644 index 00000000..06d80089 --- /dev/null +++ b/id-id/rst-id.html.markdown @@ -0,0 +1,122 @@ +--- +language: restructured text (RST) +filename: rst-id.html +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Haydar Ali Ismail", "https://github.com/haydarai"] +lang: id-id +--- + +RST adalah sebual format file yang dibuat oleh komunitas Python untuk menulis +dokumentasi (dan menjadi bagian dari Docutils). + +File-file RST adalah sebuah file-file teks simpel dengan sintaks yang ringan +(dibandingkan dengan HTML). + + +## Pemasangan + +Untuk menggunakan RST, anda harus memasang [Python](http://www.python.org) dan +paket `docutils` terlebih dahulu. + +`docutils` bisa dipasang menggunakan command berikut: + +```bash +$ easy_install docutils +``` + +Jika sistem anda sudah mempunyai `pip`, anda bisa menggunakannya juga: + +```bash +$ pip install docutils +``` + + +## Sintaks file + +Sebuah contoh sederhana dari sintaks file: + +``` +.. Baris yang dimulai dengan dua titik adalah perintah spesial. Tetapi jika +perintah tidak ditemukan, maka baris tersebut akan dianggap sebagai komentar + +=============================================================================== +Judul utama ditulis menggunakan rentetan tanda sama dengan di atas dan bawahnya +=============================================================================== + +Ingat bahwa jumlah tanda sama dengan harus sama panjangnya dengan total +karakter judul + +Judul juga digarisbawahi dengan tanda sama dengan juga +====================================================== + +Sub-judul dengan menggunakan dash +--------------------------------- + +Dan sub-sub-judul dengan menggunakan tilde +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Anda bisa menulis teks dalam *italik* atau *tebal*, anda bisa "menandai" teks +sebagai kode dengan menggunakan backquote ganda ``: ``print()``. + +Membuat daftar semudah seperti dalam Markdown: + +- Barang pertama +- Barang kedua + - Sub barang + +atau + +* Barang pertama +* Barang kedua + * Sub barang + +Tabel sangat mudah untuk ditulis: + +=========== ======== +Negara Ibu Kota +=========== ======== +Prancis Paris +Jepang Tokyo +=========== ======== + +Tabel yang lebih kompleks bisa dibuat dengan mudah (kolom tergabung atau/dan +baris) tetapi saya menyarankan anda untuk membaca dokumentasi lengkap tentang +ini :) + +Ada berbagai macam cara untuk membuat tautan: + +- Dengan menambahkan garis bawah setelah sebuah huruf : Github_ dan dengan +menambahkan URL target setelah teks (cara ini mempunyai kelebihan dengan tidak +memasukkan URL yang tidak penting ke dalam teks yang bisa dibaca). +- Dengan mengetik URL lengkap yang dapat dipahami : https://github.com (akan +otomatis diubah menjadi sebuah link) +- Dengan membuat link seperti di Markdown: `Github `_ . + +.. _Github https://github.com/ + +``` + + +## Bagaimana Cara Menggunakannya + +RST hadir dengan docutils di mana anda mempunyai `rst2html`, sebagai contoh: + +```bash +$ rst2html fileku.rst hasil.html +``` + +*Catatan : Di beberapa sistem, perintah tersebut bisa menjadi rst2html.py* + +Tetapi ada beberapa aplikasi kompleks yang menggunakan format RST: + +- [Pelican](http://blog.getpelican.com/), Generator web statik +- [Sphinx](http://sphinx-doc.org/), Generator dokumnetasi +- dan masih banyak lainnya + + +## Bacaan + +- [Referensi singkat resmi](http://docutils.sourceforge.net/docs/user/rst/quickref.html) -- cgit v1.2.3 From 9afd4fd1bd7ea9fb32dd3957c07380d3879da753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=81opusza=C5=84ski?= Date: Wed, 4 Oct 2017 16:15:38 +0200 Subject: [groovy] small fix in iteration over a map --- ca-es/groovy-ca.html.markdown | 4 +++- es-es/groovy-es.html.markdown | 4 +++- groovy.html.markdown | 4 +++- pt-br/groovy-pt.html.markdown | 4 +++- zh-cn/groovy-cn.html.markdown | 4 +++- 5 files changed, 15 insertions(+), 5 deletions(-) diff --git a/ca-es/groovy-ca.html.markdown b/ca-es/groovy-ca.html.markdown index 57674970..f0a9adbe 100644 --- a/ca-es/groovy-ca.html.markdown +++ b/ca-es/groovy-ca.html.markdown @@ -233,10 +233,12 @@ for (i in array) { //Itera per un mapa def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] -x = 0 +x = "" for ( e in map ) { x += e.value + x += " " } +assert x.equals("Roberto Grails Groovy ") /* Operadors diff --git a/es-es/groovy-es.html.markdown b/es-es/groovy-es.html.markdown index 799fc609..262d5e6a 100644 --- a/es-es/groovy-es.html.markdown +++ b/es-es/groovy-es.html.markdown @@ -232,10 +232,12 @@ for (i in array) { // Iterando sobre un mapa def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] -x = 0 +x = "" for ( e in map ) { x += e.value + x += " " } +assert x.equals("Roberto Grails Groovy ") /* Operadores diff --git a/groovy.html.markdown b/groovy.html.markdown index a3a45757..efbb2b32 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -230,10 +230,12 @@ for (i in array) { //Iterate over a map def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] -x = 0 +x = "" for ( e in map ) { x += e.value + x += " " } +assert x.equals("Roberto Grails Groovy ") /* Operators diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index 25e123c0..aed23df1 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -226,10 +226,12 @@ for (i in array) { //Itera sobre um mapa def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] -x = 0 +x = "" for ( e in map ) { x += e.value + x += " " } +assert x.equals("Roberto Grails Groovy ") /* Operadores diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index 562a0284..0e7a020c 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -219,10 +219,12 @@ for (i in array) { //遍历映射 def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] -x = 0 +x = "" for ( e in map ) { x += e.value + x += " " } +assert x.equals("Roberto Grails Groovy ") /* 运算符 -- cgit v1.2.3 From 31b9d9b8035ffe8581981e546b724ca6f3fc67d7 Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Wed, 4 Oct 2017 14:35:23 -0300 Subject: [pyqt/pt-br] Translation of PyQt to pt-br. --- pt-br/pyqt-pt.html.markdown | 92 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 pt-br/pyqt-pt.html.markdown diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown new file mode 100644 index 00000000..ced107dc --- /dev/null +++ b/pt-br/pyqt-pt.html.markdown @@ -0,0 +1,92 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Lucas Pugliesi", "https://github.com/fplucas"] +lang: pt-br +--- + +**Qt** é amplamente conhecido como um framework para desenvolvimento de +software multi-plataforma que pode rodar em vários outras plataformas de +softwares e hardwares com pouca ou nenhuma alteração no código, enquanto mantém +o poder e a velocidade de uma aplicação nativa. Embora o **Qt** tenha sido +originalmente escrito em *C++*. + + +Essa é uma adaptação de uma introdução ao QT em C++ por +[Aleksey Kholovchuk](https://github.com/vortexxx192), alguns dos exemplos de +código podem resultar na mesma funcionalidade que essa versão, apenas usando +o pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Cria um objeto para a aplicação + app = QtGui.QApplication(sys.argv) + # Cria um widget onde o nosso label será inserido + w = QtGui.QWidget() + # Adiciona um label ao widget + b = QtGui.QLabel(w) + # Informa algum texto ao label + b.setText("Hello World!") + # Define os tamanhos e posições dos objetos + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Define o título da janela + w.setWindowTitle("PyQt") + # Exibe a janela + w.show() + # Executa tudo o que foi pedido, apenas uma vez + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +Para utilizar mais funcionalidades no **pyqt** veremos a construção de alguns +outros elementos. +Aqui mostraremos como criar uma janela popup, muito útil para perguntar ao +usuário qual decisão tomar ou exibir alguma informação. + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Cria um botão e o anexa ao widget w + b = QPushButton(w) + b.setText("Press me") + b.move(50, 50) + # Informa b a chamar essa função quando for clicado + # observe que a função chamada não necessita de "()" + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Essa função deve criar uma janela de diálogo com um botão, +# aguarda ser clicado e encerra o programa +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Essa modalidade define que o popup deve bloquear as outras janelas quando ativo + d.setWindowModality(Qt.ApplicationModal) + # Ao ser clicado deve encerrar o processo + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` -- cgit v1.2.3 From d00c5e67d04d83d647746836872d3c1e1ed74d0b Mon Sep 17 00:00:00 2001 From: fnscoder Date: Wed, 4 Oct 2017 21:53:03 -0300 Subject: fix names in pt-br --- pt-br/amd-pt.html.markdown | 218 ++++++++++ pt-br/amd.html.markdown | 218 ---------- pt-br/bf-pt.html.markdown | 86 ++++ pt-br/bf.html.markdown | 86 ---- pt-br/csharp-pt.html.markdown | 896 ++++++++++++++++++++++++++++++++++++++++++ pt-br/csharp.html.markdown | 896 ------------------------------------------ pt-br/elixir-pt.html.markdown | 412 +++++++++++++++++++ pt-br/elixir.html.markdown | 412 ------------------- 8 files changed, 1612 insertions(+), 1612 deletions(-) create mode 100644 pt-br/amd-pt.html.markdown delete mode 100644 pt-br/amd.html.markdown create mode 100644 pt-br/bf-pt.html.markdown delete mode 100644 pt-br/bf.html.markdown create mode 100644 pt-br/csharp-pt.html.markdown delete mode 100644 pt-br/csharp.html.markdown create mode 100644 pt-br/elixir-pt.html.markdown delete mode 100644 pt-br/elixir.html.markdown diff --git a/pt-br/amd-pt.html.markdown b/pt-br/amd-pt.html.markdown new file mode 100644 index 00000000..38c1f70f --- /dev/null +++ b/pt-br/amd-pt.html.markdown @@ -0,0 +1,218 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Felipe Tarijon", "http://nanoincub.com/"] +lang: pt-br +filename: learnamd-pt.js +--- + +## Começando com AMD + +A API de Definição de Módulos Assíncrona **Asynchronous Module Definition** +especifica um mecanismo para definição de módulos em JavaScript para os quais o +módulo e suas dependências podem ser carregados de forma assíncrona. Isso é +particularmente bem adequado para o ambiente do browser onde o carregamento de +módulos de forma síncrona fica sujeito a problemas de performance, usabilidade, +debugging e problemas de acesso em requisições cross-domain. + +### Conceito básico +```javascript +// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require` +// e isso é tudo sobre a definição de módulo e consumo: +// `define(id?, dependências?, factory)` define um módulo +// `require(dependências, callback)` importa uma série de dependências e +// consome elas no callback passado como parâmetro. + +// Vamos começar usando o define para definir um novo módulo +// que não tem dependências. Nós vamos fazer isso passando um nome +// e uma função factory para definir: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // O valor retornado da função de factory do módulo é + // o que os outros módulos ou chamadas de require irão + // receber quando requisitarem nosso módulo `awesomeAMD`. + // O valor exportado pode ser qualquer coisa, (construtor) funções, + // objetos, primitives, até mesmo undefined (apesar de que não irão ajudar muito). + return isAMDAwesome; +}); + +// Agora, vamos definir outro módulo que depende do nosso módulo `awesomeAMD`. +// Perceba que existe um argumento adicional definindo nossas dependências do +// módulo agora: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // dependências serão passadas como argumentos da factory + // na ordem que elas forem especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('Isso é tãaaao loko!'); + } else { + alert('Bem estúpido, né não?'); + } + }; + return tellEveryone; +}); + +// Agora que nós sabemos como usar o define, vamos usar o `require` para +// começar nosso programa. A assinatura do `require` é `(arrayDedependências, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para fazer esse tutorial executável, vamos implementar uma versão muito básica +// (não-assíncrona) de AMD bem aqui nesse lugar: +function define(nome, deps, factory){ + // perceba como os módulos sem dependências são manipulados + define[nome] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primeiro vamos recuperar todas as dependências necessárias + // pela chamada requerida + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // corresponder todas as dependências da função de callback + return callback.apply(null, args); +} +// você pode ver esse código em ação aqui: http://jsfiddle.net/qap949pd/ +``` + +### Uso na vida real com require.js + +Em contraste com o exemplo introdutório, `require.js` (a biblioteca mais popular de AMD) na verdade implementa o **A** do **AMD**, permitindo que você carregue os módulos e suas +dependências via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/algumaClasse'], function(AlgumaClasse){ + // o callback é deferido até que a dependencia seja carregada + var coisa = new AlgumaClasse(); +}); +console.log('Então aqui estamos nós, esperando!'); // isso vai rodar primeiro +``` + +Por convenção, você geralmente guarda um módulo em um arquivo. `require.js` pode resolver nome de módulos baseado no caminho das pastas, então você não precisa nomear os seus módulos, mas sim simplesmente referenciar eles usando sua origem. No exemplo `algumaClasse` é adotado a pasta `modules`, relativa a configuração da sua `baseUrl`: + +* app/ + * main.js + * modules/ + * algumaClasse.js + * algunsHelpers.js + * ... + * daos/ + * coisas.js + * ... + +Isso significa que nós podemos definir `algumaClasse` sem especificar o id de um módulo: + +```javascript +/* arquivo: app/modules/algumaClasse.js */ +define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){ + // definição de módulo, claro, irá acontecer também de forma assíncrona + function AlgumaClasse(){ + this.metodo = function(){/**/}; + // ... + } + return AlgumaClasse; +}); +``` +Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize +`requirejs.config(configObj)` em seu `main.js`: + +```javascript +/* arquivo: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // você pode também carregar módulos de outros locais + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coolLib, helpers){ + // um arquivo `main` precisa chamar o require pelo menos uma vez, + // caso contrário, o código jamais rodará + coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); +}); +``` +Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: + +```html + + + + Umas 100 tags de script? Nunca mais! + + + + + +``` + +### Otimizando um projeto inteiro utilizando r.js + +Muitas pessoas preferem usar AMD para sanar a organização do código durante o desenvolvimento, mas continuam querendo colocar um único arquivo de script em produção ao invés de realizarem centenas de requisições XHRs no carregamento da página. + +`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos. + +Instale-o utilizando `npm`: +```shell +$ npm install requirejs -g +``` + +Agora você pode alimentá-lo com um arquivo de configuração: +```shell +$ r.js -o app.build.js +``` + +Para o nosso exemplo acima a configuração pode ser essa: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nome do ponto de acesso + out : 'main-built.js', // nome o arquivo para gravar a saída + baseUrl : 'app', + paths : { + // `empty:` fala para o r.js que isso ainda deve ser baixado da CDN, usando + // o local especificado no `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`: +```html + +``` + +Uma incrível e detalhada visão geral [de build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponível no repositório do GitHub. + +### Tópicos não abordados nesse tutorial +* [Plugins de carregamento / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style carregamento e exportação](http://requirejs.org/docs/commonjs.html) +* [Configuração avançada](http://requirejs.org/docs/api.html#config) +* [Shim configuration (carregando módulos sem AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Carregando e otimizando CSS com require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para builds](https://github.com/jrburke/almond) + +### Outras leituras: + +* [Especificação oficial](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Por quê AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementações: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown deleted file mode 100644 index 38c1f70f..00000000 --- a/pt-br/amd.html.markdown +++ /dev/null @@ -1,218 +0,0 @@ ---- -category: tool -tool: amd -contributors: - - ["Frederik Ring", "https://github.com/m90"] -translators: - - ["Felipe Tarijon", "http://nanoincub.com/"] -lang: pt-br -filename: learnamd-pt.js ---- - -## Começando com AMD - -A API de Definição de Módulos Assíncrona **Asynchronous Module Definition** -especifica um mecanismo para definição de módulos em JavaScript para os quais o -módulo e suas dependências podem ser carregados de forma assíncrona. Isso é -particularmente bem adequado para o ambiente do browser onde o carregamento de -módulos de forma síncrona fica sujeito a problemas de performance, usabilidade, -debugging e problemas de acesso em requisições cross-domain. - -### Conceito básico -```javascript -// O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require` -// e isso é tudo sobre a definição de módulo e consumo: -// `define(id?, dependências?, factory)` define um módulo -// `require(dependências, callback)` importa uma série de dependências e -// consome elas no callback passado como parâmetro. - -// Vamos começar usando o define para definir um novo módulo -// que não tem dependências. Nós vamos fazer isso passando um nome -// e uma função factory para definir: -define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - // O valor retornado da função de factory do módulo é - // o que os outros módulos ou chamadas de require irão - // receber quando requisitarem nosso módulo `awesomeAMD`. - // O valor exportado pode ser qualquer coisa, (construtor) funções, - // objetos, primitives, até mesmo undefined (apesar de que não irão ajudar muito). - return isAMDAwesome; -}); - -// Agora, vamos definir outro módulo que depende do nosso módulo `awesomeAMD`. -// Perceba que existe um argumento adicional definindo nossas dependências do -// módulo agora: -define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ - // dependências serão passadas como argumentos da factory - // na ordem que elas forem especificadas - var tellEveryone = function(){ - if (awesomeAMD()){ - alert('Isso é tãaaao loko!'); - } else { - alert('Bem estúpido, né não?'); - } - }; - return tellEveryone; -}); - -// Agora que nós sabemos como usar o define, vamos usar o `require` para -// começar nosso programa. A assinatura do `require` é `(arrayDedependências, callback)`. -require(['loudmouth'], function(loudmouth){ - loudmouth(); -}); - -// Para fazer esse tutorial executável, vamos implementar uma versão muito básica -// (não-assíncrona) de AMD bem aqui nesse lugar: -function define(nome, deps, factory){ - // perceba como os módulos sem dependências são manipulados - define[nome] = require(factory ? deps : [], factory || deps); -} - -function require(deps, callback){ - var args = []; - // primeiro vamos recuperar todas as dependências necessárias - // pela chamada requerida - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // corresponder todas as dependências da função de callback - return callback.apply(null, args); -} -// você pode ver esse código em ação aqui: http://jsfiddle.net/qap949pd/ -``` - -### Uso na vida real com require.js - -Em contraste com o exemplo introdutório, `require.js` (a biblioteca mais popular de AMD) na verdade implementa o **A** do **AMD**, permitindo que você carregue os módulos e suas -dependências via XHR: - -```javascript -/* file: app/main.js */ -require(['modules/algumaClasse'], function(AlgumaClasse){ - // o callback é deferido até que a dependencia seja carregada - var coisa = new AlgumaClasse(); -}); -console.log('Então aqui estamos nós, esperando!'); // isso vai rodar primeiro -``` - -Por convenção, você geralmente guarda um módulo em um arquivo. `require.js` pode resolver nome de módulos baseado no caminho das pastas, então você não precisa nomear os seus módulos, mas sim simplesmente referenciar eles usando sua origem. No exemplo `algumaClasse` é adotado a pasta `modules`, relativa a configuração da sua `baseUrl`: - -* app/ - * main.js - * modules/ - * algumaClasse.js - * algunsHelpers.js - * ... - * daos/ - * coisas.js - * ... - -Isso significa que nós podemos definir `algumaClasse` sem especificar o id de um módulo: - -```javascript -/* arquivo: app/modules/algumaClasse.js */ -define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){ - // definição de módulo, claro, irá acontecer também de forma assíncrona - function AlgumaClasse(){ - this.metodo = function(){/**/}; - // ... - } - return AlgumaClasse; -}); -``` -Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize -`requirejs.config(configObj)` em seu `main.js`: - -```javascript -/* arquivo: main.js */ -requirejs.config({ - baseUrl : 'app', - paths : { - // você pode também carregar módulos de outros locais - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } -}); -require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coolLib, helpers){ - // um arquivo `main` precisa chamar o require pelo menos uma vez, - // caso contrário, o código jamais rodará - coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); -}); -``` -Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: - -```html - - - - Umas 100 tags de script? Nunca mais! - - - - - -``` - -### Otimizando um projeto inteiro utilizando r.js - -Muitas pessoas preferem usar AMD para sanar a organização do código durante o desenvolvimento, mas continuam querendo colocar um único arquivo de script em produção ao invés de realizarem centenas de requisições XHRs no carregamento da página. - -`require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos. - -Instale-o utilizando `npm`: -```shell -$ npm install requirejs -g -``` - -Agora você pode alimentá-lo com um arquivo de configuração: -```shell -$ r.js -o app.build.js -``` - -Para o nosso exemplo acima a configuração pode ser essa: -```javascript -/* file : app.build.js */ -({ - name : 'main', // nome do ponto de acesso - out : 'main-built.js', // nome o arquivo para gravar a saída - baseUrl : 'app', - paths : { - // `empty:` fala para o r.js que isso ainda deve ser baixado da CDN, usando - // o local especificado no `main.js` - jquery : 'empty:', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } -}) -``` - -Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`: -```html - -``` - -Uma incrível e detalhada visão geral [de build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponível no repositório do GitHub. - -### Tópicos não abordados nesse tutorial -* [Plugins de carregamento / transforms](http://requirejs.org/docs/plugins.html) -* [CommonJS style carregamento e exportação](http://requirejs.org/docs/commonjs.html) -* [Configuração avançada](http://requirejs.org/docs/api.html#config) -* [Shim configuration (carregando módulos sem AMD)](http://requirejs.org/docs/api.html#config-shim) -* [Carregando e otimizando CSS com require.js](http://requirejs.org/docs/optimization.html#onecss) -* [Usando almond.js para builds](https://github.com/jrburke/almond) - -### Outras leituras: - -* [Especificação oficial](https://github.com/amdjs/amdjs-api/wiki/AMD) -* [Por quê AMD?](http://requirejs.org/docs/whyamd.html) -* [Universal Module Definition](https://github.com/umdjs/umd) - -### Implementações: - -* [require.js](http://requirejs.org) -* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) -* [cujo.js](http://cujojs.com/) -* [curl.js](https://github.com/cujojs/curl) -* [lsjs](https://github.com/zazl/lsjs) -* [mmd](https://github.com/alexlawrence/mmd) diff --git a/pt-br/bf-pt.html.markdown b/pt-br/bf-pt.html.markdown new file mode 100644 index 00000000..52a5269e --- /dev/null +++ b/pt-br/bf-pt.html.markdown @@ -0,0 +1,86 @@ +--- +language: bf +filename: learnbf-pt.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br +--- + +Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o valor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-br/bf.html.markdown b/pt-br/bf.html.markdown deleted file mode 100644 index 52a5269e..00000000 --- a/pt-br/bf.html.markdown +++ /dev/null @@ -1,86 +0,0 @@ ---- -language: bf -filename: learnbf-pt.bf -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Suzane Sant Ana", "http://github.com/suuuzi"] - - ["Rodrigo Muniz", "http://github.com/muniz95"] -lang: pt-br ---- - -Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. - -Brainfuck é representado por um vetor com 30 000 células inicializadas em zero -e um ponteiro de dados que aponta para a célula atual. - -Existem 8 comandos: -+ : Incrementa o valor da célula atual em 1. -- : Decrementa o valor da célula atual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula atual. -[ : Se o valor da célula atual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula atual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vamos ver alguns exemplos básicos em brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor -65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tente descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e os multiplica. - -Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Porém existe um problema, no final do -ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -E isto é brainfuck. Simples, não? Por divertimento você pode escrever os -seus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck em outra linguagem. O interpretador é relativamente fácil de se -implementar, mas caso você seja masoquista, tente escrever um interpretador de -brainfuck… em brainfuck. diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown new file mode 100644 index 00000000..547f4817 --- /dev/null +++ b/pt-br/csharp-pt.html.markdown @@ -0,0 +1,896 @@ +--- +language: c# +filename: csharp-pt.cs +contributors: + - ["Robson Alves", "http://robsonalves.net/"] +lang: pt-br +--- + +C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. + +[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) + +```c# +// Comentário de linha única começa com // +/* +Múltipas linhas é desta forma +*/ +/// +/// Esta é uma documentação comentário XML que pode ser usado para gerar externo +/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// +//public void MethodOrClassOrOtherWithParsableHelp() {} + +// Especificar qual namespace seu código irá usar +// Os namespaces a seguir são padrões do .NET Framework Class Library +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Mas este aqui não é : +using System.Data.Entity; +// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` + +// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" +// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +namespace Learning.CSharp +{ + // Cada .cs deve conter uma classe com o mesmo nome do arquivo + // você está autorizado a contrariar isto, mas evite por sua sanidade. + public class AprenderCsharp + { + // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes. + public static void Syntax() + { + // Use Console.WriteLine para apresentar uma linha + Console.WriteLine("Hello World"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Para apresentar sem incluir uma nova linha, use Console.Write + Console.Write("Hello "); + Console.Write("World"); + + /////////////////////////////////////////////////// + // Tpos e Variáveis + // + // Declare uma variável usando + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor, +            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // Você pode acessar todos os caracteres de string com um indexador: + char charFromString = fooString[1]; // => 'e' + // Strings são imutáveis: você não pode fazer fooString[1] = 'X'; + + // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatando, baseado no sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Datas e formatações + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const ou read-only para fazer uma variável imutável + // os valores da const são calculados durante o tempo de compilação + const int HoursWorkPerWeek = 9001; + + /////////////////////////////////////////////////// + // Estrutura de Dados + /////////////////////////////////////////////////// + + // Matrizes - zero indexado + // O tamanho do array pode ser decidido ainda na declaração + // O formato para declarar uma matriz é o seguinte: + // [] = new []; + int[] intArray = new int[10]; + + // Outra forma de declarar & inicializar uma matriz + int[] y = { 9000, 1000, 1337 }; + + // Indexando uma matriz - Acessando um elemento + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Matriz são alteráveis + intArray[1] = 1; + + // Listas + // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis + // O formato de declarar uma lista é o seguinte: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // inicializar + // O <> são para genéricos - Confira está interessante seção do material + + // Lista não possuem valores padrão. + // Um valor deve ser adicionado antes e depois acessado pelo indexador + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Outras estruturas de dados para conferir: + // Pilha/Fila + // Dicionário (uma implementação de map de hash) + // HashSet + // Read-only Coleção + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis + + // Aritmética é clara + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparações de operadores + Console.WriteLine("3 == 2? " + (3 == 2)); // => falso + Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro + Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro + Console.WriteLine("3 < 2? " + (3 < 2)); // => falso + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro + + // Operadores bit a bit (bitwise) + /* + ~ Unário bitwise complemento + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusivo OR + | Bitwise inclusivo OR + */ + + // Incrementações + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Estrutura de Controle + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // Declaração if é como a linguagem C + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Operador Ternário + // Um simples if/else pode ser escrito da seguinte forma + // ? : + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + // Inicia a interação 100 vezes, fooDoWhile 0->99 + if (false) + continue; // pule a intereção atual para apróxima + + fooDoWhile++; + + if (fooDoWhile == 50) + break; // Interrompe o laço inteiro + + } while (fooDoWhile < 100); + + //estrutura de loop for => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterado 10 vezes, fooFor 0->9 + } + + // For Each Loop + // Estrutura do foreach => foreach( in ) + // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable + // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework + // implementa uma ou mais destas interfaces. + // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Iterated over all the characters in the string + } + + // Switch Case + // Um switch funciona com os tipos de dados byte, short, char, e int. + // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum), + // A classe String, and a few special classes that wrap + // tipos primitívos: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw a FormatException on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + // A method that differs only in return type is not unique + public static void MethodSignatures( + ref int maxCount, // Pass by reference + out int count) + { + count = 15; // out param must be assigned before control leaves the method + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // BY REF AND OUT PARAMETERS + int maxCount = 0, count; // ref params must have value + MethodSignatures(ref maxCount, out count); + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // ERROR HANDLING - coping with an uncertain world + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // will no longer execute because CreateWithGears throws an exception + string some = ""; + if (true) some = null; + some.ToLower(); // throws a NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // catch all other exceptions + { + throw new ApplicationException("It hit the fan", ex); + // throw; // A rethrow that preserves the callstack + } + // catch { } // catch-all without capturing the Exception + finally + { + // executes after try or catch + } + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + + // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on + [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // need to set the values manually! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + + // Static members belong to the type itself rather then specific object. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + public static int BicyclesCreated { get; set; } + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } + + // Properties can be auto-implemented + public int FrameSize + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new InvalidOperationException("You can't change gears on a PennyFarthing"); + } + } + + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // Oops, can't do this! + return penny; + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbContext + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Attributes + * async/await, yield, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) diff --git a/pt-br/csharp.html.markdown b/pt-br/csharp.html.markdown deleted file mode 100644 index 547f4817..00000000 --- a/pt-br/csharp.html.markdown +++ /dev/null @@ -1,896 +0,0 @@ ---- -language: c# -filename: csharp-pt.cs -contributors: - - ["Robson Alves", "http://robsonalves.net/"] -lang: pt-br ---- - -C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. - -[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) - -```c# -// Comentário de linha única começa com // -/* -Múltipas linhas é desta forma -*/ -/// -/// Esta é uma documentação comentário XML que pode ser usado para gerar externo -/// documentação ou fornecer ajuda de contexto dentro de um IDE -/// -//public void MethodOrClassOrOtherWithParsableHelp() {} - -// Especificar qual namespace seu código irá usar -// Os namespaces a seguir são padrões do .NET Framework Class Library -using System; -using System.Collections.Generic; -using System.Dynamic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using System.IO; - -// Mas este aqui não é : -using System.Data.Entity; -// Para que consiga utiliza-lo, você precisa adicionar novas referências -// Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` - -// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" -// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; -namespace Learning.CSharp -{ - // Cada .cs deve conter uma classe com o mesmo nome do arquivo - // você está autorizado a contrariar isto, mas evite por sua sanidade. - public class AprenderCsharp - { - // Sintaxe Básica - Pule para as CARACTERÍSTICAS INTERESSANTES se você ja usou Java ou C++ antes. - public static void Syntax() - { - // Use Console.WriteLine para apresentar uma linha - Console.WriteLine("Hello World"); - Console.WriteLine( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // Para apresentar sem incluir uma nova linha, use Console.Write - Console.Write("Hello "); - Console.Write("World"); - - /////////////////////////////////////////////////// - // Tpos e Variáveis - // - // Declare uma variável usando - /////////////////////////////////////////////////// - - // Sbyte - Signed 8-bit integer - // (-128 <= sbyte <= 127) - sbyte fooSbyte = 100; - - // Byte - Unsigned 8-bit integer - // (0 <= byte <= 255) - byte fooByte = 100; - - // Short - 16-bit integer - // Signed - (-32,768 <= short <= 32,767) - // Unsigned - (0 <= ushort <= 65,535) - short fooShort = 10000; - ushort fooUshort = 10000; - - // Integer - 32-bit integer - int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) - uint fooUint = 1; // (0 <= uint <= 4,294,967,295) - - // Long - 64-bit integer - long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) - // Numbers default to being int or uint depending on size. - // L is used to denote that this variable value is of type long or ulong - - // Double - Double-precision 64-bit IEEE 754 Floating Point - double fooDouble = 123.4; // Precision: 15-16 digits - - // Float - Single-precision 32-bit IEEE 754 Floating Point - float fooFloat = 234.5f; // Precision: 7 digits - // f is used to denote that this variable value is of type float - - // Decimal - a 128-bits data type, with more precision than other floating-point types, - // suited for financial and monetary calculations - decimal fooDecimal = 150.3m; - - // Boolean - true & false - bool fooBoolean = true; // or false - - // Char - A single 16-bit Unicode character - char fooChar = 'A'; - - // Strings - ao contrário dos anteriores tipos base, que são todos os tipos de valor, -            // Uma string é um tipo de referência. Ou seja, você pode configurá-lo como nulo - string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; - Console.WriteLine(fooString); - - // Você pode acessar todos os caracteres de string com um indexador: - char charFromString = fooString[1]; // => 'e' - // Strings são imutáveis: você não pode fazer fooString[1] = 'X'; - - // Compare strings com sua atual cultura, ignorando maiúsculas e minúsculas - string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); - - // Formatando, baseado no sprintf - string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - - // Datas e formatações - DateTime fooDate = DateTime.Now; - Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - - // Você pode juntar um string em mais de duas linhas com o símbolo @. Para escapar do " use "" - string bazString = @"Here's some stuff -on a new line! ""Wow!"", the masses cried"; - - // Use const ou read-only para fazer uma variável imutável - // os valores da const são calculados durante o tempo de compilação - const int HoursWorkPerWeek = 9001; - - /////////////////////////////////////////////////// - // Estrutura de Dados - /////////////////////////////////////////////////// - - // Matrizes - zero indexado - // O tamanho do array pode ser decidido ainda na declaração - // O formato para declarar uma matriz é o seguinte: - // [] = new []; - int[] intArray = new int[10]; - - // Outra forma de declarar & inicializar uma matriz - int[] y = { 9000, 1000, 1337 }; - - // Indexando uma matriz - Acessando um elemento - Console.WriteLine("intArray @ 0: " + intArray[0]); - // Matriz são alteráveis - intArray[1] = 1; - - // Listas - // Listas são usadas frequentemente tanto quanto matriz por serem mais flexiveis - // O formato de declarar uma lista é o seguinte: - // List = new List(); - List intList = new List(); - List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // inicializar - // O <> são para genéricos - Confira está interessante seção do material - - // Lista não possuem valores padrão. - // Um valor deve ser adicionado antes e depois acessado pelo indexador - intList.Add(1); - Console.WriteLine("intList @ 0: " + intList[0]); - - // Outras estruturas de dados para conferir: - // Pilha/Fila - // Dicionário (uma implementação de map de hash) - // HashSet - // Read-only Coleção - // Tuple (.Net 4+) - - /////////////////////////////////////// - // Operadores - /////////////////////////////////////// - Console.WriteLine("\n->Operators"); - - int i1 = 1, i2 = 2; // Forma curta para declarar diversas variáveis - - // Aritmética é clara - Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 - - // Modulo - Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - - // Comparações de operadores - Console.WriteLine("3 == 2? " + (3 == 2)); // => falso - Console.WriteLine("3 != 2? " + (3 != 2)); // => verdadeiro - Console.WriteLine("3 > 2? " + (3 > 2)); // => verdadeiro - Console.WriteLine("3 < 2? " + (3 < 2)); // => falso - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => verdadeiro - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => verdadeiro - - // Operadores bit a bit (bitwise) - /* - ~ Unário bitwise complemento - << Signed left shift - >> Signed right shift - & Bitwise AND - ^ Bitwise exclusivo OR - | Bitwise inclusivo OR - */ - - // Incrementações - int i = 0; - Console.WriteLine("\n->Inc/Dec-rementation"); - Console.WriteLine(i++); //i = 1. Post-Incrementation - Console.WriteLine(++i); //i = 2. Pre-Incrementation - Console.WriteLine(i--); //i = 1. Post-Decrementation - Console.WriteLine(--i); //i = 0. Pre-Decrementation - - /////////////////////////////////////// - // Estrutura de Controle - /////////////////////////////////////// - Console.WriteLine("\n->Control Structures"); - - // Declaração if é como a linguagem C - int j = 10; - if (j == 10) - { - Console.WriteLine("I get printed"); - } - else if (j > 10) - { - Console.WriteLine("I don't"); - } - else - { - Console.WriteLine("I also don't"); - } - - // Operador Ternário - // Um simples if/else pode ser escrito da seguinte forma - // ? : - int toCompare = 17; - string isTrue = toCompare == 17 ? "True" : "False"; - - // While loop - int fooWhile = 0; - while (fooWhile < 100) - { - //Iterated 100 times, fooWhile 0->99 - fooWhile++; - } - - // Do While Loop - int fooDoWhile = 0; - do - { - // Inicia a interação 100 vezes, fooDoWhile 0->99 - if (false) - continue; // pule a intereção atual para apróxima - - fooDoWhile++; - - if (fooDoWhile == 50) - break; // Interrompe o laço inteiro - - } while (fooDoWhile < 100); - - //estrutura de loop for => for(; ; ) - for (int fooFor = 0; fooFor < 10; fooFor++) - { - //Iterado 10 vezes, fooFor 0->9 - } - - // For Each Loop - // Estrutura do foreach => foreach( in ) - // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable - // Toda a coleção de tipos (Array, List, Dictionary...) no .Net framework - // implementa uma ou mais destas interfaces. - // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable) - foreach (char character in "Hello World".ToCharArray()) - { - //Iterated over all the characters in the string - } - - // Switch Case - // Um switch funciona com os tipos de dados byte, short, char, e int. - // Isto também funcional com tipos enumeradors (discutidos em Tipos Enum), - // A classe String, and a few special classes that wrap - // tipos primitívos: Character, Byte, Short, and Integer. - int month = 3; - string monthString; - switch (month) - { - case 1: - monthString = "January"; - break; - case 2: - monthString = "February"; - break; - case 3: - monthString = "March"; - break; - // You can assign more than one case to an action - // But you can't add an action without a break before another case - // (if you want to do this, you would have to explicitly add a goto case x - case 6: - case 7: - case 8: - monthString = "Summer time!!"; - break; - default: - monthString = "Some other month"; - break; - } - - /////////////////////////////////////// - // Converting Data Types And Typecasting - /////////////////////////////////////// - - // Converting data - - // Convert String To Integer - // this will throw a FormatException on failure - int.Parse("123");//returns an integer version of "123" - - // try parse will default to type default on failure - // in this case: 0 - int tryInt; - if (int.TryParse("123", out tryInt)) // Function is boolean - Console.WriteLine(tryInt); // 123 - - // Convert Integer To String - // Convert class has a number of methods to facilitate conversions - Convert.ToString(123); - // or - tryInt.ToString(); - - // Casting - // Cast decimal 15 to a int - // and then implicitly cast to long - long x = (int) 15M; - } - - /////////////////////////////////////// - // CLASSES - see definitions at end of file - /////////////////////////////////////// - public static void Classes() - { - // See Declaration of objects at end of file - - // Use new to instantiate a class - Bicycle trek = new Bicycle(); - - // Call object methods - trek.SpeedUp(3); // You should always use setter and getter methods - trek.Cadence = 100; - - // ToString is a convention to display the value of this Object. - Console.WriteLine("trek info: " + trek.Info()); - - // Instantiate a new Penny Farthing - PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("funbike info: " + funbike.Info()); - - Console.Read(); - } // End main method - - // CONSOLE ENTRY A console application must have a main method as an entry point - public static void Main(string[] args) - { - OtherInterestingFeatures(); - } - - // - // INTERESTING FEATURES - // - - // DEFAULT METHOD SIGNATURES - - public // Visibility - static // Allows for direct call on class without object - int // Return Type, - MethodSignatures( - int maxCount, // First variable, expects an int - int count = 0, // will default the value to 0 if not passed in - int another = 3, - params string[] otherParams // captures all other parameters passed to method - ) - { - return -1; - } - - // Methods can have the same name, as long as the signature is unique - // A method that differs only in return type is not unique - public static void MethodSignatures( - ref int maxCount, // Pass by reference - out int count) - { - count = 15; // out param must be assigned before control leaves the method - } - - // GENERICS - // The classes for TKey and TValue is specified by the user calling this function. - // This method emulates the SetDefault of Python - public static TValue SetDefault( - IDictionary dictionary, - TKey key, - TValue defaultItem) - { - TValue result; - if (!dictionary.TryGetValue(key, out result)) - return dictionary[key] = defaultItem; - return result; - } - - // You can narrow down the objects that are passed in - public static void IterateAndPrint(T toPrint) where T: IEnumerable - { - // We can iterate, since T is a IEnumerable - foreach (var item in toPrint) - // Item is an int - Console.WriteLine(item.ToString()); - } - - public static void OtherInterestingFeatures() - { - // OPTIONAL PARAMETERS - MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); - MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones - - // BY REF AND OUT PARAMETERS - int maxCount = 0, count; // ref params must have value - MethodSignatures(ref maxCount, out count); - - // EXTENSION METHODS - int i = 3; - i.Print(); // Defined below - - // NULLABLE TYPES - great for database interaction / return values - // any value type (i.e. not a class) can be made nullable by suffixing a ? - // ? = - int? nullable = null; // short hand for Nullable - Console.WriteLine("Nullable variable: " + nullable); - bool hasValue = nullable.HasValue; // true if not null - - // ?? is syntactic sugar for specifying default value (coalesce) - // in case variable is null - int notNullable = nullable ?? 0; // 0 - - // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: - var magic = "magic is a string, at compile time, so you still get type safety"; - // magic = 9; will not work as magic is a string, not an int - - // GENERICS - // - var phonebook = new Dictionary() { - {"Sarah", "212 555 5555"} // Add some entries to the phone book - }; - - // Calling SETDEFAULT defined as a generic above - Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone - // nb, you don't need to specify the TKey and TValue since they can be - // derived implicitly - Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 - - // LAMBDA EXPRESSIONS - allow you to write code in line - Func square = (x) => x * x; // Last T item is the return value - Console.WriteLine(square(3)); // 9 - - // ERROR HANDLING - coping with an uncertain world - try - { - var funBike = PennyFarthing.CreateWithGears(6); - - // will no longer execute because CreateWithGears throws an exception - string some = ""; - if (true) some = null; - some.ToLower(); // throws a NullReferenceException - } - catch (NotSupportedException) - { - Console.WriteLine("Not so much fun now!"); - } - catch (Exception ex) // catch all other exceptions - { - throw new ApplicationException("It hit the fan", ex); - // throw; // A rethrow that preserves the callstack - } - // catch { } // catch-all without capturing the Exception - finally - { - // executes after try or catch - } - - // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. - // Most of objects that access unmanaged resources (file handle, device contexts, etc.) - // implement the IDisposable interface. The using statement takes care of - // cleaning those IDisposable objects for you. - using (StreamWriter writer = new StreamWriter("log.txt")) - { - writer.WriteLine("Nothing suspicious here"); - // At the end of scope, resources will be released. - // Even if an exception is thrown. - } - - // PARALLEL FRAMEWORK - // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", - "http://www.shaunmccarthy.com" - }; - var responses = new Dictionary(); - - // Will spin up separate threads for each request, and join on them - // before going to the next step! - Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads - website => - { - // Do something that takes a long time on the file - using (var r = WebRequest.Create(new Uri(website)).GetResponse()) - { - responses[website] = r.ContentType; - } - }); - - // This won't happen till after all requests have been completed - foreach (var key in responses.Keys) - Console.WriteLine("{0}:{1}", key, responses[key]); - - // DYNAMIC OBJECTS (great for working with other languages) - dynamic student = new ExpandoObject(); - student.FirstName = "First Name"; // No need to define class first! - - // You can even add methods (returns a string, and takes in a string) - student.Introduce = new Func( - (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); - Console.WriteLine(student.Introduce("Beth")); - - // IQUERYABLE - almost all collections implement this, which gives you a lot of - // very useful Map / Filter / Reduce style methods - var bikes = new List(); - bikes.Sort(); // Sorts the array - bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels - var result = bikes - .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) - .Where(b => b.IsBroken && b.HasTassles) - .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable - - var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection - - // Create a list of IMPLICIT objects based on some parameters of the bike - var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Hard to show here, but you get type ahead completion since the compiler can implicitly work - // out the types above! - foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) - Console.WriteLine(bikeSummary.Name); - - // ASPARALLEL - // And this is where things get wicked - combines linq and parallel operations - var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // this will happen in parallel! Threads will automagically be spun up and the - // results divvied amongst them! Amazing for large datasets when you have lots of - // cores - - // LINQ - maps a store to IQueryable objects, with delayed execution - // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document - var db = new BikeRepository(); - - // execution is delayed, which is great when querying a database - var filter = db.Bikes.Where(b => b.HasTassles); // no query run - if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality - filter = filter.Where(b => b.IsBroken); // no query run - - var query = filter - .OrderBy(b => b.Wheels) - .ThenBy(b => b.Name) - .Select(b => b.Name); // still no query run - - // Now the query runs, but opens a reader, so only populates are you iterate through - foreach (string bike in query) - Console.WriteLine(result); - - - - } - - } // End LearnCSharp class - - // You can include other classes in a .cs file - - public static class Extensions - { - // EXTENSION FUNCTIONS - public static void Print(this object obj) - { - Console.WriteLine(obj.ToString()); - } - } - - // Class Declaration Syntax: - // class { - // //data fields, constructors, functions all inside. - // //functions are called as methods in Java. - // } - - public class Bicycle - { - // Bicycle's Fields/Variables - public int Cadence // Public: Can be accessed from anywhere - { - get // get - define a method to retrieve the property - { - return _cadence; - } - set // set - define a method to set a proprety - { - _cadence = value; // Value is the value passed in to the setter - } - } - private int _cadence; - - protected virtual int Gear // Protected: Accessible from the class and subclasses - { - get; // creates an auto property so you don't need a member field - set; - } - - internal int Wheels // Internal: Accessible from within the assembly - { - get; - private set; // You can set modifiers on the get/set methods - } - - int _speed; // Everything is private by default: Only accessible from within this class. - // can also use keyword private - public string Name { get; set; } - - // Enum is a value type that consists of a set of named constants - // It is really just mapping a name to a value (an int, unless specified otherwise). - // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. - // An enum can't contain the same value twice. - public enum BikeBrand - { - AIST, - BMC, - Electra = 42, //you can explicitly set a value to a name - Gitane // 43 - } - // We defined this type inside a Bicycle class, so it is a nested type - // Code outside of this class should reference this type as Bicycle.Brand - - public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type - - // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on - [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc - public enum BikeAccessories - { - None = 0, - Bell = 1, - MudGuards = 2, // need to set the values manually! - Racks = 4, - Lights = 8, - FullPackage = Bell | MudGuards | Racks | Lights - } - - // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) - // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell - public BikeAccessories Accessories { get; set; } - - // Static members belong to the type itself rather then specific object. - // You can access them without a reference to any object: - // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); - public static int BicyclesCreated { get; set; } - - // readonly values are set at run time - // they can only be assigned upon declaration or in a constructor - readonly bool _hasCardsInSpokes = false; // read-only private - - // Constructors are a way of creating classes - // This is a default constructor - public Bicycle() - { - this.Gear = 1; // you can access members of the object with the keyword this - Cadence = 50; // but you don't always need it - _speed = 5; - Name = "Bontrager"; - Brand = BikeBrand.AIST; - BicyclesCreated++; - } - - // This is a specified constructor (it contains arguments) - public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // calls base first - { - Gear = startGear; - Cadence = startCadence; - _speed = startSpeed; - Name = name; - _hasCardsInSpokes = hasCardsInSpokes; - Brand = brand; - } - - // Constructors can be chained - public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : - this(startCadence, startSpeed, 0, "big wheels", true, brand) - { - } - - // Function Syntax: - // () - - // classes can implement getters and setters for their fields - // or they can implement properties (this is the preferred way in C#) - - // Method parameters can have default values. - // In this case, methods can be called with these parameters omitted - public void SpeedUp(int increment = 1) - { - _speed += increment; - } - - public void SlowDown(int decrement = 1) - { - _speed -= decrement; - } - - // properties get/set values - // when only data needs to be accessed, consider using properties. - // properties may have either get or set, or both - private bool _hasTassles; // private variable - public bool HasTassles // public accessor - { - get { return _hasTassles; } - set { _hasTassles = value; } - } - - // You can also define an automatic property in one line - // this syntax will create a backing field automatically. - // You can set an access modifier on either the getter or the setter (or both) - // to restrict its access: - public bool IsBroken { get; private set; } - - // Properties can be auto-implemented - public int FrameSize - { - get; - // you are able to specify access modifiers for either get or set - // this means only Bicycle class can call set on Framesize - private set; - } - - // It's also possible to define custom Indexers on objects. - // All though this is not entirely useful in this example, you - // could do bicycle[0] which yields "chris" to get the first passenger or - // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) - private string[] passengers = { "chris", "phil", "darren", "regina" }; - - public string this[int i] - { - get { - return passengers[i]; - } - - set { - return passengers[i] = value; - } - } - - //Method to display the attribute values of this Object. - public virtual string Info() - { - return "Gear: " + Gear + - " Cadence: " + Cadence + - " Speed: " + _speed + - " Name: " + Name + - " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + - "\n------------------------------\n" - ; - } - - // Methods can also be static. It can be useful for helper methods - public static bool DidWeCreateEnoughBycles() - { - // Within a static method, we only can reference static class members - return BicyclesCreated > 9000; - } // If your class only needs static members, consider marking the class itself as static. - - - } // end class Bicycle - - // PennyFarthing is a subclass of Bicycle - class PennyFarthing : Bicycle - { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) - - // calling parent constructor - public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) - { - } - - protected override int Gear - { - get - { - return 0; - } - set - { - throw new InvalidOperationException("You can't change gears on a PennyFarthing"); - } - } - - public static PennyFarthing CreateWithGears(int gears) - { - var penny = new PennyFarthing(1, 1); - penny.Gear = gears; // Oops, can't do this! - return penny; - } - - public override string Info() - { - string result = "PennyFarthing bicycle "; - result += base.ToString(); // Calling the base version of the method - return result; - } - } - - // Interfaces only contain signatures of the members, without the implementation. - interface IJumpable - { - void Jump(int meters); // all interface members are implicitly public - } - - interface IBreakable - { - bool Broken { get; } // interfaces can contain properties as well as methods & events - } - - // Class can inherit only one other class, but can implement any amount of interfaces - class MountainBike : Bicycle, IJumpable, IBreakable - { - int damage = 0; - - public void Jump(int meters) - { - damage += meters; - } - - public bool Broken - { - get - { - return damage > 100; - } - } - } - - /// - /// Used to connect to DB for LinqToSql example. - /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) - /// http://msdn.microsoft.com/en-us/data/jj193542.aspx - /// - public class BikeRepository : DbContext - { - public BikeRepository() - : base() - { - } - - public DbSet Bikes { get; set; } - } -} // End Namespace -``` - -## Topics Not Covered - - * Attributes - * async/await, yield, pragma directives - * Web Development - * ASP.NET MVC & WebApi (new) - * ASP.NET Web Forms (old) - * WebMatrix (tool) - * Desktop Development - * Windows Presentation Foundation (WPF) (new) - * Winforms (old) - -## Further Reading - - * [DotNetPerls](http://www.dotnetperls.com) - * [C# in Depth](http://manning.com/skeet2) - * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) - * [LINQ](http://shop.oreilly.com/product/9780596519254.do) - * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) - * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) - * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) - * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) - * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown new file mode 100644 index 00000000..f8c56101 --- /dev/null +++ b/pt-br/elixir-pt.html.markdown @@ -0,0 +1,412 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br +filename: learnelixir-pt.ex +--- + +Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. +É totalmente compatível com Erlang, porém conta com uma sintaxe mais padronizada +e muitos outros recursos. + +```elixir + +# Comentários de linha única começam com um símbolo de número. + +# Não há comentários de múltiplas linhas, +# mas você pode empilhar os comentários. + +# Para usar o shell do elixir use o comando `iex`. +# Compile seus módulos com o comando `elixirc`. + +# Ambos devem estar em seu path se você instalou o Elixir corretamente. + +## --------------------------- +## -- Tipos Básicos +## --------------------------- + +# Há números +3 # integer +0x1F # integer +3.0 # float + +# Atoms, que são literais, uma constante com nome. Elas começam com `:`. +:hello # atom + +# Tuplas que são guardadas contiguamente em memória. +{1,2,3} # tupla + +# Podemos acessar um elemento de uma tupla om a função `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listas que são implementadas como listas ligadas. +[1,2,3] # lista + +# Podemos acessar a primeira posição (head) e o resto (tail) de uma lista como a seguir: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# Em elixir, bem como em Erlang, o sinal `=` denota pattern match, +# e não uma atribuição. +# +# Isto significa que o que estiver à esquerda (pattern) é comparado com o que +# estiver à direita. +# +# É assim que o exemplo acima de acesso à head e tail de uma lista funciona. + +# Um pattern match retornará erro quando os lados não conferem, como neste exemplo +# onde as tuplas tem diferentes tamanhos. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Também há binários +<<1,2,3>> # binary + +# Strings e char lists +"hello" # string +'hello' # char list + +# Strings de múltiplas linhas +""" +Strings +de múltiplas +linhas. +""" +#=> "Strings\nde múltiplas\nlinhas" + +# Strings são sempre codificadas em UTF-8: +"héllò" #=> "héllò" + +# Strings são de fato apenas binários, e char lists apenas listas. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` em elixir retorna o valor ASCII para a letra `a` +?a #=> 97 + +# Para concatenar listas use `++`, para binários use `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +# Ranges são representados como `início..fim` (ambos inclusivos) +1..10 #=> 1..10 +menor..maior = 1..10 # Pattern matching pode ser usada em ranges também +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- Operadores +## --------------------------- + +# Matemática básica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# Em elixir o operador `/` sempre retorna um float. + +# Para divisão de inteiros use `div` +div(10, 2) #=> 5 + +# Para obter o resto da divisão use `rem` +rem(10, 3) #=> 1 + +# Há também operadores booleanos: `or`, `and` e `not`. +# Estes operadores esperam um booleano como primeiro argumento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir também fornece `||`, `&&` e `!` que aceitam argumentos de qualquer tipo. +# Todos os valores exceto `false` e `nil` serão avaliados como true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Para comparações temos: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` são mais estritos ao comparar integers e floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Podemos comparar também dois tipos de dados diferentes: +1 < :hello #=> true + +# A regra de ordenação no geral é definida abaixo: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# Ao citar Joe Armstrong nisto: "A ordem de fato não é importante, +# mas que uma ordem total esteja bem definida é importante." + +## --------------------------- +## -- Fluxo de Controle +## --------------------------- + +# expressão `if` +if false do + "Isso nunca será visto" +else + "Isso será" +end + +# Também há `unless` +unless true do + "Isso nunca será visto" +else + "Isso será" +end + +# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela. + +# `case` nos permite comparar um valor com muitos patterns: +case {:um, :dois} do + {:quatro, :cinco} -> + "Isso não corresponde" + {:um, x} -> + "Isso corresponde e vincula `x` a `:dois`" + _ -> + "Isso corresponde a qualquer valor" +end + +# É comum vincular o valor a `_` se não precisamos dele. +# Por exemplo, se apenas a head de uma lista nos interessa: +[head | _] = [1,2,3] +head #=> 1 + +# Para melhor legibilidade podemos fazer o seguinte: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` nos permite verificar várias condições ao mesmo tempo. +# Use `cond` em vez de aninhar vários `if`'s. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + 1 + 2 == 3 -> + "Mas eu serei" +end + +# É comum definir a última condição igual a `true`, que sempre irá corresponder. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + true -> + "Mas eu serei (isso é essencialmente um else)" +end + +# `try/catch` é usado para capturar valores que são lançados, também suporta uma +# cláusula `after` que é invocada havendo um valor capturado ou não. +try do + throw(:hello) +catch + message -> "Deu #{mensagem}." +after + IO.puts("Sou o after.") +end +#=> Sou o after +# "Deu :hello" + +## --------------------------- +## -- Módulos e Funções +## --------------------------- + +# Funções Anônimas (repare o ponto) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Elas também aceitam várias cláusulas e guards. +# Guards permitem ajustes finos de pattern matching, +# sendo indicados pela palavra `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir também fornece várias funções embutidas. +# Estas estão disponíveis no escopo atual. +is_number(10) #=> true +is_list("ola") #=> false +elem({1,2,3}, 0) #=> 1 + +# Você pode agrupar algumas funções em um módulo. Dentro de um módulo use `def` +# para definir suas funções. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Para compilar o módulo Math salve-o como `math.ex` e use `elixirc` +# em seu terminal: elixirc math.ex + +# Dentro de um módulo podemos definir funções com `def` e funções privadas com `defp`. +# Uma função definida com `def` pode ser invocada por outros módulos, +# já uma função privada pode ser invocada apenas localmente. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Declarações de funções também suportam guards cláusulas múltiplas: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Devido à imutabilidade, recursão é uma grande parte do elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Módulos do elixir suportam atributos, hpa atributos embutidos e você +# pode também adicionar os seus próprios. +defmodule MyMod do + @moduledoc """ + Este é um atributo embutido em um módulo de exemplo. + """ + + @my_data 100 # Este é um atributo customizado. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- Structs e Exceptions +## --------------------------- + +# Structs são extensões no topo de mapas que trazem valores padrão, +# garantias em tempo de compilação e polimorfismo para o Elixir. +defmodule Pessoa do + defstruct nome: nil, idade: 0, peso: 0 +end + +joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } +#=> %Pessoa{idade: 30, peso: 180, nome: "Joe"} + +# Acessa o valor de nome +joe_info.name #=> "Joe" + +# Atualiza o valor de idade +older_joe_info = %{ joe_info | idade: 31 } +#=> %Pessoa{idade: 31, peso: 180, nome: "Joe"} + +# O bloco `try` com a palavra `rescue` é usado para manipular exceções +try do + raise "algum erro" +rescue + RuntimeError -> "resgatado um erro em tempo de execução" + _error -> "isso resgatará qualquer erro" +end + +# Toda exceção possui uma mensagem +try do + raise "algum erro" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrência +## --------------------------- + +# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para +# escrever programas concorrentes em elixir são três primitivos: spawning processes, +# sending messages e receiving messages. + +# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função +# como argumento. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` retorna um pid (process identifier), você pode usar esse pid para enviar +# mensagens ao processo. Para envio de mensagens usamos o operador `send`. +# Para tudo isso ser útil precisamos estar aptos a receber mensagens. Isto é +# realizado com o mecanismo `receive`: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compile o módulo e crie um processo que avalie `area_loop` no shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Envia uma mensagem ao `pid` correspondente a um pattern na declaração de recebimento +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# O shell também é um processo, você pode usar `self` para obter o pid atual +self() #=> #PID<0.27.0> +``` + +## Referências + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) da [página do elixir](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) por Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) por Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) por Joe Armstrong diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown deleted file mode 100644 index f8c56101..00000000 --- a/pt-br/elixir.html.markdown +++ /dev/null @@ -1,412 +0,0 @@ ---- -language: elixir -contributors: - - ["Joao Marques", "http://github.com/mrshankly"] - - ["Dzianis Dashkevich", "https://github.com/dskecse"] -translators: - - ["Rodrigo Muniz", "http://github.com/muniz95"] -lang: pt-br -filename: learnelixir-pt.ex ---- - -Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. -É totalmente compatível com Erlang, porém conta com uma sintaxe mais padronizada -e muitos outros recursos. - -```elixir - -# Comentários de linha única começam com um símbolo de número. - -# Não há comentários de múltiplas linhas, -# mas você pode empilhar os comentários. - -# Para usar o shell do elixir use o comando `iex`. -# Compile seus módulos com o comando `elixirc`. - -# Ambos devem estar em seu path se você instalou o Elixir corretamente. - -## --------------------------- -## -- Tipos Básicos -## --------------------------- - -# Há números -3 # integer -0x1F # integer -3.0 # float - -# Atoms, que são literais, uma constante com nome. Elas começam com `:`. -:hello # atom - -# Tuplas que são guardadas contiguamente em memória. -{1,2,3} # tupla - -# Podemos acessar um elemento de uma tupla om a função `elem`: -elem({1, 2, 3}, 0) #=> 1 - -# Listas que são implementadas como listas ligadas. -[1,2,3] # lista - -# Podemos acessar a primeira posição (head) e o resto (tail) de uma lista como a seguir: -[head | tail] = [1,2,3] -head #=> 1 -tail #=> [2,3] - -# Em elixir, bem como em Erlang, o sinal `=` denota pattern match, -# e não uma atribuição. -# -# Isto significa que o que estiver à esquerda (pattern) é comparado com o que -# estiver à direita. -# -# É assim que o exemplo acima de acesso à head e tail de uma lista funciona. - -# Um pattern match retornará erro quando os lados não conferem, como neste exemplo -# onde as tuplas tem diferentes tamanhos. -# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} - -# Também há binários -<<1,2,3>> # binary - -# Strings e char lists -"hello" # string -'hello' # char list - -# Strings de múltiplas linhas -""" -Strings -de múltiplas -linhas. -""" -#=> "Strings\nde múltiplas\nlinhas" - -# Strings são sempre codificadas em UTF-8: -"héllò" #=> "héllò" - -# Strings são de fato apenas binários, e char lists apenas listas. -<> #=> "abc" -[?a, ?b, ?c] #=> 'abc' - -# `?a` em elixir retorna o valor ASCII para a letra `a` -?a #=> 97 - -# Para concatenar listas use `++`, para binários use `<>` -[1,2,3] ++ [4,5] #=> [1,2,3,4,5] -'hello ' ++ 'world' #=> 'hello world' - -<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> -"hello " <> "world" #=> "hello world" - -# Ranges são representados como `início..fim` (ambos inclusivos) -1..10 #=> 1..10 -menor..maior = 1..10 # Pattern matching pode ser usada em ranges também -[lower, upper] #=> [1, 10] - -## --------------------------- -## -- Operadores -## --------------------------- - -# Matemática básica -1 + 1 #=> 2 -10 - 5 #=> 5 -5 * 2 #=> 10 -10 / 2 #=> 5.0 - -# Em elixir o operador `/` sempre retorna um float. - -# Para divisão de inteiros use `div` -div(10, 2) #=> 5 - -# Para obter o resto da divisão use `rem` -rem(10, 3) #=> 1 - -# Há também operadores booleanos: `or`, `and` e `not`. -# Estes operadores esperam um booleano como primeiro argumento. -true and true #=> true -false or true #=> true -# 1 and true #=> ** (ArgumentError) argument error - -# Elixir também fornece `||`, `&&` e `!` que aceitam argumentos de qualquer tipo. -# Todos os valores exceto `false` e `nil` serão avaliados como true. -1 || true #=> 1 -false && 1 #=> false -nil && 20 #=> nil -!true #=> false - -# Para comparações temos: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` -1 == 1 #=> true -1 != 1 #=> false -1 < 2 #=> true - -# `===` e `!==` são mais estritos ao comparar integers e floats: -1 == 1.0 #=> true -1 === 1.0 #=> false - -# Podemos comparar também dois tipos de dados diferentes: -1 < :hello #=> true - -# A regra de ordenação no geral é definida abaixo: -# number < atom < reference < functions < port < pid < tuple < list < bit string - -# Ao citar Joe Armstrong nisto: "A ordem de fato não é importante, -# mas que uma ordem total esteja bem definida é importante." - -## --------------------------- -## -- Fluxo de Controle -## --------------------------- - -# expressão `if` -if false do - "Isso nunca será visto" -else - "Isso será" -end - -# Também há `unless` -unless true do - "Isso nunca será visto" -else - "Isso será" -end - -# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela. - -# `case` nos permite comparar um valor com muitos patterns: -case {:um, :dois} do - {:quatro, :cinco} -> - "Isso não corresponde" - {:um, x} -> - "Isso corresponde e vincula `x` a `:dois`" - _ -> - "Isso corresponde a qualquer valor" -end - -# É comum vincular o valor a `_` se não precisamos dele. -# Por exemplo, se apenas a head de uma lista nos interessa: -[head | _] = [1,2,3] -head #=> 1 - -# Para melhor legibilidade podemos fazer o seguinte: -[head | _tail] = [:a, :b, :c] -head #=> :a - -# `cond` nos permite verificar várias condições ao mesmo tempo. -# Use `cond` em vez de aninhar vários `if`'s. -cond do - 1 + 1 == 3 -> - "Nunca serei visto" - 2 * 5 == 12 -> - "Nem eu" - 1 + 2 == 3 -> - "Mas eu serei" -end - -# É comum definir a última condição igual a `true`, que sempre irá corresponder. -cond do - 1 + 1 == 3 -> - "Nunca serei visto" - 2 * 5 == 12 -> - "Nem eu" - true -> - "Mas eu serei (isso é essencialmente um else)" -end - -# `try/catch` é usado para capturar valores que são lançados, também suporta uma -# cláusula `after` que é invocada havendo um valor capturado ou não. -try do - throw(:hello) -catch - message -> "Deu #{mensagem}." -after - IO.puts("Sou o after.") -end -#=> Sou o after -# "Deu :hello" - -## --------------------------- -## -- Módulos e Funções -## --------------------------- - -# Funções Anônimas (repare o ponto) -square = fn(x) -> x * x end -square.(5) #=> 25 - -# Elas também aceitam várias cláusulas e guards. -# Guards permitem ajustes finos de pattern matching, -# sendo indicados pela palavra `when`: -f = fn - x, y when x > 0 -> x + y - x, y -> x * y -end - -f.(1, 3) #=> 4 -f.(-1, 3) #=> -3 - -# Elixir também fornece várias funções embutidas. -# Estas estão disponíveis no escopo atual. -is_number(10) #=> true -is_list("ola") #=> false -elem({1,2,3}, 0) #=> 1 - -# Você pode agrupar algumas funções em um módulo. Dentro de um módulo use `def` -# para definir suas funções. -defmodule Math do - def sum(a, b) do - a + b - end - - def square(x) do - x * x - end -end - -Math.sum(1, 2) #=> 3 -Math.square(3) #=> 9 - -# Para compilar o módulo Math salve-o como `math.ex` e use `elixirc` -# em seu terminal: elixirc math.ex - -# Dentro de um módulo podemos definir funções com `def` e funções privadas com `defp`. -# Uma função definida com `def` pode ser invocada por outros módulos, -# já uma função privada pode ser invocada apenas localmente. -defmodule PrivateMath do - def sum(a, b) do - do_sum(a, b) - end - - defp do_sum(a, b) do - a + b - end -end - -PrivateMath.sum(1, 2) #=> 3 -# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) - -# Declarações de funções também suportam guards cláusulas múltiplas: -defmodule Geometry do - def area({:rectangle, w, h}) do - w * h - end - - def area({:circle, r}) when is_number(r) do - 3.14 * r * r - end -end - -Geometry.area({:rectangle, 2, 3}) #=> 6 -Geometry.area({:circle, 3}) #=> 28.25999999999999801048 -# Geometry.area({:circle, "not_a_number"}) -#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 - -# Devido à imutabilidade, recursão é uma grande parte do elixir -defmodule Recursion do - def sum_list([head | tail], acc) do - sum_list(tail, acc + head) - end - - def sum_list([], acc) do - acc - end -end - -Recursion.sum_list([1,2,3], 0) #=> 6 - -# Módulos do elixir suportam atributos, hpa atributos embutidos e você -# pode também adicionar os seus próprios. -defmodule MyMod do - @moduledoc """ - Este é um atributo embutido em um módulo de exemplo. - """ - - @my_data 100 # Este é um atributo customizado. - IO.inspect(@my_data) #=> 100 -end - -## --------------------------- -## -- Structs e Exceptions -## --------------------------- - -# Structs são extensões no topo de mapas que trazem valores padrão, -# garantias em tempo de compilação e polimorfismo para o Elixir. -defmodule Pessoa do - defstruct nome: nil, idade: 0, peso: 0 -end - -joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } -#=> %Pessoa{idade: 30, peso: 180, nome: "Joe"} - -# Acessa o valor de nome -joe_info.name #=> "Joe" - -# Atualiza o valor de idade -older_joe_info = %{ joe_info | idade: 31 } -#=> %Pessoa{idade: 31, peso: 180, nome: "Joe"} - -# O bloco `try` com a palavra `rescue` é usado para manipular exceções -try do - raise "algum erro" -rescue - RuntimeError -> "resgatado um erro em tempo de execução" - _error -> "isso resgatará qualquer erro" -end - -# Toda exceção possui uma mensagem -try do - raise "algum erro" -rescue - x in [RuntimeError] -> - x.message -end - -## --------------------------- -## -- Concorrência -## --------------------------- - -# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para -# escrever programas concorrentes em elixir são três primitivos: spawning processes, -# sending messages e receiving messages. - -# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função -# como argumento. -f = fn -> 2 * 2 end #=> #Function -spawn(f) #=> #PID<0.40.0> - -# `spawn` retorna um pid (process identifier), você pode usar esse pid para enviar -# mensagens ao processo. Para envio de mensagens usamos o operador `send`. -# Para tudo isso ser útil precisamos estar aptos a receber mensagens. Isto é -# realizado com o mecanismo `receive`: -defmodule Geometry do - def area_loop do - receive do - {:rectangle, w, h} -> - IO.puts("Area = #{w * h}") - area_loop() - {:circle, r} -> - IO.puts("Area = #{3.14 * r * r}") - area_loop() - end - end -end - -# Compile o módulo e crie um processo que avalie `area_loop` no shell -pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> - -# Envia uma mensagem ao `pid` correspondente a um pattern na declaração de recebimento -send pid, {:rectangle, 2, 3} -#=> Area = 6 -# {:rectangle,2,3} - -send pid, {:circle, 2} -#=> Area = 12.56000000000000049738 -# {:circle,2} - -# O shell também é um processo, você pode usar `self` para obter o pid atual -self() #=> #PID<0.27.0> -``` - -## Referências - -* [Getting started guide](http://elixir-lang.org/getting_started/1.html) da [página do elixir](http://elixir-lang.org) -* [Elixir Documentation](http://elixir-lang.org/docs/master/) -* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) por Dave Thomas -* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) -* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) por Fred Hebert -* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) por Joe Armstrong -- cgit v1.2.3 From bb457d24a9d42061b9a8d9bc5632f5707f2150f3 Mon Sep 17 00:00:00 2001 From: fnscoder Date: Wed, 4 Oct 2017 22:03:41 -0300 Subject: fix names in pt-pt --- pt-pt/bf-pt.html.markdown | 85 ++++++ pt-pt/bf.html.markdown | 85 ------ pt-pt/swift-pt.html.markdown | 609 +++++++++++++++++++++++++++++++++++++++++++ pt-pt/swift.html.markdown | 609 ------------------------------------------- 4 files changed, 694 insertions(+), 694 deletions(-) create mode 100644 pt-pt/bf-pt.html.markdown delete mode 100644 pt-pt/bf.html.markdown create mode 100644 pt-pt/swift-pt.html.markdown delete mode 100644 pt-pt/swift.html.markdown diff --git a/pt-pt/bf-pt.html.markdown b/pt-pt/bf-pt.html.markdown new file mode 100644 index 00000000..13c22387 --- /dev/null +++ b/pt-pt/bf-pt.html.markdown @@ -0,0 +1,85 @@ +--- +language: brainfuck +filename: brainfuck-pt.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Joao Marques", "http://github.com/mrshankly"] +lang: pt-pt +--- + +Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. + +Brainfuck é representado por um vector com 30 000 células inicializadas a zero +e um ponteiro de dados que aponta para a célula actual. + +Existem 8 comandos: ++ : Incrementa o valor da célula actual em 1. +- : Decrementa o valor da célula actual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula actual. +[ : Se o valor da célula actual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula actual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vejamos alguns programas básicos de brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor +65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tenta descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e multiplica-os. + +Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do +ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os +teus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck noutra linguagem. O interpretador é relativamente fácil de se +implementar, mas se fores masoquista, tenta escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-pt/bf.html.markdown b/pt-pt/bf.html.markdown deleted file mode 100644 index 13c22387..00000000 --- a/pt-pt/bf.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -filename: brainfuck-pt.bf -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Joao Marques", "http://github.com/mrshankly"] -lang: pt-pt ---- - -Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. - -Brainfuck é representado por um vector com 30 000 células inicializadas a zero -e um ponteiro de dados que aponta para a célula actual. - -Existem 8 comandos: -+ : Incrementa o valor da célula actual em 1. -- : Decrementa o valor da célula actual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula actual. -[ : Se o valor da célula actual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula actual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vejamos alguns programas básicos de brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor -65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tenta descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e multiplica-os. - -Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do -ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os -teus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck noutra linguagem. O interpretador é relativamente fácil de se -implementar, mas se fores masoquista, tenta escrever um interpretador de -brainfuck… em brainfuck. diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown new file mode 100644 index 00000000..9462ee1c --- /dev/null +++ b/pt-pt/swift-pt.html.markdown @@ -0,0 +1,609 @@ +--- +language: swift +filename: learnswift-pt.swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["João Costa", "https://github.com/joaofcosta"] +lang: pt-pt +--- + +Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X. +Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. +Swift usa o compilador LLVM incluido no XCode 6+. + +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. + +Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. + +```swift +// importar um módulo +import UIKit + +// +// MARK: Básico +// + +// O Xcode suporta landmarks para anotação de código e lista-as na jump bar +// MARK: Marco de secção (MARK) +// TODO: Algo a fazer em breve +// FIXME: Reparar este código + +// Em Swift 2, println e print foram unidos num só método print. O print automaticamente acrescenta uma nova linha. +print("Hello, world") // println mudou para print +print("Hello, world", appendNewLine: false) // imprimir sem acrescentar uma nova linha + +// variáveis (var) podem ser modificadas depois de inicializadas +// constantes (let) NÂO podem ser modificadas depois de inicializadas + +var myVariable = 42 +let øπΩ = "value" // nomes de variáveis em unicode +let π = 3.1415926 +let convenience = "keyword" // nome de variável contextual +let weak = "keyword"; let override = "another keyword" // expressões podem ser separadas com ';' +let `class` = "keyword" // plicals permitem que keywords sejam usadas como nomes de vartiáveis +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // interpolação de Strings + +// Valores especificos à build +// usam a configuração de build -D +#if false + print("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals são um dos recursos de Swift, Optionals tanto podem conter + um valor ou conter nil (sem valor) que indica que não existe um valor. + Adicionar um ponto de exclamção (?) após definir o tipo declara + esse valor como um Optional. + + Como Swift requere que todas as propriedades tenham um valor, até nil + tem que ser explicitamente guardado como um valor Optional. + + Optional é uma enumeração. +*/ +var someOptionalString: String? = "optional" // Pode assumir o valor nil +// Igual ao de cima, mas ? é um operando pósfixo (açúcar sintático) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // Não sou nil + if someOptionalString!.hasPrefix("opt") { + print("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +/* + Tentar usar ! para aceder a Optional com valor não existente, ou seja, nil, + causa em erro de execução. + É necessário ter sempre a certeza que um Optional não tem valor nil + antes de usar ! para fazer 'force-unwrap' ao seu valor. +*/ + +// Optional implicitamente desembrulhado +var unwrappedString: String! = "Value is expected." +// O mesmo de cima, mas ! é um operando pósfixo (mais açúcar sintático) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // Tem um valor diferente de nil + if !someOptionalStringConstant.hasPrefix("ok") { + // Não tem o prefixo + } +} + +// Swift tem suporte para guardar valores de qualquer tipo. +// AnyObject == id +// Ao contrátio do `id` de Objective-C, AnyObject funciona com qualquer valor (Class, Int, struct, etc.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." + +/* + Comentar aqui + + /* + Também é possível fazer comentários aninhados + */ +*/ + +// +// MARK: Coleções (Collections) +// + +/* + Os tipos Array e Dictionary são structs e, portanto, `let` e `var` + também indicam se eles são mutáveis (var) or imutáveis (let) + na altura em que se declaram estes tipos. +*/ + +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // let == imutável +let emptyArray2 = Array() // mesmo de cima +var emptyMutableArray = [String]() // var == mutável + + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // let == imutável +let emptyDictionary2 = Dictionary() // mesmo de cima +var emptyMutableDictionary = [String: Float]() // var == mutável + + +// +// MARK: Controlo de Fluxo (Control Flow) +// + +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + print("One!") + } else { + print("Not one!") + } +} + +// for loop (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// ciclo for (limite) +for i in -1...shoppingList.count { + print(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// usar ..< para excluir o último número + +// ciclo while +var i = 1 +while i < 1000 { + i *= 2 +} + +// ciclo do-whie +do { + print("hello") +} while 1 == 2 + +// Switch +// Muito poderoso, imagine `if`s com açúcar sintático +// Funciona para String, instâncias de objectos e primitivas (Int, Double, etc.) +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // obrigatório (de forma a cobrir todos os possíveis inputs) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funções (Functions) +// + +// Funções são tipos de primeira classe, o que significa que podem ser +// aninhadas dentro de outras funções e passadas como argumento + +// Função em Swift com documentação no header + +/** + Função de cumprimento. + + - Um ponto em documentação + - Outro ponto na documentação + + :param: nome Um nome + :param: dia Um dia + :returns: Uma string com um cumprimento contendo o nome e o dia. +*/ +func greet(nome: String, dia: String) -> String { + return "Hello \(nome), today is \(dia)." +} +greet("Bob", "Tuesday") + +// Semelhante ao método de cima excepto ao comportamento dos argumentos +func greet2(#nomeObrigatório: String, nomeArgumentoExterno nomeArgumentoLocal: String) -> String { + return "Hello \(nomeObrigatório), the day is \(nomeArgumentoLocal)" +} +greet2(nomeObrigatório:"John", nomeArgumentoExterno: "Sunday") + +// Função que devolve vários itens num tuplo +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignorar tuplos ou outros valores usando _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// Argumentos variáveis +func setup(numbers: Int...) { + // é um array + let number = numbers[0] + let argCount = numbers.count +} + +// Passar e devolver funções +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// Passar por referência (inout) +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closures +// +var numbers = [1, 2, 6] + +// Funções são casos especiais de closures ({}) + +// Exemplo de um Closure. +// `->` separa o argumento e o tipo de retorno. +// `in` separa o cabeçalho do closure do corpo do closure. +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Quando o tipo é conhecido, como em cima, podemos fazer o seguinte +numbers = numbers.map({ number in 3 * number }) +// Ou até mesmo isto +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure à direita (Trailing closure) +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super curto, pois o operador < consegue inferir o tipo + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estruturas (Structures) +// + +// Estruturas (struct) e classes (class) têm capacidades muito semelhantes +struct NamesTable { + let names = [String]() + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Estruturas têm um inicializador implicito que é automaticamente gerado +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, estruturas e os seus membros têm três níveis de controlo de acesso +// Nomeadamente: interno (predefinição)(internal) , público (public), privado (private) + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos os métodos e propriedades de uma classe são públicos. +// Se só for necessário guarda dados num +// objecto estruturado, então é melhor usar uma `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Propriedade getter e setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` é uma variável implicita disponível aos setters + sideLength = newValue / 4 + } + } + + // Carregar preguiçosamente uma propriedade + // subShape permanece a nil (unintialized) até o getter ser invocado + lazy var subShape = Rect(sideLength: 4) + + // Se não for necessário um getter e setter personalizado, + // mas se quiser correr o código antes e depois de modificar ou aceder + // uma propriedade, é possível usar `willSet` e `didSet` + var identifier: String = "defaultID" { + // o argumento de `willSet` é o nome da variável para o novo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // invocar super.init no final do método de inicialização + super.init() + } + + func shrink() { + if sideLength > 0 { + sideLength -= 1 + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// A class `Square` estende (extends) a classe `Rect` (hierarquia) +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Cast de uma instância de `Square` para `Shape` +let aShape = mySquare as Shape + +// Compara instâncias, não é igual a == , visto que == compara objects (igual a) +if mySquare === mySquare { + print("Yep, it's mySquare") +} + +// Inicializador (init) com Optional +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Colocar um ponto de interrpgação depois de `init` cria um inicializador + // Optional, o qual pode retornar nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // Não vai executar pois a variável myEmptyCircle é igual a nil + print("circle is not nil") +} + + +// +// MARK: Enumerações (Enums) +// + +// Enums pode opcionalmente ser um tipo especifico ou não. +// Enums podem conter métodos tal como as 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 "♧" + } + } +} + +// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum +// quando a variável é explicitamente definida. +var suitValue: Suit = .Hearts + +// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// Enum com valores associados +enum Furniture { + // Associar com um inteiro (Int) + case Desk(height: Int) + // Associar com uma String e um Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" + + +// +// MARK: Protocolos (Protocols) +// + +// Protocolos (`protcol`s) obrigam a que os tipos tenham +// propriedades de instância, métodos de instância, métodos de tipo, +// operadores e subscripts específicos. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos definidos com @objc permitem funções com optional +// que permitem verificar se existem conformidade +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // Coloca um ponto de interrogação após uma propriedade opcional, método + // ou subscript para graciosamente ignorar um valor nil e retornar nil + // em vez de provoar um erro em tempo de execução ("optional chaining"). + if let allow = self.delegate?.canReshape?() { + // testar o delegate e depois o método + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Outro +// + +// extensões (`extension`s): Adiciona funcionalidade extra a um tipo já existente. + +// Square agora "conforma" com o protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") + +// Também é possível extender tipos já embutidos +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// Generics: Semelhante a Java e C#. Usa a palavra-chave `where` para +// especificar requisitos do `generics`. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados podem começar com caracteres: +// / = - + * % < > ! & | ^ . ~ +// ou +// Caracteres Unicode matemáticos, símbolos, setas, dingbat e +// caracteres de desenho linha/caixa. +operador prefixo !!! {} + +// Um operador prefixo que triplica o comprimento do lado quando usado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// valor atual +print(mySquare.sideLength) // 4 + +// muda o comprimento deste lado usando o operador personalizado !!!, aumenta +// o comprimento 3x +!!!mySquare +print(mySquare.sideLength) // 12 + +// Operadores também podem ser generics +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" +``` diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown deleted file mode 100644 index 9462ee1c..00000000 --- a/pt-pt/swift.html.markdown +++ /dev/null @@ -1,609 +0,0 @@ ---- -language: swift -filename: learnswift-pt.swift -contributors: - - ["Grant Timmerman", "http://github.com/grant"] - - ["Christopher Bess", "http://github.com/cbess"] - - ["Joey Huang", "http://github.com/kamidox"] - - ["Anthony Nguyen", "http://github.com/anthonyn60"] - - ["Clayton Walker", "https://github.com/cwalk"] -translators: - - ["João Costa", "https://github.com/joaofcosta"] -lang: pt-pt ---- - -Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X. -Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. -Swift usa o compilador LLVM incluido no XCode 6+. - -O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. - -Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. - -```swift -// importar um módulo -import UIKit - -// -// MARK: Básico -// - -// O Xcode suporta landmarks para anotação de código e lista-as na jump bar -// MARK: Marco de secção (MARK) -// TODO: Algo a fazer em breve -// FIXME: Reparar este código - -// Em Swift 2, println e print foram unidos num só método print. O print automaticamente acrescenta uma nova linha. -print("Hello, world") // println mudou para print -print("Hello, world", appendNewLine: false) // imprimir sem acrescentar uma nova linha - -// variáveis (var) podem ser modificadas depois de inicializadas -// constantes (let) NÂO podem ser modificadas depois de inicializadas - -var myVariable = 42 -let øπΩ = "value" // nomes de variáveis em unicode -let π = 3.1415926 -let convenience = "keyword" // nome de variável contextual -let weak = "keyword"; let override = "another keyword" // expressões podem ser separadas com ';' -let `class` = "keyword" // plicals permitem que keywords sejam usadas como nomes de vartiáveis -let explicitDouble: Double = 70 -let intValue = 0007 // 7 -let largeIntValue = 77_000 // 77000 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(π), Pi 2 = \(π * 2)" // interpolação de Strings - -// Valores especificos à build -// usam a configuração de build -D -#if false - print("Not printed") - let buildValue = 3 -#else - let buildValue = 7 -#endif -print("Build value: \(buildValue)") // Build value: 7 - -/* - Optionals são um dos recursos de Swift, Optionals tanto podem conter - um valor ou conter nil (sem valor) que indica que não existe um valor. - Adicionar um ponto de exclamção (?) após definir o tipo declara - esse valor como um Optional. - - Como Swift requere que todas as propriedades tenham um valor, até nil - tem que ser explicitamente guardado como um valor Optional. - - Optional é uma enumeração. -*/ -var someOptionalString: String? = "optional" // Pode assumir o valor nil -// Igual ao de cima, mas ? é um operando pósfixo (açúcar sintático) -var someOptionalString2: Optional = "optional" - -if someOptionalString != nil { - // Não sou nil - if someOptionalString!.hasPrefix("opt") { - print("has the prefix") - } - - let empty = someOptionalString?.isEmpty -} -someOptionalString = nil - -/* - Tentar usar ! para aceder a Optional com valor não existente, ou seja, nil, - causa em erro de execução. - É necessário ter sempre a certeza que um Optional não tem valor nil - antes de usar ! para fazer 'force-unwrap' ao seu valor. -*/ - -// Optional implicitamente desembrulhado -var unwrappedString: String! = "Value is expected." -// O mesmo de cima, mas ! é um operando pósfixo (mais açúcar sintático) -var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." - -if let someOptionalStringConstant = someOptionalString { - // Tem um valor diferente de nil - if !someOptionalStringConstant.hasPrefix("ok") { - // Não tem o prefixo - } -} - -// Swift tem suporte para guardar valores de qualquer tipo. -// AnyObject == id -// Ao contrátio do `id` de Objective-C, AnyObject funciona com qualquer valor (Class, Int, struct, etc.) -var anyObjectVar: AnyObject = 7 -anyObjectVar = "Changed value to a string, not good practice, but possible." - -/* - Comentar aqui - - /* - Também é possível fazer comentários aninhados - */ -*/ - -// -// MARK: Coleções (Collections) -// - -/* - Os tipos Array e Dictionary são structs e, portanto, `let` e `var` - também indicam se eles são mutáveis (var) or imutáveis (let) - na altura em que se declaram estes tipos. -*/ - -// Array -var shoppingList = ["catfish", "water", "lemons"] -shoppingList[1] = "bottle of water" -let emptyArray = [String]() // let == imutável -let emptyArray2 = Array() // mesmo de cima -var emptyMutableArray = [String]() // var == mutável - - -// Dictionary -var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" -] -occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() // let == imutável -let emptyDictionary2 = Dictionary() // mesmo de cima -var emptyMutableDictionary = [String: Float]() // var == mutável - - -// -// MARK: Controlo de Fluxo (Control Flow) -// - -// for loop (array) -let myArray = [1, 1, 2, 3, 5] -for value in myArray { - if value == 1 { - print("One!") - } else { - print("Not one!") - } -} - -// for loop (dictionary) -var dict = ["one": 1, "two": 2] -for (key, value) in dict { - print("\(key): \(value)") -} - -// ciclo for (limite) -for i in -1...shoppingList.count { - print(i) -} -shoppingList[1...2] = ["steak", "peacons"] -// usar ..< para excluir o último número - -// ciclo while -var i = 1 -while i < 1000 { - i *= 2 -} - -// ciclo do-whie -do { - print("hello") -} while 1 == 2 - -// Switch -// Muito poderoso, imagine `if`s com açúcar sintático -// Funciona para String, instâncias de objectos e primitivas (Int, Double, etc.) -let vegetable = "red pepper" -switch vegetable { -case "celery": - let vegetableComment = "Add some raisins and make ants on a log." -case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." -case let localScopeValue where localScopeValue.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(localScopeValue)?" -default: // obrigatório (de forma a cobrir todos os possíveis inputs) - let vegetableComment = "Everything tastes good in soup." -} - - -// -// MARK: Funções (Functions) -// - -// Funções são tipos de primeira classe, o que significa que podem ser -// aninhadas dentro de outras funções e passadas como argumento - -// Função em Swift com documentação no header - -/** - Função de cumprimento. - - - Um ponto em documentação - - Outro ponto na documentação - - :param: nome Um nome - :param: dia Um dia - :returns: Uma string com um cumprimento contendo o nome e o dia. -*/ -func greet(nome: String, dia: String) -> String { - return "Hello \(nome), today is \(dia)." -} -greet("Bob", "Tuesday") - -// Semelhante ao método de cima excepto ao comportamento dos argumentos -func greet2(#nomeObrigatório: String, nomeArgumentoExterno nomeArgumentoLocal: String) -> String { - return "Hello \(nomeObrigatório), the day is \(nomeArgumentoLocal)" -} -greet2(nomeObrigatório:"John", nomeArgumentoExterno: "Sunday") - -// Função que devolve vários itens num tuplo -func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) -} -let pricesTuple = getGasPrices() -let price = pricesTuple.2 // 3.79 -// Ignorar tuplos ou outros valores usando _ (underscore) -let (_, price1, _) = pricesTuple // price1 == 3.69 -print(price1 == pricesTuple.1) // true -print("Gas price: \(price)") - -// Argumentos variáveis -func setup(numbers: Int...) { - // é um array - let number = numbers[0] - let argCount = numbers.count -} - -// Passar e devolver funções -func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne -} -var increment = makeIncrementer() -increment(7) - -// Passar por referência (inout) -func swapTwoInts(inout a: Int, inout b: Int) { - let tempA = a - a = b - b = tempA -} -var someIntA = 7 -var someIntB = 3 -swapTwoInts(&someIntA, &someIntB) -print(someIntB) // 7 - - -// -// MARK: Closures -// -var numbers = [1, 2, 6] - -// Funções são casos especiais de closures ({}) - -// Exemplo de um Closure. -// `->` separa o argumento e o tipo de retorno. -// `in` separa o cabeçalho do closure do corpo do closure. -numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result -}) - -// Quando o tipo é conhecido, como em cima, podemos fazer o seguinte -numbers = numbers.map({ number in 3 * number }) -// Ou até mesmo isto -//numbers = numbers.map({ $0 * 3 }) - -print(numbers) // [3, 6, 18] - -// Closure à direita (Trailing closure) -numbers = sorted(numbers) { $0 > $1 } - -print(numbers) // [18, 6, 3] - -// Super curto, pois o operador < consegue inferir o tipo - -numbers = sorted(numbers, < ) - -print(numbers) // [3, 6, 18] - -// -// MARK: Estruturas (Structures) -// - -// Estruturas (struct) e classes (class) têm capacidades muito semelhantes -struct NamesTable { - let names = [String]() - - // Custom subscript - subscript(index: Int) -> String { - return names[index] - } -} - -// Estruturas têm um inicializador implicito que é automaticamente gerado -let namesTable = NamesTable(names: ["Me", "Them"]) -let name = namesTable[1] -print("Name is \(name)") // Name is Them - -// -// MARK: Classes -// - -// Classes, estruturas e os seus membros têm três níveis de controlo de acesso -// Nomeadamente: interno (predefinição)(internal) , público (public), privado (private) - -public class Shape { - public func getArea() -> Int { - return 0; - } -} - -// Todos os métodos e propriedades de uma classe são públicos. -// Se só for necessário guarda dados num -// objecto estruturado, então é melhor usar uma `struct` - -internal class Rect: Shape { - var sideLength: Int = 1 - - // Propriedade getter e setter personalizado - private var perimeter: Int { - get { - return 4 * sideLength - } - set { - // `newValue` é uma variável implicita disponível aos setters - sideLength = newValue / 4 - } - } - - // Carregar preguiçosamente uma propriedade - // subShape permanece a nil (unintialized) até o getter ser invocado - lazy var subShape = Rect(sideLength: 4) - - // Se não for necessário um getter e setter personalizado, - // mas se quiser correr o código antes e depois de modificar ou aceder - // uma propriedade, é possível usar `willSet` e `didSet` - var identifier: String = "defaultID" { - // o argumento de `willSet` é o nome da variável para o novo valor - willSet(someIdentifier) { - print(someIdentifier) - } - } - - init(sideLength: Int) { - self.sideLength = sideLength - // invocar super.init no final do método de inicialização - super.init() - } - - func shrink() { - if sideLength > 0 { - sideLength -= 1 - } - } - - override func getArea() -> Int { - return sideLength * sideLength - } -} - -// A class `Square` estende (extends) a classe `Rect` (hierarquia) -class Square: Rect { - convenience init() { - self.init(sideLength: 5) - } -} - -var mySquare = Square() -print(mySquare.getArea()) // 25 -mySquare.shrink() -print(mySquare.sideLength) // 4 - -// Cast de uma instância de `Square` para `Shape` -let aShape = mySquare as Shape - -// Compara instâncias, não é igual a == , visto que == compara objects (igual a) -if mySquare === mySquare { - print("Yep, it's mySquare") -} - -// Inicializador (init) com Optional -class Circle: Shape { - var radius: Int - override func getArea() -> Int { - return 3 * radius * radius - } - - // Colocar um ponto de interrpgação depois de `init` cria um inicializador - // Optional, o qual pode retornar nil - init?(radius: Int) { - self.radius = radius - super.init() - - if radius <= 0 { - return nil - } - } -} - -var myCircle = Circle(radius: 1) -print(myCircle?.getArea()) // Optional(3) -print(myCircle!.getArea()) // 3 -var myEmptyCircle = Circle(radius: -1) -print(myEmptyCircle?.getArea()) // "nil" -if let circle = myEmptyCircle { - // Não vai executar pois a variável myEmptyCircle é igual a nil - print("circle is not nil") -} - - -// -// MARK: Enumerações (Enums) -// - -// Enums pode opcionalmente ser um tipo especifico ou não. -// Enums podem conter métodos tal como as 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 "♧" - } - } -} - -// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum -// quando a variável é explicitamente definida. -var suitValue: Suit = .Hearts - -// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas -enum BookName: String { - case John = "John" - case Luke = "Luke" -} -print("Name: \(BookName.John.rawValue)") - -// Enum com valores associados -enum Furniture { - // Associar com um inteiro (Int) - case Desk(height: Int) - // Associar com uma String e um Int - case Chair(String, Int) - - func description() -> String { - switch self { - case .Desk(let height): - return "Desk with \(height) cm" - case .Chair(let brand, let height): - return "Chair of \(brand) with \(height) cm" - } - } -} - -var desk: Furniture = .Desk(height: 80) -print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair("Foo", 40) -print(chair.description()) // "Chair of Foo with 40 cm" - - -// -// MARK: Protocolos (Protocols) -// - -// Protocolos (`protcol`s) obrigam a que os tipos tenham -// propriedades de instância, métodos de instância, métodos de tipo, -// operadores e subscripts específicos. - -protocol ShapeGenerator { - var enabled: Bool { get set } - func buildShape() -> Shape -} - -// Protocolos definidos com @objc permitem funções com optional -// que permitem verificar se existem conformidade -@objc protocol TransformShape { - optional func reshaped() - optional func canReshape() -> Bool -} - -class MyShape: Rect { - var delegate: TransformShape? - - func grow() { - sideLength += 2 - - // Coloca um ponto de interrogação após uma propriedade opcional, método - // ou subscript para graciosamente ignorar um valor nil e retornar nil - // em vez de provoar um erro em tempo de execução ("optional chaining"). - if let allow = self.delegate?.canReshape?() { - // testar o delegate e depois o método - self.delegate?.reshaped?() - } - } -} - - -// -// MARK: Outro -// - -// extensões (`extension`s): Adiciona funcionalidade extra a um tipo já existente. - -// Square agora "conforma" com o protocolo `Printable` -extension Square: Printable { - var description: String { - return "Area: \(self.getArea()) - ID: \(self.identifier)" - } -} - -print("Square: \(mySquare)") - -// Também é possível extender tipos já embutidos -extension Int { - var customProperty: String { - return "This is \(self)" - } - - func multiplyBy(num: Int) -> Int { - return num * self - } -} - -print(7.customProperty) // "This is 7" -print(14.multiplyBy(3)) // 42 - -// Generics: Semelhante a Java e C#. Usa a palavra-chave `where` para -// especificar requisitos do `generics`. - -func findIndex(array: [T], valueToFind: T) -> Int? { - for (index, value) in enumerate(array) { - if value == valueToFind { - return index - } - } - return nil -} -let foundAtIndex = findIndex([1, 2, 3, 4], 3) -print(foundAtIndex == 2) // true - -// Operadores: -// Operadores personalizados podem começar com caracteres: -// / = - + * % < > ! & | ^ . ~ -// ou -// Caracteres Unicode matemáticos, símbolos, setas, dingbat e -// caracteres de desenho linha/caixa. -operador prefixo !!! {} - -// Um operador prefixo que triplica o comprimento do lado quando usado -prefix func !!! (inout shape: Square) -> Square { - shape.sideLength *= 3 - return shape -} - -// valor atual -print(mySquare.sideLength) // 4 - -// muda o comprimento deste lado usando o operador personalizado !!!, aumenta -// o comprimento 3x -!!!mySquare -print(mySquare.sideLength) // 12 - -// Operadores também podem ser generics -infix operator <-> {} -func <-> (inout a: T, inout b: T) { - let c = a - a = b - b = c -} - -var foo: Float = 10 -var bar: Float = 20 - -foo <-> bar -print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" -``` -- cgit v1.2.3 From 7559305fb74cc9750a1d45ea24803257d27a8c88 Mon Sep 17 00:00:00 2001 From: Sridhar Easwaran Date: Thu, 5 Oct 2017 14:40:34 +0530 Subject: added use of break keyword & new tutorial link --- java.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index fa1ff3d1..d1ce2233 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -418,6 +418,8 @@ public class LearnJava { // String class, and a few special classes that wrap primitive types: // Character, Byte, Short, and Integer. // Starting in Java 7 and above, we can also use the String type. + // Note: Do remember that, not adding "break" at end any particular case ends up in + // executing the very next case(given it satisfies the condition provided) as well. int month = 3; String monthString; switch (month) { @@ -886,6 +888,8 @@ The links provided here below are just to get an understanding of the topic, fee * [Codingbat.com](http://codingbat.com/java) +* [Codewars - Java Katas](https://www.codewars.com/?language=java) + **Books**: * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From 11fed862e42ef4dd1dba5da0f27b6f4a1206806a Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Thu, 5 Oct 2017 08:57:17 -0300 Subject: Filename learnpyqt.py to learnpyqt-pt.py --- pt-br/pyqt-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown index ced107dc..10d55784 100644 --- a/pt-br/pyqt-pt.html.markdown +++ b/pt-br/pyqt-pt.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: PyQT -filename: learnpyqt.py +filename: learnpyqt-pt.py contributors: - ["Nathan Hughes", "https://github.com/sirsharpest"] translators: -- cgit v1.2.3 From c41bfe38377ad5989665c559c437df1f0e3fabcf Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Thu, 5 Oct 2017 11:21:33 -0300 Subject: [qt/pt-br] Translation of Qt to pt-br. --- pt-br/qt-pt.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 pt-br/qt-pt.html.markdown diff --git a/pt-br/qt-pt.html.markdown b/pt-br/qt-pt.html.markdown new file mode 100644 index 00000000..99579c35 --- /dev/null +++ b/pt-br/qt-pt.html.markdown @@ -0,0 +1,174 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt-pt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +translators: + - ["Lucas Pugliesi", "https://github.com/fplucas"] +lang: pt-br +--- + +**Qt** é amplamente conhecido como um framework para desenvolvimento de +software multi-plataforma que pode rodar em vários outras plataformas de +softwares e hardwares com pouca ou nenhuma alteração no código, enquanto mantém +o poder e a velocidade de uma aplicação nativa. Embora o **Qt** tenha sido +originalmente escrito em *C++*, é possível utilizá-lo em outras linguagens: +*[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** é ótimo para criar aplicações com interface gráfica (GUI). Esse tutorial +será feito em *C++*. + +```c++ +/* + * Vamos começar + */ + +// Todos as dependências do framework Qt iniciam com a letra 'Q' maiúscula +#include +#include + +int main(int argc, char *argv[]) { + // Cria um objeto para utilizar todos os recursos da aplicação + QApplication app(argc, argv); + + // Cria um widget com linha editável e exibe na tela + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // Inicia a aplicação em um evento de loop + return app.exec(); +} +``` + +A parte gráfica do **Qt** é toda composta de *widgets* e *conexões* entre eles. + +[LEIA MAIS SOBRE WIDGETS](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Vamos criar um label e um botão. + * Um label irá aparecer quando o botão for clicado + * + * O próprio código do Qt é autoexplicativo. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // Adiciona um layout vertical + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Thanks for pressing that button"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Press me"); + layout.addWidget(&button); + + // Exibe o label oculto quando o botão é clicado + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Veja o *QObject::connect*. O método é usado para conectar o *SINAL* de um objeto +ao *ENCAIXE* outro. + +**Sinais** são emitidos quando algo ocorre com o objeto, como quando o sinal de +*clique* é acionado apertando o QPushButton. + +**Encaixes** são *ações* que são executadas em resposta aos sinais recebidos. + +[LEIA MAIS SOBRE SINAIS E ENCAIXES](http://doc.qt.io/qt-5/signalsandslots.html) + + +A seguir vamos aprender como usar não somente o comportamento padrão dos +widgets, mas também extender seus comportamentos usando herança. Vamos criar um +botão e contar quantas vezes é pressionado. Para esse propósito definiremos +nossa própria classe *CounterLabel*. Ela deve ser declarada em um arquivo +diferente devido a estrutura específica do Qt. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Define os macros presente em todo objeto Qt + +public: + CounterLabel() : counter(0) { + setText("Counter has not been increased yet"); // método do QLabel + } + +public slots: + // Ação que será chamada em resposta ao clique do botão + void increaseCounter() { + setText(QString("Counter value: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Quase igual ao exemplo anterior + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Push me once more"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +É isso! Claro, o framework Qt é muito maior do que exemplificamos no tutorial, +então esteja preparado para ler e praticar mais. + +## Leitura complementar + +- [Tutoriais Qt 4.8](http://doc.qt.io/qt-4.8/tutorials.html) +- [Tutoriais Qt 5](http://doc.qt.io/qt-5/qtexamplesandtutorials.html) + +Boa sorte e divirta-se! -- cgit v1.2.3 From 8bccfb8be287e8f85129a45abb046a3f27b1e0dd Mon Sep 17 00:00:00 2001 From: Toby Sullivan Date: Thu, 5 Oct 2017 12:19:40 -0700 Subject: Add default keyword --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index fa1ff3d1..a8c2523c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -660,7 +660,7 @@ public interface Edible { public interface Digestible { public void digest(); // Since Java 8, interfaces can have default method. - public void defaultMethod() { + public default void defaultMethod() { System.out.println("Hi from default method ..."); } } -- cgit v1.2.3 From 7d2dcc0df4b85861f7880fcd9299674a7040fff7 Mon Sep 17 00:00:00 2001 From: "J.Juan" <32603609+jjuanhdez@users.noreply.github.com> Date: Sun, 8 Oct 2017 01:05:48 +0200 Subject: Create learnsmallbasic-es.html.markdown --- es-es/learnsmallbasic-es.html.markdown | 132 +++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 es-es/learnsmallbasic-es.html.markdown diff --git a/es-es/learnsmallbasic-es.html.markdown b/es-es/learnsmallbasic-es.html.markdown new file mode 100644 index 00000000..21208792 --- /dev/null +++ b/es-es/learnsmallbasic-es.html.markdown @@ -0,0 +1,132 @@ +--- +language: SmallBASIC +filename: learnsmallbasic-es.bas +contributors: + - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"] +translators: + - ["José Juan Hernández García", "http://jjuanhdez.es"] +lang: es-es +--- + +## Acerca de + +SmallBASIC es un intérprete del lenguaje BASIC rápido y fácil de aprender, ideal para cálculos cotidianos, scripts y prototipos. SmallBASIC incluye funciones trigonométricas, matrices y álgebra, un IDE integrado, una potente librería de cadenas de texto, comandos de sistema, sonido y gráficos, junto con una sintaxis de programación estructurada. + +## Desarrollo + +SmallBASIC fue desarrollado originalmente por Nicholas Christopoulos a finales de 1999 para el Palm Pilot. El desarrollo del proyecto ha sido continuado por Chris Warren-Smith desde el año 2005. +Versiones de SmallBASIC se han hecho para una serie dispositivos de mano antiguos, incluyendo Franklin eBookman y el Nokia 770. También se han publicado varias versiones de escritorio basadas en una variedad de kits de herramientas GUI, algunas de las cuales han desaparecido. Las plataformas actualmente soportadas son Linux y Windows basadas en SDL2 y Android basadas en NDK. También está disponible una versión de línea de comandos de escritorio, aunque no suele publicarse en formato binario. +Alrededor de 2008 una gran corporación lanzó un entorno de programación BASIC con un nombre de similar. SmallBASIC no está relacionado con este otro proyecto. + +```SmallBASIC +REM Esto es un comentario +' y esto tambien es un comentario + +REM Imprimir texto +PRINT "hola" +? "? es la abreviatura de PRINT" + +REM Estructuras de control +FOR index = 0 TO 10 STEP 2 + ? "Este es el numero de linea "; index +NEXT +J = 0 +REPEAT + J++ +UNTIL J = 10 +WHILE J > 0 + J-- +WEND + +REM Estructura Select Case +SELECT CASE "Cool" + CASE "null", 1, 2, 3, 4, 5, 6, 7, 8, "Cool", "blah" + CASE "No Cool" + PRINT "Fallo epico" + CASE ELSE + PRINT "Fallo" +END SELECT + +REM Captura de errores con TRY/CATCH +TRY + fn = Freefile + OPEN filename FOR INPUT As #fn +CATCH err + PRINT "No se pudo abrir" +END TRY + +REM Procedimientos y funciones definidas por el usuario +FUNC add2(x, y) + ' variables pueden declararse como locales en el ambito de una SUB o FUNC + LOCAL k + k = "k dejara de existir cuando retorne FUNC" + add2 = x + y +END +PRINT add2(5, 5) + +SUB print_it(it) + PRINT it +END +print_it "IT...." + +REM Visualizacion de lineas y pixeles +At 0, ymax / 2 + txth ("Q") +COLOR 1: ? "sin(x)": +COLOR 8: ? "cos(x)": +COLOR 12: ? "tan(x)" +LINE 0, ymax / 2, xmax, ymax / 2 +FOR i = 0 TO xmax + PSET i, ymax / 2 - SIN(i * 2 * pi / ymax) * ymax / 4 COLOR 1 + PSET i, ymax / 2 - COS(i * 2 * pi / ymax) * ymax / 4 COLOR 8 + PSET i, ymax / 2 - TAN(i * 2 * pi / ymax) * ymax / 4 COLOR 12 +NEXT +SHOWPAGE + +REM SmallBASIC es ideal para experimentar con fractales y otros efectos interesantes +DELAY 3000 +RANDOMIZE +ff = 440.03 +FOR j = 0 TO 20 + r = RND * 1000 % 255 + b = RND * 1000 % 255 + g = RND * 1000 % 255 + c = RGB(r, b, g) + ff += 9.444 + FOR i = 0 TO 25000 + ff += ff + x = MIN(xmax, -x + COS(f * i)) + y = MIN(ymax, -y + SIN(f * i)) + PSET x, y COLOR c + IF (i % 1000 == 0) THEN + SHOWPAGE + fi + NEXT +NEXT j + +REM Para historiadores de computadoras, SmallBASIC puede ejecutar programas +REM encontrados en los primeros libros de computacion y revistas, por ejemplo: +10 LET A = 9 +20 LET B = 7 +30 PRINT A * B +40 PRINT A / B + +REM SmallBASIC también tiene soporte para algunos conceptos modernos como JSON +aa = ARRAY("{\"cat\":{\"name\":\"harry\"},\"pet\":\"true\"}") +IF (ismap(aa) == false) THEN + THROW "no es un mapa" +END IF +PRINT aa + +PAUSE + +``` +## Artículos + +* [Primeros pasos](http://smallbasic.sourceforge.net/?q=node/1573) +* [Bienvenido a SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838) + +## GitHub + +* [Código fuente](https://github.com/smallbasic/SmallBASIC) +* [Reference snapshot](http://smallbasic.github.io/) + -- cgit v1.2.3 From d0ecb9f488f850d6c33b6d9eb8975b92402101e4 Mon Sep 17 00:00:00 2001 From: Nameguy Date: Sun, 8 Oct 2017 00:56:41 -0400 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index fd40afe9..f490dd6b 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -904,7 +904,7 @@ b := String isVariable. "true if has indexed b := String isPointers. "true if index instance vars contain objects" b := String isBits. "true if index instance vars contain bytes/words" b := String isBytes. "true if index instance vars contain bytes" -b := String isWords. true if index instance vars contain words" +b := String isWords. "true if index instance vars contain words" Object withAllSubclasses size. "get total number of class entries" ``` -- cgit v1.2.3 From 0d85a0371c0254f0b8dcdb281fe456af05e422ed Mon Sep 17 00:00:00 2001 From: Nameguy Date: Sun, 8 Oct 2017 00:57:51 -0400 Subject: Update smalltalk.html.markdown --- smalltalk.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index f490dd6b..a253df55 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -186,7 +186,7 @@ x := Float pi. "pi" x := Float e. "exp constant" x := Float infinity. "infinity" x := Float nan. "not-a-number" -x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) +x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)" x := 100 atRandom. "quick random number" ``` -- cgit v1.2.3 From 44c0ba4f1c09207dea1c74073dca72cf503f614b Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sun, 8 Oct 2017 12:08:30 +0200 Subject: [markdown/it-it] Update structure and typo fix Some typo where fixed and the structure now reflect the english version of the markdown file --- it-it/markdown.html.markdown | 192 ++++++++++++++++++++++++++++--------------- 1 file changed, 128 insertions(+), 64 deletions(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index b006dbb4..f01bcc72 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -2,41 +2,62 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] + - ["Jacob Ward", "http://github.com/JacobCWard/"] translators: - ["Jacopo Andrea Giola", "http://geekpanda.net"] + - ["Ale46", "https://github.com/Ale46"] filename: markdown-it.md lang: it-it --- Markdown è stato creato da John Gruber nel 2004. Il suo scopo è quello di essere una sintassi facile da leggere e scrivere, e che può essere convertita in HTML (ad oggi anche in molti altri formati). -Mandate tutto il feedback che volete! / Sentitevi liberi di forkare o di mandare pull request! +Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida cercherà di chiarire quali caratteristiche esistono a livello globale o quando sono disponibili solo per un determinato parser. +- [Elementi HTML](#elementi-html) +- [Titoli](#titoli) +- [Stili di testo semplici](#stili-di-testo-semplici) +- [Paragrafi](#paragrafi) +- [Liste](#liste) +- [Estratti di codice](#estratti-di-codice) +- [Linea orizzontale](#linea-orizzontale) +- [Links](#links) +- [Immagini](#immagini) +- [Miscellanea](#miscellanea) + +## Elementi HTML +Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido. ```markdown - + +``` + +## Titoli - +Potete creare gli elementi HTML da `

` a `

` facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento - - +```markdown # Questo è un

## Questo è un

### Questo è un

#### Questo è un

##### Questo è un

###### Questo è un
+``` +Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2 - +```markdown Questo è un h1 ============== Questo è un h2 -------------- +``` - - +## Stili di testo semplici +Il testo può essere stilizzato in corsivo o grassetto usando markdown +```markdown *Questo testo è in corsivo.* _Come pure questo._ @@ -46,30 +67,38 @@ __Come pure questo.__ ***Questo testo è stilizzato in entrabmi i modi.*** **_Come questo!_** *__E questo!__* +``` - +In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato: +```markdown ~~Questo testo è barrato.~~ +``` +## Paragrafi - +```markdown +I paragrafi sono una o più linee di testo adiacenti separate da una o più righe vuote. -Qeusto è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? +Questo è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? Ora sono nel paragrafo 2. Anche questa linea è nel paragrafo 2! Qui siamo nel paragrafo 3! +``` - +Se volete inserire l'elemento HTML `
`, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo. +```markdown Questa frase finisce con due spazi (evidenziatemi per vederli). C'è un
sopra di me! +``` - +Le citazioni sono semplici da inserire, basta usare il carattere >. +```markdown > Questa è una citazione. Potete > mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. > Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. @@ -78,9 +107,12 @@ C'è un
sopra di me! >> di indentazione! > Quanto è comodo? - - +``` + +## Liste +Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini +```markdown * Oggetto * Oggetto * Altro oggetto @@ -96,149 +128,181 @@ oppure - Oggetto - Oggetto - Un ultimo oggetto +``` - +Le liste ordinate invece, sono inserite con un numero seguito da un punto. +```markdown 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto +``` - +Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea. +```markdown 1. Primo oggetto 1. Secondo oggetto 1. Terzo oggetto - +``` +(Questa lista verrà visualizzata esattamente come quella dell'esempio prima) - +Potete inserire anche sotto liste +```markdown 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto * Sotto-oggetto * Sotto-oggetto 4. Quarto oggetto +``` - +Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML. +```markdown I box senza la 'x' sono checkbox HTML ancora da completare. - [ ] Primo task da completare. - [ ] Secondo task che deve essere completato. Il box subito sotto è una checkbox HTML spuntata. - [x] Questo task è stato completato. +``` +## Estratti di codice - - +Potete inserire un estratto di codice (che utilizza l'elemento ) indentando una linea con quattro spazi oppure con un carattere tab. +```markdown Questa è una linea di codice Come questa +``` - +Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice +```markdown my_array.each do |item| puts item end +``` - +Codice inline può essere inserito usando il carattere backtick ` +```markdown Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! +``` - - -\`\`\`ruby +In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice +```markdown +```ruby def foobar puts "Hello world!" end -\`\`\` - - +`` ` +``` +Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i ``` iniziali - - +## Linea orizzontale +Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. +```markdown *** --- - - - **************** +``` - - +## Links +Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde () +```markdown [Cliccami!](http://test.com/) +``` - +Potete inoltre aggiungere al link un titolo mettendolo fra doppi apici dopo il link +```markdown [Cliccami!](http://test.com/ "Link a Test.com") +``` - +La sintassi funziona anche con i path relativi. +```markdown [Vai a musica](/music/). +``` - - +Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo. +```markdown [Apri questo link][link1] per più informazioni! [Guarda anche questo link][foobar] se ti va. [link1]: http://test.com/ "Bello!" [foobar]: http://foobar.biz/ "Va bene!" +``` +l titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco. - - - - +Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id. +```markdown [Questo][] è un link. [Questo]: http://thisisalink.com/ +``` +Ma non è comunemente usato. - - - - +## Immagini +Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! +```markdown ![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") +``` - +E la modalità a riferimento funziona esattamente come ci si aspetta +```markdown ![Questo è il testo alternativo.][myimage] [myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" +``` +## Miscellanea +### Auto link - - - +```markdown è equivalente ad [http://testwebsite.com/](http://testwebsite.com/) +``` +### Auto link per le email - - +```markdown +``` +### Caratteri di escaping - - +```markdown Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. +``` - - +### Combinazioni di tasti +In Github Flavored Markdown, potete utilizzare il tag per raffigurare i tasti della tastiera. +```markdown Il tuo computer è crashato? Prova a premere Ctrl+Alt+Canc +``` - - +### Tabelle +Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: +```markdown | Col1 | Col2 | Col3 | | :------------------- | :------: | -----------------: | | Allineato a sinistra | Centrato | Allineato a destra | | blah | blah | blah | +``` +oppure, per lo stesso risultato - - +```markdown Col 1 | Col2 | Col3 :-- | :-: | --: È una cosa orrenda | fatela | finire in fretta - - - ``` +--- Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From b90490ae63b23fa61201e61171047a7cf2254299 Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sun, 8 Oct 2017 12:14:02 +0200 Subject: [markdown/it-it] Fix some escape --- it-it/markdown.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index f01bcc72..1eee9e9e 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -169,7 +169,7 @@ Il box subito sotto è una checkbox HTML spuntata. ``` ## Estratti di codice -Potete inserire un estratto di codice (che utilizza l'elemento ) indentando una linea con quattro spazi oppure con un carattere tab. +Potete inserire un estratto di codice (che utilizza l'elemento ``) indentando una linea con quattro spazi oppure con un carattere tab. ```markdown Questa è una linea di codice @@ -191,14 +191,13 @@ Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! ``` In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice -```markdown -```ruby +
+```ruby
 def foobar
     puts "Hello world!"
 end
-`` `
-```
-Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i ``` iniziali
+```
+Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali ## Linea orizzontale Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. @@ -280,7 +279,7 @@ Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga ``` ### Combinazioni di tasti -In Github Flavored Markdown, potete utilizzare il tag per raffigurare i tasti della tastiera. +In Github Flavored Markdown, potete utilizzare il tag `` per raffigurare i tasti della tastiera. ```markdown Il tuo computer è crashato? Prova a premere -- cgit v1.2.3 From b82270578b05a0c8d4f7296bf3725643dc6b8115 Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sun, 8 Oct 2017 12:18:09 +0200 Subject: [markdown/it-it] Fix comment line too long --- it-it/markdown.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index 1eee9e9e..44801747 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -29,7 +29,10 @@ Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida ce Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido. ```markdown - + ``` ## Titoli -- cgit v1.2.3 From 8d9418f2084bbcab60348d0fabce32d1ca2b8bb8 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 8 Oct 2017 19:43:38 -0700 Subject: [chapel/en] Chapel version update, mixed quotes + Chapel is now version 1.16.0 + The syntax highlighter does *not* like single quotes `'` mixed with double quotes `"`. I have removed what appear to be the worst offenders. --- chapel.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 96ddc69d..e9c4019a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -188,7 +188,7 @@ if 10 < 100 then if -1 < 1 then writeln("Continuing to believe reality"); else - writeln("Send mathematician, something's wrong"); + writeln("Send mathematician, something is wrong"); // You can use parentheses if you prefer. if (10 > 100) { @@ -213,7 +213,7 @@ if a % 3 == 0 { var maximum = if thisInt < thatInt then thatInt else thisInt; // select statements are much like switch statements in other languages. -// However, select statements don't cascade like in C or Java. +// However, select statements do not cascade like in C or Java. var inputOption = "anOption"; select inputOption { when "anOption" do writeln("Chose 'anOption'"); @@ -223,7 +223,7 @@ select inputOption { } otherwise { writeln("Any other Input"); - writeln("the otherwise case doesn't need a do if the body is one line"); + writeln("the otherwise case does not need a do if the body is one line"); } } @@ -282,7 +282,7 @@ var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 var reverse2to10by2 = 2..10 by -2; // 10, 8, 6, 4, 2 var trapRange = 10..1 by -1; // Do not be fooled, this is still an empty range -writeln("Size of range '", trapRange, "' = ", trapRange.length); +writeln("Size of range ", trapRange, " = ", trapRange.length); // Note: range(boundedType= ...) and range(stridable= ...) are only // necessary if we explicitly type the variable. @@ -425,7 +425,7 @@ var thisPlusThat = thisArray + thatArray; writeln(thisPlusThat); // Moving on, arrays and loops can also be expressions, where the loop -// body's expression is the result of each iteration. +// body expression is the result of each iteration. var arrayFromLoop = for i in 1..10 do i; writeln(arrayFromLoop); @@ -1141,7 +1141,7 @@ to see if more topics have been added or more tutorials created. Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- -The Chapel language is still in-development (version 1.15.0), so there are +The Chapel language is still in-development (version 1.16.0), so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. Feel free to email the team @@ -1158,8 +1158,8 @@ Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and it's as easy as - 1. `tar -xvf chapel-1.15.0.tar.gz` - 2. `cd chapel-1.15.0` + 1. `tar -xvf chapel-1.16.0.tar.gz` + 2. `cd chapel-1.16.0` 3. `source util/setchplenv.bash # or .sh or .csh or .fish` 4. `make` 5. `make check # optional` -- cgit v1.2.3 From 62d4b1483b850da0a99c2aa6c2da8b013e308f50 Mon Sep 17 00:00:00 2001 From: Damian Rzeszot Date: Mon, 9 Oct 2017 11:56:50 +0200 Subject: swift | fix style guidelines --- ru-ru/swift-ru.html.markdown | 8 ++++---- swift.html.markdown | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index 7ff660e1..46a91660 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -376,14 +376,14 @@ print("Имя :\(name)") // Имя: Яков // Протокол `Error` используется для перехвата выбрасываемых ошибок enum MyError: Error { - case BadValue(msg: String) - case ReallyBadValue(msg: String) + case badValue(msg: String) + case reallyBadValue(msg: String) } // фунции помеченные словом `throws` должны вызываться с помощью `try` func fakeFetch(value: Int) throws -> String { guard 7 == value else { - throw MyError.ReallyBadValue(msg: "Действительно плохое значение") + throw MyError.reallyBadValue(msg: "Действительно плохое значение") } return "тест" @@ -401,7 +401,7 @@ func testTryStuff() { do { // обычно try оператор, позволяющий обработать ошибку в `catch` блоке try fakeFetch(value: 1) - } catch MyError.BadValue(let msg) { + } catch MyError.badValue(let msg) { print("Ошибка: \(msg)") } catch { // все остальное diff --git a/swift.html.markdown b/swift.html.markdown index 60915d72..46388ca5 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -361,14 +361,14 @@ print("Name is \(name)") // Name is Them // The `Error` protocol is used when throwing errors to catch enum MyError: Error { - case BadValue(msg: String) - case ReallyBadValue(msg: String) + case badValue(msg: String) + case reallyBadValue(msg: String) } // functions marked with `throws` must be called using `try` func fakeFetch(value: Int) throws -> String { guard 7 == value else { - throw MyError.ReallyBadValue(msg: "Some really bad value") + throw MyError.reallyBadValue(msg: "Some really bad value") } return "test" @@ -385,7 +385,7 @@ func testTryStuff() { do { // normal try operation that provides error handling via `catch` block try fakeFetch(value: 1) - } catch MyError.BadValue(let msg) { + } catch MyError.badValue(let msg) { print("Error message: \(msg)") } catch { // must be exhaustive -- cgit v1.2.3 From d01e5242e16c522becc1b04f9692d2556f94c4f1 Mon Sep 17 00:00:00 2001 From: Damian Rzeszot Date: Mon, 9 Oct 2017 12:01:15 +0200 Subject: swift | fix style guidelines --- de-de/swift-de.html.markdown | 12 ++++++------ es-es/swift-es.html.markdown | 12 ++++++------ pt-br/swift-pt.html.markdown | 10 +++++----- pt-pt/swift-pt.html.markdown | 14 +++++++------- ru-ru/swift-ru.html.markdown | 12 ++++++------ swift.html.markdown | 12 ++++++------ tr-tr/swift-tr.html.markdown | 12 ++++++------ zh-cn/swift-cn.html.markdown | 12 ++++++------ 8 files changed, 48 insertions(+), 48 deletions(-) diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown index b58a72d3..43b8c32a 100644 --- a/de-de/swift-de.html.markdown +++ b/de-de/swift-de.html.markdown @@ -440,13 +440,13 @@ if let circle = myEmptyCircle { // Wie Klassen auch können sie Methoden haben enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } @@ -455,7 +455,7 @@ enum Suit { // Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ // genannt werden, wenn die Variable explizit deklariert wurde -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte" enum BookName: String { diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown index 8f63517a..ea892628 100644 --- a/es-es/swift-es.html.markdown +++ b/es-es/swift-es.html.markdown @@ -446,20 +446,20 @@ if let circle = myEmptyCircle { // Al igual que las clases, pueden contener métodos enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } // Los valores de enum permite la sintaxis corta, sin necesidad de poner // el tipo del enum cuando la variable es declarada de manera explícita -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // Enums de tipo no-entero requiere asignaciones de valores crudas directas enum BookName: String { diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown index ebf74b6f..bf410352 100644 --- a/pt-br/swift-pt.html.markdown +++ b/pt-br/swift-pt.html.markdown @@ -389,13 +389,13 @@ if mySquare === mySquare { // Podem conter métodos do mesmo jeito que classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown index 9462ee1c..f7fab423 100644 --- a/pt-pt/swift-pt.html.markdown +++ b/pt-pt/swift-pt.html.markdown @@ -445,21 +445,21 @@ if let circle = myEmptyCircle { // Enums pode opcionalmente ser um tipo especifico ou não. // Enums podem conter métodos tal como as classes. -enum Suit { - case Spades, Hearts, Diamonds, Clubs +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: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } // Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum // quando a variável é explicitamente definida. -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas enum BookName: String { diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index 46a91660..24095ee5 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -535,20 +535,20 @@ if let circle = myEmptyCircle { // Они могут содержать методы подобно классам. enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } // Значения перечислений допускают сокращенный синтаксис, нет необходимости // указывать тип перечисления, когда переменная объявляется явно -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // Значения нецелочисленных перечислений должны быть указаны явно // или могут выводится с помощью функции `rawValue` из имени diff --git a/swift.html.markdown b/swift.html.markdown index 46388ca5..577fa559 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -518,20 +518,20 @@ if let circle = myEmptyCircle { // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } // Enum values allow short hand syntax, no need to type the enum type // when the variable is explicitly declared -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // String enums can have direct raw value assignments // or their raw values will be derived from the Enum field diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index e694d95d..c9473cb2 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -443,19 +443,19 @@ if let daire = benimBosDairem { // Sınıflar gibi metotlar içerebilirler. enum Kart { - case Kupa, Maca, Sinek, Karo + case kupa, maca, sinek, karo func getIcon() -> String { switch self { - case .Maca: return "♤" - case .Kupa: return "♡" - case .Karo: return "♢" - case .Sinek: return "♧" + case .maca: return "♤" + case .kupa: return "♡" + case .karo: return "♢" + case .sinek: return "♧" } } } // Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz. -var kartTipi: Kart = .Kupa +var kartTipi: Kart = .kupa // Integer olmayan enumlar direk değer (rawValue) atama gerektirir. enum KitapAdi: String { diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index cba9252d..7ebf8121 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -445,19 +445,19 @@ if let circle = myEmptyCircle { // 枚举可以像类一样,拥有方法 enum Suit { - case Spades, Hearts, Diamonds, Clubs + case spades, hearts, diamonds, clubs func getIcon() -> String { switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case .spades: return "♤" + case .hearts: return "♡" + case .diamonds: return "♢" + case .clubs: return "♧" } } } // 当变量类型明确指定为某个枚举类型时,赋值时可以省略枚举类型 -var suitValue: Suit = .Hearts +var suitValue: Suit = .hearts // 非整型的枚举类型需要在定义时赋值 enum BookName: String { -- cgit v1.2.3 From 9a9e52b54bf9bc6ebeefc996452f5944a234557f Mon Sep 17 00:00:00 2001 From: Damian Rzeszot Date: Mon, 9 Oct 2017 12:02:29 +0200 Subject: swift | fix style guidelines --- de-de/swift-de.html.markdown | 6 +++--- es-es/swift-es.html.markdown | 6 +++--- pt-pt/swift-pt.html.markdown | 6 +++--- ru-ru/swift-ru.html.markdown | 6 +++--- swift.html.markdown | 6 +++--- tr-tr/swift-tr.html.markdown | 6 +++--- zh-cn/swift-cn.html.markdown | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown index 43b8c32a..c21b7e36 100644 --- a/de-de/swift-de.html.markdown +++ b/de-de/swift-de.html.markdown @@ -459,10 +459,10 @@ var suitValue: Suit = .hearts // Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte" enum BookName: String { - case John = "John" - case Luke = "Luke" + case john = "John" + case luke = "Luke" } -print("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.john.rawValue)") // Enum mit assoziierten Werten enum Furniture { diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown index ea892628..cd16d318 100644 --- a/es-es/swift-es.html.markdown +++ b/es-es/swift-es.html.markdown @@ -463,10 +463,10 @@ var suitValue: Suit = .hearts // Enums de tipo no-entero requiere asignaciones de valores crudas directas enum BookName: String { - case John = "John" - case Luke = "Luke" + case john = "John" + case luke = "Luke" } -print("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.john.rawValue)") // Enum con valores asociados enum Furniture { diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown index f7fab423..5de2e13b 100644 --- a/pt-pt/swift-pt.html.markdown +++ b/pt-pt/swift-pt.html.markdown @@ -463,10 +463,10 @@ var suitValue: Suit = .hearts // Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas enum BookName: String { - case John = "John" - case Luke = "Luke" + case john = "John" + case luke = "Luke" } -print("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.john.rawValue)") // Enum com valores associados enum Furniture { diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index 24095ee5..5aa3d8e8 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -553,10 +553,10 @@ var suitValue: Suit = .hearts // Значения нецелочисленных перечислений должны быть указаны явно // или могут выводится с помощью функции `rawValue` из имени enum BookName: String { - case John - case Luke = "Лука" + case john + case luke = "Лука" } -print("Имя: \(BookName.John.rawValue)") +print("Имя: \(BookName.john.rawValue)") // Перечисление (enum) со связанными значениями enum Furniture { diff --git a/swift.html.markdown b/swift.html.markdown index 577fa559..a3b33e25 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -536,10 +536,10 @@ var suitValue: Suit = .hearts // String enums can have direct raw value assignments // or their raw values will be derived from the Enum field enum BookName: String { - case John - case Luke = "Luke" + case john + case luke = "Luke" } -print("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.john.rawValue)") // Enum with associated Values enum Furniture { diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index c9473cb2..5e09daa9 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -459,10 +459,10 @@ var kartTipi: Kart = .kupa // Integer olmayan enumlar direk değer (rawValue) atama gerektirir. enum KitapAdi: String { - case John = "John" - case Luke = "Luke" + case john = "John" + case luke = "Luke" } -print("Name: \(KitapAdi.John.rawValue)") +print("Name: \(KitapAdi.john.rawValue)") // Değerlerle ilişkilendirilmiş Enum enum Mobilya { diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 7ebf8121..002b117f 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -461,10 +461,10 @@ var suitValue: Suit = .hearts // 非整型的枚举类型需要在定义时赋值 enum BookName: String { - case John = "John" - case Luke = "Luke" + case john = "John" + case luke = "Luke" } -print("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.john.rawValue)") // 与特定数据类型关联的枚举 enum Furniture { -- cgit v1.2.3 From e8ee66c854b8833fcb0fd76b5e9ace6ae8379397 Mon Sep 17 00:00:00 2001 From: Damian Rzeszot Date: Mon, 9 Oct 2017 12:03:27 +0200 Subject: swift | fix style guidelines --- de-de/swift-de.html.markdown | 14 +++++++------- es-es/swift-es.html.markdown | 12 ++++++------ pt-pt/swift-pt.html.markdown | 12 ++++++------ ru-ru/swift-ru.html.markdown | 12 ++++++------ swift.html.markdown | 12 ++++++------ tr-tr/swift-tr.html.markdown | 14 +++++++------- zh-cn/swift-cn.html.markdown | 12 ++++++------ 7 files changed, 44 insertions(+), 44 deletions(-) diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown index c21b7e36..08f72a35 100644 --- a/de-de/swift-de.html.markdown +++ b/de-de/swift-de.html.markdown @@ -467,23 +467,23 @@ print("Name: \(BookName.john.rawValue)") // Enum mit assoziierten Werten enum Furniture { // mit Int assoziiert - case Desk(height: Int) + case desk(height: Int) // mit String und Int assoziiert - case Chair(String, Int) - + case chair(String, Int) + func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Desk with \(height) cm" - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Chair of \(brand) with \(height) cm" } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair("Foo", 40) +var chair = Furniture.chair("Foo", 40) print(chair.description()) // "Chair of Foo with 40 cm" diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown index cd16d318..22e3c532 100644 --- a/es-es/swift-es.html.markdown +++ b/es-es/swift-es.html.markdown @@ -471,23 +471,23 @@ print("Name: \(BookName.john.rawValue)") // Enum con valores asociados enum Furniture { // Asociación con Int - case Desk(height: Int) + case desk(height: Int) // Asociación con String e Int - case Chair(String, Int) + case chair(String, Int) func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Desk with \(height) cm" - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Chair of \(brand) with \(height) cm" } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair("Foo", 40) +var chair = Furniture.chair("Foo", 40) print(chair.description()) // "Chair of Foo with 40 cm" diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown index 5de2e13b..6b263942 100644 --- a/pt-pt/swift-pt.html.markdown +++ b/pt-pt/swift-pt.html.markdown @@ -471,23 +471,23 @@ print("Name: \(BookName.john.rawValue)") // Enum com valores associados enum Furniture { // Associar com um inteiro (Int) - case Desk(height: Int) + case desk(height: Int) // Associar com uma String e um Int - case Chair(String, Int) + case chair(String, Int) func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Desk with \(height) cm" - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Chair of \(brand) with \(height) cm" } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair("Foo", 40) +var chair = Furniture.chair("Foo", 40) print(chair.description()) // "Chair of Foo with 40 cm" diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index 5aa3d8e8..f2b1fd36 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -561,23 +561,23 @@ print("Имя: \(BookName.john.rawValue)") // Перечисление (enum) со связанными значениями enum Furniture { // Связать с типом Int - case Desk(height: Int) + case desk(height: Int) // Связать с типами String и Int - case Chair(String, Int) + case chair(String, Int) func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Письменный стол высотой \(height) см." - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Стул марки \(brand) высотой \(height) см." } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Письменный стол высотой 80 см." -var chair = Furniture.Chair("Foo", 40) +var chair = Furniture.chair("Foo", 40) print(chair.description()) // "Стул марки Foo высотой 40 см." diff --git a/swift.html.markdown b/swift.html.markdown index a3b33e25..516debed 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -544,23 +544,23 @@ print("Name: \(BookName.john.rawValue)") // Enum with associated Values enum Furniture { // Associate with Int - case Desk(height: Int) + case desk(height: Int) // Associate with String and Int - case Chair(String, Int) + case chair(String, Int) func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Desk with \(height) cm" - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Chair of \(brand) with \(height) cm" } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair("Foo", 40) +var chair = Furniture.chair("Foo", 40) print(chair.description()) // "Chair of Foo with 40 cm" diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index 5e09daa9..4c2cf59b 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -467,23 +467,23 @@ print("Name: \(KitapAdi.john.rawValue)") // Değerlerle ilişkilendirilmiş Enum enum Mobilya { // Int ile ilişkilendirilmiş - case Masa(yukseklik: Int) + case masa(yukseklik: Int) // String ve Int ile ilişkilendirilmiş - case Sandalye(String, Int) - + case sandalye(String, Int) + func aciklama() -> String { switch self { - case .Masa(let yukseklik): + case .masa(let yukseklik): return "Masa boyu \(yukseklik) cm" - case .Sandalye(let marka, let yukseklik): + case .sandalye(let marka, let yukseklik): return "\(brand) marka sandalyenin boyu \(yukseklik) cm" } } } -var masa: Mobilya = .Masa(yukseklik: 80) +var masa: Mobilya = .masa(yukseklik: 80) print(masa.aciklama()) // "Masa boyu 80 cm" -var sandalye = Mobilya.Sandalye("Foo", 40) +var sandalye = Mobilya.sandalye("Foo", 40) print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm" diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 002b117f..c25b2918 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -469,23 +469,23 @@ print("Name: \(BookName.john.rawValue)") // 与特定数据类型关联的枚举 enum Furniture { // 和 Int 型数据关联的枚举记录 - case Desk(height: Int) + case desk(height: Int) // 和 String, Int 关联的枚举记录 - case Chair(brand: String, height: Int) + case chair(brand: String, height: Int) func description() -> String { switch self { - case .Desk(let height): + case .desk(let height): return "Desk with \(height) cm" - case .Chair(let brand, let height): + case .chair(let brand, let height): return "Chair of \(brand) with \(height) cm" } } } -var desk: Furniture = .Desk(height: 80) +var desk: Furniture = .desk(height: 80) print(desk.description()) // "Desk with 80 cm" -var chair = Furniture.Chair(brand: "Foo", height: 40) +var chair = Furniture.chair(brand: "Foo", height: 40) print(chair.description()) // "Chair of Foo with 40 cm" -- cgit v1.2.3 From cfb7b656ae16c803485c7a30365e43f11c12f63d Mon Sep 17 00:00:00 2001 From: Mathieu Gemard Date: Mon, 9 Oct 2017 12:03:58 +0200 Subject: [java/fr] -Create java-fr.html.markdown (#2762) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create java-fr.html.markdown * Update java-fr.html.markdown * Update java-fr.html.markdown translation finished * typos * [java/en] changement switch/polymorphisme/interface * [java/fr] ajout d'un exemple pour l'opérateur ?: On pouvait penser qu'il fallait obligatoirement utiliser = avec ?: * [java/fr] typo --- fr-fr/java-fr.html.markdown | 939 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 939 insertions(+) create mode 100644 fr-fr/java-fr.html.markdown diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown new file mode 100644 index 00000000..d0f91611 --- /dev/null +++ b/fr-fr/java-fr.html.markdown @@ -0,0 +1,939 @@ +--- +language: java +contributors: + - ["Jake Prather", "https://github.com/JakeHP"] + - ["Jakukyo Friel", "https://weakish.github.io"] + - ["Madison Dickson", "https://github.com/mix3d"] + - ["Simon Morgan", "https://sjm.io/"] + - ["Zachary Ferguson", "https://github.com/zfergus2"] + - ["Cameron Schermerhorn", "https://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Michael Dähnert", "https://github.com/JaXt0r"] + - ["Rob Rose", "https://github.com/RobRoseKnows"] + - ["Sean Nam", "https://github.com/seannam"] +filename: JavaFr.java +translators: + - ['Mathieu Gemard', 'https://github.com/mgemard'] +lang: fr-fr +--- +Java est un langage orienté objet, concurrent et très facilement portable. Java +est inspiré du C++ mais ne reprend pas tous les concepts comme par exemple les +pointeurs et en ajoute de nouveaux comme les interfaces. +[En savoir plus.](https://fr.wikipedia.org/wiki/Java_(langage)) + +```java +// Les commentaires sur une seule ligne commencent par // + +/* +Les commentaires sur plusieurs lignes ressemblent à ceci. +*/ + +/** + * Les commentaires de la JavaDoc ressemblent à ceci. Ils sont utilisés pour + * décrire la classe et ses différents attributs. + * Attributs principaux: + * + * @author Nom (et information de contact comme l'email) de(s) auteur(s). + * @version Version actuelle du programme. + * @since Date à laquelle cette partie du programme a été ajouté. + * @param Décrit les différents paramètres pour d'une méthode. + * @return Décrit le retour de la méthode. + * @deprecated Indique si le code est déprécié ou ne doit plus être utilisé. + * @see Lien vers une autre partie de la documentation. +*/ + +// Importe la classe ArrayList qui se trouve dans le package java.util +import java.util.ArrayList; +// Importe toutes les classes qui se trouvent dans le package java.security +import java.security.*; + +// Chaque fichier .java doit contenir une classe public portant le même nom que +le fichier. +public class JavaFr { + + // Pour exécuter un programme Java, celui-ci doit posséder une méthode main + // qui fournir un point d'entrée. + public static void main(String[] args) { + + /////////////////////////////////////// + // Entrée/Sortie + /////////////////////////////////////// + + /* + * Sortie + */ + + // Utilisez System.out.println() pour afficher un texte dans la console. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Pour afficher sans retour à la ligne, on utilise System.out.print(). + System.out.print("Hello "); + System.out.print("World"); + + // Utilisez System.out.printf() pour formatter les données à afficher. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /* + * Entrée + */ + + // Utilisez Scanner pour lire l'entrée + // Nécessite: import java.util.Scanner; + Scanner scanner = new Scanner(System.in); + + // Lire une chaîne de caractères + String name = scanner.next(); + + // Lire un byte + byte numByte = scanner.nextByte(); + + // Lire un entier + int numInt = scanner.nextInt(); + + // Lire une entrée de type long + float numFloat = scanner.nextFloat(); + + // Lire une entrée de type double + double numDouble = scanner.nextDouble(); + + // Lire une entrée de type boolean + boolean bool = scanner.nextBoolean(); + + /////////////////////////////////////// + // Variables + /////////////////////////////////////// + + /* + * Déclaration de variable + */ + // Déclarez une variable avec la forme + int fooInt; + // Declarez plusieurs variables du même type , , + // + int fooInt1, fooInt2, fooInt3; + + /* + * Initialisation de variable + */ + + // Initialisez une variable sous la forme = + int barInt = 1; + // Initialisez plusieurs variables du même type et avec la même valeur + // sous la forme + // , , + // = = = + int barInt1, barInt2, barInt3; + barInt1 = barInt2 = barInt3 = 1; + + /* + * Types de variable + */ + // byte - Entier signé utilisant la notation en complément à deux sur + // 8 bits + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Si vous voulez interpréter un byte en entier non-signé, cette simple + // opération peut vous aider + int unsignedIntLessThan256 = 0xff & fooByte; + // cela contraste avec une conversion qui peut être négative. + int signedInt = (int) fooByte; + + // short - Entier signé utilisant la notation en complément à deux sur + // 16 bits + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // int - Entier signé utilisant la notation en complément à deux sur + // 32 bits + // (-2,147,483,648 <= int <= 2,147,483,647) + int bazInt = 1; + + // long - Entier signé utilisant la notation en complément à deux sur + // 64 bits + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L est utilisé pour indiquer que la variable est de type long; + // le nombre serait traité comme un int sans le L + + // Note: byte, short, int et long sont signés. Ils peuvent avoir des + // valeurs positives et négatives. + // Il n'existe pas de variantes non-signées. + // char, toutefois, est non-signé sur 16 bits + + // float - nombre à virgule flottante selon la norme IEEE 754 utilisant + // le format simple précision sur 32 bits + // 2^-149 <= float <= (2-2^-23) * 2^127 + float fooFloat = 234.5f; + // f ou F sont utilisés pour indiquer que la variable est de type float; + // autrement elle serait traitée comme un double. + + // double - nombre à virgule flottante selon la norme IEEE 754 utilisant + // le format double précision sur 64 bits + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double fooDouble = 123.4; + + // boolean - vrai & faux + boolean fooBoolean = true; + boolean barBoolean = false; + + // char - un caractère Unicode sur 16 bits + char fooChar = 'A'; + + // les variables final ne peuvent pas être réassignés à un autre objet, + final int HOURS_I_WORK_PER_WEEK = 9001; + // mais ils peuvent être initialisés plus tard. + final double E; + E = 2.71828; + + // BigInteger - entier immuable de taille arbitraire + // + // BigInteger est un type de donné qui autorise les développeurs à + // manipuler des entiers au delà de 64 bits. Les entiers sont stockés + // dans un tableau de bytes et sont manipulés grâce à des functions + // de la classe BigIntger + // + // BigInteger peut être initialiser en utilisant un tableau de bytes ou + // une chaîne de caractère. + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + // BigDecimal - entier immuable et positif de taille arbitraire + // + // BigDecimal comprend deux parties: une entier de taille arbitraire + // (BigInteger) et un entier de 32 bits représantant la position de la + // virgule. + // + // BigDecimal donne aux développeurs un contrôle total pour l'arrondie + // à la décimale. Il est recommandé de l'utiliser pour les valeurs + // monétaires et pour les cas où la value exacte de l'arondie à la + // décimale est requis. + // + // BigInteger peut être initialiser en utilisant un int, long, double ou + // String. + // On peut également utiliser un BigInteger et un int pour la + // position de la virgule. + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Sachez que la création d'un BigDecimal avec un float ou + // un double prendra en compte l'inexactitude des représention en float + // ou double. + // Préférez String pour une représention exacte. + BigDecimal tenCents = new BigDecimal("0.1"); + + // String - Chaîne de caractères + String fooString = "My String Is Here!"; + + // \n est un caractère d'échappement qui indique une nouvelle ligne + String barString = "Printing on a new line?\nNo Problem!"; + // \t est un caractère d'échappement qui indique une tabulation + String bazString = "Do you want to add a tab?\tNo Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Construction de chaînes de caractères + // #1 - avec l'opérateur + + // C'est la manière la plus simple et optimisé par le compilateur + String plusConcatenated = "Strings can " + "be concatenated " + "via + operator."; + System.out.println(plusConcatenated); + // Affiche: Strings can be concatenated via + operator. + + // #2 - avec StringBuilder + // Cette méthode ne nécessite pas d'objet String intermédiaire. Elle + // stocke juste les différentes chaînes de caractères et les assemble + // lorsque la méthode toString() est appelée. + // Attention: Cette classe n'est pas thread-safe (l'objet ne peut pas être partagé + // entre les threads). Une alternative + // (avec un impact sur les performances) thread-safe est d'utiliser la + // classe StringBuffer. + StringBuilder builderConcatenated = new StringBuilder(); + builderConcatenated.append("You "); + builderConcatenated.append("can use "); + builderConcatenated.append("the StringBuilder class."); + System.out.println(builderConcatenated.toString()); // only now is the string built + // Affiche: You can use the StringBuilder class. + + // StringBuffer est efficace quand la chaîne de caractères n'est pas + // utilisée avec la fin de sa construction. + StringBuilder stringBuilder = new StringBuilder(); + String inefficientString = ""; + for (int i = 0 ; i < 10; i++) { + stringBuilder.append(i).append(" "); + inefficientString += i + " "; + } + System.out.println(inefficientString); + System.out.println(stringBuilder.toString()); + // inefficientString est moins performant car une chaîne de caractères + // est créée à chaque itération de la boucle. + // Les concaténations avec + sont compilés en un StringBuilder et + // toString(). + // Evitez les concaténations de string dans les boucles. + + // #3 - avec la méthode format() de la classe String. + // Une autre alternative. Rapide et lisible. + String.format("%s may prefer %s.", "Or you", "String.format()"); + // Affiche: Or you may prefer String.format(). + + // Tableau + // La taille du tableau doit être précisée à l'instantiation + // Les formats suivant sont possibles pour déclarer un tableau + // [] = new []; + // [] = new []; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Une autre manière de déclarer et initialiser un tableau + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = {true, false, false}; + + // Accéder à un élément + System.out.println("intArray @ 0: " + intArray[0]); + + // Les tableaus commencent à 0 et sont muables + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Les autres types de donnés utiles sont + // ArrayList - Identique aux tableaux mais avec plus de fonctionnalités + // et de taille muable. + // LinkedList - Implémentation de listes doublement chaînées. Toutes Les + // opérations éffectuées le sont comme attendue pour une + // liste doublement chaînée. + // Map - Une collection d'objets qui fait correspondre une valeur à une + // clé. Map est une interface et ne peut pas être instantiée. Le + // type des clés et des valeurs doit être précisés à + // l'instantiation. Chaque clé doit correspondre à une seule + // valeur et chaque clé doit être unique (pas de clés dupliquées). + // HashMap - Cette classe utilise une table de hachage pour implémenter + // l'interface Map. Cela garantie que le temps d'exécution des + // opérations basiques, comme get (récuper une valeur) et + // insert (insérer une valeur), reste constant quelque soit la + // la taille. + // TreeMap - Cette classe utilise une structure en arbre et est + // ordonnée. Elle implémente un arbre bicolore (ou arbre rouge + // et noir) et ordonne les éléments en se basant sur la clé ou + // en utilisant un comparateur fournit à la création. + + /////////////////////////////////////// + // Opérateurs + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // Raccourcis pour des déclarations multiples + + // L'arithmétique + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Le modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Opérateurs de comparaison + System.out.println("3 == 2? " + (3 == 2)); // => faux + System.out.println("3 != 2? " + (3 != 2)); // => vrai + System.out.println("3 > 2? " + (3 > 2)); // => vrai + System.out.println("3 < 2? " + (3 < 2)); // => faux + System.out.println("2 <= 2? " + (2 <= 2)); // => vrai + System.out.println("2 >= 2? " + (2 >= 2)); // => vrai + + // Opérateurs boolean + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Opérateurs sur les bits + /* + ~ Complément à un + << Décalage des bits vers la gauche + >> Décalage des bits vers la droite, le signe est conservé + >>> Décalage des bits vers la droite, zéro est utilisé pour les bits + les plus à gauche + & Opérateur ET + ^ Opérateur OU exlusif + | Opérateur OU inclusif + */ + + // Opérateurs d'incrémentation + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // Les opérateurs ++ et -- incrémentent et décrémentent respectivement + // de 1. + // S'ils sont placés avant la variable, ils incrémentent la variable puis + // retournent la valeur. Placés après la varible, ils retournent la variable + // puis l'incrémentent. + System.out.println(i++); // i = 1, affiche 0 (pré-incrément) + System.out.println(++i); // i = 2, affiche 2 (post-incrément) + System.out.println(i--); // i = 1, affiche 2 (post-incrément) + System.out.println(--i); // i = 0, affiche 0 (pré-incrément) + + /////////////////////////////////////// + // Structures de contôles + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // Les instructions conditionnelle sont identiques aux langage C + int j = 10; + if (j == 10) { + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } + + // Bouble while + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Incrémente le compteur + // Itéré 100 fois, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // Boucle do-while + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Incrémente le compteur + // Itéré 99 fois, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); + + // Boucle for + // De la forme for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Itéré 10 fois, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // Fin d'une boucle for avec un label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // termine l'itération de la boucle englobante avec le label outer + } + } + } + + // Boucle for-each + // La boucle for est également capable d'itérer aussi bien sur un + // tableau que sur des objets qui implémentent l'interface Iterable. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // De la forme: for ( : ) + // Lu comme: "Pour chaque élément du tableau" + // note: le type doit correspondre à celui de l'objet itérable + for (int bar : fooList) { + System.out.println(bar); + //Itère 9 fois et affiche les chiffres de 1 à 9 + } + + // Le switch-case + // Un switch fonctionne avec les données de type byte, short, char et + // int. + // On peut également utiliser le type Enum, la classe String et les + // classes spéciales qui englobent les types primitifs (Character, Byte, + // Short et Integer). + // Depuis Java 7, on peut utiliser le type String. + int month = 3; + String monthString; + switch (month) { + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + default: monthString = "Some other month"; + break; + } + System.out.println("Switch Case Result: " + monthString); + + // try-with-resources (Java 7+) + // Le mécanisme de gestion des erreurs try-catch-finally peut être + // utilisé mais depuis Java 7 il est également possible d'utiliser + // try-with-ressources. + // try-with-resources simplifie try-catch-finally en fermant + // automatiquement les ressources + + // Pour utiliser un try-with-resources, il suffit d'inclure l'instance + // d'une classe qui implémente l'interface java.lang.AutoCloseable + try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) { + // Ici, vous pouvez essayer de faire quelque chose qui lance une + // exception. + System.out.println(br.readLine()); + // Avec Java 7, la ressource sera toujours fermé, même si elle lance + // une exception. + } catch (Exception ex) { + // La ressource sera fermé avant que le catch s'exécute. + System.out.println("readLine() failed."); + } + // Il n'y a pas besoin de finally dans ce cas, l'objet BufferedReader + // sera déjà fermé. Cela peut être utile dans certains cas spécifiques + // où le code contenu dans finally ne serait pas exécuté. + // Consulter la documention Oracle pour en savoir plus (en anglais) : + // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html + + + // Expression ternaire + // Vous pouvez utiliser l'opérateur ternaire '?' pour faire un + // assignement rapide avec une condition logique. + // Il faut lire "Si la (condition) est vraie alors utiliser la + // sinon utilisez la ". + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println("bar : " + bar); // Affiche "bar : A", car la condition est vraie + // Ou alors plus simplement + System.out.println("bar : " + (foo < 10 ? "A" : "B")); // Affiche également "bar : A" + + //////////////////////////////////////// + // Conversion de type + //////////////////////////////////////// + + // Autoboxing + + // Convertir un objet String en un objet Integer + Integer.parseInt("123"); // retourne un le type primitif int de 123 + + // Convert Integer To String + Integer.toString(123); // retourne un object String correspondant à"123" + + // Pour les autres conversions, référer vous aux classes suivantes: + // Double + // Long + // String + + /////////////////////////////////////// + // Classes et fonctions + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (voir plus loin pour la définition de la classe Bicycle) + + // Utilisez new pour instancier une classe + Bicycle trek = new Bicycle(); + + // Pour appeler une méthode de l'objet + trek.speedUp(3); // !! Il est conseillé de passer par une méthode pour + // changer la valeur d'une variable. + trek.setCadence(100); + + // toString retourne une représentation de l'objet en chaîne de caractères. + System.out.println("trek info: " + trek.toString()); + + // Initialisation avec double accolades + // Le langage Java ne permet pas de créer des collections statiques d'une + // manière simple. Généralement, on utilise la forme suivante: + private static final Set COUNTRIES = new HashSet(); + static { + COUNTRIES.add("DENMARK"); + COUNTRIES.add("SWEDEN"); + COUNTRIES.add("FINLAND"); + } + + // Mais on peut le faire d'une manière plus habile, dite initialisation + // avec double semi-colonnes + private static final Set COUNTRIES = new HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // La première semi-colonne crée une classe anonyme et la deuxième est + // un bloc d'initialisation du bloc. Ce dernier est appelé lorsque Copyright (c) + // classe anonyme est crée. Cela ne fonctionne pas uniquement pour les + // collections mais également pour toutes les classes n'étant pas + // déclarées comme final. + + } // Fin de la méthode main +} // Fin de la class JavaFr + +// Vous pouvez inclure des classes qui ne sont pas publics dans un fichier Java. +// Cependant, il est préférable de séparer les +// classes dans des fichiers différents. + +// Syntaxe de déclaration des classes: +// class { +// // Les attributs, les constructeurs et les méthodes de la classe vont ici. +// // Les functions de classes sont appelées méthode. +// } + +class Bicycle { + + // Attributs et variables de la classe Bicycle + public int cadence; // Public: Peut être accesible depuis n'importe où + private int speed; // Private: Accisible depuis la classe + protected int gear; // Protected: Accisible depuis la classe et ses sous- + // classes + String name; // default: Uniquement accesible depuis ce package + static String className; // Variable de classe static + + // Bloc static + // Java n'a pas d'implémentation pour les constructeurs statiques mais + // possède le bloc static qui peut être utilisé pour initialiser les + // variables de classe. + // Ce bloc sera appelé lorsque la classe sera chargée. + static { + className = "Bicycle"; + } + + // Les constructeurs sont un moyen de créer les classe + // Ceci est le constructeur de la classe Bicycle + public Bicycle() { + // Vous pouvez aussie appeler un autre constructeur. Par exemple en + // appelant le constructeur de la classe mère (voir héritage): + // this(1, 50, 5, "Bontrager"); + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + // Le constructeur peut prendre plusieurs arguments + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Syntaxe d'une méthode : + // ( + // ) + + // Les classes Java possèdent souvent des accesseurs (getters) et mutateurs + // (setters) pour leurs attributs. + + public int getCadence() { + return cadence; + } + + // Les méthodes void ne retourne aucune valeur + public void setCadence(int newValue) { + cadence = newValue; + } + public void setGear(int newValue) { + gear = newValue; + } + public void speedUp(int increment) { + speed += increment; + } + public void slowDown(int decrement) { + speed -= decrement; + } + public void setName(String newName) { + name = newName; + } + public String getName() { + return name; + } + + // Méthode pour afficher la valeur des attributs de l'objet. @Override est + // une annotation (voir plus loin). + @Override //On dit ici qu'on remplace la méthode de la classe Objet. + public String toString() { + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; + } +} // Fin de la classe Bicycle + +// PennyFarthing est une sous-classe de Bicycle +class PennyFarthing extends Bicycle { + // (Les Penny Farthings sont des bicyclette avec une grande roue avant. + // Il n'y a pas de roue libre, le cycliste est obligé de pédaler en + // permanence.) + + public PennyFarthing(int startCadence, int startSpeed) { + // Appelez le constructeur parent avec la méthode super() + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // Ici nous modifions la méthode setGear() de la classe mère. Il faut donc + // utiliser l'annotation @Overide. Pour en savoir plus sur les annotations, + // consulter la documention officiel (en anglais) : + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + this.gear = 0; + } +} + +// Polymorphisme (cast d'objets) +// Comme la classe PennyFarthing héritent de la classe Bicycle, on peut dire +// qu'un PennyFarthing est un Bicycle (un vélo en anglais) et écrire : +// Bicycle bicycle = new PennyFarthing(); +// Le polymorphisme est la capacité d'un objet de se faire passer pour un autre. +// Vous pouvez consulter la documentation Oracle pour plus de détails et +// concepts (en anglais) : +// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + +// Interfaces +// Déclaration d'une interface +// interface extends { +// // Constantes +// // Délaration des méthodes +// } + +// Exemple - Toute nourriture peut être mangée et digégée différemment +// L'interface Edible (traduction : comestible) décrit l'action de manger +public interface Edible { + public void eat(); // Toute classe qui implémente cette interface doit + // implémenter cette méthode +} + +// L'interface Digestible décrit l'action de digérer +public interface Digestible { + public void digest(); + // Depuis Java 8, les interfaces peuvent avoir des méthodes par défaut. + public void defaultMethod() { + System.out.println("Hi from default method ..."); + } +} + +// On peut maintenant créer une classe qui implémente chacune de ces interfaces. +public class Fruit implements Edible, Digestible { + @Override + public void eat() { + // ... + } + + @Override + public void digest() { + // ... + } +} + +// En Java, on peut hériter uniquement d'une classe mais on peut implémenter +// plusieurs interfaces: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { + @Override + public void InterfaceOneMethod() { + } + + @Override + public void InterfaceTwoMethod() { + } + +} + +// Classes abstraites + +// Syntaxe de déclaration: +// abstract class extends { +// // Constantes et variables +// // Méthodes +// } + +// Une classe abstraite contient au moins une méthode abstraite qui doit être +// définee dans la classe fille. Comme les interfaces, les classes abstraites ne +// peuvent pas être instanciées mais doivent être étendues avec les méthodes +// abstraites implémentées. À la différence des interfaces, une classe abstraite +// peut contenir des méthodes abstraites ou non-abstraites. Les méthodes dans une +// interfaces ne peuvent pas être implémentées à l'exception des méthodes static. +// Les variables d'une classe abstraite sont déclarées comme final par défaut à +// l'opposé des interfaces. Finalement les classes abstraites peuvent avoir une +// méthode main. +public abstract class Animal +{ + public abstract void makeSound(); + + // Les méthodes peuvent avoir une implémentation dans une classe abstraite. + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Note: On peut accéder à une variable privée ici. + age = 30; + } + + // On n'a pas besoin d'initialiser les variables dans les classe abstraites. + // Cependant, dans une interfaces, les variables sont implicitement + // déclarées comme final et doivent donc être initialisées. + private int age; + + public void printAge() + { + System.out.println(age); + } + + // Les classes abstraites peuvent avoir une fonction main. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // On doit également utiliser l'annotation @Override lors de la surchage de + // la méthode abstraite d'une classe abstraite. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERREUR! age est privé et n'est pas accesible. + } + + // NOTE: Vous obtiendrez une erreur si vous utilisé l'annotation @Override + // ici car Java n'autorise pas la surcharge de méthodes statiques. Ce qui ce + // passe est appelé "method hiding". Si vous voulez en savoir plus, + // consultez cette discussion (en anglais) : + // http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Classes finales + +// Syntaxe de déclaration +// final { +// // Constantes et variables +// // Méthodes déclarations +// } + +// Les classe déclarées comme final ne peuvent pas avoir de classe fille. Elles +// peuvent être considérées comme l'opposé des classes abstraites. +public final class SaberToothedCat extends Animal +{ + // On doit également utiliser l'annotation @Override lors de la surchage de + // la méthode abstraite d'une classe abstraite. + @Override + public void makeSound() + { + System.out.println("Roar"); + } +} + +// Méthodes final +public abstract class Mammal() +{ + // Syntaxe: + // final () + + // Les méthodes déclarées comme final ne peuvent pas être surchargées par + // une classe fille et en sont donc l'implémentation finale. + public final boolean isWarmBlooded() + { + return true; + } +} + +// Enumérations +// +// Le type enum est un type de donnée spécial qui permet à une variable de ne +// prendre que certaines valeurs prédéfinies. La variable doit être égales à une +// des valeurs pédéfinies pour celle-ci. En Java, les variables constantes sont +// notées en majuscules. +// On définie un type enum en utilisant le mot clé enum. Par exemple pour les +// jours de l'année: +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// On l'utilise ainsi: +public class EnumTest { + // On utilise notre énumération + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Mondays are bad."); + break; + case FRIDAY: + System.out.println("Fridays are better."); + break; + case SATURDAY: + case SUNDAY: + System.out.println("Weekends are best."); + break; + default: + System.out.println("Midweek days are so-so."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => affiche "Mondays are bad" + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => affiche "Midweek days are so-so" + } +} + +// Le type enum permet de faire bien plus que ce qui est montré ici. Il ne se +// limite pas à une liste de constante mais peut inclure des champs et méthodes. +// Vous pouvez en savoir plus ici (en anglais): +//https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Pour aller plus loin (en anglais) + +Les liens ci-dessous sont données si vous souhaitez approfondir sur le sujet, +n'hésitez pas à consulter Google pour trouver des exemples spécifiques. + +**Guides officiels d'Oracle**: + +* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +* Nouvelles fonctionnalités Java 8: + * [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) + * [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) + +**Pratiquer en ligne et tutoriels** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + +**Livres**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 13ab5a04aaabe94caff98ffb958a9ecf0e25fe3f Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Mon, 9 Oct 2017 09:17:46 -0300 Subject: rust-pt.html.markdown to pt-br folder --- pt-br/rust-pt.html.markdown | 332 ++++++++++++++++++++++++++++++++++++++++++++ rust-pt.html.markdown | 332 -------------------------------------------- 2 files changed, 332 insertions(+), 332 deletions(-) create mode 100644 pt-br/rust-pt.html.markdown delete mode 100644 rust-pt.html.markdown diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown new file mode 100644 index 00000000..8134d3c5 --- /dev/null +++ b/pt-br/rust-pt.html.markdown @@ -0,0 +1,332 @@ +--- +language: rust +filename: rust-pt.rs +contributors: + - ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"] +lang: pt-br + +--- + +Rust é uma linguagem de programação desenvolvida pelo Mozilla Research. Rust +combina controle de baixo nível sobre o desempenho com facilidades de alto +nível e garantias de segurança. + +Ele atinge esse objetico sem necessitar de um coletor de lixo ou um processo +*runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas +em C. + +A primeira versão de Rust, 0.1, apareceu em janeiro de 2012, e por três anos o +desenvolvimento correu tão rapidamente que que até recentemente o uso de +versões estáveis foi desencorajado e em vez disso a recomendação era usar as +versões empacotadas toda noite. + +Em 15 de maio de 2015, a versão 1.0 de Rust foi liberada com a garantia total +de compatibilidade reversa. Melhorias no tempo de compilação e em outros +aspectos do compilador estão disponíveis atualmente nas versões empacotadas à +noite. Rust adotou um modelo de versões *train-based* com novas versões +regularmente liberadas a cada seis semanas. A versão 1.1 beta de Rust foi +disponibilizada ao mesmo tempo que a versão 1.0. + +Apesar de Rust ser uma linguagem mais e baixo nível, Rust tem alguns conceitos +funcionais geralmente encontradas em linguagens de alto nível. Isso faz Rust +não apenas rápido, mas também fácil e eficiente para programar. + +```rust +// Isso é um comentário. Linhas de comentários são assim... +// e múltiplas linhas se parecem assim. + +/// Comentários para documentação são assim e permitem notação em markdown. +/// # Exemplos +/// +/// ``` +/// let five = 5 +/// ``` + +/////////////// +// 1. Básico // +/////////////// + +// Funções +// `i32` é o tipo para inteiros com sinal de 32 bits +fn add2(x: i32, y: i32) -> i32 { + // Implicit return (no semicolon) + x + y +} + +// Função main +fn main() { + // Números // + + // Immutable bindings + let x: i32 = 1; + + // Inteiros/Sufixos para ponto flutuante + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Inferência de tipos + // Em geral, o compilador Rust consegue inferir qual o tipo de uma + // variável, então você não tem que escrever uma anotação explícita de tipo. + // Ao longo desse tutorial, os tipos serão explicitamente anotados em + // muitos lugares, mas apenas com propóstico demonstrativo. A inferência de + // tipos pode gerenciar isso na maioria das vezes. + let implicit_x = 1; + let implicit_f = 1.3; + + // Aritmética + let sum = x + y + 13; + + // Variáveis mutáveis + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Strings // + + // String literais + let x: &str = "hello world!"; + + // Imprimindo + println!("{} {}", f, x); // 1.3 hello world + + // Uma `String` – uma String alocada no heap + let s: String = "hello world".to_string(); + + // Uma String slice - uma visão imutável em outra string. + // Basicamente, isso é um par imutável de ponteiros para uma string - ele + // não contém o conteúdo de uma strinf, apenas um ponteiro para o começo e + // um ponteiro para o fim da área de memória para a string, estaticamente + // alocada ou contida em outro objeto (nesse caso, `s`) + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hello world hello world + + // Vetores/arrays // + + // Um array de tamanho fixo + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // Um array dinâmico (vetor) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // Uma fatia – uma visão imutável em um vetor ou array + // Isso é como um string slice, mas para vetores + let slice: &[i32] = &vector; + + // Use `{:?}` para imprimir alguma coisa no estilo de depuração + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuplas // + + // Uma tupla é um conjunto de tamanho fixo de valores de tipos + // possivelmente diferentes + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // Desestruturando `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Indexando + println!("{}", x.1); // hello + + ////////////// + // 2. Tipos // + ////////////// + + // Struct + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // Uma estrutura com campos sem nome, chamada 'estrutura em tupla' + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // enum básico com na linguagem C + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // Enum com campos + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // Generics // + + struct Foo { bar: T } + + // Isso é definido na biblioteca padrão como um `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // Methods // + + impl Foo { + // Métodos recebem um parâmetro `self` explícito + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Traits (conhecidos como interfaces ou typeclasses em outras linguagens)// + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + ////////////////////////////////// + // 3. Reconhecimento de padrões // + ////////////////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // Reconhecimento avançado de padrões + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } + + ////////////////////////// + // 4. Controle de fluxo // + ////////////////////////// + + // `for` laços de repetição/iteração + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Ranges + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // prints `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` como expressão + let value = if true { + "good" + } else { + "bad" + }; + + // laço `while` de repetição + while 1 == 1 { + println!("The universe is operating normally."); + } + + // Repetição infinita + loop { + println!("Hello!"); + } + + //////////////////////////////////////// + // 5. Proteção de memória & ponteiros // + //////////////////////////////////////// + + // Ponteiro com dono - somente uma coisa pode 'possuir' esse ponteiro por + // vez. + // Isso significa que quando `Box` perde seu escopo, ele pode ser + // automaticamente desalocado com segurança. + let mut mine: Box = Box::new(3); + *mine = 5; // dereference + // Aqui, `now_its_mine` possui o controle exclusivo de `mine`. Em outras + // palavras, `mine` tem o controle transferido. + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // não compila porque `now_its_mine` é o dono + + // Referência - um ponteiro imutável que referencia outro dado + // Quando uma referência é dada a um valor, nós dizemos que o valor foi + // emprestado 'borrowed'. + // Quando um valor é emprestado sem ser mutável, ele não pode ser alterado + // ou ter a sua propriedade transferida. + // Um empréstimo finaliza quando o escopo em que ele foi criado termina. + + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // AO contrário de `mine`, `var` ainda pode ser usado + println!("{}", *ref_var); + // var = 5; // não compila porque `var` é emprestado + // *ref_var = 6; // não compila, porque `ref_var` é uma referência imutável + + // Referência mutável + // Quando um valor mutável é emprestado, ele não pode ser acessado. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' aponta para var2, que é mutável e emprestada + + println!("{}", *ref_var2); // 6 , // var2 não compila. + // ref_var2 é do tipo &mut i32, que guarda uma referência i32, não o valor. + // var2 = 2; // não compila porque `var2` é empretada. +} +``` + +## Outras leituras + +Existe muita coisa sobre Rust - isto aqui é apenas o básico para que você possa +entender as coisas mais importantes. Para aprender mais sobre Rust, leia [The +Rust Programming Language](http://doc.rust-lang.org/book/index.html) e +acompanhe [/r/rust](http://reddit.com/r/rust). A galera no canal #rust do +irc.mozilla.org também estão sempre dispostos a ajudar os novatos. + +Você pode brincar com outras característica de Rust com um compilador online +no portal oficial do projeto [Rust playpen](http://play.rust-lang.org), or ler +mais na página oficial [Rust website](http://rust-lang.org). + +No Brasil acompanhe os encontros do [Meetup Rust São Paulo] +(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/). + diff --git a/rust-pt.html.markdown b/rust-pt.html.markdown deleted file mode 100644 index 8134d3c5..00000000 --- a/rust-pt.html.markdown +++ /dev/null @@ -1,332 +0,0 @@ ---- -language: rust -filename: rust-pt.rs -contributors: - - ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"] -lang: pt-br - ---- - -Rust é uma linguagem de programação desenvolvida pelo Mozilla Research. Rust -combina controle de baixo nível sobre o desempenho com facilidades de alto -nível e garantias de segurança. - -Ele atinge esse objetico sem necessitar de um coletor de lixo ou um processo -*runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas -em C. - -A primeira versão de Rust, 0.1, apareceu em janeiro de 2012, e por três anos o -desenvolvimento correu tão rapidamente que que até recentemente o uso de -versões estáveis foi desencorajado e em vez disso a recomendação era usar as -versões empacotadas toda noite. - -Em 15 de maio de 2015, a versão 1.0 de Rust foi liberada com a garantia total -de compatibilidade reversa. Melhorias no tempo de compilação e em outros -aspectos do compilador estão disponíveis atualmente nas versões empacotadas à -noite. Rust adotou um modelo de versões *train-based* com novas versões -regularmente liberadas a cada seis semanas. A versão 1.1 beta de Rust foi -disponibilizada ao mesmo tempo que a versão 1.0. - -Apesar de Rust ser uma linguagem mais e baixo nível, Rust tem alguns conceitos -funcionais geralmente encontradas em linguagens de alto nível. Isso faz Rust -não apenas rápido, mas também fácil e eficiente para programar. - -```rust -// Isso é um comentário. Linhas de comentários são assim... -// e múltiplas linhas se parecem assim. - -/// Comentários para documentação são assim e permitem notação em markdown. -/// # Exemplos -/// -/// ``` -/// let five = 5 -/// ``` - -/////////////// -// 1. Básico // -/////////////// - -// Funções -// `i32` é o tipo para inteiros com sinal de 32 bits -fn add2(x: i32, y: i32) -> i32 { - // Implicit return (no semicolon) - x + y -} - -// Função main -fn main() { - // Números // - - // Immutable bindings - let x: i32 = 1; - - // Inteiros/Sufixos para ponto flutuante - let y: i32 = 13i32; - let f: f64 = 1.3f64; - - // Inferência de tipos - // Em geral, o compilador Rust consegue inferir qual o tipo de uma - // variável, então você não tem que escrever uma anotação explícita de tipo. - // Ao longo desse tutorial, os tipos serão explicitamente anotados em - // muitos lugares, mas apenas com propóstico demonstrativo. A inferência de - // tipos pode gerenciar isso na maioria das vezes. - let implicit_x = 1; - let implicit_f = 1.3; - - // Aritmética - let sum = x + y + 13; - - // Variáveis mutáveis - let mut mutable = 1; - mutable = 4; - mutable += 2; - - // Strings // - - // String literais - let x: &str = "hello world!"; - - // Imprimindo - println!("{} {}", f, x); // 1.3 hello world - - // Uma `String` – uma String alocada no heap - let s: String = "hello world".to_string(); - - // Uma String slice - uma visão imutável em outra string. - // Basicamente, isso é um par imutável de ponteiros para uma string - ele - // não contém o conteúdo de uma strinf, apenas um ponteiro para o começo e - // um ponteiro para o fim da área de memória para a string, estaticamente - // alocada ou contida em outro objeto (nesse caso, `s`) - let s_slice: &str = &s; - - println!("{} {}", s, s_slice); // hello world hello world - - // Vetores/arrays // - - // Um array de tamanho fixo - let four_ints: [i32; 4] = [1, 2, 3, 4]; - - // Um array dinâmico (vetor) - let mut vector: Vec = vec![1, 2, 3, 4]; - vector.push(5); - - // Uma fatia – uma visão imutável em um vetor ou array - // Isso é como um string slice, mas para vetores - let slice: &[i32] = &vector; - - // Use `{:?}` para imprimir alguma coisa no estilo de depuração - println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] - - // Tuplas // - - // Uma tupla é um conjunto de tamanho fixo de valores de tipos - // possivelmente diferentes - let x: (i32, &str, f64) = (1, "hello", 3.4); - - // Desestruturando `let` - let (a, b, c) = x; - println!("{} {} {}", a, b, c); // 1 hello 3.4 - - // Indexando - println!("{}", x.1); // hello - - ////////////// - // 2. Tipos // - ////////////// - - // Struct - struct Point { - x: i32, - y: i32, - } - - let origin: Point = Point { x: 0, y: 0 }; - - // Uma estrutura com campos sem nome, chamada 'estrutura em tupla' - struct Point2(i32, i32); - - let origin2 = Point2(0, 0); - - // enum básico com na linguagem C - enum Direction { - Left, - Right, - Up, - Down, - } - - let up = Direction::Up; - - // Enum com campos - enum OptionalI32 { - AnI32(i32), - Nothing, - } - - let two: OptionalI32 = OptionalI32::AnI32(2); - let nothing = OptionalI32::Nothing; - - // Generics // - - struct Foo { bar: T } - - // Isso é definido na biblioteca padrão como um `Option` - enum Optional { - SomeVal(T), - NoVal, - } - - // Methods // - - impl Foo { - // Métodos recebem um parâmetro `self` explícito - fn get_bar(self) -> T { - self.bar - } - } - - let a_foo = Foo { bar: 1 }; - println!("{}", a_foo.get_bar()); // 1 - - // Traits (conhecidos como interfaces ou typeclasses em outras linguagens)// - - trait Frobnicate { - fn frobnicate(self) -> Option; - } - - impl Frobnicate for Foo { - fn frobnicate(self) -> Option { - Some(self.bar) - } - } - - let another_foo = Foo { bar: 1 }; - println!("{:?}", another_foo.frobnicate()); // Some(1) - - ////////////////////////////////// - // 3. Reconhecimento de padrões // - ////////////////////////////////// - - let foo = OptionalI32::AnI32(1); - match foo { - OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), - OptionalI32::Nothing => println!("it’s nothing!"), - } - - // Reconhecimento avançado de padrões - struct FooBar { x: i32, y: OptionalI32 } - let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; - - match bar { - FooBar { x: 0, y: OptionalI32::AnI32(0) } => - println!("The numbers are zero!"), - FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => - println!("The numbers are the same"), - FooBar { x: n, y: OptionalI32::AnI32(m) } => - println!("Different numbers: {} {}", n, m), - FooBar { x: _, y: OptionalI32::Nothing } => - println!("The second number is Nothing!"), - } - - ////////////////////////// - // 4. Controle de fluxo // - ////////////////////////// - - // `for` laços de repetição/iteração - let array = [1, 2, 3]; - for i in array.iter() { - println!("{}", i); - } - - // Ranges - for i in 0u32..10 { - print!("{} ", i); - } - println!(""); - // prints `0 1 2 3 4 5 6 7 8 9 ` - - // `if` - if 1 == 1 { - println!("Maths is working!"); - } else { - println!("Oh no..."); - } - - // `if` como expressão - let value = if true { - "good" - } else { - "bad" - }; - - // laço `while` de repetição - while 1 == 1 { - println!("The universe is operating normally."); - } - - // Repetição infinita - loop { - println!("Hello!"); - } - - //////////////////////////////////////// - // 5. Proteção de memória & ponteiros // - //////////////////////////////////////// - - // Ponteiro com dono - somente uma coisa pode 'possuir' esse ponteiro por - // vez. - // Isso significa que quando `Box` perde seu escopo, ele pode ser - // automaticamente desalocado com segurança. - let mut mine: Box = Box::new(3); - *mine = 5; // dereference - // Aqui, `now_its_mine` possui o controle exclusivo de `mine`. Em outras - // palavras, `mine` tem o controle transferido. - let mut now_its_mine = mine; - *now_its_mine += 2; - - println!("{}", now_its_mine); // 7 - // println!("{}", mine); // não compila porque `now_its_mine` é o dono - - // Referência - um ponteiro imutável que referencia outro dado - // Quando uma referência é dada a um valor, nós dizemos que o valor foi - // emprestado 'borrowed'. - // Quando um valor é emprestado sem ser mutável, ele não pode ser alterado - // ou ter a sua propriedade transferida. - // Um empréstimo finaliza quando o escopo em que ele foi criado termina. - - let mut var = 4; - var = 3; - let ref_var: &i32 = &var; - - println!("{}", var); // AO contrário de `mine`, `var` ainda pode ser usado - println!("{}", *ref_var); - // var = 5; // não compila porque `var` é emprestado - // *ref_var = 6; // não compila, porque `ref_var` é uma referência imutável - - // Referência mutável - // Quando um valor mutável é emprestado, ele não pode ser acessado. - let mut var2 = 4; - let ref_var2: &mut i32 = &mut var2; - *ref_var2 += 2; // '*' aponta para var2, que é mutável e emprestada - - println!("{}", *ref_var2); // 6 , // var2 não compila. - // ref_var2 é do tipo &mut i32, que guarda uma referência i32, não o valor. - // var2 = 2; // não compila porque `var2` é empretada. -} -``` - -## Outras leituras - -Existe muita coisa sobre Rust - isto aqui é apenas o básico para que você possa -entender as coisas mais importantes. Para aprender mais sobre Rust, leia [The -Rust Programming Language](http://doc.rust-lang.org/book/index.html) e -acompanhe [/r/rust](http://reddit.com/r/rust). A galera no canal #rust do -irc.mozilla.org também estão sempre dispostos a ajudar os novatos. - -Você pode brincar com outras característica de Rust com um compilador online -no portal oficial do projeto [Rust playpen](http://play.rust-lang.org), or ler -mais na página oficial [Rust website](http://rust-lang.org). - -No Brasil acompanhe os encontros do [Meetup Rust São Paulo] -(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/). - -- cgit v1.2.3 From 8c2c5091b92da3d283bff279fb733b8f5d9212be Mon Sep 17 00:00:00 2001 From: fnscoder Date: Mon, 9 Oct 2017 15:49:51 -0300 Subject: delete duble file asymptoticnotation in pt-br --- pt-br/asymptoticnotation-pt.html.markdown | 161 ------------------------------ 1 file changed, 161 deletions(-) delete mode 100644 pt-br/asymptoticnotation-pt.html.markdown diff --git a/pt-br/asymptoticnotation-pt.html.markdown b/pt-br/asymptoticnotation-pt.html.markdown deleted file mode 100644 index c5299a11..00000000 --- a/pt-br/asymptoticnotation-pt.html.markdown +++ /dev/null @@ -1,161 +0,0 @@ ---- -category: Algorithms & Data Structures -name: Asymptotic Notation -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] -translators: - - ["Carolina Knoll", "http://github.com/carolinaknoll"] -lang: pt-br ---- - -# Aprenda X em Y minutos -## Onde X=Notação Assintótica - -# Notações Assintóticas -## O que são? - -Notações assintóticas são notações matemáticas que nos permitem analisar tempo de execução -de um algoritmo, identificando o seu comportamento de acordo como o tamanho de entrada para -o algoritmo aumenta. Também é conhecido como taxa de "crescimento" de um algoritmo. O algoritmo -simplesmente se torna incrivelmente lento conforme o seu tamanho aumenta? Será que pode-se na -maior parte manter o seu tempo de execução rápido mesmo quando o tamanho de entrada aumenta? -A notação assintótica nos dá a capacidade de responder a essas perguntas. - -## Além desta, existem outras alternativas para responder a essas perguntas? - -Uma forma seria a de contar o número de operações primitivas em diferentes tamanhos de entrada. -Embora esta seja uma solução válida, a quantidade de trabalho necessário, mesmo para algoritmos -simples, não justifica a sua utilização. - -Outra maneira é a de medir fisicamente a quantidade de tempo que leva para se executar um algoritmo -de diferentes tamanhos. No entanto, a precisão e a relatividade (já que tempos obtidos só teriam -relação à máquina em que eles foram testados) deste método estão ligadas a variáveis ambientais, -tais como especificações de hardware, poder de processamento, etc. - -## Tipos de Notação Assintótica - -Na primeira seção deste documento nós descrevemos como uma notação assintótica identifica o comportamento -de um algoritmo como as alterações de tamanho de entrada (input). Imaginemos um algoritmo como uma função -f, n como o tamanho da entrada, e f (n) sendo o tempo de execução. Assim, para um determinado algoritmo f, -com tamanho de entrada n você obtenha algum tempo de execução resultante f (n). Isto resulta num gráfico, -em que o eixo Y representa o tempo de execução, o eixo X é o tamanho da entrada, e os pontos marcados são -os resultantes da quantidade de tempo para um dado tamanho de entrada. - -Pode-se rotular uma função ou algoritmo com uma notação assintótica de diversas maneiras diferentes. -Dentre seus exemplos, está descrever um algoritmo pelo seu melhor caso, pior caso, ou caso equivalente. -O mais comum é o de analisar um algoritmo pelo seu pior caso. Isso porque você normalmente não avaliaria -pelo melhor caso, já que essas condições não são as que você está planejando. Um bom exemplo disto é o de -algoritmos de ordenação; especificamente, a adição de elementos a uma estrutura de tipo árvore. O melhor -caso para a maioria dos algoritmos pode ser tão simples como uma única operação. No entanto, na maioria -dos casos, o elemento que você está adicionando terá de ser ordenado de forma adequada através da árvore, -o que poderia significar a análise de um ramo inteiro. Este é o pior caso, e é por ele que precisamos seguir. - -### Tipos de funções, limites, e simplificação - -``` -Função Logaritmica - log n -Função Linear - an + b -Função Quadrática - an^2 + bn + c -Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde z é uma constante -Função Exponencial - a^n, onde a é uma constante -``` - -Estas são algumas classificações básicas de crescimento de função usados em várias notações. A lista -começa com a função crescimento mais lento (logarítmica, com tempo de execução mais rápido) e vai até -a mais rápida (exponencial, com tempo de execução mais lento). Observe que 'n', ou nossa entrada, -cresce em cada uma dessas funções, e o resultado claramente aumenta muito mais rapidamente em função -quadrática, polinomial e exponencial, em comparação com a logarítmica e a linear. - -Uma observação de boa importância é que, para as notações a serem discutidas, deve-se fazer o melhor -para utilizar termos mais simples. Isto significa desrespeitar constantes, e simplificar termos de -ordem, porque, como o tamanho da entrada (ou n no nosso f (n) exemplo) aumenta infinitamente (limites -matemáticos), os termos em ordens mais baixas e constantes são de pouca ou nenhuma importância. Dito -isto, se você possui constantes com valor 2^9001, ou alguma outra quantidade ridícula, inimaginável, -perceberá que a simplificação distorcerá a precisão de sua notação. - -Já que nós queremos a forma mais simples, vamos modificar nossas funções um pouco. - -``` -Logaritmica - log n -Linear - n -Quadrática - n^2 -Polinomial - n^z, onde z é uma constante -Exponencial - a^n, onde a é uma constante -``` - -### O Grande-O - -Grande-O, geralmente escrita como O, é uma Notação Assintótica para o pior caso para uma dada função. Digamos -que `f(n)` é o tempo de execução de seu algoritmo, e `g(n)` é uma complexidade de tempo arbitrário que você está -tentando se relacionar com o seu algoritmo. `f(n)` será O(g(n)), se, por qualquer constante real c (c > 0), -`f(n)` <= `c g(n)` para cada tamanho de entrada n (n > 0). - -*Exemplo 1* - -``` -f(n) = 3log n + 100 -g(n) = log n -``` - -É `f(n)` um O(g(n))? -É 3 `log n + 100` igual a O(log n)? -Vamos checar na definição de Grande-O. - -``` -3log n + 100 <= c * log n -``` - -Existe alguma constante c que satisfaça isso para todo n? - -``` -3log n + 100 <= 150 * log n, n > 2 (indefinido em n = 1) -``` - -Sim! A definição de Grande-O foi satisfeita. Sendo assim, `f(n)` é O(g(n)). - -*Exemplo 2* - -``` -f(n) = 3 * n^2 -g(n) = n -``` - -É `f(n)` um O(g(n))? -É `3 * n^2` um O(n)? -Vamos ver na definição de Grande-O. - -``` -3 * n^2 <= c * n -``` - -Existe alguma constante que satisfaça isso para todo n? -Não, não existe. `f(n)` NÃO É O(g(n)). - -### Grande-Omega - -Grande-Omega, comumente escrito como Ω, é uma Notação Assintótica para o melhor caso, ou -uma taxa de crescimento padrão para uma determinada função. - -`f(n)` é Ω(g(n)), se, por qualquer constante c real (c > 0), `f(n)` é >= `c g(n)` para cada -tamanho de entrada n (n > 0). - -Sinta-se livre para pesquisar recursos adicionais e obter mais exemplos sobre este assunto! -Grande-O é a notação primária utilizada para tempo de execução de algoritmos, de modo geral. - -### Notas de Finalização - -É complicado exibir este tipo de assunto de forma tão curta, então é definitivamente recomendado -pesquisar além dos livros e recursos on-line listados. Eles serão capazes de analisar o assunto com -uma profundidade muito maior, além de ter definições e exemplos. Mais sobre onde X="Algoritmos e -Estruturas de Dados" está a caminho: Haverá conteúdo focado na análise de exemplos de códigos reais -em breve. - -## Livros - -* [Algorithms] (http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) -* [Algorithm Design] (http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) - -## Recursos Online - -* [MIT] (http://web.mit.edu/16.070/www/lecture/big_o.pdf) -* [KhanAcademy] (https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) -- cgit v1.2.3 From 667cbfe2ba105858f2dabb55f0772c6769a2323a Mon Sep 17 00:00:00 2001 From: Chris Martin Date: Mon, 9 Oct 2017 18:51:02 -0400 Subject: [nix/en] document using ? to test set membership --- nix.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nix.html.markdown b/nix.html.markdown index ef59a135..ba122a46 100644 --- a/nix.html.markdown +++ b/nix.html.markdown @@ -208,6 +208,12 @@ with builtins; [ { a = 1; b = 2; }.a #=> 1 + # The ? operator tests whether a key is present in a set. + ({ a = 1; b = 2; } ? a) + #=> true + ({ a = 1; b = 2; } ? c) + #=> false + # The // operator merges two sets. ({ a = 1; } // { b = 2; }) #=> { a = 1; b = 2; } -- cgit v1.2.3 From efa793fbb24eaa3d9a48b819c8006d18c9025fb0 Mon Sep 17 00:00:00 2001 From: kenrick95 Date: Tue, 10 Oct 2017 21:12:21 +0800 Subject: Fix typo in CHICKEN language RSR5 --> R5RS and RSR7 --> R7RS Fixes #2803 --- CHICKEN.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown index 7fb0270b..bb2f91f0 100644 --- a/CHICKEN.html.markdown +++ b/CHICKEN.html.markdown @@ -8,7 +8,7 @@ contributors: CHICKEN is an implementation of Scheme programming language that can compile Scheme programs to C code as well as interpret them. CHICKEN -supports RSR5 and RSR7 (work in progress) standards and many extensions. +supports R5RS and R7RS (work in progress) standards and many extensions. ```scheme @@ -510,7 +510,7 @@ sqr ;; => # ``` ## Further Reading * [CHICKEN User's Manual](http://wiki.call-cc.org/man/4/The%20User%27s%20Manual). -* [RSR5 standards](http://www.schemers.org/Documents/Standards/R5RS) +* [R5RS standards](http://www.schemers.org/Documents/Standards/R5RS) ## Extra Info -- cgit v1.2.3 From 03d1072244c9ea9d2a6c13b6e84cf151445ab259 Mon Sep 17 00:00:00 2001 From: Vasiliy Petrov Date: Tue, 10 Oct 2017 23:44:57 +0300 Subject: [haml/ru] Add Russian translation for haml --- ru-ru/haml-ru.html.markdown | 233 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 ru-ru/haml-ru.html.markdown diff --git a/ru-ru/haml-ru.html.markdown b/ru-ru/haml-ru.html.markdown new file mode 100644 index 00000000..c2f8852e --- /dev/null +++ b/ru-ru/haml-ru.html.markdown @@ -0,0 +1,233 @@ +--- +language: haml +filename: learnhaml-ru.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Vasiliy Petrov", "https://github.com/Saugardas"] +translators: + - ["Vasiliy Petrov", "https://github.com/Saugardas"] +lang: ru-ru +--- + +Haml - язык разметки (в основном используемый с Ruby), с помощью которого могут быть легко описаны HTML-документы. +Он является популярной альтернативой используемому в Rails шаблонизатору (.erb), и позволяет вставлять Ruby-код в вашу разметку. + +Haml убирает избыточность закрывающих тегов благодаря отступам. +В результате получается меньшая по размерам, хорошо структурированная, логичная и читаемая разметка. + +Вы можете использовать Haml и вне Ruby-проекта. Установите гем Haml и используйте командную строку для конвертирования html-файлов: + +```shell +$ haml input_file.haml output_file.html +``` + + +```haml +/ ------------------------------------------- +/ Отступы +/ ------------------------------------------- + +/ + Отступы являются важным элементом синтаксиса, поэтому они должны быть + одинаковыми во всём документе. Обычно используют два пробела, + но это не является обязательным правилом - можно использовать любое + количество пробелов для отступов. Главное, чтобы это количество было + одинаковым во всём документе. + + +/ ------------------------------------------- +/ Комментарии +/ ------------------------------------------- + +/ Комментари начинается с символа косой черты. + +/ + Для написания многострочного комментария расположите ваш комментарий + на следующем уровне вложенности от символа косой черты + +-# "Скрытый" комментарий. Этот комментарий не попадёт в результирующий документ + + +/ ------------------------------------------- +/ Элементы HTML +/ ------------------------------------------- + +/ Чтобы написать тег, используйте символ процента (%) и название тега +%body + %header + %nav + +/ Обратите внимание на отсутствие закрывающих тегов. Код выше выведет: + +
+ +
+ + +/ + Так как тег div используется очень часто, его можно опустить. + Можно указать только имя класса или идентификатора (. или #) + Например код: + +%div.my_class + %div#my_id + +/ Можно записать: +.my_class + #my_id + +/ Для добавления контента в тег, просто добавьте текст после объявления тега +%h1 Заголовок + +/ Для многострочного содержания используйте отступы +%p + Многострочное содержание + в две строки. + +/ + Амперсанд - равно (&=) обрабатывают Ruby код также, как и без амперсанда, + но HTML-символы в результате будут экранированы. Например: + +%p + &= "Да & да" + +/ выведет 'Да & да' + +/ + Чтобы выполнять Ruby-код без экранрования, можно использовать + "восклицательный знак" и "равно" (!=) + +%p + != "Тег абзаца

" + +/ выведет 'Тег абзаца

' + +/ CSS - классы могут быть добавлены через точку от определения тега +%div.foo.bar + +/ Или с помощью хеша атрибутов +%div{ :class => 'foo bar' } + +/ Хеш атрибутов может быть добавлен для любого тега +%a{ :href => '#', :class => 'bar', :title => 'Bar' } + +/ Для булевых атрибутов просто присвойте значение 'true' +%input{ :selected => true } + +/ Для data - атрибутов присвойте ключу :data хеш с данными +%div{ :data => { :attribute => 'foo' } } + +/ Для Ruby версии 1.9 или выше, можно использовать новый синтаксис хешей +%div{ data: { attribute: 'foo' } } + +/ Также можно использовать HTML-синтаксис атрибутов +%a(href='#' title='bar') + +/ Можно использовать оба варианта одновременно +%a(href='#'){ title: @my_class.title } + + +/ ------------------------------------------- +/ Включение Ruby +/ ------------------------------------------- + +/ Для включения Ruby кода используйте знак "равно" + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ Для выполнения Ruby кода без вывода в HTML, используйте знак дефиса +- books = ['book 1', 'book 2', 'book 3'] + +/ + Можно выполнять любой Ruby код, например с блоками. + Закрывающий "end" не нужен, так как они будут закрыты автоматически, + основываясь на вложенности. + +- books.shuffle.each_with_index do |book, index| + %h1= book + + - if book do + %p This is a book + +/ Добавление списка +%ul + %li + =item1 + =item2 + +/ ------------------------------------------- +/ Пример таблицы с классами Bootstrap'a +/ ------------------------------------------- + +%table.table.table-hover + %thead + %tr + %th Header 1 + %th Header 2 + + %tr + %td Value1 + %td value2 + + %tfoot + %tr + %td + Foot value + + +/ ------------------------------------------- +/ Интерполяция Ruby кода +/ ------------------------------------------- + +/ Ruby код может быть интерполирован в текст с помощью #{} +%p Ваша самая любимая игра - #{best_game} + +/ Тоже самое, что и: +%p= "Ваша самая любимая игра - #{best_game}" + + +/ ------------------------------------------- +/ Фильтры +/ ------------------------------------------- + +/ + Фильтры передают связанный блок текста в соотвествующую + фильтрующую программу и возвращают результат в Haml + Фильтр обозначается двоеточием и названием фильтра: + +/ Markdown filter +:markdown + # Заголовк + + Текст **внутри** *блока* + +/ Код выше будет скомпилирован в +

Заголовок

+ +

Текст внутри блока

+ +/ Javascript - фильтр +:javascript + console.log('This is inline + +/ + Существует множество типов фильров (:markdown, :javascript, :coffee, + :css, :ruby и так далее). Вы можете определить собственный фильтр c + помощью Haml::Filters. + +``` + +## Дополнительные ресурсы + +- [О Haml](https://haml.ru) - Хорошее введение, описывает преимущества Haml. +- [Документация](https://haml.ru/documentation/) - Документация Haml на русском языке. -- cgit v1.2.3 From 1ca9a0911060d46609aa2b715002607fae3cc272 Mon Sep 17 00:00:00 2001 From: attil-io Date: Wed, 11 Oct 2017 19:49:55 +0200 Subject: Fix typo Remove unnecessary closing parenthesis from inline-2 macro. --- clojure-macros.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown index 89066faf..3864f676 100644 --- a/clojure-macros.html.markdown +++ b/clojure-macros.html.markdown @@ -131,7 +131,7 @@ You'll want to be familiar with Clojure. Make sure you understand everything in ; However, we'll need to make it a macro if we want it to be run at compile time (defmacro inline-2 [form] - (inline-2-helper form))) + (inline-2-helper form)) (macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) ; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) -- cgit v1.2.3 From 2095b65d8cc828b38d7d7641ea42c2fc15a78c59 Mon Sep 17 00:00:00 2001 From: Vasiliy Petrov Date: Wed, 11 Oct 2017 21:50:51 +0300 Subject: [javascript/uk-ua] Fix typo --- uk-ua/javascript-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index ac6a2bde..397b1c5e 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -17,7 +17,7 @@ JavaScript було створено в 1995 році Бренданом Айк вбудована підтримка браузерами призвела до того, що JavaScript став популярніший за власне Java. -Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, +Зараз JavaScript не обмежується тільки веб-браузером. Наприклад, Node.js, програмна платформа, що дозволяє виконувати JavaScript код з використанням рушія V8 від браузера Google Chrome, стає все більш і більш популярною. -- cgit v1.2.3 From 027e152dda5f26e2aa74f6739c21f9ca3a8a4fde Mon Sep 17 00:00:00 2001 From: Joyce Kung Date: Fri, 13 Oct 2017 12:10:32 -0400 Subject: Fixed line 59 - printing Using echo with ' ' means that the variable won't be expanded, so it should print the literal $Variable instead of some string. --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 981d7a1e..0c097c27 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -56,7 +56,7 @@ Variable= 'Some string' # => returns error: "Some string: command not found" # Using the variable: echo $Variable # => Some string echo "$Variable" # => Some string -echo '$Variable' # => Some string +echo '$Variable' # => $Variable # When you use the variable itself — assign it, export it, or else — you write # its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! -- cgit v1.2.3 From 340a7b6d7812ef5ba1903983a7cd3f5cc3385288 Mon Sep 17 00:00:00 2001 From: Marko Cubela Date: Sat, 14 Oct 2017 11:43:53 +0200 Subject: add more commit examples --- de-de/git-de.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 61f7bb67..a0ed120f 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -205,6 +205,12 @@ Speichert die aktuellen Inhalte des Index in einen neuen *Commit*. Dieser Commit ```bash # Commit mit Beschreibung erstellen. $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" + +# Alle veränderten oder gelöschten Dateien außer neue Dateien werden gestaged und dann wird ein Commit erstellt. +$ git commit -a -m "Modified foo.php and removed bar.php" + +# Ändert den letzten Commit (der letzte Commit wird mit einem neuen Commit ersetzt) +$ git commit --amend -m "Correct message" ``` ### diff -- cgit v1.2.3 From 894ddf5ec33eb2fdaf739850114f77fd9a0679dc Mon Sep 17 00:00:00 2001 From: Pratik Karki Date: Sat, 14 Oct 2017 18:46:05 +0545 Subject: fix for #2859 --- awk.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/awk.html.markdown b/awk.html.markdown index 0e27528d..e3ea6318 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -38,7 +38,7 @@ BEGIN { a = count + 1 b = count - 1 c = count * 1 - d = count / 1 + d = count / 1 # integer division e = count % 1 # modulus f = count ^ 1 # exponentiation @@ -143,7 +143,7 @@ BEGIN { } # Here's how you define a function -function arithmetic_functions(a, b, c, localvar) { +function arithmetic_functions(a, b, c, d) { # Probably the most annoying part of AWK is that there are no local # variables. Everything is global. For short scripts, this is fine, even -- cgit v1.2.3 From c174cb0829e3b1e92c9cf86a8dc0c0f77b95295d Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 15 Oct 2017 20:21:07 +0200 Subject: add backticks to escape markdown formatting characters --- dynamic-programming.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index 7df367e7..4db8e92e 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -26,7 +26,7 @@ The Longest Increasing Subsequence problem is to find the longest increasing sub First of all we have to find the value of the longest subsequences(LSi) at every index i with last element of sequence being ai. Then largest LSi would be the longest subsequence in the given sequence. To begin LSi is assigned to be one since ai is element of the sequence(Last element). Then for all `j` such that `j Date: Sun, 15 Oct 2017 21:34:21 +0200 Subject: fix small typos --- haxe.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index e811031e..df2a1e78 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -770,8 +770,8 @@ class UsingExample { ``` We're still only scratching the surface here of what Haxe can do. For a formal -overiew of all Haxe features, checkout the [online -manual](http://haxe.org/manual), the [online api](http://api.haxe.org/), and +overview of all Haxe features, checkout the [online +manual](http://haxe.org/manual), the [online API](http://api.haxe.org/), and "haxelib", the [haxe library repo] (http://lib.haxe.org/). For more advanced topics, consider checking out: -- cgit v1.2.3 From 90e384819801beb00edd67372a84dcd879c13d9d Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 15 Oct 2017 22:16:31 +0200 Subject: add missing lang declaration to html-it The missing declaration caused the italian version show up as a duplicate HTML article, becoming the parent of every further translation. --- it-it/html-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/html-it.html.markdown b/it-it/html-it.html.markdown index 1d2a0618..471019a1 100644 --- a/it-it/html-it.html.markdown +++ b/it-it/html-it.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: - ["Ale46", "http://github.com/Ale46/"] +lang: it-it --- HTML sta per HyperText Markup Language (linguaggio a marcatori per ipertesti). -- cgit v1.2.3 From 6b8264756b574be0af84e0a8a104cfa75c0027bb Mon Sep 17 00:00:00 2001 From: "Joseph Gabriel J. Adaoag" Date: Fri, 13 Oct 2017 16:20:14 +0800 Subject: Fix tuck definition --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 09f3beb0..ff094017 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -59,7 +59,7 @@ Forth, but most of what is written here should work elsewhere. \ ---------------------- More Advanced Stack Manipulation ---------------------- -1 2 3 4 tuck \ duplicate the top item into the second slot: 1 2 4 3 4 ok +1 2 3 4 tuck \ duplicate the top item below the second slot: 1 2 4 3 4 ok 1 2 3 4 over \ duplicate the second item to the top: 1 2 3 4 3 ok 1 2 3 4 2 roll \ *move* the item at that position to the top: 1 3 4 2 ok 1 2 3 4 2 pick \ *duplicate* the item at that position to the top: 1 2 3 4 2 ok -- cgit v1.2.3 From 53604f0358c7ae771ce39254a7fe7588f2aceac5 Mon Sep 17 00:00:00 2001 From: Marko Cubela Date: Tue, 17 Oct 2017 09:38:17 +0200 Subject: added signed commit example --- git.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 088c109f..582f8863 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -292,6 +292,10 @@ contains the changes made and a message created by the user. # commit with a message $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +# signed commit with a message (user.signingkey must have been set +# with your GPG key e.g. git config --global user.signingkey 5173AAD5) +$ git commit -S -m "signed commit message" + # automatically stage modified or deleted files, except new files, and then commit $ git commit -a -m "Modified foo.php and removed bar.php" -- cgit v1.2.3 From cccc97c01ac739968c74d7352fd3790400172b84 Mon Sep 17 00:00:00 2001 From: Enshin Andrey Date: Tue, 17 Oct 2017 18:45:02 +0900 Subject: Update ruby-ru.html.markdown --- ru-ru/ruby-ru.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index f54c89b4..e69c6d94 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -182,8 +182,9 @@ array.[] 12 #=> nil array[-1] #=> 5 array.last #=> 5 -# С заданными левой и правой границами индексов -array[2, 4] #=> [3, 4, 5] +# Задавая индекс и количество элементов +array[0,2] #=> [1, 2] +array[0,999] #=> [1, 2, 3, 4, 5] # Или с использованием диапазона значений array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 42d9ae2dd37845b4c385980f872e09ac056a93a6 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Tue, 17 Oct 2017 17:59:45 -0200 Subject: Translate awk to pt_BR --- pt-br/awk-pt.html.markdown | 376 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 pt-br/awk-pt.html.markdown diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown new file mode 100644 index 00000000..75b73abe --- /dev/null +++ b/pt-br/awk-pt.html.markdown @@ -0,0 +1,376 @@ +--- +language: awk +filename: learnawk-pt.awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br + +--- + +AWK é uma ferramenta padrão em todos os sistemas UNIX compatíveis com POSIX. É +como um Perl despojado, perfeito para tarefas de processamento de texto e +outras tarefas de script. Possui uma sintaxe C-like, mas sem ponto e vírgula, +gerenciamento manual de memória, ou tipagem estática. Destaca-se no +processamento de texto. Você pode chamá-lo a partir de um shell-script, ou você +pode usá-lo como uma linguagem de script autônomo. + +Por que usar AWK ao invés de Perl? Principalmente porque AWK faz parte do UNIX. +Você pode sempre contar com ele, enquanto o futuro do Perl é indefinido. AWK é +também mais fácil de ler que Perl. Para scripts simples de processamento de +texto, particularmente aqueles que leem arquivos linha por linha e fatiam texto +por delimitadores, AWK é provavelmente a ferramenta certa para a tarefa. + +```awk +#!/usr/bin/awk -f + +# Comentários são assim + +# Programas AWK consistem de uma coleção de padrões e ações. O mais +# importante padrão é chamado BEGIN. Ações estão dentro de blocos +# entre chaves. + +BEGIN { + + # O bloco BEGIN será executado no começo do programa. É onde você coloca + # todo código que prepara a execução, antes que você processe qualquer + # arquivo de texto. Se você não tem arquivos de texto, então pense no + # BEGIN como o ponto principal de entrada. + + # Variáveis são globais. Simplesmente atribua valores ou as use, sem + # necessidade de declarar. + + # Operadores são como em C e similares + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 # divisão inteira + e = count % 1 # módulo + f = count ^ 1 # exponenciação + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementando e decrementando por um + a++ + b-- + + # Como um operador pré-fixado, retorna o valor incrementado + ++a + --b + + # Perceba, não há pontuação, como ponto-e-vírgula, ao final das declarações + + # Declarações de controle + if (count == 0) + print "Começando com count em 0" + else + print "Como é que é?" + + # Ou você pode usar o operador ternário + print (count == 0) ? "Começando com count em 0" : "Como é que é?" + + # Blocos multilinhas devem usar chaves + while (a < 10) { + print "Concatenação de texto é feita" " com uma série" " de" + " textos separados por espaço" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Uma boa opção para um loop de uma linha" + + # Quanto a comparações, eis os padrões: + a < b # Menor que + a <= b # Menor ou igual a + a != b # Não igual + a == b # Igual + a > b # Maior que + a >= b # Maior ou igual a + + # Bem como operadores lógicos + a && b # E + a || b # OU (inclusivo) + + # Em adição, há o utilíssimo operador para expressões regulares + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Matrizes + arr[0] = "foo" + arr[1] = "bar" + # Infelizmente, não há outra forma para inicializar uma matriz. Apenas + # coloque cada valor em uma linha, como mostrado acima. + + # Você também pode ter matrizes associativas + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # E matrizes multidimensionais, com algumas limitações que não mencionarei + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # Você pode testar a pertinência de um elemento em uma matriz + if ("foo" in assoc) + print "Fooey!" + + # Você pode também usar o operador 'in' para percorrer as chaves de uma + # matriz associativa + for (key in assoc) + print assoc[key] + + # Os argumentos da linha de comando estão em uma matriz especial ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # Você pode remover elementos de uma matriz + # Isso é muito útil para prevenir que o AWK assuma que os argumentos são + # arquivo para ele processar + delete ARGV[1] + + # A quantidade de argumentos passados está na variável ARGC + print ARGC + + # O AWK tem várias funções nativas. Elas estão separadas em três categorias. + # Demonstrarei cada uma delas logo mais abaixo. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Eis como você deve definir uma função +function arithmetic_functions(a, b, c, d) { + + # Provavelmente a parte mais irritante do AWK é ele não possuir variáveis + # locais. Tudo é global. Para pequenos scripts, isso não é problema, e + # pode até mesmo ser considerado útil, mas para grandes scripts, isso pode + # ser um problema. + + # Mas há como contornar isso (um hack). Os argumentos de função são locais + # para a função e o AWK permite que você defina mais argumentos de função + # do que ele precise. Então, coloque a variável local na declaração de + # função, como eu fiz acima. Como uma convenção, adicione alguns espaços + # extras para distinguir entre parâmetros de função reais e variáveis + # locais. Neste exemplo, a, b e c são parâmetros reais, enquanto d é + # meramente uma variável local. + + # Agora, serão demonstradas as funções aritméticas + + # Muitas implementações AWK possuem algumas funções trigonométricas padrão + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arco-tangente de b / a + + # E conteúdo logarítmico + localvar = exp(a) + localvar = log(a) + + # Raiz quadrada + localvar = sqrt(a) + + # Descartando a parte não inteira de um número em ponto flutuante. + localvar = int(5.34) # localvar => 5 + + # Números aleatórios + srand() # Forneça uma semente como argumento. Por padrão, ele usa a hora atual + localvar = rand() # Número aleatório entre 0 e 1. + + # Aqui mostramos como retornar um valor + return localvar +} + +function string_functions( localvar, arr) { + + # Sendo o AWK uma linguagem para processamento de texto, ele possui + # várias funções para manipulação de texto, muitas das quais + # fortemente dependentes de expressões regulares. + + # Procurar e substituir, primeira instância (sub), ou todas (gsub) + # Ambas retornam o número de instâncias substituídas + localvar = "fooooobar" + sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" + gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + + # Localiza um texto que casa com uma expressão regular + # index() faz a mesma coisa, mas não permite uma expressão regular + match(localvar, "t") # => 4, pois 't' é o quarto carácter + + # Separa por delimitador + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Outras coisas úteis + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # Você já viu como imprimir + print "Hello world" + + # Também há o printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # O AWK não disponibiliza manipuladores de arquivo. Ele irá automaticamente + # manipular um arquivo quando você fizer algo que precise disso. O texto + # que você usou para isso pode ser usado como um manipulador de arquivo, + # para propósitos de E/S. Isso faz ele parecer com um shell script: + + print "foobar" >"/tmp/foobar.txt" + + # Agora a string "/tmp/foobar.txt" é um manipulador de arquivos. Você pode + # fechá-lo: + close("/tmp/foobar.txt") + + # Aqui está como você pode executar alguma coisa no shell + system("echo foobar") # => prints foobar + + # Lê uma linha da entrada padrão e armazena em localvar + getline localvar + + # Lê uma linha de um pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Lê uma linha de um arquivo e armazena em localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# Como dito no início, os programas AWK consistem de uma coleção de padrões +# e ações. Você já viu o padrão BEGIN, o mais importante. Outros padrões são +# usados apenas se você estiver processando linhas de arquivos ou a entrada +# padrão. + +# Quando você passa argumentos para o AWK, eles são tratados como nomes de +# arquivos para processar. Todos serão processados, em ordem. Pense nisso como +# um implícito para loop, iterando sobre as linhas nesses arquivos. Esses +# padrões e ações são como instruções de mudança dentro do loop. + +/^fo+bar$/ { + + # Esta ação será executada para cada linha que corresponda à expressão + # regular, / ^ fo + bar $ /, e será ignorada para qualquer linha que não + # corresponda. Vamos apenas imprimir a linha: + + print + + # Opa, sem argumento! Isso ocorre pois print tem um argumento padrão: $0. + # $0 é o nome da linha atual que está sendo processada. Essa variável é + # criada automaticamente para você. + + # Você provavelmente pode adivinhar que existem outras variáveis $. Toda + # linha é implicitamente dividida antes de cada ação ser chamada, como + # o shell faz. E, como o shell, cada campo pode ser acessado com um sinal + # de cifrão + + # Isso irá imprimir o segundo e quarto campos da linha + print $2, $4 + + # O AWK automaticamente define muitas outras variáveis para ajudar você + # a inspecionar processar cada linha. A mais importante delas é NF. + + # Imprime o número de campos da linha atual + print NF + + # Imprime o último campo da linha atual + print $NF +} + +# Todo padrão é na verdade um teste verdadeiro/falso. A expressão regular no +# último padrão também é um teste verdadeiro/falso, mas parte dele estava +# escondido. Se você não informar um texto para testar, AWK assumirá $0, +# a linha que está atualmente sendo processada. Assim, a versão completa +# é a seguinte: + +$0 ~ /^fo+bar$/ { + print "Equivalente ao último padrão" +} + +a > 0 { + # Isso será executado uma vez para cada linha, quando a for positivo +} + +# Você entendeu. Processar arquivos de texto, ler uma linha de cada vez, e +# fazer algo com ela, particularmente dividir com base em um delimitador, é +# tão comum no UNIX que AWK é uma linguagem de script que faz tudo por você, +# sem você precisa perguntar. Tudo o que você precisa fazer é escrever os +# padrões e ações com base no que você espera da entrada, e o que você quer +# fazer com isso. + +# Aqui está um exemplo rápido de um script simples, o tipo de coisa que o AWK +# é perfeito para fazer. Ele irá ler um nome da entrada padrão e depois +imprimirá a média de idade de todos com esse primeiro nome. Digamos que você +forneça como argumento o nome de um arquivo com esses dados: + +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Eis o script: + +BEGIN { + + # Primeiro, pergunte o nome do usuário + print "Para qual nome você quer calcular a média de idade?" + + # Pega uma linha da entrada padrão, não dos arquivos indicados na + # linha de comando + getline name <"/dev/stdin" +} + +# Agora, processa cada linha em que o primeiro nome é o nome informado +$1 == name { + + # Dentro desse bloco, nós temos acesso a algumas variáveis uteis, que + # foram pré-carregadas para nós: + # $0 é a linha corrente completa + # $3 é o terceiro campo, que é o que nos interessa aqui + # NF é a quantidade de campos, que deve ser 3 + # NR é o número de registros (linhas) lidas até agora + # FILENAME é o nome do arquivo sendo processado + # FS é o delimitador em uso, que é " " aqui + # ...etc. Há muito mais, documentadas no manual. + + # Mantenha um registro do total e da quantidade de linhas encontradas + sum += $3 + nlines++ +} + +# Outro padrão especial é chamado END. Ele será executado após o processamento +# de todos os arquivos de texto. Ao contrário de BEGIN, ele só será executado +# se você tiver dado a ele dados para processar. Ele será executado depois de +# todos os arquivos terem sido lidos e processados de acordo com as regras e +# ações que você forneceu. O objetivo disso em geral é produzir algum tipo de +# relatório final, ou fazer algo com o agregado dos dados acumulados ao longo +# do script. + +END { + if (nlines) + print "A média da idade para " name " é " sum / nlines +} + +``` +Leituras adicionais (em inglês): + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux. -- cgit v1.2.3 From 9b6d84309c8b554ab87b19e27eadbe550d5204a6 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 19 Oct 2017 22:26:32 -0700 Subject: [python3/en] Add single inheritance section --- python3.html.markdown | 128 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 111 insertions(+), 17 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 5aa61b65..e02aed43 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -669,7 +669,7 @@ class Human: # An instance method. All methods take "self" as the first argument def say(self, msg): - print ("{name}: {message}".format(name=self.name, message=msg)) + print("{name}: {message}".format(name=self.name, message=msg)) # Another instance method def sing(self): @@ -740,7 +740,101 @@ if __name__ == '__main__': #################################################### -## 6.1 Multiple Inheritance +## 6.1 Inheritance +#################################################### + +# Inheritance allows new child classes to be defined that inherit methods and +# variables from their parent class. + +# Using the Human class defined above as the base or parent class, we can +# define a child class, Superhero, which inherits the class variables like +# "species", "name", and "age", as well as methods, like "sing" and "grunt" +# from the Human class, but can also have its own unique properties. + +# To take advantage of modularization by file you could place the classes above in their own files, +# say, human.py + +# To import functions from other files use the following format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Specify the parent class(es) as parameters to the class definition +class Superhero(Human): + + # If the child class should inherit all of the parent's definitions without + # any modifications, you can just use the "pass" keyword (and nothing else) + # but in this case it is commented out to allow for a unique child class: + # pass + + # Child classes can override their parents' attributes + species = 'Superhuman' + + # Children automatically inherit their parent class's constructor including + # its arguments, but can also define additional arguments or definitions + # and override its methods such as the class constructor. + # This constructor inherits the "name" argument from the "Human" class and + # adds the "superpower" and "movie" arguments: + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # add additional class attributes: + self.fictional = True + self.movie = movie + self.superpowers = superpowers + + # The "super" function lets you access the parent class's methods + # that are overwritten by the child, in this case, the __init__ method. + # This calls the parent class constructor: + super().__init__(name) + + # overload the sing method + def sing(self): + return 'Dun, dun, DUN!' + + # add an additional class method + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') + + # Get the Method Resolution search Order used by both getattr() and super() + # This attribute is dynamic and can be updated + print(Superhero.__mro__) # => (, + # => , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhero + + # Calls overloaded method + print(sup.sing()) # => Dun, dun, DUN! + + # Calls method from Human + sup.say('Spoon') # => Tick: Spoon + + # Call method that exists only in Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Inherited class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute that only exists within Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Multiple Inheritance #################################################### # Another class definition @@ -766,20 +860,16 @@ if __name__ == '__main__': print(b.fly) # To take advantage of modularization by file you could place the classes above in their own files, -# say, human.py and bat.py +# say, superhero.py and bat.py # To import functions from other files use the following format # from "filename-without-extension" import "function-or-class" - # superhero.py -from human import Human +from superhero import Superhero from bat import Bat -# Batman inherits from both Human and Bat -class Batman(Human, Bat): - - # Batman has its own value for the species class attribute - species = 'Superhero' +# Batman inherits from both Superhero and Bat +class Batman(Superhero, Bat): def __init__(self, *args, **kwargs): # Typically to inherit attributes you have to call super: @@ -789,7 +879,8 @@ class Batman(Human, Bat): # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". - Human.__init__(self, 'anonymous', *args, **kwargs) + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck' @@ -802,8 +893,8 @@ if __name__ == '__main__': sup = Batman() # Instance type checks - if isinstance(sup, Human): - print('I am human') + if isinstance(sup, Superhero): + print('I am a superhero) if isinstance(sup, Bat): print('I am bat') if type(sup) is Batman: @@ -811,10 +902,13 @@ if __name__ == '__main__': # Get the Method Resolution search Order used by both getattr() and super(). # This attribute is dynamic and can be updated - print(Batman.__mro__) # => (, , , ) + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhero + print(sup.get_species()) # => Superhuman # Calls overloaded method print(sup.sing()) # => nan nan nan nan nan batman! @@ -827,10 +921,10 @@ if __name__ == '__main__': # Inherited class attribute sup.age = 100 - print(sup.age) + print(sup.age) # => 100 # Inherited attribute from 2nd ancestor whose default value was overridden. - print('Can I fly? ' + str(sup.fly)) + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False -- cgit v1.2.3 From 5bbb8ef6cd315e0a1d6373f878f66146ba4ef938 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 19 Oct 2017 23:07:29 -0700 Subject: [nim/en] Add multi-line comments --- nim.html.markdown | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/nim.html.markdown b/nim.html.markdown index 07674532..30dfa94f 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -12,6 +12,25 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. ```nim +# Single-line comments start with a # + +#[ + Multi-line comments begin with a #[ + ... and end with ]# + +They don't care about indentation + + #[ + and they can be nested + ]# + +]# + +discard """ +This can also work as a multiline comment. +Or for unparsable, broken code +""" + var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" @@ -35,10 +54,6 @@ when compileBadCode: # `when` is a compile time `if` discard 1 > 2 # Note: The compiler will complain if the result of an expression # is unused. `discard` bypasses this. -discard """ -This can work as a multiline comment. -Or for unparsable, broken code -""" # # Data Structures -- cgit v1.2.3 From b3cb49f69f0b4949c53339e0141011ff46612bbb Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 19 Oct 2017 23:14:24 -0700 Subject: [r/en] Fix read.csv per #2236 --- r.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index 7a94ba05..e7486e60 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -663,7 +663,8 @@ require(plyr) # "pets.csv" is a file on the internet # (but it could just as easily be a file on your own computer) -pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +require(RCurl) +pets <- read.csv(textConnection(getURL("http://learnxinyminutes.com/docs/pets.csv"))) pets head(pets, 2) # first two rows tail(pets, 1) # last row -- cgit v1.2.3 From 1e97fa343304c7b1f6ff0bbe6f79ed521b33ad92 Mon Sep 17 00:00:00 2001 From: Adam Frey Date: Fri, 20 Oct 2017 14:50:20 -0400 Subject: [edn] Fix incorrect format for EDN symbols EDN symbols do not start with a # character --- edn.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/edn.html.markdown b/edn.html.markdown index 04346eb8..9ecfb24f 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -44,13 +44,13 @@ false :cheese :olives -; Symbols are used to represent identifiers. They start with #. +; Symbols are used to represent identifiers. ; You can namespace symbols by using /. Whatever precedes / is -; the namespace of the name. -#spoon -#kitchen/spoon ; not the same as #spoon -#kitchen/fork -#github/fork ; you can't eat with this +; the namespace of the symbol. +spoon +kitchen/spoon ; not the same as spoon +kitchen/fork +github/fork ; you can't eat with this ; Integers and floats 42 -- cgit v1.2.3 From 2cc38552e9fde371a1fa930b1313cb1b87999e8d Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 21 Oct 2017 17:28:41 +0200 Subject: [rst/it-it] Italian translation for rst --- it-it/rst-it.html.markdown | 110 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 it-it/rst-it.html.markdown diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown new file mode 100644 index 00000000..8947c738 --- /dev/null +++ b/it-it/rst-it.html.markdown @@ -0,0 +1,110 @@ +--- +language: restructured text (RST) +filename: restructuredtext-it.rst +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Ale46", "https://github.com/Ale46"] +lang: it-it +--- + +RST è un formato di file formalmente creato dalla comunità Python per scrivere documentazione (e quindi fa parte di Docutils). + +I file RST sono semplici file di testo con una sintassi leggera (in confronto all'HTML). + +## Installazione + +Per usare Restructured Text, sarà necessario installare [Python](http://www.python.org) ed il pacchetto `docutils`. + +`docutils` può essere installato da riga di comando: + +```bash +$ easy_install docutils +``` + +O se il tuo sistema ha `pip`, puoi usare anche lui: + +```bash +$ pip install docutils +``` + + +## Sintassi del file + +Un semplice esempio della sintassi del file: + +``` +.. Le righe che iniziano con due punti sono comandi speciali. Ma se non è possibile trovare alcun comando, la riga viene considerata come un commento + +=============================================================================== +I titoli principali sono scritti utilizzando caratteri di uguale, sopra e sotto +=============================================================================== + +Si noti che devono esistere tanti caratteri di uguale quanti sono i caratteri del titolo. + +Anche il titolo è sottolineato con caratteri di uguale +====================================================== + +Sottotitoli con i trattini +-------------------------- + +E sotto-sottotitoli con tildi +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Puoi inserire il testo in *corsivo* o in **grassetto**, puoi "contrassegnare" il testo come codice con un doppio apice ``: `` print () ``. + +Le liste sono semplici come in Markdown: + +- primo articolo +- Secondo elemento +     - Sottoelemento + +o + +* Primo elemento +* Secondo elemento +     * Sottoelemento + +Le tabelle sono davvero facili da scrivere: + +=========== ======== +Stato Capitale +=========== ======== +Francia Parigi +Giappone Tokio +=========== ======== + +Le tabelle più complesse possono essere fatte facilmente (colonne e/o righe unite) ma ti suggerisco di leggere il documento completo per questo :) + +Esistono diversi modi per creare collegamenti: + +- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo modo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). +- Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento) +- Facendo un collegamento simile a Markdown: `Github `_ . + +.. _Github https://github.com/ + +``` + + +## Come usarlo + +RST viene fornito con docutils che dispone di `rst2html`, per esempio: + +```bash +$ rst2html miofile.rst output.html +``` + +*Nota : In alcuni sistemi il comando potrebbe essere rst2html.py* + +Ma ci sono applicazioni più complesse che utilizzano il formato RST: + +- [Pelican](http://blog.getpelican.com/), un generatore di siti statici +- [Sphinx](http://sphinx-doc.org/), un generatore di documentazione +- e molti altri + + +## Letture + +- [Riferimento ufficiale rapido](http://docutils.sourceforge.net/docs/user/rst/quickref.html) -- cgit v1.2.3 From d86597d4991b907f3d1940daf9ce97ca0ecf68dd Mon Sep 17 00:00:00 2001 From: Jonathan D Johnston Date: Sat, 21 Oct 2017 20:33:14 -0400 Subject: Improve the "Tagged Elements" section of EDN doc - Change Clojure code to eliminate errors and to match commented output > Change edn/read-string to clojure.edn/read-string (no _require_ in text) > Change map->menu-item to map->MenuItem to match defrecord and output - Modify the text to make it easier to understand the given example --- edn.html.markdown | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/edn.html.markdown b/edn.html.markdown index 9ecfb24f..f47853f0 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -84,22 +84,26 @@ github/fork ; you can't eat with this #MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} -; Let me explain this with a clojure example. Suppose I want to transform that +; Let me explain this with a Clojure example. Suppose I want to transform that ; piece of EDN into a MenuItem record. (defrecord MenuItem [name rating]) -; To transform EDN to clojure values, I will need to use the built in EDN -; reader, edn/read-string +; defrecord defined, among other things, map->MenuItem which will take a map +; of field names (as keywords) to values and generate a user.MenuItem record -(edn/read-string "{:eggs 2 :butter 1 :flour 5}") +; To transform EDN to Clojure values, I will need to use the built-in EDN +; reader, clojure.edn/read-string + +(clojure.edn/read-string "{:eggs 2 :butter 1 :flour 5}") ; -> {:eggs 2 :butter 1 :flour 5} -; To transform tagged elements, define the reader function and pass a map -; that maps tags to reader functions to edn/read-string like so +; To transform tagged elements, pass to clojure.edn/read-string an option map +; with a :readers map that maps tag symbols to data-reader functions, like so -(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} - "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") +(clojure.edn/read-string + {:readers {'MyYelpClone/MenuItem map->MenuItem}} + "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") ; -> #user.MenuItem{:name "eggs-benedict", :rating 10} ``` -- cgit v1.2.3 From 2eb1aa6abdc07cf25d6706a0ed5f9963fdd60605 Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Sun, 22 Oct 2017 13:52:48 +0200 Subject: Update html.html.markdown --- html.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html.html.markdown b/html.html.markdown index 3c855b5c..6516e5dd 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -111,7 +111,7 @@ This article is concerned principally with HTML syntax and some useful tips. ## Usage -HTML is written in files ending with `.html`. +HTML is written in files ending with `.html` or `.htm`. The mime type is `text/html`. ## To Learn More -- cgit v1.2.3 From 8368738bf31c713619160e0cef9b52a755139e0f Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Sun, 22 Oct 2017 17:23:46 +0200 Subject: [pyqt/de] Translate pyqt to german --- de-de/pyqt-de.html.markdown | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 de-de/pyqt-de.html.markdown diff --git a/de-de/pyqt-de.html.markdown b/de-de/pyqt-de.html.markdown new file mode 100644 index 00000000..93ee20d4 --- /dev/null +++ b/de-de/pyqt-de.html.markdown @@ -0,0 +1,89 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt-de.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +**Qt** ist eine weit bekanntes Framework mit den man plattformunabhängige Programme schreiben kann, +die auf verschiedenen Sotfware und Hardware Plattformen laufen mit kleinen oder keinen Änderungen im Code. +Dabei besitzen sie trozdem die Power und Geschwindigkeit von nativen Anwendungen. +**Qt** wurde ursprünglich in *C++** geschrieben. + +Das ist eine Adaption von dem C++ Intro für QT von [Aleksey Kholovchuk](https://github.com/vortexxx192), +manche der Codebeispiele sollte in der selben Funktionalität resultieren. +Diese Version wurde in pyqt erstellt. + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Erschafft ein Anwendungsobjekt. + app = QtGui.QApplication(sys.argv) + # Erschafft ein Widget, auf dem unser Label platziert wird. + w = QtGui.QWidget() + # Fügt ein Label zu dem Widget hinzu. + b = QtGui.QLabel(w) + # Setzt einen Text für das Label. + b.setText("Hello World!") + # Setzt die Größe und die Platzierungsinfomationen. + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Setzt unserem Fenster einen schönen Titel. + w.setWindowTitle("PyQt") + # Lässt alles anzeigen. + w.show() + # Führe alles aus, nachdem wir alles aufgebaut haben. + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können, +müssen wir anfangen zusätzliche Elemente zu bauen. +Hier zeigen wir wie man eine Dialog Popup Box einführt. +Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen. + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Erschafft einen Knopf und fügt das Widget w hinzu + b = QPushButton(w) + b.setText("drücke mich") + b.move(50, 50) + # Wenn b gedrückt wird, wird diese Funktion aufgerufen. + # Bemerke das Fehlen von () bei dem Funktionsaufruf. + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen. +# Der Knopf wartet bis er geklickt wird und beendet das Programm +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Diese Modalität sagt dem Popup, dass es den Parent blocken soll, solange es aktiv ist. + d.setWindowModality(Qt.ApplicationModal) + # Beim klicken möchte ich, dass der gesamte Prozess beendet wird. + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` -- cgit v1.2.3 From aa94772b921ececf488810167e4949b10a1705ce Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Sun, 22 Oct 2017 17:43:50 +0200 Subject: [qt/de] Translate qt to german --- de-de/qt-de.html.markdown | 175 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 de-de/qt-de.html.markdown diff --git a/de-de/qt-de.html.markdown b/de-de/qt-de.html.markdown new file mode 100644 index 00000000..480030fe --- /dev/null +++ b/de-de/qt-de.html.markdown @@ -0,0 +1,175 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt-de.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +**Qt** ist ein weithin bekanntes Framework zum Entwickeln von cross-platform Software, +die auf verschiedenen Hard- und Softwareplatformen mit wenig oder keinen Veränderungen im Code läuft. +Dabei besitzt man die Power und Geschiwindigkeit von nativen Anwendungen. +Obwohl **Qt** ursprünglich in *C++* geschrieben wurde, +gibt es verschiedene Ports für andere Sprachen: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** eignet sich hervorragend zum Erstellen von Anwendungen mit grafischer Benutzeroberfläche (GUI). +Dieses Tutorial zeigt, wie man das in *C++* macht. + +```c++ +/* + * Lass uns klassisch starten + */ + +// Alle Header vom Qt Framework starten mit dem Großbuchstaben 'Q'. +#include +#include + +int main(int argc, char *argv[]) { + // Erstellt ein Objekt um applikationsweit die Resourcen zu managen. + QApplication app(argc, argv); + + // Erstellt ein Line edit Widget und zeigt es auf dem Bildschirm + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // Startet die Event Loop der Anwendung. + return app.exec(); +} +``` + +Die GUI bezogene Teile von **Qt** bestehen aus *Widgets* und den *Verbindungen* +dazwischen. + +[Lies mehr über Widgets](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Lass uns Label und einen Button machen. + * Ein Label soll auftauchen, wenn der Button gedrückt wird. + * + * Der Qt Code spricht für sich selbst. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // Füge ein vertikales Layout hinzu + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Danke für das Knopf drücken"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Drück mich"); + layout.addWidget(&button); + + // Zeigt verstecktes Label, wenn der Button gedrückt wird. + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Beachte den *QObject::connect* Teil. Diese Methode wird verwendet, +um *Signale* eines Objekts mit den *Slots* eines Objektes zu verbinden. + +**Signale** werden ausgegeben, wenn bestimmte Dinge mit Objekten passieren. +Beispielsweise wird das *pressed* Signal ausgegeben, +wenn der Benutzer auf das QPushButton Objekt drückt. + +**Slots** sind Aktionen, die als Reaktion auf empfangene Signale ausgeführt werden können. + +[Lies mehr über Slots und Signale](http://doc.qt.io/qt-5/signalsandslots.html) + + +Als Nächstes lernen wir, dass wir nicht nur Standard Widgets verwenden können, +sondern auch ihr Verhalten mithilfe von Vererbung verändern können. +Lass uns einen Button erschaffen, der zählt, wie häufig er gedrückt wird. +Dafür definieren wir unsere eigene Klasse *CounterLabel*. +Diese muss wegen der speziellen Qt Architektur in einer seperaten Datei deklariert werden. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Qt definiertes Makro, welches in jedem modifizierten Widget vorhanden sein muss. + +public: + CounterLabel() : counter(0) { + setText("Zähler wurde noch nicht erhöht."); // Methode von QLabel + } + +public slots: + // Aktion, die ausgeführt wird, wenn der Button gedrückt wird. + void increaseCounter() { + setText(QString("Zähler Wert: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // Zähllabel +``` + +```c++ +// main.cpp +// Fast das Gleiche, wie das vorherige Beispiel + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Drück mich nochmal."); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +Das wars! Natürlich ist das Qt Framework erheblich größer, als der der Teil der in diesem Tutorial behandelt wurde. +Das heißt, es gibt viel zu lesen und zu üben. + +## Further reading + +- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html) +- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html) + +Viel Erfolg und viel Spaß! -- cgit v1.2.3 From 8dedecc999b17eee78b6f405bcc50a8d1316ec32 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Sun, 22 Oct 2017 17:54:53 +0200 Subject: [edn/de] Translate edn to german --- de-de/edn-de.html.markdown | 112 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 de-de/edn-de.html.markdown diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown new file mode 100644 index 00000000..4f452d7e --- /dev/null +++ b/de-de/edn-de.html.markdown @@ -0,0 +1,112 @@ +--- +language: edn +filename: learnedn-de.edn +contributors: + - ["Jason Yeo", "https://github.com/jsyeo"] + - ["Jonathan D Johnston", "https://github.com/jdjohnston"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +Extensible Data Notation (EDN) ist ein Format für serialisierte Daten. + +EDN ist ein Subset der von Clojure verwendeten Syntax. Das Lesen von Daten, die durch EDN definiert werden, ist +sicherer als das, was durch die vollständige Clojure-Syntax definiert wird, insbesondere von nicht +vertrauenswürdigen Quellen. EDN ist beschränkt auf Daten, kein Code. Es ist ähnlich in seinen Zielen zu JSON. +Obwohl es mehr in Clojure verwendet wird, gibt es verschiedene Implementationen von EDN in vielen +verschiedenen anderen Sprachen. + +Der Hauptvorteil von EDN im Gegensatz zu JSON und YAML ist, dass es erweiterbar ist. +Wir werden später sehen wie es erweitert werden kann. + +```clojure +; Kommentare starten mit einem Semikolon. +; Alles nach dem Semikolon wird ignoriert. + +;;;;;;;;;;;;;;;;;;; +;;; Basistypen ;;; +;;;;;;;;;;;;;;;;;;; + +nil ; auch bekannt in anderen Sprachen als null + +; Booleans +true +false + +; Strings werden in Gänsefüßchen eingeschlossen. +"hungarian breakfast" +"farmer's cheesy omelette" + +; Charaktere werden einem Backslash vorangestellt +\g \r \a \c \e + +; Schlüsselwörter beginnen mit einenm Doppelpunkt. Sie verhalten sich wie Enums. +; Ähnlich, wie Symbole in Ruby. +:eggs +:cheese +:olives + +; Symbole werden verwendet um Identifier zu repräsentieren. Sie beginnen mit einem #. +; Du kannst einen Namespace für Symbole nutzen, wenn du / verwendest. Egal was / vorangestellt wird +; ist der Namespace dieses Namens. +#spoon +#kitchen/spoon ; nicht das selbe, wie #spoon +#kitchen/fork +#github/fork ; damit kannst du nicht essen + +; Integers und Floats +42 +3.14159 + +; Listen sind Sequenzen von Werten +(:bun :beef-patty 9 "yum!") + +; Vektoren erlauben zufälligen Zugriff +[:gelato 1 2 -2] + +; Maps sind assoziative Datenstrukturen, die einen Schlüssel mit einem Wert verbinden. +{:eggs 2 + :lemon-juice 3.5 + :butter 1} + +; Du bist nicht beschränkt ausschließlich Schlüsselwörter als Schlüssel zu verwenden. +{[1 2 3 4] "tell the people what she wore", + [5 6 7 8] "the more you see the more you hate"} + +; Du kannst Kommas für eine bessere Lesbarkeit verwenden. Sie werden wie Leerraum behandelt. +; Sets sind Sammlungen, die eindeutige Elemente enthalten. +#{:a :b 88 "huat"} + +;;;;;;;;;;;;;;;;;;;;;;;;; +;;; makierte Elemente ;;; +;;;;;;;;;;;;;;;;;;;;;;;;; + +; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden. + +#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} + +; Lass mich das mit einem Clojure Beispiel erklären. +; Angenommen ich möchte dieses Stück EDM in einen MenuItem record umwandeln. +(defrecord MenuItem [name rating]) + +; Um EDN in clojure Werte umzuwandeln, muss ich den eingebauten EDN Leser +;edn/read-string verwenden + +(edn/read-string "{:eggs 2 :butter 1 :flour 5}") +; -> {:eggs 2 :butter 1 :flour 5} + +; Definiere die Leserfunktion, um markierte Elemente zu transformieren +; und übergebe eine Map, die Tags den Lesefunktionen als edn / read-string zuweisen + +(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} + "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") +; -> #user.MenuItem{:name "eggs-benedict", :rating 10} + +``` + +# Referenzen + +- [EDN spec](https://github.com/edn-format/edn) +- [Implementationen](https://github.com/edn-format/edn/wiki/Implementations) +- [makierte Elemente](http://www.compoundtheory.com/clojure-edn-walkthrough/) -- cgit v1.2.3 From 8d311de256f3813d6a83f8bb07a3495cd643d7cc Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Sun, 22 Oct 2017 18:01:59 +0200 Subject: [nix/de] Translate nix to german --- de-de/nix-de.html.markdown | 358 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 de-de/nix-de.html.markdown diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown new file mode 100644 index 00000000..8c78ffbc --- /dev/null +++ b/de-de/nix-de.html.markdown @@ -0,0 +1,358 @@ +--- +language: nix +filename: learnnix-de.nix +contributors: + - ["Chris Martin", "http://chris-martin.org/"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +Nix ist eine simple funktionale Programmiersprache, die für den +[Nix package manager](https://nixos.org/nix/) und +[NixOS](https://nixos.org/) entwickelt wurde. + +Du kannst Nix Ausdrücke evaluieren mithilfe von +[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) +oder [`nix-repl`](https://github.com/edolstra/nix-repl). + +``` +with builtins; [ + + # Kommentare + #========================================= + + # Inline Kommentare sehen so aus. + + /* Multizeilen Kommentare + sehen so aus. */ + + + # Booleans + #========================================= + + (true && false) # Und + #=> false + + (true || false) # Oder + #=> true + + (if 3 < 4 then "a" else "b") # Bedingungen + #=> "a" + + + # Integers + #========================================= + + # Integers sind die einzigen numerischen Typen. + + 1 0 42 (-3) # Einige integers + + (4 + 6 + 12 - 2) # Addition + #=> 20 + + (7 / 2) # Division + #=> 3 + + + # Strings + #========================================= + + "String Literale sind in Gänsefüßchen." + + " + String Literale können mehrere + Zeilen umspannen. + " + + '' + Dies wird als Literal mit eingerückten String bezeichnet. + Es entfernt intelligent führende Leerzeichen. + '' + + '' + a + b + '' + #=> "a\n b" + + ("ab" + "cd") # String Konkatenation + #=> "abcd" + + # Mit Antiquotation kannst du Werte in Strings einbetten. + ("Dein Homeverzeichnis ist ${getEnv "HOME"}") + #=> "Dein Homeverzeichnis ist /home/alice" + + + # Paths + #========================================= + + # Nix besitzt einen primitven Datentyp für Pfade + /tmp/tutorials/learn.nix + + # Ein relativer Pfad wird beim Parsing zu einem absoluten Pfad aufgelöst, + # relativ zu der Datei in der es auftritt. + tutorials/learn.nix + #=> /the-base-path/tutorials/learn.nix + + # Ein Pfad muss mindestens einen Schrägstrich enthalten. Ein Pfad für eine + # Datei im selben Verzeichnis benötigt ein ./ Präfix. + ./learn.nix + #=> /the-base-path/learn.nix + + # Der / Operator muss von Leerraum umgeben sein wenn du dividieren möchtest. + 7/2 # Das ist ein Pfadliteral + (7 / 2) # Das ist ein Integerliteral + + + # Importe + #========================================= + + # Eine nix Datei besitzt einen einzelnen top-level Ausdruck mit keinen freien Variablen. + # Ein Import-Ausdruck wird zum Wert der Datei, die importiert wird, ausgewertet. + (import /tmp/foo.nix) + + # Importe können ebenso mit Strings spezifiziert werden. + (import "/tmp/foo.nix") + + # Import Pfade müssen absolut sein. Pfadliterale + # sind automatisch aufgelöst, das ist ein Ordnung. + (import ./foo.nix) + + # Jedoch passiert dies nicht mit Strings. + (import "./foo.nix") + #=> error: string ‘foo.nix’ doesn't represent an absolute path + + + # Let + #========================================= + + # `let` Blöcke erlauben es uns Werte zu Variablen zu binden. + (let x = "a"; in + x + x + x) + #=> "aaa" + + # Bindungen können auf sich gegenseitig verweisen. Die Reihenfolge spielt + # keine Rolle. + (let y = x + "b"; + x = "a"; in + y + "c") + #=> "abc" + + # Innere Bindungen überschatten Äußere. + (let a = 1; in + let a = 2; in + a) + #=> 2 + + + # Funktionen + #========================================= + + (n: n + 1) # Funktion, die 1 addiert + + ((n: n + 1) 5) # Dieselbe Funktion angewendet auf 5. + #=> 6 + + # Es gibt keine spezielle Syntax für benannte Funktionen, aber sie + # können mit `let` Blöcken, wie jeder andere Wert auch, gebunden werden. + (let succ = (n: n + 1); in succ 5) + #=> 6 + + # Eine Funktion hat genau ein Argument. + # Mehrere Argumente können erreicht werden mithilfe von Currying. + ((x: y: x + "-" + y) "a" "b") + #=> "a-b" + + # Benannte Funktionsargumente gibt es auch. Diese werden wir einführen, nachdem wir uns Sets + # angeschaut haben. + + # Listen + #========================================= + + # Listen werden durck eckige Klammern gekennzeichnet. + + (length [1 2 3 "x"]) + #=> 4 + + ([1 2 3] ++ [4 5]) + #=> [1 2 3 4 5] + + (concatLists [[1 2] [3 4] [5]]) + #=> [1 2 3 4 5] + + (head [1 2 3]) + #=> 1 + (tail [1 2 3]) + #=> [2 3] + + (elemAt ["a" "b" "c" "d"] 2) + #=> "c" + + (elem 2 [1 2 3]) + #=> true + (elem 5 [1 2 3]) + #=> false + + (filter (n: n < 3) [1 2 3 4]) + #=> [ 1 2 ] + + + # Sets + #========================================= + + # Ein "Set" ist eine ungeordnete Zuordnung mit Stringschlüsseln. + { foo = [1 2]; bar = "x"; } + + # Der . Operator nimmt einen Wert aus dem Set. + { a = 1; b = 2; }.a + #=> 1 + + # Der ? Operator testet, ob der Schlüssel in dem Set vorhanden ist. + ({ a = 1; b = 2; } ? a) + #=> true + ({ a = 1; b = 2; } ? c) + #=> false + + # Der // Operator mergt zwei Sets. + ({ a = 1; } // { b = 2; }) + #=> { a = 1; b = 2; } + + # Werte auf der rechten Seite überschrieben die Werte auf der linken Seite. + ({ a = 1; b = 2; } // { a = 3; c = 4; }) + #=> { a = 3; b = 2; c = 4; } + + # Das Schlüsselwort rec bezeichenet ein "rekursives Set", in der sich Attribute + # aufeinander beziehen können. + (let a = 1; in { a = 2; b = a; }.b) + #=> 1 + (let a = 1; in rec { a = 2; b = a; }.b) + #=> 2 + + # Verschachetelte Sets können stückweise definiert werden. + { + a.b = 1; + a.c.d = 2; + a.c.e = 3; + }.a.c + #=> { d = 2; e = 3; } + + # Die Nachkommen eines Attributs können in diesem Feld nicht zugeordnet werden, wenn + # das Attribut selbst nicht zugeweisen wurde. + { + a = { b = 1; }; + a.c = 2; + } + #=> error: attribute ‘a’ already defined + + + # With + #========================================= + + # Der Körper eines Sets Blocks wird mit der Zurodnung eines Satzes an die Variablen gebunden. + (with { a = 1; b = 2; }; + a + b) + # => 3 + + # Innere Bindungen überschatten äußere Bindungen. + (with { a = 1; b = 2; }; + (with { a = 5; }; + a + b)) + #=> 7 + + # Die erste Linie diese Tutorials startet mit "with builtins;", + # weil builtins ein Set mit allen eingebauten + # Funktionen (length, head, tail, filter, etc.) umfasst. + # Das erspart uns beispielseweise "builtins.length" zu schreiben, + # anstatt nur "length". + + + # Set patterns + #========================================= + + # Sets sind nützlich, wenn du mehrere Werte einer Funktion + # übergeben musst. + (args: args.x + "-" + args.y) { x = "a"; y = "b"; } + #=> "a-b" + + # Dies kann mit Hilfe von Set patterns deutlicher geschrieben werden. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; } + #=> "a-b" + + # Standardmäßig schlägt das Muster bei Sets mit zusätzlichen Schlüsseln fehl. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> error: anonymous function called with unexpected argument ‘z’ + + # Durch Hinzufügen von ", ..." können zusätzliche Schlüssel ignoriert werden. + ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> "a-b" + + + # Errors + #========================================= + + # `throw` bewirkt, dass die Auswertung mit einer Fehlermeldung abgebrochen wird. + (2 + (throw "foo")) + #=> error: foo + + # `tryEval` fängt geworfene Fehler. + (tryEval 42) + #=> { success = true; value = 42; } + (tryEval (2 + (throw "foo"))) + #=> { success = false; value = false; } + + # `abort` ist ähnlich wie throw, aber es ist fatal. Es kann nicht gefangen werden. + (tryEval (abort "foo")) + #=> error: evaluation aborted with the following error message: ‘foo’ + + # `assert` evaluiert zu dem gegebenen Wert, wenn die Bedingung wahr ist, sonst + # löst es eine abfangbare Exception aus. + (assert 1 < 2; 42) + #=> 42 + (assert 1 > 2; 42) + #=> error: assertion failed at (string):1:1 + (tryEval (assert 1 > 2; 42)) + #=> { success = false; value = false; } + + + # Impurity + #========================================= + + # Da die Wiederholbarkeit von Builds für den Nix Packetmangager entscheidend ist, + # werden in der Nix Sprache reine funktionale Elemente betont. Es gibt aber ein paar + # unreine Elemente. + # Du kannst auf Umgebungsvarialben verweisen. + (getEnv "HOME") + #=> "/home/alice" + + # Die trace Funktion wird zum Debugging verwendet. Sie gibt das erste Argument zu stderr aus + # und evaluiert das zweite Argument. + (trace 1 2) + #=> trace: 1 + #=> 2 + + # Du kannst Dateien in den Nix store schreiben. Obwohl unrein, kannst du dir relativ sicher sein, + # dass es sicher ist, da der Dateiname aus dem Hash des Inhalts abgeleitet wird. + # Du kannst Dateien von überall lesen. In diesem Beispiel schreiben wir Dateien in den Store + # und lesen wieder davon. + (let filename = toFile "foo.txt" "hello!"; in + [filename (builtins.readFile filename)]) + #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] + + # Außerdem können wir Dateien in den Nix Store downloaden. + (fetchurl "https://example.com/package-1.2.3.tgz") + #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" + +] +``` + +### Weitere Resourcen + +* [Nix Manual - Nix expression language] + (https://nixos.org/nix/manual/#ch-expression-language) + +* [James Fisher - Nix by example - Part 1: The Nix expression language] + (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) + +* [Susan Potter - Nix Cookbook - Nix By Example] + (http://funops.co/nix-cookbook/nix-by-example/) -- cgit v1.2.3 From a65623736d76ed76bd24a4a24a02a6707372a199 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Sun, 22 Oct 2017 23:41:56 +0700 Subject: Added Vietnamese translation for TypeScript language --- vi-vn/typescript-vi.html.markdown | 192 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 vi-vn/typescript-vi.html.markdown diff --git a/vi-vn/typescript-vi.html.markdown b/vi-vn/typescript-vi.html.markdown new file mode 100644 index 00000000..16b77ffc --- /dev/null +++ b/vi-vn/typescript-vi.html.markdown @@ -0,0 +1,192 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +filename: learntypescript-vi.ts +lang: vi-vn +--- + +TypeScript là ngôn ngữ được viết nhằm tinh giản quá trình phát triển ứng dụng quy mô lớn được viết bằng JavaScript. +TypeScript bổ sung thêm các khái niệm phổ biến như Class, Module, Interface, Generic và Static typing (tùy chọn) vào JavaScript. +Ngôn ngữ này là tập lớn hơn của JavaScript: tất cả code JavaScript đều là code TypeScript đúng nên nó có thể được thêm vào các dự án một cách nhanh chóng. Trình biên dịch TypeScript sẽ sinh ra JavaScript. + +Bài viết này sẽ chỉ tập trung tới các cú pháp bổ sung mà TypeScript thêm vào thay vì nói đến cả các cú pháp [JavaScript](javascript-vi.html.markdown). + +Để thử dùng TypeScript với trình biên dịch, đi đến [Sân chơi TypeScript](http://www.typescriptlang.org/play) nơi mà bạn có thể nhập code, sử dụng chức năng hỗ trợ tự hoàn thành code - autocompletion và trực tiếp quan sát mã JavaScript được sinh ra. + +```ts +// Đây là 3 khai báo kiểu biến cơ bản trong TypeScript +// (JavaScript chỉ có kiểu của giá trị, không có kiểu của biến) +let isDone: boolean = false; +let lines: number = 42; +let name: string = "Anders"; + +// Bạn có thể bỏ khai báo kiểu của biến nếu như nó đã được suy ra từ kiểu giá trị cơ bản +let isDone = false; +let lines = 42; +let name = "Anders"; + +// Có kiểu biến "any" tương thích với mọi kiểu của biến, +// được dùng khi ta không chắc chắn về kiểu của biến khi được khai báo +let notSure: any = 4; +notSure = "có thể là một biến kiểu string"; +notSure = false; // cũng có thể là biến kiểu boolean + +// Dùng từ khóa const cho khái báo biến không thay đổi (constant variable) +const numLivesForCat = 9; +numLivesForCat = 1; // Có lỗi! + +// Khi khai báo tập hợp ta có thể dùng mảng có kiểu được khai báo trước - typed array +let list: number[] = [1, 2, 3]; +// Ta cũng có thể sử dụng mảng kiểu chung - generic array +let list: Array = [1, 2, 3]; + +// Để dùng enumeration - danh sách của một tập hợp: +enum Color { Red, Green, Blue }; +let c: Color = Color.Green; + +// Nếu function không trả về kết quả, sử dụng "void" cho kết quả trả về +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Function trong TypeScript là first-class citizen (tạm dịch: phần tử hạng nhất), hỗ trợ thao tác tới các thực thể khác +// (vd: truyền vào như tham số, được trả về từ function, chỉnh sửa, gán vào một biến) +// TypeScript hỗ trợ sử dụng function với cú pháp lambda (mũi tên) và suy luận kiểu trả về + +// Các cú pháp dưới đây tương đương với nhau, +// trình biên dịch sẽ tự nhận biết và sinh ra mã JavaScript giống nhau +let f1 = function (i: number): number { return i * i; } +// Kiểu trả về nếu không khai báo được tự suy diễn +let f2 = function (i: number) { return i * i; } +// Cú pháp mũi tên (arrow syntax) +let f3 = (i: number): number => { return i * i; } +// Cú pháp mũi tên với kiểu trả về được suy diễn +let f4 = (i: number) => { return i * i; } +// Cú pháp mũi tên với kiểu trả về được suy diễn +// khi không sử dụng dấu ngoặc nhọn {} thì không cần sử dụng return +let f5 = (i: number) => i * i; + +// Interface mang tính cấu trúc, mọi thứ có các đặc điểm (property) đều tương thích +interface IPerson { + name: string; + // Đặc điểm có thể tùy chọn bằng sử dụng dấu "?" + age?: number; + // Có thể sử dụng function + move(): void; +} + +// Object sử dụng interface IPerson nói trên +// có thể được coi là 1 thực thể Person vì nó có đặc điểm name và chức năng move +let p: Person = { name: "Bobby", move: () => { } }; +// Object sử dụng property tùy chọn +let validPerson: Person = { name: "Bobby", age: 42, move: () => { } }; +// Khai báo dưới đây gây lỗi vì giá trị đặc điểm age không mang kiểu number +let invalidPerson: Person = { name: "Bobby", age: true }; + +// Interface cũng có thể mô tả đặc tả của function +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Chỉ có kiểu của tham số là quan trọng còn tên không quan trọng +let mySearch: SearchFunc; +mySearch = function (src: string, sub: string) { + return src.search(sub) != -1; +} + +// Class - các khai báo mặc định là public +class Point { + // Property + x: number; + + // Constructor - sử dụng tham số với từ khóa public/private + // sẽ tạo ra property tương ứng (ví dụ với property y) + // Có thể khai báo giá trị mặc định + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Function + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Biến Static + static origin = new Point(0, 0); +} + +let p1 = new Point(10, 20); +let p2 = new Point(25); // y sử dụng giá trị mặc định là 0 + +// Thừa kế - Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Bắt buộc phải gọi constructor của class cha + } + + // Overwrite/Polymorphism - Ghi đè/Đa hình + dist() { + let d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// module, "." có thể được dùng như những module con +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +let s1 = new Geometry.Square(5); + +// Bí danh (alias) có thể được sử dụng để tham vấn module khác +import G = Geometry; + +let s2 = new G.Square(10); + +// Generic +// Class +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interface +interface Pair { + item1: T; + item2: T; +} + +// Function +let pairToTuple = function (p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +let tuple = pairToTuple({ item1: "hello", item2: "world" }); + +// Các thư viện viết bằng JavaScript thường đi kèm file định nghĩa kiểu để có thể sử dụng cho TypeScript +// Thêm vào tham vấn tới file định nghĩa: +/// + +// Template Strings - Chuỗi dạng mẫu (string sử dụng dấu `) +// String Interpolation - Nội suy chuỗi with với template string +let name = 'Tyrone'; +let greeting = `Chào ${name}, bạn khỏe không?` +// Chuỗi nhiều dòng với template string +let multiline = `Đây là ví dụ +cho chuỗi nhiều dòng`; + +``` + +## Tìm hiểu thêm + +* [Website TypeScript chính thức](http://www.typescriptlang.org/) +* [Đặc tả ngôn ngữ TypeScript] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) +* [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) +* [Mã nguồn trên GitHub] (https://github.com/Microsoft/TypeScript) +* [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 25c57dc0dbf5fe4c793a5130022c50f79bc7bbac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Sun, 22 Oct 2017 21:34:32 +0300 Subject: Update typescript-vi.html.markdown Moved @thanhpd to the `translators` section. --- vi-vn/typescript-vi.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/vi-vn/typescript-vi.html.markdown b/vi-vn/typescript-vi.html.markdown index 16b77ffc..ba459c11 100644 --- a/vi-vn/typescript-vi.html.markdown +++ b/vi-vn/typescript-vi.html.markdown @@ -2,6 +2,7 @@ language: TypeScript contributors: - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: - ["Thanh Duy Phan", "https://github.com/thanhpd"] filename: learntypescript-vi.ts lang: vi-vn -- cgit v1.2.3 From a01402b7b1486475abee1f77880dc9b7334ec44d Mon Sep 17 00:00:00 2001 From: Harry Sun Date: Sun, 22 Oct 2017 21:44:54 -0500 Subject: Update go-cn.html.markdown --- zh-cn/go-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 75498367..37b4b137 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -142,6 +142,7 @@ func learnTypes() { func learnNamedReturns(x, y int) (z int) { z = x * y return // z is implicit here, because we named it earlier. +} // Go全面支持垃圾回收。Go有指针,但是不支持指针运算。 // 你会因为空指针而犯错,但是不会因为增加指针而犯错。 -- cgit v1.2.3 From b01b53a46dbb4d2a35c44ad2caff521f442b2741 Mon Sep 17 00:00:00 2001 From: ksami Date: Mon, 23 Oct 2017 17:36:18 +0800 Subject: clarify use case for verbatim strings added example for using @ symbol with strings --- csharp.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 963f38f4..bb8bf6e5 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -132,6 +132,12 @@ namespace Learning.CSharp DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + // Verbatim String + // You can use the @ symbol before a string literal to escape all characters in the string + string path = "C:\\Users\\User\\Desktop"; + string verbatimPath = "C:\Users\User\Desktop"; + Console.WriteLine(path == verbatimPath); // => true + // You can split a string over two lines with the @ symbol. To escape " use "" string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; -- cgit v1.2.3 From 3e072363d9b454973f116e39d4690ed73662f452 Mon Sep 17 00:00:00 2001 From: ksami Date: Mon, 23 Oct 2017 17:41:57 +0800 Subject: missed out the @ symbol --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index bb8bf6e5..77737182 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -135,7 +135,7 @@ namespace Learning.CSharp // Verbatim String // You can use the @ symbol before a string literal to escape all characters in the string string path = "C:\\Users\\User\\Desktop"; - string verbatimPath = "C:\Users\User\Desktop"; + string verbatimPath = @"C:\Users\User\Desktop"; Console.WriteLine(path == verbatimPath); // => true // You can split a string over two lines with the @ symbol. To escape " use "" -- cgit v1.2.3 From 467f143b9cc3c267d87b295e1ca84ef9308873a2 Mon Sep 17 00:00:00 2001 From: ksami Date: Mon, 23 Oct 2017 17:50:07 +0800 Subject: add example for verbatim interpolated string --- csharp.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 77737182..c98a7da9 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -955,6 +955,7 @@ on a new line! ""Wow!"", the masses cried"; // String interpolation by prefixing the string with $ // and wrapping the expression you want to interpolate with { braces } + // You can also combine both interpolated and verbatim strings with $@ public class Rectangle { public int Length { get; set; } @@ -967,6 +968,9 @@ on a new line! ""Wow!"", the masses cried"; { Rectangle rect = new Rectangle { Length = 5, Width = 3 }; Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + + string username = "User"; + Console.WriteLine($@"C:\Users\{username}\Desktop"); } } -- cgit v1.2.3 From d7326e1b260dc97a20c7303ce90bd354caab0e14 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 23 Oct 2017 13:07:42 -0200 Subject: small typo --- pt-br/amd-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/amd-pt.html.markdown b/pt-br/amd-pt.html.markdown index 38c1f70f..40c7cd09 100644 --- a/pt-br/amd-pt.html.markdown +++ b/pt-br/amd-pt.html.markdown @@ -141,7 +141,7 @@ require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coo coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); }); ``` -Apps baseados em `require.js` geralmente terão u´m único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: +Apps baseados em `require.js` geralmente terão um único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: ```html -- cgit v1.2.3 From 62892f4ca1a838eb556b3cbd4122d89a8b9f87b7 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 23 Oct 2017 13:14:03 -0200 Subject: [asciidoc/pt-br] Small typo --- pt-br/asciidoc-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/asciidoc-pt.html.markdown b/pt-br/asciidoc-pt.html.markdown index 1dee31db..b12c0693 100644 --- a/pt-br/asciidoc-pt.html.markdown +++ b/pt-br/asciidoc-pt.html.markdown @@ -99,7 +99,7 @@ Para criar uma lista com marcadores use asteriscos. * baz ``` -Para criar uma lista númerada use pontos. +Para criar uma lista numerada use pontos. ``` . item 1 -- cgit v1.2.3 From b485624a93bc10f22753d81726ec3481652ee5bc Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 23 Oct 2017 13:19:59 -0200 Subject: [asymptotic-notation/pt-br] Small typo --- pt-br/asymptotic-notation-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown index 2e299d09..aecc2194 100644 --- a/pt-br/asymptotic-notation-pt.html.markdown +++ b/pt-br/asymptotic-notation-pt.html.markdown @@ -38,7 +38,7 @@ Na primeira seção desse documento, descrevemos como Notação Assintótica ide *f*, *n* como o tamanho da entrada e *f(n)* sendo o tempo de execução. Então, para dado algoritmo *f*, com entrada de tamanho *n*, você terá tempo de execução *f(n)*. Isto resulta em um gráfico onde a coordernada Y é o tempo de execução -, a coordernada X representa o tamanho da entrada e os pontos representao o tempo +, a coordernada X representa o tamanho da entrada e os pontos representam o tempo de execução para dado tamanho de entrada. Você pode representar a função, ou o algoritmo, com Notação Assintótica de várias -- cgit v1.2.3 From 0f3b319d66cbf0193d017fc6e18facbbc96469c9 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 23 Oct 2017 13:30:25 -0200 Subject: [c++/pt-br] Small typos --- pt-br/c++-pt.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index c1cfbbb1..09bfc825 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -20,7 +20,7 @@ foi concebida para Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais recentes, C++ é amplamente utilizado porque compila para instruções nativas que -podem ser executadas diretamente pelo processador e oferece um controlo rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +podem ser executadas diretamente pelo processador e oferece um controle rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade faz C++ uma das linguagens de programação mais utilizadas. @@ -40,10 +40,10 @@ faz C++ uma das linguagens de programação mais utilizadas. int main(int argc, char** argv) { - // Argumentos de linha de comando são passados em pelo argc e argv da mesma + // Argumentos de linha de comando são passados para argc e argv da mesma // forma que eles estão em C. // argc indica o número de argumentos, - // e argv é um array de strings, feito C (char*) representado os argumentos + // e argv é um array de strings, feito C (char*) representando os argumentos // O primeiro argumento é o nome pelo qual o programa foi chamado. // argc e argv pode ser omitido se você não se importa com argumentos, // dando a assinatura da função de int main() @@ -274,7 +274,7 @@ public: void setWeight(int dogsWeight); - // Funções que não modificam o estado do objecto devem ser marcadas como + // Funções que não modificam o estado do objeto devem ser marcadas como // const. Isso permite que você chamá-los se for dada uma referência const // para o objeto. Além disso, observe as funções devem ser explicitamente // declarados como _virtual_, a fim de ser substituídas em classes -- cgit v1.2.3 From b057f5f2bd43368043c1b8ed19e5335e66d18cc0 Mon Sep 17 00:00:00 2001 From: Thiago Ribeiro Date: Mon, 23 Oct 2017 13:44:26 -0200 Subject: [c/pt-br] small typo --- pt-br/c-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 6e7aa8c2..c0cfb0ba 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -191,7 +191,7 @@ int main() { f1 / f2; // => 0.5, mais ou menos epsilon // Números e cálculos de ponto flutuante não são exatos - // Modulo também existe + // Módulo também existe 11 % 3; // => 2 // Operadores de comparação provavelmente são familiares, -- cgit v1.2.3 From 10bd172129c2df170c6609a5d209fed8417f76b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20J=C3=BCrges?= Date: Mon, 23 Oct 2017 18:12:14 +0200 Subject: Translated LOLCODE to german --- de-de/LOLCODE-de.html.markdown | 188 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 de-de/LOLCODE-de.html.markdown diff --git a/de-de/LOLCODE-de.html.markdown b/de-de/LOLCODE-de.html.markdown new file mode 100644 index 00000000..155c5657 --- /dev/null +++ b/de-de/LOLCODE-de.html.markdown @@ -0,0 +1,188 @@ +--- +language: LOLCODE +filename: learnLOLCODE.lol +contributors: + - ["abactel", "https://github.com/abactel"] +translators: + - ["Henrik Jürges", "http://github.com/santifa"] +lang: de-de +--- + +LOLCODE ist eine esoterische Programmiersprache die die Sprache der [lolcats](https://upload.wikimedia.org/wikipedia/commons/a/ab/Lolcat_in_folder.jpg?1493656347257) nachahmt. + +``` +BTW Das ist ein Kommentar +BTW Das Programm muss mit `HAI ` beginnen und mit `KTHXBYE` enden. + +HAI 1.3 +CAN HAS STDIO? BTW Standard Header importieren + +OBTW + ========================================================================== + ============================== Grundlegendes ============================= + ========================================================================== +TLDR + +BTW Texte anzeigen: +VISIBLE "HELLO WORLD" + +BTW Variablen deklarieren: +I HAS A MESSAGE ITZ "CATZ ARE GOOD" +VISIBLE MESSAGE + +OBTW + Variablen sind dynamisch typisiert und der Typ muss nicht explizit + angegeben werden. Die möglichen Typen sind: +TLDR + +I HAS A STRING ITZ "DOGZ ARE GOOOD" BTW Typ ist YARN +I HAS A INTEGER ITZ 42 BTW Typ ist NUMBR +I HAS A FLOAT ITZ 3.1415 BTW Typ ist NUMBAR +I HAS A BOOLEAN ITZ WIN BTW Typ ist TROOF +I HAS A UNTYPED BTW Typ ist NOOB + +BTW Eingaben von Nutzern: +I HAS A AGE +GIMMEH AGE +BTW Die Variable wird als YARN gespeichert und kann in eine +BTW NUMBR konvertiert werden: +AGE IS NOW A NUMBR + +OBTW + ========================================================================== + ================================== MATHE ================================= + ========================================================================== +TLDR + +BTW LOLCODE benutzt polnische Notation für Mathe. + +BTW grundlegende mathematische Notationen: + +SUM OF 21 AN 33 BTW 21 + 33 +DIFF OF 90 AN 10 BTW 90 - 10 +PRODUKT OF 12 AN 13 BTW 12 * 13 +QUOSHUNT OF 32 AN 43 BTW 32 / 43 +MOD OF 43 AN 64 BTW 43 modulo 64 +BIGGR OF 23 AN 53 BTW max(23, 53) +SMALLR OF 53 AN 45 BTW min(53, 45) + +BTW binäre Notation: + +BOTH OF WIN AN WIN BTW und: WIN if x=WIN, y=WIN +EITHER OF FAIL AN WIN BTW oder: FAIL if x=FAIL, y=FAIL +WON OF WIN AN FAIL BTW exklusives oder: FAIL if x=y +NOT FAIL BTW unäre Negation: WIN if x=FAIL +ALL OF WIN AN WIN MKAY BTW beliebige Stelligkeit bei AND +ANY OF WIN AN FAIL MKAY BTW beliebige Stelligkeit bei OR + +BTW Vergleiche: + +BOTH SAEM "CAT" AN "DOG" BTW WIN wenn x == y +DIFFRINT 732 AN 184 BTW WIN wenn x != y +BOTH SAEM 12 AN BIGGR OF 12 AN 4 BTW x >= y +BOTH SAEM 43 AN SMALLR OF 43 AN 56 BTW x <= y +DIFFRINT 64 AN SMALLR OF 64 AN 2 BTW x > y +DIFFRINT 75 AN BIGGR OF 75 AN 643 BTW x < y + +OBTW + ========================================================================== + ============================= Flusskontrolle ============================= + ========================================================================== +TLDR + +BTW If/then Statement: +I HAS A ANIMAL +GIMMEH ANIMAL +BOTH SAEM ANIMAL AN "CAT", O RLY? + YA RLY + VISIBLE "YOU HAV A CAT" + MEBBE BOTH SAEM ANIMAL AN "MAUS" + VISIBLE "NOM NOM NOM. I EATED IT." + NO WAI + VISIBLE "AHHH IS A WOOF WOOF" +OIC + +BTW Case Statement: +I HAS A COLOR +GIMMEH COLOR +COLOR, WTF? + OMG "R" + VISIBLE "RED FISH" + GTFO + OMG "Y" + VISIBLE "YELLOW FISH" + BTW Weil hier kein `GTFO` ist wird auch das nächste Statement überprüft + OMG "G" + OMG "B" + VISIBLE "FISH HAS A FLAVOR" + GTFO + OMGWTF + VISIBLE "FISH IS TRANSPARENT OHNO WAT" +OIC + +BTW For Schleife: +I HAS A TEMPERATURE +GIMMEH TEMPERATURE +TEMPERATURE IS NOW A NUMBR +IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN TEMPERATURE + VISIBLE ITERATOR +IM OUTTA YR LOOP + +BTW While Schleife: +IM IN YR LOOP NERFIN YR ITERATOR WILE DIFFRINT ITERATOR AN -10 + VISIBLE ITERATOR +IM OUTTA YR LOOP + +OBTW + ========================================================================= + ================================ Strings ================================ + ========================================================================= +TLDR + +BTW Zeilenumbrüche: +VISIBLE "FIRST LINE :) SECOND LINE" + +BTW Tabulatoren: +VISIBLE ":>SPACES ARE SUPERIOR" + +BTW Bell (macht beep): +VISIBLE "NXT CUSTOMER PLS :o" + +BTW Anführungszeichen in Strings: +VISIBLE "HE SAID :"I LIKE CAKE:"" + +BTW Doppelpunkte in Strings : +VISIBLE "WHERE I LIVE:: CYBERSPACE" + +OBTW + ========================================================================= + =============================== Funktionen ============================== + ========================================================================= +TLDR + +BTW Definieren einer neuen Funktion: +HOW IZ I SELECTMOVE YR MOVE BTW `MOVE` ist ein Argument + BOTH SAEM MOVE AN "ROCK", O RLY? + YA RLY + VISIBLE "YOU HAV A ROCK" + NO WAI + VISIBLE "OH NO IS A SNIP-SNIP" + OIC + GTFO BTW Gibt NOOB zurück +IF U SAY SO + +BTW Eine Funktion deklarieren und einen Wert zurückgeben: +HOW IZ I IZYELLOW + FOUND YR "YELLOW" +IF U SAY SO + +BTW Eine Funktion aufrufen: +I IZ IZYELLOW MKAY + +KTHXBYE +``` + +## Weiterführende Informationen: + +- [LCI compiler](https://github.com/justinmeza/lci) +- [Official spec](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md) -- cgit v1.2.3 From fc57b35478e2ba624005fdb0138c98bb4916fbf4 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Mon, 23 Oct 2017 16:16:44 -0200 Subject: Translate whip to pt_BR --- pt-br/whip-pt.html.markdown | 247 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 pt-br/whip-pt.html.markdown diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown new file mode 100644 index 00000000..989bae05 --- /dev/null +++ b/pt-br/whip-pt.html.markdown @@ -0,0 +1,247 @@ +--- +language: whip +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] +author: Tenor Biel +author_url: http://github.com/L8D +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br +filename: whip-pt.lisp +--- + +Whip é um dialeto de Lisp feito para construir scripts e trabalhar com +conceitos mais simples. +Ele também copia muitas funções e sintaxe de Haskell (uma linguagem não correlata) + +Esse documento foi escrito pelo próprio autor da linguagem. Então é isso. + +```scheme +; Comentário são como em Lisp. Pontos-e-vírgulas... + +; A maioria das declarações de primeiro nível estão dentro de "listas" +; que nada mais são que coisas entre parêntesis separadas por espaços em branco +nao_é_uma_lista +(uma lista) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 1. Números, texto e operadores + +; Whip tem um tipo numérico (que é um double de 64 bits IEE 754, do JavaScript) +3 ; => 3 +1.5 ; => 1.5 + +; Funções são chamadas se elas são o primeiro elemento em uma lista +(funcao_chamada argumentos) + +; A maioria das operações são feitas com funções +; Todas as funções aritméticas básicas são bem diretas +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 +; até mesmo o módulo +(% 9 4) ; => 1 +; Divisão não inteira ao estilo JavaScript. +(/ 5 2) ; => 2.5 + +; Aninhamento de listas funciona como esperado. +(* 2 (+ 1 3)) ; => 8 + +; Há um tipo boleano. +true +false + +; Textos são criados com ". +"Hello, world" + +; Caracteres são criados com '. +'a' + +; Para negação usa-se a função 'not'. +(not true) ; => false +(not false) ; => true + +; Mas a maioria das funções não-haskell tem atalhos +; o não atalho é um '!'. +(! (! true)) ; => true + +; Igualdade é `equal` ou `=`. +(= 1 1) ; => true +(equal 2 1) ; => false + +; Por exemplo, inigualdade pode ser verificada combinando as funções +;`not` e `equal`. +(! (= 2 1)) ; => true + +; Mais comparações +(< 1 10) ; => true +(> 1 10) ; => false +; e suas contra partes para texto. +(lesser 1 10) ; => true +(greater 1 10) ; => false + +; Texto pode ser concatenado com +. +(+ "Hello " "world!") ; => "Hello world!" + +; Você pode usar as características comparativas do JavaScript. +(< 'a' 'b') ; => true +; ... e coerção de tipos +(= '5' 5) + +; As funções `at` ou `@` acessarão caracteres de um texto, começando em 0. +(at 0 'a') ; => 'a' +(@ 3 "foobar") ; => 'b' + +; Também existem as variáveis `null` e `undefined`. +null ; usada para indicar a ausência de algum valor +undefined ; usada para indicar que um valor não foi informado + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 2. Variáveis, matrizes e dicionários + +; Variáveis são declaradas com as funções `def` ou `let`. +; Variáveis que não tiveram valor atribuído serão `undefined`. +(def some_var 5) +; `def` deixará a variável no contexto global. +; `let` deixará a variável no contexto local, e tem uma sintaxe estranha. +(let ((a_var 5)) (+ a_var 5)) ; => 10 +(+ a_var 5) ; = undefined + 5 => undefined + +; Matrizes são listas de valores de qualquer tipo. +; Elas basicamente são listas sem funções no início +(1 2 3) ; => [1, 2, 3] (sintaxe JavaScript) + +; Dicionários em Whip são o equivalente a 'object' em JavaScript ou +; 'dict' em python ou 'hash' em Ruby: eles s]ão uma coleção desordenada +de pares chave-valor. +{"key1" "value1" "key2" 2 3 3} + +; Chaves podem ser apenas identificadores, números ou texto. +(def my_dict {my_key "my_value" "my other key" 4}) +; Mas em Whip, dicionários são parceados como: valor, espaço, valor; +; com mais espaço entre cada. Então isso significa que +{"key" "value" +"another key" +1234 +} +é avaliado da mesma forma que +{"key" "value" "another key" 1234} + +; Dicionários podem ser acessados usando a função `at` +; (como em texto e listas) +(@ "my other key" my_dict) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 3. Lógica e controle de fluxo + +; A função `if` é muito simples, ainda que muito diferente do que em muitas +linguagens imperativas. +(if true "returned if first arg is true" "returned if first arg is false") +; => "returned if first arg is true" + +; E por conta do legado operador ternário +; `?` é o atalho não utilizado para `if`. +(? false true false) ; => false + +; `both` é uma declaração lógica `and`, e `either` é o `or` lógico. +(both true true) ; => true +(both true false) ; => false +(either true false) ; => true +(either false false) ; => false +; E seus atalhos são +; & => both +; ^ => either +(& true true) ; => true +(^ false true) ; => true + +;;;;;;;;; +; Lambdas + +; Lambdas em Whip são declaradas com as funções `lambda` ou `->`. +; E funções são na verdade lambdas com nomes. +(def my_function (-> (x y) (+ (+ x y) 10))) +; | | | | +; | | | valor retornado (com escopo contento argumentos) +; | | argumentos +; | declaração de funções lambda +; | +; nome do lambda a ser declarado + +(my_function 10 10) ; = (+ (+ 10 10) 10) => 30 + +; Obviamente, todos os lambdas por definição são anônimos e +; tecnicamente sempre usados anonimamente. Redundância. +((lambda (x) x) 10) ; => 10 + +;;;;;;;;;;;;;;;; +; Comprehensions + +; `range` or `..` geram uma lista dos números para +; cada número entre seus dois argumentos. +(range 1 5) ; => (1 2 3 4 5) +(.. 0 2) ; => (0 1 2) + +; `map` aplica seu primeiro argumento (que deve ser um lambda/função) +; a cada item dos argumentos seguintes (que precisa ser uma lista) +(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) + +; Reduce +(reduce + (.. 1 5)) +; equivalente a +((+ (+ (+ 1 2) 3) 4) 5) + +; Nota: map e reduce não possuem atalhos + +; `slice` ou `\` é similar ao .slice() do JavaScript +; mas veja que ele pega uma lista como primeiro argumento, não o último. +(slice (.. 1 5) 2) ; => (3 4 5) +(\ (.. 0 100) -5) ; => (96 97 98 99 100) + +; `append` ou `<<` são auto explicativos +(append 4 (1 2 3)) ; => (1 2 3 4) +(<< "bar" ("foo")) ; => ("foo" "bar") + +; Length é auto explicativo. +(length (1 2 3)) ; => 3 +(_ "foobar") ; => 6 + +;;;;;;;;;;;;;;; +; Delicadezas Haskell + +; Primeiro item de uma lista +(head (1 2 3)) ; => 1 +; Pega do segundo ao último elemento de uma lista +(tail (1 2 3)) ; => (2 3) +; Último item de uma lista +(last (1 2 3)) ; => 3 +; Contrário de `tail` +(init (1 2 3)) ; => (1 2) +; Pega do primeiro até o elemento especificado da lista +(take 1 (1 2 3 4)) ; (1 2) +; Contrário de `take` +(drop 1 (1 2 3 4)) ; (3 4) +; Menos valor em uma lista +(min (1 2 3 4)) ; 1 +; Maior valor em uma lista +(max (1 2 3 4)) ; 4 +; Verifica se o valor está em uma lista ou objeto +(elem 1 (1 2 3)) ; true +(elem "foo" {"foo" "bar"}) ; true +(elem "bar" {"foo" "bar"}) ; false +; Inverte a ordem de uma lista +(reverse (1 2 3 4)) ; => (4 3 2 1) +; Verifica se o valor é par ou ímpar +(even 1) ; => false +(odd 1) ; => true +; Separa um texto cortando por espaço em branco +(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") +; Junta lista de textos +(unwords ("foo" "bar")) ; => "foobar" +; Sucessor e predecessor +(pred 21) ; => 20 +(succ 20) ; => 21 +``` + +Para mais informação, verifique o [repositório](http://github.com/L8D/whip) -- cgit v1.2.3 From 265042a219ddb681125fb72549bea280a114e671 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Mon, 23 Oct 2017 16:31:26 -0200 Subject: Add comment to separate functions categories --- whip.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/whip.html.markdown b/whip.html.markdown index e7e5e427..c692714a 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -3,6 +3,7 @@ language: whip contributors: - ["Tenor Biel", "http://github.com/L8D"] - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] author: Tenor Biel author_url: http://github.com/L8D filename: whip.lisp @@ -232,6 +233,7 @@ undefined ; user to indicate a value that hasn't been set (words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") ; Join list of strings together. (unwords ("foo" "bar")) ; => "foobar" +; Successor and Predecessor (pred 21) ; => 20 (succ 20) ; => 21 ``` -- cgit v1.2.3 From 55efb934b8d7f2034020d17e331f02b852952012 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Mon, 23 Oct 2017 15:11:13 -0700 Subject: python3/en cleanup for single inheritance merge --- python3.html.markdown | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index e02aed43..37987582 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -785,7 +785,7 @@ class Superhero(Human): self.superpowers = superpowers # The "super" function lets you access the parent class's methods - # that are overwritten by the child, in this case, the __init__ method. + # that are overridden by the child, in this case, the __init__ method. # This calls the parent class constructor: super().__init__(name) @@ -814,7 +814,7 @@ if __name__ == '__main__': # => , ) # Calls parent method but uses its own class attribute - print(sup.get_species()) # => Superhero + print(sup.get_species()) # => Superhuman # Calls overloaded method print(sup.sing()) # => Dun, dun, DUN! @@ -838,6 +838,7 @@ if __name__ == '__main__': #################################################### # Another class definition +# bat.py class Bat: species = 'Baty' @@ -859,16 +860,13 @@ if __name__ == '__main__': print(b.say('hello')) print(b.fly) -# To take advantage of modularization by file you could place the classes above in their own files, -# say, superhero.py and bat.py -# To import functions from other files use the following format -# from "filename-without-extension" import "function-or-class" +# And yet another class definition that inherits from Superhero and Bat # superhero.py from superhero import Superhero from bat import Bat -# Batman inherits from both Superhero and Bat +# Define Batman as a child that inherits from both Superhero and Bat class Batman(Superhero, Bat): def __init__(self, *args, **kwargs): @@ -892,14 +890,6 @@ class Batman(Superhero, Bat): if __name__ == '__main__': sup = Batman() - # Instance type checks - if isinstance(sup, Superhero): - print('I am a superhero) - if isinstance(sup, Bat): - print('I am bat') - if type(sup) is Batman: - print('I am Batman') - # Get the Method Resolution search Order used by both getattr() and super(). # This attribute is dynamic and can be updated print(Batman.__mro__) # => (, -- cgit v1.2.3 From 95b5f9a4c4fa17b1d4854185a08e2a3434944de0 Mon Sep 17 00:00:00 2001 From: ksami Date: Tue, 24 Oct 2017 13:29:11 +0800 Subject: #2314 add delegates and events to csharp/en --- csharp.html.markdown | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index c98a7da9..24ce803e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -640,6 +640,54 @@ on a new line! ""Wow!"", the masses cried"; } } + + // DELEGATES AND EVENTS + public class DelegateTest + { + public static int count = 0; + public static int Increment() + { + // increment count then return it + return ++count; + } + + // A delegate is a reference to a method + // To reference the Increment method, + // first declare a delegate with the same signature + // ie. takes no arguments and returns an int + public delegate int IncrementDelegate(); + + // An event can also be used to trigger delegates + // Create an event with the delegate type + public static event IncrementDelegate MyEvent; + + static void Main(string[] args) + { + // Refer to the Increment method by instantiating the delegate + // and passing the method itself in as an argument + IncrementDelegate inc = new IncrementDelegate(Increment); + Console.WriteLine(inc()); // => 1 + + // Delegates can be composed with the + operator + IncrementDelegate composedInc = inc; + composedInc += inc; + composedInc += inc; + + // composedInc will run Increment 3 times + Console.WriteLine(composedInc()); // => 4 + + + // Subscribe to the event with the delegate + MyEvent += new IncrementDelegate(Increment); + MyEvent += new IncrementDelegate(Increment); + + // Trigger the event + // ie. run all delegates subscribed to this event + Console.WriteLine(MyEvent()); // => 6 + } + } + + // Class Declaration Syntax: // class { // //data fields, constructors, functions all inside. -- cgit v1.2.3 From be1381f6bbcedff978027c80c4a1e579748cb769 Mon Sep 17 00:00:00 2001 From: Senrion Date: Tue, 24 Oct 2017 07:52:54 +0200 Subject: [edn/de] fixing typos --- de-de/edn-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown index 4f452d7e..2434d1bd 100644 --- a/de-de/edn-de.html.markdown +++ b/de-de/edn-de.html.markdown @@ -41,7 +41,7 @@ false ; Charaktere werden einem Backslash vorangestellt \g \r \a \c \e -; Schlüsselwörter beginnen mit einenm Doppelpunkt. Sie verhalten sich wie Enums. +; Schlüsselwörter beginnen mit einem Doppelpunkt. Sie verhalten sich wie Enums. ; Ähnlich, wie Symbole in Ruby. :eggs :cheese @@ -79,7 +79,7 @@ false #{:a :b 88 "huat"} ;;;;;;;;;;;;;;;;;;;;;;;;; -;;; makierte Elemente ;;; +;;; markierte Elemente ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; ; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden. @@ -91,7 +91,7 @@ false (defrecord MenuItem [name rating]) ; Um EDN in clojure Werte umzuwandeln, muss ich den eingebauten EDN Leser -;edn/read-string verwenden +; edn/read-string verwenden (edn/read-string "{:eggs 2 :butter 1 :flour 5}") ; -> {:eggs 2 :butter 1 :flour 5} -- cgit v1.2.3 From 4eb33f98b47dfbf6ae0c7c2148faadab310f53c5 Mon Sep 17 00:00:00 2001 From: ksami Date: Tue, 24 Oct 2017 15:20:20 +0800 Subject: add topics for tuples to csharp/en Added explanation and examples for tuples, deconstruction of tuples and other objects, and discarding unwanted fields during deconstruction --- csharp.html.markdown | 72 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 56 insertions(+), 16 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index c98a7da9..54d5ea09 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1106,25 +1106,65 @@ namespace Learning.More.CSharp } } +//New C# 7 Feature +//Install Microsoft.Net.Compilers Latest from Nuget +//Install System.ValueTuple Latest from Nuget using System; namespace Csharp7 { - //New C# 7 Feature - //Install Microsoft.Net.Compilers Latest from Nuget - //Install System.ValueTuple Latest from Nuget - class Program - { - static void Main(string[] args) - { - //Type 1 Declaration - (string FirstName, string LastName) names1 = ("Peter", "Parker"); - Console.WriteLine(names1.FirstName); - - //Type 2 Declaration - var names2 = (First:"Peter", Last:"Parker"); - Console.WriteLine(names2.Last); - } - } + // TUPLES, DECONSTRUCTION AND DISCARDS + class TuplesTest + { + public (string, string) GetName() + { + // Fields in tuples are by default named Item1, Item2... + var names1 = ("Peter", "Parker"); + Console.WriteLine(names1.Item2); // => Parker + + // Fields can instead be explicitly named + // Type 1 Declaration + (string FirstName, string LastName) names2 = ("Peter", "Parker"); + + // Type 2 Declaration + var names3 = (First:"Peter", Last:"Parker"); + + Console.WriteLine(names2.FirstName); // => Peter + Console.WriteLine(names3.Last); // => Parker + + return names3; + } + + public string GetLastName() { + var fullName = GetName(); + + // Tuples can be deconstructed + (string firstName, string lastName) = fullName; + + // Fields in a deconstructed tuple can be discarded by using _ + var (_, last) = fullName; + return last; + } + + // Any type can be deconstructed in the same way by + // specifying a Deconstruct method + public int randomNumber = 4; + public int anotherRandomNumber = 10; + + public void Deconstruct(out int randomNumber, out int anotherRandomNumber) + { + randomNumber = this.randomNumber; + anotherRandomNumber = this.anotherRandomNumber; + } + + static void Main(string[] args) + { + var tt = new TuplesTest(); + (int num1, int num2) = tt; + Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10 + + Console.WriteLine(tt.GetLastName()); + } + } } ``` -- cgit v1.2.3 From 52324c9d0f8bd5d2d6a1167c3c6775e00c842b6b Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 20:46:38 +0700 Subject: Added Vietnamese translation for Less --- vi-vn/less-vi.html.markdown | 405 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 405 insertions(+) create mode 100644 vi-vn/less-vi.html.markdown diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown new file mode 100644 index 00000000..73940592 --- /dev/null +++ b/vi-vn/less-vi.html.markdown @@ -0,0 +1,405 @@ +--- +language: less +contributors: + - ["Saravanan Ganesh", "http://srrvnn.me"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +filename: learnless-vi.ts +lang: vi-vn +--- + +Less là một CSS pre-processor (bộ tiền xử lí CSS), nó thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Less cùng với các CSS pre-processor khác như [Sass](http://sass-lang.com/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +```css + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Biến +==============================*/ + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '@' để khai báo một biến. */ + +@primary-color: #a3a4ff; +@secondary-color: #51527f; +@body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. + Now if you want to change a color, you only have to make the change once.*/ +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: @primary-color; + color: @secondary-color; + font-family: @body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ + +body { + background-color: #a3a4ff; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Mixins +==============================*/ + + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin chỉ bằng việc thêm selector + vào trong nội dung style của element khác */ + +div { + .center; + background-color: @primary-color; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + +/* You can omit the mixin code from being compiled by adding parenthesis + after the selector */ +/* Ta có thể ngăn không cho code mixin được biên dịch + bằng cách thêm cặp ngoặc tròn đằng sau selector */ + +.center() { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +div { + .center; + background-color: @primary-color; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + + + +/* Nesting - Lồng +==============================*/ + + +/* Less cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Function +==============================*/ + + +/* Less cung cấp các function có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Function được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ + +body { + width: round(10.25px); +} + +.header { + background-color: lighten(#000, 0.5); +} + +.footer { + background-color: fadeout(#000, 0.25) +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.header { + background-color: #010101; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa function mới. + Function khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng function hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + function sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử' là ứng cử viên + sáng giá cho việc dùng function có thể tái sử dụng được. +*/ + +/* Function này tính giá trị trung bình của hai số: */ +.average(@x, @y) { + @average-result: ((@x + @y) / 2); +} + +div { + .average(16px, 50px); // gọi mixin + padding: @average-result; // sử dụng giá trị trả về của mixin +} + +/* Biên dịch thành: */ + +div { + padding: 33px; +} + + + +/* Mở rộng (Thừa kế) +==============================*/ + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + height: 50px; +} + +.display-success { + &:extend(.display); + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, +.display-success { + height: 50px; +} +.display-success { + border-color: #22df56; +} + +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the properties + would be duplicated for each statement that + called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Less compiler. */ +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + +/* Partials and Imports - Chia nhỏ và nhập vào +==============================*/ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Less cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Less sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Toán học +==============================*/ + + +/* Less cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Less thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +@content-area: 960px; +@main-content: 600px; +@sidebar-content: 300px; + +@main-size: @main-content / @content-area * 100%; +@sidebar-size: @sidebar-content / @content-area * 100%; +@gutter: 100% - (@main-size + @sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: @main-size; +} + +.sidebar { + width: @sidebar-size; +} + +.gutter { + width: @gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + +## Tập sử dụng Less + +Nếu bạn cần xài thử Less trên trình duyệt, hãy ghé qua: +* [Codepen](http://codepen.io/) +* [LESS2CSS](http://lesscss.org/less-preview/) + +## Tính tương thích + +Less có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://lesscss.org/features/) +* [Less CSS - Hướng dẫn cho người mới bắt đầu](http://www.hongkiat.com/blog/less-basic/) \ No newline at end of file -- cgit v1.2.3 From 4d248efdb8a927ebb14c53aa0da5d025838195a6 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 20:48:16 +0700 Subject: Fixed minor typo for Less translation file --- vi-vn/less-vi.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown index 73940592..f861fb0e 100644 --- a/vi-vn/less-vi.html.markdown +++ b/vi-vn/less-vi.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] translators: - ["Thanh Duy Phan", "https://github.com/thanhpd"] -filename: learnless-vi.ts +filename: learnless-vi.less lang: vi-vn --- -- cgit v1.2.3 From ab094ff0615d7236be17368b50795adf756f98c0 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 22:12:24 +0700 Subject: Re-edit Less translation file --- vi-vn/less-vi.html.markdown | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown index f861fb0e..594ccc31 100644 --- a/vi-vn/less-vi.html.markdown +++ b/vi-vn/less-vi.html.markdown @@ -30,8 +30,6 @@ Less là một CSS pre-processor (bộ tiền xử lí CSS), nó thêm các tín @secondary-color: #51527f; @body-font: 'Roboto', sans-serif; -/* You can use the variables throughout your stylesheet. - Now if you want to change a color, you only have to make the change once.*/ /* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. Nhờ sử dụng biến ta chỉ cần thay đổi một lần tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ @@ -98,8 +96,6 @@ div { background-color: #a3a4ff; } -/* You can omit the mixin code from being compiled by adding parenthesis - after the selector */ /* Ta có thể ngăn không cho code mixin được biên dịch bằng cách thêm cặp ngoặc tròn đằng sau selector */ @@ -275,12 +271,6 @@ div { border-color: #22df56; } -/* Extending a CSS statement is preferable to creating a mixin - because of the way it groups together the classes that all share - the same base styling. If this was done with a mixin, the properties - would be duplicated for each statement that - called the mixin. While it won't affect your workflow, it will - add unnecessary bloat to the files created by the Less compiler. */ /* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới bởi cách nó nhóm các lớp có chung một style gốc. Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp -- cgit v1.2.3 From 838efd36532faf52d631bbc798b284bbc7867479 Mon Sep 17 00:00:00 2001 From: Allwin Baby Panikulam Date: Thu, 26 Oct 2017 01:12:10 +0800 Subject: Fix link to javascript docs --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 44fd791a..10f01ebc 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](/docs/javascript). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. -- cgit v1.2.3 From ab84fe8cf57d42b78b4a6d441ebd47acc65bd520 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:27:36 -0200 Subject: [c#/pt-br] Small typos --- pt-br/csharp-pt.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..377ac984 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -6,23 +6,23 @@ contributors: lang: pt-br --- -C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. +C# é uma linguagem elegante, altamente tipada e orientada a objetos que permite aos desenvolvedores criar uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. -[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) +[Leia mais aqui.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) ```c# -// Comentário de linha única começa com // +// Comentários de linha única começam com // /* -Múltipas linhas é desta forma +Comentários de múltiplas linhas são desta forma */ /// -/// Esta é uma documentação comentário XML que pode ser usado para gerar externo -/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// Este é um comentário de documentação XML que pode ser usado para gerar documentação +/// externa ou para fornecer ajuda de contexto dentro de uma IDE /// //public void MethodOrClassOrOtherWithParsableHelp() {} -// Especificar qual namespace seu código irá usar -// Os namespaces a seguir são padrões do .NET Framework Class Library +// Especifica os namespaces que o código irá usar +// Os namespaces a seguir são padrões da biblioteca de classes do .NET Framework using System; using System.Collections.Generic; using System.Dynamic; @@ -33,11 +33,11 @@ using System.IO; // Mas este aqui não é : using System.Data.Entity; -// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Para que consiga utilizá-lo, você precisa adicionar novas referências // Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` -// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" -// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +// Namespaces são escopos definidos para organizar o código em "pacotes" ou "módulos" +// Usando este código a partir de outro arquivo de origem: using Learning.CSharp; namespace Learning.CSharp { // Cada .cs deve conter uma classe com o mesmo nome do arquivo -- cgit v1.2.3 From d1b6dda7bd074ba76c0d136d4176f358b0a94adb Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:38:59 -0200 Subject: [java/pt-br] Small typo --- pt-br/java-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 82989502..1b9d7fc6 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -42,7 +42,7 @@ public class LearnJava { " Double: " + 3.14 + " Boolean: " + true); - // Para imprimir sem inserir uma nova lina, use o System.out.print + // Para imprimir sem inserir uma nova linha, use o System.out.print System.out.print("Olá "); System.out.print("Mundo"); -- cgit v1.2.3 From a246fb409059fce98b5f4ebf6ae17036112ce750 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:42:06 -0200 Subject: [json/pt-br] Small typo --- pt-br/json-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fd822c03..62d9ccad 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -16,7 +16,7 @@ Como JSON é um formato de intercâmbio de dados, este será, muito provavelment JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. -Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null. +Um valor JSON pode ser um número, uma string, um array, um objeto, um booleano (true, false) ou null. Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+. -- cgit v1.2.3 From 5a4785cac438809a714a700ad15e09518052c014 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:46:29 -0200 Subject: [javascript/pt-br] Small typo --- pt-br/javascript-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 7b6729ef..ed4a6ff3 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -25,7 +25,7 @@ Feedback são muito apreciados! Você me encontrar em ```js // Comentários são como em C. Comentários de uma linha começam com duas barras, -/* e comentários de múltplas linhas começam com barra-asterisco +/* e comentários de múltiplas linhas começam com barra-asterisco e fecham com asterisco-barra */ // comandos podem ser terminados com ; -- cgit v1.2.3 From 3a41a6006ff421b45ae46a521b900216ac28daf7 Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Thu, 26 Oct 2017 10:15:32 +0200 Subject: html-de.html.markdown removed a Double Point. improved usage part to follow english original --- de-de/html-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown index 2ee18129..0bf58f9c 100644 --- a/de-de/html-de.html.markdown +++ b/de-de/html-de.html.markdown @@ -9,7 +9,7 @@ lang: de-de --- HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache). -Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben.. +Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben. Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien. Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags. Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt. @@ -111,7 +111,7 @@ Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben ## Verwendung -HTML Dateien enden mit `.html`. +HTML Dateien enden mit `.html` oder mit `.htm`. Der Mime Typ ist meist `text/html`. ## Um mehr zu lernen -- cgit v1.2.3 From 5670c7381dbffa12b3d2b5e51ac9b8b1c4d9dca1 Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 11:22:40 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..800e3097 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -823,7 +823,7 @@ on a new line! ""Wow!"", the masses cried"; } } - // Interfaces only contain signatures of the members, without the implementation. + // Interfaces contêm apenas as assinaturas dos membros, sem a implementação. interface IJumpable { void Jump(int meters); // all interface members are implicitly public -- cgit v1.2.3 From 9f7322b6208a693a013df81da6b1aadd095b78fd Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:39:25 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..3f13f1aa 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -784,7 +784,7 @@ on a new line! ""Wow!"", the masses cried"; } // end class Bicycle - // PennyFarthing is a subclass of Bicycle + // PennyFarthing é uma subclasse de Bicycle class PennyFarthing : Bicycle { // (Penny Farthings are those bicycles with the big front wheel. -- cgit v1.2.3 From b5cac96eff8d92f9fb736d6e3e61d21d771f1e2a Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:44:09 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..cc3885d2 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -790,7 +790,7 @@ on a new line! ""Wow!"", the masses cried"; // (Penny Farthings are those bicycles with the big front wheel. // They have no gears.) - // calling parent constructor + // chamando construtor pai public PennyFarthing(int startCadence, int startSpeed) : base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { -- cgit v1.2.3 From ee3f34379abd8bea7274d024571b8596c6c759d4 Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:47:42 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..a1bd980b 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -762,7 +762,7 @@ on a new line! ""Wow!"", the masses cried"; } } - //Method to display the attribute values of this Object. + //Método para exibir os valores dos atributos deste objeto. public virtual string Info() { return "Gear: " + Gear + -- cgit v1.2.3 From 18eb083fb64c77b6cf4aec36686a7058f2b03fdc Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:42:44 -0200 Subject: [css/pt-br] Missing translation --- pt-br/css-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index b1fbd961..956b3614 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -25,7 +25,7 @@ O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. ```css /* Comentários aparecem dentro do slash-asterisk, tal como esta linha! - não há "comentários de uma linha"; este é o único estilo de comentário * / + Não há "comentários de uma linha"; este é o único estilo de comentário * / /* #################### ## SELETORES -- cgit v1.2.3 From 12d4277200728b24c11da63d069c30ba555ac49c Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:48:09 -0200 Subject: [c++/pt-br] Small typos --- pt-br/c++-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 09bfc825..cd4adde7 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -18,9 +18,9 @@ foi concebida para - suportar programação orientada a objetos - suportar programação genérica -Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais -recentes, C++ é amplamente utilizado porque compila para instruções nativas que -podem ser executadas diretamente pelo processador e oferece um controle rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +Embora sua sintaxe possa ser mais difícil ou complexa do que as linguagens mais +recentes, C++ é amplamente utilizada porque compila para instruções nativas que +podem ser executadas diretamente pelo processador e oferece um controle rígido sobre o hardware (como C), enquanto oferece recursos de alto nível, como os genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade faz C++ uma das linguagens de programação mais utilizadas. -- cgit v1.2.3 From 469740c35f4059ece40887f881d27705a536e35f Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:51:16 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..ff01c31a 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -52,7 +52,7 @@ my %fruta_cor = ( banana => "amarelo", ); -# Scalars, arrays and hashes são documentados mais profundamentes em perldata. +# Scalars, arrays and hashes são documentados mais profundamente em perldata. # (perldoc perldata). # Mais tipos de dados complexos podem ser construídas utilizando referências, -- cgit v1.2.3 From e787065d76fdf9eeba2747e3b5baaadd532156da Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:52:52 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..19a72635 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -55,7 +55,7 @@ my %fruta_cor = ( # Scalars, arrays and hashes são documentados mais profundamentes em perldata. # (perldoc perldata). -# Mais tipos de dados complexos podem ser construídas utilizando referências, +# Mais tipos de dados complexos podem ser construídos utilizando referências, # o que permite que você crie listas e hashes dentro de listas e hashes. #### Condicionais e construtores de iteração -- cgit v1.2.3 From adb4fb69ad4554665d9708ca3e82b22464dbb98f Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:55:43 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..c1e6e76f 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -21,7 +21,7 @@ Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada # Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo. # Um nome de variável válido começa com uma letra ou sublinhado, -# seguido por qualquer número de letras, números ou sublinhados. +# seguido por qualquer quantidade de letras, números ou sublinhados. ### Perl has three main variable types: $scalar, @array, e %hash. -- cgit v1.2.3 From 1569318bdcfea0c486cd2fa6a374446fe6ae02c0 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 14:11:13 -0200 Subject: [c++/pt-br] Small typos --- pt-br/c-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index c0cfb0ba..0dca7ab0 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -182,7 +182,7 @@ int main() { int a, b, c; a = b = c = 0; - // Aritimética é óbvia + // Aritmética é óbvia i1 + i2; // => 3 i2 - i1; // => 1 i2 * i1; // => 2 -- cgit v1.2.3 From 189336c674856a036112b9b32a6254b07aa6aa75 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 14:21:20 -0200 Subject: [visualbasic/pt-br] Small typos --- pt-br/visualbasic-pt.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index 76cca567..b94ab609 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -15,9 +15,9 @@ module Module1 Sub Main () ' Uma visão geral de console de aplicativos do Visual Basic antes de - ' mergulharmos mais profundamente na linguagem + ' mergulharmos mais profundamente na linguagem. ' Aspas simples começam comentários. - ' Para Navegar este tutorial dentro do compilador do Visual Basic, + ' Para navegar neste tutorial dentro do compilador do Visual Basic, ' eu criei um sistema de navegação. ' Este sistema de navegação vai ser explicado conforme avançarmos no ' tutorial, e você vai entender o que isso significa. @@ -93,16 +93,16 @@ module Module1 Private Sub HelloWorldInput () Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes" ' Variáveis - 'Os dados inseridos por um usuário precisa ser armazenada . + 'Os dados inseridos por um usuário precisam ser armazenados. ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType . - ' Neste tutorial, nós queremos saber o que o seu nome, e faça o programa + ' Neste tutorial, nós queremos saber qual é o seu nome, e faça o programa ' Responder ao que é dito. Nome de usuário Dim As String " Nós usamos string como string é uma variável de texto baseado . Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome. - username = Console.ReadLine () ' armazena o nome usuários. - Console.WriteLine (" Olá " + nome do usuário) " A saída é Olá ' Seu nome ' + username = Console.ReadLine () ' armazena o nome do usuário. + Console.WriteLine (" Olá " + username) ' A saída é "Olá < seu nome >". Console.ReadLine () ' Outsputs acima. ' O código acima irá lhe fazer uma pergunta seguiu imprimindo sua resposta. " Outras variáveis ​​incluem Integer e usamos inteiro para números inteiros. -- cgit v1.2.3 From 6d836a9fda6ea007d3393799c83f3f12df91affb Mon Sep 17 00:00:00 2001 From: ksami Date: Fri, 27 Oct 2017 14:27:14 +0800 Subject: Add more c#7 features Added pattern matching, reference locals and local functions under c#7 features --- csharp.html.markdown | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 3790747c..f27adf18 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1213,6 +1213,85 @@ namespace Csharp7 Console.WriteLine(tt.GetLastName()); } } + + // PATTERN MATCHING + class PatternMatchingTest + { + public static (string, int)? CreateLogMessage(object data) + { + switch(data) + { + // Additional filtering using when + case System.Net.Http.HttpRequestException h when h.Message.Contains("404"): + return (h.Message, 404); + case System.Net.Http.HttpRequestException h when h.Message.Contains("400"): + return (h.Message, 400); + case Exception e: + return (e.Message, 500); + case string s: + return (s, s.Contains("Error") ? 500 : 200); + case null: + return null; + default: + return (data.ToString(), 500); + } + } + } + + // REFERENCE LOCALS + // Allow you to return a reference to an object instead of just its value + class RefLocalsTest + { + // note ref in return + public static ref string FindItem(string[] arr, string el) + { + for(int i=0; i apple + } + } + + // LOCAL FUNCTIONS + class LocalFunctionTest + { + private static int _id = 0; + public int id; + public LocalFunctionTest() + { + id = generateId(); + + // This local function can only be accessed in this scope + int generateId() + { + return _id++; + } + } + + public static void AnotherMethod() + { + var lf1 = new LocalFunctionTest(); + var lf2 = new LocalFunctionTest(); + Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1 + + int id = generateId(); + // error CS0103: The name 'generateId' does not exist in the current context + } + } } ``` -- cgit v1.2.3 From c14dc8fd1d0f04b90c9e5195bb21acc88f90e05b Mon Sep 17 00:00:00 2001 From: Fer Date: Fri, 27 Oct 2017 07:55:22 -0200 Subject: Update csharp-pt.html.markdown --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 800e3097..a6e82211 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -826,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; // Interfaces contêm apenas as assinaturas dos membros, sem a implementação. interface IJumpable { - void Jump(int meters); // all interface members are implicitly public + void Jump(int meters); // todos os membros da interface são implicitamente públicos } interface IBreakable -- cgit v1.2.3 From e063c7ef3556cc3b8fc2515a8175474461c83a2d Mon Sep 17 00:00:00 2001 From: Fer Date: Fri, 27 Oct 2017 08:03:05 -0200 Subject: Update csharp-pt.html.markdown --- pt-br/csharp-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 3f13f1aa..8d34d772 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -787,8 +787,8 @@ on a new line! ""Wow!"", the masses cried"; // PennyFarthing é uma subclasse de Bicycle class PennyFarthing : Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) + // (Penny Farthings são aquelas bicicletas com uma grande roda frontal. + // Elas não tem correias.) // calling parent constructor public PennyFarthing(int startCadence, int startSpeed) : -- cgit v1.2.3 From 7466732d20bc605d3c5aa8a504d2129ef26acf5a Mon Sep 17 00:00:00 2001 From: thanhpd Date: Fri, 27 Oct 2017 17:43:16 +0700 Subject: Added Vietnamese translation for Sass language --- vi-vn/sass-vi.html.markdown | 590 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 vi-vn/sass-vi.html.markdown diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown new file mode 100644 index 00000000..313890d4 --- /dev/null +++ b/vi-vn/sass-vi.html.markdown @@ -0,0 +1,590 @@ +--- +language: sass +filename: learnsass-vi.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy. +Bài hướng dẫn này sử dụng SCSS. + +Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn. + +```sass + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Variable - Biến +============================== */ + + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '$' để khai báo một biến. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Control Directive - Chỉ thị +============================== */ + + +/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */ + +/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại. + Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line). + Chế độ này rất có ích khi thực hiện debug trên file SCSS. */ + +.info { + display: inline-block; +} + +/* @for là khối vòng lặp trên một khoảng các giá trị. + Nó rất có ích cho việc đặt style của một tập hợp các phần tử. + Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */ + +// Lặp 3 lần (không kể 4) +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +// Lặp 3 lần (kể cả 3) +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Biên dịch thành */ + +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS tự động chuyển mã #FFFFFF thành white (trắng) +} + +/* Khối lặp @while rất cơ bản: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Sẽ được biên dịch thành: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm. + List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Sẽ sinh ra: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/* Mixin +==============================*/ + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. + Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height + bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Biên dịch thành: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Function - Hàm +============================== */ + + + +/* Less cung cấp các hàm có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Hàm được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25); +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa hàm mới. + hàm khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên + sáng giá cho việc dùng hàm có thể tái sử dụng được. +*/ + +/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Biên dịch thành: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Mở rộng (Thừa kế) +============================== */ + + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + + +/* Nesting - Lồng +============================== */ + + + +/* Sass cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào +============================== */ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS. + File con không được biên dịch thành file CSS riêng. */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Placeholder Selectors - Selector trống +============================== */ + + + +/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng. + Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể + sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì + sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Biên dịch thành: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Toán tử toán học +============================== */ + + + +/* Sass cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Sass thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS hay Sass? +Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass. +Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc). + + +## Tập sử dụng Sass +Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS. + +## Tính tương thích +Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức. -- cgit v1.2.3 From 5a511b6e3c26d3f60fdd217c401b7c5983629838 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Fri, 27 Oct 2017 17:43:16 +0700 Subject: Added Vietnamese translation for Sass language --- vi-vn/sass-vi.html.markdown | 590 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 vi-vn/sass-vi.html.markdown diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown new file mode 100644 index 00000000..313890d4 --- /dev/null +++ b/vi-vn/sass-vi.html.markdown @@ -0,0 +1,590 @@ +--- +language: sass +filename: learnsass-vi.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy. +Bài hướng dẫn này sử dụng SCSS. + +Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn. + +```sass + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Variable - Biến +============================== */ + + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '$' để khai báo một biến. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Control Directive - Chỉ thị +============================== */ + + +/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */ + +/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại. + Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line). + Chế độ này rất có ích khi thực hiện debug trên file SCSS. */ + +.info { + display: inline-block; +} + +/* @for là khối vòng lặp trên một khoảng các giá trị. + Nó rất có ích cho việc đặt style của một tập hợp các phần tử. + Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */ + +// Lặp 3 lần (không kể 4) +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +// Lặp 3 lần (kể cả 3) +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Biên dịch thành */ + +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS tự động chuyển mã #FFFFFF thành white (trắng) +} + +/* Khối lặp @while rất cơ bản: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Sẽ được biên dịch thành: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm. + List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Sẽ sinh ra: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/* Mixin +==============================*/ + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. + Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height + bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Biên dịch thành: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Function - Hàm +============================== */ + + + +/* Less cung cấp các hàm có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Hàm được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25); +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa hàm mới. + hàm khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên + sáng giá cho việc dùng hàm có thể tái sử dụng được. +*/ + +/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Biên dịch thành: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Mở rộng (Thừa kế) +============================== */ + + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + + +/* Nesting - Lồng +============================== */ + + + +/* Sass cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào +============================== */ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS. + File con không được biên dịch thành file CSS riêng. */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Placeholder Selectors - Selector trống +============================== */ + + + +/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng. + Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể + sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì + sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Biên dịch thành: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Toán tử toán học +============================== */ + + + +/* Sass cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Sass thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS hay Sass? +Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass. +Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc). + + +## Tập sử dụng Sass +Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS. + +## Tính tương thích +Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức. -- cgit v1.2.3 From 46fab3c0be2852661fb972555a20c9f7083ad17d Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:20:32 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..b4ace9a4 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -22,7 +22,7 @@ Sempre se lembre!! ## Maneiras de Solucionar tais Problemas -1. Top-Down (De cima para baixo): Começe solucionando o problema quebrando-o em +1. Top-Down (De cima para baixo): Comece solucionando o problema quebrando-o em partes. Se você perceber que o problema já foi resolvido, então simplemente pegue a resposta salva. Se ainda não foi resolvido, solucione-o e salve a resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente -- cgit v1.2.3 From 1504f4af99ef6811158c270143e035bc6ac3eed4 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:21:48 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..a90b11ec 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -29,7 +29,7 @@ resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente referenciado como Memorização. 2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os -subproblemas são resolvidos e começe a solucionar dos problemas mais triviais, +subproblemas são resolvidos e comece a solucionar dos problemas mais triviais, até o problema dado. Neste processo, é garantido que os subproblemas são resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica. -- cgit v1.2.3 From 01bcf645997fbea7b5b6d8e5ffb01b9d9c5fc7a6 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:22:50 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..40e6fda2 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -31,7 +31,7 @@ referenciado como Memorização. 2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os subproblemas são resolvidos e começe a solucionar dos problemas mais triviais, até o problema dado. Neste processo, é garantido que os subproblemas são -resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica. +resolvidos antes de resolver o problema. Isto é referenciado como Programação Dinâmica. ## Exemplo de Programação Dinâmica -- cgit v1.2.3 From 5f5dd74260efd76af39262c1608cd3c3e14f5576 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:29:00 -0200 Subject: [dynamic-programming/pt-br] - Better reading --- pt-br/dynamic-programming-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..45b52790 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -51,7 +51,7 @@ array antecedente e uma variável como maiorSequenciasAteAgora e seu índice ajudariam a poupar muito tempo. Um conceito similar poderia ser aplicado ao procurar o maior caminho em um grafo acíclico dirigido. ---------------------------------------------------------------------------- + ``` for i=0 to n-1 LS[i]=1 @@ -62,7 +62,7 @@ grafo acíclico dirigido. if (largest < LS[i]) ``` -### Alguns Problemas Famosos de Programação Dinâmica +## Alguns Problemas Famosos de Programação Dinâmica ``` Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- cgit v1.2.3 From 9ac6b5775bcda6d1e881825f0425ca36bc8775d9 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Fri, 27 Oct 2017 20:44:07 +0200 Subject: [go/it-it] Wording and missing translation --- it-it/go-it.html.markdown | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index e005f2dc..e49ccd79 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -26,14 +26,14 @@ Aggiunge la concorrenza in maniera diretta e semplice da capire, per far forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili per la programmazione in larga scala. -Go comes with a great standard library and an enthusiastic community. +Go include un'ottima libreria standard e ha una community entusiasta. ```go // Commento su riga singola /* Commento su riga multipla */ -// In cima a ogni file è necessario specificare il package. +// In cima ad ogni file è necessario specificare il package. // Main è un package speciale che identifica un eseguibile anziché una libreria. package main @@ -65,19 +65,19 @@ func oltreIlCiaoMondo() { x = 3 // Assegnazione di una variabile. // E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente. y := 4 - // Una funzione che ritorna due valori. - somma, prod := imparaMoltepliciValoriDiRitorno(x, y) + // Una funzione che restituisce due valori. + somma, prod := imparaMoltepliciValoriRestituiti(x, y) fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output. imparaTipi() // < y minuti, devi imparare ancora! } /* <- commento su righe multiple -Le funzioni possono avere parametri e ritornare (molteplici!) valori. -Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati. +Le funzioni possono avere parametri e restituire (molteplici!) valori. +In questo esempio, x e y sono gli argomenti, mentre somma e prod sono i valori restituiti. Da notare il fatto che x e somma vengono dichiarati come interi. */ -func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) { - return x + y, x * y // Ritorna due valori. +func imparaMoltepliciValoriRestituiti(x, y int) (somma, prod int) { + return x + y, x * y // Restituisce due valori. } // Ecco alcuni tipi presenti in Go @@ -86,7 +86,7 @@ func imparaTipi() { str := "Impara il Go!" // Tipo stringa. s2 := `Una stringa letterale -puo' includere andata a capo.` // Sempre di tipo stringa. +può includere andata a capo.` // Sempre di tipo stringa. // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. @@ -144,20 +144,20 @@ puo' includere andata a capo.` // Sempre di tipo stringa. imparaControlloDiFlusso() // Torniamo in carreggiata. } -// In Go è possibile associare dei nomi ai valori di ritorno di una funzione. -// Assegnare un nome al tipo di dato ritornato permette di fare return in vari +// In Go è possibile associare dei nomi ai valori restituiti da una funzione. +// Assegnare un nome al tipo di dato restituito permette di fare return in vari // punti all'interno del corpo della funzione, ma anche di usare return senza -// specificare in modo esplicito che cosa ritornare. -func imparaValoriDiRitornoConNome(x, y int) (z int) { +// specificare in modo esplicito che cosa restituire. +func imparaValoriRestituitiConNome(x, y int) (z int) { z = x * y return // z è implicito, perchè compare nella definizione di funzione. } // Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei -// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente -// incrementare un puntatore. +// puntatori. Puoi commettere errori a causa di puntatori nulli, ma non puoi +// incrementare un puntatore direttamente. func imparaLaMemoria() (p, q *int) { - // I valori di ritorno (con nome) p e q sono puntatori a int. + // I valori restituiti (con nome) p e q sono puntatori a int. p = new(int) // La funzione new si occupa di allocare memoria. // L'int allocato viene inizializzato a 0, dunque p non è più nil. s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria. @@ -207,14 +207,14 @@ func imparaControlloDiFlusso() { } // x == 42 qua. - // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme. + // Il for è l'unica istruzione per i loop in Go, ma ha varie forme. for { // Ciclo infinito. break // Scherzavo. continue // Non si arriva qua. } - // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale. - // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa). + // Puoi usare range per iterare lungo un vettore, slice, stringa, mappa o canale. + // range restituisce uno (per i canali) o due valori (vettore, slice, stringa, mappa). for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} { // per ogni coppia dentro la mappa, stampa chiave e valore fmt.Printf("chiave=%s, valore=%d\n", chiave, valore) @@ -236,7 +236,7 @@ func imparaControlloDiFlusso() { // Inoltre le funzioni letterali possono essere definite e chiamate // inline, col ruolo di parametri di funzione, a patto che: // a) la funzione letterale venga chiamata subito (), - // b) il valore ritornato è in accordo con il tipo dell'argomento. + // b) il valore restituito è in accordo con il tipo dell'argomento. fmt.Println("Somma e raddoppia due numeri: ", func(a, b int) int { return (a + b) * 2 @@ -247,7 +247,7 @@ func imparaControlloDiFlusso() { goto amore amore: - imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente! + imparaFabbricaDiFunzioni() // Una funzione che restituisce un'altra funzione è divertente! imparaDefer() // Un tour veloce di una parola chiave importante. imparaInterfacce() // Arriva la roba buona! } @@ -271,7 +271,7 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { func imparaDefer() (ok bool) { // Le istruzioni dette "deferred" (rinviate) sono eseguite - // appena prima che la funzione ritorni. + // appena prima che la funzione abbia termine. defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") defer fmt.Println("\nQuesta riga viene stampata per prima perché") // defer viene usato di solito per chiudere un file, così la funzione che -- cgit v1.2.3 From f21a5f061b757223456edc632bb807e046bc5bf8 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Fri, 27 Oct 2017 20:53:15 +0200 Subject: [rst/it] Improve wording --- it-it/rst-it.html.markdown | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown index 8947c738..a834e899 100644 --- a/it-it/rst-it.html.markdown +++ b/it-it/rst-it.html.markdown @@ -6,10 +6,12 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] translators: - ["Ale46", "https://github.com/Ale46"] + - ["Chris54721", "https://chris54721.net"] lang: it-it --- -RST è un formato di file formalmente creato dalla comunità Python per scrivere documentazione (e quindi fa parte di Docutils). +RST (Restructured Text) è un formato di file inizialmente creato dalla comunità Python +per la documentazione (per questo motivo appartiene a Docutils). I file RST sono semplici file di testo con una sintassi leggera (in confronto all'HTML). @@ -23,7 +25,7 @@ Per usare Restructured Text, sarà necessario installare [Python](http://www.pyt $ easy_install docutils ``` -O se il tuo sistema ha `pip`, puoi usare anche lui: +Oppure, se hai `pip` installato sul tuo sistema: ```bash $ pip install docutils @@ -32,7 +34,7 @@ $ pip install docutils ## Sintassi del file -Un semplice esempio della sintassi del file: +Ecco un semplice esempio della sintassi RST: ``` .. Le righe che iniziano con due punti sono comandi speciali. Ma se non è possibile trovare alcun comando, la riga viene considerata come un commento @@ -41,16 +43,16 @@ Un semplice esempio della sintassi del file: I titoli principali sono scritti utilizzando caratteri di uguale, sopra e sotto =============================================================================== -Si noti che devono esistere tanti caratteri di uguale quanti sono i caratteri del titolo. +Si noti che devono esserci tanti caratteri di uguale quanti caratteri del titolo. -Anche il titolo è sottolineato con caratteri di uguale -====================================================== +Anche i titoli normali usano caratteri di uguale, ma solo sotto +=============================================================== -Sottotitoli con i trattini --------------------------- +I sottotitoli usano i trattini +------------------------------ -E sotto-sottotitoli con tildi -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +E i sotto-sottotitoli le tildi +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Puoi inserire il testo in *corsivo* o in **grassetto**, puoi "contrassegnare" il testo come codice con un doppio apice ``: `` print () ``. @@ -60,13 +62,13 @@ Le liste sono semplici come in Markdown: - Secondo elemento      - Sottoelemento -o +oppure * Primo elemento * Secondo elemento      * Sottoelemento -Le tabelle sono davvero facili da scrivere: +Le tabelle sono molto semplici da inserire: =========== ======== Stato Capitale @@ -75,22 +77,21 @@ Francia Parigi Giappone Tokio =========== ======== -Le tabelle più complesse possono essere fatte facilmente (colonne e/o righe unite) ma ti suggerisco di leggere il documento completo per questo :) +Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o righe unite) ma ti suggerisco di leggere la documentazione completa per questo :) Esistono diversi modi per creare collegamenti: -- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo modo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). +- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). - Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento) -- Facendo un collegamento simile a Markdown: `Github `_ . +- Utilizzando una sintassi simile a Markdown: `Github `_ . .. _Github https://github.com/ ``` - ## Come usarlo -RST viene fornito con docutils che dispone di `rst2html`, per esempio: +RST viene fornito con docutils, che dispone di `rst2html`, per esempio: ```bash $ rst2html miofile.rst output.html -- cgit v1.2.3 From 6800d632b179661a8902db748fea50b7012e8208 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 15:50:49 -0400 Subject: Cleaning up whitespace --- vim.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/vim.html.markdown b/vim.html.markdown index 7723136f..6fc52564 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -8,9 +8,9 @@ filename: LearnVim.txt [Vim](http://www.vim.org) -(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text -editor designed for speed and increased productivity, and is ubiquitous in most -unix-based systems. It has numerous keybindings for speedy navigation to +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text +editor designed for speed and increased productivity, and is ubiquitous in most +unix-based systems. It has numerous keybindings for speedy navigation to specific points in the file, and for fast editing. ## Basics of navigating Vim @@ -51,12 +51,12 @@ specific points in the file, and for fast editing. # Jumping to characters f # Jump forward and land on - t # Jump forward and land right before + t # Jump forward and land right before - # For example, + # For example, f< # Jump forward and land on < t< # Jump forward and land right before < - + # Moving by word w # Move forward by one word @@ -77,15 +77,15 @@ specific points in the file, and for fast editing. Vim is based on the concept on **modes**. -Command Mode - vim starts up in this mode, used to navigate and write commands -Insert Mode - used to make changes in your file -Visual Mode - used to highlight text and do operations to them +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` i # Puts vim into insert mode, before the cursor position a # Puts vim into insert mode, after the cursor position - v # Puts vim into visual mode + v # Puts vim into visual mode : # Puts vim into ex mode # 'Escapes' from whichever mode you're in, into Command mode @@ -102,18 +102,18 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm ## The 'Grammar' of vim -Vim can be thought of as a set of commands in a +Vim can be thought of as a set of commands in a 'Verb-Modifier-Noun' format, where: -Verb - your action -Modifier - how you're doing your action +Verb - your action +Modifier - how you're doing your action Noun - the object on which your action acts on A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - + d # Delete c # Change y # Yank (copy) @@ -135,7 +135,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': s # Sentence p # Paragraph b # Block - + # Sample 'sentences' or commands d2w # Delete 2 words @@ -180,7 +180,7 @@ Here's a sample ~/.vimrc file: ``` " Example ~/.vimrc -" 2015.10 +" 2015.10 " Required for vim to be iMproved set nocompatible -- cgit v1.2.3 From 437adfa5a4f07dfbae9e54c258fb0f8815a6c2dc Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 15:51:05 -0400 Subject: Adding help documentation --- vim.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/vim.html.markdown b/vim.html.markdown index 6fc52564..15144b8d 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -17,6 +17,7 @@ specific points in the file, and for fast editing. ``` vim # Open in vim + :help # Open up built-in help docs about if any exists :q # Quit vim :w # Save current file :wq # Save file and quit vim @@ -73,6 +74,15 @@ specific points in the file, and for fast editing. L # Move to the bottom of the screen ``` +## Help docs: + +Vim has built in help documentation that can accessed with `:help `. +For example `:help navigation` will pull up documentation about how to navigate +your workspace! + +`:help` can also be used without an option. This will bring up a default help dialog +that aims to make getting started with vim more approachable! + ## Modes: Vim is based on the concept on **modes**. -- cgit v1.2.3 From 575dc7c0184978f73c4327c5f27f1c41c090fa5a Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 16:09:35 -0400 Subject: Adding missing semicolons --- javascript.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c8a52d..4ed8f849 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -103,7 +103,7 @@ false; // ... which works with more than just strings "1, 2, " + 3; // = "1, 2, 3" -"Hello " + ["world", "!"] // = "Hello world,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // and are compared with < and > "a" < "b"; // = true @@ -222,7 +222,7 @@ while (true){ var input; do { input = getInput(); -} while (!isValid(input)) +} while (!isValid(input)); // The `for` loop is the same as C and Java: // initialization; continue condition; iteration. @@ -293,7 +293,7 @@ myFunction("foo"); // = "FOO" // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction(){ return // <- semicolon automatically inserted here - {thisIsAn: 'object literal'} + {thisIsAn: 'object literal'}; } myFunction(); // = undefined @@ -388,7 +388,7 @@ myFunc(); // = undefined // through `this`, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); -} +}; myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" @@ -397,7 +397,7 @@ myObj.myOtherFunc(); // = "HELLO WORLD!" var anotherFunc = function(s){ return this.myString + s; -} +}; anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // The `apply` function is nearly identical, but takes an array for an argument @@ -420,7 +420,7 @@ boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" // `bind` can also be used to partially apply (curry) a function. -var product = function(a, b){ return a * b; } +var product = function(a, b){ return a * b; }; var doubler = product.bind(this, 2); doubler(8); // = 16 @@ -430,11 +430,11 @@ doubler(8); // = 16 var MyConstructor = function(){ this.myNumber = 5; -} +}; myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Unlike most other popular object-oriented languages, JavaScript has no +// Unlike most other popular object-oriented languages, JavaScript has no // concept of 'instances' created from 'class' blueprints; instead, JavaScript // combines instantiation and inheritance into a single concept: a 'prototype'. @@ -451,7 +451,7 @@ var myObj = { var myPrototype = { meaningOfLife: 42, myFunc: function(){ - return this.myString.toLowerCase() + return this.myString.toLowerCase(); } }; @@ -515,7 +515,7 @@ MyConstructor.prototype = { }; var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 +myNewObj2.myNumber = 6; myNewObj2.getMyNumber(); // = 6 // Built-in types like strings and numbers also have constructors that create @@ -540,7 +540,7 @@ if (new Number(0)){ // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); -} +}; "abc".firstCharacter(); // = "a" // This fact is often used in "polyfilling", which is implementing newer @@ -556,7 +556,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists Constructor.prototype = proto; // then use it to create a new, appropriately-prototyped object return new Constructor(); - } + }; } ``` -- cgit v1.2.3 From 56a82546e9196a94a0085eae0abd0578702a578f Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Sat, 28 Oct 2017 15:36:34 +1030 Subject: Improve comment about final modifier --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 7b59b085..73e4bd2e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -173,7 +173,7 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // final variables can't be reassigned to another object, + // final variables can't be reassigned, final int HOURS_I_WORK_PER_WEEK = 9001; // but they can be initialized later. final double E; -- cgit v1.2.3 From 32090679c2a6a79933fa94f36a7dcddd22a20897 Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Sat, 28 Oct 2017 16:09:07 +1030 Subject: Improve comments on abstract classes --- java.html.markdown | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 73e4bd2e..621d500c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -703,15 +703,21 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // // Method declarations // } -// Marking a class as abstract means that it contains at least one abstract -// method that must be defined in a child class. Similar to interfaces, abstract -// classes cannot be instantiated, but instead must be extended and the abstract -// methods defined. Different from interfaces, abstract classes can contain a -// mixture of concrete and abstract methods. Methods in an interface cannot -// have a body, unless the method is static, and variables are final by default, -// unlike an abstract class. Also abstract classes CAN have the "main" method. +// Abstract Classes cannot be instantiated. +// Abstract classes may define abstract methods. +// Abstract methods have no body and are marked abstract +// Non-abstract child classes must @Override all abstract methods +// from their super-classes. +// Abstract classes can be useful when combining repetitive logic +// with customised behavior, but as Abstract classes require +// inheritance, they violate "Composition over inheritance" +// so consider other approaches using composition. +// https://en.wikipedia.org/wiki/Composition_over_inheritance + public abstract class Animal { + private int age; + public abstract void makeSound(); // Method can have a body @@ -722,17 +728,12 @@ public abstract class Animal age = 30; } - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - private int age; - public void printAge() { System.out.println(age); } - // Abstract classes can have main function. + // Abstract classes can have main method. public static void main(String[] args) { System.out.println("I am abstract"); -- cgit v1.2.3 From 0aaae2653cc4edef745c7f0de2b5c038097337d2 Mon Sep 17 00:00:00 2001 From: LukaxFeh <32396925+LukaxFeh@users.noreply.github.com> Date: Sun, 29 Oct 2017 13:09:01 -0200 Subject: Fix file names in french (#2984) * fix file name * fix file names * fix file names * fix file names * fix file names * fix file names --- fr-fr/d-fr.html.markdown | 264 +++++++++++++++ fr-fr/d.html.markdown | 264 --------------- fr-fr/haskell-fr.html.markdown | 431 +++++++++++++++++++++++++ fr-fr/haskell.html.markdown | 431 ------------------------- fr-fr/markdown-fr.html.markdown | 289 +++++++++++++++++ fr-fr/markdown.html.markdown | 289 ----------------- fr-fr/php-fr.html.markdown | 697 ++++++++++++++++++++++++++++++++++++++++ fr-fr/php.html.markdown | 697 ---------------------------------------- fr-fr/scala-fr.html.markdown | 460 ++++++++++++++++++++++++++ fr-fr/scala.html.markdown | 460 -------------------------- fr-fr/vim-fr.html.markdown | 239 ++++++++++++++ fr-fr/vim.html.markdown | 239 -------------- 12 files changed, 2380 insertions(+), 2380 deletions(-) create mode 100644 fr-fr/d-fr.html.markdown delete mode 100644 fr-fr/d.html.markdown create mode 100644 fr-fr/haskell-fr.html.markdown delete mode 100644 fr-fr/haskell.html.markdown create mode 100644 fr-fr/markdown-fr.html.markdown delete mode 100644 fr-fr/markdown.html.markdown create mode 100644 fr-fr/php-fr.html.markdown delete mode 100644 fr-fr/php.html.markdown create mode 100644 fr-fr/scala-fr.html.markdown delete mode 100644 fr-fr/scala.html.markdown create mode 100644 fr-fr/vim-fr.html.markdown delete mode 100644 fr-fr/vim.html.markdown diff --git a/fr-fr/d-fr.html.markdown b/fr-fr/d-fr.html.markdown new file mode 100644 index 00000000..8d98f9dc --- /dev/null +++ b/fr-fr/d-fr.html.markdown @@ -0,0 +1,264 @@ +--- +language: D +filename: learnd-fr.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: + - ["Quentin Ladeveze", "aceawan.eu"] +lang: fr-fr +--- + +```c +// Commençons par un classique +module hello; + +import std.stdio; + +// args n'est pas obligatoire +void main(string[] args) { + writeln("Bonjour le monde !"); +} +``` + +Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a +de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). +D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient +des fonctionnalités aussi bien de bas niveau que de haut niveau. + +D est activement développé par de nombreuses personnes très intelligents, guidées par +[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et +[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). +Après cette petite introduction, jetons un coup d'oeil à quelques exemples. + +```c +import std.stdio; + +void main() { + //Les conditions et les boucles sont classiques. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. + auto n = 1; + + // On peut faciliter la lecture des valeurs numériques + // en y insérant des `_`. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For et while sont très utiles, mais en D, on préfère foreach. + // Les deux points : '..', créent un intervalle continu de valeurs + // incluant la première mais excluant la dernière. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // On peut également utiliser foreach_reverse pour itérer à l'envers. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("Non !"); + } + } +} +``` +On peut définir de nouveaux types avec les mots-clés `struct`, `class`, +`union` et `enum`. Ces types sont passés à la fonction par valeur (ils sont copiés) +De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. + +```c +// Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '' + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // S'il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de mettre des parenthèses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Utilisez alias pour créer des abreviations pour les types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// On peut tout aussi bien créer des templates de function ! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé +// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. +// Ici ils seront toujours passés par référence à 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Avec les templates, on peut également passer des valeurs en paramètres. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // T est 'int' par défaut + +``` +À propos de classes, parlons des propriétés. Une propriété est, en gros, +une méthode qui peut se comporter comme une lvalue. On peut donc utiliser +la syntaxe des structures classiques (`struct.x = 7`) comme si il +s'agissait de méthodes getter ou setter. + +```c +// Considérons une classe paramétrée avec les types 'T' et 'U' +class MyClass(T, U) { + T _data; + U _other; +} + +// Et des méthodes "getter" et "setter" comme suit: +class MyClass(T, U) { + T _data; + U _other; + + // Les constructeurs s'appellent toujours 'this'. + this(T t, U u) { + // Ceci va appeller les setters ci-dessous. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// Et on l'utilise de cette façon: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) + import std.stdio; + + // On appelle les getters pour obtenir les valeurs. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // On appelle les setter pour assigner de nouvelles valeurs. + mc.data = 8; + mc.other = "eight"; + + // On appelle les setter pour obtenir les nouvelles valeurs. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` +Avec les propriétés, on peut construire nos setters et nos getters +comme on le souhaite, tout en gardant une syntaxe très propre, +comme si on accédait directement à des membres de la classe. + +Les autres fonctionnalités orientées objets à notre disposition +incluent les interfaces, les classes abstraites, et la surcharge +de méthodes. D gère l'héritage comme Java: On ne peut hériter que +d'une seule classe et implémenter autant d'interface que voulu. + +Nous venons d'explorer les fonctionnalités objet du D, mais changeons +un peu de domaine. D permet la programmation fonctionelle, avec les fonctions +de premier ordre, les fonctions `pures` et les données immuables. +De plus, tout vos algorithmes fonctionels favoris (map, reduce, filter) +sont disponibles dans le module `std.algorithm`. + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // construit un intervalle excluant la dernière valeur. + +void main() { + // On veut un algorithme qui affiche la somme de la liste des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! + + // On se contente de passer des expressions lambda en paramètre à des templates. + // On peut fournir au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Vous voyez qu'on a calculé `num` comme on le ferait en haskell par exemple ? +C'est grâce à une innovation de D qu'on appelle "Uniform Function Call Syntax". +Avec l'UFCS, on peut choisir d'écrire un appel à une fonction de manière +classique, ou comme un appel à une méthode. Walter Brighter a écrit un +article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Pour faire court, on peut appeller une fonction dont le premier paramètre +est de type A, comme si c'était une méthode de A. + +J'aime le parallélisme. Vous aimez le parallélisme ? Bien sûr que vous aimez ça. +Voyons comment on le fait en D ! + +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // On veut calculer la racine carrée de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. + auto arr = new double[1_000_000]; + + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown deleted file mode 100644 index 8d98f9dc..00000000 --- a/fr-fr/d.html.markdown +++ /dev/null @@ -1,264 +0,0 @@ ---- -language: D -filename: learnd-fr.d -contributors: - - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] -translators: - - ["Quentin Ladeveze", "aceawan.eu"] -lang: fr-fr ---- - -```c -// Commençons par un classique -module hello; - -import std.stdio; - -// args n'est pas obligatoire -void main(string[] args) { - writeln("Bonjour le monde !"); -} -``` - -Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a -de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). -D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient -des fonctionnalités aussi bien de bas niveau que de haut niveau. - -D est activement développé par de nombreuses personnes très intelligents, guidées par -[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et -[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). -Après cette petite introduction, jetons un coup d'oeil à quelques exemples. - -```c -import std.stdio; - -void main() { - //Les conditions et les boucles sont classiques. - for(int i = 0; i < 10000; i++) { - writeln(i); - } - - // On peut utiliser auto pour inférer automatiquement le - // type d'une variable. - auto n = 1; - - // On peut faciliter la lecture des valeurs numériques - // en y insérant des `_`. - while(n < 10_000) { - n += n; - } - - do { - n -= (n / 2); - } while(n > 0); - - // For et while sont très utiles, mais en D, on préfère foreach. - // Les deux points : '..', créent un intervalle continu de valeurs - // incluant la première mais excluant la dernière. - foreach(i; 1..1_000_000) { - if(n % 2 == 0) - writeln(i); - } - - // On peut également utiliser foreach_reverse pour itérer à l'envers. - foreach_reverse(i; 1..int.max) { - if(n % 2 == 1) { - writeln(i); - } else { - writeln("Non !"); - } - } -} -``` -On peut définir de nouveaux types avec les mots-clés `struct`, `class`, -`union` et `enum`. Ces types sont passés à la fonction par valeur (ils sont copiés) -De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. - -```c -// Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. -struct LinkedList(T) { - T data = null; - - // Utilisez '!' pour instancier un type paramétré. - // Encore une fois semblable à '' - LinkedList!(T)* next; -} - -class BinTree(T) { - T data = null; - - // S'il n'y a qu'un seul paramètre de template, - // on peut s'abstenir de mettre des parenthèses. - BinTree!T left; - BinTree!T right; -} - -enum Day { - Sunday, - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, -} - -// Utilisez alias pour créer des abreviations pour les types. -alias IntList = LinkedList!int; -alias NumTree = BinTree!double; - -// On peut tout aussi bien créer des templates de function ! -T max(T)(T a, T b) { - if(a < b) - return b; - - return a; -} - -// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé -// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. -// Ici ils seront toujours passés par référence à 'swap()'. -void swap(T)(ref T a, ref T b) { - auto temp = a; - - a = b; - b = temp; -} - -// Avec les templates, on peut également passer des valeurs en paramètres. -class Matrix(uint m, uint n, T = int) { - T[m] rows; - T[n] columns; -} - -auto mat = new Matrix!(3, 3); // T est 'int' par défaut - -``` -À propos de classes, parlons des propriétés. Une propriété est, en gros, -une méthode qui peut se comporter comme une lvalue. On peut donc utiliser -la syntaxe des structures classiques (`struct.x = 7`) comme si il -s'agissait de méthodes getter ou setter. - -```c -// Considérons une classe paramétrée avec les types 'T' et 'U' -class MyClass(T, U) { - T _data; - U _other; -} - -// Et des méthodes "getter" et "setter" comme suit: -class MyClass(T, U) { - T _data; - U _other; - - // Les constructeurs s'appellent toujours 'this'. - this(T t, U u) { - // Ceci va appeller les setters ci-dessous. - data = t; - other = u; - } - - // getters - @property T data() { - return _data; - } - - @property U other() { - return _other; - } - - // setters - @property void data(T t) { - _data = t; - } - - @property void other(U u) { - _other = u; - } -} - -// Et on l'utilise de cette façon: -void main() { - auto mc = new MyClass!(int, string)(7, "seven"); - - // Importer le module 'stdio' de la bibliothèque standard permet - // d'écrire dans la console (les imports peuvent être locaux à une portée) - import std.stdio; - - // On appelle les getters pour obtenir les valeurs. - writefln("Earlier: data = %d, str = %s", mc.data, mc.other); - - // On appelle les setter pour assigner de nouvelles valeurs. - mc.data = 8; - mc.other = "eight"; - - // On appelle les setter pour obtenir les nouvelles valeurs. - writefln("Later: data = %d, str = %s", mc.data, mc.other); -} -``` -Avec les propriétés, on peut construire nos setters et nos getters -comme on le souhaite, tout en gardant une syntaxe très propre, -comme si on accédait directement à des membres de la classe. - -Les autres fonctionnalités orientées objets à notre disposition -incluent les interfaces, les classes abstraites, et la surcharge -de méthodes. D gère l'héritage comme Java: On ne peut hériter que -d'une seule classe et implémenter autant d'interface que voulu. - -Nous venons d'explorer les fonctionnalités objet du D, mais changeons -un peu de domaine. D permet la programmation fonctionelle, avec les fonctions -de premier ordre, les fonctions `pures` et les données immuables. -De plus, tout vos algorithmes fonctionels favoris (map, reduce, filter) -sont disponibles dans le module `std.algorithm`. - -```c -import std.algorithm : map, filter, reduce; -import std.range : iota; // construit un intervalle excluant la dernière valeur. - -void main() { - // On veut un algorithme qui affiche la somme de la liste des carrés - // des entiers paires de 1 à 100. Un jeu d'enfant ! - - // On se contente de passer des expressions lambda en paramètre à des templates. - // On peut fournir au template n'importe quelle fonction, mais dans notre - // cas, les lambdas sont pratiques. - auto num = iota(1, 101).filter!(x => x % 2 == 0) - .map!(y => y ^^ 2) - .reduce!((a, b) => a + b); - - writeln(num); -} -``` - -Vous voyez qu'on a calculé `num` comme on le ferait en haskell par exemple ? -C'est grâce à une innovation de D qu'on appelle "Uniform Function Call Syntax". -Avec l'UFCS, on peut choisir d'écrire un appel à une fonction de manière -classique, ou comme un appel à une méthode. Walter Brighter a écrit un -article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) -Pour faire court, on peut appeller une fonction dont le premier paramètre -est de type A, comme si c'était une méthode de A. - -J'aime le parallélisme. Vous aimez le parallélisme ? Bien sûr que vous aimez ça. -Voyons comment on le fait en D ! - -```c -import std.stdio; -import std.parallelism : parallel; -import std.math : sqrt; - -void main() { - // On veut calculer la racine carrée de tous les nombres - // dans notre tableau, et profiter de tous les coeurs - // à notre disposition. - auto arr = new double[1_000_000]; - - // On utilise un index et une référence à chaque élément du tableau. - // On appelle juste la fonction parallel sur notre tableau ! - foreach(i, ref elem; parallel(arr)) { - ref = sqrt(i + 1.0); - } -} - - -``` diff --git a/fr-fr/haskell-fr.html.markdown b/fr-fr/haskell-fr.html.markdown new file mode 100644 index 00000000..a34dc098 --- /dev/null +++ b/fr-fr/haskell-fr.html.markdown @@ -0,0 +1,431 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["David Baumgartner", "http://davidbaumgartner.ch"] +lang: fr-fr +filename: learnhaskell-fr.hs +--- + +Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. + +```haskell +-- Un commentaire en une ligne commence avec deux tirets. +{- Un commentaire sur plusieurs lignes peut être contenu dans +un bloc de cette façon. +-} + +---------------------------------------------------- +-- 1. Types de données primitifs et opérateurs +---------------------------------------------------- + +-- Vous avez les nombres +3 -- 3 + +-- Les maths sont comme vous vous y attendez +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- La division n'est pas entière par défaut +35 / 4 -- 8.75 + +-- division entière +35 `div` 4 -- 8 + +-- Les booléens sont primitifs +True +False + +-- Opérations avec les booléens +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. +-- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous +-- les arguments sont juste listés après la fonction. Le schéma général est +-- donc : +-- func arg1 arg2 arg3... +-- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. + +-- Caractères et chaînes de caractère +"Ceci est une chaîne de caractère." +'a' -- caractère +'Vous ne pouvez pas utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! + +-- Les chaînes peuvent être concaténées +"Hello " ++ "world!" -- "Hello world!" + +-- Une chaîne de caractère est *réellement* une liste +"Ceci est une chaîne." !! 0 -- 'C' + + +---------------------------------------------------- +-- 2. Listes et tuples +---------------------------------------------------- + +-- Tous les éléments d'une liste doit avoir le même type. +-- les deux lignes suivantes sont semblables +[1, 2, 3, 4, 5] +[1..5] + +-- Il y a aussi des listes infinies en Haskell ! +[1..] -- une liste de tous les nombres naturels + +-- Les listes infinies fonctionnent parce que Haskell est « paresseux »: +-- ça veut dire qu'il n'évalue que ce qui a besoin de l'être. Vous pouvez +-- donc vous demander le 1000e élément de votre liste et il vous le donnera : + +[1..] !! 999 -- 1000 + +-- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste +-- de cette liste « infinie » n'existe pas encore ! En fait, Haskell ne va jamais +-- le faire à moins qu'il ne le doive. + +-- Adjoindre deux listes +[1..5] ++ [6..10] + +-- ajouter au début de la liste +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- l'indice d'une liste +[0..] !! 5 -- 5 + +-- d'autres opérations sur les listes +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +--liste en compréhension +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +--avec un conditionnel +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Chaque élément d'un tuple peut être d'un type différent, mais un +-- tuple a une longueur fixée. +-- Un tuple : +("haskell", 1) + +-- accéder aux éléments d'un tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- Une simple fonction qui prend deux paramètres +add a b = a + b + +-- Notez que si vous utilisez ghci (l'interpréteur Haskell) +-- vous devrez utiliser `let`. Par exemple : +-- let add a b = a + b + +-- Utiliser une fonction +add 1 2 -- 3 + +-- Vous pouvez également mettre le nom de la fonction entre les +-- deux arguments avec des accents graves : +1 `add` 2 -- 3 + +-- Vous pouvez également définir des fonctions qui n'ont pas de +-- lettres ! Ça vous laisse créer vos propres opérateurs ! Voilà +-- un opérateur qui fait une division entière : +(//) a b = a `div` b +35 // 4 -- 8 + +-- Gardes : Une façon de gérer la valeur de vos arguments en amont +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Le filtrage par motif est similaire. Là, on a donné trois +-- définitions différentes de `fib`. Haskell appellera automatiquement +-- la première fonction qui correspond au motif de la valeur. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Filtrage par motif sur un tuple. +foo (x, y) = (x + 1, y + 2) + +-- Filtrage par motif sur des listes. Ici, `x` est le premier +-- élément de la liste, et `xs` le reste. On peut écrire notre +-- propre fonction `map` : +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Les fonctions anonymes sont créées avec des barres obliques +-- inverses, suivies de tous les arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Une utilisation de fold (appelée `inject` dans quelques autres +-- langages) avec comme paramètre une fonction anonyme. +-- `foldl1` veut dire fold left -- soit littéralement pli gauche -- +-- et utilise la première valeur de la liste comme accumulateur. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Plus de fonctions +---------------------------------------------------- + +-- curryfication : si vous n'appliquez pas tous les arguments à une +-- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne +-- une fonction qui prend le reste des arguments. + +add a b = a + b +foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 +foo 5 -- 15 + +-- Une autre façon de l'écrire +foo = (+10) +foo 5 -- 15 + +-- Composition de fonctions +-- la fonction (.) enchaîne deux fonctions. +-- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute +-- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fixation de priorité +-- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité +-- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite +-- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` +-- pour vous débarrasser de beaucoup de parenthèses : + +-- avant +(even (fib 7)) -- False + +-- ensuite +even . fib $ 7 -- False + +---------------------------------------------------- +-- 5. Signature de type +---------------------------------------------------- + +-- Haskell a un système de types très strict : par exemple, tout a un type. + +-- Quelques types simples : +5 :: Integer +"hello" :: String +True :: Bool + +-- Les fonctions ont également des types. +-- `not` prend un booléen et retourne un booléen. +-- not :: Bool -> Bool + +-- Voilà une fonction qui prend deux paramètres. +-- add :: Integer -> Integer -> Integer + +-- Quand vous définissez une valeur (souvenez-vous, tout est valeur en +-- Haskell), une bonne pratique est d'écrire son type explicitement +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Flux de contrôle et structures conditionnelles +---------------------------------------------------- + +-- structure conditionnelle if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- les structures if peuvent être écrites sur plusieurs lignes +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- les structures case : voilà comment vous pourriez analyser les arguments de +-- ligne de commande +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell n'a pas de boucles parce qu'il utilise la récursion. +-- `map` applique une fonction sur chaque élément d'une liste + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- vous pouvez créer une fonction `for` en utilisant `map` +for array func = map func array + +-- et l'utiliser +for [0..5] $ \i -> show i + +-- nous aurions pu l'écrire également ainsi +for [0..5] show + +-- vous pouvez utiliser foldl et foldr pour +-- réduire une liste +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- C'est donc la même chose que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl évalue de gauche à droite, foldr +-- de droite à gauche +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Et c'est équivalent à +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Types de données +---------------------------------------------------- + +-- Vous pouvez écrire vos propres types de données en Haskell + +data Couleur = Rouge | Bleu | Vert + +-- Et maintenant l'utiliser dans une fonction + + +say :: Couleur -> String +say Rouge = "Vous êtes Rouge !" +say Bleu = "Vous êtes Bleu !" +say Vert = "Vous êtes Vert !" + +-- Vos types peuvent également avoir des paramètres + +data Maybe a = Nothing | Just a + +-- Tous les exemples ci-dessous sont issus du type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Tandis que l'IO ne peut pas être totalement expliqué pleinement +-- sans que les monades ne le soient, il n'est pas difficile +-- d'expliquer suffisamment pour commencer. + +-- Quand un programme en Haskell est exécuté, la fonction `main` +-- est appelée. Il doit retourner une valeur de type `IO ()`. +-- Par exemple : + +main :: IO () +main = putStrLn $ "Bonjour, le ciel ! " ++ (say Blue) +-- putStrLn a comme type String -> IO () + +-- La façon la plus simple pour faire de l'IO est de faire un programme +-- fonction de String vers String. La fonction +-- interact :: (String -> String) -> IO () +-- prend un texte, applique une fonction et affiche le résultat. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Vous pouvez considérer qu'une valeur de type `IO ()` représente +-- une séquence d'actions que l'ordinateur exécute, un peu comme +-- dans un langage impératif. On peut utiliser la structure `do` +-- pour enchaîner des actions. Par exemple : + +sayHello :: IO () +sayHello = do + putStrLn "Quel est ton nom ?" + name <- getLine -- prend une ligne et assigne sa valeur à `name` + putStrLn $ "Salut, " ++ name + +-- Exercice : écrire votre propre version d'`interact` qui ne fait +-- que de lire une ligne d'entrée. + +-- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule +-- action qui sera exécutée est la valeur de `main`. +-- Pour lancer `sayHello`, commentez l'ancienne définition de `main` +-- et remplacez-le par : +-- main = sayHello + +-- Essaions de mieux comprendre comment la fonction `getLine` que +-- nous venons d'utiliser. Son type est : +-- getLine :: IO String +-- vous pouvez considérer le type `IO a` comme un programme que +-- le programme va générer comme une valeur de type `a` quand +-- il sera exécuté. On peut l'enregistrer et la réutiliser en +-- utilisant `<-`. On peut aussi faire nos propres actions +-- de type `IO String` : + +action :: IO String +action = do + putStrLn "C'est une ligne. Heu" + input1 <- getLine + input2 <- getLine + -- Le type de la structure `do` est celui de sa dernière ligne. + -- `return` n'est pas un mot clef, mais simplement une fonction. + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- On peut maintenant l'utiliser comme on a utilisé `getLine` +-- tout à l'heure + +main'' = do + putStrLn "Je vais afficher deux lignes !" + result <- action + putStrLn result + putStrLn "C'était tout !" + +-- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise +-- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe +-- quelle fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) +-- devient marqué comme `IO` dans la signature de son type. Ça nous montre +-- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur +-- ou ne changent pas d'état) et quelles fonctions ne le sont pas. + +-- C'est une fonctionnalité très puissante, car il est facile d'exécuter +-- des fonctions pures simultanément, et donc la concurrence en Haskell +-- est très facile. + + +---------------------------------------------------- +-- 9. Le REPL de Haskell +---------------------------------------------------- + +-- Lancer le REPL en tapant `ghci`. +-- Vous pouvez maintenant taper du code Haskell. +-- Toutes les nouvelles valeurs peuvent être crées +-- avec `let` : + +let foo = 5 + +-- Vous pouvez voir le type de n'importe quelle valeur avec `:t` : + +>:t foo +foo :: Integer + +-- Vous pouvez également lancer des actions de type `IO ()` + +> sayHello +Quel est ton nom ? +Ami +Salut, Ami ! + +``` + +Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple : une implémentation de quicksort : + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). + +Vous pouvez trouver une approche beaucoup plus douce avec les excellents +[Learn you a Haskell](http://lyah.haskell.fr/) ou +[Real World Haskell (en)](http://book.realworldhaskell.org/). diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown deleted file mode 100644 index a34dc098..00000000 --- a/fr-fr/haskell.html.markdown +++ /dev/null @@ -1,431 +0,0 @@ ---- -language: Haskell -contributors: - - ["Adit Bhargava", "http://adit.io"] -translators: - - ["David Baumgartner", "http://davidbaumgartner.ch"] -lang: fr-fr -filename: learnhaskell-fr.hs ---- - -Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. - -```haskell --- Un commentaire en une ligne commence avec deux tirets. -{- Un commentaire sur plusieurs lignes peut être contenu dans -un bloc de cette façon. --} - ----------------------------------------------------- --- 1. Types de données primitifs et opérateurs ----------------------------------------------------- - --- Vous avez les nombres -3 -- 3 - --- Les maths sont comme vous vous y attendez -1 + 1 -- 2 -8 - 1 -- 7 -10 * 2 -- 20 -35 / 5 -- 7.0 - --- La division n'est pas entière par défaut -35 / 4 -- 8.75 - --- division entière -35 `div` 4 -- 8 - --- Les booléens sont primitifs -True -False - --- Opérations avec les booléens -not True -- False -not False -- True -1 == 1 -- True -1 /= 1 -- False -1 < 10 -- True - --- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. --- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous --- les arguments sont juste listés après la fonction. Le schéma général est --- donc : --- func arg1 arg2 arg3... --- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. - --- Caractères et chaînes de caractère -"Ceci est une chaîne de caractère." -'a' -- caractère -'Vous ne pouvez pas utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! - --- Les chaînes peuvent être concaténées -"Hello " ++ "world!" -- "Hello world!" - --- Une chaîne de caractère est *réellement* une liste -"Ceci est une chaîne." !! 0 -- 'C' - - ----------------------------------------------------- --- 2. Listes et tuples ----------------------------------------------------- - --- Tous les éléments d'une liste doit avoir le même type. --- les deux lignes suivantes sont semblables -[1, 2, 3, 4, 5] -[1..5] - --- Il y a aussi des listes infinies en Haskell ! -[1..] -- une liste de tous les nombres naturels - --- Les listes infinies fonctionnent parce que Haskell est « paresseux »: --- ça veut dire qu'il n'évalue que ce qui a besoin de l'être. Vous pouvez --- donc vous demander le 1000e élément de votre liste et il vous le donnera : - -[1..] !! 999 -- 1000 - --- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste --- de cette liste « infinie » n'existe pas encore ! En fait, Haskell ne va jamais --- le faire à moins qu'il ne le doive. - --- Adjoindre deux listes -[1..5] ++ [6..10] - --- ajouter au début de la liste -0:[1..5] -- [0, 1, 2, 3, 4, 5] - --- l'indice d'une liste -[0..] !! 5 -- 5 - --- d'autres opérations sur les listes -head [1..5] -- 1 -tail [1..5] -- [2, 3, 4, 5] -init [1..5] -- [1, 2, 3, 4] -last [1..5] -- 5 - ---liste en compréhension -[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] - ---avec un conditionnel -[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] - --- Chaque élément d'un tuple peut être d'un type différent, mais un --- tuple a une longueur fixée. --- Un tuple : -("haskell", 1) - --- accéder aux éléments d'un tuple -fst ("haskell", 1) -- "haskell" -snd ("haskell", 1) -- 1 - ----------------------------------------------------- --- 3. Functions ----------------------------------------------------- --- Une simple fonction qui prend deux paramètres -add a b = a + b - --- Notez que si vous utilisez ghci (l'interpréteur Haskell) --- vous devrez utiliser `let`. Par exemple : --- let add a b = a + b - --- Utiliser une fonction -add 1 2 -- 3 - --- Vous pouvez également mettre le nom de la fonction entre les --- deux arguments avec des accents graves : -1 `add` 2 -- 3 - --- Vous pouvez également définir des fonctions qui n'ont pas de --- lettres ! Ça vous laisse créer vos propres opérateurs ! Voilà --- un opérateur qui fait une division entière : -(//) a b = a `div` b -35 // 4 -- 8 - --- Gardes : Une façon de gérer la valeur de vos arguments en amont -fib x - | x < 2 = x - | otherwise = fib (x - 1) + fib (x - 2) - --- Le filtrage par motif est similaire. Là, on a donné trois --- définitions différentes de `fib`. Haskell appellera automatiquement --- la première fonction qui correspond au motif de la valeur. -fib 1 = 1 -fib 2 = 2 -fib x = fib (x - 1) + fib (x - 2) - --- Filtrage par motif sur un tuple. -foo (x, y) = (x + 1, y + 2) - --- Filtrage par motif sur des listes. Ici, `x` est le premier --- élément de la liste, et `xs` le reste. On peut écrire notre --- propre fonction `map` : -myMap func [] = [] -myMap func (x:xs) = func x:(myMap func xs) - --- Les fonctions anonymes sont créées avec des barres obliques --- inverses, suivies de tous les arguments. -myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] - --- Une utilisation de fold (appelée `inject` dans quelques autres --- langages) avec comme paramètre une fonction anonyme. --- `foldl1` veut dire fold left -- soit littéralement pli gauche -- --- et utilise la première valeur de la liste comme accumulateur. -foldl1 (\acc x -> acc + x) [1..5] -- 15 - ----------------------------------------------------- --- 4. Plus de fonctions ----------------------------------------------------- - --- curryfication : si vous n'appliquez pas tous les arguments à une --- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne --- une fonction qui prend le reste des arguments. - -add a b = a + b -foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 -foo 5 -- 15 - --- Une autre façon de l'écrire -foo = (+10) -foo 5 -- 15 - --- Composition de fonctions --- la fonction (.) enchaîne deux fonctions. --- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute --- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. -foo = (*5) . (+10) - --- (5 + 10) * 5 = 75 -foo 5 -- 75 - --- fixation de priorité --- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité --- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite --- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` --- pour vous débarrasser de beaucoup de parenthèses : - --- avant -(even (fib 7)) -- False - --- ensuite -even . fib $ 7 -- False - ----------------------------------------------------- --- 5. Signature de type ----------------------------------------------------- - --- Haskell a un système de types très strict : par exemple, tout a un type. - --- Quelques types simples : -5 :: Integer -"hello" :: String -True :: Bool - --- Les fonctions ont également des types. --- `not` prend un booléen et retourne un booléen. --- not :: Bool -> Bool - --- Voilà une fonction qui prend deux paramètres. --- add :: Integer -> Integer -> Integer - --- Quand vous définissez une valeur (souvenez-vous, tout est valeur en --- Haskell), une bonne pratique est d'écrire son type explicitement -double :: Integer -> Integer -double x = x * 2 - ----------------------------------------------------- --- 6. Flux de contrôle et structures conditionnelles ----------------------------------------------------- - --- structure conditionnelle if -haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" - --- les structures if peuvent être écrites sur plusieurs lignes -haskell = if 1 == 1 - then "awesome" - else "awful" - --- les structures case : voilà comment vous pourriez analyser les arguments de --- ligne de commande -case args of - "help" -> printHelp - "start" -> startProgram - _ -> putStrLn "bad args" - - --- Haskell n'a pas de boucles parce qu'il utilise la récursion. --- `map` applique une fonction sur chaque élément d'une liste - -map (*2) [1..5] -- [2, 4, 6, 8, 10] - --- vous pouvez créer une fonction `for` en utilisant `map` -for array func = map func array - --- et l'utiliser -for [0..5] $ \i -> show i - --- nous aurions pu l'écrire également ainsi -for [0..5] show - --- vous pouvez utiliser foldl et foldr pour --- réduire une liste --- foldl -foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 - --- C'est donc la même chose que -(2 * (2 * (2 * 4 + 1) + 2) + 3) - --- foldl évalue de gauche à droite, foldr --- de droite à gauche -foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 - --- Et c'est équivalent à -(2 * 3 + (2 * 2 + (2 * 1 + 4))) - ----------------------------------------------------- --- 7. Types de données ----------------------------------------------------- - --- Vous pouvez écrire vos propres types de données en Haskell - -data Couleur = Rouge | Bleu | Vert - --- Et maintenant l'utiliser dans une fonction - - -say :: Couleur -> String -say Rouge = "Vous êtes Rouge !" -say Bleu = "Vous êtes Bleu !" -say Vert = "Vous êtes Vert !" - --- Vos types peuvent également avoir des paramètres - -data Maybe a = Nothing | Just a - --- Tous les exemples ci-dessous sont issus du type Maybe -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` - ----------------------------------------------------- --- 8. Haskell IO ----------------------------------------------------- - --- Tandis que l'IO ne peut pas être totalement expliqué pleinement --- sans que les monades ne le soient, il n'est pas difficile --- d'expliquer suffisamment pour commencer. - --- Quand un programme en Haskell est exécuté, la fonction `main` --- est appelée. Il doit retourner une valeur de type `IO ()`. --- Par exemple : - -main :: IO () -main = putStrLn $ "Bonjour, le ciel ! " ++ (say Blue) --- putStrLn a comme type String -> IO () - --- La façon la plus simple pour faire de l'IO est de faire un programme --- fonction de String vers String. La fonction --- interact :: (String -> String) -> IO () --- prend un texte, applique une fonction et affiche le résultat. - -countLines :: String -> String -countLines = show . length . lines - -main' = interact countLines - --- Vous pouvez considérer qu'une valeur de type `IO ()` représente --- une séquence d'actions que l'ordinateur exécute, un peu comme --- dans un langage impératif. On peut utiliser la structure `do` --- pour enchaîner des actions. Par exemple : - -sayHello :: IO () -sayHello = do - putStrLn "Quel est ton nom ?" - name <- getLine -- prend une ligne et assigne sa valeur à `name` - putStrLn $ "Salut, " ++ name - --- Exercice : écrire votre propre version d'`interact` qui ne fait --- que de lire une ligne d'entrée. - --- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule --- action qui sera exécutée est la valeur de `main`. --- Pour lancer `sayHello`, commentez l'ancienne définition de `main` --- et remplacez-le par : --- main = sayHello - --- Essaions de mieux comprendre comment la fonction `getLine` que --- nous venons d'utiliser. Son type est : --- getLine :: IO String --- vous pouvez considérer le type `IO a` comme un programme que --- le programme va générer comme une valeur de type `a` quand --- il sera exécuté. On peut l'enregistrer et la réutiliser en --- utilisant `<-`. On peut aussi faire nos propres actions --- de type `IO String` : - -action :: IO String -action = do - putStrLn "C'est une ligne. Heu" - input1 <- getLine - input2 <- getLine - -- Le type de la structure `do` est celui de sa dernière ligne. - -- `return` n'est pas un mot clef, mais simplement une fonction. - return (input1 ++ "\n" ++ input2) -- return :: String -> IO String - --- On peut maintenant l'utiliser comme on a utilisé `getLine` --- tout à l'heure - -main'' = do - putStrLn "Je vais afficher deux lignes !" - result <- action - putStrLn result - putStrLn "C'était tout !" - --- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise --- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe --- quelle fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) --- devient marqué comme `IO` dans la signature de son type. Ça nous montre --- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur --- ou ne changent pas d'état) et quelles fonctions ne le sont pas. - --- C'est une fonctionnalité très puissante, car il est facile d'exécuter --- des fonctions pures simultanément, et donc la concurrence en Haskell --- est très facile. - - ----------------------------------------------------- --- 9. Le REPL de Haskell ----------------------------------------------------- - --- Lancer le REPL en tapant `ghci`. --- Vous pouvez maintenant taper du code Haskell. --- Toutes les nouvelles valeurs peuvent être crées --- avec `let` : - -let foo = 5 - --- Vous pouvez voir le type de n'importe quelle valeur avec `:t` : - ->:t foo -foo :: Integer - --- Vous pouvez également lancer des actions de type `IO ()` - -> sayHello -Quel est ton nom ? -Ami -Salut, Ami ! - -``` - -Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple : une implémentation de quicksort : - -```haskell -qsort [] = [] -qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater - where lesser = filter (< p) xs - greater = filter (>= p) xs -``` - -Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). - -Vous pouvez trouver une approche beaucoup plus douce avec les excellents -[Learn you a Haskell](http://lyah.haskell.fr/) ou -[Real World Haskell (en)](http://book.realworldhaskell.org/). diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown new file mode 100644 index 00000000..2e4e8461 --- /dev/null +++ b/fr-fr/markdown-fr.html.markdown @@ -0,0 +1,289 @@ +--- +language: markdown +contributors: +- ["Andrei Curelaru", "http://www.infinidad.fr"] +filename: markdown-fr.md +lang: fr-fr +--- + +Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe +facile à lire et à écrire, aisément convertible en HTML + (et beaucoup d'autres formats aussi à présent). + +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! + + +```markdown + + + + + + + + +# Ceci est un

+## Ceci est un

+### Ceci est un

+#### Ceci est un

+##### Ceci est un

+###### Ceci est un
+ + + +Ceci est un h1 +============= + +Ceci est un h2 +------------- + + + + +*Ce texte est en italique.* +_Celui-ci aussi._ + +**Ce texte est en gras.** +__Celui-là aussi.__ + +***Ce texte a les deux styles.*** +**_Pareil ici_** +*__Et là!__* + + + +~~Ce texte est barré avec strikethrough.~~ + + + +Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? + +Maintenant je suis dans le paragraphe 2. +Je suis toujours dans le paragraphe 2! + + +Puis là, eh oui, le paragraphe 3! + + + +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). + +Bigre, il y a un
au dessus de moi! + + + +> Ceci est une superbe citation. Vous pouvez même +> revenir à la ligne quand ça vous chante, et placer un `>` +> devant chaque bout de ligne faisant partie +> de la citation. +> La taille ne compte pas^^ tant que chaque ligne commence par un `>`. + +> Vous pouvez aussi utiliser plus d'un niveau +>> d'imbrication! +> Classe et facile, pas vrai? + + + + +* Item +* Item +* Un autre item + +ou + ++ Item ++ Item ++ Encore un item + +ou + +- Item +- Item +- Un dernier item + + + +1. Item un +2. Item deux +3. Item trois + + + +1. Item un +1. Item deux +1. Item trois + + + + +1. Item un +2. Item deux +3. Item trois +* Sub-item +* Sub-item +4. Item quatre + + + +Les [ ] ci dessous, n'ayant pas de [ x ], +deviendront des cases à cocher HTML non-cochées. + +- [ ] Première tache à réaliser. +- [ ] Une autre chose à faire. +La case suivante sera une case à cocher HTML cochée. +- [x] Ça ... c'est fait! + + + + + echo "Ça, c'est du Code!"; + var Ça = "aussi !"; + + + + my_array.each do |item| + puts item + end + + + +La fonction `run()` ne vous oblige pas à aller courir! + + + +\`\`\`ruby + +def foobar +puts "Hello world!" +end +\`\`\` + +<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub +va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> + + + + +*** +--- +- - - +**************** + + + + +[Clic moi!](http://test.com/) + + + +[Clic moi!](http://test.com/ "Lien vers Test.com") + + + +[En avant la musique](/music/). + + + +[Cliquez ici][link1] pour plus d'information! +[Regardez aussi par ici][foobar] si vous voulez. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + + + + + +[Ceci][] est un lien. + +[ceci]: http://ceciestunlien.com/ + + + + + + +![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") + + + +![Ceci est l'attribut ALT de l'image][monimage] + +[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." + + + + + est équivalent à : +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + +Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ + +Pour taper *ce texte* entouré d'astérisques mais pas en italique : +Tapez \*ce texte\*. + + + + +| Col1 | Col2 | Col3 | +| :----------- | :------: | ------------: | +| Alignement Gauche | Centé | Alignement Droite | +| bla | bla | bla | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ough que c'est moche | svp | arrêtez + + + +``` + +Pour plus d'information : + consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, + et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown deleted file mode 100644 index 2e4e8461..00000000 --- a/fr-fr/markdown.html.markdown +++ /dev/null @@ -1,289 +0,0 @@ ---- -language: markdown -contributors: -- ["Andrei Curelaru", "http://www.infinidad.fr"] -filename: markdown-fr.md -lang: fr-fr ---- - -Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML - (et beaucoup d'autres formats aussi à présent). - -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" -et envoyer des pull request! - - -```markdown - - - - - - - - -# Ceci est un

-## Ceci est un

-### Ceci est un

-#### Ceci est un

-##### Ceci est un

-###### Ceci est un
- - - -Ceci est un h1 -============= - -Ceci est un h2 -------------- - - - - -*Ce texte est en italique.* -_Celui-ci aussi._ - -**Ce texte est en gras.** -__Celui-là aussi.__ - -***Ce texte a les deux styles.*** -**_Pareil ici_** -*__Et là!__* - - - -~~Ce texte est barré avec strikethrough.~~ - - - -Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? - -Maintenant je suis dans le paragraphe 2. -Je suis toujours dans le paragraphe 2! - - -Puis là, eh oui, le paragraphe 3! - - - -J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). - -Bigre, il y a un
au dessus de moi! - - - -> Ceci est une superbe citation. Vous pouvez même -> revenir à la ligne quand ça vous chante, et placer un `>` -> devant chaque bout de ligne faisant partie -> de la citation. -> La taille ne compte pas^^ tant que chaque ligne commence par un `>`. - -> Vous pouvez aussi utiliser plus d'un niveau ->> d'imbrication! -> Classe et facile, pas vrai? - - - - -* Item -* Item -* Un autre item - -ou - -+ Item -+ Item -+ Encore un item - -ou - -- Item -- Item -- Un dernier item - - - -1. Item un -2. Item deux -3. Item trois - - - -1. Item un -1. Item deux -1. Item trois - - - - -1. Item un -2. Item deux -3. Item trois -* Sub-item -* Sub-item -4. Item quatre - - - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. - -- [ ] Première tache à réaliser. -- [ ] Une autre chose à faire. -La case suivante sera une case à cocher HTML cochée. -- [x] Ça ... c'est fait! - - - - - echo "Ça, c'est du Code!"; - var Ça = "aussi !"; - - - - my_array.each do |item| - puts item - end - - - -La fonction `run()` ne vous oblige pas à aller courir! - - - -\`\`\`ruby - -def foobar -puts "Hello world!" -end -\`\`\` - -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub -va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> - - - - -*** ---- -- - - -**************** - - - - -[Clic moi!](http://test.com/) - - - -[Clic moi!](http://test.com/ "Lien vers Test.com") - - - -[En avant la musique](/music/). - - - -[Cliquez ici][link1] pour plus d'information! -[Regardez aussi par ici][foobar] si vous voulez. - -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" - - - - - -[Ceci][] est un lien. - -[ceci]: http://ceciestunlien.com/ - - - - - - -![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") - - - -![Ceci est l'attribut ALT de l'image][monimage] - -[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." - - - - - est équivalent à : -[http://testwebsite.com/](http://testwebsite.com/) - - - - - - -Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ - -Pour taper *ce texte* entouré d'astérisques mais pas en italique : -Tapez \*ce texte\*. - - - - -| Col1 | Col2 | Col3 | -| :----------- | :------: | ------------: | -| Alignement Gauche | Centé | Alignement Droite | -| bla | bla | bla | - - - -Col 1 | Col2 | Col3 -:-- | :-: | --: -Ough que c'est moche | svp | arrêtez - - - -``` - -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. diff --git a/fr-fr/php-fr.html.markdown b/fr-fr/php-fr.html.markdown new file mode 100644 index 00000000..823630bd --- /dev/null +++ b/fr-fr/php-fr.html.markdown @@ -0,0 +1,697 @@ +--- +language: PHP +filename: php-fr.php +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Pascal Boutin", "http://pboutin.net/"] +lang: fr-fr +--- + +This document describes PHP 5+. + +```php + // Le code PHP doit être placé à l'intérieur de balises '' + +// Deux barres obliques amorcent un commentaire simple. + +# Le dièse aussi, bien que les barres obliques soient plus courantes + +/* + Les barres obliques et les astérisques peuvent être utilisés + pour faire un commentaire multi-lignes. +*/ + +// Utilisez "echo" ou "print" afficher une sortie +print('Hello '); // Affiche "Hello " sans retour à la ligne + +// Les parenthèses sont facultatives pour print et echo +echo "World\n"; // Affiche "World" avec un retour à la ligne + +// toutes les instructions doivent se terminer par un point-virgule + +// Tout ce qui se trouve en dehors des est automatiquement +// affiché en sortie +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (un 0 devant la valeur désigne une valeur octale) +$int4 = 0x0F; // => 15 (un 0x devant la valeur désigne une valeur hexadécimale) + +// Réels (floats, doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Suppression d'une variable +unset($int1); + +// Arithmétique +$sum = 1 + 1; // 2 (addition) +$difference = 2 - 1; // 1 (soustraction) +$product = 2 * 2; // 4 (produit) +$quotient = 2 / 1; // 2 (division) + +// Arithmétique (raccourcis) +$number = 0; +$number += 2; // Incrémente $number de 2 +echo $number++; // Affiche 2 (incrémente après l'évaluation) +echo ++$number; // Affiche 4 (incrémente avant l'évaluation) +$number /= $float; // Divise et assigne le quotient à $number + +// Les chaînes de caractères (strings) doivent être à +// l'intérieur d'une paire d'apostrophes +$sgl_quotes = '$String'; // => '$String' + +// Évitez les guillemets sauf pour inclure le contenu d'une autre variable +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Les caractères spéciaux sont seulement échappés avec des guillemets +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// En cas de besoin, placez la variable dans des accolades +$money = "I have $${number} in the bank."; + +// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes +// multi-lignes non-interprétées +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 a introduit une nouvelle syntaxe +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // affiche 1 + +// Dans une liste simple, l'index est automatiquement attribué en tant que clé +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Ajoute un élément à la fin du tableau +$array[] = 'Four'; + +// Retrait d'un élément du tableau +unset($array[3]); + +/******************************** + * Affichage + */ + +echo('Hello World!'); +// Affiche Hello World! dans stdout. +// Stdout est la page web si on exécute depuis un navigateur. + +print('Hello World!'); // Pareil à "écho" + +// Pour écho, vous n'avez pas besoin des parenthèses +echo 'Hello World!'; +print 'Hello World!'; // Pour print non plus + +$paragraph = 'paragraph'; + +echo 100; // Affichez un scalaire directement +echo $paragraph; // ou des variables + +// Si le raccourci de sortie est configuré, ou si votre version de PHP est +// 5.4.0+, vous pouvez utiliser ceci: +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Affiche le type et la valeur de la variable dans stdout +var_dump($z); // prints int(0) + +// Affiche la variable dans stdout dans un format plus convivial +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logique + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert affiche un avertissement dans son argument n'est pas vrai + +// Ces comparaisons vont toujours être vraies, même si leurs +// types ne sont pas les mêmes. +assert($a == $b); // égalité +assert($c != $a); // inégalité +assert($c <> $a); // inégalité (moins courant) +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Ces comparaisons vont seulement être vraies si les types concordent. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Opérateur 'spaceship' depuis PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 car ils sont égaux +echo $a <=> $b; // -1 car $a < $b +echo $b <=> $a; // 1 car $b > $a + +// Les variables peuvent être transtypées dépendamment de leur usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 + +$string = 'one'; +echo $string + $string; // => 0 +// Donne 0 car l'opérateur + ne peut pas transtyper la chaîne 'one' en un nombre + +// On peut également transtyper manuellement pour utiliser +// une variable dans un autre type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// Il y a également des fonctions dédiées pour transtyper +$integer = 5; +$string = strval($integer); + +$var = null; // Valeur nulle + + +/******************************** + * Structures de contrôle + */ + +if (true) { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne le suis pas'; +} else { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne suis pas affiché'; +} elseif (true) { + print 'Je le suis'; +} + +// Opérateur ternaire +print (false ? 'N\'est pas affiché' : 'L\'est'); + +// Opérateur ternaire depuis PHP 5.3 +// équivalent de $x ? $x : 'Does' +$x = false; +print($x ?: 'Does'); + +// depuis PHP 7, on peut facilement vérifier si une valeur est nulle +$a = null; +$b = 'Hello World'; +echo $a ?? 'a is not set'; // Affiche 'a is not set' +echo $b ?? 'b is not set'; // Affiche 'Hello World' + + +$x = 0; +if ($x === '0') { + print 'Pas affiché'; +} elseif($x == '1') { + print 'Pas affiché'; +} else { + print 'Affiché'; +} + + +// Cette syntaxe alternative est particulièrement utile avec du HTML: +?> + + +

Ceci est affiché si $x est vrai

+ +

Ceci est affiché si $x est faux

+ + + 2, 'car' => 4]; + +// Les boucles 'foreach' sont utiles pour parcourir les tableaux +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Affiche "24" + +echo "\n"; + +// Il est également possible d'accéder aux clés du tableau +foreach ($wheels as $vehicle => $wheel_count) { + echo "The $vehicle have $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Permet d'arrêter la boucle + } + echo $i++; +} // Affiche "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Permet de passer immédiatement à l'itération suivante + } + echo $i; +} // Affiche "0124" + + +/******************************** + * Fonctions + */ + +// On peut déclarer une fonction avec le mot clé 'function' +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + + +// Les noms de fonction débutent par le symbole $ +// Un nom de variable valide commence par une lettre ou un souligné, +// suivi de n'importe quelle lettre, nombre ou de soulignés. + +function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result n'est pas accessible en dehors de la fonction +// print $result; // Retourne un avertissement + +// Depuis PHP 5.3 on peut déclarer des fonctions anonymes +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Une fonction peut retourner une fonction +function bar ($x, $y) { + // On peut utiliser 'use' pour passer des variables externes + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Affiche "A - B - C" + +// On peut exécuter une fonction par son nom en chaîne de caractères +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Utile pour déterminer par programmation quelle fonction exécuter. + +// On peut également utiliser +call_user_func(callable $callback [, $parameter [, ... ]]); + +/******************************** + * Insertions + */ + +instanceProp = $instanceProp; + } + + // Les méthodes sont déclarés par des fonctions au sein de la classe + public function myMethod() + { + print 'MyClass'; + } + + // le mot clé 'final' rend la function impossible à surcharger + final function youCannotOverrideMe() + { + } + +/* + * Les attributs et méthodes statiques peuvent être accédés sans devoir + * instancier la classe. Les attributs statiques ne sont pas accessibles depuis + * une instance, même si les méthodes statiques le sont. + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Les constantes d'une classe peuvent toujours être utilisé de façon statique +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Retourne 'static'; +MyClass::myStaticMethod(); // Retourne 'I am static'; + +// On peut instancier une classe en utilisant le mot clé 'new' +$my_class = new MyClass('An instance property'); + +// On peut accéder aux attributs/méthodes d'une instance avec -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// On peut hériter d'une classe en utilisant 'extends' +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Surcharge d'une méthode + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Retourne "protected" +$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" + +// On peut empêcher qu'une classe soit héritée +final class YouCannotExtendMe +{ +} + +// On peut utiliser des "méthodes magiques" pour se faire des accesseurs +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Va utiliser la méthode __get() +$x->property = 'Something'; // Va utiliser la méthode __set() + +// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou +// elle peuvent implémenter une interface (en utilisant le mot clé 'implement'). + +// Une interface peut être déclarée avec le mot clé 'interface' + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// Les interfaces peuvent hériter d'autres interfaces +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Les classes peuvent implémenter plusieurs interfaces à la fois +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + +/******************************** + * Espaces de noms (namespaces) + */ + +// Cette section est séparée, car une déclaration d'espace de nom doit être +// la première chose que l'on retrouve dans un fichier PHP, +// imaginons que c'est le cas + +' - -// Deux barres obliques amorcent un commentaire simple. - -# Le dièse aussi, bien que les barres obliques soient plus courantes - -/* - Les barres obliques et les astérisques peuvent être utilisés - pour faire un commentaire multi-lignes. -*/ - -// Utilisez "echo" ou "print" afficher une sortie -print('Hello '); // Affiche "Hello " sans retour à la ligne - -// Les parenthèses sont facultatives pour print et echo -echo "World\n"; // Affiche "World" avec un retour à la ligne - -// toutes les instructions doivent se terminer par un point-virgule - -// Tout ce qui se trouve en dehors des est automatiquement -// affiché en sortie -Hello World Again! - 12 -$int2 = -12; // => -12 -$int3 = 012; // => 10 (un 0 devant la valeur désigne une valeur octale) -$int4 = 0x0F; // => 15 (un 0x devant la valeur désigne une valeur hexadécimale) - -// Réels (floats, doubles) -$float = 1.234; -$float = 1.2e3; -$float = 7E-10; - -// Suppression d'une variable -unset($int1); - -// Arithmétique -$sum = 1 + 1; // 2 (addition) -$difference = 2 - 1; // 1 (soustraction) -$product = 2 * 2; // 4 (produit) -$quotient = 2 / 1; // 2 (division) - -// Arithmétique (raccourcis) -$number = 0; -$number += 2; // Incrémente $number de 2 -echo $number++; // Affiche 2 (incrémente après l'évaluation) -echo ++$number; // Affiche 4 (incrémente avant l'évaluation) -$number /= $float; // Divise et assigne le quotient à $number - -// Les chaînes de caractères (strings) doivent être à -// l'intérieur d'une paire d'apostrophes -$sgl_quotes = '$String'; // => '$String' - -// Évitez les guillemets sauf pour inclure le contenu d'une autre variable -$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' - -// Les caractères spéciaux sont seulement échappés avec des guillemets -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; - -// En cas de besoin, placez la variable dans des accolades -$money = "I have $${number} in the bank."; - -// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes -// multi-lignes non-interprétées -$nowdoc = <<<'END' -Multi line -string -END; - -// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées -$heredoc = << 1, 'Two' => 2, 'Three' => 3); - -// PHP 5.4 a introduit une nouvelle syntaxe -$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; - -echo $associative['One']; // affiche 1 - -// Dans une liste simple, l'index est automatiquement attribué en tant que clé -$array = ['One', 'Two', 'Three']; -echo $array[0]; // => "One" - -// Ajoute un élément à la fin du tableau -$array[] = 'Four'; - -// Retrait d'un élément du tableau -unset($array[3]); - -/******************************** - * Affichage - */ - -echo('Hello World!'); -// Affiche Hello World! dans stdout. -// Stdout est la page web si on exécute depuis un navigateur. - -print('Hello World!'); // Pareil à "écho" - -// Pour écho, vous n'avez pas besoin des parenthèses -echo 'Hello World!'; -print 'Hello World!'; // Pour print non plus - -$paragraph = 'paragraph'; - -echo 100; // Affichez un scalaire directement -echo $paragraph; // ou des variables - -// Si le raccourci de sortie est configuré, ou si votre version de PHP est -// 5.4.0+, vous pouvez utiliser ceci: -?> -

- 2 -echo $z; // => 2 -$y = 0; -echo $x; // => 2 -echo $z; // => 0 - -// Affiche le type et la valeur de la variable dans stdout -var_dump($z); // prints int(0) - -// Affiche la variable dans stdout dans un format plus convivial -print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) - -/******************************** - * Logique - */ -$a = 0; -$b = '0'; -$c = '1'; -$d = '1'; - -// assert affiche un avertissement dans son argument n'est pas vrai - -// Ces comparaisons vont toujours être vraies, même si leurs -// types ne sont pas les mêmes. -assert($a == $b); // égalité -assert($c != $a); // inégalité -assert($c <> $a); // inégalité (moins courant) -assert($a < $c); -assert($c > $b); -assert($a <= $b); -assert($c >= $d); - -// Ces comparaisons vont seulement être vraies si les types concordent. -assert($c === $d); -assert($a !== $d); -assert(1 === '1'); -assert(1 !== '1'); - -// Opérateur 'spaceship' depuis PHP 7 -$a = 100; -$b = 1000; - -echo $a <=> $a; // 0 car ils sont égaux -echo $a <=> $b; // -1 car $a < $b -echo $b <=> $a; // 1 car $b > $a - -// Les variables peuvent être transtypées dépendamment de leur usage. - -$integer = 1; -echo $integer + $integer; // => 2 - -$string = '1'; -echo $string + $string; // => 2 - -$string = 'one'; -echo $string + $string; // => 0 -// Donne 0 car l'opérateur + ne peut pas transtyper la chaîne 'one' en un nombre - -// On peut également transtyper manuellement pour utiliser -// une variable dans un autre type - -$boolean = (boolean) 1; // => true - -$zero = 0; -$boolean = (boolean) $zero; // => false - -// Il y a également des fonctions dédiées pour transtyper -$integer = 5; -$string = strval($integer); - -$var = null; // Valeur nulle - - -/******************************** - * Structures de contrôle - */ - -if (true) { - print 'Je suis affiché'; -} - -if (false) { - print 'Je ne le suis pas'; -} else { - print 'Je suis affiché'; -} - -if (false) { - print 'Je ne suis pas affiché'; -} elseif (true) { - print 'Je le suis'; -} - -// Opérateur ternaire -print (false ? 'N\'est pas affiché' : 'L\'est'); - -// Opérateur ternaire depuis PHP 5.3 -// équivalent de $x ? $x : 'Does' -$x = false; -print($x ?: 'Does'); - -// depuis PHP 7, on peut facilement vérifier si une valeur est nulle -$a = null; -$b = 'Hello World'; -echo $a ?? 'a is not set'; // Affiche 'a is not set' -echo $b ?? 'b is not set'; // Affiche 'Hello World' - - -$x = 0; -if ($x === '0') { - print 'Pas affiché'; -} elseif($x == '1') { - print 'Pas affiché'; -} else { - print 'Affiché'; -} - - -// Cette syntaxe alternative est particulièrement utile avec du HTML: -?> - - -

Ceci est affiché si $x est vrai

- -

Ceci est affiché si $x est faux

- - - 2, 'car' => 4]; - -// Les boucles 'foreach' sont utiles pour parcourir les tableaux -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Affiche "24" - -echo "\n"; - -// Il est également possible d'accéder aux clés du tableau -foreach ($wheels as $vehicle => $wheel_count) { - echo "The $vehicle have $wheel_count wheels"; -} - -echo "\n"; - -$i = 0; -while ($i < 5) { - if ($i === 3) { - break; // Permet d'arrêter la boucle - } - echo $i++; -} // Affiche "012" - -for ($i = 0; $i < 5; $i++) { - if ($i === 3) { - continue; // Permet de passer immédiatement à l'itération suivante - } - echo $i; -} // Affiche "0124" - - -/******************************** - * Fonctions - */ - -// On peut déclarer une fonction avec le mot clé 'function' -function my_function () { - return 'Hello'; -} - -echo my_function(); // => "Hello" - - -// Les noms de fonction débutent par le symbole $ -// Un nom de variable valide commence par une lettre ou un souligné, -// suivi de n'importe quelle lettre, nombre ou de soulignés. - -function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 - $result = $x + $y; - return $result; -} - -echo add(4); // => 5 -echo add(4, 2); // => 6 - -// $result n'est pas accessible en dehors de la fonction -// print $result; // Retourne un avertissement - -// Depuis PHP 5.3 on peut déclarer des fonctions anonymes -$inc = function ($x) { - return $x + 1; -}; - -echo $inc(2); // => 3 - -function foo ($x, $y, $z) { - echo "$x - $y - $z"; -} - -// Une fonction peut retourner une fonction -function bar ($x, $y) { - // On peut utiliser 'use' pour passer des variables externes - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; -} - -$bar = bar('A', 'B'); -$bar('C'); // Affiche "A - B - C" - -// On peut exécuter une fonction par son nom en chaîne de caractères -$function_name = 'add'; -echo $function_name(1, 2); // => 3 -// Utile pour déterminer par programmation quelle fonction exécuter. - -// On peut également utiliser -call_user_func(callable $callback [, $parameter [, ... ]]); - -/******************************** - * Insertions - */ - -instanceProp = $instanceProp; - } - - // Les méthodes sont déclarés par des fonctions au sein de la classe - public function myMethod() - { - print 'MyClass'; - } - - // le mot clé 'final' rend la function impossible à surcharger - final function youCannotOverrideMe() - { - } - -/* - * Les attributs et méthodes statiques peuvent être accédés sans devoir - * instancier la classe. Les attributs statiques ne sont pas accessibles depuis - * une instance, même si les méthodes statiques le sont. - */ - - public static function myStaticMethod() - { - print 'I am static'; - } -} - -// Les constantes d'une classe peuvent toujours être utilisé de façon statique -echo MyClass::MY_CONST; // Outputs 'value'; - -echo MyClass::$staticVar; // Retourne 'static'; -MyClass::myStaticMethod(); // Retourne 'I am static'; - -// On peut instancier une classe en utilisant le mot clé 'new' -$my_class = new MyClass('An instance property'); - -// On peut accéder aux attributs/méthodes d'une instance avec -> -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" - - -// On peut hériter d'une classe en utilisant 'extends' -class MyOtherClass extends MyClass -{ - function printProtectedProperty() - { - echo $this->prot; - } - - // Surcharge d'une méthode - function myMethod() - { - parent::myMethod(); - print ' > MyOtherClass'; - } -} - -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Retourne "protected" -$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" - -// On peut empêcher qu'une classe soit héritée -final class YouCannotExtendMe -{ -} - -// On peut utiliser des "méthodes magiques" pour se faire des accesseurs -class MyMapClass -{ - private $property; - - public function __get($key) - { - return $this->$key; - } - - public function __set($key, $value) - { - $this->$key = $value; - } -} - -$x = new MyMapClass(); -echo $x->property; // Va utiliser la méthode __get() -$x->property = 'Something'; // Va utiliser la méthode __set() - -// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou -// elle peuvent implémenter une interface (en utilisant le mot clé 'implement'). - -// Une interface peut être déclarée avec le mot clé 'interface' - -interface InterfaceOne -{ - public function doSomething(); -} - -interface InterfaceTwo -{ - public function doSomethingElse(); -} - -// Les interfaces peuvent hériter d'autres interfaces -interface InterfaceThree extends InterfaceTwo -{ - public function doAnotherContract(); -} - -abstract class MyAbstractClass implements InterfaceOne -{ - public $x = 'doSomething'; -} - -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo -{ - public function doSomething() - { - echo $x; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - - -// Les classes peuvent implémenter plusieurs interfaces à la fois -class SomeOtherClass implements InterfaceOne, InterfaceTwo -{ - public function doSomething() - { - echo 'doSomething'; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - -/******************************** - * Espaces de noms (namespaces) - */ - -// Cette section est séparée, car une déclaration d'espace de nom doit être -// la première chose que l'on retrouve dans un fichier PHP, -// imaginons que c'est le cas - - + + C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive. + Vous pouvez y exécuter des commandes. + Allons-y : +*/ + +println(10) // affiche l'integer 10 + +println("Boo!") // affiche avec retour à la ligne la chaîne de caractère Boo! + + +// Quelques basiques + +// Imprimer et forcer une nouvelle ligne à la prochaine impression +println("Hello world!") +// Imprimer sans forcer une nouvelle ligne à la prochaine impression +print("Hello world") + +// Pour déclarer des valeurs on utilise var ou val +// Les déclarations val sont immuables, tandis que les var sont muables. +// L'immuabilité est une bonne chose. + +val x = 10 // x vaut maintenant 10 +x = 20 // erreur : réaffectation à val +var x = 10 +x = 20 // x vaut maintenant 20 + +// Les commentaires d'une ligne commencent par deux slashs + +/* +Les commentaires multilignes ressemblent à ça. +*/ + +// les valeurs booléennes +true +false + +// Les opérateurs booléens +!true // false +!false // true +true == false // false +10 > 5 // true + +// Les opérateurs mathématiques sont habituels +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + + +// Le REPL donne le type et la valeur du résultat quand vous évaluez une commande + +1 + 7 + +/* Les lignes ci-dessous donnent les résultats : + + scala> 1 + 7 + res29: Int = 8 + + Ça signifie que le résultat de l'évaluation 1 + 7 est un objet de + type Int avec une valeur de 8 + + 1+7 donnera le même résultat +*/ + + +// Tout est un objet, même une fonction. Tapez ceci dans le REPL : + +7 // donne res30: Int = 7 (res30 est seulement un nom de variable généré pour le résultat) + + +// La ligne suivante est une fonction qui prend un Int et retourne son carré +(x:Int) => x * x + + +// On peut assigner cette fonction à un identifieur comme ceci : +val sq = (x:Int) => x * x + +/* La ligne suivante nous dit : + + sq: Int => Int = + + Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur. + sq est une fonction qui prend un Int et retourne un Int. + + + sq peut être exécutée comme ci-dessous : +*/ + +sq(10) // donne comme résultat : res33: Int = 100. + + +// les deux-points définissent explicitement le type de la valeur, +// dans ce cas une fonction qui prend un Int et retourne un Int. +val add10: Int => Int = _ + 10 + +// Scala autorise des méthodes et des fonctions à retourner +// ou prendre comme paramètres des autres fonctions ou méthodes + + +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 est appliqué à chaque éléments + + +// Les fonctions anonymes peuvent être utilisées à la place des fonctions nommées : +List(1, 2, 3) map (x => x + 10) + + + + +// Le tiret du bas peut être utilisé si la fonction anonyme ne prend qu'un paramètre. +// Il se comporte comme une variable +List(1, 2, 3) map (_ + 10) + + + +// Si le bloc et la fonction anonyme prennent tous les deux un seul argument, +// vous pouvez omettre le tiret du bas +List("Dom", "Bob", "Natalia") foreach println + + + +// Les structures de données + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Lance une exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Lance une exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Jetez un oeil sur la documentation de map ici - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + */ + + +// Tuples + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Exemple d'utilisation +val divideInts = (x:Int, y:Int) => (x / y, x % y) + + +divideInts(10,3) // La fonction divideInts donne le résultat et le reste de la division + +// Pour accéder à un élément d'un tuple, utilisez _._n +// où n est l'index de base 1 de l'élément +val d = divideInts(10,3) + +d._1 + +d._2 + + + +// Des combinaisons + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + + + +// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et +// sélectionne tous les éléments qui satisfont ce prédicat +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name: String, age: Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + + +// Scala a une méthode foreach définie pour certaines collections +// qui prend en argument une fonction renvoyant Unit (une méthode void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + + + +// Compréhensions de listes + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + + + +/* Les exemples précédents ne sont pas des boucles for. La sémantique des boucles for + est "répète", alors qu'une for-compréhension définit une relation + entre deux ensembles de données. */ + + + +// Boucles et itération + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément. +// Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais. + + +(5 to 1 by -1) foreach ( println ) + +// Une boucle while +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'est passé ? Pourquoi ? + + + + + + +i // Montre la valeur de i. Notez que while est une boucle au sens classique. + // Il exécute séquentiellement pendant que la variable de boucle change. + // While est très rapide, + // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus + // facile pour comprendre et pour faire la parallélisation + +i = 0 +// La boucle do while +do { + println("x is still less than 10"); + i += 1 +} while (i < 10) + + +// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. +// Les fonctions récursives ont besoin d'un type de retour explicite, +// le compilateur ne peut pas le déduire. +// Ici c'est Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} + + + +// Structures de contrôle + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + + + +// Les caractéristiques "Orienté Objet" + +// Création d'une classe Dog +class Dog { + // Une méthode appelée bark qui retourne une chaîne de caractère + def bark: String = { + // le corps de la méthode + "Woof, woof!" + } +} + + +// Les classes peuvent contenir presque n'importe quelle autre construction, incluant d'autres classes, +// des fonctions, des méthodes, des objets, des classes case, des traits, etc ... + + + +// Les classes case + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + + +// Correspondances de motifs + +val me = Person("George", "1234") + +me match { case Person(name, number) => { + "We matched someone : " + name + ", phone : " + number }} + +me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } + +me match { case Person("George", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } + +me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + +val kate = Person("Kate", "1234") + +kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + + + +// Expressions régulières + +val email = "(.*)@(.*)".r // On fait une Regex en invoquant r sur la chaîne de caractère + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + + + +// Les chaînes de caractères + +"Les chaînes de caractères Scala sont entourées de doubles guillements" +'a' // Un caractère de Scala +// 'Les simples guillemets n'existent pas en Scala' // Erreur +"Les chaînes de caractères possèdent les méthodes usuelles de Java".length +"Il y a aussi quelques méthodes extra de Scala.".reverse + +// Voir également : scala.collection.immutable.StringOps + +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) + +val n = 45 +println(s"We have $n apples") + +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(2-1)} years old") + +// Certains caractères ont besoin d'être "échappés", +// ex un guillemet à l'intérieur d'une chaîne de caractères : +val a = "They stood outside the \"Rose and Crown\"" + +// Les triples guillemets permettent d'écrire des chaînes de caractères +// sur plusieurs lignes et peuvent contenir des guillemets + +val html = """
+

Press belo', Joe

+ | +
""" + + + +// Structure et organisation d'une application + +// Importer des chaînes de caratères +import scala.collection.immutable.List + +// Importer tous les sous-paquets +import scala.collection.immutable._ + +// Importer plusieurs classes en une seule instruction +import scala.collection.immutable.{List, Map} + +// Renommer un import en utilisant '=>' +import scala.collection.immutable.{ List => ImmutableList } + +// Importer toutes les classes, à l'exception de certaines. +// La ligne suivante exclut Map et Set : +import scala.collection.immutable.{Map => _, Set => _, _} + +// Le point d'entrée du programme est défini dans un fichier scala +// utilisant un objet, avec une simple méthode main : +object Application { + def main(args: Array[String]): Unit = { + // Votre code ici. + } +} + +// Les fichiers peuvent contenir plusieurs classes et plusieurs objets. +// On les compile avec scalac + + + + +// Entrée et Sortie + +// Pour lire un fichier ligne par ligne +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + +// On utilise le PrintWriter de Java pour écrire un fichier + + +``` + +## Autres ressources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) + +Rejoindre le [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown deleted file mode 100644 index c6a61745..00000000 --- a/fr-fr/scala.html.markdown +++ /dev/null @@ -1,460 +0,0 @@ ---- -language: Scala -contributors: - - ["George Petrov", "http://github.com/petrovg"] - - ["Dominic Bou-Samra", "http://dbousamra.github.com"] -translators: - - ["Anne-Catherine Dehier", "https://github.com/spellart"] -filename: learnscala-fr.scala -lang: fr-fr ---- - -### Scala - le langage évolutif - -```scala - -/* - Pour vous préparer : - - 1) (Téléchargez Scala)[http://www.scala-lang.org/downloads] - 2) Dézippez/décompressez dans votre endroit préféré - et ajoutez le chemin du sous-répertoire bin au chemin du système - 3) Commencez un REPL de Scala en tapant juste scala. Vous devriez voir le prompteur : - - scala> - - C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive. - Vous pouvez y exécuter des commandes. - Allons-y : -*/ - -println(10) // affiche l'integer 10 - -println("Boo!") // affiche avec retour à la ligne la chaîne de caractère Boo! - - -// Quelques basiques - -// Imprimer et forcer une nouvelle ligne à la prochaine impression -println("Hello world!") -// Imprimer sans forcer une nouvelle ligne à la prochaine impression -print("Hello world") - -// Pour déclarer des valeurs on utilise var ou val -// Les déclarations val sont immuables, tandis que les var sont muables. -// L'immuabilité est une bonne chose. - -val x = 10 // x vaut maintenant 10 -x = 20 // erreur : réaffectation à val -var x = 10 -x = 20 // x vaut maintenant 20 - -// Les commentaires d'une ligne commencent par deux slashs - -/* -Les commentaires multilignes ressemblent à ça. -*/ - -// les valeurs booléennes -true -false - -// Les opérateurs booléens -!true // false -!false // true -true == false // false -10 > 5 // true - -// Les opérateurs mathématiques sont habituels -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 - - -// Le REPL donne le type et la valeur du résultat quand vous évaluez une commande - -1 + 7 - -/* Les lignes ci-dessous donnent les résultats : - - scala> 1 + 7 - res29: Int = 8 - - Ça signifie que le résultat de l'évaluation 1 + 7 est un objet de - type Int avec une valeur de 8 - - 1+7 donnera le même résultat -*/ - - -// Tout est un objet, même une fonction. Tapez ceci dans le REPL : - -7 // donne res30: Int = 7 (res30 est seulement un nom de variable généré pour le résultat) - - -// La ligne suivante est une fonction qui prend un Int et retourne son carré -(x:Int) => x * x - - -// On peut assigner cette fonction à un identifieur comme ceci : -val sq = (x:Int) => x * x - -/* La ligne suivante nous dit : - - sq: Int => Int = - - Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur. - sq est une fonction qui prend un Int et retourne un Int. - - - sq peut être exécutée comme ci-dessous : -*/ - -sq(10) // donne comme résultat : res33: Int = 100. - - -// les deux-points définissent explicitement le type de la valeur, -// dans ce cas une fonction qui prend un Int et retourne un Int. -val add10: Int => Int = _ + 10 - -// Scala autorise des méthodes et des fonctions à retourner -// ou prendre comme paramètres des autres fonctions ou méthodes - - -List(1, 2, 3) map add10 // List(11, 12, 13) - add10 est appliqué à chaque éléments - - -// Les fonctions anonymes peuvent être utilisées à la place des fonctions nommées : -List(1, 2, 3) map (x => x + 10) - - - - -// Le tiret du bas peut être utilisé si la fonction anonyme ne prend qu'un paramètre. -// Il se comporte comme une variable -List(1, 2, 3) map (_ + 10) - - - -// Si le bloc et la fonction anonyme prennent tous les deux un seul argument, -// vous pouvez omettre le tiret du bas -List("Dom", "Bob", "Natalia") foreach println - - - -// Les structures de données - -val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) -a(21) // Lance une exception - -val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") -m("bottle") // Lance une exception - -val safeM = m.withDefaultValue("no lo se") -safeM("bottle") - -val s = Set(1, 3, 7) -s(0) -s(1) - -/* Jetez un oeil sur la documentation de map ici - - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map - */ - - -// Tuples - -(1, 2) - -(4, 3, 2) - -(1, 2, "three") - -(a, 2, "three") - -// Exemple d'utilisation -val divideInts = (x:Int, y:Int) => (x / y, x % y) - - -divideInts(10,3) // La fonction divideInts donne le résultat et le reste de la division - -// Pour accéder à un élément d'un tuple, utilisez _._n -// où n est l'index de base 1 de l'élément -val d = divideInts(10,3) - -d._1 - -d._2 - - - -// Des combinaisons - -s.map(sq) - -val sSquared = s. map(sq) - -sSquared.filter(_ < 10) - -sSquared.reduce (_+_) - - - -// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et -// sélectionne tous les éléments qui satisfont ce prédicat -List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name: String, age: Int) -List( - Person(name = "Dom", age = 23), - Person(name = "Bob", age = 30) -).filter(_.age > 25) // List(Person("Bob", 30)) - - - -// Scala a une méthode foreach définie pour certaines collections -// qui prend en argument une fonction renvoyant Unit (une méthode void) -val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println - - - - -// Compréhensions de listes - -for { n <- s } yield sq(n) - -val nSquared2 = for { n <- s } yield sq(n) - -for { n <- nSquared2 if n < 10 } yield n - -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared - - - -/* Les exemples précédents ne sont pas des boucles for. La sémantique des boucles for - est "répète", alors qu'une for-compréhension définit une relation - entre deux ensembles de données. */ - - - -// Boucles et itération - -1 to 5 -val r = 1 to 5 -r.foreach( println ) - -r foreach println -// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément. -// Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais. - - -(5 to 1 by -1) foreach ( println ) - -// Une boucle while -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - -while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'est passé ? Pourquoi ? - - - - - - -i // Montre la valeur de i. Notez que while est une boucle au sens classique. - // Il exécute séquentiellement pendant que la variable de boucle change. - // While est très rapide, - // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus - // facile pour comprendre et pour faire la parallélisation - -i = 0 -// La boucle do while -do { - println("x is still less than 10"); - i += 1 -} while (i < 10) - - -// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. -// Les fonctions récursives ont besoin d'un type de retour explicite, -// le compilateur ne peut pas le déduire. -// Ici c'est Unit. -def showNumbersInRange(a:Int, b:Int):Unit = { - print(a) - if (a < b) - showNumbersInRange(a + 1, b) -} - - - -// Structures de contrôle - -val x = 10 - -if (x == 1) println("yeah") -if (x == 10) println("yeah") -if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") - -println(if (x == 10) "yeah" else "nope") -val text = if (x == 10) "yeah" else "nope" - -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - - - -// Les caractéristiques "Orienté Objet" - -// Création d'une classe Dog -class Dog { - // Une méthode appelée bark qui retourne une chaîne de caractère - def bark: String = { - // le corps de la méthode - "Woof, woof!" - } -} - - -// Les classes peuvent contenir presque n'importe quelle autre construction, incluant d'autres classes, -// des fonctions, des méthodes, des objets, des classes case, des traits, etc ... - - - -// Les classes case - -case class Person(name:String, phoneNumber:String) - -Person("George", "1234") == Person("Kate", "1236") - - - - -// Correspondances de motifs - -val me = Person("George", "1234") - -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} - -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } - -me match { case Person("George", number) => "Match"; case _ => "Hm..." } - -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } - -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } - -val kate = Person("Kate", "1234") - -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } - - - -// Expressions régulières - -val email = "(.*)@(.*)".r // On fait une Regex en invoquant r sur la chaîne de caractère - -val email(user, domain) = "henry@zkpr.com" - -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name -} - - - -// Les chaînes de caractères - -"Les chaînes de caractères Scala sont entourées de doubles guillements" -'a' // Un caractère de Scala -// 'Les simples guillemets n'existent pas en Scala' // Erreur -"Les chaînes de caractères possèdent les méthodes usuelles de Java".length -"Il y a aussi quelques méthodes extra de Scala.".reverse - -// Voir également : scala.collection.immutable.StringOps - -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) - -val n = 45 -println(s"We have $n apples") - -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") - -// Certains caractères ont besoin d'être "échappés", -// ex un guillemet à l'intérieur d'une chaîne de caractères : -val a = "They stood outside the \"Rose and Crown\"" - -// Les triples guillemets permettent d'écrire des chaînes de caractères -// sur plusieurs lignes et peuvent contenir des guillemets - -val html = """
-

Press belo', Joe

- | -
""" - - - -// Structure et organisation d'une application - -// Importer des chaînes de caratères -import scala.collection.immutable.List - -// Importer tous les sous-paquets -import scala.collection.immutable._ - -// Importer plusieurs classes en une seule instruction -import scala.collection.immutable.{List, Map} - -// Renommer un import en utilisant '=>' -import scala.collection.immutable.{ List => ImmutableList } - -// Importer toutes les classes, à l'exception de certaines. -// La ligne suivante exclut Map et Set : -import scala.collection.immutable.{Map => _, Set => _, _} - -// Le point d'entrée du programme est défini dans un fichier scala -// utilisant un objet, avec une simple méthode main : -object Application { - def main(args: Array[String]): Unit = { - // Votre code ici. - } -} - -// Les fichiers peuvent contenir plusieurs classes et plusieurs objets. -// On les compile avec scalac - - - - -// Entrée et Sortie - -// Pour lire un fichier ligne par ligne -import scala.io.Source -for(line <- Source.fromFile("myfile.txt").getLines()) - println(line) - -// On utilise le PrintWriter de Java pour écrire un fichier - - -``` - -## Autres ressources - -[Scala for the impatient](http://horstmann.com/scala/) - -[Twitter Scala school](http://twitter.github.io/scala_school/) - -[The scala documentation](http://docs.scala-lang.org/) - -[Try Scala in your browser](http://scalatutorials.com/tour/) - -Rejoindre le [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/fr-fr/vim-fr.html.markdown b/fr-fr/vim-fr.html.markdown new file mode 100644 index 00000000..b2f1d24d --- /dev/null +++ b/fr-fr/vim-fr.html.markdown @@ -0,0 +1,239 @@ +--- +category: tool +tool: vim +filename: LearnVim-fr.txt +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Thibault", "https://github.com/napnac"] +lang: fr-fr +--- + + +[Vim](http://www.vim.org) +(Vi IMproved) est le clone le plus populaire de l'éditeur de texte vi sous Unix. +Vim est un éditeur de texte omniprésent sur les systèmes de type Unix, et a pour +objectif la rapidité ainsi que l'augmentation de la productivité. Il a de +nombreux raccourcis claviers pour une navigation et une édition plus rapide. + +## Navigation basique avec Vim + +``` + vim # Ouvre avec vim + :q # Quitte vim + :w # Sauvegarde le fichier actuel + :wq # Sauvegarde le fichier actuel et quitte vim + :q! # Quitte vim sans sauvegarder + # ! *force* l'exécution de :q, ce qui par conséquent + # oblige vim à quitter sans sauvegarder + :x # Sauvegarde le fichier et quitte vim (raccourcis de :wq) + + u # Annuler + CTRL+R # Rétablir + + h # Déplace le curseur vers la gauche + j # Déplace le curseur vers le bas + k # Déplace le curseur vers le haut + l # Déplace le curseur vers la droite + + # Mouvements au sein d'une ligne + + 0 # Va au début de la ligne + $ # Va à la fin de la ligne + ^ # Va au premier caractère non blanc de la ligne + + # Rechercher dans un texte + + /mot # Surligne toutes les occurrences du mot après le curseur + ?mot # Surligne toutes les occurrences du mot avant le curseur + n # Déplace le curseur sur la prochaine occurrence du mot recherché + N # Déplace le curseur sur la précédente occurrence du mot recherché + + :%s/abc/def/g # Transforme les 'abc' en 'def' sur chaque ligne du texte + :s/abc/def/g # Transforme les 'abc' en 'def' sur la ligne actuelle + + # Se déplacer vers un caractère + + f # Se déplace en avant jusqu'à + t # Se déplace en avant juste avant + + # Par exemple + f< # Se déplace en avant jusqu'à < + t< # Se déplace en avant juste avant < + + # Se déplacer dans un mot + + w # Avance d'un mot + b # Recule d'un mot + e # Se déplace jusqu'à la fin du mot actuel + + # D'autres raccourcis pour se déplacer + + gg # Va au début du fichier + G # Va à la fin du fichier + :NB # Va à la ligne numéro NB (où NB est un nombre) + H # Se déplace jusqu'en haut de l'écran + M # Se déplace jusqu'au milieu de l'écran + L # Se déplace jusqu'en bas de l'écran +``` + +## Modes + +Vim est basé sur le concept de **modes**. + +Mode Commande - pour se déplacer et exécuter des commandes (vim démarre dans ce mode) +Mode Insertion - pour éditer le fichier +Mode Visuel - pour sélectionner du texte et réaliser des opérations dessus +Mode Ex - pour entrer des commandes avec ':' + +``` + i # Mode insertion, avant le curseur + a # Mode insertion, après le curseur + v # Mode visuel + : # Mode ex + # 'Echap' permet de revenir dans le mode commande + + # Copier/Coller du texte + + y # Copie le texte sélectionné + yy # Copie la ligne actuelle + d # Supprime ce qui est sélectionné + dd # Supprime la ligne actuelle + p # Colle après le curseur + P # Colle avant le curseur + x # Supprime le caractère sous le curseur +``` + +## La "Grammaire" de Vim + +Vim peut être vu comme un ensemble de commande sous la forme +'Verbe-Modificateur-Nom' : + +Verbe - notre action +Modificateur - la manière de faire l'action +Nom - l'objet désigné par l'action + +Quelques exemples importants de 'Verbes', 'Modificateurs', et de 'Noms' : + +``` + # 'Verbes' + + d # Supprime + c # Transforme + y # Copie + v # Sélectionne + + # 'Modificateurs' + + i # A l'intérieur + a # Autour + NB # Nombre + f # Cherche quelque chose et se déplace dessus + t # Cherche quelque chose et se déplace juste avant + / # Cherche une chaîne de caractères après le curseur + ? # Cherche une chaîne de caractères avant le curseur + + # 'Noms' + + w # Mot + s # Phrase + p # Paragraphe + b # Bloc + + # Exemple de 'phrases' ou commandes + + d2w # Supprime 2 mots + cis # Transforme l'intérieur de la phrase + yip # Copie l'intérieur du paragraphe + ct< # Transforme le texte du curseur jusqu'au caractère avant le < + d$ # Supprime jusqu'à la fin de la ligne +``` + +## Quelques raccourcis et astuces + +``` + > # Indente la sélection d'un bloc + < # Dé-indente la sélection d'un bloc + :earlier 15m # Retrouve le document comme il était il y a 15 minutes + :later 15m # Inverse la commande précédente + ddp # Echange la position de deux lignes consécutives (dd puis p) + . # Répète la dernière action effectuée +``` + +## Macros + +Les macros sont des actions enregistrables. +Quand on commence à enregistrer une macro, Vim enregistre **toutes** les actions +et les commandes que vous utilisez, jusqu'à ce que vous arrêtiez d'enregistrer. +Lorsque vous appelez une macro, elle applique exactement les mêmes actions et +commandes sur le texte sélectionné. + +``` + qa # Commence l'enregistrement de la macro 'a' + q # Arrête l'enregistrement + @a # Appelle la macro 'a' +``` + +### Configuration de ~/.vimrc + +Le fichier .vimrc est utilisé pour configurer Vim lors du démarrage. + +Voici un exemple de fichier ~/.vimrc : + +``` +" Exemple de ~/.vimrc +" 2015.10 + +" Nécessaire à Vim pour être 'iMproved' +set nocompatible + +" Détermine l'extension du fichier à partir du nom pour permettre une indentation +" automatique intelligente, etc. +filetype indent plugin on + +" Active la coloration syntaxique +syntax on + +" Une meilleure complétion de la ligne de commande +set wildmenu + +" Utilise une recherche insensible à la case sauf quand on utilise des majuscules +set ignorecase +set smartcase + +" Quand on commence une nouvelle ligne et qu'aucun type d'indentation n'est activé +" on utilise la même indentation que sur la ligne précédente +set autoindent + +" Affiche le numéro de la ligne sur la gauche de l'écran +set number + +" Options d'indentation, à changer en fonction des préférences personnelles + +" Nombre d'espaces visuels par tabulation +set tabstop=4 + +" Nombre d'espaces par tabulation +set softtabstop=4 + +" Nombre d'espaces indentés avec les opérations d'indentations (>> et <<) +set shiftwidth=4 + +" Convertis les tabulations en espaces +set expandtab + +" Active des tabulations et des espaces intelligents pour l'indentation et l'alignement +set smarttab +``` + +### Références + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) diff --git a/fr-fr/vim.html.markdown b/fr-fr/vim.html.markdown deleted file mode 100644 index b2f1d24d..00000000 --- a/fr-fr/vim.html.markdown +++ /dev/null @@ -1,239 +0,0 @@ ---- -category: tool -tool: vim -filename: LearnVim-fr.txt -contributors: - - ["RadhikaG", "https://github.com/RadhikaG"] -translators: - - ["Thibault", "https://github.com/napnac"] -lang: fr-fr ---- - - -[Vim](http://www.vim.org) -(Vi IMproved) est le clone le plus populaire de l'éditeur de texte vi sous Unix. -Vim est un éditeur de texte omniprésent sur les systèmes de type Unix, et a pour -objectif la rapidité ainsi que l'augmentation de la productivité. Il a de -nombreux raccourcis claviers pour une navigation et une édition plus rapide. - -## Navigation basique avec Vim - -``` - vim # Ouvre avec vim - :q # Quitte vim - :w # Sauvegarde le fichier actuel - :wq # Sauvegarde le fichier actuel et quitte vim - :q! # Quitte vim sans sauvegarder - # ! *force* l'exécution de :q, ce qui par conséquent - # oblige vim à quitter sans sauvegarder - :x # Sauvegarde le fichier et quitte vim (raccourcis de :wq) - - u # Annuler - CTRL+R # Rétablir - - h # Déplace le curseur vers la gauche - j # Déplace le curseur vers le bas - k # Déplace le curseur vers le haut - l # Déplace le curseur vers la droite - - # Mouvements au sein d'une ligne - - 0 # Va au début de la ligne - $ # Va à la fin de la ligne - ^ # Va au premier caractère non blanc de la ligne - - # Rechercher dans un texte - - /mot # Surligne toutes les occurrences du mot après le curseur - ?mot # Surligne toutes les occurrences du mot avant le curseur - n # Déplace le curseur sur la prochaine occurrence du mot recherché - N # Déplace le curseur sur la précédente occurrence du mot recherché - - :%s/abc/def/g # Transforme les 'abc' en 'def' sur chaque ligne du texte - :s/abc/def/g # Transforme les 'abc' en 'def' sur la ligne actuelle - - # Se déplacer vers un caractère - - f # Se déplace en avant jusqu'à - t # Se déplace en avant juste avant - - # Par exemple - f< # Se déplace en avant jusqu'à < - t< # Se déplace en avant juste avant < - - # Se déplacer dans un mot - - w # Avance d'un mot - b # Recule d'un mot - e # Se déplace jusqu'à la fin du mot actuel - - # D'autres raccourcis pour se déplacer - - gg # Va au début du fichier - G # Va à la fin du fichier - :NB # Va à la ligne numéro NB (où NB est un nombre) - H # Se déplace jusqu'en haut de l'écran - M # Se déplace jusqu'au milieu de l'écran - L # Se déplace jusqu'en bas de l'écran -``` - -## Modes - -Vim est basé sur le concept de **modes**. - -Mode Commande - pour se déplacer et exécuter des commandes (vim démarre dans ce mode) -Mode Insertion - pour éditer le fichier -Mode Visuel - pour sélectionner du texte et réaliser des opérations dessus -Mode Ex - pour entrer des commandes avec ':' - -``` - i # Mode insertion, avant le curseur - a # Mode insertion, après le curseur - v # Mode visuel - : # Mode ex - # 'Echap' permet de revenir dans le mode commande - - # Copier/Coller du texte - - y # Copie le texte sélectionné - yy # Copie la ligne actuelle - d # Supprime ce qui est sélectionné - dd # Supprime la ligne actuelle - p # Colle après le curseur - P # Colle avant le curseur - x # Supprime le caractère sous le curseur -``` - -## La "Grammaire" de Vim - -Vim peut être vu comme un ensemble de commande sous la forme -'Verbe-Modificateur-Nom' : - -Verbe - notre action -Modificateur - la manière de faire l'action -Nom - l'objet désigné par l'action - -Quelques exemples importants de 'Verbes', 'Modificateurs', et de 'Noms' : - -``` - # 'Verbes' - - d # Supprime - c # Transforme - y # Copie - v # Sélectionne - - # 'Modificateurs' - - i # A l'intérieur - a # Autour - NB # Nombre - f # Cherche quelque chose et se déplace dessus - t # Cherche quelque chose et se déplace juste avant - / # Cherche une chaîne de caractères après le curseur - ? # Cherche une chaîne de caractères avant le curseur - - # 'Noms' - - w # Mot - s # Phrase - p # Paragraphe - b # Bloc - - # Exemple de 'phrases' ou commandes - - d2w # Supprime 2 mots - cis # Transforme l'intérieur de la phrase - yip # Copie l'intérieur du paragraphe - ct< # Transforme le texte du curseur jusqu'au caractère avant le < - d$ # Supprime jusqu'à la fin de la ligne -``` - -## Quelques raccourcis et astuces - -``` - > # Indente la sélection d'un bloc - < # Dé-indente la sélection d'un bloc - :earlier 15m # Retrouve le document comme il était il y a 15 minutes - :later 15m # Inverse la commande précédente - ddp # Echange la position de deux lignes consécutives (dd puis p) - . # Répète la dernière action effectuée -``` - -## Macros - -Les macros sont des actions enregistrables. -Quand on commence à enregistrer une macro, Vim enregistre **toutes** les actions -et les commandes que vous utilisez, jusqu'à ce que vous arrêtiez d'enregistrer. -Lorsque vous appelez une macro, elle applique exactement les mêmes actions et -commandes sur le texte sélectionné. - -``` - qa # Commence l'enregistrement de la macro 'a' - q # Arrête l'enregistrement - @a # Appelle la macro 'a' -``` - -### Configuration de ~/.vimrc - -Le fichier .vimrc est utilisé pour configurer Vim lors du démarrage. - -Voici un exemple de fichier ~/.vimrc : - -``` -" Exemple de ~/.vimrc -" 2015.10 - -" Nécessaire à Vim pour être 'iMproved' -set nocompatible - -" Détermine l'extension du fichier à partir du nom pour permettre une indentation -" automatique intelligente, etc. -filetype indent plugin on - -" Active la coloration syntaxique -syntax on - -" Une meilleure complétion de la ligne de commande -set wildmenu - -" Utilise une recherche insensible à la case sauf quand on utilise des majuscules -set ignorecase -set smartcase - -" Quand on commence une nouvelle ligne et qu'aucun type d'indentation n'est activé -" on utilise la même indentation que sur la ligne précédente -set autoindent - -" Affiche le numéro de la ligne sur la gauche de l'écran -set number - -" Options d'indentation, à changer en fonction des préférences personnelles - -" Nombre d'espaces visuels par tabulation -set tabstop=4 - -" Nombre d'espaces par tabulation -set softtabstop=4 - -" Nombre d'espaces indentés avec les opérations d'indentations (>> et <<) -set shiftwidth=4 - -" Convertis les tabulations en espaces -set expandtab - -" Active des tabulations et des espaces intelligents pour l'indentation et l'alignement -set smarttab -``` - -### Références - -[Vim | Home](http://www.vim.org/index.php) - -`$ vimtutor` - -[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) - -[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) - -[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) -- cgit v1.2.3 From 59dc72ceac36b0e6d9785d332570f45553b67b00 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 30 Oct 2017 05:43:23 +0100 Subject: [nix/de] fixed some typos --- de-de/nix-de.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown index 8c78ffbc..79b60d20 100644 --- a/de-de/nix-de.html.markdown +++ b/de-de/nix-de.html.markdown @@ -58,7 +58,7 @@ with builtins; [ # Strings #========================================= - "String Literale sind in Gänsefüßchen." + "String Literale sind in Anführungszeichen." " String Literale können mehrere @@ -87,7 +87,7 @@ with builtins; [ # Paths #========================================= - # Nix besitzt einen primitven Datentyp für Pfade + # Nix besitzt einen primitiven Datentyp für Pfade /tmp/tutorials/learn.nix # Ein relativer Pfad wird beim Parsing zu einem absoluten Pfad aufgelöst, @@ -170,7 +170,7 @@ with builtins; [ # Listen #========================================= - # Listen werden durck eckige Klammern gekennzeichnet. + # Listen werden durch eckige Klammern gekennzeichnet. (length [1 2 3 "x"]) #=> 4 @@ -218,18 +218,18 @@ with builtins; [ ({ a = 1; } // { b = 2; }) #=> { a = 1; b = 2; } - # Werte auf der rechten Seite überschrieben die Werte auf der linken Seite. + # Werte auf der rechten Seite überschreiben die Werte auf der linken Seite. ({ a = 1; b = 2; } // { a = 3; c = 4; }) #=> { a = 3; b = 2; c = 4; } - # Das Schlüsselwort rec bezeichenet ein "rekursives Set", in der sich Attribute + # Das Schlüsselwort rec bezeichenet ein "rekursives Set", in dem sich Attribute # aufeinander beziehen können. (let a = 1; in { a = 2; b = a; }.b) #=> 1 (let a = 1; in rec { a = 2; b = a; }.b) #=> 2 - # Verschachetelte Sets können stückweise definiert werden. + # Verschachtelte Sets können stückweise definiert werden. { a.b = 1; a.c.d = 2; @@ -238,7 +238,7 @@ with builtins; [ #=> { d = 2; e = 3; } # Die Nachkommen eines Attributs können in diesem Feld nicht zugeordnet werden, wenn - # das Attribut selbst nicht zugeweisen wurde. + # das Attribut selbst nicht zugewiesen wurde. { a = { b = 1; }; a.c = 2; @@ -249,7 +249,7 @@ with builtins; [ # With #========================================= - # Der Körper eines Sets Blocks wird mit der Zurodnung eines Satzes an die Variablen gebunden. + # Der Körper eines Sets Blocks wird mit der Zuordnung eines Satzes an die Variablen gebunden. (with { a = 1; b = 2; }; a + b) # => 3 @@ -263,7 +263,7 @@ with builtins; [ # Die erste Linie diese Tutorials startet mit "with builtins;", # weil builtins ein Set mit allen eingebauten # Funktionen (length, head, tail, filter, etc.) umfasst. - # Das erspart uns beispielseweise "builtins.length" zu schreiben, + # Das erspart uns beispielsweise "builtins.length" zu schreiben, # anstatt nur "length". @@ -318,10 +318,10 @@ with builtins; [ # Impurity #========================================= - # Da die Wiederholbarkeit von Builds für den Nix Packetmangager entscheidend ist, + # Da die Wiederholbarkeit von Builds für den Nix Packetmanager entscheidend ist, # werden in der Nix Sprache reine funktionale Elemente betont. Es gibt aber ein paar # unreine Elemente. - # Du kannst auf Umgebungsvarialben verweisen. + # Du kannst auf Umgebungsvariablen verweisen. (getEnv "HOME") #=> "/home/alice" @@ -331,7 +331,7 @@ with builtins; [ #=> trace: 1 #=> 2 - # Du kannst Dateien in den Nix store schreiben. Obwohl unrein, kannst du dir relativ sicher sein, + # Du kannst Dateien in den Nix Store schreiben. Obwohl unrein, kannst du dir relativ sicher sein, # dass es sicher ist, da der Dateiname aus dem Hash des Inhalts abgeleitet wird. # Du kannst Dateien von überall lesen. In diesem Beispiel schreiben wir Dateien in den Store # und lesen wieder davon. @@ -339,14 +339,14 @@ with builtins; [ [filename (builtins.readFile filename)]) #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] - # Außerdem können wir Dateien in den Nix Store downloaden. + # Außerdem können wir Dateien in den Nix Store herunterladen. (fetchurl "https://example.com/package-1.2.3.tgz") #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" ] ``` -### Weitere Resourcen +### Weitere Ressourcen * [Nix Manual - Nix expression language] (https://nixos.org/nix/manual/#ch-expression-language) -- cgit v1.2.3 From d1ed7e02da50f3e03e517175b1ff866332c049f2 Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Mon, 30 Oct 2017 23:55:40 +1030 Subject: Improve TreeMap documentation --- java.html.markdown | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 621d500c..36d56625 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -280,7 +280,7 @@ public class LearnJava { // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for a // doubly-linked list. - // Maps - A set of objects that map keys to values. Map is + // Maps - A mapping of key Objects to value Objects. Map is // an interface and therefore cannot be instantiated. // The type of keys and values contained in a Map must // be specified upon instantiation of the implementing @@ -289,10 +289,16 @@ public class LearnJava { // HashMaps - This class uses a hashtable to implement the Map // interface. This allows the execution time of basic // operations, such as get and insert element, to remain - // constant even for large sets. - // TreeMap - This class is a sorted tree structure. It implements a red - // black tree and sorts the entries based on the key value or - // the comparator provided while creating the object + // constant-amortized even for large sets. + // TreeMap - A Map that is sorted by its keys. Each modification + // maintains the sorting defined by either a Comparator + // supplied at instantiation, or comparisons of each Object + // if they implement the Comparable interface. + // Failure of keys to implement Comparable combined with failure to + // supply a Comparator will throw ClassCastExceptions. + // Insertion and removal operations take O(log(n)) time + // so avoid using this data structure unless you are taking + // advantage of the sorting. /////////////////////////////////////// // Operators -- cgit v1.2.3 From 833c7bea6ced906d32e4029e704d1a2a831c9b05 Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Mon, 30 Oct 2017 23:58:22 +1030 Subject: Improve arithmetic output --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 36d56625..dd875c16 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -312,7 +312,7 @@ public class LearnJava { System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) - System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5 // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 -- cgit v1.2.3 From 3ffb8256ae007b55df71f63de66428b51f64a003 Mon Sep 17 00:00:00 2001 From: Meisyarah Dwiastuti Date: Tue, 31 Oct 2017 09:54:09 +0100 Subject: Add data type checking examples --- python.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 946cbc0c..89fa7046 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -363,6 +363,12 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False +10 not in filled_set # => True + +# Check data type of variable +type(li) # => list +type(filled_dict) # => dict +type(5) # => int #################################################### -- cgit v1.2.3 From 90058a767241d54b3f42a032b6aaae78f43d3889 Mon Sep 17 00:00:00 2001 From: Nasgul Date: Tue, 31 Oct 2017 13:51:56 +0200 Subject: Add delete of variable Add delete of variable --- ru-ru/php-ru.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 014ff5d0..af77a9ca 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -61,6 +61,8 @@ $int4 = 0x0F; // => 15 (ведущие символы 0x означают шес // Двоичная запись integer доступна начиная с PHP 5.4.0. $int5 = 0b11111111; // 255 (0b в начале означает двоичное число) +// Удаление переменной +unset($int1); // Дробные числа $float = 1.234; -- cgit v1.2.3 From ef8e72783bb0d308c799f0a6c62dc9285e4809e7 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Fri, 27 Oct 2017 17:43:16 +0700 Subject: Added Vietnamese translation for Sass language --- vi-vn/sass-vi.html.markdown | 590 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 vi-vn/sass-vi.html.markdown diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown new file mode 100644 index 00000000..313890d4 --- /dev/null +++ b/vi-vn/sass-vi.html.markdown @@ -0,0 +1,590 @@ +--- +language: sass +filename: learnsass-vi.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy. +Bài hướng dẫn này sử dụng SCSS. + +Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn. + +```sass + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Variable - Biến +============================== */ + + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '$' để khai báo một biến. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Control Directive - Chỉ thị +============================== */ + + +/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */ + +/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại. + Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line). + Chế độ này rất có ích khi thực hiện debug trên file SCSS. */ + +.info { + display: inline-block; +} + +/* @for là khối vòng lặp trên một khoảng các giá trị. + Nó rất có ích cho việc đặt style của một tập hợp các phần tử. + Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */ + +// Lặp 3 lần (không kể 4) +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +// Lặp 3 lần (kể cả 3) +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Biên dịch thành */ + +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS tự động chuyển mã #FFFFFF thành white (trắng) +} + +/* Khối lặp @while rất cơ bản: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Sẽ được biên dịch thành: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm. + List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Sẽ sinh ra: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/* Mixin +==============================*/ + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. + Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height + bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Biên dịch thành: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Function - Hàm +============================== */ + + + +/* Less cung cấp các hàm có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Hàm được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25); +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa hàm mới. + hàm khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên + sáng giá cho việc dùng hàm có thể tái sử dụng được. +*/ + +/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Biên dịch thành: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Mở rộng (Thừa kế) +============================== */ + + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + + +/* Nesting - Lồng +============================== */ + + + +/* Sass cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào +============================== */ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS. + File con không được biên dịch thành file CSS riêng. */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Placeholder Selectors - Selector trống +============================== */ + + + +/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng. + Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể + sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì + sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Biên dịch thành: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Toán tử toán học +============================== */ + + + +/* Sass cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Sass thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS hay Sass? +Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass. +Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc). + + +## Tập sử dụng Sass +Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS. + +## Tính tương thích +Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức. -- cgit v1.2.3 From 28ce1bc6d79a817de6145638af34778879c4e4fb Mon Sep 17 00:00:00 2001 From: thanhpd Date: Tue, 31 Oct 2017 22:12:33 +0700 Subject: Added Vietnamese translation for Markdown language --- vi-vn/markdown-vi.html.markdown | 325 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 325 insertions(+) create mode 100644 vi-vn/markdown-vi.html.markdown diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown new file mode 100644 index 00000000..0ba267f9 --- /dev/null +++ b/vi-vn/markdown-vi.html.markdown @@ -0,0 +1,325 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] + - ["Jacob Ward", "http://github.com/JacobCWard/"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +filename: markdown-vi.md +lang: vi-vn +--- + + +Ngôn ngữ Markdown được sáng lập bởi John Gruber vào năm 2004. Nó được tạo ra với mục đích dễ đọc với cú pháp có thể được dễ dàng chuyển đổi qua HTML và các ngôn ngữ khác + +Markdown có sự khác biệt trong cách cài đặt giữa các trình phân tích cú pháp. Hướng dẫn này sẽ đề cập, giải thích tới nếu tính năng có thể được sử dụng chung hay nó chỉ áp dụng cho một trình phân tích riêng biệt. + +- [Phần tử HTML](#html-elements) +- [Đầu mục](#headings) +- [Định dạng văn bản](#simple-text-styles) +- [Đoạn văn](#paragraphs) +- [Danh sách](#lists) +- [Khối code](#code-blocks) +- [Đường kẻ ngang](#horizontal-rule) +- [Liên kết](#links) +- [Ảnh](#images) +- [Khác](#miscellany) + +## Phần tử HTML +Markdown là tập cha của HTML, vì vậy bất cứ file HTML nào đều là Markdown đúng. + +```markdown + +``` + +## Đầu mục + +Ta có thể tạo các phần tử đầu mục HTML từ `

` cho đến `

` dễ dàng +bằng cách thêm số lượng dấu thăng (#) đằng trước chuỗi cần tạo đầu mục. + +```markdown +# Đây là đầu mục

+## Đây là đầu mục

+### Đây là đầu mục

+#### Đây là đầu mục

+##### Đây là đầu mục

+###### Đây là đầu mục
+``` +Markdown còn cung cấp cách khác để tạo đầu mục hạng nhất h1 và hạng nhì h2. + +```markdown +Đây là đầu mục h1 +============= + +Đây là đầu mục h2 +------------- +``` + +## Định dạng văn bản + +Văn bản có thể được định dạng dễ dàng như in nghiêng hay làm đậm sử dụng Markdown. + +```markdown +*Đoạn văn bản này được in nghiêng.* +_Và đoạn này cũng như vậy._ + +**Đoạn văn bản này được in đậm.** +__Và đoạn này cũng vậy.__ + +***Đoạn văn bản này được in nghiêng và đậm.*** +**_Cách này cũng tương tự_** +*__Và cách này nữa__* +``` + +Trong cài đặt Markdown để hiển thị file của GitHub,ta còn có gạch ngang: + +```markdown +~~Đoạn văn bản này được gạch ngang.~~ +``` +## Đoạn văn + +Đoạn văn bao gồm một hay nhiều dòng văn bản liên tiếp nhau được phân cách +bởi một hay nhiều dòng trống. + +```markdown +Đây là đoạn văn thứ nhất. + +Đây là đoạn văn thứ hai. +Dòng này vẫn thuộc đoạn văn thứ hai, do không có cách dòng. + + +Đây là đoạn văn thứ ba. +``` + +Nếu cần chèn thêm thẻ ngắt dòng `
` của HTML, ta có thể kết thúc đoạn văn bản +bằng cách thêm vào từ 2 dấu cách (space) trở lên và bắt đầu đoạn văn bản mới. + +```markdown +Dòng này kết thúc với 2 dấu cách (highlight để nhìn thấy). + +Có phần tử
ở bên trên. +``` + +Khối trích dẫn được sử dụng với kí tự > + +```markdown +> Đây là khối trích dẫn. Ta có thể +> ngắt dòng thủ công và thêm kí tự `>` trước mỗi dòng hoặc ta có thể để dòng tự ngắt nếu cần thiệt khi quá dài. +> Không có sự khác biệt nào, chỉ cần nó bắt đầu với kí tự `>` + +> Ta còn có thể dùng nhiều mức +>> của khối trích dẫn. +> Như vậy có tốt không? + +``` + +## Danh sách + +Danh sách không có thứ tự có thể được tạo sử dụng dấu sao, dấu cộng hay dấu trừ đầu dòng. + +```markdown +* Một mục +* Một mục +* Một mục nữa + +hoặc + ++ Một mục ++ Một mục ++ Một mục khác + +hay + +- Một mục +- Một mục +- Một mục sau +``` + +Danh sách có thứ tự được tạo bởi một số theo sau bằng một dấu chấm. + +```markdown +1. Mục thứ nhất +2. Mục thứ hai +3. Mục thứ ba +``` + +Ta không nhất thiết phải điền số thứ thự cho chỉ mục đúng mà Markdown sẽ tự hiển thị danh sách theo thứ tự đã được sắp xếp, tuy nhiên cách làm này không tốt! + +```markdown +1. Mục thứ nhất +1. Mục thứ hai +1. Mục thứ ba +``` +(Sẽ hiển thị như ví dụ trước đó) + +Ta còn có thể sử dụng danh sách con + +```markdown +1. Mục thứ nhất +2. Mục thứ hai +3. Mục thứ ba + * Mục nhỏ + * Mục nhỏ +4. Mục thứ tư +``` + +Markdown còn cung cấp danh mục (checklist). Nó sẽ hiển thị ra hộp đánh dấu dạng HTML. + +```markdown +Boxes below without the 'x' are unchecked HTML checkboxes. +- [ ] First task to complete. +- [ ] Second task that needs done +This checkbox below will be a checked HTML checkbox. +- [x] This task has been completed +``` + +## Khối code + +Ta có thể đánh dấu một đoạn code (tương tự sử dụng phần tử HTML ``) bằng việc thụt đầu dòng sử dụng bốn dấu cách (space) hoặc một dấu nhảy (tab) + +```markdown + This is code + So is this +``` + +Ta còn có thể thêm dấu nhảy (hoặc thêm vào bốn dấu cách nữa) để căn chỉnh phần bên trong đoạn code + +```markdown + my_array.each do |item| + puts item + end +``` + +Code hiển thị cùng dòng có thể được đánh dấu sử dụng cặp ``. + +```markdown +John didn't even know what the `go_to()` function did! +``` + +Trong Markdown của GitHub, ta còn có thêm cách để hiển thị code: + +
+```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 \`\`\` +Đoạn trên không cần sử dụng thụt đầu dòng, và GitHub sẽ tô sáng cú pháp sử dụng ngôn ngữ mà ta cung cấp sau đoạn kí tự \`\`\` + +## Kẻ ngang + +Dòng kẻ ngang (`
`) có thể được thêm vào dễ dàng sử dụng từ 3 kí tự sao (*) hoặc gạch ngang (-), không quan trọng có khoảng cách giữa các kí tự hay không. + + +```markdown +*** +--- +- - - +**************** +``` + +## Liên kết + +Một trong những thứ tốt nhất khi làm việc với Markdown là khả năng tạo liên kết hết sức dễ dàng. Đoạn text hiển thị được đóng trong cặp ngoặc vuông [] kèm theo đường dẫn url trong cặp ngoặc tròn (). + +```markdown +[Click me!](http://test.com/) +``` +Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nháy bên trong cặp ngoặc tròn + +```markdown +[Click me!](http://test.com/ "Link to Test.com") +``` +Đường dẫn tương đối cũng hoạt động. + +```markdown +[Go to music](/music/). +``` + +Markdown còn hỗ trợ liên kết kiểu tham chiếu. + +
[Nhấn vào đây][link1] để xem thêm!
+[Ngoài ra nhấn vào đây][foobar] nếu bạn muốn xem qua.
+
+[link1]: http://test.com/ "Tuyệt!"
+[foobar]: http://foobar.biz/ "Tốt!"
+ +Tiêu đề có thể được đóng trong dấu nháy hay ngoặc đơn, hoặc có thể được bỏ qua. Tham chiếu có thể được đặt bất kì đâu trong văn bản và ID của tham chiếu có thể là bất kì gì miễn là nó độc nhất. + +Ngoài ra còn có kiểu đặt tên ngầm cho phép ta sử dụng đường dẫn làm ID. + +
[This][] is a link.
+
+[this]: http://thisisalink.com/
+ +Nhưng nó không được sử dụng rộng rãi. + +## Ảnh + +Hiển thị ảnh tương tự như liên kết nhưng có thêm dấu chấm than đằng trước + +```markdown +![Thuộc tính alt cho ảnh](http://imgur.com/myimage.jpg "Tiêu đề tùy chọn") +``` + +Và kiểu tham chiếu cũng hoạt động như vậy. + +
![Đây là thuộc tính alt.][myimage]
+
+[myimage]: relative/urls/cool/image.jpg "Đây là tiêu đề"
+ +## Khác + +### Tự động đặt liên kết + +```markdown + tương đương với +[http://testwebsite.com/](http://testwebsite.com/) +``` + +### Tự động đặt liên kết cho email + +```markdown + +``` + +### Hiển thị Kí tự đặc biệt + +```markdown +Khi ta muốn viết *đoạn văn bản này có dấu sao bao quanh* nhưng ta không muốn nó bị in nghiêng, ta có thể sử dụng: \*đoạn văn bản này có dấu sao bao quanh\*. +``` + +### Phím bàn phím + +Trong Markdown của Github, ta có thể sử dụng thẻ `` để thay cho phím trên bàn phím. + +```markdown +Máy treo? Thử bấm tổ hợp +Ctrl+Alt+Del +``` +### Bảng biểu + +Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v và khá khó viết: + +```markdown +| Cột 1 | Cột2 | Cột 3 | +| :----------- | :------: | ------------: | +| Căn trái | Căn giữa | Căn phải | +| blah | blah | blah | +``` +Hoặc có thể sử dụng kết quả dưới đây + +```markdown +Cột 1 | Cột 2 | Cột 3 +:-- | :-: | --: +blah | blah | blah +``` + +--- +Để biết thêm thông tin, hãy ghé qua hướng dẫn chính thức về cú pháp của John Gruber [tại đây](http://daringfireball.net/projects/markdown/syntax) và cheatsheet của Adam Pritchard [tại đây](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From a877bebb6f64fe99aeb777e763e6a8839dfad985 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Thu, 2 Nov 2017 12:22:33 -0700 Subject: [chapel/en] Update links Chapel changed their home site from chapel.cray.com to chapel-lang.org. All chapel links are changed, have been tested, and currently work. All links were tested as well, and all currently work. Also, I changed my (Ian J. Bertolacci) collaborators link to my new institution. --- chapel.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index e9c4019a..9190f462 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -2,11 +2,11 @@ language: chapel filename: learnchapel.chpl contributors: - - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] - - ["Ben Harshbarger", "http://github.com/benharsh/"] + - ["Ian J. Bertolacci", "https://www.cs.arizona.edu/~ianbertolacci/"] + - ["Ben Harshbarger", "https://github.com/benharsh/"] --- -You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com). +You can read all about Chapel at [Cray's official Chapel website](https://chapel-lang.org). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. @@ -1124,16 +1124,16 @@ This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) and -the [module documentation](http://chapel.cray.com/docs/latest/) for more +Refer to the [language specification](https://chapel-lang.org/docs/latest/language/spec.html) and +the [module documentation](https://chapel-lang.org/docs/latest/) for more details. -Occasionally check back here and on the [Chapel site](http://chapel.cray.com) +Occasionally check back here and on the [Chapel site](https://chapel-lang.org) to see if more topics have been added or more tutorials created. ### What this tutorial is lacking: - * Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html) + * Exposition of the [standard modules](https://chapel-lang.org/docs/latest/modules/standard.html) * Multiple Locales (distributed memory system) * Records * Parallel iterators -- cgit v1.2.3 From beec5bf9ac9146fec973f96be2917630d230e26b Mon Sep 17 00:00:00 2001 From: LukaxFeh <32396925+LukaxFeh@users.noreply.github.com> Date: Mon, 6 Nov 2017 10:49:48 -0200 Subject: Fix file names (#2987) Fix file names * fix file names * fix file names * fix file names * fix file names * fix file names * Fixed file name * fixed file name * fixed file name * fixed file name * fixed file name * fixed file name * fixed file name --- sk-sk/bash-sk.html.markdown | 286 +++++++++++++++++++ sk-sk/bash.html.markdown | 286 ------------------- sk-sk/coffeescript-sk.html.markdown | 108 +++++++ sk-sk/coffeescript.html.markdown | 108 ------- sk-sk/elixir-sk.html.markdown | 470 ++++++++++++++++++++++++++++++ sk-sk/elixir.html.markdown | 470 ------------------------------ sk-sk/git-sk.html.markdown | 523 ++++++++++++++++++++++++++++++++++ sk-sk/git.html.markdown | 523 ---------------------------------- sk-sk/json-sk.html.markdown | 61 ++++ sk-sk/json.html.markdown | 61 ---- sk-sk/latex-sk.html.markdown.tex | 227 +++++++++++++++ sk-sk/latex.html.markdown.tex | 227 --------------- sk-sk/ruby-sk.html.markdown | 553 ++++++++++++++++++++++++++++++++++++ sk-sk/ruby.html.markdown | 553 ------------------------------------ 14 files changed, 2228 insertions(+), 2228 deletions(-) create mode 100644 sk-sk/bash-sk.html.markdown delete mode 100644 sk-sk/bash.html.markdown create mode 100644 sk-sk/coffeescript-sk.html.markdown delete mode 100644 sk-sk/coffeescript.html.markdown create mode 100644 sk-sk/elixir-sk.html.markdown delete mode 100644 sk-sk/elixir.html.markdown create mode 100644 sk-sk/git-sk.html.markdown delete mode 100644 sk-sk/git.html.markdown create mode 100644 sk-sk/json-sk.html.markdown delete mode 100644 sk-sk/json.html.markdown create mode 100644 sk-sk/latex-sk.html.markdown.tex delete mode 100644 sk-sk/latex.html.markdown.tex create mode 100644 sk-sk/ruby-sk.html.markdown delete mode 100644 sk-sk/ruby.html.markdown diff --git a/sk-sk/bash-sk.html.markdown b/sk-sk/bash-sk.html.markdown new file mode 100644 index 00000000..e9d1490c --- /dev/null +++ b/sk-sk/bash-sk.html.markdown @@ -0,0 +1,286 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: LearnBash-sk.sh +--- + +Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol +tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený +shell pre Linux a Mac OS X. +Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo +vykonané priamo v shelli. + +[Viac informácií tu.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Prvý riadok skriptu je tzv. shebang, ktorý systému povie ako skript vykonať: +# http://en.wikipedia.org/wiki/Shebang_(Unix) +# Komentáre začínajú znakom #. Shebang je tiež komentár. + +# Jednoduchý príklad: +echo Ahoj svet! + +# Každý príkaz začína na novom riadku alebo za bodkočiarkou: +echo 'Toto je prvý riadok'; echo 'Toto je druhý riadok' + +# Deklarácia premenných vyzerá takto: +Premenna="Nejaky retazec" + +# Ale nie takto: +Premenna = "Nejaky retazec" +# Bash si bude myslieť, že Premenna je príkaz, ktorý musí vykonať. +# Výsledkom bude chyba, pretože taký príkaz nenájde. + +# Alebo takto: +Premenna= 'Nejaky retazec' +# Bash zistí, že 'Nejaky retazec' je príkaz, ktorý musí vykonať. +# Výsledkom je opäť chyba, lebo taký príkaz neexistuje. + +# Používanie premenných: +echo $Premenna +echo "$Premenna" +echo '$Premenna' +# Keď je premenná použitá samostatne - priradenie, exportovanie a pod. - jej +# meno sa píše bez znaku $. Keď sa používa hodnota premennej, pred názov sa +# dáva znak $. Pozor však pri použití ' (apostrof), ktorý nenahradí premennú +# hodnotou! + +# Nahradenie reťazca v premennej +echo ${Premenna/Nieco/A} +# Toto nahradí prvý výskyt reťazca "Nieco" za "A" + +# Podreťazec z premennej +Dlzka=7 +echo ${Premenna:0:Dlzka} +# Toto vráti iba prvých 7 znakov z hodnoty premennej + +# Predvolená hodnota premennej +echo ${Foo:-"PredvolenaHodnotaAkFooChybaAleboJePrazdna"} +# Toto funguje pre null (Foo=) a prázdny reťazec (Foo=""); +# nula (Foo=0) vráti 0. Všimni si, že toto iba vráti predvolenú hodnotu, +# ale nezmení hodnotu premennej. + +# Štandardné premenné: +# Existujú aj užitočné "vstavané" premenné, ako +echo "Hodnota vrátená posledným programom: $?" +echo "PID skriptu: $$" +echo "Počet argumentov: $#" +echo "Argumeny skriptu: $@" +echo "Argumeny skriptu oddelené do rôznych premenných: $1 $2..." + +# Čítanie hodnoty zo vstupu: +echo "Ako sa voláš?" +read Meno # Premenná nemusí byť deklarovaná skôr +echo Ahoj, $Meno! + +# Klasická if štruktúra: +# použi 'man test' Pre viac informácií o podmienkach +if [ $Meno -ne $USER ] +then + echo "Meno nie je tvoje používateľské meno" +else + echo "Meno je tvoje používateľské meno" +fi + +# Existuje aj podmienené vykonanie +echo "Vykonané vždy" || echo "Vykonané iba ak prvý príkaz zlyhá" +echo "Vykonané vždy" && echo "Vykonané iba ak prvý príkaz uspeje" + +# Pre použitie && a || s if-podmienkou je potrebné použiť zátvorky: +if [ $Meno == "Steve" ] && [ $Vek -eq 15 ] +then + echo "Toto sa spustí ak $Meno je Steve a $Vek je 15." +fi + +if [ $Meno == "Daniya" ] || [ $Meno == "Zach" ] +then + echo "Toto sa spustí ak $Meno je Daniya alebo Zach." +fi + +# Pre výrazy sa používa nasledovný formát: +echo $(( 10 + 5 )) + +# Na rozdiel od programovacích jazykov shell pracuje v kontexte aktuálneho +# adresára. Môžeš si prehliadať súbory a adresáre v aktuálnom adresári pomocou +# príkazu ls: +ls + +# Tieto príkazy majú aj argumenty pre úpravu ich správania: +ls -l # Vypíše zoznam súborov a priečinkov, každý na samostatnom riadku + +# Výsledok predchádzajúceho príkazu môže byť využitý priamo ako vstup pre +# ďalší príkaz. +# Príkaz grep filtruje vstupvyužitím poskytnutého vzoru. Takto môžeme vypísať +# iba .txt súbory: +ls -l | grep "\.txt" + +# Vstup a výstup príkazu (stdin, stdout, stderr) môžu byť presmerované. +# Toto číta stdin až po ^EOF$ a prepíše hello.py riadkami medzi "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Spustí hello.py s rôznymi presmerovaniami pre stdin, stdout a stderr: +python hello.py < "vstup.in" +python hello.py > "vystup.out" +python hello.py 2> "chyby.err" +python hello.py > "vystup-a-chyby.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Chybový výstup prepíše uvedený súbor, ak už existuje. +# Ak chceš výstup pridať za existujúci obsah, použi ">>": +python hello.py >> "vystup.out" 2>> "chyby.err" + +# Prepíše vystup.out, pripojí k chyby.err a spočíta riadky: +info bash 'Basic Shell Features' 'Redirections' > vystup.out 2>> chyby.err +wc -l vystup.out chyby.err + +# Spustí príkaz a vypíše deskriptor súboru (napr. /dev/fd/123) +# pozri: man fd +echo <(echo "#ahojsvet") + +# Prepíše vystup.out s "#ahojsvet": +cat > vystup.out <(echo "#ahojsvet") +echo "#ahojsvet" > vystup.out +echo "#ahojsvet" | cat > vystup.out +echo "#ahojsvet" | tee vystup.out >/dev/null + +# Potichu odstráni dočasné súbory (pridaj '-i' pre interaktivitu) +rm -v vystup.out chyby.err vystup-a-chyby.log + +# Príkazy môžu byť nahradené v iných príkazoch použitím $( ): +# Nasledujúci príkaz vypíše počet súborov a adresárov v aktuálnom adresári +echo "Je tu $(ls | wc -l) súborov a priečinkov." + +# To isté sa dá spraviť pomocou spätného apostrofu ``, tie však nemôžu byť +# vhniezdené - preferovaný spôsob je preto $( ). +echo "Je tu `ls | wc -l` súborov a priečinkov." + +# Bash používa case, ktorý funguje podobne ako switch v Jave a C++: +case "$Premenna" in + #Zoznam vzorov pre podmienky + 0) echo "Je to nula.";; + 1) echo "Je to jednotka.";; + *) echo "Nie je to null.";; +esac + +# for-cyklus iteruje cez všetky argumenty: +# Obsah premennej $Premenna sa vypíše trikrát. +for Premenna in {1..3} +do + echo "$Premenna" +done + +# Alebo "tradičným" spôsobom: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Môžu sa použiť aj na súbory.. +# Toto spustí príkaz 'cat' na subor1 a subor2 +for Premenna in subor1 subor2 +do + cat "$Premenna" +done + +# ..alebo na výstup príkazu. +# Toto použije príkaz cat na výstup z ls. +for Vystup in $(ls) +do + cat "$Vystup" +done + +# while-cykklus: +while [ true ] +do + echo "telo cyklu..." + break +done + +# Môžeš tiež definovať funkice +# Definícia: +function foo () +{ + echo "Argumenty fungujú rovnako ako pri skriptoch: $@" + echo "A: $1 $2..." + echo "Toto je funkcia" + return 0 +} + +# alebo jednoducho +bar () +{ + echo "Iný spôsob definície funkcií" + return 0 +} + +# Volanie funkcie +foo "Moje meno je" $Meno + +# Existuje veľa užitočných príkazov, ktoré sa oplatí naučiť: +# vypíše posledných 10 riadkov zo subor.txt +tail -n 10 subor.txt +# vypíše prvých 10 riadkov zo subor.txt +head -n 10 subor.txt +# zotriedi riadky zo subor.txt +sort subor.txt +# vypíše alebo vynechá opakované riadky, použitím -d ich vypíše +uniq -d subor.txt +# vypíše iba prvý stĺpecpred znakom ',' +cut -d ',' -f 1 subor.txt +# nahradí každý výskyt 'oukej' za 'super' v subor.txt (možnosť použiť regex) +sed -i 's/oukej/super/g' subor.txt +# vypíše všetky riadky zo subor.txt ktoré vyhovujú regexu +# ukážka vypíše riadky ktoré začínajú s "foo" a končia s "bar" +grep "^foo.*bar$" subor.txt +# pre výpis počtu riadkov vyhovujúcich regexu slúži "-c" +grep -c "^foo.*bar$" subor.txt +# pre vyhľadávanie reťazca bez regexu slúži fgrep (alebo grep -F) +fgrep "^foo.*bar$" subor.txt + + +# Prečítaj si dokumentáciu k Bash shellu použitím príkazu 'help': +help +help help +help for +help return +help source +help . + +# Prečítaj si Bash manpage dokumentáciu príkazom 'man' +apropos bash +man 1 bash +man bash + +# Prečítaj si info dokumentáciu pomocou 'info' (? pre help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Prečítaj si bash info dokumentáciu: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown deleted file mode 100644 index e9d1490c..00000000 --- a/sk-sk/bash.html.markdown +++ /dev/null @@ -1,286 +0,0 @@ ---- -category: tool -tool: bash -contributors: - - ["Max Yankov", "https://github.com/golergka"] - - ["Darren Lin", "https://github.com/CogBear"] - - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] - - ["Denis Arh", "https://github.com/darh"] - - ["akirahirose", "https://twitter.com/akirahirose"] - - ["Anton Strömkvist", "http://lutic.org/"] - - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gregrory Kielian", "https://github.com/gskielian"] - - ["Etan Reisner", "https://github.com/deryni"] -translators: - - ["Juraj Kostolanský", "http://www.kostolansky.sk"] -lang: sk-sk -filename: LearnBash-sk.sh ---- - -Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol -tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený -shell pre Linux a Mac OS X. -Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo -vykonané priamo v shelli. - -[Viac informácií tu.](http://www.gnu.org/software/bash/manual/bashref.html) - -```bash -#!/bin/bash -# Prvý riadok skriptu je tzv. shebang, ktorý systému povie ako skript vykonať: -# http://en.wikipedia.org/wiki/Shebang_(Unix) -# Komentáre začínajú znakom #. Shebang je tiež komentár. - -# Jednoduchý príklad: -echo Ahoj svet! - -# Každý príkaz začína na novom riadku alebo za bodkočiarkou: -echo 'Toto je prvý riadok'; echo 'Toto je druhý riadok' - -# Deklarácia premenných vyzerá takto: -Premenna="Nejaky retazec" - -# Ale nie takto: -Premenna = "Nejaky retazec" -# Bash si bude myslieť, že Premenna je príkaz, ktorý musí vykonať. -# Výsledkom bude chyba, pretože taký príkaz nenájde. - -# Alebo takto: -Premenna= 'Nejaky retazec' -# Bash zistí, že 'Nejaky retazec' je príkaz, ktorý musí vykonať. -# Výsledkom je opäť chyba, lebo taký príkaz neexistuje. - -# Používanie premenných: -echo $Premenna -echo "$Premenna" -echo '$Premenna' -# Keď je premenná použitá samostatne - priradenie, exportovanie a pod. - jej -# meno sa píše bez znaku $. Keď sa používa hodnota premennej, pred názov sa -# dáva znak $. Pozor však pri použití ' (apostrof), ktorý nenahradí premennú -# hodnotou! - -# Nahradenie reťazca v premennej -echo ${Premenna/Nieco/A} -# Toto nahradí prvý výskyt reťazca "Nieco" za "A" - -# Podreťazec z premennej -Dlzka=7 -echo ${Premenna:0:Dlzka} -# Toto vráti iba prvých 7 znakov z hodnoty premennej - -# Predvolená hodnota premennej -echo ${Foo:-"PredvolenaHodnotaAkFooChybaAleboJePrazdna"} -# Toto funguje pre null (Foo=) a prázdny reťazec (Foo=""); -# nula (Foo=0) vráti 0. Všimni si, že toto iba vráti predvolenú hodnotu, -# ale nezmení hodnotu premennej. - -# Štandardné premenné: -# Existujú aj užitočné "vstavané" premenné, ako -echo "Hodnota vrátená posledným programom: $?" -echo "PID skriptu: $$" -echo "Počet argumentov: $#" -echo "Argumeny skriptu: $@" -echo "Argumeny skriptu oddelené do rôznych premenných: $1 $2..." - -# Čítanie hodnoty zo vstupu: -echo "Ako sa voláš?" -read Meno # Premenná nemusí byť deklarovaná skôr -echo Ahoj, $Meno! - -# Klasická if štruktúra: -# použi 'man test' Pre viac informácií o podmienkach -if [ $Meno -ne $USER ] -then - echo "Meno nie je tvoje používateľské meno" -else - echo "Meno je tvoje používateľské meno" -fi - -# Existuje aj podmienené vykonanie -echo "Vykonané vždy" || echo "Vykonané iba ak prvý príkaz zlyhá" -echo "Vykonané vždy" && echo "Vykonané iba ak prvý príkaz uspeje" - -# Pre použitie && a || s if-podmienkou je potrebné použiť zátvorky: -if [ $Meno == "Steve" ] && [ $Vek -eq 15 ] -then - echo "Toto sa spustí ak $Meno je Steve a $Vek je 15." -fi - -if [ $Meno == "Daniya" ] || [ $Meno == "Zach" ] -then - echo "Toto sa spustí ak $Meno je Daniya alebo Zach." -fi - -# Pre výrazy sa používa nasledovný formát: -echo $(( 10 + 5 )) - -# Na rozdiel od programovacích jazykov shell pracuje v kontexte aktuálneho -# adresára. Môžeš si prehliadať súbory a adresáre v aktuálnom adresári pomocou -# príkazu ls: -ls - -# Tieto príkazy majú aj argumenty pre úpravu ich správania: -ls -l # Vypíše zoznam súborov a priečinkov, každý na samostatnom riadku - -# Výsledok predchádzajúceho príkazu môže byť využitý priamo ako vstup pre -# ďalší príkaz. -# Príkaz grep filtruje vstupvyužitím poskytnutého vzoru. Takto môžeme vypísať -# iba .txt súbory: -ls -l | grep "\.txt" - -# Vstup a výstup príkazu (stdin, stdout, stderr) môžu byť presmerované. -# Toto číta stdin až po ^EOF$ a prepíše hello.py riadkami medzi "EOF": -cat > hello.py << EOF -#!/usr/bin/env python -from __future__ import print_function -import sys -print("#stdout", file=sys.stdout) -print("#stderr", file=sys.stderr) -for line in sys.stdin: - print(line, file=sys.stdout) -EOF - -# Spustí hello.py s rôznymi presmerovaniami pre stdin, stdout a stderr: -python hello.py < "vstup.in" -python hello.py > "vystup.out" -python hello.py 2> "chyby.err" -python hello.py > "vystup-a-chyby.log" 2>&1 -python hello.py > /dev/null 2>&1 -# Chybový výstup prepíše uvedený súbor, ak už existuje. -# Ak chceš výstup pridať za existujúci obsah, použi ">>": -python hello.py >> "vystup.out" 2>> "chyby.err" - -# Prepíše vystup.out, pripojí k chyby.err a spočíta riadky: -info bash 'Basic Shell Features' 'Redirections' > vystup.out 2>> chyby.err -wc -l vystup.out chyby.err - -# Spustí príkaz a vypíše deskriptor súboru (napr. /dev/fd/123) -# pozri: man fd -echo <(echo "#ahojsvet") - -# Prepíše vystup.out s "#ahojsvet": -cat > vystup.out <(echo "#ahojsvet") -echo "#ahojsvet" > vystup.out -echo "#ahojsvet" | cat > vystup.out -echo "#ahojsvet" | tee vystup.out >/dev/null - -# Potichu odstráni dočasné súbory (pridaj '-i' pre interaktivitu) -rm -v vystup.out chyby.err vystup-a-chyby.log - -# Príkazy môžu byť nahradené v iných príkazoch použitím $( ): -# Nasledujúci príkaz vypíše počet súborov a adresárov v aktuálnom adresári -echo "Je tu $(ls | wc -l) súborov a priečinkov." - -# To isté sa dá spraviť pomocou spätného apostrofu ``, tie však nemôžu byť -# vhniezdené - preferovaný spôsob je preto $( ). -echo "Je tu `ls | wc -l` súborov a priečinkov." - -# Bash používa case, ktorý funguje podobne ako switch v Jave a C++: -case "$Premenna" in - #Zoznam vzorov pre podmienky - 0) echo "Je to nula.";; - 1) echo "Je to jednotka.";; - *) echo "Nie je to null.";; -esac - -# for-cyklus iteruje cez všetky argumenty: -# Obsah premennej $Premenna sa vypíše trikrát. -for Premenna in {1..3} -do - echo "$Premenna" -done - -# Alebo "tradičným" spôsobom: -for ((a=1; a <= 3; a++)) -do - echo $a -done - -# Môžu sa použiť aj na súbory.. -# Toto spustí príkaz 'cat' na subor1 a subor2 -for Premenna in subor1 subor2 -do - cat "$Premenna" -done - -# ..alebo na výstup príkazu. -# Toto použije príkaz cat na výstup z ls. -for Vystup in $(ls) -do - cat "$Vystup" -done - -# while-cykklus: -while [ true ] -do - echo "telo cyklu..." - break -done - -# Môžeš tiež definovať funkice -# Definícia: -function foo () -{ - echo "Argumenty fungujú rovnako ako pri skriptoch: $@" - echo "A: $1 $2..." - echo "Toto je funkcia" - return 0 -} - -# alebo jednoducho -bar () -{ - echo "Iný spôsob definície funkcií" - return 0 -} - -# Volanie funkcie -foo "Moje meno je" $Meno - -# Existuje veľa užitočných príkazov, ktoré sa oplatí naučiť: -# vypíše posledných 10 riadkov zo subor.txt -tail -n 10 subor.txt -# vypíše prvých 10 riadkov zo subor.txt -head -n 10 subor.txt -# zotriedi riadky zo subor.txt -sort subor.txt -# vypíše alebo vynechá opakované riadky, použitím -d ich vypíše -uniq -d subor.txt -# vypíše iba prvý stĺpecpred znakom ',' -cut -d ',' -f 1 subor.txt -# nahradí každý výskyt 'oukej' za 'super' v subor.txt (možnosť použiť regex) -sed -i 's/oukej/super/g' subor.txt -# vypíše všetky riadky zo subor.txt ktoré vyhovujú regexu -# ukážka vypíše riadky ktoré začínajú s "foo" a končia s "bar" -grep "^foo.*bar$" subor.txt -# pre výpis počtu riadkov vyhovujúcich regexu slúži "-c" -grep -c "^foo.*bar$" subor.txt -# pre vyhľadávanie reťazca bez regexu slúži fgrep (alebo grep -F) -fgrep "^foo.*bar$" subor.txt - - -# Prečítaj si dokumentáciu k Bash shellu použitím príkazu 'help': -help -help help -help for -help return -help source -help . - -# Prečítaj si Bash manpage dokumentáciu príkazom 'man' -apropos bash -man 1 bash -man bash - -# Prečítaj si info dokumentáciu pomocou 'info' (? pre help) -apropos info | grep '^info.*(' -man info -info info -info 5 info - -# Prečítaj si bash info dokumentáciu: -info bash -info bash 'Bash Features' -info bash 6 -info --apropos bash -``` diff --git a/sk-sk/coffeescript-sk.html.markdown b/sk-sk/coffeescript-sk.html.markdown new file mode 100644 index 00000000..30bbceec --- /dev/null +++ b/sk-sk/coffeescript-sk.html.markdown @@ -0,0 +1,108 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: coffeescript-fr.coffee +--- + +CoffeeScript je jazyk, ktorý sa kompiluje do ekvivalentného JavaScriptu, +neexistuje peňho interpretácia počas behu programu (runtime). +CoffeeScript sa snaží vytvárať čitateľný, pekne formátovaný a optimalizovaný +JavaScriptový kód pracujúci pod každým JavaScriptovým prostredím. + +Pozri tiež [stránku CoffeeScript](http://coffeescript.org/), ktoré obsahuje kompletný tutoriál o CoffeeScripte. + +```coffeescript +# CoffeeScript je jazyk hipsterov. +# Ide s trendom mnohých moderných jazykov. +# Komentáre sú podobné tým v Ruby a Pythone, používajú symbol #. + +### +Blokové komentáre vyzerajú takto, prekladajú sa priamo do '/ * ... * /' +pre výsledný kód JavaScriptu. + +Predtým, než budeš pokračovať, mal by si rozumieť sémantike JavaScriptu. +### + +# Priradenia: +cislo = 42 #=> var cislo = 42; +opak = true #=> var opak = true; + +# Podmienky: +cislo = -42 if opak #=> if(opak) { cislo = -42; } + +# Funkcie: +stvorec = (x) -> x * x #=> var stvorec = function(x) { return x * x; } + +vypln = (nadoba, tekutina = "káva") -> + "#{nadoba} sa napĺňa tekutinou #{tekutina}..." +#=>var vypln; +# +#vypln = function(nadoba, tekutina) { +# if (tekutina == null) { +# tekutina = "káva"; +# } +# return nadoba + " sa napĺňa tekutinou " + tekutina + "..."; +#}; + +# Rozsahy: +zoznam = [1..5] #=> var zoznam = [1, 2, 3, 4, 5]; + +# Objekty: +matika = + zaklad: Math.sqrt + stvorec: square + kocka: (x) -> x * square x +#=> var matika = { +# "zaklad": Math.sqrt, +# "stvorec": square, +# "kocka": function(x) { return x * square(x); } +#} + +# Splat operátor: +zavod = (vitaz, bezci...) -> + print vitaz, bezci +#=>zavod = function() { +# var vitaz, bezci; +# vitaz = arguments[0], +# bezci = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vitaz, bezci); +#}; + +# Existencia: +alert "Vedel som to!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) +# { alert("Vedel som to!"); } + +# Pole: +kocky = (matika.kocka cislo for cislo in zoznam) +#=>kocky = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = zoznam.length; _i < _len; _i++) { +# cislo = zoznam[_i]; +# _results.push(matika.kocka(cislo)); +# } +# return _results; +# })(); + +jedla = ['brokolica', 'špenát', 'čokoláda'] +zjedz jedlo for jedlo in jedla when jedlo isnt 'čokoláda' +#=>jedla = ['brokolica', 'špenát', 'čokoláda']; +# +#for (_k = 0, _len2 = jedla.length; _k < _len2; _k++) { +# jedlo = jedla[_k]; +# if (jedlo !== 'čokoláda') { +# zjedz(jedlo); +# } +#} +``` + +## Ďalšie zdroje + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/sk-sk/coffeescript.html.markdown b/sk-sk/coffeescript.html.markdown deleted file mode 100644 index 30bbceec..00000000 --- a/sk-sk/coffeescript.html.markdown +++ /dev/null @@ -1,108 +0,0 @@ ---- -language: coffeescript -contributors: - - ["Tenor Biel", "http://github.com/L8D"] - - ["Xavier Yao", "http://github.com/xavieryao"] -translators: - - ["Juraj Kostolanský", "http://www.kostolansky.sk"] -lang: sk-sk -filename: coffeescript-fr.coffee ---- - -CoffeeScript je jazyk, ktorý sa kompiluje do ekvivalentného JavaScriptu, -neexistuje peňho interpretácia počas behu programu (runtime). -CoffeeScript sa snaží vytvárať čitateľný, pekne formátovaný a optimalizovaný -JavaScriptový kód pracujúci pod každým JavaScriptovým prostredím. - -Pozri tiež [stránku CoffeeScript](http://coffeescript.org/), ktoré obsahuje kompletný tutoriál o CoffeeScripte. - -```coffeescript -# CoffeeScript je jazyk hipsterov. -# Ide s trendom mnohých moderných jazykov. -# Komentáre sú podobné tým v Ruby a Pythone, používajú symbol #. - -### -Blokové komentáre vyzerajú takto, prekladajú sa priamo do '/ * ... * /' -pre výsledný kód JavaScriptu. - -Predtým, než budeš pokračovať, mal by si rozumieť sémantike JavaScriptu. -### - -# Priradenia: -cislo = 42 #=> var cislo = 42; -opak = true #=> var opak = true; - -# Podmienky: -cislo = -42 if opak #=> if(opak) { cislo = -42; } - -# Funkcie: -stvorec = (x) -> x * x #=> var stvorec = function(x) { return x * x; } - -vypln = (nadoba, tekutina = "káva") -> - "#{nadoba} sa napĺňa tekutinou #{tekutina}..." -#=>var vypln; -# -#vypln = function(nadoba, tekutina) { -# if (tekutina == null) { -# tekutina = "káva"; -# } -# return nadoba + " sa napĺňa tekutinou " + tekutina + "..."; -#}; - -# Rozsahy: -zoznam = [1..5] #=> var zoznam = [1, 2, 3, 4, 5]; - -# Objekty: -matika = - zaklad: Math.sqrt - stvorec: square - kocka: (x) -> x * square x -#=> var matika = { -# "zaklad": Math.sqrt, -# "stvorec": square, -# "kocka": function(x) { return x * square(x); } -#} - -# Splat operátor: -zavod = (vitaz, bezci...) -> - print vitaz, bezci -#=>zavod = function() { -# var vitaz, bezci; -# vitaz = arguments[0], -# bezci = 2 <= arguments.length ? __slice.call(arguments, 1) : []; -# return print(vitaz, bezci); -#}; - -# Existencia: -alert "Vedel som to!" if elvis? -#=> if(typeof elvis !== "undefined" && elvis !== null) -# { alert("Vedel som to!"); } - -# Pole: -kocky = (matika.kocka cislo for cislo in zoznam) -#=>kocky = (function() { -# var _i, _len, _results; -# _results = []; -# for (_i = 0, _len = zoznam.length; _i < _len; _i++) { -# cislo = zoznam[_i]; -# _results.push(matika.kocka(cislo)); -# } -# return _results; -# })(); - -jedla = ['brokolica', 'špenát', 'čokoláda'] -zjedz jedlo for jedlo in jedla when jedlo isnt 'čokoláda' -#=>jedla = ['brokolica', 'špenát', 'čokoláda']; -# -#for (_k = 0, _len2 = jedla.length; _k < _len2; _k++) { -# jedlo = jedla[_k]; -# if (jedlo !== 'čokoláda') { -# zjedz(jedlo); -# } -#} -``` - -## Ďalšie zdroje - -- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) -- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/sk-sk/elixir-sk.html.markdown b/sk-sk/elixir-sk.html.markdown new file mode 100644 index 00000000..2401f92e --- /dev/null +++ b/sk-sk/elixir-sk.html.markdown @@ -0,0 +1,470 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] +translators: + - ["Peter Szatmary", "https://github.com/peterszatmary"] +lang: sk-sk +filename: learnelixir-sk.ex +--- + +Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym +strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax +a množstvo funkcií. + +```Elixir + +# Jednoriadkový komentár začína symbolom # + +# Neexistuje viacriadkový komentár, avšak je možné vyskladať za sebou viac +# jednoriadkových komentárov. + +# Pre spustenie Elixir shellu zadajte príkaz `iex` +# Kompiláciu zdrojových kódov vykonáte príkazom `elixirc` + +# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir +# správne. + +## --------------------------- +## -- Základné typy +## --------------------------- + +# Čísla +3 # integer +0x1F # integer +3.0 # float + +# Atómy, sú literály, konštanty s rovnakým menom. Začínajú s `:`. +:ahoj # atom + +# Tzv. Tuples sú v pamäti uložené súvisle. +{1,2,3} # tuple + +# Pristúpiť k tuple elementu vieme pomocou funkcie `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Zoznamy sú implementované ako linkované zoznamy. +[1,2,3] # zoznam + +# Vieme pristúpiť k hlavičke (head) a chvostu (tail) zoznamu: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# V Elixire, rovnako ako v Erlangu, `=` znamená pattern matching a nie +# klasické priradenie. +# +# To znamená, že ľavá strana (pattern / vzor) je postavená oproti pravej +# strane. +# +# Takto funguje aj príklad vyššie s čítaním hlavičky a chvosta zoznamu. + +# Pattern match končí chybou ak sa obe strany nezhodujú, v tomto príklade majú +# tuples rôznu veľkosť. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Binárne typy +<<1,2,3>> # binary + +# Reťazce a zoznamy znakov +"ahoj" # reťazec +'ahoj' # zoznam znakov + +# Viacriadkový reťazec +""" +Ja som viacriadkový +reťazec. +""" +#=> "Ja som viacriadkový\nreťazec.\n" + +# Reťazce sú kódované v UTF-8: +"héllò" #=> "héllò" + +# Reťazce sú skutočne iba binárne typy, a zoznamy znakov sú iba zoznamy. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` v elixire vráti ASCII číselnú reprezentáciu pre znak `a` +?a #=> 97 + +# Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'ahoj ' ++ 'svet' #=> 'ahoj svet' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"Ahoj " <> "svet" #=> "ahoj svet" + +# Rozsahy sú reprezentované ako `začiatok..koniec` (obe inkluzívne) +1..10 #=> 1..10 +dolna..horna = 1..10 # Na rozsahy možno použiť rovnako pattern matching +[dolna, horna] #=> [1, 10] + +# Mapy sú páry kľúč-hodnota +pohlavia = %{"david" => "muž", "gillian" => "žena"} +pohlavia["david"] #=> "muž" + +# Mapy s kľúčmi reprezentovanými atómami môžu byť použité takto +pohlavia = %{david: "muž", gillian: "žena"} +pohlavia.gillian #=> "žena" + +## --------------------------- +## -- Operátory +## --------------------------- + +# Trošku matematiky +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# V elixire operátor `/` vždy vráti float (reálne číslo). + +# Pre celočíselné delenie sa používa `div` +div(10, 2) #=> 5 + +# Pre celočíselné delenie so zvyškom `rem` +rem(10, 3) #=> 1 + +# Boolean operátory: `or`, `and` a `not`. +# Tieto operátori očakávajú ako svoj prvý argument boolean. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir tiež poskytuje `||`, `&&` a `!` , ktoré akceptujú argumenty +# ľubovoľného typu. +# Všetky hodnoty okrem `false` a `nil` budú vyhodnotené ako true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Pre porovnávanie máme: `==`, `!=`, `===`, `!==`, `<=`, +`>=`, `<` a `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` a `!==` sú viac striktné pri porovnávaní celých čísel (integer) a +# desatinných čísel (float). +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Vieme porovnať dokonca dva rôzne údajové typy: +1 < :ahoj #=> true + +# Celkové poradie triedenia: +# +# číslo < atom < referencia < funkcia < port < pid < tuple < zoznam < bitový +# string + +# Výrok Joe Armstronga: "Aktuálne poradie nie je dôležité, ale +# dôležité je to, že celkové poradie je dobre definované." + +## --------------------------- +## -- Riadenie toku +## --------------------------- + +# `if` výraz +if false do + "Toto nebude nikdy videné" +else + "Toto bude" +end + +# Existuje aj `unless` +unless true do + "Toto nebude nikdy videné" +else + "Toto bude" +end + +# Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v +# elixire sa spoliehajú práve na pattern matching. + +# `case` dovolí nám porovnať hodnotu oproti mnohým vzorom: +case {:one, :two} do + {:four, :five} -> + "Toto nebude zhodné" + {:one, x} -> + "Toto bude zhodné a nastaví `x` na hodnotu `:two` " + _ -> + "Toto bude zhodné z ľubovoľnou hodnotou." +end + +# Je zvyčajné nastaviť hodnotu do `_` ak ju nepotrebujete. +# Napríklad, ak je pre nás potrebná iba hlavička zoznamu (head): +[head | _] = [1,2,3] +head #=> 1 + +# Pre lepšiu čitateľnosť môžme urobiť nasledovné: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` dovoľuje kontrolovať viac podmienok naraz. +# Použite `cond` namiesto vnorovania mnohých `if` výrazov. +cond do + 1 + 1 == 3 -> + "Nebudem nikdy videný" + 2 * 5 == 12 -> + "Ani ja" + 1 + 2 == 3 -> + "Ja budem" +end + +# Je bežné nastaviť poslednú podmienku rovnajúcu sa `true` , ktorá bude vždy +# zodpovedať. +cond do + 1 + 1 == 3 -> + "Nebudem nikdy videný" + 2 * 5 == 12 -> + "Ani ja" + true -> + "Ale ja budem (je to v podstate vetva else)" +end + +# `try/catch` sa používa na zachytenie hodnôt, ktoré boli vyhodené, takisto +# podporuje `after` klauzulu, ktorá je zavolaná vždy, či bola hodnota +# zachytená alebo nie. +try do + throw(:ahoj) +catch + message -> "Mám #{message}." +after + IO.puts("Som after klauzula.") +end +#=> Som after klauzula +# "Mám :ahoj" + +## --------------------------- +## -- Moduly a funkcie +## --------------------------- + +# Anonymné funkcie (všimnite si bodku) +stvorec = fn(x) -> x * x end +stvorec.(5) #=> 25 + +# Takisto akceptujú viax klauzúl a tzv. stráže (guards). +# Stráže vám umožnia pattern matching ešte viac zlepšiť, tieto časti sú +# označené kľúčovým slovom `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir tiež poskytuje množstvo vstavaných funkcií. +# Tie sú dostupné v aktuálnom scope (viditeľnej oblasti). +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# Možno zgrupovať viac funkcií do jedného modulu. V module použite `def` +# na definíciu funkcie. +defmodule Matematika do + def sucet(a, b) do + a + b + end + + def na_druhu(x) do + x * x + end +end + +Matematika.sucet(1, 2) #=> 3 +Matematika.na_druhu(3) #=> 9 + +# Na zkompilovanie našeho Matematika modulu ho uložte ako `math.ex` a použite +# `elixirc` v termináli: elixirc math.ex + +# V module môžme definovať funkcie s `def` a privátne funkcie s `defp`. +# Funkcia definovaná s `def` je možné volať z iných modulov, privátne funkcie +# môžu byť volané iba lokálne. +defmodule SukromnaMatematika do + def sucet(a, b) do + rob_sucet(a, b) + end + + defp rob_sucet(a, b) do + a + b + end +end + +SukromnaMatematika.sucet(1, 2) #=> 3 +# SukromnaMatematika.rob_sucet(1, 2) #=> ** (UndefinedFunctionError) + +# Deklarácie funkcií tiež podporujú stráže (guards) a viacnásobné klauzuly: + +defmodule Geometria do + def oblast({:obdlznik, w, h}) do + w * h + end + + def oblast({:kruh, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometria.oblast({:obdlznik, 2, 3}) #=> 6 +Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048 +# Geometria.oblast({:kruh, "nie_je_cislo"}) +#=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1 + +# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru +defmodule Rekurzia do + def sumuj_zoznam([hlavicka | schvost], acc) do + sumuj_zoznam(chvost, acc + hlavicka) + end + + def sumuj_zoznam([], acc) do + acc + end +end + +Rekurzia.sumuj_zoznam([1,2,3], 0) #=> 6 + +# Elixir moduly podporujú atribúty, existujú vstavané atribúty a takisto +# môžte pridávať vlastné. +defmodule MojModul do + @moduledoc """ + Toto je vstavaný atribút v príkladovom module. + """ + + @moj_udaj 100 # Toto je vlastný atribút. + IO.inspect(@moj_udaj) #=> 100 +end + +# Pipe operátor (rúra) |> umožnuje predať výsledok výrazu ako prvý parameter +# do ďalšej funkcie. + +Range.new(1,10) +|> Enum.map(fn x -> x * x end) +|> Enum.filter(fn x -> rem(x, 2) == 0 end) +#=> [4, 16, 36, 64, 100] + +## --------------------------- +## -- Štruktúry a výnimky +## --------------------------- + +# Štruktúry sú rozšírenia postavené na mapách, ktoré prinášajú defaultné +# hodnoty, garancie v čase kompilácie a polymorfizmus do Elixiru. +defmodule Osoba do + defstruct meno: nil, vek: 0, vyska: 0 +end + +joe_info = %Osoba{ meno: "Joe", vek: 30, vyska: 180 } +#=> %Osoba{vek: 30, vyska: 180, meno: "Joe"} + +# Prístup k hodnote mena +joe_info.meno #=> "Joe" + +# Zmena hodnoty veku +starsi_joe_info = %{ joe_info | vek: 31 } +#=> %Osoba{vek: 31, vyska: 180, meno: "Joe"} + +# `try` blok s kľúčovým slovom `rescue` sa používa na riadenie výnimiek +try do + raise "nejaký error" +rescue + RuntimeError -> "zachytí runtime error" + _error -> "zachytí ľubovoľný iný error" +end +#=> "zachytí runtime error" + +# Každá výnimka má správu +try do + raise "nejaký error" +rescue + x in [RuntimeError] -> + x.message +end +#=> "nejaký error" + +## --------------------------- +## -- Konkurencia +## --------------------------- + +# Elixir sa pri konkurencii spolieha na Actor model. Všetko čo je +# potrebné na písanie konkuretných programov v elixire sú tri primitívy: +# spawning procesy, posielanie a prijímanie správ. + +# Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako +# parameter funkciu. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` vracia pid (identifikátor procesu), tento pid možno použiť na +# posielanie správ procesu. Správu pošleme `send` operatorátorom. +# Aby všetko fungovalo ako má, potrebujeme byť schopný správu prijať. To +# dosiahneme s `receive` mechanizmom: + +# `receive do` blok sa používa na počúvanie správ a ich spracúvavanie v čase +# prijatia. `receive do` blok spracuje iba jednu prijatú správu. Pre +# spracovanie viacerých správ, musí funkcia s `receive do` blokom rekurzívne +# volať samu seba, aby sa dostala opäť do `receive do` bloku. + +defmodule Geometria do + def slucka_oblasti do + receive do + {:obdlznik, w, h} -> + IO.puts("Oblast = #{w * h}") + slucka_oblasti() + {:kruh, r} -> + IO.puts("Oblast = #{3.14 * r * r}") + slucka_oblasti() + end + end +end + +# Kompiluj modul a vytvor proces, ktorý vyhodnotí `slucka_oblasti` v shelli + +pid = spawn(fn -> Geometria.slucka_oblasti() end) #=> #PID<0.40.0> +# Alternatívne +pid = spawn(Geometria, :slucka_oblasti, []) + +# Pošli správu ku `pid`, ktorá bude v zhode so vzorom v receive časti +send pid, {:obdlznik, 2, 3} +#=> Oblast = 6 +# {:obdlznik,2,3} + +send pid, {:kruh, 2} +#=> Oblast = 12.56000000000000049738 +# {:kruh,2} + +# Shell je takisto proces, môžete použiť `self` pre zistenie aktuálneho pid-u +self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agenti +## --------------------------- + +# Agent je proces, ktorý udržuje informácie o meniacej sa hodnote + +# Vytvor agenta s `Agent.start_link` parametrom, ktorého je funkcia +# Iniciálny stav agenta bude čokoľvek, čo daná funkcia vráti +{ok, moj_agent} = Agent.start_link(fn -> ["cervena, zelena"] end) + +# `Agent.get` vezme meno agenta a `fn` , ktorej je odovzdaný aktuálny stav +# Čokoľvek čo `fn` vráti je to, čo dostanete späť +Agent.get(moj_agent, fn farby -> farby end) #=> ["cervena, "zelena"] + +# Zmena stavu agenta rovnakým spôsobom +Agent.update(moj_agent, fn farby -> ["modra" | farby] end) +``` + +## Referencie + +* [Začíname](http://elixir-lang.org/getting-started/introduction.html) z +[Elixir stránky](http://elixir-lang.org) +* [Elixir dokumentácia](http://elixir-lang.org/docs/master/) +* [Elixir programovanie](https://pragprog.com/book/elixir/programming-elixir) + od Dave Thomasa +* [Elixir ťahák](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* [Nauč sa kúsok Erlangu pre veľké dobro!](http://learnyousomeerlang.com/) od +Freda Heberta +* [Erlang programovanie: Softvér pre konkurentný svet](https://pragprog +.com/book/jaerlang2/programming-erlang) od Joe Armstronga diff --git a/sk-sk/elixir.html.markdown b/sk-sk/elixir.html.markdown deleted file mode 100644 index 2401f92e..00000000 --- a/sk-sk/elixir.html.markdown +++ /dev/null @@ -1,470 +0,0 @@ ---- -language: elixir -contributors: - - ["Joao Marques", "http://github.com/mrshankly"] - - ["Dzianis Dashkevich", "https://github.com/dskecse"] - - ["Ryan Plant", "https://github.com/ryanplant-au"] -translators: - - ["Peter Szatmary", "https://github.com/peterszatmary"] -lang: sk-sk -filename: learnelixir-sk.ex ---- - -Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym -strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax -a množstvo funkcií. - -```Elixir - -# Jednoriadkový komentár začína symbolom # - -# Neexistuje viacriadkový komentár, avšak je možné vyskladať za sebou viac -# jednoriadkových komentárov. - -# Pre spustenie Elixir shellu zadajte príkaz `iex` -# Kompiláciu zdrojových kódov vykonáte príkazom `elixirc` - -# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir -# správne. - -## --------------------------- -## -- Základné typy -## --------------------------- - -# Čísla -3 # integer -0x1F # integer -3.0 # float - -# Atómy, sú literály, konštanty s rovnakým menom. Začínajú s `:`. -:ahoj # atom - -# Tzv. Tuples sú v pamäti uložené súvisle. -{1,2,3} # tuple - -# Pristúpiť k tuple elementu vieme pomocou funkcie `elem`: -elem({1, 2, 3}, 0) #=> 1 - -# Zoznamy sú implementované ako linkované zoznamy. -[1,2,3] # zoznam - -# Vieme pristúpiť k hlavičke (head) a chvostu (tail) zoznamu: -[head | tail] = [1,2,3] -head #=> 1 -tail #=> [2,3] - -# V Elixire, rovnako ako v Erlangu, `=` znamená pattern matching a nie -# klasické priradenie. -# -# To znamená, že ľavá strana (pattern / vzor) je postavená oproti pravej -# strane. -# -# Takto funguje aj príklad vyššie s čítaním hlavičky a chvosta zoznamu. - -# Pattern match končí chybou ak sa obe strany nezhodujú, v tomto príklade majú -# tuples rôznu veľkosť. -# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} - -# Binárne typy -<<1,2,3>> # binary - -# Reťazce a zoznamy znakov -"ahoj" # reťazec -'ahoj' # zoznam znakov - -# Viacriadkový reťazec -""" -Ja som viacriadkový -reťazec. -""" -#=> "Ja som viacriadkový\nreťazec.\n" - -# Reťazce sú kódované v UTF-8: -"héllò" #=> "héllò" - -# Reťazce sú skutočne iba binárne typy, a zoznamy znakov sú iba zoznamy. -<> #=> "abc" -[?a, ?b, ?c] #=> 'abc' - -# `?a` v elixire vráti ASCII číselnú reprezentáciu pre znak `a` -?a #=> 97 - -# Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>` -[1,2,3] ++ [4,5] #=> [1,2,3,4,5] -'ahoj ' ++ 'svet' #=> 'ahoj svet' - -<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> -"Ahoj " <> "svet" #=> "ahoj svet" - -# Rozsahy sú reprezentované ako `začiatok..koniec` (obe inkluzívne) -1..10 #=> 1..10 -dolna..horna = 1..10 # Na rozsahy možno použiť rovnako pattern matching -[dolna, horna] #=> [1, 10] - -# Mapy sú páry kľúč-hodnota -pohlavia = %{"david" => "muž", "gillian" => "žena"} -pohlavia["david"] #=> "muž" - -# Mapy s kľúčmi reprezentovanými atómami môžu byť použité takto -pohlavia = %{david: "muž", gillian: "žena"} -pohlavia.gillian #=> "žena" - -## --------------------------- -## -- Operátory -## --------------------------- - -# Trošku matematiky -1 + 1 #=> 2 -10 - 5 #=> 5 -5 * 2 #=> 10 -10 / 2 #=> 5.0 - -# V elixire operátor `/` vždy vráti float (reálne číslo). - -# Pre celočíselné delenie sa používa `div` -div(10, 2) #=> 5 - -# Pre celočíselné delenie so zvyškom `rem` -rem(10, 3) #=> 1 - -# Boolean operátory: `or`, `and` a `not`. -# Tieto operátori očakávajú ako svoj prvý argument boolean. -true and true #=> true -false or true #=> true -# 1 and true #=> ** (ArgumentError) argument error - -# Elixir tiež poskytuje `||`, `&&` a `!` , ktoré akceptujú argumenty -# ľubovoľného typu. -# Všetky hodnoty okrem `false` a `nil` budú vyhodnotené ako true. -1 || true #=> 1 -false && 1 #=> false -nil && 20 #=> nil -!true #=> false - -# Pre porovnávanie máme: `==`, `!=`, `===`, `!==`, `<=`, -`>=`, `<` a `>` -1 == 1 #=> true -1 != 1 #=> false -1 < 2 #=> true - -# `===` a `!==` sú viac striktné pri porovnávaní celých čísel (integer) a -# desatinných čísel (float). -1 == 1.0 #=> true -1 === 1.0 #=> false - -# Vieme porovnať dokonca dva rôzne údajové typy: -1 < :ahoj #=> true - -# Celkové poradie triedenia: -# -# číslo < atom < referencia < funkcia < port < pid < tuple < zoznam < bitový -# string - -# Výrok Joe Armstronga: "Aktuálne poradie nie je dôležité, ale -# dôležité je to, že celkové poradie je dobre definované." - -## --------------------------- -## -- Riadenie toku -## --------------------------- - -# `if` výraz -if false do - "Toto nebude nikdy videné" -else - "Toto bude" -end - -# Existuje aj `unless` -unless true do - "Toto nebude nikdy videné" -else - "Toto bude" -end - -# Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v -# elixire sa spoliehajú práve na pattern matching. - -# `case` dovolí nám porovnať hodnotu oproti mnohým vzorom: -case {:one, :two} do - {:four, :five} -> - "Toto nebude zhodné" - {:one, x} -> - "Toto bude zhodné a nastaví `x` na hodnotu `:two` " - _ -> - "Toto bude zhodné z ľubovoľnou hodnotou." -end - -# Je zvyčajné nastaviť hodnotu do `_` ak ju nepotrebujete. -# Napríklad, ak je pre nás potrebná iba hlavička zoznamu (head): -[head | _] = [1,2,3] -head #=> 1 - -# Pre lepšiu čitateľnosť môžme urobiť nasledovné: -[head | _tail] = [:a, :b, :c] -head #=> :a - -# `cond` dovoľuje kontrolovať viac podmienok naraz. -# Použite `cond` namiesto vnorovania mnohých `if` výrazov. -cond do - 1 + 1 == 3 -> - "Nebudem nikdy videný" - 2 * 5 == 12 -> - "Ani ja" - 1 + 2 == 3 -> - "Ja budem" -end - -# Je bežné nastaviť poslednú podmienku rovnajúcu sa `true` , ktorá bude vždy -# zodpovedať. -cond do - 1 + 1 == 3 -> - "Nebudem nikdy videný" - 2 * 5 == 12 -> - "Ani ja" - true -> - "Ale ja budem (je to v podstate vetva else)" -end - -# `try/catch` sa používa na zachytenie hodnôt, ktoré boli vyhodené, takisto -# podporuje `after` klauzulu, ktorá je zavolaná vždy, či bola hodnota -# zachytená alebo nie. -try do - throw(:ahoj) -catch - message -> "Mám #{message}." -after - IO.puts("Som after klauzula.") -end -#=> Som after klauzula -# "Mám :ahoj" - -## --------------------------- -## -- Moduly a funkcie -## --------------------------- - -# Anonymné funkcie (všimnite si bodku) -stvorec = fn(x) -> x * x end -stvorec.(5) #=> 25 - -# Takisto akceptujú viax klauzúl a tzv. stráže (guards). -# Stráže vám umožnia pattern matching ešte viac zlepšiť, tieto časti sú -# označené kľúčovým slovom `when`: -f = fn - x, y when x > 0 -> x + y - x, y -> x * y -end - -f.(1, 3) #=> 4 -f.(-1, 3) #=> -3 - -# Elixir tiež poskytuje množstvo vstavaných funkcií. -# Tie sú dostupné v aktuálnom scope (viditeľnej oblasti). -is_number(10) #=> true -is_list("hello") #=> false -elem({1,2,3}, 0) #=> 1 - -# Možno zgrupovať viac funkcií do jedného modulu. V module použite `def` -# na definíciu funkcie. -defmodule Matematika do - def sucet(a, b) do - a + b - end - - def na_druhu(x) do - x * x - end -end - -Matematika.sucet(1, 2) #=> 3 -Matematika.na_druhu(3) #=> 9 - -# Na zkompilovanie našeho Matematika modulu ho uložte ako `math.ex` a použite -# `elixirc` v termináli: elixirc math.ex - -# V module môžme definovať funkcie s `def` a privátne funkcie s `defp`. -# Funkcia definovaná s `def` je možné volať z iných modulov, privátne funkcie -# môžu byť volané iba lokálne. -defmodule SukromnaMatematika do - def sucet(a, b) do - rob_sucet(a, b) - end - - defp rob_sucet(a, b) do - a + b - end -end - -SukromnaMatematika.sucet(1, 2) #=> 3 -# SukromnaMatematika.rob_sucet(1, 2) #=> ** (UndefinedFunctionError) - -# Deklarácie funkcií tiež podporujú stráže (guards) a viacnásobné klauzuly: - -defmodule Geometria do - def oblast({:obdlznik, w, h}) do - w * h - end - - def oblast({:kruh, r}) when is_number(r) do - 3.14 * r * r - end -end - -Geometria.oblast({:obdlznik, 2, 3}) #=> 6 -Geometria.oblast({:kruh, 3}) #=> 28.25999999999999801048 -# Geometria.oblast({:kruh, "nie_je_cislo"}) -#=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1 - -# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru -defmodule Rekurzia do - def sumuj_zoznam([hlavicka | schvost], acc) do - sumuj_zoznam(chvost, acc + hlavicka) - end - - def sumuj_zoznam([], acc) do - acc - end -end - -Rekurzia.sumuj_zoznam([1,2,3], 0) #=> 6 - -# Elixir moduly podporujú atribúty, existujú vstavané atribúty a takisto -# môžte pridávať vlastné. -defmodule MojModul do - @moduledoc """ - Toto je vstavaný atribút v príkladovom module. - """ - - @moj_udaj 100 # Toto je vlastný atribút. - IO.inspect(@moj_udaj) #=> 100 -end - -# Pipe operátor (rúra) |> umožnuje predať výsledok výrazu ako prvý parameter -# do ďalšej funkcie. - -Range.new(1,10) -|> Enum.map(fn x -> x * x end) -|> Enum.filter(fn x -> rem(x, 2) == 0 end) -#=> [4, 16, 36, 64, 100] - -## --------------------------- -## -- Štruktúry a výnimky -## --------------------------- - -# Štruktúry sú rozšírenia postavené na mapách, ktoré prinášajú defaultné -# hodnoty, garancie v čase kompilácie a polymorfizmus do Elixiru. -defmodule Osoba do - defstruct meno: nil, vek: 0, vyska: 0 -end - -joe_info = %Osoba{ meno: "Joe", vek: 30, vyska: 180 } -#=> %Osoba{vek: 30, vyska: 180, meno: "Joe"} - -# Prístup k hodnote mena -joe_info.meno #=> "Joe" - -# Zmena hodnoty veku -starsi_joe_info = %{ joe_info | vek: 31 } -#=> %Osoba{vek: 31, vyska: 180, meno: "Joe"} - -# `try` blok s kľúčovým slovom `rescue` sa používa na riadenie výnimiek -try do - raise "nejaký error" -rescue - RuntimeError -> "zachytí runtime error" - _error -> "zachytí ľubovoľný iný error" -end -#=> "zachytí runtime error" - -# Každá výnimka má správu -try do - raise "nejaký error" -rescue - x in [RuntimeError] -> - x.message -end -#=> "nejaký error" - -## --------------------------- -## -- Konkurencia -## --------------------------- - -# Elixir sa pri konkurencii spolieha na Actor model. Všetko čo je -# potrebné na písanie konkuretných programov v elixire sú tri primitívy: -# spawning procesy, posielanie a prijímanie správ. - -# Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako -# parameter funkciu. -f = fn -> 2 * 2 end #=> #Function -spawn(f) #=> #PID<0.40.0> - -# `spawn` vracia pid (identifikátor procesu), tento pid možno použiť na -# posielanie správ procesu. Správu pošleme `send` operatorátorom. -# Aby všetko fungovalo ako má, potrebujeme byť schopný správu prijať. To -# dosiahneme s `receive` mechanizmom: - -# `receive do` blok sa používa na počúvanie správ a ich spracúvavanie v čase -# prijatia. `receive do` blok spracuje iba jednu prijatú správu. Pre -# spracovanie viacerých správ, musí funkcia s `receive do` blokom rekurzívne -# volať samu seba, aby sa dostala opäť do `receive do` bloku. - -defmodule Geometria do - def slucka_oblasti do - receive do - {:obdlznik, w, h} -> - IO.puts("Oblast = #{w * h}") - slucka_oblasti() - {:kruh, r} -> - IO.puts("Oblast = #{3.14 * r * r}") - slucka_oblasti() - end - end -end - -# Kompiluj modul a vytvor proces, ktorý vyhodnotí `slucka_oblasti` v shelli - -pid = spawn(fn -> Geometria.slucka_oblasti() end) #=> #PID<0.40.0> -# Alternatívne -pid = spawn(Geometria, :slucka_oblasti, []) - -# Pošli správu ku `pid`, ktorá bude v zhode so vzorom v receive časti -send pid, {:obdlznik, 2, 3} -#=> Oblast = 6 -# {:obdlznik,2,3} - -send pid, {:kruh, 2} -#=> Oblast = 12.56000000000000049738 -# {:kruh,2} - -# Shell je takisto proces, môžete použiť `self` pre zistenie aktuálneho pid-u -self() #=> #PID<0.27.0> - -## --------------------------- -## -- Agenti -## --------------------------- - -# Agent je proces, ktorý udržuje informácie o meniacej sa hodnote - -# Vytvor agenta s `Agent.start_link` parametrom, ktorého je funkcia -# Iniciálny stav agenta bude čokoľvek, čo daná funkcia vráti -{ok, moj_agent} = Agent.start_link(fn -> ["cervena, zelena"] end) - -# `Agent.get` vezme meno agenta a `fn` , ktorej je odovzdaný aktuálny stav -# Čokoľvek čo `fn` vráti je to, čo dostanete späť -Agent.get(moj_agent, fn farby -> farby end) #=> ["cervena, "zelena"] - -# Zmena stavu agenta rovnakým spôsobom -Agent.update(moj_agent, fn farby -> ["modra" | farby] end) -``` - -## Referencie - -* [Začíname](http://elixir-lang.org/getting-started/introduction.html) z -[Elixir stránky](http://elixir-lang.org) -* [Elixir dokumentácia](http://elixir-lang.org/docs/master/) -* [Elixir programovanie](https://pragprog.com/book/elixir/programming-elixir) - od Dave Thomasa -* [Elixir ťahák](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) -* [Nauč sa kúsok Erlangu pre veľké dobro!](http://learnyousomeerlang.com/) od -Freda Heberta -* [Erlang programovanie: Softvér pre konkurentný svet](https://pragprog -.com/book/jaerlang2/programming-erlang) od Joe Armstronga diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown new file mode 100644 index 00000000..21741406 --- /dev/null +++ b/sk-sk/git-sk.html.markdown @@ -0,0 +1,523 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] + - ["Andrew Taylor", "http://github.com/andrewjt71"] +translators: + - ["Terka Slanináková", "http://github.com/TerkaSlan"] +lang: sk-sk +filename: LearnGit-sk.txt +--- + +Git je distribuovaný systém riadenia revízií a správy zdrojového kódu. + +Funguje robením "snímkov" tvojho projektu, s ktorými ďalej pracuje na revíziach a správe zdrojových kódov. + +## Koncept Revízií + +### Čo je riadenie revízií? + +Riadenie revízií je systém, ktorý postupom času zaznamenáva zmeny súboru (súborov). + +### Centralizované Revízie VS Distribuované revízie + +* Centralizované riadenie revízií sa zameriava na synchronizáciu, sledovanie a zálohovanie súborov. +* Distribuované riadenie revízií sa zameriava na zdieľanie zmien. Kaťdá zmena má jedinečný identifikátor (id). +* Distribuované systémy nemajú definovanú štruktúru. S gitom môžeš mať centralizovaný systém v subversion (SVN) štýle. + +[Ďalšie informácie](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Prečo Používať Git? + +* Môžeš pracovať offline. +* Spolupráca s ostatnými je jednoduchá! +* Vetvenie je jednoduché! +* Zlučovanie je jednoduché! +* Git je rýchly. +* Git je flexibilný. + +## Architektúra Gitu + + +### Repozitár + +Skupina súborov, adresárov, minulých záznamov, commitov (konkrétnych revízií) a odkazy na aktuálu vetvu (HEADs). Predstav si ho ako údajovú štruktúru, kde ti každý "prvok" zdrojového kódu poskytne (okrem iného) prístup k minulým revíziam. + +Git repozitár sa skladá z .git adresára a pracovného stromu + +### .git Adresár (časť repozitára) + +.git adresár obsahuje všetky konfigurácie, logy, vetvy, odkaz na aktuálnu vetvu (HEAD) a ostatné. +[Detailný zoznam.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Pracovný Strom (Working Tree - časť repozitára) + +Toto sú adresáre a súbory v tvojom repozitári. Tiež sa tomu hovorí pracovný adresár. + +### Index (časť .git adresára) + +Index je také odpočívadlo Gitu. Je to v podstate vrstva, ktorá oddeľuje pracovný strom od Git repozitára. Toto dáva vývojárom viac možností nad tým, čo do repozitára naozaj pošlú. + +### Commit + +Commit je "snímka" zmien, či manipulácií s tvojím Pracovným Stromom. Ak si napríklad pridal 5 súborov a odstránil 2 ďalšie, tieto zmeny budú zachytené v commite. Ten môže (ale nemusí) byť zverejnený (pushed) do iných repozitárov. + +### Vetva (Branch) + +Vetva je ukazateľ na posledný vykonaný commit. Po ďalších commitnutiach sa ukazateľ bude automaticky posúvať na ten najnovší. + +### Tag + +Tag je označenie špecifického bodu v minulosti. Typicky sa používa na značenie vydaných verzií (v1.0, atď). + +### HEAD a head (časť .git adresára) + +HEAD je ukazateľ na aktuálnu vetvu. Repozitár má len 1 *aktívny* HEAD. +head je ukazateľ, ktorý môže ukazovať na akýkoľvek commit. Repozitár môže mať niekoľko headov. + +### Štádia Gitu +* Modified - Súbor bol zmenený, no nebol ešte commitnutý do Git Databázy. +* Staged - Zmenený súbor, ktorý pôjde do najbližšieho commit snímku. +* Committed - Súbory boli commitnuté do Git Databázy. + +### Koncepčné zdroje + +* [Git Pre Informatikov](http://eagain.net/articles/git-for-computer-scientists/) +* [Git Pre Designerov](http://hoth.entp.com/output/git_for_designers.html) + + +## Príkazy + + +### init + +Vytvorí prázdny Git repozitár. Jeho nastavenia, uložené informácie a mnoho iného sú uložené v adresári (zložke) s názvom ".git". + +```bash +$ git init +``` + +### config + +Konfiguruj nastavenia. Či už pre repozitár, samotný systém, alebo globálne konfigurácie (súbor pre globálny config je `~/.gitconfig`). + + +```bash +# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne) +$ git config --global user.email "MôjEmail@Zoho.com" +$ git config --global user.name "Moje Meno " +``` + +[Prečítaj si viac o git configu.](http://git-scm.com/docs/git-config) + +### pomoc + +Máš tiež prístup k extrémne detailnej dokumentácií pre každý príkaz (po anglicky). Hodí sa, ak potrebuješ pripomenúť semantiku. + +```bash +# Rýchlo zobraz všetky dostupné príkazy +$ git help + +# Zobraz všetky dostupné príkazy +$ git help -a + +# Zobraz konkrétnu pomoc - použivateľský manuál +# git help +$ git help add +$ git help commit +$ git help init +# alebo git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignoruj súbory + +Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore +``` + + +### status + +Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a aktuálnym HEAD commitom. + + +```bash +# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely +$ git status + +# Zistí iné vychytávky o git statuse +$ git help status +``` + +### add + +Pripraví súbory na commit pridaním do tzv. staging indexu. Ak ich nepridáš pomocou `git add` do staging indexu, nebudú zahrnuté v commitoch! + +```bash +# pridá súbor z tvojho pracovného adresára +$ git add HelloWorld.java + +# pridá súbor z iného adresára +$ git add /cesta/k/súboru/HelloWorld.c + +# Môžeš použiť regulárne výrazy! +$ git add ./*.java +``` +Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára. + +### branch + +Spravuj svoje vetvy. Môžeš ich pomocou tohto príkazu zobraziť, meniť, vytvoriť, či zmazať. + +```bash +# zobraz existujúce vetvy a vzdialené repozitáre +$ git branch -a + +# vytvor novú vetvu +$ git branch myNewBranch + +# vymaž vetvu +$ git branch -d myBranch + +# premenuj vetvu +# git branch -m +$ git branch -m mojaStaraVetva mojaNovaVetva + +# zmeň opis vetvy +$ git branch myBranchName --edit-description +``` + +### tag + +Spravuj svoje tagy + +```bash +# Zobraz tagy +$ git tag +# Vytvor tag so správou +# -m špecifikuje správu, ktorá bude s tagom uložená. +# Ak nešpeficikuješ správu pri tagu so správou, +# Git spustí tvoj editor, aby si ju napísal. +$ git tag -a v2.0 -m 'moja verzia 2.0' +# Ukáž informácie o tagu +# Zobrazí zadané informácie, dátum tagnutia commitu +# a správu pred zobrazením informácií o commite. +$ git show v2.0 +# Zverejní (pushne) jediný tag do vzdialeného repozitára +$ git push origin v2.0 +# Zverejní viacero tagov do vzdialeného repozitára +$ git push origin --tags +``` + +### checkout + +Aktualizuje všetky súbory v pracovnom strome, aby odpovedali verzií v indexe, alebo v inom strome. + +```bash +# Aktualizuj strom, aby odpovedal (predvolene) +# hlavnej vetve repozitáru (master branch) +$ git checkout +# Aktualizuj strom, aby odpovedal konrkétnej vetve +$ git checkout menoVetvy +# Vytvor novú vetvu & prepni sa na ňu +# ekvivalentný príkaz: "git branch ; git checkout " +$ git checkout -b nováVetva +``` + +### clone + +"Naklonuje", alebo vytvorí kópiu existujúceho repozitára do nového adresára. Tiež pridá špeciálne ďiaľkovo-monitorujúce vetvy (remote-tracking branches), ktoré ti umožnia zverejňovať do vzdialených vetiev. + +```bash +# Naklonuj learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# naklonuj iba konkrétnu vetvu +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Uloží aktuálny obsah indexu v novom "commite". Ten obsahuje vytvorené zmeny a s nimi súvisiace správy vytvorené použivateľom. + +```bash +# commitni so správou +$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c" + +# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni. +$ git commit -a -m "Zmenil som foo.php a vymazal bar.php" + +# zmeň posledný commit (toto nahradí predchádzajúci commit novým) +$ git commit --amend -m "Správna správa" +``` + +### diff + +Ukáže rozdiel medzi súborom v pracovnom repozitári, indexe a commitoch. + +```bash +# Ukáž rozdiel medzi pracovným repozitárom a indexom. +$ git diff + +# Ukáž rozdiely medzi indexom a najnovším commitom. +$ git diff --cached + +# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom. +$ git diff HEAD +``` + +### grep + +Umožní ti rýchlo prehľadávať repozitár. + +Možná konfigurácia: + +```bash +# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku +$ git config --global grep.lineNumber true + +# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Vďaka Travisovi Jefferymu za túto sekciu +# Hľadaj "názovPremennej" vo všetkých java súboroch +$ git grep 'názovPremennej' -- '*.java' + +# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google je tvoj kamarát; pre viac príkladov skoč na +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Zobral commity do repozitára. + +```bash +# Zobraz všetky commity +$ git log + +# Zobraz iba správy a referencie commitov +$ git log --oneline + +# Zobraz zlúčené (merged) commity +$ git log --merges + +# Zobraz všetky commity vo forme ASCII grafu +$ git log --graph +``` + +### merge + +"Zlúč" zmeny externých commitov do aktuálnej vetvy. + +```bash +# Zlúč vybranú vetvu do aktuálnej. +$ git merge názovVetvy + +# Vždy vytvor zlučovací commit +$ git merge --no-ff názovVetvy +``` + +### mv + +Premenuj, alebo presuň súbor + +```bash +# Premenuj súbor +$ git mv HelloWorld.c HelloNewWorld.c + +# Presuň súbor +$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c + +# "Nasilu" premenuj, alebo presuň +# "existujúciSúbor" už v adresári existuje, bude prepísaný +$ git mv -f môjSúbor existujúciSúbor +``` + +### pull + +Uloží obsah repozitára a zlúči ho s inou vetvou. + +```bash +# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien +# zo vzdialených "origin" a "master" vetiev. +# git pull +$ git pull origin master + +# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu +# zlúčením nových zmien zo vzdialenej vetvy +$ git pull + +# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase) +# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Zverejní a zlúči zmeny z lokálnej do vzdialenej vetvy. + +```bash +# Zverejni a zlúč zmeny z lokálneho repozitára do +# vzdialených vetiev s názvom "origin" a "master". +# git push +$ git push origin master + +# Predvolene git zverejní a zlúči zmeny z +# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej +$ git push + +# Na spojenie lokálnej vetvy so vzdialenou pridaj -u: +$ git push -u origin master +# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz: +$ git push +``` + +### stash + +Umožní ti opustiť chaotický stav pracovného adresára a uloží ho na zásobník nedokončených zmien, ku ktorým sa môžeš kedykoľvek vrátiť. + +Povedzme, že si urobil nejaké zmeny vo svojom git repozitári, ale teraz potrebuješ pullnúť zo vzdialenej repo. Keďže máš necommitnuté zmeny, príkaz `git pull` nebude fungovať. Namiesto toho môžeš použiť `git stash` a uložiť svoje nedokončené zmeny na zásobník! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Teraz môžeš uložiť vzdialenú vetvu! + +```bash +$ git pull +``` + +Over, či je všetko v poriadku + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +Môžeš si pozrieť, čo za chaos je na zásobníku cez `git stash list`. +Nedokončené zmeny sú uložené ako Last-In-First-Out (Prvý dnu, posledný von) štruktúra, navrchu sa objavia najnovšie zmeny. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log +``` + +Keď so zmenami budeš chcieť pracovať, odstráň ich zo stacku. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` urobí presne to isté + +Hotovo, môžeš pokračovať v práci! + +[Čítaj viac.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + +### rebase (pozor) + +Zober všetky zmeny commitnuté do vetvy a aplikuj ich na inú vetvu. +*Tento príkaz nerob na verejných repozitároch*. + +```bash +# Aplikuj commity z experimentálnej vetvy na master +# git rebase +$ git rebase master experimentBranch +``` + +[Čítaj viac.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (pozor) + +Resetni HEAD (ukazateľ na aktuálnu vetvu) do konrkétneho stavu. To ti umožní vziať späť zlúčenia, zverejnenia, commity, pridania atď. Je to užitočný, no nebezpečný príkaz, pokiaľ nevieš, čo robíš. + +```bash +# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený) +$ git reset + +# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše) +$ git reset --hard + +# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený) +# všetky zmeny sú zachované v adresári. +$ git reset 31f2bb1 + +# Presunie vrchol aktuálnuej vetvy naopak do konkrétneho commitu +# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny). +$ git reset --hard 31f2bb1 +``` +### revert + +Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav +projektu do predchádzajúceho bodu v čase. Revert pridá nový commit, inverzný tomu, ktorý chceš vymazať, tým ho od-urobí. + +```bash +# Vezmi späť konkrétny commit +$ git revert +``` + +### rm + +Opak od git add, rm odstráni súbory z aktuálneho pracovného stromu. + +```bash +# odstráň HelloWorld.c +$ git rm HelloWorld.c + +# Odstráň súbor z vnoreného adresára +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Ďalšie informácie + +* [tryGit - Zábavný interaktívny spôsob, ako sa naučiť Git.](http://try.github.io/levels/1/challenges/1) + +* [Udemy Git Tutoriál: Kompletný návod](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - Návod, ktorý Ťa prevedie základmi Gitu](http://gitimmersion.com/) + +* [git-scm - Video Tutoriály](http://git-scm.com/videos) + +* [git-scm - Dokumentácia](http://git-scm.com/docs) + +* [Atlassian Git - Tutoriály & Postupy](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) + +* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [Úvod do Gitu a GitHubu pre začiatočníkov (Tutoriál)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown deleted file mode 100644 index 21741406..00000000 --- a/sk-sk/git.html.markdown +++ /dev/null @@ -1,523 +0,0 @@ ---- -category: tool -tool: git -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Leo Rudberg" , "http://github.com/LOZORD"] - - ["Betsy Lorton" , "http://github.com/schbetsy"] - - ["Bruno Volcov", "http://github.com/volcov"] - - ["Andrew Taylor", "http://github.com/andrewjt71"] -translators: - - ["Terka Slanináková", "http://github.com/TerkaSlan"] -lang: sk-sk -filename: LearnGit-sk.txt ---- - -Git je distribuovaný systém riadenia revízií a správy zdrojového kódu. - -Funguje robením "snímkov" tvojho projektu, s ktorými ďalej pracuje na revíziach a správe zdrojových kódov. - -## Koncept Revízií - -### Čo je riadenie revízií? - -Riadenie revízií je systém, ktorý postupom času zaznamenáva zmeny súboru (súborov). - -### Centralizované Revízie VS Distribuované revízie - -* Centralizované riadenie revízií sa zameriava na synchronizáciu, sledovanie a zálohovanie súborov. -* Distribuované riadenie revízií sa zameriava na zdieľanie zmien. Kaťdá zmena má jedinečný identifikátor (id). -* Distribuované systémy nemajú definovanú štruktúru. S gitom môžeš mať centralizovaný systém v subversion (SVN) štýle. - -[Ďalšie informácie](http://git-scm.com/book/en/Getting-Started-About-Version-Control) - -### Prečo Používať Git? - -* Môžeš pracovať offline. -* Spolupráca s ostatnými je jednoduchá! -* Vetvenie je jednoduché! -* Zlučovanie je jednoduché! -* Git je rýchly. -* Git je flexibilný. - -## Architektúra Gitu - - -### Repozitár - -Skupina súborov, adresárov, minulých záznamov, commitov (konkrétnych revízií) a odkazy na aktuálu vetvu (HEADs). Predstav si ho ako údajovú štruktúru, kde ti každý "prvok" zdrojového kódu poskytne (okrem iného) prístup k minulým revíziam. - -Git repozitár sa skladá z .git adresára a pracovného stromu - -### .git Adresár (časť repozitára) - -.git adresár obsahuje všetky konfigurácie, logy, vetvy, odkaz na aktuálnu vetvu (HEAD) a ostatné. -[Detailný zoznam.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) - -### Pracovný Strom (Working Tree - časť repozitára) - -Toto sú adresáre a súbory v tvojom repozitári. Tiež sa tomu hovorí pracovný adresár. - -### Index (časť .git adresára) - -Index je také odpočívadlo Gitu. Je to v podstate vrstva, ktorá oddeľuje pracovný strom od Git repozitára. Toto dáva vývojárom viac možností nad tým, čo do repozitára naozaj pošlú. - -### Commit - -Commit je "snímka" zmien, či manipulácií s tvojím Pracovným Stromom. Ak si napríklad pridal 5 súborov a odstránil 2 ďalšie, tieto zmeny budú zachytené v commite. Ten môže (ale nemusí) byť zverejnený (pushed) do iných repozitárov. - -### Vetva (Branch) - -Vetva je ukazateľ na posledný vykonaný commit. Po ďalších commitnutiach sa ukazateľ bude automaticky posúvať na ten najnovší. - -### Tag - -Tag je označenie špecifického bodu v minulosti. Typicky sa používa na značenie vydaných verzií (v1.0, atď). - -### HEAD a head (časť .git adresára) - -HEAD je ukazateľ na aktuálnu vetvu. Repozitár má len 1 *aktívny* HEAD. -head je ukazateľ, ktorý môže ukazovať na akýkoľvek commit. Repozitár môže mať niekoľko headov. - -### Štádia Gitu -* Modified - Súbor bol zmenený, no nebol ešte commitnutý do Git Databázy. -* Staged - Zmenený súbor, ktorý pôjde do najbližšieho commit snímku. -* Committed - Súbory boli commitnuté do Git Databázy. - -### Koncepčné zdroje - -* [Git Pre Informatikov](http://eagain.net/articles/git-for-computer-scientists/) -* [Git Pre Designerov](http://hoth.entp.com/output/git_for_designers.html) - - -## Príkazy - - -### init - -Vytvorí prázdny Git repozitár. Jeho nastavenia, uložené informácie a mnoho iného sú uložené v adresári (zložke) s názvom ".git". - -```bash -$ git init -``` - -### config - -Konfiguruj nastavenia. Či už pre repozitár, samotný systém, alebo globálne konfigurácie (súbor pre globálny config je `~/.gitconfig`). - - -```bash -# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne) -$ git config --global user.email "MôjEmail@Zoho.com" -$ git config --global user.name "Moje Meno " -``` - -[Prečítaj si viac o git configu.](http://git-scm.com/docs/git-config) - -### pomoc - -Máš tiež prístup k extrémne detailnej dokumentácií pre každý príkaz (po anglicky). Hodí sa, ak potrebuješ pripomenúť semantiku. - -```bash -# Rýchlo zobraz všetky dostupné príkazy -$ git help - -# Zobraz všetky dostupné príkazy -$ git help -a - -# Zobraz konkrétnu pomoc - použivateľský manuál -# git help -$ git help add -$ git help commit -$ git help init -# alebo git --help -$ git add --help -$ git commit --help -$ git init --help -``` - -### ignoruj súbory - -Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári. -```bash -$ echo "temp/" >> .gitignore -$ echo "private_key" >> .gitignore -``` - - -### status - -Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a aktuálnym HEAD commitom. - - -```bash -# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely -$ git status - -# Zistí iné vychytávky o git statuse -$ git help status -``` - -### add - -Pripraví súbory na commit pridaním do tzv. staging indexu. Ak ich nepridáš pomocou `git add` do staging indexu, nebudú zahrnuté v commitoch! - -```bash -# pridá súbor z tvojho pracovného adresára -$ git add HelloWorld.java - -# pridá súbor z iného adresára -$ git add /cesta/k/súboru/HelloWorld.c - -# Môžeš použiť regulárne výrazy! -$ git add ./*.java -``` -Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára. - -### branch - -Spravuj svoje vetvy. Môžeš ich pomocou tohto príkazu zobraziť, meniť, vytvoriť, či zmazať. - -```bash -# zobraz existujúce vetvy a vzdialené repozitáre -$ git branch -a - -# vytvor novú vetvu -$ git branch myNewBranch - -# vymaž vetvu -$ git branch -d myBranch - -# premenuj vetvu -# git branch -m -$ git branch -m mojaStaraVetva mojaNovaVetva - -# zmeň opis vetvy -$ git branch myBranchName --edit-description -``` - -### tag - -Spravuj svoje tagy - -```bash -# Zobraz tagy -$ git tag -# Vytvor tag so správou -# -m špecifikuje správu, ktorá bude s tagom uložená. -# Ak nešpeficikuješ správu pri tagu so správou, -# Git spustí tvoj editor, aby si ju napísal. -$ git tag -a v2.0 -m 'moja verzia 2.0' -# Ukáž informácie o tagu -# Zobrazí zadané informácie, dátum tagnutia commitu -# a správu pred zobrazením informácií o commite. -$ git show v2.0 -# Zverejní (pushne) jediný tag do vzdialeného repozitára -$ git push origin v2.0 -# Zverejní viacero tagov do vzdialeného repozitára -$ git push origin --tags -``` - -### checkout - -Aktualizuje všetky súbory v pracovnom strome, aby odpovedali verzií v indexe, alebo v inom strome. - -```bash -# Aktualizuj strom, aby odpovedal (predvolene) -# hlavnej vetve repozitáru (master branch) -$ git checkout -# Aktualizuj strom, aby odpovedal konrkétnej vetve -$ git checkout menoVetvy -# Vytvor novú vetvu & prepni sa na ňu -# ekvivalentný príkaz: "git branch ; git checkout " -$ git checkout -b nováVetva -``` - -### clone - -"Naklonuje", alebo vytvorí kópiu existujúceho repozitára do nového adresára. Tiež pridá špeciálne ďiaľkovo-monitorujúce vetvy (remote-tracking branches), ktoré ti umožnia zverejňovať do vzdialených vetiev. - -```bash -# Naklonuj learnxinyminutes-docs -$ git clone https://github.com/adambard/learnxinyminutes-docs.git -# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku -$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git -# naklonuj iba konkrétnu vetvu -$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch -``` - -### commit - -Uloží aktuálny obsah indexu v novom "commite". Ten obsahuje vytvorené zmeny a s nimi súvisiace správy vytvorené použivateľom. - -```bash -# commitni so správou -$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c" - -# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni. -$ git commit -a -m "Zmenil som foo.php a vymazal bar.php" - -# zmeň posledný commit (toto nahradí predchádzajúci commit novým) -$ git commit --amend -m "Správna správa" -``` - -### diff - -Ukáže rozdiel medzi súborom v pracovnom repozitári, indexe a commitoch. - -```bash -# Ukáž rozdiel medzi pracovným repozitárom a indexom. -$ git diff - -# Ukáž rozdiely medzi indexom a najnovším commitom. -$ git diff --cached - -# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom. -$ git diff HEAD -``` - -### grep - -Umožní ti rýchlo prehľadávať repozitár. - -Možná konfigurácia: - -```bash -# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku -$ git config --global grep.lineNumber true - -# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania -$ git config --global alias.g "grep --break --heading --line-number" -``` - -```bash -# Vďaka Travisovi Jefferymu za túto sekciu -# Hľadaj "názovPremennej" vo všetkých java súboroch -$ git grep 'názovPremennej' -- '*.java' - -# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) -``` - -Google je tvoj kamarát; pre viac príkladov skoč na -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) - -### log - -Zobral commity do repozitára. - -```bash -# Zobraz všetky commity -$ git log - -# Zobraz iba správy a referencie commitov -$ git log --oneline - -# Zobraz zlúčené (merged) commity -$ git log --merges - -# Zobraz všetky commity vo forme ASCII grafu -$ git log --graph -``` - -### merge - -"Zlúč" zmeny externých commitov do aktuálnej vetvy. - -```bash -# Zlúč vybranú vetvu do aktuálnej. -$ git merge názovVetvy - -# Vždy vytvor zlučovací commit -$ git merge --no-ff názovVetvy -``` - -### mv - -Premenuj, alebo presuň súbor - -```bash -# Premenuj súbor -$ git mv HelloWorld.c HelloNewWorld.c - -# Presuň súbor -$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c - -# "Nasilu" premenuj, alebo presuň -# "existujúciSúbor" už v adresári existuje, bude prepísaný -$ git mv -f môjSúbor existujúciSúbor -``` - -### pull - -Uloží obsah repozitára a zlúči ho s inou vetvou. - -```bash -# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien -# zo vzdialených "origin" a "master" vetiev. -# git pull -$ git pull origin master - -# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu -# zlúčením nových zmien zo vzdialenej vetvy -$ git pull - -# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase) -# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull , git rebase " -$ git pull origin master --rebase -``` - -### push - -Zverejní a zlúči zmeny z lokálnej do vzdialenej vetvy. - -```bash -# Zverejni a zlúč zmeny z lokálneho repozitára do -# vzdialených vetiev s názvom "origin" a "master". -# git push -$ git push origin master - -# Predvolene git zverejní a zlúči zmeny z -# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej -$ git push - -# Na spojenie lokálnej vetvy so vzdialenou pridaj -u: -$ git push -u origin master -# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz: -$ git push -``` - -### stash - -Umožní ti opustiť chaotický stav pracovného adresára a uloží ho na zásobník nedokončených zmien, ku ktorým sa môžeš kedykoľvek vrátiť. - -Povedzme, že si urobil nejaké zmeny vo svojom git repozitári, ale teraz potrebuješ pullnúť zo vzdialenej repo. Keďže máš necommitnuté zmeny, príkaz `git pull` nebude fungovať. Namiesto toho môžeš použiť `git stash` a uložiť svoje nedokončené zmeny na zásobník! - -```bash -$ git stash -Saved working directory and index state \ - "WIP on master: 049d078 added the index file" - HEAD is now at 049d078 added the index file - (To restore them type "git stash apply") -``` - -Teraz môžeš uložiť vzdialenú vetvu! - -```bash -$ git pull -``` - -Over, či je všetko v poriadku - -```bash -$ git status -# On branch master -nothing to commit, working directory clean -``` - -Môžeš si pozrieť, čo za chaos je na zásobníku cez `git stash list`. -Nedokončené zmeny sú uložené ako Last-In-First-Out (Prvý dnu, posledný von) štruktúra, navrchu sa objavia najnovšie zmeny. - -```bash -$ git stash list -stash@{0}: WIP on master: 049d078 added the index file -stash@{1}: WIP on master: c264051 Revert "added file_size" -stash@{2}: WIP on master: 21d80a5 added number to log -``` - -Keď so zmenami budeš chcieť pracovať, odstráň ich zo stacku. - -```bash -$ git stash pop -# On branch master -# Changes not staged for commit: -# (use "git add ..." to update what will be committed) -# -# modified: index.html -# modified: lib/simplegit.rb -# -``` - -`git stash apply` urobí presne to isté - -Hotovo, môžeš pokračovať v práci! - -[Čítaj viac.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) - -### rebase (pozor) - -Zober všetky zmeny commitnuté do vetvy a aplikuj ich na inú vetvu. -*Tento príkaz nerob na verejných repozitároch*. - -```bash -# Aplikuj commity z experimentálnej vetvy na master -# git rebase -$ git rebase master experimentBranch -``` - -[Čítaj viac.](http://git-scm.com/book/en/Git-Branching-Rebasing) - -### reset (pozor) - -Resetni HEAD (ukazateľ na aktuálnu vetvu) do konrkétneho stavu. To ti umožní vziať späť zlúčenia, zverejnenia, commity, pridania atď. Je to užitočný, no nebezpečný príkaz, pokiaľ nevieš, čo robíš. - -```bash -# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený) -$ git reset - -# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše) -$ git reset --hard - -# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený) -# všetky zmeny sú zachované v adresári. -$ git reset 31f2bb1 - -# Presunie vrchol aktuálnuej vetvy naopak do konkrétneho commitu -# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny). -$ git reset --hard 31f2bb1 -``` -### revert - -Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav -projektu do predchádzajúceho bodu v čase. Revert pridá nový commit, inverzný tomu, ktorý chceš vymazať, tým ho od-urobí. - -```bash -# Vezmi späť konkrétny commit -$ git revert -``` - -### rm - -Opak od git add, rm odstráni súbory z aktuálneho pracovného stromu. - -```bash -# odstráň HelloWorld.c -$ git rm HelloWorld.c - -# Odstráň súbor z vnoreného adresára -$ git rm /pather/to/the/file/HelloWorld.c -``` - -## Ďalšie informácie - -* [tryGit - Zábavný interaktívny spôsob, ako sa naučiť Git.](http://try.github.io/levels/1/challenges/1) - -* [Udemy Git Tutoriál: Kompletný návod](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) - -* [Git Immersion - Návod, ktorý Ťa prevedie základmi Gitu](http://gitimmersion.com/) - -* [git-scm - Video Tutoriály](http://git-scm.com/videos) - -* [git-scm - Dokumentácia](http://git-scm.com/docs) - -* [Atlassian Git - Tutoriály & Postupy](https://www.atlassian.com/git/) - -* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) - -* [GitGuys](http://www.gitguys.com/) - -* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html) - -* [Pro Git](http://www.git-scm.com/book/en/v2) - -* [Úvod do Gitu a GitHubu pre začiatočníkov (Tutoriál)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/sk-sk/json-sk.html.markdown b/sk-sk/json-sk.html.markdown new file mode 100644 index 00000000..2b1fbb58 --- /dev/null +++ b/sk-sk/json-sk.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson-sk.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +--- + +Nakoľko je JSON extrémne jednoduchý formát na výmenu dát, toto bude +pravdepodobne najjednoduchšie "Learn X in Y Minutes". + +JSON v jeho základnej forme nemá komentáre, ale veľa parserov akceptuje +komentáre v štýle C (`//`, `/* */`). V tomto návode však bude všetko +100% valídny JSON. + +```json +{ + "kľúč": "hodnota", + + "kľúč": "musí byť vždy uzavretý v dvojitých uvodzovkách", + "čísla": 0, + "reťazce": "Ahøj, svet. Unicode je povolený pri použití \"únikovej sekvencie (escaping)\".", + "boolean?": true, + "nič": null, + + "veľké číslo": 1.2e+100, + + "objekty": { + "komentár": "Väčšina štruktúry bude pochádzať z objektov.", + + "pole": [0, 1, 2, 3, "Pole môže obsahovať čokoľvek.", 5], + + "iný objekt": { + "komentár": "Môžu byť vhniezdené, čo môže byť užitočné." + } + }, + + "nezmysly": [ + { + "zdroje draslíka": ["banány"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatívny štýl": { + "komentár": "sleduj toto!" + , "pozícia čiarky": "nezáleží na nej - pokiaľ je pred hodnotou, všetko je ok" + , "iný komentár": "pekné, že?" + }, + + "to bolo rýchle": "A už sme aj na konci. Teraz ovládš všetko, čo ti JSON môže ponúknuť." +} +``` diff --git a/sk-sk/json.html.markdown b/sk-sk/json.html.markdown deleted file mode 100644 index 2b1fbb58..00000000 --- a/sk-sk/json.html.markdown +++ /dev/null @@ -1,61 +0,0 @@ ---- -language: json -filename: learnjson-sk.json -contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: - - ["Juraj Kostolanský", "http://www.kostolansky.sk"] -lang: sk-sk ---- - -Nakoľko je JSON extrémne jednoduchý formát na výmenu dát, toto bude -pravdepodobne najjednoduchšie "Learn X in Y Minutes". - -JSON v jeho základnej forme nemá komentáre, ale veľa parserov akceptuje -komentáre v štýle C (`//`, `/* */`). V tomto návode však bude všetko -100% valídny JSON. - -```json -{ - "kľúč": "hodnota", - - "kľúč": "musí byť vždy uzavretý v dvojitých uvodzovkách", - "čísla": 0, - "reťazce": "Ahøj, svet. Unicode je povolený pri použití \"únikovej sekvencie (escaping)\".", - "boolean?": true, - "nič": null, - - "veľké číslo": 1.2e+100, - - "objekty": { - "komentár": "Väčšina štruktúry bude pochádzať z objektov.", - - "pole": [0, 1, 2, 3, "Pole môže obsahovať čokoľvek.", 5], - - "iný objekt": { - "komentár": "Môžu byť vhniezdené, čo môže byť užitočné." - } - }, - - "nezmysly": [ - { - "zdroje draslíka": ["banány"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "neo"], - [0, 0, 0, 1] - ] - ], - - "alternatívny štýl": { - "komentár": "sleduj toto!" - , "pozícia čiarky": "nezáleží na nej - pokiaľ je pred hodnotou, všetko je ok" - , "iný komentár": "pekné, že?" - }, - - "to bolo rýchle": "A už sme aj na konci. Teraz ovládš všetko, čo ti JSON môže ponúknuť." -} -``` diff --git a/sk-sk/latex-sk.html.markdown.tex b/sk-sk/latex-sk.html.markdown.tex new file mode 100644 index 00000000..5e2f9c7f --- /dev/null +++ b/sk-sk/latex-sk.html.markdown.tex @@ -0,0 +1,227 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Terka Slanináková", "http://github.com/TerkaSlan"] +filename: learn-latex-sk.tex +--- + +```tex +% Všetky komentáre začínajú s % +% Viac-riadkové komentáre sa nedajú urobiť + +% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer + +% Každý LaTeX príkaz začína s opačným lomítkom (\) + +% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu +% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. +% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. +\documentclass[12pt]{article} + +% Ďalej definujeme balíčky, ktoré dokuemnt používa. +% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. +% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. +\usepackage{caption} +\usepackage{float} +\usepackage[utf8]{inputenc} +% Tu môžme definovať ostatné vlastnosti dokumentu! +% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} +% Vygeneruje dnešný dátum +\date{\today} +\title{Nauč sa LaTeX za Y Minút!} +% Teraz môžme začať pracovať na samotnom dokumente. +% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") +\begin{document} +% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. +\maketitle + +% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. +% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, +% no pred hlavnými sekciami tela.. +% Tento príkaz je tiež dostupný v triedach article a report. +% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract +% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom +\renewcommand\abstractname{Abstrakt} + +\begin{abstract} +LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! +\end{abstract} + +% Príkazy pre sekciu sú intuitívne +% Všetky nadpisy sekcií sú pridané automaticky do obsahu. +\section{Úvod} +Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! + +\section{Ďalšia sekcia} +Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. + +\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. +Zdá sa mi, že treba ďalšiu. + +\subsubsection{Pytagoras} +To je ono! +\label{subsec:pytagoras} + +% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. +% Toto funguje aj na iné príkazy. +\section*{Toto je nečíslovaná sekcia} +Všetky číslované byť nemusia! + +\section{Nejaké poznámočky} +Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak +potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do +zdrojového kódu. \\ + +\section{Zoznamy} +Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. +\begin{enumerate} % "enumerate" spustí číslovanie prvkov. + % \item povie LaTeXu, ako že treba pripočítať 1 + \item Vlašský šalát. + \item 5 rožkov. + \item 3 Horalky. + % číslovanie môžeme pozmeniť použitím [] + \item[koľko?] Stredne veľkých guličkoviek. + + Ja už nie som položka zoznamu, no stále som časť "enumerate". + +\end{enumerate} % Všetky prostredia končia s "end". + +\section{Matika} + +Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ + +Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; +Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ + +Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. +Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ +% Všimni si, že som pridal $ pred a po symboloch. Je to +% preto, lebo pri písaní sme v textovom móde, +% no matematické symboly existujú len v matematickom. +% Vstúpime doňho z textového práve '$' znamienkami. +% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. +% Do matematického módu sa dá dostať aj s \[\] + +\[a^2 + b^2 = c^2 \] + +Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. +Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! + +Operátory sú dôležitou súčasťou matematických dokumentov: +goniometrické funkcie ($\sin$, $\cos$, $\tan$), +logaritmy and exponenciálne výrazy ($\log$, $\exp$), +limity ($\lim$), atď. +majú pred-definované LaTeXové príkazy. +Napíšme si rovnicu, nech vidíme, ako to funguje: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatívne komplexné zlomky sa píšu ako +% \frac{čitateľ}{menovateľ} +$\frac{n!}{k!(n - k)!}$ \\ + +Rovnice tiež môžeme zadať v "rovnicovom prostredí". + +% Takto funguje rovnicové prostredie +\begin{equation} % vstúpi do matematického módu + c^2 = a^2 + b^2. + \label{eq:pythagoras} % na odkazovanie +\end{equation} % všetky \begin príkazy musia mať konečný príkaz. + +Teraz môžeme odkázať na novovytvorenú rovnicu! +Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. + +Sumácie a Integrály sa píšu príkazmi sum a int: + +% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) +% v rovnicovom prostredí. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Obrázky} + +Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. +\renewcommand\figurename{Obrázok} +\begin{figure}[H] % H značí možnosť zarovnania. + \centering % nacentruje obrázok na stránku + % Vloží obrázok na 80% šírky stránky. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). + \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} +% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj +\renewcommand\tablename{Tabuľka} + +\subsection{Tabuľky} +Tabuľky sa vkládajú podobne ako obrázky. + +\begin{table}[H] + \caption{Nadpis tabuľky.} + % zátvorky: {} hovoria ako sa vykreslí každý riadok. + % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! + \begin{tabular}{c|cc} + Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ + \hline % horizontálna čiara + 1 & Ladislav & Meliško \\ + 2 & Eva & Máziková + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Už čoskoro :) + +\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} +Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. +Toto sa robí vo verbatim prostredí. + +% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) +% ale verbatim je to najzákladnejšie, čo môžeš použiť. +\begin{verbatim} + print("Hello World!") + a%b; pozri! Vo verbatime môžme použiť % znamienka. + random = 4; #priradené randomným hodom kockou +\end{verbatim} + +\section{Kompilácia} + +Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? +(áno, tento dokument sa musí kompilovať). \\ +Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: + \begin{enumerate} + \item Napíš dokument v čistom texte (v "zdrojáku"). + \item Skompiluj zdroják na získanie pdfka. + Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. +Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. + +\section{Koniec} + +To je zatiaľ všetko! + +% koniec dokumentu +\end{document} +``` + +## Viac o LaTeXe (anglicky) + +* Úžasná LaTeX wikikniha: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* Naozajstný tutoriál: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/sk-sk/latex.html.markdown.tex b/sk-sk/latex.html.markdown.tex deleted file mode 100644 index 5e2f9c7f..00000000 --- a/sk-sk/latex.html.markdown.tex +++ /dev/null @@ -1,227 +0,0 @@ ---- -language: latex -contributors: - - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - - ["Colton Kohnke", "http://github.com/voltnor"] - - ["Sricharan Chiruvolu", "http://sricharan.xyz"] -translators: - - ["Terka Slanináková", "http://github.com/TerkaSlan"] -filename: learn-latex-sk.tex ---- - -```tex -% Všetky komentáre začínajú s % -% Viac-riadkové komentáre sa nedajú urobiť - -% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer - -% Každý LaTeX príkaz začína s opačným lomítkom (\) - -% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu -% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. -% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. -\documentclass[12pt]{article} - -% Ďalej definujeme balíčky, ktoré dokuemnt používa. -% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. -% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. -\usepackage{caption} -\usepackage{float} -\usepackage[utf8]{inputenc} -% Tu môžme definovať ostatné vlastnosti dokumentu! -% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" -\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} -% Vygeneruje dnešný dátum -\date{\today} -\title{Nauč sa LaTeX za Y Minút!} -% Teraz môžme začať pracovať na samotnom dokumente. -% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") -\begin{document} -% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. -\maketitle - -% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. -% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, -% no pred hlavnými sekciami tela.. -% Tento príkaz je tiež dostupný v triedach article a report. -% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract -% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom -\renewcommand\abstractname{Abstrakt} - -\begin{abstract} -LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! -\end{abstract} - -% Príkazy pre sekciu sú intuitívne -% Všetky nadpisy sekcií sú pridané automaticky do obsahu. -\section{Úvod} -Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! - -\section{Ďalšia sekcia} -Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. - -\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. -Zdá sa mi, že treba ďalšiu. - -\subsubsection{Pytagoras} -To je ono! -\label{subsec:pytagoras} - -% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. -% Toto funguje aj na iné príkazy. -\section*{Toto je nečíslovaná sekcia} -Všetky číslované byť nemusia! - -\section{Nejaké poznámočky} -Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak -potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do -zdrojového kódu. \\ - -\section{Zoznamy} -Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. -\begin{enumerate} % "enumerate" spustí číslovanie prvkov. - % \item povie LaTeXu, ako že treba pripočítať 1 - \item Vlašský šalát. - \item 5 rožkov. - \item 3 Horalky. - % číslovanie môžeme pozmeniť použitím [] - \item[koľko?] Stredne veľkých guličkoviek. - - Ja už nie som položka zoznamu, no stále som časť "enumerate". - -\end{enumerate} % Všetky prostredia končia s "end". - -\section{Matika} - -Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ - -Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; -Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ - -Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. -Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ -% Všimni si, že som pridal $ pred a po symboloch. Je to -% preto, lebo pri písaní sme v textovom móde, -% no matematické symboly existujú len v matematickom. -% Vstúpime doňho z textového práve '$' znamienkami. -% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. -% Do matematického módu sa dá dostať aj s \[\] - -\[a^2 + b^2 = c^2 \] - -Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. -Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! - -Operátory sú dôležitou súčasťou matematických dokumentov: -goniometrické funkcie ($\sin$, $\cos$, $\tan$), -logaritmy and exponenciálne výrazy ($\log$, $\exp$), -limity ($\lim$), atď. -majú pred-definované LaTeXové príkazy. -Napíšme si rovnicu, nech vidíme, ako to funguje: \\ - -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ - -Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: - -% 10 / 7 -$^{10}/_{7}$ - -% Relatívne komplexné zlomky sa píšu ako -% \frac{čitateľ}{menovateľ} -$\frac{n!}{k!(n - k)!}$ \\ - -Rovnice tiež môžeme zadať v "rovnicovom prostredí". - -% Takto funguje rovnicové prostredie -\begin{equation} % vstúpi do matematického módu - c^2 = a^2 + b^2. - \label{eq:pythagoras} % na odkazovanie -\end{equation} % všetky \begin príkazy musia mať konečný príkaz. - -Teraz môžeme odkázať na novovytvorenú rovnicu! -Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. - -Sumácie a Integrály sa píšu príkazmi sum a int: - -% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) -% v rovnicovom prostredí. -\begin{equation} - \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} - \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} - -\section{Obrázky} - -Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. -\renewcommand\figurename{Obrázok} -\begin{figure}[H] % H značí možnosť zarovnania. - \centering % nacentruje obrázok na stránku - % Vloží obrázok na 80% šírky stránky. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). - \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} - \label{fig:right-triangle} -\end{figure} -% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj -\renewcommand\tablename{Tabuľka} - -\subsection{Tabuľky} -Tabuľky sa vkládajú podobne ako obrázky. - -\begin{table}[H] - \caption{Nadpis tabuľky.} - % zátvorky: {} hovoria ako sa vykreslí každý riadok. - % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! - \begin{tabular}{c|cc} - Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ - \hline % horizontálna čiara - 1 & Ladislav & Meliško \\ - 2 & Eva & Máziková - \end{tabular} -\end{table} - -% \section{Hyperlinks} % Už čoskoro :) - -\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} -Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. -Toto sa robí vo verbatim prostredí. - -% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) -% ale verbatim je to najzákladnejšie, čo môžeš použiť. -\begin{verbatim} - print("Hello World!") - a%b; pozri! Vo verbatime môžme použiť % znamienka. - random = 4; #priradené randomným hodom kockou -\end{verbatim} - -\section{Kompilácia} - -Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? -(áno, tento dokument sa musí kompilovať). \\ -Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: - \begin{enumerate} - \item Napíš dokument v čistom texte (v "zdrojáku"). - \item Skompiluj zdroják na získanie pdfka. - Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf - \end{verbatim} - \end{enumerate} - -Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. -Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. - -\section{Koniec} - -To je zatiaľ všetko! - -% koniec dokumentu -\end{document} -``` - -## Viac o LaTeXe (anglicky) - -* Úžasná LaTeX wikikniha: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) -* Naozajstný tutoriál: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/sk-sk/ruby-sk.html.markdown b/sk-sk/ruby-sk.html.markdown new file mode 100644 index 00000000..799865b0 --- /dev/null +++ b/sk-sk/ruby-sk.html.markdown @@ -0,0 +1,553 @@ +--- +language: ruby +filename: learnruby-sk.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +--- + +```ruby +# Toto je komentár + +=begin +Toto je viacriadkový komentár +Nikto ho nepoužíva +Ani ty by si nemal +=end + +# V prvom rade: Všetko je objekt. + +# Čísla sú objekty + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Základná aritmetika +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# Aritmetika je iba syntaktickým cukrom +# pre volanie metódy nad objektom +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Špeciálne hodnoty sú objektami +nil # nič +true # pravda +false # lož + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Rovnosť +1 == 1 #=> true +2 == 1 #=> false + +# Nerovnosť +1 != 1 #=> false +2 != 1 #=> true + +# Okrem samotného false, nil je jedinou ďalšou 'nepravdivou' hodnotou + +!nil #=> true +!false #=> true +!0 #=> false + +# Ďalšie porovnania +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Logické operácie +true && false #=> false +true || false #=> true +!true #=> false + +# Existujú aj alternatívne verzie logických operátorov s nižšou prioritou. +# Tie sa využívajú ako konštrukcie pre riadenie toku na reťazenie výrazov +# kým jeden z nich nevráti true alebo false. + +# `sprav_nieco_ine` sa vykoná ak bude `sprav_nieco` úspešné (vráti true) +sprav_nieco() and sprav_nieco_ine() +# `zaznamenaj_chybu` sa vykoná ak `sprav_nieco` neuspeje (vráti false) +sprav_nieco() or zaznamenaj_chybu() + + +# Reťazce sú objekty + +'Ja som reťazec'.class #=> String +"Ja som tiež reťazec".class #=> String + +retazec = 'použiť interpoláciu reťazca' +"Môžem #{retazec} pri použití dvojitých úvodzoviek" +#=> "Môžem použiť interpoláciu reťazca pri použití dvojitých úvodzoviek" + +# Preferuj jednoduché úvodzovky pred dvojitými, ak je to možné +# Dvojité úvodzovky totiž vyžadujú ďalšie výpočty + +# Kombinuj reťazce, ale nie s číslami +'ahoj ' + 'svet' #=> "ahoj svet" +'ahoj ' + 3 #=> TypeError: can't convert Fixnum into String +'ahoj ' + 3.to_s #=> "ahoj 3" + +# Výpis na štandardný výstup +puts "Píšem!" + + +# Premenné +x = 25 #=> 25 +x #=> 25 + +# Všimni si, že priradenie vracia priradenú hodnotu +# To umožňuje viacnásobné priradenie: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Podľa konvencie sa pre mená premenných využíva snake_case +snake_case = true + +# Používaj správne (opisné) mená premenných +cesta_ku_korenovemu_adresaru = '/dobre/meno/' +cesta = '/zle/meno/' + + +# Symboly (sú objektami) +# Symboly sú nemenné znovupoužiteľné konštanty, ktoré sú interne +# reprezentované ako číslo. Často sa používajú namiesto reťazcov +# pre efektívnu reprezentáciu špecifickej hodnoty. + +:cakajuci.class #=> Symbol + +status = :cakajuci + +status == :cakajuci #=> true + +status == 'cakajuci' #=> false + +status == :schvaleny #=> false + + +# Polia + +# Toto je pole +pole = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Polia môžu obsahovať rôzne typy objektov + +[1, 'ahoj', false] #=> [1, "ahoj", false] + +# Polia môžu byť indexované +# Od začiatku +pole[0] #=> 1 +pole[12] #=> nil + +# Podobne ako pri aritmetike, prístup prostredníctvom [var] +# je iba syntaktickým cukrom pre volanie metódy [] nad objektom +pole.[] 0 #=> 1 +pole.[] 12 #=> nil + +# Od konca +pole[-1] #=> 5 + +# Pomocou počiatočného indexu a dĺžky +pole[2, 3] #=> [3, 4, 5] + +# Alebo rozsahom +pole[1..3] #=> [2, 3, 4] + +# Pridanie prvku do pola +pole << 6 #=> [1, 2, 3, 4, 5, 6] +# Alebo takto +pole.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Skontroluje, či už je objekt v poli +pole.include?(1) #=> true + + +# Asociatívne polia (hash) sú slovníkmi s dvojicami kľúč-hodnota. +# Asociatívne polia sú označované kučeravými zátvorkami: +asoc_pole = { 'farba' => 'zelena', 'cislo' => 5 } + +asoc_pole.keys #=> ['farba', 'cislo'] + +# V asociatívnych poliach sa rýchlo vyhľadáva pomocou kľúča +asoc_pole['farba'] #=> 'zelena' +asoc_pole['cislo'] #=> 5 + +# Asking a hash for a key that doesn't exist returns nil: +asoc_pole['nic tu nie je'] #=> nil + +# Od verzie Ruby 1.9 existuje špeciálna syntax, +# pri ktorej sa využíva symbol ako kľúč + +nove_asoc_pole = { defcon: 3, akcia: true } +nove_asoc_pole.keys #=> [:defcon, :akcia] + +# Skontroluje existenciu kľúča a hodnoty v asociatívnom poli +nove_asoc_pole.has_key?(:defcon) #=> true +nove_asoc_pole.has_value?(3) #=> true + +# Tip: Polia aj asociatívne polia sú vypočítateľné (Enumerable) +# Zdieľajú veľa užitočných metód ako each, map, count a ďalšie + + +# Štruktúry riadenia + +if true + 'if podmienka' +elsif false + 'else if, voliteľná vetva' +else + 'else, tiež voliteľná vetva' +end + +for pocitadlo in 1..5 + puts "iterácia #{pocitadlo}" +end +#=> iterácia 1 +#=> iterácia 2 +#=> iterácia 3 +#=> iterácia 4 +#=> iterácia 5 + +# NIKTO však nepoužíva for cyklus +# Aj ty by si mal preferovať metódu "each" a podať jej blok +# Blok kus kódu, ktorý môžeš podať metódam ako "each" +# Je podobný lambdám alebo anonymným funkciám v iných jazykoch +# +# Metóda "each" pre rozsah spustí blokpre každý element tohto rozsahu +# Blok získava počítadlo ako parameter +# Volanie metódy "each" s blokomvyzerá takto: + +(1..5).each do |pocitadlo| + puts "iterácia #{pocitadlo}" +end +#=> iterácia 1 +#=> iterácia 2 +#=> iterácia 3 +#=> iterácia 4 +#=> iterácia 5 + +# Blok môže byť uzavretý aj v kučeravých záítvorkách: +(1..5).each { |pocitadlo| puts "iterácia #{pocitadlo}" } + +# Obsah dátových štruktúr môže byť tiež prechádzaný pomocou metódy "each" +pole.each do |prvok| + puts "#{prvok} je súčasťou pola" +end +asoc_pole.each do |kluc, hodnota| + puts "#{kluc} je #{hodnota}" +end + +pocitadlo = 1 +while pocitadlo <= 5 do + puts "iterácia #{pocitadlo}" + pocitadlo += 1 +end +#=> iterácia 1 +#=> iterácia 2 +#=> iterácia 3 +#=> iterácia 4 +#=> iterácia 5 + +znamka = 'B' + +case znamka +when 'A' + puts 'Len tak ďalej, chlapče' +when 'B' + puts 'Viac šťastia nabudúce' +when 'C' + puts 'Zvládneš to aj lepšie' +when 'D' + puts 'S odratými ušami' +when 'F' + puts 'Zlyhal si!' +else + puts 'Iný systém známkovania, čo?' +end +#=> "Viac šťastia nabudúce" + +# prípady (cases) môžu tiež využívať rozsahy +znamka = 82 +case znamka +when 90..100 + puts 'Hurá!' +when 80...90 + puts 'Dobrá práca' +else + puts 'Zlyhal si!' +end +#=> "Dobrá práca" + +# Zaobchádzanie s výnimkami +begin + # kód, ktorý môže vyhodiť výnimku + raise NoMemoryError, 'Došla ti pamäť.' +rescue NoMemoryError => premenna_vynimky + puts 'Nastala vynimka NoMemoryError', premenna_vynimky +rescue RuntimeError => ina_premenna_vynimky + puts 'Nastala vynimka RuntimeError' +else + puts 'Toto sa spustí, ak nenastala žiadna výnimka' +ensure + puts 'Táto časť kódu sa spustí vždy' +end + +# Funkcie + +def zdvojnasob(x) + x * 2 +end + +# Funkcie (a bloky) implicitne vracajú hodnotu posledného výrazu +zdvojnasob(2) #=> 4 + +# Zátvorky sú voliteľné ak je výsledok jednoznačný +zdvojnasob 3 #=> 6 + +zdvojnasob zdvojnasob 3 #=> 12 + +def suma(x, y) + x + y +end + +# Argumenty metódy sa oddeľujú čiarkami +suma 3, 4 #=> 7 + +suma suma(3, 4), 5 #=> 12 + +# yield +# Všetky metódy majú implicitný, voliteľný parameter bloku +# môže byť zavolaný ako kľúčové slovo 'yield' + +def obal + puts '{' + yield + puts '}' +end + +obal { puts 'ahoj svet' } + +# { +# ahoj svet +# } + + +# Funkcii môžeš odovzdať blok +# "&" označuje referenciu na tento blok +def hostia(&blok) + blok.call 'nejake argumenty' +end + +# Tiež môžeš odovzdať zoznam argumentov, ktoré sa prevedú na pole +# Na to sa využíva operátor "*" +def hostia(*pole) + pole.each { |host| puts host } +end + + +# Trieda sa definuje kľúčovým slovom class +class Clovek + + # Premenná triedy. Je zdieľaná všetkými inštanciami tejto triedy. + @@druh = 'H. sapiens' + + # Jednoduchý inicializátor + def initialize(meno, vek = 0) + # Priradí argument k premennej inštancie "meno" + @meno = meno + # Ak nie je uvedený vek, použije sa špecifikovaná predvolená hodnota + @vek = vek + end + + # Jednoduchá metóda pre nastavenie hodnoty premennej + def meno=(meno) + @meno = meno + end + + # Jednoduchá metóda pre získanie hodnoty premennej + def meno + @meno + end + + # Vyššie uvedená funkcionalita môže byť zapúzdrená použitím + # metódy attr_accessor + attr_accessor :meno + + # Metódy pre nastavenie a získanie hodnoty premennej môžu byť vytvorené + # aj individuálne + attr_reader :meno + attr_writer :meno + + # Metóda triedy používa kľúčové slovo self pre odlíšenie + # od metód inštancií. Môže byť volaná iba nad triedou, nie inštanciou. + def self.povedz(sprava) + puts sprava + end + + def druh + @@druh + end +end + + +# Vytvorenie inštancie triedy +jim = Clovek.new('Jim Halpert') + +dwight = Clovek.new('Dwight K. Schrute') + +# Skúsme zavolať zopár metód +jim.druh #=> "H. sapiens" +jim.meno #=> "Jim Halpert" +jim.meno = "Jim Halpert II" #=> "Jim Halpert II" +jim.meno #=> "Jim Halpert II" +dwight.druh #=> "H. sapiens" +dwight.meno #=> "Dwight K. Schrute" + +# Volanie metódy triedy +Clovek.povedz('Ahoj') #=> "Ahoj" + +# Rozsah platnosti premennej je definovaná spôsobom, akým ju nazveme. +# Premenné začínajúce znakom $ majú globálnu platnosť. +$premenna = "Ja som globálna premenná" +defined? $premenna #=> "global-variable" + +# Premenné začínajúce znakom @ majú platnosť v rámci inštancie +@premenna = "Ja som premenná inštancie" +defined? @premenna #=> "instance-variable" + +# Premenné začínajúce znakmi @@ majú platnosť v rámci triedy +@@premenna= "Ja som premenná triedy" +defined? @@premenna #=> "class variable" + +# Premenné začínajúce veľkým písmenom sú konštanty +Premenna = "Ja som konštanta" +defined? Premenna #=> "constant" + +# Trieda je tiež objektom v ruby, takže aj ona môže mať premenné inštancie. +# Premenná triedy je zdieľaná triedou a jej nasledovníkmi. + +# Základná trieda +class Clovek + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(hodnota) + @@foo = hodnota + end +end + +# Odvodená trieda +class Pracovnik < Clovek +end + +Clovek.foo # 0 +Pracovnik.foo # 0 + +Clovek.foo = 2 # 2 +Pracovnik.foo # 2 + +# Premenné inštancie triedy nie sú zdieľané jej nasledovníkmi. + +class Clovek + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(hodnota) + @bar = hodnota + end +end + +class Doktor < Clovek +end + +Clovek.bar # 0 +Doktor.bar # nil + +module PrikladModulu + def foo + 'foo' + end +end + +# Vloženie modulu (include) previaže jeho metódy s inštanciou triedy. +# Rozšírenie modulu (extend) previaže jeho metódy so samotnou triedou. + +class Osoba + include PrikladModulu +end + +class Kniha + extend PrikladModulu +end + +Osoba.foo # => NoMethodError: undefined method `foo' for Osoba:Class +Osoba.new.foo # => 'foo' +Kniha.foo # => 'foo' +Kniha.new.foo # => NoMethodError: undefined method `foo' + +# Spätné volania sú vykonané pri vložení alebo rozšírení modulu + +module PrikladKoncernu + def self.included(zaklad) + zaklad.extend(MetodyTriedy) + zaklad.send(:include, MetodyInstancie) + end + + module MetodyTriedy + def bar + 'bar' + end + end + + module MetodyInstancie + def qux + 'qux' + end + end +end + +class Nieco + include PrikladKoncernu +end + +Nieco.bar # => 'bar' +Nieco.qux # => NoMethodError: undefined method `qux' +Nieco.new.bar # => NoMethodError: undefined method `bar' +Nieco.new.qux # => 'qux' +``` + +## Ďalšie zdroje + +- [Nauč sa ruby v príkladoch s úlohami](http://www.learneroo.com/modules/61/nodes/338) - Variácia tejto referencie s úlohami v prehliadači. +- [Oficiálna dokumentácia](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby z iných jazykov](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/) - Staršia [bezplatná edícia](http://ruby-doc.com/docs/ProgrammingRuby/) je dostupná online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Komunitná príručka odporúčaných štýlov programovania v Ruby. diff --git a/sk-sk/ruby.html.markdown b/sk-sk/ruby.html.markdown deleted file mode 100644 index 799865b0..00000000 --- a/sk-sk/ruby.html.markdown +++ /dev/null @@ -1,553 +0,0 @@ ---- -language: ruby -filename: learnruby-sk.rb -contributors: - - ["David Underwood", "http://theflyingdeveloper.com"] - - ["Joel Walden", "http://joelwalden.net"] - - ["Luke Holder", "http://twitter.com/lukeholder"] - - ["Tristan Hume", "http://thume.ca/"] - - ["Nick LaMuro", "https://github.com/NickLaMuro"] - - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] - - ["Ariel Krakowski", "http://www.learneroo.com"] - - ["Dzianis Dashkevich", "https://github.com/dskecse"] - - ["Levi Bostian", "https://github.com/levibostian"] - - ["Rahil Momin", "https://github.com/iamrahil"] -translators: - - ["Juraj Kostolanský", "http://www.kostolansky.sk"] -lang: sk-sk ---- - -```ruby -# Toto je komentár - -=begin -Toto je viacriadkový komentár -Nikto ho nepoužíva -Ani ty by si nemal -=end - -# V prvom rade: Všetko je objekt. - -# Čísla sú objekty - -3.class #=> Fixnum - -3.to_s #=> "3" - - -# Základná aritmetika -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 -2**5 #=> 32 - -# Aritmetika je iba syntaktickým cukrom -# pre volanie metódy nad objektom -1.+(3) #=> 4 -10.* 5 #=> 50 - -# Špeciálne hodnoty sú objektami -nil # nič -true # pravda -false # lož - -nil.class #=> NilClass -true.class #=> TrueClass -false.class #=> FalseClass - -# Rovnosť -1 == 1 #=> true -2 == 1 #=> false - -# Nerovnosť -1 != 1 #=> false -2 != 1 #=> true - -# Okrem samotného false, nil je jedinou ďalšou 'nepravdivou' hodnotou - -!nil #=> true -!false #=> true -!0 #=> false - -# Ďalšie porovnania -1 < 10 #=> true -1 > 10 #=> false -2 <= 2 #=> true -2 >= 2 #=> true - -# Logické operácie -true && false #=> false -true || false #=> true -!true #=> false - -# Existujú aj alternatívne verzie logických operátorov s nižšou prioritou. -# Tie sa využívajú ako konštrukcie pre riadenie toku na reťazenie výrazov -# kým jeden z nich nevráti true alebo false. - -# `sprav_nieco_ine` sa vykoná ak bude `sprav_nieco` úspešné (vráti true) -sprav_nieco() and sprav_nieco_ine() -# `zaznamenaj_chybu` sa vykoná ak `sprav_nieco` neuspeje (vráti false) -sprav_nieco() or zaznamenaj_chybu() - - -# Reťazce sú objekty - -'Ja som reťazec'.class #=> String -"Ja som tiež reťazec".class #=> String - -retazec = 'použiť interpoláciu reťazca' -"Môžem #{retazec} pri použití dvojitých úvodzoviek" -#=> "Môžem použiť interpoláciu reťazca pri použití dvojitých úvodzoviek" - -# Preferuj jednoduché úvodzovky pred dvojitými, ak je to možné -# Dvojité úvodzovky totiž vyžadujú ďalšie výpočty - -# Kombinuj reťazce, ale nie s číslami -'ahoj ' + 'svet' #=> "ahoj svet" -'ahoj ' + 3 #=> TypeError: can't convert Fixnum into String -'ahoj ' + 3.to_s #=> "ahoj 3" - -# Výpis na štandardný výstup -puts "Píšem!" - - -# Premenné -x = 25 #=> 25 -x #=> 25 - -# Všimni si, že priradenie vracia priradenú hodnotu -# To umožňuje viacnásobné priradenie: - -x = y = 10 #=> 10 -x #=> 10 -y #=> 10 - -# Podľa konvencie sa pre mená premenných využíva snake_case -snake_case = true - -# Používaj správne (opisné) mená premenných -cesta_ku_korenovemu_adresaru = '/dobre/meno/' -cesta = '/zle/meno/' - - -# Symboly (sú objektami) -# Symboly sú nemenné znovupoužiteľné konštanty, ktoré sú interne -# reprezentované ako číslo. Často sa používajú namiesto reťazcov -# pre efektívnu reprezentáciu špecifickej hodnoty. - -:cakajuci.class #=> Symbol - -status = :cakajuci - -status == :cakajuci #=> true - -status == 'cakajuci' #=> false - -status == :schvaleny #=> false - - -# Polia - -# Toto je pole -pole = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] - -# Polia môžu obsahovať rôzne typy objektov - -[1, 'ahoj', false] #=> [1, "ahoj", false] - -# Polia môžu byť indexované -# Od začiatku -pole[0] #=> 1 -pole[12] #=> nil - -# Podobne ako pri aritmetike, prístup prostredníctvom [var] -# je iba syntaktickým cukrom pre volanie metódy [] nad objektom -pole.[] 0 #=> 1 -pole.[] 12 #=> nil - -# Od konca -pole[-1] #=> 5 - -# Pomocou počiatočného indexu a dĺžky -pole[2, 3] #=> [3, 4, 5] - -# Alebo rozsahom -pole[1..3] #=> [2, 3, 4] - -# Pridanie prvku do pola -pole << 6 #=> [1, 2, 3, 4, 5, 6] -# Alebo takto -pole.push(6) #=> [1, 2, 3, 4, 5, 6] - -# Skontroluje, či už je objekt v poli -pole.include?(1) #=> true - - -# Asociatívne polia (hash) sú slovníkmi s dvojicami kľúč-hodnota. -# Asociatívne polia sú označované kučeravými zátvorkami: -asoc_pole = { 'farba' => 'zelena', 'cislo' => 5 } - -asoc_pole.keys #=> ['farba', 'cislo'] - -# V asociatívnych poliach sa rýchlo vyhľadáva pomocou kľúča -asoc_pole['farba'] #=> 'zelena' -asoc_pole['cislo'] #=> 5 - -# Asking a hash for a key that doesn't exist returns nil: -asoc_pole['nic tu nie je'] #=> nil - -# Od verzie Ruby 1.9 existuje špeciálna syntax, -# pri ktorej sa využíva symbol ako kľúč - -nove_asoc_pole = { defcon: 3, akcia: true } -nove_asoc_pole.keys #=> [:defcon, :akcia] - -# Skontroluje existenciu kľúča a hodnoty v asociatívnom poli -nove_asoc_pole.has_key?(:defcon) #=> true -nove_asoc_pole.has_value?(3) #=> true - -# Tip: Polia aj asociatívne polia sú vypočítateľné (Enumerable) -# Zdieľajú veľa užitočných metód ako each, map, count a ďalšie - - -# Štruktúry riadenia - -if true - 'if podmienka' -elsif false - 'else if, voliteľná vetva' -else - 'else, tiež voliteľná vetva' -end - -for pocitadlo in 1..5 - puts "iterácia #{pocitadlo}" -end -#=> iterácia 1 -#=> iterácia 2 -#=> iterácia 3 -#=> iterácia 4 -#=> iterácia 5 - -# NIKTO však nepoužíva for cyklus -# Aj ty by si mal preferovať metódu "each" a podať jej blok -# Blok kus kódu, ktorý môžeš podať metódam ako "each" -# Je podobný lambdám alebo anonymným funkciám v iných jazykoch -# -# Metóda "each" pre rozsah spustí blokpre každý element tohto rozsahu -# Blok získava počítadlo ako parameter -# Volanie metódy "each" s blokomvyzerá takto: - -(1..5).each do |pocitadlo| - puts "iterácia #{pocitadlo}" -end -#=> iterácia 1 -#=> iterácia 2 -#=> iterácia 3 -#=> iterácia 4 -#=> iterácia 5 - -# Blok môže byť uzavretý aj v kučeravých záítvorkách: -(1..5).each { |pocitadlo| puts "iterácia #{pocitadlo}" } - -# Obsah dátových štruktúr môže byť tiež prechádzaný pomocou metódy "each" -pole.each do |prvok| - puts "#{prvok} je súčasťou pola" -end -asoc_pole.each do |kluc, hodnota| - puts "#{kluc} je #{hodnota}" -end - -pocitadlo = 1 -while pocitadlo <= 5 do - puts "iterácia #{pocitadlo}" - pocitadlo += 1 -end -#=> iterácia 1 -#=> iterácia 2 -#=> iterácia 3 -#=> iterácia 4 -#=> iterácia 5 - -znamka = 'B' - -case znamka -when 'A' - puts 'Len tak ďalej, chlapče' -when 'B' - puts 'Viac šťastia nabudúce' -when 'C' - puts 'Zvládneš to aj lepšie' -when 'D' - puts 'S odratými ušami' -when 'F' - puts 'Zlyhal si!' -else - puts 'Iný systém známkovania, čo?' -end -#=> "Viac šťastia nabudúce" - -# prípady (cases) môžu tiež využívať rozsahy -znamka = 82 -case znamka -when 90..100 - puts 'Hurá!' -when 80...90 - puts 'Dobrá práca' -else - puts 'Zlyhal si!' -end -#=> "Dobrá práca" - -# Zaobchádzanie s výnimkami -begin - # kód, ktorý môže vyhodiť výnimku - raise NoMemoryError, 'Došla ti pamäť.' -rescue NoMemoryError => premenna_vynimky - puts 'Nastala vynimka NoMemoryError', premenna_vynimky -rescue RuntimeError => ina_premenna_vynimky - puts 'Nastala vynimka RuntimeError' -else - puts 'Toto sa spustí, ak nenastala žiadna výnimka' -ensure - puts 'Táto časť kódu sa spustí vždy' -end - -# Funkcie - -def zdvojnasob(x) - x * 2 -end - -# Funkcie (a bloky) implicitne vracajú hodnotu posledného výrazu -zdvojnasob(2) #=> 4 - -# Zátvorky sú voliteľné ak je výsledok jednoznačný -zdvojnasob 3 #=> 6 - -zdvojnasob zdvojnasob 3 #=> 12 - -def suma(x, y) - x + y -end - -# Argumenty metódy sa oddeľujú čiarkami -suma 3, 4 #=> 7 - -suma suma(3, 4), 5 #=> 12 - -# yield -# Všetky metódy majú implicitný, voliteľný parameter bloku -# môže byť zavolaný ako kľúčové slovo 'yield' - -def obal - puts '{' - yield - puts '}' -end - -obal { puts 'ahoj svet' } - -# { -# ahoj svet -# } - - -# Funkcii môžeš odovzdať blok -# "&" označuje referenciu na tento blok -def hostia(&blok) - blok.call 'nejake argumenty' -end - -# Tiež môžeš odovzdať zoznam argumentov, ktoré sa prevedú na pole -# Na to sa využíva operátor "*" -def hostia(*pole) - pole.each { |host| puts host } -end - - -# Trieda sa definuje kľúčovým slovom class -class Clovek - - # Premenná triedy. Je zdieľaná všetkými inštanciami tejto triedy. - @@druh = 'H. sapiens' - - # Jednoduchý inicializátor - def initialize(meno, vek = 0) - # Priradí argument k premennej inštancie "meno" - @meno = meno - # Ak nie je uvedený vek, použije sa špecifikovaná predvolená hodnota - @vek = vek - end - - # Jednoduchá metóda pre nastavenie hodnoty premennej - def meno=(meno) - @meno = meno - end - - # Jednoduchá metóda pre získanie hodnoty premennej - def meno - @meno - end - - # Vyššie uvedená funkcionalita môže byť zapúzdrená použitím - # metódy attr_accessor - attr_accessor :meno - - # Metódy pre nastavenie a získanie hodnoty premennej môžu byť vytvorené - # aj individuálne - attr_reader :meno - attr_writer :meno - - # Metóda triedy používa kľúčové slovo self pre odlíšenie - # od metód inštancií. Môže byť volaná iba nad triedou, nie inštanciou. - def self.povedz(sprava) - puts sprava - end - - def druh - @@druh - end -end - - -# Vytvorenie inštancie triedy -jim = Clovek.new('Jim Halpert') - -dwight = Clovek.new('Dwight K. Schrute') - -# Skúsme zavolať zopár metód -jim.druh #=> "H. sapiens" -jim.meno #=> "Jim Halpert" -jim.meno = "Jim Halpert II" #=> "Jim Halpert II" -jim.meno #=> "Jim Halpert II" -dwight.druh #=> "H. sapiens" -dwight.meno #=> "Dwight K. Schrute" - -# Volanie metódy triedy -Clovek.povedz('Ahoj') #=> "Ahoj" - -# Rozsah platnosti premennej je definovaná spôsobom, akým ju nazveme. -# Premenné začínajúce znakom $ majú globálnu platnosť. -$premenna = "Ja som globálna premenná" -defined? $premenna #=> "global-variable" - -# Premenné začínajúce znakom @ majú platnosť v rámci inštancie -@premenna = "Ja som premenná inštancie" -defined? @premenna #=> "instance-variable" - -# Premenné začínajúce znakmi @@ majú platnosť v rámci triedy -@@premenna= "Ja som premenná triedy" -defined? @@premenna #=> "class variable" - -# Premenné začínajúce veľkým písmenom sú konštanty -Premenna = "Ja som konštanta" -defined? Premenna #=> "constant" - -# Trieda je tiež objektom v ruby, takže aj ona môže mať premenné inštancie. -# Premenná triedy je zdieľaná triedou a jej nasledovníkmi. - -# Základná trieda -class Clovek - @@foo = 0 - - def self.foo - @@foo - end - - def self.foo=(hodnota) - @@foo = hodnota - end -end - -# Odvodená trieda -class Pracovnik < Clovek -end - -Clovek.foo # 0 -Pracovnik.foo # 0 - -Clovek.foo = 2 # 2 -Pracovnik.foo # 2 - -# Premenné inštancie triedy nie sú zdieľané jej nasledovníkmi. - -class Clovek - @bar = 0 - - def self.bar - @bar - end - - def self.bar=(hodnota) - @bar = hodnota - end -end - -class Doktor < Clovek -end - -Clovek.bar # 0 -Doktor.bar # nil - -module PrikladModulu - def foo - 'foo' - end -end - -# Vloženie modulu (include) previaže jeho metódy s inštanciou triedy. -# Rozšírenie modulu (extend) previaže jeho metódy so samotnou triedou. - -class Osoba - include PrikladModulu -end - -class Kniha - extend PrikladModulu -end - -Osoba.foo # => NoMethodError: undefined method `foo' for Osoba:Class -Osoba.new.foo # => 'foo' -Kniha.foo # => 'foo' -Kniha.new.foo # => NoMethodError: undefined method `foo' - -# Spätné volania sú vykonané pri vložení alebo rozšírení modulu - -module PrikladKoncernu - def self.included(zaklad) - zaklad.extend(MetodyTriedy) - zaklad.send(:include, MetodyInstancie) - end - - module MetodyTriedy - def bar - 'bar' - end - end - - module MetodyInstancie - def qux - 'qux' - end - end -end - -class Nieco - include PrikladKoncernu -end - -Nieco.bar # => 'bar' -Nieco.qux # => NoMethodError: undefined method `qux' -Nieco.new.bar # => NoMethodError: undefined method `bar' -Nieco.new.qux # => 'qux' -``` - -## Ďalšie zdroje - -- [Nauč sa ruby v príkladoch s úlohami](http://www.learneroo.com/modules/61/nodes/338) - Variácia tejto referencie s úlohami v prehliadači. -- [Oficiálna dokumentácia](http://www.ruby-doc.org/core-2.1.1/) -- [Ruby z iných jazykov](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/) - Staršia [bezplatná edícia](http://ruby-doc.com/docs/ProgrammingRuby/) je dostupná online. -- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Komunitná príručka odporúčaných štýlov programovania v Ruby. -- cgit v1.2.3 From e42fa72be6e4b25730d163f601343978dc9fdbe9 Mon Sep 17 00:00:00 2001 From: Muhammad Rifqi Fatchurrahman Putra Danar Date: Mon, 6 Nov 2017 20:01:02 +0700 Subject: [bf/id-id] Add Indonesian translation for brainfuck language (#2985) * [bf/id-id] Add Indonesian translation for brainfuck language * [bf/id-id] add missing -id to the filename --- id-id/bf-id.html.markdown | 86 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 id-id/bf-id.html.markdown diff --git a/id-id/bf-id.html.markdown b/id-id/bf-id.html.markdown new file mode 100644 index 00000000..9901290b --- /dev/null +++ b/id-id/bf-id.html.markdown @@ -0,0 +1,86 @@ +--- +language: "Brainfuck" +filename: brainfuck-id.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Muhammad Rifqi Fatchurrahman", "http://muhrifqii.github.io/"] +lang: id-id +--- + +Brainfuck (tidak dalam huruf kapital kecuali pada awal kalimat) adalah sebuah +bahasa pemrograman Turing-complete yang sangat minim yang hanya memiliki 8 perintah. + +Anda bisa mencoba brainfuck pada browser dengan menggunakan [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +```bf +Karakter apapun selain "><+-.,[]" (tanda kutip tidak termasuk) diabaikan. + +Brainfuck direpresentasikan dengan sebuah array yang memiliki 30,000 cell yang +diinisialisasi dengan nol dan pointer data yang menunjuk ke current cell. + +Terdapat delapan perintah: ++ : Menaikkan nilai pada current cell sebesar satu. +- : Menurunkan nilai pada current cell sebesar satu. +> : Menggeser pointer data ke cell selanjutnya (cell sebelah kanan). +< : Menggeser pointer data ke cell sebelumnya (cell sebelah kiri). +. : Mencetak nilai ASCII pada current cell (misal 65 = 'A'). +, : Membaca sebuah karakter masukan tunggal ke dalam current cell. +[ : Jika nilai pada current cell bernilai nol, lewati hingga mencapai ] yang sesuai. + Jika tidak, pindah ke instruksi berikutnya. +] : Jika nilai pada current cell bernilai nol, pindah ke instruksi berikutnya. + Jika tidak, mundur pada instruksi hingga mencapai [ yang sesuai. + +[ dan ] membentuk sebuah rekursi while. Tentu saja mereka harus seimbang. + +Mari kita lihat beberapa program brainfuck dasar. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Program ini mencetak huruf 'A'. Mula-mula, cell #1 dinaikkan ke 6. +Cell #1 akan digunakan untuk rekursi. Lalu, masuk ke rekursi ([) dan pindah +ke cell #2. Cell #2 dinaikkan 10 kali, mundur ke cell #1, dan menurunkan +cell #1. Rekursi ini berlangsung 6 kali (melakukan 6 penurunan nilai untuk +cell #1 hingga mencapai 0, di titik mana dia melewati hingga mencapai ] dan +terus berlanjut). + +Pada titik ini, kita berada pada cell #1, yang memiliki nilai 0, sedangkan cell #2 +memiliki sebuah nilai 60. Kita berpindah ke cell #2, menaikkan nilai 5 kali, memunculkan +nilai 65, lalu cetak nilai pada cell #2. 65 adalah 'A' pada ASCII, jadi 'A' +dicetak ke terminal. + +, [ > + < - ] > . + +Program ini membaca sebuah karakter dari masukan user dan menyalin karakternya ke +cell #1. Setelah itu rekursi dimulai. Geser ke cell #2, menaikkan nilai pada cell #2, +mundur ke cell #1, dan menurunkan nilai pada cell #1. Hal ini berlanjut sampai cell #1 +bernilai 0, dan cell #2 menyimpan nilai lama dari cell #1. Karena kita berada di cell #1 +saat ujung rekursi, geser ke cell #2, lalu cetak nilai dalam bentuk ASCII. + +Perlu diingat bahwa spasi itu murni untuk memudahkan membaca. Anda bisa +menuliskannya dengan mudah seperti: + +,[>+<-]>. + +Coba dan cari tahu apa yang program ini lakukan: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Program ini menerima dua buah angka sebagai input, lalu mengalikannya. + +Intinya adalah membaca dua masukan. Lalu mulai pada rekursi terluar yang +kondisinya pada cell #1. Lalu pindah ke cell #2, dan mulai rekursi terdalam +yang kondisinya ada pada cell #2, menaikkan nilai pada cell #3. Namun, +ada suatu masalah: Pada akhir dari rekursi terdalam, cell #2 bernilai nol. +Pada kasus tersebut, rekursi terdalam tidak dapat bekerja lagi mulai setelah ini. +Untuk menyelesaikan masalah tersebut, kita juga menaikkan cell #4, dan menyalin +ulang cell #4 ke cell #2. Maka cell #3 adalah hasilnya. +``` + +Dan itulah brainfuck. Tidak terlalu sulit kan? Hanya untuk iseng-iseng, anda +bisa menuliskan porgram brainfuck anda sendiri, atau anda bisa menuliskan interpreter +brainfuck pada bahasa lain. Interpreternya tidak begitu sulit untuk diimplementasikan, +tapi jika anda seorang masokis, cobalah menulis sebuah interpreter brainfuck... dalam +brainfuck. + -- cgit v1.2.3