From 2532d97bca71bdee8e2b340e53f802cb755922d0 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 12:12:22 -0200 Subject: Translating brainfuck to pt-br --- pt-br/brainfuck-pt.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++ pt-br/brainfuck-pt.html.markdown~ | 84 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 pt-br/brainfuck-pt.html.markdown create mode 100644 pt-br/brainfuck-pt.html.markdown~ diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown new file mode 100644 index 00000000..72c2cf6e --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] +lang: pt-pt +--- + +Brainfuck (em letras minúsculas, eceto 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 vaor 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/brainfuck-pt.html.markdown~ b/pt-br/brainfuck-pt.html.markdown~ new file mode 100644 index 00000000..72c2cf6e --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown~ @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] +lang: pt-pt +--- + +Brainfuck (em letras minúsculas, eceto 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 vaor 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. -- cgit v1.2.3 From f7c84056ff777caeaac165f935aa49b3b7cccd67 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 12:13:16 -0200 Subject: Translating brainfuck to pt-br --- pt-br/brainfuck-pt.html.markdown~ | 84 --------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 pt-br/brainfuck-pt.html.markdown~ diff --git a/pt-br/brainfuck-pt.html.markdown~ b/pt-br/brainfuck-pt.html.markdown~ deleted file mode 100644 index 72c2cf6e..00000000 --- a/pt-br/brainfuck-pt.html.markdown~ +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Suzane Sant Ana", "http://github.com/suuuzi"] -lang: pt-pt ---- - -Brainfuck (em letras minúsculas, eceto 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 vaor 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. -- cgit v1.2.3 From 37584056a09f93395d7079c0df5ac2b569638d4b Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 13:13:13 -0200 Subject: Translating Git to pt-br --- pt-br/git-pt.html.markdown | 312 +++++++++++++++++++++++---------------------- 1 file changed, 161 insertions(+), 151 deletions(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 6d2a55cd..b8cbd0a9 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -1,110 +1,119 @@ --- category: tool tool: git +lang: pt-pt +filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - - ["Miguel Araújo", "https://github.com/miguelarauj1o"] -lang: pt-br -filename: learngit-pt.txt + - ["Suzane Sant Ana", "http://github.com/suuuzi"] --- -Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte. +Git é um sistema distribuido de gestão para código fonte e controle de versões. -Ele faz isso através de uma série de momentos instantâneos de seu projeto, e ele funciona -com esses momentos para lhe fornecer a funcionalidade para a versão e -gerenciar o seu código-fonte. +Funciona através de uma série de registos de estado do projeto e usa esse +registo para permitir funcionalidades de versionamento e gestão de código +fonte. -## Versionando Conceitos +## Conceitos de versionamento -### O que é controle de versão? +### O que é controle de versão -O controle de versão é um sistema que registra alterações em um arquivo ou conjunto -de arquivos, ao longo do tempo. +Controle de versão (*source control*) é um processo de registo de alterações +a um arquivo ou conjunto de arquivos ao longo do tempo. -### Versionamento Centralizado VS Versionamento Distribuído +### Controle de versão: Centralizado VS Distribuído -* Controle de versão centralizado concentra-se na sincronização, controle e backup de arquivos. -* Controle de versão distribuído concentra-se na partilha de mudanças. Toda mudança tem um ID único. -* Sistemas Distribuídos não têm estrutura definida. Você poderia facilmente ter um estilo SVN, -sistema centralizado, com git. +* Controle de versão centralizado foca na sincronização, registo e *backup* +de arquivos. +* Controle de versão distribuído foca em compartilhar alterações. Cada +alteração é associada a um *id* único. +* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +centralizado ao estilo SVN usando git. -[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control) +[Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) -### Porque usar o Git? +### Por que usar git? -* Possibilidade de trabalhar offline -* Colaborar com os outros é fácil! -* Ramificação é fácil -* Mesclagem é fácil -* Git é rápido -* Git é flexível. +* Permite trabalhar offline. +* Colaborar com outros é fácil! +* Criar *branches* é fácil! +* Fazer *merge* é fácil! +* Git é rápido. +* Git é flexivel. + +## Git - Arquitetura -## Arquitetura Git ### Repositório -Um conjunto de arquivos, diretórios, registros históricos, cometes, e cabeças. Imagine-o -como uma estrutura de dados de código-fonte, com o atributo que cada "elemento" do -código-fonte dá-lhe acesso ao seu histórico de revisão, entre outras coisas. +Um conjunto de arquivos, diretórios, registos históricos, *commits* e +referências. Pode ser descrito como uma estrutura de dados de código fonte +com a particularidade de cada elemento do código fonte permitir acesso ao +histórico das suas alterações, entre outras coisas. -Um repositório git é composto do diretório git. e árvore de trabalho. +Um repositório git é constituido pelo diretório .git e a *working tree* ### Diretório .git (componente do repositório) -O diretório git. contém todas as configurações, registros, galhos, cabeça(HEAD) e muito mais. -[Lista Detalhada](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) +O repositório .git contém todas as configurações, *logs*, *branches*, +referências e outros. + +[Lista detalhada (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) -### Árvore de trabalho (componente do repositório) +### *Working Tree* (componente do repositório) -Esta é, basicamente, os diretórios e arquivos no seu repositório. Ele é muitas vezes referida -como seu diretório de trabalho. +A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto. -### Índice (componente do diretório .git) +### *Index* (componente do diretório .git) -O Índice é a área de teste no git. É basicamente uma camada que separa a sua árvore de trabalho -a partir do repositório Git. Isso dá aos desenvolvedores mais poder sobre o que é enviado para o -repositório Git. +O *Index* é a camada da interface no git. É o elemento que separa +o diretório do projeto do repositório git. Isto permite aos programadores um +maior controle sobre o que é registado no repositório git. -### Comete (commit) +### *Commit* -A commit git é um instantâneo de um conjunto de alterações ou manipulações a sua árvore de trabalho. -Por exemplo, se você adicionou 5 imagens, e removeu outros dois, estas mudanças serão contidas -em um commit (ou instantâneo). Esta confirmação pode ser empurrado para outros repositórios, ou não! +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto. +Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações +serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado +para outros repositórios ou não! -### Ramo (branch) +### *Branch* -Um ramo é, essencialmente, um ponteiro que aponta para o último commit que você fez. Como -você se comprometer, este ponteiro irá atualizar automaticamente e apontar para o último commit. +Um *branch* é essencialmente uma referência que aponta para o último *commit* +efetuado. Na medida que são feitos novos commits, esta referência é atualizada +automaticamente e passa a apontar para o commit mais recente. -### Cabeça (HEAD) e cabeça (head) (componente do diretório .git) +### *HEAD* e *head* (componentes do diretório .git) -HEAD é um ponteiro que aponta para o ramo atual. Um repositório tem apenas 1 * ativo * HEAD. -head é um ponteiro que aponta para qualquer commit. Um repositório pode ter qualquer número de commits. +*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem +uma *HEAD* activa. +*head* é uma referência que aponta para qualquer *commit*. Um repositório pode +ter um número indefinido de *heads* -### Recursos Conceituais +### Recursos conceituais (EN) -* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para Cientistas de Computação](http://eagain.net/articles/git-for-computer-scientists/) * [Git para Designers](http://hoth.entp.com/output/git_for_designers.html) ## Comandos -### init +### *init* -Criar um repositório Git vazio. As configurações do repositório Git, informações armazenadas, -e mais são armazenados em um diretório (pasta) com o nome ". git". +Cria um repositório Git vazio. As definições, informação guardada e outros do +repositório git são guardados em uma pasta chamada ".git". ```bash $ git init ``` -### config +### *config* -Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou -configurações globais. +Permite configurar as definições, sejam as definições do repositório, sistema +ou configurações globais. ```bash -# Impressão e definir algumas variáveis ​​de configuração básica (global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -112,22 +121,21 @@ $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` -[Saiba mais sobre o git config.](http://git-scm.com/docs/git-config) +[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help -Para lhe dar um acesso rápido a um guia extremamente detalhada de cada comando. ou -apenas dar-lhe um rápido lembrete de algumas semânticas. +Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica. ```bash -# Rapidamente verificar os comandos disponíveis +# Ver rapidamente os comandos disponiveis $ git help -# Confira todos os comandos disponíveis +# Ver todos os comandos disponiveis $ git help -a -# Ajuda específica de comando - manual do usuário -# git help +# Usar o *help* para um comando especifico +# git help $ git help add $ git help commit $ git help init @@ -135,85 +143,89 @@ $ git help init ### status -Para mostrar as diferenças entre o arquivo de índice (basicamente o trabalho de -copiar/repo) e a HEAD commit corrente. +Apresenta as diferenças entre o arquivo *index* (a versão corrente +do repositório) e o *commit* da *HEAD* atual. + ```bash -# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças +# Apresenta o *branch*, arquivos não monitorados, alterações e outras +# difereças $ git status -# Para saber outras "tid bits" sobre git status +# Para aprender mais detalhes sobre git *status* $ git help status ``` ### add -Para adicionar arquivos para a atual árvore/directory/repo trabalho. Se você não -der `git add` nos novos arquivos para o trabalhando árvore/diretório, eles não serão -incluídos em commits! +Adiciona arquivos ao repositório corrente. Se os arquivos novos não forem +adicionados através de `git add` ao repositório, então eles não serão +incluidos nos commits! ```bash -# Adicionar um arquivo no seu diretório de trabalho atual +# adiciona um arquivo no diretório do projeto atual $ git add HelloWorld.java -# Adicionar um arquivo em um diretório aninhado +# adiciona um arquivo num sub-diretório $ git add /path/to/file/HelloWorld.c -# Suporte a expressões regulares! +# permite usar expressões regulares! $ git add ./*.java ``` ### branch -Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando. +Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este +comando. ```bash -# Lista ramos e controles remotos existentes +# listar *branches* existentes e remotos $ git branch -a -# Criar um novo ramo +# criar um novo *branch* $ git branch myNewBranch -# Apagar um ramo +# apagar um *branch* $ git branch -d myBranch -# Renomear um ramo +# alterar o nome de um *branch* # git branch -m $ git branch -m myBranchName myNewBranchName -# Editar a descrição de um ramo +# editar a descrição de um *branch* $ git branch myBranchName --edit-description ``` ### checkout -Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no -índice, ou árvore especificada. +Atualiza todos os arquivos no diretório do projeto para que fiquem iguais +à versão do index ou do *branch* especificado. ```bash -# Finalizar um repo - padrão de ramo mestre +# Checkout de um repositório - por padrão para o branch master $ git checkout -# Checa um ramo especificado +# Checkout de um branch especifico $ git checkout branchName -# Criar um novo ramo e mudar para ela, como: " git branch; git checkout " +# Cria um novo branch e faz checkout para ele. +# Equivalente a: "git branch ; git checkout " $ git checkout -b newBranch ``` ### clone -Clones, ou cópias, de um repositório existente para um novo diretório. Ele também adiciona -filiais remotas de rastreamento para cada ramo no repo clonado, que permite que você empurre -a um ramo remoto. +Clona ou copia um repositório existente para um novo diretório. Também +adiciona *branches* de monitoramento remoto para cada *branch* no repositório +clonado o que permite enviar alterações para um *branch* remoto. ```bash -# Clone learnxinyminutes-docs +# Clona learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git ``` ### commit -Armazena o conteúdo atual do índice em um novo "commit". Este commit contém -as alterações feitas e uma mensagem criada pelo utilizador. +Guarda o conteudo atual do index num novo *commit*. Este *commit* contém +as alterações feitas e a mensagem criada pelo usuário. ```bash # commit com uma mensagem @@ -222,170 +234,170 @@ $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" ### diff -Mostra as diferenças entre um arquivo no diretório, o índice de trabalho e commits. +Apresenta as diferenças entre um arquivo no repositório do projeto, *index* +e *commits* ```bash -# Mostrar diferença entre o seu diretório de trabalho e o índice. +# Apresenta a diferença entre o diretório atual e o index $ git diff -# Mostrar diferenças entre o índice e o commit mais recente. +# Apresenta a diferença entre o index e os commits mais recentes $ git diff --cached -# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente. +# Apresenta a diferença entre o diretório atual e o commit mais recente $ git diff HEAD ``` ### grep -Permite procurar rapidamente um repositório. +Permite procurar facilmente num repositório Configurações opcionais: ```bash -# Obrigado ao Travis Jeffery por isto -# Configure os números de linha a serem mostrados nos resultados de busca grep +# Define a apresentação de números de linha nos resultados do grep $ git config --global grep.lineNumber true -# Fazer resultados de pesquisa mais legível, incluindo agrupamento +# Agrupa os resultados da pesquisa para facilitar a leitura $ git config --global alias.g "grep --break --heading --line-number" ``` ```bash -# Procure por "variableName" em todos os arquivos java +# Pesquisa por "variableName" em todos os arquivos java $ git grep 'variableName' -- '*.java' -# Procure por uma linha que contém "arrayListName" e "adicionar" ou "remover" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) +# Pesquisa por uma linha que contém "arrayListName" e "add" ou "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) ``` -Google é seu amigo; para mais exemplos -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) +O Google é seu amigo; para mais exemplos: +[Git Grep Ninja (EN)](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) ### log -Mostrar commits para o repositório. +Apresenta commits do repositório. ```bash -# Mostrar todos os commits +# Apresenta todos os commits $ git log -# Mostrar um número X de commits +# Apresenta X commits $ git log -n 10 -# Mostrar somente commits mesclados +# Apresenta apenas commits de merge $ git log --merges ``` ### merge -"Merge" em mudanças de commits externos no branch atual. +"Merge" junta as alterações de commits externos com o *branch* atual. ```bash -# Mesclar o ramo especificado para o atual. +# Junta o branch especificado com o atual $ git merge branchName -# Gera sempre uma mesclagem commit ao mesclar +# Para gerar sempre um commit ao juntar os branches $ git merge --no-ff branchName ``` ### mv -Renomear ou mover um arquivo +Alterar o nome ou mover um arquivo. ```bash -# Renomear um arquivo +# Alterar o nome de um arquivo $ git mv HelloWorld.c HelloNewWorld.c # Mover um arquivo $ git mv HelloWorld.c ./new/path/HelloWorld.c -# Força renomear ou mover -# "ExistingFile" já existe no diretório, será substituído +# Forçar a alteração de nome ou mudança local +# "existingFile" já existe no directório, será sobrescrito. $ git mv -f myFile existingFile ``` ### pull -Puxa de um repositório e se funde com outro ramo. +Puxa alterações de um repositório e as junta com outro branch ```bash -# Atualize seu repo local, através da fusão de novas mudanças -# A partir da "origem" remoto e ramo "master (mestre)". +# Atualiza o repositório local, juntando as novas alterações +# do repositório remoto 'origin' e branch 'master' # git pull -# git pull => implícito por padrão => git pull origin master +# git pull => aplica a predefinição => git pull origin master $ git pull origin master -# Mesclar em mudanças de ramo remoto e rebase -# Ramo commita em seu repo local, como: "git pull , git rebase " +# Juntar alterações do branch remote e fazer rebase commits do branch +# no repositório local, como: "git pull , git rebase " $ git pull origin master --rebase ``` ### push -Empurre e mesclar as alterações de uma ramificação para uma remota e ramo. +Enviar e juntar alterações de um branch para o seu branch correspondente +num repositório remoto. ```bash -# Pressione e mesclar as alterações de um repo local para um -# Chamado remoto "origem" e ramo de "mestre". +# Envia e junta as alterações de um repositório local +# para um remoto denominado "origin" no branch "master". # git push -# git push => implícito por padrão => git push origin master +# git push => aplica a predefinição => git push origin master $ git push origin master - -# Para ligar atual filial local com uma filial remota, bandeira add-u: -$ git push -u origin master -# Agora, a qualquer hora que você quer empurrar a partir desse mesmo ramo local, uso de atalho: -$ git push ``` -### rebase (CAUTELA) +### rebase (cautela!) -Tire todas as alterações que foram commitadas em um ramo, e reproduzi-las em outro ramo. -* Não rebase commits que você tenha empurrado a um repo público *. +Pega em todas as alterações que foram registadas num branch e volta a +aplicá-las em outro branch. +*Não deve ser feito rebase de commits que foram enviados para um repositório +público* ```bash -# Rebase experimentBranch para mestre +# Faz Rebase de experimentBranch para master # git rebase $ git rebase master experimentBranch ``` -[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing) +[Leitura adicional (EN).](http://git-scm.com/book/en/Git-Branching-Rebasing) -### reset (CAUTELA) +### reset (cuidado!) -Repor o atual HEAD de estado especificado. Isto permite-lhe desfazer fusões (merge), -puxa (push), commits, acrescenta (add), e muito mais. É um grande comando, mas também -perigoso se não saber o que se está fazendo. +Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, +*pulls*, *commits*, *adds* e outros. É um comando muito poderoso mas também +perigoso quando não há certeza do que se está fazendo. ```bash -# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado) +# Restabelece a camada intermediária de registo para o último +# commit (o directório fica sem alterações) $ git reset -# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado +# Restabelece a camada intermediária de registo para o último commit, e +# sobrescreve o projeto atual $ git reset --hard -# Move a ponta ramo atual para o especificado commit (deixa diretório inalterado) -# Todas as alterações ainda existem no diretório. +# Move a head do branch atual para o commit especificado, sem alterar o projeto. +# todas as alterações ainda existem no projeto $ git reset 31f2bb1 -# Move a ponta ramo atual para trás, para o commit especificado -# E faz o jogo dir trabalho (exclui mudanças não commitadas e todos os commits -# Após o commit especificado). +# Inverte a head do branch atual para o commit especificado +# fazendo com que este esteja em sintonia com o diretório do projeto +# Remove alterações não registadas e todos os commits após o commit especificado $ git reset --hard 31f2bb1 ``` ### rm -O oposto do git add, git rm remove arquivos da atual árvore de trabalho. +O oposto de git add, git rm remove arquivos do branch atual. ```bash # remove HelloWorld.c $ git rm HelloWorld.c -# Remove um arquivo de um diretório aninhado +# Remove um arquivo de um sub-directório $ git rm /pather/to/the/file/HelloWorld.c ``` -# # Mais informações +## Informação complementar (EN) * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) @@ -398,5 +410,3 @@ $ git rm /pather/to/the/file/HelloWorld.c * [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) - -* [Git - guia prático](http://rogerdudler.github.io/git-guide/index.pt_BR.html) \ No newline at end of file -- cgit v1.2.3 From a3318599c8514b970a18148e687fae6a69d8f81e Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 13:15:42 -0200 Subject: Fixing some typos in Git pt-pt translation --- pt-pt/git-pt.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown index 66cda07f..a85c9704 100644 --- a/pt-pt/git-pt.html.markdown +++ b/pt-pt/git-pt.html.markdown @@ -74,8 +74,7 @@ maior controlo sobre o que é registado no repositório git. ### *Commit* -Um *commit** de git é um registo de um cojunto de alterações ou manipulações -no nos ficheiros do projecto. +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos ficheiros do projecto. Por exemplo, ao adicionar cinco ficheiros e remover outros 2, estas alterações serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado para outros repositórios ou não! @@ -83,7 +82,7 @@ para outros repositórios ou não! ### *Branch* Um *branch* é essencialmente uma referência que aponta para o último *commit* -efetuado. à medida que são feitos novos commits, esta referência é atualizada +efetuado. À medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. ### *HEAD* e *head* (componentes do directório .git) @@ -115,7 +114,7 @@ Permite configurar as definições, sejam as definições do repositório, siste ou configurações globais. ```bash -# Imprime & Define Algumas Variáveis de Configuração Básicas (Global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -123,7 +122,7 @@ $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` -[Aprenda Mais Sobre git config. (EN)](http://git-scm.com/docs/git-config) +[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help @@ -166,7 +165,7 @@ adicionados através de `git add` ao repositório, então eles não serão incluidos nos commits! ```bash -# adiciona um ficheiro no directório do project atual +# adiciona um ficheiro no directório do projecto atual $ git add HelloWorld.java # adiciona um ficheiro num sub-directório @@ -371,7 +370,7 @@ Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, perigoso se não há certeza quanto ao que se está a fazer. ```bash -# Restabelece a camada intermediária dr registo para o último +# Restabelece a camada intermediária de registo para o último # commit (o directório fica sem alterações) $ git reset -- cgit v1.2.3 From f4bd1bc8b462e09330ae22ae89a72c11354aa8ac Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 15:32:55 -0200 Subject: Python 3: Changing 'the other tutorial' to a link refering the other tutorial --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 6b1d3156..0293d7d2 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -13,7 +13,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 3 specifically. Check out the other tutorial if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 ```python -- cgit v1.2.3 From 22a0f44e64e6c7ac969556b9648ebcfca4bad187 Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 15:36:20 -0200 Subject: Refering Python3 tutorial link --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index da04d381..478804cd 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -14,7 +14,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. +to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). ```python -- cgit v1.2.3 From 8858382c044e6be744811a80a479de7304fcb3da Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Sat, 14 Feb 2015 22:26:14 +0100 Subject: Update go-de.html.markdown Fixed many, many grammar mistakes. --- de-de/go-de.html.markdown | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index ca27fdc7..4b50112e 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -5,34 +5,34 @@ contributors: - ["Joseph Adams", "https://github.com/jcla1"] lang: de-de --- -Go wurde entwickelt um probleme zu lösen. Sie ist zwar nicht der neuste Trend in -der Informatik, aber sie ist eine der neusten und schnellsten Wege um Aufgabe in +Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in +der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in der realen Welt zu lösen. -Sie hat vertraute Elemente von imperativen Sprachen mit statisher Typisierung +Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große Programmierprojekte. -Außerdem beinhaltet Go eine gut ausgestattete standard bibliothek und hat eine -aktive community. +Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine +aktive Community. ```go // Einzeiliger Kommentar /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Packet-Klausel. -// "main" ist ein besonderer Packetname, da er ein ausführbares Programm +// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. package main -// Ein "import" wird verwendet um Packte zu deklarieren, die in dieser +// Ein "import" wird verwendet, um Pakete zu deklarieren, die in dieser // Quelldatei Anwendung finden. import ( - "fmt" // Ein Packet in der Go standard Bibliothek + "fmt" // Ein Paket in der Go Standardbibliothek "net/http" // Ja, ein Webserver. "strconv" // Zeichenkettenmanipulation ) @@ -42,10 +42,10 @@ import ( // Programms. Vergessen Sie nicht die geschweiften Klammern! func main() { // Println gibt eine Zeile zu stdout aus. - // Der Prefix "fmt" bestimmt das Packet aus welchem die Funktion stammt. + // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. fmt.Println("Hello world!") - // Aufruf einer weiteren Funktion definiert innerhalb dieses Packets. + // Aufruf einer weiteren Funktion definiert innerhalb dieses Pakets. beyondHello() } @@ -217,7 +217,7 @@ func learnInterfaces() { // Aufruf der String Methode von i, gleiche Ausgabe wie zuvor. fmt.Println(i.String()) - // Funktionen des fmt-Packets rufen die String() Methode auf um eine + // Funktionen des fmt-Pakets rufen die String() Methode auf um eine // druckbare variante des Empfängers zu erhalten. fmt.Println(p) // gleiche Ausgabe wie zuvor fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor @@ -287,7 +287,7 @@ func learnConcurrency() { learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } -// Eine einzige Funktion aus dem http-Packet kann einen Webserver starten. +// Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die // sich angeschlossen werden soll. -- cgit v1.2.3 From b7c25da54c006a3aa885ebcbf7bfe7b8ff2ccc1e Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Sun, 15 Feb 2015 00:46:06 +0100 Subject: Update go-de.html.markdown More fixes. --- de-de/go-de.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 4b50112e..83d59c8b 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -54,7 +54,7 @@ func main() { func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. - // Kurze Deklaration: Benutzen Sie ":=" um die Typisierung automatisch zu + // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. y := 4 @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Wiedergabe zweier Werte } -// Überblick ueber einige eingebaute Typen und Literale. +// Überblick über einige eingebaute Typen und Literale. func learnTypes() { // Kurze Deklarationen sind die Norm. s := "Lernen Sie Go!" // Zeichenketten-Typ @@ -111,7 +111,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ m["eins"] = 1 // Ungebrauchte Variablen sind Fehler in Go - // Der Unterstrich wird verwendet um einen Wert zu verwerfen. + // Der Unterstrich wird verwendet, um einen Wert zu verwerfen. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Die Ausgabe zählt natürlich auch als Gebrauch fmt.Println(s, c, a4, s3, d2, m) @@ -142,7 +142,7 @@ func learnFlowControl() { if true { fmt.Println("hab's dir ja gesagt!") } - // Die Formattierung ist durch den Befehl "go fmt" standardisiert + // Die Formatierung ist durch den Befehl "go fmt" standardisiert if false { // nicht hier } else { @@ -170,7 +170,7 @@ func learnFlowControl() { continue // wird nie ausgeführt } - // Wie bei for, bedeutet := in einer Bedingten Anweisung zunächst die + // Wie bei for, bedeutet := in einer bedingten Anweisung zunächst die // Zuweisung und erst dann die Überprüfung der Bedingung. if y := expensiveComputation(); y > x { x = y @@ -218,7 +218,7 @@ func learnInterfaces() { fmt.Println(i.String()) // Funktionen des fmt-Pakets rufen die String() Methode auf um eine - // druckbare variante des Empfängers zu erhalten. + // druckbare Variante des Empfängers zu erhalten. fmt.Println(p) // gleiche Ausgabe wie zuvor fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor @@ -244,18 +244,18 @@ func learnErrorHandling() { learnConcurrency() } -// c ist ein Kannal, ein sicheres Kommunikationsmedium. +// c ist ein Kanal, ein sicheres Kommunikationsmedium. func inc(i int, c chan int) { - c <- i + 1 // <- ist der "send" Operator, wenn ein Kannal auf der Linken ist + c <- i + 1 // <- ist der "send" Operator, wenn ein Kanal auf der Linken ist } // Wir verwenden "inc" um Zahlen parallel zu erhöhen. func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für - // maps, slices und Kannäle. + // maps, slices und Kanäle. c := make(chan int) // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kannal. + // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) @@ -269,16 +269,16 @@ func learnConcurrency() { // Start einer neuen Goroutine, nur um einen Wert zu senden go func() { c <- 84 }() - go func() { cs <- "wortreich" }() // schon wider, diesmal für + go func() { cs <- "wortreich" }() // schon wieder, diesmal für // "select" hat eine Syntax wie ein switch Statement, aber jeder Fall ist - // eine Kannaloperation. Es wählt eine Fall zufällig aus allen die - // kommunikationsbereit sind aus. + // eine Kanaloperation. Es wählt einen Fall zufällig aus allen, die + // kommunikationsbereit sind, aus. select { case i := <-c: // der empfangene Wert kann einer Variable zugewiesen werden fmt.Printf("es ist ein: %T", i) case <-cs: // oder der Wert kann verworfen werden fmt.Println("es ist eine Zeichenkette!") - case <-cc: // leerer Kannal, nicht bereit für den Empfang + case <-cc: // leerer Kanal, nicht bereit für den Empfang fmt.Println("wird nicht passieren.") } // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. @@ -289,14 +289,14 @@ func learnConcurrency() { // Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { - // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die + // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse, an die // sich angeschlossen werden soll. // Der zweite Parameter ist ein Interface, speziell: ein http.Handler err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) // Fehler sollte man nicht ignorieren! } -// Wir lassen "pair" das http.Handler Interface erfüllen indem wir seine einzige +// Wir lassen "pair" das http.Handler Interface erfüllen, indem wir seine einzige // Methode implementieren: ServeHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Senden von Daten mit einer Methode des http.ResponseWriter @@ -313,6 +313,6 @@ Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktions- -Namen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). +verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). -- cgit v1.2.3 From 79170764a1b5069e648bb3764f95fbc3043e851b Mon Sep 17 00:00:00 2001 From: Wincent Balin Date: Tue, 3 Mar 2015 12:20:57 +0100 Subject: Update python-de.html.markdown Fixed typos. --- de-de/python-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 5ddb6f4b..ae29d6f9 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -149,7 +149,7 @@ li[0] #=> 1 # Das letzte Element ansehen li[-1] #=> 3 -# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError li[4] # Raises an IndexError # Wir können uns Ranges mit Slice-Syntax ansehen @@ -188,7 +188,7 @@ tup[:2] #=> (1, 2) # Wir können Tupel (oder Listen) in Variablen entpacken a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tuple werden standardmäßig erstellt, wenn wir uns die Klammern sparen +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen d, e, f = 4, 5, 6 # Es ist kinderleicht zwei Werte zu tauschen e, d = d, e # d is now 5 and e is now 4 -- cgit v1.2.3 From 2ae3d41c2749645fec4748c764ccd5c9405424e5 Mon Sep 17 00:00:00 2001 From: Nolan Prescott Date: Tue, 10 Mar 2015 15:09:35 -0500 Subject: Fix formatting, close #990 Cleaned up mixed tabs/spaces Wrapped lines at 80 characters Fixed incorrect comment regarding property name --- typescript.html.markdown | 125 ++++++++++++++++++++++++++--------------------- 1 file changed, 68 insertions(+), 57 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 9f04169a..937ebda1 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -14,100 +14,111 @@ This article will focus only on TypeScript extra syntax, as oposed to [JavaScrip 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. ```js -//There are 3 basic types in TypeScript +// There are 3 basic types in TypeScript var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//..When it's impossible to know, there is the "Any" type +// When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean -//For collections, there are typed arrays and generic arrays +// For collections, there are typed arrays and generic arrays var list: number[] = [1, 2, 3]; -//Alternatively, using the generic array type +// Alternatively, using the generic array type var list: Array = [1, 2, 3]; -//For enumerations: +// For enumerations: enum Color {Red, Green, Blue}; var c: Color = Color.Green; -//Lastly, "void" is used in the special case of a function not returning anything +// Lastly, "void" is used in the special case of a function returning nothing function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference -//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted +// Functions are first class citizens, support the lambda "fat arrow" syntax and +// use type inference + +// The following are equivalent, the same signature will be infered by the +// compiler, and same JavaScript will be emitted var f1 = function(i: number) : number { return i * i; } -var f2 = function(i: number) { return i * i; } //Return type infered +// Return type inferred +var f2 = function(i: number) { return i * i; } var f3 = (i : number) : number => { return i * i; } -var f4 = (i: number) => { return i * i; } //Return type infered -var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed +// Return type inferred +var f4 = (i: number) => { return i * i; } +// Return type inferred, one-liner means no return keyword needed +var f5 = (i: number) => i * i; -//Interfaces are structural, anything that has the properties is compliant with the interface +// Interfaces are structural, anything that has the properties is compliant with +// the interface interface Person { name: string; - //Optional properties, marked with a "?" + // Optional properties, marked with a "?" age?: number; - //And of course functions + // And of course functions move(): void; } -//..Object that implements the "Person" interface -var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties -//..Objects that have the optional property: +// Object that implements the "Person" interface +// Can be treated as a Person since it has the name and move properties +var p : Person = { name: "Bobby", move : () => {} }; +// Objects that have the optional property: var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; -var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number +// Is not a person because age is not a number +var invalidPerson : Person = { name: "Bobby", age: true }; -//..Interfaces can also describe a function type +// Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//..Only the parameters' types are important, names are not important. +// Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -//Classes - members are public by default +// Classes - members are public by default class Point { - //Properties - x: number; - - //Constructor - the public/private keywords in this context will generate the boiler plate code - // for the property and the initialization in the constructor. - // In this example, "y" will be defined just like "x" is, but with less code - //Default values are also supported - constructor(x: number, public y: number = 0) { - this.x = x; - } - - //Functions - dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - - //Static members - static origin = new Point(0, 0); + // Properties + x: number; + + // Constructor - the public/private keywords in this context will generate + // the boiler plate code for the property and the initialization in the + // constructor. + // In this example, "y" will be defined just like "x" is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static members + static origin = new Point(0, 0); } var p1 = new Point(10 ,20); var p2 = new Point(25); //y will be 0 -//Inheritance +// Inheritance class Point3D extends Point { - constructor(x: number, y: number, public z: number = 0) { - super(x, y); //Explicit call to the super class constructor is mandatory - } - - //Overwrite - dist() { - var d = super.dist(); - return Math.sqrt(d * d + this.z * this.z); - } + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Explicit call to the super class constructor is mandatory + } + + // Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } } -//Modules, "." can be used as separator for sub modules +// Modules, "." can be used as separator for sub modules module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -120,32 +131,32 @@ module Geometry { var s1 = new Geometry.Square(5); -//..Local alias for referencing a module +// Local alias for referencing a module import G = Geometry; var s2 = new G.Square(10); -//Generics -//..Classes +// Generics +// Classes class Tuple { constructor(public item1: T1, public item2: T2) { } } -//..Interfaces +// Interfaces interface Pair { - item1: T; - item2: T; + item1: T; + item2: T; } -//..And functions +// And functions var pairToTuple = function(p: Pair) { - return new Tuple(p.item1, p.item2); + return new Tuple(p.item1, p.item2); }; var tuple = pairToTuple({ item1:"hello", item2:"world"}); -//Including references to a definition file: +// Including references to a definition file: /// ``` -- cgit v1.2.3 From 394e7ecb84c68983f0bb210a8286cca0ff29e6d1 Mon Sep 17 00:00:00 2001 From: Nolan Prescott Date: Tue, 10 Mar 2015 15:35:00 -0500 Subject: whitespace typo, fix #989 --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 937ebda1..662af494 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -46,7 +46,7 @@ function bigHorribleAlert(): void { var f1 = function(i: number) : number { return i * i; } // Return type inferred var f2 = function(i: number) { return i * i; } -var f3 = (i : number) : number => { return i * i; } +var f3 = (i: number) : number => { return i * i; } // Return type inferred var f4 = (i: number) => { return i * i; } // Return type inferred, one-liner means no return keyword needed -- cgit v1.2.3 From 69480d51b82fdc7d2ad3d035c5744d85f56af807 Mon Sep 17 00:00:00 2001 From: Nolan Prescott Date: Tue, 10 Mar 2015 16:58:18 -0500 Subject: fix spacing issue --- typescript.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 662af494..27a1f71a 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -43,14 +43,14 @@ function bigHorribleAlert(): void { // The following are equivalent, the same signature will be infered by the // compiler, and same JavaScript will be emitted -var f1 = function(i: number) : number { return i * i; } +var f1 = function(i: number): number { return i * i; } // Return type inferred var f2 = function(i: number) { return i * i; } -var f3 = (i: number) : number => { return i * i; } +var f3 = (i: number): number => { return i * i; } // Return type inferred var f4 = (i: number) => { return i * i; } // Return type inferred, one-liner means no return keyword needed -var f5 = (i: number) => i * i; +var f5 = (i: number) => i * i; // Interfaces are structural, anything that has the properties is compliant with // the interface @@ -64,11 +64,11 @@ interface Person { // Object that implements the "Person" interface // Can be treated as a Person since it has the name and move properties -var p : Person = { name: "Bobby", move : () => {} }; +var p: Person = { name: "Bobby", move: () => {} }; // Objects that have the optional property: -var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; // Is not a person because age is not a number -var invalidPerson : Person = { name: "Bobby", age: true }; +var invalidPerson: Person = { name: "Bobby", age: true }; // Interfaces can also describe a function type interface SearchFunc { @@ -84,7 +84,7 @@ mySearch = function(src: string, sub: string) { class Point { // Properties x: number; - + // Constructor - the public/private keywords in this context will generate // the boiler plate code for the property and the initialization in the // constructor. @@ -94,10 +94,10 @@ class Point { constructor(x: number, public y: number = 0) { this.x = x; } - + // Functions dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - + // Static members static origin = new Point(0, 0); } @@ -110,7 +110,7 @@ class Point3D extends Point { constructor(x: number, y: number, public z: number = 0) { super(x, y); // Explicit call to the super class constructor is mandatory } - + // Overwrite dist() { var d = super.dist(); -- cgit v1.2.3 From 6034688980162cc5099dd2701b88e449182862f7 Mon Sep 17 00:00:00 2001 From: Antonio Lima Date: Sun, 15 Mar 2015 21:17:52 -0400 Subject: No-space array notation type[] --- java.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index ebe11bd3..10dd498c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -103,15 +103,15 @@ public class LearnJava { // Arrays //The array size must be decided upon instantiation //The following formats work for declaring an array - // [] = new []; + //[] = new []; // [] = new []; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; // Another way to declare & initialize an array - int [] y = {9000, 1000, 1337}; - String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; boolean bools[] = new boolean[] {true, false, false}; // Indexing an array - Accessing an element -- cgit v1.2.3 From 4e00fa4734bd39436f3336b4ce1034b65c265657 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Mon, 16 Mar 2015 21:09:17 +0200 Subject: Update haskell.html.markdown. Wrong explanation about '$' operator --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 79fbf09f..d5dfd122 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -202,9 +202,9 @@ foo = (*5) . (+10) foo 5 -- 75 -- fixing precedence --- Haskell has another function called `$`. This changes the precedence --- so that everything to the left of it gets computed first and then applied --- to everything on the right. You can use `$` (often in combination with `.`) +-- Haskell has another function called `$`. Anything appearing after it will +-- take precedence over anything that comes before. +-- You can use `$` (often in combination with `.`) -- to get rid of a lot of parentheses: -- before -- cgit v1.2.3 From 9fb21f1ce4c02e8cad50046f90d026ccab284626 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Mon, 16 Mar 2015 21:24:21 +0200 Subject: Haskell.html.markdown. Wrong result of an expression. The seventh Fibonacci number is 13 (odd number), so the result of 'even 13' is false. --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index d5dfd122..f1025d44 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -208,13 +208,13 @@ foo 5 -- 75 -- to get rid of a lot of parentheses: -- before -(even (fib 7)) -- true +(even (fib 7)) -- false -- after -even . fib $ 7 -- true +even . fib $ 7 -- false -- equivalently -even $ fib 7 -- true +even $ fib 7 -- false ---------------------------------------------------- -- 5. Type signatures -- cgit v1.2.3 From a81affb3027b81aa16eba8cac159a18081cff449 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 16 Mar 2015 14:07:19 -0600 Subject: Make the two fib functions consistent --- haskell.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 79fbf09f..2f807c5f 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -148,12 +148,12 @@ add 1 2 -- 3 -- Guards: an easy way to do branching in functions fib x - | x < 2 = x + | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) -- Pattern matching is similar. Here we have given three different -- definitions for fib. Haskell will automatically call the first --- function that matches the pattern of the value. +-- function that matches the pattern of the value. fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) @@ -181,7 +181,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- -- partial application: if you don't pass in all the arguments to a function, --- it gets "partially applied". That means it returns a function that takes the +-- it gets "partially applied". That means it returns a function that takes the -- rest of the arguments. add a b = a + b @@ -319,13 +319,13 @@ Nothing -- of type `Maybe a` for any `a` -- called. It must return a value of type `IO ()`. For example: main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) +main = putStrLn $ "Hello, sky! " ++ (say Blue) -- putStrLn has type String -> IO () --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function -- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the +-- inputs some text, runs a function on it, and prints out the -- output. countLines :: String -> String @@ -339,43 +339,43 @@ main' = interact countLines -- the `do` notation to chain actions together. For example: sayHello :: IO () -sayHello = do +sayHello = do putStrLn "What is your name?" name <- getLine -- this gets a line and gives it the name "name" putStrLn $ "Hello, " ++ name - + -- Exercise: write your own version of `interact` that only reads -- one line of input. - + -- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` -- and replace it with: -- main = sayHello --- Let's understand better how the function `getLine` we just +-- Let's understand better how the function `getLine` we just -- used works. Its type is: -- getLine :: IO String -- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` +-- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- store and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String action = do putStrLn "This is a line. Duh" - input1 <- getLine + input1 <- getLine input2 <- getLine -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `return` is not a keyword, but merely a function return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- We can use this just like we used `getLine`: main'' = do putStrLn "I will echo two lines!" - result <- action + result <- action putStrLn result putStrLn "This was all, folks!" -- cgit v1.2.3 From abce4e0a2fd8598a2768bcef86623a02e5f572e5 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 20:25:44 +0000 Subject: Adding Go French translation --- fr-fr/go-fr.html.markdown | 430 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 fr-fr/go-fr.html.markdown diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown new file mode 100644 index 00000000..1d2b656b --- /dev/null +++ b/fr-fr/go-fr.html.markdown @@ -0,0 +1,430 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] +--- + +Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la +dernière tendance en ce qui au développement, mais c'est la nouvelle façon de +régler des défis réels de façcon rapide. + +Le langage possède des concepts familiers à la programmation impérative avec +typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à +comprendre pour les processeurs multi coeurs d'aujourd'hui et apporte des +fonctionnalités facilitant le développement à grande échelle. + +Développer avec Go, c'est bénéficier d'une riche librairie standard et d'une +communauté active. + +```go +// Commentaire ligne simple +/* Commentaire + multiligne */ + +// Un paquet débute avec une clause "package" +// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt +// qu'une librairie +package main + +// "Import" déclare les paquets référencés dans ce fichier. +import ( + "fmt" // Un paquet dans la librairie standard. + "io/ioutil" // Implémente des fonctions utilitaires I/O. + m "math" // Librairie mathématique utilisant un alias local "m". + "net/http" // Un serveur Web! + "strconv" // Librairie pour convertir les chaînes de caractères. +) + +// Une définition de fonction. La fonction "main" est spéciale - c'est le point +// d'entrée du binaire. Celle-ci est encapsulée par des accolades. +func main() { + // Println retourne une ligne à stdout. + // Associez la fonction avec son paquet respectif, fmt. + fmt.Println("Hello world!") + + // Appelez une fonction différente à partir de ce paquet. + beyondHello() +} + +// Les fonctions ont des paramètres entre parenthèses. +// Les parenthèses sont nécessaires avec ou sans paramètre. +func beyondHello() { + var x int // Déclaration de variable. Les variables doivent être déclarées + // avant leur utilisation. + x = 3 // Assignation de valeur. + // Les déclarations courtes utilisent := pour inférer le type, déclarer et + // assigner. + y := 4 + sum, prod := learnMultiple(x, y) // La fonction retourne deux valeurs. + fmt.Println("sum:", sum, "prod:", prod) // Affichage simple. + learnTypes() // < y minutes, en savoir plus! +} + +// Les fonctions peuvent avoir des paramètres et plusieurs valeurs retournées. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Deux valeurs retournées. +} + +// Quelques types inclus et littéraux. +func learnTypes() { + // Déclaration courte produit généralement le type désiré. + str := "Learn Go!" // Type string. + + s2 := `Une chaîne de caractères peut contenir des +sauts de ligne.` // Chaîne de caractère. + + // Littéral non-ASCII. Les sources Go utilisent le charset UTF-8. + g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère + // unicode. + + f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. + c := 3 + 4i // complex128, représenté à l'interne par deux float64. + + // Syntaxe "var" avec une valeur d'initialisation. + var u uint = 7 // Non signé, mais la taille dépend selon l'entier. + var pi float32 = 22. / 7 + + // Conversion avec syntaxe courte. + n := byte('\n') // byte est un alias du type uint8. + + // Les tableaux ont des tailles fixes à la compilation. + var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0. + a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3 + // éléments, contenant les valeurs 3, 1 et 5. + + // Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun + // des avantages, mais les usages des slices sont plus communs. + s3 := []int{4, 5, 9} // Comparable à a3. + s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0. + var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire. + bs := []byte("a slice") // Conversion d'une chaîne en slice de bytes. + + // Parce qu'elles sont dynamiques, les slices peuvent être jointes sur + // demande. Pour joindre un élément à une slice, la fonction standard append() + // est utilisée. Le premier argument est la slice à utiliser. Habituellement, + // la variable tableau est mise à jour sur place, voir ci-bas. + s := []int{1, 2, 3} // Le résultat est une slice de taille 3. + s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6. + fmt.Println(s) // La valeur est maintenant de [1 2 3 4 5 6] + // Pour ajouter une autre slice, au lieu d'utiliser une liste de valeurs + // atomiques, il est possible de mettre en argument une référence de + // slice littérale de cette façon, avec des points de suspension, signifiant + // qu'il faut prendre les éléments de la slice et les ajouter à la slice s. + s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice + // littérale. + fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Déclare p, q comme étant des pointeurs de type int. + fmt.Println(*p, *q) // * suit un pointeur. Ceci retourne deux ints. + + // Les maps sont des tableaux associatifs de taille dynamique, comme les + // hash ou les types dictionnaires de certains langages. + m := map[string]int{"trois": 3, "quatre": 4} + m["un"] = 1 + + // Les valeurs inutilisées sont des erreurs en Go. + // Un tiret bas permet d'utiliser une variable, mais d'en jeter la valeur. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // L'affichage est considéré comme une utilisation de la variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // De retour dans le flux. +} + +// Il est possible, à l'opposée de plusieurs autres langages, à des fonctions +// en go d'avoir des valeurs retournées avec nom. +// Assigner un nom à un type retourné par une fonction permet de retrouver sa +// valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z est implicite, car la variable a été définie précédemment. +} + +// La récupération de la mémoire est automatique en Go. Le langage possède des +// pointeurs, mais aucun pointeur arithmétique. Vous pouvez faire une erreur +// avec un pointeur nil, mais pas en incrémentant un pointeur. +func learnMemory() (p, q *int) { + // Les valeurs retournées définies p et q ont le type pointeur int. + p = new(int) // Fonction standard "new" alloue la mémoire. + // Le int alloué est initialisé à 0, p n'est plus nil. + s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire. + s[3] = 7 // Assigne l'un des entiers. + r := -2 // Déclare une autre variable locale. + return &s[3], &r // & retourne l'adresse d'un objet. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // Bien que les "if" requiert des accolades, les parenthèses ne le sont pas. + if true { + fmt.Println("voilà!") + } + // Le formate est standardisé par la commande shell "go fmt." + if false { + // bing. + } else { + // bang. + } + // Utilisez "switch" au lieu des "if" en chaîne + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Les "case" n'ont pas besoin de "break;". + case 43: + // Non-exécuté. + } + // Comme les "if", "for" n'utilise pas de parenthèses. + // Les variables déclarées dans "for" et "if" sont locales à leur portée. + for x := 0; x < 3; x++ { // ++ est une incrémentation. + fmt.Println("itération ", x) + } + // x == 42 ici. + + // "For" est le seul type de boucle en Go, mais possède différentes formes. + for { // Boucle infinie + break // C'est une farce + continue // Non atteint. + } + + // Vous pouvez utiliser un "range" pour itérer dans un tableau, une slice, une + // chaîne, une map ou un channel. Les "range" retournent un canal ou deux + // valeurs (tableau, slice, chaîne et map). + for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} { + // pour chaque pair dans une map, affichage de la valeur et clé + fmt.Printf("clé=%s, valeur=%d\n", key, value) + } + + // À l'opposé du "for", := dans un "if" signifie la déclaration et + // l'assignation y en premier, et ensuite y > x + if y := expensiveComputation(); y > x { + x = y + } + // Les fonctions littérales est une fermeture (closure). + xBig := func() bool { + return x > 10000 // Réfère à la variable x déclarée en haut du "switch". + } + fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x). + x = 1.3e3 // Ceci fait x == 1300 + fmt.Println("xBig:", xBig()) // Maintenant false. + + // De plus, les fonctions littérales peuvent être définies et appelée + // sur la même ligne, agissant comme argument de fonctions, tant que: + // a) la fonction littérale est appelée suite à (), + // b) le résultat correspond au type de l'argument. + fmt.Println("Ajoute + multiplie deux nombres: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Appelé avec les arguments 10 et 2 + // => Ajoute + double deux nombres: 24 + + // Quand vous en aurez besoin, vous allez l'adorer. + goto love +love: + + learnFunctionFactory() // func retournant func correspond à fun(3)(3). + learnDefer() // Un survol de cette instruction important. + learnInterfaces() // Incontournable! +} + +func learnFunctionFactory() { + // Les deux syntaxes sont identiques, bien que la seconde est plus pratique. + fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!")) + + d := sentenceFactory("été") + fmt.Println(d("Une matinée d'", "agréable!")) + fmt.Println(d("Une soirée d'", "relaxante!")) +} + +// Le décorateur est un patron de conception commun dans d'autres langages. +// Il est possible de faire de même en Go avec des fonctions littérales +// acceptant des arguments. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // nouvelle chaîne + } +} + +func learnDefer() (ok bool) { + // Les déclarations différées sont exécutées avant la sortie d'une fonction. + defer fmt.Println("les déclarations différées s'exécutent en ordre LIFO.") + defer fmt.Println("\nCette ligne est affichée en premier parce que") + // Les déclarations différées sont utilisées fréquemment pour fermer un + // fichier, afin que la fonction ferme le fichier en fin d'exécution. + return true +} + +// Défini Stringer comme étant une interface avec une méthode, String. +type Stringer interface { + String() string +} + +// Défini pair comme étant une structure contenant deux entiers, x et y. +type pair struct { + x, y int +} + +// Défini une méthode associée au type pair. Pair implémente maintenant Stringer +func (p pair) String() string { // p s'appelle le "destinataire" + // Sprintf est une autre fonction publique dans le paquet fmt. + // La syntaxe avec point permet de faire référence aux valeurs de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // La syntaxe avec accolade défini une "structure littérale". Ceci s'évalue + // comme étant une strucutre. La syntaxe := déclare et initialise p comme + // étant cette structure. + p := pair{3, 4} + fmt.Println(p.String()) // Appelle la méthode String de p, de type pair. + var i Stringer // Déclare i de l'interface de type Stringer. + i = p // Valide, car pair implémente Stringer. + // Appelle la méthode String de i, de type Stringer. Retourne la même valeur + // que ci-haut. + fmt.Println(i.String()) + + // Les fonctions dans le paquet fmt appellent la méthode String, demandant + // aux objets d'afficher une représentation de leur structure. + fmt.Println(p) // Affiche la même chose que ci-haut. Println appelle la + // méthode String. + fmt.Println(i) // Affiche la même chose que ci-haut. + + learnVariadicParams("apprentissage", "génial", "ici!") +} + +// Les fonctions peuvent avoir des paramètres variables. +func learnVariadicParams(myStrings ...interface{}) { + // Itère chaque valeur du paramètre variable. + // Le tiret bas sert à ignorer l'index retourné du tableau. + for _, param := range myStrings { + fmt.Println("paramètre:", param) + } + + // Passe une valeur variadique comme paramètre variadique. + fmt.Println("paramètres:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" expression utilisée pour définir si quelque chose a fonctionné ou + // non. + m := map[int]string{3: "trois", 4: "quatre"} + if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map. + fmt.Println("inexistant") + } else { + fmt.Print(x) // x serait la valeur, si elle se trouvait dans la map. + } + // Une erreur ne retourne qu'un "ok", mais également plus d'information + // par rapport à un problème survenu. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discarte la valeur + // retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Nous réviserons les interfaces un peu plus tard. Maintenant, + learnConcurrency() +} + +// c est un canal, un objet permettant de communiquer en simultané de façon +// sécuritaire. +func inc(i int, c chan int) { + c <- i + 1 // <- est l'opérateur "destination" quand un canal apparaît à + // gauche. +} + +// Nous utiliserons inc pour incrémenter des nombres en même temps. +func learnConcurrency() { + // La fonction "make" utilisée précédemment pour générer un slice. Elle + // alloue et initialise les slices, maps et les canaux. + c := make(chan int) + // Démarrage de trois goroutines simultanées. Les nombres seront incrémentés + // simultanément, peut-être en paralèle si la machine le permet et configurée + // correctement. Les trois utilisent le même canal. + go inc(0, c) // go est une déclaration démarrant une nouvelle goroutine. + go inc(10, c) + go inc(-805, c) + // Lis et affiche trois résultats du canal - impossible de savoir dans quel + // ordre! + fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de + // "réception". + + cs := make(chan string) // Un autre canal, celui-ci gère des chaînes. + ccs := make(chan chan string) // Un canal de canaux de chaînes. + go func() { c <- 84 }() // Démarre une nouvelle goroutine, pour + // envoyer une valeur. + go func() { cs <- "wordy" }() // De nouveau, pour cs cette fois-ci. + // Select possède une syntaxe similaire au switch, mais chaque cas requiert + // une opération impliquant un canal. Il sélectionne un cas aléatoirement + // prêt à communiquer. + select { + case i := <-c: // La valeur reçue peut être assignée à une variable, + fmt.Printf("c'est un %T", i) + case <-cs: // ou la valeur reçue peut être discartée. + fmt.Println("c'est une chaîne") + case <-ccs: // Un canal vide, indisponible à la communication. + fmt.Println("ne surviendra pas.") + } + // À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines + // démarrée plus haut a complété, la seconde restera bloquée. + + learnWebProgramming() // Go permet la programmation Web. +} + +// Une seule fonction du paquet http démarre un serveur Web. +func learnWebProgramming() { + + // Le premier paramètre de ListenAndServe is une adresse TCP à écouter. + // Le second est une interface, de type http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // n'ignorez pas les erreurs! + }() + + requestServer() +} + +// Fait de pair un http.Handler en implémentant sa seule méthode: ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Répondez à une requête à l'aide de la méthode http.ResponseWriter. + w.Write([]byte("Vous avez appris Go en Y minutes!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nLe serveur Web a dit: `%s`", string(body)) +} +``` + +## En savoir plus + +La référence Go se trouve sur [le site officiel de Go](http://golang.org/). +Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. + +Une lecture de la documentation du langage est grandement conseillée. C'est +facile à lire et très court (comparé aux autres langages). + +Vous pouvez exécuter modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. + +Sur la liste de lecteur des étudiants de Go se trouve le [code source de la +librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre +le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous +pouvez cliquer sur le nom d'une fonction dans [la +documentation](http://golang.org/pkg/) et le code source apparaît! + +Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/). -- cgit v1.2.3 From 290c0956d00ddfe23a8cad9ce17f2eaed3a099c0 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 20:29:01 +0000 Subject: updating translators information --- fr-fr/go-fr.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 1d2b656b..31e1e92b 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-fr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -10,7 +10,9 @@ contributors: - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] +translators: - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] +lang: fr-fr --- Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la -- cgit v1.2.3 From 9922336a9df1359b57695bd5df538d98b8ab2dc0 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Monette Date: Tue, 17 Mar 2015 23:17:50 +0000 Subject: Updating French translation Thanks vendethiel for all the suggestions! --- fr-fr/go-fr.html.markdown | 140 ++++++++++++++++++++++++---------------------- 1 file changed, 73 insertions(+), 67 deletions(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 31e1e92b..2ff5902f 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo-fr.go +filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -10,21 +10,19 @@ contributors: - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] -translators: - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] -lang: fr-fr --- -Go a été créé dans l'optique de déveloper de façcon efficace. Ce n'est pas la -dernière tendance en ce qui au développement, mais c'est la nouvelle façon de -régler des défis réels de façcon rapide. +Go a été créé dans l'optique de développer de façon efficace. Ce n'est pas la +dernière tendance en ce qui est au développement, mais c'est la nouvelle façon +de régler des défis réels de façon rapide. Le langage possède des concepts familiers à la programmation impérative avec typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à -comprendre pour les processeurs multi coeurs d'aujourd'hui et apporte des +comprendre, pour les processeurs multi coeurs d'aujourd'hui et apporte des fonctionnalités facilitant le développement à grande échelle. -Développer avec Go, c'est bénéficier d'une riche librairie standard et d'une +Développer avec Go, c'est bénéficier d'une riche bibliothèque standard et d'une communauté active. ```go @@ -34,22 +32,22 @@ communauté active. // Un paquet débute avec une clause "package" // "Main" est un nom spécial déclarant un paquet de type exécutable plutôt -// qu'une librairie +// qu'une bibliothèque package main // "Import" déclare les paquets référencés dans ce fichier. import ( - "fmt" // Un paquet dans la librairie standard. + "fmt" // Un paquet dans la bibliothèque standard. "io/ioutil" // Implémente des fonctions utilitaires I/O. - m "math" // Librairie mathématique utilisant un alias local "m". + m "math" // Bibliothèque mathématique utilisant un alias local "m". "net/http" // Un serveur Web! - "strconv" // Librairie pour convertir les chaînes de caractères. + "strconv" // Bibliothèque pour convertir les chaînes de caractères. ) // Une définition de fonction. La fonction "main" est spéciale - c'est le point -// d'entrée du binaire. Celle-ci est encapsulée par des accolades. +// d'entrée du binaire. func main() { - // Println retourne une ligne à stdout. + // Println retournera la valeur à la console. // Associez la fonction avec son paquet respectif, fmt. fmt.Println("Hello world!") @@ -78,7 +76,7 @@ func learnMultiple(x, y int) (sum, prod int) { // Quelques types inclus et littéraux. func learnTypes() { - // Déclaration courte produit généralement le type désiré. + // Une déclaration courte infère généralement le type désiré. str := "Learn Go!" // Type string. s2 := `Une chaîne de caractères peut contenir des @@ -89,7 +87,7 @@ sauts de ligne.` // Chaîne de caractère. // unicode. f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. - c := 3 + 4i // complex128, représenté à l'interne par deux float64. + c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur. // Syntaxe "var" avec une valeur d'initialisation. var u uint = 7 // Non signé, mais la taille dépend selon l'entier. @@ -98,13 +96,13 @@ sauts de ligne.` // Chaîne de caractère. // Conversion avec syntaxe courte. n := byte('\n') // byte est un alias du type uint8. - // Les tableaux ont des tailles fixes à la compilation. + // Les tableaux ont une taille fixe déclarée à la compilation. var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0. a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3 // éléments, contenant les valeurs 3, 1 et 5. // Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun - // des avantages, mais les usages des slices sont plus communs. + // des avantages, mais les cas d'utilisation des slices sont plus fréquents. s3 := []int{4, 5, 9} // Comparable à a3. s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0. var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire. @@ -114,13 +112,13 @@ sauts de ligne.` // Chaîne de caractère. // demande. Pour joindre un élément à une slice, la fonction standard append() // est utilisée. Le premier argument est la slice à utiliser. Habituellement, // la variable tableau est mise à jour sur place, voir ci-bas. - s := []int{1, 2, 3} // Le résultat est une slice de taille 3. + s := []int{1, 2, 3} // Le résultat est une slice de taille 3. s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6. - fmt.Println(s) // La valeur est maintenant de [1 2 3 4 5 6] - // Pour ajouter une autre slice, au lieu d'utiliser une liste de valeurs + fmt.Println(s) // La valeur est de [1 2 3 4 5 6] + + // Pour ajouter une slice à une autre, au lieu d'utiliser une liste de valeurs // atomiques, il est possible de mettre en argument une référence de - // slice littérale de cette façon, avec des points de suspension, signifiant - // qu'il faut prendre les éléments de la slice et les ajouter à la slice s. + // slice littérale grâce aux points de suspension. s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice // littérale. fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9] @@ -133,17 +131,19 @@ sauts de ligne.` // Chaîne de caractère. m := map[string]int{"trois": 3, "quatre": 4} m["un"] = 1 - // Les valeurs inutilisées sont des erreurs en Go. - // Un tiret bas permet d'utiliser une variable, mais d'en jeter la valeur. + // Les valeurs inutilisées sont considérées comme des erreurs en Go. + // Un tiret bas permet d'ignorer une valeur inutilisée, évitant une erreur. _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs - // L'affichage est considéré comme une utilisation de la variable. + + // Cependant, son affichage en console est considéré comme une utilisation, + // ce qui ne sera pas considéré comme une erreur à la compilation. fmt.Println(s, c, a4, s3, d2, m) learnFlowControl() // De retour dans le flux. } -// Il est possible, à l'opposée de plusieurs autres langages, à des fonctions -// en go d'avoir des valeurs retournées avec nom. +// Il est possible, à l'opposé de plusieurs autres langages, de retourner des +// variables par leur nom à partir de fonctions. // Assigner un nom à un type retourné par une fonction permet de retrouver sa // valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus. func learnNamedReturns(x, y int) (z int) { @@ -152,10 +152,11 @@ func learnNamedReturns(x, y int) (z int) { } // La récupération de la mémoire est automatique en Go. Le langage possède des -// pointeurs, mais aucun pointeur arithmétique. Vous pouvez faire une erreur -// avec un pointeur nil, mais pas en incrémentant un pointeur. +// pointeurs, mais aucune arithmétique des pointeurs (*(a + b) en C). Vous +// pouvez produire une erreur avec un pointeur nil, mais pas en incrémentant un +// pointeur. func learnMemory() (p, q *int) { - // Les valeurs retournées définies p et q ont le type pointeur int. + // Les valeurs retournées p et q auront le type pointeur int. p = new(int) // Fonction standard "new" alloue la mémoire. // Le int alloué est initialisé à 0, p n'est plus nil. s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire. @@ -169,11 +170,12 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // Bien que les "if" requiert des accolades, les parenthèses ne le sont pas. + // Bien que les "if" requièrent des accolades, les parenthèses ne sont pas + // nécessaires pour contenir le test booléen. if true { fmt.Println("voilà!") } - // Le formate est standardisé par la commande shell "go fmt." + // Le formatage du code est standardisé par la commande shell "go fmt." if false { // bing. } else { @@ -189,8 +191,9 @@ func learnFlowControl() { case 43: // Non-exécuté. } - // Comme les "if", "for" n'utilise pas de parenthèses. - // Les variables déclarées dans "for" et "if" sont locales à leur portée. + // Comme les "if", les "for" n'utilisent pas de parenthèses. + // Les variables déclarées dans les "for" et les "if" sont locales à leur + // portée. for x := 0; x < 3; x++ { // ++ est une incrémentation. fmt.Println("itération ", x) } @@ -202,8 +205,8 @@ func learnFlowControl() { continue // Non atteint. } - // Vous pouvez utiliser un "range" pour itérer dans un tableau, une slice, une - // chaîne, une map ou un channel. Les "range" retournent un canal ou deux + // Vous pouvez utiliser une "range" pour itérer dans un tableau, une slice, une + // chaîne, une map ou un canal. Les "range" retournent un canal ou deux // valeurs (tableau, slice, chaîne et map). for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} { // pour chaque pair dans une map, affichage de la valeur et clé @@ -215,35 +218,35 @@ func learnFlowControl() { if y := expensiveComputation(); y > x { x = y } - // Les fonctions littérales est une fermeture (closure). + // Les fonctions littérales sont des fermetures. xBig := func() bool { - return x > 10000 // Réfère à la variable x déclarée en haut du "switch". + return x > 10000 } fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x). x = 1.3e3 // Ceci fait x == 1300 fmt.Println("xBig:", xBig()) // Maintenant false. - // De plus, les fonctions littérales peuvent être définies et appelée - // sur la même ligne, agissant comme argument de fonctions, tant que: + // De plus, les fonctions littérales peuvent être définies et appelées + // sur la même ligne, agissant comme argument à cette fonction, tant que: // a) la fonction littérale est appelée suite à (), // b) le résultat correspond au type de l'argument. - fmt.Println("Ajoute + multiplie deux nombres: ", + fmt.Println("Ajoute + multiplie deux nombres : ", func(a, b int) int { return (a + b) * 2 - }(10, 2)) // Appelé avec les arguments 10 et 2 - // => Ajoute + double deux nombres: 24 + }(10, 2)) // Appelle la fonction avec les arguments 10 et 2 + // => Ajoute + double deux nombres : 24 // Quand vous en aurez besoin, vous allez l'adorer. goto love love: - learnFunctionFactory() // func retournant func correspond à fun(3)(3). - learnDefer() // Un survol de cette instruction important. - learnInterfaces() // Incontournable! + learnFunctionFactory() // func retournant func correspondant à fun(3)(3). + learnDefer() // Un survol de cette instruction importante. + learnInterfaces() // Incontournable ! } func learnFunctionFactory() { - // Les deux syntaxes sont identiques, bien que la seconde est plus pratique. + // Les deux syntaxes sont identiques, bien que la seconde soit plus pratique. fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!")) d := sentenceFactory("été") @@ -287,12 +290,12 @@ func (p pair) String() string { // p s'appelle le "destinataire" } func learnInterfaces() { - // La syntaxe avec accolade défini une "structure littérale". Ceci s'évalue - // comme étant une strucutre. La syntaxe := déclare et initialise p comme - // étant cette structure. + // La syntaxe avec accolade défini une "structure littérale". Celle-ci + // s'évalue comme étant une structure. La syntaxe := déclare et initialise p + // comme étant une instance. p := pair{3, 4} fmt.Println(p.String()) // Appelle la méthode String de p, de type pair. - var i Stringer // Déclare i de l'interface de type Stringer. + var i Stringer // Déclare i instance de l'interface Stringer. i = p // Valide, car pair implémente Stringer. // Appelle la méthode String de i, de type Stringer. Retourne la même valeur // que ci-haut. @@ -307,9 +310,11 @@ func learnInterfaces() { learnVariadicParams("apprentissage", "génial", "ici!") } -// Les fonctions peuvent avoir des paramètres variables. +// Les fonctions peuvent être définie de façon à accepter un ou plusieurs +// paramètres grâce aux points de suspension, offrant une flexibilité lors de +// son appel. func learnVariadicParams(myStrings ...interface{}) { - // Itère chaque valeur du paramètre variable. + // Itère chaque paramètre dans la range. // Le tiret bas sert à ignorer l'index retourné du tableau. for _, param := range myStrings { fmt.Println("paramètre:", param) @@ -322,8 +327,8 @@ func learnVariadicParams(myStrings ...interface{}) { } func learnErrorHandling() { - // ", ok" expression utilisée pour définir si quelque chose a fonctionné ou - // non. + // ", ok" idiome utilisée pour définir si l'opération s'est déroulée avec + // succès ou non m := map[int]string{3: "trois", 4: "quatre"} if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map. fmt.Println("inexistant") @@ -336,14 +341,14 @@ func learnErrorHandling() { // retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } - // Nous réviserons les interfaces un peu plus tard. Maintenant, + // Nous réviserons les interfaces un peu plus tard. Pour l'instant, learnConcurrency() } // c est un canal, un objet permettant de communiquer en simultané de façon -// sécuritaire. +// sécurisée. func inc(i int, c chan int) { - c <- i + 1 // <- est l'opérateur "destination" quand un canal apparaît à + c <- i + 1 // <- est l'opérateur "envoi" quand un canal apparaît à // gauche. } @@ -355,11 +360,11 @@ func learnConcurrency() { // Démarrage de trois goroutines simultanées. Les nombres seront incrémentés // simultanément, peut-être en paralèle si la machine le permet et configurée // correctement. Les trois utilisent le même canal. - go inc(0, c) // go est une déclaration démarrant une nouvelle goroutine. + go inc(0, c) // go est une instruction démarrant une nouvelle goroutine. go inc(10, c) go inc(-805, c) // Lis et affiche trois résultats du canal - impossible de savoir dans quel - // ordre! + // ordre ! fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de // "réception". @@ -374,13 +379,13 @@ func learnConcurrency() { select { case i := <-c: // La valeur reçue peut être assignée à une variable, fmt.Printf("c'est un %T", i) - case <-cs: // ou la valeur reçue peut être discartée. + case <-cs: // ou la valeur reçue peut être ignorée. fmt.Println("c'est une chaîne") case <-ccs: // Un canal vide, indisponible à la communication. fmt.Println("ne surviendra pas.") } // À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines - // démarrée plus haut a complété, la seconde restera bloquée. + // démarrée plus haut a complétée, la seconde restera bloquée. learnWebProgramming() // Go permet la programmation Web. } @@ -388,17 +393,18 @@ func learnConcurrency() { // Une seule fonction du paquet http démarre un serveur Web. func learnWebProgramming() { - // Le premier paramètre de ListenAndServe is une adresse TCP à écouter. + // Le premier paramètre de ListenAndServe est une adresse TCP à écouter. // Le second est une interface, de type http.Handler. go func() { err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // n'ignorez pas les erreurs! + fmt.Println(err) // n'ignorez pas les erreurs ! }() requestServer() } -// Fait de pair un http.Handler en implémentant sa seule méthode: ServeHTTP. +// Implémente la méthode ServeHTTP de http.Handler à pair, la rendant compatible +// avec les opérations utilisant l'interface http.Handler. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Répondez à une requête à l'aide de la méthode http.ResponseWriter. w.Write([]byte("Vous avez appris Go en Y minutes!")) @@ -421,7 +427,7 @@ Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. Une lecture de la documentation du langage est grandement conseillée. C'est facile à lire et très court (comparé aux autres langages). -Vous pouvez exécuter modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. +Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. Sur la liste de lecteur des étudiants de Go se trouve le [code source de la librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre -- cgit v1.2.3 From 1b1d10e2d9b7493039382f0f6020e82d317d0c52 Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:37:42 +0530 Subject: add include? method on arrays --- ruby.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 1883d1ad..800f0445 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -169,6 +169,9 @@ array[1..3] #=> [2, 3, 4] # Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] +# Check if an item exists in an array +array.include?(1) #=> true + # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: hash = { 'color' => 'green', 'number' => 5 } -- cgit v1.2.3 From 37c00223d013da83d847767fbab6a3c4f960ad1a Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:38:16 +0530 Subject: add has_key? and has_value? methods on hashes --- ruby.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 800f0445..8c9d8fc5 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -191,6 +191,10 @@ new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] +# Check existence of keys and values in hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Both Arrays and Hashes are Enumerable # They share a lot of useful methods such as each, map, count, and more -- cgit v1.2.3 From 1246edea3f83063b24c97240a10246025831843d Mon Sep 17 00:00:00 2001 From: Rahil Momin Date: Thu, 19 Mar 2015 15:38:27 +0530 Subject: add to ruby contributors --- ruby.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 8c9d8fc5..792c9c95 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Ariel Krakowski", "http://www.learneroo.com"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] --- -- cgit v1.2.3 From 7243f13fc6462e9fee8d463e13446ab7339e9d67 Mon Sep 17 00:00:00 2001 From: ronaldxs Date: Fri, 20 Mar 2015 16:40:25 -0400 Subject: thrice .... gather ^3 counts three times "0 1 2" not 5 Probably just a paste-o mistake. Want to count 3 times not 5. --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 85ab1d79..1b320028 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -963,7 +963,7 @@ say join ',', gather if False { # But consider: constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything # versus: -constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 3 4 +constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 # - `lazy` - Defer actual evaluation until value is fetched (forces lazy context) # Not yet implemented !! -- cgit v1.2.3 From f1159951711a45c6f52b78ec247634c18f7de0b5 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 01:19:13 +0300 Subject: Use "haxe" highlighting instead of C# --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 8599de8d..b8e6a265 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -11,7 +11,7 @@ Haxe author). Note that this guide is for Haxe version 3. Some of the guide may be applicable to older versions, but it is recommended to use other references. -```csharp +```haxe /* Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org This is an executable tutorial. You can compile and run it using the haxe -- cgit v1.2.3 From 0e118934db0c6813482cee606ce15cec681a9ae0 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 01:21:28 +0300 Subject: [haxe] some additions and fixes (closes #489) --- haxe.html.markdown | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index b8e6a265..e57c46a8 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -3,6 +3,7 @@ language: haxe filename: LearnHaxe3.hx contributors: - ["Justin Donaldson", "https://github.com/jdonaldson/"] + - ["Dan Korostelev", "https://github.com/nadako/"] --- Haxe is a web-oriented language that provides platform support for C++, C#, @@ -34,16 +35,20 @@ references. /* This is your first actual haxe code coming up, it's declaring an empty package. A package isn't necessary, but it's useful if you want to create a - namespace for your code (e.g. org.module.ClassName). + namespace for your code (e.g. org.yourapp.ClassName). + + Omitting package declaration is the same as declaring empty package. */ package; // empty package, no namespace. /* - Packages define modules for your code. Each module (e.g. org.module) must - be lower case, and should exist as a folder structure containing the class. - Class (and type) names must be capitalized. E.g, the class "org.module.Foo" - should have the folder structure org/module/Foo.hx, as accessible from the - compiler's working directory or class path. + Packages are directories that contain modules. Each module is a .hx file + that contains types defined in a package. Package names (e.g. org.yourapp) + must be lower case while module names are capitalized. A module contain one + or more types whose names are also capitalized. + + E.g, the class "org.yourapp.Foo" should have the folder structure org/module/Foo.hx, + as accessible from the compiler's working directory or class path. If you import code from other files, it must be declared before the rest of the code. Haxe provides a lot of common default classes to get you started: @@ -53,6 +58,12 @@ import haxe.ds.ArraySort; // you can import many classes/modules at once with "*" import haxe.ds.*; +// you can import static fields +import Lambda.array; + +// you can also use "*" to import all static fields +import Math.*; + /* You can also import classes in a special way, enabling them to extend the functionality of other classes like a "mixin". More on 'using' later. @@ -172,7 +183,8 @@ class LearnHaxe3{ Regexes are also supported, but there's not enough space to go into much detail. */ - trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))"); + var re = ~/foobar/; + trace(re.match('foo') + " is the value for (~/foobar/.match('foo')))"); /* Arrays are zero-indexed, dynamic, and mutable. Missing values are @@ -383,11 +395,7 @@ class LearnHaxe3{ */ // if statements - var k = if (true){ - 10; - } else { - 20; - } + var k = if (true) 10 else 20; trace("K equals ", k); // outputs 10 @@ -628,6 +636,7 @@ enum ComplexEnum{ ComplexEnumEnum(c:ComplexEnum); } // Note: The enum above can include *other* enums as well, including itself! +// Note: This is what called *Algebraic data type* in some other languages. class ComplexEnumTest{ public static function example(){ -- cgit v1.2.3 From 20d612ce5c8e1fe8ea23c15ff937142ef53f5034 Mon Sep 17 00:00:00 2001 From: Fatih Erikli Date: Tue, 24 Mar 2015 11:11:14 +0200 Subject: Add brainfuck-visualizer link --- brainfuck.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 27ac6921..aa1fcc40 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -8,6 +8,8 @@ contributors: Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. +You can try brainfuck on your browser with brainfuck-visualizer. + ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. -- cgit v1.2.3 From 03398877482f08c017e6774665f2c3b6e206ed34 Mon Sep 17 00:00:00 2001 From: Dan Korostelev Date: Tue, 24 Mar 2015 12:37:49 +0300 Subject: [haxe] polishing --- haxe.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index e57c46a8..c807d2d7 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -12,7 +12,7 @@ Haxe author). Note that this guide is for Haxe version 3. Some of the guide may be applicable to older versions, but it is recommended to use other references. -```haxe +```csharp /* Welcome to Learn Haxe 3 in 15 minutes. http://www.haxe.org This is an executable tutorial. You can compile and run it using the haxe @@ -37,7 +37,7 @@ references. package. A package isn't necessary, but it's useful if you want to create a namespace for your code (e.g. org.yourapp.ClassName). - Omitting package declaration is the same as declaring empty package. + Omitting package declaration is the same as declaring an empty package. */ package; // empty package, no namespace. @@ -636,7 +636,7 @@ enum ComplexEnum{ ComplexEnumEnum(c:ComplexEnum); } // Note: The enum above can include *other* enums as well, including itself! -// Note: This is what called *Algebraic data type* in some other languages. +// Note: This is what's called *Algebraic data type* in some other languages. class ComplexEnumTest{ public static function example(){ -- cgit v1.2.3 From 7e7a60d47ce0113e1a5b4ee8642984c60a08f569 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 12:29:01 +0200 Subject: Update python3.html.markdown. Changes to spacing and online resources 1. Some changes related to spacing 2. Added an online resource --- python3.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 0293d7d2..e8913267 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -276,7 +276,7 @@ empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} -#Can set new variables to a set +# Can set new variables to a set filled_set = some_set # Add one more item to the set @@ -394,7 +394,6 @@ our_iterator.__next__() # Raises StopIteration list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - #################################################### ## 4. Functions #################################################### @@ -410,7 +409,6 @@ add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. - # You can define functions that take a variable number of # positional arguments def varargs(*args): @@ -418,7 +416,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword arguments, as well def keyword_args(**kwargs): @@ -636,6 +633,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) ### Dead Tree -- cgit v1.2.3 From 44c37d5531d42a73b0bde49525e586b413489caf Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 19:26:19 +0200 Subject: [python3.html.mardown] Added a short statement about magic methods Terminology related to Python special functions --- python3.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index e8913267..56126ad3 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -498,7 +498,9 @@ class Human(object): # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name -- cgit v1.2.3 From c7a9731b07071c2380a5383ab976592df970aa50 Mon Sep 17 00:00:00 2001 From: Fatih Erikli Date: Tue, 24 Mar 2015 22:24:49 +0200 Subject: Change link format --- brainfuck.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index aa1fcc40..a76169c8 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -8,7 +8,7 @@ contributors: Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. -You can try brainfuck on your browser with brainfuck-visualizer. +You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. -- cgit v1.2.3 From 2f43da109ffab5a4d3dd582cc51a7c3d95dd4987 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Wed, 25 Mar 2015 18:08:32 +0200 Subject: [haskell.html.markdown] Changed explanation for Haskell '$' operator --- haskell.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index f1025d44..6bdc78e0 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -202,10 +202,12 @@ foo = (*5) . (+10) foo 5 -- 75 -- fixing precedence --- Haskell has another function called `$`. Anything appearing after it will --- take precedence over anything that comes before. --- You can use `$` (often in combination with `.`) --- to get rid of a lot of parentheses: +-- Haskell has another operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator +-- has priority of 0 and is right-associative. Such a low priority means that +-- all other operators on both sides of `$` will be evaluated before applying +-- the `$`. -- before (even (fib 7)) -- false -- cgit v1.2.3 From c5c8004450567a4be4c814e3c18725688c1601b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 19:50:46 +0200 Subject: Primitive Datatypes and Operators --- tr-tr/python3-tr.html.markdown | 645 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 645 insertions(+) create mode 100644 tr-tr/python3-tr.html.markdown diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown new file mode 100644 index 00000000..d815e4f9 --- /dev/null +++ b/tr-tr/python3-tr.html.markdown @@ -0,0 +1,645 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: learnpython3-tr.py +--- + +Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. + +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. + +```python + +# Single line comments start with a number symbol. + +""" Multiline strings can be written + using three "s, and are often used + as comments +""" + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# You have numbers +3 # => 3 + +# Math is what you would expect +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Except division which returns floats by default +35 / 5 # => 7.0 + +# Result of integer division truncated down both for positive and negative. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# When you use a float, results are floats +3 * 2.0 # => 6.0 + +# Modulo operation +7 % 3 # => 1 + +# Exponentiation (x to the yth power) +2**4 # => 16 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Boolean values are primitives +True +False + +# negate with not +not True # => False +not False # => True + +# Boolean Operators +# Note "and" and "or" are case-sensitive +True and False #=> False +False or True #=> True + +# Note using Bool operators with ints +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Equality is == +1 == 1 # => True +2 == 1 # => False + +# Inequality is != +1 != 1 # => False +2 != 1 # => True + +# More comparisons +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparisons can be chained! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Strings are created with " or ' +"This is a string." +'This is also a string.' + +# Strings can be added too! But try not to do this. +"Hello " + "world!" # => "Hello world!" + +# A string can be treated like a list of characters +"This is a string"[0] # => 'T' + +# .format can be used to format strings, like this: +"{} can be {}".format("strings", "interpolated") + +# You can repeat the formatting arguments to save some typing. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# You can use keywords if you don't want to count. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# If your Python 3 code also needs to run on Python 2.5 and below, you can also +# still use the old style of formatting: +"%s can be %s the %s way" % ("strings", "interpolated", "old") + + +# None is an object +None # => None + +# Don't use the equality "==" symbol to compare objects to None +# Use "is" instead. This checks for equality of object identity. +"etc" is None # => False +None is None # => True + +# None, 0, and empty strings/lists/dicts all evaluate to False. +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print function +print("I'm Python. Nice to meet you!") + +# No need to declare variables before assigning to them. +# Convention is to use lower_case_with_underscores +some_var = 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_unknown_var # Raises a NameError + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Revert the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +# Note: values for li and for other_li are not modified. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do all those list thingies on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# Tuples are created by default if you leave out the parentheses +d, e, f = 4, 5, 6 +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as a list with "keys()". +# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. +# Note - Same as above regarding key ordering. +list(filled_dict.values()) # => [3, 2, 1] + + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + +# Adding to a dictionary +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 #another way to add to dict + +# Remove keys from a dictionary with del +del filled_dict["one"] # Removes the key "one" from filled dict + + +# Sets store ... well sets +empty_set = set() +# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Can set new variables to a set +filled_set = some_set + +# Add one more item to the set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow and Iterables +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # This elif clause is optional. + print("some_var is smaller than 10.") +else: # This is optional too. + print("some_var is indeed 10.") + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +"range(number)" returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print("All good!") # Runs only if the code in try raises no exceptions + +# Python offers a fundamental abstraction called the Iterable. +# An iterable is an object that can be treated as a sequence. +# The object returned the range function, is an iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface + +# We can loop over it. +for i in our_iterable: + print(i) # Prints one, two, three + +# However we cannot address elements by index. +our_iterable[1] # Raises a TypeError + +# An iterable is an object that knows how to create an iterator. +our_iterator = iter(our_iterable) + +# Our iterator is an object that can remember the state as we traverse through it. +# We get the next object by calling the __next__ function. +our_iterator.__next__() #=> "one" + +# It maintains state as we call __next__. +our_iterator.__next__() #=> "two" +our_iterator.__next__() #=> "three" + +# After the iterator has returned all of its data, it gives you a StopIterator Exception +our_iterator.__next__() # Raises StopIteration + +# You can grab all the elements of an iterator by calling list() on it. +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + +# You can define functions that take a variable number of +# positional arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# You can define functions that take a variable number of +# keyword arguments, as well +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand tuples and use ** to expand kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + + +# Function Scope +x = 5 + +def setX(num): + # Local var x not the same as global variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +# List comprehension stores the output as a list which can itself be a nested list +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# We subclass from object to get a class. +class Human(object): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantiate a class +i = Human(name="Ian") +print(i.say("hi")) # prints out "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +print(math.sqrt(16)) # => 4 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# A generator creates values on the fly. +# Instead of generating and returning all values at once it creates one in each +# iteration. This means values bigger than 15 wont be processed in +# double_numbers. +# Note range is a generator too. Creating a list 1-900000000 would take lot of +# time to be made +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +range_ = range(1, 900000000) +# will double all numbers until a result >=30 found +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorators +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # Can you buy me a beer? +print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) + +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + -- cgit v1.2.3 From 46273c1ffe60c581968c9b43d1fb603a881823e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 20:34:27 +0200 Subject: Variables and Collections --- tr-tr/python3-tr.html.markdown | 297 ++++++++++++++++++++--------------------- 1 file changed, 148 insertions(+), 149 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index d815e4f9..4939f219 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -17,119 +17,119 @@ Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [bur ```python -# Single line comments start with a number symbol. +# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. -""" Multiline strings can be written - using three "s, and are often used - as comments +""" Çok satırlı olmasını istediğiniz yorumlar + üç adet tırnak(") işareti ile + yapılmaktadır """ #################################################### -## 1. Primitive Datatypes and Operators +## 1. Temel Veri Türleri ve Operatörler #################################################### -# You have numbers +# Sayılar 3 # => 3 -# Math is what you would expect +# Tahmin edebileceğiniz gibi matematik 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats by default +# Bölme işlemi varsayılan olarak onluk döndürür 35 / 5 # => 7.0 -# Result of integer division truncated down both for positive and negative. +# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too +5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# When you use a float, results are floats +# Onluk kullanırsanız, sonuç da onluk olur 3 * 2.0 # => 6.0 -# Modulo operation +# Kalan operatörü 7 % 3 # => 1 -# Exponentiation (x to the yth power) +# Üs (2 üzeri 4) 2**4 # => 16 -# Enforce precedence with parentheses +# Parantez ile önceliği değiştirebilirsiniz (1 + 3) * 2 # => 8 -# Boolean values are primitives +# Boolean(Doğru-Yanlış) değerleri standart True False -# negate with not +# 'değil' ile terse çevirme not True # => False not False # => True -# Boolean Operators -# Note "and" and "or" are case-sensitive +# Boolean Operatörleri +# "and" ve "or" büyük küçük harf duyarlıdır True and False #=> False False or True #=> True -# Note using Bool operators with ints +# Bool operatörleri ile sayı kullanımı 0 and 2 #=> 0 -5 or 0 #=> -5 0 == False #=> True 2 == True #=> False 1 == True #=> True -# Equality is == +# Eşitlik kontrolü == 1 == 1 # => True 2 == 1 # => False -# Inequality is != +# Eşitsizlik Kontrolü != 1 != 1 # => False 2 != 1 # => True -# More comparisons +# Diğer karşılaştırmalar 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True -# Comparisons can be chained! +# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# Strings are created with " or ' -"This is a string." -'This is also a string.' +# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir +"Bu bir yazı." +'Bu da bir yazı.' -# Strings can be added too! But try not to do this. -"Hello " + "world!" # => "Hello world!" +# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. +"Merhaba " + "dünya!" # => "Merhaba dünya!" -# A string can be treated like a list of characters -"This is a string"[0] # => 'T' +# Bir yazı(string) karakter listesi gibi işlenebilir +"Bu bir yazı"[0] # => 'B' -# .format can be used to format strings, like this: -"{} can be {}".format("strings", "interpolated") +# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: +"{} da ayrıca {}".format("yazılar", "işlenebilir") -# You can repeat the formatting arguments to save some typing. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. +"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") +#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" -# You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. +"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" -# If your Python 3 code also needs to run on Python 2.5 and below, you can also -# still use the old style of formatting: -"%s can be %s the %s way" % ("strings", "interpolated", "old") +# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, +# eski stil formatlamayı kullanabilirsiniz: +"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") -# None is an object +# Hiçbir şey(none) da bir objedir None # => None -# Don't use the equality "==" symbol to compare objects to None -# Use "is" instead. This checks for equality of object identity. -"etc" is None # => False +# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın +# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. +"vb" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts all evaluate to False. -# All other values are True +# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. +# Diğer veriler ise True değeri döndürür bool(0) # => False bool("") # => False bool([]) #=> False @@ -137,164 +137,163 @@ bool({}) #=> False #################################################### -## 2. Variables and Collections +## 2. Değişkenler ve Koleksiyonlar #################################################### -# Python has a print function -print("I'm Python. Nice to meet you!") +# Python bir yazdırma fonksiyonuna sahip +print("Ben Python. Tanıştığıma memnun oldum!") -# No need to declare variables before assigning to them. -# Convention is to use lower_case_with_underscores -some_var = 5 -some_var # => 5 +# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. +# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin +bir_degisken = 5 +bir_degisken # => 5 -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_unknown_var # Raises a NameError +# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. +# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. +bir_bilinmeyen_degisken # NameError hatası oluşturur -# Lists store sequences +# Listeler ile sıralamaları tutabilirsiniz li = [] -# You can start with a prefilled list -other_li = [4, 5, 6] - -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop -li.pop() # => 3 and li is now [1, 2, 4] -# Let's put it back -li.append(3) # li is now [1, 2, 4, 3] again. - -# Access a list like you would any array +# Önceden doldurulmuş listeler ile başlayabilirsiniz +diger_li = [4, 5, 6] + +# 'append' ile listenin sonuna ekleme yapabilirsiniz +li.append(1) # li artık [1] oldu +li.append(2) # li artık [1, 2] oldu +li.append(4) # li artık [1, 2, 4] oldu +li.append(3) # li artık [1, 2, 4, 3] oldu +# 'pop' ile listenin son elementini kaldırabilirsiniz +li.pop() # => 3 ve li artık [1, 2, 4] +# Çıkarttığımız tekrardan ekleyelim +li.append(3) # li yeniden [1, 2, 4, 3] oldu. + +# Dizi gibi listeye erişim sağlayın li[0] # => 1 -# Look at the last element +# Son elemente bakın li[-1] # => 3 -# Looking out of bounds is an IndexError -li[4] # Raises an IndexError +# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur +li[4] # IndexError hatası oluşturur -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) +# Bir kısmını almak isterseniz. li[1:3] # => [2, 4] -# Omit the beginning +# Başlangıç belirtmezseniz li[2:] # => [4, 3] -# Omit the end +# Sonu belirtmesseniz li[:3] # => [1, 2, 4] -# Select every second entry +# Her ikişer objeyi seçme li[::2] # =>[1, 4] -# Revert the list +# Listeyi tersten almak li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] +# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz +# li[baslangic:son:adim] -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz +del li[2] # li artık [1, 2, 3] oldu -# You can add lists -# Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +# Listelerde de ekleme yapabilirsiniz +# Not: değerler üzerinde değişiklik yapılmaz. +li + diger_li # => [1, 2, 3, 4, 5, 6] -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# Listeleri birbirine bağlamak için "extend()" kullanılabilir +li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu -# Check for existence in a list with "in" +# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir 1 in li # => True -# Examine the length with "len()" +# Uzunluğu öğrenmek için "len()" kullanılabilir len(li) # => 6 -# Tuples are like lists but are immutable. +# Tüpler listeler gibidir fakat değiştirilemez. tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # Raises a TypeError +tup[0] = 3 # TypeError hatası oluşturur -# You can do all those list thingies on tuples too +# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -# Tuples are created by default if you leave out the parentheses +# Tüpleri(veya listeleri) değişkenlere açabilirsiniz +a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 +# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur d, e, f = 4, 5, 6 -# Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +# 2 değeri birbirine değiştirmek bu kadar kolay +e, d = d, e # 'd' artık 5 ve 'e' artık 4 -# Dictionaries store mappings -empty_dict = {} -# Here is a prefilled dictionary -filled_dict = {"one": 1, "two": 2, "three": 3} +# Sözlükler anahtar kodlarla verileri tutar +bos_sozl = {} +# Önceden doldurulmuş sözlük oluşturma +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} -# Look up values with [] -filled_dict["one"] # => 1 +# Değere bakmak için [] kullanalım +dolu_sozl["bir"] # => 1 -# Get all keys as a list with "keys()". -# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +# Bütün anahtarları almak için "keys()" kullanılabilir. +# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. +# Not - Sözlük anahtarlarının sıralaması kesin değildir. +# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. +list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] -# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. -# Note - Same as above regarding key ordering. -list(filled_dict.values()) # => [3, 2, 1] +# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor +# Not - Sıralama değişebilir. +list(dolu_sozl.values()) # => [3, 2, 1] -# Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz +"bir" in dolu_sozl # => True +1 in dolu_sozl # => False -# Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. +dolu_sozl["dort"] # KeyError hatası oluşturur -# Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing -filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz +dolu_sozl.get("bir") # => 1 +dolu_sozl.get("dort") # => None +# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. +dolu_sozl.get("bir", 4) # => 1 +dolu_sozl.get("dort", 4) # => 4 -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 +# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır +dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip +dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip -# Adding to a dictionary -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +# Sözlüğe ekleme +dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} +#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu -# Remove keys from a dictionary with del -del filled_dict["one"] # Removes the key "one" from filled dict +# Sözlükten anahtar silmek için 'del' kullanılabilir +del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir -# Sets store ... well sets -empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +# Setler ... set işte :D +bos_set = set() +# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. +bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} -# Can set new variables to a set -filled_set = some_set +# Sete yeni setler ekleyebilirsiniz +dolu_set = bir_set -# Add one more item to the set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Sete bir diğer öğe ekleme +dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu -# Do set intersection with & -other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz +diger_set = {3, 4, 5, 6} +dolu_set & diger_set # => {3, 4, 5} -# Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz +dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} -# Do set difference with - +# Farklılıkları almak için "-" kullanabilirsiniz {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# Check for existence in a set with in -2 in filled_set # => True -10 in filled_set # => False +# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir +2 in dolu_set # => True +10 in dolu_set # => False #################################################### -- cgit v1.2.3 From 1ab0a6eb5e73079393844719da067c37e84b8fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:05:25 +0200 Subject: Control Flow and Iterables --- tr-tr/python3-tr.html.markdown | 109 ++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 55 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 4939f219..b1806e7b 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -297,37 +297,37 @@ dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} #################################################### -## 3. Control Flow and Iterables +## 3. Kontrol Akışları ve Temel Soyutlandırma #################################################### -# Let's just make a variable -some_var = 5 +# Bir değişken oluşturalım +bir_degisken = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" -if some_var > 10: - print("some_var is totally bigger than 10.") -elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") -else: # This is optional too. - print("some_var is indeed 10.") +# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! +# çıktı olarak "bir_degisken 10 dan küçük" yazar +if bir_degisken > 10: + print("bir_degisken 10 dan büyük") +elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. + print("bir_degisken 10 dan küçük") +else: # Bu ifade de zorunlu değil. + print("bir_degisken değeri 10") """ -For loops iterate over lists -prints: - dog is a mammal - cat is a mammal - mouse is a mammal +Döngülerle lsiteleri döngüye alabilirsiniz +çıktı: + köpek bir memeli hayvandır + kedi bir memeli hayvandır + fare bir memeli hayvandır """ -for animal in ["dog", "cat", "mouse"]: - # You can use format() to interpolate formatted strings - print("{} is a mammal".format(animal)) +for hayvan in ["köpek", "kedi, "fare"]: + # format ile kolayca yazıyı biçimlendirelim + print("{} bir memeli hayvandır".format(hayvan)) """ -"range(number)" returns a list of numbers -from zero to the given number -prints: +"range(sayi)" bir sayı listesi döndür +0'dan belirttiğiniz sayıyıa kadar +çıktı: 0 1 2 @@ -337,8 +337,8 @@ for i in range(4): print(i) """ -While loops go until a condition is no longer met. -prints: +'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. +çıktı: 0 1 2 @@ -347,50 +347,49 @@ prints: x = 0 while x < 4: print(x) - x += 1 # Shorthand for x = x + 1 + x += 1 # Uzun hali x = x + 1 -# Handle exceptions with a try/except block +# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz try: - # Use "raise" to raise an error - raise IndexError("This is an index error") + # Bir hata oluşturmak için "raise" kullanabilirsiniz + raise IndexError("Bu bir index hatası") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Önemsiz, devam et. except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print("All good!") # Runs only if the code in try raises no exceptions + pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. +else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır + print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı -# Python offers a fundamental abstraction called the Iterable. -# An iterable is an object that can be treated as a sequence. -# The object returned the range function, is an iterable. +# Temel Soyutlandırma, bir objenin işlenmiş halidir. +# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. -filled_dict = {"one": 1, "two": 2, "three": 3} -our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} +temel_soyut = dolu_sozl.keys() +print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu -# We can loop over it. -for i in our_iterable: - print(i) # Prints one, two, three +# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. +for i in temel_soyut: + print(i) # Çıktısı: bir, iki, uc -# However we cannot address elements by index. -our_iterable[1] # Raises a TypeError +# Fakat, elementin anahtarına değerine. +temel_soyut[1] # TypeError hatası! -# An iterable is an object that knows how to create an iterator. -our_iterator = iter(our_iterable) +# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. +iterator = iter(temel_soyut) -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object by calling the __next__ function. -our_iterator.__next__() #=> "one" +# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır +# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. +iterator.__next__() #=> "bir" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir +iterator.__next__() #=> "iki" +iterator.__next__() #=> "uc" -# After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. +iterator.__next__() # StopIteration hatası -# You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. +list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] #################################################### -- cgit v1.2.3 From 71d688379641a91f6247920962a005d9af635a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:26:00 +0200 Subject: Functions --- tr-tr/python3-tr.html.markdown | 100 ++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 52 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index b1806e7b..6babb7d0 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -393,93 +393,89 @@ list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] #################################################### -## 4. Functions +## 4. Fonksiyonlar #################################################### -# Use "def" to create new functions -def add(x, y): - print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement +# "def" ile yeni fonksiyonlar oluşturabilirsiniz +def topla(x, y): + print("x = {} ve y = {}".format(x, y)) + return x + y # Değer döndürmek için 'return' kullanmalısınız -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# Fonksiyonu parametleri ile çağırıyoruz +topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek +topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. -# You can define functions that take a variable number of -# positional arguments -def varargs(*args): - return args +# Sınırsız sayıda argüman da alabilirsiniz +def argumanlar(*argumanlar): + return argumanlar -varargs(1, 2, 3) # => (1, 2, 3) +argumanlar(1, 2, 3) # => (1, 2, 3) -# You can define functions that take a variable number of -# keyword arguments, as well -def keyword_args(**kwargs): - return kwargs +# Parametrelerin anahtar değerlerini almak isterseniz +def anahtar_par(**anahtarlar): + return anahtar -# Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +# Çalıştırdığımızda +anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} -# You can do both at once, if you like -def all_the_args(*args, **kwargs): - print(args) - print(kwargs) +# İsterseniz, bu ikisini birden kullanabilirsiniz +def tum_argumanlar(*argumanlar, **anahtarla): + print(argumanlar) + print(anahtarla) """ -all_the_args(1, 2, a=3, b=4) prints: +tum_argumanlar(1, 2, a=3, b=4) çıktı: (1, 2) {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. -args = (1, 2, 3, 4) -kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +# Fonksiyonu çağırırken de aynısını kullanabilirsiniz +argumanlar = (1, 2, 3, 4) +anahtarla = {"a": 3, "b": 4} +tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) +tum_argumanlar(**anahtarla) # = foo(a=3, b=4) +tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) -# Function Scope +# Fonksiyonlarda kullanacağımız bir değişken oluşturalım x = 5 -def setX(num): - # Local var x not the same as global variable x - x = num # => 43 +def belirleX(sayi): + # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil + x = sayi # => 43 print (x) # => 43 -def setGlobalX(num): +def globalBelirleX(sayi): global x print (x) # => 5 - x = num # global var x is now set to 6 + x = sayi # global olan x değişkeni artık 6 print (x) # => 6 -setX(43) -setGlobalX(6) +belirleX(43) +globalBelirleX(6) -# Python has first class functions -def create_adder(x): - def adder(y): +# Sınıf fonksiyonları oluşturma +def toplama_olustur(x): + def topla(y): return x + y - return adder + return topla -add_10 = create_adder(10) -add_10(3) # => 13 +ekle_10 = toplama_olustur(10) +ekle_10(3) # => 13 -# There are also anonymous functions +# Bilinmeyen fonksiyon (lambda x: x > 2)(3) # => True # TODO - Fix for iterables -# There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] +# Belirli sayıdan yükseğini alma fonksiyonu +map(ekle_10, [1, 2, 3]) # => [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# Filtreleme işlemi için liste comprehensions da kullanabiliriz +[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -- cgit v1.2.3 From e34c67290a311c32a208793f44e5d0d51bf37bc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Wed, 25 Mar 2015 21:36:52 +0200 Subject: Classes --- tr-tr/python3-tr.html.markdown | 68 ++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 6babb7d0..ee858fb6 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -479,59 +479,57 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -## 5. Classes +## 5. Sınıflar #################################################### -# We subclass from object to get a class. -class Human(object): +# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. +class Insan(obje): - # A class attribute. It is shared by all instances of this class - species = "H. sapiens" + # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir + tur = "H. sapiens" - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called magic methods (or sometimes called dunder methods) - # You should not invent such names on your own. - def __init__(self, name): - # Assign the argument to the instance's name attribute - self.name = name + # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. + # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar + # python tarafından tanımlanan isimlerdir. + # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! + def __init__(self, isim): + # Parametreyi sınıfın değerine atayalım + self.isim = isim - # An instance method. All methods take "self" as the first argument - def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. + def soyle(self, mesaj): + return "{isim}: {mesaj}".format(isim=self.name, mesaj=mesaj) - # A class method is shared among all instances - # They are called with the calling class as the first argument + # Bir sınıf metotu bütün nesnelere paylaştırılır + # İlk parametre olarak sınıf alırlar @classmethod - def get_species(cls): - return cls.species + def getir_tur(snf): + return snf.tur - # A static method is called without a class or instance reference + # Bir statik metot, sınıf ve nesnesiz çağrılır @staticmethod def grunt(): return "*grunt*" -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# Sınıfı çağıralım +i = Insan(isim="Ahmet") +print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +j = Insan("Ali") +print(j.soyle("selam")) # çıktı "Ali: selam" -# Call our class method -i.get_species() # => "H. sapiens" +# Sınıf metodumuzu çağıraim +i.getir_tur() # => "H. sapiens" -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Paylaşılan değeri değiştirelim +Insan.tur = "H. neanderthalensis" +i.getir_tur() # => "H. neanderthalensis" +j.getir_tur() # => "H. neanderthalensis" -# Call the static method -Human.grunt() # => "*grunt*" +# Statik metodumuzu çağıralım +Insan.grunt() # => "*grunt*" #################################################### -- cgit v1.2.3 From 965d7972d1ef7dfbfc9c07de72bbce81898eb703 Mon Sep 17 00:00:00 2001 From: Jeff Erickson Date: Wed, 25 Mar 2015 16:53:46 -0400 Subject: Minor typo: fixed curly bracket direction (} -> {) --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1b320028..f0ef6600 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -560,7 +560,7 @@ subset VeryBigInteger of Int where * > 500; multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # a multi is a `sub` by default +multi sayit(Str $s) { # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" -- cgit v1.2.3 From 4d74369df3a33f22442ce5938768500d55e9fa94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:23:45 +0200 Subject: Modules --- tr-tr/python3-tr.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index ee858fb6..83ce892d 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -533,32 +533,32 @@ Insan.grunt() # => "*grunt*" #################################################### -## 6. Modules +## 6. Moduller #################################################### -# You can import modules +# Modülleri içe aktarabilirsiniz import math print(math.sqrt(16)) # => 4 -# You can get specific functions from a module +# Modülden belirli bir fonksiyonları alabilirsiniz from math import ceil, floor print(ceil(3.7)) # => 4.0 print(floor(3.7)) # => 3.0 -# You can import all functions from a module. -# Warning: this is not recommended +# Modüldeki tüm fonksiyonları içe aktarabilirsiniz +# Dikkat: bunu yapmanızı önermem. from math import * -# You can shorten module names +# Modül isimlerini değiştirebilirsiniz. +# Not: Modül ismini kısaltmanız çok daha iyi olacaktır import math as m math.sqrt(16) == m.sqrt(16) # => True -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. +# Python modulleri aslında birer python dosyalarıdır. +# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün +# ismi ile dosyanın ismi aynı olacaktır. -# You can find out which functions and attributes -# defines a module. +# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. import math dir(math) -- cgit v1.2.3 From fde928afa6ef076087acf6c2dbfde0b53ba46e99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:36:05 +0200 Subject: Advanced --- tr-tr/python3-tr.html.markdown | 62 ++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 83ce892d..fcd57229 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -564,56 +564,54 @@ dir(math) #################################################### -## 7. Advanced +## 7. Gelişmiş #################################################### -# Generators help you make lazy code -def double_numbers(iterable): - for i in iterable: +# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır +def kare_sayilar(nesne): + for i in nesne: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword +# Bir oluşturucu(generator) değerleri anında oluşturur. +# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan +# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük +# değerler işlenmeyecektir. +# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda +# çok fazla vakit alacaktır. +# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım +for i in kare_sayilar(range_): print(i) if i >= 30: break -# Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# Dekoratörler +# Bu örnekte, +# Eğer lutfen_soyle True ise dönen değer değişecektir. from functools import wraps -def beg(target_function): - @wraps(target_function) - def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg +def yalvar(hedef_fonksiyon): + @wraps(hedef_fonksiyon) + def metot(*args, **kwargs): + msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) + if lutfen_soyle: + return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") + return msj - return wrapper + return metot -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please +@yalvar +def soyle(lutfen_soyle=False): + msj = "Bana soda alır mısın?" + return msj, lutfen_soyle -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +print(soyle()) # Bana soda alır mısın? +print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( ``` ## Ready For More? -- cgit v1.2.3 From c26eb3384b7c1201d903acfdee67b1709696c249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Thu, 26 Mar 2015 15:36:45 +0200 Subject: Ready To More? --- tr-tr/python3-tr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index fcd57229..2477c5da 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -614,9 +614,9 @@ print(soyle()) # Bana soda alır mısın? print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( ``` -## Ready For More? +## Daha Fazlasına Hazır Mısınız? -### Free Online +### Ücretsiz Online * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) @@ -627,7 +627,7 @@ print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayana * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) -### Dead Tree +### Kitaplar * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From e8a1ee8912d1c9bb0145c2afbdc530463fc612b7 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Fri, 27 Mar 2015 15:25:33 +0200 Subject: [haskell.html.markdown] Explanation for Haskell '$' operator with support from @geoffliu --- haskell.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6bdc78e0..6c98c2b6 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -205,9 +205,8 @@ foo 5 -- 75 -- Haskell has another operator called `$`. This operator applies a function -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator --- has priority of 0 and is right-associative. Such a low priority means that --- all other operators on both sides of `$` will be evaluated before applying --- the `$`. +-- has priority of 0 and is right-associative. Such a low priority means that +-- the expression on its right is applied as the parameter to the function on its left. -- before (even (fib 7)) -- false -- cgit v1.2.3 From e267eed62caf49d6d2b0d91c60d30b700d08729f Mon Sep 17 00:00:00 2001 From: Max Filippov Date: Mon, 30 Mar 2015 10:08:30 +0300 Subject: c.html: fix #1021 (bitwise negation and shifting into the sign bit) 0x0f is of type int, for 32-bit int the result is 0xfffffff0. 31'st bit is the sign bit of a 32-bit wide int. --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 1696d28f..d3f20eda 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -234,7 +234,7 @@ int main() { // same with j-- and --j // Bitwise operators! - ~0x0F; // => 0xF0 (bitwise negation, "1's complement") + ~0x0F; // => 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int) 0x0F & 0xF0; // => 0x00 (bitwise AND) 0x0F | 0xF0; // => 0xFF (bitwise OR) 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) @@ -242,7 +242,7 @@ int main() { 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) // Be careful when shifting signed integers - the following are undefined: - // - shifting into the sign bit of a signed integer (int a = 1 << 32) + // - shifting into the sign bit of a signed integer (int a = 1 << 31) // - left-shifting a negative number (int a = -1 << 2) // - shifting by an offset which is >= the width of the type of the LHS: // int a = 1 << 32; // UB if int is 32 bits wide -- cgit v1.2.3 From 8823c084ecf33db212635c2e6c635f6294ec4e89 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: Mon, 30 Mar 2015 13:24:30 +0300 Subject: [javascript/ru] Multiline comments correction, fixes #1023 --- ru-ru/javascript-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index e7398c88..79844565 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -22,8 +22,8 @@ Google Chrome, становится все более популярной. ```js // Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, -/* а многострочные комментарии начинаются с звёздочка-слэш - и заканчиваются символами слэш-звёздочка */ +/* а многострочные комментарии начинаются с последовательности слэш-звёздочка + и заканчиваются символами звёздочка-слэш */ // Инструкции могут заканчиваться точкой с запятой ; doStuff(); -- cgit v1.2.3 From 3c565a5535d7f6fb788b2a7b719262dd1a88720b Mon Sep 17 00:00:00 2001 From: nomatteus Date: Mon, 30 Mar 2015 16:13:26 -0400 Subject: Fix syntax error: Remove semicolon from last branch of erlang if-expression. http://erlang.org/doc/reference_manual/expressions.html#id78310 --- erlang.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index 04086aeb..a7390c3e 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -206,7 +206,7 @@ max(X, Y) -> if X > Y -> X; X < Y -> Y; - true -> nil; + true -> nil end. % Warning: at least one of the guards in the `if` expression must evaluate to true; -- cgit v1.2.3 From 212ba8301419923cffb82fa4d4ef7c91832b6096 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eray=20Ayd=C4=B1n?= Date: Mon, 30 Mar 2015 21:26:26 +0000 Subject: Markdown tr-tr language --- tr-tr/markdown-tr.html.markdown | 251 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 251 insertions(+) create mode 100644 tr-tr/markdown-tr.html.markdown diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown new file mode 100644 index 00000000..bac8f6fc --- /dev/null +++ b/tr-tr/markdown-tr.html.markdown @@ -0,0 +1,251 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: markdown-tr.md +--- + +Markdown, 2004 yılında John Gruber tarafından oluşturuldu. Asıl amacı kolay okuma ve yazmayı sağlamakla beraber kolayca HTML (artık bir çok diğer formatlara) dönüşüm sağlamaktır. + + +```markdown + + + + + + +# Bu bir

+## Bu bir

+### Bu bir

+#### Bu bir

+##### Bu bir

+###### Bu bir
+ + +Bu bir h1 +========= + +Bu bir h2 +--------- + + + +*Bu yazı italik.* +_Bu yazı da italik._ + +**Bu yazı kalın.** +__Bu yazı da kalın.__ + +***Bu yazı hem kalın hem italik.*** +**_Bu da öyle!_** +*__Hatta bu bile!__* + + +~~Bu yazı üstü çizili olarak gözükecek.~~ + + + +Bu bir paragraf. Paragrafın içeriğine devam ediyorum, eğlenceli değil mi? + +Şimdi 2. paragrafıma geçtim. +Hala 2. paragraftayım, çünkü boş bir satır bırakmadım. + +Bu da 3. paragrafım! + + + +Bu yazının sonunda 2 boşluk var (bu satırı seçerek kontrol edebilirsiniz). + +Bir üst satırda
etiketi var! + + + +> Bu bir blok etiketi. Satırlara ayırmak için +> her satırın başında `>` karakter yerleştirmeli veya tek satırda bütün içeriği yazabilirsiniz. +> Satır `>` karakteri ile başladığı sürece sorun yok. + +> Ayrıca alt alta da blok elementi açabilirsiniz +>> iç içe yani +> düzgün değil mi ? + + + + +* Nesne +* Nesne +* Bir başka nesne + +veya + ++ Nesne ++ Nesne ++ Bir başka nesne + +veya + +- Nesne +- Nesne +- Son bir nesne + + + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + + + +1. İlk nesne +1. İkinci nesne +1. Üçüncü nesne + + + + + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + * Alt nesne + * Alt nesne +4. Dördüncü nesne + + +Kutunun içerisinde `x` yoksa eğer seçim kutusu boş olacaktır. +- [ ] Yapılacak ilk görev. +- [ ] Yapılması gereken bir başka görev +Aşağıdaki seçim kutusu ise içi dolu olacaktır. +- [x] Bu görev başarıyla yapıldı + + + + + Bu bir kod + öyle mi? + + + + my_array.each do |item| + puts item + end + + + +Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Bana tıkla!](http://test.com) + + + +[Bana tıkla!](http://test.com "Test.com'a gider") + + +[Müzik dinle](/muzik/). + + + +[Bu linke tıklayarak][link1] daha detaylı bilgi alabilirsiniz! +[Ayrıca bu linki de inceleyin][foobar] tabi istiyorsanız. + +[link1]: http://test.com/ "harika!" +[foobar]: http://foobar.biz/ "okey!" + + + + + +[Bu][] bir link. +[bu]: http://bubirlink.com + + + + + +![Bu alt etiketine gelecek içerik](http://imgur.com/resmim.jpg "Bu da isteğe bağlı olan bir başlık") + + +![Bu alt etiketi.][resmim] + +[resmim]: bagil/linkler/de/calisiyor.jpg "Başlık isterseniz buraya girebilirsiniz" + + + + + ile +[http://testwebsite.com/](http://testwebsite.com) aynı şeyler + + + + + + + +Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmamasını istiyorum, +bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*. + + + + +| Sütun1 | Sütun 2 | Sütün 3 | +| :----------- | :------: | ------------: | +| Sola dayalı | Ortalı | Sağa dayalı | +| test | test | test | + + + +Sütun 1 | Sütun 2 | Sütun 3 +:-- | :-: | --: +Çok çirkin göözüküyor | değil | mi? + + + +``` + +Daha detaylı bilgi için, John Gruber'in resmi söz dizimi yazısını [buradan](http://daringfireball.net/projects/markdown/syntax) veya Adam Pritchard'ın mükemmel hatırlatma kağıdını [buradan](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) inceleyebilirsiniz. -- cgit v1.2.3 From 5e79da614c98070cfbf908af1c7be9b6abf3b2ed Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 31 Mar 2015 15:46:34 -0700 Subject: Added lang tag to go-fr --- fr-fr/go-fr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 2ff5902f..16558e7e 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -2,6 +2,7 @@ name: Go category: language language: Go +lang: fr-fr filename: learngo.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] -- cgit v1.2.3 From 4c46a456bd5e33aec2a3cab7b7c33a375d5a97ed Mon Sep 17 00:00:00 2001 From: Philippe Bricout Date: Wed, 1 Apr 2015 15:13:59 +0200 Subject: Update perl6.html.markdown ($_.chars > 50) ~~ True : this is always True. --- perl6.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index f0ef6600..8404f9f8 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -253,7 +253,9 @@ given "foo bar" { when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, # so you can also put "normal" conditionals. # This when is equivalent to this `if`: - # if ($_.chars > 50) ~~ True {...} + # if $_ ~~ ($_.chars > 50) {...} + # Which means: + # if $_.chars > 50 {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) -- cgit v1.2.3 From 145ede1f98fed18bbdfc1d1e807551d62deb1154 Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sun, 5 Apr 2015 11:24:10 -0300 Subject: Update brainfuck-pt.html.markdown fixing bug: pt-pt instead of pt-br --- pt-br/brainfuck-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown index 72c2cf6e..c7ce55ee 100644 --- a/pt-br/brainfuck-pt.html.markdown +++ b/pt-br/brainfuck-pt.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Suzane Sant Ana", "http://github.com/suuuzi"] -lang: pt-pt +lang: pt-br --- Brainfuck (em letras minúsculas, eceto no início de frases) é uma linguagem de -- cgit v1.2.3 From e6b77595f2669d66ac7be43c6e6083cbff80a9a7 Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sun, 5 Apr 2015 11:24:34 -0300 Subject: fixing bug: pt-pt instead of pt-br fixing bug: pt-pt instead of pt-br --- pt-br/git-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index b8cbd0a9..981da503 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -1,7 +1,7 @@ --- category: tool tool: git -lang: pt-pt +lang: pt-br filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] -- cgit v1.2.3 From dac116d322ca587647cff5576e3534c33e6e30e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D1=8E=D0=BA=20=D0=94=D0=BC=D0=B8=D1=82?= =?UTF-8?q?=D1=80=D0=B8=D0=B9?= Date: Tue, 7 Apr 2015 12:30:52 +0300 Subject: Update python3-ru.html.markdown Typo fix --- ru-ru/python3-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index fd95c876..2a7b3f7b 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -593,7 +593,7 @@ def double_numbers(iterable): range_ = range(1, 900000000) # Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(xrange_): +for i in double_numbers(range_): print(i) if i >= 30: break -- cgit v1.2.3